intial
This commit is contained in:
22
node_modules/@sveltejs/acorn-typescript/LICENSE.md
generated
vendored
Normal file
22
node_modules/@sveltejs/acorn-typescript/LICENSE.md
generated
vendored
Normal file
@@ -0,0 +1,22 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2022 Tyreal Hu
|
||||
Copyright (c) 2025 The Svelte Team
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
70
node_modules/@sveltejs/acorn-typescript/README.md
generated
vendored
Normal file
70
node_modules/@sveltejs/acorn-typescript/README.md
generated
vendored
Normal file
@@ -0,0 +1,70 @@
|
||||
# @sveltejs/acorn-typescript
|
||||
|
||||
[](LICENSE.md) [](https://svelte.dev/chat)
|
||||
|
||||
This is a plugin for [Acorn](http://marijnhaverbeke.nl/acorn/) - a tiny, fast JavaScript parser, written completely in JavaScript.
|
||||
|
||||
It was created as an experimental alternative, faster [TypeScript](https://www.typescriptlang.org/) parser. It will help you to parse
|
||||
TypeScript using Acorn.
|
||||
|
||||
## Usage
|
||||
|
||||
To get started, import the plugin and use Acorn's extension mechanism to register it. You have to enable `options.locations` while using `@sveltejs/acorn-typescript`.
|
||||
|
||||
```typescript
|
||||
import { Parser } from 'acorn';
|
||||
import { tsPlugin } from '@sveltejs/acorn-typescript';
|
||||
|
||||
const node = Parser.extend(tsPlugin()).parse(
|
||||
`
|
||||
const a = 1
|
||||
type A = number
|
||||
export {
|
||||
a,
|
||||
type A as B
|
||||
}
|
||||
`,
|
||||
{
|
||||
sourceType: 'module',
|
||||
ecmaVersion: 'latest',
|
||||
locations: true
|
||||
}
|
||||
);
|
||||
```
|
||||
|
||||
If you want to enable parsing within a TypeScript ambient context, where certain syntax have different rules (like `.d.ts` files and inside [declare module blocks](https://www.typescriptlang.org/docs/handbook/declaration-files/introduction.html)):
|
||||
|
||||
```typescript
|
||||
import { Parser } from 'acorn';
|
||||
import { tsPlugin } from '@sveltejs/acorn-typescript';
|
||||
|
||||
const node = Parser.extend(tsPlugin({ dts: true })).parse(
|
||||
`
|
||||
const a = 1
|
||||
type A = number
|
||||
export {
|
||||
a,
|
||||
type A as B
|
||||
}
|
||||
`,
|
||||
{
|
||||
sourceType: 'module',
|
||||
ecmaVersion: 'latest',
|
||||
locations: true
|
||||
}
|
||||
);
|
||||
```
|
||||
|
||||
## SUPPORTED
|
||||
|
||||
- Typescript normal syntax
|
||||
- Support to parse TypeScript [Decorators](https://www.typescriptlang.org/docs/handbook/decorators.html)
|
||||
- Support to parse JSX & TSX
|
||||
|
||||
## CHANGELOG
|
||||
|
||||
[click](./CHANGELOG.md)
|
||||
|
||||
## Acknowledgments
|
||||
|
||||
We want to thank [TyrealHu](https://github.com/TyrealHu) for his original work on this project. He maintained [`acorn-typescript`](https://github.com/TyrealHu/acorn-typescript) until early 2024.
|
||||
12
node_modules/@sveltejs/acorn-typescript/index.d.ts
generated
vendored
Normal file
12
node_modules/@sveltejs/acorn-typescript/index.d.ts
generated
vendored
Normal file
@@ -0,0 +1,12 @@
|
||||
import { Parser } from 'acorn';
|
||||
|
||||
export function tsPlugin(options?: {
|
||||
dts?: boolean;
|
||||
/** Whether to use JSX. Defaults to false */
|
||||
jsx?:
|
||||
| boolean
|
||||
| {
|
||||
allowNamespaces?: boolean;
|
||||
allowNamespacedObjects?: boolean;
|
||||
};
|
||||
}): (BaseParser: typeof Parser) => typeof Parser;
|
||||
5636
node_modules/@sveltejs/acorn-typescript/index.js
generated
vendored
Normal file
5636
node_modules/@sveltejs/acorn-typescript/index.js
generated
vendored
Normal file
File diff suppressed because it is too large
Load Diff
55
node_modules/@sveltejs/acorn-typescript/package.json
generated
vendored
Normal file
55
node_modules/@sveltejs/acorn-typescript/package.json
generated
vendored
Normal file
@@ -0,0 +1,55 @@
|
||||
{
|
||||
"name": "@sveltejs/acorn-typescript",
|
||||
"version": "1.0.13",
|
||||
"description": "Acorn plugin that parses TypeScript",
|
||||
"type": "module",
|
||||
"types": "index.d.ts",
|
||||
"files": [
|
||||
"index.js",
|
||||
"index.d.ts"
|
||||
],
|
||||
"exports": {
|
||||
".": {
|
||||
"types": "./index.d.ts",
|
||||
"default": "./index.js"
|
||||
}
|
||||
},
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/sveltejs/acorn-typescript.git"
|
||||
},
|
||||
"author": "tyrealhu and the Svelte team",
|
||||
"license": "MIT",
|
||||
"bugs": {
|
||||
"url": "https://github.com/sveltejs/acorn-typescript/issues"
|
||||
},
|
||||
"homepage": "https://github.com/sveltejs/acorn-typescript#readme",
|
||||
"devDependencies": {
|
||||
"@changesets/changelog-github": "1.0.0-next.6",
|
||||
"@changesets/cli": "^2.27.11",
|
||||
"acorn": "^8.14.0",
|
||||
"acorn-jsx": "~5.3.2",
|
||||
"cross-env": "^7.0.3",
|
||||
"esbuild": "^0.25.0",
|
||||
"prettier": "~3.5.2",
|
||||
"test262": "git+https://github.com/tc39/test262.git#88ebb1e3755198cd08757bca1698effbbf360345",
|
||||
"test262-parser-runner": "^0.5.0",
|
||||
"typescript": "^5.7.3",
|
||||
"vitest": "^3.0.7"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"acorn": "^8.9.0"
|
||||
},
|
||||
"scripts": {
|
||||
"build": "esbuild src/index.ts --bundle --format=esm --outfile=index.js --platform=node --external:acorn",
|
||||
"format": "prettier --write .",
|
||||
"check": "tsc --noEmit",
|
||||
"lint": "prettier --check .",
|
||||
"test": "vitest run",
|
||||
"test:update": "cross-env UPDATE_SNAPSHOT=true vitest run && pnpm run format",
|
||||
"test:test262": "pnpm run build && node ./test/run_test262.js",
|
||||
"changeset:version": "changeset version && git add --all",
|
||||
"changeset:release": "changeset publish",
|
||||
"playground": "pnpm build && node ./playground/index.js"
|
||||
}
|
||||
}
|
||||
7
node_modules/@sveltejs/adapter-auto/LICENSE
generated
vendored
Normal file
7
node_modules/@sveltejs/adapter-auto/LICENSE
generated
vendored
Normal file
@@ -0,0 +1,7 @@
|
||||
Copyright (c) 2020 [these people](https://github.com/sveltejs/kit/graphs/contributors)
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
11
node_modules/@sveltejs/adapter-auto/README.md
generated
vendored
Normal file
11
node_modules/@sveltejs/adapter-auto/README.md
generated
vendored
Normal file
@@ -0,0 +1,11 @@
|
||||
# adapter-auto
|
||||
|
||||
Automatically chooses the SvelteKit adapter for your current environment, if possible.
|
||||
|
||||
## Docs
|
||||
|
||||
[Docs](https://svelte.dev/docs/kit/adapter-auto)
|
||||
|
||||
## Changelog
|
||||
|
||||
[The Changelog for this package is available on GitHub](https://github.com/sveltejs/kit/blob/main/packages/adapter-auto/CHANGELOG.md).
|
||||
49
node_modules/@sveltejs/adapter-auto/adapters.js
generated
vendored
Normal file
49
node_modules/@sveltejs/adapter-auto/adapters.js
generated
vendored
Normal file
@@ -0,0 +1,49 @@
|
||||
import process from 'node:process';
|
||||
|
||||
// List of adapters to check for. `version` is used to pin the installed adapter version and should point
|
||||
// to the latest version of the adapter that is compatible with adapter-auto's current peerDependency version of SvelteKit.
|
||||
export const adapters = [
|
||||
{
|
||||
name: 'Vercel',
|
||||
test: () => !!process.env.VERCEL,
|
||||
module: '@sveltejs/adapter-vercel',
|
||||
version: '7'
|
||||
},
|
||||
{
|
||||
name: 'Cloudflare Pages',
|
||||
test: () => !!process.env.CF_PAGES,
|
||||
module: '@sveltejs/adapter-cloudflare',
|
||||
version: '8'
|
||||
},
|
||||
{
|
||||
name: 'Netlify',
|
||||
test: () => !!process.env.NETLIFY,
|
||||
module: '@sveltejs/adapter-netlify',
|
||||
version: '7'
|
||||
},
|
||||
{
|
||||
name: 'Azure Static Web Apps',
|
||||
test: () => process.env.GITHUB_ACTION_REPOSITORY === 'Azure/static-web-apps-deploy',
|
||||
module: 'svelte-adapter-azure-swa',
|
||||
version: '0.20'
|
||||
},
|
||||
{
|
||||
name: 'AWS via SST',
|
||||
test: () => !!process.env.SST,
|
||||
module: 'svelte-kit-sst',
|
||||
version: '2'
|
||||
},
|
||||
{
|
||||
name: 'Google Cloud Run',
|
||||
test: () => !!process.env.GCP_BUILDPACKS,
|
||||
module: '@sveltejs/adapter-node',
|
||||
version: '6'
|
||||
},
|
||||
{
|
||||
name: 'Render',
|
||||
test: () => !!process.env.RENDER,
|
||||
module: '@sveltejs/adapter-node',
|
||||
// TODO replace with a stable version
|
||||
version: 'next'
|
||||
}
|
||||
];
|
||||
3
node_modules/@sveltejs/adapter-auto/index.d.ts
generated
vendored
Normal file
3
node_modules/@sveltejs/adapter-auto/index.d.ts
generated
vendored
Normal file
@@ -0,0 +1,3 @@
|
||||
import { Adapter } from '@sveltejs/kit';
|
||||
|
||||
export default function plugin(): Adapter;
|
||||
172
node_modules/@sveltejs/adapter-auto/index.js
generated
vendored
Normal file
172
node_modules/@sveltejs/adapter-auto/index.js
generated
vendored
Normal file
@@ -0,0 +1,172 @@
|
||||
import { execSync } from 'node:child_process';
|
||||
import { pathToFileURL } from 'node:url';
|
||||
import { adapters } from './adapters.js';
|
||||
import path from 'node:path';
|
||||
import fs from 'node:fs';
|
||||
import process from 'node:process';
|
||||
|
||||
/** @type {Record<string, (name: string, version: string) => string>} */
|
||||
const commands = {
|
||||
npm: (name, version) => `npm install -D ${name}@${version}`,
|
||||
pnpm: (name, version) => `pnpm add -D ${name}@${version}`,
|
||||
yarn: (name, version) => `yarn add -D ${name}@${version}`,
|
||||
bun: (name, version) => `bun add -D ${name}@${version}`,
|
||||
deno: (name, version) => `deno install -D npm:${name}@${version}`
|
||||
};
|
||||
|
||||
function detect_lockfile() {
|
||||
let dir = process.cwd();
|
||||
|
||||
/** @param {string} file */
|
||||
const exists = (file) => fs.existsSync(path.join(dir, file));
|
||||
|
||||
do {
|
||||
if (exists('pnpm-lock.yaml')) return 'pnpm';
|
||||
if (exists('yarn.lock')) return 'yarn';
|
||||
if (exists('package-lock.json')) return 'npm';
|
||||
if (exists('bun.lockb') || exists('bun.lock')) return 'bun';
|
||||
if (exists('deno.lock')) return 'deno';
|
||||
} while (dir !== (dir = path.dirname(dir)));
|
||||
|
||||
return 'npm';
|
||||
}
|
||||
|
||||
function detect_package_manager() {
|
||||
const manager = detect_lockfile();
|
||||
|
||||
try {
|
||||
execSync(`${manager} --version`);
|
||||
return manager;
|
||||
} catch {
|
||||
return 'npm';
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolves a peer dependency relative to the current CWD. Duplicated with `packages/kit`
|
||||
* @param {string} dependency
|
||||
*/
|
||||
function resolve_peer(dependency) {
|
||||
let [name, ...parts] = dependency.split('/');
|
||||
if (name[0] === '@') name += `/${parts.shift()}`;
|
||||
|
||||
let dir = process.cwd();
|
||||
|
||||
while (!fs.existsSync(`${dir}/node_modules/${name}/package.json`)) {
|
||||
if (dir === (dir = path.dirname(dir))) {
|
||||
throw new Error(
|
||||
`Could not resolve peer dependency "${name}" relative to your project — please install it and try again.`
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
const pkg_dir = `${dir}/node_modules/${name}`;
|
||||
const pkg = JSON.parse(fs.readFileSync(`${pkg_dir}/package.json`, 'utf-8'));
|
||||
|
||||
const subpackage = ['.', ...parts].join('/');
|
||||
|
||||
let exported = pkg.exports[subpackage];
|
||||
|
||||
while (typeof exported !== 'string') {
|
||||
if (!exported) {
|
||||
throw new Error(`Could not find valid "${subpackage}" export in ${name}/package.json`);
|
||||
}
|
||||
|
||||
exported = exported['import'] ?? exported['default'];
|
||||
}
|
||||
|
||||
return path.resolve(pkg_dir, exported);
|
||||
}
|
||||
|
||||
/** @typedef {import('@sveltejs/kit').Adapter} Adapter */
|
||||
|
||||
/**
|
||||
* @returns {Promise<Adapter | undefined>} The corresponding adapter for the current environment if found otherwise undefined
|
||||
*/
|
||||
async function get_adapter() {
|
||||
const match = adapters.find((candidate) => candidate.test());
|
||||
|
||||
if (!match) return;
|
||||
|
||||
/** @type {string} */
|
||||
let resolved;
|
||||
|
||||
try {
|
||||
resolved = resolve_peer(match.module);
|
||||
} catch {
|
||||
const package_manager = detect_package_manager();
|
||||
const command = commands[package_manager](match.module, match.version);
|
||||
|
||||
try {
|
||||
console.log(`Installing ${match.module}...`);
|
||||
|
||||
execSync(command, {
|
||||
stdio: 'inherit',
|
||||
env: {
|
||||
...process.env,
|
||||
NODE_ENV: undefined
|
||||
}
|
||||
});
|
||||
|
||||
resolved = resolve_peer(match.module);
|
||||
|
||||
console.log(`Successfully installed ${match.module}.`);
|
||||
console.warn(
|
||||
`\nIf you plan to continue deploying to ${match.name}, consider replacing @sveltejs/adapter-auto with ${match.module}. This will give you faster installs and more control over deployment configuration.\n`
|
||||
);
|
||||
} catch (e) {
|
||||
throw new Error(
|
||||
`Could not install ${match.module}. Please install it yourself by adding it to your package.json's devDependencies and try building your project again.`,
|
||||
{ cause: e }
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/** @type {{ default: () => Adapter }} */
|
||||
const module = await import(pathToFileURL(resolved).href);
|
||||
|
||||
const adapter = module.default();
|
||||
|
||||
return {
|
||||
...adapter,
|
||||
adapt: (builder) => {
|
||||
builder.log.info(`Detected environment: ${match.name}. Using ${match.module}`);
|
||||
return adapter.adapt(builder);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
/** @type {typeof import('./index.js').default} */
|
||||
export default () => ({
|
||||
name: '@sveltejs/adapter-auto',
|
||||
adapt: async (builder) => {
|
||||
const adapter = await get_adapter();
|
||||
|
||||
if (adapter) return adapter.adapt(builder);
|
||||
|
||||
builder.log.warn(
|
||||
'Could not detect a supported production environment. See https://svelte.dev/docs/kit/adapters to learn how to configure your app to run on the platform of your choosing'
|
||||
);
|
||||
},
|
||||
supports: {
|
||||
read: () => {
|
||||
supports_error(
|
||||
'The read function imported from $app/server only works in certain environments'
|
||||
);
|
||||
},
|
||||
instrumentation: () => {
|
||||
supports_error('`instrumentation.server.js` only works in certain environments');
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* @param {string} message
|
||||
* @returns {never}
|
||||
* @throws {Error}
|
||||
*/
|
||||
function supports_error(message) {
|
||||
throw new Error(
|
||||
`${message}. Since you're using @sveltejs/adapter-auto, SvelteKit cannot determine whether it will work when your app is deployed. Please replace it with an adapter tailored to your target environment.`
|
||||
);
|
||||
}
|
||||
51
node_modules/@sveltejs/adapter-auto/package.json
generated
vendored
Normal file
51
node_modules/@sveltejs/adapter-auto/package.json
generated
vendored
Normal file
@@ -0,0 +1,51 @@
|
||||
{
|
||||
"name": "@sveltejs/adapter-auto",
|
||||
"version": "8.0.0",
|
||||
"description": "Automatically chooses the SvelteKit adapter for your current environment, if possible.",
|
||||
"keywords": [
|
||||
"adapter",
|
||||
"automatically",
|
||||
"deploy",
|
||||
"hosting",
|
||||
"platform",
|
||||
"svelte",
|
||||
"sveltekit"
|
||||
],
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/sveltejs/kit.git",
|
||||
"directory": "packages/adapter-auto"
|
||||
},
|
||||
"license": "MIT",
|
||||
"homepage": "https://svelte.dev/docs/kit/adapter-auto",
|
||||
"type": "module",
|
||||
"exports": {
|
||||
".": {
|
||||
"types": "./index.d.ts",
|
||||
"import": "./index.js"
|
||||
},
|
||||
"./package.json": "./package.json"
|
||||
},
|
||||
"types": "index.d.ts",
|
||||
"files": [
|
||||
"index.js",
|
||||
"index.d.ts",
|
||||
"adapters.js"
|
||||
],
|
||||
"devDependencies": {
|
||||
"@sveltejs/kit": "^3.0.0",
|
||||
"@types/node": "^22.19.19",
|
||||
"@typescript/native": "npm:typescript@^7.0.2",
|
||||
"vitest": "^5.0.1"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@sveltejs/kit": "^3.0.0-next.0"
|
||||
},
|
||||
"scripts": {
|
||||
"lint": "oxfmt --check .",
|
||||
"format": "oxfmt --write .",
|
||||
"check": "node node_modules/@typescript/native/bin/tsc",
|
||||
"test": "vitest run",
|
||||
"test:unit": "vitest run"
|
||||
}
|
||||
}
|
||||
7
node_modules/@sveltejs/kit/LICENSE
generated
vendored
Normal file
7
node_modules/@sveltejs/kit/LICENSE
generated
vendored
Normal file
@@ -0,0 +1,7 @@
|
||||
Copyright (c) 2020 [these people](https://github.com/sveltejs/kit/graphs/contributors)
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
18
node_modules/@sveltejs/kit/README.md
generated
vendored
Normal file
18
node_modules/@sveltejs/kit/README.md
generated
vendored
Normal file
@@ -0,0 +1,18 @@
|
||||
# The fastest way to build Svelte apps
|
||||
|
||||
This is the [SvelteKit](https://svelte.dev/docs/kit) framework and CLI.
|
||||
|
||||
The quickest way to get started is via the [sv](https://npmjs.com/package/sv) package:
|
||||
|
||||
```sh
|
||||
npx sv create my-app
|
||||
cd my-app
|
||||
npm install
|
||||
npm run dev
|
||||
```
|
||||
|
||||
See the [documentation](https://svelte.dev/docs/kit) to learn more.
|
||||
|
||||
## Changelog
|
||||
|
||||
[The Changelog for this package is available on GitHub](https://github.com/sveltejs/kit/blob/main/packages/kit/CHANGELOG.md).
|
||||
204
node_modules/@sveltejs/kit/package.json
generated
vendored
Normal file
204
node_modules/@sveltejs/kit/package.json
generated
vendored
Normal file
@@ -0,0 +1,204 @@
|
||||
{
|
||||
"name": "@sveltejs/kit",
|
||||
"version": "3.1.1",
|
||||
"description": "SvelteKit is the fastest way to build Svelte apps",
|
||||
"keywords": [
|
||||
"framework",
|
||||
"official",
|
||||
"svelte",
|
||||
"sveltekit",
|
||||
"vite"
|
||||
],
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/sveltejs/kit.git",
|
||||
"directory": "packages/kit"
|
||||
},
|
||||
"license": "MIT",
|
||||
"homepage": "https://svelte.dev",
|
||||
"type": "module",
|
||||
"dependencies": {
|
||||
"@rolldown/pluginutils": "^1.0.1",
|
||||
"@standard-schema/spec": "^1.1.0",
|
||||
"cookie": "^2.0.1",
|
||||
"devalue": "^5.9.4",
|
||||
"esm-env": "^1.2.2",
|
||||
"magic-string": "^1.2.3",
|
||||
"mrmime": "^2.0.1",
|
||||
"sirv": "^3.0.2"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@opentelemetry/api": "^1.9.1",
|
||||
"@playwright/test": "^1.62.1",
|
||||
"@sveltejs/message-box": "^1.1.3",
|
||||
"@sveltejs/vite-plugin-svelte": "^7.3.0",
|
||||
"@types/connect": "^3.4.38",
|
||||
"@typescript/native": "npm:typescript@^7.0.2",
|
||||
"@types/node": "^22.19.19",
|
||||
"dts-buddy": "^0.8.3",
|
||||
"jsdom": "^30.0.0",
|
||||
"svelte": "^5.57.1",
|
||||
"svelte-preprocess": "^6.0.5",
|
||||
"typescript": "~6.0.3",
|
||||
"valibot": "^1.4.2",
|
||||
"vite": "^8.2.1",
|
||||
"vitest": "^5.0.1"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@opentelemetry/api": "^1.0.0",
|
||||
"@sveltejs/vite-plugin-svelte": "^7.0.0",
|
||||
"svelte": "^5.57.1",
|
||||
"typescript": "^6.0.0",
|
||||
"vite": "^8.0.12"
|
||||
},
|
||||
"peerDependenciesMeta": {
|
||||
"@opentelemetry/api": {
|
||||
"optional": true
|
||||
},
|
||||
"typescript": {
|
||||
"optional": true
|
||||
}
|
||||
},
|
||||
"bin": {
|
||||
"svelte-kit": "svelte-kit.js"
|
||||
},
|
||||
"files": [
|
||||
"src",
|
||||
"!src/**/*.spec.js",
|
||||
"!src/**/fixtures",
|
||||
"!src/**/test",
|
||||
"types",
|
||||
"svelte-kit.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/state": {
|
||||
"types": "./src/runtime/app/state/client.svelte.js",
|
||||
"workerd": "./src/runtime/app/state/server.js",
|
||||
"browser": "./src/runtime/app/state/client.svelte.js",
|
||||
"default": "./src/runtime/app/state/server.js"
|
||||
},
|
||||
"#app/state/client": {
|
||||
"types": "./src/runtime/app/state/client.svelte.js",
|
||||
"workerd": "./src/runtime/invalid-import.js",
|
||||
"browser": "./src/runtime/app/state/client.svelte.js",
|
||||
"default": "./src/runtime/invalid-import.js"
|
||||
},
|
||||
"#internal": {
|
||||
"workerd": "./src/exports/internal/server/index.js",
|
||||
"browser": "./src/exports/internal/client.js",
|
||||
"default": "./src/exports/internal/server/index.js"
|
||||
}
|
||||
},
|
||||
"exports": {
|
||||
"./package.json": "./package.json",
|
||||
".": {
|
||||
"types": "./types/index.d.ts",
|
||||
"import": "./src/exports/index.js"
|
||||
},
|
||||
"./internal": {
|
||||
"types": "./types/index.d.ts",
|
||||
"import": "./src/exports/internal/index.js"
|
||||
},
|
||||
"./internal/env": {
|
||||
"types": "./types/index.d.ts",
|
||||
"import": "./src/exports/internal/env.js"
|
||||
},
|
||||
"./internal/types": {
|
||||
"types": "./src/exports/internal/types.d.ts"
|
||||
},
|
||||
"./internal/server": {
|
||||
"types": "./types/index.d.ts",
|
||||
"import": "./src/exports/internal/server/index.js"
|
||||
},
|
||||
"./adapter": {
|
||||
"types": "./types/index.d.ts",
|
||||
"import": "./src/exports/adapter.js"
|
||||
},
|
||||
"./node": {
|
||||
"types": "./types/index.d.ts",
|
||||
"import": "./src/exports/node/index.js"
|
||||
},
|
||||
"./hooks": {
|
||||
"types": "./types/index.d.ts",
|
||||
"import": "./src/exports/hooks/index.js"
|
||||
},
|
||||
"./env": {
|
||||
"types": "./types/index.d.ts",
|
||||
"import": "./src/exports/env/index.js"
|
||||
},
|
||||
"./params": {
|
||||
"types": "./types/index.d.ts",
|
||||
"import": "./src/exports/params/index.js"
|
||||
},
|
||||
"./vite": {
|
||||
"types": "./types/index.d.ts",
|
||||
"import": "./src/exports/vite/index.js"
|
||||
}
|
||||
},
|
||||
"types": "types/index.d.ts",
|
||||
"engines": {
|
||||
"node": ">=22.17"
|
||||
},
|
||||
"scripts": {
|
||||
"lint": "oxfmt --check .",
|
||||
"check": "pnpm tsc-native && pnpm tsc-native --project test/types/tsconfig.json && pnpm tsc-native --project test/types/app-error-enhanced/tsconfig.json",
|
||||
"check:all": "pnpm tsc-native && pnpm -r --filter=\"./**\" check",
|
||||
"format": "oxfmt --write .",
|
||||
"test": "pnpm test:unit && pnpm test:integration",
|
||||
"test:integration": "pnpm -r --workspace-concurrency 2 --filter=\"./test/**\" test",
|
||||
"test:dev": "pnpm -r --workspace-concurrency 2 --filter=\"./test/**\" test:dev",
|
||||
"test:build": "pnpm -r --workspace-concurrency 2 --filter=\"./test/**\" test:build",
|
||||
"test:dev:basics": "pnpm --filter=test-basics test:dev",
|
||||
"test:dev:rest": "pnpm -r --workspace-concurrency 2 --filter=\"./test/**\" --filter=\"!test-basics\" test:dev",
|
||||
"test:build:basics": "pnpm --filter=test-basics test:build",
|
||||
"test:build:rest": "pnpm -r --workspace-concurrency 2 --filter=\"./test/**\" --filter=\"!test-basics\" test:build",
|
||||
"test:cross-platform:dev": "pnpm -r --workspace-concurrency 1 --filter=\"./test/**\" test:cross-platform:dev",
|
||||
"test:cross-platform:build": "pnpm -r --workspace-concurrency 1 --filter=\"./test/**\" test:cross-platform:build",
|
||||
"test:server-side-route-resolution:dev": "pnpm -r --workspace-concurrency 1 --filter=\"./test/**\" test:server-side-route-resolution:dev",
|
||||
"test:server-side-route-resolution:build": "pnpm -r --workspace-concurrency 1 --filter=\"./test/**\" test:server-side-route-resolution:build",
|
||||
"test:svelte-async:dev": "pnpm -r --workspace-concurrency 1 --filter=\"./test/**\" test:svelte-async:dev",
|
||||
"test:svelte-async:build": "pnpm -r --workspace-concurrency 1 --filter=\"./test/**\" test:svelte-async:build",
|
||||
"test:unit": "vitest run -c vitest.kit.config.js",
|
||||
"tsc-native": "node node_modules/@typescript/native/bin/tsc",
|
||||
"generate:messages": "node scripts/process-messages/index.js",
|
||||
"generate:version": "node scripts/generate-version.js",
|
||||
"generate:types": "node scripts/generate-dts.js"
|
||||
}
|
||||
}
|
||||
127
node_modules/@sveltejs/kit/src/cli.js
generated
vendored
Executable file
127
node_modules/@sveltejs/kit/src/cli.js
generated
vendored
Executable file
@@ -0,0 +1,127 @@
|
||||
import fs from 'node:fs';
|
||||
import process from 'node:process';
|
||||
import { parseArgs, styleText } from 'node:util';
|
||||
import { extract_svelte_config, load_vite_config } from './core/config/index.js';
|
||||
import { coalesce_to_error } from './utils/error.js';
|
||||
import { import_peer } from './utils/import.js';
|
||||
import { resolve_env_entry } from './core/env.js';
|
||||
|
||||
/** @param {unknown} e */
|
||||
function handle_error(e) {
|
||||
const error = coalesce_to_error(e);
|
||||
|
||||
if (error.name === 'SyntaxError') throw error;
|
||||
|
||||
console.error(styleText(['bold', 'red'], `> ${error.message}`));
|
||||
if (error.stack) {
|
||||
console.error(styleText('grey', error.stack.split('\n').slice(1).join('\n')));
|
||||
}
|
||||
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
const pkg = JSON.parse(fs.readFileSync(new URL('../package.json', import.meta.url), 'utf-8'));
|
||||
|
||||
const help = `
|
||||
Usage: svelte-kit <command> [options]
|
||||
|
||||
Commands:
|
||||
sync Synchronise generated type definitions
|
||||
|
||||
Options:
|
||||
--version, -v Show version number
|
||||
--help, -h Show this help message
|
||||
|
||||
Sync Options:
|
||||
--config, -c <config> Specify a custom Vite config file
|
||||
--mode <mode> Specify a mode for loading environment variables (default: development)
|
||||
`;
|
||||
|
||||
let parsed;
|
||||
try {
|
||||
parsed = parseArgs({
|
||||
options: {
|
||||
version: { type: 'boolean', short: 'v' },
|
||||
help: { type: 'boolean', short: 'h' },
|
||||
mode: { type: 'string', default: 'development' },
|
||||
config: { type: 'string', short: 'c', default: undefined }
|
||||
},
|
||||
allowPositionals: true,
|
||||
strict: true
|
||||
});
|
||||
} catch (err) {
|
||||
const error = /** @type {Error} */ (err);
|
||||
console.error(styleText(['bold', 'red'], `> ${error.message}`));
|
||||
console.log(help);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
const { values, positionals } = parsed;
|
||||
|
||||
if (values.version) {
|
||||
console.log(pkg.version);
|
||||
process.exit(0);
|
||||
}
|
||||
|
||||
if (values.help) {
|
||||
console.log(help);
|
||||
process.exit(0);
|
||||
}
|
||||
|
||||
const command = positionals[0];
|
||||
|
||||
if (!command) {
|
||||
console.log(help);
|
||||
process.exit(0);
|
||||
}
|
||||
|
||||
if (command === 'sync') {
|
||||
// create placeholder node_modules/$app/tsconfig.json if necessary, to squelch warnings.
|
||||
// this isn't bulletproof — if someone has some esoteric config, it will continue
|
||||
// to harmlessly warn — but we handle the 90% case and clean up after ourselves
|
||||
const dir = 'node_modules/$app';
|
||||
const base_tsconfig = `${dir}/tsconfig.json`;
|
||||
const base_tsconfig_json = '{}';
|
||||
|
||||
const sveltekit_dir_exists = fs.existsSync(dir);
|
||||
const base_tsconfig_exists = fs.existsSync(base_tsconfig);
|
||||
|
||||
if (!base_tsconfig_exists) {
|
||||
try {
|
||||
fs.mkdirSync(dir, { recursive: true });
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
|
||||
fs.writeFileSync(base_tsconfig, base_tsconfig_json);
|
||||
}
|
||||
|
||||
try {
|
||||
const vite = /** @type {typeof import('vite')} */ (await import_peer('vite', process.cwd()));
|
||||
|
||||
const vite_config = await load_vite_config(values.config, vite);
|
||||
const sveltekit_config = extract_svelte_config(vite_config);
|
||||
|
||||
const sync = await import('./core/sync/sync.js');
|
||||
sync.all_types(sveltekit_config, vite_config.root);
|
||||
|
||||
const entry = resolve_env_entry(sveltekit_config, vite_config.root);
|
||||
await sync.env(sveltekit_config, entry, vite_config.root, values.mode);
|
||||
} catch (error) {
|
||||
handle_error(error);
|
||||
} finally {
|
||||
// if we errored, or accidentally created the wrong file
|
||||
// (could happen!) then clean up after ourselves
|
||||
if (fs.readFileSync(base_tsconfig, 'utf-8') === base_tsconfig_json) {
|
||||
fs.unlinkSync(base_tsconfig);
|
||||
}
|
||||
|
||||
if (!sveltekit_dir_exists && fs.readdirSync(dir).length === 0) {
|
||||
fs.rmSync(dir, { recursive: true });
|
||||
}
|
||||
}
|
||||
} else {
|
||||
console.error(styleText(['bold', 'red'], `> Unknown command: ${command}`));
|
||||
console.log(help);
|
||||
process.exit(1);
|
||||
}
|
||||
36
node_modules/@sveltejs/kit/src/constants.js
generated
vendored
Normal file
36
node_modules/@sveltejs/kit/src/constants.js
generated
vendored
Normal file
@@ -0,0 +1,36 @@
|
||||
/**
|
||||
* A fake asset path used in `vite dev` and `vite preview`, so that we can
|
||||
* serve local assets while verifying that requests are correctly prefixed
|
||||
*/
|
||||
export const SVELTE_KIT_ASSETS = '/_svelte_kit_assets';
|
||||
|
||||
export const GENERATED_COMMENT = '// this file is generated — do not edit it';
|
||||
|
||||
export const ENDPOINT_METHODS = [
|
||||
'GET',
|
||||
'POST',
|
||||
'PUT',
|
||||
'PATCH',
|
||||
'DELETE',
|
||||
'OPTIONS',
|
||||
'HEAD',
|
||||
'QUERY'
|
||||
];
|
||||
|
||||
export const MUTATIVE_METHODS = ['POST', 'PUT', 'PATCH', 'DELETE'];
|
||||
|
||||
/** methods whose responses depend on the request body, so they can never be prerendered */
|
||||
export const BODY_DEPENDENT_METHODS = [...MUTATIVE_METHODS, 'QUERY'];
|
||||
|
||||
export const PAGE_METHODS = ['GET', 'POST', 'HEAD'];
|
||||
|
||||
export const SRC_ROOT = import.meta.dirname;
|
||||
|
||||
// eslint-disable-next-line n/prefer-global/process
|
||||
export const IN_WEBCONTAINER = !!globalThis.process?.versions?.webcontainer;
|
||||
|
||||
/**
|
||||
* If an an adapter deploys a catch-all serverless function, the rerouted URL
|
||||
* is stored in this header.
|
||||
*/
|
||||
export const REROUTED_URL_HEADER = 'x-sveltekit-rerouted-url';
|
||||
426
node_modules/@sveltejs/kit/src/core/adapt/builder.js
generated
vendored
Normal file
426
node_modules/@sveltejs/kit/src/core/adapt/builder.js
generated
vendored
Normal file
@@ -0,0 +1,426 @@
|
||||
/** @import { StandardSchemaV1 } from '@standard-schema/spec' */
|
||||
/** @import { ResolvedConfig } from 'vite' */
|
||||
/** @import { Builder, RouteDefinition } from '@sveltejs/kit' */
|
||||
/** @import { EnvVarConfig } from '@sveltejs/kit/env' */
|
||||
/** @import { RouteData, ValidatedConfig, BuildData, ServerMetadata, ServerMetadataRoute, Prerendered, PrerenderMap, Logger, RemoteChunk } from 'types' */
|
||||
import { loadEnv } from 'vite';
|
||||
import * as devalue from 'devalue';
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { promisify } from 'node:util';
|
||||
import zlib from 'node:zlib';
|
||||
import { copy, relative_path, walk } from '../../utils/filesystem.js';
|
||||
import { posixify } from '../../utils/os.js';
|
||||
import { generate_manifest } from '../generate_manifest/index.js';
|
||||
import { get_route_segments } from '../../utils/routing.js';
|
||||
import generate_fallback from '../postbuild/fallback.js';
|
||||
import { dedent, write } from '../sync/utils.js';
|
||||
import { find_server_assets } from '../generate_manifest/find_server_assets.js';
|
||||
import { create_exported_declarations } from '../env.js';
|
||||
import { handle_issues, validate } from '../../exports/internal/env.js';
|
||||
import * as e from '../../messages/build-errors.js';
|
||||
import * as w from '../../messages/build-warnings.js';
|
||||
import { get_mime_lookup } from '../utils.js';
|
||||
import { lookup as mime_lookup } from '../../utils/mime.js';
|
||||
|
||||
const gzip = promisify(zlib.gzip);
|
||||
const brotli = promisify(zlib.brotliCompress);
|
||||
const extensions = [
|
||||
'.html',
|
||||
'.js',
|
||||
'.mjs',
|
||||
'.json',
|
||||
'.css',
|
||||
'.svg',
|
||||
'.xml',
|
||||
'.wasm',
|
||||
'.txt',
|
||||
'.md',
|
||||
'.mdx'
|
||||
];
|
||||
|
||||
/**
|
||||
* Creates the Builder which is passed to adapters for building the application.
|
||||
* @param {{
|
||||
* config: ValidatedConfig;
|
||||
* build_data: BuildData;
|
||||
* server_metadata: ServerMetadata;
|
||||
* route_data: RouteData[];
|
||||
* prerendered: Prerendered;
|
||||
* prerender_map: PrerenderMap;
|
||||
* app_manifest: typeof import('$app/manifest');
|
||||
* log: Logger;
|
||||
* vite_config: ResolvedConfig;
|
||||
* remotes: RemoteChunk[];
|
||||
* explicit_env_config: Record<string, EnvVarConfig<any>> | null;
|
||||
* }} opts
|
||||
* @returns {Builder}
|
||||
*/
|
||||
export function create_builder({
|
||||
config,
|
||||
build_data,
|
||||
server_metadata,
|
||||
route_data,
|
||||
prerendered,
|
||||
prerender_map,
|
||||
app_manifest,
|
||||
log,
|
||||
vite_config,
|
||||
remotes,
|
||||
explicit_env_config
|
||||
}) {
|
||||
/** @type {Map<RouteDefinition, RouteData>} */
|
||||
const lookup = new Map();
|
||||
|
||||
/**
|
||||
* Rather than exposing the internal `RouteData` type, which is subject to change,
|
||||
* we expose a stable type that adapters can use to group/filter routes
|
||||
*/
|
||||
const routes = route_data.map((route) => {
|
||||
const { config, methods, page, api } = /** @type {ServerMetadataRoute} */ (
|
||||
server_metadata.routes.get(route.id)
|
||||
);
|
||||
|
||||
/** @type {RouteDefinition} */
|
||||
const facade = {
|
||||
id: route.id,
|
||||
api,
|
||||
page,
|
||||
segments: get_route_segments(route.id).map((segment) => ({
|
||||
dynamic: segment.includes('['),
|
||||
rest: segment.includes('[...'),
|
||||
content: segment
|
||||
})),
|
||||
pattern: route.pattern,
|
||||
prerender: prerender_map.get(route.id) ?? false,
|
||||
methods,
|
||||
config
|
||||
};
|
||||
|
||||
lookup.set(facade, route);
|
||||
|
||||
return facade;
|
||||
});
|
||||
|
||||
// $app/manifest cannot include the service worker because it's used by the service worker itself,
|
||||
// but the adapter needs to know about it so we add it here.
|
||||
if (build_data.service_worker) {
|
||||
app_manifest.assets.push({ path: build_data.service_worker });
|
||||
}
|
||||
|
||||
return {
|
||||
log,
|
||||
rimraf: (dir) => fs.rmSync(dir, { force: true, recursive: true }),
|
||||
mkdirp: (dir) => fs.mkdirSync(dir, { recursive: true }),
|
||||
copy,
|
||||
|
||||
config,
|
||||
prerendered,
|
||||
routes,
|
||||
manifest: app_manifest,
|
||||
get mimeTypes() {
|
||||
// TODO - make the `generate_manifest` function return data instead of a string, and retrieve mime types from there
|
||||
const mime_types = get_mime_lookup(build_data.manifest_data);
|
||||
const server_assets = find_server_assets(
|
||||
build_data,
|
||||
route_data.filter((route) => prerender_map.get(route.id) !== true),
|
||||
vite_config.root
|
||||
);
|
||||
for (const file of server_assets) {
|
||||
const ext = path.extname(file);
|
||||
mime_types[ext] ??= mime_lookup(ext) || '';
|
||||
}
|
||||
|
||||
// record extensions that only exist in prerendered or client output (e.g. a favicon.ico),
|
||||
// so that adapters can serve those files without a mime database of their own
|
||||
for (const directory of ['prerendered', 'client']) {
|
||||
const dir = path.join(build_data.out_dir, directory);
|
||||
if (!fs.existsSync(dir)) continue;
|
||||
|
||||
for (const file of walk(dir)) {
|
||||
const ext = path.extname(file);
|
||||
if (ext) mime_types[ext] ??= mime_lookup(ext) || '';
|
||||
}
|
||||
}
|
||||
return mime_types;
|
||||
},
|
||||
|
||||
async compress(directory) {
|
||||
if (!fs.existsSync(directory)) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const files = [...walk(directory)].filter((file) => extensions.includes(path.extname(file)));
|
||||
|
||||
// zlib work is serialised on the threadpool and each brotli encoder is allocated up front,
|
||||
// so a handful of files in flight is as fast as all of them and keeps memory flat
|
||||
let i = 0;
|
||||
await Promise.all(
|
||||
Array.from({ length: 16 }, async () => {
|
||||
while (i < files.length) await compress_file(path.resolve(directory, files[i++]));
|
||||
})
|
||||
);
|
||||
|
||||
return files;
|
||||
},
|
||||
|
||||
findServerAssets(route_data) {
|
||||
return find_server_assets(
|
||||
build_data,
|
||||
route_data.map((route) => /** @type {import('types').RouteData} */ (lookup.get(route))),
|
||||
vite_config.root
|
||||
);
|
||||
},
|
||||
|
||||
async generateFallback(dest) {
|
||||
const manifest_path = `${config.outDir}/output/server/manifest-full.js`;
|
||||
const env = loadEnv(vite_config.mode, config.env.dir, '');
|
||||
|
||||
const fallback = await generate_fallback({
|
||||
manifest_path,
|
||||
env,
|
||||
out_dir: config.outDir,
|
||||
origin: config.paths.origin || 'http://sveltekit-prerender',
|
||||
assets: config.files.assets
|
||||
});
|
||||
|
||||
if (fs.existsSync(dest)) {
|
||||
w.adapter_fallback_overwrites({ file: dest });
|
||||
}
|
||||
|
||||
write(dest, fallback);
|
||||
},
|
||||
|
||||
generateEnvModule() {
|
||||
if (!build_data.client?.uses_env_dynamic_public) return;
|
||||
|
||||
const dest = `${config.outDir}/output/prerendered/dependencies/${config.appDir}`;
|
||||
const env = loadEnv(vite_config.mode, config.env.dir, '');
|
||||
|
||||
/** @type {Record<string, any>} */
|
||||
const values = {};
|
||||
const variables = explicit_env_config ?? {};
|
||||
|
||||
/** @type {Record<string, StandardSchemaV1.Issue[]>} */
|
||||
const issues = {};
|
||||
|
||||
for (const [name, config] of Object.entries(variables)) {
|
||||
if (config.static || !config.public) continue;
|
||||
values[name] = validate(variables, env[name], name, issues);
|
||||
}
|
||||
|
||||
handle_issues(issues);
|
||||
|
||||
const payload = devalue.uneval(values);
|
||||
|
||||
write(`${dest}/env.js`, `export const env=${payload}`);
|
||||
},
|
||||
|
||||
generateManifest() {
|
||||
e.adapter_generate_manifest_removed();
|
||||
},
|
||||
|
||||
generateServerInstance(dest, { routes: subset, serverDirectory } = {}) {
|
||||
const relative = relative_path(
|
||||
path.dirname(dest),
|
||||
serverDirectory ?? this.getServerDirectory()
|
||||
);
|
||||
write(
|
||||
dest,
|
||||
dedent`
|
||||
import { create_server } from '${relative}/index.js';
|
||||
const manifest = ${generate_manifest({
|
||||
build_data,
|
||||
prerendered: prerendered.paths,
|
||||
relative_path: relative,
|
||||
routes: subset
|
||||
? subset.map((route) => /** @type {import('types').RouteData} */ (lookup.get(route)))
|
||||
: route_data.filter((route) => prerender_map.get(route.id) !== true),
|
||||
remotes,
|
||||
root: vite_config.root
|
||||
})};
|
||||
export const server = create_server(manifest);
|
||||
`
|
||||
);
|
||||
},
|
||||
|
||||
getBuildDirectory(name) {
|
||||
return `${config.outDir}/${name}`;
|
||||
},
|
||||
|
||||
getClientDirectory() {
|
||||
return `${config.outDir}/output/client`;
|
||||
},
|
||||
|
||||
getServerDirectory() {
|
||||
return `${config.outDir}/output/server`;
|
||||
},
|
||||
|
||||
getAppPath() {
|
||||
return build_data.app_path;
|
||||
},
|
||||
|
||||
writeClient(dest) {
|
||||
return copy(`${config.outDir}/output/client`, dest, {
|
||||
// avoid making vite build artefacts public
|
||||
filter: (basename) => basename !== '.vite'
|
||||
});
|
||||
},
|
||||
|
||||
writePrerendered(dest) {
|
||||
const source = `${config.outDir}/output/prerendered`;
|
||||
|
||||
return [
|
||||
...copy(`${source}/pages`, dest),
|
||||
...copy(`${source}/dependencies`, dest),
|
||||
...copy(`${source}/data`, dest)
|
||||
];
|
||||
},
|
||||
|
||||
writeServer(dest) {
|
||||
return copy(`${config.outDir}/output/server`, dest);
|
||||
},
|
||||
|
||||
createInstrumentationInitializer({
|
||||
outputDirectory,
|
||||
environment,
|
||||
serverDirectory = `${config.outDir}/output/server`
|
||||
}) {
|
||||
const provider = path.join(outputDirectory, '__sveltekit_env.js');
|
||||
write(provider, environment ?? 'export default process.env;');
|
||||
|
||||
const initializer = path.join(outputDirectory, '__sveltekit_env_init.js');
|
||||
write(
|
||||
initializer,
|
||||
create_env_module({
|
||||
environment: to_import_specifier(
|
||||
posixify(path.relative(path.dirname(initializer), provider))
|
||||
),
|
||||
set_env: to_import_specifier(
|
||||
posixify(path.relative(path.dirname(initializer), `${serverDirectory}/env.js`))
|
||||
)
|
||||
})
|
||||
);
|
||||
|
||||
return initializer;
|
||||
},
|
||||
|
||||
hasServerInstrumentationFile() {
|
||||
return fs.existsSync(`${config.outDir}/output/server/instrumentation.server.js`);
|
||||
},
|
||||
|
||||
instrument({
|
||||
entrypoint,
|
||||
instrumentation,
|
||||
start = path.join(path.dirname(entrypoint), 'start.js'),
|
||||
initializer,
|
||||
module = {
|
||||
exports: ['default']
|
||||
}
|
||||
}) {
|
||||
if (!fs.existsSync(instrumentation)) {
|
||||
e.adapter_instrumentation_file_missing({
|
||||
kind: 'Instrumentation file',
|
||||
file: instrumentation
|
||||
});
|
||||
}
|
||||
if (!fs.existsSync(entrypoint)) {
|
||||
e.adapter_instrumentation_file_missing({ kind: 'Entrypoint file', file: entrypoint });
|
||||
}
|
||||
if (!fs.existsSync(initializer)) {
|
||||
e.adapter_instrumentation_file_missing({
|
||||
kind: 'Instrumentation initializer',
|
||||
file: initializer
|
||||
});
|
||||
}
|
||||
|
||||
copy(entrypoint, start);
|
||||
if (fs.existsSync(`${entrypoint}.map`)) {
|
||||
copy(`${entrypoint}.map`, `${start}.map`);
|
||||
}
|
||||
|
||||
const relative_instrumentation = posixify(
|
||||
path.relative(path.dirname(entrypoint), instrumentation)
|
||||
);
|
||||
const relative_start = posixify(path.relative(path.dirname(entrypoint), start));
|
||||
const relative_initializer = posixify(path.relative(path.dirname(entrypoint), initializer));
|
||||
|
||||
const facade =
|
||||
'generateText' in module
|
||||
? module.generateText({
|
||||
instrumentation: relative_instrumentation,
|
||||
start: relative_start,
|
||||
initializer: relative_initializer
|
||||
})
|
||||
: create_instrumentation_facade({
|
||||
instrumentation: relative_instrumentation,
|
||||
start: relative_start,
|
||||
exports: module.exports,
|
||||
initializer: relative_initializer
|
||||
});
|
||||
|
||||
fs.rmSync(entrypoint, { force: true, recursive: true });
|
||||
write(entrypoint, facade);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Writes gzip and brotli variants next to `file`
|
||||
* @param {string} file
|
||||
*/
|
||||
async function compress_file(file) {
|
||||
const contents = await fs.promises.readFile(file);
|
||||
|
||||
const [gz, br] = await Promise.all([
|
||||
gzip(contents, { level: zlib.constants.Z_BEST_COMPRESSION }),
|
||||
brotli(contents)
|
||||
]);
|
||||
|
||||
await Promise.all([
|
||||
fs.promises.writeFile(`${file}.gz`, gz),
|
||||
fs.promises.writeFile(`${file}.br`, br)
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Given a list of exports, generate a facade that:
|
||||
* - Imports the environment initializer
|
||||
* - Imports the instrumentation file
|
||||
* - Imports `exports` from the entrypoint (dynamically)
|
||||
* - Re-exports `exports` from the entrypoint
|
||||
*
|
||||
* @param {{ instrumentation: string; start: string; exports: string[]; initializer: string }} opts
|
||||
* @returns {string}
|
||||
*/
|
||||
function create_instrumentation_facade({ instrumentation, start, exports, initializer }) {
|
||||
const { namespace, declarations, reexports } = create_exported_declarations(
|
||||
exports,
|
||||
(name, ns) => `${ns}.${name}`,
|
||||
'__mod'
|
||||
);
|
||||
|
||||
const parts = [
|
||||
`import ${JSON.stringify(to_import_specifier(initializer))};`,
|
||||
`import ${JSON.stringify(to_import_specifier(instrumentation))};`,
|
||||
`const ${namespace} = await import(${JSON.stringify(to_import_specifier(start))});`,
|
||||
declarations.join('\n'),
|
||||
reexports.length > 0 ? `export { ${reexports.join(', ')} };` : ''
|
||||
];
|
||||
|
||||
return parts.filter(Boolean).join('\n');
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {string} path
|
||||
*/
|
||||
function to_import_specifier(path) {
|
||||
return path.startsWith('.') ? path : `./${path}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {{ environment: string; set_env: string }} opts
|
||||
*/
|
||||
function create_env_module({ environment, set_env }) {
|
||||
return `import env from ${JSON.stringify(environment)};\nimport { set_env } from ${JSON.stringify(set_env)};\nset_env(env);\n`;
|
||||
}
|
||||
62
node_modules/@sveltejs/kit/src/core/adapt/index.js
generated
vendored
Normal file
62
node_modules/@sveltejs/kit/src/core/adapt/index.js
generated
vendored
Normal file
@@ -0,0 +1,62 @@
|
||||
import { styleText } from 'node:util';
|
||||
import { create_builder } from './builder.js';
|
||||
import * as w from '../../messages/build-warnings.js';
|
||||
|
||||
/**
|
||||
* @param {import('types').ValidatedConfig} config
|
||||
* @param {import('types').BuildData} build_data
|
||||
* @param {import('types').ServerMetadata} server_metadata
|
||||
* @param {import('types').Prerendered} prerendered
|
||||
* @param {import('types').PrerenderMap} prerender_map
|
||||
* @param {typeof import('$app/manifest')} app_manifest
|
||||
* @param {import('types').Logger} log
|
||||
* @param {import('types').RemoteChunk[]} remotes
|
||||
* @param {import('vite').ResolvedConfig} vite_config
|
||||
* @param {Record<string, import('@sveltejs/kit/env').EnvVarConfig<any>> | null} explicit_env_config
|
||||
*/
|
||||
export async function adapt(
|
||||
config,
|
||||
build_data,
|
||||
server_metadata,
|
||||
prerendered,
|
||||
prerender_map,
|
||||
app_manifest,
|
||||
log,
|
||||
remotes,
|
||||
vite_config,
|
||||
explicit_env_config
|
||||
) {
|
||||
const { name, adapt } = config.adapter;
|
||||
|
||||
console.log(styleText(['bold', 'cyan'], `\n> Using ${name}`));
|
||||
|
||||
let warned = false;
|
||||
|
||||
const builder = create_builder({
|
||||
config: {
|
||||
...config,
|
||||
get kit() {
|
||||
if (!warned) {
|
||||
warned = true;
|
||||
w.adapter_config_kit_deprecated();
|
||||
}
|
||||
|
||||
return config;
|
||||
}
|
||||
},
|
||||
build_data,
|
||||
server_metadata,
|
||||
route_data: build_data.manifest_data.routes.filter((route) => route.page || route.endpoint),
|
||||
prerendered,
|
||||
prerender_map,
|
||||
app_manifest,
|
||||
log,
|
||||
remotes,
|
||||
vite_config,
|
||||
explicit_env_config
|
||||
});
|
||||
|
||||
await adapt(builder);
|
||||
|
||||
log.success('done');
|
||||
}
|
||||
80
node_modules/@sveltejs/kit/src/core/config/default-error.html
generated
vendored
Normal file
80
node_modules/@sveltejs/kit/src/core/config/default-error.html
generated
vendored
Normal file
@@ -0,0 +1,80 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<title>%sveltekit.error.message%</title>
|
||||
|
||||
<style>
|
||||
body {
|
||||
--bg: white;
|
||||
--fg: #222;
|
||||
--divider: #ccc;
|
||||
background: var(--bg);
|
||||
color: var(--fg);
|
||||
font-family:
|
||||
system-ui,
|
||||
-apple-system,
|
||||
BlinkMacSystemFont,
|
||||
'Segoe UI',
|
||||
Roboto,
|
||||
Oxygen,
|
||||
Ubuntu,
|
||||
Cantarell,
|
||||
'Open Sans',
|
||||
'Helvetica Neue',
|
||||
sans-serif;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
height: 100vh;
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.error {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
max-width: 32rem;
|
||||
margin: 0 1rem;
|
||||
}
|
||||
|
||||
.status {
|
||||
font-weight: 200;
|
||||
font-size: 3rem;
|
||||
line-height: 1;
|
||||
position: relative;
|
||||
top: -0.05rem;
|
||||
}
|
||||
|
||||
.message {
|
||||
border-left: 1px solid var(--divider);
|
||||
padding: 0 0 0 1rem;
|
||||
margin: 0 0 0 1rem;
|
||||
min-height: 2.5rem;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.message h1 {
|
||||
font-weight: 400;
|
||||
font-size: 1em;
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
@media (prefers-color-scheme: dark) {
|
||||
body {
|
||||
--bg: #222;
|
||||
--fg: #ddd;
|
||||
--divider: #666;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="error">
|
||||
<span class="status">%sveltekit.status%</span>
|
||||
<div class="message">
|
||||
<h1>%sveltekit.error.message%</h1>
|
||||
</div>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
210
node_modules/@sveltejs/kit/src/core/config/index.js
generated
vendored
Normal file
210
node_modules/@sveltejs/kit/src/core/config/index.js
generated
vendored
Normal file
@@ -0,0 +1,210 @@
|
||||
/** @import { Config } from '@sveltejs/kit/vite' */
|
||||
/** @import { ValidatedConfig } from 'types' */
|
||||
/** @import { ResolvedConfig } from 'vite' */
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import process from 'node:process';
|
||||
import { styleText } from 'node:util';
|
||||
import { validate_options, kit_options, kit_experimental_options } from './options.js';
|
||||
import { resolve_entry } from '../../utils/filesystem.js';
|
||||
import { import_peer } from '../../utils/import.js';
|
||||
import { stackless } from '../../utils/error.js';
|
||||
import * as e from '../../messages/build-errors.js';
|
||||
|
||||
/**
|
||||
* Splits the config passed to the `sveltekit` Vite plugin into the options that
|
||||
* SvelteKit processes itself and the options that are forwarded to
|
||||
* `vite-plugin-svelte`. SvelteKit makes no assumptions about which options
|
||||
* `vite-plugin-svelte` accepts — it plucks out its own options and passes
|
||||
* everything else along (`vite-plugin-svelte` does its own validation).
|
||||
* @param {Config} config
|
||||
* @returns {{ svelte_config: Config, vite_plugin_svelte_config: Record<string, any> }}
|
||||
*/
|
||||
export function split_config(config) {
|
||||
/** @type {Config} */
|
||||
const svelte_config = {};
|
||||
|
||||
/** @type {Record<string, any>} */
|
||||
const vite_plugin_svelte_config = {};
|
||||
|
||||
for (const key in config) {
|
||||
if (key === 'experimental') {
|
||||
// `experimental` is a namespace that both SvelteKit and vite-plugin-svelte
|
||||
// use, so pluck out the flags SvelteKit recognises and pass the rest along
|
||||
const experimental = /** @type {Record<string, any>} */ (config[key]) ?? {};
|
||||
|
||||
/** @type {Record<string, any>} */
|
||||
const kit_experimental = {};
|
||||
/** @type {Record<string, any>} */
|
||||
const vps_experimental = {};
|
||||
|
||||
for (const flag in experimental) {
|
||||
if (kit_experimental_options.includes(flag)) {
|
||||
kit_experimental[flag] = experimental[flag];
|
||||
} else {
|
||||
vps_experimental[flag] = experimental[flag];
|
||||
}
|
||||
}
|
||||
|
||||
if (Object.keys(kit_experimental).length > 0) {
|
||||
svelte_config.experimental = kit_experimental;
|
||||
}
|
||||
if (Object.keys(vps_experimental).length > 0) {
|
||||
vite_plugin_svelte_config.experimental = vps_experimental;
|
||||
}
|
||||
} else if (kit_options.includes(key)) {
|
||||
// @ts-expect-error - we've verified this is one of SvelteKit's own options
|
||||
svelte_config[key] = config[key];
|
||||
} else {
|
||||
vite_plugin_svelte_config[key] = /** @type {Record<string, any>} */ (config)[key];
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
svelte_config,
|
||||
vite_plugin_svelte_config
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Loads the template (src/app.html by default) and validates that it has the
|
||||
* required content.
|
||||
* @param {string} cwd
|
||||
* @param {ValidatedConfig} config
|
||||
*/
|
||||
export function load_template(cwd, config) {
|
||||
const { files } = config;
|
||||
|
||||
const relative = path.relative(cwd, files.appTemplate);
|
||||
|
||||
if (!fs.existsSync(files.appTemplate)) {
|
||||
e.app_template_missing({ file: relative });
|
||||
}
|
||||
|
||||
const contents = fs.readFileSync(files.appTemplate, 'utf8');
|
||||
|
||||
const expected_tags = ['%sveltekit.head%', '%sveltekit.body%'];
|
||||
expected_tags.forEach((tag) => {
|
||||
if (contents.indexOf(tag) === -1) {
|
||||
e.app_template_tag_missing({ file: relative, tag });
|
||||
}
|
||||
});
|
||||
|
||||
return contents;
|
||||
}
|
||||
|
||||
/**
|
||||
* Loads the error page (src/error.html by default) if it exists.
|
||||
* Falls back to a generic error page content.
|
||||
* @param {ValidatedConfig} config
|
||||
*/
|
||||
export function load_error_page(config) {
|
||||
let { errorTemplate } = config.files;
|
||||
|
||||
// Don't do this inside resolving the config, because that would mean
|
||||
// adding/removing error.html isn't detected and would require a restart.
|
||||
if (!fs.existsSync(config.files.errorTemplate)) {
|
||||
errorTemplate = path.join(import.meta.dirname, 'default-error.html');
|
||||
}
|
||||
|
||||
return fs.readFileSync(errorTemplate, 'utf-8');
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {string} [config]
|
||||
* @param {typeof import('vite')} [vite]
|
||||
*/
|
||||
export async function load_vite_config(config, vite) {
|
||||
vite ??= /** @type {typeof import('vite')} */ (await import_peer('vite', process.cwd()));
|
||||
|
||||
return vite.resolveConfig({ configFile: config }, 'build', process.env.MODE ?? 'production');
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {ResolvedConfig} vite_config
|
||||
* @returns {ValidatedConfig}
|
||||
*/
|
||||
export function extract_svelte_config(vite_config) {
|
||||
const plugin = vite_config.plugins.find((p) => p.name === 'vite-plugin-sveltekit-setup');
|
||||
return plugin?.api.options ?? process_config(validate_config({}), vite_config.root);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {ValidatedConfig} config
|
||||
* @param {string} cwd
|
||||
* @returns {ValidatedConfig}
|
||||
*/
|
||||
export function process_config(config, cwd) {
|
||||
if (
|
||||
config.csp?.directives?.['require-trusted-types-for']?.includes('script') &&
|
||||
config.serviceWorker.register &&
|
||||
resolve_entry(path.resolve(cwd, config.files.serviceWorker), config.moduleExtensions) &&
|
||||
!config.csp?.directives?.['trusted-types']?.includes('sveltekit-trusted-url')
|
||||
) {
|
||||
e.config_csp_trusted_types_missing();
|
||||
}
|
||||
|
||||
config.outDir = path.resolve(cwd, config.outDir);
|
||||
config.env.dir = path.resolve(cwd, config.env.dir);
|
||||
|
||||
for (const key in config.files) {
|
||||
if (key === 'hooks') {
|
||||
config.files.hooks.client = path.resolve(cwd, config.files.hooks.client);
|
||||
config.files.hooks.server = path.resolve(cwd, config.files.hooks.server);
|
||||
config.files.hooks.universal = path.resolve(cwd, config.files.hooks.universal);
|
||||
} else if (key !== 'lib' /* TODO remove when we remove the `lib` option altogether */) {
|
||||
// @ts-expect-error
|
||||
config.files[key] = path.resolve(cwd, config.files[key]);
|
||||
}
|
||||
}
|
||||
|
||||
return config;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {Config} config
|
||||
* @returns {ValidatedConfig}
|
||||
*/
|
||||
export function validate_config(config) {
|
||||
try {
|
||||
if (typeof config !== 'object') {
|
||||
e.config_not_object();
|
||||
}
|
||||
|
||||
const validated = validate_options(config, 'config');
|
||||
const files = validated.files;
|
||||
|
||||
files.hooks.client ??= path.join(files.src, 'hooks.client');
|
||||
files.hooks.server ??= path.join(files.src, 'hooks.server');
|
||||
files.hooks.universal ??= path.join(files.src, 'hooks');
|
||||
files.params ??= path.join(files.src, 'params');
|
||||
files.routes ??= path.join(files.src, 'routes');
|
||||
files.serviceWorker ??= path.join(files.src, 'service-worker');
|
||||
files.appTemplate ??= path.join(files.src, 'app.html');
|
||||
files.errorTemplate ??= path.join(files.src, 'error.html');
|
||||
|
||||
if (validated.router.resolution === 'server') {
|
||||
if (validated.router.type === 'hash') {
|
||||
e.config_server_resolution_hash();
|
||||
}
|
||||
if (validated.output.bundleStrategy !== 'split') {
|
||||
e.config_server_resolution_bundle_strategy();
|
||||
}
|
||||
}
|
||||
|
||||
if (typeof config.adapter?.vite === 'function') {
|
||||
validated.adapter.vite = config.adapter.vite({
|
||||
config: validated
|
||||
});
|
||||
}
|
||||
|
||||
return validated;
|
||||
} catch (e) {
|
||||
const error = /** @type {Error} */ (e);
|
||||
|
||||
// Print a nicer version of the error to the console
|
||||
console.log(styleText(['bold', 'red'], `\n${error.message}\n`));
|
||||
|
||||
throw stackless('Failed to load SvelteKit options from Vite config');
|
||||
}
|
||||
}
|
||||
474
node_modules/@sveltejs/kit/src/core/config/options.js
generated
vendored
Normal file
474
node_modules/@sveltejs/kit/src/core/config/options.js
generated
vendored
Normal file
@@ -0,0 +1,474 @@
|
||||
/** @import { ValidatedConfig } from 'types' */
|
||||
/** @import { Validator } from './types.js' */
|
||||
import * as e from '../../messages/build-errors.js';
|
||||
import * as w from '../../messages/build-warnings.js';
|
||||
import { join_or } from '../../utils/format.js';
|
||||
|
||||
const directives = object({
|
||||
'child-src': string_array(),
|
||||
'default-src': string_array(),
|
||||
'frame-src': string_array(),
|
||||
'worker-src': string_array(),
|
||||
'connect-src': string_array(),
|
||||
'font-src': string_array(),
|
||||
'img-src': string_array(),
|
||||
'manifest-src': string_array(),
|
||||
'media-src': string_array(),
|
||||
'object-src': string_array(),
|
||||
'prefetch-src': string_array(),
|
||||
'script-src': string_array(),
|
||||
'script-src-elem': string_array(),
|
||||
'script-src-attr': string_array(),
|
||||
'style-src': string_array(),
|
||||
'style-src-elem': string_array(),
|
||||
'style-src-attr': string_array(),
|
||||
'base-uri': string_array(),
|
||||
sandbox: string_array(),
|
||||
'form-action': string_array(),
|
||||
'frame-ancestors': string_array(),
|
||||
'navigate-to': string_array(),
|
||||
'report-uri': string_array(),
|
||||
'report-to': string_array(),
|
||||
'require-trusted-types-for': string_array(),
|
||||
'trusted-types': string_array(),
|
||||
'upgrade-insecure-requests': boolean(false),
|
||||
'require-sri-for': string_array(),
|
||||
'block-all-mixed-content': boolean(false),
|
||||
'plugin-types': string_array(),
|
||||
referrer: string_array()
|
||||
});
|
||||
|
||||
const prerender_handler = validate(undefined, (input, keypath) => {
|
||||
if (typeof input === 'function') return input;
|
||||
if (['fail', 'warn', 'ignore'].includes(input)) return input;
|
||||
e.config_invalid_prerender_handler({ keypath });
|
||||
});
|
||||
|
||||
const options = {
|
||||
adapter: validate(undefined, (input, keypath) => {
|
||||
if (typeof input !== 'object' || !input.adapt) {
|
||||
e.config_invalid_adapter({ keypath });
|
||||
}
|
||||
|
||||
return input;
|
||||
}),
|
||||
|
||||
alias: deprecate(
|
||||
validate({}, (input, keypath) => {
|
||||
if (typeof input !== 'object') {
|
||||
e.config_expected_object({ keypath });
|
||||
}
|
||||
|
||||
for (const key in input) {
|
||||
assert_string(input[key], `${keypath}.${key}`);
|
||||
}
|
||||
|
||||
return input;
|
||||
}),
|
||||
w.config_option_deprecated_alias
|
||||
),
|
||||
|
||||
appDir: validate('_app', (input, keypath) => {
|
||||
assert_string(input, keypath);
|
||||
|
||||
if (input) {
|
||||
if (input.startsWith('/') || input.endsWith('/')) {
|
||||
e.config_app_dir_slash({ keypath });
|
||||
}
|
||||
} else {
|
||||
e.config_empty_string({ keypath });
|
||||
}
|
||||
|
||||
return input;
|
||||
}),
|
||||
|
||||
compilerOptions: any(),
|
||||
|
||||
csp: object({
|
||||
mode: list(['auto', 'hash', 'nonce']),
|
||||
directives,
|
||||
reportOnly: directives
|
||||
}),
|
||||
|
||||
csrf: object({
|
||||
checkOrigin: removed(e.config_option_removed_check_origin),
|
||||
trustedOrigins: string_array([])
|
||||
}),
|
||||
|
||||
embedded: boolean(false),
|
||||
|
||||
env: object({
|
||||
dir: string('')
|
||||
}),
|
||||
|
||||
experimental: object(
|
||||
{
|
||||
tracing: removed(e.config_option_removed_experimental_tracing),
|
||||
instrumentation: removed(e.config_option_removed_experimental_instrumentation),
|
||||
remoteFunctions: boolean(false),
|
||||
forkPreloads: boolean(false),
|
||||
handleRenderingErrors: removed()
|
||||
},
|
||||
true
|
||||
),
|
||||
|
||||
extensions: validate(['.svelte'], (input, keypath) => {
|
||||
if (!Array.isArray(input) || !input.every((page) => typeof page === 'string')) {
|
||||
e.config_expected_string_array({ keypath });
|
||||
}
|
||||
|
||||
input.forEach((extension) => {
|
||||
if (extension[0] !== '.') {
|
||||
e.config_extension_missing_dot({ keypath, extension });
|
||||
}
|
||||
|
||||
if (!/^(\.[a-z0-9]+)+$/i.test(extension)) {
|
||||
e.config_extension_invalid({ extension });
|
||||
}
|
||||
});
|
||||
|
||||
return input;
|
||||
}),
|
||||
|
||||
files: object({
|
||||
src: string('src'),
|
||||
assets: string('static'),
|
||||
hooks: object({
|
||||
client: string(null),
|
||||
server: string(null),
|
||||
universal: string(null)
|
||||
}),
|
||||
lib: removed(e.config_option_removed_files_lib),
|
||||
params: string(null),
|
||||
routes: string(null),
|
||||
serviceWorker: string(null),
|
||||
appTemplate: string(null),
|
||||
errorTemplate: string(null)
|
||||
}),
|
||||
|
||||
inlineStyleThreshold: number(0),
|
||||
|
||||
moduleExtensions: string_array(['.js', '.ts']),
|
||||
|
||||
kit: validate(undefined, (input) => {
|
||||
const keys = Object.keys(input)
|
||||
.map((key) => `\`${key}\``)
|
||||
.join(', ');
|
||||
|
||||
e.config_kit_namespace({ keys });
|
||||
}),
|
||||
|
||||
outDir: string('.svelte-kit'),
|
||||
|
||||
output: object({
|
||||
linkHeaderPreload: boolean(false),
|
||||
preloadStrategy: removed(e.config_option_removed_preload_strategy),
|
||||
bundleStrategy: list(['split', 'single', 'inline'])
|
||||
}),
|
||||
|
||||
paths: object({
|
||||
base: validate('', (input, keypath) => {
|
||||
assert_string(input, keypath);
|
||||
|
||||
if (input !== '' && (input.endsWith('/') || !input.startsWith('/'))) {
|
||||
e.config_paths_base_invalid({ keypath });
|
||||
}
|
||||
|
||||
return input;
|
||||
}),
|
||||
assets: validate('', (input, keypath) => {
|
||||
assert_string(input, keypath);
|
||||
|
||||
if (input) {
|
||||
if (!/^[a-z]+:\/\//.test(input)) {
|
||||
e.config_paths_assets_not_absolute({ keypath });
|
||||
}
|
||||
|
||||
if (input.endsWith('/')) {
|
||||
e.config_paths_assets_trailing_slash({ keypath });
|
||||
}
|
||||
}
|
||||
|
||||
return input;
|
||||
}),
|
||||
origin: validate(undefined, (input, keypath) => {
|
||||
assert_string(input, keypath);
|
||||
|
||||
let url;
|
||||
|
||||
try {
|
||||
url = new URL(input);
|
||||
} catch {
|
||||
e.config_origin_invalid({ keypath, input });
|
||||
}
|
||||
|
||||
if (url.protocol !== 'http:' && url.protocol !== 'https:') {
|
||||
e.config_origin_protocol({ keypath, protocol: url.protocol });
|
||||
}
|
||||
|
||||
const origin = url.origin;
|
||||
|
||||
if (input !== origin) {
|
||||
e.config_origin_has_path({ keypath, input, origin });
|
||||
}
|
||||
|
||||
return origin;
|
||||
}),
|
||||
relative: boolean(true)
|
||||
}),
|
||||
|
||||
preprocess: any(),
|
||||
|
||||
prerender: object({
|
||||
concurrency: validate(1, (input, keypath) => {
|
||||
if (!Number.isInteger(input) || input < 1) {
|
||||
e.config_expected_positive_integer({ keypath });
|
||||
}
|
||||
|
||||
return input;
|
||||
}),
|
||||
crawl: boolean(true),
|
||||
entries: validate(['*'], (input, keypath) => {
|
||||
if (!Array.isArray(input) || !input.every((page) => typeof page === 'string')) {
|
||||
e.config_expected_string_array({ keypath });
|
||||
}
|
||||
|
||||
input.forEach((page) => {
|
||||
if (page !== '*' && page[0] !== '/') {
|
||||
e.config_prerender_entry_invalid({ keypath, entry: page });
|
||||
}
|
||||
});
|
||||
|
||||
return input;
|
||||
}),
|
||||
|
||||
handleHttpError: prerender_handler,
|
||||
handleMissingId: prerender_handler,
|
||||
handleEntryGeneratorMismatch: prerender_handler,
|
||||
handleUnseenRoutes: prerender_handler,
|
||||
handleInvalidUrl: prerender_handler,
|
||||
|
||||
origin: removed(e.config_option_removed_prerender_origin)
|
||||
}),
|
||||
|
||||
router: object({
|
||||
type: list(['pathname', 'hash']),
|
||||
resolution: list(['client', 'server'])
|
||||
}),
|
||||
|
||||
serviceWorker: object({
|
||||
files: removed(),
|
||||
register: boolean(true),
|
||||
// options could be undefined but if it is defined we only validate that
|
||||
// it's an object since the type comes from the browser itself
|
||||
options: validate(undefined, object({}, true))
|
||||
}),
|
||||
|
||||
tracing: object({
|
||||
server: boolean(false)
|
||||
}),
|
||||
|
||||
typescript: deprecate(
|
||||
object({
|
||||
config: fun()
|
||||
}),
|
||||
w.config_option_deprecated_typescript
|
||||
),
|
||||
|
||||
version: object({
|
||||
name: string(Date.now().toString()),
|
||||
pollInterval: number(3_600_000)
|
||||
}),
|
||||
|
||||
vitePlugin: removed(e.config_option_removed_vite_plugin)
|
||||
};
|
||||
|
||||
/** @type {Validator<ValidatedConfig>} */
|
||||
export const validate_options = object(options, true);
|
||||
|
||||
/**
|
||||
* @param {Validator} fn
|
||||
* @param {(values: { keypath: string }) => void} warn
|
||||
* @returns {Validator}
|
||||
*/
|
||||
function deprecate(fn, warn = w.config_option_deprecated) {
|
||||
return (input, keypath) => {
|
||||
if (input !== undefined) {
|
||||
warn({ keypath });
|
||||
}
|
||||
|
||||
return fn(input, keypath);
|
||||
};
|
||||
}
|
||||
|
||||
// Derive the names of SvelteKit's own config options from the schema, so they
|
||||
// stay in sync automatically. These are used to separate Kit's options from
|
||||
// `vite-plugin-svelte`'s options when config is passed via the Vite plugin.
|
||||
const kit_defaults = validate_options({}, 'config');
|
||||
|
||||
/** The names of the options that live under the `kit` namespace */
|
||||
export const kit_options = Object.keys(kit_defaults);
|
||||
|
||||
/** The names of the options that live under the `kit.experimental` namespace */
|
||||
export const kit_experimental_options = Object.keys(kit_defaults.experimental);
|
||||
|
||||
/**
|
||||
* @param {(values: { keypath: string }) => never} error
|
||||
* @returns {Validator}
|
||||
*/
|
||||
function removed(error = e.config_option_removed) {
|
||||
return (input, keypath) => {
|
||||
if (typeof input !== 'undefined') {
|
||||
error({ keypath });
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {Record<string, Validator>} children
|
||||
* @param {boolean} [allow_unknown]
|
||||
* @returns {Validator}
|
||||
*/
|
||||
export function object(children, allow_unknown = false) {
|
||||
return (input, keypath) => {
|
||||
/** @type {Record<string, any>} */
|
||||
const output = {};
|
||||
|
||||
if ((input && typeof input !== 'object') || Array.isArray(input)) {
|
||||
e.config_expected_object({ keypath });
|
||||
}
|
||||
|
||||
for (const key in input) {
|
||||
if (!(key in children)) {
|
||||
if (allow_unknown) {
|
||||
const value = input[key];
|
||||
if (value !== undefined) output[key] = value;
|
||||
} else {
|
||||
// special case
|
||||
const suggestion =
|
||||
keypath === 'config.kit' && key in kit_options ? `config.${key}` : undefined;
|
||||
|
||||
e.config_unexpected_option({ keypath: `${keypath}.${key}`, suggestion });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for (const key in children) {
|
||||
const validator = children[key];
|
||||
output[key] = validator(input && input[key], `${keypath}.${key}`);
|
||||
}
|
||||
|
||||
return output;
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {any} fallback
|
||||
* @param {(value: any, keypath: string) => any} fn
|
||||
* @returns {Validator}
|
||||
*/
|
||||
export function validate(fallback, fn) {
|
||||
return (input, keypath) => {
|
||||
return input === undefined ? fallback : fn(input, keypath);
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {string | null} fallback
|
||||
* @param {boolean} allow_empty
|
||||
* @returns {Validator}
|
||||
*/
|
||||
function string(fallback, allow_empty = true) {
|
||||
return validate(fallback, (input, keypath) => {
|
||||
assert_string(input, keypath);
|
||||
|
||||
if (!allow_empty && input === '') {
|
||||
e.config_empty_string({ keypath });
|
||||
}
|
||||
|
||||
return input;
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {string[] | undefined} [fallback]
|
||||
* @returns {Validator}
|
||||
*/
|
||||
function string_array(fallback) {
|
||||
return validate(fallback, (input, keypath) => {
|
||||
if (!Array.isArray(input) || input.some((value) => typeof value !== 'string')) {
|
||||
e.config_expected_string_array({ keypath });
|
||||
}
|
||||
|
||||
return input;
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {number} fallback
|
||||
* @returns {Validator}
|
||||
*/
|
||||
function number(fallback) {
|
||||
return validate(fallback, (input, keypath) => {
|
||||
if (typeof input !== 'number') {
|
||||
e.config_expected_number({ keypath });
|
||||
}
|
||||
return input;
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {boolean} fallback
|
||||
* @returns {Validator}
|
||||
*/
|
||||
function boolean(fallback) {
|
||||
return validate(fallback, (input, keypath) => {
|
||||
if (typeof input !== 'boolean') {
|
||||
e.config_expected_boolean({ keypath });
|
||||
}
|
||||
return input;
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {string[]} options
|
||||
* @returns {Validator}
|
||||
*/
|
||||
function list(options, fallback = options[0]) {
|
||||
return validate(fallback, (input, keypath) => {
|
||||
if (!options.includes(input)) {
|
||||
const quoted = options.map((option) => `"${option}"`);
|
||||
const expected =
|
||||
options.length > 2 ? `one of ${join_or(quoted)}` : `either ${join_or(quoted)}`;
|
||||
|
||||
e.config_expected_one_of({ keypath, options: expected });
|
||||
}
|
||||
return input;
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* @returns {Validator}
|
||||
*/
|
||||
function fun() {
|
||||
return validate(undefined, (input, keypath) => {
|
||||
if (typeof input !== 'function') {
|
||||
e.config_expected_function({ keypath });
|
||||
}
|
||||
return input;
|
||||
});
|
||||
}
|
||||
|
||||
function any() {
|
||||
return validate(undefined, (input) => input);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {string} input
|
||||
* @param {string} keypath
|
||||
*/
|
||||
function assert_string(input, keypath) {
|
||||
if (typeof input !== 'string') {
|
||||
e.config_expected_string({ keypath });
|
||||
}
|
||||
}
|
||||
1
node_modules/@sveltejs/kit/src/core/config/types.d.ts
generated
vendored
Normal file
1
node_modules/@sveltejs/kit/src/core/config/types.d.ts
generated
vendored
Normal file
@@ -0,0 +1 @@
|
||||
export type Validator<T = any> = (input: any, keypath: string) => T;
|
||||
443
node_modules/@sveltejs/kit/src/core/env.js
generated
vendored
Normal file
443
node_modules/@sveltejs/kit/src/core/env.js
generated
vendored
Normal file
@@ -0,0 +1,443 @@
|
||||
/** @import { StandardSchemaV1 } from '@standard-schema/spec' */
|
||||
/** @import { EnvVarConfig } from '@sveltejs/kit/env' */
|
||||
/** @import { ValidatedConfig } from 'types' */
|
||||
import path from 'node:path';
|
||||
import * as devalue from 'devalue';
|
||||
import { dedent } from './sync/utils.js';
|
||||
import { get_global_name, runtime_directory } from './utils.js';
|
||||
import * as e from '../messages/build-errors.js';
|
||||
import { resolve_entry } from '../utils/filesystem.js';
|
||||
import { handle_issues, validate } from '../exports/internal/env.js';
|
||||
import { get_config_aliases } from '../exports/vite/utils.js';
|
||||
import { get_runner } from '../runner.js';
|
||||
import { import_peer } from '../utils/import.js';
|
||||
import { posixify } from '../utils/os.js';
|
||||
|
||||
/**
|
||||
* @typedef {'public' | 'private'} EnvType
|
||||
*/
|
||||
|
||||
/**
|
||||
* @param {ValidatedConfig} config
|
||||
* @param {string} root
|
||||
* @returns {string | null}
|
||||
*/
|
||||
export function resolve_env_entry(config, root) {
|
||||
const entry = resolve_entry(path.resolve(root, config.files.src, 'env'), config.moduleExtensions);
|
||||
// posix, like the paths Vite hands to `hotUpdate`
|
||||
return entry && posixify(entry);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {ValidatedConfig} kit
|
||||
* @param {string | null} file
|
||||
* @param {string} root
|
||||
* @param {string} mode
|
||||
* @returns {Promise<{ variables: Record<string, EnvVarConfig<any>> | null, deps: Set<string> }>}
|
||||
*/
|
||||
export async function load_explicit_env(kit, file, root, mode) {
|
||||
/** @type {Set<string>} */
|
||||
const deps = new Set();
|
||||
/** @type {Map<EnvType, string>} */
|
||||
const env_importers = new Map();
|
||||
|
||||
if (!file) {
|
||||
return { variables: null, deps };
|
||||
}
|
||||
|
||||
/** @type {typeof import('vite')} */
|
||||
const vite = await import_peer('vite', root);
|
||||
|
||||
const server = await vite.createServer({
|
||||
configFile: false,
|
||||
logLevel: 'silent',
|
||||
server: { watch: null },
|
||||
mode,
|
||||
define: {
|
||||
// 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: [
|
||||
{ find: '$app/env', replacement: `${runtime_directory}/app/env` },
|
||||
...get_config_aliases(kit, root)
|
||||
]
|
||||
},
|
||||
plugins: [
|
||||
{
|
||||
name: 'dependency-scanner',
|
||||
enforce: 'pre',
|
||||
resolveId(id, importer) {
|
||||
const prefixes = ['$app/env/', `${runtime_directory}/app/env/`];
|
||||
const prefix = prefixes.find((prefix) => id.startsWith(prefix));
|
||||
const type = prefix && id.slice(prefix.length);
|
||||
|
||||
if (importer && (type === 'private' || type === 'public')) {
|
||||
env_importers.set(type, importer);
|
||||
}
|
||||
},
|
||||
load(id) {
|
||||
deps.add(id);
|
||||
}
|
||||
}
|
||||
]
|
||||
});
|
||||
|
||||
/** @type {Record<string, EnvVarConfig<any>>} */
|
||||
let variables;
|
||||
|
||||
const runner = get_runner(vite, server);
|
||||
|
||||
/** @type {typeof import('../runtime/app/env/server.js')} */ (
|
||||
await runner.import(`${runtime_directory}/app/env/server.js`)
|
||||
).set_building();
|
||||
|
||||
try {
|
||||
({ variables } = await runner.import(file));
|
||||
|
||||
if (!variables || typeof variables !== 'object') {
|
||||
e.env_variables_missing({ file });
|
||||
}
|
||||
|
||||
// validate
|
||||
for (const name of Object.keys(variables)) {
|
||||
if (!valid_identifier.test(name) || reserved.has(name)) {
|
||||
e.env_invalid_variable_name({ name: JSON.stringify(name) });
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
const error = /** @type {any} */ (err || {});
|
||||
|
||||
if (error.code === 'ERR_MODULE_NOT_FOUND') {
|
||||
const match = error.message?.match(
|
||||
/<sveltekit:generated>\/env\/(private|public)\/server\.js/
|
||||
);
|
||||
|
||||
if (match) {
|
||||
const type = /** @type {EnvType} */ (match[1]);
|
||||
const importer = env_importers.get(type);
|
||||
// the stack trace would only point into Vite's module runner
|
||||
e.env_circular_import(
|
||||
{ type, importer: importer && posixify(path.relative(root, importer)) },
|
||||
{ stackless: true }
|
||||
);
|
||||
}
|
||||
|
||||
if (error.message?.includes(`Cannot find module '$app`)) {
|
||||
e.env_app_import(undefined, { cause: err });
|
||||
}
|
||||
}
|
||||
|
||||
throw error;
|
||||
} finally {
|
||||
await server.close();
|
||||
}
|
||||
|
||||
return { variables, deps };
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates the `<sveltekit:generated>/env/*` modules, keyed by path relative to `dir`. Every module
|
||||
* derives from one pass over `variables`, so an inlined value is validated once per build.
|
||||
* @param {ValidatedConfig} config
|
||||
* @param {Record<string, EnvVarConfig<any>> | null} variables
|
||||
* @param {Record<string, string>} env
|
||||
* @param {string} dir
|
||||
* @param {string | null} entry
|
||||
* @param {boolean} is_dev
|
||||
* @returns {Record<string, string>}
|
||||
*/
|
||||
export function create_env_modules(config, variables, env, dir, entry, is_dev) {
|
||||
/** @type {Record<string, StandardSchemaV1.Issue[]>} */
|
||||
const issues = {};
|
||||
|
||||
/** @type {Record<string, string>} */
|
||||
const dev_env = {};
|
||||
|
||||
/** @type {string[]} */
|
||||
const declarations = [];
|
||||
/** @type {string[]} */
|
||||
const setters = [];
|
||||
/** @type {string[]} */
|
||||
const public_exports = [];
|
||||
/** @type {string[]} */
|
||||
const private_exports = [];
|
||||
/** @type {string[]} */
|
||||
const sw_properties = [];
|
||||
|
||||
let sw_dynamic = false;
|
||||
|
||||
for (const [name, { public: is_public, static: is_static }] of Object.entries(variables ?? {})) {
|
||||
if (is_dev && name in env) dev_env[name] = env[name];
|
||||
|
||||
const exports = is_public ? public_exports : private_exports;
|
||||
|
||||
if (is_static) {
|
||||
const value = devalue.uneval(validate(variables ?? {}, env[name], name, issues));
|
||||
exports.push(`export const ${name} = ${value};\n`);
|
||||
|
||||
if (is_public) {
|
||||
declarations.push(`explicit_public_env.${name} = ${value};`);
|
||||
sw_properties.push(`${name}: ${value}`);
|
||||
}
|
||||
} else {
|
||||
exports.push(`export const ${name} = env.${name};\n`);
|
||||
setters.push(
|
||||
`const ${name} = validate(variables, env.${name}, ${JSON.stringify(name)}, issues);`
|
||||
);
|
||||
|
||||
if (is_public) {
|
||||
setters.push(`explicit_public_env.${name} = ${name};`);
|
||||
setters.push(`rendered_env.${name} = ${name};`);
|
||||
sw_dynamic = true;
|
||||
// in dev there is no prerendered env module, so the service worker inlines the value
|
||||
if (is_dev) {
|
||||
const value = devalue.uneval(validate(variables ?? {}, env[name], name, issues));
|
||||
sw_properties.push(`${name}: ${value}`);
|
||||
}
|
||||
} else {
|
||||
setters.push(`dynamic_private_env.${name} = ${name};`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
handle_issues(issues);
|
||||
|
||||
const config_blocks = [
|
||||
entry
|
||||
? [
|
||||
`import { variables } from ${JSON.stringify(entry)};`,
|
||||
`import { validate, handle_issues } from '@sveltejs/kit/internal/env';`
|
||||
].join('\n')
|
||||
: [`const variables = {};`, `const handle_issues = () => {};`].join('\n'),
|
||||
`const issues = {};`,
|
||||
'export { variables }',
|
||||
'export const dynamic_private_env = {};',
|
||||
'export const explicit_public_env = {};',
|
||||
'export const rendered_env = {};',
|
||||
...declarations,
|
||||
`handle_issues(issues);`,
|
||||
dedent`
|
||||
export function set_env(env) {
|
||||
const issues = {};
|
||||
${setters.join('\n')}
|
||||
handle_issues(issues);
|
||||
}`
|
||||
];
|
||||
|
||||
if (is_dev) {
|
||||
// In dev, initialise the env immediately. Tools like `vite-node` load modules
|
||||
// through the Vite config but don't run the SvelteKit dev server, which is what
|
||||
// normally calls `set_env`. Without this, dynamic env vars imported from
|
||||
// `$app/env/public` and `$app/env/private` would be `undefined` in such contexts.
|
||||
config_blocks.push(`set_env(${devalue.uneval(dev_env)});`);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {string} prelude
|
||||
* @param {string[]} exports
|
||||
*/
|
||||
const module = (prelude, exports) => (variables ? `${prelude}\n\n${exports.join('')}` : '');
|
||||
|
||||
const global = `globalThis.${get_global_name(config.version.name, is_dev)}`;
|
||||
|
||||
const version = JSON.stringify(config.version.name);
|
||||
|
||||
// a production build with dynamic public env vars loads them at runtime via an import of
|
||||
// the prerendered `env.js`; otherwise the values are inlined
|
||||
const service_worker =
|
||||
!is_dev && sw_dynamic
|
||||
? dedent`
|
||||
import { env } from '${config.paths.base}/${config.appDir}/env.js';
|
||||
|
||||
${global} = {
|
||||
base: location.pathname.split('/').slice(0, -1).join('/'),
|
||||
env,
|
||||
version: ${version}
|
||||
};
|
||||
`
|
||||
: dedent`
|
||||
${global} = {
|
||||
base: location.pathname.split('/').slice(0, -1).join('/'),
|
||||
env: {
|
||||
${sw_properties.join(',\n\t\t') || '// empty'}
|
||||
},
|
||||
version: ${version}
|
||||
};
|
||||
`;
|
||||
|
||||
return {
|
||||
'config.js': config_blocks.join('\n\n'),
|
||||
'public/server.js': module(
|
||||
`import { rendered_env as env } from '../config.js';`,
|
||||
public_exports
|
||||
),
|
||||
'private/server.js': module(
|
||||
`import { dynamic_private_env as env } from '../config.js';`,
|
||||
private_exports
|
||||
),
|
||||
'public/client.js': module(
|
||||
is_dev
|
||||
? `const { env } = ${global};`
|
||||
: `import { payload } from ${JSON.stringify(posixify(path.relative(`${dir}/public`, `${runtime_directory}/client/payload.js`)))};\nconst env = payload.env;`,
|
||||
public_exports
|
||||
),
|
||||
'service-worker.js': service_worker
|
||||
};
|
||||
}
|
||||
|
||||
/** @param {string} description */
|
||||
function create_jsdoc(description) {
|
||||
return `/**\n${description
|
||||
.split('\n')
|
||||
.map((line) => ` * ${line.replaceAll('*/', '*\\/')}`)
|
||||
.join('\n')}\n */`;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {Record<string, EnvVarConfig<any>>} variables
|
||||
* @param {string} relative
|
||||
* @param {EnvType} type
|
||||
*/
|
||||
export function create_explicit_env_types(variables, relative, type) {
|
||||
const declarations = Object.entries(variables)
|
||||
.filter(([_, config]) => !!config.public === (type === 'public'))
|
||||
.map(([name, config]) => {
|
||||
const comment = config.description ? `${create_jsdoc(config.description)}\n` : '';
|
||||
const type = config.schema
|
||||
? `import('@sveltejs/kit/internal/types').StandardSchemaV1.InferOutput<typeof import('${relative}').variables.${name}.schema>`
|
||||
: 'string';
|
||||
return `${comment}export const ${name}: ${type};`;
|
||||
});
|
||||
|
||||
return dedent`
|
||||
declare module '$app/env/${type}' {
|
||||
${declarations.join('\n') || `// no ${type} environment variables were defined`}
|
||||
}
|
||||
`;
|
||||
}
|
||||
|
||||
export const reserved = new Set([
|
||||
'do',
|
||||
'if',
|
||||
'in',
|
||||
'for',
|
||||
'let',
|
||||
'new',
|
||||
'try',
|
||||
'var',
|
||||
'case',
|
||||
'else',
|
||||
'enum',
|
||||
'eval',
|
||||
'null',
|
||||
'this',
|
||||
'true',
|
||||
'void',
|
||||
'with',
|
||||
'await',
|
||||
'break',
|
||||
'catch',
|
||||
'class',
|
||||
'const',
|
||||
'false',
|
||||
'super',
|
||||
'throw',
|
||||
'while',
|
||||
'yield',
|
||||
'delete',
|
||||
'export',
|
||||
'import',
|
||||
'public',
|
||||
'return',
|
||||
'static',
|
||||
'switch',
|
||||
'typeof',
|
||||
'default',
|
||||
'extends',
|
||||
'finally',
|
||||
'package',
|
||||
'private',
|
||||
'continue',
|
||||
'debugger',
|
||||
'function',
|
||||
'arguments',
|
||||
'interface',
|
||||
'protected',
|
||||
'implements',
|
||||
'instanceof'
|
||||
]);
|
||||
|
||||
export const valid_identifier = /^[a-zA-Z_$][a-zA-Z0-9_$]*$/;
|
||||
|
||||
/**
|
||||
* Generates `export const` declarations (and, for reserved-word names that need
|
||||
* aliasing, `const` + re-export specifiers) for a set of named exports.
|
||||
*
|
||||
* For regular names, emits a single efficient `export const name = expr;` statement.
|
||||
* For reserved-word names (e.g. `delete`, `class`), emits `const alias = expr;` plus
|
||||
* a re-export specifier (`alias as name`), since reserved words can't be `const`
|
||||
* binding names but CAN appear in export specifiers.
|
||||
*
|
||||
* You can do evil things like `export { c as class }`. In order to import/re-export
|
||||
* these, you need to alias the binding, then un-alias it when re-exporting:
|
||||
*
|
||||
* const _0 = ...; // safe binding name
|
||||
* export { _0 as class }; // valid — `class` is allowed in export specifiers
|
||||
*
|
||||
* Aliases are chosen to avoid collisions with any of the supplied names. The
|
||||
* namespace binding (used to hold the imported module) is likewise chosen to
|
||||
* avoid collisions.
|
||||
*
|
||||
* @param {Iterable<string>} names — the export names
|
||||
* @param {(name: string, namespace: string) => string} build_expression —
|
||||
* called for each name to produce the right-hand side of the declaration;
|
||||
* receives the chosen namespace binding so it can reference the imported module
|
||||
* @param {string} namespace_prefix — the preferred binding name for the namespace
|
||||
* (suffixed with a number if it collides with any export name)
|
||||
* @returns {{ namespace: string, declarations: string[], reexports: string[] }}
|
||||
*/
|
||||
export function create_exported_declarations(names, build_expression, namespace_prefix) {
|
||||
/** @type {Set<string>} */
|
||||
const set = new Set(names);
|
||||
|
||||
let namespace = namespace_prefix;
|
||||
let namespace_index = 0;
|
||||
while (set.has(namespace)) {
|
||||
namespace = `${namespace_prefix}${namespace_index++}`;
|
||||
}
|
||||
|
||||
let alias_index = 0;
|
||||
/** @type {Map<string, string>} */
|
||||
const aliases = new Map();
|
||||
|
||||
for (const name of set) {
|
||||
if (!reserved.has(name)) continue;
|
||||
|
||||
let alias = `_${alias_index++}`;
|
||||
while (set.has(alias)) {
|
||||
alias = `_${alias_index++}`;
|
||||
}
|
||||
aliases.set(name, alias);
|
||||
}
|
||||
|
||||
/** @type {string[]} */
|
||||
const declarations = [];
|
||||
/** @type {string[]} */
|
||||
const reexports = [];
|
||||
|
||||
for (const name of set) {
|
||||
const alias = aliases.get(name);
|
||||
const expr = build_expression(name, namespace);
|
||||
if (alias) {
|
||||
declarations.push(`const ${alias} = ${expr};`);
|
||||
reexports.push(`${alias} as ${name}`);
|
||||
} else {
|
||||
declarations.push(`export const ${name} = ${expr};`);
|
||||
}
|
||||
}
|
||||
|
||||
return { namespace, declarations, reexports };
|
||||
}
|
||||
24
node_modules/@sveltejs/kit/src/core/features.js
generated
vendored
Normal file
24
node_modules/@sveltejs/kit/src/core/features.js
generated
vendored
Normal file
@@ -0,0 +1,24 @@
|
||||
import * as e from '../messages/build-errors.js';
|
||||
|
||||
/**
|
||||
* @param {string} route_id
|
||||
* @param {Record<string, any>} config
|
||||
* @param {string} feature
|
||||
* @param {import('@sveltejs/kit').Adapter | undefined} adapter
|
||||
*/
|
||||
export function check_feature(route_id, config, feature, adapter) {
|
||||
if (!adapter) return;
|
||||
|
||||
switch (feature) {
|
||||
case '$app/server:read': {
|
||||
const supported = adapter.supports?.read?.({
|
||||
route: { id: route_id },
|
||||
config
|
||||
});
|
||||
|
||||
if (!supported) {
|
||||
e.adapter_read_unsupported({ route: route_id, adapter: adapter.name });
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
57
node_modules/@sveltejs/kit/src/core/generate_manifest/find_server_assets.js
generated
vendored
Normal file
57
node_modules/@sveltejs/kit/src/core/generate_manifest/find_server_assets.js
generated
vendored
Normal file
@@ -0,0 +1,57 @@
|
||||
import { find_deps } from '../../exports/vite/build/utils.js';
|
||||
|
||||
/**
|
||||
* Finds all the assets that are imported by server files associated with `routes`
|
||||
* @param {import('types').BuildData} build_data
|
||||
* @param {import('types').RouteData[]} routes
|
||||
* @param {string} root
|
||||
*/
|
||||
export function find_server_assets(build_data, routes, root) {
|
||||
/**
|
||||
* All nodes actually used in the routes definition (prerendered routes are omitted).
|
||||
* Root layout/error is always included as they are needed for 404 and root errors.
|
||||
* @type {Set<any>}
|
||||
*/
|
||||
const used_nodes = new Set([0, 1]);
|
||||
|
||||
/** @type {Set<string>} */
|
||||
const server_assets = new Set();
|
||||
|
||||
/** @param {string} id */
|
||||
function add_assets(id) {
|
||||
if (id in build_data.server_manifest) {
|
||||
const deps = find_deps(build_data.server_manifest, id, false, root);
|
||||
for (const asset of deps.assets) {
|
||||
server_assets.add(asset);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for (const route of routes) {
|
||||
if (route.page) {
|
||||
for (const i of route.page.layouts) used_nodes.add(i);
|
||||
for (const i of route.page.errors) used_nodes.add(i);
|
||||
used_nodes.add(route.page.leaf);
|
||||
}
|
||||
|
||||
if (route.endpoint) {
|
||||
add_assets(route.endpoint.file);
|
||||
}
|
||||
}
|
||||
|
||||
for (const n of used_nodes) {
|
||||
const node = build_data.manifest_data.nodes[n];
|
||||
if (node?.universal) add_assets(node.universal);
|
||||
if (node?.server) add_assets(node.server);
|
||||
}
|
||||
|
||||
if (build_data.manifest_data.hooks.server) {
|
||||
add_assets(build_data.manifest_data.hooks.server);
|
||||
}
|
||||
|
||||
if (build_data.manifest_data.hooks.universal) {
|
||||
add_assets(build_data.manifest_data.hooks.universal);
|
||||
}
|
||||
|
||||
return Array.from(server_assets);
|
||||
}
|
||||
162
node_modules/@sveltejs/kit/src/core/generate_manifest/index.js
generated
vendored
Normal file
162
node_modules/@sveltejs/kit/src/core/generate_manifest/index.js
generated
vendored
Normal file
@@ -0,0 +1,162 @@
|
||||
/** @import { BuildData, RemoteChunk, RouteData } from 'types' */
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { lookup as mime_lookup } from '../../utils/mime.js';
|
||||
import { s } from '../../utils/misc.js';
|
||||
import { get_mime_lookup } from '../utils.js';
|
||||
import { resolve_symlinks } from '../../exports/vite/build/utils.js';
|
||||
import { compact } from '../../utils/array.js';
|
||||
import { join_relative } from '../../utils/filesystem.js';
|
||||
import { dedent } from '../sync/utils.js';
|
||||
import { find_server_assets } from './find_server_assets.js';
|
||||
import { uneval } from 'devalue';
|
||||
|
||||
/**
|
||||
* Generates the data used to write the server-side manifest.js file. This data is used in the Vite
|
||||
* build process, to power routing, etc.
|
||||
* @param {{
|
||||
* build_data: BuildData;
|
||||
* prerendered: string[];
|
||||
* relative_path: string;
|
||||
* routes: RouteData[];
|
||||
* remotes: RemoteChunk[];
|
||||
* root: string;
|
||||
* }} opts
|
||||
*/
|
||||
export function generate_manifest({
|
||||
build_data,
|
||||
prerendered,
|
||||
relative_path,
|
||||
routes,
|
||||
remotes,
|
||||
root
|
||||
}) {
|
||||
/**
|
||||
* @type {Map<any, number>} The new index of each node in the filtered nodes array
|
||||
*/
|
||||
const reindexed = new Map();
|
||||
/**
|
||||
* All nodes actually used in the routes definition (prerendered routes are omitted).
|
||||
* Root layout/error is always included as they are needed for 404 and root errors.
|
||||
* @type {Set<any>}
|
||||
*/
|
||||
const used_nodes = new Set([0, 1]);
|
||||
|
||||
const server_assets = find_server_assets(build_data, routes, root);
|
||||
|
||||
for (const route of routes) {
|
||||
if (route.page) {
|
||||
for (const i of route.page.layouts) used_nodes.add(i);
|
||||
for (const i of route.page.errors) used_nodes.add(i);
|
||||
used_nodes.add(route.page.leaf);
|
||||
}
|
||||
}
|
||||
|
||||
const node_paths = compact(
|
||||
build_data.manifest_data.nodes.map((_, i) => {
|
||||
if (used_nodes.has(i)) {
|
||||
reindexed.set(i, reindexed.size);
|
||||
return join_relative(relative_path, `/nodes/${i}.js`);
|
||||
}
|
||||
})
|
||||
);
|
||||
|
||||
/** @type {(path: string) => string} */
|
||||
const loader = (path) => `__memo(() => import('${path}'))`;
|
||||
|
||||
const assets = build_data.manifest_data.assets.map((asset) => asset.file);
|
||||
if (build_data.service_worker) {
|
||||
assets.push(build_data.service_worker);
|
||||
}
|
||||
|
||||
const uses_matchers = build_data.manifest_data.routes.some((route) =>
|
||||
route.params.some((param) => param.matcher)
|
||||
);
|
||||
|
||||
/** @param {Array<number | undefined>} indexes */
|
||||
function get_nodes(indexes) {
|
||||
const string = indexes.map((n) => reindexed.get(n) ?? '').join(',');
|
||||
|
||||
// since JavaScript ignores trailing commas, we need to insert a dummy
|
||||
// comma so that the array has the correct length if the last item
|
||||
// is undefined
|
||||
return `[${string},]`;
|
||||
}
|
||||
|
||||
const mime_types = get_mime_lookup(build_data.manifest_data);
|
||||
|
||||
/** @type {Record<string, number>} */
|
||||
const files = {};
|
||||
for (const file of server_assets) {
|
||||
files[file] = fs.statSync(path.resolve(build_data.out_dir, 'server', file)).size;
|
||||
|
||||
const ext = path.extname(file);
|
||||
mime_types[ext] ??= mime_lookup(ext) || '';
|
||||
}
|
||||
|
||||
// record extensions that only exist in prerendered output, e.g. a prerendered favicon.ico
|
||||
for (const pathname of prerendered) {
|
||||
const ext = path.extname(pathname);
|
||||
if (ext) mime_types[ext] ??= mime_lookup(ext) || '';
|
||||
}
|
||||
|
||||
// prettier-ignore
|
||||
// String representation of
|
||||
/** @template {import('types').SSRManifest} T */
|
||||
const manifest_expr = dedent`
|
||||
{
|
||||
app_dir: ${s(build_data.app_dir)},
|
||||
app_path: ${s(build_data.app_path)},
|
||||
assets: new Set(${s(assets)}),
|
||||
mime_types: ${s(mime_types)},
|
||||
client: ${uneval(build_data.client)},
|
||||
|
||||
nodes: [
|
||||
${(node_paths).map(loader).join(',\n')}
|
||||
],
|
||||
remotes: {
|
||||
${remotes.map((remote) => `'${remote.hash}': ${loader(join_relative(relative_path, `chunks/remote-${remote.hash}.js`))}`).join(',\n')}
|
||||
},
|
||||
routes: [
|
||||
${routes.map(route => {
|
||||
if (!route.page && !route.endpoint) return;
|
||||
|
||||
return dedent`
|
||||
{
|
||||
id: ${s(route.id)},
|
||||
pattern: ${route.pattern},
|
||||
params: ${s(route.params)},
|
||||
page: ${route.page ? `{ layouts: ${get_nodes(route.page.layouts)}, errors: ${get_nodes(route.page.errors)}, leaf: ${reindexed.get(route.page.leaf)} }` : 'null'},
|
||||
endpoint: ${route.endpoint ? loader(join_relative(relative_path, resolve_symlinks(build_data.server_manifest, route.endpoint.file, root).chunk.file)) : 'null'}
|
||||
}
|
||||
`;
|
||||
}).filter(Boolean).join(',\n')}
|
||||
],
|
||||
prerendered_routes: new Set(${s(prerendered)}),
|
||||
matchers: async () => {
|
||||
${
|
||||
uses_matchers && build_data.manifest_data.params
|
||||
? dedent`
|
||||
const { params } = await import('${join_relative(relative_path, '/entries/params.js')}');
|
||||
return params;
|
||||
`
|
||||
: 'return {};'
|
||||
}
|
||||
},
|
||||
server_assets: ${s(files)}
|
||||
}
|
||||
`;
|
||||
|
||||
// Memoize the loaders to prevent Node from doing unnecessary work
|
||||
// on every dynamic import call
|
||||
return dedent`
|
||||
(() => {
|
||||
function __memo(fn) {
|
||||
let value;
|
||||
return () => value ??= (value = fn());
|
||||
}
|
||||
|
||||
return ${manifest_expr}
|
||||
})()
|
||||
`;
|
||||
}
|
||||
68
node_modules/@sveltejs/kit/src/core/params.js
generated
vendored
Normal file
68
node_modules/@sveltejs/kit/src/core/params.js
generated
vendored
Normal file
@@ -0,0 +1,68 @@
|
||||
/** @import { ParamMatcher } from '@sveltejs/kit/params' */
|
||||
import path from 'node:path';
|
||||
import { pathToFileURL } from 'node:url';
|
||||
import * as e from '../messages/build-errors.js';
|
||||
|
||||
/**
|
||||
* @param {import('types').RouteData[]} routes
|
||||
* @returns {Set<string>}
|
||||
*/
|
||||
export function collect_matcher_names(routes) {
|
||||
/** @type {Set<string>} */
|
||||
const names = new Set();
|
||||
|
||||
for (const route of routes) {
|
||||
for (const param of route.params) {
|
||||
if (param.matcher) names.add(param.matcher);
|
||||
}
|
||||
}
|
||||
|
||||
return names;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {Record<string, unknown>} params
|
||||
* @param {Set<string>} names
|
||||
* @param {string} [file]
|
||||
*/
|
||||
export function validate_param_matchers(params, names, file) {
|
||||
for (const name of names) {
|
||||
if (!Object.hasOwn(params, name)) {
|
||||
e.param_matcher_missing({ name, file: file || undefined });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {{
|
||||
* routes: import('types').RouteData[];
|
||||
* params_path: string | null;
|
||||
* root: string;
|
||||
* load?: (file: string) => Promise<Record<string, unknown>>;
|
||||
* }} opts
|
||||
* @returns {Promise<Record<string, ParamMatcher> | null>}
|
||||
*/
|
||||
export async function load_and_validate_params({ routes, params_path, root, load }) {
|
||||
const names = collect_matcher_names(routes);
|
||||
|
||||
if (names.size === 0) return null;
|
||||
|
||||
if (!params_path) {
|
||||
e.param_matcher_missing({ name: /** @type {string} */ (names.values().next().value) });
|
||||
}
|
||||
|
||||
const file = path.resolve(root, params_path);
|
||||
const module = load ? await load(file) : await import(pathToFileURL(file).href);
|
||||
|
||||
if (!module.params || typeof module.params !== 'object') {
|
||||
e.params_export_missing({ file: params_path });
|
||||
}
|
||||
|
||||
validate_param_matchers(
|
||||
/** @type {Record<string, unknown>} */ (module.params),
|
||||
names,
|
||||
params_path
|
||||
);
|
||||
|
||||
return /** @type {Record<string, ParamMatcher>} */ (module.params);
|
||||
}
|
||||
284
node_modules/@sveltejs/kit/src/core/postbuild/analyse.js
generated
vendored
Normal file
284
node_modules/@sveltejs/kit/src/core/postbuild/analyse.js
generated
vendored
Normal file
@@ -0,0 +1,284 @@
|
||||
/** @import { RemoteChunk } from 'types' */
|
||||
import { join } from 'node:path';
|
||||
import { pathToFileURL } from 'node:url';
|
||||
import { validate_server_exports } from '../../utils/exports.js';
|
||||
import { extract_svelte_config, load_vite_config } from '../config/index.js';
|
||||
import { forked } from '../../utils/fork.js';
|
||||
import { BODY_DEPENDENT_METHODS, ENDPOINT_METHODS } from '../../constants.js';
|
||||
import { has_server_load, resolve_route } from '../../utils/routing.js';
|
||||
import { check_feature } from '../features.js';
|
||||
import { createReadableStream } from '@sveltejs/kit/node';
|
||||
import { PageNodes } from '../../utils/page_nodes.js';
|
||||
import { enable_verbose_errors } from '../../messages/internal/shared.js';
|
||||
import * as e from '../../messages/build-errors.js';
|
||||
import * as server_errors from '../../messages/server-errors.js';
|
||||
import * as shared_errors from '../../messages/shared-errors.js';
|
||||
|
||||
export default forked(import.meta.url, analyse);
|
||||
|
||||
/**
|
||||
* @param {{
|
||||
* hash: boolean;
|
||||
* manifest_path: string;
|
||||
* manifest_data: import('types').ManifestData;
|
||||
* server_manifest: import('vite').Manifest;
|
||||
* tracked_features: Record<string, string[]>;
|
||||
* env: Record<string, string>;
|
||||
* remotes: RemoteChunk[];
|
||||
* vite_config_file: string | undefined;
|
||||
* }} opts
|
||||
*/
|
||||
async function analyse({
|
||||
hash,
|
||||
manifest_path,
|
||||
manifest_data,
|
||||
server_manifest,
|
||||
tracked_features,
|
||||
env,
|
||||
remotes,
|
||||
vite_config_file
|
||||
}) {
|
||||
// this worker validates exports and resolves `entries` with Kit's own modules, rather than the
|
||||
// bundled server's copies that `configure` affects, so its shared errors need the full text too
|
||||
enable_verbose_errors();
|
||||
|
||||
/** @type {import('types').SSRManifest} */
|
||||
const manifest = (await import(pathToFileURL(manifest_path).href)).manifest;
|
||||
|
||||
const vite_config = await load_vite_config(vite_config_file);
|
||||
const config = extract_svelte_config(vite_config);
|
||||
const server_root = join(config.outDir, 'output');
|
||||
|
||||
/** @type {import('types').ServerModule} */
|
||||
const { configure } = await import(pathToFileURL(`${server_root}/server/index.js`).href);
|
||||
|
||||
await configure({
|
||||
building: true,
|
||||
manifest,
|
||||
env,
|
||||
read: (file) => createReadableStream(`${server_root}/server/${file}`)
|
||||
});
|
||||
|
||||
/** @type {import('types').ServerMetadata} */
|
||||
const metadata = {
|
||||
nodes: [],
|
||||
routes: new Map(),
|
||||
remotes: new Map()
|
||||
};
|
||||
|
||||
const nodes = await Promise.all(manifest.nodes.map((loader) => loader()));
|
||||
|
||||
// analyse nodes
|
||||
for (const node of nodes) {
|
||||
if (hash && node.universal) {
|
||||
const options = Object.keys(node.universal).filter((o) => o !== 'load');
|
||||
if (options.length > 0) {
|
||||
shared_errors.router_hash_page_options({
|
||||
source: /** @type {string} */ (node.universal_id),
|
||||
options: options.map((o) => `'${o}'`).join(', ')
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
metadata.nodes[node.index] = {
|
||||
has_server_load: has_server_load(node),
|
||||
has_universal_load: node.universal?.load !== undefined
|
||||
};
|
||||
}
|
||||
|
||||
// analyse routes
|
||||
for (const route of manifest.routes) {
|
||||
const page =
|
||||
route.page &&
|
||||
analyse_page(
|
||||
route.page.layouts.map((n) => (n === undefined ? n : nodes[n])),
|
||||
nodes[route.page.leaf]
|
||||
);
|
||||
|
||||
const endpoint = route.endpoint && analyse_endpoint(route, await route.endpoint());
|
||||
|
||||
if (page?.prerender && endpoint?.prerender) {
|
||||
const endpoint_file = manifest_data.routes
|
||||
.find((r) => r.id === route.id)
|
||||
?.endpoint?.file.split('/')
|
||||
.pop();
|
||||
|
||||
e.route_prerender_page_and_endpoint({ id: route.id, file: endpoint_file ?? '+server.js' });
|
||||
}
|
||||
|
||||
if (page?.config && endpoint?.config) {
|
||||
for (const key in { ...page.config, ...endpoint.config }) {
|
||||
if (JSON.stringify(page.config[key]) !== JSON.stringify(endpoint.config[key])) {
|
||||
e.route_config_mismatch({ id: route.id });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const route_config = page?.config ?? endpoint?.config ?? {};
|
||||
const prerender = page?.prerender ?? endpoint?.prerender;
|
||||
|
||||
if (prerender !== true) {
|
||||
for (const feature of list_features(
|
||||
route,
|
||||
manifest_data,
|
||||
server_manifest,
|
||||
tracked_features
|
||||
)) {
|
||||
check_feature(route.id, route_config, feature, config.adapter);
|
||||
}
|
||||
}
|
||||
|
||||
const page_methods = page?.methods ?? [];
|
||||
const api_methods = endpoint?.methods ?? [];
|
||||
const entries = page?.entries ?? endpoint?.entries;
|
||||
|
||||
metadata.routes.set(route.id, {
|
||||
config: route_config,
|
||||
methods: Array.from(new Set([...page_methods, ...api_methods])),
|
||||
page: {
|
||||
methods: page_methods
|
||||
},
|
||||
api: {
|
||||
methods: api_methods
|
||||
},
|
||||
prerender,
|
||||
entries:
|
||||
entries && (await entries()).map((entry_object) => resolve_route(route.id, entry_object))
|
||||
});
|
||||
}
|
||||
|
||||
// analyse remotes
|
||||
for (const remote of remotes) {
|
||||
const loader = manifest.remotes[remote.hash];
|
||||
const { default: functions } = await loader();
|
||||
|
||||
const exports = new Map();
|
||||
|
||||
for (const name in functions) {
|
||||
const internals = /** @type {import('types').RemoteInternals} */ (functions[name].__);
|
||||
const type = internals.type;
|
||||
|
||||
exports.set(name, {
|
||||
type,
|
||||
dynamic: type !== 'prerender' || internals.dynamic
|
||||
});
|
||||
}
|
||||
|
||||
metadata.remotes.set(remote.hash, exports);
|
||||
}
|
||||
|
||||
return { metadata };
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {import('types').SSRRoute} route
|
||||
* @param {import('types').SSREndpoint} mod
|
||||
*/
|
||||
function analyse_endpoint(route, mod) {
|
||||
validate_server_exports(mod, route.id);
|
||||
|
||||
if (
|
||||
mod.prerender &&
|
||||
(mod.fallback ||
|
||||
/** @type {import('types').HttpMethod[]} */ (BODY_DEPENDENT_METHODS).some(
|
||||
(method) => mod[method]
|
||||
))
|
||||
) {
|
||||
server_errors.prerender_endpoint_methods({
|
||||
methods: BODY_DEPENDENT_METHODS.join(', '),
|
||||
id: route.id
|
||||
});
|
||||
}
|
||||
|
||||
/** @type {Array<import('types').HttpMethod | '*'>} */
|
||||
const methods = [];
|
||||
|
||||
for (const method of /** @type {import('types').HttpMethod[]} */ (ENDPOINT_METHODS)) {
|
||||
if (mod[method]) methods.push(method);
|
||||
}
|
||||
|
||||
if (mod.fallback) {
|
||||
methods.push('*');
|
||||
}
|
||||
|
||||
return {
|
||||
config: mod.config,
|
||||
entries: mod.entries,
|
||||
methods,
|
||||
prerender: mod.prerender ?? false
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {Array<import('types').SSRNode | undefined>} layouts
|
||||
* @param {import('types').SSRNode} leaf
|
||||
*/
|
||||
function analyse_page(layouts, leaf) {
|
||||
/** @type {Array<'GET' | 'POST'>} */
|
||||
const methods = ['GET'];
|
||||
if (leaf.server?.actions) methods.push('POST');
|
||||
|
||||
const nodes = new PageNodes([...layouts, leaf]);
|
||||
nodes.validate();
|
||||
|
||||
return {
|
||||
config: nodes.get_config(),
|
||||
entries: leaf.universal?.entries ?? leaf.server?.entries,
|
||||
methods,
|
||||
prerender: nodes.prerender()
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {import('types').SSRRoute} route
|
||||
* @param {import('types').ManifestData} manifest_data
|
||||
* @param {import('vite').Manifest} server_manifest
|
||||
* @param {Record<string, string[]>} tracked_features
|
||||
*/
|
||||
function list_features(route, manifest_data, server_manifest, tracked_features) {
|
||||
const features = new Set();
|
||||
|
||||
const route_data = /** @type {import('types').RouteData} */ (
|
||||
manifest_data.routes.find((r) => r.id === route.id)
|
||||
);
|
||||
|
||||
const visited = new Set();
|
||||
/** @param {string} id */
|
||||
function visit(id) {
|
||||
if (visited.has(id)) return;
|
||||
visited.add(id);
|
||||
|
||||
const chunk = server_manifest[id];
|
||||
if (!chunk) return;
|
||||
|
||||
if (chunk.file in tracked_features) {
|
||||
for (const feature of tracked_features[chunk.file]) {
|
||||
features.add(feature);
|
||||
}
|
||||
}
|
||||
|
||||
if (chunk.imports) {
|
||||
for (const id of chunk.imports) {
|
||||
visit(id);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let page_node = route_data?.leaf;
|
||||
while (page_node) {
|
||||
if (page_node.server) visit(page_node.server);
|
||||
page_node = page_node.parent ?? null;
|
||||
}
|
||||
|
||||
if (route_data.endpoint) {
|
||||
visit(route_data.endpoint.file);
|
||||
}
|
||||
|
||||
if (manifest_data.hooks.server) {
|
||||
// TODO if hooks.server.js imports `read`, it will be in the entry chunk
|
||||
// we don't currently account for that case
|
||||
visit(manifest_data.hooks.server);
|
||||
}
|
||||
|
||||
return Array.from(features);
|
||||
}
|
||||
259
node_modules/@sveltejs/kit/src/core/postbuild/crawl.js
generated
vendored
Normal file
259
node_modules/@sveltejs/kit/src/core/postbuild/crawl.js
generated
vendored
Normal file
@@ -0,0 +1,259 @@
|
||||
import { resolve, decode_uri } from '../../utils/url.js';
|
||||
import { decode } from './entities.js';
|
||||
|
||||
const DOCTYPE = 'DOCTYPE';
|
||||
const CDATA_OPEN = '[CDATA[';
|
||||
const CDATA_CLOSE = ']]>';
|
||||
const COMMENT_OPEN = '--';
|
||||
const COMMENT_CLOSE = '-->';
|
||||
|
||||
const TAG_OPEN = /[a-zA-Z]/;
|
||||
const TAG_CHAR = /[a-zA-Z0-9]/;
|
||||
const ATTRIBUTE_NAME = /[^\t\n\f />"'=]/;
|
||||
|
||||
const WHITESPACE = /[\s\n\r]/;
|
||||
|
||||
const CRAWLABLE_META_NAME_ATTRS = new Set([
|
||||
'og:url',
|
||||
'og:image',
|
||||
'og:image:url',
|
||||
'og:image:secure_url',
|
||||
'og:video',
|
||||
'og:video:url',
|
||||
'og:video:secure_url',
|
||||
'og:audio',
|
||||
'og:audio:url',
|
||||
'og:audio:secure_url',
|
||||
'twitter:image'
|
||||
]);
|
||||
|
||||
/**
|
||||
* @param {string} html
|
||||
* @param {string} base
|
||||
*/
|
||||
export function crawl(html, base) {
|
||||
/** @type {string[]} */
|
||||
const ids = [];
|
||||
|
||||
/** @type {string[]} */
|
||||
const hrefs = [];
|
||||
|
||||
/** @type {string[]} */
|
||||
const invalid = [];
|
||||
|
||||
/** @param {string} url */
|
||||
const push_href = (url) => {
|
||||
try {
|
||||
hrefs.push(resolve(base, url));
|
||||
} catch {
|
||||
invalid.push(url);
|
||||
}
|
||||
};
|
||||
|
||||
let i = 0;
|
||||
main: while (i < html.length) {
|
||||
const char = html[i];
|
||||
|
||||
if (char === '<') {
|
||||
if (html[i + 1] === '!') {
|
||||
i += 2;
|
||||
|
||||
if (html.slice(i, i + DOCTYPE.length).toUpperCase() === DOCTYPE) {
|
||||
i += DOCTYPE.length;
|
||||
while (i < html.length) {
|
||||
if (html[i++] === '>') {
|
||||
continue main;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// skip cdata
|
||||
if (html.slice(i, i + CDATA_OPEN.length) === CDATA_OPEN) {
|
||||
i += CDATA_OPEN.length;
|
||||
while (i < html.length) {
|
||||
if (html.slice(i, i + CDATA_CLOSE.length) === CDATA_CLOSE) {
|
||||
i += CDATA_CLOSE.length;
|
||||
continue main;
|
||||
}
|
||||
|
||||
i += 1;
|
||||
}
|
||||
}
|
||||
|
||||
// skip comments
|
||||
if (html.slice(i, i + COMMENT_OPEN.length) === COMMENT_OPEN) {
|
||||
i += COMMENT_OPEN.length;
|
||||
while (i < html.length) {
|
||||
if (html.slice(i, i + COMMENT_CLOSE.length) === COMMENT_CLOSE) {
|
||||
i += COMMENT_CLOSE.length;
|
||||
continue main;
|
||||
}
|
||||
|
||||
i += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// parse opening tags
|
||||
const start = ++i;
|
||||
if (TAG_OPEN.test(html[start])) {
|
||||
while (i < html.length) {
|
||||
if (!TAG_CHAR.test(html[i])) {
|
||||
break;
|
||||
}
|
||||
|
||||
i += 1;
|
||||
}
|
||||
|
||||
const tag = html.slice(start, i).toUpperCase();
|
||||
|
||||
/** @type {Record<string, string>} */
|
||||
const attributes = {};
|
||||
|
||||
if (tag === 'SCRIPT' || tag === 'STYLE') {
|
||||
while (i < html.length) {
|
||||
if (
|
||||
html[i] === '<' &&
|
||||
html[i + 1] === '/' &&
|
||||
html.slice(i + 2, i + 2 + tag.length).toUpperCase() === tag
|
||||
) {
|
||||
continue main;
|
||||
}
|
||||
|
||||
i += 1;
|
||||
}
|
||||
}
|
||||
|
||||
while (i < html.length) {
|
||||
const start = i;
|
||||
|
||||
const char = html[start];
|
||||
if (char === '>') break;
|
||||
|
||||
if (ATTRIBUTE_NAME.test(char)) {
|
||||
i += 1;
|
||||
|
||||
while (i < html.length) {
|
||||
if (!ATTRIBUTE_NAME.test(html[i])) {
|
||||
break;
|
||||
}
|
||||
|
||||
i += 1;
|
||||
}
|
||||
|
||||
const name = html.slice(start, i).toLowerCase();
|
||||
|
||||
while (WHITESPACE.test(html[i])) i += 1;
|
||||
|
||||
if (html[i] === '=') {
|
||||
i += 1;
|
||||
while (WHITESPACE.test(html[i])) i += 1;
|
||||
|
||||
let value;
|
||||
|
||||
if (html[i] === "'" || html[i] === '"') {
|
||||
const quote = html[i++];
|
||||
|
||||
const start = i;
|
||||
let escaped = false;
|
||||
|
||||
while (i < html.length) {
|
||||
if (escaped) {
|
||||
escaped = false;
|
||||
} else {
|
||||
const char = html[i];
|
||||
|
||||
if (html[i] === quote) {
|
||||
break;
|
||||
}
|
||||
|
||||
if (char === '\\') {
|
||||
escaped = true;
|
||||
}
|
||||
}
|
||||
|
||||
i += 1;
|
||||
}
|
||||
|
||||
value = html.slice(start, i);
|
||||
} else {
|
||||
const start = i;
|
||||
while (i < html.length && html[i] !== '>' && !WHITESPACE.test(html[i])) i += 1;
|
||||
value = html.slice(start, i);
|
||||
|
||||
i -= 1;
|
||||
}
|
||||
|
||||
value = decode(value);
|
||||
attributes[name] = value;
|
||||
} else {
|
||||
i -= 1;
|
||||
}
|
||||
}
|
||||
|
||||
i += 1;
|
||||
}
|
||||
|
||||
const { href, id, name, property, rel, src, srcset, content } = attributes;
|
||||
|
||||
if (href) {
|
||||
if (tag === 'BASE') {
|
||||
try {
|
||||
base = resolve(base, href);
|
||||
} catch {
|
||||
invalid.push(href);
|
||||
}
|
||||
} else if (!rel || !/\bexternal\b/i.test(rel)) {
|
||||
push_href(href);
|
||||
}
|
||||
}
|
||||
|
||||
if (id) {
|
||||
ids.push(decode_uri(id));
|
||||
}
|
||||
|
||||
if (name && tag === 'A') {
|
||||
ids.push(decode_uri(name));
|
||||
}
|
||||
|
||||
if (src) {
|
||||
push_href(src);
|
||||
}
|
||||
|
||||
if (srcset) {
|
||||
let value = srcset;
|
||||
const candidates = [];
|
||||
let insideURL = true;
|
||||
value = value.trim();
|
||||
for (let i = 0; i < value.length; i++) {
|
||||
if (value[i] === ',' && (!insideURL || (insideURL && WHITESPACE.test(value[i + 1])))) {
|
||||
candidates.push(value.slice(0, i));
|
||||
value = value.substring(i + 1).trim();
|
||||
i = 0;
|
||||
insideURL = true;
|
||||
} else if (WHITESPACE.test(value[i])) {
|
||||
insideURL = false;
|
||||
}
|
||||
}
|
||||
candidates.push(value);
|
||||
for (const candidate of candidates) {
|
||||
const src = candidate.split(WHITESPACE)[0];
|
||||
if (src) push_href(src);
|
||||
}
|
||||
}
|
||||
|
||||
if (tag === 'META' && content) {
|
||||
const attr = name ?? property;
|
||||
|
||||
if (attr && CRAWLABLE_META_NAME_ATTRS.has(attr)) {
|
||||
push_href(content);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
i += 1;
|
||||
}
|
||||
|
||||
return { ids, hrefs, invalid };
|
||||
}
|
||||
2258
node_modules/@sveltejs/kit/src/core/postbuild/entities.js
generated
vendored
Normal file
2258
node_modules/@sveltejs/kit/src/core/postbuild/entities.js
generated
vendored
Normal file
File diff suppressed because it is too large
Load Diff
48
node_modules/@sveltejs/kit/src/core/postbuild/fallback.js
generated
vendored
Normal file
48
node_modules/@sveltejs/kit/src/core/postbuild/fallback.js
generated
vendored
Normal file
@@ -0,0 +1,48 @@
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { join } from 'node:path';
|
||||
import { pathToFileURL } from 'node:url';
|
||||
import { forked } from '../../utils/fork.js';
|
||||
import * as e from '../../messages/build-errors.js';
|
||||
|
||||
export default forked(import.meta.url, generate_fallback);
|
||||
|
||||
/**
|
||||
* @param {{
|
||||
* manifest_path: string;
|
||||
* env: Record<string, string>
|
||||
* out_dir: string;
|
||||
* origin: string;
|
||||
* assets: string;
|
||||
* }} opts
|
||||
*/
|
||||
async function generate_fallback({ manifest_path, env, out_dir, origin, assets }) {
|
||||
const server_root = join(out_dir, 'output');
|
||||
|
||||
/** @type {import('types').ServerModule} */
|
||||
const { configure } = await import(pathToFileURL(`${server_root}/server/index.js`).href);
|
||||
|
||||
/** @type {import('types').SSRManifest} */
|
||||
const manifest = (await import(pathToFileURL(manifest_path).href)).manifest;
|
||||
|
||||
const { init, respond } = await configure({ building: true, manifest, env });
|
||||
await init();
|
||||
|
||||
const response = await respond(new Request(origin + '/[fallback]'), {
|
||||
getClientAddress: () => {
|
||||
e.prerender_client_address();
|
||||
},
|
||||
prerendering: {
|
||||
fallback: true,
|
||||
dependencies: new Map(),
|
||||
remote_responses: new Map(),
|
||||
resolved_route_ids: new Set()
|
||||
},
|
||||
read: (file) => readFileSync(join(assets, file))
|
||||
});
|
||||
|
||||
if (response.ok) {
|
||||
return await response.text();
|
||||
}
|
||||
|
||||
e.prerender_fallback_failed(undefined, { stackless: true });
|
||||
}
|
||||
760
node_modules/@sveltejs/kit/src/core/postbuild/prerender.js
generated
vendored
Normal file
760
node_modules/@sveltejs/kit/src/core/postbuild/prerender.js
generated
vendored
Normal file
@@ -0,0 +1,760 @@
|
||||
import process from 'node:process';
|
||||
import { existsSync, mkdirSync, readFileSync, statSync, writeFileSync } from 'node:fs';
|
||||
import { dirname, join } from 'node:path';
|
||||
import { pathToFileURL } from 'node:url';
|
||||
import { walk } from '../../utils/filesystem.js';
|
||||
import { noop } from '../../utils/functions.js';
|
||||
import { decode_uri, is_root_relative, resolve } from '../../utils/url.js';
|
||||
import { escape_html } from '../../utils/escape.js';
|
||||
import { logger } from '../utils.js';
|
||||
import { extract_svelte_config, load_vite_config } from '../config/index.js';
|
||||
import { get_route_segments } from '../../utils/routing.js';
|
||||
import { queue } from './queue.js';
|
||||
import { crawl } from './crawl.js';
|
||||
import { forked } from '../../utils/fork.js';
|
||||
import * as devalue from 'devalue';
|
||||
import { createReadableStream } from '@sveltejs/kit/node';
|
||||
import generate_fallback from './fallback.js';
|
||||
import { stringify_remote_arg } from '../../runtime/shared.js';
|
||||
import { matches_content_type } from '../../utils/http.js';
|
||||
import { fix_stack_trace } from '../../runtime/server/sourcemaps.js';
|
||||
import * as e from '../../messages/build-errors.js';
|
||||
import * as w from '../../messages/build-warnings.js';
|
||||
import { capture_message } from '../../messages/internal/build.js';
|
||||
import { bullet_list } from '../../utils/format.js';
|
||||
|
||||
export default forked(import.meta.url, prerender);
|
||||
|
||||
// https://html.spec.whatwg.org/multipage/browsing-the-web.html#scrolling-to-a-fragment
|
||||
// "If fragment is the empty string, then return the special value top of the document."
|
||||
// ...and
|
||||
// "If decodedFragment is an ASCII case-insensitive match for the string 'top', then return the top of the document."
|
||||
const SPECIAL_HASHLINKS = new Set(['', 'top']);
|
||||
|
||||
/**
|
||||
* @param {{
|
||||
* hash: boolean;
|
||||
* out: string;
|
||||
* manifest_path: string;
|
||||
* metadata: import('types').ServerMetadata;
|
||||
* verbose: boolean;
|
||||
* env: Record<string, string>;
|
||||
* vite_config_file: string | undefined;
|
||||
* is_tty: boolean | undefined;
|
||||
* }} opts
|
||||
*/
|
||||
async function prerender({
|
||||
hash,
|
||||
out,
|
||||
manifest_path,
|
||||
metadata,
|
||||
verbose,
|
||||
env,
|
||||
vite_config_file,
|
||||
is_tty
|
||||
}) {
|
||||
/** @type {import('types').SSRManifest} */
|
||||
const manifest = (await import(pathToFileURL(manifest_path).href)).manifest;
|
||||
|
||||
/** @type {import('types').ServerModule} */
|
||||
const { configure, format_response } = await import(pathToFileURL(`${out}/server/index.js`).href);
|
||||
|
||||
const { init, respond } = await configure({
|
||||
building: true,
|
||||
prerendering: true,
|
||||
env,
|
||||
manifest,
|
||||
read: (file) => createReadableStream(`${out}/server/${file}`)
|
||||
});
|
||||
|
||||
const throw_handled = () => {
|
||||
throw new Error('__handled__');
|
||||
};
|
||||
|
||||
/**
|
||||
* @template {{message: string}} T
|
||||
* @template {Omit<T, 'message'>} K
|
||||
* @param {string} name
|
||||
* @param {'fail' | 'warn' | 'ignore' | undefined | ((details: T) => void)} input
|
||||
* @param {(details: K) => string} format
|
||||
* @returns {(details: K & { error?: unknown }) => void}
|
||||
*/
|
||||
function normalise_error_handler(name, input, format) {
|
||||
/**
|
||||
* @param {any} details
|
||||
*/
|
||||
function log_failure(details) {
|
||||
const message = format(details);
|
||||
log.error(`\n${message}\n`);
|
||||
}
|
||||
|
||||
switch (input) {
|
||||
case 'fail':
|
||||
return (details) => {
|
||||
log_failure(details);
|
||||
throw_handled();
|
||||
};
|
||||
case 'warn':
|
||||
return log_failure;
|
||||
case 'ignore':
|
||||
return noop;
|
||||
case undefined: {
|
||||
return (details) => {
|
||||
log_failure(details);
|
||||
|
||||
log.err(
|
||||
`To suppress or handle this error, implement \`${name}\` in https://svelte.dev/docs/kit/@sveltejs-kit-vite#prerender\n`
|
||||
);
|
||||
|
||||
throw_handled();
|
||||
};
|
||||
}
|
||||
default:
|
||||
return (details) => {
|
||||
const message = format(details);
|
||||
|
||||
try {
|
||||
// @ts-expect-error TS thinks T might be of a different kind, but it's not
|
||||
input({ ...details, message });
|
||||
} catch (error) {
|
||||
log.prettyError(error, import.meta.dirname);
|
||||
throw_handled();
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
const OK = 2;
|
||||
const REDIRECT = 3;
|
||||
|
||||
/** @type {import('types').Prerendered} */
|
||||
const prerendered = {
|
||||
pages: new Map(),
|
||||
assets: new Map(),
|
||||
redirects: new Map(),
|
||||
paths: []
|
||||
};
|
||||
|
||||
/** @type {import('types').PrerenderMap} */
|
||||
const prerender_map = new Map();
|
||||
|
||||
for (const [id, { prerender }] of metadata.routes) {
|
||||
if (prerender !== undefined) {
|
||||
prerender_map.set(id, prerender);
|
||||
}
|
||||
}
|
||||
|
||||
/** @type {Set<string>} */
|
||||
const prerendered_routes = new Set();
|
||||
|
||||
const vite_config = await load_vite_config(vite_config_file);
|
||||
|
||||
const config = extract_svelte_config(vite_config);
|
||||
|
||||
const prerender_origin = config.paths.origin || 'http://sveltekit-prerender';
|
||||
|
||||
if (hash) {
|
||||
const fallback = await generate_fallback({
|
||||
manifest_path,
|
||||
env,
|
||||
out_dir: config.outDir,
|
||||
origin: prerender_origin,
|
||||
assets: config.files.assets
|
||||
});
|
||||
|
||||
const file = output_filename('/', true);
|
||||
const dest = `${config.outDir}/output/prerendered/pages/${file}`;
|
||||
|
||||
mkdirSync(dirname(dest), { recursive: true });
|
||||
writeFileSync(dest, fallback);
|
||||
|
||||
prerendered.pages.set('/', { file });
|
||||
|
||||
return { prerendered, prerender_map };
|
||||
}
|
||||
|
||||
const emulator = await config.adapter?.emulate?.();
|
||||
|
||||
/** @type {import('types').Logger} */
|
||||
const log = logger({ verbose });
|
||||
|
||||
/** @type {Map<string, string>} */
|
||||
const saved = new Map();
|
||||
|
||||
const handle_http_error = normalise_error_handler(
|
||||
'handleHttpError',
|
||||
config.prerender.handleHttpError,
|
||||
({ status, path, referrer, referenceType }) => {
|
||||
if (status === 404) {
|
||||
if (!path.startsWith(config.paths.base)) {
|
||||
return capture_message(() =>
|
||||
e.prerender_path_outside_base(
|
||||
referrer ? { path, reference_type: referenceType, referrer } : { path }
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
if (referrer) {
|
||||
return capture_message(() =>
|
||||
e.prerender_http_error({ path, reference_type: referenceType, referrer })
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
return capture_message(() => e.prerender_http_error({ path }));
|
||||
}
|
||||
);
|
||||
|
||||
const handle_missing_id = normalise_error_handler(
|
||||
'handleMissingId',
|
||||
config.prerender.handleMissingId,
|
||||
({ path, id, referrers }) => {
|
||||
return capture_message(() =>
|
||||
e.prerender_missing_id({
|
||||
path,
|
||||
id,
|
||||
referrers: bullet_list(referrers)
|
||||
})
|
||||
);
|
||||
}
|
||||
);
|
||||
|
||||
const handle_entry_generator_mismatch = normalise_error_handler(
|
||||
'handleEntryGeneratorMismatch',
|
||||
config.prerender.handleEntryGeneratorMismatch,
|
||||
({ generatedFromId, entry, matchedId }) => {
|
||||
return capture_message(() =>
|
||||
e.prerender_entry_generator_mismatch({
|
||||
id: generatedFromId,
|
||||
entry,
|
||||
matched: matchedId === entry ? 'a static route' : matchedId
|
||||
})
|
||||
);
|
||||
}
|
||||
);
|
||||
|
||||
const handle_not_prerendered_route = normalise_error_handler(
|
||||
'handleUnseenRoutes',
|
||||
config.prerender.handleUnseenRoutes,
|
||||
({ routes }) => {
|
||||
return capture_message(() => e.prerender_unseen_routes({ routes: bullet_list(routes) }));
|
||||
}
|
||||
);
|
||||
|
||||
const handle_invalid_url = normalise_error_handler(
|
||||
'handleInvalidUrl',
|
||||
config.prerender.handleInvalidUrl,
|
||||
({ href, referrer }) => {
|
||||
return capture_message(() =>
|
||||
e.prerender_invalid_url(referrer ? { href, referrer } : { href })
|
||||
);
|
||||
}
|
||||
);
|
||||
|
||||
const q = queue(config.prerender.concurrency);
|
||||
|
||||
/**
|
||||
* @param {string} path
|
||||
* @param {boolean} is_html
|
||||
*/
|
||||
function output_filename(path, is_html) {
|
||||
const file = path.slice(config.paths.base.length + 1) || 'index.html';
|
||||
|
||||
if (is_html && !file.endsWith('.html')) {
|
||||
return file + (file.endsWith('/') ? 'index.html' : '.html');
|
||||
}
|
||||
|
||||
return file;
|
||||
}
|
||||
|
||||
const files = new Set(walk(`${out}/client`));
|
||||
files.add(`${config.appDir}/env.js`);
|
||||
|
||||
const immutable = `${config.appDir}/immutable`;
|
||||
if (existsSync(`${out}/server/${immutable}`)) {
|
||||
for (const file of walk(`${out}/server/${immutable}`)) {
|
||||
files.add(`${config.appDir}/immutable/${file}`);
|
||||
}
|
||||
}
|
||||
|
||||
const remote_prefix = `${config.paths.base}/${config.appDir}/remote/`;
|
||||
|
||||
const seen = new Set();
|
||||
const written = new Set();
|
||||
|
||||
/** @type {Map<string, Promise<any>>} */
|
||||
const remote_responses = new Map();
|
||||
|
||||
/** @type {null | { clear: () => void; update: (path: string) => void; updated: number }} */
|
||||
let progress = null;
|
||||
|
||||
if (is_tty) {
|
||||
// Where possible, provide progress feedback by showing the path we're
|
||||
// currently requesting, then clearing the line once the response comes in.
|
||||
// This avoids the wall of text that happens when you prerender
|
||||
// many pages and log each response
|
||||
const { stdout, stderr } = process;
|
||||
|
||||
let current = false;
|
||||
let needs_newline = true;
|
||||
|
||||
const write = stdout.write;
|
||||
|
||||
/** @param {string} value */
|
||||
const print = (value) => write.call(stdout, value);
|
||||
|
||||
/** @type {ProxyHandler<typeof stdout.write>} */
|
||||
const intercept = {
|
||||
apply(target, this_arg, args) {
|
||||
const chunk = args[0];
|
||||
if (chunk.length > 0) {
|
||||
current = false;
|
||||
needs_newline =
|
||||
typeof chunk === 'string' ? !chunk.endsWith('\n') : chunk[chunk.length - 1] !== 10;
|
||||
}
|
||||
return Reflect.apply(target, this_arg, args);
|
||||
}
|
||||
};
|
||||
|
||||
stdout.write = new Proxy(stdout.write, intercept);
|
||||
stderr.write = new Proxy(stderr.write, intercept);
|
||||
|
||||
progress = {
|
||||
clear: () => {
|
||||
// If app code writes to stdout or stderr, don't move the cursor to clear
|
||||
// the previous progress log, because that will corrupt things
|
||||
if (!current) return;
|
||||
|
||||
print('\x1B[1A'); // move cursor to start of progress update
|
||||
print('\x1B[2K'); // clear current line
|
||||
},
|
||||
|
||||
update: (path) => {
|
||||
// if we're in the middle of a line, start a new one
|
||||
if (needs_newline) print('\n');
|
||||
|
||||
print(`crawling ${path}\n`);
|
||||
current = true;
|
||||
needs_newline = false;
|
||||
},
|
||||
|
||||
updated: 0
|
||||
};
|
||||
}
|
||||
|
||||
/** @type {Set<string>} */
|
||||
const resolved_route_ids = new Set();
|
||||
|
||||
/** @type {Map<string, Set<string>>} */
|
||||
const expected_hashlinks = new Map();
|
||||
|
||||
/** @type {Map<string, Set<string>>} */
|
||||
const actual_hashlinks = new Map();
|
||||
|
||||
/**
|
||||
* @param {string | null} referrer
|
||||
* @param {string} decoded
|
||||
* @param {string} [encoded]
|
||||
* @param {string} [generated_from_id]
|
||||
*/
|
||||
function enqueue(referrer, decoded, encoded, generated_from_id) {
|
||||
if (seen.has(decoded)) return;
|
||||
seen.add(decoded);
|
||||
|
||||
const file = decoded.slice(config.paths.base.length + 1);
|
||||
if (files.has(file)) return;
|
||||
|
||||
return q.add(() => visit(decoded, encoded || encodeURI(decoded), referrer, generated_from_id));
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {string} decoded
|
||||
* @param {string} encoded
|
||||
* @param {string?} referrer
|
||||
* @param {string} [generated_from_id]
|
||||
*/
|
||||
async function visit(decoded, encoded, referrer, generated_from_id) {
|
||||
if (!decoded.startsWith(config.paths.base)) {
|
||||
handle_http_error({ status: 404, path: decoded, referrer, referenceType: 'linked' });
|
||||
return;
|
||||
}
|
||||
|
||||
/** @type {Map<string, import('types').PrerenderDependency>} */
|
||||
const dependencies = new Map();
|
||||
|
||||
if (progress) {
|
||||
progress.clear();
|
||||
progress.update(decoded);
|
||||
|
||||
if (Date.now() - progress.updated > 50) {
|
||||
progress.updated = Date.now();
|
||||
|
||||
// without this, the update will rarely be visible, and progress will appear stuck
|
||||
await new Promise((f) => setTimeout(f, 0));
|
||||
}
|
||||
}
|
||||
|
||||
const request = new Request(prerender_origin + encoded);
|
||||
|
||||
const response = await respond(request, {
|
||||
getClientAddress() {
|
||||
e.prerender_client_address();
|
||||
},
|
||||
prerendering: {
|
||||
dependencies,
|
||||
remote_responses,
|
||||
resolved_route_ids
|
||||
},
|
||||
read: (file) => {
|
||||
// stuff we just wrote
|
||||
const filepath = saved.get(file);
|
||||
if (filepath) return readFileSync(filepath);
|
||||
|
||||
// Static assets emitted during build
|
||||
if (file.startsWith(config.appDir)) {
|
||||
return readFileSync(`${out}/server/${file}`);
|
||||
}
|
||||
|
||||
// stuff in `static`
|
||||
return readFileSync(join(config.files.assets, file));
|
||||
},
|
||||
emulator
|
||||
});
|
||||
|
||||
const encoded_id = response.headers.get('x-sveltekit-routeid');
|
||||
const decoded_id = encoded_id && decode_uri(encoded_id);
|
||||
if (
|
||||
decoded_id !== null &&
|
||||
generated_from_id !== undefined &&
|
||||
decoded_id !== generated_from_id
|
||||
) {
|
||||
handle_entry_generator_mismatch({
|
||||
generatedFromId: generated_from_id,
|
||||
entry: decoded,
|
||||
matchedId: decoded_id
|
||||
});
|
||||
}
|
||||
|
||||
if (response.status >= 400) {
|
||||
console.log(format_response(response.status, request));
|
||||
}
|
||||
|
||||
const body = Buffer.from(await response.arrayBuffer());
|
||||
|
||||
const category = decoded.startsWith(remote_prefix) ? 'data' : 'pages';
|
||||
save(category, response, body, decoded, encoded, referrer, 'linked');
|
||||
|
||||
for (const [dependency_path, result] of dependencies) {
|
||||
// this seems circuitous, but using new URL allows us to not care
|
||||
// whether dependency_path is encoded or not
|
||||
const encoded_dependency_path = new URL(dependency_path, 'http://localhost').pathname;
|
||||
const decoded_dependency_path = decode_uri(encoded_dependency_path);
|
||||
|
||||
const headers = Object.fromEntries(result.response.headers);
|
||||
|
||||
const prerender = headers['x-sveltekit-prerender'];
|
||||
if (prerender) {
|
||||
const encoded_route_id = headers['x-sveltekit-routeid'];
|
||||
if (encoded_route_id != null) {
|
||||
const route_id = decode_uri(encoded_route_id);
|
||||
const existing_value = prerender_map.get(route_id);
|
||||
if (existing_value !== 'auto') {
|
||||
prerender_map.set(route_id, prerender === 'true' ? true : 'auto');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const body = result.body ?? new Uint8Array(await result.response.arrayBuffer());
|
||||
|
||||
const category = decoded_dependency_path.startsWith(remote_prefix) ? 'data' : 'dependencies';
|
||||
|
||||
save(
|
||||
category,
|
||||
result.response,
|
||||
body,
|
||||
decoded_dependency_path,
|
||||
encoded_dependency_path,
|
||||
decoded,
|
||||
'fetched'
|
||||
);
|
||||
}
|
||||
|
||||
// avoid triggering `filterSerializeResponseHeaders` guard
|
||||
const headers = Object.fromEntries(response.headers);
|
||||
|
||||
// if it's a 200 HTML response, crawl it. Skip error responses, as we don't save those
|
||||
if (
|
||||
response.ok &&
|
||||
config.prerender.crawl &&
|
||||
matches_content_type(headers['content-type'], 'text/html')
|
||||
) {
|
||||
const { ids, hrefs, invalid } = crawl(body.toString(), decoded);
|
||||
|
||||
for (const href of invalid) {
|
||||
handle_invalid_url({ href, referrer: decoded });
|
||||
}
|
||||
|
||||
actual_hashlinks.set(decoded, new Set(ids));
|
||||
|
||||
/** @param {string} href */
|
||||
const removePrerenderOrigin = (href) => {
|
||||
if (href.startsWith(prerender_origin)) {
|
||||
if (href === prerender_origin) return '/';
|
||||
if (href.at(prerender_origin.length) !== '/') return href;
|
||||
return href.slice(prerender_origin.length);
|
||||
}
|
||||
return href;
|
||||
};
|
||||
|
||||
for (const href of hrefs.map(removePrerenderOrigin)) {
|
||||
if (!is_root_relative(href)) continue;
|
||||
|
||||
const { pathname, search, hash } = new URL(href, 'http://localhost');
|
||||
|
||||
if (search) {
|
||||
// TODO warn that query strings have no effect on statically-exported pages
|
||||
}
|
||||
|
||||
if (hash) {
|
||||
const key = decode_uri(pathname + hash);
|
||||
|
||||
if (!expected_hashlinks.has(key)) {
|
||||
expected_hashlinks.set(key, new Set());
|
||||
}
|
||||
|
||||
/** @type {Set<string>} */ (expected_hashlinks.get(key)).add(decoded);
|
||||
}
|
||||
|
||||
void enqueue(decoded, decode_uri(pathname), pathname);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {'pages' | 'dependencies' | 'data'} category
|
||||
* @param {Response} response
|
||||
* @param {string | Uint8Array} body
|
||||
* @param {string} decoded
|
||||
* @param {string} encoded
|
||||
* @param {string | null} referrer
|
||||
* @param {'linked' | 'fetched'} referenceType
|
||||
*/
|
||||
function save(category, response, body, decoded, encoded, referrer, referenceType) {
|
||||
const response_type = Math.floor(response.status / 100);
|
||||
const headers = Object.fromEntries(response.headers);
|
||||
|
||||
const type = headers['content-type'];
|
||||
const is_html = response_type === REDIRECT || matches_content_type(type, 'text/html');
|
||||
|
||||
if (!is_html && response.status === 200 && decoded.slice(config.paths.base.length + 1) === '') {
|
||||
e.prerender_root_non_html({ base: config.paths.base || '/' });
|
||||
}
|
||||
|
||||
const file = output_filename(decoded, is_html);
|
||||
const dest = `${config.outDir}/output/prerendered/${category}/${file}`;
|
||||
|
||||
if (written.has(file)) return;
|
||||
|
||||
const encoded_route_id = response.headers.get('x-sveltekit-routeid');
|
||||
const route_id = encoded_route_id != null ? decode_uri(encoded_route_id) : null;
|
||||
if (route_id !== null) prerendered_routes.add(route_id);
|
||||
|
||||
if (response_type === REDIRECT) {
|
||||
const location = headers['location'];
|
||||
|
||||
if (location) {
|
||||
const resolved = resolve(encoded, location);
|
||||
if (is_root_relative(resolved)) {
|
||||
void enqueue(decoded, decode_uri(resolved), resolved);
|
||||
}
|
||||
|
||||
if (!headers['x-sveltekit-normalize']) {
|
||||
mkdirSync(dirname(dest), { recursive: true });
|
||||
|
||||
writeFileSync(
|
||||
dest,
|
||||
`<script>location.href=${devalue.uneval(
|
||||
location
|
||||
)};</script><meta http-equiv="refresh" content="${escape_html(
|
||||
`0;url=${location}`,
|
||||
true
|
||||
)}">`
|
||||
);
|
||||
|
||||
written.add(file);
|
||||
|
||||
if (!prerendered.redirects.has(decoded)) {
|
||||
prerendered.redirects.set(decoded, {
|
||||
status: response.status,
|
||||
location: resolved
|
||||
});
|
||||
|
||||
prerendered.paths.push(decoded);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
w.prerender_redirect_location_missing({ path: decoded });
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
if (response.status === 200) {
|
||||
if (existsSync(dest) && statSync(dest).isDirectory()) {
|
||||
e.prerender_directory_conflict({ path: decoded });
|
||||
}
|
||||
|
||||
const dir = dirname(dest);
|
||||
|
||||
if (existsSync(dir) && !statSync(dir).isDirectory()) {
|
||||
const parent = decoded.split('/').slice(0, -1).join('/');
|
||||
e.prerender_directory_conflict({ path: decoded, parent });
|
||||
}
|
||||
|
||||
mkdirSync(dir, { recursive: true });
|
||||
|
||||
writeFileSync(dest, body);
|
||||
written.add(file);
|
||||
|
||||
if (is_html) {
|
||||
prerendered.pages.set(decoded, {
|
||||
file
|
||||
});
|
||||
} else {
|
||||
prerendered.assets.set(decoded, {
|
||||
type
|
||||
});
|
||||
}
|
||||
|
||||
prerendered.paths.push(decoded);
|
||||
} else if (response_type !== OK) {
|
||||
handle_http_error({
|
||||
status: response.status,
|
||||
path: decoded,
|
||||
referrer,
|
||||
referenceType
|
||||
});
|
||||
}
|
||||
|
||||
manifest.assets.add(file);
|
||||
saved.set(file, dest);
|
||||
}
|
||||
|
||||
/** @type {Array<{ id: string, entries: Array<string>}>} */
|
||||
const route_level_entries = [];
|
||||
for (const [id, { entries }] of metadata.routes.entries()) {
|
||||
if (entries) {
|
||||
route_level_entries.push({ id, entries });
|
||||
}
|
||||
}
|
||||
|
||||
let should_prerender = false;
|
||||
|
||||
for (const value of prerender_map.values()) {
|
||||
if (value) {
|
||||
should_prerender = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
/** @type {Array<import('types').RemotePrerenderInternals>} */
|
||||
const prerender_functions = [];
|
||||
|
||||
for (const loader of Object.values(manifest.remotes)) {
|
||||
const module = await loader();
|
||||
|
||||
for (const fn of Object.values(module.default)) {
|
||||
if (fn?.__?.type === 'prerender') {
|
||||
prerender_functions.push(fn.__);
|
||||
should_prerender = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!should_prerender) {
|
||||
return { prerendered, prerender_map };
|
||||
}
|
||||
|
||||
// only run the server after the `should_prerender` check so that we
|
||||
// don't run the user's init hook unnecessarily
|
||||
await init();
|
||||
|
||||
log.info('Prerendering');
|
||||
|
||||
for (const entry of config.prerender.entries) {
|
||||
if (entry === '*') {
|
||||
for (const [id, prerender] of prerender_map) {
|
||||
if (prerender) {
|
||||
// remove optional parameters from the route
|
||||
const segments = get_route_segments(id).filter((segment) => !segment.startsWith('[['));
|
||||
const processed_id = '/' + segments.join('/');
|
||||
|
||||
if (processed_id.includes('[')) continue;
|
||||
const path = `/${get_route_segments(processed_id).join('/')}`;
|
||||
void enqueue(null, config.paths.base + path);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
void enqueue(null, config.paths.base + entry);
|
||||
}
|
||||
}
|
||||
|
||||
for (const { id, entries } of route_level_entries) {
|
||||
for (const entry of entries) {
|
||||
void enqueue(null, config.paths.base + entry, undefined, id);
|
||||
}
|
||||
}
|
||||
|
||||
for (const internals of prerender_functions) {
|
||||
/** @type {any[]} */
|
||||
let inputs;
|
||||
|
||||
try {
|
||||
inputs = (await internals.inputs?.()) ?? [];
|
||||
} catch (e) {
|
||||
if (e instanceof Error) fix_stack_trace(e);
|
||||
throw e;
|
||||
}
|
||||
|
||||
if (internals.has_arg) {
|
||||
for (const arg of inputs) {
|
||||
void enqueue(null, remote_prefix + internals.id + '/' + stringify_remote_arg(arg));
|
||||
}
|
||||
} else {
|
||||
void enqueue(null, remote_prefix + internals.id);
|
||||
}
|
||||
}
|
||||
|
||||
await q.done();
|
||||
progress?.clear();
|
||||
|
||||
// handle invalid fragment links
|
||||
for (const [key, referrers] of expected_hashlinks) {
|
||||
const index = key.indexOf('#');
|
||||
const path = key.slice(0, index);
|
||||
const id = key.slice(index + 1);
|
||||
|
||||
const hashlinks = actual_hashlinks.get(path);
|
||||
// ignore fragment links to pages that were not prerendered
|
||||
if (!hashlinks) continue;
|
||||
|
||||
if (!hashlinks.has(id) && !SPECIAL_HASHLINKS.has(id)) {
|
||||
handle_missing_id({ id, path, referrers: Array.from(referrers) });
|
||||
}
|
||||
}
|
||||
|
||||
/** @type {string[]} */
|
||||
const not_prerendered = [];
|
||||
|
||||
for (const [route_id, prerender] of prerender_map) {
|
||||
if (prerender === true && !prerendered_routes.has(route_id)) {
|
||||
not_prerendered.push(route_id);
|
||||
}
|
||||
}
|
||||
|
||||
if (not_prerendered.length > 0) {
|
||||
handle_not_prerendered_route({ routes: not_prerendered });
|
||||
}
|
||||
|
||||
return { prerendered, prerender_map };
|
||||
}
|
||||
72
node_modules/@sveltejs/kit/src/core/postbuild/queue.js
generated
vendored
Normal file
72
node_modules/@sveltejs/kit/src/core/postbuild/queue.js
generated
vendored
Normal file
@@ -0,0 +1,72 @@
|
||||
/**
|
||||
* @typedef {{
|
||||
* fn: () => Promise<any>,
|
||||
* fulfil: (value: any) => void,
|
||||
* reject: (error: Error) => void
|
||||
* }} Task
|
||||
*/
|
||||
|
||||
/** @param {number} concurrency */
|
||||
export function queue(concurrency) {
|
||||
/** @type {Task[]} */
|
||||
const tasks = [];
|
||||
const { promise, resolve, reject } = /** @type {PromiseWithResolvers<void>} */ (
|
||||
Promise.withResolvers()
|
||||
);
|
||||
|
||||
let current = 0;
|
||||
let closed = false;
|
||||
|
||||
promise.catch(() => {
|
||||
// this is necessary in case a catch handler is never added
|
||||
// to the done promise by the user
|
||||
});
|
||||
|
||||
function dequeue() {
|
||||
if (current < concurrency) {
|
||||
const task = tasks.shift();
|
||||
|
||||
if (task) {
|
||||
current += 1;
|
||||
const promise = (async () => task.fn())(); // could throw synchronously
|
||||
|
||||
void promise
|
||||
.then(task.fulfil, (err) => {
|
||||
task.reject(err);
|
||||
reject(err);
|
||||
})
|
||||
.then(() => {
|
||||
current -= 1;
|
||||
dequeue();
|
||||
});
|
||||
} else if (current === 0) {
|
||||
closed = true;
|
||||
resolve();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
/** @param {() => any} fn */
|
||||
add: (fn) => {
|
||||
if (closed) throw new Error('Cannot add tasks to a queue that has ended');
|
||||
|
||||
const promise = new Promise((fulfil, reject) => {
|
||||
tasks.push({ fn, fulfil, reject });
|
||||
});
|
||||
promise.catch(() => {});
|
||||
|
||||
dequeue();
|
||||
return promise;
|
||||
},
|
||||
|
||||
done: () => {
|
||||
if (current === 0) {
|
||||
closed = true;
|
||||
resolve();
|
||||
}
|
||||
|
||||
return promise;
|
||||
}
|
||||
};
|
||||
}
|
||||
72
node_modules/@sveltejs/kit/src/core/sync/create_manifest_data/conflict.js
generated
vendored
Normal file
72
node_modules/@sveltejs/kit/src/core/sync/create_manifest_data/conflict.js
generated
vendored
Normal file
@@ -0,0 +1,72 @@
|
||||
import * as e from '../../../messages/build-errors.js';
|
||||
|
||||
/** @param {import('types').RouteData[]} routes */
|
||||
export function prevent_conflicts(routes) {
|
||||
/** @type {Map<string, string>} */
|
||||
const lookup = new Map();
|
||||
|
||||
for (const route of routes) {
|
||||
if (!route.leaf && !route.endpoint) continue;
|
||||
|
||||
/** @type {string[]} */
|
||||
let permutations;
|
||||
|
||||
const normalized = normalize_route_id(route.id);
|
||||
|
||||
const ends_with_optional = /<\?.+?>$/.test(normalized);
|
||||
if (!ends_with_optional && Array.from(normalized.matchAll(/<\?.+?>/g)).length) {
|
||||
// find all permutations created by optional parameters
|
||||
const split = normalized.split(/<\?(.+?)>/g);
|
||||
|
||||
permutations = [/** @type {string} */ (split[0])];
|
||||
|
||||
// turn `x/[[optional]]/y` into `x/y` and `x/[required]/y`
|
||||
for (let i = 1; i < split.length; i += 2) {
|
||||
const matcher = split[i];
|
||||
const next = split[i + 1];
|
||||
|
||||
permutations = permutations.reduce((a, b) => {
|
||||
a.push(b + next);
|
||||
if (!(matcher === '*' && b.endsWith('//'))) a.push(b + `<${matcher}>${next}`);
|
||||
return a;
|
||||
}, /** @type {string[]} */ ([]));
|
||||
}
|
||||
} else {
|
||||
permutations = [normalized];
|
||||
}
|
||||
|
||||
for (const permutation of permutations) {
|
||||
// remove leading/trailing/duplicated slashes caused by prior
|
||||
// manipulation of optional parameters and (groups)
|
||||
const key = permutation
|
||||
.replace(/\/{2,}/, '/')
|
||||
.replace(/^\//, '')
|
||||
.replace(/\/$/, '');
|
||||
|
||||
if (lookup.has(key)) {
|
||||
e.route_conflict({ first: /** @type {string} */ (lookup.get(key)), second: route.id });
|
||||
}
|
||||
|
||||
lookup.set(key, route.id);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** @param {string} id */
|
||||
function normalize_route_id(id) {
|
||||
return (
|
||||
id
|
||||
// remove groups
|
||||
.replace(/(?<=^|\/)\(.+?\)(?=$|\/)/g, '')
|
||||
|
||||
.replace(/\[[ux]\+([0-9a-f]+)\]/g, (_, x) =>
|
||||
String.fromCodePoint(parseInt(x, 16)).replace(/\//g, '%2f')
|
||||
)
|
||||
|
||||
// replace `[param]` with `<*>`, `[param=x]` with `<x>`, and `[[param]]` with `<?*>`
|
||||
.replace(
|
||||
/\[(?:(\[)|(\.\.\.))?.+?(=.+?)?\]\]?/g,
|
||||
(_, optional, rest, matcher) => `<${optional ? '?' : ''}${rest ?? ''}${matcher ?? '*'}>`
|
||||
)
|
||||
);
|
||||
}
|
||||
585
node_modules/@sveltejs/kit/src/core/sync/create_manifest_data/index.js
generated
vendored
Normal file
585
node_modules/@sveltejs/kit/src/core/sync/create_manifest_data/index.js
generated
vendored
Normal file
@@ -0,0 +1,585 @@
|
||||
/** @import { ValidatedConfig } from 'types' */
|
||||
import { lookup } from '../../../utils/mime.js';
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { resolve_entry, walk } from '../../../utils/filesystem.js';
|
||||
import { posixify } from '../../../utils/os.js';
|
||||
import { parse_route_id, validate_route_id_params } from '../../../utils/routing.js';
|
||||
import { runtime_directory } from '../../utils.js';
|
||||
import * as e from '../../../messages/build-errors.js';
|
||||
import * as w from '../../../messages/build-warnings.js';
|
||||
import { prevent_conflicts } from './conflict.js';
|
||||
import { sort_routes } from './sort.js';
|
||||
import {
|
||||
create_node_analyser,
|
||||
get_page_options
|
||||
} from '../../../exports/vite/static_analysis/index.js';
|
||||
|
||||
const component_name_pattern = /^\+(?:(page(?:@(.*))?)|(layout(?:@(.*))?)|(error))$/;
|
||||
|
||||
const module_name_pattern =
|
||||
/^\+(?:(server)|(page(?:(@[a-zA-Z0-9_-]*))?(\.server)?)|(layout(?:(@[a-zA-Z0-9_-]*))?(\.server)?))$/;
|
||||
|
||||
/**
|
||||
* Generates the manifest data used for the client-side manifest and types generation.
|
||||
* @param {ValidatedConfig} config
|
||||
* @param {string} root
|
||||
* @param {string} [fallback] Where to look for fallback components
|
||||
* @returns {import('types').ManifestData}
|
||||
*/
|
||||
export default function create_manifest_data(
|
||||
config,
|
||||
root,
|
||||
fallback = `${runtime_directory}/components`
|
||||
) {
|
||||
const assets = create_assets(config);
|
||||
const hooks = create_hooks(config, root);
|
||||
const params = resolve_params(config, root);
|
||||
const { nodes, routes } = create_routes_and_nodes(root, config, fallback);
|
||||
|
||||
return {
|
||||
assets,
|
||||
hooks,
|
||||
params,
|
||||
nodes,
|
||||
routes
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether this route has a `+page`. Independent of `is_endpoint_route` — a route can be both.
|
||||
* @param {import('types').RouteData} route
|
||||
* @returns {boolean}
|
||||
*/
|
||||
export function is_page_route(route) {
|
||||
return !!route.page;
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether this route has a `+server`. Independent of `is_page_route` — a route can be both.
|
||||
* @param {import('types').RouteData} route
|
||||
* @returns {boolean}
|
||||
*/
|
||||
export function is_endpoint_route(route) {
|
||||
return !!route.endpoint;
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether the router can match this route. `manifest_data.routes` also contains entries for
|
||||
* directories with layouts or errors, which never reach `event.route.id`.
|
||||
* @param {import('types').RouteData} route
|
||||
* @returns {boolean}
|
||||
*/
|
||||
export function is_app_route(route) {
|
||||
return is_page_route(route) || is_endpoint_route(route);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a list of files in the `static` directory.
|
||||
* @param {import('types').ValidatedConfig} config
|
||||
*/
|
||||
export function create_assets(config) {
|
||||
if (!fs.existsSync(config.files.assets)) return [];
|
||||
|
||||
return [...walk(config.files.assets)].map((file) => ({
|
||||
file,
|
||||
type: lookup(file) || null
|
||||
}));
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {import('types').ValidatedConfig} config
|
||||
* @param {string} cwd
|
||||
*/
|
||||
function create_hooks(config, cwd) {
|
||||
const client = resolve_entry(config.files.hooks.client, config.moduleExtensions);
|
||||
const server = resolve_entry(config.files.hooks.server, config.moduleExtensions);
|
||||
const universal = resolve_entry(config.files.hooks.universal, config.moduleExtensions);
|
||||
|
||||
return {
|
||||
client: client && posixify(path.relative(cwd, client)),
|
||||
server: server && posixify(path.relative(cwd, server)),
|
||||
universal: universal && posixify(path.relative(cwd, universal))
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {import('types').ValidatedConfig} config
|
||||
* @param {string} cwd
|
||||
*/
|
||||
function resolve_params(config, cwd) {
|
||||
const params_file = resolve_entry(config.files.params, config.moduleExtensions);
|
||||
return params_file ? posixify(path.relative(cwd, params_file)) : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {string} cwd
|
||||
* @param {import('types').ValidatedConfig} config
|
||||
* @param {string} fallback
|
||||
*/
|
||||
function create_routes_and_nodes(cwd, config, fallback) {
|
||||
/** @type {import('types').RouteData[]} */
|
||||
let routes = [];
|
||||
|
||||
const routes_base = posixify(path.relative(cwd, config.files.routes));
|
||||
|
||||
const valid_extensions = [...config.extensions, ...config.moduleExtensions];
|
||||
|
||||
/** @type {import('types').PageNode[]} */
|
||||
const nodes = [];
|
||||
|
||||
// create route data by processing files in `src/routes`
|
||||
if (fs.existsSync(config.files.routes)) {
|
||||
/**
|
||||
* @param {number} depth
|
||||
* @param {string} id
|
||||
* @param {string} segment
|
||||
* @param {import('types').RouteData | null} parent
|
||||
*/
|
||||
const walk = (depth, id, segment, parent) => {
|
||||
const unescaped = id.replace(/\[([ux])\+([^\]]+)\]/gi, (match, type, code) => {
|
||||
if (match !== match.toLowerCase()) {
|
||||
e.route_escape_uppercase({ id });
|
||||
}
|
||||
|
||||
if (!/[0-9a-f]+/.test(code)) {
|
||||
e.route_escape_invalid({ id });
|
||||
}
|
||||
|
||||
if (type === 'x') {
|
||||
if (code.length !== 2) {
|
||||
e.route_escape_hex_length({ id });
|
||||
}
|
||||
|
||||
return String.fromCharCode(parseInt(code, 16));
|
||||
} else {
|
||||
if (code.length < 4 || code.length > 6) {
|
||||
e.route_escape_unicode_length({ id });
|
||||
}
|
||||
|
||||
return String.fromCodePoint(parseInt(code, 16));
|
||||
}
|
||||
});
|
||||
|
||||
if (/\]\[/.test(unescaped)) {
|
||||
e.route_params_adjacent({ id });
|
||||
}
|
||||
|
||||
if (count_occurrences('[', id) !== count_occurrences(']', id)) {
|
||||
e.route_unbalanced_brackets({ id });
|
||||
}
|
||||
|
||||
if (/#/.test(segment)) {
|
||||
// Vite will barf on files with # in them
|
||||
e.route_hash_character({ id, suggestion: id.replace(/#/g, '[x+23]') });
|
||||
}
|
||||
|
||||
if (/\[\.\.\.[\w-]+\]\/\[\[/.test(id)) {
|
||||
e.route_optional_after_rest({ id });
|
||||
}
|
||||
|
||||
if (/\[\[\.\.\./.test(id)) {
|
||||
e.route_optional_rest({ id });
|
||||
}
|
||||
|
||||
const invalid_param = validate_route_id_params(id);
|
||||
if (invalid_param !== undefined) {
|
||||
e.route_param_invalid({ param: invalid_param, id });
|
||||
}
|
||||
|
||||
const { pattern, params } = parse_route_id(id);
|
||||
|
||||
/** @type {import('types').RouteData} */
|
||||
const route = {
|
||||
id,
|
||||
parent,
|
||||
|
||||
segment,
|
||||
pattern,
|
||||
params,
|
||||
|
||||
layout: null,
|
||||
error: null,
|
||||
leaf: null,
|
||||
page: null,
|
||||
endpoint: null
|
||||
};
|
||||
|
||||
// important to do this before walking children, so that child
|
||||
// routes appear later
|
||||
routes.push(route);
|
||||
|
||||
// if we don't do this, the route map becomes unwieldy to console.log
|
||||
Object.defineProperty(route, 'parent', { enumerable: false });
|
||||
|
||||
const dir = path.join(cwd, routes_base, id);
|
||||
|
||||
// We sort the entries because `readdirSync` order is not guaranteed and differs
|
||||
// between runtimes (e.g. Node returns entries alphabetically, Bun in directory
|
||||
// order). Node indices are assigned from this traversal order, so without sorting
|
||||
// the SSR and client manifests can disagree, causing hydration mismatches.
|
||||
const files = fs
|
||||
.readdirSync(dir, { withFileTypes: true })
|
||||
.sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0))
|
||||
.map((entry) => ({
|
||||
is_dir: entry.isSymbolicLink()
|
||||
? fs.statSync(path.join(dir, entry.name)).isDirectory()
|
||||
: entry.isDirectory(),
|
||||
name: entry.name
|
||||
}));
|
||||
|
||||
// process files first
|
||||
for (const file of files) {
|
||||
if (file.is_dir) continue;
|
||||
|
||||
const ext = valid_extensions.find((ext) => file.name.endsWith(ext));
|
||||
if (!ext) continue;
|
||||
|
||||
if (!file.name.startsWith('+')) {
|
||||
const name = file.name.slice(0, -ext.length);
|
||||
const pattern = config.extensions.includes(ext)
|
||||
? component_name_pattern
|
||||
: module_name_pattern;
|
||||
|
||||
// check if it is a valid route filename but missing the + prefix
|
||||
if (pattern.test(`+${name}`)) {
|
||||
w.route_file_prefix_missing({
|
||||
corrected: `+${file.name}`,
|
||||
file: path.join(dir, file.name)
|
||||
});
|
||||
}
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
// allow e.g. `+page.stories.svelte` or `+server.test.ts`
|
||||
if (
|
||||
file.name.includes('.test.') ||
|
||||
file.name.includes('.spec.') ||
|
||||
file.name.includes('.stories.')
|
||||
) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (file.name.endsWith('.d.ts')) {
|
||||
let name = file.name.slice(0, -5);
|
||||
const ext = valid_extensions.find((ext) => name.endsWith(ext));
|
||||
if (ext) name = name.slice(0, -ext.length);
|
||||
|
||||
if (component_name_pattern.test(name) || module_name_pattern.test(name)) continue;
|
||||
}
|
||||
|
||||
const project_relative = posixify(path.relative(cwd, path.join(dir, file.name)));
|
||||
|
||||
const item = analyze(
|
||||
project_relative,
|
||||
file.name,
|
||||
config.extensions,
|
||||
config.moduleExtensions
|
||||
);
|
||||
|
||||
if (config.router.type === 'hash' && item.kind === 'server') {
|
||||
e.route_server_file_hash_router({ file: project_relative });
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {string} type
|
||||
* @param {string} existing_file
|
||||
* @returns {never}
|
||||
*/
|
||||
function duplicate_files(type, existing_file) {
|
||||
e.route_duplicate_files({
|
||||
type,
|
||||
directory: `${routes_base}${route.id}`,
|
||||
existing: path.basename(existing_file),
|
||||
file: file.name
|
||||
});
|
||||
}
|
||||
|
||||
if (item.kind === 'component') {
|
||||
if (item.is_error) {
|
||||
route.error = {
|
||||
depth,
|
||||
component: project_relative
|
||||
};
|
||||
} else if (item.is_layout) {
|
||||
if (!route.layout) {
|
||||
route.layout = { depth, child_pages: [] };
|
||||
} else if (route.layout.component) {
|
||||
duplicate_files('layout component', route.layout.component);
|
||||
}
|
||||
|
||||
route.layout.component = project_relative;
|
||||
if (item.uses_layout !== undefined) route.layout.parent_id = item.uses_layout;
|
||||
} else {
|
||||
if (!route.leaf) {
|
||||
route.leaf = { depth };
|
||||
} else if (route.leaf.component) {
|
||||
duplicate_files('page component', route.leaf.component);
|
||||
}
|
||||
|
||||
route.leaf.component = project_relative;
|
||||
if (item.uses_layout !== undefined) route.leaf.parent_id = item.uses_layout;
|
||||
}
|
||||
} else if (item.is_layout) {
|
||||
if (!route.layout) {
|
||||
route.layout = { depth, child_pages: [] };
|
||||
} else if (route.layout[item.kind]) {
|
||||
duplicate_files(
|
||||
item.kind + ' layout module',
|
||||
/** @type {string} */ (route.layout[item.kind])
|
||||
);
|
||||
}
|
||||
|
||||
route.layout[item.kind] = project_relative;
|
||||
} else if (item.is_page) {
|
||||
if (!route.leaf) {
|
||||
route.leaf = { depth };
|
||||
} else if (route.leaf[item.kind]) {
|
||||
duplicate_files(
|
||||
item.kind + ' page module',
|
||||
/** @type {string} */ (route.leaf[item.kind])
|
||||
);
|
||||
}
|
||||
|
||||
route.leaf[item.kind] = project_relative;
|
||||
} else {
|
||||
if (route.endpoint) {
|
||||
duplicate_files('endpoint', route.endpoint.file);
|
||||
}
|
||||
|
||||
route.endpoint = {
|
||||
file: project_relative,
|
||||
page_options: null // will be filled later
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
// then handle children
|
||||
for (const file of files) {
|
||||
if (file.is_dir) {
|
||||
walk(depth + 1, path.posix.join(id, file.name), file.name, route);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
walk(0, '/', '', null);
|
||||
|
||||
if (routes.length === 1) {
|
||||
const root = routes[0];
|
||||
if (!root.leaf && !root.error && !root.layout && !root.endpoint) {
|
||||
e.routes_not_found();
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// If there's no routes directory, we'll just create a single empty route. This ensures the root layout and
|
||||
// error components are included in the manifest, which is needed for subsequent build/dev commands to work
|
||||
routes.push({
|
||||
id: '/',
|
||||
segment: '',
|
||||
pattern: /^$/,
|
||||
params: [],
|
||||
parent: null,
|
||||
layout: null,
|
||||
error: null,
|
||||
leaf: null,
|
||||
page: null,
|
||||
endpoint: null
|
||||
});
|
||||
}
|
||||
|
||||
prevent_conflicts(routes);
|
||||
|
||||
// fallback root layout and root error components
|
||||
const root = routes[0];
|
||||
|
||||
if (!root.layout?.component) {
|
||||
if (!root.layout) root.layout = { depth: 0, child_pages: [] };
|
||||
root.layout.component = posixify(path.relative(cwd, `${fallback}/layout.svelte`));
|
||||
}
|
||||
|
||||
if (!root.error?.component) {
|
||||
if (!root.error) root.error = { depth: 0, parent: root.layout };
|
||||
root.error.component = posixify(path.relative(cwd, `${fallback}/error.svelte`));
|
||||
}
|
||||
|
||||
// populate the page nodes list
|
||||
// we do layouts/errors first as they are more likely to be reused,
|
||||
// and smaller indexes take fewer bytes. also, this guarantees that
|
||||
// the default error/layout are 0/1
|
||||
for (const route of routes) {
|
||||
if (route.layout) {
|
||||
if (!route.layout?.component) {
|
||||
route.layout.component = posixify(path.relative(cwd, `${fallback}/layout.svelte`));
|
||||
}
|
||||
nodes.push(route.layout);
|
||||
}
|
||||
if (route.error) nodes.push(route.error);
|
||||
}
|
||||
|
||||
for (const route of routes) {
|
||||
if (route.leaf) nodes.push(route.leaf);
|
||||
}
|
||||
|
||||
const indexes = new Map(nodes.map((node, i) => [node, i]));
|
||||
|
||||
const node_analyser = create_node_analyser(cwd);
|
||||
|
||||
// add the related layout, page, and error nodes for a route
|
||||
for (const route of routes) {
|
||||
if (!route.leaf) continue;
|
||||
|
||||
route.page = {
|
||||
layouts: [],
|
||||
errors: [],
|
||||
leaf: /** @type {number} */ (indexes.get(route.leaf))
|
||||
};
|
||||
|
||||
/** @type {import('types').RouteData | null} */
|
||||
let current_route = route;
|
||||
let current_node = route.leaf;
|
||||
let parent_id = route.leaf.parent_id;
|
||||
|
||||
while (current_route) {
|
||||
if (parent_id === undefined || current_route.segment === parent_id) {
|
||||
if (current_route.layout || current_route.error) {
|
||||
route.page.layouts.unshift(
|
||||
current_route.layout ? indexes.get(current_route.layout) : undefined
|
||||
);
|
||||
route.page.errors.unshift(
|
||||
current_route.error ? indexes.get(current_route.error) : undefined
|
||||
);
|
||||
}
|
||||
|
||||
if (current_route.layout) {
|
||||
/** @type {import('types').PageNode[]} */ (current_route.layout.child_pages).push(
|
||||
route.leaf
|
||||
);
|
||||
current_node.parent = current_node = current_route.layout;
|
||||
parent_id = current_node.parent_id;
|
||||
} else {
|
||||
parent_id = undefined;
|
||||
}
|
||||
}
|
||||
|
||||
current_route = current_route.parent;
|
||||
}
|
||||
|
||||
if (parent_id !== undefined) {
|
||||
e.route_layout_segment_missing({
|
||||
file: /** @type {string} */ (current_node.component),
|
||||
segment: parent_id
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// remove route objects with no route file
|
||||
routes = routes.filter((route) => route.endpoint || route.leaf || route.layout || route.error);
|
||||
|
||||
// add parents to error nodes so that we can compute which page options apply to them
|
||||
for (const route of routes) {
|
||||
if (!route.error) continue;
|
||||
|
||||
/** @type {import('types').RouteData | null} */
|
||||
let current_route = route;
|
||||
while (current_route) {
|
||||
if (current_route.layout) {
|
||||
route.error.parent = current_route.layout;
|
||||
break;
|
||||
}
|
||||
current_route = current_route.parent;
|
||||
}
|
||||
}
|
||||
|
||||
// compute the final page options for each page node
|
||||
for (const node of nodes) {
|
||||
node.page_options = node_analyser.get_page_options(node);
|
||||
}
|
||||
|
||||
for (const route of routes) {
|
||||
if (route.endpoint) {
|
||||
route.endpoint.page_options = get_page_options(route.endpoint.file, cwd);
|
||||
}
|
||||
|
||||
if (route.page && route.endpoint) {
|
||||
const page = nodes[route.page.leaf];
|
||||
if (page.page_options?.prerender || route.endpoint.page_options?.prerender) {
|
||||
const endpoint_file = route.endpoint.file.split('/').pop();
|
||||
|
||||
e.route_prerender_page_and_endpoint({
|
||||
id: route.id,
|
||||
file: /** @type {string} */ (endpoint_file)
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
nodes,
|
||||
routes: sort_routes(routes)
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Determine if and how the file is relevant to the routing system.
|
||||
* @param {string} project_relative
|
||||
* @param {string} file
|
||||
* @param {string[]} component_extensions
|
||||
* @param {string[]} module_extensions
|
||||
* @returns {import('./types.js').RouteFile}
|
||||
*/
|
||||
function analyze(project_relative, file, component_extensions, module_extensions) {
|
||||
const component_extension = component_extensions.find((ext) => file.endsWith(ext));
|
||||
if (component_extension) {
|
||||
const name = file.slice(0, -component_extension.length);
|
||||
const match = component_name_pattern.exec(name);
|
||||
if (!match) {
|
||||
e.route_file_reserved({ file: project_relative });
|
||||
}
|
||||
|
||||
return {
|
||||
kind: 'component',
|
||||
is_page: !!match[1],
|
||||
is_layout: !!match[3],
|
||||
is_error: !!match[5],
|
||||
uses_layout: match[2] ?? match[4]
|
||||
};
|
||||
}
|
||||
|
||||
const module_extension = module_extensions.find((ext) => file.endsWith(ext));
|
||||
if (module_extension) {
|
||||
const name = file.slice(0, -module_extension.length);
|
||||
const match = module_name_pattern.exec(name);
|
||||
if (!match) {
|
||||
e.route_file_reserved({ file: project_relative });
|
||||
} else if (match[3] || match[6]) {
|
||||
e.route_named_layout_in_module({
|
||||
layout: match[3] || match[6],
|
||||
name: file,
|
||||
file: project_relative
|
||||
});
|
||||
}
|
||||
|
||||
const kind = match[1] || match[4] || match[7] ? 'server' : 'universal';
|
||||
|
||||
return {
|
||||
kind,
|
||||
is_page: !!match[2],
|
||||
is_layout: !!match[5]
|
||||
};
|
||||
}
|
||||
|
||||
e.route_file_reserved({ file: project_relative });
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {string} needle
|
||||
* @param {string} haystack
|
||||
*/
|
||||
function count_occurrences(needle, haystack) {
|
||||
let count = 0;
|
||||
for (let i = 0; i < haystack.length; i += 1) {
|
||||
if (haystack[i] === needle) count += 1;
|
||||
}
|
||||
return count;
|
||||
}
|
||||
162
node_modules/@sveltejs/kit/src/core/sync/create_manifest_data/sort.js
generated
vendored
Normal file
162
node_modules/@sveltejs/kit/src/core/sync/create_manifest_data/sort.js
generated
vendored
Normal file
@@ -0,0 +1,162 @@
|
||||
import { get_route_segments } from '../../../utils/routing.js';
|
||||
|
||||
/**
|
||||
* @typedef {{
|
||||
* type: 'static' | 'required' | 'optional' | 'rest';
|
||||
* content: string;
|
||||
* matched: boolean;
|
||||
* }} Part
|
||||
*/
|
||||
|
||||
/**
|
||||
* @typedef {Part[]} Segment
|
||||
*/
|
||||
|
||||
const EMPTY = { type: 'static', content: '', matched: false };
|
||||
|
||||
/** @param {import('types').RouteData[]} routes */
|
||||
export function sort_routes(routes) {
|
||||
/** @type {Map<string, Part[]>} */
|
||||
const segment_cache = new Map();
|
||||
|
||||
/** @param {string} segment */
|
||||
function get_parts(segment) {
|
||||
if (!segment_cache.has(segment)) {
|
||||
segment_cache.set(segment, split(segment));
|
||||
}
|
||||
|
||||
return segment_cache.get(segment);
|
||||
}
|
||||
|
||||
/** @param {string} id */
|
||||
function split(id) {
|
||||
/** @type {Part[]} */
|
||||
const parts = [];
|
||||
|
||||
let i = 0;
|
||||
while (i <= id.length) {
|
||||
const start = id.indexOf('[', i);
|
||||
if (start === -1) {
|
||||
parts.push({ type: 'static', content: id.slice(i), matched: false });
|
||||
break;
|
||||
}
|
||||
|
||||
parts.push({ type: 'static', content: id.slice(i, start), matched: false });
|
||||
|
||||
const type = id[start + 1] === '[' ? 'optional' : id[start + 1] === '.' ? 'rest' : 'required';
|
||||
const delimiter = type === 'optional' ? ']]' : ']';
|
||||
const end = id.indexOf(delimiter, start);
|
||||
|
||||
if (end === -1) {
|
||||
throw new Error(`Invalid route ID ${id}`);
|
||||
}
|
||||
|
||||
const content = id.slice(start, (i = end + delimiter.length));
|
||||
|
||||
parts.push({
|
||||
type,
|
||||
content,
|
||||
matched: content.includes('=')
|
||||
});
|
||||
}
|
||||
|
||||
return parts;
|
||||
}
|
||||
|
||||
return routes.sort((route_a, route_b) => {
|
||||
const segments_a = split_route_id(route_a.id).map(get_parts);
|
||||
const segments_b = split_route_id(route_b.id).map(get_parts);
|
||||
|
||||
for (let i = 0; i < Math.max(segments_a.length, segments_b.length); i += 1) {
|
||||
const segment_a = segments_a[i] ?? [EMPTY];
|
||||
const segment_b = segments_b[i] ?? [EMPTY];
|
||||
|
||||
for (let j = 0; j < Math.max(segment_a.length, segment_b.length); j += 1) {
|
||||
const a = segment_a[j];
|
||||
const b = segment_b[j];
|
||||
|
||||
// first part of each segment is always static
|
||||
// (though it may be the empty string), then
|
||||
// it alternates between dynamic and static
|
||||
// (i.e. [foo][bar] is disallowed)
|
||||
const dynamic = j % 2 === 1;
|
||||
|
||||
if (dynamic) {
|
||||
if (!a) return -1;
|
||||
if (!b) return +1;
|
||||
|
||||
// get the next static chunk, so we can handle [...rest] edge cases
|
||||
const next_a = segment_a[j + 1].content || segments_a[i + 1]?.[0].content;
|
||||
const next_b = segment_b[j + 1].content || segments_b[i + 1]?.[0].content;
|
||||
|
||||
// `[...rest]/x` outranks `[...rest]`
|
||||
if (a.type === 'rest' && b.type === 'rest') {
|
||||
if (next_a && next_b) continue;
|
||||
if (next_a) return -1;
|
||||
if (next_b) return +1;
|
||||
}
|
||||
|
||||
// `[...rest]/x` outranks `[required]` or `[required]/[required]`
|
||||
// but not `[required]/x`
|
||||
if (a.type === 'rest') {
|
||||
return next_a && !next_b ? -1 : +1;
|
||||
}
|
||||
|
||||
if (b.type === 'rest') {
|
||||
return next_b && !next_a ? +1 : -1;
|
||||
}
|
||||
|
||||
// part with matcher outranks one without
|
||||
if (a.matched !== b.matched) {
|
||||
return a.matched ? -1 : +1;
|
||||
}
|
||||
|
||||
if (a.type !== b.type) {
|
||||
// `[...rest]` has already been accounted for, so here
|
||||
// we're comparing between `[required]` and `[[optional]]`
|
||||
if (a.type === 'required') return -1;
|
||||
if (b.type === 'required') return +1;
|
||||
}
|
||||
} else if (a.content !== b.content) {
|
||||
// shallower path outranks deeper path
|
||||
if (a === EMPTY) return -1;
|
||||
if (b === EMPTY) return +1;
|
||||
|
||||
return sort_static(a.content, b.content);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return route_a.id < route_b.id ? +1 : -1;
|
||||
});
|
||||
}
|
||||
|
||||
/** @param {string} id */
|
||||
function split_route_id(id) {
|
||||
return get_route_segments(
|
||||
id
|
||||
// remove all [[optional]] parts unless they're at the very end
|
||||
// or it ends with a route group
|
||||
.replace(/\[\[[^\]]+\]\](?!(?:\/\([^/]+\))*$)/g, '')
|
||||
).filter(Boolean);
|
||||
}
|
||||
|
||||
/**
|
||||
* Sort two strings lexicographically, except `foobar` outranks `foo`
|
||||
* @param {string} a
|
||||
* @param {string} b
|
||||
*/
|
||||
function sort_static(a, b) {
|
||||
if (a === b) return 0;
|
||||
|
||||
for (let i = 0; true; i += 1) {
|
||||
const char_a = a[i];
|
||||
const char_b = b[i];
|
||||
|
||||
if (char_a !== char_b) {
|
||||
if (char_a === undefined) return +1;
|
||||
if (char_b === undefined) return -1;
|
||||
return char_a < char_b ? -1 : +1;
|
||||
}
|
||||
}
|
||||
}
|
||||
37
node_modules/@sveltejs/kit/src/core/sync/create_manifest_data/types.d.ts
generated
vendored
Normal file
37
node_modules/@sveltejs/kit/src/core/sync/create_manifest_data/types.d.ts
generated
vendored
Normal file
@@ -0,0 +1,37 @@
|
||||
import { PageNode } from 'types';
|
||||
|
||||
interface Part {
|
||||
dynamic: boolean;
|
||||
optional: boolean;
|
||||
rest: boolean;
|
||||
type: string | null;
|
||||
}
|
||||
|
||||
interface RouteTreeNode {
|
||||
error: PageNode | undefined;
|
||||
layout: PageNode | undefined;
|
||||
}
|
||||
|
||||
export type RouteTree = Map<string, RouteTreeNode>;
|
||||
|
||||
interface RouteComponent {
|
||||
kind: 'component';
|
||||
is_page: boolean;
|
||||
is_layout: boolean;
|
||||
is_error: boolean;
|
||||
uses_layout: string | undefined;
|
||||
}
|
||||
|
||||
interface RouteSharedModule {
|
||||
kind: 'universal';
|
||||
is_page: boolean;
|
||||
is_layout: boolean;
|
||||
}
|
||||
|
||||
interface RouteServerModule {
|
||||
kind: 'server';
|
||||
is_page: boolean;
|
||||
is_layout: boolean;
|
||||
}
|
||||
|
||||
export type RouteFile = RouteComponent | RouteSharedModule | RouteServerModule;
|
||||
109
node_modules/@sveltejs/kit/src/core/sync/sync.js
generated
vendored
Normal file
109
node_modules/@sveltejs/kit/src/core/sync/sync.js
generated
vendored
Normal file
@@ -0,0 +1,109 @@
|
||||
/** @import { ValidatedConfig, ManifestData } from 'types' */
|
||||
import path from 'node:path';
|
||||
import create_manifest_data from './create_manifest_data/index.js';
|
||||
import { write_client_manifest } from './write_client_manifest.js';
|
||||
import { write_tsconfig } from './write_tsconfig/index.js';
|
||||
import { write_types, write_all_types } from './write_types/index.js';
|
||||
import { write_app_types } from './write_app_types.js';
|
||||
import { write_server } from './write_server.js';
|
||||
import {
|
||||
create_node_analyser,
|
||||
get_page_options
|
||||
} from '../../exports/vite/static_analysis/index.js';
|
||||
import { load_explicit_env } from '../env.js';
|
||||
import { write_env } from './write_env.js';
|
||||
import { write_app_manifest } from './write_app_manifest.js';
|
||||
|
||||
/**
|
||||
* Update SvelteKit's generated files
|
||||
* @param {ValidatedConfig} config
|
||||
* @param {string} root The project root directory
|
||||
* @param {ManifestData} manifest_data
|
||||
* @param {boolean} is_build
|
||||
*/
|
||||
export function create(config, root, manifest_data, is_build) {
|
||||
const output = path.join(config.outDir, `generated/${is_build ? 'build' : 'dev'}`);
|
||||
|
||||
write_app_manifest(output, manifest_data, is_build);
|
||||
write_client_manifest(config, manifest_data, `${output}/client`, root);
|
||||
write_server(config, output, root);
|
||||
write_all_types(config, manifest_data, root);
|
||||
write_app_types(config, manifest_data, root);
|
||||
}
|
||||
|
||||
/**
|
||||
* Update SvelteKit's generated files in response to a single file content update.
|
||||
* Do not call this when the file in question was created/deleted.
|
||||
*
|
||||
* @param {ValidatedConfig} config
|
||||
* @param {import('types').ManifestData} manifest_data
|
||||
* @param {string} file
|
||||
* @param {string} root The project root directory
|
||||
* @returns {boolean} Whether the update completed, or a full manifest rebuild is needed
|
||||
*/
|
||||
export function update(config, manifest_data, file, root) {
|
||||
try {
|
||||
const node_analyser = create_node_analyser(root);
|
||||
|
||||
for (const node of manifest_data.nodes) {
|
||||
node.page_options = node_analyser.get_page_options(node);
|
||||
}
|
||||
|
||||
for (const route of manifest_data.routes) {
|
||||
if (route.endpoint) {
|
||||
route.endpoint.page_options = get_page_options(route.endpoint.file, root);
|
||||
}
|
||||
}
|
||||
|
||||
write_types(config, manifest_data, file, root);
|
||||
write_app_types(config, manifest_data, root);
|
||||
} catch (error) {
|
||||
// A route file can disappear before the watcher delivers its unlink event. In that case,
|
||||
// the manifest is stale and must be rebuilt instead of incrementally updated.
|
||||
if (error && typeof error === 'object' && 'code' in error && error.code === 'ENOENT') {
|
||||
return false;
|
||||
}
|
||||
|
||||
throw error;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Run write_tsconfig and sync.create in series during build
|
||||
* @param {ValidatedConfig} config
|
||||
* @param {string} root The project root directory
|
||||
* @param {ManifestData} manifest_data
|
||||
*/
|
||||
export function all(config, root, manifest_data) {
|
||||
write_tsconfig(config, root);
|
||||
create(config, root, manifest_data, true);
|
||||
}
|
||||
|
||||
/**
|
||||
* Run sync.init and then generate all type files.
|
||||
* @param {ValidatedConfig} config
|
||||
* @param {string} root
|
||||
*/
|
||||
export function all_types(config, root) {
|
||||
write_tsconfig(config, root);
|
||||
const manifest_data = create_manifest_data(config, root);
|
||||
write_all_types(config, manifest_data, root);
|
||||
write_app_types(config, manifest_data, root);
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate modules and types for explicit env vars
|
||||
* @param {ValidatedConfig} kit
|
||||
* @param {string | null} entry
|
||||
* @param {string} root The Vite root
|
||||
* @param {string} mode The Vite mode
|
||||
*/
|
||||
export async function env(kit, entry, root, mode) {
|
||||
const env_config = await load_explicit_env(kit, entry, root, mode);
|
||||
|
||||
write_env(entry, env_config.variables, root);
|
||||
|
||||
return env_config;
|
||||
}
|
||||
6
node_modules/@sveltejs/kit/src/core/sync/ts.js
generated
vendored
Normal file
6
node_modules/@sveltejs/kit/src/core/sync/ts.js
generated
vendored
Normal file
@@ -0,0 +1,6 @@
|
||||
/** @type {typeof import('typescript')} */
|
||||
// @ts-ignore
|
||||
export let ts = undefined;
|
||||
try {
|
||||
ts = (await import('typescript')).default;
|
||||
} catch {}
|
||||
98
node_modules/@sveltejs/kit/src/core/sync/utils.js
generated
vendored
Normal file
98
node_modules/@sveltejs/kit/src/core/sync/utils.js
generated
vendored
Normal file
@@ -0,0 +1,98 @@
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { resolve_entry } from '../../utils/filesystem.js';
|
||||
import * as w from '../../messages/build-warnings.js';
|
||||
|
||||
/**
|
||||
* @param {string} file
|
||||
* @param {string} code
|
||||
*/
|
||||
export function write_if_changed(file, code) {
|
||||
// compare against the file itself rather than what this process wrote earlier: another
|
||||
// process syncing the same project (such as `vitest run` beside `vite dev`) would
|
||||
// otherwise rewrite every generated file with identical bytes, and the dev server
|
||||
// reloads on each of them
|
||||
if (code !== read(file)) {
|
||||
write(file, code);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {string} file
|
||||
* @param {string} code
|
||||
*/
|
||||
export function write(file, code) {
|
||||
fs.mkdirSync(path.dirname(file), { recursive: true });
|
||||
fs.writeFileSync(file, code);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {string} file
|
||||
* @returns {string | undefined} the contents of the file, or `undefined` if it cannot be read
|
||||
*/
|
||||
function read(file) {
|
||||
try {
|
||||
return fs.readFileSync(file, 'utf-8');
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
/** @type {WeakMap<TemplateStringsArray, { strings: string[], indents: string[] }>} */
|
||||
const dedent_map = new WeakMap();
|
||||
|
||||
/**
|
||||
* Allows indenting template strings without the extra indentation ending up in the result.
|
||||
* Still allows indentation of lines relative to one another in the template string.
|
||||
* @param {TemplateStringsArray} strings
|
||||
* @param {any[]} values
|
||||
*/
|
||||
export function dedent(strings, ...values) {
|
||||
let dedented = dedent_map.get(strings);
|
||||
|
||||
if (!dedented) {
|
||||
const indentation = /** @type {RegExpExecArray} */ (/\n?([ \t]*)/.exec(strings[0]))[1];
|
||||
const pattern = new RegExp(`^${indentation}`, 'gm');
|
||||
|
||||
dedented = {
|
||||
strings: strings.map((str) => str.replace(pattern, '')),
|
||||
indents: []
|
||||
};
|
||||
|
||||
let current = '\n';
|
||||
|
||||
for (let i = 0; i < values.length; i += 1) {
|
||||
const string = dedented.strings[i];
|
||||
const match = /\n([ \t]*)$/.exec(string);
|
||||
|
||||
if (match) current = match[0];
|
||||
dedented.indents[i] = current;
|
||||
}
|
||||
|
||||
dedent_map.set(strings, dedented);
|
||||
}
|
||||
|
||||
let str = dedented.strings[0];
|
||||
for (let i = 0; i < values.length; i += 1) {
|
||||
str += String(values[i]).replace(/\n/g, dedented.indents[i]) + dedented.strings[i + 1];
|
||||
}
|
||||
|
||||
str = str.trim();
|
||||
|
||||
return str;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {string} original
|
||||
* @param {string} typo The common misspelling to check for
|
||||
* @param {string} description What was wrong with the filename
|
||||
* @param {string[]} extensions the extensions a module may have
|
||||
*/
|
||||
export function check_spelling(original, typo, description, extensions) {
|
||||
const misspelled = resolve_entry(typo, extensions);
|
||||
if (!misspelled) return;
|
||||
|
||||
const corrected = path.basename(misspelled).replace(path.basename(typo), path.basename(original));
|
||||
|
||||
w.file_name_misspelled({ description, corrected, file: path.resolve(misspelled) });
|
||||
}
|
||||
87
node_modules/@sveltejs/kit/src/core/sync/write_app_manifest.js
generated
vendored
Normal file
87
node_modules/@sveltejs/kit/src/core/sync/write_app_manifest.js
generated
vendored
Normal file
@@ -0,0 +1,87 @@
|
||||
/** @import { Asset, ManifestData, RouteData } from 'types' */
|
||||
/** @import { ManifestRoute } from '$app/manifest' */
|
||||
|
||||
import { s } from '../../utils/misc.js';
|
||||
import { is_app_route, is_endpoint_route, is_page_route } from './create_manifest_data/index.js';
|
||||
import { dedent, write_if_changed } from './utils.js';
|
||||
|
||||
/**
|
||||
* Creates the `$app/manifest` data module. During development, real values
|
||||
* are emitted for `assets` and `routes` (the only data known at that point).
|
||||
*
|
||||
* During build, bare identifier placeholders (fake globals) are emitted.
|
||||
* The bundler leaves these as unresolved global references in the output,
|
||||
* which are then replaced with real values by scanning the output chunks
|
||||
* after each build completes. This avoids the content-hash feedback loop:
|
||||
* the manifest data lives in its own chunk with a fixed filename, so
|
||||
* importers' hashes are stable regardless of the manifest content.
|
||||
*
|
||||
* @param {string} out
|
||||
* @param {ManifestData | undefined} manifest_data
|
||||
* @param {boolean} is_build
|
||||
*/
|
||||
export function write_app_manifest(out, manifest_data, is_build) {
|
||||
const code = is_build
|
||||
? // Bare identifiers (fake globals) — the bundler leaves these as
|
||||
// unresolved global references in the output. They are replaced
|
||||
// with real values by `replace_manifest_placeholder_variables`
|
||||
// after each build completes.
|
||||
dedent`
|
||||
export const immutable = __SVELTEKIT_MANIFEST_IMMUTABLE__;
|
||||
export const assets = __SVELTEKIT_MANIFEST_ASSETS__;
|
||||
export const prerendered = __SVELTEKIT_MANIFEST_PRERENDERED__;
|
||||
export const routes = __SVELTEKIT_MANIFEST_ROUTES__;
|
||||
`
|
||||
: // In dev, an empty manifest is written before dependency scanning starts.
|
||||
// `configureServer` replaces it with the full manifest before modules are served.
|
||||
dedent`
|
||||
// empty during dev
|
||||
export const immutable = [];
|
||||
export const prerendered = [];
|
||||
|
||||
export const assets = [
|
||||
${stringify_assets(manifest_data?.assets)}
|
||||
];
|
||||
|
||||
export const routes = [
|
||||
${stringify_routes(manifest_data?.routes)}
|
||||
];
|
||||
`;
|
||||
|
||||
write_if_changed(`${out}/app-manifest.js`, code);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {Asset[] | undefined} assets
|
||||
* @returns {string}
|
||||
*/
|
||||
function stringify_assets(assets) {
|
||||
return assets?.map((asset) => s({ path: asset.file })).join(',\n') ?? '';
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {RouteData[] | undefined} routes
|
||||
* @returns {ManifestRoute[]}
|
||||
*/
|
||||
export function get_manifest_routes(routes) {
|
||||
return (
|
||||
routes?.filter(is_app_route).map(
|
||||
(route) =>
|
||||
/** @type {ManifestRoute} */ ({
|
||||
id: route.id,
|
||||
page: is_page_route(route),
|
||||
endpoint: is_endpoint_route(route)
|
||||
})
|
||||
) ?? []
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {RouteData[] | undefined} routes
|
||||
* @returns {string}
|
||||
*/
|
||||
function stringify_routes(routes) {
|
||||
return get_manifest_routes(routes)
|
||||
.map((route) => s(route))
|
||||
.join(',\n');
|
||||
}
|
||||
315
node_modules/@sveltejs/kit/src/core/sync/write_app_types.js
generated
vendored
Normal file
315
node_modules/@sveltejs/kit/src/core/sync/write_app_types.js
generated
vendored
Normal file
@@ -0,0 +1,315 @@
|
||||
import path from 'node:path';
|
||||
import { GENERATED_COMMENT } from '../../constants.js';
|
||||
import { resolve_entry } from '../../utils/filesystem.js';
|
||||
import { posixify } from '../../utils/os.js';
|
||||
import { write_if_changed } from './utils.js';
|
||||
import { s } from '../../utils/misc.js';
|
||||
import {
|
||||
decode_escape_sequence,
|
||||
encode_pathname_chars,
|
||||
get_route_segments,
|
||||
segment_pattern
|
||||
} from '../../utils/routing.js';
|
||||
import { is_app_route, is_endpoint_route, is_page_route } from './create_manifest_data/index.js';
|
||||
|
||||
const optional_param_pattern = /^\[\[[\w-]+(?:=[\w-]+)?\]\]$/;
|
||||
const rest_param_pattern = /^\[\.\.\.[\w-]+(?:=[\w-]+)?\]$/;
|
||||
|
||||
/**
|
||||
* Convert a route ID to the pathnames it can match (relative to the base path), in which each
|
||||
* param is replaced with `${string}` and each escape sequence is expanded. A param that fills an
|
||||
* entire segment can be absent, so it contributes a pathname with the segment and one without,
|
||||
* rather than one that absorbs the `/`
|
||||
* @param {string} id
|
||||
*/
|
||||
const get_pathname_patterns = (id) => {
|
||||
let pathnames = [''];
|
||||
|
||||
for (const segment of get_route_segments(id)) {
|
||||
const omittable = optional_param_pattern.test(segment) || rest_param_pattern.test(segment);
|
||||
const content = omittable
|
||||
? '${string}'
|
||||
: segment.replace(segment_pattern, (_, escape_type, escape_code) =>
|
||||
escape_type ? encode_pathname_chars(decode_escape_sequence(escape_code)) : '${string}'
|
||||
);
|
||||
|
||||
pathnames = pathnames.flatMap((pathname) => {
|
||||
const joined = pathname === '' ? content : `${pathname}/${content}`;
|
||||
return omittable ? [joined, pathname] : [joined];
|
||||
});
|
||||
}
|
||||
|
||||
return [...new Set(pathnames)];
|
||||
};
|
||||
|
||||
/**
|
||||
* Get pathnames to add based on trailingSlash settings
|
||||
* @param {string} pathname
|
||||
* @param {import('types').RouteData} route
|
||||
* @returns {string[]}
|
||||
*/
|
||||
function get_pathnames_for_trailing_slash(pathname, route) {
|
||||
/** @type {Set<string>} */
|
||||
const pathnames = new Set();
|
||||
|
||||
/**
|
||||
* @param {{ trailingSlash?: import('types').TrailingSlash } | null | undefined} page_options
|
||||
*/
|
||||
const add_pathnames = (page_options) => {
|
||||
if (page_options === null || page_options?.trailingSlash === 'ignore') {
|
||||
pathnames.add(pathname);
|
||||
pathnames.add(pathname + '/');
|
||||
} else if (page_options?.trailingSlash === 'always') {
|
||||
pathnames.add(pathname + '/');
|
||||
} else {
|
||||
pathnames.add(pathname);
|
||||
}
|
||||
};
|
||||
|
||||
if (route.leaf) add_pathnames(route.leaf.page_options ?? null);
|
||||
if (route.endpoint) add_pathnames(route.endpoint.page_options);
|
||||
|
||||
return Array.from(pathnames);
|
||||
}
|
||||
|
||||
// `declare module "svelte/elements"` needs to happen in a non-ambient module, and dts-buddy generates one big ambient module,
|
||||
// so we can't add it there - therefore generate the typings ourselves here.
|
||||
// We're not using the `declare namespace svelteHTML` variant because that one doesn't augment the HTMLAttributes interface
|
||||
// people could use to type their own components.
|
||||
// The T generic is needed or else there's a "all declarations must have identical type parameters" error.
|
||||
const template = `
|
||||
declare module "svelte/elements" {
|
||||
export interface HTMLAttributes<T> {
|
||||
'data-sveltekit-preload-code'?:
|
||||
| true
|
||||
| false
|
||||
| ''
|
||||
| 'eager'
|
||||
| 'viewport'
|
||||
| 'hover'
|
||||
| 'tap'
|
||||
| undefined
|
||||
| null;
|
||||
'data-sveltekit-preload-data'?: true | false | '' | 'hover' | 'tap' | undefined | null;
|
||||
'data-sveltekit-reload'?: true | false | '' | undefined | null;
|
||||
'data-sveltekit-replacestate'?: true | false | '' | undefined | null;
|
||||
'data-sveltekit-reset'?: true | false | '' | undefined | null;
|
||||
}
|
||||
}
|
||||
`;
|
||||
|
||||
/**
|
||||
* Generate app types interface extension
|
||||
* @param {import('types').ManifestData} manifest_data
|
||||
* @param {import('types').ValidatedConfig} config
|
||||
* @param {string} dir
|
||||
*/
|
||||
function generate_app_types(manifest_data, config, dir) {
|
||||
/** @type {Map<string, string>} */
|
||||
const matcher_types = new Map();
|
||||
|
||||
/** @param {string | undefined} matcher */
|
||||
const get_matcher_type = (matcher) => {
|
||||
if (!matcher) return 'string';
|
||||
|
||||
let type = matcher_types.get(matcher);
|
||||
if (!type) {
|
||||
const path_to_params = () => {
|
||||
const params_file =
|
||||
resolve_entry(config.files.params, config.moduleExtensions) ??
|
||||
config.files.params.replace(/\.(js|ts)$/, '') + '.js';
|
||||
|
||||
return posixify(path.relative(dir, params_file));
|
||||
};
|
||||
|
||||
type = `import('@sveltejs/kit/params').MatcherParam<(typeof import('${path_to_params()}').params)[${JSON.stringify(matcher)}]>`;
|
||||
matcher_types.set(matcher, type);
|
||||
}
|
||||
|
||||
return type;
|
||||
};
|
||||
|
||||
/** @param {Set<string> | null} matchers */
|
||||
const get_matchers_type = (matchers) => {
|
||||
if (matchers === null) return 'string';
|
||||
|
||||
return Array.from(matchers)
|
||||
.map((matcher) => get_matcher_type(matcher))
|
||||
.join(' | ');
|
||||
};
|
||||
|
||||
/** @type {Set<string>} */
|
||||
const route_ids = new Set(manifest_data.routes.map((route) => route.id));
|
||||
|
||||
/**
|
||||
* @param {string} id
|
||||
* @returns {string[]}
|
||||
*/
|
||||
const get_ancestor_route_ids = (id) => {
|
||||
/** @type {string[]} */
|
||||
const ancestors = [];
|
||||
|
||||
if (route_ids.has('/')) {
|
||||
ancestors.push('/');
|
||||
}
|
||||
|
||||
let current = '';
|
||||
for (const segment of id.slice(1).split('/')) {
|
||||
if (!segment) continue;
|
||||
|
||||
current += '/' + segment;
|
||||
if (route_ids.has(current)) {
|
||||
ancestors.push(current);
|
||||
}
|
||||
}
|
||||
|
||||
return ancestors;
|
||||
};
|
||||
|
||||
/** @type {Set<string>} */
|
||||
const pathnames = new Set();
|
||||
|
||||
/** @type {string[]} */
|
||||
const page_route_ids = [];
|
||||
|
||||
/** @type {string[]} */
|
||||
const endpoint_route_ids = [];
|
||||
|
||||
/** @type {string[]} */
|
||||
const app_route_ids = [];
|
||||
|
||||
/** @type {string[]} */
|
||||
const dynamic_routes = [];
|
||||
|
||||
/** @type {string[]} */
|
||||
const layouts = [];
|
||||
|
||||
/** @type {Map<string, Map<string, { optional: boolean, matchers: Set<string> | null }>>} */
|
||||
const layout_params_by_route = new Map(
|
||||
manifest_data.routes
|
||||
.filter((route) => route.layout)
|
||||
.map((route) => [
|
||||
route.id,
|
||||
new Map(
|
||||
route.params.map((p) => [
|
||||
p.name,
|
||||
{ optional: p.optional, matchers: p.matcher ? new Set([p.matcher]) : null }
|
||||
])
|
||||
)
|
||||
])
|
||||
);
|
||||
|
||||
for (const route of manifest_data.routes) {
|
||||
const ancestors = get_ancestor_route_ids(route.id);
|
||||
|
||||
for (const ancestor_id of ancestors) {
|
||||
const ancestor_params = layout_params_by_route.get(ancestor_id);
|
||||
if (!ancestor_params) continue;
|
||||
|
||||
for (const p of route.params) {
|
||||
const matcher = p.matcher ?? null;
|
||||
const entry = ancestor_params.get(p.name);
|
||||
if (!entry) {
|
||||
ancestor_params.set(p.name, {
|
||||
optional: true,
|
||||
matchers: matcher === null ? null : new Set([matcher])
|
||||
});
|
||||
continue;
|
||||
}
|
||||
|
||||
if (entry.matchers === null) continue;
|
||||
|
||||
if (matcher === null) {
|
||||
entry.matchers = null;
|
||||
continue;
|
||||
}
|
||||
|
||||
entry.matchers.add(matcher);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for (const route of manifest_data.routes) {
|
||||
const id = s(route.id);
|
||||
|
||||
if (is_page_route(route)) page_route_ids.push(id);
|
||||
if (is_endpoint_route(route)) endpoint_route_ids.push(id);
|
||||
if (is_app_route(route)) app_route_ids.push(id);
|
||||
|
||||
/** @type {(path: string) => string} */
|
||||
let serialise = s;
|
||||
|
||||
if (route.params.length > 0) {
|
||||
const params = route.params.map((p) => {
|
||||
const type = get_matcher_type(p.matcher);
|
||||
return `${/^\w+$/.test(p.name) ? p.name : `'${p.name}'`}${p.optional ? '?:' : ':'} ${type}${p.optional ? ' | undefined' : ''}`;
|
||||
});
|
||||
|
||||
if (is_app_route(route)) {
|
||||
dynamic_routes.push(`${s(route.id)}: { ${params.join('; ')} }`);
|
||||
}
|
||||
|
||||
serialise = (p) => `\`${p}\` & {}`;
|
||||
}
|
||||
|
||||
for (const pathname of get_pathname_patterns(route.id)) {
|
||||
for (const p of get_pathnames_for_trailing_slash(pathname, route)) {
|
||||
pathnames.add(serialise(p));
|
||||
}
|
||||
}
|
||||
|
||||
let layout_type = 'Record<string, never>';
|
||||
|
||||
const layout_params = layout_params_by_route.get(route.id);
|
||||
if (layout_params) {
|
||||
const params = Array.from(layout_params)
|
||||
.map(([name, { optional, matchers }]) => {
|
||||
const type = get_matchers_type(matchers);
|
||||
return `${/^\w+$/.test(name) ? name : `'${name}'`}${optional ? '?:' : ':'} ${type}${optional ? ' | undefined' : ''}`;
|
||||
})
|
||||
.join('; ');
|
||||
|
||||
if (params.length > 0) layout_type = `{ ${params} }`;
|
||||
}
|
||||
|
||||
if (route.layout) layouts.push(`${s(route.id)}: ${layout_type}`);
|
||||
}
|
||||
|
||||
const assets = manifest_data.assets.map((asset) => s(asset.file));
|
||||
|
||||
return [
|
||||
'declare module "$app/types" {',
|
||||
'\texport interface AppTypes {',
|
||||
`\t\tPageRouteId(): ${page_route_ids.join(' | ') || 'never'};`,
|
||||
`\t\tEndpointRouteId(): ${endpoint_route_ids.join(' | ') || 'never'};`,
|
||||
`\t\tRouteId(): ${app_route_ids.join(' | ') || 'never'};`,
|
||||
`\t\tRouteParams(): {\n\t\t\t${dynamic_routes.join(';\n\t\t\t')}\n\t\t};`,
|
||||
`\t\tLayoutParams(): {\n\t\t\t${layouts.join(';\n\t\t\t')}\n\t\t};`,
|
||||
`\t\tPath(): ${Array.from(pathnames).join(' | ') || 'never'};`,
|
||||
'\t\tResolvedPathname(): `${"/" | `/${string}/`}${ReturnType<AppTypes[\'Path\']>}`;',
|
||||
`\t\tAssetPath(): ${assets.join(' | ') || 'never'};`,
|
||||
'\t}',
|
||||
'}'
|
||||
].join('\n');
|
||||
}
|
||||
|
||||
/**
|
||||
* Writes `node_modules/$app/types/index.d.ts`. This file contains
|
||||
* declarations for `$app/types` and `svelte/elements`, and
|
||||
* imports `env.ts` which declares `$app/env/(public|private)`
|
||||
* @param {import('types').ValidatedConfig} config
|
||||
* @param {import('types').ManifestData} manifest_data
|
||||
* @param {string} root
|
||||
*/
|
||||
export function write_app_types(config, manifest_data, root) {
|
||||
const dir = path.join(root, 'node_modules/$app/types');
|
||||
|
||||
const content = [
|
||||
GENERATED_COMMENT,
|
||||
`import '@sveltejs/kit';\nimport './env.js';`, // .js file ending needed for nodenext module resolution
|
||||
generate_app_types(manifest_data, config, dir),
|
||||
template.trim()
|
||||
].join('\n\n');
|
||||
|
||||
write_if_changed(path.join(dir, 'index.d.ts'), content);
|
||||
}
|
||||
194
node_modules/@sveltejs/kit/src/core/sync/write_client_manifest.js
generated
vendored
Normal file
194
node_modules/@sveltejs/kit/src/core/sync/write_client_manifest.js
generated
vendored
Normal file
@@ -0,0 +1,194 @@
|
||||
import path from 'node:path';
|
||||
import { check_spelling, dedent, write_if_changed } from './utils.js';
|
||||
import { relative_path, resolve_entry } from '../../utils/filesystem.js';
|
||||
import { s } from '../../utils/misc.js';
|
||||
|
||||
/**
|
||||
* Writes the client manifest to disk. The manifest is used to power the router. It contains the
|
||||
* list of routes and corresponding Svelte components (i.e. pages and layouts).
|
||||
* @param {import('types').ValidatedConfig} kit
|
||||
* @param {import('types').ManifestData} manifest_data
|
||||
* @param {string} output
|
||||
* @param {string} root The project root directory
|
||||
* @param {import('types').ServerMetadata['nodes']} [metadata] If this is omitted, we have to assume that all routes with a `+layout/page.server.js` file have a server load function
|
||||
*/
|
||||
export function write_client_manifest(kit, manifest_data, output, root, metadata) {
|
||||
const client_routing = kit.router.resolution === 'client';
|
||||
|
||||
/**
|
||||
* Creates a module that exports a `CSRPageNode`
|
||||
* @param {import('types').PageNode} node
|
||||
*/
|
||||
function generate_node(node) {
|
||||
const declarations = [];
|
||||
|
||||
if (node.universal) {
|
||||
declarations.push(
|
||||
`import * as universal from ${s(relative_path(`${output}/nodes`, path.resolve(root, node.universal)))};`,
|
||||
'export { universal };'
|
||||
);
|
||||
}
|
||||
|
||||
if (node.component) {
|
||||
declarations.push(
|
||||
`export { default as component } from ${s(
|
||||
relative_path(`${output}/nodes`, path.resolve(root, node.component))
|
||||
)};`
|
||||
);
|
||||
}
|
||||
|
||||
return declarations.join('\n');
|
||||
}
|
||||
|
||||
/** @type {Map<import('types').PageNode, number>} */
|
||||
const indices = new Map();
|
||||
const nodes = manifest_data.nodes
|
||||
.map((node, i) => {
|
||||
indices.set(node, i);
|
||||
|
||||
write_if_changed(`${output}/nodes/${i}.js`, generate_node(node));
|
||||
return `() => import('./nodes/${i}')`;
|
||||
})
|
||||
// If route resolution happens on the server, we only need the root layout and root error page
|
||||
// upfront, the rest is loaded on demand as the user navigates the app
|
||||
.slice(0, client_routing ? manifest_data.nodes.length : 2)
|
||||
.join(',\n');
|
||||
|
||||
const layouts_with_server_load = new Set();
|
||||
|
||||
let dictionary = dedent`
|
||||
{
|
||||
${manifest_data.routes
|
||||
.map((route) => {
|
||||
if (route.page) {
|
||||
const errors = route.page.errors.slice(1).map((n) => n ?? '');
|
||||
const layouts = route.page.layouts.slice(1).map((n) => n ?? '');
|
||||
|
||||
while (layouts.at(-1) === '') layouts.pop();
|
||||
while (errors.at(-1) === '') errors.pop();
|
||||
|
||||
let leaf_has_server_load = false;
|
||||
if (route.leaf) {
|
||||
if (metadata) {
|
||||
const i = /** @type {number} */ (indices.get(route.leaf));
|
||||
|
||||
leaf_has_server_load = metadata[i].has_server_load;
|
||||
} else if (route.leaf.server) {
|
||||
leaf_has_server_load = true;
|
||||
}
|
||||
}
|
||||
|
||||
// Encode whether or not the route uses server data
|
||||
// using the ones' complement, to save space
|
||||
const array = [`${leaf_has_server_load ? '~' : ''}${route.page.leaf}`];
|
||||
|
||||
// Encode whether or not the layout uses server data.
|
||||
// It's a different method compared to pages because layouts
|
||||
// are reused across pages, so we save space by doing it this way.
|
||||
route.page.layouts.forEach((layout) => {
|
||||
if (layout == undefined) return;
|
||||
|
||||
let layout_has_server_load = false;
|
||||
|
||||
if (metadata) {
|
||||
layout_has_server_load = metadata[layout].has_server_load;
|
||||
} else if (manifest_data.nodes[layout].server) {
|
||||
layout_has_server_load = true;
|
||||
}
|
||||
|
||||
if (layout_has_server_load) {
|
||||
layouts_with_server_load.add(layout);
|
||||
}
|
||||
});
|
||||
|
||||
// only include non-root layout/error nodes if they exist
|
||||
if (layouts.length > 0 || errors.length > 0) array.push(`[${layouts.join(',')}]`);
|
||||
if (errors.length > 0) array.push(`[${errors.join(',')}]`);
|
||||
|
||||
return `${s(route.id)}: [${array.join(',')}]`;
|
||||
}
|
||||
})
|
||||
.filter(Boolean)
|
||||
.join(',\n')}
|
||||
}
|
||||
`;
|
||||
|
||||
if (!client_routing) {
|
||||
dictionary = '{}';
|
||||
const root_layout = layouts_with_server_load.has(0);
|
||||
layouts_with_server_load.clear();
|
||||
if (root_layout) layouts_with_server_load.add(0);
|
||||
}
|
||||
|
||||
const client_hooks_file = resolve_entry(kit.files.hooks.client, kit.moduleExtensions);
|
||||
const universal_hooks_file = resolve_entry(kit.files.hooks.universal, kit.moduleExtensions);
|
||||
|
||||
if (!client_hooks_file) {
|
||||
check_spelling(
|
||||
'src/hooks.client',
|
||||
'src/+hooks.client',
|
||||
'Unexpected + prefix',
|
||||
kit.moduleExtensions
|
||||
);
|
||||
check_spelling('src/hooks.client', 'src/hook.client', 'Missing s suffix', kit.moduleExtensions);
|
||||
}
|
||||
|
||||
// Stringified version of
|
||||
/** @type {import('../../runtime/client/types.js').SvelteKitApp} */
|
||||
write_if_changed(
|
||||
`${output}/app.js`,
|
||||
dedent`
|
||||
${
|
||||
client_hooks_file
|
||||
? `import * as client_hooks from '${relative_path(output, client_hooks_file)}';`
|
||||
: ''
|
||||
}
|
||||
${
|
||||
universal_hooks_file
|
||||
? `import * as universal_hooks from '${relative_path(output, universal_hooks_file)}';`
|
||||
: ''
|
||||
}
|
||||
|
||||
${client_routing ? "export { matchers } from './matchers.js';" : 'export const matchers = {};'}
|
||||
|
||||
export const nodes = [
|
||||
${nodes}
|
||||
];
|
||||
|
||||
export const server_loads = [${[...layouts_with_server_load].join(',')}];
|
||||
|
||||
export const dictionary = ${dictionary};
|
||||
|
||||
export const hooks = {
|
||||
handleError: ${
|
||||
client_hooks_file ? 'client_hooks.handleError || ' : ''
|
||||
}(({ kind, error }) => { if (kind === 'unknown') { console.error(error); } }),
|
||||
${client_hooks_file ? 'init: client_hooks.init,' : ''}
|
||||
reroute: ${universal_hooks_file ? 'universal_hooks.reroute || ' : ''}(() => {}),
|
||||
transport: ${universal_hooks_file ? 'universal_hooks.transport || ' : ''}{}
|
||||
};
|
||||
|
||||
export const decoders = Object.fromEntries(Object.entries(hooks.transport).map(([k, v]) => [k, v.decode]));
|
||||
export const encoders = Object.fromEntries(Object.entries(hooks.transport).map(([k, v]) => [k, v.encode]));
|
||||
|
||||
export const hash = ${s(kit.router.type === 'hash')};
|
||||
|
||||
export const decode = (type, value) => decoders[type](value);
|
||||
|
||||
export const get_error_template = () => import('../shared/error-template.js').then(m => m.default);
|
||||
`
|
||||
);
|
||||
|
||||
if (client_routing) {
|
||||
const uses_matchers = manifest_data.routes.some((route) =>
|
||||
route.params.some((param) => param.matcher)
|
||||
);
|
||||
|
||||
const module =
|
||||
!manifest_data.params || !uses_matchers
|
||||
? 'export const matchers = {};'
|
||||
: `import { params as matchers } from ${s(relative_path(output, path.resolve(root, manifest_data.params)))};\n\nexport { matchers };`;
|
||||
|
||||
write_if_changed(`${output}/matchers.js`, module);
|
||||
}
|
||||
}
|
||||
39
node_modules/@sveltejs/kit/src/core/sync/write_env.js
generated
vendored
Normal file
39
node_modules/@sveltejs/kit/src/core/sync/write_env.js
generated
vendored
Normal file
@@ -0,0 +1,39 @@
|
||||
/** @import { EnvVarConfig } from '@sveltejs/kit/env' */
|
||||
import path from 'node:path';
|
||||
import { create_explicit_env_types } from '../env.js';
|
||||
import { write_if_changed } from './utils.js';
|
||||
import { posixify } from '../../utils/os.js';
|
||||
|
||||
const DOCS = '// See https://svelte.dev/docs/kit/environment-variables for more information';
|
||||
|
||||
/**
|
||||
* Writes ambient declarations including types reference to @sveltejs/kit,
|
||||
* and the existing environment variables in process.env to
|
||||
* $env/static/private and $env/static/public
|
||||
* @param {string | null} entry
|
||||
* @param {Record<string, EnvVarConfig<any>> | null} env_config
|
||||
* @param {string} root
|
||||
*/
|
||||
export function write_env(entry, env_config, root) {
|
||||
const content = [];
|
||||
|
||||
const dir = path.join(root, 'node_modules/$app/types');
|
||||
const out = path.join(dir, 'env.d.ts');
|
||||
|
||||
if (entry && env_config) {
|
||||
const relative = posixify(path.relative(dir, entry));
|
||||
content.push(
|
||||
`// This file is generated from ${relative}.\n${DOCS}`,
|
||||
create_explicit_env_types(env_config, relative, 'private'),
|
||||
create_explicit_env_types(env_config, relative, 'public')
|
||||
);
|
||||
} else {
|
||||
content.push(
|
||||
DOCS,
|
||||
create_explicit_env_types({}, '', 'private'),
|
||||
create_explicit_env_types({}, '', 'public')
|
||||
);
|
||||
}
|
||||
|
||||
write_if_changed(out, content.join('\n\n'));
|
||||
}
|
||||
115
node_modules/@sveltejs/kit/src/core/sync/write_server.js
generated
vendored
Normal file
115
node_modules/@sveltejs/kit/src/core/sync/write_server.js
generated
vendored
Normal file
@@ -0,0 +1,115 @@
|
||||
import path from 'node:path';
|
||||
import { resolve_entry } from '../../utils/filesystem.js';
|
||||
import { posixify } from '../../utils/os.js';
|
||||
import { s } from '../../utils/misc.js';
|
||||
import { load_error_page, load_template } from '../config/index.js';
|
||||
import { check_spelling, write_if_changed } from './utils.js';
|
||||
import { escape_html } from '../../utils/escape.js';
|
||||
|
||||
/**
|
||||
* @param {{
|
||||
* server_hooks: string | null;
|
||||
* universal_hooks: string | null;
|
||||
* config: import('types').ValidatedConfig;
|
||||
* template: string;
|
||||
* }} opts
|
||||
*/
|
||||
const server_template = ({ config, server_hooks, universal_hooks, template }) => `
|
||||
import error from './shared/error-template.js';
|
||||
|
||||
export const options = {
|
||||
app_template_contains_nonce: ${template.includes('%sveltekit.nonce%')},
|
||||
csp: ${s(config.csp)},
|
||||
csrf_trusted_origins: ${s(config.csrf.trustedOrigins)},
|
||||
service_worker_options: ${config.serviceWorker.register ? s(config.serviceWorker.options) : 'null'},
|
||||
templates: {
|
||||
app: ({ head, body, assets, nonce, env }) => ${s(template)
|
||||
.replace('%sveltekit.head%', '" + head + "')
|
||||
.replace('%sveltekit.body%', '" + body + "')
|
||||
.replace(/%sveltekit\.assets%/g, '" + assets + "')
|
||||
.replace(/%sveltekit\.nonce%/g, '" + nonce + "')
|
||||
.replace(/%sveltekit\.version%/g, escape_html(config.version.name))
|
||||
.replace(
|
||||
/%sveltekit\.env\.([^%]+)%/g,
|
||||
(_match, capture) => `" + (env[${s(capture)}] ?? "") + "`
|
||||
)},
|
||||
error
|
||||
}
|
||||
};
|
||||
|
||||
export async function get_hooks() {
|
||||
let handle;
|
||||
let handleFetch;
|
||||
let handleError;
|
||||
let init;
|
||||
${server_hooks ? `({ handle, handleFetch, handleError, init } = await import(${s(server_hooks)}));` : ''}
|
||||
|
||||
let reroute;
|
||||
let transport;
|
||||
${universal_hooks ? `({ reroute, transport } = await import(${s(universal_hooks)}));` : ''}
|
||||
|
||||
return {
|
||||
handle,
|
||||
handleFetch,
|
||||
handleError,
|
||||
init,
|
||||
reroute,
|
||||
transport
|
||||
};
|
||||
}
|
||||
`;
|
||||
|
||||
/**
|
||||
* Write server configuration to disk
|
||||
* @param {import('types').ValidatedConfig} config
|
||||
* @param {string} output
|
||||
* @param {string} root The project root directory
|
||||
*/
|
||||
export function write_server(config, output, root) {
|
||||
const server_hooks_file = resolve_entry(config.files.hooks.server, config.moduleExtensions);
|
||||
const universal_hooks_file = resolve_entry(config.files.hooks.universal, config.moduleExtensions);
|
||||
|
||||
if (!server_hooks_file) {
|
||||
check_spelling(
|
||||
'src/hooks.server',
|
||||
'src/+hooks.server',
|
||||
'Unexpected + prefix',
|
||||
config.moduleExtensions
|
||||
);
|
||||
check_spelling(
|
||||
'src/hooks.server',
|
||||
'src/hook.server',
|
||||
'Missing s suffix',
|
||||
config.moduleExtensions
|
||||
);
|
||||
}
|
||||
|
||||
if (!universal_hooks_file) {
|
||||
check_spelling('src/hooks', 'src/+hooks', 'Unexpected + prefix', config.moduleExtensions);
|
||||
check_spelling('src/hooks', 'src/hook', 'Missing s suffix', config.moduleExtensions);
|
||||
}
|
||||
|
||||
/** @param {string} file */
|
||||
function relative(file) {
|
||||
return posixify(path.relative(output, file));
|
||||
}
|
||||
|
||||
write_if_changed(
|
||||
`${output}/shared/error-template.js`,
|
||||
`export default ({ status, message }) => ${s(load_error_page(config))
|
||||
.replace(/%sveltekit\.status%/g, '" + status + "')
|
||||
.replace(/%sveltekit\.error\.message%/g, '" + message + "')};`
|
||||
);
|
||||
|
||||
// Contains the stringified version of
|
||||
/** @type {import('types').SSROptions} */
|
||||
write_if_changed(
|
||||
`${output}/server.js`,
|
||||
server_template({
|
||||
config,
|
||||
server_hooks: server_hooks_file ? relative(server_hooks_file) : null,
|
||||
universal_hooks: universal_hooks_file ? relative(universal_hooks_file) : null,
|
||||
template: load_template(root, config)
|
||||
})
|
||||
);
|
||||
}
|
||||
268
node_modules/@sveltejs/kit/src/core/sync/write_tsconfig/index.js
generated
vendored
Normal file
268
node_modules/@sveltejs/kit/src/core/sync/write_tsconfig/index.js
generated
vendored
Normal file
@@ -0,0 +1,268 @@
|
||||
/** @import { ValidatedConfig } from 'types' */
|
||||
import process from 'node:process';
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { write_if_changed } from '../utils.js';
|
||||
import {
|
||||
ESSENTIAL_OPTIONS,
|
||||
normalize_config,
|
||||
RECOMMENDED_OPTIONS,
|
||||
remove_trailing_slashstar
|
||||
} from './utils.js';
|
||||
import { extends_id, validate_resolved_config } from './validate.js';
|
||||
import * as e from '../../../messages/build-errors.js';
|
||||
import * as w from '../../../messages/build-warnings.js';
|
||||
import { posixify } from '../../../utils/os.js';
|
||||
import { bullet_list } from '../../../utils/format.js';
|
||||
|
||||
/** @type {typeof import('typescript')} */
|
||||
let ts;
|
||||
try {
|
||||
ts = await import('typescript');
|
||||
} catch {
|
||||
// The user has not installed TypeScript.
|
||||
}
|
||||
|
||||
/**
|
||||
* Generates the tsconfig that the user's tsconfig inherits from.
|
||||
* @param {ValidatedConfig} kit
|
||||
* @param {string} root
|
||||
*/
|
||||
export function write_tsconfig(kit, root) {
|
||||
const paths = get_paths(kit, root);
|
||||
const types = ['$app/types'];
|
||||
|
||||
write_parent_tsconfig(
|
||||
root,
|
||||
'$app/tsconfig',
|
||||
{
|
||||
compilerOptions: {
|
||||
paths,
|
||||
rootDirs: [root, `${kit.outDir}/types`],
|
||||
types,
|
||||
|
||||
// This is required for svelte-package to work as expected
|
||||
// Can be overwritten
|
||||
lib: ['ESNext', 'DOM', 'DOM.Iterable'],
|
||||
|
||||
...ESSENTIAL_OPTIONS,
|
||||
...RECOMMENDED_OPTIONS
|
||||
}
|
||||
},
|
||||
kit.typescript.config
|
||||
);
|
||||
|
||||
validate_config(root, {
|
||||
paths,
|
||||
types,
|
||||
exclusions: [kit.files.serviceWorker],
|
||||
example: {
|
||||
extends: '$app/tsconfig',
|
||||
include: ['src', 'test', '*'],
|
||||
exclude: ['src/service-worker']
|
||||
}
|
||||
});
|
||||
|
||||
write_parent_tsconfig(root, '$app/tsconfig/service-worker', {
|
||||
compilerOptions: {
|
||||
paths,
|
||||
types,
|
||||
lib: ['ESNext', 'WebWorker'],
|
||||
...ESSENTIAL_OPTIONS,
|
||||
...RECOMMENDED_OPTIONS
|
||||
}
|
||||
});
|
||||
|
||||
validate_config(kit.files.serviceWorker, {
|
||||
paths,
|
||||
types,
|
||||
example: {
|
||||
extends: '$app/tsconfig/service-worker'
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Write a generated `tsconfig.json` inside `node_modules`, for the
|
||||
* user config to extend
|
||||
* @param {string} root The project root
|
||||
* @param {string} id The id of the generated config
|
||||
* @param {any} config The contents of the generated tsconfig, with paths relative to `root`
|
||||
* @param {ValidatedConfig['typescript']['config']} [transform] TODO get rid of this
|
||||
*/
|
||||
function write_parent_tsconfig(root, id, config, transform) {
|
||||
// simplified tsconfig resolvers (e.g. Playwright's) only find `${id}.json`, not `${id}/tsconfig.json`
|
||||
const out_file = path.join(root, `node_modules/${id}.json`);
|
||||
|
||||
let normalized = normalize_config(out_file, config);
|
||||
normalized = transform?.(normalized) ?? normalized;
|
||||
|
||||
write_if_changed(out_file, JSON.stringify(normalized, null, '\t'));
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {string} dir The directory to resolve a user config from
|
||||
* @param {Object} options
|
||||
* @param {Record<string, string[]>} options.paths The expected paths
|
||||
* @param {string[]} options.types The expected types
|
||||
* @param {string[]} [options.exclusions] Files that should be excluded
|
||||
* @param {any} options.example What to print if the user config does _not_ extend the generated config
|
||||
*/
|
||||
function validate_config(dir, options) {
|
||||
if (!ts) {
|
||||
// The user has not installed TypeScript. Skip validation of config.
|
||||
return;
|
||||
}
|
||||
|
||||
const user_config = load_user_tsconfig(dir);
|
||||
if (!user_config || !modified_since_last_check(user_config.file)) return;
|
||||
|
||||
// now that we've written the parent config, we can resolve the
|
||||
// user config and validate that nothing important was overwritten
|
||||
if (!extends_id(user_config.options, options.example.extends)) {
|
||||
w.tsconfig_extends_missing({
|
||||
file: path.relative(process.cwd(), user_config.file),
|
||||
example: JSON.stringify(options.example, null, ' ')
|
||||
});
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
const resolved = ts.parseJsonConfigFileContent(user_config.options, ts.sys, dir);
|
||||
|
||||
const warnings = validate_resolved_config(
|
||||
dir,
|
||||
resolved,
|
||||
options.paths,
|
||||
options.types,
|
||||
options.exclusions
|
||||
);
|
||||
|
||||
if (warnings.length > 0) {
|
||||
w.tsconfig_invalid({
|
||||
file: path.relative(process.cwd(), user_config.file),
|
||||
issues: bullet_list(warnings)
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/** @type {Map<string, number>} */
|
||||
const mtimes = new Map();
|
||||
|
||||
/**
|
||||
* Returns true if the file was modified since we last got here,
|
||||
* otherwise we can skip warnings
|
||||
* @param {string} file
|
||||
*/
|
||||
function modified_since_last_check(file) {
|
||||
const a = mtimes.get(file) ?? -1;
|
||||
const b = fs.statSync(file).mtimeMs;
|
||||
mtimes.set(file, b);
|
||||
|
||||
return b > a;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {string} cwd
|
||||
* @param {string} file
|
||||
*/
|
||||
function maybe_file(cwd, file) {
|
||||
const resolved = path.resolve(cwd, file);
|
||||
if (fs.existsSync(resolved)) {
|
||||
return resolved;
|
||||
}
|
||||
}
|
||||
|
||||
/** @param {string} cwd */
|
||||
function load_user_tsconfig(cwd) {
|
||||
const file = maybe_file(cwd, 'tsconfig.json') || maybe_file(cwd, 'jsconfig.json');
|
||||
if (!file) return;
|
||||
|
||||
const options = load_tsconfig(file);
|
||||
|
||||
return {
|
||||
file,
|
||||
kind: path.basename(file),
|
||||
options
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {string} file
|
||||
*/
|
||||
function load_tsconfig(file) {
|
||||
const options = ts.readConfigFile(posixify(file), ts.sys.readFile);
|
||||
|
||||
if (options.error) {
|
||||
/** @type {string | undefined} */
|
||||
let location;
|
||||
|
||||
if (options.error.file && options.error.start !== undefined) {
|
||||
const line_start = options.error.file.text.lastIndexOf('\n', options.error.start);
|
||||
|
||||
const line =
|
||||
line_start === -1
|
||||
? 0
|
||||
: options.error.file.text.slice(0, options.error.start).split('\n').length;
|
||||
const column = options.error.start - line_start;
|
||||
|
||||
location = `${path.relative(process.cwd(), file)}:${line}:${column}`;
|
||||
}
|
||||
|
||||
e.tsconfig_parse_failed(
|
||||
typeof options.error.messageText === 'string'
|
||||
? { details: options.error.messageText }
|
||||
: undefined,
|
||||
{ stackless: true, location }
|
||||
);
|
||||
}
|
||||
|
||||
return options.config;
|
||||
}
|
||||
|
||||
/** Matches anything (except the empty string/string with newline), and separates any trailing `/*` */
|
||||
const alias_key = /^(.+?)(\/\*)?$/;
|
||||
|
||||
/** Matches anything (except the empty string/string with newline), and separates any trailing `/*` or file extension */
|
||||
const alias_value = /^(.+?)((\/\*)|(\.\w+))?$/;
|
||||
|
||||
/**
|
||||
* Generates tsconfig path aliases from kit's aliases and the package.json `imports` field.
|
||||
* Related to vite alias creation.
|
||||
*
|
||||
* @param {import('types').ValidatedConfig} config
|
||||
* @param {string} root
|
||||
* @returns {Record<string, string[]>}
|
||||
*/
|
||||
function get_paths(config, root) {
|
||||
const alias = {
|
||||
...config.alias
|
||||
};
|
||||
|
||||
/** @type {Record<string, string[]>} */
|
||||
const paths = {};
|
||||
|
||||
for (const [key, value] of Object.entries(alias)) {
|
||||
const key_match = alias_key.exec(key);
|
||||
if (!key_match) e.config_alias_key_invalid({ key });
|
||||
|
||||
const value_match = alias_value.exec(value);
|
||||
if (!value_match) e.config_alias_value_invalid({ value });
|
||||
|
||||
const resolved = path.resolve(root, remove_trailing_slashstar(value));
|
||||
const slashstar = key_match[2];
|
||||
|
||||
if (slashstar) {
|
||||
paths[key] = [resolved + '/*'];
|
||||
} else {
|
||||
paths[key] = [resolved];
|
||||
const fileending = value_match[4];
|
||||
|
||||
if (!fileending && !(key + '/*' in alias)) {
|
||||
paths[key + '/*'] = [resolved + '/*'];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return paths;
|
||||
}
|
||||
7
node_modules/@sveltejs/kit/src/core/sync/write_tsconfig/test-app/package.json
generated
vendored
Normal file
7
node_modules/@sveltejs/kit/src/core/sync/write_tsconfig/test-app/package.json
generated
vendored
Normal file
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"private": true,
|
||||
"imports": {
|
||||
"#lib": "./src/lib",
|
||||
"#lib/*": "./src/lib/*"
|
||||
}
|
||||
}
|
||||
77
node_modules/@sveltejs/kit/src/core/sync/write_tsconfig/utils.js
generated
vendored
Normal file
77
node_modules/@sveltejs/kit/src/core/sync/write_tsconfig/utils.js
generated
vendored
Normal file
@@ -0,0 +1,77 @@
|
||||
import path from 'node:path';
|
||||
import { posixify } from '../../../utils/os.js';
|
||||
|
||||
/**
|
||||
* Without these, compilation will fail
|
||||
* @type {Record<string, any>}
|
||||
*/
|
||||
export const ESSENTIAL_OPTIONS = {
|
||||
// svelte-preprocess cannot figure out whether you have a value or a type, so tell TypeScript
|
||||
// to enforce using \`import type\` instead of \`import\` for Types.
|
||||
// Also, TypeScript doesn't know about import usages in the template because it only sees the
|
||||
// script of a Svelte file. Therefore preserve all value imports.
|
||||
verbatimModuleSyntax: true,
|
||||
// Vite compiles modules one at a time
|
||||
isolatedModules: true
|
||||
};
|
||||
|
||||
/**
|
||||
* Options that are strongly recommended, either because not having them is silly or
|
||||
* because the align TypeScript's behaviour with Vite's, but which can be overwritten
|
||||
* @type {Record<string, any>}
|
||||
*/
|
||||
export const RECOMMENDED_OPTIONS = {
|
||||
allowJs: true,
|
||||
checkJs: true,
|
||||
forceConsistentCasingInFileNames: true,
|
||||
resolveJsonModule: true,
|
||||
moduleDetection: 'force',
|
||||
moduleResolution: 'bundler',
|
||||
allowImportingTsExtensions: true,
|
||||
module: 'esnext',
|
||||
target: 'esnext',
|
||||
skipLibCheck: true,
|
||||
esModuleInterop: true,
|
||||
noEmit: true // prevent tsconfig error "overwriting input files" - Vite handles the build and ignores this
|
||||
};
|
||||
|
||||
/**
|
||||
* Makes paths relative to the output file
|
||||
* @param {string} out
|
||||
* @param {any} config
|
||||
* @param {(input: any) => any} [transform] TODO get rid of this option
|
||||
*/
|
||||
export function normalize_config(out, config, transform) {
|
||||
const dir = path.dirname(out);
|
||||
const relative = (/** @type {string} */ file) => posixify(path.relative(dir, file));
|
||||
|
||||
const paths =
|
||||
config.compilerOptions?.paths &&
|
||||
Object.fromEntries(
|
||||
Object.entries(config.compilerOptions?.paths).map(([k, v]) => [k, v.map(relative)])
|
||||
);
|
||||
|
||||
const normalized = {
|
||||
...config,
|
||||
compilerOptions: {
|
||||
...config.compilerOptions,
|
||||
paths,
|
||||
rootDirs: config.compilerOptions?.rootDirs?.map(relative)
|
||||
},
|
||||
include: config.include?.map(relative),
|
||||
exclude: config.exclude?.map(relative)
|
||||
};
|
||||
|
||||
return transform?.(normalized) ?? normalized;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {string} file
|
||||
*/
|
||||
export function remove_trailing_slashstar(file) {
|
||||
if (file.endsWith('/*')) {
|
||||
return file.slice(0, -2);
|
||||
} else {
|
||||
return file;
|
||||
}
|
||||
}
|
||||
128
node_modules/@sveltejs/kit/src/core/sync/write_tsconfig/validate.js
generated
vendored
Normal file
128
node_modules/@sveltejs/kit/src/core/sync/write_tsconfig/validate.js
generated
vendored
Normal file
@@ -0,0 +1,128 @@
|
||||
/** @import ts from 'typescript' */
|
||||
import path from 'node:path';
|
||||
import { ESSENTIAL_OPTIONS, remove_trailing_slashstar } from './utils.js';
|
||||
import { posixify } from '../../../utils/os.js';
|
||||
|
||||
const formatter = new Intl.ListFormat('en-gb', { type: 'conjunction' });
|
||||
|
||||
/**
|
||||
* @param {string[]} things
|
||||
*/
|
||||
function join(things) {
|
||||
return formatter.format(things.map((thing) => JSON.stringify(thing)));
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {string} dir
|
||||
* @param {ts.ParsedCommandLine} resolved
|
||||
* @param {Record<string, string[]>} paths
|
||||
* @param {string[]} types
|
||||
* @param {string[]} [exclusions]
|
||||
*/
|
||||
export function validate_resolved_config(dir, resolved, paths, types, exclusions) {
|
||||
/** @type {string[]} */
|
||||
const warnings = [];
|
||||
|
||||
if (resolved.options.types) {
|
||||
validate_types(warnings, types, resolved.options.types);
|
||||
}
|
||||
|
||||
if (resolved.options.paths) {
|
||||
validate_paths(
|
||||
warnings,
|
||||
/** @type {string} */ (resolved.options.pathsBasePath),
|
||||
paths,
|
||||
resolved.options.paths
|
||||
);
|
||||
}
|
||||
|
||||
if (exclusions) {
|
||||
validate_exclusions(warnings, dir, exclusions, resolved.fileNames);
|
||||
}
|
||||
|
||||
for (const key in ESSENTIAL_OPTIONS) {
|
||||
if (resolved.options[key] !== ESSENTIAL_OPTIONS[key]) {
|
||||
warnings.push(
|
||||
`"${key}" was overwritten. It should be ${JSON.stringify(ESSENTIAL_OPTIONS[key])}`
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
return warnings;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {string[]} warnings
|
||||
* @param {string[]} expected
|
||||
* @param {string[]} actual
|
||||
*/
|
||||
export function validate_types(warnings, expected, actual) {
|
||||
const missing_types = expected.filter((/** @type {string} */ type) => !actual.includes(type));
|
||||
|
||||
if (missing_types.length > 0) {
|
||||
warnings.push(`"types" was overwritten. It must include ${join(missing_types)}`);
|
||||
}
|
||||
|
||||
return warnings;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {string[]} warnings
|
||||
* @param {string} base
|
||||
* @param {Record<string, string[]>} expected
|
||||
* @param {ts.MapLike<string[]>} actual
|
||||
*/
|
||||
export function validate_paths(warnings, base, expected, actual) {
|
||||
/** @type {Set<string>} */
|
||||
const mismatch = new Set();
|
||||
|
||||
for (const [k, e] of Object.entries(expected)) {
|
||||
const a = actual[k]?.map((/** @type {string} */ x) =>
|
||||
path.resolve(/** @type {string} */ (base), x)
|
||||
);
|
||||
|
||||
if (JSON.stringify(e) !== JSON.stringify(a)) {
|
||||
mismatch.add(remove_trailing_slashstar(k));
|
||||
}
|
||||
}
|
||||
|
||||
if (mismatch.size > 0) {
|
||||
const joined = join([...mismatch]);
|
||||
|
||||
warnings.push(`"paths" was overwritten. Imports from ${joined} may not typecheck`);
|
||||
}
|
||||
|
||||
return warnings;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {string[]} warnings
|
||||
* @param {string} dir
|
||||
* @param {string[]} exclusions
|
||||
* @param {string[]} files
|
||||
*/
|
||||
export function validate_exclusions(warnings, dir, exclusions, files) {
|
||||
const missing_exclusions = exclusions.map(posixify).filter((exclusion) => {
|
||||
return files.some(
|
||||
(f) => f === exclusion || f.startsWith(exclusion + '/') || f.startsWith(exclusion + '.')
|
||||
);
|
||||
});
|
||||
|
||||
if (missing_exclusions.length > 0) {
|
||||
warnings.push(
|
||||
`${join(missing_exclusions.map((file) => posixify(path.relative(dir, file))))} should be added to the "exclude" array`
|
||||
);
|
||||
}
|
||||
|
||||
return warnings;
|
||||
}
|
||||
|
||||
/**
|
||||
* Validates that a tsconfig contains `"extends": "<id>"`
|
||||
* @param {any} options
|
||||
* @param {string} id
|
||||
*/
|
||||
export function extends_id(options, id) {
|
||||
const o = options.extends;
|
||||
return Array.isArray(o) ? o.includes(id) : o === id;
|
||||
}
|
||||
885
node_modules/@sveltejs/kit/src/core/sync/write_types/index.js
generated
vendored
Normal file
885
node_modules/@sveltejs/kit/src/core/sync/write_types/index.js
generated
vendored
Normal file
@@ -0,0 +1,885 @@
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import MagicString from 'magic-string';
|
||||
import { walk, resolve_entry } from '../../../utils/filesystem.js';
|
||||
import { compact } from '../../../utils/array.js';
|
||||
import { posixify } from '../../../utils/os.js';
|
||||
import { ts } from '../ts.js';
|
||||
import { is_page_route } from '../create_manifest_data/index.js';
|
||||
const remove_relative_parent_traversals = (/** @type {string} */ path) =>
|
||||
path.replace(/\.\.\//g, '');
|
||||
const is_whitespace = (/** @type {string} */ char) => /\s/.test(char);
|
||||
|
||||
/**
|
||||
* @typedef {{
|
||||
* file_name: string;
|
||||
* modified: boolean;
|
||||
* code: string;
|
||||
* exports: any[];
|
||||
* } | null} Proxy
|
||||
*
|
||||
* @typedef {{
|
||||
* server: Proxy,
|
||||
* universal: Proxy
|
||||
* }} Proxies
|
||||
*
|
||||
* @typedef {Map<import('types').PageNode, {route: import('types').RouteData, proxies: Proxies}>} RoutesMap
|
||||
*/
|
||||
|
||||
/**
|
||||
* Creates types for the whole manifest
|
||||
* @param {import('types').ValidatedConfig} config
|
||||
* @param {import('types').ManifestData} manifest_data
|
||||
* @param {string} root The project root directory
|
||||
*/
|
||||
export function write_all_types(config, manifest_data, root) {
|
||||
if (!ts) return;
|
||||
|
||||
const types_dir = `${config.outDir}/types`;
|
||||
|
||||
// empty out files that no longer need to exist
|
||||
const routes_dir = remove_relative_parent_traversals(
|
||||
posixify(path.relative(root, config.files.routes))
|
||||
);
|
||||
const expected_directories = new Set(
|
||||
manifest_data.routes.map((route) => path.posix.join(routes_dir, route.id))
|
||||
);
|
||||
|
||||
if (fs.existsSync(types_dir)) {
|
||||
for (const file of walk(types_dir)) {
|
||||
const dir = path.posix.dirname(file);
|
||||
if (!expected_directories.has(dir)) {
|
||||
fs.rmSync(path.join(types_dir, file), { force: true, recursive: true });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Read/write meta data on each invocation, not once per node process,
|
||||
// it could be invoked by another process in the meantime.
|
||||
const meta_data_file = `${types_dir}/route_meta_data.json`;
|
||||
const has_meta_data = fs.existsSync(meta_data_file);
|
||||
const meta_data = has_meta_data
|
||||
? /** @type {Record<string, string[]>} */ (JSON.parse(fs.readFileSync(meta_data_file, 'utf-8')))
|
||||
: {};
|
||||
const routes_map = create_routes_map(manifest_data);
|
||||
// For each directory, write $types.d.ts
|
||||
for (const route of manifest_data.routes) {
|
||||
if (!route.leaf && !route.layout && !route.endpoint) continue; // nothing to do
|
||||
|
||||
const outdir = path.join(config.outDir, 'types', routes_dir, route.id);
|
||||
|
||||
// check if the types are out of date
|
||||
/** @type {string[]} */
|
||||
const input_files = [];
|
||||
|
||||
/** @type {import('types').PageNode | null} */
|
||||
let node = route.leaf;
|
||||
while (node) {
|
||||
if (node.universal) input_files.push(node.universal);
|
||||
if (node.server) input_files.push(node.server);
|
||||
node = node.parent ?? null;
|
||||
}
|
||||
|
||||
/** @type {import('types').PageNode | null} */
|
||||
node = route.layout;
|
||||
while (node) {
|
||||
if (node.universal) input_files.push(node.universal);
|
||||
if (node.server) input_files.push(node.server);
|
||||
node = node.parent ?? null;
|
||||
}
|
||||
|
||||
if (route.endpoint) {
|
||||
input_files.push(route.endpoint.file);
|
||||
}
|
||||
|
||||
try {
|
||||
fs.mkdirSync(outdir, { recursive: true });
|
||||
} catch {}
|
||||
|
||||
const output_files = compact(
|
||||
fs.readdirSync(outdir).map((name) => {
|
||||
const stats = fs.statSync(path.join(outdir, name));
|
||||
if (stats.isDirectory()) return;
|
||||
return {
|
||||
name,
|
||||
updated: stats.mtimeMs
|
||||
};
|
||||
})
|
||||
);
|
||||
|
||||
const source_last_updated = Math.max(
|
||||
// ctimeMs includes move operations whereas mtimeMs does not
|
||||
...input_files.map((file) => fs.statSync(path.resolve(root, file)).ctimeMs)
|
||||
);
|
||||
const types_last_updated = Math.max(...output_files.map((file) => file.updated));
|
||||
|
||||
const should_generate =
|
||||
// source files were generated more recently than the types
|
||||
source_last_updated > types_last_updated ||
|
||||
// no meta data file exists yet
|
||||
!has_meta_data ||
|
||||
// some file was deleted
|
||||
!meta_data[route.id]?.every((file) => input_files.includes(file));
|
||||
|
||||
if (should_generate) {
|
||||
// track which old files end up being surplus to requirements
|
||||
const to_delete = new Set(output_files.map((file) => file.name));
|
||||
update_types(config, routes_map, route, root, to_delete);
|
||||
meta_data[route.id] = input_files;
|
||||
}
|
||||
}
|
||||
|
||||
// Remove entries for routes that no longer exist so the file does not
|
||||
// accumulate stale keys after routes are deleted.
|
||||
const current_route_ids = new Set(manifest_data.routes.map((route) => route.id));
|
||||
for (const id of Object.keys(meta_data)) {
|
||||
if (!current_route_ids.has(id)) delete meta_data[id];
|
||||
}
|
||||
|
||||
fs.writeFileSync(meta_data_file, JSON.stringify(meta_data, null, '\t'));
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates types related to the given file. This should only be called
|
||||
* if the file in question was edited, not if it was created/deleted/moved.
|
||||
* @param {import('types').ValidatedConfig} config
|
||||
* @param {import('types').ManifestData} manifest_data
|
||||
* @param {string} file
|
||||
* @param {string} root The project root directory
|
||||
*/
|
||||
export function write_types(config, manifest_data, file, root) {
|
||||
if (!ts) return;
|
||||
|
||||
if (!path.basename(file).startsWith('+')) {
|
||||
// Not a route file
|
||||
return;
|
||||
}
|
||||
|
||||
const id = '/' + posixify(path.relative(config.files.routes, path.dirname(file)));
|
||||
|
||||
const route = manifest_data.routes.find((route) => route.id === id);
|
||||
if (!route) return;
|
||||
if (!route.leaf && !route.layout && !route.endpoint) return; // nothing to do
|
||||
|
||||
update_types(config, create_routes_map(manifest_data), route, root);
|
||||
}
|
||||
|
||||
/**
|
||||
* Collect all leafs into a leaf -> route map
|
||||
* @param {import('types').ManifestData} manifest_data
|
||||
*/
|
||||
function create_routes_map(manifest_data) {
|
||||
/** @type {RoutesMap} */
|
||||
const map = new Map();
|
||||
for (const route of manifest_data.routes) {
|
||||
if (route.leaf) {
|
||||
map.set(route.leaf, { route, proxies: { server: null, universal: null } });
|
||||
}
|
||||
}
|
||||
return map;
|
||||
}
|
||||
|
||||
/**
|
||||
* Update types for a specific route
|
||||
* @param {import('types').ValidatedConfig} config
|
||||
* @param {RoutesMap} routes
|
||||
* @param {import('types').RouteData} route
|
||||
* @param {string} root The project root directory
|
||||
* @param {Set<string>} [to_delete]
|
||||
*/
|
||||
function update_types(config, routes, route, root, to_delete = new Set()) {
|
||||
const routes_dir = remove_relative_parent_traversals(
|
||||
posixify(path.relative(root, config.files.routes))
|
||||
);
|
||||
const outdir = path.join(config.outDir, 'types', routes_dir, route.id);
|
||||
|
||||
// now generate new types
|
||||
const imports = [
|
||||
"import type * as Kit from '@sveltejs/kit';",
|
||||
"import { MatcherParam } from '@sveltejs/kit/params';"
|
||||
];
|
||||
|
||||
/** @type {string[]} */
|
||||
const declarations = [];
|
||||
|
||||
/** @type {string[]} */
|
||||
const exports = [];
|
||||
|
||||
// add 'Expand' helper
|
||||
// Makes sure a type is "repackaged" and therefore more readable
|
||||
declarations.push('type Expand<T> = T extends infer O ? { [K in keyof O]: O[K] } : never;');
|
||||
|
||||
declarations.push(
|
||||
'type RouteParams = ' + generate_params_type(route.params, outdir, config) + ';'
|
||||
);
|
||||
|
||||
if (route.params.length > 0) {
|
||||
exports.push(
|
||||
'export type EntryGenerator = () => Promise<Array<RouteParams>> | Array<RouteParams>;'
|
||||
);
|
||||
}
|
||||
|
||||
declarations.push(`type RouteId = '${route.id}';`);
|
||||
|
||||
// These could also be placed in our public types, but it would bloat them unnecessarily and we may want to change these in the future
|
||||
if (route.layout || route.leaf) {
|
||||
declarations.push(
|
||||
// If T extends the empty object, void is also allowed as a return type
|
||||
'type MaybeWithVoid<T> = {} extends T ? T | void : T;',
|
||||
|
||||
// Returns the key of the object whose values are required.
|
||||
'export type RequiredKeys<T> = { [K in keyof T]-?: {} extends { [P in K]: T[K] } ? never : K; }[keyof T];',
|
||||
|
||||
// Helper type to get the correct output type for load functions. It should be passed the parent type to check what types from App.PageData are still required.
|
||||
// If none, void is also allowed as a return type.
|
||||
'type OutputDataShape<T> = MaybeWithVoid<Omit<App.PageData, RequiredKeys<T>> & Partial<Pick<App.PageData, keyof T & keyof App.PageData>> & Record<string, any>>',
|
||||
|
||||
// null & {} == null, we need to prevent that in some situations
|
||||
'type EnsureDefined<T> = T extends null | undefined ? {} : T;',
|
||||
|
||||
// Takes a union type and returns a union type where each type also has all properties
|
||||
// of all possible types (typed as undefined), making accessing them more ergonomic
|
||||
'type OptionalUnion<U extends Record<string, any>, A extends keyof U = U extends U ? keyof U : never> = U extends unknown ? { [P in Exclude<A, keyof U>]?: never } & U : never;',
|
||||
|
||||
// Re-export `Snapshot` from @sveltejs/kit — in future we could use this to infer <T> from the return type of `snapshot.capture`
|
||||
'/** @deprecated Use the `snapshot` helper from `$app/navigation` instead. */',
|
||||
'export type Snapshot<T = any> = Kit.Snapshot<T>;',
|
||||
|
||||
'export type ErrorProps = { error: App.Error };'
|
||||
);
|
||||
}
|
||||
|
||||
if (route.leaf) {
|
||||
let route_info = routes.get(route.leaf);
|
||||
if (!route_info) {
|
||||
// This should be defined, but belts and braces
|
||||
route_info = { route, proxies: { server: null, universal: null } };
|
||||
routes.set(route.leaf, route_info);
|
||||
}
|
||||
|
||||
const {
|
||||
declarations: d,
|
||||
exports: e,
|
||||
proxies
|
||||
} = process_node(route.leaf, outdir, true, route_info.proxies, root);
|
||||
|
||||
exports.push(...e);
|
||||
declarations.push(...d);
|
||||
|
||||
if (proxies.server) {
|
||||
route_info.proxies.server = proxies.server;
|
||||
if (proxies.server?.modified) to_delete.delete(proxies.server.file_name);
|
||||
}
|
||||
if (proxies.universal) {
|
||||
route_info.proxies.universal = proxies.universal;
|
||||
if (proxies.universal?.modified) to_delete.delete(proxies.universal.file_name);
|
||||
}
|
||||
|
||||
if (route.leaf.server) {
|
||||
exports.push(
|
||||
'export type Action<OutputData extends Record<string, any> | void = Record<string, any> | void> = Kit.Action<RouteParams, OutputData, RouteId>',
|
||||
'export type Actions<OutputData extends Record<string, any> | void = Record<string, any> | void> = Kit.Actions<RouteParams, OutputData, RouteId>',
|
||||
'export type PageProps = { params: RouteParams; data: PageData; form: ActionData }'
|
||||
);
|
||||
} else {
|
||||
exports.push('export type PageProps = { params: RouteParams; data: PageData }');
|
||||
}
|
||||
}
|
||||
|
||||
if (route.layout) {
|
||||
let all_pages_have_load = true;
|
||||
/** @type {import('types').RouteParam[]} */
|
||||
const layout_params = [];
|
||||
// a layout can live in a directory that has no `+page` of its own, in which case its own id
|
||||
// is never the matched route — a request to a colocated `+server` doesn't execute layouts
|
||||
const ids = is_page_route(route) ? ['RouteId'] : [];
|
||||
|
||||
route.layout.child_pages?.forEach((page) => {
|
||||
const leaf = routes.get(page);
|
||||
if (leaf) {
|
||||
if (leaf.route.page) ids.push(`"${leaf.route.id}"`);
|
||||
|
||||
for (const param of leaf.route.params) {
|
||||
// skip if already added
|
||||
if (layout_params.some((p) => p.name === param.name)) continue;
|
||||
layout_params.push({ ...param, optional: true });
|
||||
}
|
||||
|
||||
ensureProxies(page, leaf.proxies, root);
|
||||
|
||||
if (
|
||||
// Be defensive - if a proxy doesn't exist (because it couldn't be created), assume a load function exists.
|
||||
// If we didn't and it's a false negative, the user could wrongfully get a type error on layouts.
|
||||
(leaf.proxies.server && !leaf.proxies.server.exports.includes('load')) ||
|
||||
(leaf.proxies.universal && !leaf.proxies.universal.exports.includes('load'))
|
||||
) {
|
||||
all_pages_have_load = false;
|
||||
}
|
||||
}
|
||||
if (!page.server && !page.universal) {
|
||||
all_pages_have_load = false;
|
||||
}
|
||||
});
|
||||
|
||||
if (route.id === '/') {
|
||||
// root layout is used for fallback error page, where ID can be null
|
||||
ids.push('null');
|
||||
}
|
||||
|
||||
declarations.push(`type LayoutRouteId = ${ids.join(' | ') || 'never'}`);
|
||||
|
||||
declarations.push(
|
||||
'type LayoutParams = RouteParams & ' + generate_params_type(layout_params, outdir, config)
|
||||
);
|
||||
|
||||
const {
|
||||
exports: e,
|
||||
declarations: d,
|
||||
proxies
|
||||
} = process_node(
|
||||
route.layout,
|
||||
outdir,
|
||||
false,
|
||||
{ server: null, universal: null },
|
||||
root,
|
||||
all_pages_have_load
|
||||
);
|
||||
|
||||
exports.push(...e);
|
||||
declarations.push(...d);
|
||||
|
||||
if (proxies.server?.modified) to_delete.delete(proxies.server.file_name);
|
||||
if (proxies.universal?.modified) to_delete.delete(proxies.universal.file_name);
|
||||
|
||||
exports.push(
|
||||
'export type LayoutProps = { params: LayoutParams; data: LayoutData; children: import("svelte").Snippet }'
|
||||
);
|
||||
}
|
||||
|
||||
if (route.endpoint) {
|
||||
exports.push('export type RequestHandler = Kit.RequestHandler<RouteParams, RouteId>;');
|
||||
}
|
||||
|
||||
if (route.leaf?.server || route.layout?.server || route.endpoint) {
|
||||
exports.push('export type RequestEvent = Kit.RequestEvent<RouteParams, RouteId>;');
|
||||
}
|
||||
|
||||
const output = [imports.join('\n'), declarations.join('\n'), exports.join('\n')]
|
||||
.filter(Boolean)
|
||||
.join('\n\n');
|
||||
|
||||
fs.writeFileSync(`${outdir}/$types.d.ts`, output);
|
||||
to_delete.delete('$types.d.ts');
|
||||
|
||||
for (const file of to_delete) {
|
||||
fs.unlinkSync(path.join(outdir, file));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {import('types').PageNode} node
|
||||
* @param {string} outdir
|
||||
* @param {boolean} is_page
|
||||
* @param {Proxies} proxies
|
||||
* @param {string} root The project root directory
|
||||
* @param {boolean} [all_pages_have_load]
|
||||
*/
|
||||
function process_node(node, outdir, is_page, proxies, root, all_pages_have_load = true) {
|
||||
const params = `${is_page ? 'Route' : 'Layout'}Params`;
|
||||
const prefix = is_page ? 'Page' : 'Layout';
|
||||
|
||||
const route_id = is_page ? 'RouteId' : 'LayoutRouteId';
|
||||
|
||||
/** @type {string[]} */
|
||||
const declarations = [];
|
||||
/** @type {string[]} */
|
||||
const exports = [];
|
||||
|
||||
/** @type {string} */
|
||||
let server_data;
|
||||
/** @type {string} */
|
||||
let data;
|
||||
|
||||
ensureProxies(node, proxies, root);
|
||||
|
||||
if (node.server) {
|
||||
const basename = path.basename(node.server);
|
||||
const proxy = proxies.server;
|
||||
if (proxy?.modified) {
|
||||
fs.writeFileSync(`${outdir}/proxy${basename}`, proxy.code);
|
||||
}
|
||||
|
||||
server_data = get_data_type(node.server, 'null', proxy, true);
|
||||
|
||||
const parent_type = `${prefix}ServerParentData`;
|
||||
|
||||
declarations.push(`type ${parent_type} = ${get_parent_type(node, 'LayoutServerData')};`);
|
||||
|
||||
// +page.js load present -> server can return all-optional data
|
||||
const output_data_shape =
|
||||
node.universal || (!is_page && all_pages_have_load)
|
||||
? 'Partial<App.PageData> & Record<string, any> | void'
|
||||
: `OutputDataShape<${parent_type}>`;
|
||||
exports.push(
|
||||
`export type ${prefix}ServerLoad<OutputData extends ${output_data_shape} = ${output_data_shape}> = Kit.ServerLoad<${params}, ${parent_type}, OutputData, ${route_id}>;`
|
||||
);
|
||||
|
||||
exports.push(`export type ${prefix}ServerLoadEvent = Parameters<${prefix}ServerLoad>[0];`);
|
||||
|
||||
if (is_page) {
|
||||
let type = 'unknown';
|
||||
if (proxy && proxy.exports.includes('actions')) {
|
||||
// If the file wasn't tweaked, we can use the return type of the original file.
|
||||
// The advantage is that type updates are reflected without saving.
|
||||
const from = proxy.modified
|
||||
? `./proxy${replace_ext_with_js(basename)}`
|
||||
: path_to_original(outdir, node.server, root);
|
||||
|
||||
exports.push(
|
||||
'type ExcludeActionFailure<T> = T extends Kit.ActionFailure<any> ? never : T extends void ? never : T;',
|
||||
'type ActionsSuccess<T extends Record<string, (...args: any) => any>> = { [Key in keyof T]: ExcludeActionFailure<Awaited<ReturnType<T[Key]>>>; }[keyof T];',
|
||||
'type ExtractActionFailure<T> = T extends Kit.ActionFailure<infer X> ? X extends void ? never : X : never;',
|
||||
'type ActionsFailure<T extends Record<string, (...args: any) => any>> = { [Key in keyof T]: Exclude<ExtractActionFailure<Awaited<ReturnType<T[Key]>>>, void>; }[keyof T];',
|
||||
`type ActionsExport = typeof import('${from}').actions`,
|
||||
"export type SubmitFunction = import('$app/forms').SubmitFunction<Expand<ActionsSuccess<ActionsExport>>, Expand<ActionsFailure<ActionsExport>>>"
|
||||
);
|
||||
|
||||
type = 'Expand<Kit.AwaitedActions<ActionsExport>> | null';
|
||||
}
|
||||
exports.push(`export type ActionData = ${type};`);
|
||||
}
|
||||
} else {
|
||||
server_data = 'null';
|
||||
}
|
||||
exports.push(`export type ${prefix}ServerData = ${server_data};`);
|
||||
|
||||
const parent_type = `${prefix}ParentData`;
|
||||
declarations.push(`type ${parent_type} = ${get_parent_type(node, 'LayoutData')};`);
|
||||
|
||||
if (node.universal) {
|
||||
const proxy = proxies.universal;
|
||||
if (proxy?.modified) {
|
||||
fs.writeFileSync(`${outdir}/proxy${path.basename(node.universal)}`, proxy.code);
|
||||
}
|
||||
|
||||
const type = get_data_type(
|
||||
node.universal,
|
||||
`${parent_type} & EnsureDefined<${prefix}ServerData>`,
|
||||
proxy
|
||||
);
|
||||
|
||||
data = `Expand<Omit<${parent_type}, keyof ${type}> & OptionalUnion<EnsureDefined<${type}>>>`;
|
||||
|
||||
const output_data_shape =
|
||||
!is_page && all_pages_have_load
|
||||
? 'Partial<App.PageData> & Record<string, any> | void'
|
||||
: `OutputDataShape<${parent_type}>`;
|
||||
exports.push(
|
||||
`export type ${prefix}Load<OutputData extends ${output_data_shape} = ${output_data_shape}> = Kit.Load<${params}, ${prefix}ServerData, ${parent_type}, OutputData, ${route_id}>;`
|
||||
);
|
||||
|
||||
exports.push(`export type ${prefix}LoadEvent = Parameters<${prefix}Load>[0];`);
|
||||
} else if (server_data === 'null') {
|
||||
data = `Expand<${parent_type}>`;
|
||||
} else {
|
||||
data = `Expand<Omit<${parent_type}, keyof ${prefix}ServerData> & EnsureDefined<${prefix}ServerData>>`;
|
||||
}
|
||||
|
||||
exports.push(`export type ${prefix}Data = ${data};`);
|
||||
|
||||
return { declarations, exports, proxies };
|
||||
|
||||
/**
|
||||
* @param {string} file_path
|
||||
* @param {string} fallback
|
||||
* @param {Proxy} proxy
|
||||
* @param {boolean} expand
|
||||
*/
|
||||
function get_data_type(file_path, fallback, proxy, expand = false) {
|
||||
if (proxy) {
|
||||
if (proxy.exports.includes('load')) {
|
||||
// If the file wasn't tweaked, we can use the return type of the original file.
|
||||
// The advantage is that type updates are reflected without saving.
|
||||
const from = proxy.modified
|
||||
? `./proxy${replace_ext_with_js(path.basename(file_path))}`
|
||||
: path_to_original(outdir, file_path, root);
|
||||
const type = `Kit.LoadProperties<Awaited<ReturnType<typeof import('${from}').load>>>`;
|
||||
return expand ? `Expand<OptionalUnion<EnsureDefined<${type}>>>` : type;
|
||||
} else {
|
||||
return fallback;
|
||||
}
|
||||
} else {
|
||||
return 'unknown';
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* This function populates the proxies object, if necessary and not already done.
|
||||
* Proxies are used to tweak the code of a file before it's typechecked.
|
||||
* They are needed in two places - when generating the types for a page or layout.
|
||||
* To not do the same work twice, we generate the proxies once and pass them around.
|
||||
*
|
||||
* @param {import('types').PageNode} node
|
||||
* @param {Proxies} proxies
|
||||
* @param {string} root The project root directory
|
||||
*/
|
||||
function ensureProxies(node, proxies, root) {
|
||||
if (node.server && !proxies.server) {
|
||||
proxies.server = createProxy(node.server, true, root);
|
||||
}
|
||||
|
||||
if (node.universal && !proxies.universal) {
|
||||
proxies.universal = createProxy(node.universal, false, root);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {string} file_path
|
||||
* @param {boolean} is_server
|
||||
* @param {string} root The project root directory
|
||||
* @returns {Proxy}
|
||||
*/
|
||||
function createProxy(file_path, is_server, root) {
|
||||
const proxy = tweak_types(fs.readFileSync(path.resolve(root, file_path), 'utf8'), is_server);
|
||||
if (proxy) {
|
||||
return {
|
||||
...proxy,
|
||||
file_name: `proxy${path.basename(file_path)}`
|
||||
};
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the parent type string by recursively looking up the parent layout and accumulate them to one type.
|
||||
* @param {import('types').PageNode} node
|
||||
* @param {string} type
|
||||
*/
|
||||
function get_parent_type(node, type) {
|
||||
const parent_imports = [];
|
||||
|
||||
let parent = node.parent;
|
||||
|
||||
while (parent) {
|
||||
const d = node.depth - parent.depth;
|
||||
// unshift because we need it the other way round for the import string
|
||||
parent_imports.unshift(
|
||||
`${d === 0 ? '' : `import('${'../'.repeat(d)}${'$types.js'}').`}${type}`
|
||||
);
|
||||
parent = parent.parent;
|
||||
}
|
||||
|
||||
let parent_str = `EnsureDefined<${parent_imports[0] || '{}'}>`;
|
||||
for (let i = 1; i < parent_imports.length; i++) {
|
||||
// Omit is necessary because a parent could have a property with the same key which would
|
||||
// cause a type conflict. At runtime the child overwrites the parent property in this case,
|
||||
// so reflect that in the type definition.
|
||||
// EnsureDefined is necessary because {something: string} & null becomes null.
|
||||
// Output types of server loads can be null but when passed in through the `parent` parameter they are the empty object instead.
|
||||
parent_str = `Omit<${parent_str}, keyof ${parent_imports[i]}> & EnsureDefined<${parent_imports[i]}>`;
|
||||
}
|
||||
return parent_str;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {string} outdir
|
||||
* @param {string} file_path
|
||||
* @param {string} root The project root directory
|
||||
*/
|
||||
function path_to_original(outdir, file_path, root) {
|
||||
return posixify(path.relative(outdir, path.join(root, replace_ext_with_js(file_path))));
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {string} file_path
|
||||
*/
|
||||
function replace_ext_with_js(file_path) {
|
||||
// Another extension than `.js` (or nothing, but that fails with node16 moduleResolution)
|
||||
// will result in TS failing to lookup the file
|
||||
const ext = path.extname(file_path);
|
||||
return file_path.slice(0, -ext.length) + '.js';
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {import('types').RouteParam[]} params
|
||||
* @param {string} outdir
|
||||
* @param {import('types').ValidatedConfig} config
|
||||
*/
|
||||
function generate_params_type(params, outdir, config) {
|
||||
const path_to_params = () => {
|
||||
const params_file =
|
||||
resolve_entry(config.files.params, config.moduleExtensions) ??
|
||||
config.files.params.replace(/\.(js|ts)$/, '') + '.js';
|
||||
|
||||
return posixify(path.relative(outdir, params_file));
|
||||
};
|
||||
|
||||
const params_import = path_to_params();
|
||||
|
||||
return `{ ${params
|
||||
.map(
|
||||
(param) =>
|
||||
`${/^\w+$/.test(param.name) ? param.name : `'${param.name}'`}${param.optional ? '?' : ''}: ${
|
||||
param.matcher
|
||||
? `MatcherParam<(typeof import('${params_import}').params)[${JSON.stringify(param.matcher)}]>`
|
||||
: 'string'
|
||||
}${param.optional ? ' | undefined' : ''}`
|
||||
)
|
||||
.join('; ')} }`;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {string} content
|
||||
* @param {boolean} is_server
|
||||
* @returns {Omit<NonNullable<Proxy>, 'file_name'> | null}
|
||||
*/
|
||||
export function tweak_types(content, is_server) {
|
||||
const names = new Set(is_server ? ['load', 'actions'] : ['load']);
|
||||
|
||||
try {
|
||||
let modified = false;
|
||||
|
||||
const ast = ts.createSourceFile(
|
||||
'filename.ts',
|
||||
content,
|
||||
ts.ScriptTarget.Latest,
|
||||
false,
|
||||
ts.ScriptKind.TS
|
||||
);
|
||||
|
||||
const code = new MagicString(content);
|
||||
|
||||
const exports = new Map();
|
||||
/** @param {import('typescript').BindingName} name */
|
||||
function add_export(name) {
|
||||
if (ts.isIdentifier(name)) {
|
||||
if (names.has(name.text)) exports.set(name.text, name.text);
|
||||
} else {
|
||||
for (const element of name.elements) {
|
||||
if (ts.isBindingElement(element)) add_export(element.name);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
ast.forEachChild((node) => {
|
||||
if (
|
||||
ts.isExportDeclaration(node) &&
|
||||
node.exportClause &&
|
||||
ts.isNamedExports(node.exportClause)
|
||||
) {
|
||||
node.exportClause.elements.forEach((element) => {
|
||||
const exported = element.name;
|
||||
if (names.has(element.name.text)) {
|
||||
const local = element.propertyName || element.name;
|
||||
exports.set(exported.text, local.text);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
if (
|
||||
ts.canHaveModifiers(node) &&
|
||||
ts.getModifiers(node)?.some((modifier) => modifier.kind === ts.SyntaxKind.ExportKeyword)
|
||||
) {
|
||||
if (ts.isFunctionDeclaration(node) && node.name?.text && names.has(node.name?.text)) {
|
||||
exports.set(node.name.text, node.name.text);
|
||||
}
|
||||
|
||||
if (ts.isVariableStatement(node)) {
|
||||
node.declarationList.declarations.forEach((declaration) => {
|
||||
add_export(declaration.name);
|
||||
});
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* @param {import('typescript').Node} node
|
||||
* @param {import('typescript').Node} value
|
||||
*/
|
||||
function replace_jsdoc_type_tags(node, value) {
|
||||
let _modified = false;
|
||||
// @ts-ignore
|
||||
if (node.jsDoc) {
|
||||
// @ts-ignore
|
||||
for (const comment of node.jsDoc) {
|
||||
for (const tag of comment.tags ?? []) {
|
||||
if (ts.isJSDocTypeTag(tag)) {
|
||||
const is_fn =
|
||||
ts.isFunctionDeclaration(value) ||
|
||||
ts.isFunctionExpression(value) ||
|
||||
ts.isArrowFunction(value);
|
||||
|
||||
if (is_fn && value.parameters?.length > 0) {
|
||||
const name = ts.isIdentifier(value.parameters[0].name)
|
||||
? value.parameters[0].name.text
|
||||
: 'event';
|
||||
code.overwrite(tag.tagName.pos, tag.tagName.end, 'param');
|
||||
code.prependRight(tag.typeExpression.pos + 1, 'Parameters<');
|
||||
code.appendLeft(tag.typeExpression.end - 1, '>[0]');
|
||||
code.appendLeft(tag.typeExpression.end, ` ${name}`);
|
||||
} else {
|
||||
code.overwrite(tag.pos, tag.end, '');
|
||||
}
|
||||
_modified = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
modified = modified || _modified;
|
||||
return _modified;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {number} name_end position of the identifier the annotation is attached to
|
||||
* @param {import('typescript').TypeNode} type_node
|
||||
* @returns {string} the removed annotation's text
|
||||
*/
|
||||
function strip_type_annotation(name_end, type_node) {
|
||||
let a = type_node.pos;
|
||||
const b = type_node.end;
|
||||
while (is_whitespace(content[a])) a += 1;
|
||||
|
||||
const type = content.slice(a, b);
|
||||
code.remove(name_end, type_node.end);
|
||||
modified = true;
|
||||
return type;
|
||||
}
|
||||
|
||||
/**
|
||||
* Types the first parameter of an untyped arrow/function expression.
|
||||
* @param {import('typescript').Expression | undefined} rhs
|
||||
* @param {string} type
|
||||
* @returns {boolean} `false` if there was nothing to annotate
|
||||
*/
|
||||
function annotate_first_param(rhs, type) {
|
||||
if (
|
||||
!rhs ||
|
||||
!(ts.isArrowFunction(rhs) || ts.isFunctionExpression(rhs)) ||
|
||||
!rhs.parameters.length
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const arg = rhs.parameters[0];
|
||||
const add_parens = content[arg.pos - 1] !== '(';
|
||||
|
||||
if (add_parens) code.prependRight(arg.pos, '(');
|
||||
|
||||
if (arg.type) return false;
|
||||
|
||||
code.appendLeft(arg.name.end, `: ${type}` + (add_parens ? ')' : ''));
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {import('typescript').Expression | undefined} initializer
|
||||
* @param {(prop: import('typescript').PropertyAssignment) => void} callback
|
||||
*/
|
||||
function for_each_action(initializer, callback) {
|
||||
if (initializer && ts.isObjectLiteralExpression(initializer)) {
|
||||
for (const prop of initializer.properties) {
|
||||
if (ts.isPropertyAssignment(prop) && ts.isIdentifier(prop.name)) {
|
||||
callback(prop);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
ast.forEachChild((node) => {
|
||||
if (ts.isFunctionDeclaration(node) && node.name?.text && node.name?.text === 'load') {
|
||||
// remove JSDoc comment above `export function load ...`
|
||||
replace_jsdoc_type_tags(node, node);
|
||||
}
|
||||
|
||||
if (ts.isVariableStatement(node)) {
|
||||
// remove JSDoc comment above `export const load = ...`
|
||||
if (
|
||||
ts.isIdentifier(node.declarationList.declarations[0].name) &&
|
||||
names.has(node.declarationList.declarations[0].name.text) &&
|
||||
node.declarationList.declarations[0].initializer
|
||||
) {
|
||||
replace_jsdoc_type_tags(node, node.declarationList.declarations[0].initializer);
|
||||
}
|
||||
|
||||
for (const declaration of node.declarationList.declarations) {
|
||||
if (
|
||||
ts.isIdentifier(declaration.name) &&
|
||||
declaration.name.text === 'load' &&
|
||||
declaration.initializer
|
||||
) {
|
||||
// edge case — remove JSDoc comment above individual export
|
||||
replace_jsdoc_type_tags(declaration, declaration.initializer);
|
||||
|
||||
if (declaration.type) {
|
||||
const type = strip_type_annotation(declaration.name.end, declaration.type);
|
||||
|
||||
if (!annotate_first_param(declaration.initializer, `Parameters<${type}>[0]`)) {
|
||||
// prevent "type X is imported but not used" (isn't silenced by @ts-nocheck) when svelte-check runs
|
||||
code.append(`;null as any as ${type};`);
|
||||
}
|
||||
}
|
||||
} else if (
|
||||
is_server &&
|
||||
ts.isIdentifier(declaration.name) &&
|
||||
declaration.name?.text === 'actions' &&
|
||||
declaration.initializer
|
||||
) {
|
||||
// remove JSDoc comment from `export const actions = ..`
|
||||
const removed = replace_jsdoc_type_tags(node, declaration.initializer);
|
||||
// ... and move type to each individual action
|
||||
if (removed) {
|
||||
for_each_action(declaration.initializer, (prop) => {
|
||||
const rhs = prop.initializer;
|
||||
const replaced = replace_jsdoc_type_tags(prop, rhs);
|
||||
if (
|
||||
!replaced &&
|
||||
rhs &&
|
||||
(ts.isArrowFunction(rhs) || ts.isFunctionExpression(rhs)) &&
|
||||
rhs.parameters?.[0]
|
||||
) {
|
||||
const name = ts.isIdentifier(rhs.parameters[0].name)
|
||||
? rhs.parameters[0].name.text
|
||||
: 'event';
|
||||
code.prependRight(
|
||||
rhs.pos,
|
||||
`/** @param {import('./$types').RequestEvent} ${name} */ `
|
||||
);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
if (declaration.type) {
|
||||
const type = strip_type_annotation(declaration.name.end, declaration.type);
|
||||
code.append(`;null as any as ${type};`);
|
||||
|
||||
// ... and move type to each individual action
|
||||
for_each_action(declaration.initializer, (prop) => {
|
||||
annotate_first_param(prop.initializer, "import('./$types').RequestEvent");
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
if (modified) {
|
||||
// Ignore all type errors so they don't show up twice when svelte-check runs
|
||||
// Account for possible @ts-check which would overwrite @ts-nocheck
|
||||
if (code.original.startsWith('// @ts-check')) {
|
||||
code.prependLeft('// @ts-check'.length, '\n// @ts-nocheck\n');
|
||||
} else {
|
||||
code.prepend('// @ts-nocheck\n');
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
modified,
|
||||
code: code.toString(),
|
||||
exports: Array.from(exports.keys())
|
||||
};
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
95
node_modules/@sveltejs/kit/src/core/utils.js
generated
vendored
Normal file
95
node_modules/@sveltejs/kit/src/core/utils.js
generated
vendored
Normal file
@@ -0,0 +1,95 @@
|
||||
import path from 'node:path';
|
||||
import { styleText } from 'node:util';
|
||||
import { to_fs } from '../utils/vite.js';
|
||||
import { noop } from '../utils/functions.js';
|
||||
import { posixify } from '../utils/os.js';
|
||||
import { hash } from '../utils/hash.js';
|
||||
|
||||
/**
|
||||
* Resolved path of the `runtime` directory posix-ified
|
||||
*
|
||||
* TODO Windows issue:
|
||||
* Vite or sth else somehow sets the driver letter inconsistently to lower or upper case depending on the run environment.
|
||||
* In playwright debug mode run through VS Code this a root-to-lowercase conversion is needed in order for the tests to run.
|
||||
* If we do this conversion in other cases it has the opposite effect though and fails.
|
||||
*/
|
||||
export const runtime_directory = posixify(path.resolve(import.meta.dirname, '../runtime'));
|
||||
|
||||
/**
|
||||
* The name of the `globalThis.__sveltekit_xxx` object the app's payload is attached to
|
||||
* @param {string} version_name
|
||||
* @param {boolean} dev
|
||||
*/
|
||||
export function get_global_name(version_name, dev) {
|
||||
return dev ? '__sveltekit_dev' : `__sveltekit_${hash(version_name)}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* This allows us to import SvelteKit internals that aren't exposed via `pkg.exports` in a
|
||||
* way that works whether `@sveltejs/kit` is installed inside the project's `node_modules`
|
||||
* or in a workspace root
|
||||
* @param {string} root
|
||||
* @returns {string}
|
||||
*/
|
||||
export function get_runtime_base(root) {
|
||||
return runtime_directory.startsWith(root)
|
||||
? `/${posixify(path.relative(root, runtime_directory))}`
|
||||
: to_fs(runtime_directory);
|
||||
}
|
||||
|
||||
/** @param {{ verbose: boolean }} opts */
|
||||
export function logger({ verbose } = { verbose: true }) {
|
||||
/** @type {import('types').Logger} */
|
||||
const log = (msg) => console.log(msg);
|
||||
|
||||
/** @param {string} msg */
|
||||
const err = (msg) => console.error(msg);
|
||||
|
||||
log.success = (msg) => log(styleText('green', `✔ ${msg}`));
|
||||
log.error = (msg) => err(styleText(['bold', 'red'], msg));
|
||||
log.warn = (msg) => console.warn(styleText(['bold', 'yellow'], msg));
|
||||
log.minor = verbose ? (msg) => log(styleText('grey', msg)) : noop;
|
||||
log.info = verbose ? log : noop;
|
||||
log.err = err;
|
||||
|
||||
log.prettyError = (error, caller) => {
|
||||
/** @type {unknown} */
|
||||
let e = error;
|
||||
|
||||
while (e instanceof Error) {
|
||||
let stack = e.stack;
|
||||
if (stack) {
|
||||
if (caller) {
|
||||
const i = stack.indexOf(caller);
|
||||
// Cut the stack trace off at the point when our internal one starts
|
||||
stack = stack.slice(0, stack.lastIndexOf('\n', i));
|
||||
}
|
||||
|
||||
err(stack);
|
||||
}
|
||||
|
||||
e = e.cause;
|
||||
}
|
||||
|
||||
if (e) {
|
||||
err(String(e));
|
||||
}
|
||||
};
|
||||
|
||||
return log;
|
||||
}
|
||||
|
||||
/** @param {import('types').ManifestData} manifest_data */
|
||||
export function get_mime_lookup(manifest_data) {
|
||||
/** @type {Record<string, string>} */
|
||||
const mime = {};
|
||||
|
||||
manifest_data.assets.forEach((asset) => {
|
||||
if (asset.type) {
|
||||
const ext = path.extname(asset.file);
|
||||
mime[ext] = asset.type;
|
||||
}
|
||||
});
|
||||
|
||||
return mime;
|
||||
}
|
||||
22
node_modules/@sveltejs/kit/src/exports/adapter.js
generated
vendored
Normal file
22
node_modules/@sveltejs/kit/src/exports/adapter.js
generated
vendored
Normal file
@@ -0,0 +1,22 @@
|
||||
import { REROUTED_URL_HEADER } from '../constants.js';
|
||||
|
||||
/**
|
||||
* Helps a catch-all request handler pass the request to a different handler if
|
||||
* the `reroute` hook has returned a URL pathname that's different from the
|
||||
* incoming request.
|
||||
*
|
||||
* If your adapter is capable of deploying multiple serverless functions, it's a
|
||||
* good idea to also deploy a "catch-all" one to handle uncaught requests.
|
||||
* Running this in that function allows the app's `reroute` hook to rewrite
|
||||
* the request URL and invoke the next appropriate serverless function, if any.
|
||||
* @param {Response} response The response returned from the SvelteKit `server.respond` function
|
||||
* @param {(url: URL) => Response | Promise<Response>} next Your platform-specific implementation for invoking the next handler with a different request URL
|
||||
* @returns {Response | Promise<Response>}
|
||||
* @since 3.0.0
|
||||
*/
|
||||
export function applyReroute(response, next) {
|
||||
const rerouted_url = response.headers.get(REROUTED_URL_HEADER);
|
||||
if (!rerouted_url) return response;
|
||||
|
||||
return next(new URL(rerouted_url));
|
||||
}
|
||||
77
node_modules/@sveltejs/kit/src/exports/env/index.js
generated
vendored
Normal file
77
node_modules/@sveltejs/kit/src/exports/env/index.js
generated
vendored
Normal file
@@ -0,0 +1,77 @@
|
||||
/** @import { StandardSchemaV1 } from '@standard-schema/spec' */
|
||||
/** @import { DefinedEnvVars, EnvVarConfig } from '@sveltejs/kit/env' */
|
||||
|
||||
/**
|
||||
* Utility for defining [environment variables](https://svelte.dev/docs/kit/environment-variables),
|
||||
* which are made available via `$app/env/public` and `$app/env/private`.
|
||||
*
|
||||
* @example
|
||||
* ```js
|
||||
* import { defineEnvVars } from '@sveltejs/kit/env';
|
||||
* import * as v from 'valibot';
|
||||
*
|
||||
* export const variables = defineEnvVars({
|
||||
* API_URL: {
|
||||
* schema: v.pipe(v.string(), v.url())
|
||||
* },
|
||||
* PORT: {
|
||||
* schema: (value) => {
|
||||
* if (value === undefined) return 3000;
|
||||
* const port = Number(value);
|
||||
* if (!Number.isInteger(port)) throw new Error('PORT must be an integer');
|
||||
* return port;
|
||||
* }
|
||||
* }
|
||||
* });
|
||||
* ```
|
||||
*
|
||||
* @template {Record<string, EnvVarConfig<any>>} T
|
||||
* @param {T} variables
|
||||
* @returns {DefinedEnvVars<T>}
|
||||
*/
|
||||
export function defineEnvVars(variables) {
|
||||
/** @type {Record<string, EnvVarConfig<any>>} */
|
||||
const normalized = {};
|
||||
|
||||
for (const [name, config] of Object.entries(variables)) {
|
||||
// standard schemas can be callable (e.g. ArkType), so a function is only a validator if it isn't one
|
||||
normalized[name] =
|
||||
typeof config.schema === 'function' && !('~standard' in config.schema)
|
||||
? { ...config, schema: normalize_env_schema(config.schema) }
|
||||
: config;
|
||||
}
|
||||
|
||||
return /** @type {DefinedEnvVars<T>} */ (normalized);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {(value: string | undefined) => any} fn
|
||||
* @returns {StandardSchemaV1<string | undefined, any>}
|
||||
*/
|
||||
function normalize_env_schema(fn) {
|
||||
return /** @type {StandardSchemaV1<string | undefined, any>} */ (
|
||||
/** @type {unknown} */ ({
|
||||
'~standard': {
|
||||
validate(/** @type {unknown} */ value) {
|
||||
let result;
|
||||
|
||||
try {
|
||||
result = fn(/** @type {string | undefined} */ (value));
|
||||
} catch (error) {
|
||||
return {
|
||||
issues: [
|
||||
{
|
||||
message: error instanceof Error ? error.message || 'Invalid value' : String(error)
|
||||
}
|
||||
]
|
||||
};
|
||||
}
|
||||
|
||||
if (result instanceof Promise) return result; // will be rejected upstream
|
||||
|
||||
return { value: result };
|
||||
}
|
||||
}
|
||||
})
|
||||
);
|
||||
}
|
||||
55
node_modules/@sveltejs/kit/src/exports/env/public.d.ts
generated
vendored
Normal file
55
node_modules/@sveltejs/kit/src/exports/env/public.d.ts
generated
vendored
Normal file
@@ -0,0 +1,55 @@
|
||||
import { StandardSchemaV1 } from '@standard-schema/spec';
|
||||
|
||||
export * from './index.js';
|
||||
|
||||
/**
|
||||
* [Environment variables](https://svelte.dev/docs/kit/environment-variables) can be configured by exporting
|
||||
* a `variables` object from `src/env.ts`, using [`defineEnvVars`](https://svelte.dev/docs/kit/@sveltejs-kit-env#defineEnvVars).
|
||||
*/
|
||||
export interface EnvVarConfig<T> {
|
||||
/**
|
||||
* Whether the environment variable can be accessed by client-side code.
|
||||
* - if `true`, it can be imported from `$app/env/public`
|
||||
* - if `false`, it can be imported from `$app/env/private`, which is a [server-only module](https://svelte.dev/docs/kit/server-only-modules)
|
||||
* @default false
|
||||
*/
|
||||
public?: boolean;
|
||||
/**
|
||||
* Whether the value is determined at build time or when the app runs.
|
||||
* - if `true`, the build time value is inlined into the bundle. This enables optimisations like dead-code elimination
|
||||
* - if `false`, the value is read from the environment when the app starts
|
||||
* @default false
|
||||
*/
|
||||
static?: boolean;
|
||||
/**
|
||||
* A [Standard Schema](https://standardschema.dev/) validator that is applied to the value when the app starts.
|
||||
* Alternatively, a function that returns the (possibly transformed) value, or throws an error explaining
|
||||
* the problem. Returning `undefined` is valid, so a function can describe an optional variable.
|
||||
* The validator can output any value — not necessarily a string — but public, non-static values must be
|
||||
* serializable by [devalue](https://github.com/sveltejs/devalue) so that they can be sent to the browser.
|
||||
*
|
||||
* If omitted, the value must be set, but may be an empty string.
|
||||
*/
|
||||
schema?: StandardSchemaV1<string | undefined, T> | ((value: string | undefined) => T | undefined);
|
||||
/**
|
||||
* A description of the variable that will be used for inline documentation on hover.
|
||||
*/
|
||||
description?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* The return type of [`defineEnvVars`](https://svelte.dev/docs/kit/@sveltejs-kit-env#defineEnvVars).
|
||||
*/
|
||||
export type DefinedEnvVars<T extends Record<string, EnvVarConfig<any>>> = {
|
||||
readonly [K in keyof T]: EnvVarEntry<T[K]>;
|
||||
};
|
||||
|
||||
/**
|
||||
* Normalizes an environment variable config's schema (standard schema or function) to standard schema.
|
||||
*/
|
||||
type EnvVarEntry<C extends EnvVarConfig<any>> =
|
||||
C['schema'] extends StandardSchemaV1<any, any>
|
||||
? C
|
||||
: C['schema'] extends (value: any) => infer R
|
||||
? Omit<C, 'schema'> & { schema: StandardSchemaV1<string | undefined, R> }
|
||||
: C;
|
||||
10
node_modules/@sveltejs/kit/src/exports/hooks/index.js
generated
vendored
Normal file
10
node_modules/@sveltejs/kit/src/exports/hooks/index.js
generated
vendored
Normal file
@@ -0,0 +1,10 @@
|
||||
import * as e from '../../messages/server-errors.js';
|
||||
|
||||
export { sequence } from './sequence.js';
|
||||
|
||||
/**
|
||||
* @internal
|
||||
*/
|
||||
export function defineEnvVars() {
|
||||
e.define_env_vars_moved();
|
||||
}
|
||||
202
node_modules/@sveltejs/kit/src/exports/hooks/public.d.ts
generated
vendored
Normal file
202
node_modules/@sveltejs/kit/src/exports/hooks/public.d.ts
generated
vendored
Normal file
@@ -0,0 +1,202 @@
|
||||
import { StandardSchemaV1 } from '@standard-schema/spec';
|
||||
import { NavigationEvent, RequestEvent } from '@sveltejs/kit';
|
||||
import { MaybePromise } from 'types';
|
||||
|
||||
export * from './index.js';
|
||||
|
||||
/**
|
||||
* The [`handle`](https://svelte.dev/docs/kit/hooks#handle) hook runs every time the SvelteKit server receives a [request](https://svelte.dev/docs/kit/web-standards#Fetch-APIs-Request) and
|
||||
* determines the [response](https://svelte.dev/docs/kit/web-standards#Fetch-APIs-Response).
|
||||
* It receives an `event` object representing the request and a function called `resolve`, which renders the route and generates a `Response`.
|
||||
* This allows you to modify response headers or bodies, or bypass SvelteKit entirely (for implementing routes programmatically, for example).
|
||||
*/
|
||||
export type Handle = (input: {
|
||||
event: RequestEvent;
|
||||
resolve: (event: RequestEvent, opts?: ResolveOptions) => Promise<Response>;
|
||||
}) => MaybePromise<Response>;
|
||||
|
||||
type CaughtErrorMap = {
|
||||
app: App.Error;
|
||||
framework: { status: number; message: string };
|
||||
unknown: unknown;
|
||||
};
|
||||
|
||||
type ValidationCaughtError<Issue extends StandardSchemaV1.Issue> = {
|
||||
kind: 'validation';
|
||||
error: { status: number; message: string };
|
||||
issues: Issue[];
|
||||
};
|
||||
|
||||
/**
|
||||
* The error passed to the [`handleError`](https://svelte.dev/docs/kit/hooks#handleError) hooks.
|
||||
* Use the `kind` discriminant to distinguish errors from your app (thrown with the
|
||||
* [`error`](https://svelte.dev/docs/kit/errors#App-errors) helper), errors generated by
|
||||
* SvelteKit itself (such as 404s), validation errors, and unknown errors (thrown by your code,
|
||||
* or code it calls).
|
||||
*/
|
||||
export type CaughtError<Issue extends StandardSchemaV1.Issue = StandardSchemaV1.Issue> =
|
||||
| {
|
||||
[Kind in keyof CaughtErrorMap]: {
|
||||
/** Identifies the category and origin of the error */
|
||||
kind: Kind;
|
||||
/** The caught error. Its type depends on `kind` */
|
||||
error: CaughtErrorMap[Kind];
|
||||
/** Only present for validation errors */
|
||||
issues?: undefined;
|
||||
};
|
||||
}[keyof CaughtErrorMap]
|
||||
| ValidationCaughtError<Issue>;
|
||||
|
||||
/** The error passed to the client-side `handleError` hook. */
|
||||
export type ClientCaughtError = Exclude<CaughtError, { kind: 'validation' }>;
|
||||
|
||||
/**
|
||||
* The server-side [`handleError`](https://svelte.dev/docs/kit/hooks#handleError) hook runs for every error thrown while responding to a request, except redirects.
|
||||
*
|
||||
* The `kind` property discriminates between _app_ errors (thrown with the [`error`](https://svelte.dev/docs/kit/errors#App-errors) helper),
|
||||
* _framework_ errors (generated by SvelteKit itself, such as 404s), _validation_ errors (caused by invalid remote function arguments)
|
||||
* and _unknown_ errors (thrown by your code, or code it calls).
|
||||
*
|
||||
* The hook returns an object matching `App.Error`, in which `status` and `message` are optional — return them only to
|
||||
* override the defaults. Omitted properties are inherited from the caught error: the body passed to `error(...)` for app errors,
|
||||
* the status and safe message for framework and validation errors, and `500`/`'Internal Error'` for unknown errors. Return nothing to
|
||||
* keep the defaults entirely (if you augment `App.Error` with required properties, you must return those).
|
||||
*
|
||||
* Make sure that this function _never_ throws an error.
|
||||
*/
|
||||
export type HandleServerError<Issue extends StandardSchemaV1.Issue = StandardSchemaV1.Issue> = (
|
||||
input: CaughtError<Issue> & { event: RequestEvent }
|
||||
) => MaybePromise<AppErrorWithOptionalDefaults | VoidIfNoRequiredAppErrorProperties>;
|
||||
|
||||
/**
|
||||
* The client-side [`handleError`](https://svelte.dev/docs/kit/hooks#handleError) hook runs for every error thrown while navigating, except redirects.
|
||||
* Errors that were already transformed by the server-side hook are not passed to it a second time.
|
||||
*
|
||||
* The `kind` property discriminates between _app_ errors (thrown with the [`error`](https://svelte.dev/docs/kit/errors#App-errors) helper),
|
||||
* _framework_ errors (generated by SvelteKit itself, such as 404s) and _unknown_ errors (thrown by your code, or code it calls).
|
||||
*
|
||||
* The hook returns an object matching `App.Error`, in which `status` and `message` are optional — return them only to
|
||||
* override the defaults. Omitted properties are inherited from the caught error: the body passed to `error(...)` for app errors,
|
||||
* the status and safe message for framework errors, and `500`/`'Internal Error'` for unknown errors. Return nothing to
|
||||
* keep the defaults entirely (if you augment `App.Error` with required properties, you must return those).
|
||||
*
|
||||
* Make sure that this function _never_ throws an error.
|
||||
*/
|
||||
export type HandleClientError = (
|
||||
input: ClientCaughtError & { event: NavigationEvent }
|
||||
) => MaybePromise<AppErrorWithOptionalDefaults | VoidIfNoRequiredAppErrorProperties>;
|
||||
|
||||
/**
|
||||
* The [`handleFetch`](https://svelte.dev/docs/kit/hooks#handleFetch) hook allows you to modify (or replace) the result of an [`event.fetch`](https://svelte.dev/docs/kit/load#Making-fetch-requests) call that runs on the server (or during prerendering) inside an endpoint, `load`, `action`, `handle`, `handleError` or `reroute`.
|
||||
*/
|
||||
export type HandleFetch = (input: {
|
||||
event: RequestEvent;
|
||||
request: Request;
|
||||
fetch: typeof fetch;
|
||||
}) => MaybePromise<Response>;
|
||||
|
||||
/**
|
||||
* The [`init`](https://svelte.dev/docs/kit/hooks#init) will be invoked before the server responds to its first request
|
||||
* @since 2.10.0
|
||||
*/
|
||||
export type ServerInit = () => MaybePromise<void>;
|
||||
|
||||
/**
|
||||
* The [`init`](https://svelte.dev/docs/kit/hooks#init) will be invoked once the app starts in the browser
|
||||
* @since 2.10.0
|
||||
*/
|
||||
export type ClientInit = () => MaybePromise<void>;
|
||||
|
||||
/**
|
||||
* The [`reroute`](https://svelte.dev/docs/kit/hooks#reroute) hook allows you to modify the URL before it is used to determine which route to render.
|
||||
* @since 2.3.0
|
||||
*/
|
||||
export type Reroute = (event: { url: URL; fetch: typeof fetch }) => MaybePromise<void | string>;
|
||||
|
||||
/**
|
||||
* The [`transport`](https://svelte.dev/docs/kit/hooks#transport) hook allows you to transport custom types across the server/client boundary.
|
||||
*
|
||||
* Each transporter has a pair of `encode` and `decode` functions. On the server, `encode` determines whether a value is an instance of the custom type and, if so, returns a non-falsy encoding of the value which can be an object or an array (or `false` otherwise).
|
||||
*
|
||||
* In the browser, `decode` turns the encoding back into an instance of the custom type.
|
||||
*
|
||||
* ```ts
|
||||
* import type { Transport } from '@sveltejs/kit/hooks';
|
||||
*
|
||||
* declare class MyCustomType {
|
||||
* data: any
|
||||
* }
|
||||
*
|
||||
* // hooks.js
|
||||
* export const transport: Transport = {
|
||||
* MyCustomType: {
|
||||
* encode: (value) => value instanceof MyCustomType && [value.data],
|
||||
* decode: ([data]) => new MyCustomType(data)
|
||||
* }
|
||||
* };
|
||||
* ```
|
||||
* @since 2.11.0
|
||||
*/
|
||||
export type Transport = Record<string, Transporter>;
|
||||
|
||||
/**
|
||||
* A member of the [`transport`](https://svelte.dev/docs/kit/hooks#transport) hook.
|
||||
*/
|
||||
export interface Transporter<
|
||||
T = any,
|
||||
U = any /* minus falsy values, but we can't properly express that */
|
||||
> {
|
||||
encode: (value: T) => false | U;
|
||||
decode: (data: U) => T;
|
||||
}
|
||||
|
||||
export interface ResolveOptions {
|
||||
/**
|
||||
* Applies custom transforms to HTML. If `done` is true, it's the final chunk. Chunks are not guaranteed to be well-formed HTML
|
||||
* (they could include an element's opening tag but not its closing tag, for example)
|
||||
* but they will always be split at sensible boundaries such as `%sveltekit.head%` or layout/page components.
|
||||
* @param input the html chunk and the info if this is the last chunk
|
||||
*/
|
||||
transformPageChunk?: (input: { html: string; done: boolean }) => MaybePromise<string | undefined>;
|
||||
/**
|
||||
* Determines which headers should be included in serialized responses when a `load` function loads a resource with `fetch`.
|
||||
* By default, none will be included.
|
||||
* @param name header name
|
||||
* @param value header value
|
||||
*/
|
||||
filterSerializedResponseHeaders?: (name: string, value: string) => boolean;
|
||||
/**
|
||||
* Determines which files should be preloaded. Files are preloaded via `<link>` tags added to the
|
||||
* `<head>` tag; if `output.linkHeaderPreload` is enabled, dynamically rendered pages use the
|
||||
* [`Link` response header](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Link) instead.
|
||||
* By default, `js` and `css` files will be preloaded.
|
||||
*
|
||||
* For `font` files, `input` also has a `filename` property, the source file's pathname relative
|
||||
* to the project root, so that a filter can match on it instead of the hashed path. `js` and
|
||||
* `css` files are bundled and have no single source file name.
|
||||
* @param input the type of the file and its path
|
||||
*/
|
||||
preload?: (
|
||||
input:
|
||||
| { type: 'css' | 'js' | 'asset'; path: string }
|
||||
| { type: 'font'; path: string; filename: string }
|
||||
) => boolean;
|
||||
}
|
||||
|
||||
type AppErrorWithOptionalDefaults = Omit<App.Error, 'status' | 'message'> & {
|
||||
status?: App.Error['status'];
|
||||
message?: App.Error['message'];
|
||||
};
|
||||
|
||||
/**
|
||||
* `void` is only a valid `handleError` return when `App.Error` adds no required properties
|
||||
* beyond `status` and `message` — both of which are optional in the return, since they default
|
||||
* to those of the caught error. If `App.Error` is augmented with required properties, the hook
|
||||
* must return them, so returning nothing becomes a type error.
|
||||
*/
|
||||
type VoidIfNoRequiredAppErrorProperties = {
|
||||
status: number;
|
||||
message: string;
|
||||
} extends App.Error
|
||||
? void
|
||||
: never;
|
||||
148
node_modules/@sveltejs/kit/src/exports/hooks/sequence.js
generated
vendored
Normal file
148
node_modules/@sveltejs/kit/src/exports/hooks/sequence.js
generated
vendored
Normal file
@@ -0,0 +1,148 @@
|
||||
/** @import { RequestEvent } from '@sveltejs/kit' */
|
||||
/** @import { Handle, ResolveOptions } from '@sveltejs/kit/hooks' */
|
||||
import {
|
||||
merge_tracing,
|
||||
get_request_store,
|
||||
record_span,
|
||||
with_request_store
|
||||
} from '@sveltejs/kit/internal/server';
|
||||
|
||||
/**
|
||||
* A helper function for sequencing multiple `handle` calls in a middleware-like manner.
|
||||
* The behavior for the `handle` options is as follows:
|
||||
* - `transformPageChunk` is applied in reverse order and merged
|
||||
* - `preload` is applied in forward order, the first option "wins" and no `preload` options after it are called
|
||||
* - `filterSerializedResponseHeaders` behaves the same as `preload`
|
||||
*
|
||||
* ```js
|
||||
* /// file: src/hooks.server.js
|
||||
* import { sequence } from '@sveltejs/kit/hooks';
|
||||
*
|
||||
* /// type: import('@sveltejs/kit/hooks').Handle
|
||||
* async function first({ event, resolve }) {
|
||||
* console.log('first pre-processing');
|
||||
* const result = await resolve(event, {
|
||||
* transformPageChunk: ({ html }) => {
|
||||
* // transforms are applied in reverse order
|
||||
* console.log('first transform');
|
||||
* return html;
|
||||
* },
|
||||
* preload: () => {
|
||||
* // this one wins as it's the first defined in the chain
|
||||
* console.log('first preload');
|
||||
* return true;
|
||||
* }
|
||||
* });
|
||||
* console.log('first post-processing');
|
||||
* return result;
|
||||
* }
|
||||
*
|
||||
* /// type: import('@sveltejs/kit/hooks').Handle
|
||||
* async function second({ event, resolve }) {
|
||||
* console.log('second pre-processing');
|
||||
* const result = await resolve(event, {
|
||||
* transformPageChunk: ({ html }) => {
|
||||
* console.log('second transform');
|
||||
* return html;
|
||||
* },
|
||||
* preload: () => {
|
||||
* console.log('second preload');
|
||||
* return true;
|
||||
* },
|
||||
* filterSerializedResponseHeaders: () => {
|
||||
* // this one wins as it's the first defined in the chain
|
||||
* console.log('second filterSerializedResponseHeaders');
|
||||
* return true;
|
||||
* }
|
||||
* });
|
||||
* console.log('second post-processing');
|
||||
* return result;
|
||||
* }
|
||||
*
|
||||
* export const handle = sequence(first, second);
|
||||
* ```
|
||||
*
|
||||
* The example above would print:
|
||||
*
|
||||
* ```
|
||||
* first pre-processing
|
||||
* first preload
|
||||
* second pre-processing
|
||||
* second filterSerializedResponseHeaders
|
||||
* second transform
|
||||
* first transform
|
||||
* second post-processing
|
||||
* first post-processing
|
||||
* ```
|
||||
*
|
||||
* Calling `resolve` invokes the next handler in the sequence (or SvelteKit itself, if it is the last one). To pass data between handlers, use `event.locals`.
|
||||
*
|
||||
* @param {...Handle} handlers The chain of `handle` functions
|
||||
* @returns {Handle}
|
||||
*/
|
||||
export function sequence(...handlers) {
|
||||
const length = handlers.length;
|
||||
if (!length) return ({ event, resolve }) => resolve(event);
|
||||
|
||||
return ({ event, resolve }) => {
|
||||
const { state } = get_request_store();
|
||||
return apply_handle(0, event, {});
|
||||
|
||||
/**
|
||||
* @param {number} i
|
||||
* @param {RequestEvent} event
|
||||
* @param {ResolveOptions | undefined} parent_options
|
||||
* @returns {Promise<Response>}
|
||||
*/
|
||||
function apply_handle(i, event, parent_options) {
|
||||
const handle = handlers[i];
|
||||
|
||||
return record_span({
|
||||
name: `sveltekit.handle.sequenced.${handle.name ? handle.name : i}`,
|
||||
attributes: {},
|
||||
fn: async (current) => {
|
||||
const traced_event = merge_tracing(event, current);
|
||||
return await with_request_store({ event: traced_event, state }, () =>
|
||||
handle({
|
||||
event: traced_event,
|
||||
resolve: (event, options) => {
|
||||
/** @type {ResolveOptions['transformPageChunk']} */
|
||||
const transformPageChunk = async ({ html, done }) => {
|
||||
if (options?.transformPageChunk) {
|
||||
html = (await options.transformPageChunk({ html, done })) ?? '';
|
||||
}
|
||||
|
||||
if (parent_options?.transformPageChunk) {
|
||||
html = (await parent_options.transformPageChunk({ html, done })) ?? '';
|
||||
}
|
||||
|
||||
return html;
|
||||
};
|
||||
|
||||
/** @type {ResolveOptions['filterSerializedResponseHeaders']} */
|
||||
const filterSerializedResponseHeaders =
|
||||
parent_options?.filterSerializedResponseHeaders ??
|
||||
options?.filterSerializedResponseHeaders;
|
||||
|
||||
/** @type {ResolveOptions['preload']} */
|
||||
const preload = parent_options?.preload ?? options?.preload;
|
||||
|
||||
return i < length - 1
|
||||
? apply_handle(i + 1, event, {
|
||||
transformPageChunk,
|
||||
filterSerializedResponseHeaders,
|
||||
preload
|
||||
})
|
||||
: resolve(event, {
|
||||
transformPageChunk,
|
||||
filterSerializedResponseHeaders,
|
||||
preload
|
||||
});
|
||||
}
|
||||
})
|
||||
);
|
||||
}
|
||||
});
|
||||
}
|
||||
};
|
||||
}
|
||||
328
node_modules/@sveltejs/kit/src/exports/index.js
generated
vendored
Normal file
328
node_modules/@sveltejs/kit/src/exports/index.js
generated
vendored
Normal file
@@ -0,0 +1,328 @@
|
||||
/** @import { StandardSchemaV1 } from '@standard-schema/spec' */
|
||||
import { HttpError, Redirect, ActionFailure, ValidationError } from './internal/shared.js';
|
||||
import { BROWSER, DEV } from 'esm-env';
|
||||
import {
|
||||
add_data_suffix,
|
||||
add_resolution_suffix,
|
||||
has_data_suffix,
|
||||
has_resolution_suffix,
|
||||
strip_data_suffix,
|
||||
strip_resolution_suffix
|
||||
} from '../pathname.js';
|
||||
import { validate_redirect_location } from './url.js';
|
||||
import * as e from '../messages/shared-errors.js';
|
||||
import * as w from '../messages/shared-warnings.js';
|
||||
|
||||
const text_encoder = new TextEncoder();
|
||||
|
||||
export { VERSION } from '../version.js';
|
||||
|
||||
// Keep the status codes as `number` because restricting to certain numbers makes it unnecessarily hard to use compared to the benefits
|
||||
// (we have runtime errors already to check for invalid codes). Also see https://github.com/sveltejs/kit/issues/11780
|
||||
|
||||
// we have to repeat the JSDoc because the display for function overloads is broken
|
||||
// see https://github.com/microsoft/TypeScript/issues/55056
|
||||
|
||||
/**
|
||||
* Throws an error with a HTTP status code and an optional message.
|
||||
* When called during request handling, this will cause SvelteKit to
|
||||
* return an error response; the error will be passed to `handleError` as an _expected_ error.
|
||||
* Make sure you're not catching the thrown error, which would prevent SvelteKit from handling it.
|
||||
* @param {number} status The [HTTP status code](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status#client_error_responses). Must be in the range 400-599.
|
||||
* @param {string} [message] The error message.
|
||||
* @overload
|
||||
* @param {{ status: number; message: string } extends App.Error ? number : never} status
|
||||
* @param {{ status: number; message: string } extends App.Error ? string : never} [message]
|
||||
* @return {never}
|
||||
* @throws {import('./public.js').HttpError} This error instructs SvelteKit to initiate HTTP error handling.
|
||||
* @throws {Error} If the provided status is invalid (not between 400 and 599).
|
||||
*/
|
||||
/**
|
||||
* Throws an error with a HTTP status code and an optional message.
|
||||
* When called during request handling, this will cause SvelteKit to
|
||||
* return an error response; the error will be passed to `handleError` as an _expected_ error.
|
||||
* Make sure you're not catching the thrown error, which would prevent SvelteKit from handling it.
|
||||
* @param {number} status The [HTTP status code](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status#client_error_responses). Must be in the range 400-599.
|
||||
* @param {string} message The error message.
|
||||
* @param {keyof Omit<App.Error, 'status' | 'message'> extends never ? never : Omit<App.Error, 'status' | 'message'>} properties Additional properties of the App.Error type.
|
||||
* @overload
|
||||
* @param {number} status
|
||||
* @param {string} message
|
||||
* @param {keyof Omit<App.Error, 'status' | 'message'> extends never ? never : Omit<App.Error, 'status' | 'message'>} properties
|
||||
* @return {never}
|
||||
* @throws {import('./public.js').HttpError} This error instructs SvelteKit to initiate HTTP error handling.
|
||||
* @throws {Error} If the provided status is invalid (not between 400 and 599).
|
||||
*/
|
||||
/**
|
||||
* Throws an error with a HTTP status code and an optional message.
|
||||
* When called during request handling, this will cause SvelteKit to
|
||||
* return an error response; the error will be passed to `handleError` as an _expected_ error.
|
||||
* Make sure you're not catching the thrown error, which would prevent SvelteKit from handling it.
|
||||
* @deprecated Passing an `App.Error` body as the second argument is deprecated — pass the `message` as the second argument, and any additional properties as the third
|
||||
* @param {number} status The [HTTP status code](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status#client_error_responses). Must be in the range 400-599.
|
||||
* @param {Omit<App.Error, 'status'> & { status?: App.Error['status'] }} body An object that conforms to the App.Error type. If a string is passed, it will be used as the message property.
|
||||
* @overload
|
||||
* @param {number} status
|
||||
* @param {Omit<App.Error, 'status'> & { status?: App.Error['status'] }} properties
|
||||
* @return {never}
|
||||
* @throws {import('./public.js').HttpError} This error instructs SvelteKit to initiate HTTP error handling.
|
||||
* @throws {Error} If the provided status is invalid (not between 400 and 599).
|
||||
*/
|
||||
/**
|
||||
* Throws an error with a HTTP status code and an optional message.
|
||||
* When called during request handling, this will cause SvelteKit to
|
||||
* return an error response; the error will be passed to `handleError` as an _expected_ error.
|
||||
* Make sure you're not catching the thrown error, which would prevent SvelteKit from handling it.
|
||||
* @param {any} status The [HTTP status code](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status#client_error_responses). Must be in the range 400-599.
|
||||
* @param {any} [message] A string, or (deprecated) a partial App.Error object
|
||||
* @param {any} [properties] Additional properties of the App.Error type when passing a string message.
|
||||
* @return {never}
|
||||
* @throws {import('./public.js').HttpError} This error instructs SvelteKit to initiate HTTP error handling.
|
||||
* @throws {Error} If the provided status is invalid (not between 400 and 599).
|
||||
*/
|
||||
export function error(status, message, properties) {
|
||||
if ((!BROWSER || DEV) && (isNaN(status) || status < 400 || status > 599)) {
|
||||
e.invalid_error_status({ status: String(status) });
|
||||
}
|
||||
|
||||
if (message !== undefined && typeof message !== 'string') {
|
||||
if (DEV) {
|
||||
w.error_body_deprecated();
|
||||
}
|
||||
|
||||
({ message, ...properties } = message);
|
||||
}
|
||||
|
||||
throw new HttpError({ ...properties, status, message: message ?? `Error: ${status}` });
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks whether this is an error thrown by {@link error}.
|
||||
* @template {number} T
|
||||
* @param {unknown} e
|
||||
* @param {T} [status] The status to filter for.
|
||||
* @return {e is (import('./public.js').HttpError & { status: T extends undefined ? never : T })}
|
||||
*/
|
||||
export function isHttpError(e, status) {
|
||||
if (!(e instanceof HttpError)) return false;
|
||||
return !status || e.status === status;
|
||||
}
|
||||
|
||||
/**
|
||||
* Redirect a request. When called during request handling, SvelteKit will return a redirect response.
|
||||
* Make sure you're not catching the thrown redirect, which would prevent SvelteKit from handling it.
|
||||
*
|
||||
* Most common status codes:
|
||||
* * `303 See Other`: redirect as a GET request (often used after a form POST request)
|
||||
* * `307 Temporary Redirect`: redirect will keep the request method
|
||||
* * `308 Permanent Redirect`: redirect will keep the request method, SEO will be transferred to the new page
|
||||
*
|
||||
* [See all redirect status codes](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status#redirection_messages)
|
||||
*
|
||||
* @param {300 | 301 | 302 | 303 | 304 | 305 | 306 | 307 | 308 | ({} & number)} status The [HTTP status code](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status#redirection_messages). Must be in the range 300-308.
|
||||
* @param {string | URL} location The location to redirect to.
|
||||
* @param {{ external?: boolean | string[] }} [options] To redirect to an external URL, you must pass `{ external: true }` to allow any external URL except `javascript:` URLs, or `{ external: [...] }` with an allowlist of permitted origins.
|
||||
* @throws {import('./public.js').Redirect} This error instructs SvelteKit to redirect to the specified location.
|
||||
* @throws {Error} If the provided status is invalid, the location cannot be used as a header value, or the location is an external URL without permission.
|
||||
* @return {never}
|
||||
*/
|
||||
export function redirect(status, location, options) {
|
||||
if ((!BROWSER || DEV) && (isNaN(status) || status < 300 || status > 308)) {
|
||||
e.invalid_redirect_status({ status: String(status) });
|
||||
}
|
||||
|
||||
const href = location.toString();
|
||||
validate_redirect_location(href, options);
|
||||
|
||||
throw new Redirect(
|
||||
// @ts-ignore
|
||||
status,
|
||||
href
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks whether this is a redirect thrown by {@link redirect}.
|
||||
* @param {unknown} e The object to check.
|
||||
* @return {e is import('./public.js').Redirect}
|
||||
*/
|
||||
export function isRedirect(e) {
|
||||
return e instanceof Redirect;
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a JSON `Response` object from the supplied data.
|
||||
* @param {any} data The value that will be serialized as JSON.
|
||||
* @param {ResponseInit} [init] Options such as `status` and `headers` that will be added to the response. `Content-Type: application/json` and `Content-Length` headers will be added automatically.
|
||||
* @deprecated use `Response.json`
|
||||
*/
|
||||
export function json(data, init) {
|
||||
const body = JSON.stringify(data);
|
||||
|
||||
// we can't just do `text(JSON.stringify(data), init)` because
|
||||
// it will set a default `content-type` header. duplicated code
|
||||
// means less duplicated work
|
||||
const headers = new Headers(init?.headers);
|
||||
if (!headers.has('content-length')) {
|
||||
headers.set('content-length', text_encoder.encode(body).byteLength.toString());
|
||||
}
|
||||
|
||||
if (!headers.has('content-type')) {
|
||||
headers.set('content-type', 'application/json');
|
||||
}
|
||||
|
||||
return new Response(body, {
|
||||
...init,
|
||||
headers
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a `Response` object from the supplied body.
|
||||
* @param {string} body The value that will be used as-is.
|
||||
* @param {ResponseInit} [init] Options such as `status` and `headers` that will be added to the response. A `Content-Length` header will be added automatically.
|
||||
* @deprecated use `new Response`
|
||||
*/
|
||||
export function text(body, init) {
|
||||
const headers = new Headers(init?.headers);
|
||||
if (!headers.has('content-length')) {
|
||||
const encoded = text_encoder.encode(body);
|
||||
headers.set('content-length', encoded.byteLength.toString());
|
||||
return new Response(encoded, {
|
||||
...init,
|
||||
headers
|
||||
});
|
||||
}
|
||||
|
||||
return new Response(body, {
|
||||
...init,
|
||||
headers
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Create an `ActionFailure` object. Call when form submission fails.
|
||||
* @param {number} status The [HTTP status code](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status#client_error_responses). Must be in the range 400-599.
|
||||
* @overload
|
||||
* @param {number} status
|
||||
* @returns {import('./public.js').ActionFailure<undefined>}
|
||||
*/
|
||||
/**
|
||||
* Create an `ActionFailure` object. Call when form submission fails.
|
||||
* @template [T=undefined]
|
||||
* @param {number} status The [HTTP status code](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status#client_error_responses). Must be in the range 400-599.
|
||||
* @param {T} data Data associated with the failure (e.g. validation errors)
|
||||
* @overload
|
||||
* @param {number} status
|
||||
* @param {T} data
|
||||
* @returns {import('./public.js').ActionFailure<T>}
|
||||
*/
|
||||
/**
|
||||
* Create an `ActionFailure` object. Call when form submission fails.
|
||||
* @param {number} status
|
||||
* @param {any} [data]
|
||||
* @returns {import('./public.js').ActionFailure<any>}
|
||||
*/
|
||||
export function fail(status, data) {
|
||||
// @ts-expect-error unique symbol missing
|
||||
return new ActionFailure(status, data);
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks whether this is an action failure thrown by {@link fail}.
|
||||
* @param {unknown} e The object to check.
|
||||
* @return {e is import('./public.js').ActionFailure}
|
||||
*/
|
||||
export function isActionFailure(e) {
|
||||
return e instanceof ActionFailure;
|
||||
}
|
||||
|
||||
/**
|
||||
* Use this to throw a validation error to imperatively fail form validation.
|
||||
* Can be used in combination with `issue` passed to form actions to create field-specific issues.
|
||||
*
|
||||
* @example
|
||||
* ```ts
|
||||
* import { invalid } from '@sveltejs/kit';
|
||||
* import { form } from '$app/server';
|
||||
* import { tryLogin } from '#lib/server/auth';
|
||||
* import * as v from 'valibot';
|
||||
*
|
||||
* export const login = form(
|
||||
* v.object({ name: v.string(), _password: v.string() }),
|
||||
* async ({ name, _password }) => {
|
||||
* const success = tryLogin(name, _password);
|
||||
* if (!success) {
|
||||
* invalid('Incorrect username or password');
|
||||
* }
|
||||
*
|
||||
* // ...
|
||||
* }
|
||||
* );
|
||||
* ```
|
||||
* @param {...(StandardSchemaV1.Issue | string)} issues
|
||||
* @returns {never}
|
||||
* @since 2.47.3
|
||||
*/
|
||||
export function invalid(...issues) {
|
||||
throw new ValidationError(
|
||||
issues.map((issue) => (typeof issue === 'string' ? { message: issue } : issue))
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks whether this is a validation error thrown by {@link invalid}.
|
||||
* @param {unknown} e The object to check.
|
||||
* @return {e is import('./public.js').ValidationError}
|
||||
* @since 2.47.3
|
||||
*/
|
||||
export function isValidationError(e) {
|
||||
return e instanceof ValidationError;
|
||||
}
|
||||
|
||||
/**
|
||||
* Strips possible SvelteKit-internal suffixes and trailing slashes from the URL pathname.
|
||||
* Returns the normalized URL as well as a method for adding the potential suffix back
|
||||
* based on a new pathname (possibly including search) or URL.
|
||||
* ```js
|
||||
* import { normalizeUrl } from '@sveltejs/kit';
|
||||
*
|
||||
* const { url, denormalize } = normalizeUrl('/blog/post/__data.json');
|
||||
* console.log(url.pathname); // /blog/post
|
||||
* console.log(denormalize('/blog/post/a')); // /blog/post/a/__data.json
|
||||
* ```
|
||||
* @param {URL | string} url
|
||||
* @returns {{ url: URL, wasNormalized: boolean, denormalize: (url?: string | URL) => URL }}
|
||||
* @since 2.18.0
|
||||
*/
|
||||
export function normalizeUrl(url) {
|
||||
url = new URL(url, 'a://a');
|
||||
|
||||
const is_route_resolution = has_resolution_suffix(url.pathname);
|
||||
const is_data_request = has_data_suffix(url.pathname);
|
||||
const has_trailing_slash = url.pathname !== '/' && url.pathname.endsWith('/');
|
||||
|
||||
if (is_route_resolution) {
|
||||
url.pathname = strip_resolution_suffix(url.pathname);
|
||||
} else if (is_data_request) {
|
||||
url.pathname = strip_data_suffix(url.pathname);
|
||||
} else if (has_trailing_slash) {
|
||||
url.pathname = url.pathname.slice(0, -1);
|
||||
}
|
||||
|
||||
return {
|
||||
url,
|
||||
wasNormalized: is_data_request || is_route_resolution || has_trailing_slash,
|
||||
denormalize: (new_url = url) => {
|
||||
new_url = new URL(new_url, url);
|
||||
if (is_route_resolution) {
|
||||
new_url.pathname = add_resolution_suffix(new_url.pathname);
|
||||
} else if (is_data_request) {
|
||||
new_url.pathname = add_data_suffix(new_url.pathname);
|
||||
} else if (has_trailing_slash && !new_url.pathname.endsWith('/')) {
|
||||
new_url.pathname += '/';
|
||||
}
|
||||
return new_url;
|
||||
}
|
||||
};
|
||||
}
|
||||
5
node_modules/@sveltejs/kit/src/exports/internal/client.js
generated
vendored
Normal file
5
node_modules/@sveltejs/kit/src/exports/internal/client.js
generated
vendored
Normal file
@@ -0,0 +1,5 @@
|
||||
export function get_origin() {
|
||||
return window.location.origin;
|
||||
}
|
||||
|
||||
export * from './shared.js';
|
||||
74
node_modules/@sveltejs/kit/src/exports/internal/env.js
generated
vendored
Normal file
74
node_modules/@sveltejs/kit/src/exports/internal/env.js
generated
vendored
Normal file
@@ -0,0 +1,74 @@
|
||||
/** @import { StandardSchemaV1 } from '@standard-schema/spec' */
|
||||
/** @import { EnvVarConfig } from '@sveltejs/kit/env' */
|
||||
|
||||
import * as e from '../../messages/server-errors.js';
|
||||
import { bullet_list } from '../../utils/format.js';
|
||||
|
||||
export const MISSING = {
|
||||
message: `Value is missing. If it is optional, add a validator declaring it as such.`
|
||||
};
|
||||
|
||||
export const BAD_VALIDATOR = {
|
||||
message: 'Variable was configured with a validator that does not implement Standard Schema'
|
||||
};
|
||||
|
||||
export const ASYNC_VALIDATOR = {
|
||||
message: 'Variable uses an async validator, which is not supported'
|
||||
};
|
||||
|
||||
/**
|
||||
* @param {Record<string, EnvVarConfig<any> | undefined>} variables
|
||||
* @param {string | undefined} value
|
||||
* @param {string} name
|
||||
* @param {Record<string, StandardSchemaV1.Issue[]>} issues
|
||||
* @returns
|
||||
*/
|
||||
export function validate(variables, value, name, issues) {
|
||||
const config = variables[name] ?? {};
|
||||
// `defineEnvVars` normalizes function validators to standard schemas
|
||||
const validator = /** @type {StandardSchemaV1<string | undefined, any> | undefined} */ (
|
||||
config.schema
|
||||
);
|
||||
|
||||
if (!validator) {
|
||||
if (value === undefined) issues[name] = [MISSING];
|
||||
return value;
|
||||
}
|
||||
|
||||
if (!validator['~standard']) {
|
||||
issues[name] = [BAD_VALIDATOR];
|
||||
return;
|
||||
}
|
||||
|
||||
const result = validator['~standard'].validate(value);
|
||||
|
||||
if (result instanceof Promise) {
|
||||
issues[name] = [ASYNC_VALIDATOR];
|
||||
return;
|
||||
}
|
||||
|
||||
if (result.issues) {
|
||||
issues[name] = [...result.issues];
|
||||
return;
|
||||
}
|
||||
|
||||
return result.value;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {Record<string, StandardSchemaV1.Issue[]>} issues
|
||||
*/
|
||||
export function handle_issues(issues) {
|
||||
const entries = Object.entries(issues);
|
||||
|
||||
if (entries.length === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
const list = entries
|
||||
.map(([name, issues]) => `${name}\n${bullet_list(issues.map((issue) => issue.message))}`)
|
||||
.join('\n\n');
|
||||
|
||||
// the stack would only point into SvelteKit's generated modules
|
||||
e.env_invalid({ issues: `\n${list}\n` }, { stackless: true });
|
||||
}
|
||||
1
node_modules/@sveltejs/kit/src/exports/internal/index.js
generated
vendored
Normal file
1
node_modules/@sveltejs/kit/src/exports/internal/index.js
generated
vendored
Normal file
@@ -0,0 +1 @@
|
||||
export * from '#internal';
|
||||
69
node_modules/@sveltejs/kit/src/exports/internal/server/event.js
generated
vendored
Normal file
69
node_modules/@sveltejs/kit/src/exports/internal/server/event.js
generated
vendored
Normal file
@@ -0,0 +1,69 @@
|
||||
/** @import { RequestEvent } from '@sveltejs/kit' */
|
||||
/** @import { RequestStore } from 'types' */
|
||||
/** @import { AsyncLocalStorage } from 'node:async_hooks' */
|
||||
import { IN_WEBCONTAINER } from '../../../constants.js';
|
||||
import * as e from '../../../messages/server-errors.js';
|
||||
|
||||
/** @type {RequestStore | null} */
|
||||
let sync_store = null;
|
||||
|
||||
/** @type {AsyncLocalStorage<RequestStore | null> | null} */
|
||||
let als;
|
||||
|
||||
import('node:async_hooks')
|
||||
.then((hooks) => (als = new hooks.AsyncLocalStorage()))
|
||||
.catch(() => {
|
||||
// can't use AsyncLocalStorage, but can still call getRequestEvent synchronously.
|
||||
// this isn't behind `supports` because it's basically just StackBlitz (i.e.
|
||||
// in-browser usage) that doesn't support it AFAICT
|
||||
});
|
||||
|
||||
/**
|
||||
* Returns the current `RequestEvent`. Can be used inside server hooks, server `load` functions, actions, and endpoints (and functions called by them).
|
||||
*
|
||||
* In environments without [`AsyncLocalStorage`](https://nodejs.org/api/async_context.html#class-asynclocalstorage), this must be called synchronously (i.e. not after an `await`).
|
||||
* @since 2.20.0
|
||||
*
|
||||
* @returns {RequestEvent}
|
||||
*/
|
||||
export function getRequestEvent() {
|
||||
const event = try_get_request_store()?.event;
|
||||
|
||||
if (!event) {
|
||||
if (als) e.request_event_unavailable();
|
||||
e.request_event_after_await();
|
||||
}
|
||||
|
||||
return event;
|
||||
}
|
||||
|
||||
export function get_request_store() {
|
||||
const result = try_get_request_store();
|
||||
if (!result) {
|
||||
if (als) throw new Error('Could not get the request store. This is an internal error.');
|
||||
e.request_store_after_await();
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
export function try_get_request_store() {
|
||||
return sync_store ?? als?.getStore() ?? null;
|
||||
}
|
||||
|
||||
/**
|
||||
* @template T
|
||||
* @param {RequestStore | null} store
|
||||
* @param {() => T} fn
|
||||
*/
|
||||
export function with_request_store(store, fn) {
|
||||
try {
|
||||
sync_store = store;
|
||||
return als ? als.run(store, fn) : fn();
|
||||
} finally {
|
||||
// Since AsyncLocalStorage is not working in webcontainers, we don't reset `sync_store`
|
||||
// and handle only one request at a time in `src/runtime/server/index.js`.
|
||||
if (!IN_WEBCONTAINER) {
|
||||
sync_store = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
37
node_modules/@sveltejs/kit/src/exports/internal/server/index.js
generated
vendored
Normal file
37
node_modules/@sveltejs/kit/src/exports/internal/server/index.js
generated
vendored
Normal file
@@ -0,0 +1,37 @@
|
||||
/** @import { Span } from '@opentelemetry/api' */
|
||||
import { try_get_request_store } from './event.js';
|
||||
|
||||
export function get_origin() {
|
||||
// `request.url` rather than `event.url`, which throws inside queries
|
||||
const request = try_get_request_store()?.event.request;
|
||||
return request && new URL(request.url).origin;
|
||||
}
|
||||
|
||||
/**
|
||||
* @template {{ tracing: { enabled: boolean, root: Span, current: Span } }} T
|
||||
* @param {T} event_like
|
||||
* @param {Span} current
|
||||
* @returns {T}
|
||||
*/
|
||||
export function merge_tracing(event_like, current) {
|
||||
return {
|
||||
...event_like,
|
||||
tracing: {
|
||||
...event_like.tracing,
|
||||
current
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
export {
|
||||
with_request_store,
|
||||
getRequestEvent,
|
||||
get_request_store,
|
||||
try_get_request_store
|
||||
} from './event.js';
|
||||
|
||||
export { init_remote_functions } from './remote-functions.js';
|
||||
|
||||
export { init_tracing, otel, record_span } from './telemetry.js';
|
||||
|
||||
export * from '../shared.js';
|
||||
25
node_modules/@sveltejs/kit/src/exports/internal/server/remote-functions.js
generated
vendored
Normal file
25
node_modules/@sveltejs/kit/src/exports/internal/server/remote-functions.js
generated
vendored
Normal file
@@ -0,0 +1,25 @@
|
||||
/** @import { RemoteInternals } from 'types' */
|
||||
import * as e from '../../../messages/server-errors.js';
|
||||
|
||||
/** @type {RemoteInternals['type'][]} */
|
||||
const types = ['command', 'form', 'prerender', 'query', 'query_batch', 'query_live'];
|
||||
|
||||
/**
|
||||
* @param {Record<string, any>} module
|
||||
* @param {string} file
|
||||
* @param {string} hash
|
||||
*/
|
||||
export function init_remote_functions(module, file, hash) {
|
||||
if (module.default) {
|
||||
e.remote_module_default_export({ file });
|
||||
}
|
||||
|
||||
for (const [name, fn] of Object.entries(module)) {
|
||||
if (!types.includes(fn?.__?.type)) {
|
||||
e.remote_module_invalid_export({ name, file });
|
||||
}
|
||||
|
||||
fn.__.id = `${hash}/${name}`;
|
||||
fn.__.name = name;
|
||||
}
|
||||
}
|
||||
92
node_modules/@sveltejs/kit/src/exports/internal/server/telemetry.js
generated
vendored
Normal file
92
node_modules/@sveltejs/kit/src/exports/internal/server/telemetry.js
generated
vendored
Normal file
@@ -0,0 +1,92 @@
|
||||
/** @import { Tracer, SpanStatusCode, PropagationAPI, ContextAPI } from '@opentelemetry/api' */
|
||||
/** @import { RecordSpan } from 'types' */
|
||||
import { HttpError, Redirect } from '../shared.js';
|
||||
import { noop_span } from '../../../telemetry.js';
|
||||
import * as e from '../../../messages/server-errors.js';
|
||||
|
||||
// Import this module by its bare specifier so bundled and external code share its state.
|
||||
|
||||
/** @type {Promise<{ tracer: Tracer, SpanStatusCode: typeof SpanStatusCode, propagation: PropagationAPI, context: ContextAPI }> | null} */
|
||||
export let otel = null;
|
||||
|
||||
/**
|
||||
* The caller passes in `import('@opentelemetry/api')` so the import lives behind
|
||||
* `__SVELTEKIT_SERVER_TRACING_ENABLED__` in the bundled runtime and is eliminated
|
||||
* from builds with tracing disabled, where the package may not be installed.
|
||||
* @param {Promise<typeof import('@opentelemetry/api')>} api
|
||||
* @returns {void}
|
||||
*/
|
||||
export function init_tracing(api) {
|
||||
otel ??= api
|
||||
.then((module) => {
|
||||
return {
|
||||
tracer: module.trace.getTracer('sveltekit'),
|
||||
propagation: module.propagation,
|
||||
context: module.context,
|
||||
SpanStatusCode: module.SpanStatusCode
|
||||
};
|
||||
})
|
||||
.catch(() => e.tracing_api_missing());
|
||||
}
|
||||
|
||||
/** @type {RecordSpan} */
|
||||
export async function record_span({ name, attributes, fn }) {
|
||||
if (otel === null) {
|
||||
return fn(noop_span);
|
||||
}
|
||||
|
||||
const { SpanStatusCode, tracer } = await otel;
|
||||
|
||||
return tracer.startActiveSpan(name, { attributes }, async (span) => {
|
||||
try {
|
||||
return await fn(span);
|
||||
} catch (error) {
|
||||
if (error instanceof HttpError) {
|
||||
span.setAttributes({
|
||||
[`${name}.result.type`]: 'known_error',
|
||||
[`${name}.result.status`]: error.status,
|
||||
[`${name}.result.message`]: error.body.message
|
||||
});
|
||||
if (error.status >= 500) {
|
||||
span.recordException({
|
||||
name: 'HttpError',
|
||||
message: error.body.message
|
||||
});
|
||||
span.setStatus({
|
||||
code: SpanStatusCode.ERROR,
|
||||
message: error.body.message
|
||||
});
|
||||
}
|
||||
} else if (error instanceof Redirect) {
|
||||
span.setAttributes({
|
||||
[`${name}.result.type`]: 'redirect',
|
||||
[`${name}.result.status`]: error.status,
|
||||
[`${name}.result.location`]: error.location
|
||||
});
|
||||
} else if (error instanceof Error) {
|
||||
span.setAttributes({
|
||||
[`${name}.result.type`]: 'unknown_error'
|
||||
});
|
||||
span.recordException({
|
||||
name: error.name,
|
||||
message: error.message,
|
||||
// conditional so this compiles under consumers' `exactOptionalPropertyTypes`
|
||||
...(error.stack !== undefined && { stack: error.stack })
|
||||
});
|
||||
span.setStatus({
|
||||
code: SpanStatusCode.ERROR,
|
||||
message: error.message
|
||||
});
|
||||
} else {
|
||||
span.setAttributes({
|
||||
[`${name}.result.type`]: 'unknown_error'
|
||||
});
|
||||
span.setStatus({ code: SpanStatusCode.ERROR });
|
||||
}
|
||||
|
||||
throw error;
|
||||
} finally {
|
||||
span.end();
|
||||
}
|
||||
});
|
||||
}
|
||||
90
node_modules/@sveltejs/kit/src/exports/internal/shared.js
generated
vendored
Normal file
90
node_modules/@sveltejs/kit/src/exports/internal/shared.js
generated
vendored
Normal file
@@ -0,0 +1,90 @@
|
||||
/** @import { StandardSchemaV1 } from '@standard-schema/spec' */
|
||||
|
||||
export class HttpError {
|
||||
/**
|
||||
* @param {App.Error} error
|
||||
*/
|
||||
constructor(error) {
|
||||
this.status = error.status;
|
||||
this.body = error;
|
||||
}
|
||||
|
||||
toString() {
|
||||
return JSON.stringify(this.body);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* An `HttpError` whose body is already in its final, user-facing form — either produced by the
|
||||
* `handleError` hook on the server and reconstructed here from the response, or authored directly
|
||||
* by the client runtime. Unlike a plain `HttpError` (which represents a fresh `error(...)` call
|
||||
* that the hook has yet to see), `handleError` must not run on it.
|
||||
* @extends HttpError
|
||||
*/
|
||||
export class HandledHttpError extends HttpError {}
|
||||
|
||||
export class Redirect {
|
||||
/**
|
||||
* @param {300 | 301 | 302 | 303 | 304 | 305 | 306 | 307 | 308} status
|
||||
* @param {string} location
|
||||
*/
|
||||
constructor(status, location) {
|
||||
try {
|
||||
new Headers({ location });
|
||||
} catch {
|
||||
throw new Error(
|
||||
`Invalid redirect location ${JSON.stringify(location)}: ` +
|
||||
'this string contains characters that cannot be used in HTTP headers'
|
||||
);
|
||||
}
|
||||
|
||||
this.status = status;
|
||||
this.location = location;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* An error that was thrown from within the SvelteKit runtime that is not fatal and doesn't result in a 500, such as a 404.
|
||||
* `SvelteKitError` goes through `handleError`.
|
||||
* @extends Error
|
||||
*/
|
||||
export class SvelteKitError extends Error {
|
||||
/**
|
||||
* @param {number} status
|
||||
* @param {string} text
|
||||
* @param {string} message
|
||||
*/
|
||||
constructor(status, text, message) {
|
||||
super(message);
|
||||
this.status = status;
|
||||
this.text = text;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @template [T=undefined]
|
||||
*/
|
||||
export class ActionFailure {
|
||||
/**
|
||||
* @param {number} status
|
||||
* @param {T} data
|
||||
*/
|
||||
constructor(status, data) {
|
||||
this.status = status;
|
||||
this.data = data;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Error thrown when form validation fails imperatively
|
||||
*/
|
||||
export class ValidationError extends Error {
|
||||
/**
|
||||
* @param {StandardSchemaV1.Issue[]} issues
|
||||
*/
|
||||
constructor(issues) {
|
||||
super('Validation failed');
|
||||
this.name = 'ValidationError';
|
||||
this.issues = issues;
|
||||
}
|
||||
}
|
||||
3
node_modules/@sveltejs/kit/src/exports/internal/types.d.ts
generated
vendored
Normal file
3
node_modules/@sveltejs/kit/src/exports/internal/types.d.ts
generated
vendored
Normal file
@@ -0,0 +1,3 @@
|
||||
// We re-export this so we can use it in the `$app/env/*` module declarations
|
||||
// without the app needing to depend on this package
|
||||
export { StandardSchemaV1 } from '@standard-schema/spec';
|
||||
348
node_modules/@sveltejs/kit/src/exports/node/index.js
generated
vendored
Normal file
348
node_modules/@sveltejs/kit/src/exports/node/index.js
generated
vendored
Normal file
@@ -0,0 +1,348 @@
|
||||
import { createReadStream } from 'node:fs';
|
||||
import { Readable } from 'node:stream';
|
||||
import { SvelteKitError } from '../internal/shared.js';
|
||||
import { noop } from '../../utils/functions.js';
|
||||
|
||||
/** @type {WeakMap<import('http').IncomingMessage, (chunk: Buffer) => void>} */
|
||||
const body_data_listeners = new WeakMap();
|
||||
|
||||
/**
|
||||
* @param {import('http').IncomingMessage} req
|
||||
* @param {number} [body_size_limit]
|
||||
*/
|
||||
function get_raw_body(req, body_size_limit) {
|
||||
const h = req.headers;
|
||||
|
||||
const content_length = Number(h['content-length']);
|
||||
const has_content_length = Number.isFinite(content_length);
|
||||
|
||||
// check if no request body
|
||||
if (
|
||||
(req.httpVersionMajor === 1 && !has_content_length && h['transfer-encoding'] == null) ||
|
||||
content_length === 0
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (req.destroyed) {
|
||||
const readable = new ReadableStream();
|
||||
void readable.cancel();
|
||||
return readable;
|
||||
}
|
||||
|
||||
let size = 0;
|
||||
let cancelled = false;
|
||||
|
||||
return new ReadableStream({
|
||||
start(controller) {
|
||||
if (body_size_limit !== undefined && has_content_length && content_length > body_size_limit) {
|
||||
const error = new SvelteKitError(
|
||||
413,
|
||||
'Payload Too Large',
|
||||
`Content-length of ${content_length} exceeds limit of ${body_size_limit} bytes.`
|
||||
);
|
||||
|
||||
controller.error(error);
|
||||
return;
|
||||
}
|
||||
|
||||
/** @param {Error} error */
|
||||
const on_error = (error) => {
|
||||
cancelled = true;
|
||||
controller.error(error);
|
||||
};
|
||||
|
||||
const on_end = () => {
|
||||
if (cancelled) return;
|
||||
controller.close();
|
||||
};
|
||||
|
||||
/** @param {Buffer} chunk */
|
||||
const on_data = (chunk) => {
|
||||
if (cancelled) return;
|
||||
|
||||
size += chunk.length;
|
||||
|
||||
if (body_size_limit !== undefined && size > body_size_limit) {
|
||||
cancelled = true;
|
||||
|
||||
const message = `request body size exceeded BODY_SIZE_LIMIT of ${body_size_limit}`;
|
||||
|
||||
const error = new SvelteKitError(413, 'Payload Too Large', message);
|
||||
controller.error(error);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
if (has_content_length && size > content_length) {
|
||||
cancelled = true;
|
||||
|
||||
const message = `request body size exceeded content-length of ${content_length}`;
|
||||
|
||||
const error = new SvelteKitError(413, 'Payload Too Large', message);
|
||||
controller.error(error);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
controller.enqueue(chunk);
|
||||
|
||||
if (controller.desiredSize === null || controller.desiredSize <= 0) {
|
||||
req.pause();
|
||||
}
|
||||
};
|
||||
|
||||
req.on('error', on_error);
|
||||
req.on('end', on_end);
|
||||
req.on('data', on_data);
|
||||
body_data_listeners.set(req, on_data);
|
||||
},
|
||||
|
||||
pull() {
|
||||
req.resume();
|
||||
},
|
||||
|
||||
cancel(reason) {
|
||||
cancelled = true;
|
||||
req.destroy(reason);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {{
|
||||
* request: import('http').IncomingMessage;
|
||||
* response?: import('http').ServerResponse;
|
||||
* base: string;
|
||||
* bodySizeLimit?: number;
|
||||
* }} options
|
||||
* @returns {Request}
|
||||
*/
|
||||
export function getRequest({ request, response, base, bodySizeLimit }) {
|
||||
let headers = /** @type {Record<string, string>} */ (request.headers);
|
||||
if (request.httpVersionMajor >= 2) {
|
||||
// the Request constructor rejects headers with ':' in the name
|
||||
headers = Object.assign({}, headers);
|
||||
// https://www.rfc-editor.org/rfc/rfc9113.html#section-8.3.1-2.3.5
|
||||
if (headers[':authority']) {
|
||||
headers.host = headers[':authority'];
|
||||
}
|
||||
delete headers[':authority'];
|
||||
delete headers[':method'];
|
||||
delete headers[':path'];
|
||||
delete headers[':scheme'];
|
||||
}
|
||||
|
||||
const controller = new AbortController();
|
||||
|
||||
request.once('close', () => {
|
||||
if (request.readableAborted) {
|
||||
controller.abort();
|
||||
}
|
||||
});
|
||||
|
||||
// `readableAborted` stays false once the request has been fully read (or drained),
|
||||
// so a client disconnect must also be detected on the response side. `writableEnded`
|
||||
// rather than `writableFinished` because HTTP/2 marks cancelled streams as finished
|
||||
response?.once('close', () => {
|
||||
if (!response.writableEnded) {
|
||||
controller.abort();
|
||||
}
|
||||
});
|
||||
|
||||
return new Request(base + request.url, {
|
||||
// @ts-expect-error
|
||||
duplex: 'half',
|
||||
method: request.method,
|
||||
headers: Object.entries(headers),
|
||||
signal: controller.signal,
|
||||
body:
|
||||
request.method === 'GET' || request.method === 'HEAD'
|
||||
? undefined
|
||||
: get_raw_body(request, bodySizeLimit)
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Drains any unconsumed request body once the response has been sent. When a
|
||||
* route doesn't read the request body (for example a page route receiving a
|
||||
* POST), the unread bytes remain buffered in the socket. On keep-alive
|
||||
* connections Node's HTTP parser then reads those leftover bytes as the next
|
||||
* request, fails to parse them, and resets the connection — losing any
|
||||
* pipelined request. Resuming the request discards the bytes so the connection
|
||||
* stays usable.
|
||||
*
|
||||
* Because `get_raw_body` attaches a `data` listener, Node marks the request as
|
||||
* being consumed (`req._consuming`) and skips its own automatic drain, so we
|
||||
* have to do it ourselves. The whole remaining body is read and discarded; this
|
||||
* is the intended trade-off (keeping the connection reusable) over destroying it.
|
||||
* @see https://github.com/sveltejs/kit/issues/14916
|
||||
* @see https://github.com/sveltejs/kit/issues/15526
|
||||
* @param {import('http').ServerResponse} res
|
||||
*/
|
||||
function drain_request(res) {
|
||||
const req = res.req;
|
||||
if (!req || req.readableEnded || req.destroyed) return;
|
||||
|
||||
// When the body went unread, get_raw_body's `data` listener is still attached
|
||||
// and enqueues into a ReadableStream nobody consumes; it pauses the request at
|
||||
// the high water mark, so one chunk sits in memory and the rest stays buffered
|
||||
// in the socket. Remove only that `data` listener so the resumed stream drops
|
||||
// the remaining bytes instead of re-buffering them. The `end` and `error`
|
||||
// listeners stay attached so the body's ReadableStream is still closed (or
|
||||
// errored) once draining completes, and a consumer that stopped reading
|
||||
// mid-body sees a clean end instead of hanging.
|
||||
const on_data = body_data_listeners.get(req);
|
||||
if (on_data) {
|
||||
req.removeListener('data', on_data);
|
||||
body_data_listeners.delete(req);
|
||||
}
|
||||
|
||||
req.resume();
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {import('http').ServerResponse} res
|
||||
* @param {Response} response
|
||||
* @returns {void}
|
||||
*/
|
||||
export function setResponse(res, response) {
|
||||
res.once('finish', () => drain_request(res));
|
||||
res.once('close', () => drain_request(res));
|
||||
|
||||
for (const [key, value] of response.headers) {
|
||||
try {
|
||||
res.setHeader(key, key === 'set-cookie' ? response.headers.getSetCookie() : value);
|
||||
} catch (error) {
|
||||
res.getHeaderNames().forEach((name) => res.removeHeader(name));
|
||||
res.writeHead(500).end(String(error));
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
if (!response.body) {
|
||||
res.writeHead(response.status);
|
||||
res.end();
|
||||
return;
|
||||
}
|
||||
|
||||
if (response.body.locked) {
|
||||
res.writeHead(response.status);
|
||||
res.end(
|
||||
'Fatal error: Response body is locked. ' +
|
||||
"This can happen when the response was already read (for example through 'response.json()' or 'response.text()')."
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
const reader = response.body.getReader();
|
||||
|
||||
if (res.destroyed) {
|
||||
void reader.cancel();
|
||||
return;
|
||||
}
|
||||
|
||||
const cancel = (/** @type {Error|undefined} */ error) => {
|
||||
res.off('close', cancel);
|
||||
res.off('error', cancel);
|
||||
|
||||
// If the reader has already been interrupted with an error earlier,
|
||||
// then it will appear here, it is useless, but it needs to be catch.
|
||||
reader.cancel(error).catch(noop);
|
||||
if (error) res.destroy(error);
|
||||
};
|
||||
|
||||
res.on('close', cancel);
|
||||
res.on('error', cancel);
|
||||
|
||||
/** @type {Uint8Array<ArrayBuffer>[]} */
|
||||
const buffered = [];
|
||||
|
||||
/** @type {ReturnType<typeof reader.read> | null} */
|
||||
let pending = null;
|
||||
|
||||
void probe();
|
||||
|
||||
// a fixed body (a string, buffer or blob, however constructed) settles all its
|
||||
// reads before the next macrotask, so it can be measured and sent with a
|
||||
// `content-length`; a genuine stream leaves a read pending and only has its
|
||||
// headers delayed by a single tick
|
||||
async function probe() {
|
||||
try {
|
||||
/** @type {Promise<undefined>} */
|
||||
const deadline = new Promise((fulfil) => setImmediate(() => fulfil(undefined)));
|
||||
|
||||
while (buffered.length < 2) {
|
||||
pending = reader.read();
|
||||
const result = await Promise.race([pending, deadline]);
|
||||
|
||||
if (!result) break; // deadline hit — treat the body as a stream
|
||||
|
||||
pending = null;
|
||||
|
||||
if (result.done) {
|
||||
// a `content-length` next to a `transfer-encoding` would be invalid
|
||||
if (!res.hasHeader('content-length') && !res.hasHeader('transfer-encoding')) {
|
||||
res.setHeader(
|
||||
'content-length',
|
||||
buffered.reduce((total, chunk) => total + chunk.byteLength, 0)
|
||||
);
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
buffered.push(result.value);
|
||||
}
|
||||
|
||||
if (res.destroyed) return;
|
||||
|
||||
res.writeHead(response.status);
|
||||
await next();
|
||||
} catch (error) {
|
||||
if (!res.headersSent) res.writeHead(response.status);
|
||||
cancel(error instanceof Error ? error : new Error(String(error)));
|
||||
}
|
||||
}
|
||||
|
||||
async function next() {
|
||||
try {
|
||||
for (;;) {
|
||||
/** @type {Awaited<ReturnType<typeof reader.read>>} */
|
||||
let result;
|
||||
if (buffered.length > 0) {
|
||||
result = {
|
||||
done: false,
|
||||
value: /** @type {Uint8Array<ArrayBuffer>} */ (buffered.shift())
|
||||
};
|
||||
} else if (pending) {
|
||||
result = await pending;
|
||||
pending = null;
|
||||
} else {
|
||||
result = await reader.read();
|
||||
}
|
||||
|
||||
const { done, value } = result;
|
||||
|
||||
if (done) break;
|
||||
|
||||
if (!res.write(value)) {
|
||||
res.once('drain', next);
|
||||
return;
|
||||
}
|
||||
}
|
||||
res.end();
|
||||
} catch (error) {
|
||||
cancel(error instanceof Error ? error : new Error(String(error)));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts a file on disk to a readable stream
|
||||
* @param {string} file
|
||||
* @returns {ReadableStream}
|
||||
* @since 2.4.0
|
||||
*/
|
||||
export function createReadableStream(file) {
|
||||
return /** @type {ReadableStream} */ (Readable.toWeb(createReadStream(file)));
|
||||
}
|
||||
71
node_modules/@sveltejs/kit/src/exports/params/index.js
generated
vendored
Normal file
71
node_modules/@sveltejs/kit/src/exports/params/index.js
generated
vendored
Normal file
@@ -0,0 +1,71 @@
|
||||
/** @import { ParamDefinition, ParamMatcher } from '@sveltejs/kit/params' */
|
||||
import * as e from '../../messages/shared-errors.js';
|
||||
|
||||
/**
|
||||
* Define [parameter matchers](https://svelte.dev/docs/kit/advanced-routing#Matching) for your app.
|
||||
*
|
||||
* @example
|
||||
* ```js
|
||||
* import { defineParams } from '@sveltejs/kit/params';
|
||||
* import * as v from 'valibot';
|
||||
*
|
||||
* export const params = defineParams({
|
||||
* locale: (param) => {
|
||||
* if (param !== 'de' && param !== 'en') return;
|
||||
* return param;
|
||||
* },
|
||||
* number: v.pipe(v.string(), v.toNumber())
|
||||
* });
|
||||
* ```
|
||||
*
|
||||
* @template {Record<string, import('./public.js').ParamDefinition>} T
|
||||
* @param {T} definitions
|
||||
* @returns {import('./public.js').DefinedParams<T>}
|
||||
*/
|
||||
export function defineParams(definitions) {
|
||||
/** @type {Record<string, import('./public.js').ParamMatcher>} */
|
||||
const matchers = {};
|
||||
|
||||
for (const [key, definition] of Object.entries(definitions)) {
|
||||
matchers[key] = normalize_param_definition(definition);
|
||||
}
|
||||
|
||||
return /** @type {import('./public.js').DefinedParams<T>} */ (matchers);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {ParamDefinition} definition
|
||||
* @returns {ParamMatcher}
|
||||
*/
|
||||
export function normalize_param_definition(definition) {
|
||||
// standard schemas can be callable (e.g. ArkType), so this must be checked before the function case
|
||||
if (
|
||||
definition &&
|
||||
(typeof definition === 'object' || typeof definition === 'function') &&
|
||||
'~standard' in definition
|
||||
) {
|
||||
return definition;
|
||||
}
|
||||
|
||||
if (typeof definition === 'function') {
|
||||
return /** @type {ParamMatcher} */ (
|
||||
/** @type {unknown} */ ({
|
||||
'~standard': {
|
||||
validate(/** @type {unknown} */ value) {
|
||||
const result = definition(/** @type {string} */ (value));
|
||||
|
||||
if (result === undefined) {
|
||||
return { issues: [{ message: 'Invalid param' }] };
|
||||
}
|
||||
|
||||
if (/** @type {any} */ (result) instanceof Promise) return result; // will be validated and rejected upstream
|
||||
|
||||
return { value: result };
|
||||
}
|
||||
}
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
e.param_definition_invalid();
|
||||
}
|
||||
63
node_modules/@sveltejs/kit/src/exports/params/public.d.ts
generated
vendored
Normal file
63
node_modules/@sveltejs/kit/src/exports/params/public.d.ts
generated
vendored
Normal file
@@ -0,0 +1,63 @@
|
||||
import { StandardSchemaV1 } from '@standard-schema/spec';
|
||||
|
||||
/**
|
||||
* The shape of a param matcher. See [matching](https://svelte.dev/docs/kit/advanced-routing#Matching) for more info.
|
||||
*/
|
||||
export type ParamMatcher<Output = any> = StandardSchemaV1<string, Output>;
|
||||
|
||||
/**
|
||||
* A value that can be parsed from a URL param and losslessly encoded with `String(...)`.
|
||||
*/
|
||||
export type ParamValue = string | number | boolean | bigint;
|
||||
|
||||
/**
|
||||
* A param matcher definition passed to [`defineParams`](https://svelte.dev/docs/kit/@sveltejs-kit-params#defineParams).
|
||||
*/
|
||||
export type ParamDefinition =
|
||||
| ((param: string) => ParamValue | undefined)
|
||||
| StandardSchemaV1<string, ParamValue>;
|
||||
|
||||
/**
|
||||
* The return type of [`defineParams`](https://svelte.dev/docs/kit/@sveltejs-kit-params#defineParams).
|
||||
*/
|
||||
export type DefinedParams<T extends Record<string, ParamDefinition>> = {
|
||||
readonly [K in keyof T]: ParamEntry<T[K]>;
|
||||
};
|
||||
|
||||
/**
|
||||
* Normalizes a property of defineParams (schema or function) to standard schema.
|
||||
*/
|
||||
type ParamEntry<M> =
|
||||
M extends StandardSchemaV1<any, any>
|
||||
? StandardSchemaV1.InferOutput<M> extends ParamValue
|
||||
? StandardSchemaV1<any, M>
|
||||
: StandardSchemaV1<any, never>
|
||||
: M extends (param: string) => infer R
|
||||
? Exclude<R, undefined> extends ParamValue
|
||||
? StandardSchemaV1<any, Exclude<R, undefined>>
|
||||
: StandardSchemaV1<any, never>
|
||||
: never;
|
||||
|
||||
/**
|
||||
* Extracts the param type from a matcher.
|
||||
*/
|
||||
export type MatcherParam<M extends StandardSchemaV1<any, any>> =
|
||||
M extends StandardSchemaV1<any, infer Inner>
|
||||
? Inner extends ParamValue
|
||||
? Inner
|
||||
: Inner extends StandardSchemaV1<any, any>
|
||||
? StandardSchemaV1.InferOutput<Inner> extends ParamValue
|
||||
? StandardSchemaV1.InferOutput<Inner>
|
||||
: never
|
||||
: never
|
||||
: never;
|
||||
|
||||
/**
|
||||
* Define [parameter matchers](https://svelte.dev/docs/kit/advanced-routing#Matching) for your app.
|
||||
*
|
||||
* @template T
|
||||
* @param definitions
|
||||
*/
|
||||
export function defineParams<T extends Record<string, ParamDefinition>>(
|
||||
definitions: T
|
||||
): DefinedParams<T>;
|
||||
888
node_modules/@sveltejs/kit/src/exports/public.d.ts
generated
vendored
Normal file
888
node_modules/@sveltejs/kit/src/exports/public.d.ts
generated
vendored
Normal file
@@ -0,0 +1,888 @@
|
||||
import 'svelte'; // pick up `declare module "*.svelte"`
|
||||
import 'vite/client'; // pick up `declare module "*.jpg"`, etc.
|
||||
import '../types/ambient.js';
|
||||
|
||||
import {
|
||||
AdapterEntry,
|
||||
HttpMethod,
|
||||
Logger,
|
||||
MaybePromise,
|
||||
Prerendered,
|
||||
PrerenderOption,
|
||||
RequestOptions,
|
||||
RouteSegment
|
||||
} from '../types/private.js';
|
||||
import { ValidatedConfig } from 'types';
|
||||
import { Plugin } from 'vite';
|
||||
import { RouteId as AppRouteId, LayoutParams as AppLayoutParams } from '$app/types';
|
||||
import { StandardSchemaV1 } from '@standard-schema/spec';
|
||||
import { getRequest, setResponse } from '@sveltejs/kit/node';
|
||||
|
||||
export { PrerenderOption } from '../types/private.js';
|
||||
|
||||
// @ts-ignore this is an optional peer dependency so could be missing. Written like this so dts-buddy preserves the ts-ignore
|
||||
type Span = import('@opentelemetry/api').Span;
|
||||
|
||||
/**
|
||||
* [Adapters](https://svelte.dev/docs/kit/adapters) are responsible for taking the production build and turning it into something that can be deployed to a platform of your choosing.
|
||||
*/
|
||||
export interface Adapter {
|
||||
/**
|
||||
* The name of the adapter, using for logging. Will typically correspond to the package name.
|
||||
*/
|
||||
name: string;
|
||||
/**
|
||||
* This function is called after SvelteKit has built your app.
|
||||
* @param builder An object provided by SvelteKit that contains methods for adapting the app
|
||||
*/
|
||||
adapt: (builder: Builder) => MaybePromise<void>;
|
||||
/**
|
||||
* Checks called during dev and build to determine whether specific features will work in production with this adapter.
|
||||
*/
|
||||
supports?: {
|
||||
/**
|
||||
* Test support for `read` from `$app/server`.
|
||||
* @param details.config The merged adapter-specific route config exported from the route with `export const config`
|
||||
*/
|
||||
read?: (details: { config: Record<string, any>; route: { id: string } }) => boolean;
|
||||
|
||||
/**
|
||||
* Test support for `instrumentation.server.js`. To pass, the adapter must support running `instrumentation.server.js` prior to the application code.
|
||||
* @since 2.31.0
|
||||
*/
|
||||
instrumentation?: () => boolean;
|
||||
};
|
||||
/**
|
||||
* Creates an `Emulator`, which allows the adapter to influence the environment
|
||||
* during dev, build and prerendering.
|
||||
*/
|
||||
emulate?: () => MaybePromise<Emulator>;
|
||||
/**
|
||||
* Options for configuring and interacting with Vite
|
||||
* @since 3.0.0
|
||||
*/
|
||||
vite?: AdapterViteConfig | ((ctx: { config: ValidatedConfig }) => AdapterViteConfig);
|
||||
}
|
||||
|
||||
export interface AdapterViteConfig {
|
||||
/**
|
||||
* This function overrides the default behavior during Vite's dev and preview modes
|
||||
* to convert an `http.IncomingMessage` to a `Request` object.
|
||||
* To call the original `setRequest` function, import it from `@sveltejs/kit/node`.
|
||||
* @since 3.0.0
|
||||
*/
|
||||
getRequest?: typeof getRequest;
|
||||
/**
|
||||
* This function overrides the default behavior in Vite's dev and preview modes
|
||||
* to write a `Response` object to a `http.ServerResponse`.
|
||||
* To call the original `setResponse` function, import it from `@sveltejs/kit/node`.
|
||||
* @since 3.0.0
|
||||
*/
|
||||
setResponse?: typeof setResponse;
|
||||
/**
|
||||
* Vite plugins injected by the adapter. By default,
|
||||
* they are placed before SvelteKit's plugins.
|
||||
* @since 3.0.0
|
||||
*/
|
||||
plugins?:
|
||||
| Plugin[]
|
||||
| {
|
||||
/**
|
||||
* Vite plugins placed before any of SvelteKit's own plugins.
|
||||
* @since 3.0.0
|
||||
*/
|
||||
pre?: Plugin[];
|
||||
/**
|
||||
* Vite plugins placed after any of SvelteKit's own plugins.
|
||||
* @since 3.0.0
|
||||
*/
|
||||
post?: Plugin[];
|
||||
};
|
||||
}
|
||||
|
||||
export type LoadProperties<input extends Record<string, any> | void> = input extends void
|
||||
? undefined // needs to be undefined, because void will break intellisense
|
||||
: input extends Record<string, any>
|
||||
? input
|
||||
: unknown;
|
||||
|
||||
export type AwaitedActions<T extends Record<string, (...args: any) => any>> = OptionalUnion<
|
||||
{
|
||||
[Key in keyof T]: UnpackValidationError<Awaited<ReturnType<T[Key]>>>;
|
||||
}[keyof T]
|
||||
>;
|
||||
|
||||
// Takes a union type and returns a union type where each type also has all properties
|
||||
// of all possible types (typed as undefined), making accessing them more ergonomic
|
||||
type OptionalUnion<
|
||||
U extends Record<string, any>, // not unknown, else interfaces don't satisfy this constraint
|
||||
A extends keyof U = U extends U ? keyof U : never
|
||||
> = U extends unknown ? { [P in Exclude<A, keyof U>]?: never } & U : never;
|
||||
|
||||
declare const uniqueSymbol: unique symbol;
|
||||
|
||||
export interface ActionFailure<T = undefined> {
|
||||
status: number;
|
||||
data: T;
|
||||
[uniqueSymbol]: true; // necessary or else UnpackValidationError could wrongly unpack objects with the same shape as ActionFailure
|
||||
}
|
||||
|
||||
/**
|
||||
* A validation error thrown by `invalid`.
|
||||
*/
|
||||
export interface ValidationError {
|
||||
/** The validation issues */
|
||||
issues: StandardSchemaV1.Issue[];
|
||||
}
|
||||
|
||||
type UnpackValidationError<T> =
|
||||
T extends ActionFailure<infer X>
|
||||
? X
|
||||
: T extends void
|
||||
? undefined // needs to be undefined, because void will corrupt union type
|
||||
: T;
|
||||
|
||||
/**
|
||||
* This object is passed to the `adapt` function of adapters.
|
||||
* It contains various methods and properties that are useful for adapting the app.
|
||||
*/
|
||||
export interface Builder {
|
||||
/** Print messages to the console. `log.info` and `log.minor` are silent unless Vite's `logLevel` is `info`. */
|
||||
log: Logger;
|
||||
/**
|
||||
* Remove `dir` and all its contents.
|
||||
* @deprecated Use `fs.rmSync(dir, { force: true, recursive: true })` instead
|
||||
*/
|
||||
rimraf: (dir: string) => void;
|
||||
/**
|
||||
* Create `dir` and any required parent directories.
|
||||
* @deprecated Use `fs.mkdirSync(dir, { recursive: true })` instead
|
||||
*/
|
||||
mkdirp: (dir: string) => void;
|
||||
|
||||
/** The fully resolved SvelteKit config. */
|
||||
config: ValidatedConfig;
|
||||
/** Information about prerendered pages and assets, if any. */
|
||||
prerendered: Prerendered;
|
||||
/** An array of all routes (including prerendered) */
|
||||
routes: RouteDefinition[];
|
||||
/**
|
||||
* The value of the `$app/manifest` module.
|
||||
* The only difference is `manifest.assets` also includes the service worker, if it exists.
|
||||
* @since 3.0.0
|
||||
*/
|
||||
manifest: typeof import('$app/manifest');
|
||||
/**
|
||||
* A record of file extensions to MIME types
|
||||
* @since 3.0.0
|
||||
*/
|
||||
mimeTypes: Record<string, string>;
|
||||
|
||||
/**
|
||||
* Create separate functions that map to one or more routes of your app.
|
||||
* @param fn A function that groups a set of routes into an entry point
|
||||
* @deprecated removed in 3.0. Use `builder.routes` instead
|
||||
*/
|
||||
createEntries?: (fn: (route: RouteDefinition) => AdapterEntry) => Promise<void>;
|
||||
|
||||
/**
|
||||
* Find all the assets imported by server files belonging to `routes`
|
||||
*/
|
||||
findServerAssets: (routes: RouteDefinition[]) => string[];
|
||||
|
||||
/**
|
||||
* Generate a fallback page for a static webserver to use when no route is matched. Useful for single-page apps.
|
||||
*/
|
||||
generateFallback: (dest: string) => Promise<void>;
|
||||
|
||||
/**
|
||||
* Generate a module exposing public environment variables as `$app/env/public` if the app uses it.
|
||||
*/
|
||||
generateEnvModule: () => void;
|
||||
|
||||
/**
|
||||
* Generate a server-side manifest to initialise the SvelteKit [server](https://svelte.dev/docs/kit/@sveltejs-kit#Server) with.
|
||||
* @param opts
|
||||
* @param opts.relativePath A relative path to the base directory of the server build output
|
||||
* @deprecated removed in 3.0. Use `builder.generateServerInstance` or `builder.manifest` instead
|
||||
*/
|
||||
generateManifest?: (opts: { relativePath: string; routes?: RouteDefinition[] }) => string;
|
||||
|
||||
/**
|
||||
* Resolve a path to the `name` directory inside `outDir`, e.g. `/path/to/.svelte-kit/my-adapter`.
|
||||
* @param name path to the file, relative to the build directory
|
||||
*/
|
||||
getBuildDirectory: (name: string) => string;
|
||||
/** Get the fully resolved path to the directory containing client-side assets, including the contents of your `static` directory. */
|
||||
getClientDirectory: () => string;
|
||||
/** Get the fully resolved path to the directory containing server-side code. */
|
||||
getServerDirectory: () => string;
|
||||
/** Get the application path including any configured `base` path, e.g. `my-base-path/_app`. */
|
||||
getAppPath: () => string;
|
||||
|
||||
/**
|
||||
* Generates a module exposing a SvelteKit [Server](https://svelte.dev/docs/kit/@sveltejs-kit#Server) instance.
|
||||
* @param dest
|
||||
* @param opts.routes A subset of the routes to include in the server's manifest
|
||||
* @param opts.serverDirectory The directory containing the server code. Defaults to `getServerDirectory()`.
|
||||
* @since 3.0.0
|
||||
*/
|
||||
generateServerInstance: (
|
||||
dest: string,
|
||||
opts?: {
|
||||
routes?: RouteDefinition[];
|
||||
serverDirectory?: string;
|
||||
}
|
||||
) => void;
|
||||
/**
|
||||
* Write client assets to `dest`.
|
||||
* @param dest the destination folder
|
||||
* @returns an array of files written to `dest`
|
||||
*/
|
||||
writeClient: (dest: string) => string[];
|
||||
/**
|
||||
* Write prerendered files to `dest`.
|
||||
* @param dest the destination folder
|
||||
* @returns an array of files written to `dest`
|
||||
*/
|
||||
writePrerendered: (dest: string) => string[];
|
||||
/**
|
||||
* Write server-side code to `dest`.
|
||||
* @param dest the destination folder
|
||||
* @returns an array of files written to `dest`
|
||||
*/
|
||||
writeServer: (dest: string) => string[];
|
||||
|
||||
/**
|
||||
* Generate an initializer that populates `$env/dynamic/private` before server instrumentation
|
||||
* runs. Include the returned module in any subsequent bundling or tracing step.
|
||||
* @param options an object containing the following properties:
|
||||
* @param options.outputDirectory the directory in which to create the initializer.
|
||||
* @param options.environment the contents of a module whose default export contains the platform's environment variables. If omitted, `process.env` is used.
|
||||
* @param options.serverDirectory the directory containing the server build output. Defaults to `getServerDirectory()`.
|
||||
* @returns the filesystem path to the generated initializer.
|
||||
* @since 3.0.0
|
||||
*/
|
||||
createInstrumentationInitializer: (options: {
|
||||
outputDirectory: string;
|
||||
environment?: string;
|
||||
serverDirectory?: string;
|
||||
}) => string;
|
||||
|
||||
/**
|
||||
* Copy a file or directory.
|
||||
* @param from the source file or directory
|
||||
* @param to the destination file or directory
|
||||
* @param opts.filter a function to determine whether a file or directory should be copied
|
||||
* @param opts.replace a map of strings to replace
|
||||
* @returns an array of files that were copied
|
||||
*/
|
||||
copy: (
|
||||
from: string,
|
||||
to: string,
|
||||
opts?: {
|
||||
filter?(basename: string): boolean;
|
||||
replace?: Record<string, string>;
|
||||
}
|
||||
) => string[];
|
||||
|
||||
/**
|
||||
* Check if the server instrumentation file exists.
|
||||
* @returns true if the server instrumentation file exists, false otherwise
|
||||
* @since 2.31.0
|
||||
*/
|
||||
hasServerInstrumentationFile: () => boolean;
|
||||
|
||||
/**
|
||||
* Instrument `entrypoint` with `instrumentation`.
|
||||
*
|
||||
* Renames `entrypoint` to `start` and creates a new module at
|
||||
* `entrypoint` which imports `instrumentation` and then dynamically imports `start`. This allows
|
||||
* the module hooks necessary for instrumentation libraries to be loaded prior to any application code.
|
||||
*
|
||||
* `initializer` is a module generated by `createInstrumentationInitializer`. It must be included
|
||||
* in any bundling or tracing step before calling this method.
|
||||
*
|
||||
* Caveats:
|
||||
* - "Live exports" will not work. If your adapter uses live exports, your users will need to manually import the server instrumentation on startup.
|
||||
* - If `tla` is `false`, OTEL auto-instrumentation may not work properly. Use it if your environment supports it.
|
||||
* - Use `hasServerInstrumentationFile` to check if the user has a server instrumentation file; if they don't, you shouldn't do this.
|
||||
*
|
||||
* @param options an object containing the following properties:
|
||||
* @param options.entrypoint the path to the entrypoint to trace.
|
||||
* @param options.instrumentation the path to the instrumentation file.
|
||||
* @param options.start the name of the start file. This is what `entrypoint` will be renamed to.
|
||||
* @param options.initializer the filesystem path to the bundled or copied instrumentation initializer.
|
||||
* @param options.module configuration for the resulting entrypoint module.
|
||||
* @param options.module.exports
|
||||
* @param options.module.generateText a function that receives the relative paths to the initializer, instrumentation and start files, and generates the text of the module to be traced. It must import `initializer` before `instrumentation`, and dynamically import `start` after instrumentation has run. If not provided, the default implementation will be used, which uses top-level await.
|
||||
* @since 3.0.0
|
||||
*/
|
||||
instrument: (args: {
|
||||
entrypoint: string;
|
||||
instrumentation: string;
|
||||
start?: string;
|
||||
initializer: string;
|
||||
module?:
|
||||
| {
|
||||
exports: string[];
|
||||
}
|
||||
| {
|
||||
generateText: (args: {
|
||||
instrumentation: string;
|
||||
start: string;
|
||||
initializer: string;
|
||||
}) => string;
|
||||
};
|
||||
}) => void;
|
||||
|
||||
/**
|
||||
* Compress files in `directory` with gzip and brotli, where appropriate. Generates `.gz` and `.br` files alongside the originals.
|
||||
* @param {string} directory The directory containing the files to be compressed
|
||||
* @returns an array of the files in `directory` that were compressed
|
||||
*/
|
||||
compress: (directory: string) => Promise<string[]>;
|
||||
}
|
||||
|
||||
export interface Cookies {
|
||||
/**
|
||||
* Gets a cookie that was previously set with `cookies.set`, or from the request headers.
|
||||
* @param name the name of the cookie
|
||||
* @param opts the options, passed directly to `cookie.parseCookie`. See documentation [here](https://github.com/jshttp/cookie?tab=readme-ov-file#cookieparsecookiestr-options)
|
||||
*/
|
||||
get: (name: string, opts?: import('cookie').ParseOptions) => string | undefined;
|
||||
|
||||
/**
|
||||
* Gets all cookies that were previously set with `cookies.set`, or from the request headers.
|
||||
* @param opts the options, passed directly to `cookie.parseCookie`. See documentation [here](https://github.com/jshttp/cookie?tab=readme-ov-file#cookieparsecookiestr-options)
|
||||
*/
|
||||
getAll: (opts?: import('cookie').ParseOptions) => Array<{ name: string; value: string }>;
|
||||
|
||||
/**
|
||||
* Sets a cookie. This will add a `set-cookie` header to the response, but also make the cookie available via `cookies.get` or `cookies.getAll` during the current request.
|
||||
*
|
||||
* The `httpOnly` is `true` by default, as is `secure`, except during development, when it defaults to `false`. These must be explicitly disabled if you want cookies to be readable by client-side JavaScript and/or transmitted over HTTP.
|
||||
*
|
||||
* The `path` option is `'/'` by default. You can use relative paths, or set `path: ''` to make the cookie only available on the current path and its children.
|
||||
* @param name the name of the cookie
|
||||
* @param value the cookie value
|
||||
* @param opts the options passed to `cookie.stringifySetCookie` with the SvelteKit defaults described above. See documentation [here](https://github.com/jshttp/cookie?tab=readme-ov-file#cookiestringifysetcookiesetcookieobj-options)
|
||||
*/
|
||||
set: (name: string, value: string, opts?: import('cookie').SerializeOptions) => void;
|
||||
|
||||
/**
|
||||
* Deletes a cookie by setting its value to an empty string and setting the expiry date in the past.
|
||||
*
|
||||
* The `httpOnly` is `true` by default, as is `secure`, except during development, when it defaults to `false`. These must be explicitly disabled if you want cookies to be readable by client-side JavaScript and/or transmitted over HTTP.
|
||||
*
|
||||
* The `path` option is `'/'` by default. You can use relative paths, or set `path: ''` to make the cookie only available on the current path and its children.
|
||||
* @param name the name of the cookie
|
||||
* @param opts the options passed to `cookie.stringifySetCookie` with the SvelteKit defaults described above. See documentation [here](https://github.com/jshttp/cookie?tab=readme-ov-file#cookiestringifysetcookiesetcookieobj-options)
|
||||
*/
|
||||
delete: (name: string, opts?: import('cookie').SerializeOptions) => void;
|
||||
|
||||
/**
|
||||
* Parses a single `Set-Cookie` header. This allows you to apply cookies received from an external source:
|
||||
*
|
||||
* ```js
|
||||
* import { getRequestEvent } from '$app/server';
|
||||
*
|
||||
* export async function GET() {
|
||||
* const { cookies } = getRequestEvent();
|
||||
*
|
||||
* const response = await fetch('...');
|
||||
*
|
||||
* for (const str of response.headers.getSetCookie()) {
|
||||
* const { name, value, ...options } = cookies.parse(str);
|
||||
* cookies.set(name, value, options);
|
||||
* }
|
||||
*
|
||||
* // ...
|
||||
* }
|
||||
* ```
|
||||
*
|
||||
* Note the use of `headers.getSetCookie()`, which returns an array of cookie headers, _not_ `headers.get('set-cookie')` which returns a single comma-separated string.
|
||||
*/
|
||||
parse: typeof import('cookie').parseSetCookie;
|
||||
|
||||
/**
|
||||
* Serialize a cookie name-value pair into a `Set-Cookie` header string, but don't apply it to the response.
|
||||
*
|
||||
* The `httpOnly` is `true` by default, as is `secure`, except during development, when it defaults to `false`. These must be explicitly disabled if you want cookies to be readable by client-side JavaScript and/or transmitted over HTTP.
|
||||
*
|
||||
* The `path` option is `'/'` by default. You can use relative paths, or set `path: ''` to make the cookie only available on the current path and its children.
|
||||
* @param name the name of the cookie
|
||||
* @param value the cookie value
|
||||
* @param opts the options passed to `cookie.stringifySetCookie` with the SvelteKit defaults described above. See documentation [here](https://github.com/jshttp/cookie?tab=readme-ov-file#cookiestringifysetcookiesetcookieobj-options)
|
||||
*/
|
||||
serialize: (name: string, value: string, opts?: import('cookie').SerializeOptions) => string;
|
||||
}
|
||||
|
||||
/**
|
||||
* A collection of functions that influence the environment during dev, build and prerendering
|
||||
*/
|
||||
export interface Emulator {
|
||||
/**
|
||||
* A function that is called with the current route `config` and `prerender` option
|
||||
* and returns an `App.Platform` object
|
||||
*/
|
||||
platform?(details: { config: any; prerender: PrerenderOption }): MaybePromise<App.Platform>;
|
||||
}
|
||||
|
||||
/**
|
||||
* The generic form of `PageLoad` and `LayoutLoad`. You should import those from `./$types` (see [generated types](https://svelte.dev/docs/kit/types#Generated-types))
|
||||
* rather than using `Load` directly.
|
||||
*/
|
||||
export type Load<
|
||||
Params extends AppLayoutParams<'/'> = AppLayoutParams<'/'>,
|
||||
InputData extends Record<string, unknown> | null = Record<string, any> | null,
|
||||
ParentData extends Record<string, unknown> = Record<string, any>,
|
||||
OutputData extends Record<string, unknown> | void = Record<string, any> | void,
|
||||
RouteId extends AppRouteId | null = AppRouteId | null
|
||||
> = (event: LoadEvent<Params, InputData, ParentData, RouteId>) => MaybePromise<OutputData>;
|
||||
|
||||
/**
|
||||
* The generic form of `PageLoadEvent` and `LayoutLoadEvent`. You should import those from `./$types` (see [generated types](https://svelte.dev/docs/kit/types#Generated-types))
|
||||
* rather than using `LoadEvent` directly.
|
||||
*/
|
||||
export interface LoadEvent<
|
||||
Params extends AppLayoutParams<'/'> = AppLayoutParams<'/'>,
|
||||
Data extends Record<string, unknown> | null = Record<string, any> | null,
|
||||
ParentData extends Record<string, unknown> = Record<string, any>,
|
||||
RouteId extends AppRouteId | null = AppRouteId | null
|
||||
> extends NavigationEvent<Params, RouteId> {
|
||||
/**
|
||||
* `fetch` is equivalent to the [native `fetch` web API](https://developer.mozilla.org/en-US/docs/Web/API/fetch), with a few additional features:
|
||||
*
|
||||
* - It can be used to make credentialed requests on the server, as it inherits the `cookie` and `authorization` headers for the page request.
|
||||
* - It can make relative requests on the server (ordinarily, `fetch` requires a URL with an origin when used in a server context).
|
||||
* - Internal requests (e.g. for `+server.js` routes) go directly to the handler function when running on the server, without the overhead of an HTTP call.
|
||||
* - During server-side rendering, the response will be captured and inlined into the rendered HTML by hooking into the `text` and `json` methods of the `Response` object. Note that headers will _not_ be serialized, unless explicitly included via [`filterSerializedResponseHeaders`](https://svelte.dev/docs/kit/hooks#handle)
|
||||
* - During hydration, the response will be read from the HTML, guaranteeing consistency and preventing an additional network request.
|
||||
*
|
||||
* You can learn more about making credentialed requests with cookies [here](https://svelte.dev/docs/kit/load#Cookies)
|
||||
*/
|
||||
fetch: typeof fetch;
|
||||
/**
|
||||
* Contains the data returned by the route's server `load` function (in `+layout.server.js` or `+page.server.js`), if any.
|
||||
*/
|
||||
data: Data;
|
||||
/**
|
||||
* If you need to set headers for the response, you can do so using the this method. This is useful if you want the page to be cached, for example:
|
||||
*
|
||||
* ```js
|
||||
* /// file: src/routes/blog/+page.js
|
||||
* export async function load({ fetch, setHeaders }) {
|
||||
* const url = `https://cms.example.com/articles.json`;
|
||||
* const response = await fetch(url);
|
||||
*
|
||||
* setHeaders({
|
||||
* age: response.headers.get('age'),
|
||||
* 'cache-control': response.headers.get('cache-control')
|
||||
* });
|
||||
*
|
||||
* return response.json();
|
||||
* }
|
||||
* ```
|
||||
*
|
||||
* Setting the same header multiple times (even in separate `load` functions) is an error — you can only set a given header once.
|
||||
*
|
||||
* You cannot add a `set-cookie` header with `setHeaders` — use the [`cookies`](https://svelte.dev/docs/kit/@sveltejs-kit#Cookies) API in a server-only `load` function instead.
|
||||
*
|
||||
* `setHeaders` has no effect when a `load` function runs in the browser.
|
||||
*/
|
||||
setHeaders: (headers: Record<string, string>) => void;
|
||||
/**
|
||||
* `await parent()` returns data from parent `+layout.js` `load` functions.
|
||||
* Implicitly, a missing `+layout.js` is treated as a `({ data }) => data` function, meaning that it will return and forward data from parent `+layout.server.js` files.
|
||||
*
|
||||
* Be careful not to introduce accidental waterfalls when using `await parent()`. If for example you only want to merge parent data into the returned output, call it _after_ fetching your other data.
|
||||
*/
|
||||
parent: () => Promise<ParentData>;
|
||||
/**
|
||||
* This function declares that the `load` function has a _dependency_ on one or more URLs or custom identifiers, which can subsequently be used with [`invalidate()`](https://svelte.dev/docs/kit/$app-navigation#invalidate) to cause `load` to rerun.
|
||||
*
|
||||
* Most of the time you won't need this, as `fetch` calls `depends` on your behalf — it's only necessary if you're using a custom API client that bypasses `fetch`.
|
||||
*
|
||||
* URLs can be absolute or relative to the page being loaded, and must be [encoded](https://developer.mozilla.org/en-US/docs/Glossary/percent-encoding).
|
||||
*
|
||||
* Custom identifiers have to be prefixed with one or more lowercase letters followed by a colon to conform to the [URI specification](https://www.rfc-editor.org/rfc/rfc3986.html).
|
||||
*
|
||||
* The following example shows how to use `depends` to register a dependency on a custom identifier, which is `invalidate`d after a button click, making the `load` function rerun.
|
||||
*
|
||||
* ```js
|
||||
* /// file: src/routes/+page.js
|
||||
* let count = 0;
|
||||
* export async function load({ depends }) {
|
||||
* depends('increase:count');
|
||||
*
|
||||
* return { count: count++ };
|
||||
* }
|
||||
* ```
|
||||
*
|
||||
* ```html
|
||||
* /// file: src/routes/+page.svelte
|
||||
* <script>
|
||||
* import { invalidate } from '$app/navigation';
|
||||
*
|
||||
* let { data } = $props();
|
||||
*
|
||||
* const increase = async () => {
|
||||
* await invalidate('increase:count');
|
||||
* }
|
||||
* </script>
|
||||
*
|
||||
* <p>{data.count}<p>
|
||||
* <button on:click={increase}>Increase Count</button>
|
||||
* ```
|
||||
*/
|
||||
depends: (...deps: Array<`${string}:${string}`>) => void;
|
||||
/**
|
||||
* Use this function to opt out of dependency tracking for everything that is synchronously called within the callback. Example:
|
||||
*
|
||||
* ```js
|
||||
* /// file: src/routes/+page.server.js
|
||||
* export async function load({ untrack, url }) {
|
||||
* // Untrack url.pathname so that path changes don't trigger a rerun
|
||||
* if (untrack(() => url.pathname === '/')) {
|
||||
* return { message: 'Welcome!' };
|
||||
* }
|
||||
* }
|
||||
* ```
|
||||
*/
|
||||
untrack: <T>(fn: () => T) => T;
|
||||
|
||||
/**
|
||||
* Access to spans for tracing. If tracing is not enabled or the function is being run in the browser, these spans will do nothing.
|
||||
* @since 2.31.0
|
||||
*/
|
||||
tracing: {
|
||||
/** Whether tracing is enabled. */
|
||||
enabled: boolean;
|
||||
/** The root span for the request. This span is named `sveltekit.handle.root`. */
|
||||
root: Span;
|
||||
/** The span associated with the current `load` function. */
|
||||
current: Span;
|
||||
};
|
||||
}
|
||||
|
||||
export interface NavigationEvent<
|
||||
Params extends AppLayoutParams<'/'> = AppLayoutParams<'/'>,
|
||||
RouteId extends AppRouteId | null = AppRouteId | null
|
||||
> {
|
||||
/**
|
||||
* The parameters of the current page - e.g. for a route like `/blog/[slug]`, a `{ slug: string }` object
|
||||
*/
|
||||
params: Params;
|
||||
/**
|
||||
* Info about the current route
|
||||
*/
|
||||
route: {
|
||||
/**
|
||||
* The ID of the current route - e.g. for `src/routes/blog/[slug]`, it would be `/blog/[slug]`. It is `null` when no route is matched.
|
||||
*/
|
||||
id: RouteId;
|
||||
};
|
||||
/**
|
||||
* The URL of the current page
|
||||
*/
|
||||
url: URL;
|
||||
}
|
||||
|
||||
export interface RequestEvent<
|
||||
Params extends AppLayoutParams<'/'> = AppLayoutParams<'/'>,
|
||||
RouteId extends AppRouteId | null = AppRouteId | null
|
||||
> {
|
||||
/**
|
||||
* Get or set cookies related to the current request
|
||||
*/
|
||||
readonly cookies: Cookies;
|
||||
/**
|
||||
* `fetch` is equivalent to the [native `fetch` web API](https://developer.mozilla.org/en-US/docs/Web/API/fetch), with a few additional features:
|
||||
*
|
||||
* - It can be used to make credentialed requests on the server, as it inherits the `cookie` and `authorization` headers for the page request.
|
||||
* - It can make relative requests on the server (ordinarily, `fetch` requires a URL with an origin when used in a server context).
|
||||
* - Internal requests (e.g. for `+server.js` routes) go directly to the handler function when running on the server, without the overhead of an HTTP call.
|
||||
* - During server-side rendering, the response will be captured and inlined into the rendered HTML by hooking into the `text` and `json` methods of the `Response` object. Note that headers will _not_ be serialized, unless explicitly included via [`filterSerializedResponseHeaders`](https://svelte.dev/docs/kit/hooks#handle)
|
||||
* - During hydration, the response will be read from the HTML, guaranteeing consistency and preventing an additional network request.
|
||||
*
|
||||
* You can learn more about making credentialed requests with cookies [here](https://svelte.dev/docs/kit/load#Cookies).
|
||||
*/
|
||||
readonly fetch: typeof fetch;
|
||||
/**
|
||||
* The client's IP address, set by the adapter.
|
||||
*/
|
||||
readonly getClientAddress: () => string;
|
||||
/**
|
||||
* Contains custom data that was added to the request within the [`server handle hook`](https://svelte.dev/docs/kit/hooks#handle).
|
||||
*/
|
||||
readonly locals: App.Locals;
|
||||
/**
|
||||
* The parameters of the current route - e.g. for a route like `/blog/[slug]`, a `{ slug: string }` object.
|
||||
*
|
||||
* Inside `query` functions (including `query.batch` and `query.live`), accessing this property throws an error.
|
||||
* Pass values from the page as arguments to the query instead. Inside `form` and `command` functions it relates to the page
|
||||
* the remote function was called from, _not_ the URL of the endpoint SvelteKit creates for the remote function. Never use it
|
||||
* to determine whether or not a user is authorized to access certain data, as these values are part of the request which could be manipulated.
|
||||
*/
|
||||
readonly params: Params;
|
||||
/**
|
||||
* Additional data made available through the adapter.
|
||||
*/
|
||||
readonly platform: Readonly<App.Platform> | undefined;
|
||||
/**
|
||||
* The original request object.
|
||||
*/
|
||||
readonly request: Request;
|
||||
/**
|
||||
* Info about the current route.
|
||||
*/
|
||||
readonly route: {
|
||||
/**
|
||||
* The ID of the current route - e.g. for `src/routes/blog/[slug]`, it would be `/blog/[slug]`. It is `null` when no route is matched.
|
||||
*
|
||||
* Inside `query` functions (including `query.batch` and `query.live`), accessing this property throws an error.
|
||||
* Pass values from the page as arguments to the query instead. Inside `form` and `command` functions it relates to the page
|
||||
* the remote function was called from, _not_ the URL of the endpoint SvelteKit creates for the remote function. Never use it
|
||||
* to determine whether or not a user is authorized to access certain data, as these values are part of the request which could be manipulated.
|
||||
*/
|
||||
id: RouteId;
|
||||
};
|
||||
/**
|
||||
* If you need to set headers for the response, you can do so using the this method. This is useful if you want the page to be cached, for example:
|
||||
*
|
||||
* ```js
|
||||
* /// file: src/routes/blog/+page.js
|
||||
* export async function load({ fetch, setHeaders }) {
|
||||
* const url = `https://cms.example.com/articles.json`;
|
||||
* const response = await fetch(url);
|
||||
*
|
||||
* setHeaders({
|
||||
* age: response.headers.get('age'),
|
||||
* 'cache-control': response.headers.get('cache-control')
|
||||
* });
|
||||
*
|
||||
* return response.json();
|
||||
* }
|
||||
* ```
|
||||
*
|
||||
* Setting the same header multiple times (even in separate `load` functions) is an error — you can only set a given header once.
|
||||
*
|
||||
* You cannot add a `set-cookie` header with `setHeaders` — use the [`cookies`](https://svelte.dev/docs/kit/@sveltejs-kit#Cookies) API instead.
|
||||
*/
|
||||
readonly setHeaders: (headers: Record<string, string>) => void;
|
||||
/**
|
||||
* The requested URL.
|
||||
*
|
||||
* Inside `query` functions (including `query.batch` and `query.live`), accessing this property throws an error.
|
||||
* Pass values from the page as arguments to the query instead. Inside `form` and `command` functions it relates to the page
|
||||
* the remote function was called from, _not_ the URL of the endpoint SvelteKit creates for the remote function. Never use it
|
||||
* to determine whether or not a user is authorized to access certain data, as these values are part of the request which could be manipulated.
|
||||
*/
|
||||
readonly url: URL;
|
||||
/**
|
||||
* `true` if the request comes from the client asking for `+page/layout.server.js` data. The `url` property will be stripped of the internal information
|
||||
* related to the data request in this case. Use this property instead if the distinction is important to you.
|
||||
*/
|
||||
readonly isDataRequest: boolean;
|
||||
/**
|
||||
* `true` for `+server.js` calls coming from SvelteKit without the overhead of actually making an HTTP request. This happens when you make same-origin `fetch` requests on the server.
|
||||
*/
|
||||
readonly isSubRequest: boolean;
|
||||
|
||||
/**
|
||||
* Access to spans for tracing. If tracing is not enabled, these spans will do nothing.
|
||||
* @since 2.31.0
|
||||
*/
|
||||
readonly tracing: {
|
||||
/** Whether tracing is enabled. */
|
||||
enabled: boolean;
|
||||
/** The root span for the request. This span is named `sveltekit.handle.root`. */
|
||||
root: Span;
|
||||
/** The span associated with the current `handle` hook, `load` function, form action, or `+server` handler. */
|
||||
current: Span;
|
||||
};
|
||||
|
||||
/**
|
||||
* `true` if the request comes from the client via a remote function. The `url` property will be stripped of the internal information
|
||||
* related to the data request in this case. Use this property instead if the distinction is important to you.
|
||||
*/
|
||||
readonly isRemoteRequest: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* A `(event: RequestEvent) => Response` function exported from a `+server.js` file that corresponds to an HTTP verb (`GET`, `PUT`, `PATCH`, etc) and handles requests with that method.
|
||||
*
|
||||
* It receives `Params` as the first generic argument, which you can skip by using [generated types](https://svelte.dev/docs/kit/types#Generated-types) instead.
|
||||
*/
|
||||
export type RequestHandler<
|
||||
Params extends AppLayoutParams<'/'> = AppLayoutParams<'/'>,
|
||||
RouteId extends AppRouteId | null = AppRouteId | null
|
||||
> = (event: RequestEvent<Params, RouteId>) => MaybePromise<Response>;
|
||||
|
||||
export interface RouteDefinition<Config = any> {
|
||||
id: string;
|
||||
api: {
|
||||
methods: Array<HttpMethod | '*'>;
|
||||
};
|
||||
page: {
|
||||
methods: Array<Extract<HttpMethod, 'GET' | 'POST'>>;
|
||||
};
|
||||
pattern: RegExp;
|
||||
prerender: PrerenderOption;
|
||||
segments: RouteSegment[];
|
||||
methods: Array<HttpMethod | '*'>;
|
||||
config: Config;
|
||||
}
|
||||
|
||||
export interface Server {
|
||||
init(options: ServerInitOptions): Promise<void>;
|
||||
respond(request: Request, options: RequestOptions): Promise<Response>;
|
||||
}
|
||||
|
||||
export interface ServerInitOptions {
|
||||
/** A map of environment variables. */
|
||||
env: Record<string, string | undefined>;
|
||||
/** A function that turns an asset filename into a `ReadableStream`. Required for the `read` export from `$app/server` to work. */
|
||||
read?: (file: string) => MaybePromise<ReadableStream | null>;
|
||||
}
|
||||
|
||||
/**
|
||||
* The generic form of `PageServerLoad` and `LayoutServerLoad`. You should import those from `./$types` (see [generated types](https://svelte.dev/docs/kit/types#Generated-types))
|
||||
* rather than using `ServerLoad` directly.
|
||||
*/
|
||||
export type ServerLoad<
|
||||
Params extends AppLayoutParams<'/'> = AppLayoutParams<'/'>,
|
||||
ParentData extends Record<string, any> = Record<string, any>,
|
||||
OutputData extends Record<string, any> | void = Record<string, any> | void,
|
||||
RouteId extends AppRouteId | null = AppRouteId | null
|
||||
> = (event: ServerLoadEvent<Params, ParentData, RouteId>) => MaybePromise<OutputData>;
|
||||
|
||||
export interface ServerLoadEvent<
|
||||
Params extends AppLayoutParams<'/'> = AppLayoutParams<'/'>,
|
||||
ParentData extends Record<string, any> = Record<string, any>,
|
||||
RouteId extends AppRouteId | null = AppRouteId | null
|
||||
> extends RequestEvent<Params, RouteId> {
|
||||
/**
|
||||
* `await parent()` returns data from parent `+layout.server.js` `load` functions.
|
||||
*
|
||||
* Be careful not to introduce accidental waterfalls when using `await parent()`. If for example you only want to merge parent data into the returned output, call it _after_ fetching your other data.
|
||||
*/
|
||||
parent: () => Promise<ParentData>;
|
||||
/**
|
||||
* This function declares that the `load` function has a _dependency_ on one or more URLs or custom identifiers, which can subsequently be used with [`invalidate()`](https://svelte.dev/docs/kit/$app-navigation#invalidate) to cause `load` to rerun.
|
||||
*
|
||||
* Most of the time you won't need this, as `fetch` calls `depends` on your behalf — it's only necessary if you're using a custom API client that bypasses `fetch`.
|
||||
*
|
||||
* URLs can be absolute or relative to the page being loaded, and must be [encoded](https://developer.mozilla.org/en-US/docs/Glossary/percent-encoding).
|
||||
*
|
||||
* Custom identifiers have to be prefixed with one or more lowercase letters followed by a colon to conform to the [URI specification](https://www.rfc-editor.org/rfc/rfc3986.html).
|
||||
*
|
||||
* The following example shows how to use `depends` to register a dependency on a custom identifier, which is `invalidate`d after a button click, making the `load` function rerun.
|
||||
*
|
||||
* ```js
|
||||
* /// file: src/routes/+page.js
|
||||
* let count = 0;
|
||||
* export async function load({ depends }) {
|
||||
* depends('increase:count');
|
||||
*
|
||||
* return { count: count++ };
|
||||
* }
|
||||
* ```
|
||||
*
|
||||
* ```html
|
||||
* /// file: src/routes/+page.svelte
|
||||
* <script>
|
||||
* import { invalidate } from '$app/navigation';
|
||||
*
|
||||
* let { data } = $props();
|
||||
*
|
||||
* const increase = async () => {
|
||||
* await invalidate('increase:count');
|
||||
* }
|
||||
* </script>
|
||||
*
|
||||
* <p>{data.count}<p>
|
||||
* <button on:click={increase}>Increase Count</button>
|
||||
* ```
|
||||
*/
|
||||
depends: (...deps: string[]) => void;
|
||||
/**
|
||||
* Use this function to opt out of dependency tracking for everything that is synchronously called within the callback. Example:
|
||||
*
|
||||
* ```js
|
||||
* /// file: src/routes/+page.js
|
||||
* export async function load({ untrack, url }) {
|
||||
* // Untrack url.pathname so that path changes don't trigger a rerun
|
||||
* if (untrack(() => url.pathname === '/')) {
|
||||
* return { message: 'Welcome!' };
|
||||
* }
|
||||
* }
|
||||
* ```
|
||||
*/
|
||||
untrack: <T>(fn: () => T) => T;
|
||||
|
||||
/**
|
||||
* Access to spans for tracing. If tracing is not enabled, these spans will do nothing.
|
||||
* @since 2.31.0
|
||||
*/
|
||||
tracing: {
|
||||
/** Whether tracing is enabled. */
|
||||
enabled: boolean;
|
||||
/** The root span for the request. This span is named `sveltekit.handle.root`. */
|
||||
root: Span;
|
||||
/** The span associated with the current server `load` function. */
|
||||
current: Span;
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Shape of a form action method that is part of `export const actions = {...}` in `+page.server.js`.
|
||||
* See [form actions](https://svelte.dev/docs/kit/form-actions) for more information.
|
||||
*/
|
||||
export type Action<
|
||||
Params extends AppLayoutParams<'/'> = AppLayoutParams<'/'>,
|
||||
OutputData extends Record<string, any> | void = Record<string, any> | void,
|
||||
RouteId extends AppRouteId | null = AppRouteId | null
|
||||
> = (event: RequestEvent<Params, RouteId>) => MaybePromise<OutputData>;
|
||||
|
||||
/**
|
||||
* Shape of the `export const actions = {...}` object in `+page.server.js`.
|
||||
* See [form actions](https://svelte.dev/docs/kit/form-actions) for more information.
|
||||
*/
|
||||
export type Actions<
|
||||
Params extends AppLayoutParams<'/'> = AppLayoutParams<'/'>,
|
||||
OutputData extends Record<string, any> | void = Record<string, any> | void,
|
||||
RouteId extends AppRouteId | null = AppRouteId | null
|
||||
> = Record<string, Action<Params, OutputData, RouteId>>;
|
||||
|
||||
/**
|
||||
* The object returned by the [`error`](https://svelte.dev/docs/kit/@sveltejs-kit#error) function.
|
||||
*/
|
||||
export interface HttpError {
|
||||
/** The [HTTP status code](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status#client_error_responses), in the range 400-599. */
|
||||
status: number;
|
||||
/** The content of the error. */
|
||||
body: App.Error;
|
||||
}
|
||||
|
||||
/**
|
||||
* The object returned by the [`redirect`](https://svelte.dev/docs/kit/@sveltejs-kit#redirect) function.
|
||||
*/
|
||||
export interface Redirect {
|
||||
/** The [HTTP status code](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status#redirection_messages), in the range 300-308. */
|
||||
status: 300 | 301 | 302 | 303 | 304 | 305 | 306 | 307 | 308;
|
||||
/** The location to redirect to. */
|
||||
location: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* The type of `export const snapshot` exported from a page or layout component.
|
||||
* @deprecated Use the [`snapshot`](https://svelte.dev/docs/kit/$app-navigation#snapshot) helper from `$app/navigation` instead.
|
||||
*/
|
||||
export interface Snapshot<T = any> {
|
||||
capture: () => T;
|
||||
restore: (snapshot: T) => void;
|
||||
}
|
||||
|
||||
export * from './index.js';
|
||||
68
node_modules/@sveltejs/kit/src/exports/url.js
generated
vendored
Normal file
68
node_modules/@sveltejs/kit/src/exports/url.js
generated
vendored
Normal file
@@ -0,0 +1,68 @@
|
||||
// we use the export subpath to conditionally import the client/server `get_origin`
|
||||
// so that `node:async_hooks` isn't pulled into the client build
|
||||
import { get_origin } from '#internal';
|
||||
import { matches_external_allowlist_entry } from '../utils/url.js';
|
||||
import * as e from '../messages/shared-errors.js';
|
||||
|
||||
// See https://datatracker.ietf.org/doc/html/rfc2606 - no domains under the .invalid TLD can be registered
|
||||
const REDIRECT_BASE = 'https://sveltekit-redirect.invalid';
|
||||
|
||||
/**
|
||||
* Whether a redirect location is absolute, i.e. not a root-relative or path-relative URL,
|
||||
* and not pointing to the same origin as we're currently on (if determineable).
|
||||
* @param {string} location
|
||||
*/
|
||||
export function is_external_location(location) {
|
||||
const origin = get_origin();
|
||||
|
||||
try {
|
||||
return !matches_external_allowlist_entry(location, origin ?? REDIRECT_BASE);
|
||||
} catch {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
const javascript_protocols = new Set(['javascript:', 'data:']);
|
||||
|
||||
/**
|
||||
* @param {string} location
|
||||
*/
|
||||
function is_javascript_location(location) {
|
||||
try {
|
||||
return javascript_protocols.has(new URL(location, REDIRECT_BASE).protocol);
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {string} location
|
||||
* @param {{ external?: boolean | string[] }} [options]
|
||||
*/
|
||||
export function validate_redirect_location(location, options) {
|
||||
if (!is_external_location(location)) return;
|
||||
|
||||
const external = options?.external;
|
||||
|
||||
if (!external) {
|
||||
e.redirect_external_not_allowed({ location: JSON.stringify(location) });
|
||||
}
|
||||
|
||||
if (external === true) {
|
||||
if (is_javascript_location(location)) {
|
||||
e.redirect_external_javascript({ location: JSON.stringify(location) });
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
if (Array.isArray(external)) {
|
||||
if (!external.some((allowed) => matches_external_allowlist_entry(location, allowed))) {
|
||||
e.redirect_external_not_in_allowlist({ location: JSON.stringify(location) });
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
e.redirect_external_option_invalid();
|
||||
}
|
||||
279
node_modules/@sveltejs/kit/src/exports/vite/build/build_server.js
generated
vendored
Normal file
279
node_modules/@sveltejs/kit/src/exports/vite/build/build_server.js
generated
vendored
Normal file
@@ -0,0 +1,279 @@
|
||||
/** @import { AssetDependencies, ManifestData, ValidatedConfig } from 'types' */
|
||||
/** @import { Manifest, Rolldown } from 'vite' */
|
||||
import fs from 'node:fs';
|
||||
import {
|
||||
create_function_as_string,
|
||||
filter_fonts,
|
||||
find_deps,
|
||||
generate_placeholder,
|
||||
resolve_symlinks
|
||||
} from './utils.js';
|
||||
import { s } from '../../../utils/misc.js';
|
||||
import { normalizePath } from 'vite';
|
||||
import { basename } from 'node:path';
|
||||
import { fix_css_urls } from '../../../utils/css.js';
|
||||
import { escape_for_interpolation } from '../../../utils/escape.js';
|
||||
|
||||
/**
|
||||
* @param {string} out
|
||||
* @param {ValidatedConfig} kit
|
||||
* @param {ManifestData} manifest_data
|
||||
* @param {Manifest} server_manifest
|
||||
* @param {Manifest | null} client_manifest
|
||||
* @param {string} assets_path
|
||||
* @param {(Rolldown.OutputAsset | Rolldown.OutputChunk)[]} chunks
|
||||
* @param {string} root
|
||||
* @returns {void}
|
||||
*/
|
||||
export function build_server_nodes(
|
||||
out,
|
||||
kit,
|
||||
manifest_data,
|
||||
server_manifest,
|
||||
client_manifest,
|
||||
assets_path,
|
||||
chunks,
|
||||
root
|
||||
) {
|
||||
fs.mkdirSync(`${out}/server/nodes`, { recursive: true });
|
||||
fs.mkdirSync(`${out}/server/stylesheets`, { recursive: true });
|
||||
|
||||
/**
|
||||
* Stylesheet names and their contents which are below the inline threshold
|
||||
* @type {Map<string, string>}
|
||||
*/
|
||||
const stylesheets_to_inline = new Map();
|
||||
|
||||
/**
|
||||
* For CSS inlining, we either store a string or a function that returns the
|
||||
* styles with the correct relative URLs
|
||||
* @type {(css: string, eager_assets: Set<string>) => string}
|
||||
*/
|
||||
let prepare_css_for_inlining = (css) => s(css);
|
||||
|
||||
if (chunks && kit.inlineStyleThreshold > 0 && kit.output.bundleStrategy === 'split') {
|
||||
for (const chunk of chunks) {
|
||||
if (chunk.type !== 'asset' || !chunk.fileName.endsWith('.css')) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const source = chunk.source.toString();
|
||||
if (source.length < kit.inlineStyleThreshold) {
|
||||
stylesheets_to_inline.set(chunk.fileName, source);
|
||||
}
|
||||
}
|
||||
|
||||
// If the client CSS has URL references to assets, we need to adjust the
|
||||
// relative path so that they are correct when inlined into the document.
|
||||
// Although `paths.assets` is static, we need to pass in a fake path
|
||||
// `/_svelte_kit_assets` at runtime when running `vite preview`
|
||||
if (kit.paths.assets || kit.paths.relative) {
|
||||
const static_assets = new Set(
|
||||
manifest_data.assets.map((asset) => decodeURIComponent(asset.file))
|
||||
);
|
||||
|
||||
const segments = /** @type {string} */ (assets_path).split('/');
|
||||
const static_asset_prefix = segments.map(() => '..').join('/') + '/';
|
||||
|
||||
prepare_css_for_inlining = (css, eager_assets) => {
|
||||
const assets_placeholder = generate_placeholder(css, 'ASSETS');
|
||||
const base_placeholder = generate_placeholder(css, 'BASE');
|
||||
|
||||
const transformed_css = fix_css_urls({
|
||||
css,
|
||||
vite_assets: eager_assets,
|
||||
static_assets,
|
||||
paths_assets: assets_placeholder,
|
||||
base: base_placeholder,
|
||||
static_asset_prefix
|
||||
});
|
||||
|
||||
// only convert to a function if we have adjusted any URLs
|
||||
if (css !== transformed_css) {
|
||||
const escaped = escape_for_interpolation(transformed_css, [
|
||||
{
|
||||
placeholder: assets_placeholder,
|
||||
replacement: '${assets}'
|
||||
},
|
||||
{
|
||||
placeholder: base_placeholder,
|
||||
replacement: '${base}'
|
||||
}
|
||||
]);
|
||||
return create_function_as_string('css', ['assets', 'base'], escaped);
|
||||
}
|
||||
|
||||
return s(css);
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/** path to the `.svelte-kit` directory */
|
||||
const out_dir = normalizePath(kit.outDir);
|
||||
|
||||
for (let i = 0; i < manifest_data.nodes.length; i++) {
|
||||
const node = manifest_data.nodes[i];
|
||||
|
||||
/** @type {string[]} */
|
||||
const imports = [];
|
||||
|
||||
// String representation of
|
||||
/* @type {SSRNode} */
|
||||
/** @type {string[]} */
|
||||
const exports = [`export const index = ${i};`];
|
||||
|
||||
/** @type {string[]} */
|
||||
let imported = [];
|
||||
|
||||
/** @type {string[]} */
|
||||
let stylesheets = [];
|
||||
|
||||
/** @type {import('types').FontDependency[]} */
|
||||
let fonts = [];
|
||||
|
||||
/** @type {Set<string>} */
|
||||
const eager_assets = new Set();
|
||||
|
||||
const uses_server_component = node.child_pages
|
||||
? node.child_pages.some((child) => child.page_options?.ssr !== false)
|
||||
: node.page_options?.ssr !== false;
|
||||
|
||||
if (node.component && uses_server_component) {
|
||||
exports.push(
|
||||
'let component_cache;',
|
||||
`export const component = async () => component_cache ??= (await import('../${
|
||||
resolve_symlinks(server_manifest, node.component, root).chunk.file
|
||||
}')).default;`
|
||||
);
|
||||
}
|
||||
|
||||
if (node.universal) {
|
||||
if (
|
||||
(kit.router.type === 'hash' &&
|
||||
node.page_options !== null &&
|
||||
node.page_options?.ssr === undefined) ||
|
||||
(node.page_options && node.page_options.ssr === false)
|
||||
) {
|
||||
exports.push(`export const universal = ${s(node.page_options, null, 2)};`);
|
||||
} else {
|
||||
imports.push(
|
||||
`import * as universal from '../${resolve_symlinks(server_manifest, node.universal, root).chunk.file}';`
|
||||
);
|
||||
// TODO: when building for analysis, explain why the file was loaded on the server if we fail to load it
|
||||
exports.push('export { universal };');
|
||||
}
|
||||
exports.push(`export const universal_id = ${s(node.universal)};`);
|
||||
}
|
||||
|
||||
if (node.server) {
|
||||
imports.push(
|
||||
`import * as server from '../${resolve_symlinks(server_manifest, node.server, root).chunk.file}';`
|
||||
);
|
||||
exports.push('export { server };');
|
||||
exports.push(`export const server_id = ${s(node.server)};`);
|
||||
}
|
||||
|
||||
if ((node.universal || node.component) && kit.output.bundleStrategy === 'split') {
|
||||
/** @type {AssetDependencies | undefined} */
|
||||
let component;
|
||||
if (node.component) {
|
||||
component = find_deps(server_manifest, node.component, true, root);
|
||||
}
|
||||
|
||||
/** @type {AssetDependencies | undefined} */
|
||||
let universal;
|
||||
if (node.universal) {
|
||||
universal = find_deps(server_manifest, node.universal, true, root);
|
||||
}
|
||||
|
||||
if (client_manifest) {
|
||||
const entry_path = `${out_dir}/generated/build/client-optimized/nodes/${i}.js`;
|
||||
const entry = find_deps(client_manifest, entry_path, true, root);
|
||||
|
||||
// Eagerly load client stylesheets and fonts imported by the SSR-ed page to avoid FOUC.
|
||||
// However, if it is not used during SSR (not present in the server manifest),
|
||||
// then it can be lazily loaded in the browser.
|
||||
|
||||
/** @type {Set<string>} */
|
||||
const eager_css = new Set();
|
||||
|
||||
entry.stylesheet_map.forEach((value, filepath) => {
|
||||
// pages and layouts are renamed to node indexes when optimised for the client
|
||||
// so we use the original filename instead to check against the server manifest
|
||||
if (filepath === entry_path) {
|
||||
filepath = node.component ?? filepath;
|
||||
}
|
||||
|
||||
if (component?.stylesheet_map.has(filepath) || universal?.stylesheet_map.has(filepath)) {
|
||||
value.css.forEach((file) => eager_css.add(file));
|
||||
value.assets.forEach((file) => eager_assets.add(file));
|
||||
}
|
||||
});
|
||||
|
||||
imported = entry.imports;
|
||||
stylesheets = Array.from(eager_css);
|
||||
fonts = filter_fonts(Array.from(eager_assets), client_manifest, root);
|
||||
} else {
|
||||
for (const entry of [component, universal]) {
|
||||
if (!entry) continue;
|
||||
imported.push(...entry.imports);
|
||||
stylesheets.push(...entry.stylesheets);
|
||||
fonts.push(...entry.fonts);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
exports.push(
|
||||
`export const imports = ${s(imported)};`,
|
||||
`export const stylesheets = ${s(stylesheets)};`,
|
||||
`export const fonts = ${s(fonts)};`
|
||||
);
|
||||
|
||||
/**
|
||||
* Assets that have been processed by Vite (decoded and with the asset path stripped)
|
||||
* @type {Set<string>}
|
||||
*/
|
||||
let vite_assets = new Set();
|
||||
|
||||
// Keep track of Vite asset filenames so that we avoid touching unrelated ones
|
||||
// when adjusting the inlined CSS
|
||||
if (stylesheets_to_inline.size && eager_assets.size) {
|
||||
vite_assets = new Set(
|
||||
Array.from(eager_assets).map((asset) => {
|
||||
return decodeURIComponent(asset.replace(`${assets_path}/`, ''));
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
if (stylesheets_to_inline.size) {
|
||||
/** @type {string[]} */
|
||||
const inline_styles = [];
|
||||
|
||||
stylesheets.forEach((file, i) => {
|
||||
if (stylesheets_to_inline.has(file)) {
|
||||
const filename = basename(file);
|
||||
const dest = `${out}/server/stylesheets/${filename}.js`;
|
||||
|
||||
const css = /** @type {string} */ (stylesheets_to_inline.get(file));
|
||||
|
||||
fs.writeFileSync(
|
||||
dest,
|
||||
`// ${filename}\nexport default ${prepare_css_for_inlining(css, vite_assets)};`
|
||||
);
|
||||
const name = `stylesheet_${i}`;
|
||||
imports.push(`import ${name} from '../stylesheets/${filename}.js';`);
|
||||
inline_styles.push(`\t${s(file)}: ${name}`);
|
||||
}
|
||||
});
|
||||
|
||||
if (inline_styles.length > 0) {
|
||||
exports.push(`export const inline_styles = () => ({\n${inline_styles.join(',\n')}\n});`);
|
||||
}
|
||||
}
|
||||
|
||||
fs.writeFileSync(
|
||||
`${out}/server/nodes/${i}.js`,
|
||||
`${imports.join('\n')}\n\n${exports.join('\n')}\n`
|
||||
);
|
||||
}
|
||||
}
|
||||
1169
node_modules/@sveltejs/kit/src/exports/vite/build/index.js
generated
vendored
Normal file
1169
node_modules/@sveltejs/kit/src/exports/vite/build/index.js
generated
vendored
Normal file
File diff suppressed because it is too large
Load Diff
137
node_modules/@sveltejs/kit/src/exports/vite/build/remote.js
generated
vendored
Normal file
137
node_modules/@sveltejs/kit/src/exports/vite/build/remote.js
generated
vendored
Normal file
@@ -0,0 +1,137 @@
|
||||
/** @import { ServerMetadata } from 'types' */
|
||||
/** @import { Rolldown } from 'vite' */
|
||||
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import MagicString from 'magic-string';
|
||||
import { posixify } from '../../../utils/os.js';
|
||||
import * as e from '../../../messages/build-errors.js';
|
||||
import { capture_message } from '../../../messages/internal/build.js';
|
||||
|
||||
/**
|
||||
* @param {typeof import('vite')} vite
|
||||
* @param {string} out
|
||||
* @param {Array<{ hash: string, file: string }>} remotes
|
||||
* @param {Map<string, string>} remote_original_by_hash
|
||||
* @param {ServerMetadata} metadata
|
||||
* @param {string} cwd
|
||||
* @param {(Rolldown.OutputAsset | Rolldown.OutputChunk)[]} server_chunks
|
||||
* @param {NonNullable<import('vitest/config').ViteUserConfig['build']>['sourcemap']} sourcemap
|
||||
*/
|
||||
export async function treeshake_prerendered_remotes(
|
||||
vite,
|
||||
out,
|
||||
remotes,
|
||||
remote_original_by_hash,
|
||||
metadata,
|
||||
cwd,
|
||||
server_chunks,
|
||||
sourcemap
|
||||
) {
|
||||
if (remotes.length === 0) return;
|
||||
|
||||
/** @type {string[]} */
|
||||
const chunk_paths = [];
|
||||
|
||||
// embedded in the server bundle, which only runs on the server, so the full text is kept
|
||||
const not_dynamic_message = JSON.stringify(
|
||||
capture_message(() => e.remote_prerender_not_dynamic())
|
||||
);
|
||||
|
||||
for (const remote of remotes) {
|
||||
const exports_map = metadata.remotes.get(remote.hash);
|
||||
if (!exports_map) continue;
|
||||
|
||||
/** @type {string[]} */
|
||||
const dynamic = [];
|
||||
/** @type {string[]} */
|
||||
const prerendered = [];
|
||||
|
||||
for (const [name, value] of exports_map) {
|
||||
(value.dynamic ? dynamic : prerendered).push(name);
|
||||
}
|
||||
|
||||
if (prerendered.length === 0) continue; // nothing to treeshake
|
||||
|
||||
const original_id = remote_original_by_hash.get(remote.hash);
|
||||
if (!original_id) continue;
|
||||
|
||||
const remote_chunk = server_chunks.find((chunk) => {
|
||||
return chunk.type === 'chunk' && chunk.moduleIds.includes(original_id);
|
||||
});
|
||||
|
||||
if (!remote_chunk) continue;
|
||||
|
||||
const chunk_path = posixify(path.relative(cwd, `${out}/server/${remote_chunk.fileName}`));
|
||||
|
||||
const code = fs.readFileSync(chunk_path, 'utf-8');
|
||||
const parsed = vite.parseSync(chunk_path, code);
|
||||
if (parsed.errors.length) throw new Error(parsed.errors[0].message);
|
||||
const modified_code = new MagicString(code);
|
||||
|
||||
for (const fn of prerendered) {
|
||||
for (const node of parsed.program.body) {
|
||||
const declaration =
|
||||
node.type === 'ExportNamedDeclaration'
|
||||
? node.declaration
|
||||
: node.type === 'VariableDeclaration'
|
||||
? node
|
||||
: null;
|
||||
|
||||
if (!declaration || declaration.type !== 'VariableDeclaration') continue;
|
||||
|
||||
for (const declarator of declaration.declarations) {
|
||||
if (declarator.id.type === 'Identifier' && declarator.id.name === fn) {
|
||||
modified_code.overwrite(
|
||||
node.start,
|
||||
node.end,
|
||||
`const ${fn} = prerender('unchecked', () => { throw new Error(${not_dynamic_message}) });`
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for (const node of parsed.program.body) {
|
||||
if (node.type === 'ExportDefaultDeclaration') {
|
||||
modified_code.remove(node.start, node.end);
|
||||
}
|
||||
}
|
||||
|
||||
const stubbed = modified_code.toString();
|
||||
fs.writeFileSync(chunk_path, stubbed);
|
||||
chunk_paths.push(chunk_path);
|
||||
}
|
||||
|
||||
if (!chunk_paths.length) return;
|
||||
|
||||
for (const chunk_path of chunk_paths) {
|
||||
const bundle = /** @type {Rolldown.RolldownOutput} */ (
|
||||
await vite.build({
|
||||
configFile: false,
|
||||
build: {
|
||||
write: false,
|
||||
ssr: true,
|
||||
target: 'esnext',
|
||||
sourcemap,
|
||||
rolldownOptions: {
|
||||
// avoid resolving imports
|
||||
external: (id) => !id.endsWith(chunk_path),
|
||||
input: {
|
||||
treeshaken: chunk_path
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
);
|
||||
|
||||
// the only possible outputs are the treeshaken chunk and, with sourcemaps, its map
|
||||
for (const output of bundle.output) {
|
||||
if (output.type === 'chunk') {
|
||||
fs.writeFileSync(chunk_path, output.code);
|
||||
} else {
|
||||
fs.writeFileSync(chunk_path + '.map', output.source);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
99
node_modules/@sveltejs/kit/src/exports/vite/build/service-worker.js
generated
vendored
Normal file
99
node_modules/@sveltejs/kit/src/exports/vite/build/service-worker.js
generated
vendored
Normal file
@@ -0,0 +1,99 @@
|
||||
/** @import { ValidatedConfig } from 'types' */
|
||||
/** @import { Plugin, UserConfig } from 'vite' */
|
||||
import { runtime_directory } from '../../../core/utils.js';
|
||||
import { warn_overridden_config } from '../utils.js';
|
||||
import * as e from '../../../messages/build-errors.js';
|
||||
|
||||
/**
|
||||
* @param {ValidatedConfig} kit
|
||||
* @param {() => { service_worker_entry_file: string | null; kit_global: string; out: string; initial_config: UserConfig; }} get_config
|
||||
* @returns {Plugin}
|
||||
*/
|
||||
export function plugin_service_worker_build(kit, get_config) {
|
||||
return {
|
||||
name: 'vite-plugin-sveltekit-service-worker',
|
||||
|
||||
config(config) {
|
||||
const { service_worker_entry_file, kit_global, out, initial_config } = get_config();
|
||||
|
||||
if (!service_worker_entry_file) return;
|
||||
|
||||
if (kit.paths.assets) {
|
||||
e.service_worker_assets();
|
||||
}
|
||||
|
||||
const user_service_worker_output_config =
|
||||
config.environments?.serviceWorker?.build?.rolldownOptions?.output;
|
||||
|
||||
/** @type {UserConfig} */
|
||||
const new_config = {
|
||||
environments: {
|
||||
serviceWorker: {
|
||||
define: {
|
||||
__SVELTEKIT_PAYLOAD__: kit_global
|
||||
},
|
||||
build: {
|
||||
modulePreload: false,
|
||||
rolldownOptions: {
|
||||
external: [`${kit.paths.base}/${kit.appDir}/env.js`],
|
||||
input: {
|
||||
'service-worker': service_worker_entry_file
|
||||
},
|
||||
output: {
|
||||
format: 'es',
|
||||
entryFileNames: 'service-worker.js',
|
||||
assetFileNames: `${kit.appDir}/immutable/assets/[name].[hash][extname]`,
|
||||
codeSplitting:
|
||||
(Array.isArray(user_service_worker_output_config)
|
||||
? user_service_worker_output_config[0].codeSplitting
|
||||
: user_service_worker_output_config?.codeSplitting) ?? false
|
||||
}
|
||||
},
|
||||
outDir: `${out}/client`,
|
||||
minify: initial_config.build?.minify,
|
||||
// avoid overwriting the client build Vite manifest
|
||||
manifest: '.vite/service-worker-manifest.json'
|
||||
},
|
||||
consumer: 'client'
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
warn_overridden_config(config, new_config);
|
||||
|
||||
return new_config;
|
||||
},
|
||||
|
||||
// our serviceWorker environment only exists when building because Vite only
|
||||
// supports the default client environment during development (for now)
|
||||
applyToEnvironment(environment) {
|
||||
return environment.name === 'serviceWorker';
|
||||
},
|
||||
|
||||
generateBundle(_, bundle) {
|
||||
const invalid_modules = new Set();
|
||||
const modules = new Map([
|
||||
[`${runtime_directory}/app/forms/index.js`, '$app/forms'],
|
||||
[`${runtime_directory}/app/navigation/index.js`, '$app/navigation'],
|
||||
[`${runtime_directory}/app/state/index.js`, '$app/state']
|
||||
]);
|
||||
|
||||
for (const output of Object.values(bundle)) {
|
||||
if (output.type !== 'chunk') continue;
|
||||
|
||||
for (const id of output.moduleIds) {
|
||||
const module = modules.get(id);
|
||||
if (module) invalid_modules.add(module);
|
||||
}
|
||||
}
|
||||
|
||||
if (invalid_modules.size > 0) {
|
||||
e.service_worker_invalid_import({
|
||||
modules: Array.from(modules.values())
|
||||
.filter((module) => invalid_modules.has(module))
|
||||
.join(', ')
|
||||
});
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
200
node_modules/@sveltejs/kit/src/exports/vite/build/utils.js
generated
vendored
Normal file
200
node_modules/@sveltejs/kit/src/exports/vite/build/utils.js
generated
vendored
Normal file
@@ -0,0 +1,200 @@
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { normalizePath } from 'vite';
|
||||
|
||||
/**
|
||||
* Adds transitive JS and CSS dependencies to the js and css inputs.
|
||||
* @param {import('vite').Manifest} manifest
|
||||
* @param {string} entry
|
||||
* @param {boolean} add_dynamic_css
|
||||
* @param {string} root
|
||||
* @returns {import('types').AssetDependencies}
|
||||
*/
|
||||
export function find_deps(manifest, entry, add_dynamic_css, root) {
|
||||
/** @type {Set<string>} */
|
||||
const seen = new Set();
|
||||
|
||||
/** @type {Set<string>} */
|
||||
const imports = new Set();
|
||||
|
||||
/** @type {Set<string>} */
|
||||
const stylesheets = new Set();
|
||||
|
||||
/** @type {Set<string>} */
|
||||
const imported_assets = new Set();
|
||||
|
||||
/** @type {Map<string, { css: Set<string>; assets: Set<string> }>} */
|
||||
const stylesheet_map = new Map();
|
||||
|
||||
/**
|
||||
* @param {string} current
|
||||
* @param {boolean} add_js
|
||||
* @param {string} initial_importer
|
||||
* @param {number} dynamic_import_depth
|
||||
*/
|
||||
function traverse(current, add_js, initial_importer, dynamic_import_depth) {
|
||||
if (seen.has(current)) return;
|
||||
seen.add(current);
|
||||
|
||||
const { chunk } = resolve_symlinks(manifest, current, root);
|
||||
|
||||
if (add_js) imports.add(chunk.file);
|
||||
|
||||
if (chunk.assets) {
|
||||
chunk.assets.forEach((asset) => imported_assets.add(asset));
|
||||
}
|
||||
|
||||
if (chunk.css) {
|
||||
chunk.css.forEach((file) => stylesheets.add(file));
|
||||
}
|
||||
|
||||
if (chunk.imports) {
|
||||
chunk.imports.forEach((file) =>
|
||||
traverse(file, add_js, initial_importer, dynamic_import_depth)
|
||||
);
|
||||
}
|
||||
|
||||
if (!add_dynamic_css) return;
|
||||
|
||||
if ((chunk.css || chunk.assets) && dynamic_import_depth <= 1) {
|
||||
// group files based on the initial importer because if a file is only ever
|
||||
// a transitive dependency, it doesn't have a suitable name we can map back to
|
||||
// the server manifest
|
||||
if (stylesheet_map.has(initial_importer)) {
|
||||
const { css, assets } = /** @type {{ css: Set<string>; assets: Set<string> }} */ (
|
||||
stylesheet_map.get(initial_importer)
|
||||
);
|
||||
if (chunk.css) chunk.css.forEach((file) => css.add(file));
|
||||
if (chunk.assets) chunk.assets.forEach((file) => assets.add(file));
|
||||
} else {
|
||||
stylesheet_map.set(initial_importer, {
|
||||
css: new Set(chunk.css),
|
||||
assets: new Set(chunk.assets)
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
if (chunk.dynamicImports) {
|
||||
dynamic_import_depth++;
|
||||
chunk.dynamicImports.forEach((file) => {
|
||||
traverse(file, false, file, dynamic_import_depth);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
const { chunk, file } = resolve_symlinks(manifest, entry, root);
|
||||
|
||||
traverse(file, true, entry, 0);
|
||||
|
||||
const assets = Array.from(imported_assets);
|
||||
|
||||
return {
|
||||
assets,
|
||||
file: chunk.file,
|
||||
imports: Array.from(imports),
|
||||
stylesheets: Array.from(stylesheets),
|
||||
// TODO do we need this separately?
|
||||
fonts: filter_fonts(assets, manifest, root),
|
||||
stylesheet_map
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {import('vite').Manifest} manifest
|
||||
* @param {string} file
|
||||
* @param {string} root
|
||||
*/
|
||||
export function resolve_symlinks(manifest, file, root) {
|
||||
while (!manifest[file]) {
|
||||
const next = normalizePath(path.relative(root, fs.realpathSync(file)));
|
||||
if (next === file) throw new Error(`Could not find file "${file}" in Vite manifest`);
|
||||
file = next;
|
||||
}
|
||||
|
||||
const chunk = manifest[file];
|
||||
|
||||
return { chunk, file };
|
||||
}
|
||||
|
||||
/** @type {WeakMap<import('vite').Manifest, Map<string, string>>} */
|
||||
const source_maps = new WeakMap();
|
||||
|
||||
/**
|
||||
* @param {string[]} assets
|
||||
* @param {import('vite').Manifest} manifest
|
||||
* @param {string} root
|
||||
* @returns {import('types').FontDependency[]}
|
||||
*/
|
||||
export function filter_fonts(assets, manifest, root) {
|
||||
let sources = source_maps.get(manifest);
|
||||
|
||||
if (!sources) {
|
||||
sources = new Map();
|
||||
source_maps.set(manifest, sources);
|
||||
|
||||
// identical files are emitted once but can have several sources — keep the first
|
||||
for (const key of Object.keys(manifest).sort()) {
|
||||
const { file, src } = manifest[key];
|
||||
if (src && !sources.has(file)) {
|
||||
sources.set(file, src);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return assets
|
||||
.filter((asset) => /\.(woff2?|ttf|otf)$/.test(asset))
|
||||
.map((file) => {
|
||||
const src = sources.get(file) ?? file;
|
||||
const marker = '/node_modules/';
|
||||
const index = src.lastIndexOf(marker);
|
||||
|
||||
// Vite follows package manager symlinks when generating the manifest. Prefer the
|
||||
// project-local node_modules path when it points to the same file.
|
||||
if (index !== -1) {
|
||||
const filename = `node_modules/${src.slice(index + marker.length)}`;
|
||||
const source = path.resolve(root, src);
|
||||
const unresolved = path.resolve(root, filename);
|
||||
|
||||
if (
|
||||
fs.existsSync(source) &&
|
||||
fs.existsSync(unresolved) &&
|
||||
fs.realpathSync(unresolved) === fs.realpathSync(source)
|
||||
) {
|
||||
return { file, filename };
|
||||
}
|
||||
}
|
||||
|
||||
return { file, filename: normalizePath(path.relative(root, path.resolve(root, src))) };
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Writes a function with arguments used by a template literal.
|
||||
* This helps us store strings in a module and inject values at runtime.
|
||||
* @param {string} name The name of the function
|
||||
* @param {string[]} placeholder_names The names of the placeholders in the string
|
||||
* @param {string} str A string with placeholders such as "Hello ${arg0}".
|
||||
* It must have backslashes, backticks and dollar signs already escaped.
|
||||
* @returns {string} The function written as a string
|
||||
*/
|
||||
export function create_function_as_string(name, placeholder_names, str) {
|
||||
const args = placeholder_names ? placeholder_names.join(', ') : '';
|
||||
return `function ${name}(${args}) { return \`${str}\`; }`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Guarantees that the generated placeholder is not already present in the content.
|
||||
* @param {string} content
|
||||
* @param {string} key
|
||||
* @returns {string}
|
||||
*/
|
||||
export function generate_placeholder(content, key) {
|
||||
let id = 1;
|
||||
let placeholder = `__SVELTEKIT_${key}_${id}__`;
|
||||
|
||||
while (content.includes(placeholder)) {
|
||||
placeholder = `__SVELTEKIT_${key}_${++id}__`;
|
||||
}
|
||||
|
||||
return placeholder;
|
||||
}
|
||||
309
node_modules/@sveltejs/kit/src/exports/vite/dev/generate_manifest.js
generated
vendored
Normal file
309
node_modules/@sveltejs/kit/src/exports/vite/dev/generate_manifest.js
generated
vendored
Normal file
@@ -0,0 +1,309 @@
|
||||
/** @import { EnvironmentModuleNode, ErrorPayload, ViteDevServer } from 'vite' */
|
||||
/** @import { ModuleRunner } from 'vite/module-runner' */
|
||||
/** @import { ManifestData, SSRManifest, SSRNode, RemoteChunk, UniversalNode, ValidatedConfig } from 'types' */
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { get_mime_lookup, get_runtime_base } from '../../../core/utils.js';
|
||||
import { from_fs, to_fs } from '../../../utils/vite.js';
|
||||
import { compact } from '../../../utils/array.js';
|
||||
import * as e from '../../../messages/build-errors.js';
|
||||
import { styleText } from 'node:util';
|
||||
|
||||
// vite-specifc queries that we should skip handling for css urls
|
||||
const vite_css_query_regex = /(?:\?|&)(?:raw|url|inline)(?:&|$)/;
|
||||
|
||||
/**
|
||||
* @param {typeof import('vite')} vite
|
||||
* @param {ViteDevServer} vite_dev_server
|
||||
* @param {ModuleRunner} runner
|
||||
* @param {ValidatedConfig} svelte_config
|
||||
* @param {ManifestData} manifest_data
|
||||
* @param {string} root
|
||||
* @param {() => RemoteChunk[]} get_remotes
|
||||
* @returns {SSRManifest}
|
||||
*/
|
||||
export function generate_manifest(
|
||||
vite,
|
||||
vite_dev_server,
|
||||
runner,
|
||||
svelte_config,
|
||||
manifest_data,
|
||||
root,
|
||||
get_remotes
|
||||
) {
|
||||
return {
|
||||
app_dir: svelte_config.appDir,
|
||||
app_path: svelte_config.appDir,
|
||||
assets: new Set(manifest_data.assets.map((asset) => asset.file)),
|
||||
mime_types: get_mime_lookup(manifest_data),
|
||||
client: {
|
||||
start: `${get_runtime_base(root)}/client/entry.js`,
|
||||
app: `${to_fs(svelte_config.outDir)}/generated/dev/client/app.js`,
|
||||
imports: [],
|
||||
stylesheets: [],
|
||||
fonts: [],
|
||||
uses_env_dynamic_public: true,
|
||||
nodes:
|
||||
svelte_config.router.resolution === 'client'
|
||||
? undefined
|
||||
: manifest_data.nodes.map((node, i) => {
|
||||
if (node.component || node.universal) {
|
||||
return `${to_fs(svelte_config.outDir)}/generated/dev/client/nodes/${i}.js`;
|
||||
}
|
||||
}),
|
||||
// `css` is not necessary in dev, as the JS file from `nodes` will reference the CSS file
|
||||
routes:
|
||||
svelte_config.router.resolution === 'client'
|
||||
? undefined
|
||||
: compact(
|
||||
manifest_data.routes.map((route) => {
|
||||
if (!route.page) return;
|
||||
|
||||
return {
|
||||
id: route.id,
|
||||
pattern: route.pattern,
|
||||
params: route.params,
|
||||
layouts: route.page.layouts.map((l) =>
|
||||
l !== undefined ? [!!manifest_data.nodes[l].server, l] : undefined
|
||||
),
|
||||
errors: route.page.errors,
|
||||
leaf: [!!manifest_data.nodes[route.page.leaf].server, route.page.leaf]
|
||||
};
|
||||
})
|
||||
)
|
||||
},
|
||||
server_assets: new Proxy(
|
||||
{},
|
||||
{
|
||||
has: (_, /** @type {string} */ file) => fs.existsSync(from_fs(file)),
|
||||
get: (_, /** @type {string} */ file) => fs.statSync(from_fs(file)).size
|
||||
}
|
||||
),
|
||||
nodes: manifest_data.nodes.map((node, index) => {
|
||||
return async () => {
|
||||
const result = /** @type {SSRNode} */ ({});
|
||||
result.index = index;
|
||||
result.universal_id = node.universal;
|
||||
result.server_id = node.server;
|
||||
|
||||
// these are unused in dev, but it's easier to include them
|
||||
result.imports = [];
|
||||
result.stylesheets = [];
|
||||
result.fonts = [];
|
||||
|
||||
/** @type {EnvironmentModuleNode[]} */
|
||||
const module_nodes = [];
|
||||
|
||||
if (node.component) {
|
||||
result.component = async () => {
|
||||
const { module_node, module } = await resolve(
|
||||
vite,
|
||||
vite_dev_server,
|
||||
runner,
|
||||
/** @type {string} */ (node.component)
|
||||
);
|
||||
|
||||
module_nodes.push(module_node);
|
||||
|
||||
return module.default;
|
||||
};
|
||||
}
|
||||
|
||||
if (node.universal) {
|
||||
if (node.page_options?.ssr === false) {
|
||||
result.universal = /** @type {UniversalNode} */ (node.page_options);
|
||||
} else {
|
||||
// TODO: explain why the file was loaded on the server if we fail to load it
|
||||
const { module, module_node } = await resolve(
|
||||
vite,
|
||||
vite_dev_server,
|
||||
runner,
|
||||
node.universal
|
||||
);
|
||||
module_nodes.push(module_node);
|
||||
result.universal = module;
|
||||
}
|
||||
}
|
||||
|
||||
if (node.server) {
|
||||
const { module } = await resolve(vite, vite_dev_server, runner, node.server);
|
||||
result.server = module;
|
||||
}
|
||||
|
||||
// in dev we inline all styles to avoid FOUC. this gets populated lazily so that
|
||||
// components/stylesheets loaded via import() during `load` are included
|
||||
result.inline_styles = async () => {
|
||||
/** @type {Set<EnvironmentModuleNode>} */
|
||||
const deps = new Set();
|
||||
|
||||
for (const module_node of module_nodes) {
|
||||
await find_deps(vite_dev_server, module_node, deps);
|
||||
}
|
||||
|
||||
/** @type {Record<string, string>} */
|
||||
const styles = {};
|
||||
|
||||
for (const dep of deps) {
|
||||
if (vite.isCSSRequest(dep.url) && !vite_css_query_regex.test(dep.url)) {
|
||||
const inlineCssUrl = dep.url.includes('?')
|
||||
? dep.url.replace('?', '?inline&')
|
||||
: dep.url + '?inline';
|
||||
try {
|
||||
const mod = await runner.import(inlineCssUrl);
|
||||
styles[dep.url] = mod.default;
|
||||
} catch {
|
||||
// this can happen with dynamically imported modules, I think
|
||||
// because the Vite module graph doesn't distinguish between
|
||||
// static and dynamic imports? TODO investigate, submit fix
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return styles;
|
||||
};
|
||||
|
||||
return result;
|
||||
};
|
||||
}),
|
||||
prerendered_routes: new Set(),
|
||||
get remotes() {
|
||||
return Object.fromEntries(
|
||||
get_remotes().map((remote) => [
|
||||
remote.hash,
|
||||
() => runner.import(remote.file).then((module) => ({ default: module }))
|
||||
])
|
||||
);
|
||||
},
|
||||
routes: compact(
|
||||
manifest_data.routes.map((route) => {
|
||||
if (!route.page && !route.endpoint) return null;
|
||||
|
||||
const endpoint = route.endpoint;
|
||||
|
||||
return {
|
||||
id: route.id,
|
||||
pattern: route.pattern,
|
||||
params: route.params,
|
||||
page: route.page,
|
||||
endpoint: endpoint
|
||||
? async () => {
|
||||
const url = path.resolve(root, endpoint.file);
|
||||
return await loud_ssr_load_module(vite, vite_dev_server, runner, url);
|
||||
}
|
||||
: null,
|
||||
endpoint_id: endpoint?.file
|
||||
};
|
||||
})
|
||||
),
|
||||
matchers: async () => {
|
||||
if (!manifest_data.params) return {};
|
||||
|
||||
const url = path.resolve(root, manifest_data.params);
|
||||
const module = await runner.import(url);
|
||||
|
||||
if (!module.params) {
|
||||
e.params_export_missing({ file: manifest_data.params });
|
||||
}
|
||||
|
||||
return module.params;
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {typeof import('vite')} vite
|
||||
* @param {ViteDevServer} vite_dev_server
|
||||
* @param {ModuleRunner} runner
|
||||
* @param {string} url
|
||||
* @returns {Promise<Record<string, any>>}
|
||||
*/
|
||||
export async function loud_ssr_load_module(vite, vite_dev_server, runner, url) {
|
||||
try {
|
||||
return await runner.import(url);
|
||||
} catch (/** @type {any} */ err) {
|
||||
const msg = vite.buildErrorMessage(err, [
|
||||
styleText('red', `Internal server error: ${err.message}`)
|
||||
]);
|
||||
|
||||
if (!vite_dev_server.config.logger.hasErrorLogged(err)) {
|
||||
vite_dev_server.config.logger.error(msg, { error: err });
|
||||
}
|
||||
|
||||
// TODO this is inadequate — it doesn't reliably show the overlay on every page load,
|
||||
// and when it does appear it may immediately vanish. `hot.send` broadcasts
|
||||
// to all connected clients, even ones that are unaffected by the error.
|
||||
// we need a more considered approach
|
||||
vite_dev_server.environments.client.hot.send({
|
||||
type: 'error',
|
||||
err: /** @type {ErrorPayload['err']} */ ({
|
||||
...err,
|
||||
// these properties are non-enumerable and will
|
||||
// not be serialized unless we explicitly include them
|
||||
message: err.message,
|
||||
stack: err.stack ?? ''
|
||||
})
|
||||
});
|
||||
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {typeof import('vite')} vite
|
||||
* @param {ViteDevServer} vite_dev_server
|
||||
* @param {ModuleRunner} runner
|
||||
* @param {string} id
|
||||
*/
|
||||
async function resolve(vite, vite_dev_server, runner, id) {
|
||||
const url = id.startsWith('..') ? to_fs(path.resolve(id)) : `/${id}`;
|
||||
|
||||
const module = await loud_ssr_load_module(vite, vite_dev_server, runner, url);
|
||||
|
||||
const module_node = await vite_dev_server.environments.ssr.moduleGraph.getModuleByUrl(url);
|
||||
if (!module_node) throw new Error(`Could not find node for ${url}`);
|
||||
|
||||
return { module, module_node, url };
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {ViteDevServer} vite
|
||||
* @param {EnvironmentModuleNode} node
|
||||
* @param {Set<EnvironmentModuleNode>} deps
|
||||
*/
|
||||
async function find_deps(vite, node, deps) {
|
||||
// since `transformResult.deps` contains URLs instead of `ModuleNode`s, this process is asynchronous.
|
||||
// instead of using `await`, we resolve all branches in parallel.
|
||||
/** @type {Promise<void>[]} */
|
||||
const branches = [];
|
||||
|
||||
/** @param {EnvironmentModuleNode} node */
|
||||
async function add(node) {
|
||||
if (!deps.has(node)) {
|
||||
deps.add(node);
|
||||
await find_deps(vite, node, deps);
|
||||
}
|
||||
}
|
||||
|
||||
/** @param {string} url */
|
||||
async function add_by_url(url) {
|
||||
const node = await vite.environments.ssr.moduleGraph.getModuleByUrl(url);
|
||||
|
||||
if (node) {
|
||||
await add(node);
|
||||
}
|
||||
}
|
||||
|
||||
if (node.transformResult) {
|
||||
if (node.transformResult.deps) {
|
||||
node.transformResult.deps.forEach((url) => branches.push(add_by_url(url)));
|
||||
}
|
||||
|
||||
if (node.transformResult.dynamicDeps) {
|
||||
node.transformResult.dynamicDeps.forEach((url) => branches.push(add_by_url(url)));
|
||||
}
|
||||
} else {
|
||||
node.importedModules.forEach((node) => branches.push(add(node)));
|
||||
}
|
||||
|
||||
await Promise.all(branches);
|
||||
}
|
||||
504
node_modules/@sveltejs/kit/src/exports/vite/dev/index.js
generated
vendored
Normal file
504
node_modules/@sveltejs/kit/src/exports/vite/dev/index.js
generated
vendored
Normal file
@@ -0,0 +1,504 @@
|
||||
/** @import { RequestEvent } from '@sveltejs/kit' */
|
||||
/** @import { ViteDevServer } from 'vite' */
|
||||
/** @import { ManifestData, PrerenderOption, RemoteChunk, ServerModule, ValidatedConfig, SSRManifest } from 'types' */
|
||||
import process from 'node:process';
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { URL } from 'node:url';
|
||||
import { AsyncLocalStorage } from 'node:async_hooks';
|
||||
import { styleText } from 'node:util';
|
||||
import sirv from 'sirv';
|
||||
import { generate_manifest, loud_ssr_load_module } from './generate_manifest.js';
|
||||
import { createReadableStream, getRequest, setResponse } from '../../../exports/node/index.js';
|
||||
import { coalesce_to_error, set_error_stack } from '../../../utils/error.js';
|
||||
import { resolve_entry } from '../../../utils/filesystem.js';
|
||||
import { load_and_validate_params } from '../../../core/params.js';
|
||||
import { from_fs, to_fs } from '../../../utils/vite.js';
|
||||
import { posixify } from '../../../utils/os.js';
|
||||
import { load_error_page } from '../../../core/config/index.js';
|
||||
import { SRC_ROOT, SVELTE_KIT_ASSETS } from '../../../constants.js';
|
||||
import * as sync from '../../../core/sync/sync.js';
|
||||
import { get_runtime_base } from '../../../core/utils.js';
|
||||
import '../../../utils/mime.js'; // extend mrmime with additional types (affects sirv too)
|
||||
import { is_chrome_devtools_request, is_remote_module, not_found } from '../utils.js';
|
||||
import { SCHEME } from '../../../utils/url.js';
|
||||
import { check_feature } from '../../../core/features.js';
|
||||
import * as e from '../../../messages/build-errors.js';
|
||||
import { escape_html } from '../../../utils/escape.js';
|
||||
import { get_runner } from '../../../runner.js';
|
||||
import { write_server } from '../../../core/sync/write_server.js';
|
||||
import { write_tsconfig } from '../../../core/sync/write_tsconfig/index.js';
|
||||
import create_manifest_data from '../../../core/sync/create_manifest_data/index.js';
|
||||
|
||||
/**
|
||||
* @param {typeof import('vite')} vite the peer resolved vite module
|
||||
* @param {ViteDevServer} vite_dev_server
|
||||
* @param {ValidatedConfig} svelte_config
|
||||
* @param {() => RemoteChunk[]} get_remotes
|
||||
* @param {string} root The project root directory
|
||||
* @param {(manifest_data: ManifestData) => void} set_manifest_data
|
||||
* @return {Promise<Promise<() => void>>}
|
||||
*/
|
||||
export async function dev(
|
||||
vite,
|
||||
vite_dev_server,
|
||||
svelte_config,
|
||||
get_remotes,
|
||||
root,
|
||||
set_manifest_data
|
||||
) {
|
||||
/** @type {AsyncLocalStorage<{ event: RequestEvent, config: any, prerender: PrerenderOption }>} */
|
||||
const async_local_storage = new AsyncLocalStorage();
|
||||
|
||||
globalThis.__SVELTEKIT_TRACK__ = (label) => {
|
||||
const context = async_local_storage.getStore();
|
||||
if (!context || context.prerender === true) return;
|
||||
|
||||
check_feature(
|
||||
/** @type {string} */ (context.event.route.id),
|
||||
context.config,
|
||||
label,
|
||||
svelte_config.adapter
|
||||
);
|
||||
};
|
||||
|
||||
const fetch = globalThis.fetch;
|
||||
globalThis.fetch = (info, init) => {
|
||||
if (typeof info === 'string' && !SCHEME.test(info)) {
|
||||
e.fetch_relative_url({ url: info });
|
||||
}
|
||||
|
||||
return fetch(info, init);
|
||||
};
|
||||
|
||||
write_tsconfig(svelte_config, root);
|
||||
|
||||
/** @type {ManifestData} */
|
||||
let manifest_data;
|
||||
/** @type {SSRManifest} */
|
||||
let manifest;
|
||||
|
||||
/** @type {Error | null} */
|
||||
let manifest_error = null;
|
||||
|
||||
const runner = get_runner(vite, vite_dev_server);
|
||||
const { hot } = vite_dev_server.environments.client;
|
||||
|
||||
/**
|
||||
* Log a response to the console, routed through Vite's logger so that it
|
||||
* respects the configured `logLevel` and any `customLogger`
|
||||
* @param {number} status
|
||||
* @param {string} log
|
||||
*/
|
||||
function log_dev_response(status, log) {
|
||||
if (status < 400) {
|
||||
vite_dev_server.config.logger.info(log);
|
||||
} else {
|
||||
vite_dev_server.config.logger.error(log);
|
||||
}
|
||||
}
|
||||
|
||||
/** @param {boolean} [validate_params] */
|
||||
async function update_manifest(validate_params = true) {
|
||||
try {
|
||||
manifest_data = create_manifest_data(svelte_config, root);
|
||||
sync.create(svelte_config, root, manifest_data, false);
|
||||
set_manifest_data(manifest_data);
|
||||
|
||||
if (!validate_params) return;
|
||||
|
||||
await load_and_validate_params({
|
||||
routes: manifest_data.routes,
|
||||
params_path: manifest_data.params,
|
||||
root,
|
||||
load: (file) => loud_ssr_load_module(vite, vite_dev_server, runner, file)
|
||||
});
|
||||
|
||||
if (manifest_error) {
|
||||
manifest_error = null;
|
||||
hot.send({ type: 'full-reload' });
|
||||
}
|
||||
} catch (error) {
|
||||
manifest_error = /** @type {Error} */ (error);
|
||||
|
||||
console.error(styleText(['bold', 'red'], manifest_error.message));
|
||||
hot.send({
|
||||
type: 'error',
|
||||
err: {
|
||||
message: manifest_error.message ?? 'Invalid routes',
|
||||
stack: ''
|
||||
}
|
||||
});
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
manifest = generate_manifest(
|
||||
vite,
|
||||
vite_dev_server,
|
||||
runner,
|
||||
svelte_config,
|
||||
manifest_data,
|
||||
root,
|
||||
get_remotes
|
||||
);
|
||||
}
|
||||
|
||||
// Initializing the Vite SSR runner before the server starts is unsafe, but generated types
|
||||
// don't depend on it and should be available as soon as the dev server is ready.
|
||||
await update_manifest(false);
|
||||
|
||||
/** @param {Error} error */
|
||||
function fix_stack_trace(error) {
|
||||
if (!error.stack) {
|
||||
return;
|
||||
}
|
||||
|
||||
let prelude = '';
|
||||
let start = -1;
|
||||
let end = 0;
|
||||
|
||||
const lines = error.stack
|
||||
.replaceAll('\0', '') // remove null bytes from e.g. virtual module IDs, or the response will fail
|
||||
.split('\n')
|
||||
.map((line, i) => {
|
||||
const match = /^ {4}at (?:[^(]+ \((.+)\)|(.+))$/.exec(line);
|
||||
if (!match) {
|
||||
prelude += line + '\n';
|
||||
end = i + 1;
|
||||
return line;
|
||||
}
|
||||
|
||||
const loc = match[1] ?? match[2];
|
||||
const file = loc.replace(/:\d+:\d+$/, '');
|
||||
|
||||
if (fs.existsSync(file)) {
|
||||
if (!file.includes('node_modules') && !file.includes(SRC_ROOT)) {
|
||||
if (start === -1) start = i;
|
||||
end = i + 1;
|
||||
}
|
||||
|
||||
return line.replace(file, path.relative(process.cwd(), file));
|
||||
}
|
||||
|
||||
return line;
|
||||
})
|
||||
// if no user-code frame was found, keep only the prelude (message/header)
|
||||
// lines and drop everything else so the message isn't duplicated
|
||||
.slice(start === -1 ? end : start, end);
|
||||
|
||||
return set_error_stack(error, prelude + lines.join('\n'));
|
||||
}
|
||||
|
||||
const params_file = resolve_entry(svelte_config.files.params, svelte_config.moduleExtensions);
|
||||
|
||||
/**
|
||||
* @param {string} event
|
||||
* @param {(file: string) => void} cb
|
||||
*/
|
||||
const watch = (event, cb) => {
|
||||
vite_dev_server.watcher.on(event, (file) => {
|
||||
if (
|
||||
file.startsWith(svelte_config.files.routes + path.sep) ||
|
||||
file.startsWith(svelte_config.files.assets + path.sep) ||
|
||||
(params_file && file === params_file) ||
|
||||
is_remote_module(file) ||
|
||||
// in contrast to server hooks, client hooks are written to the client manifest
|
||||
// and therefore need rebuilding when they are added/removed
|
||||
file.startsWith(svelte_config.files.hooks.client)
|
||||
) {
|
||||
cb(file);
|
||||
}
|
||||
});
|
||||
};
|
||||
/** @type {NodeJS.Timeout | null } */
|
||||
let timeout = null;
|
||||
/** @param {() => void} to_run */
|
||||
const debounce = (to_run) => {
|
||||
timeout && clearTimeout(timeout);
|
||||
timeout = setTimeout(() => {
|
||||
timeout = null;
|
||||
to_run();
|
||||
}, 100);
|
||||
};
|
||||
|
||||
// Debounce add/unlink events because in case of folder deletion or moves
|
||||
// they fire in rapid succession, causing needless invocations.
|
||||
// These watchers only run for routes, param matchers, and client hooks.
|
||||
watch('add', () => debounce(update_manifest));
|
||||
watch('unlink', () => debounce(update_manifest));
|
||||
watch('change', (file) => {
|
||||
// `manifest_data` may be undefined if initial manifest creation failed. In that case
|
||||
// there's nothing to update — the manifest will be created from scratch on the first request.
|
||||
if (!manifest_data) return;
|
||||
// Don't run for a single file if the whole manifest is about to get updated
|
||||
// Unless it's a file where the trailing slash page option might have changed
|
||||
if (timeout || !/\+(page|layout|server).*$/.test(file)) return;
|
||||
if (!sync.update(svelte_config, manifest_data, file, root)) debounce(update_manifest);
|
||||
});
|
||||
|
||||
const { appTemplate, errorTemplate, serviceWorker, hooks } = svelte_config.files;
|
||||
|
||||
// vite client only executes a full reload if the triggering html file path is index.html
|
||||
// kit defaults to src/app.html, so unless user changed that to index.html
|
||||
// send the vite client a full-reload event without path being set
|
||||
if (appTemplate !== 'index.html') {
|
||||
vite_dev_server.watcher.on('change', (file) => {
|
||||
if (file === appTemplate) {
|
||||
hot.send({ type: 'full-reload' });
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
vite_dev_server.watcher.on('all', (_, file) => {
|
||||
if (
|
||||
file === appTemplate ||
|
||||
file === errorTemplate ||
|
||||
file.startsWith(serviceWorker) ||
|
||||
file.startsWith(hooks.server)
|
||||
) {
|
||||
write_server(svelte_config, path.join(svelte_config.outDir, 'generated', 'dev'), root);
|
||||
}
|
||||
});
|
||||
|
||||
const assets = svelte_config.paths.assets ? SVELTE_KIT_ASSETS : svelte_config.paths.base;
|
||||
const asset_server = sirv(svelte_config.files.assets, {
|
||||
dev: true,
|
||||
etag: true,
|
||||
maxAge: 0,
|
||||
extensions: []
|
||||
});
|
||||
|
||||
vite_dev_server.middlewares.use((req, res, next) => {
|
||||
const base = `${vite_dev_server.config.server.https ? 'https' : 'http'}://${
|
||||
req.headers[':authority'] || req.headers.host
|
||||
}`;
|
||||
|
||||
const decoded = decodeURI(new URL(base + req.url).pathname);
|
||||
|
||||
if (decoded.startsWith(assets)) {
|
||||
const pathname = decoded.slice(assets.length);
|
||||
const file = svelte_config.files.assets + pathname;
|
||||
|
||||
if (fs.existsSync(file) && !fs.statSync(file).isDirectory()) {
|
||||
if (has_correct_case(file, svelte_config.files.assets)) {
|
||||
req.url = encodeURI(pathname); // don't need query/hash
|
||||
asset_server(req, res);
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
next();
|
||||
});
|
||||
|
||||
const env = vite.loadEnv(vite_dev_server.config.mode, svelte_config.env.dir, '');
|
||||
const emulator = await svelte_config.adapter?.emulate?.();
|
||||
|
||||
/** @type {Promise<void> | undefined} */
|
||||
let init_manifest;
|
||||
|
||||
return () => {
|
||||
const serve_static_middleware = vite_dev_server.middlewares.stack.find(
|
||||
(middleware) =>
|
||||
/** @type {Function} */ (middleware.handle).name === 'viteServeStaticMiddleware'
|
||||
);
|
||||
|
||||
// Vite's static middleware would serve project files at URLs like /test, /static and
|
||||
// /package.json before our routes get a chance. See https://github.com/vitejs/vite/issues/7363
|
||||
remove_static_middlewares(vite_dev_server.middlewares);
|
||||
|
||||
vite_dev_server.middlewares.use(async (req, res) => {
|
||||
// Vite throws a Cannot read properties of undefined (reading 'wrapDynamicImport')
|
||||
// if you try to run ssr.runner.import before the server has started so
|
||||
// we do it inside here to avoid that
|
||||
await (init_manifest ??= update_manifest());
|
||||
|
||||
// Vite's base middleware strips out the base path. Restore it
|
||||
const original_url = req.url;
|
||||
req.url = req.originalUrl;
|
||||
try {
|
||||
const base = `${vite_dev_server.config.server.https ? 'https' : 'http'}://${
|
||||
req.headers[':authority'] || req.headers.host
|
||||
}`;
|
||||
|
||||
const decoded = decodeURI(new URL(base + req.url).pathname);
|
||||
const file = posixify(
|
||||
path.resolve(root, decoded.slice(svelte_config.paths.base.length + 1))
|
||||
);
|
||||
const is_file = fs.existsSync(file) && !fs.statSync(file).isDirectory();
|
||||
const allowed =
|
||||
!vite_dev_server.config.server.fs.strict ||
|
||||
vite_dev_server.config.server.fs.allow.some((dir) => file.startsWith(dir));
|
||||
|
||||
if (is_file && allowed) {
|
||||
req.url = original_url;
|
||||
// @ts-expect-error
|
||||
serve_static_middleware.handle(req, res);
|
||||
return;
|
||||
}
|
||||
|
||||
if (is_chrome_devtools_request(decoded, res)) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (!decoded.startsWith(svelte_config.paths.base)) {
|
||||
return not_found(req, res, svelte_config.paths.base);
|
||||
}
|
||||
|
||||
if (decoded === svelte_config.paths.base + '/service-worker.js') {
|
||||
const resolved = resolve_entry(
|
||||
svelte_config.files.serviceWorker,
|
||||
svelte_config.moduleExtensions
|
||||
);
|
||||
|
||||
if (resolved) {
|
||||
res.writeHead(200, {
|
||||
'content-type': 'application/javascript'
|
||||
});
|
||||
res.end(`import '${svelte_config.paths.base}${to_fs(resolved)}';`);
|
||||
} else {
|
||||
res.writeHead(404);
|
||||
res.end('not found');
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
// resolve the instrumentation file per request so that changes to it
|
||||
// are picked up on new requests
|
||||
const resolved_instrumentation = resolve_entry(
|
||||
path.join(svelte_config.files.src, 'instrumentation.server'),
|
||||
svelte_config.moduleExtensions
|
||||
);
|
||||
|
||||
if (resolved_instrumentation) {
|
||||
if (svelte_config.adapter && !svelte_config.adapter.supports?.instrumentation?.()) {
|
||||
e.adapter_instrumentation_unsupported({
|
||||
file: resolved_instrumentation,
|
||||
adapter: svelte_config.adapter.name
|
||||
});
|
||||
}
|
||||
|
||||
const { set_env } = await runner.import('<sveltekit:generated>/env/config.js');
|
||||
set_env(env);
|
||||
await runner.import(resolved_instrumentation);
|
||||
}
|
||||
|
||||
const { configure, format_response } = /** @type {ServerModule} */ (
|
||||
await runner.import(`${get_runtime_base(root)}/server/index.js`)
|
||||
);
|
||||
|
||||
const { init, respond } = await configure({
|
||||
manifest,
|
||||
env,
|
||||
read: (file) => createReadableStream(from_fs(file)),
|
||||
assets,
|
||||
fix_stack_trace
|
||||
});
|
||||
|
||||
await init();
|
||||
|
||||
const request = (svelte_config.adapter?.vite?.getRequest ?? getRequest)({
|
||||
base,
|
||||
request: req,
|
||||
response: res
|
||||
});
|
||||
|
||||
if (manifest_error) {
|
||||
console.error(styleText(['bold', 'red'], manifest_error.message));
|
||||
|
||||
const error_page = load_error_page(svelte_config);
|
||||
|
||||
/** @param {{ status: number; message: string }} opts */
|
||||
const error_template = ({ status, message }) => {
|
||||
return error_page
|
||||
.replace(/%sveltekit\.status%/g, String(status))
|
||||
.replace(/%sveltekit\.error\.message%/g, escape_html(message));
|
||||
};
|
||||
|
||||
res.writeHead(500, {
|
||||
'Content-Type': 'text/html; charset=utf-8'
|
||||
});
|
||||
res.end(
|
||||
error_template({ status: 500, message: manifest_error.message ?? 'Invalid routes' })
|
||||
);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
const rendered = await respond(request, {
|
||||
getClientAddress: () => {
|
||||
const { remoteAddress } = req.socket;
|
||||
if (remoteAddress) return remoteAddress;
|
||||
throw new Error('Could not determine clientAddress');
|
||||
},
|
||||
read: (file) => {
|
||||
if (file in manifest.server_assets) {
|
||||
return fs.readFileSync(from_fs(file));
|
||||
}
|
||||
|
||||
return fs.readFileSync(path.join(svelte_config.files.assets, file));
|
||||
},
|
||||
before_handle: async (event, config, prerender, handle) => {
|
||||
// we need to use .run because .enterWith() is not supported in Cloudflare Workers
|
||||
// see https://blog.cloudflare.com/workers-node-js-asynclocalstorage/
|
||||
return await async_local_storage.run({ event, config, prerender }, handle);
|
||||
},
|
||||
emulator
|
||||
});
|
||||
|
||||
if (rendered.status === 404) {
|
||||
// @ts-expect-error
|
||||
serve_static_middleware.handle(req, res, () => {
|
||||
log_dev_response(rendered.status, format_response(rendered.status, request));
|
||||
(svelte_config.adapter?.vite?.setResponse ?? setResponse)(res, rendered);
|
||||
});
|
||||
} else {
|
||||
log_dev_response(rendered.status, format_response(rendered.status, request));
|
||||
(svelte_config.adapter?.vite?.setResponse ?? setResponse)(res, rendered);
|
||||
}
|
||||
} catch (e) {
|
||||
const error = coalesce_to_error(e);
|
||||
res.statusCode = 500;
|
||||
fix_stack_trace(error);
|
||||
console.error(styleText(['bold', 'red'], String(error)));
|
||||
res.end(error.stack || error.message); // handle `stackless` errors
|
||||
}
|
||||
});
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {import('connect').Server} server
|
||||
*/
|
||||
function remove_static_middlewares(server) {
|
||||
const static_middlewares = ['viteServeStaticMiddleware', 'viteServePublicMiddleware'];
|
||||
for (let i = server.stack.length - 1; i > 0; i--) {
|
||||
// @ts-expect-error using internals
|
||||
if (static_middlewares.includes(server.stack[i].handle.name)) {
|
||||
server.stack.splice(i, 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Determine if a file is being requested with the correct case,
|
||||
* to ensure consistent behaviour between dev and prod and across
|
||||
* operating systems. Note that we can't use realpath here,
|
||||
* because we don't want to follow symlinks
|
||||
* @param {string} file
|
||||
* @param {string} assets
|
||||
* @returns {boolean}
|
||||
*/
|
||||
function has_correct_case(file, assets) {
|
||||
if (file === assets) return true;
|
||||
|
||||
const parent = path.dirname(file);
|
||||
|
||||
if (fs.readdirSync(parent).includes(path.basename(file))) {
|
||||
return has_correct_case(parent, assets);
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
676
node_modules/@sveltejs/kit/src/exports/vite/index.js
generated
vendored
Normal file
676
node_modules/@sveltejs/kit/src/exports/vite/index.js
generated
vendored
Normal file
@@ -0,0 +1,676 @@
|
||||
/** @import { EnvVarConfig } from '@sveltejs/kit/env' */
|
||||
/** @import { Options } from '@sveltejs/vite-plugin-svelte' */
|
||||
/** @import { PreprocessorGroup } from 'svelte/compiler' */
|
||||
/** @import { ManifestData, RemoteChunk, ServerMetadata, ValidatedConfig } from 'types' */
|
||||
/** @import { CorsOptions, Plugin, ResolvedConfig, Rolldown, UserConfig } from 'vite' */
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import process from 'node:process';
|
||||
import * as vite from 'vite';
|
||||
|
||||
import { resolve_entry } from '../../utils/filesystem.js';
|
||||
import { posixify } from '../../utils/os.js';
|
||||
import { to_fs } from '../../utils/vite.js';
|
||||
import { runtime_directory, get_global_name } from '../../core/utils.js';
|
||||
import { dev } from './dev/index.js';
|
||||
import { preview } from './preview/index.js';
|
||||
import {
|
||||
enforced_config,
|
||||
get_config_aliases,
|
||||
is_remote_module,
|
||||
remote_module_pattern,
|
||||
uses_unsupported_html_hook,
|
||||
warn_overridden_config
|
||||
} from './utils.js';
|
||||
import * as e from '../../messages/build-errors.js';
|
||||
import * as w from '../../messages/build-warnings.js';
|
||||
import { s } from '../../utils/misc.js';
|
||||
import create_manifest_data from '../../core/sync/create_manifest_data/index.js';
|
||||
import { get_import_aliases, get_hash_import_keys } from '../../utils/imports.js';
|
||||
import { import_peer } from '../../utils/import.js';
|
||||
import { should_ignore, has_children } from './static_analysis/utils.js';
|
||||
import { process_config, split_config, validate_config } from '../../core/config/index.js';
|
||||
import { plugin_env_vars, plugin_service_worker_env_vars } from './plugins/env-vars.js';
|
||||
import { plugin_guard } from './plugins/guard.js';
|
||||
import { plugin_remote, plugin_remote_guard } from './plugins/remote.js';
|
||||
import { write_app_manifest } from '../../core/sync/write_app_manifest.js';
|
||||
import { plugin_service_worker_build } from './build/service-worker.js';
|
||||
import { plugin_adapter, plugin_compile } from './build/index.js';
|
||||
import { bullet_list } from '../../utils/format.js';
|
||||
|
||||
const options_regex = /(export\s+const\s+(prerender|csr|ssr|trailingSlash))\s*=/s;
|
||||
|
||||
/**
|
||||
* Resolves the CORS config for dev and preview servers.
|
||||
* SvelteKit needs `preflightContinue: true` so that OPTIONS requests for
|
||||
* `+server.js` endpoints aren't intercepted by Vite's CORS middleware.
|
||||
* If the user has explicitly set values that prevent this, we warn them
|
||||
* and preserve their settings.
|
||||
* @param {CorsOptions | boolean | undefined} user_cors
|
||||
* @param {'server.cors' | 'preview.cors'} key
|
||||
* @param {boolean} warn Whether to emit a warning when the user's settings prevent OPTIONS handlers from working. Only relevant for the dev/preview servers, not `vite build`.
|
||||
* @returns {CorsOptions | undefined}
|
||||
*/
|
||||
function resolve_cors(user_cors, key, warn) {
|
||||
// `preview.cors` falls back to the resolved `server.cors`, so emitting a value here when
|
||||
// the user hasn't set one is what drops Vite's `defaultAllowedOrigins` restriction
|
||||
if (user_cors === undefined) {
|
||||
return key === 'server.cors' ? { preflightContinue: true } : undefined;
|
||||
}
|
||||
|
||||
// with `cors: false` Vite installs no CORS middleware, so OPTIONS handlers already work
|
||||
if (user_cors === false) return undefined;
|
||||
|
||||
if (typeof user_cors === 'object' && user_cors !== null) {
|
||||
if (user_cors.preflightContinue === undefined) return { preflightContinue: true };
|
||||
if (user_cors.preflightContinue) return undefined;
|
||||
}
|
||||
|
||||
if (warn) {
|
||||
w.cors_preflight_continue({ key });
|
||||
}
|
||||
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const removed_modules = [
|
||||
{
|
||||
name: '$lib',
|
||||
pattern: /^\$lib(?:\/.*|\?.*)?$/,
|
||||
error: e.module_removed_lib
|
||||
},
|
||||
{
|
||||
name: '$service-worker',
|
||||
pattern: /^\$service-worker(?:\?.*)?$/,
|
||||
error: e.module_removed_service_worker
|
||||
}
|
||||
];
|
||||
|
||||
/** @type {Set<string>} */
|
||||
const warned = new Set();
|
||||
|
||||
/** @type {PreprocessorGroup} */
|
||||
const warning_preprocessor = {
|
||||
name: 'sveltekit:warnings',
|
||||
script: ({ content, filename }) => {
|
||||
if (!filename) return;
|
||||
|
||||
const basename = path.basename(filename);
|
||||
if (basename.startsWith('+page.') || basename.startsWith('+layout.')) {
|
||||
const match = content.match(options_regex);
|
||||
if (match && match.index !== undefined && !should_ignore(content, match.index)) {
|
||||
const fixed = basename.replace('.svelte', '(.server).js/ts');
|
||||
const file = path.relative(process.cwd(), filename);
|
||||
const key = `page_option_in_component:${file}:${match[1]}`;
|
||||
|
||||
if (!warned.has(key)) {
|
||||
w.page_option_in_component({ file, option: match[1], fixed });
|
||||
warned.add(key);
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
markup: ({ content, filename }) => {
|
||||
if (!filename) return;
|
||||
|
||||
const basename = path.basename(filename);
|
||||
|
||||
if (basename.startsWith('+layout.') && !has_children(content, true)) {
|
||||
const file = path.relative(process.cwd(), filename);
|
||||
const key = `layout_children_missing:${file}`;
|
||||
|
||||
if (!warned.has(key)) {
|
||||
w.layout_children_missing({ file });
|
||||
warned.add(key);
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
/** @type {typeof import('@sveltejs/vite-plugin-svelte')} */
|
||||
let vite_plugin_svelte;
|
||||
|
||||
/**
|
||||
* The SvelteKit Vite plugin, which must be added to your `vite.config.js` file along with your project's configuration:
|
||||
*
|
||||
* ```js
|
||||
* /// file: vite.config.js
|
||||
* import adapter from '@sveltejs/adapter-auto';
|
||||
* import { sveltekit } from '@sveltejs/kit/vite';
|
||||
* import { defineConfig } from 'vite';
|
||||
*
|
||||
* export default defineConfig({
|
||||
* plugins: [
|
||||
* sveltekit({
|
||||
* adapter: adapter(),
|
||||
* compilerOptions: {
|
||||
* experimental: {
|
||||
* async: true
|
||||
* }
|
||||
* },
|
||||
* experimental: {
|
||||
* remoteFunctions: true
|
||||
* }
|
||||
* })
|
||||
* ]
|
||||
* });
|
||||
* ```
|
||||
*
|
||||
* As well as SvelteKit, the plugin options are used by other tooling that integrates with Svelte such as editor extensions.
|
||||
*
|
||||
* Any options that don't belong to SvelteKit are passed through to [`vite-plugin-svelte`](https://github.com/sveltejs/vite-plugin-svelte/blob/main/docs/config.md), so you can set options like `inspector` here too. The `experimental` namespace is shared — SvelteKit reads its own flags and forwards the rest.
|
||||
*
|
||||
* > [!LEGACY]
|
||||
* > Prior to SvelteKit 3, config lived in a `svelte.config.js` file, which is no longer supported. The ability to configure SvelteKit via `vite.config.js` was added in version 2.62.
|
||||
*
|
||||
* @param {import('./public.js').Config} [config]
|
||||
* @returns {Promise<Plugin[]>}
|
||||
*/
|
||||
export async function sveltekit(config) {
|
||||
const cwd = process.cwd();
|
||||
|
||||
// any options passed to the plugin that SvelteKit doesn't use itself are
|
||||
// forwarded to vite-plugin-svelte, which does its own validation
|
||||
const split = split_config(config ?? {});
|
||||
const svelte_config = validate_config(split.svelte_config);
|
||||
|
||||
if (Array.isArray(svelte_config.preprocess)) {
|
||||
svelte_config.preprocess.push(warning_preprocessor);
|
||||
} else if (svelte_config.preprocess) {
|
||||
svelte_config.preprocess = [svelte_config.preprocess, warning_preprocessor];
|
||||
} else {
|
||||
svelte_config.preprocess = warning_preprocessor;
|
||||
}
|
||||
|
||||
vite_plugin_svelte = await import_peer('@sveltejs/vite-plugin-svelte', cwd);
|
||||
|
||||
/** @type {Partial<Options>} */
|
||||
const inline_vps_config = {
|
||||
preprocess: svelte_config.preprocess,
|
||||
// pass through any options that SvelteKit doesn't use itself, so that
|
||||
// the options SvelteKit manages always take precedence
|
||||
...split.vite_plugin_svelte_config,
|
||||
// we don't want vite-plugin-svelte to load the svelte.config.js file because
|
||||
// we expect options to be passed through the SvelteKit Vite plugin
|
||||
configFile: false
|
||||
};
|
||||
|
||||
// vite-plugin-svelte inline config options need to be added conditionally
|
||||
// because passing undefined causes it to crash
|
||||
if (svelte_config.extensions) {
|
||||
inline_vps_config.extensions = svelte_config.extensions;
|
||||
}
|
||||
|
||||
if (svelte_config.compilerOptions) {
|
||||
inline_vps_config.compilerOptions = svelte_config.compilerOptions;
|
||||
}
|
||||
|
||||
return [...vite_plugin_svelte.svelte(inline_vps_config), ...kit({ svelte_config })];
|
||||
}
|
||||
|
||||
/** @param {UserConfig | ResolvedConfig} vite_config */
|
||||
function resolve_root(vite_config) {
|
||||
return posixify(vite_config.root ? path.resolve(vite_config.root) : process.cwd());
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the SvelteKit Vite plugin. Vite executes Rolldown hooks as well as some of its own.
|
||||
* Background reading is available at:
|
||||
* - https://vite.dev/guide/api-plugin.html
|
||||
* - https://rolldown.rs/apis/plugin-api
|
||||
*
|
||||
* You can get an idea of the lifecycle by looking at the flow charts here:
|
||||
* - https://rolldown.rs/apis/plugin-api#build-hooks
|
||||
* - https://rolldown.rs/apis/plugin-api#output-generation-hooks
|
||||
*
|
||||
* @param {object} opts
|
||||
* @param {ValidatedConfig} opts.svelte_config
|
||||
* @return {Plugin[]}
|
||||
*/
|
||||
function kit({ svelte_config }) {
|
||||
/**
|
||||
* The posix-ified root of the project based on the Vite configuration.
|
||||
* @type {string}
|
||||
*/
|
||||
let root;
|
||||
|
||||
/** @type {ValidatedConfig} */
|
||||
let kit;
|
||||
/** @type {string} `kit.outDir` but posix-ified */
|
||||
let out_dir;
|
||||
/** @type {string} The base directory for the Vite builds */
|
||||
let out;
|
||||
|
||||
/** @type {boolean} */
|
||||
let is_build;
|
||||
|
||||
/** @type {ManifestData} */
|
||||
let manifest_data;
|
||||
|
||||
/** @type {UserConfig} */
|
||||
let initial_config;
|
||||
|
||||
/** @type {string | null} */
|
||||
let service_worker_entry_file;
|
||||
/** @type {Array<{ alias: string, path: string }>} */
|
||||
let normalized_aliases;
|
||||
|
||||
const sourcemapIgnoreList = /** @param {string} relative_path */ (relative_path) =>
|
||||
relative_path.includes('node_modules') || relative_path.includes(kit.outDir);
|
||||
|
||||
/** @type {string} the `__sveltekit_xxx` name, without `globalThis.` */
|
||||
let global_name;
|
||||
|
||||
/** @type {string} name for `globalThis.__sveltekit_xxx` */
|
||||
let kit_global;
|
||||
|
||||
/** @type {Plugin} */
|
||||
const plugin_resolve_root = {
|
||||
name: 'vite-plugin-sveltekit-resolve-root',
|
||||
// make sure it runs first
|
||||
enforce: 'pre',
|
||||
config: {
|
||||
order: 'pre',
|
||||
handler(config) {
|
||||
root = resolve_root(config);
|
||||
|
||||
for (const file of ['svelte.config.js', 'svelte.config.ts']) {
|
||||
if (fs.existsSync(path.join(root, file))) {
|
||||
e.config_file_unsupported({ file });
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
/** @type {Plugin} */
|
||||
const plugin_setup = {
|
||||
name: 'vite-plugin-sveltekit-setup',
|
||||
api: {
|
||||
options: svelte_config
|
||||
},
|
||||
resolveId: {
|
||||
filter: { id: removed_modules.map(({ pattern }) => pattern) },
|
||||
async handler(id, importer, options) {
|
||||
const resolved = await this.resolve(id, importer, { ...options, skipSelf: true });
|
||||
if (resolved) return resolved;
|
||||
|
||||
const aliases = svelte_config.alias;
|
||||
for (const { name, pattern, error } of removed_modules) {
|
||||
if (!pattern.test(id)) continue;
|
||||
|
||||
// If the user re-added an alias for this module (as the migration message
|
||||
// suggests), a failed resolution means a genuine missing file rather than
|
||||
// use of the removed module. Let Vite report the real "not found" error
|
||||
// instead of the misleading migration message.
|
||||
if (name in aliases || `${name}/*` in aliases) return;
|
||||
|
||||
error(undefined, { stackless: true });
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* Build the SvelteKit-provided Vite config to be merged with the user's vite.config.js file.
|
||||
* @see https://vitejs.dev/guide/api-plugin.html#config
|
||||
*/
|
||||
config: {
|
||||
order: 'pre',
|
||||
handler(config, config_env) {
|
||||
initial_config = config;
|
||||
is_build = config_env.command === 'build';
|
||||
|
||||
kit = process_config(svelte_config, root);
|
||||
out_dir = posixify(kit.outDir);
|
||||
out = `${out_dir}/output`;
|
||||
|
||||
global_name = get_global_name(kit.version.name, !is_build);
|
||||
kit_global = `globalThis.${global_name}`;
|
||||
|
||||
service_worker_entry_file = resolve_entry(kit.files.serviceWorker, kit.moduleExtensions);
|
||||
service_worker_entry_file &&= posixify(service_worker_entry_file);
|
||||
|
||||
normalized_aliases = get_import_aliases(root, vite.normalizePath.bind(vite));
|
||||
|
||||
// Add `#`-prefixed import keys to the enforced config so users are warned
|
||||
// if they try to set them in their Vite config's resolve.alias
|
||||
const enforced_alias = /** @type {Record<string, true>} */ (
|
||||
/** @type {any} */ (enforced_config.resolve).alias
|
||||
);
|
||||
for (const key of get_hash_import_keys(root)) {
|
||||
enforced_alias[key] = true;
|
||||
}
|
||||
|
||||
const allow = new Set([
|
||||
kit.files.routes,
|
||||
kit.files.src,
|
||||
kit.outDir,
|
||||
path.resolve(root, kit.files.src),
|
||||
path.resolve(root, 'node_modules'),
|
||||
// ensures that the client entry is served even if it's located outside
|
||||
// the local node_modules, such as the pnpm global virtual store
|
||||
runtime_directory,
|
||||
path.resolve('node_modules'),
|
||||
// include the directory that contains the workspaces declaration
|
||||
// which usually also contains hoisted packages
|
||||
// see https://vite.dev/guide/api-javascript#searchforworkspaceroot
|
||||
path.resolve(vite.searchForWorkspaceRoot(process.cwd()), 'node_modules')
|
||||
]);
|
||||
|
||||
// Add directories from `#`-prefixed package.json imports to the allow list
|
||||
for (const { path: alias_path } of normalized_aliases) {
|
||||
allow.add(alias_path);
|
||||
}
|
||||
|
||||
// We can only add directories to the allow list, so we find out
|
||||
// if there's a client hooks file and pass its directory
|
||||
const client_hooks = resolve_entry(kit.files.hooks.client, kit.moduleExtensions);
|
||||
if (client_hooks) allow.add(path.dirname(client_hooks));
|
||||
|
||||
// dev and preview config can be shared
|
||||
/** @type {UserConfig} */
|
||||
const new_config = {
|
||||
appType: 'custom',
|
||||
environments: {
|
||||
ssr: {
|
||||
build: {
|
||||
sourcemap:
|
||||
config.environments?.ssr?.build?.sourcemap ?? config.build?.sourcemap ?? true
|
||||
}
|
||||
}
|
||||
},
|
||||
resolve: {
|
||||
alias: [
|
||||
{ find: '$app', replacement: `${runtime_directory}/app` },
|
||||
{ find: '$env', replacement: `${runtime_directory}/env` },
|
||||
{
|
||||
find: '<sveltekit:generated>',
|
||||
replacement: `${out_dir}/generated/${is_build ? 'build' : 'dev'}`
|
||||
},
|
||||
...get_config_aliases(kit, root)
|
||||
]
|
||||
},
|
||||
server: {
|
||||
cors: resolve_cors(config.server?.cors, 'server.cors', !is_build),
|
||||
fs: {
|
||||
allow: [...allow]
|
||||
},
|
||||
sourcemapIgnoreList,
|
||||
watch: {
|
||||
ignored: [
|
||||
// Ignore all siblings of config.outDir/generated, at any depth
|
||||
`${out_dir}/!(generated)`,
|
||||
`${out_dir}/!(generated)/**`
|
||||
]
|
||||
}
|
||||
},
|
||||
preview: {
|
||||
cors: resolve_cors(config.preview?.cors, 'preview.cors', !is_build)
|
||||
},
|
||||
optimizeDeps: {
|
||||
entries: [
|
||||
`${kit.files.routes}/**/+*.{svelte,js,ts}`,
|
||||
`!${kit.files.routes}/**/+*server.*`
|
||||
],
|
||||
exclude: [
|
||||
// Without this SvelteKit will be prebundled on the client, which means we end up with two versions of Redirect etc.
|
||||
// Also see https://github.com/sveltejs/kit/issues/5952#issuecomment-1218844057
|
||||
'@sveltejs/kit',
|
||||
// exclude kit features so that libraries using them work even when they are prebundled
|
||||
// this does not affect app code, just handling of imported libraries that use $app or $env
|
||||
'$app',
|
||||
'$env'
|
||||
],
|
||||
// avoid Vite dev server reloading the first time a page is requested
|
||||
include: ['@sveltejs/kit > devalue', '@sveltejs/kit > esm-env']
|
||||
},
|
||||
ssr: {
|
||||
noExternal: [
|
||||
// This ensures that esm-env is inlined into the server output with the
|
||||
// export conditions resolved correctly through Vite. This prevents adapters
|
||||
// that bundle later on from resolving the export conditions incorrectly
|
||||
// and for example include browser-only code in the server output
|
||||
// because they for example use rolldown.build with `platform: 'browser'`
|
||||
'esm-env',
|
||||
// This forces `$app/*` modules to be bundled, since they depend on
|
||||
// generated modules like `<sveltekit:generated>/env/config.js` (this isn't a valid bare
|
||||
// import, but Vitest's externalization logic matches it against the module path)
|
||||
'@sveltejs/kit/src/runtime'
|
||||
],
|
||||
// Any CommonJS dependencies of Kit (of which there are currently none) must always be externalized.
|
||||
// Without this, the tests will still pass but `pnpm dev` will fail in projects that link `@sveltejs/kit`.
|
||||
|
||||
// `@opentelemetry/api` must be externalized so that `instrumentation.server.js` and the
|
||||
// SvelteKit runtime share a single instance of the module (the global tracer/propagation
|
||||
// is set on that instance — two bundled copies would mean instrumentation hooks are
|
||||
// invisible to the runtime). Externalizing also prevents the bundler from colocating
|
||||
// `@opentelemetry/api` into a shared chunk that also contains application modules, which
|
||||
// would cause those modules to be evaluated before `Server.init()` sets env vars — see
|
||||
// https://github.com/sveltejs/kit/issues/16288
|
||||
external: ['@opentelemetry/api']
|
||||
},
|
||||
publicDir: kit.files.assets
|
||||
};
|
||||
|
||||
// externalize .remote.js files to stop dependency tracing during prebundling
|
||||
if (kit.experimental.remoteFunctions) {
|
||||
// @ts-expect-error optimizeDeps is already set above
|
||||
new_config.optimizeDeps.rolldownOptions ??= {};
|
||||
// @ts-expect-error
|
||||
new_config.optimizeDeps.rolldownOptions.plugins ??= [];
|
||||
// @ts-expect-error
|
||||
new_config.optimizeDeps.rolldownOptions.plugins.push(
|
||||
/** @type {Rolldown.Plugin} */ ({
|
||||
name: 'vite-plugin-sveltekit-setup:optimize-remote-functions',
|
||||
resolveId: {
|
||||
filter: { id: remote_module_pattern },
|
||||
async handler(id, importer) {
|
||||
const resolved = await this.resolve(id, importer, { skipSelf: true });
|
||||
if (!resolved) return { id, external: true };
|
||||
if (!is_remote_module(resolved.id)) return;
|
||||
// a servable /@fs url; 'absolute' stops rolldown relativizing it in the deps bundle
|
||||
return { id: to_fs(resolved.id), external: 'absolute' };
|
||||
}
|
||||
}
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
const define = {
|
||||
__SVELTEKIT_APP_DIR__: s(posixify(kit.appDir)),
|
||||
__SVELTEKIT_APP_VERSION__: s(kit.version.name),
|
||||
__SVELTEKIT_APP_VERSION_CHECKS_ENABLED__: s(kit.output.bundleStrategy !== 'inline'),
|
||||
__SVELTEKIT_EMBEDDED__: s(kit.embedded),
|
||||
__SVELTEKIT_FORK_PRELOADS__: s(kit.experimental.forkPreloads),
|
||||
__SVELTEKIT_PATHS_ASSETS__: s(kit.paths.assets),
|
||||
__SVELTEKIT_PATHS_BASE__: s(kit.paths.base),
|
||||
__SVELTEKIT_PATHS_RELATIVE__: s(kit.paths.relative),
|
||||
__SVELTEKIT_CLIENT_ROUTING__: s(kit.router.resolution === 'client'),
|
||||
__SVELTEKIT_HASH_ROUTING__: s(kit.router.type === 'hash'),
|
||||
__SVELTEKIT_SERVER_TRACING_ENABLED__: s(kit.tracing.server),
|
||||
__SVELTEKIT_SUPPORTS_ASYNC__: s(
|
||||
svelte_config.compilerOptions?.experimental?.async ?? false
|
||||
),
|
||||
__SVELTEKIT_DEV__: s(!is_build),
|
||||
__SVELTEKIT_GLOBAL_NAME__: s(global_name),
|
||||
__SVELTEKIT_CSRF_CHECK_ORIGIN__: s(!kit.csrf.trustedOrigins.includes('*')),
|
||||
__SVELTEKIT_LINK_HEADER_PRELOAD__: s(kit.output.linkHeaderPreload),
|
||||
__SVELTEKIT_PATHS_ORIGIN__: s(kit.paths.origin) ?? 'undefined',
|
||||
__SVELTEKIT_SERVICE_WORKER__: s(kit.serviceWorker.register && !!service_worker_entry_file)
|
||||
};
|
||||
|
||||
if (is_build) {
|
||||
new_config.define = {
|
||||
...define,
|
||||
__SVELTEKIT_ADAPTER_NAME__: s(kit.adapter?.name),
|
||||
__SVELTEKIT_APP_VERSION_FILE__: s(`${kit.appDir}/version.json`),
|
||||
__SVELTEKIT_APP_VERSION_POLL_INTERVAL__: s(kit.version.pollInterval)
|
||||
};
|
||||
} else {
|
||||
new_config.define = {
|
||||
...define,
|
||||
__SVELTEKIT_APP_VERSION_POLL_INTERVAL__: '0',
|
||||
__SVELTEKIT_PAYLOAD__: kit_global, // only relevant when bundleStrategy !== 'split'
|
||||
__SVELTEKIT_HAS_SERVER_LOAD__: 'true',
|
||||
__SVELTEKIT_HAS_UNIVERSAL_LOAD__: 'true'
|
||||
};
|
||||
|
||||
// we avoid setting base to paths.assets in dev so that we get the
|
||||
// trailing slash redirect to paths.base if it is set
|
||||
new_config.base = kit.paths.base || '/';
|
||||
}
|
||||
|
||||
// Vite's `define` is a compile-time text replacement, but Vitest strips
|
||||
// user `define` from the server config and reinstalls the values only as
|
||||
// `globalThis` properties inside test workers, so anything
|
||||
// that runs outside of a test will freak out over
|
||||
// them not being defined
|
||||
if (process.env.VITEST === 'true') {
|
||||
for (const key in new_config.define) {
|
||||
const value = new_config.define[key];
|
||||
try {
|
||||
/** @type {Record<string, any>} */ (globalThis)[key] = JSON.parse(value);
|
||||
} catch {
|
||||
// `kit_global` isn't JSON, so don't try to parse it. We may one day
|
||||
// need to define it in Vitest somehow but for now, ignore it
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
warn_overridden_config(config, new_config);
|
||||
|
||||
return new_config;
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* Stores the final config.
|
||||
*/
|
||||
configResolved(config) {
|
||||
if (!is_build) {
|
||||
// Dependency scanning starts before configureServer creates the full manifest
|
||||
write_app_manifest(`${out_dir}/generated/dev`, undefined, false);
|
||||
}
|
||||
|
||||
const unsupported_plugins = config.plugins.filter(uses_unsupported_html_hook);
|
||||
if (unsupported_plugins.length) {
|
||||
const plugins = bullet_list(
|
||||
unsupported_plugins.map((plugin) => plugin.name || '(missing plugin name)')
|
||||
);
|
||||
|
||||
w.transform_index_html_unsupported({ plugins });
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* Adds the SvelteKit middleware to do SSR in dev mode.
|
||||
* @see https://vitejs.dev/guide/api-plugin.html#configureserver
|
||||
*/
|
||||
async configureServer(server) {
|
||||
return await dev(
|
||||
vite,
|
||||
server,
|
||||
svelte_config,
|
||||
() => remote_metadata.remotes,
|
||||
root,
|
||||
(data) => {
|
||||
manifest_data = data;
|
||||
}
|
||||
);
|
||||
},
|
||||
|
||||
/**
|
||||
* Adds the SvelteKit middleware to do SSR in preview mode.
|
||||
* @see https://vitejs.dev/guide/api-plugin.html#configurepreviewserver
|
||||
*/
|
||||
configurePreviewServer(server) {
|
||||
return preview(server, svelte_config);
|
||||
}
|
||||
};
|
||||
|
||||
/** @type {ServerMetadata | null} build analysis results */
|
||||
let build_metadata = null;
|
||||
|
||||
/** @type {Record<string, EnvVarConfig<any>> | null} */
|
||||
let explicit_env_config = null;
|
||||
|
||||
/** @type {{ remotes: RemoteChunk[]; remote_original_by_hash: Map<string, string>}} */
|
||||
let remote_metadata = {
|
||||
remotes: [],
|
||||
remote_original_by_hash: new Map()
|
||||
};
|
||||
|
||||
/** @type {(() => Promise<void>) | null} */
|
||||
let finalise = null;
|
||||
|
||||
if (Array.isArray(svelte_config.adapter?.vite?.plugins)) {
|
||||
svelte_config.adapter.vite.plugins = {
|
||||
pre: svelte_config.adapter.vite.plugins
|
||||
};
|
||||
}
|
||||
|
||||
return /** @type {Plugin[]} */ (
|
||||
[
|
||||
svelte_config.adapter?.vite?.plugins?.pre,
|
||||
plugin_resolve_root,
|
||||
plugin_setup,
|
||||
plugin_remote_guard(svelte_config),
|
||||
plugin_remote(
|
||||
svelte_config,
|
||||
() => ({ root, vite }),
|
||||
() => build_metadata,
|
||||
(metadata) => {
|
||||
remote_metadata = metadata;
|
||||
}
|
||||
),
|
||||
plugin_env_vars(svelte_config, (vars) => {
|
||||
explicit_env_config = vars;
|
||||
}),
|
||||
process.env.TEST !== 'true'
|
||||
? plugin_guard(
|
||||
svelte_config,
|
||||
() => ({
|
||||
vite,
|
||||
root,
|
||||
normalized_aliases,
|
||||
service_worker_entry_file
|
||||
}),
|
||||
// in dev, this doesn't exist yet, so we need to create it
|
||||
() => (manifest_data ??= create_manifest_data(svelte_config, root))
|
||||
)
|
||||
: undefined,
|
||||
plugin_service_worker_build(svelte_config, () => ({
|
||||
service_worker_entry_file,
|
||||
kit_global,
|
||||
initial_config,
|
||||
out
|
||||
})),
|
||||
plugin_service_worker_env_vars(() => service_worker_entry_file),
|
||||
plugin_compile(
|
||||
svelte_config,
|
||||
() => ({
|
||||
root,
|
||||
initial_config,
|
||||
global_name,
|
||||
kit_global,
|
||||
vite,
|
||||
service_worker_entry_file,
|
||||
sourcemapIgnoreList
|
||||
}),
|
||||
(metadata) => {
|
||||
build_metadata = metadata;
|
||||
},
|
||||
(data) => {
|
||||
manifest_data = data;
|
||||
},
|
||||
() => explicit_env_config,
|
||||
() => remote_metadata,
|
||||
(fn) => {
|
||||
finalise = fn;
|
||||
}
|
||||
),
|
||||
plugin_adapter(async () => await finalise?.()),
|
||||
svelte_config.adapter?.vite?.plugins?.post
|
||||
].filter(Boolean)
|
||||
);
|
||||
}
|
||||
10
node_modules/@sveltejs/kit/src/exports/vite/module_ids.js
generated
vendored
Normal file
10
node_modules/@sveltejs/kit/src/exports/vite/module_ids.js
generated
vendored
Normal file
@@ -0,0 +1,10 @@
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { posixify } from '../../utils/os.js';
|
||||
|
||||
export const app_server = posixify(
|
||||
fileURLToPath(new URL('../../runtime/app/server/index.js', import.meta.url))
|
||||
);
|
||||
|
||||
export const app_env_private = posixify(
|
||||
fileURLToPath(new URL('../../runtime/app/env/private/index.js', import.meta.url))
|
||||
);
|
||||
141
node_modules/@sveltejs/kit/src/exports/vite/plugins/env-vars.js
generated
vendored
Normal file
141
node_modules/@sveltejs/kit/src/exports/vite/plugins/env-vars.js
generated
vendored
Normal file
@@ -0,0 +1,141 @@
|
||||
/** @import { Plugin, ResolvedConfig } from 'vite' */
|
||||
/** @import { EnvVarConfig } from '@sveltejs/kit/env' */
|
||||
/** @import { ValidatedConfig } from 'types' */
|
||||
import path from 'node:path';
|
||||
import { exactRegex } from '@rolldown/pluginutils';
|
||||
import MagicString from 'magic-string';
|
||||
import * as sync from '../../../core/sync/sync.js';
|
||||
import { create_env_modules, resolve_env_entry } from '../../../core/env.js';
|
||||
import { import_peer } from '../../../utils/import.js';
|
||||
import { write_if_changed } from '../../../core/sync/utils.js';
|
||||
import { posixify } from '../../../utils/os.js';
|
||||
|
||||
/**
|
||||
* Generate (and, in dev, maintain) the `${outDir}/generated/{build,dev}/env` modules
|
||||
* derived from `src/env.ts`
|
||||
*
|
||||
* @param {ValidatedConfig} config
|
||||
* @param {(variables: Record<string, EnvVarConfig<any>> | null) => void} callback
|
||||
* @returns {Plugin}
|
||||
*/
|
||||
export function plugin_env_vars(config, callback) {
|
||||
/** @type {string} */
|
||||
let dir;
|
||||
|
||||
/** @type {Record<string, any>} */
|
||||
let env;
|
||||
|
||||
/** @type {ResolvedConfig} */
|
||||
let resolved_config;
|
||||
|
||||
/** @type {Set<string>} */
|
||||
let deps = new Set();
|
||||
|
||||
let is_build = false;
|
||||
|
||||
/** @type {Promise<void> | undefined} */
|
||||
let generated;
|
||||
|
||||
async function generate() {
|
||||
const entry = resolve_env_entry(config, resolved_config.root);
|
||||
const synced = await sync.env(config, entry, resolved_config.root, resolved_config.mode);
|
||||
|
||||
deps = synced.deps;
|
||||
|
||||
const vars = synced.variables;
|
||||
callback(vars);
|
||||
|
||||
const modules = create_env_modules(
|
||||
config,
|
||||
vars,
|
||||
env,
|
||||
dir,
|
||||
entry && posixify(path.relative(dir, entry)),
|
||||
!is_build
|
||||
);
|
||||
|
||||
for (const [file, code] of Object.entries(modules)) {
|
||||
write_if_changed(`${dir}/${file}`, code);
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
name: 'vite-plugin-sveltekit-env-vars',
|
||||
|
||||
async configResolved(c) {
|
||||
resolved_config = c;
|
||||
|
||||
const vite = await import_peer('vite', c.root);
|
||||
env = vite.loadEnv(c.mode, path.resolve(c.root, config.env.dir), '');
|
||||
|
||||
is_build = c.command === 'build';
|
||||
|
||||
dir = posixify(
|
||||
path.resolve(c.root, config.outDir, `generated/${is_build ? 'build' : 'dev'}/env`)
|
||||
);
|
||||
},
|
||||
|
||||
async buildStart() {
|
||||
// runs once via the memo — per-process, whichever environment starts first
|
||||
// (environment names vary by adapter), and never in the postbuild forks,
|
||||
// which resolve the config without building
|
||||
await (generated ??= generate());
|
||||
},
|
||||
|
||||
async hotUpdate({ type, file }) {
|
||||
// runs for every environment; the generated modules are shared, so do the work once
|
||||
if (this.environment.name !== 'client') return;
|
||||
|
||||
const created = type === 'create' && file === resolve_env_entry(config, resolved_config.root);
|
||||
if (!deps.has(file) && !created) return;
|
||||
|
||||
await generate();
|
||||
if (type !== 'update') this.environment.hot.send({ type: 'full-reload' });
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {() => string | null} get_service_worker_entry_file
|
||||
* @returns {Plugin}
|
||||
*/
|
||||
export function plugin_service_worker_env_vars(get_service_worker_entry_file) {
|
||||
/** @type {string | null} */
|
||||
let service_worker_entry_file;
|
||||
|
||||
/** @satisfies {Plugin} */
|
||||
const plugin = {
|
||||
name: 'vite-plugin-sveltekit-service-worker-env',
|
||||
configResolved() {
|
||||
service_worker_entry_file = get_service_worker_entry_file();
|
||||
|
||||
if (service_worker_entry_file) {
|
||||
plugin.transform.filter = {
|
||||
id: exactRegex(service_worker_entry_file)
|
||||
};
|
||||
}
|
||||
},
|
||||
applyToEnvironment(environment) {
|
||||
return !!service_worker_entry_file && environment.config.consumer === 'client';
|
||||
},
|
||||
transform: {
|
||||
filter: {},
|
||||
handler(code, id) {
|
||||
// prepend the service worker with an import that configures
|
||||
// `env`, in case `$app/env/public` is imported. In production
|
||||
// this is required: dynamic public env vars aren't known at
|
||||
// build time, so `env.js` is loaded at runtime. In dev, the
|
||||
// imported module just inlines the current values instead.
|
||||
const transformed = new MagicString(code).prepend(
|
||||
"import '<sveltekit:generated>/env/service-worker.js';\n"
|
||||
);
|
||||
return {
|
||||
code: transformed.toString(),
|
||||
map: transformed.generateMap({ source: id, hires: true })
|
||||
};
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
return plugin;
|
||||
}
|
||||
231
node_modules/@sveltejs/kit/src/exports/vite/plugins/guard.js
generated
vendored
Normal file
231
node_modules/@sveltejs/kit/src/exports/vite/plugins/guard.js
generated
vendored
Normal file
@@ -0,0 +1,231 @@
|
||||
/** @import { TopLevelFilterExpression } from '@rolldown/pluginutils' */
|
||||
/** @import { ManifestData, ValidatedConfig } from 'types' */
|
||||
/** @import { Plugin } from 'vite' */
|
||||
import path from 'node:path';
|
||||
import { and, exactRegex, importerId, include, not } from '@rolldown/pluginutils';
|
||||
import { app_env_private, app_server } from '../module_ids.js';
|
||||
import {
|
||||
error_for_missing_config,
|
||||
is_server_only_path,
|
||||
normalize_id,
|
||||
query_pattern,
|
||||
remote_module_pattern,
|
||||
server_only_directory_pattern,
|
||||
server_only_module_pattern
|
||||
} from '../utils.js';
|
||||
import * as e from '../../../messages/build-errors.js';
|
||||
import { posixify } from '../../../utils/os.js';
|
||||
|
||||
const server_only_module_with_query_pattern = /[/.]server\.[^/?]+\?/;
|
||||
|
||||
/**
|
||||
* Ensures that client-side code can't accidentally import server-side code,
|
||||
* whether in `*.server.js` files, `$app/server`, any `/server/` directory, or `$app/env/private`
|
||||
* @param {ValidatedConfig} kit
|
||||
* @param {() => { vite: typeof import('vite'); root: string; normalized_aliases: Array<{ alias: string, path: string }>; service_worker_entry_file: string | null; }} get_config
|
||||
* @param {() => ManifestData} get_manifest_data
|
||||
* @returns {Plugin}
|
||||
*/
|
||||
export function plugin_guard(kit, get_config, get_manifest_data) {
|
||||
/** @type {string} */
|
||||
let root;
|
||||
|
||||
/** @type {string} */
|
||||
let normalized_cwd;
|
||||
/** @type {Array<{ alias: string, path: string }>} */
|
||||
let normalized_aliases;
|
||||
/** @type {string} */
|
||||
let normalized_node_modules;
|
||||
/** @type {string} */
|
||||
let normalized_routes;
|
||||
/** @type {string} */
|
||||
let normalized_assets;
|
||||
|
||||
/** @type {string | null} */
|
||||
let service_worker_entry_file;
|
||||
|
||||
/** @type {Map<string, Set<string>>} */
|
||||
const import_map = new Map();
|
||||
|
||||
return {
|
||||
name: 'vite-plugin-sveltekit-guard',
|
||||
|
||||
// Run this plugin before built-in resolution, so that relative imports
|
||||
// are added to the module graph
|
||||
enforce: 'pre',
|
||||
|
||||
configResolved() {
|
||||
/** @type {typeof import('vite')} */
|
||||
let vite;
|
||||
({ vite, root, normalized_aliases, service_worker_entry_file } = get_config());
|
||||
|
||||
normalized_cwd = vite.normalizePath(root);
|
||||
normalized_node_modules = vite.normalizePath(path.resolve(root, 'node_modules'));
|
||||
normalized_routes = vite.normalizePath(path.resolve(root, kit.files.routes));
|
||||
normalized_assets = vite.normalizePath(path.resolve(root, kit.files.assets));
|
||||
},
|
||||
|
||||
applyToEnvironment(environment) {
|
||||
// the import map is only read for client-side violations in `load`, so skip other environments
|
||||
return environment.config.consumer === 'client';
|
||||
},
|
||||
|
||||
resolveId: {
|
||||
// composable filters are not accepted type-wise but still work during build
|
||||
// see https://github.com/vitejs/rolldown-vite/issues/605
|
||||
filter: /** @type {any} */ (
|
||||
/** @satisfies {TopLevelFilterExpression[]} */ ([
|
||||
include(and(importerId(/.+/), not(importerId(/index\.html$/))))
|
||||
])
|
||||
),
|
||||
async handler(id, importer, options) {
|
||||
// composable filters only work during build so we still need this guard for dev
|
||||
// see https://github.com/vitejs/rolldown-vite/issues/605
|
||||
if (importer && !importer.endsWith('index.html')) {
|
||||
const resolved = await this.resolve(id, importer, options);
|
||||
|
||||
if (resolved) {
|
||||
const normalized = normalize_id(resolved.id, normalized_aliases, normalized_cwd);
|
||||
|
||||
let importers = import_map.get(normalized);
|
||||
|
||||
if (!importers) {
|
||||
importers = new Set();
|
||||
import_map.set(normalized, importers);
|
||||
}
|
||||
|
||||
importers.add(normalize_id(importer, normalized_aliases, normalized_cwd));
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
load: {
|
||||
filter: {
|
||||
id: [
|
||||
exactRegex(app_server),
|
||||
exactRegex(app_env_private),
|
||||
server_only_module_pattern,
|
||||
// `server_only_module_pattern` won't match if the query contains a `/`
|
||||
server_only_module_with_query_pattern,
|
||||
server_only_directory_pattern
|
||||
]
|
||||
},
|
||||
handler(id) {
|
||||
const normalized = normalize_id(id, normalized_aliases, normalized_cwd);
|
||||
|
||||
const is_server_only =
|
||||
normalized === '$app/env/private' ||
|
||||
normalized === '$app/server' ||
|
||||
is_server_only_path(id.replace(query_pattern, ''), {
|
||||
root: normalized_cwd,
|
||||
node_modules: normalized_node_modules,
|
||||
routes: normalized_routes,
|
||||
assets: normalized_assets
|
||||
});
|
||||
|
||||
if (!is_server_only) return;
|
||||
|
||||
const manifest_data = get_manifest_data();
|
||||
|
||||
/** @type {Set<string>} */
|
||||
const entrypoints = new Set();
|
||||
|
||||
/**
|
||||
* Entrypoints must be normalized like the import map keys, or files
|
||||
* outside the project root (e.g. hooks) would never match an importer
|
||||
* @param {string} file - absolute, or relative to the project root
|
||||
*/
|
||||
const add_entrypoint = (file) => {
|
||||
entrypoints.add(
|
||||
normalize_id(posixify(path.resolve(root, file)), normalized_aliases, normalized_cwd)
|
||||
);
|
||||
};
|
||||
|
||||
for (const node of manifest_data.nodes) {
|
||||
if (node.component) add_entrypoint(node.component);
|
||||
if (node.universal) add_entrypoint(node.universal);
|
||||
}
|
||||
|
||||
if (manifest_data.hooks.client) add_entrypoint(manifest_data.hooks.client);
|
||||
if (manifest_data.hooks.universal) add_entrypoint(manifest_data.hooks.universal);
|
||||
|
||||
// param matchers run in the browser when `router.resolution` is `'client'`
|
||||
if (manifest_data.params && kit.router.resolution === 'client') {
|
||||
add_entrypoint(manifest_data.params);
|
||||
}
|
||||
|
||||
if (service_worker_entry_file) {
|
||||
add_entrypoint(service_worker_entry_file);
|
||||
}
|
||||
|
||||
// Walk up the import graph from the server-only module, looking for a chain
|
||||
// that leads back to a client entrypoint. We search all candidates (not just
|
||||
// the first) because a module can be imported by both server and client code,
|
||||
// and a greedy first-match could follow a server-only branch that never
|
||||
// reaches an entrypoint — see https://github.com/sveltejs/kit/issues/16232
|
||||
/** @type {Set<string>} */
|
||||
let visited = new Set([normalized]);
|
||||
|
||||
/**
|
||||
* @param {string} current
|
||||
* @param {string[]} chain
|
||||
* @param {(id: string) => boolean} is_target
|
||||
* @returns {string[] | null}
|
||||
*/
|
||||
function find_chain(current, chain, is_target) {
|
||||
const importers = import_map.get(current);
|
||||
if (!importers) return null;
|
||||
|
||||
for (const importer of importers) {
|
||||
if (visited.has(importer)) continue;
|
||||
visited.add(importer);
|
||||
|
||||
const next_chain = [...chain, importer];
|
||||
if (is_target(importer)) {
|
||||
return next_chain;
|
||||
}
|
||||
const result = find_chain(importer, next_chain, is_target);
|
||||
if (result) return result;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
let chain = find_chain(normalized, [normalized], (id) => entrypoints.has(id));
|
||||
|
||||
if (!chain) {
|
||||
// This module is being loaded into the client bundle, so it must be reachable from
|
||||
// client code even if none of the known entrypoints import it. Fail closed rather
|
||||
// than letting it through, and report the chain back to whatever module pulled it in
|
||||
visited = new Set([normalized]);
|
||||
chain = find_chain(normalized, [normalized], (id) => !import_map.has(id)) ?? [normalized];
|
||||
}
|
||||
|
||||
if (
|
||||
!kit.experimental.remoteFunctions &&
|
||||
chain.some((id) => remote_module_pattern.test(id))
|
||||
) {
|
||||
error_for_missing_config('remote functions', 'experimental.remoteFunctions', 'true');
|
||||
}
|
||||
|
||||
const pyramid = chain
|
||||
.reverse()
|
||||
.map((id, i) => {
|
||||
return `${' '.repeat(i + 1)}${id}`;
|
||||
})
|
||||
.join(' imports\n');
|
||||
|
||||
if (remote_module_pattern.test(id)) {
|
||||
e.remote_module_server_only({ module: normalized, chain: pyramid }, { stackless: true });
|
||||
}
|
||||
|
||||
e.server_only_import({ module: normalized, chain: pyramid }, { stackless: true });
|
||||
}
|
||||
},
|
||||
|
||||
// avoid watch mode rebuilds using stale import map data
|
||||
buildEnd() {
|
||||
import_map.clear();
|
||||
}
|
||||
};
|
||||
}
|
||||
237
node_modules/@sveltejs/kit/src/exports/vite/plugins/remote.js
generated
vendored
Normal file
237
node_modules/@sveltejs/kit/src/exports/vite/plugins/remote.js
generated
vendored
Normal file
@@ -0,0 +1,237 @@
|
||||
/** @import { RemoteChunk, RemoteInternals, ServerMetadata, ValidatedConfig } from 'types' */
|
||||
/** @import { Plugin, ViteDevServer } from 'vite' */
|
||||
import path from 'node:path';
|
||||
import { prefixRegex } from '@rolldown/pluginutils';
|
||||
import MagicString from 'magic-string';
|
||||
import { error_for_missing_config, is_remote_module, remote_module_pattern } from '../utils.js';
|
||||
import { create_exported_declarations } from '../../../core/env.js';
|
||||
import { dedent } from '../../../core/sync/utils.js';
|
||||
import { runtime_directory } from '../../../core/utils.js';
|
||||
import { get_runner } from '../../../runner.js';
|
||||
import { hash } from '../../../utils/hash.js';
|
||||
import { s } from '../../../utils/misc.js';
|
||||
import { posixify } from '../../../utils/os.js';
|
||||
|
||||
/**
|
||||
* @param {ValidatedConfig} svelte_config
|
||||
* @param {() => { root: string; vite: typeof import('vite'); }} get_config
|
||||
* @param {() => ServerMetadata | null} get_build_metadata
|
||||
* @param {(remote_metadata: {remotes: RemoteChunk[]; remote_original_by_hash: Map<string, string>}) => void} set_remote_metadata
|
||||
* @returns {Plugin}
|
||||
*/
|
||||
export function plugin_remote(svelte_config, get_config, get_build_metadata, set_remote_metadata) {
|
||||
/** @type {string} */
|
||||
let root;
|
||||
/** @type {typeof import('vite')} */
|
||||
let vite;
|
||||
|
||||
/** @type {ViteDevServer} */
|
||||
let dev_server;
|
||||
|
||||
/** @type {ServerMetadata | null} */
|
||||
let build_metadata;
|
||||
|
||||
/** @type {RemoteChunk[]} */
|
||||
let remotes = [];
|
||||
|
||||
/** @type {Map<string, string>} Maps remote hash -> original module id */
|
||||
const remote_original_by_hash = new Map();
|
||||
/** @type {Set<string>} Track which remote hashes have already been emitted */
|
||||
const emitted_remote_hashes = new Set();
|
||||
|
||||
return {
|
||||
name: 'vite-plugin-sveltekit-remote',
|
||||
|
||||
configResolved() {
|
||||
({ root, vite } = get_config());
|
||||
},
|
||||
|
||||
configureServer(_dev_server) {
|
||||
dev_server = _dev_server;
|
||||
},
|
||||
|
||||
applyToEnvironment(environment) {
|
||||
return svelte_config.experimental.remoteFunctions && environment.name !== 'serviceWorker';
|
||||
},
|
||||
|
||||
perEnvironmentStartEndDuringDev: true,
|
||||
|
||||
buildStart() {
|
||||
// avoid stale data when building with watch mode
|
||||
if (this.meta.watchMode && this.environment.config.consumer === 'server') {
|
||||
remotes = [];
|
||||
remote_original_by_hash.clear();
|
||||
emitted_remote_hashes.clear();
|
||||
}
|
||||
|
||||
build_metadata = get_build_metadata();
|
||||
set_remote_metadata({ remotes, remote_original_by_hash });
|
||||
},
|
||||
|
||||
// prevent other plugins from resolving our remote virtual module
|
||||
resolveId: {
|
||||
filter: {
|
||||
id: prefixRegex('\0sveltekit-remote:')
|
||||
},
|
||||
handler(id) {
|
||||
return id;
|
||||
}
|
||||
},
|
||||
|
||||
load: {
|
||||
filter: {
|
||||
id: prefixRegex('\0sveltekit-remote:')
|
||||
},
|
||||
handler(id) {
|
||||
// On-the-fly generated entry point for remote file just forwards the original module
|
||||
// We're not using manualChunks because it can cause problems with circular dependencies
|
||||
// (e.g. https://github.com/sveltejs/kit/issues/14679) and module ordering in general
|
||||
// (e.g. https://github.com/sveltejs/kit/issues/14590).
|
||||
const hash_id = id.slice('\0sveltekit-remote:'.length);
|
||||
const original = remote_original_by_hash.get(hash_id);
|
||||
if (!original) throw new Error(`Expected to find metadata for remote file ${id}`);
|
||||
return `import * as m from ${s(original)};\nexport default m;`;
|
||||
}
|
||||
},
|
||||
|
||||
transform: {
|
||||
filter: {
|
||||
id: remote_module_pattern
|
||||
},
|
||||
async handler(code, id) {
|
||||
if (!is_remote_module(id)) return;
|
||||
|
||||
const file = posixify(path.relative(root, id));
|
||||
const remote = {
|
||||
hash: hash(file),
|
||||
file
|
||||
};
|
||||
|
||||
if (this.environment.config.consumer === 'server') {
|
||||
remotes.push(remote);
|
||||
|
||||
// we need to add an `await Promise.resolve()` because if the user imports this function
|
||||
// on the client AND in a load function when loading the client module we will trigger
|
||||
// an import during dev. During a link preload, the module can be mistakenly
|
||||
// loaded and transformed twice and the first time all its exports would be undefined
|
||||
// triggering a dev server error. By adding a microtask we ensure that the module is fully loaded
|
||||
const ms = new MagicString(code);
|
||||
|
||||
// Extra newlines to prevent syntax errors around missing semicolons or comments
|
||||
ms.append(
|
||||
'\n\n' +
|
||||
dedent`
|
||||
import * as $$_self_$$ from './${path.basename(id)}';
|
||||
import { init_remote_functions as $$_init_$$ } from '@sveltejs/kit/internal/server';
|
||||
|
||||
${dev_server ? 'await Promise.resolve()' : ''}
|
||||
|
||||
$$_init_$$($$_self_$$, ${s(file)}, ${s(remote.hash)});
|
||||
|
||||
for (const [name, fn] of Object.entries($$_self_$$)) {
|
||||
fn.__.id = ${s(remote.hash)} + '/' + name;
|
||||
fn.__.name = name;
|
||||
}
|
||||
`
|
||||
);
|
||||
|
||||
// Emit a dedicated entry chunk for this remote in SSR builds (prod only)
|
||||
if (!dev_server) {
|
||||
remote_original_by_hash.set(remote.hash, id);
|
||||
|
||||
if (!emitted_remote_hashes.has(remote.hash)) {
|
||||
this.emitFile({
|
||||
type: 'chunk',
|
||||
id: `\0sveltekit-remote:${remote.hash}`,
|
||||
name: `remote-${remote.hash}`
|
||||
});
|
||||
emitted_remote_hashes.add(remote.hash);
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
code: ms.toString(),
|
||||
map: ms.generateMap({ hires: 'boundary' })
|
||||
};
|
||||
}
|
||||
|
||||
// For the client, read the exports and create a new module that only contains fetch functions with the correct metadata
|
||||
|
||||
/** @type {Map<string, RemoteInternals['type']>} */
|
||||
const map = new Map();
|
||||
|
||||
// in dev, load the server module here (which will result in this hook
|
||||
// being called again with `opts.ssr === true` if the module isn't
|
||||
// already loaded) so we can determine what it exports
|
||||
if (dev_server) {
|
||||
const module = await get_runner(vite, dev_server).import(id);
|
||||
|
||||
for (const [name, value] of Object.entries(module)) {
|
||||
const type = value?.__?.type;
|
||||
if (type) map.set(name, type);
|
||||
}
|
||||
}
|
||||
// in prod, we already built and analysed the server code before
|
||||
// building the client code, so `remotes` is populated
|
||||
else if (build_metadata?.remotes) {
|
||||
const exports = build_metadata.remotes.get(remote.hash);
|
||||
if (!exports) throw new Error('Expected to find metadata for remote file ' + id);
|
||||
|
||||
for (const [name, value] of exports) {
|
||||
map.set(name, value.type);
|
||||
}
|
||||
}
|
||||
|
||||
const { namespace, declarations, reexports } = create_exported_declarations(
|
||||
map.keys(),
|
||||
(name, ns) => `${ns}.${map.get(name)}('${remote.hash}/${name}')`,
|
||||
'__remote'
|
||||
);
|
||||
|
||||
const relative = posixify(
|
||||
path.relative(path.dirname(id), `${runtime_directory}/client/remote-functions/index.js`)
|
||||
);
|
||||
|
||||
let result = `import * as ${namespace} from '${relative}';\n\n${declarations.join('\n')}`;
|
||||
if (reexports.length > 0) {
|
||||
result += `\nexport { ${reexports.join(', ')} };`;
|
||||
}
|
||||
result += '\n';
|
||||
|
||||
if (dev_server) {
|
||||
result += `\nimport.meta.hot?.accept();\n`;
|
||||
}
|
||||
|
||||
return {
|
||||
code: result,
|
||||
map: null
|
||||
};
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {ValidatedConfig} svelte_config
|
||||
* @returns {Plugin}
|
||||
*/
|
||||
export function plugin_remote_guard(svelte_config) {
|
||||
return {
|
||||
name: 'vite-plugin-sveltekit-remote-guard',
|
||||
|
||||
applyToEnvironment() {
|
||||
return !svelte_config.experimental.remoteFunctions;
|
||||
},
|
||||
|
||||
transform: {
|
||||
filter: {
|
||||
id: new RegExp(
|
||||
`.remote(${svelte_config.moduleExtensions.join('|')})$`.replaceAll('.', '\\.')
|
||||
)
|
||||
},
|
||||
handler() {
|
||||
error_for_missing_config('remote functions', 'experimental.remoteFunctions', 'true');
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
283
node_modules/@sveltejs/kit/src/exports/vite/preview/index.js
generated
vendored
Normal file
283
node_modules/@sveltejs/kit/src/exports/vite/preview/index.js
generated
vendored
Normal file
@@ -0,0 +1,283 @@
|
||||
/** @import { NextHandleFunction } from 'connect' */
|
||||
/** @import { PreviewServer } from 'vite' */
|
||||
/** @import { ValidatedConfig, ServerModule } from 'types' */
|
||||
import fs from 'node:fs';
|
||||
import { join } from 'node:path';
|
||||
import { pathToFileURL } from 'node:url';
|
||||
import { lookup } from '../../../utils/mime.js';
|
||||
import sirv from 'sirv';
|
||||
import { loadEnv, normalizePath } from 'vite';
|
||||
import { createReadableStream, getRequest, setResponse } from '../../../exports/node/index.js';
|
||||
import { SVELTE_KIT_ASSETS } from '../../../constants.js';
|
||||
import { relative_pathname } from '../../../utils/url.js';
|
||||
import { is_chrome_devtools_request, not_found } from '../utils.js';
|
||||
import { set_error_stack } from '../../../utils/error.js';
|
||||
import * as e from '../../../messages/build-errors.js';
|
||||
|
||||
/**
|
||||
* @param {PreviewServer} vite
|
||||
* @param {ValidatedConfig} svelte_config
|
||||
*/
|
||||
export async function preview(vite, svelte_config) {
|
||||
const { paths } = svelte_config;
|
||||
const base = paths.base;
|
||||
const assets = paths.assets ? SVELTE_KIT_ASSETS : paths.base;
|
||||
|
||||
const protocol = vite.config.preview.https ? 'https' : 'http';
|
||||
|
||||
const etag = `"${Date.now()}"`;
|
||||
|
||||
const dir = join(svelte_config.outDir, 'output/server');
|
||||
|
||||
if (!fs.existsSync(`${dir}/manifest.js`)) {
|
||||
e.preview_build_missing({ dir }, { stackless: true });
|
||||
}
|
||||
|
||||
const instrumentation = join(dir, 'instrumentation.server.js');
|
||||
if (fs.existsSync(instrumentation)) {
|
||||
await import(pathToFileURL(instrumentation).href);
|
||||
}
|
||||
|
||||
/** @type {ServerModule} */
|
||||
const { configure } = await import(pathToFileURL(join(dir, 'index.js')).href);
|
||||
|
||||
/** @type {{ manifest: import('types').SSRManifest }} */
|
||||
const { manifest } = await import(pathToFileURL(join(dir, 'manifest.js')).href);
|
||||
|
||||
/** @type {import('types').ServerInstance} */
|
||||
let server;
|
||||
|
||||
try {
|
||||
server = await configure({
|
||||
manifest,
|
||||
env: loadEnv(vite.config.mode, svelte_config.env.dir, ''),
|
||||
read: (file) => createReadableStream(`${dir}/${file}`),
|
||||
assets
|
||||
});
|
||||
|
||||
await server.init();
|
||||
} catch (error) {
|
||||
// Vite erases the error message when starting the preview server so we store
|
||||
// it in the stack instead. This ensures errors thrown using `stackless`
|
||||
// are still readable
|
||||
if (error instanceof Error) set_error_stack(error, error.message);
|
||||
throw error;
|
||||
}
|
||||
|
||||
const emulator = await svelte_config.adapter?.emulate?.();
|
||||
|
||||
return () => {
|
||||
// Remove the base middleware. It screws with the URL.
|
||||
// It also only lets through requests beginning with the base path, so that requests beginning
|
||||
// with the assets URL never reach us. We could serve assets separately before the base
|
||||
// middleware, but we'd need that to occur after the compression and cors middlewares, so would
|
||||
// need to insert it manually into the stack, which would be at least as bad as doing this.
|
||||
for (let i = vite.middlewares.stack.length - 1; i > 0; i--) {
|
||||
// @ts-expect-error using internals
|
||||
if (vite.middlewares.stack[i].handle.name === 'viteBaseMiddleware') {
|
||||
vite.middlewares.stack.splice(i, 1);
|
||||
}
|
||||
}
|
||||
|
||||
// generated client assets and the contents of `static`
|
||||
vite.middlewares.use(
|
||||
scoped(
|
||||
assets,
|
||||
sirv(join(svelte_config.outDir, 'output/client'), {
|
||||
setHeaders: (res, pathname) => {
|
||||
// only apply to immutable directory, not e.g. version.json
|
||||
if (pathname.startsWith(`/${svelte_config.appDir}/immutable`)) {
|
||||
res.setHeader('cache-control', 'public,max-age=31536000,immutable');
|
||||
}
|
||||
}
|
||||
})
|
||||
)
|
||||
);
|
||||
|
||||
vite.middlewares.use((req, res, next) => {
|
||||
const original_url = /** @type {string} */ (req.url);
|
||||
const { pathname, search } = new URL(original_url, 'http://dummy');
|
||||
|
||||
// if `paths.base === '/a/b/c`, then the root route is `/a/b/c/`,
|
||||
// regardless of the `trailingSlash` route option
|
||||
if (base.length > 1 && pathname === base) {
|
||||
let location = base + '/';
|
||||
if (search) location += search;
|
||||
res.writeHead(307, {
|
||||
location
|
||||
});
|
||||
res.end();
|
||||
return;
|
||||
}
|
||||
|
||||
if (is_chrome_devtools_request(pathname, res)) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (pathname.startsWith(base)) {
|
||||
next();
|
||||
} else {
|
||||
res.statusCode = 404;
|
||||
not_found(req, res, base);
|
||||
}
|
||||
});
|
||||
|
||||
// prerendered dependencies
|
||||
vite.middlewares.use(
|
||||
scoped(base, mutable(join(svelte_config.outDir, 'output/prerendered/dependencies')))
|
||||
);
|
||||
|
||||
// prerendered pages (we can't just use sirv because we need to
|
||||
// preserve the correct trailingSlash behaviour)
|
||||
vite.middlewares.use(
|
||||
scoped(base, (req, res, next) => {
|
||||
let if_none_match_value = req.headers['if-none-match'];
|
||||
|
||||
if (if_none_match_value?.startsWith('W/"')) {
|
||||
if_none_match_value = if_none_match_value.substring(2);
|
||||
}
|
||||
|
||||
if (if_none_match_value === etag) {
|
||||
res.statusCode = 304;
|
||||
res.end();
|
||||
return;
|
||||
}
|
||||
|
||||
const { pathname, search } = new URL(/** @type {string} */ (req.url), 'http://dummy');
|
||||
|
||||
const dir = pathname.startsWith(`/${svelte_config.appDir}/remote/`) ? 'data' : 'pages';
|
||||
const root = join(svelte_config.outDir, `output/prerendered/${dir}`);
|
||||
let decoded = pathname;
|
||||
|
||||
try {
|
||||
decoded = decodeURI(pathname);
|
||||
} catch {
|
||||
// malformed URI
|
||||
}
|
||||
|
||||
let filename = normalizePath(join(root, decoded));
|
||||
let prerendered = is_file(filename, root);
|
||||
|
||||
if (!prerendered) {
|
||||
const has_trailing_slash = pathname.endsWith('/');
|
||||
const html_filename = `${filename}${has_trailing_slash ? 'index.html' : '.html'}`;
|
||||
|
||||
/** @type {string | undefined} */
|
||||
let redirect;
|
||||
|
||||
if (is_file(html_filename, root)) {
|
||||
filename = html_filename;
|
||||
prerendered = true;
|
||||
} else if (has_trailing_slash) {
|
||||
if (is_file(filename.slice(0, -1) + '.html', root)) {
|
||||
redirect = pathname.slice(0, -1);
|
||||
}
|
||||
} else if (is_file(filename + '/index.html', root)) {
|
||||
redirect = pathname + '/';
|
||||
}
|
||||
|
||||
if (redirect) {
|
||||
res.writeHead(308, {
|
||||
// relative so (possibly invisible) path prefixes are preserved
|
||||
location: relative_pathname(pathname, redirect) + search
|
||||
});
|
||||
|
||||
res.end();
|
||||
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
if (prerendered) {
|
||||
res.writeHead(200, {
|
||||
'content-type': lookup(pathname) || 'text/html',
|
||||
etag
|
||||
});
|
||||
|
||||
fs.createReadStream(filename).pipe(res);
|
||||
} else {
|
||||
next();
|
||||
}
|
||||
})
|
||||
);
|
||||
|
||||
// SSR
|
||||
vite.middlewares.use(async (req, res) => {
|
||||
const host = req.headers[':authority'] || req.headers.host;
|
||||
|
||||
const request = (svelte_config.adapter?.vite?.getRequest ?? getRequest)({
|
||||
base: `${protocol}://${host}`,
|
||||
request: req,
|
||||
response: res
|
||||
});
|
||||
|
||||
(svelte_config.adapter?.vite?.setResponse ?? setResponse)(
|
||||
res,
|
||||
await server.respond(request, {
|
||||
getClientAddress: () => {
|
||||
const { remoteAddress } = req.socket;
|
||||
if (remoteAddress) return remoteAddress;
|
||||
throw new Error('Could not determine clientAddress');
|
||||
},
|
||||
read: (file) => {
|
||||
if (file in manifest.server_assets) {
|
||||
return fs.readFileSync(join(dir, file));
|
||||
}
|
||||
|
||||
return fs.readFileSync(join(svelte_config.files.assets, file));
|
||||
},
|
||||
emulator
|
||||
})
|
||||
);
|
||||
});
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {string} dir
|
||||
* @returns {NextHandleFunction}
|
||||
*/
|
||||
const mutable = (dir) =>
|
||||
fs.existsSync(dir)
|
||||
? sirv(dir, {
|
||||
etag: true,
|
||||
maxAge: 0
|
||||
})
|
||||
: (_req, _res, next) => next();
|
||||
|
||||
/**
|
||||
* @param {string} scope
|
||||
* @param {NextHandleFunction} handler
|
||||
* @returns {NextHandleFunction}
|
||||
*/
|
||||
function scoped(scope, handler) {
|
||||
if (scope === '') return handler;
|
||||
|
||||
return (req, res, next) => {
|
||||
if (req.url?.startsWith(scope)) {
|
||||
const original_url = req.url;
|
||||
req.url = req.url.slice(scope.length);
|
||||
handler(req, res, () => {
|
||||
req.url = original_url;
|
||||
next();
|
||||
});
|
||||
} else {
|
||||
next();
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {string} path
|
||||
* @param {string} root
|
||||
* @returns {boolean}
|
||||
*/
|
||||
function is_file(path, root) {
|
||||
return (
|
||||
fs.existsSync(root) &&
|
||||
fs.existsSync(path) &&
|
||||
!fs.statSync(path).isDirectory() &&
|
||||
// Decoding can introduce path separators on Windows. Check containment after resolving them.
|
||||
normalizePath(fs.realpathSync(path)).startsWith(`${normalizePath(fs.realpathSync(root))}/`)
|
||||
);
|
||||
}
|
||||
587
node_modules/@sveltejs/kit/src/exports/vite/public.d.ts
generated
vendored
Normal file
587
node_modules/@sveltejs/kit/src/exports/vite/public.d.ts
generated
vendored
Normal file
@@ -0,0 +1,587 @@
|
||||
import { Adapter } from '@sveltejs/kit';
|
||||
import { Options } from '@sveltejs/vite-plugin-svelte';
|
||||
import {
|
||||
CspDirectives,
|
||||
PrerenderEntryGeneratorMismatchHandlerValue,
|
||||
PrerenderHttpErrorHandlerValue,
|
||||
PrerenderInvalidUrlHandlerValue,
|
||||
PrerenderMissingIdHandlerValue,
|
||||
PrerenderUnseenRoutesHandlerValue
|
||||
} from 'types';
|
||||
|
||||
export * from './index.js';
|
||||
|
||||
// this indirection helps make the docs look pretty
|
||||
type VitePluginSvelteOptions = Omit<Options, 'experimental'>;
|
||||
type VitePluginSvelteOptionsExperimental = Options['experimental'];
|
||||
|
||||
/**
|
||||
* An extension of [`vite-plugin-svelte`'s options](https://github.com/sveltejs/vite-plugin-svelte/blob/main/docs/config.md#svelte-options).
|
||||
*/
|
||||
export interface Config extends VitePluginSvelteOptions {
|
||||
/**
|
||||
* Your [adapter](https://svelte.dev/docs/kit/adapters) is run when executing `vite build`. It determines how the output is converted for different platforms.
|
||||
* @default undefined
|
||||
*/
|
||||
adapter?: Adapter;
|
||||
/**
|
||||
* An object containing zero or more aliases used to replace values in `import` statements. These aliases are automatically passed to Vite and TypeScript.
|
||||
*
|
||||
* This option is deprecated. Use [subpath imports](https://svelte.dev/docs/kit/$lib) instead.
|
||||
*
|
||||
* > [!NOTE] You will need to run `npm run dev` to have SvelteKit automatically generate the required alias configuration in `jsconfig.json` or `tsconfig.json`.
|
||||
* @deprecated
|
||||
* @default {}
|
||||
*/
|
||||
alias?: Record<string, string>;
|
||||
/**
|
||||
* The directory where SvelteKit keeps its stuff, including static assets (such as JS and CSS) and internally-used routes.
|
||||
*
|
||||
* If `paths.assets` is specified, there will be two app directories — `${paths.assets}/${appDir}` and `${paths.base}/${appDir}`.
|
||||
* @default "_app"
|
||||
*/
|
||||
appDir?: string;
|
||||
/**
|
||||
* [Content Security Policy](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy) configuration. CSP helps to protect your users against cross-site scripting (XSS) attacks, by limiting the places resources can be loaded from. For example, a configuration like this...
|
||||
*
|
||||
* ```js
|
||||
* /// file: vite.config.js
|
||||
* import { sveltekit } from '@sveltejs/kit/vite';
|
||||
* import { defineConfig } from 'vite';
|
||||
*
|
||||
* export default defineConfig({
|
||||
* plugins: [
|
||||
* sveltekit({
|
||||
* csp: {
|
||||
* directives: {
|
||||
* 'script-src': ['self']
|
||||
* },
|
||||
* // must be specified with either the `report-uri` or `report-to` directives, or both
|
||||
* reportOnly: {
|
||||
* 'script-src': ['self'],
|
||||
* 'report-uri': ['/']
|
||||
* }
|
||||
* }
|
||||
* })
|
||||
* ]
|
||||
* });
|
||||
* ```
|
||||
*
|
||||
* ...would prevent scripts loading from external sites. SvelteKit will augment the specified directives with nonces or hashes (depending on `mode`) for any inline styles and scripts it generates.
|
||||
*
|
||||
* To add a nonce for scripts and links manually included in `src/app.html`, you may use the placeholder `%sveltekit.nonce%` (for example `<script nonce="%sveltekit.nonce%">`).
|
||||
*
|
||||
* When pages are prerendered, the CSP header is added via a `<meta http-equiv>` tag (note that in this case, `frame-ancestors`, `report-uri` and `sandbox` directives will be ignored).
|
||||
*
|
||||
* > [!NOTE] When `mode` is `'auto'`, SvelteKit will use nonces for dynamically rendered pages and hashes for prerendered pages. Using nonces with prerendered pages is insecure and therefore forbidden.
|
||||
*
|
||||
* If this level of configuration is insufficient and you have more dynamic requirements, you can use the [`handle` hook](https://svelte.dev/docs/kit/hooks#handle) to roll your own CSP.
|
||||
*/
|
||||
csp?: {
|
||||
/**
|
||||
* Whether to use hashes or nonces to restrict `<script>` and `<style>` elements. `'auto'` will use hashes for prerendered pages, and nonces for dynamically rendered pages.
|
||||
*/
|
||||
mode?: 'hash' | 'nonce' | 'auto';
|
||||
/**
|
||||
* Directives that will be added to `Content-Security-Policy` headers.
|
||||
*/
|
||||
directives?: CspDirectives;
|
||||
/**
|
||||
* Directives that will be added to `Content-Security-Policy-Report-Only` headers.
|
||||
*/
|
||||
reportOnly?: CspDirectives;
|
||||
};
|
||||
/**
|
||||
* Protection against [cross-site request forgery (CSRF)](https://owasp.org/www-community/attacks/csrf) attacks.
|
||||
*/
|
||||
csrf?: {
|
||||
/**
|
||||
* Whether to check the incoming `origin` header for `POST`, `PUT`, `PATCH`, or `DELETE` form submissions and verify that it matches the server's origin.
|
||||
*
|
||||
* To allow people to make `POST`, `PUT`, `PATCH`, or `DELETE` requests with a `Content-Type` of `application/x-www-form-urlencoded`, `multipart/form-data`, or `text/plain` to your app from other origins, you will need to disable this option. Be careful!
|
||||
* @default true
|
||||
* @deprecated removed in 3.0. Use `trustedOrigins: ['*']` instead
|
||||
*/
|
||||
checkOrigin?: boolean;
|
||||
/**
|
||||
* An array of origins that are allowed to make cross-origin form submissions to your app.
|
||||
*
|
||||
* Each origin should be a complete origin including protocol (e.g., `https://payment-gateway.com`).
|
||||
* This is useful for allowing trusted third-party services like payment gateways or authentication providers to submit forms to your app.
|
||||
*
|
||||
* If the array contains `'*'`, all origins will be trusted. This is generally not recommended!
|
||||
*
|
||||
* > [!NOTE] Only add origins you completely trust, as this bypasses CSRF protection for those origins.
|
||||
*
|
||||
* CSRF checks only apply in production, not in local development.
|
||||
* @default []
|
||||
* @example
|
||||
* ```js
|
||||
* ['https://checkout.stripe.com', 'https://accounts.google.com']
|
||||
* ```
|
||||
*/
|
||||
trustedOrigins?: string[];
|
||||
};
|
||||
/**
|
||||
* Whether or not the app is embedded inside a larger app. If `true`, SvelteKit will add its event listeners related to navigation etc on the parent of `%sveltekit.body%` instead of `window`, and will pass `params` from the server rather than inferring them from `location.pathname`.
|
||||
* Note that it is generally not supported to embed multiple SvelteKit apps on the same page and use client-side SvelteKit features within them (things such as pushing to the history state assume a single instance).
|
||||
* @default false
|
||||
*/
|
||||
embedded?: boolean;
|
||||
/**
|
||||
* Environment variable configuration
|
||||
*/
|
||||
env?: {
|
||||
/**
|
||||
* The directory to search for `.env` files.
|
||||
* @default "."
|
||||
*/
|
||||
dir?: string;
|
||||
};
|
||||
/** Experimental features. Here be dragons. These are not subject to semantic versioning, so breaking changes or removal can happen in any release. */
|
||||
experimental?: VitePluginSvelteOptionsExperimental & {
|
||||
/**
|
||||
* Whether to enable the experimental remote functions feature. This feature is not yet stable and may be changed or removed at any time.
|
||||
* @default false
|
||||
*/
|
||||
remoteFunctions?: boolean;
|
||||
|
||||
/**
|
||||
* Whether to enable the experimental forked preloading feature using Svelte's fork API.
|
||||
* @default false
|
||||
*/
|
||||
forkPreloads?: boolean;
|
||||
};
|
||||
/**
|
||||
* Where to find various files within your project.
|
||||
* @deprecated this feature is still supported, but it's generally recommended to use [monorepos](https://levelup.video/tutorials/monorepos-with-pnpm) instead
|
||||
*/
|
||||
files?: {
|
||||
/**
|
||||
* The location of your source code.
|
||||
* @deprecated this feature is still supported, but it's generally recommended to use [monorepos](https://levelup.video/tutorials/monorepos-with-pnpm) instead
|
||||
* @default "src"
|
||||
* @since 2.28
|
||||
*/
|
||||
src?: string;
|
||||
/**
|
||||
* A place to put static files that should have stable URLs and undergo no processing, such as `favicon.ico` or `manifest.json`.
|
||||
* @deprecated this feature is still supported, but it's generally recommended to use [monorepos](https://levelup.video/tutorials/monorepos-with-pnpm) instead
|
||||
* @default "static"
|
||||
*/
|
||||
assets?: string;
|
||||
hooks?: {
|
||||
/**
|
||||
* The location of your client [hooks](https://svelte.dev/docs/kit/hooks).
|
||||
* @deprecated this feature is still supported, but it's generally recommended to use [monorepos](https://levelup.video/tutorials/monorepos-with-pnpm) instead
|
||||
* @default "src/hooks.client"
|
||||
*/
|
||||
client?: string;
|
||||
/**
|
||||
* The location of your server [hooks](https://svelte.dev/docs/kit/hooks).
|
||||
* @deprecated this feature is still supported, but it's generally recommended to use [monorepos](https://levelup.video/tutorials/monorepos-with-pnpm) instead
|
||||
* @default "src/hooks.server"
|
||||
*/
|
||||
server?: string;
|
||||
/**
|
||||
* The location of your universal [hooks](https://svelte.dev/docs/kit/hooks).
|
||||
* @deprecated this feature is still supported, but it's generally recommended to use [monorepos](https://levelup.video/tutorials/monorepos-with-pnpm) instead
|
||||
* @default "src/hooks"
|
||||
* @since 2.3.0
|
||||
*/
|
||||
universal?: string;
|
||||
};
|
||||
/**
|
||||
* A directory containing [parameter matchers](https://svelte.dev/docs/kit/advanced-routing#Matching).
|
||||
* @deprecated this feature is still supported, but it's generally recommended to use [monorepos](https://levelup.video/tutorials/monorepos-with-pnpm) instead
|
||||
* @default "src/params"
|
||||
*/
|
||||
params?: string;
|
||||
/**
|
||||
* The files that define the structure of your app (see [Routing](https://svelte.dev/docs/kit/routing)).
|
||||
* @deprecated this feature is still supported, but it's generally recommended to use [monorepos](https://levelup.video/tutorials/monorepos-with-pnpm) instead
|
||||
* @default "src/routes"
|
||||
*/
|
||||
routes?: string;
|
||||
/**
|
||||
* The location of your service worker's entry point (see [Service workers](https://svelte.dev/docs/kit/service-workers)).
|
||||
* @deprecated this feature is still supported, but it's generally recommended to use [monorepos](https://levelup.video/tutorials/monorepos-with-pnpm) instead
|
||||
* @default "src/service-worker"
|
||||
*/
|
||||
serviceWorker?: string;
|
||||
/**
|
||||
* The location of the template for HTML responses.
|
||||
* @deprecated this feature is still supported, but it's generally recommended to use [monorepos](https://levelup.video/tutorials/monorepos-with-pnpm) instead
|
||||
* @default "src/app.html"
|
||||
*/
|
||||
appTemplate?: string;
|
||||
/**
|
||||
* The location of the template for fallback error responses.
|
||||
* @deprecated this feature is still supported, but it's generally recommended to use [monorepos](https://levelup.video/tutorials/monorepos-with-pnpm) instead
|
||||
* @default "src/error.html"
|
||||
*/
|
||||
errorTemplate?: string;
|
||||
};
|
||||
/**
|
||||
* Inline CSS inside a `<style>` block at the head of the HTML. This option is a number that specifies the maximum length of a CSS file in UTF-16 code units, as specified by the [String.length](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/length) property, to be inlined. All CSS files needed for the page that are smaller than this value are merged and inlined in a `<style>` block.
|
||||
*
|
||||
* > [!NOTE] This results in fewer initial requests and can improve your [First Contentful Paint](https://web.dev/first-contentful-paint) score. However, it generates larger HTML output and reduces the effectiveness of browser caches. Use it advisedly.
|
||||
* @default 0
|
||||
*/
|
||||
inlineStyleThreshold?: number;
|
||||
/**
|
||||
* An array of file extensions that SvelteKit will treat as modules. Files with extensions that match neither `config.extensions` nor `config.moduleExtensions` will be ignored.
|
||||
* @default [".js", ".ts"]
|
||||
*/
|
||||
moduleExtensions?: string[];
|
||||
/**
|
||||
* The directory that SvelteKit writes files to during `dev` and `build`. You should exclude this directory from version control.
|
||||
* @default ".svelte-kit"
|
||||
*/
|
||||
outDir?: string;
|
||||
/**
|
||||
* Options related to the build output format
|
||||
*/
|
||||
output?: {
|
||||
/**
|
||||
* Whether to use the [HTTP `Link` header](https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/Link) to preload assets instead of the [`<link>` HTML element](https://developer.mozilla.org/en-US/docs/Web/HTML/Reference/Elements/link) for non-prerendered pages.
|
||||
*
|
||||
* Note that some web servers such as Nginx and Apache have a default header size limit which may be easily exceeded.
|
||||
* If you are using one of these web servers, you may want to leave this as `false` or configure a higher limit.
|
||||
*
|
||||
* @default false
|
||||
* @since 3.0.0
|
||||
*/
|
||||
linkHeaderPreload?: boolean;
|
||||
/**
|
||||
* SvelteKit will preload the JavaScript modules needed for the initial page to avoid import 'waterfalls', resulting in faster application startup. There
|
||||
* are three strategies with different trade-offs:
|
||||
* - `modulepreload` - uses `<link rel="modulepreload">`. This delivers the best results in Chromium-based browsers, in Firefox 115+, and Safari 17+. It is ignored in older browsers.
|
||||
* - `preload-js` - uses `<link rel="preload">`. Prevents waterfalls in Chromium and Safari, but Chromium will parse each module twice (once as a script, once as a module). Causes modules to be requested twice in Firefox. This is a good setting if you want to maximise performance for users on iOS devices at the cost of a very slight degradation for Chromium users.
|
||||
* - `preload-mjs` - uses `<link rel="preload">` but with the `.mjs` extension which prevents double-parsing in Chromium. Some static webservers will fail to serve .mjs files with a `Content-Type: application/javascript` header, which will cause your application to break. If that doesn't apply to you, this is the option that will deliver the best performance for the largest number of users, until `modulepreload` is more widely supported.
|
||||
* @default "modulepreload"
|
||||
* @since 1.8.4
|
||||
* @deprecated removed in 3.0
|
||||
*/
|
||||
preloadStrategy?: 'modulepreload' | 'preload-js' | 'preload-mjs';
|
||||
/**
|
||||
* The bundle strategy option affects how your app's JavaScript and CSS files are loaded.
|
||||
* - If `'split'`, splits the app up into multiple .js/.css files so that they are loaded lazily as the user navigates around the app. This is the default, and is recommended for most scenarios.
|
||||
* - If `'single'`, creates just one .js bundle and one .css file containing code for the entire app.
|
||||
* - If `'inline'`, inlines all JavaScript and CSS of the entire app into the HTML. The result is usable without a server (i.e. you can just open the file in your browser).
|
||||
*
|
||||
* When using `'split'`, you can also adjust the bundling behaviour by setting [`output.codeSplitting`](https://rolldown.rs/reference/OutputOptions.codeSplitting) inside your Vite config's [`build.rolldownOptions`](https://vite.dev/config/build-options#build-rolldownoptions).
|
||||
*
|
||||
* If you want to inline your assets, you'll need to set Vite's [`build.assetsInlineLimit`](https://vite.dev/config/build-options.html#build-assetsinlinelimit) option to an appropriate size then import your assets through Vite.
|
||||
*
|
||||
* ```js
|
||||
* /// file: vite.config.js
|
||||
* import { sveltekit } from '@sveltejs/kit/vite';
|
||||
* import { defineConfig } from 'vite';
|
||||
*
|
||||
* export default defineConfig({
|
||||
* plugins: [sveltekit()],
|
||||
* build: {
|
||||
* // inline all imported assets
|
||||
* assetsInlineLimit: Infinity
|
||||
* }
|
||||
* });
|
||||
* ```
|
||||
*
|
||||
* ```svelte
|
||||
* /// file: src/routes/+layout.svelte
|
||||
* <script>
|
||||
* // import the asset through Vite
|
||||
* import favicon from './favicon.png';
|
||||
* </script>
|
||||
*
|
||||
* <svelte:head>
|
||||
* <!-- this asset will be inlined as a base64 URL -->
|
||||
* <link rel="icon" href={favicon} />
|
||||
* </svelte:head>
|
||||
* ```
|
||||
* @default 'split'
|
||||
* @since 2.13.0
|
||||
*/
|
||||
bundleStrategy?: 'split' | 'single' | 'inline';
|
||||
};
|
||||
paths?: {
|
||||
/**
|
||||
* 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.
|
||||
* @default ""
|
||||
*/
|
||||
assets?: '' | `http://${string}` | `https://${string}`;
|
||||
/**
|
||||
* A root-relative path that must start, but not end with `/` (e.g. `/base-path`), unless it is the empty string. This specifies where your app is served from and allows the app to live on a non-root path. Note that you need to prepend all your root-relative links with the base value or they will point to the root of your domain, not your `base` (this is how the browser works). You can use [`resolve(...)` from `$app/paths`](https://svelte.dev/docs/kit/$app-paths#resolve) for that: `<a href="{resolve('/your-page')}">Link</a>`. If you find yourself writing this often, it may make sense to extract this into a reusable component.
|
||||
* @default ""
|
||||
*/
|
||||
base?: '' | `/${string}`;
|
||||
/**
|
||||
* The origin of your app, used for CSRF protection and prerendering.
|
||||
*
|
||||
* By default, this is `undefined`, meaning SvelteKit will derive the origin from `request.url` (which is set by the adapter, and ultimately by the platform).
|
||||
*
|
||||
* If your app is served from an origin that isn't known at request time — for example because it's deployed to a preview deployment whose URL isn't known at build time, or because it's behind a reverse proxy that doesn't pass the `host` header — you can set this to a string like `https://my-site.com`.
|
||||
*
|
||||
* This is also used as the value of `url.origin` during prerendering (when unset, it defaults to `http://sveltekit-prerender`), and as the trusted origin for CSRF checks on form submissions and remote function calls.
|
||||
*
|
||||
* @default undefined
|
||||
* @since 3.0
|
||||
*/
|
||||
origin?: string;
|
||||
/**
|
||||
* Whether to use relative asset paths.
|
||||
*
|
||||
* If `true`, paths created with `resolve()` and `asset()` imported from `$app/paths` will be replaced with relative asset paths during server-side rendering, resulting in more portable HTML.
|
||||
* If `false`, `%sveltekit.assets%` and references to build artifacts will always be root-relative paths, unless `paths.assets` is an external URL
|
||||
*
|
||||
* [Single-page app](https://svelte.dev/docs/kit/single-page-apps) fallback pages will always use absolute paths, regardless of this setting.
|
||||
*
|
||||
* If your app uses a `<base>` element, you should set this to `false`, otherwise asset URLs will incorrectly be resolved against the `<base>` URL rather than the current page.
|
||||
*
|
||||
* In 1.0, `undefined` was a valid value, which was set by default. In that case, if `paths.assets` was not external, SvelteKit would replace `%sveltekit.assets%` with a relative path and use relative paths to reference build artifacts, but `base` and `assets` imported from `$app/paths` would be as specified in your config.
|
||||
*
|
||||
* @default true
|
||||
* @since 1.9.0
|
||||
*/
|
||||
relative?: boolean;
|
||||
};
|
||||
/**
|
||||
* See [Prerendering](https://svelte.dev/docs/kit/page-options#prerender).
|
||||
*/
|
||||
prerender?: {
|
||||
/**
|
||||
* How many pages can be prerendered simultaneously. JS is single-threaded, but in cases where prerendering performance is network-bound (for example loading content from a remote CMS) this can speed things up by processing other tasks while waiting on the network response.
|
||||
* @default 1
|
||||
*/
|
||||
concurrency?: number;
|
||||
/**
|
||||
* Whether SvelteKit should find pages to prerender by following links from `entries`.
|
||||
* @default true
|
||||
*/
|
||||
crawl?: boolean;
|
||||
/**
|
||||
* An array of pages to prerender, or start crawling from (if `crawl: true`). The `*` string includes all routes containing no required `[parameters]` with optional parameters included as being empty (since SvelteKit doesn't know what value any parameters should have).
|
||||
* @default ["*"]
|
||||
*/
|
||||
entries?: Array<'*' | `/${string}`>;
|
||||
/**
|
||||
* How to respond to HTTP errors encountered while prerendering the app.
|
||||
*
|
||||
* - `'fail'` — fail the build
|
||||
* - `'ignore'` - silently ignore the failure and continue
|
||||
* - `'warn'` — continue, but print a warning
|
||||
* - `(details) => void` — a custom error handler that takes a `details` object with `status`, `path`, `referrer`, `referenceType` and `message` properties. If you `throw` from this function, the build will fail
|
||||
*
|
||||
* ```js
|
||||
* /// file: vite.config.js
|
||||
* import { sveltekit } from '@sveltejs/kit/vite';
|
||||
* import { defineConfig } from 'vite';
|
||||
*
|
||||
* export default defineConfig({
|
||||
* plugins: [
|
||||
* sveltekit({
|
||||
* prerender: {
|
||||
* handleHttpError: ({ path, referrer, message }) => {
|
||||
* // ignore deliberate link to shiny 404 page
|
||||
* if (path === '/not-found' && referrer === '/blog/how-we-built-our-404-page') {
|
||||
* return;
|
||||
* }
|
||||
*
|
||||
* // otherwise fail the build
|
||||
* throw new Error(message);
|
||||
* }
|
||||
* }
|
||||
* })
|
||||
* ]
|
||||
* });
|
||||
* ```
|
||||
*
|
||||
* @default "fail"
|
||||
* @since 1.15.7
|
||||
*/
|
||||
handleHttpError?: PrerenderHttpErrorHandlerValue;
|
||||
/**
|
||||
* How to respond when hash links from one prerendered page to another don't correspond to an `id` on the destination page.
|
||||
*
|
||||
* - `'fail'` — fail the build
|
||||
* - `'ignore'` - silently ignore the failure and continue
|
||||
* - `'warn'` — continue, but print a warning
|
||||
* - `(details) => void` — a custom error handler that takes a `details` object with `path`, `id`, `referrers` and `message` properties. If you `throw` from this function, the build will fail
|
||||
*
|
||||
* @default "fail"
|
||||
* @since 1.15.7
|
||||
*/
|
||||
handleMissingId?: PrerenderMissingIdHandlerValue;
|
||||
/**
|
||||
* How to respond when an entry generated by the `entries` export doesn't match the route it was generated from.
|
||||
*
|
||||
* - `'fail'` — fail the build
|
||||
* - `'ignore'` - silently ignore the failure and continue
|
||||
* - `'warn'` — continue, but print a warning
|
||||
* - `(details) => void` — a custom error handler that takes a `details` object with `generatedFromId`, `entry`, `matchedId` and `message` properties. If you `throw` from this function, the build will fail
|
||||
*
|
||||
* @default "fail"
|
||||
* @since 1.16.0
|
||||
*/
|
||||
handleEntryGeneratorMismatch?: PrerenderEntryGeneratorMismatchHandlerValue;
|
||||
/**
|
||||
* How to respond when a route is marked as prerenderable but has not been prerendered.
|
||||
*
|
||||
* - `'fail'` — fail the build
|
||||
* - `'ignore'` - silently ignore the failure and continue
|
||||
* - `'warn'` — continue, but print a warning
|
||||
* - `(details) => void` — a custom error handler that takes a `details` object with a `routes` property which contains all routes that haven't been prerendered. If you `throw` from this function, the build will fail
|
||||
*
|
||||
* The default behavior is to fail the build. This may be undesirable when you know that some of your routes may never be reached under certain
|
||||
* circumstances such as a CMS not returning data for a specific area, resulting in certain routes never being reached.
|
||||
*
|
||||
* @default "fail"
|
||||
* @since 2.16.0
|
||||
*/
|
||||
handleUnseenRoutes?: PrerenderUnseenRoutesHandlerValue;
|
||||
/**
|
||||
* How to respond when SvelteKit encounters a URL it cannot parse while crawling prerendered HTML (for example, an AT Protocol URL such as `at://did:plc:...`).
|
||||
*
|
||||
* - `'fail'` — fail the build
|
||||
* - `'ignore'` - silently ignore the failure and continue
|
||||
* - `'warn'` — continue, but print a warning
|
||||
* - `(details) => void` — a custom error handler that takes a `details` object with `href`, `referrer` and `message` properties. If you `throw` from this function, the build will fail
|
||||
*
|
||||
* @default "fail"
|
||||
* @since 2.67.0
|
||||
*/
|
||||
handleInvalidUrl?: PrerenderInvalidUrlHandlerValue;
|
||||
};
|
||||
router?: {
|
||||
/**
|
||||
* What type of client-side router to use.
|
||||
* - `'pathname'` is the default and means the current URL pathname determines the route
|
||||
* - `'hash'` means the route is determined by `location.hash`. In this case, SSR and prerendering are disabled. This is only recommended if `pathname` is not an option, for example because you don't control the webserver where your app is deployed.
|
||||
* It comes with some caveats: you can't use server-side rendering (or indeed any server logic), and you have to make sure that the links in your app all start with #/, or they won't work. Beyond that, everything works exactly like a normal SvelteKit app.
|
||||
*
|
||||
* @default "pathname"
|
||||
* @since 2.14.0
|
||||
*/
|
||||
type?: 'pathname' | 'hash';
|
||||
/**
|
||||
* How to determine which route to load when navigating to a new page.
|
||||
*
|
||||
* By default, SvelteKit will serve a route manifest to the browser.
|
||||
* When navigating, this manifest is used (along with the `reroute` hook, if it exists) to determine which components to load and which `load` functions to run.
|
||||
* Because everything happens on the client, this decision can be made immediately. The drawback is that the manifest needs to be
|
||||
* loaded and parsed before the first navigation can happen, which may have an impact if your app contains many routes.
|
||||
*
|
||||
* Alternatively, SvelteKit can determine the route on the server. This means that for every navigation to a path that has not yet been visited, the server will be asked to determine the route.
|
||||
* This has several advantages:
|
||||
* - The client does not need to load the routing manifest upfront, which can lead to faster initial page loads
|
||||
* - The list of routes is hidden from public view
|
||||
* - The server has an opportunity to intercept each navigation (for example through middleware in front of SvelteKit, such as a reverse proxy or your platform's edge functions), enabling (for example) A/B testing opaque to SvelteKit
|
||||
*
|
||||
* Route resolution requests are answered as soon as the route has been looked up, before the `handle` hook is invoked. To intercept them within SvelteKit itself, use the `reroute` hook, which runs for these requests too.
|
||||
*
|
||||
* The drawback is that for unvisited paths, resolution will take slightly longer (though this is mitigated by [preloading](https://svelte.dev/docs/kit/link-options#data-sveltekit-preload-data)).
|
||||
*
|
||||
* > [!NOTE] When using server-side route resolution and prerendering, the resolution is prerendered along with the route itself.
|
||||
*
|
||||
* @default "client"
|
||||
* @since 2.17.0
|
||||
*/
|
||||
resolution?: 'client' | 'server';
|
||||
};
|
||||
serviceWorker?:
|
||||
| {
|
||||
/**
|
||||
* Whether to automatically register the service worker, if it exists.
|
||||
* @default true
|
||||
*/
|
||||
register: true;
|
||||
/**
|
||||
* Options for serviceWorker.register("...", options);
|
||||
*/
|
||||
options?: RegistrationOptions;
|
||||
}
|
||||
| {
|
||||
/**
|
||||
* Whether to automatically register the service worker, if it exists.
|
||||
* @default true
|
||||
*/
|
||||
register?: false;
|
||||
};
|
||||
/**
|
||||
* Options for enabling [OpenTelemetry](https://opentelemetry.io/) tracing for SvelteKit operations.
|
||||
* @default { server: false }
|
||||
*/
|
||||
tracing?: {
|
||||
/**
|
||||
* Enables server-side [OpenTelemetry](https://opentelemetry.io/) span emission for SvelteKit operations including the [`handle` hook](https://svelte.dev/docs/kit/hooks#handle), [`load` functions](https://svelte.dev/docs/kit/load), [form actions](https://svelte.dev/docs/kit/form-actions), [`+server` handlers](https://svelte.dev/docs/kit/routing#server), and [remote functions](https://svelte.dev/docs/kit/remote-functions). Tracing — and more significantly, observability instrumentation — can have a nontrivial overhead, so consider whether you really need it, or if it might be more appropriate to turn it on in development and preview environments only.
|
||||
* @default false
|
||||
*/
|
||||
server?: boolean;
|
||||
};
|
||||
/**
|
||||
* @deprecated Add configuration to `tsconfig.json` directly
|
||||
*/
|
||||
typescript?: {
|
||||
/**
|
||||
* A function that allows you to edit the generated `tsconfig.json`. You can mutate the config (recommended) or return a new one.
|
||||
* This is useful for extending a shared `tsconfig.json` in a monorepo root, for example.
|
||||
*
|
||||
* Note that any paths configured here should be relative to the generated config file, which is written to `node_modules/$app/tsconfig.json`.
|
||||
*
|
||||
* @since 1.3.0
|
||||
*/
|
||||
config?: (config: Record<string, any>) => Record<string, any> | void;
|
||||
};
|
||||
/**
|
||||
* Client-side navigation can be buggy if you deploy a new version of your app while people are using it. If the code for the new page is already loaded, it may have stale content; if it isn't, the app's route manifest may point to a JavaScript file that no longer exists.
|
||||
* SvelteKit helps you solve this problem through version management. The current version is included in data, remote, and form action responses via the `x-sveltekit-version` header, so SvelteKit can detect new deployments without polling — for example when a navigation triggers a server `load` function, or when a remote function is called. SvelteKit also checks for new versions when the tab regains focus or becomes visible.
|
||||
* If SvelteKit encounters an error while loading the page and detects that a new version has been deployed (using the `name` specified here, which defaults to a timestamp of the build) it will fall back to traditional full-page navigation.
|
||||
* Not all navigations will result in an error though, for example if the JavaScript for the next page is already loaded. If you still want to force a full-page navigation in these cases, use `beforeNavigate`:
|
||||
* ```html
|
||||
* /// file: +layout.svelte
|
||||
* <script>
|
||||
* import { beforeNavigate } from '$app/navigation';
|
||||
* import { updated } from '$app/state';
|
||||
*
|
||||
* beforeNavigate(({ willUnload, to }) => {
|
||||
* if (updated.current && !willUnload && to?.url) {
|
||||
* location.href = to.url.href;
|
||||
* }
|
||||
* });
|
||||
* </script>
|
||||
* ```
|
||||
*
|
||||
* In addition to these checks, SvelteKit polls for new versions on an interval and sets [`updated.current`](https://svelte.dev/docs/kit/$app-state#updated) to `true` when it detects one. Set `pollInterval` to `0` to disable polling (the header- and event-based checks will still run).
|
||||
*/
|
||||
version?: {
|
||||
/**
|
||||
* The current app version string. If specified, this must be deterministic (e.g. a commit ref rather than `Math.random()` or `Date.now().toString()`), otherwise defaults to a timestamp of the build.
|
||||
*
|
||||
* For example, to use the current commit hash, you could do use `git rev-parse HEAD`:
|
||||
*
|
||||
* ```js
|
||||
* /// file: vite.config.js
|
||||
* import * as child_process from 'node:child_process';
|
||||
* import { sveltekit } from '@sveltejs/kit/vite';
|
||||
* import { defineConfig } from 'vite';
|
||||
*
|
||||
* export default defineConfig({
|
||||
* plugins: [
|
||||
* sveltekit({
|
||||
* version: {
|
||||
* name: child_process.execSync('git rev-parse HEAD').toString().trim()
|
||||
* }
|
||||
* })
|
||||
* ]
|
||||
* });
|
||||
* ```
|
||||
*/
|
||||
name?: string;
|
||||
/**
|
||||
* The interval in milliseconds to poll for version changes. If this is `0`, no polling occurs. SvelteKit also checks for new versions on server responses (via the `x-sveltekit-version` header) and when the tab regains focus or becomes visible, so polling is only needed for long-lived sessions on a single page.
|
||||
* @default 3600000
|
||||
*/
|
||||
pollInterval?: number;
|
||||
};
|
||||
}
|
||||
305
node_modules/@sveltejs/kit/src/exports/vite/static_analysis/index.js
generated
vendored
Normal file
305
node_modules/@sveltejs/kit/src/exports/vite/static_analysis/index.js
generated
vendored
Normal file
@@ -0,0 +1,305 @@
|
||||
/** @import { PageOptions } from './types.js' */
|
||||
/** @import { ESTree } from 'vite' */
|
||||
import path from 'node:path';
|
||||
import { parseSync } from 'vite';
|
||||
import { read } from '../../../utils/filesystem.js';
|
||||
|
||||
export const valid_page_options_array = /** @type {const} */ ([
|
||||
'ssr',
|
||||
'prerender',
|
||||
'csr',
|
||||
'trailingSlash',
|
||||
'config',
|
||||
'entries',
|
||||
'load'
|
||||
]);
|
||||
|
||||
/** @type {Set<string>} */
|
||||
const valid_page_options = new Set(valid_page_options_array);
|
||||
|
||||
const skip_parsing_regex = new RegExp(
|
||||
`${Array.from(valid_page_options).join('|')}|(?:export[\\s\\n]+\\*[\\s\\n]+from)`
|
||||
);
|
||||
|
||||
/**
|
||||
* Collects page options from a +page.js/+layout.js file, ignoring reassignments
|
||||
* and using the declared value (except for load functions, for which the value is `true`).
|
||||
* Returns `null` if any export is too difficult to analyse.
|
||||
* @param {string} filename The name of the file to report when an error occurs
|
||||
* @param {string} input
|
||||
* @returns {PageOptions | null}
|
||||
*/
|
||||
export function statically_analyse_page_options(filename, input) {
|
||||
// if there's a chance there are no page exports or an unparseable
|
||||
// export all declaration, then we can skip the AST parsing which is expensive
|
||||
if (!skip_parsing_regex.test(input)) {
|
||||
return {};
|
||||
}
|
||||
|
||||
try {
|
||||
const source = parseSync(filename, input, { sourceType: 'module' });
|
||||
if (source.errors.length) throw new Error(source.errors[0].message);
|
||||
|
||||
/** @type {Map<string, Extract<ESTree.Expression, { type: 'Literal' }>['value']>} */
|
||||
const page_options = new Map();
|
||||
|
||||
for (const statement of source.program.body) {
|
||||
// ignore export all declarations with aliases that are not page options
|
||||
if (
|
||||
statement.type === 'ExportAllDeclaration' &&
|
||||
statement.exported &&
|
||||
!valid_page_options.has(get_name(statement.exported))
|
||||
) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (
|
||||
statement.type === 'ExportDefaultDeclaration' ||
|
||||
statement.type === 'ExportAllDeclaration'
|
||||
) {
|
||||
return null;
|
||||
} else if (statement.type !== 'ExportNamedDeclaration') {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (statement.specifiers.length) {
|
||||
/** @type {Map<string, string>} */
|
||||
const export_specifiers = new Map();
|
||||
for (const specifier of statement.specifiers) {
|
||||
const exported_name = get_name(specifier.exported);
|
||||
if (!valid_page_options.has(exported_name)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (statement.source) {
|
||||
return null;
|
||||
}
|
||||
|
||||
export_specifiers.set(get_name(specifier.local), exported_name);
|
||||
}
|
||||
|
||||
for (const statement of source.program.body) {
|
||||
switch (statement.type) {
|
||||
case 'ImportDeclaration': {
|
||||
for (const import_specifier of statement.specifiers) {
|
||||
if (export_specifiers.has(import_specifier.local.name)) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
break;
|
||||
}
|
||||
case 'ExportNamedDeclaration':
|
||||
case 'VariableDeclaration':
|
||||
case 'FunctionDeclaration':
|
||||
case 'ClassDeclaration': {
|
||||
const declaration =
|
||||
statement.type === 'ExportNamedDeclaration' ? statement.declaration : statement;
|
||||
|
||||
if (!declaration) {
|
||||
break;
|
||||
}
|
||||
|
||||
// class and function declarations
|
||||
if (declaration.type !== 'VariableDeclaration') {
|
||||
if (
|
||||
declaration.id?.type === 'Identifier' &&
|
||||
export_specifiers.has(declaration.id.name)
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
for (const variable_declarator of declaration.declarations) {
|
||||
if (
|
||||
variable_declarator.id.type !== 'Identifier' ||
|
||||
!export_specifiers.has(variable_declarator.id.name)
|
||||
) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (variable_declarator.init?.type === 'Literal') {
|
||||
page_options.set(
|
||||
/** @type {string} */ (export_specifiers.get(variable_declarator.id.name)),
|
||||
variable_declarator.init.value
|
||||
);
|
||||
export_specifiers.delete(variable_declarator.id.name);
|
||||
continue;
|
||||
}
|
||||
|
||||
// Special case: We only want to know that 'load' is exported (in a way that doesn't cause truthy checks in other places to trigger)
|
||||
if (variable_declarator.id.name === 'load') {
|
||||
page_options.set('load', null);
|
||||
export_specifiers.delete('load');
|
||||
continue;
|
||||
}
|
||||
|
||||
// references a declaration we can't easily evaluate statically
|
||||
return null;
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// there were some export specifiers that we couldn't resolve
|
||||
if (export_specifiers.size) {
|
||||
return null;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!statement.declaration) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// class and function declarations
|
||||
if (statement.declaration.type !== 'VariableDeclaration') {
|
||||
const { id } = statement.declaration;
|
||||
if (id?.type === 'Identifier' && valid_page_options.has(id.name)) {
|
||||
// Special case: We only want to know that 'load' is exported (in a way that doesn't cause truthy checks in other places to trigger)
|
||||
if (id.name === 'load') {
|
||||
page_options.set('load', null);
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
for (const declaration of statement.declaration.declarations) {
|
||||
if (declaration.id.type !== 'Identifier') {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (!valid_page_options.has(declaration.id.name)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (declaration.init?.type === 'Literal') {
|
||||
page_options.set(declaration.id.name, declaration.init.value);
|
||||
continue;
|
||||
}
|
||||
|
||||
// Special case: We only want to know that 'load' is exported (in a way that doesn't cause truthy checks in other places to trigger)
|
||||
if (declaration.id.name === 'load') {
|
||||
page_options.set('load', null);
|
||||
continue;
|
||||
}
|
||||
|
||||
// references a declaration we can't easily evaluate statically
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
return Object.fromEntries(page_options);
|
||||
} catch (error) {
|
||||
if (error instanceof Error) {
|
||||
error.message = `Failed to statically analyse page options for ${filename}. ${error.message}`;
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {ESTree.ModuleExportName} node
|
||||
* @returns {string}
|
||||
*/
|
||||
function get_name(node) {
|
||||
return node.type === 'Identifier' ? node.name : /** @type {string} */ (node.value);
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads and statically analyses a file for page options
|
||||
* @param {string} filepath
|
||||
* @param {string} root The project root directory
|
||||
* @returns {PageOptions | null} Returns the page options for the file or `null` if unanalysable
|
||||
*/
|
||||
export function get_page_options(filepath, root) {
|
||||
const input = read(path.resolve(root, filepath));
|
||||
|
||||
try {
|
||||
const page_options = statically_analyse_page_options(filepath, input);
|
||||
if (page_options === null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return page_options;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {string} root
|
||||
*/
|
||||
export function create_node_analyser(root) {
|
||||
const static_exports = new Map();
|
||||
|
||||
/**
|
||||
* @param {string | undefined} key
|
||||
* @param {PageOptions | null} page_options
|
||||
*/
|
||||
const cache = (key, page_options) => {
|
||||
if (key) static_exports.set(key, { page_options, children: [] });
|
||||
};
|
||||
|
||||
/**
|
||||
* Computes the final page options (may include load function as `load: null`; special case) for a node (if possible). Otherwise, returns `null`.
|
||||
* @param {import('types').PageNode} node
|
||||
* @returns {PageOptions | null}
|
||||
*/
|
||||
const crawl = (node) => {
|
||||
const key = node.universal || node.server;
|
||||
if (key && static_exports.has(key)) {
|
||||
return { ...static_exports.get(key)?.page_options };
|
||||
}
|
||||
|
||||
/** @type {PageOptions} */
|
||||
let page_options = {};
|
||||
|
||||
if (node.parent) {
|
||||
const parent_options = crawl(node.parent);
|
||||
|
||||
const parent_key = node.parent.universal || node.parent.server;
|
||||
if (key && parent_key) {
|
||||
static_exports.get(parent_key)?.children.push(key);
|
||||
}
|
||||
|
||||
if (parent_options === null) {
|
||||
// if the parent cannot be analysed, we can't know what page options
|
||||
// the child node inherits, so we also mark it as unanalysable
|
||||
cache(key, null);
|
||||
return null;
|
||||
}
|
||||
|
||||
page_options = { ...parent_options };
|
||||
}
|
||||
|
||||
if (node.server) {
|
||||
const server_page_options = get_page_options(node.server, root);
|
||||
if (server_page_options === null) {
|
||||
cache(key, null);
|
||||
return null;
|
||||
}
|
||||
page_options = { ...page_options, ...server_page_options };
|
||||
}
|
||||
|
||||
if (node.universal) {
|
||||
const universal_page_options = get_page_options(node.universal, root);
|
||||
if (universal_page_options === null) {
|
||||
cache(key, null);
|
||||
return null;
|
||||
}
|
||||
page_options = { ...page_options, ...universal_page_options };
|
||||
}
|
||||
|
||||
cache(key, page_options);
|
||||
|
||||
return page_options;
|
||||
};
|
||||
|
||||
return {
|
||||
get_page_options: crawl
|
||||
};
|
||||
}
|
||||
14
node_modules/@sveltejs/kit/src/exports/vite/static_analysis/types.d.ts
generated
vendored
Normal file
14
node_modules/@sveltejs/kit/src/exports/vite/static_analysis/types.d.ts
generated
vendored
Normal file
@@ -0,0 +1,14 @@
|
||||
import type { PrerenderOption, TrailingSlash } from 'types';
|
||||
import type { valid_page_options_array } from './index.js';
|
||||
|
||||
type ValidPageOption = (typeof valid_page_options_array)[number];
|
||||
|
||||
export type PageOptions = Partial<{
|
||||
[K in ValidPageOption]: K extends 'ssr' | 'csr'
|
||||
? boolean
|
||||
: K extends 'prerender'
|
||||
? PrerenderOption
|
||||
: K extends 'trailingSlash'
|
||||
? TrailingSlash
|
||||
: any;
|
||||
}>;
|
||||
118
node_modules/@sveltejs/kit/src/exports/vite/static_analysis/utils.js
generated
vendored
Normal file
118
node_modules/@sveltejs/kit/src/exports/vite/static_analysis/utils.js
generated
vendored
Normal file
@@ -0,0 +1,118 @@
|
||||
/**
|
||||
* Check if content has children rendering (slot, @render, or children prop forwarding)
|
||||
* @param {string} content - The markup content
|
||||
* @param {boolean} is_svelte_5_plus - Whether the project uses Svelte 5+
|
||||
* @returns {boolean}
|
||||
*/
|
||||
export function has_children(content, is_svelte_5_plus) {
|
||||
return (
|
||||
content.includes('<slot') ||
|
||||
(is_svelte_5_plus &&
|
||||
(content.includes('{@render') ||
|
||||
// children may be forwarded to a child component as a prop
|
||||
content.includes('{children}') ||
|
||||
content.includes('children={')))
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if a match position is within a comment or a string
|
||||
* @param {string} content - The full content
|
||||
* @param {number} match_index - The index where the match starts
|
||||
* @returns {boolean} - True if the match is within a comment
|
||||
*/
|
||||
export function should_ignore(content, match_index) {
|
||||
// Track if we're inside different types of quotes and comments
|
||||
let in_single_quote = false;
|
||||
let in_double_quote = false;
|
||||
let in_template_literal = false;
|
||||
let in_single_line_comment = false;
|
||||
let in_multi_line_comment = false;
|
||||
let in_html_comment = false;
|
||||
|
||||
for (let i = 0; i < match_index; i++) {
|
||||
const char = content[i];
|
||||
const next_two = content.slice(i, i + 2);
|
||||
const next_four = content.slice(i, i + 4);
|
||||
|
||||
// Handle end of single line comment
|
||||
if (in_single_line_comment && char === '\n') {
|
||||
in_single_line_comment = false;
|
||||
continue;
|
||||
}
|
||||
|
||||
// Handle end of multi-line comment
|
||||
if (in_multi_line_comment && next_two === '*/') {
|
||||
in_multi_line_comment = false;
|
||||
i++; // Skip the '/' part
|
||||
continue;
|
||||
}
|
||||
|
||||
// Handle end of HTML comment
|
||||
if (in_html_comment && content.slice(i, i + 3) === '-->') {
|
||||
in_html_comment = false;
|
||||
i += 2; // Skip the '-->' part
|
||||
continue;
|
||||
}
|
||||
|
||||
// If we're in any comment, skip processing
|
||||
if (in_single_line_comment || in_multi_line_comment || in_html_comment) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// Handle escape sequences in strings
|
||||
if ((in_single_quote || in_double_quote || in_template_literal) && char === '\\') {
|
||||
i++; // Skip the escaped character
|
||||
continue;
|
||||
}
|
||||
|
||||
// Handle string boundaries
|
||||
if (!in_double_quote && !in_template_literal && char === "'") {
|
||||
in_single_quote = !in_single_quote;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!in_single_quote && !in_template_literal && char === '"') {
|
||||
in_double_quote = !in_double_quote;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!in_single_quote && !in_double_quote && char === '`') {
|
||||
in_template_literal = !in_template_literal;
|
||||
continue;
|
||||
}
|
||||
|
||||
// If we're inside any string, don't process comment delimiters
|
||||
if (in_single_quote || in_double_quote || in_template_literal) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// Check for comment starts
|
||||
if (next_two === '//') {
|
||||
in_single_line_comment = true;
|
||||
i++; // Skip the second '/'
|
||||
continue;
|
||||
}
|
||||
|
||||
if (next_two === '/*') {
|
||||
in_multi_line_comment = true;
|
||||
i++; // Skip the '*'
|
||||
continue;
|
||||
}
|
||||
|
||||
if (next_four === '<!--') {
|
||||
in_html_comment = true;
|
||||
i += 3; // Skip the '<!--'
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
in_single_line_comment ||
|
||||
in_multi_line_comment ||
|
||||
in_html_comment ||
|
||||
in_single_quote ||
|
||||
in_double_quote ||
|
||||
in_template_literal
|
||||
);
|
||||
}
|
||||
3
node_modules/@sveltejs/kit/src/exports/vite/types.d.ts
generated
vendored
Normal file
3
node_modules/@sveltejs/kit/src/exports/vite/types.d.ts
generated
vendored
Normal file
@@ -0,0 +1,3 @@
|
||||
export interface EnforcedConfig {
|
||||
[key: string]: EnforcedConfig | true;
|
||||
}
|
||||
361
node_modules/@sveltejs/kit/src/exports/vite/utils.js
generated
vendored
Normal file
361
node_modules/@sveltejs/kit/src/exports/vite/utils.js
generated
vendored
Normal file
@@ -0,0 +1,361 @@
|
||||
/** @import { UserConfig } from 'vite' */
|
||||
/** @import { EnforcedConfig } from './types.js' */
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import process from 'node:process';
|
||||
import { posixify } from '../../utils/os.js';
|
||||
import { negotiate } from '../../utils/http.js';
|
||||
import { escape_html } from '../../utils/escape.js';
|
||||
import { escape_for_regexp } from '../../utils/regex.js';
|
||||
import * as e from '../../messages/build-errors.js';
|
||||
import * as w from '../../messages/build-warnings.js';
|
||||
import { app_server, app_env_private } from './module_ids.js';
|
||||
import { bullet_list } from '../../utils/format.js';
|
||||
|
||||
/**
|
||||
* Transforms alias to a valid vite.resolve.alias array.
|
||||
*
|
||||
* Related to tsconfig path alias creation.
|
||||
*
|
||||
* @param {import('types').ValidatedConfig} config
|
||||
* @param {string} root
|
||||
*/
|
||||
export function get_config_aliases(config, root) {
|
||||
/** @type {import('vite').Alias[]} */
|
||||
const alias = [];
|
||||
|
||||
for (let [key, value] of Object.entries(config.alias)) {
|
||||
value = posixify(value);
|
||||
if (value.endsWith('/*')) {
|
||||
value = value.slice(0, -2);
|
||||
}
|
||||
if (key.endsWith('/*')) {
|
||||
// Doing just `{ find: key.slice(0, -2) ,..}` would mean `import .. from "key"` would also be matched, which we don't want
|
||||
alias.push({
|
||||
find: new RegExp(`^${escape_for_regexp(key.slice(0, -2))}\\/(.+)$`),
|
||||
replacement: `${posixify(path.resolve(root, value))}/$1`
|
||||
});
|
||||
} else if (key + '/*' in config.alias) {
|
||||
// key and key/* both exist -> the replacement for key needs to happen _only_ on import .. from "key"
|
||||
alias.push({
|
||||
find: new RegExp(`^${escape_for_regexp(key)}$`),
|
||||
replacement: posixify(path.resolve(root, value))
|
||||
});
|
||||
} else {
|
||||
alias.push({ find: key, replacement: posixify(path.resolve(root, value)) });
|
||||
}
|
||||
}
|
||||
|
||||
return alias;
|
||||
}
|
||||
|
||||
/**
|
||||
* Silently respond with 404 for Chrome DevTools workspaces request.
|
||||
* Chrome always requests this at the root, regardless of base path.
|
||||
* Users who want workspaces can install `vite-plugin-devtools-json`,
|
||||
* which takes precedence as Vite plugin middleware runs first.
|
||||
* @param {string} pathname
|
||||
* @param {import('http').ServerResponse} res
|
||||
* @returns {boolean} `true` if the request was handled
|
||||
*/
|
||||
export function is_chrome_devtools_request(pathname, res) {
|
||||
if (pathname === '/.well-known/appspecific/com.chrome.devtools.json') {
|
||||
res.writeHead(404);
|
||||
res.end('not found');
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {import('http').IncomingMessage} req
|
||||
* @param {import('http').ServerResponse} res
|
||||
* @param {string} base
|
||||
*/
|
||||
export function not_found(req, res, base) {
|
||||
const type = negotiate(req.headers.accept ?? '*', ['text/plain', 'text/html']);
|
||||
|
||||
// special case — handle `/` request automatically
|
||||
if (req.url === '/' && type === 'text/html') {
|
||||
res.statusCode = 307;
|
||||
res.setHeader('location', base);
|
||||
res.end();
|
||||
return;
|
||||
}
|
||||
|
||||
res.statusCode = 404;
|
||||
|
||||
const prefixed = base + req.url;
|
||||
|
||||
if (type === 'text/html') {
|
||||
res.setHeader('Content-Type', 'text/html');
|
||||
res.end(
|
||||
`The server is configured with a public base URL of ${escape_html(
|
||||
base
|
||||
)} - did you mean to visit <a href="${escape_html(prefixed, true)}">${escape_html(
|
||||
prefixed
|
||||
)}</a> instead?`
|
||||
);
|
||||
} else {
|
||||
res.end(
|
||||
`The server is configured with a public base URL of ${escape_html(
|
||||
base
|
||||
)} - did you mean to visit ${escape_html(prefixed)} instead?`
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export const query_pattern = /\?.*$/s;
|
||||
|
||||
/**
|
||||
* Removes cwd path from the start of the id and replaces any `#`-prefixed
|
||||
* import alias target paths with their alias names.
|
||||
* @param {string} id
|
||||
* @param {Array<{ alias: string, path: string }>} aliases — sorted by path length descending
|
||||
* @param {string} cwd
|
||||
*/
|
||||
export function normalize_id(id, aliases, cwd) {
|
||||
id = id.replace(query_pattern, '');
|
||||
|
||||
// check before the cwd is removed — in a user's app these modules live
|
||||
// inside `node_modules`, i.e. within the cwd
|
||||
if (id === app_server) {
|
||||
return '$app/server';
|
||||
}
|
||||
|
||||
if (id === app_env_private) {
|
||||
return '$app/env/private';
|
||||
}
|
||||
|
||||
for (const { alias, path } of aliases) {
|
||||
if (id === path || id.startsWith(path + '/')) {
|
||||
id = id.replace(path, alias);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (id.startsWith(cwd + '/')) {
|
||||
id = path.relative(cwd, id);
|
||||
}
|
||||
|
||||
return posixify(id);
|
||||
}
|
||||
|
||||
export const remote_module_pattern = /[/.]remote\.[^/]+$/;
|
||||
|
||||
/**
|
||||
* A cache of which directories can export remote modules
|
||||
* @type {Map<string, boolean>}
|
||||
*/
|
||||
const remote_module_cache = new Map();
|
||||
|
||||
/**
|
||||
* Whether `id` is a remote module. Files in node_modules only count if the
|
||||
* package they belong to has a peer dependency on `@sveltejs/kit`
|
||||
* @param {string} id
|
||||
* @returns {boolean}
|
||||
*/
|
||||
export function is_remote_module(id) {
|
||||
id = posixify(id);
|
||||
if (!remote_module_pattern.test(id)) return false;
|
||||
if (!id.includes('node_modules')) return true;
|
||||
|
||||
return can_export_remote_module(path.dirname(id));
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {string} directory
|
||||
* @returns {boolean}
|
||||
*/
|
||||
function can_export_remote_module(directory) {
|
||||
let cached = remote_module_cache.get(directory);
|
||||
if (cached !== undefined) return cached;
|
||||
|
||||
let pkg;
|
||||
|
||||
try {
|
||||
pkg = JSON.parse(fs.readFileSync(path.join(directory, 'package.json'), 'utf8'));
|
||||
} catch {}
|
||||
|
||||
if (pkg?.peerDependencies?.['@sveltejs/kit']) {
|
||||
cached = true;
|
||||
} else {
|
||||
const parent = path.dirname(directory);
|
||||
|
||||
cached =
|
||||
path.basename(directory) === 'node_modules' || parent === directory
|
||||
? false // base case
|
||||
: can_export_remote_module(parent); // recurse
|
||||
}
|
||||
|
||||
remote_module_cache.set(directory, cached);
|
||||
return cached;
|
||||
}
|
||||
|
||||
export const server_only_module_pattern = /[/.]server\.[^/]+$/;
|
||||
export const server_only_directory_pattern = /\/server\//;
|
||||
|
||||
/**
|
||||
* Whether a module inside the project is server-only because of its filename (e.g. `foo.server.js`)
|
||||
* or because it is inside a `server` directory. Only the part of the path inside the project root
|
||||
* is considered, so that a project located in a `server` directory isn't treated as server-only.
|
||||
* Modules outside the root or in `node_modules` are never considered server-only by path.
|
||||
* @param {string} id posixified absolute path of the module
|
||||
* @param {{ root: string; node_modules: string; routes: string; assets: string }} dirs posixified absolute paths
|
||||
* @returns {boolean}
|
||||
*/
|
||||
export function is_server_only_path(id, { root, node_modules, routes, assets }) {
|
||||
if (!id.startsWith(root + '/') || id.startsWith(node_modules + '/')) return false;
|
||||
|
||||
const relative = id.slice(root.length);
|
||||
|
||||
return (
|
||||
server_only_module_pattern.test(relative) ||
|
||||
(server_only_directory_pattern.test(relative) &&
|
||||
!id.startsWith(routes + '/') &&
|
||||
!id.startsWith(assets + '/'))
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* For `error_for_missing_config('remote functions', 'experimental.remoteFunctions', 'true')`,
|
||||
* returns:
|
||||
*
|
||||
* ```
|
||||
* To enable remote functions, add the following to the SvelteKit plugin in your `vite.config.js`:
|
||||
*
|
||||
*\`\`\`js
|
||||
* experimental: {
|
||||
* remoteFunctions: true
|
||||
* }
|
||||
*\`\`\`
|
||||
*```
|
||||
* @param {string} feature_name
|
||||
* @param {string} path
|
||||
* @param {string} value
|
||||
* @returns {never}
|
||||
*/
|
||||
export function error_for_missing_config(feature_name, path, value) {
|
||||
e.config_feature_disabled(
|
||||
{ feature: feature_name, config: config_snippet(path, value) },
|
||||
{ stackless: true }
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Formats the config needed to set the option at `path` to `value`, nesting objects as needed
|
||||
* @param {string} path a keypath such as `experimental.remoteFunctions`
|
||||
* @param {string} value
|
||||
*/
|
||||
export function config_snippet(path, value) {
|
||||
const hole = '__HOLE__';
|
||||
|
||||
return path.split('.').reduce((acc, part, i, parts) => {
|
||||
const indent = ' '.repeat(i);
|
||||
const rhs = i === parts.length - 1 ? value : `{\n${hole}\n${indent}}`;
|
||||
|
||||
return acc.replace(hole, `${indent}${part}: ${rhs}`);
|
||||
}, hole);
|
||||
}
|
||||
|
||||
/** @type {EnforcedConfig} */
|
||||
export const enforced_config = {
|
||||
appType: true,
|
||||
base: true,
|
||||
build: {
|
||||
cssCodeSplit: true,
|
||||
emptyOutDir: true,
|
||||
lib: {
|
||||
entry: true,
|
||||
name: true,
|
||||
formats: true
|
||||
},
|
||||
manifest: true,
|
||||
outDir: true,
|
||||
rolldownOptions: {
|
||||
input: true,
|
||||
output: {
|
||||
format: true,
|
||||
entryFileNames: true,
|
||||
chunkFileNames: true,
|
||||
assetFileNames: true
|
||||
},
|
||||
preserveEntrySignatures: true
|
||||
},
|
||||
ssr: true
|
||||
},
|
||||
publicDir: true,
|
||||
resolve: {
|
||||
alias: {
|
||||
$app: true,
|
||||
$env: true,
|
||||
'<sveltekit:generated>': true
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* @param {UserConfig} config
|
||||
* @param {UserConfig} resolved_config
|
||||
*/
|
||||
export function warn_overridden_config(config, resolved_config) {
|
||||
const overridden = find_overridden_config(config, resolved_config, enforced_config, '', []);
|
||||
|
||||
if (overridden.length > 0) {
|
||||
w.vite_config_overridden({ options: bullet_list(overridden) });
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {Record<string, any>} config
|
||||
* @param {Record<string, any>} resolved_config
|
||||
* @param {EnforcedConfig} enforced_config
|
||||
* @param {string} path
|
||||
* @param {string[]} out used locally to compute the return value
|
||||
*/
|
||||
export function find_overridden_config(config, resolved_config, enforced_config, path, out) {
|
||||
if (config == null || resolved_config == null) {
|
||||
return out;
|
||||
}
|
||||
|
||||
for (const key in enforced_config) {
|
||||
if (typeof config === 'object' && key in config && key in resolved_config) {
|
||||
const enforced = enforced_config[key];
|
||||
const resolved = resolved_config[key];
|
||||
|
||||
if (enforced === true) {
|
||||
if (comparable(config[key]) !== comparable(resolved)) {
|
||||
out.push(path + key);
|
||||
}
|
||||
} else {
|
||||
find_overridden_config(config[key], resolved, enforced, path + key + '.', out);
|
||||
}
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* Normalizes a config value for comparison, since Windows paths may use backslashes
|
||||
* and differ in casing (e.g. the drive letter) depending on where they came from.
|
||||
* @param {any} value
|
||||
*/
|
||||
export function comparable(value) {
|
||||
if (typeof value !== 'string') return value;
|
||||
const normalized = posixify(value);
|
||||
return process.platform === 'win32' ? normalized.toLowerCase() : normalized;
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether a plugin uses the `transformIndexHtml` hook, which SvelteKit apps don't support
|
||||
* @param {import('vite').Plugin} plugin
|
||||
* @returns {boolean}
|
||||
*/
|
||||
export function uses_unsupported_html_hook(plugin) {
|
||||
// Vitest and Storybook invoke this hook for their own HTML, not the SvelteKit app
|
||||
return (
|
||||
!!plugin.transformIndexHtml &&
|
||||
plugin.name !== 'vitest:browser:loader' &&
|
||||
!plugin.name?.includes('storybook')
|
||||
);
|
||||
}
|
||||
948
node_modules/@sveltejs/kit/src/messages/build-errors.js
generated
vendored
Normal file
948
node_modules/@sveltejs/kit/src/messages/build-errors.js
generated
vendored
Normal file
@@ -0,0 +1,948 @@
|
||||
/* This file is generated by scripts/process-messages/index.js. Do not edit! */
|
||||
|
||||
/** @import { ThrowOptions } from './internal/build.js' */
|
||||
import { throw_error } from './internal/build.js';
|
||||
|
||||
/**
|
||||
* The `generateManifest` adapter API has been removed — use `generateServerInstance` or `builder.manifest` instead. You may need to update your adapter
|
||||
* @param {void} _values
|
||||
* @param {ThrowOptions} [options]
|
||||
* @returns {never}
|
||||
*/
|
||||
export function adapter_generate_manifest_removed(_values, options) {
|
||||
throw_error('adapter_generate_manifest_removed', `The \`generateManifest\` adapter API has been removed — use \`generateServerInstance\` or \`builder.manifest\` instead. You may need to update your adapter`, options, adapter_generate_manifest_removed);
|
||||
}
|
||||
|
||||
/**
|
||||
* %kind% `%file%` not found. This is probably a bug in your adapter.
|
||||
* @param {{ "kind": string; "file": string }} _values
|
||||
* @param {ThrowOptions} [options]
|
||||
* @returns {never}
|
||||
*/
|
||||
export function adapter_instrumentation_file_missing(_values, options) {
|
||||
throw_error('adapter_instrumentation_file_missing', `${_values.kind} \`${_values.file}\` not found. This is probably a bug in your adapter.`, options, adapter_instrumentation_file_missing);
|
||||
}
|
||||
|
||||
/**
|
||||
* `%file%` is unsupported in `%adapter%`.
|
||||
* @param {{ "file": string; "adapter": string }} _values
|
||||
* @param {ThrowOptions} [options]
|
||||
* @returns {never}
|
||||
*/
|
||||
export function adapter_instrumentation_unsupported(_values, options) {
|
||||
throw_error('adapter_instrumentation_unsupported', `\`${_values.file}\` is unsupported in \`${_values.adapter}\`.`, options, adapter_instrumentation_unsupported);
|
||||
}
|
||||
|
||||
/**
|
||||
* Cannot use `read` from `$app/server` in `%route%` when using `%adapter%`. Please ensure that your adapter is up to date and supports this feature.
|
||||
* @param {{ "route": string; "adapter": string }} _values
|
||||
* @param {ThrowOptions} [options]
|
||||
* @returns {never}
|
||||
*/
|
||||
export function adapter_read_unsupported(_values, options) {
|
||||
throw_error('adapter_read_unsupported', `Cannot use \`read\` from \`$app/server\` in \`${_values.route}\` when using \`${_values.adapter}\`. Please ensure that your adapter is up to date and supports this feature.`, options, adapter_read_unsupported);
|
||||
}
|
||||
|
||||
/**
|
||||
* %file% does not exist
|
||||
* @param {{ "file": string }} _values
|
||||
* @param {ThrowOptions} [options]
|
||||
* @returns {never}
|
||||
*/
|
||||
export function app_template_missing(_values, options) {
|
||||
throw_error('app_template_missing', `${_values.file} does not exist`, options, app_template_missing);
|
||||
}
|
||||
|
||||
/**
|
||||
* %file% is missing `%tag%`
|
||||
* @param {{ "file": string; "tag": string }} _values
|
||||
* @param {ThrowOptions} [options]
|
||||
* @returns {never}
|
||||
*/
|
||||
export function app_template_tag_missing(_values, options) {
|
||||
throw_error('app_template_tag_missing', `${_values.file} is missing \`${_values.tag}\``, options, app_template_tag_missing);
|
||||
}
|
||||
|
||||
/**
|
||||
* Invalid alias key: `%key%`
|
||||
* @param {{ "key": string }} _values
|
||||
* @param {ThrowOptions} [options]
|
||||
* @returns {never}
|
||||
*/
|
||||
export function config_alias_key_invalid(_values, options) {
|
||||
throw_error('config_alias_key_invalid', `Invalid alias key: \`${_values.key}\``, options, config_alias_key_invalid);
|
||||
}
|
||||
|
||||
/**
|
||||
* Invalid alias value: `%value%`
|
||||
* @param {{ "value": string }} _values
|
||||
* @param {ThrowOptions} [options]
|
||||
* @returns {never}
|
||||
*/
|
||||
export function config_alias_value_invalid(_values, options) {
|
||||
throw_error('config_alias_value_invalid', `Invalid alias value: \`${_values.value}\``, options, config_alias_value_invalid);
|
||||
}
|
||||
|
||||
/**
|
||||
* `%keypath%` cannot start or end with `'/'`
|
||||
* @param {{ "keypath": string }} _values
|
||||
* @param {ThrowOptions} [options]
|
||||
* @returns {never}
|
||||
*/
|
||||
export function config_app_dir_slash(_values, options) {
|
||||
throw_error('config_app_dir_slash', `\`${_values.keypath}\` cannot start or end with \`'/'\``, options, config_app_dir_slash);
|
||||
}
|
||||
|
||||
/**
|
||||
* The `csp.directives['trusted-types']` option must include `'svelte-trusted-html'` unless all pages have `csr: false`
|
||||
* @param {void} _values
|
||||
* @param {ThrowOptions} [options]
|
||||
* @returns {never}
|
||||
*/
|
||||
export function config_csp_trusted_html_missing(_values, options) {
|
||||
throw_error('config_csp_trusted_html_missing', `The \`csp.directives['trusted-types']\` option must include \`'svelte-trusted-html'\` unless all pages have \`csr: false\``, options, config_csp_trusted_html_missing);
|
||||
}
|
||||
|
||||
/**
|
||||
* The `csp.directives['trusted-types']` option must include `'sveltekit-trusted-url'` when `serviceWorker.register` is `true`
|
||||
* @param {void} _values
|
||||
* @param {ThrowOptions} [options]
|
||||
* @returns {never}
|
||||
*/
|
||||
export function config_csp_trusted_types_missing(_values, options) {
|
||||
throw_error('config_csp_trusted_types_missing', `The \`csp.directives['trusted-types']\` option must include \`'sveltekit-trusted-url'\` when \`serviceWorker.register\` is \`true\``, options, config_csp_trusted_types_missing);
|
||||
}
|
||||
|
||||
/**
|
||||
* `%keypath%` cannot be empty
|
||||
* @param {{ "keypath": string }} _values
|
||||
* @param {ThrowOptions} [options]
|
||||
* @returns {never}
|
||||
*/
|
||||
export function config_empty_string(_values, options) {
|
||||
throw_error('config_empty_string', `\`${_values.keypath}\` cannot be empty`, options, config_empty_string);
|
||||
}
|
||||
|
||||
/**
|
||||
* `%keypath%` should be true or false, if specified
|
||||
* @param {{ "keypath": string }} _values
|
||||
* @param {ThrowOptions} [options]
|
||||
* @returns {never}
|
||||
*/
|
||||
export function config_expected_boolean(_values, options) {
|
||||
throw_error('config_expected_boolean', `\`${_values.keypath}\` should be true or false, if specified`, options, config_expected_boolean);
|
||||
}
|
||||
|
||||
/**
|
||||
* `%keypath%` should be a function, if specified
|
||||
* @param {{ "keypath": string }} _values
|
||||
* @param {ThrowOptions} [options]
|
||||
* @returns {never}
|
||||
*/
|
||||
export function config_expected_function(_values, options) {
|
||||
throw_error('config_expected_function', `\`${_values.keypath}\` should be a function, if specified`, options, config_expected_function);
|
||||
}
|
||||
|
||||
/**
|
||||
* `%keypath%` should be a number, if specified
|
||||
* @param {{ "keypath": string }} _values
|
||||
* @param {ThrowOptions} [options]
|
||||
* @returns {never}
|
||||
*/
|
||||
export function config_expected_number(_values, options) {
|
||||
throw_error('config_expected_number', `\`${_values.keypath}\` should be a number, if specified`, options, config_expected_number);
|
||||
}
|
||||
|
||||
/**
|
||||
* `%keypath%` should be an object
|
||||
* @param {{ "keypath": string }} _values
|
||||
* @param {ThrowOptions} [options]
|
||||
* @returns {never}
|
||||
*/
|
||||
export function config_expected_object(_values, options) {
|
||||
throw_error('config_expected_object', `\`${_values.keypath}\` should be an object`, options, config_expected_object);
|
||||
}
|
||||
|
||||
/**
|
||||
* `%keypath%` should be %options%
|
||||
* @param {{ "keypath": string; "options": string }} _values
|
||||
* @param {ThrowOptions} [options]
|
||||
* @returns {never}
|
||||
*/
|
||||
export function config_expected_one_of(_values, options) {
|
||||
throw_error('config_expected_one_of', `\`${_values.keypath}\` should be ${_values.options}`, options, config_expected_one_of);
|
||||
}
|
||||
|
||||
/**
|
||||
* `%keypath%` should be a positive integer, if specified
|
||||
* @param {{ "keypath": string }} _values
|
||||
* @param {ThrowOptions} [options]
|
||||
* @returns {never}
|
||||
*/
|
||||
export function config_expected_positive_integer(_values, options) {
|
||||
throw_error('config_expected_positive_integer', `\`${_values.keypath}\` should be a positive integer, if specified`, options, config_expected_positive_integer);
|
||||
}
|
||||
|
||||
/**
|
||||
* `%keypath%` should be a string, if specified
|
||||
* @param {{ "keypath": string }} _values
|
||||
* @param {ThrowOptions} [options]
|
||||
* @returns {never}
|
||||
*/
|
||||
export function config_expected_string(_values, options) {
|
||||
throw_error('config_expected_string', `\`${_values.keypath}\` should be a string, if specified`, options, config_expected_string);
|
||||
}
|
||||
|
||||
/**
|
||||
* `%keypath%` should be an array of strings, if specified
|
||||
* @param {{ "keypath": string }} _values
|
||||
* @param {ThrowOptions} [options]
|
||||
* @returns {never}
|
||||
*/
|
||||
export function config_expected_string_array(_values, options) {
|
||||
throw_error('config_expected_string_array', `\`${_values.keypath}\` should be an array of strings, if specified`, options, config_expected_string_array);
|
||||
}
|
||||
|
||||
/**
|
||||
* File extensions must be alphanumeric — saw `'%extension%'`
|
||||
* @param {{ "extension": string }} _values
|
||||
* @param {ThrowOptions} [options]
|
||||
* @returns {never}
|
||||
*/
|
||||
export function config_extension_invalid(_values, options) {
|
||||
throw_error('config_extension_invalid', `File extensions must be alphanumeric — saw \`'${_values.extension}'\``, options, config_extension_invalid);
|
||||
}
|
||||
|
||||
/**
|
||||
* Each member of %keypath% must start with `'.'` — saw `'%extension%'`
|
||||
* @param {{ "keypath": string; "extension": string }} _values
|
||||
* @param {ThrowOptions} [options]
|
||||
* @returns {never}
|
||||
*/
|
||||
export function config_extension_missing_dot(_values, options) {
|
||||
throw_error('config_extension_missing_dot', `Each member of ${_values.keypath} must start with \`'.'\` — saw \`'${_values.extension}'\``, options, config_extension_missing_dot);
|
||||
}
|
||||
|
||||
/**
|
||||
* To enable %feature%, add the following to your SvelteKit plugin in `vite.config.js`:
|
||||
|
||||
%config%
|
||||
* @param {{ "feature": string; "config": string }} _values
|
||||
* @param {ThrowOptions} [options]
|
||||
* @returns {never}
|
||||
*/
|
||||
export function config_feature_disabled(_values, options) {
|
||||
throw_error('config_feature_disabled', `To enable ${_values.feature}, add the following to your SvelteKit plugin in \`vite.config.js\`:
|
||||
|
||||
${_values.config}`, options, config_feature_disabled);
|
||||
}
|
||||
|
||||
/**
|
||||
* `%file%` is no longer used. Please pass configuration via the `sveltekit(...)` plugin in your Vite config.
|
||||
* @param {{ "file": string }} _values
|
||||
* @param {ThrowOptions} [options]
|
||||
* @returns {never}
|
||||
*/
|
||||
export function config_file_unsupported(_values, options) {
|
||||
throw_error('config_file_unsupported', `\`${_values.file}\` is no longer used. Please pass configuration via the \`sveltekit(...)\` plugin in your Vite config.`, options, config_file_unsupported);
|
||||
}
|
||||
|
||||
/**
|
||||
* The SvelteKit Vite plugin `%keypath%` should be an object with an `adapt` method
|
||||
* @param {{ "keypath": string }} _values
|
||||
* @param {ThrowOptions} [options]
|
||||
* @returns {never}
|
||||
*/
|
||||
export function config_invalid_adapter(_values, options) {
|
||||
throw_error('config_invalid_adapter', `The SvelteKit Vite plugin \`${_values.keypath}\` should be an object with an \`adapt\` method`, options, config_invalid_adapter);
|
||||
}
|
||||
|
||||
/**
|
||||
* `%keypath%` should be `'fail'`, `'warn'`, `'ignore'` or a custom function
|
||||
* @param {{ "keypath": string }} _values
|
||||
* @param {ThrowOptions} [options]
|
||||
* @returns {never}
|
||||
*/
|
||||
export function config_invalid_prerender_handler(_values, options) {
|
||||
throw_error('config_invalid_prerender_handler', `\`${_values.keypath}\` should be \`'fail'\`, \`'warn'\`, \`'ignore'\` or a custom function`, options, config_invalid_prerender_handler);
|
||||
}
|
||||
|
||||
/**
|
||||
* SvelteKit configuration (%keys%) no longer lives inside a `kit` namespace. Pass it directly to the `sveltekit(...)` Vite plugin
|
||||
* @param {{ "keys": string }} _values
|
||||
* @param {ThrowOptions} [options]
|
||||
* @returns {never}
|
||||
*/
|
||||
export function config_kit_namespace(_values, options) {
|
||||
throw_error('config_kit_namespace', `SvelteKit configuration (${_values.keys}) no longer lives inside a \`kit\` namespace. Pass it directly to the \`sveltekit(...)\` Vite plugin`, options, config_kit_namespace);
|
||||
}
|
||||
|
||||
/**
|
||||
* The SvelteKit options from the Vite config must be an object
|
||||
* @param {void} _values
|
||||
* @param {ThrowOptions} [options]
|
||||
* @returns {never}
|
||||
*/
|
||||
export function config_not_object(_values, options) {
|
||||
throw_error('config_not_object', `The SvelteKit options from the Vite config must be an object`, options, config_not_object);
|
||||
}
|
||||
|
||||
/**
|
||||
* The `%keypath%` option has been removed. Please see the list of breaking changes for your major release
|
||||
* @param {{ "keypath": string }} _values
|
||||
* @param {ThrowOptions} [options]
|
||||
* @returns {never}
|
||||
*/
|
||||
export function config_option_removed(_values, options) {
|
||||
throw_error('config_option_removed', `The \`${_values.keypath}\` option has been removed. Please see the list of breaking changes for your major release`, options, config_option_removed);
|
||||
}
|
||||
|
||||
/**
|
||||
* `%keypath%` has been removed in favour of `csrf.trustedOrigins`
|
||||
* @param {{ "keypath": string }} _values
|
||||
* @param {ThrowOptions} [options]
|
||||
* @returns {never}
|
||||
*/
|
||||
export function config_option_removed_check_origin(_values, options) {
|
||||
throw_error('config_option_removed_check_origin', `\`${_values.keypath}\` has been removed in favour of \`csrf.trustedOrigins\``, options, config_option_removed_check_origin);
|
||||
}
|
||||
|
||||
/**
|
||||
* `%keypath%` has been removed. `src/instrumentation.server.js` is now included in the build automatically when it exists; no opt-in is required
|
||||
* @param {{ "keypath": string }} _values
|
||||
* @param {ThrowOptions} [options]
|
||||
* @returns {never}
|
||||
*/
|
||||
export function config_option_removed_experimental_instrumentation(_values, options) {
|
||||
throw_error('config_option_removed_experimental_instrumentation', `\`${_values.keypath}\` has been removed. \`src/instrumentation.server.js\` is now included in the build automatically when it exists; no opt-in is required`, options, config_option_removed_experimental_instrumentation);
|
||||
}
|
||||
|
||||
/**
|
||||
* `%keypath%` has been removed. Server-side tracing is now configured via `tracing.server`
|
||||
* @param {{ "keypath": string }} _values
|
||||
* @param {ThrowOptions} [options]
|
||||
* @returns {never}
|
||||
*/
|
||||
export function config_option_removed_experimental_tracing(_values, options) {
|
||||
throw_error('config_option_removed_experimental_tracing', `\`${_values.keypath}\` has been removed. Server-side tracing is now configured via \`tracing.server\``, options, config_option_removed_experimental_tracing);
|
||||
}
|
||||
|
||||
/**
|
||||
* `%keypath%` has been removed. Use `#lib` instead of `$lib`: https://svelte.dev/docs/kit/$lib
|
||||
* @param {{ "keypath": string }} _values
|
||||
* @param {ThrowOptions} [options]
|
||||
* @returns {never}
|
||||
*/
|
||||
export function config_option_removed_files_lib(_values, options) {
|
||||
throw_error('config_option_removed_files_lib', `\`${_values.keypath}\` has been removed. Use \`#lib\` instead of \`$lib\`: https://svelte.dev/docs/kit/$lib`, options, config_option_removed_files_lib);
|
||||
}
|
||||
|
||||
/**
|
||||
* `%keypath%` has been removed. `modulepreload` will always be used
|
||||
* @param {{ "keypath": string }} _values
|
||||
* @param {ThrowOptions} [options]
|
||||
* @returns {never}
|
||||
*/
|
||||
export function config_option_removed_preload_strategy(_values, options) {
|
||||
throw_error('config_option_removed_preload_strategy', `\`${_values.keypath}\` has been removed. \`modulepreload\` will always be used`, options, config_option_removed_preload_strategy);
|
||||
}
|
||||
|
||||
/**
|
||||
* `%keypath%` has been removed in favour of `config.paths.origin`
|
||||
* @param {{ "keypath": string }} _values
|
||||
* @param {ThrowOptions} [options]
|
||||
* @returns {never}
|
||||
*/
|
||||
export function config_option_removed_prerender_origin(_values, options) {
|
||||
throw_error('config_option_removed_prerender_origin', `\`${_values.keypath}\` has been removed in favour of \`config.paths.origin\``, options, config_option_removed_prerender_origin);
|
||||
}
|
||||
|
||||
/**
|
||||
* `%keypath%` has been removed. Pass `vite-plugin-svelte` options directly to the `sveltekit(...)` Vite plugin
|
||||
* @param {{ "keypath": string }} _values
|
||||
* @param {ThrowOptions} [options]
|
||||
* @returns {never}
|
||||
*/
|
||||
export function config_option_removed_vite_plugin(_values, options) {
|
||||
throw_error('config_option_removed_vite_plugin', `\`${_values.keypath}\` has been removed. Pass \`vite-plugin-svelte\` options directly to the \`sveltekit(...)\` Vite plugin`, options, config_option_removed_vite_plugin);
|
||||
}
|
||||
|
||||
/**
|
||||
* `%keypath%` must be a valid origin — received `'%input%'` which contains a path, query, or hash. Use the bare origin `'%origin%'` instead
|
||||
* @param {{ "keypath": string; "input": string; "origin": string }} _values
|
||||
* @param {ThrowOptions} [options]
|
||||
* @returns {never}
|
||||
*/
|
||||
export function config_origin_has_path(_values, options) {
|
||||
throw_error('config_origin_has_path', `\`${_values.keypath}\` must be a valid origin — received \`'${_values.input}'\` which contains a path, query, or hash. Use the bare origin \`'${_values.origin}'\` instead`, options, config_origin_has_path);
|
||||
}
|
||||
|
||||
/**
|
||||
* `%keypath%` must be a valid origin (e.g. 'https://my-site.com'). `'%input%'` could not be parsed as a URL
|
||||
* @param {{ "keypath": string; "input": string }} _values
|
||||
* @param {ThrowOptions} [options]
|
||||
* @returns {never}
|
||||
*/
|
||||
export function config_origin_invalid(_values, options) {
|
||||
throw_error('config_origin_invalid', `\`${_values.keypath}\` must be a valid origin (e.g. 'https://my-site.com'). \`'${_values.input}'\` could not be parsed as a URL`, options, config_origin_invalid);
|
||||
}
|
||||
|
||||
/**
|
||||
* `%keypath%` must be a valid origin — only 'http' and 'https' protocols are supported, received '%protocol%'
|
||||
* @param {{ "keypath": string; "protocol": string }} _values
|
||||
* @param {ThrowOptions} [options]
|
||||
* @returns {never}
|
||||
*/
|
||||
export function config_origin_protocol(_values, options) {
|
||||
throw_error('config_origin_protocol', `\`${_values.keypath}\` must be a valid origin — only 'http' and 'https' protocols are supported, received '${_values.protocol}'`, options, config_origin_protocol);
|
||||
}
|
||||
|
||||
/**
|
||||
* `%keypath%` option must be an absolute path, if specified
|
||||
* @param {{ "keypath": string }} _values
|
||||
* @param {ThrowOptions} [options]
|
||||
* @returns {never}
|
||||
*/
|
||||
export function config_paths_assets_not_absolute(_values, options) {
|
||||
throw_error('config_paths_assets_not_absolute', `\`${_values.keypath}\` option must be an absolute path, if specified`, options, config_paths_assets_not_absolute);
|
||||
}
|
||||
|
||||
/**
|
||||
* `%keypath%` option must not end with `'/'`
|
||||
* @param {{ "keypath": string }} _values
|
||||
* @param {ThrowOptions} [options]
|
||||
* @returns {never}
|
||||
*/
|
||||
export function config_paths_assets_trailing_slash(_values, options) {
|
||||
throw_error('config_paths_assets_trailing_slash', `\`${_values.keypath}\` option must not end with \`'/'\``, options, config_paths_assets_trailing_slash);
|
||||
}
|
||||
|
||||
/**
|
||||
* `%keypath%` option must either be the empty string or a root-relative path that starts but doesn't end with `'/'`
|
||||
* @param {{ "keypath": string }} _values
|
||||
* @param {ThrowOptions} [options]
|
||||
* @returns {never}
|
||||
*/
|
||||
export function config_paths_base_invalid(_values, options) {
|
||||
throw_error('config_paths_base_invalid', `\`${_values.keypath}\` option must either be the empty string or a root-relative path that starts but doesn't end with \`'/'\``, options, config_paths_base_invalid);
|
||||
}
|
||||
|
||||
/**
|
||||
* Each member of `%keypath%` must be either `'*'` or an absolute path beginning with `'/'` — saw `'%entry%'`
|
||||
* @param {{ "keypath": string; "entry": string }} _values
|
||||
* @param {ThrowOptions} [options]
|
||||
* @returns {never}
|
||||
*/
|
||||
export function config_prerender_entry_invalid(_values, options) {
|
||||
throw_error('config_prerender_entry_invalid', `Each member of \`${_values.keypath}\` must be either \`'*'\` or an absolute path beginning with \`'/'\` — saw \`'${_values.entry}'\``, options, config_prerender_entry_invalid);
|
||||
}
|
||||
|
||||
/**
|
||||
* The `router.resolution` option cannot be `'server'` if `output.bundleStrategy` is `'inline'` or `'single'`
|
||||
* @param {void} _values
|
||||
* @param {ThrowOptions} [options]
|
||||
* @returns {never}
|
||||
*/
|
||||
export function config_server_resolution_bundle_strategy(_values, options) {
|
||||
throw_error('config_server_resolution_bundle_strategy', `The \`router.resolution\` option cannot be \`'server'\` if \`output.bundleStrategy\` is \`'inline'\` or \`'single'\``, options, config_server_resolution_bundle_strategy);
|
||||
}
|
||||
|
||||
/**
|
||||
* The `router.resolution` option cannot be `'server'` if `router.type` is `'hash'`
|
||||
* @param {void} _values
|
||||
* @param {ThrowOptions} [options]
|
||||
* @returns {never}
|
||||
*/
|
||||
export function config_server_resolution_hash(_values, options) {
|
||||
throw_error('config_server_resolution_hash', `The \`router.resolution\` option cannot be \`'server'\` if \`router.type\` is \`'hash'\``, options, config_server_resolution_hash);
|
||||
}
|
||||
|
||||
/**
|
||||
* Unexpected option `%keypath%`
|
||||
* @param {{ "keypath": string; "suggestion"?: string }} _values
|
||||
* @param {ThrowOptions} [options]
|
||||
* @returns {never}
|
||||
*/
|
||||
export function config_unexpected_option(_values, options) {
|
||||
throw_error('config_unexpected_option', (_values?.suggestion !== undefined ? `Unexpected option \`${_values.keypath}\` (did you mean \`${_values.suggestion}\`?)` : `Unexpected option \`${_values.keypath}\``), options, config_unexpected_option);
|
||||
}
|
||||
|
||||
/**
|
||||
* Cannot import `$app/*` modules other than `$app/env` inside `src/env`
|
||||
* @param {void} _values
|
||||
* @param {ThrowOptions} [options]
|
||||
* @returns {never}
|
||||
*/
|
||||
export function env_app_import(_values, options) {
|
||||
throw_error('env_app_import', `Cannot import \`$app/*\` modules other than \`$app/env\` inside \`src/env\``, options, env_app_import);
|
||||
}
|
||||
|
||||
/**
|
||||
* Cannot import `$app/env/%type%` inside `src/env` or its dependencies because it creates a circular dependency
|
||||
* @param {{ "type": string; "importer"?: string }} _values
|
||||
* @param {ThrowOptions} [options]
|
||||
* @returns {never}
|
||||
*/
|
||||
export function env_circular_import(_values, options) {
|
||||
throw_error('env_circular_import', (_values?.importer !== undefined ? `Module \`${_values.importer}\` imports \`$app/env/${_values.type}\`, which creates a circular dependency with \`src/env\`` : `Cannot import \`$app/env/${_values.type}\` inside \`src/env\` or its dependencies because it creates a circular dependency`), options, env_circular_import);
|
||||
}
|
||||
|
||||
/**
|
||||
* Invalid environment variable name `%name%`
|
||||
* @param {{ "name": string }} _values
|
||||
* @param {ThrowOptions} [options]
|
||||
* @returns {never}
|
||||
*/
|
||||
export function env_invalid_variable_name(_values, options) {
|
||||
throw_error('env_invalid_variable_name', `Invalid environment variable name \`${_values.name}\``, options, env_invalid_variable_name);
|
||||
}
|
||||
|
||||
/**
|
||||
* `%file%` must export a variables object
|
||||
* @param {{ "file": string }} _values
|
||||
* @param {ThrowOptions} [options]
|
||||
* @returns {never}
|
||||
*/
|
||||
export function env_variables_missing(_values, options) {
|
||||
throw_error('env_variables_missing', `\`${_values.file}\` must export a variables object`, options, env_variables_missing);
|
||||
}
|
||||
|
||||
/**
|
||||
* Cannot use relative URL (`%url%`) with global `fetch` — use `event.fetch` instead: https://svelte.dev/docs/kit/web-standards#Fetch-APIs
|
||||
* @param {{ "url": string }} _values
|
||||
* @param {ThrowOptions} [options]
|
||||
* @returns {never}
|
||||
*/
|
||||
export function fetch_relative_url(_values, options) {
|
||||
throw_error('fetch_relative_url', `Cannot use relative URL (\`${_values.url}\`) with global \`fetch\` — use \`event.fetch\` instead: https://svelte.dev/docs/kit/web-standards#Fetch-APIs`, options, fetch_relative_url);
|
||||
}
|
||||
|
||||
/**
|
||||
* `$lib` has been removed. Use `#lib` instead: https://svelte.dev/docs/kit/$lib. To keep using `$lib`, add `alias: { '$lib': 'src/lib' }` to your SvelteKit config.
|
||||
* @param {void} _values
|
||||
* @param {ThrowOptions} [options]
|
||||
* @returns {never}
|
||||
*/
|
||||
export function module_removed_lib(_values, options) {
|
||||
throw_error('module_removed_lib', `\`$lib\` has been removed. Use \`#lib\` instead: https://svelte.dev/docs/kit/$lib. To keep using \`$lib\`, add \`alias: { '$lib': 'src/lib' }\` to your SvelteKit config.`, options, module_removed_lib);
|
||||
}
|
||||
|
||||
/**
|
||||
* `$service-worker` has been removed. Use `immutable`, `assets` and `prerendered` from `$app/manifest`, `version` from `$app/env`, and `resolve(...)` from `$app/paths` instead: https://svelte.dev/docs/kit/$service-worker
|
||||
* @param {void} _values
|
||||
* @param {ThrowOptions} [options]
|
||||
* @returns {never}
|
||||
*/
|
||||
export function module_removed_service_worker(_values, options) {
|
||||
throw_error('module_removed_service_worker', `\`$service-worker\` has been removed. Use \`immutable\`, \`assets\` and \`prerendered\` from \`$app/manifest\`, \`version\` from \`$app/env\`, and \`resolve(...)\` from \`$app/paths\` instead: https://svelte.dev/docs/kit/$service-worker`, options, module_removed_service_worker);
|
||||
}
|
||||
|
||||
/**
|
||||
* No matcher found for parameter `%name%`
|
||||
* @param {{ "name": string; "file"?: string }} _values
|
||||
* @param {ThrowOptions} [options]
|
||||
* @returns {never}
|
||||
*/
|
||||
export function param_matcher_missing(_values, options) {
|
||||
throw_error('param_matcher_missing', (_values?.file !== undefined ? `No matcher found for parameter \`${_values.name}\` in \`${_values.file}\`` : `No matcher found for parameter \`${_values.name}\``), options, param_matcher_missing);
|
||||
}
|
||||
|
||||
/**
|
||||
* `%file%` does not export `params` from `defineParams`
|
||||
* @param {{ "file": string }} _values
|
||||
* @param {ThrowOptions} [options]
|
||||
* @returns {never}
|
||||
*/
|
||||
export function params_export_missing(_values, options) {
|
||||
throw_error('params_export_missing', `\`${_values.file}\` does not export \`params\` from \`defineParams\``, options, params_export_missing);
|
||||
}
|
||||
|
||||
/**
|
||||
* Cannot read `clientAddress` during prerendering
|
||||
* @param {void} _values
|
||||
* @param {ThrowOptions} [options]
|
||||
* @returns {never}
|
||||
*/
|
||||
export function prerender_client_address(_values, options) {
|
||||
throw_error('prerender_client_address', `Cannot read \`clientAddress\` during prerendering`, options, prerender_client_address);
|
||||
}
|
||||
|
||||
/**
|
||||
* Cannot save `%path%` as it is already a directory. See https://svelte.dev/docs/kit/page-options#prerender-Route-conflicts for more information
|
||||
* @param {{ "path": string; "parent"?: string }} _values
|
||||
* @param {ThrowOptions} [options]
|
||||
* @returns {never}
|
||||
*/
|
||||
export function prerender_directory_conflict(_values, options) {
|
||||
throw_error('prerender_directory_conflict', (_values?.parent !== undefined ? `Cannot save \`${_values.path}\` as \`${_values.parent}\` is already a file. See https://svelte.dev/docs/kit/page-options#prerender-Route-conflicts for more information` : `Cannot save \`${_values.path}\` as it is already a directory. See https://svelte.dev/docs/kit/page-options#prerender-Route-conflicts for more information`), options, prerender_directory_conflict);
|
||||
}
|
||||
|
||||
/**
|
||||
* The `entries` export from `%id%` generated entry `%entry%`, which was matched by `%matched%`
|
||||
* @param {{ "id": string; "entry": string; "matched": string }} _values
|
||||
* @param {ThrowOptions} [options]
|
||||
* @returns {never}
|
||||
*/
|
||||
export function prerender_entry_generator_mismatch(_values, options) {
|
||||
throw_error('prerender_entry_generator_mismatch', `The \`entries\` export from \`${_values.id}\` generated entry \`${_values.entry}\`, which was matched by \`${_values.matched}\``, options, prerender_entry_generator_mismatch);
|
||||
}
|
||||
|
||||
/**
|
||||
* Could not create a fallback page
|
||||
* @param {void} _values
|
||||
* @param {ThrowOptions} [options]
|
||||
* @returns {never}
|
||||
*/
|
||||
export function prerender_fallback_failed(_values, options) {
|
||||
throw_error('prerender_fallback_failed', `Could not create a fallback page`, options, prerender_fallback_failed);
|
||||
}
|
||||
|
||||
/**
|
||||
* Failed to prerender `%path%`
|
||||
* @param {{ "path": string; "reference_type"?: string; "referrer"?: string }} _values
|
||||
* @param {ThrowOptions} [options]
|
||||
* @returns {never}
|
||||
*/
|
||||
export function prerender_http_error(_values, options) {
|
||||
throw_error('prerender_http_error', (_values?.reference_type !== undefined ? `\`${_values.path}\` was ${_values.reference_type} from \`${_values.referrer}\`` : `Failed to prerender \`${_values.path}\``), options, prerender_http_error);
|
||||
}
|
||||
|
||||
/**
|
||||
* Invalid URL `%href%`
|
||||
* @param {{ "href": string; "referrer"?: string }} _values
|
||||
* @param {ThrowOptions} [options]
|
||||
* @returns {never}
|
||||
*/
|
||||
export function prerender_invalid_url(_values, options) {
|
||||
throw_error('prerender_invalid_url', (_values?.referrer !== undefined ? `Invalid URL \`${_values.href}\` (linked from \`${_values.referrer}\`)` : `Invalid URL \`${_values.href}\``), options, prerender_invalid_url);
|
||||
}
|
||||
|
||||
/**
|
||||
* The following pages contain links to `%path%#%id%`, but no element with `id="%id%"` exists on `%path%`:
|
||||
%referrers%
|
||||
* @param {{ "path": string; "id": string; "referrers": string }} _values
|
||||
* @param {ThrowOptions} [options]
|
||||
* @returns {never}
|
||||
*/
|
||||
export function prerender_missing_id(_values, options) {
|
||||
throw_error('prerender_missing_id', `The following pages contain links to \`${_values.path}#${_values.id}\`, but no element with \`id="${_values.id}"\` exists on \`${_values.path}\`:
|
||||
${_values.referrers}`, options, prerender_missing_id);
|
||||
}
|
||||
|
||||
/**
|
||||
* `%path%` does not begin with `base`. You can fix this by using `resolve('%path%')` from `$app/paths`. The base path is configurable from `paths.base`
|
||||
* @param {{ "path": string; "reference_type"?: string; "referrer"?: string }} _values
|
||||
* @param {ThrowOptions} [options]
|
||||
* @returns {never}
|
||||
*/
|
||||
export function prerender_path_outside_base(_values, options) {
|
||||
throw_error('prerender_path_outside_base', (_values?.reference_type !== undefined ? `\`${_values.path}\` (${_values.reference_type} from \`${_values.referrer}\`) does not begin with \`base\`. You can fix this by using \`resolve('${_values.path}')\` from \`$app/paths\`. The base path is configurable from \`paths.base\`` : `\`${_values.path}\` does not begin with \`base\`. You can fix this by using \`resolve('${_values.path}')\` from \`$app/paths\`. The base path is configurable from \`paths.base\``), options, prerender_path_outside_base);
|
||||
}
|
||||
|
||||
/**
|
||||
* Cannot prerender a root `+server.js` that returns a non-HTML response — static hosts always serve an HTML file for `%base%`
|
||||
* @param {{ "base": string }} _values
|
||||
* @param {ThrowOptions} [options]
|
||||
* @returns {never}
|
||||
*/
|
||||
export function prerender_root_non_html(_values, options) {
|
||||
throw_error('prerender_root_non_html', `Cannot prerender a root \`+server.js\` that returns a non-HTML response — static hosts always serve an HTML file for \`${_values.base}\``, options, prerender_root_non_html);
|
||||
}
|
||||
|
||||
/**
|
||||
* The following routes were marked as prerenderable, but were not prerendered because they were not found while crawling your app:
|
||||
%routes%
|
||||
* @param {{ "routes": string }} _values
|
||||
* @param {ThrowOptions} [options]
|
||||
* @returns {never}
|
||||
*/
|
||||
export function prerender_unseen_routes(_values, options) {
|
||||
throw_error('prerender_unseen_routes', `The following routes were marked as prerenderable, but were not prerendered because they were not found while crawling your app:
|
||||
${_values.routes}`, options, prerender_unseen_routes);
|
||||
}
|
||||
|
||||
/**
|
||||
* Server files not found at `%dir%`, did you run `build` first?
|
||||
* @param {{ "dir": string }} _values
|
||||
* @param {ThrowOptions} [options]
|
||||
* @returns {never}
|
||||
*/
|
||||
export function preview_build_missing(_values, options) {
|
||||
throw_error('preview_build_missing', `Server files not found at \`${_values.dir}\`, did you run \`build\` first?`, options, preview_build_missing);
|
||||
}
|
||||
|
||||
/**
|
||||
* Cannot import remote module `%module%` into code that runs in the browser because it is server-only.
|
||||
|
||||
%chain%
|
||||
|
||||
Move the remote module outside any `server` directory, and remove any `server` segment from its filename.
|
||||
* @param {{ "module": string; "chain": string }} _values
|
||||
* @param {ThrowOptions} [options]
|
||||
* @returns {never}
|
||||
*/
|
||||
export function remote_module_server_only(_values, options) {
|
||||
throw_error('remote_module_server_only', `Cannot import remote module \`${_values.module}\` into code that runs in the browser because it is server-only.
|
||||
|
||||
${_values.chain}
|
||||
|
||||
Move the remote module outside any \`server\` directory, and remove any \`server\` segment from its filename.`, options, remote_module_server_only);
|
||||
}
|
||||
|
||||
/**
|
||||
* Unexpectedly called `prerender` function. Did you forget to set `{ dynamic: true }`?
|
||||
* @param {void} _values
|
||||
* @param {ThrowOptions} [options]
|
||||
* @returns {never}
|
||||
*/
|
||||
export function remote_prerender_not_dynamic(_values, options) {
|
||||
throw_error('remote_prerender_not_dynamic', `Unexpectedly called \`prerender\` function. Did you forget to set \`{ dynamic: true }\`?`, options, remote_prerender_not_dynamic);
|
||||
}
|
||||
|
||||
/**
|
||||
* Mismatched route config for `%id%` — the `+page` and `+server` files must export the same config, if any
|
||||
* @param {{ "id": string }} _values
|
||||
* @param {ThrowOptions} [options]
|
||||
* @returns {never}
|
||||
*/
|
||||
export function route_config_mismatch(_values, options) {
|
||||
throw_error('route_config_mismatch', `Mismatched route config for \`${_values.id}\` — the \`+page\` and \`+server\` files must export the same config, if any`, options, route_config_mismatch);
|
||||
}
|
||||
|
||||
/**
|
||||
* The `%first%` and `%second%` routes conflict with each other
|
||||
* @param {{ "first": string; "second": string }} _values
|
||||
* @param {ThrowOptions} [options]
|
||||
* @returns {never}
|
||||
*/
|
||||
export function route_conflict(_values, options) {
|
||||
throw_error('route_conflict', `The \`${_values.first}\` and \`${_values.second}\` routes conflict with each other`, options, route_conflict);
|
||||
}
|
||||
|
||||
/**
|
||||
* Multiple %type% files found in `%directory%` : `%existing%` and `%file%`
|
||||
* @param {{ "type": string; "directory": string; "existing": string; "file": string }} _values
|
||||
* @param {ThrowOptions} [options]
|
||||
* @returns {never}
|
||||
*/
|
||||
export function route_duplicate_files(_values, options) {
|
||||
throw_error('route_duplicate_files', `Multiple ${_values.type} files found in \`${_values.directory}\` : \`${_values.existing}\` and \`${_values.file}\``, options, route_duplicate_files);
|
||||
}
|
||||
|
||||
/**
|
||||
* Hexadecimal escape sequence in `%id%` must be two characters
|
||||
* @param {{ "id": string }} _values
|
||||
* @param {ThrowOptions} [options]
|
||||
* @returns {never}
|
||||
*/
|
||||
export function route_escape_hex_length(_values, options) {
|
||||
throw_error('route_escape_hex_length', `Hexadecimal escape sequence in \`${_values.id}\` must be two characters`, options, route_escape_hex_length);
|
||||
}
|
||||
|
||||
/**
|
||||
* Invalid character escape sequence in `%id%`
|
||||
* @param {{ "id": string }} _values
|
||||
* @param {ThrowOptions} [options]
|
||||
* @returns {never}
|
||||
*/
|
||||
export function route_escape_invalid(_values, options) {
|
||||
throw_error('route_escape_invalid', `Invalid character escape sequence in \`${_values.id}\``, options, route_escape_invalid);
|
||||
}
|
||||
|
||||
/**
|
||||
* Unicode escape sequence in `%id%` must be between four and six characters
|
||||
* @param {{ "id": string }} _values
|
||||
* @param {ThrowOptions} [options]
|
||||
* @returns {never}
|
||||
*/
|
||||
export function route_escape_unicode_length(_values, options) {
|
||||
throw_error('route_escape_unicode_length', `Unicode escape sequence in \`${_values.id}\` must be between four and six characters`, options, route_escape_unicode_length);
|
||||
}
|
||||
|
||||
/**
|
||||
* Character escape sequence in `%id%` must be lowercase
|
||||
* @param {{ "id": string }} _values
|
||||
* @param {ThrowOptions} [options]
|
||||
* @returns {never}
|
||||
*/
|
||||
export function route_escape_uppercase(_values, options) {
|
||||
throw_error('route_escape_uppercase', `Character escape sequence in \`${_values.id}\` must be lowercase`, options, route_escape_uppercase);
|
||||
}
|
||||
|
||||
/**
|
||||
* Files prefixed with `+` are reserved (saw `%file%`)
|
||||
* @param {{ "file": string }} _values
|
||||
* @param {ThrowOptions} [options]
|
||||
* @returns {never}
|
||||
*/
|
||||
export function route_file_reserved(_values, options) {
|
||||
throw_error('route_file_reserved', `Files prefixed with \`+\` are reserved (saw \`${_values.file}\`)`, options, route_file_reserved);
|
||||
}
|
||||
|
||||
/**
|
||||
* Route `%id%` should be renamed to %suggestion%
|
||||
* @param {{ "id": string; "suggestion": string }} _values
|
||||
* @param {ThrowOptions} [options]
|
||||
* @returns {never}
|
||||
*/
|
||||
export function route_hash_character(_values, options) {
|
||||
throw_error('route_hash_character', `Route \`${_values.id}\` should be renamed to ${_values.suggestion}`, options, route_hash_character);
|
||||
}
|
||||
|
||||
/**
|
||||
* `%file%` references missing segment `%segment%`
|
||||
* @param {{ "file": string; "segment": string }} _values
|
||||
* @param {ThrowOptions} [options]
|
||||
* @returns {never}
|
||||
*/
|
||||
export function route_layout_segment_missing(_values, options) {
|
||||
throw_error('route_layout_segment_missing', `\`${_values.file}\` references missing segment \`${_values.segment}\``, options, route_layout_segment_missing);
|
||||
}
|
||||
|
||||
/**
|
||||
* Only Svelte files can reference named layouts. Remove `%layout%` from `%name%` (at `%file%`)
|
||||
* @param {{ "layout": string; "name": string; "file": string }} _values
|
||||
* @param {ThrowOptions} [options]
|
||||
* @returns {never}
|
||||
*/
|
||||
export function route_named_layout_in_module(_values, options) {
|
||||
throw_error('route_named_layout_in_module', `Only Svelte files can reference named layouts. Remove \`${_values.layout}\` from \`${_values.name}\` (at \`${_values.file}\`)`, options, route_named_layout_in_module);
|
||||
}
|
||||
|
||||
/**
|
||||
* Invalid route `%id%` — an `[[optional]]` route segment cannot follow a `[...rest]` route segment
|
||||
* @param {{ "id": string }} _values
|
||||
* @param {ThrowOptions} [options]
|
||||
* @returns {never}
|
||||
*/
|
||||
export function route_optional_after_rest(_values, options) {
|
||||
throw_error('route_optional_after_rest', `Invalid route \`${_values.id}\` — an \`[[optional]]\` route segment cannot follow a \`[...rest]\` route segment`, options, route_optional_after_rest);
|
||||
}
|
||||
|
||||
/**
|
||||
* Invalid route `%id%` — a rest route segment is always optional, remove the outer square brackets
|
||||
* @param {{ "id": string }} _values
|
||||
* @param {ThrowOptions} [options]
|
||||
* @returns {never}
|
||||
*/
|
||||
export function route_optional_rest(_values, options) {
|
||||
throw_error('route_optional_rest', `Invalid route \`${_values.id}\` — a rest route segment is always optional, remove the outer square brackets`, options, route_optional_rest);
|
||||
}
|
||||
|
||||
/**
|
||||
* Invalid param: %param% in route `%id%`. Params and matcher names can only have underscores, hyphens, and alphanumeric characters.
|
||||
* @param {{ "param": string; "id": string }} _values
|
||||
* @param {ThrowOptions} [options]
|
||||
* @returns {never}
|
||||
*/
|
||||
export function route_param_invalid(_values, options) {
|
||||
throw_error('route_param_invalid', `Invalid param: ${_values.param} in route \`${_values.id}\`. Params and matcher names can only have underscores, hyphens, and alphanumeric characters.`, options, route_param_invalid);
|
||||
}
|
||||
|
||||
/**
|
||||
* Invalid route `%id%` — parameters must be separated
|
||||
* @param {{ "id": string }} _values
|
||||
* @param {ThrowOptions} [options]
|
||||
* @returns {never}
|
||||
*/
|
||||
export function route_params_adjacent(_values, options) {
|
||||
throw_error('route_params_adjacent', `Invalid route \`${_values.id}\` — parameters must be separated`, options, route_params_adjacent);
|
||||
}
|
||||
|
||||
/**
|
||||
* Cannot prerender a route (`%id%`) with both a `+page.svelte` and a `%file%`
|
||||
* @param {{ "id": string; "file": string }} _values
|
||||
* @param {ThrowOptions} [options]
|
||||
* @returns {never}
|
||||
*/
|
||||
export function route_prerender_page_and_endpoint(_values, options) {
|
||||
throw_error('route_prerender_page_and_endpoint', `Cannot prerender a route (\`${_values.id}\`) with both a \`+page.svelte\` and a \`${_values.file}\``, options, route_prerender_page_and_endpoint);
|
||||
}
|
||||
|
||||
/**
|
||||
* Cannot use server-only files in an app with `router.type === 'hash'`: `%file%`
|
||||
* @param {{ "file": string }} _values
|
||||
* @param {ThrowOptions} [options]
|
||||
* @returns {never}
|
||||
*/
|
||||
export function route_server_file_hash_router(_values, options) {
|
||||
throw_error('route_server_file_hash_router', `Cannot use server-only files in an app with \`router.type === 'hash'\`: \`${_values.file}\``, options, route_server_file_hash_router);
|
||||
}
|
||||
|
||||
/**
|
||||
* Invalid route `%id%` — brackets are unbalanced
|
||||
* @param {{ "id": string }} _values
|
||||
* @param {ThrowOptions} [options]
|
||||
* @returns {never}
|
||||
*/
|
||||
export function route_unbalanced_brackets(_values, options) {
|
||||
throw_error('route_unbalanced_brackets', `Invalid route \`${_values.id}\` — brackets are unbalanced`, options, route_unbalanced_brackets);
|
||||
}
|
||||
|
||||
/**
|
||||
* No routes found. If you are using a custom `src/routes` directory, make sure it is specified in your SvelteKit Vite plugin options
|
||||
* @param {void} _values
|
||||
* @param {ThrowOptions} [options]
|
||||
* @returns {never}
|
||||
*/
|
||||
export function routes_not_found(_values, options) {
|
||||
throw_error('routes_not_found', `No routes found. If you are using a custom \`src/routes\` directory, make sure it is specified in your SvelteKit Vite plugin options`, options, routes_not_found);
|
||||
}
|
||||
|
||||
/**
|
||||
* Cannot import `%module%` into code that runs in the browser, as this could leak sensitive information.
|
||||
|
||||
%chain%
|
||||
|
||||
If you're only using the import as a type, change it to `import type`.
|
||||
* @param {{ "module": string; "chain": string }} _values
|
||||
* @param {ThrowOptions} [options]
|
||||
* @returns {never}
|
||||
*/
|
||||
export function server_only_import(_values, options) {
|
||||
throw_error('server_only_import', `Cannot import \`${_values.module}\` into code that runs in the browser, as this could leak sensitive information.
|
||||
|
||||
${_values.chain}
|
||||
|
||||
If you're only using the import as a type, change it to \`import type\`.`, options, server_only_import);
|
||||
}
|
||||
|
||||
/**
|
||||
* Cannot use service worker alongside `config.paths.assets`
|
||||
* @param {void} _values
|
||||
* @param {ThrowOptions} [options]
|
||||
* @returns {never}
|
||||
*/
|
||||
export function service_worker_assets(_values, options) {
|
||||
throw_error('service_worker_assets', `Cannot use service worker alongside \`config.paths.assets\``, options, service_worker_assets);
|
||||
}
|
||||
|
||||
/**
|
||||
* Cannot import %modules% into service-worker code.
|
||||
* @param {{ "modules": string }} _values
|
||||
* @param {ThrowOptions} [options]
|
||||
* @returns {never}
|
||||
*/
|
||||
export function service_worker_invalid_import(_values, options) {
|
||||
throw_error('service_worker_invalid_import', `Cannot import ${_values.modules} into service-worker code.`, options, service_worker_invalid_import);
|
||||
}
|
||||
|
||||
/**
|
||||
* Failed to parse TypeScript config
|
||||
* @param {void | { "details": string }} _values
|
||||
* @param {ThrowOptions} [options]
|
||||
* @returns {never}
|
||||
*/
|
||||
export function tsconfig_parse_failed(_values, options) {
|
||||
throw_error('tsconfig_parse_failed', (_values?.details !== undefined ? `Failed to parse TypeScript config: ${_values.details}` : `Failed to parse TypeScript config`), options, tsconfig_parse_failed);
|
||||
}
|
||||
|
||||
/**
|
||||
* The configured Vite SSR environment must be a `RunnableDevEnvironment`
|
||||
* @param {void} _values
|
||||
* @param {ThrowOptions} [options]
|
||||
* @returns {never}
|
||||
*/
|
||||
export function vite_ssr_environment_not_runnable(_values, options) {
|
||||
throw_error('vite_ssr_environment_not_runnable', `The configured Vite SSR environment must be a \`RunnableDevEnvironment\``, options, vite_ssr_environment_not_runnable);
|
||||
}
|
||||
139
node_modules/@sveltejs/kit/src/messages/build-warnings.js
generated
vendored
Normal file
139
node_modules/@sveltejs/kit/src/messages/build-warnings.js
generated
vendored
Normal file
@@ -0,0 +1,139 @@
|
||||
/* This file is generated by scripts/process-messages/index.js. Do not edit! */
|
||||
|
||||
import { warn } from './internal/build.js';
|
||||
|
||||
/**
|
||||
* Reading `config.kit` inside adapters is deprecated — it should access configuration on the `config` object directly. You may need to update your adapter
|
||||
* @param {void} _values
|
||||
*/
|
||||
export function adapter_config_kit_deprecated(_values) {
|
||||
warn('adapter_config_kit_deprecated', `Reading \`config.kit\` inside adapters is deprecated — it should access configuration on the \`config\` object directly. You may need to update your adapter`);
|
||||
}
|
||||
|
||||
/**
|
||||
* Overwriting `%file%` with fallback page. Consider using a different name for the fallback.
|
||||
* @param {{ "file": string }} _values
|
||||
*/
|
||||
export function adapter_fallback_overwrites(_values) {
|
||||
warn('adapter_fallback_overwrites', `Overwriting \`${_values.file}\` with fallback page. Consider using a different name for the fallback.`);
|
||||
}
|
||||
|
||||
/**
|
||||
* No adapter specified. See https://svelte.dev/docs/kit/adapters to learn how to configure your app to run on the platform of your choosing
|
||||
* @param {void} _values
|
||||
*/
|
||||
export function adapter_missing(_values) {
|
||||
warn('adapter_missing', `No adapter specified. See https://svelte.dev/docs/kit/adapters to learn how to configure your app to run on the platform of your choosing`);
|
||||
}
|
||||
|
||||
/**
|
||||
* The `%keypath%` option is deprecated, and will be removed in a future version
|
||||
* @param {{ "keypath": string }} _values
|
||||
*/
|
||||
export function config_option_deprecated(_values) {
|
||||
warn('config_option_deprecated', `The \`${_values.keypath}\` option is deprecated, and will be removed in a future version`);
|
||||
}
|
||||
|
||||
/**
|
||||
* The `%keypath%` option is deprecated, and will be removed in a future version of SvelteKit. Use subpath imports instead: https://svelte.dev/docs/kit/$lib
|
||||
* @param {{ "keypath": string }} _values
|
||||
*/
|
||||
export function config_option_deprecated_alias(_values) {
|
||||
warn('config_option_deprecated_alias', `The \`${_values.keypath}\` option is deprecated, and will be removed in a future version of SvelteKit. Use subpath imports instead: https://svelte.dev/docs/kit/$lib`);
|
||||
}
|
||||
|
||||
/**
|
||||
* The `%keypath%` option is deprecated, and will be removed in a future version. Add configuration to `tsconfig.json` directly
|
||||
* @param {{ "keypath": string }} _values
|
||||
*/
|
||||
export function config_option_deprecated_typescript(_values) {
|
||||
warn('config_option_deprecated_typescript', `The \`${_values.keypath}\` option is deprecated, and will be removed in a future version. Add configuration to \`tsconfig.json\` directly`);
|
||||
}
|
||||
|
||||
/**
|
||||
* `OPTIONS` request handlers will not work unless `%key%.preflightContinue` is set to `true`
|
||||
* @param {{ "key": string }} _values
|
||||
*/
|
||||
export function cors_preflight_continue(_values) {
|
||||
warn('cors_preflight_continue', `\`OPTIONS\` request handlers will not work unless \`${_values.key}.preflightContinue\` is set to \`true\``);
|
||||
}
|
||||
|
||||
/**
|
||||
* %description%. Did you mean %corrected%? at %file%
|
||||
* @param {{ "description": string; "corrected": string; "file": string }} _values
|
||||
*/
|
||||
export function file_name_misspelled(_values) {
|
||||
warn('file_name_misspelled', `${_values.description}. Did you mean ${_values.corrected}? at ${_values.file}`);
|
||||
}
|
||||
|
||||
/**
|
||||
* `%file%`: `<slot />` or `{@render ...}` tag missing — inner content will not be rendered
|
||||
* @param {{ "file": string }} _values
|
||||
*/
|
||||
export function layout_children_missing(_values) {
|
||||
warn('layout_children_missing', `\`${_values.file}\`: \`<slot />\` or \`{@render ...}\` tag missing — inner content will not be rendered`);
|
||||
}
|
||||
|
||||
/**
|
||||
* `%file%`: `%option%` will be ignored — move it to `%fixed%` instead. See https://svelte.dev/docs/kit/page-options for more information.
|
||||
* @param {{ "file": string; "option": string; "fixed": string }} _values
|
||||
*/
|
||||
export function page_option_in_component(_values) {
|
||||
warn('page_option_in_component', `\`${_values.file}\`: \`${_values.option}\` will be ignored — move it to \`${_values.fixed}\` instead. See https://svelte.dev/docs/kit/page-options for more information.`);
|
||||
}
|
||||
|
||||
/**
|
||||
* `location` header missing on redirect received from `%path%`
|
||||
* @param {{ "path": string }} _values
|
||||
*/
|
||||
export function prerender_redirect_location_missing(_values) {
|
||||
warn('prerender_redirect_location_missing', `\`location\` header missing on redirect received from \`${_values.path}\``);
|
||||
}
|
||||
|
||||
/**
|
||||
* Missing route file prefix. Did you mean %corrected%? at %file%
|
||||
* @param {{ "corrected": string; "file": string }} _values
|
||||
*/
|
||||
export function route_file_prefix_missing(_values) {
|
||||
warn('route_file_prefix_missing', `Missing route file prefix. Did you mean ${_values.corrected}? at ${_values.file}`);
|
||||
}
|
||||
|
||||
/**
|
||||
* The following plugins may not work correctly because they use the `transformIndexHtml` hook which is not supported:
|
||||
%plugins%
|
||||
* @param {{ "plugins": string }} _values
|
||||
*/
|
||||
export function transform_index_html_unsupported(_values) {
|
||||
warn('transform_index_html_unsupported', `The following plugins may not work correctly because they use the \`transformIndexHtml\` hook which is not supported:
|
||||
${_values.plugins}`);
|
||||
}
|
||||
|
||||
/**
|
||||
* `%file%` should extend SvelteKit's built-in configuration:
|
||||
%example%
|
||||
* @param {{ "file": string; "example": string }} _values
|
||||
*/
|
||||
export function tsconfig_extends_missing(_values) {
|
||||
warn('tsconfig_extends_missing', `\`${_values.file}\` should extend SvelteKit's built-in configuration:
|
||||
${_values.example}`);
|
||||
}
|
||||
|
||||
/**
|
||||
* Found issues while validating `%file%`:
|
||||
%issues%
|
||||
* @param {{ "file": string; "issues": string }} _values
|
||||
*/
|
||||
export function tsconfig_invalid(_values) {
|
||||
warn('tsconfig_invalid', `Found issues while validating \`${_values.file}\`:
|
||||
${_values.issues}`);
|
||||
}
|
||||
|
||||
/**
|
||||
* The following Vite config options will be overridden by SvelteKit:
|
||||
%options%
|
||||
* @param {{ "options": string }} _values
|
||||
*/
|
||||
export function vite_config_overridden(_values) {
|
||||
warn('vite_config_overridden', `The following Vite config options will be overridden by SvelteKit:
|
||||
${_values.options}`);
|
||||
}
|
||||
277
node_modules/@sveltejs/kit/src/messages/client-errors.js
generated
vendored
Normal file
277
node_modules/@sveltejs/kit/src/messages/client-errors.js
generated
vendored
Normal file
@@ -0,0 +1,277 @@
|
||||
/* This file is generated by scripts/process-messages/index.js. Do not edit! */
|
||||
|
||||
import { DEV } from 'esm-env';
|
||||
import { throw_error } from './internal/shared.js';
|
||||
|
||||
/**
|
||||
* Your form contains `<input type="file">` fields, but is missing the necessary `enctype="multipart/form-data"` attribute
|
||||
* @param {void} _values
|
||||
* @returns {never}
|
||||
*/
|
||||
export function enhance_file_without_enctype(_values) {
|
||||
if (DEV) {
|
||||
throw_error('enhance_file_without_enctype', `Your form contains \`<input type="file">\` fields, but is missing the necessary \`enctype="multipart/form-data"\` attribute`, enhance_file_without_enctype);
|
||||
}
|
||||
|
||||
throw new Error('https://svelte.dev/e/kit/enhance_file_without_enctype');
|
||||
}
|
||||
|
||||
/**
|
||||
* `use:enhance` can only be used on `<form>` elements with `method="POST"`
|
||||
* @param {void} _values
|
||||
* @returns {never}
|
||||
*/
|
||||
export function enhance_invalid_method(_values) {
|
||||
if (DEV) {
|
||||
throw_error('enhance_invalid_method', `\`use:enhance\` can only be used on \`<form>\` elements with \`method="POST"\``, enhance_invalid_method);
|
||||
}
|
||||
|
||||
throw new Error('https://svelte.dev/e/kit/enhance_invalid_method');
|
||||
}
|
||||
|
||||
/**
|
||||
* The `goto(..., { noScroll: true, keepFocus: true })` options have been replaced by `reset: false`
|
||||
* @param {void} _values
|
||||
* @returns {never}
|
||||
*/
|
||||
export function goto_options_removed(_values) {
|
||||
if (DEV) {
|
||||
throw_error('goto_options_removed', `The \`goto(..., { noScroll: true, keepFocus: true })\` options have been replaced by \`reset: false\``, goto_options_removed);
|
||||
}
|
||||
|
||||
throw new Error('https://svelte.dev/e/kit/goto_options_removed');
|
||||
}
|
||||
|
||||
/**
|
||||
* Cannot call `%caller%(...)` before router is initialized
|
||||
* @param {{ "caller": string }} _values
|
||||
* @returns {never}
|
||||
*/
|
||||
export function navigation_before_start(_values) {
|
||||
if (DEV) {
|
||||
throw_error('navigation_before_start', `Cannot call \`${_values.caller}(...)\` before router is initialized`, navigation_before_start);
|
||||
}
|
||||
|
||||
throw new Error('https://svelte.dev/e/kit/navigation_before_start');
|
||||
}
|
||||
|
||||
/**
|
||||
* Cannot use `%caller%` with an external URL. Use `window.location = "%url%"` instead
|
||||
* @param {{ "caller": string; "url": string }} _values
|
||||
* @returns {never}
|
||||
*/
|
||||
export function navigation_external_url(_values) {
|
||||
if (DEV) {
|
||||
throw_error('navigation_external_url', `Cannot use \`${_values.caller}\` with an external URL. Use \`window.location = "${_values.url}"\` instead`, navigation_external_url);
|
||||
}
|
||||
|
||||
throw new Error('https://svelte.dev/e/kit/navigation_external_url');
|
||||
}
|
||||
|
||||
/**
|
||||
* Cannot use `%caller%` with a URL that does not resolve to a route within the app. Use `window.location = "%url%"` instead
|
||||
* @param {{ "caller": string; "url": string }} _values
|
||||
* @returns {never}
|
||||
*/
|
||||
export function navigation_route_missing(_values) {
|
||||
if (DEV) {
|
||||
throw_error('navigation_route_missing', `Cannot use \`${_values.caller}\` with a URL that does not resolve to a route within the app. Use \`window.location = "${_values.url}"\` instead`, navigation_route_missing);
|
||||
}
|
||||
|
||||
throw new Error('https://svelte.dev/e/kit/navigation_route_missing');
|
||||
}
|
||||
|
||||
/**
|
||||
* `preloadCode` expects a route ID starting with `/` (such as `/blog/[slug]`), but received `%id%`
|
||||
* @param {{ "id": string }} _values
|
||||
* @returns {never}
|
||||
*/
|
||||
export function preload_invalid_route_id(_values) {
|
||||
if (DEV) {
|
||||
throw_error('preload_invalid_route_id', `\`preloadCode\` expects a route ID starting with \`/\` (such as \`/blog/[slug]\`), but received \`${_values.id}\``, preload_invalid_route_id);
|
||||
}
|
||||
|
||||
throw new Error('https://svelte.dev/e/kit/preload_invalid_route_id');
|
||||
}
|
||||
|
||||
/**
|
||||
* Attempted to preload a URL that does not belong to this app: `%url%`
|
||||
* @param {{ "url": string }} _values
|
||||
* @returns {never}
|
||||
*/
|
||||
export function preload_url_outside_app(_values) {
|
||||
if (DEV) {
|
||||
throw_error('preload_url_outside_app', `Attempted to preload a URL that does not belong to this app: \`${_values.url}\``, preload_url_outside_app);
|
||||
}
|
||||
|
||||
throw new Error('https://svelte.dev/e/kit/preload_url_outside_app');
|
||||
}
|
||||
|
||||
/**
|
||||
* Redirect loop while navigating to `%url%`
|
||||
* @param {{ "url": string }} _values
|
||||
* @returns {never}
|
||||
*/
|
||||
export function redirect_loop(_values) {
|
||||
if (DEV) {
|
||||
throw_error('redirect_loop', `Redirect loop while navigating to \`${_values.url}\``, redirect_loop);
|
||||
}
|
||||
|
||||
throw new Error('https://svelte.dev/e/kit/redirect_loop');
|
||||
}
|
||||
|
||||
/**
|
||||
* Redirects are not allowed in commands. Return a result instead and use `goto` on the client
|
||||
* @param {void} _values
|
||||
* @returns {never}
|
||||
*/
|
||||
export function remote_command_redirect(_values) {
|
||||
if (DEV) {
|
||||
throw_error('remote_command_redirect', `Redirects are not allowed in commands. Return a result instead and use \`goto\` on the client`, remote_command_redirect);
|
||||
}
|
||||
|
||||
throw new Error('https://svelte.dev/e/kit/remote_command_redirect');
|
||||
}
|
||||
|
||||
/**
|
||||
* Cannot mix and match file and non-file inputs under the same name (`%name%`)
|
||||
* @param {{ "name": string }} _values
|
||||
* @returns {never}
|
||||
*/
|
||||
export function remote_form_mixed_inputs(_values) {
|
||||
if (DEV) {
|
||||
throw_error('remote_form_mixed_inputs', `Cannot mix and match file and non-file inputs under the same name (\`${_values.name}\`)`, remote_form_mixed_inputs);
|
||||
}
|
||||
|
||||
throw new Error('https://svelte.dev/e/kit/remote_form_mixed_inputs');
|
||||
}
|
||||
|
||||
/**
|
||||
* A form object can only be attached to a single `<form>` element
|
||||
* @param {void} _values
|
||||
* @returns {never}
|
||||
*/
|
||||
export function remote_form_multiple_elements(_values) {
|
||||
if (DEV) {
|
||||
throw_error('remote_form_multiple_elements', `A form object can only be attached to a single \`<form>\` element`, remote_form_multiple_elements);
|
||||
}
|
||||
|
||||
throw new Error('https://svelte.dev/e/kit/remote_form_multiple_elements');
|
||||
}
|
||||
|
||||
/**
|
||||
* Can only use the `multiple` attribute when `name` includes a `[]` suffix — consider changing `%name%` to `%name%[]`
|
||||
* @param {{ "name": string }} _values
|
||||
* @returns {never}
|
||||
*/
|
||||
export function remote_form_multiple_files(_values) {
|
||||
if (DEV) {
|
||||
throw_error('remote_form_multiple_files', `Can only use the \`multiple\` attribute when \`name\` includes a \`[]\` suffix — consider changing \`${_values.name}\` to \`${_values.name}[]\``, remote_form_multiple_files);
|
||||
}
|
||||
|
||||
throw new Error('https://svelte.dev/e/kit/remote_form_multiple_files');
|
||||
}
|
||||
|
||||
/**
|
||||
* Cannot call `submit()` before the form is attached
|
||||
* @param {void} _values
|
||||
* @returns {never}
|
||||
*/
|
||||
export function remote_form_not_attached(_values) {
|
||||
if (DEV) {
|
||||
throw_error('remote_form_not_attached', `Cannot call \`submit()\` before the form is attached`, remote_form_not_attached);
|
||||
}
|
||||
|
||||
throw new Error('https://svelte.dev/e/kit/remote_form_not_attached');
|
||||
}
|
||||
|
||||
/**
|
||||
* `$` is used to collect all FormData validation issues and cannot be used as the `name` of a form control
|
||||
* @param {void} _values
|
||||
* @returns {never}
|
||||
*/
|
||||
export function remote_form_reserved_field(_values) {
|
||||
if (DEV) {
|
||||
throw_error('remote_form_reserved_field', `\`$\` is used to collect all FormData validation issues and cannot be used as the \`name\` of a form control`, remote_form_reserved_field);
|
||||
}
|
||||
|
||||
throw new Error('https://svelte.dev/e/kit/remote_form_reserved_field');
|
||||
}
|
||||
|
||||
/**
|
||||
* Multiple overrides for the same query are not allowed in a single `updates()` invocation
|
||||
* @param {void} _values
|
||||
* @returns {never}
|
||||
*/
|
||||
export function remote_updates_duplicate_override(_values) {
|
||||
if (DEV) {
|
||||
throw_error('remote_updates_duplicate_override', `Multiple overrides for the same query are not allowed in a single \`updates()\` invocation`, remote_updates_duplicate_override);
|
||||
}
|
||||
|
||||
throw new Error('https://svelte.dev/e/kit/remote_updates_duplicate_override');
|
||||
}
|
||||
|
||||
/**
|
||||
* `updates()` expects a query or live query function, query resource, or query override
|
||||
* @param {void} _values
|
||||
* @returns {never}
|
||||
*/
|
||||
export function remote_updates_invalid_argument(_values) {
|
||||
if (DEV) {
|
||||
throw_error('remote_updates_invalid_argument', `\`updates()\` expects a query or live query function, query resource, or query override`, remote_updates_invalid_argument);
|
||||
}
|
||||
|
||||
throw new Error('https://svelte.dev/e/kit/remote_updates_invalid_argument');
|
||||
}
|
||||
|
||||
/**
|
||||
* Cannot use reserved query parameter `%key%`
|
||||
* @param {{ "key": string }} _values
|
||||
* @returns {never}
|
||||
*/
|
||||
export function reserved_query_parameter(_values) {
|
||||
if (DEV) {
|
||||
throw_error('reserved_query_parameter', `Cannot use reserved query parameter \`${_values.key}\``, reserved_query_parameter);
|
||||
}
|
||||
|
||||
throw new Error('https://svelte.dev/e/kit/reserved_query_parameter');
|
||||
}
|
||||
|
||||
/**
|
||||
* Can only disable scroll handling during navigation
|
||||
* @param {void} _values
|
||||
* @returns {never}
|
||||
*/
|
||||
export function scroll_handling_outside_navigation(_values) {
|
||||
if (DEV) {
|
||||
throw_error('scroll_handling_outside_navigation', `Can only disable scroll handling during navigation`, scroll_handling_outside_navigation);
|
||||
}
|
||||
|
||||
throw new Error('https://svelte.dev/e/kit/scroll_handling_outside_navigation');
|
||||
}
|
||||
|
||||
/**
|
||||
* `snapshot()` was called multiple times from the same call site. Pass a unique `id` to distinguish the instances.
|
||||
* @param {void | { "id": string }} _values
|
||||
* @returns {never}
|
||||
*/
|
||||
export function snapshot_duplicate_id(_values) {
|
||||
if (DEV) {
|
||||
throw_error('snapshot_duplicate_id', (_values?.id !== undefined ? `A snapshot with id \`${_values.id}\` is already registered. Pass a unique \`id\`.` : `\`snapshot()\` was called multiple times from the same call site. Pass a unique \`id\` to distinguish the instances.`), snapshot_duplicate_id);
|
||||
}
|
||||
|
||||
throw new Error('https://svelte.dev/e/kit/snapshot_duplicate_id');
|
||||
}
|
||||
|
||||
/**
|
||||
* Could not generate a snapshot id from the stack trace. Pass an `id` instead.
|
||||
* @param {void} _values
|
||||
* @returns {never}
|
||||
*/
|
||||
export function snapshot_id_missing(_values) {
|
||||
if (DEV) {
|
||||
throw_error('snapshot_id_missing', `Could not generate a snapshot id from the stack trace. Pass an \`id\` instead.`, snapshot_id_missing);
|
||||
}
|
||||
|
||||
throw new Error('https://svelte.dev/e/kit/snapshot_id_missing');
|
||||
}
|
||||
393
node_modules/@sveltejs/kit/src/messages/client-warnings.js
generated
vendored
Normal file
393
node_modules/@sveltejs/kit/src/messages/client-warnings.js
generated
vendored
Normal file
@@ -0,0 +1,393 @@
|
||||
/* This file is generated by scripts/process-messages/index.js. Do not edit! */
|
||||
|
||||
/** @import { ClientWarningOptions } from './internal/shared.js' */
|
||||
import { DEV } from 'esm-env';
|
||||
import { bold, normal } from './internal/shared.js';
|
||||
|
||||
/**
|
||||
* Placing `%tag%` directly inside `<body>` is not recommended, as your app may break for users who have certain browser extensions installed
|
||||
* @param {{ "tag": string }} _values
|
||||
* @param {ClientWarningOptions} [options]
|
||||
*/
|
||||
export function app_body_unwrapped(_values, options) {
|
||||
const details = options?.element ? [options.element] : [];
|
||||
|
||||
if (DEV) {
|
||||
console.warn(
|
||||
`%c[sveltekit] ${'app_body_unwrapped'}\n%c${`Placing \`${_values.tag}\` directly inside \`<body>\` is not recommended, as your app may break for users who have certain browser extensions installed`}\nhttps://svelte.dev/e/kit/${'app_body_unwrapped'}`,
|
||||
bold,
|
||||
normal,
|
||||
...details
|
||||
);
|
||||
} else {
|
||||
console.warn('https://svelte.dev/e/kit/app_body_unwrapped', ...details);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The `update({ invalidateAll })` option has been deprecated in favour of `update({ refreshAll })`
|
||||
* @param {void} _values
|
||||
* @param {ClientWarningOptions} [options]
|
||||
*/
|
||||
export function enhance_invalidate_all_deprecated(_values, options) {
|
||||
const details = options?.element ? [options.element] : [];
|
||||
|
||||
if (DEV) {
|
||||
console.warn(
|
||||
`%c[sveltekit] ${'enhance_invalidate_all_deprecated'}\n%c${`The \`update({ invalidateAll })\` option has been deprecated in favour of \`update({ refreshAll })\``}\nhttps://svelte.dev/e/kit/${'enhance_invalidate_all_deprecated'}`,
|
||||
bold,
|
||||
normal,
|
||||
...details
|
||||
);
|
||||
} else {
|
||||
console.warn('https://svelte.dev/e/kit/enhance_invalidate_all_deprecated', ...details);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* An error occurred while loading the page. This will cause a full page reload
|
||||
* @param {void} _values
|
||||
* @param {ClientWarningOptions} [options]
|
||||
*/
|
||||
export function full_reload_after_error(_values, options) {
|
||||
const details = options?.element ? [options.element] : [];
|
||||
|
||||
if (DEV) {
|
||||
console.warn(
|
||||
`%c[sveltekit] ${'full_reload_after_error'}\n%c${`An error occurred while loading the page. This will cause a full page reload`}\nhttps://svelte.dev/e/kit/${'full_reload_after_error'}`,
|
||||
bold,
|
||||
normal,
|
||||
...details
|
||||
);
|
||||
} else {
|
||||
console.warn('https://svelte.dev/e/kit/full_reload_after_error', ...details);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The `goto(..., { invalidateAll: %value% })` option has been deprecated in favour of `refreshAll`
|
||||
* @param {{ "value": string }} _values
|
||||
* @param {ClientWarningOptions} [options]
|
||||
*/
|
||||
export function goto_invalidate_all_deprecated(_values, options) {
|
||||
const details = options?.element ? [options.element] : [];
|
||||
|
||||
if (DEV) {
|
||||
console.warn(
|
||||
`%c[sveltekit] ${'goto_invalidate_all_deprecated'}\n%c${`The \`goto(..., { invalidateAll: ${_values.value} })\` option has been deprecated in favour of \`refreshAll\``}\nhttps://svelte.dev/e/kit/${'goto_invalidate_all_deprecated'}`,
|
||||
bold,
|
||||
normal,
|
||||
...details
|
||||
);
|
||||
} else {
|
||||
console.warn('https://svelte.dev/e/kit/goto_invalidate_all_deprecated', ...details);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The `goto(..., { replaceState: %value% })` option has been deprecated in favour of `replace`
|
||||
* @param {{ "value": string }} _values
|
||||
* @param {ClientWarningOptions} [options]
|
||||
*/
|
||||
export function goto_replace_state_deprecated(_values, options) {
|
||||
const details = options?.element ? [options.element] : [];
|
||||
|
||||
if (DEV) {
|
||||
console.warn(
|
||||
`%c[sveltekit] ${'goto_replace_state_deprecated'}\n%c${`The \`goto(..., { replaceState: ${_values.value} })\` option has been deprecated in favour of \`replace\``}\nhttps://svelte.dev/e/kit/${'goto_replace_state_deprecated'}`,
|
||||
bold,
|
||||
normal,
|
||||
...details
|
||||
);
|
||||
} else {
|
||||
console.warn('https://svelte.dev/e/kit/goto_replace_state_deprecated', ...details);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Avoid using `history.pushState(...)` and `history.replaceState(...)` as these will conflict with SvelteKit's router. Use `goto(...)` from `$app/navigation` instead.
|
||||
* @param {void} _values
|
||||
* @param {ClientWarningOptions} [options]
|
||||
*/
|
||||
export function history_api_conflict(_values, options) {
|
||||
const details = options?.element ? [options.element] : [];
|
||||
|
||||
if (DEV) {
|
||||
console.warn(
|
||||
`%c[sveltekit] ${'history_api_conflict'}\n%c${`Avoid using \`history.pushState(...)\` and \`history.replaceState(...)\` as these will conflict with SvelteKit's router. Use \`goto(...)\` from \`$app/navigation\` instead.`}\nhttps://svelte.dev/e/kit/${'history_api_conflict'}`,
|
||||
bold,
|
||||
normal,
|
||||
...details
|
||||
);
|
||||
} else {
|
||||
console.warn('https://svelte.dev/e/kit/history_api_conflict', ...details);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The next HMR update will cause the page to reload
|
||||
* @param {void} _values
|
||||
* @param {ClientWarningOptions} [options]
|
||||
*/
|
||||
export function hmr_reload_after_error(_values, options) {
|
||||
const details = options?.element ? [options.element] : [];
|
||||
|
||||
if (DEV) {
|
||||
console.warn(
|
||||
`%c[sveltekit] ${'hmr_reload_after_error'}\n%c${`The next HMR update will cause the page to reload`}\nhttps://svelte.dev/e/kit/${'hmr_reload_after_error'}`,
|
||||
bold,
|
||||
normal,
|
||||
...details
|
||||
);
|
||||
} else {
|
||||
console.warn('https://svelte.dev/e/kit/hmr_reload_after_error', ...details);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Unexpected value for `%name%` — should be one of %options%
|
||||
* @param {{ "name": string; "options": string }} _values
|
||||
* @param {ClientWarningOptions} [options]
|
||||
*/
|
||||
export function link_option_invalid(_values, options) {
|
||||
const details = options?.element ? [options.element] : [];
|
||||
|
||||
if (DEV) {
|
||||
console.warn(
|
||||
`%c[sveltekit] ${'link_option_invalid'}\n%c${`Unexpected value for \`${_values.name}\` — should be one of ${_values.options}`}\nhttps://svelte.dev/e/kit/${'link_option_invalid'}`,
|
||||
bold,
|
||||
normal,
|
||||
...details
|
||||
);
|
||||
} else {
|
||||
console.warn('https://svelte.dev/e/kit/link_option_invalid', ...details);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* `data-sveltekit-%name%="true"` has been replaced with `data-sveltekit-reset="false"`
|
||||
* @param {{ "name": string }} _values
|
||||
* @param {ClientWarningOptions} [options]
|
||||
*/
|
||||
export function link_option_replaced(_values, options) {
|
||||
const details = options?.element ? [options.element] : [];
|
||||
|
||||
if (DEV) {
|
||||
console.warn(
|
||||
`%c[sveltekit] ${'link_option_replaced'}\n%c${`\`data-sveltekit-${_values.name}="true"\` has been replaced with \`data-sveltekit-reset="false"\``}\nhttps://svelte.dev/e/kit/${'link_option_replaced'}`,
|
||||
bold,
|
||||
normal,
|
||||
...details
|
||||
);
|
||||
} else {
|
||||
console.warn('https://svelte.dev/e/kit/link_option_replaced', ...details);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* `%id%` has no `+page`, so there is no code to preload. If you meant to warm up an endpoint, request it with `fetch` instead.
|
||||
* @param {{ "id": string }} _values
|
||||
* @param {ClientWarningOptions} [options]
|
||||
*/
|
||||
export function preload_code_endpoint_only(_values, options) {
|
||||
const details = options?.element ? [options.element] : [];
|
||||
|
||||
if (DEV) {
|
||||
console.warn(
|
||||
`%c[sveltekit] ${'preload_code_endpoint_only'}\n%c${`\`${_values.id}\` has no \`+page\`, so there is no code to preload. If you meant to warm up an endpoint, request it with \`fetch\` instead.`}\nhttps://svelte.dev/e/kit/${'preload_code_endpoint_only'}`,
|
||||
bold,
|
||||
normal,
|
||||
...details
|
||||
);
|
||||
} else {
|
||||
console.warn('https://svelte.dev/e/kit/preload_code_endpoint_only', ...details);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Preloading data for `%path%` failed with the following error: %message%
|
||||
* @param {{ "path": string; "message": string }} _values
|
||||
* @param {ClientWarningOptions} [options]
|
||||
*/
|
||||
export function preload_data_failed(_values, options) {
|
||||
const details = options?.element ? [options.element] : [];
|
||||
|
||||
if (DEV) {
|
||||
console.warn(
|
||||
`%c[sveltekit] ${'preload_data_failed'}\n%c${`Preloading data for \`${_values.path}\` failed with the following error: ${_values.message}`}\nhttps://svelte.dev/e/kit/${'preload_data_failed'}`,
|
||||
bold,
|
||||
normal,
|
||||
...details
|
||||
);
|
||||
} else {
|
||||
console.warn('https://svelte.dev/e/kit/preload_data_failed', ...details);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* `%id%` did not match any route, but it does match as a pathname — use `match(...)` from `$app/paths` to convert a pathname into a route ID
|
||||
* @param {{ "id": string }} _values
|
||||
* @param {ClientWarningOptions} [options]
|
||||
*/
|
||||
export function preload_route_is_pathname(_values, options) {
|
||||
const details = options?.element ? [options.element] : [];
|
||||
|
||||
if (DEV) {
|
||||
console.warn(
|
||||
`%c[sveltekit] ${'preload_route_is_pathname'}\n%c${`\`${_values.id}\` did not match any route, but it does match as a pathname — use \`match(...)\` from \`$app/paths\` to convert a pathname into a route ID`}\nhttps://svelte.dev/e/kit/${'preload_route_is_pathname'}`,
|
||||
bold,
|
||||
normal,
|
||||
...details
|
||||
);
|
||||
} else {
|
||||
console.warn('https://svelte.dev/e/kit/preload_route_is_pathname', ...details);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* `%id%` did not match any route
|
||||
* @param {{ "id": string }} _values
|
||||
* @param {ClientWarningOptions} [options]
|
||||
*/
|
||||
export function preload_route_missing(_values, options) {
|
||||
const details = options?.element ? [options.element] : [];
|
||||
|
||||
if (DEV) {
|
||||
console.warn(
|
||||
`%c[sveltekit] ${'preload_route_missing'}\n%c${`\`${_values.id}\` did not match any route`}\nhttps://svelte.dev/e/kit/${'preload_route_missing'}`,
|
||||
bold,
|
||||
normal,
|
||||
...details
|
||||
);
|
||||
} else {
|
||||
console.warn('https://svelte.dev/e/kit/preload_route_missing', ...details);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* `pushState(...)` is deprecated. Use `goto(url, { state, shallow: true })` instead.
|
||||
* @param {void} _values
|
||||
* @param {ClientWarningOptions} [options]
|
||||
*/
|
||||
export function push_state_deprecated(_values, options) {
|
||||
const details = options?.element ? [options.element] : [];
|
||||
|
||||
if (DEV) {
|
||||
console.warn(
|
||||
`%c[sveltekit] ${'push_state_deprecated'}\n%c${`\`pushState(...)\` is deprecated. Use \`goto(url, { state, shallow: true })\` instead.`}\nhttps://svelte.dev/e/kit/${'push_state_deprecated'}`,
|
||||
bold,
|
||||
normal,
|
||||
...details
|
||||
);
|
||||
} else {
|
||||
console.warn('https://svelte.dev/e/kit/push_state_deprecated', ...details);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Form submission had invalid data, but the validation issues were ignored:
|
||||
|
||||
%issues%
|
||||
|
||||
Make sure you provide actionable feedback to users, using e.g. `myForm.fields.myField.issues()` or `myForm.fields.allIssues()`
|
||||
* @param {{ "issues": string }} _values
|
||||
* @param {ClientWarningOptions} [options]
|
||||
*/
|
||||
export function remote_form_issues_ignored(_values, options) {
|
||||
const details = options?.element ? [options.element] : [];
|
||||
|
||||
if (DEV) {
|
||||
console.warn(
|
||||
`%c[sveltekit] ${'remote_form_issues_ignored'}\n%c${`Form submission had invalid data, but the validation issues were ignored:
|
||||
|
||||
${_values.issues}
|
||||
|
||||
Make sure you provide actionable feedback to users, using e.g. \`myForm.fields.myField.issues()\` or \`myForm.fields.allIssues()\``}\nhttps://svelte.dev/e/kit/${'remote_form_issues_ignored'}`,
|
||||
bold,
|
||||
normal,
|
||||
...details
|
||||
);
|
||||
} else {
|
||||
console.warn('https://svelte.dev/e/kit/remote_form_issues_ignored', ...details);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Updates can only be sent once per %invocation%. Ignoring additional updates.
|
||||
* @param {{ "invocation": string }} _values
|
||||
* @param {ClientWarningOptions} [options]
|
||||
*/
|
||||
export function remote_updates_repeated(_values, options) {
|
||||
const details = options?.element ? [options.element] : [];
|
||||
|
||||
if (DEV) {
|
||||
console.warn(
|
||||
`%c[sveltekit] ${'remote_updates_repeated'}\n%c${`Updates can only be sent once per ${_values.invocation}. Ignoring additional updates.`}\nhttps://svelte.dev/e/kit/${'remote_updates_repeated'}`,
|
||||
bold,
|
||||
normal,
|
||||
...details
|
||||
);
|
||||
} else {
|
||||
console.warn('https://svelte.dev/e/kit/remote_updates_repeated', ...details);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* `replaceState(...)` is deprecated. Use `goto(url, { state, shallow: true, replace: true })` instead.
|
||||
* @param {void} _values
|
||||
* @param {ClientWarningOptions} [options]
|
||||
*/
|
||||
export function replace_state_deprecated(_values, options) {
|
||||
const details = options?.element ? [options.element] : [];
|
||||
|
||||
if (DEV) {
|
||||
console.warn(
|
||||
`%c[sveltekit] ${'replace_state_deprecated'}\n%c${`\`replaceState(...)\` is deprecated. Use \`goto(url, { state, shallow: true, replace: true })\` instead.`}\nhttps://svelte.dev/e/kit/${'replace_state_deprecated'}`,
|
||||
bold,
|
||||
normal,
|
||||
...details
|
||||
);
|
||||
} else {
|
||||
console.warn('https://svelte.dev/e/kit/replace_state_deprecated', ...details);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* `export const snapshot` is deprecated. Use the `snapshot` helper from `$app/navigation` instead.
|
||||
* @param {void} _values
|
||||
* @param {ClientWarningOptions} [options]
|
||||
*/
|
||||
export function snapshot_export_deprecated(_values, options) {
|
||||
const details = options?.element ? [options.element] : [];
|
||||
|
||||
if (DEV) {
|
||||
console.warn(
|
||||
`%c[sveltekit] ${'snapshot_export_deprecated'}\n%c${`\`export const snapshot\` is deprecated. Use the \`snapshot\` helper from \`$app/navigation\` instead.`}\nhttps://svelte.dev/e/kit/${'snapshot_export_deprecated'}`,
|
||||
bold,
|
||||
normal,
|
||||
...details
|
||||
);
|
||||
} else {
|
||||
console.warn('https://svelte.dev/e/kit/snapshot_export_deprecated', ...details);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Loading `%url%` using `window.fetch`. For best results, use the `fetch` that is passed to your `load` function
|
||||
* @param {{ "url": string }} _values
|
||||
* @param {ClientWarningOptions} [options]
|
||||
*/
|
||||
export function window_fetch_in_load(_values, options) {
|
||||
const details = options?.element ? [options.element] : [];
|
||||
|
||||
if (DEV) {
|
||||
console.warn(
|
||||
`%c[sveltekit] ${'window_fetch_in_load'}\n%c${`Loading \`${_values.url}\` using \`window.fetch\`. For best results, use the \`fetch\` that is passed to your \`load\` function`}\nhttps://svelte.dev/e/kit/${'window_fetch_in_load'}`,
|
||||
bold,
|
||||
normal,
|
||||
...details
|
||||
);
|
||||
} else {
|
||||
console.warn('https://svelte.dev/e/kit/window_fetch_in_load', ...details);
|
||||
}
|
||||
}
|
||||
58
node_modules/@sveltejs/kit/src/messages/internal/build.js
generated
vendored
Normal file
58
node_modules/@sveltejs/kit/src/messages/internal/build.js
generated
vendored
Normal file
@@ -0,0 +1,58 @@
|
||||
import { styleText } from 'node:util';
|
||||
|
||||
/**
|
||||
* @typedef {{ cause?: unknown; stackless?: boolean; location?: string }} ThrowOptions
|
||||
*/
|
||||
|
||||
/**
|
||||
* @param {string} code
|
||||
* @param {string} message
|
||||
*/
|
||||
function format(code, message) {
|
||||
return `${code}\n${message}\nhttps://svelte.dev/e/kit/${code}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {string} code
|
||||
* @param {string} message
|
||||
* @param {ThrowOptions | undefined} options
|
||||
* @param {Function} caller The generated helper, which is omitted from the stack along with this function
|
||||
* @returns {never}
|
||||
*/
|
||||
export function throw_error(code, message, options, caller) {
|
||||
const error = new Error(
|
||||
format(code, message),
|
||||
options?.cause === undefined ? undefined : { cause: options.cause }
|
||||
);
|
||||
error.name = 'SvelteKit error';
|
||||
|
||||
if (options?.location) error.stack = `${error.message}\n at ${options.location}`;
|
||||
else if (options?.stackless) error.stack = '';
|
||||
else Error.captureStackTrace(error, caller);
|
||||
|
||||
throw error;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the message of the diagnostic thrown by `fn`, for the few places that need the
|
||||
* formatted text as a string (callbacks, CLI output, generated code) rather than a thrown error.
|
||||
* There's probably a better solution to this, but it's needed so
|
||||
* sparsely that it would almost certainly not be worth the effort
|
||||
* @param {() => never} fn A function that calls a generated `build-errors` helper
|
||||
* @returns {string}
|
||||
*/
|
||||
export function capture_message(fn) {
|
||||
try {
|
||||
fn();
|
||||
} catch (error) {
|
||||
return /** @type {Error} */ (error).message;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {string} code
|
||||
* @param {string} message
|
||||
*/
|
||||
export function warn(code, message) {
|
||||
console.warn(styleText(['bold', 'yellow'], format(code, message)));
|
||||
}
|
||||
39
node_modules/@sveltejs/kit/src/messages/internal/server.js
generated
vendored
Normal file
39
node_modules/@sveltejs/kit/src/messages/internal/server.js
generated
vendored
Normal file
@@ -0,0 +1,39 @@
|
||||
/**
|
||||
* @typedef {{ cause?: unknown; stackless?: boolean }} ServerThrowOptions
|
||||
*/
|
||||
|
||||
/**
|
||||
* Throws the full diagnostic. Unlike shared errors, server-only errors keep their full text in production
|
||||
* @param {string} code
|
||||
* @param {string} message
|
||||
* @param {ServerThrowOptions | undefined} options
|
||||
* @param {Function} caller The generated helper, which is omitted from the stack along with this function
|
||||
* @returns {never}
|
||||
*/
|
||||
export function throw_error(code, message, options, caller) {
|
||||
const error = new Error(
|
||||
`${code}\n${message}\nhttps://svelte.dev/e/kit/${code}`,
|
||||
options?.cause === undefined ? undefined : { cause: options.cause }
|
||||
);
|
||||
error.name = 'SvelteKit error';
|
||||
|
||||
if (options?.stackless) error.stack = '';
|
||||
// not available in every runtime, in which case the stack also includes these two frames
|
||||
else Error.captureStackTrace?.(error, caller);
|
||||
|
||||
throw error;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the error thrown by `fn`, for the few places that pass an error on (for example to
|
||||
* `handleError` or a later `console.error`) rather than throwing it. Its stack starts inside `fn`
|
||||
* @param {() => never} fn A function that calls a generated `server-errors` helper
|
||||
* @returns {Error}
|
||||
*/
|
||||
export function capture_error(fn) {
|
||||
try {
|
||||
fn();
|
||||
} catch (error) {
|
||||
return /** @type {Error} */ (error);
|
||||
}
|
||||
}
|
||||
51
node_modules/@sveltejs/kit/src/messages/internal/shared.js
generated
vendored
Normal file
51
node_modules/@sveltejs/kit/src/messages/internal/shared.js
generated
vendored
Normal file
@@ -0,0 +1,51 @@
|
||||
/**
|
||||
* Whether shared errors include their full text on the server even though `DEV` is false. This is
|
||||
* enabled while the app is being built (analysed or prerendered)
|
||||
*/
|
||||
export let verbose = false;
|
||||
|
||||
export function enable_verbose_errors() {
|
||||
verbose = true;
|
||||
}
|
||||
|
||||
/**
|
||||
* @typedef {{ element?: Element }} ClientWarningOptions
|
||||
* - `element`: logged after the warning, so that it can be inspected in the browser's devtools
|
||||
*/
|
||||
|
||||
/** `console.warn` styles for the code and text of shared runtime warnings, as in Svelte */
|
||||
export const bold = 'font-weight: bold';
|
||||
export const normal = 'font-weight: normal';
|
||||
|
||||
/**
|
||||
* Throws the full diagnostic. Generated helpers throw their URL-only production error inline, so
|
||||
* bundlers can remove both this call and the message text from production browser builds
|
||||
* @param {string} code
|
||||
* @param {string} message
|
||||
* @param {Function} caller The generated helper, which is omitted from the stack along with this function
|
||||
* @returns {never}
|
||||
*/
|
||||
export function throw_error(code, message, caller) {
|
||||
const error = new Error(`${code}\n${message}\nhttps://svelte.dev/e/kit/${code}`);
|
||||
error.name = 'SvelteKit error';
|
||||
|
||||
// not available in every browser, in which case the stack also includes these two frames
|
||||
Error.captureStackTrace?.(error, caller);
|
||||
|
||||
throw error;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the error thrown by `fn`, for the few places that pass an error on (for example to
|
||||
* `handleError`) rather than throwing it. Unlike `capture_error` in `./server.js`, this can be
|
||||
* bundled for browsers, so the thrown error only contains the URL in production
|
||||
* @param {() => never} fn A function that calls a generated `client-errors` or `shared-errors` helper
|
||||
* @returns {Error}
|
||||
*/
|
||||
export function capture_error(fn) {
|
||||
try {
|
||||
fn();
|
||||
} catch (error) {
|
||||
return /** @type {Error} */ (error);
|
||||
}
|
||||
}
|
||||
596
node_modules/@sveltejs/kit/src/messages/server-errors.js
generated
vendored
Normal file
596
node_modules/@sveltejs/kit/src/messages/server-errors.js
generated
vendored
Normal file
@@ -0,0 +1,596 @@
|
||||
/* This file is generated by scripts/process-messages/index.js. Do not edit! */
|
||||
|
||||
/** @import { ServerThrowOptions } from './internal/server.js' */
|
||||
import { throw_error } from './internal/server.js';
|
||||
|
||||
/**
|
||||
* Data returned from action inside `%id%` is not serializable: %message%
|
||||
* @param {{ "id": string; "message": string; "path"?: string }} _values
|
||||
* @param {ServerThrowOptions} [options]
|
||||
* @returns {never}
|
||||
*/
|
||||
export function action_data_not_serializable(_values, options) {
|
||||
throw_error('action_data_not_serializable', (_values?.path !== undefined ? `Data returned from action inside \`${_values.id}\` is not serializable: ${_values.message} (\`${_values.path}\`)` : `Data returned from action inside \`${_values.id}\` is not serializable: ${_values.message}`), options, action_data_not_serializable);
|
||||
}
|
||||
|
||||
/**
|
||||
* When using named actions, the default action cannot be used. See the docs for more info: https://svelte.dev/docs/kit/form-actions#Named-actions
|
||||
* @param {void} _values
|
||||
* @param {ServerThrowOptions} [options]
|
||||
* @returns {never}
|
||||
*/
|
||||
export function action_default_with_named(_values, options) {
|
||||
throw_error('action_default_with_named', `When using named actions, the default action cannot be used. See the docs for more info: https://svelte.dev/docs/kit/form-actions#Named-actions`, options, action_default_with_named);
|
||||
}
|
||||
|
||||
/**
|
||||
* Cannot use reserved action name `default`
|
||||
* @param {void} _values
|
||||
* @param {ServerThrowOptions} [options]
|
||||
* @returns {never}
|
||||
*/
|
||||
export function action_name_reserved(_values, options) {
|
||||
throw_error('action_name_reserved', `Cannot use reserved action name \`default\``, options, action_name_reserved);
|
||||
}
|
||||
|
||||
/**
|
||||
* Data returned from action inside `%id%` is not serializable. Form actions need to return plain objects or `fail()`. E.g. `return { success: true }` or `return fail(400, { message: "invalid" });`
|
||||
* @param {{ "id": string }} _values
|
||||
* @param {ServerThrowOptions} [options]
|
||||
* @returns {never}
|
||||
*/
|
||||
export function action_response_not_serializable(_values, options) {
|
||||
throw_error('action_response_not_serializable', `Data returned from action inside \`${_values.id}\` is not serializable. Form actions need to return plain objects or \`fail()\`. E.g. \`return { success: true }\` or \`return fail(400, { message: "invalid" });\``, options, action_response_not_serializable);
|
||||
}
|
||||
|
||||
/**
|
||||
* Cannot `return error(...)` — use `error(...)` or `return fail(...)` instead
|
||||
* @param {void} _values
|
||||
* @param {ServerThrowOptions} [options]
|
||||
* @returns {never}
|
||||
*/
|
||||
export function action_return_error(_values, options) {
|
||||
throw_error('action_return_error', `Cannot \`return error(...)\` — use \`error(...)\` or \`return fail(...)\` instead`, options, action_return_error);
|
||||
}
|
||||
|
||||
/**
|
||||
* Cannot `return redirect(...)` — use `redirect(...)` instead
|
||||
* @param {void} _values
|
||||
* @param {ServerThrowOptions} [options]
|
||||
* @returns {never}
|
||||
*/
|
||||
export function action_return_redirect(_values, options) {
|
||||
throw_error('action_return_redirect', `Cannot \`return redirect(...)\` — use \`redirect(...)\` instead`, options, action_return_redirect);
|
||||
}
|
||||
|
||||
/**
|
||||
* Cannot `throw fail()`. Use `return fail()`
|
||||
* @param {void} _values
|
||||
* @param {ServerThrowOptions} [options]
|
||||
* @returns {never}
|
||||
*/
|
||||
export function action_throw_fail(_values, options) {
|
||||
throw_error('action_throw_fail', `Cannot \`throw fail()\`. Use \`return fail()\``, options, action_throw_fail);
|
||||
}
|
||||
|
||||
/**
|
||||
* `%adapter%` does not specify `getClientAddress`. Please raise an issue
|
||||
* @param {{ "adapter": string }} _values
|
||||
* @param {ServerThrowOptions} [options]
|
||||
* @returns {never}
|
||||
*/
|
||||
export function client_address_unsupported(_values, options) {
|
||||
throw_error('client_address_unsupported', `\`${_values.adapter}\` does not specify \`getClientAddress\`. Please raise an issue`, options, client_address_unsupported);
|
||||
}
|
||||
|
||||
/**
|
||||
* Cookie `%name%` is too large, and will be discarded by the browser
|
||||
* @param {{ "name": string }} _values
|
||||
* @param {ServerThrowOptions} [options]
|
||||
* @returns {never}
|
||||
*/
|
||||
export function cookie_too_large(_values, options) {
|
||||
throw_error('cookie_too_large', `Cookie \`${_values.name}\` is too large, and will be discarded by the browser`, options, cookie_too_large);
|
||||
}
|
||||
|
||||
/**
|
||||
* Cannot serialize cookies until after the route is determined
|
||||
* @param {void} _values
|
||||
* @param {ServerThrowOptions} [options]
|
||||
* @returns {never}
|
||||
*/
|
||||
export function cookies_serialize_before_route(_values, options) {
|
||||
throw_error('cookies_serialize_before_route', `Cannot serialize cookies until after the route is determined`, options, cookies_serialize_before_route);
|
||||
}
|
||||
|
||||
/**
|
||||
* Cannot use `cookies.set(...)` after the response has been generated
|
||||
* @param {void} _values
|
||||
* @param {ServerThrowOptions} [options]
|
||||
* @returns {never}
|
||||
*/
|
||||
export function cookies_set_after_response(_values, options) {
|
||||
throw_error('cookies_set_after_response', `Cannot use \`cookies.set(...)\` after the response has been generated`, options, cookies_set_after_response);
|
||||
}
|
||||
|
||||
/**
|
||||
* `content-security-policy-report-only` must be specified with either the `report-to` or `report-uri` directives, or both
|
||||
* @param {void} _values
|
||||
* @param {ServerThrowOptions} [options]
|
||||
* @returns {never}
|
||||
*/
|
||||
export function csp_report_only_missing_report(_values, options) {
|
||||
throw_error('csp_report_only_missing_report', `\`content-security-policy-report-only\` must be specified with either the \`report-to\` or \`report-uri\` directives, or both`, options, csp_report_only_missing_report);
|
||||
}
|
||||
|
||||
/**
|
||||
* `defineEnvVars` has moved — import it from `@sveltejs/kit/env` instead
|
||||
* @param {void} _values
|
||||
* @param {ServerThrowOptions} [options]
|
||||
* @returns {never}
|
||||
*/
|
||||
export function define_env_vars_moved(_values, options) {
|
||||
throw_error('define_env_vars_moved', `\`defineEnvVars\` has moved — import it from \`@sveltejs/kit/env\` instead`, options, define_env_vars_moved);
|
||||
}
|
||||
|
||||
/**
|
||||
* Invalid response from route `%path%`: handler should return a `Response` object
|
||||
* @param {{ "path": string }} _values
|
||||
* @param {ServerThrowOptions} [options]
|
||||
* @returns {never}
|
||||
*/
|
||||
export function endpoint_invalid_response(_values, options) {
|
||||
throw_error('endpoint_invalid_response', `Invalid response from route \`${_values.path}\`: handler should return a \`Response\` object`, options, endpoint_invalid_response);
|
||||
}
|
||||
|
||||
/**
|
||||
* Invalid environment variables:
|
||||
%issues%
|
||||
* @param {{ "issues": string }} _values
|
||||
* @param {ServerThrowOptions} [options]
|
||||
* @returns {never}
|
||||
*/
|
||||
export function env_invalid(_values, options) {
|
||||
throw_error('env_invalid', `Invalid environment variables:
|
||||
${_values.issues}`, options, env_invalid);
|
||||
}
|
||||
|
||||
/**
|
||||
* Cannot return `fetch(...)` directly from a handler if the response has a `Content-Encoding: %encoding%` header. The body has already been decoded
|
||||
* @param {{ "encoding": string }} _values
|
||||
* @param {ServerThrowOptions} [options]
|
||||
* @returns {never}
|
||||
*/
|
||||
export function fetch_response_decoded(_values, options) {
|
||||
throw_error('fetch_response_decoded', `Cannot return \`fetch(...)\` directly from a handler if the response has a \`Content-Encoding: ${_values.encoding}\` header. The body has already been decoded`, options, fetch_response_decoded);
|
||||
}
|
||||
|
||||
/**
|
||||
* The `handleError` hook failed
|
||||
* @param {void} _values
|
||||
* @param {ServerThrowOptions} [options]
|
||||
* @returns {never}
|
||||
*/
|
||||
export function handle_error_hook_failed(_values, options) {
|
||||
throw_error('handle_error_hook_failed', `The \`handleError\` hook failed`, options, handle_error_hook_failed);
|
||||
}
|
||||
|
||||
/**
|
||||
* `%name%` header is already set
|
||||
* @param {{ "name": string }} _values
|
||||
* @param {ServerThrowOptions} [options]
|
||||
* @returns {never}
|
||||
*/
|
||||
export function header_already_set(_values, options) {
|
||||
throw_error('header_already_set', `\`${_values.name}\` header is already set`, options, header_already_set);
|
||||
}
|
||||
|
||||
/**
|
||||
* CORS error: %reason% `Access-Control-Allow-Origin` header is present on the requested resource
|
||||
* @param {{ "reason": string }} _values
|
||||
* @param {ServerThrowOptions} [options]
|
||||
* @returns {never}
|
||||
*/
|
||||
export function load_fetch_cors(_values, options) {
|
||||
throw_error('load_fetch_cors', `CORS error: ${_values.reason} \`Access-Control-Allow-Origin\` header is present on the requested resource`, options, load_fetch_cors);
|
||||
}
|
||||
|
||||
/**
|
||||
* Data returned from `load` while rendering `%id%` is not a plain object
|
||||
* @param {{ "id": string }} _values
|
||||
* @param {ServerThrowOptions} [options]
|
||||
* @returns {never}
|
||||
*/
|
||||
export function load_not_plain_object(_values, options) {
|
||||
throw_error('load_not_plain_object', `Data returned from \`load\` while rendering \`${_values.id}\` is not a plain object`, options, load_not_plain_object);
|
||||
}
|
||||
|
||||
/**
|
||||
* Data returned from `load` while rendering `%id%` is not serializable: %message% (`%path%`). If you need to serialize/deserialize custom types, use transport hooks: https://svelte.dev/docs/kit/hooks#transport.
|
||||
* @param {{ "id": string; "message": string; "path": string }} _values
|
||||
* @param {ServerThrowOptions} [options]
|
||||
* @returns {never}
|
||||
*/
|
||||
export function load_not_serializable(_values, options) {
|
||||
throw_error('load_not_serializable', `Data returned from \`load\` while rendering \`${_values.id}\` is not serializable: ${_values.message} (\`${_values.path}\`). If you need to serialize/deserialize custom types, use transport hooks: https://svelte.dev/docs/kit/hooks#transport.`, options, load_not_serializable);
|
||||
}
|
||||
|
||||
/**
|
||||
* Failed to serialize promise while rendering `%id%`
|
||||
* @param {{ "id": string }} _values
|
||||
* @param {ServerThrowOptions} [options]
|
||||
* @returns {never}
|
||||
*/
|
||||
export function load_promise_not_serializable(_values, options) {
|
||||
throw_error('load_promise_not_serializable', `Failed to serialize promise while rendering \`${_values.id}\``, options, load_promise_not_serializable);
|
||||
}
|
||||
|
||||
/**
|
||||
* Failed to get response header `%name%` — it must be included by the `filterSerializedResponseHeaders` option: https://svelte.dev/docs/kit/hooks#handle (at `%id%`)
|
||||
* @param {{ "name": string; "id": string }} _values
|
||||
* @param {ServerThrowOptions} [options]
|
||||
* @returns {never}
|
||||
*/
|
||||
export function load_response_header_not_serialized(_values, options) {
|
||||
throw_error('load_response_header_not_serialized', `Failed to get response header \`${_values.name}\` — it must be included by the \`filterSerializedResponseHeaders\` option: https://svelte.dev/docs/kit/hooks#handle (at \`${_values.id}\`)`, options, load_response_header_not_serialized);
|
||||
}
|
||||
|
||||
/**
|
||||
* Cannot prerender pages with actions
|
||||
* @param {void} _values
|
||||
* @param {ServerThrowOptions} [options]
|
||||
* @returns {never}
|
||||
*/
|
||||
export function prerender_actions(_values, options) {
|
||||
throw_error('prerender_actions', `Cannot prerender pages with actions`, options, prerender_actions);
|
||||
}
|
||||
|
||||
/**
|
||||
* Cannot prerender a `+server` file with %methods% or fallback handlers (`%id%`)
|
||||
* @param {{ "methods": string; "id": string }} _values
|
||||
* @param {ServerThrowOptions} [options]
|
||||
* @returns {never}
|
||||
*/
|
||||
export function prerender_endpoint_methods(_values, options) {
|
||||
throw_error('prerender_endpoint_methods', `Cannot prerender a \`+server\` file with ${_values.methods} or fallback handlers (\`${_values.id}\`)`, options, prerender_endpoint_methods);
|
||||
}
|
||||
|
||||
/**
|
||||
* `%id%` is not prerenderable
|
||||
* @param {{ "id": string }} _values
|
||||
* @param {ServerThrowOptions} [options]
|
||||
* @returns {never}
|
||||
*/
|
||||
export function prerender_endpoint_not_prerenderable(_values, options) {
|
||||
throw_error('prerender_endpoint_not_prerenderable', `\`${_values.id}\` is not prerenderable`, options, prerender_endpoint_not_prerenderable);
|
||||
}
|
||||
|
||||
/**
|
||||
* Cannot use prerendering if `config.csp.mode === 'nonce'`
|
||||
* @param {void} _values
|
||||
* @param {ServerThrowOptions} [options]
|
||||
* @returns {never}
|
||||
*/
|
||||
export function prerender_nonce(_values, options) {
|
||||
throw_error('prerender_nonce', `Cannot use prerendering if \`config.csp.mode === 'nonce'\``, options, prerender_nonce);
|
||||
}
|
||||
|
||||
/**
|
||||
* Cannot use prerendering if page template contains `%tag%`
|
||||
* @param {{ "tag": string }} _values
|
||||
* @param {ServerThrowOptions} [options]
|
||||
* @returns {never}
|
||||
*/
|
||||
export function prerender_template_nonce(_values, options) {
|
||||
throw_error('prerender_template_nonce', `Cannot use prerendering if page template contains \`${_values.tag}\``, options, prerender_template_nonce);
|
||||
}
|
||||
|
||||
/**
|
||||
* Asset does not exist: `%file%`
|
||||
* @param {{ "file": string }} _values
|
||||
* @param {ServerThrowOptions} [options]
|
||||
* @returns {never}
|
||||
*/
|
||||
export function read_asset_missing(_values, options) {
|
||||
throw_error('read_asset_missing', `Asset does not exist: \`${_values.file}\``, options, read_asset_missing);
|
||||
}
|
||||
|
||||
/**
|
||||
* No `read` implementation was provided. Please ensure that your adapter is up to date and supports this feature
|
||||
* @param {void} _values
|
||||
* @param {ServerThrowOptions} [options]
|
||||
* @returns {never}
|
||||
*/
|
||||
export function read_implementation_missing(_values, options) {
|
||||
throw_error('read_implementation_missing', `No \`read\` implementation was provided. Please ensure that your adapter is up to date and supports this feature`, options, read_implementation_missing);
|
||||
}
|
||||
|
||||
/**
|
||||
* Cannot call a command (`%name%`) from a `%method%` handler
|
||||
* @param {{ "name": string; "method": string }} _values
|
||||
* @param {ServerThrowOptions} [options]
|
||||
* @returns {never}
|
||||
*/
|
||||
export function remote_command_method(_values, options) {
|
||||
throw_error('remote_command_method', `Cannot call a command (\`${_values.name}\`) from a \`${_values.method}\` handler`, options, remote_command_method);
|
||||
}
|
||||
|
||||
/**
|
||||
* Cannot call a command (`%name%`) inside a query or prerender function
|
||||
* @param {{ "name": string }} _values
|
||||
* @param {ServerThrowOptions} [options]
|
||||
* @returns {never}
|
||||
*/
|
||||
export function remote_command_readonly(_values, options) {
|
||||
throw_error('remote_command_readonly', `Cannot call a command (\`${_values.name}\`) inside a query or prerender function`, options, remote_command_readonly);
|
||||
}
|
||||
|
||||
/**
|
||||
* Cannot call a command (`%name%`) during server-side rendering
|
||||
* @param {{ "name": string }} _values
|
||||
* @param {ServerThrowOptions} [options]
|
||||
* @returns {never}
|
||||
*/
|
||||
export function remote_command_render(_values, options) {
|
||||
throw_error('remote_command_render', `Cannot call a command (\`${_values.name}\`) during server-side rendering`, options, remote_command_render);
|
||||
}
|
||||
|
||||
/**
|
||||
* Cannot %operation% cookies in `query` or `prerender` functions
|
||||
* @param {{ "operation": string }} _values
|
||||
* @param {ServerThrowOptions} [options]
|
||||
* @returns {never}
|
||||
*/
|
||||
export function remote_cookie_forbidden(_values, options) {
|
||||
throw_error('remote_cookie_forbidden', `Cannot ${_values.operation} cookies in \`query\` or \`prerender\` functions`, options, remote_cookie_forbidden);
|
||||
}
|
||||
|
||||
/**
|
||||
* Cookies %operation% in remote functions must have an absolute path
|
||||
* @param {{ "operation": string }} _values
|
||||
* @param {ServerThrowOptions} [options]
|
||||
* @returns {never}
|
||||
*/
|
||||
export function remote_cookie_path_relative(_values, options) {
|
||||
throw_error('remote_cookie_path_relative', `Cookies ${_values.operation} in remote functions must have an absolute path`, options, remote_cookie_path_relative);
|
||||
}
|
||||
|
||||
/**
|
||||
* `fail(...)` is for form actions. A remote `form` handler should call `invalid(...)` instead. See https://svelte.dev/docs/kit/remote-functions#form-Programmatic-validation
|
||||
* @param {void} _values
|
||||
* @param {ServerThrowOptions} [options]
|
||||
* @returns {never}
|
||||
*/
|
||||
export function remote_form_fail(_values, options) {
|
||||
throw_error('remote_form_fail', `\`fail(...)\` is for form actions. A remote \`form\` handler should call \`invalid(...)\` instead. See https://svelte.dev/docs/kit/remote-functions#form-Programmatic-validation`, options, remote_form_fail);
|
||||
}
|
||||
|
||||
/**
|
||||
* `setHeaders` is not allowed in remote functions
|
||||
* @param {void} _values
|
||||
* @param {ServerThrowOptions} [options]
|
||||
* @returns {never}
|
||||
*/
|
||||
export function remote_headers_forbidden(_values, options) {
|
||||
throw_error('remote_headers_forbidden', `\`setHeaders\` is not allowed in remote functions`, options, remote_headers_forbidden);
|
||||
}
|
||||
|
||||
/**
|
||||
* Invalid validator passed to remote function. Expected `'unchecked'` or a Standard Schema (https://standardschema.dev)
|
||||
* @param {void} _values
|
||||
* @param {ServerThrowOptions} [options]
|
||||
* @returns {never}
|
||||
*/
|
||||
export function remote_invalid_validator(_values, options) {
|
||||
throw_error('remote_invalid_validator', `Invalid validator passed to remote function. Expected \`'unchecked'\` or a Standard Schema (https://standardschema.dev)`, options, remote_invalid_validator);
|
||||
}
|
||||
|
||||
/**
|
||||
* Cannot export `default` from a remote module (`%file%`) — please use named exports instead
|
||||
* @param {{ "file": string }} _values
|
||||
* @param {ServerThrowOptions} [options]
|
||||
* @returns {never}
|
||||
*/
|
||||
export function remote_module_default_export(_values, options) {
|
||||
throw_error('remote_module_default_export', `Cannot export \`default\` from a remote module (\`${_values.file}\`) — please use named exports instead`, options, remote_module_default_export);
|
||||
}
|
||||
|
||||
/**
|
||||
* `%name%` exported from `%file%` is invalid — all exports from this file must be remote functions
|
||||
* @param {{ "name": string; "file": string }} _values
|
||||
* @param {ServerThrowOptions} [options]
|
||||
* @returns {never}
|
||||
*/
|
||||
export function remote_module_invalid_export(_values, options) {
|
||||
throw_error('remote_module_invalid_export', `\`${_values.name}\` exported from \`${_values.file}\` is invalid — all exports from this file must be remote functions`, options, remote_module_invalid_export);
|
||||
}
|
||||
|
||||
/**
|
||||
* `query.live` `%name%` did not yield a value
|
||||
* @param {{ "name": string }} _values
|
||||
* @param {ServerThrowOptions} [options]
|
||||
* @returns {never}
|
||||
*/
|
||||
export function remote_query_live_no_value(_values, options) {
|
||||
throw_error('remote_query_live_no_value', `\`query.live\` \`${_values.name}\` did not yield a value`, options, remote_query_live_no_value);
|
||||
}
|
||||
|
||||
/**
|
||||
* `query.live` `%name%` must return an `Iterator`, `Iterable`, `AsyncIterator` or `AsyncIterable`
|
||||
* @param {{ "name": string }} _values
|
||||
* @param {ServerThrowOptions} [options]
|
||||
* @returns {never}
|
||||
*/
|
||||
export function remote_query_live_not_iterable(_values, options) {
|
||||
throw_error('remote_query_live_not_iterable', `\`query.live\` \`${_values.name}\` must return an \`Iterator\`, \`Iterable\`, \`AsyncIterator\` or \`AsyncIterable\``, options, remote_query_live_not_iterable);
|
||||
}
|
||||
|
||||
/**
|
||||
* Cannot call `%type%` `%name%` while prerendering, as prerendered pages need static data. Use `prerender` from `$app/server` instead
|
||||
* @param {{ "type": string; "name": string }} _values
|
||||
* @param {ServerThrowOptions} [options]
|
||||
* @returns {never}
|
||||
*/
|
||||
export function remote_query_prerender(_values, options) {
|
||||
throw_error('remote_query_prerender', `Cannot call \`${_values.type}\` \`${_values.name}\` while prerendering, as prerendered pages need static data. Use \`prerender\` from \`$app/server\` instead`, options, remote_query_prerender);
|
||||
}
|
||||
|
||||
/**
|
||||
* Cannot access `event.%property%` in a query. Pass the value as an argument to the query instead
|
||||
* @param {{ "property": string }} _values
|
||||
* @param {ServerThrowOptions} [options]
|
||||
* @returns {never}
|
||||
*/
|
||||
export function remote_request_property(_values, options) {
|
||||
throw_error('remote_request_property', `Cannot access \`event.${_values.property}\` in a query. Pass the value as an argument to the query instead`, options, remote_request_property);
|
||||
}
|
||||
|
||||
/**
|
||||
* `requested(%name%, %limit%)` cannot be used with synchronous iteration because the query validator is async. Use `for await ... of` instead
|
||||
* @param {{ "name": string; "limit": string }} _values
|
||||
* @param {ServerThrowOptions} [options]
|
||||
* @returns {never}
|
||||
*/
|
||||
export function remote_requested_async_validator(_values, options) {
|
||||
throw_error('remote_requested_async_validator', `\`requested(${_values.name}, ${_values.limit})\` cannot be used with synchronous iteration because the query validator is async. Use \`for await ... of\` instead`, options, remote_requested_async_validator);
|
||||
}
|
||||
|
||||
/**
|
||||
* `requested(...)` can only be called in the context of a command/form remote function
|
||||
* @param {void} _values
|
||||
* @param {ServerThrowOptions} [options]
|
||||
* @returns {never}
|
||||
*/
|
||||
export function remote_requested_context(_values, options) {
|
||||
throw_error('remote_requested_context', `\`requested(...)\` can only be called in the context of a command/form remote function`, options, remote_requested_context);
|
||||
}
|
||||
|
||||
/**
|
||||
* Limit must be a non-negative integer or `Infinity`
|
||||
* @param {void} _values
|
||||
* @param {ServerThrowOptions} [options]
|
||||
* @returns {never}
|
||||
*/
|
||||
export function remote_requested_invalid_limit(_values, options) {
|
||||
throw_error('remote_requested_invalid_limit', `Limit must be a non-negative integer or \`Infinity\``, options, remote_requested_invalid_limit);
|
||||
}
|
||||
|
||||
/**
|
||||
* `requested(...)` expects a query function created with `query(...)`, `query.batch(...)`, or `query.live(...)`
|
||||
* @param {void} _values
|
||||
* @param {ServerThrowOptions} [options]
|
||||
* @returns {never}
|
||||
*/
|
||||
export function remote_requested_invalid_query(_values, options) {
|
||||
throw_error('remote_requested_invalid_query', `\`requested(...)\` expects a query function created with \`query(...)\`, \`query.batch(...)\`, or \`query.live(...)\``, options, remote_requested_invalid_query);
|
||||
}
|
||||
|
||||
/**
|
||||
* `%method%()` is invalid for %type% queries. Use `%replacement%()` instead.
|
||||
* @param {{ "method": string; "type": string; "replacement": string }} _values
|
||||
* @param {ServerThrowOptions} [options]
|
||||
* @returns {never}
|
||||
*/
|
||||
export function remote_requested_wrong_method(_values, options) {
|
||||
throw_error('remote_requested_wrong_method', `\`${_values.method}()\` is invalid for ${_values.type} queries. Use \`${_values.replacement}()\` instead.`, options, remote_requested_wrong_method);
|
||||
}
|
||||
|
||||
/**
|
||||
* Can only read the current request event inside functions invoked during `handle`, such as server `load` functions, actions, endpoints, and other server hooks. In environments without `AsyncLocalStorage`, the event must be read synchronously, not after an `await`.
|
||||
* @param {void} _values
|
||||
* @param {ServerThrowOptions} [options]
|
||||
* @returns {never}
|
||||
*/
|
||||
export function request_event_after_await(_values, options) {
|
||||
throw_error('request_event_after_await', `Can only read the current request event inside functions invoked during \`handle\`, such as server \`load\` functions, actions, endpoints, and other server hooks. In environments without \`AsyncLocalStorage\`, the event must be read synchronously, not after an \`await\`.`, options, request_event_after_await);
|
||||
}
|
||||
|
||||
/**
|
||||
* Can only read the current request event inside functions invoked during `handle`, such as server `load` functions, actions, endpoints, and other server hooks.
|
||||
* @param {void} _values
|
||||
* @param {ServerThrowOptions} [options]
|
||||
* @returns {never}
|
||||
*/
|
||||
export function request_event_unavailable(_values, options) {
|
||||
throw_error('request_event_unavailable', `Can only read the current request event inside functions invoked during \`handle\`, such as server \`load\` functions, actions, endpoints, and other server hooks.`, options, request_event_unavailable);
|
||||
}
|
||||
|
||||
/**
|
||||
* Could not get the request store. In environments without `AsyncLocalStorage`, the request store (used by e.g. remote functions) must be accessed synchronously, not after an `await`. If it was accessed synchronously then this is an internal error.
|
||||
* @param {void} _values
|
||||
* @param {ServerThrowOptions} [options]
|
||||
* @returns {never}
|
||||
*/
|
||||
export function request_store_after_await(_values, options) {
|
||||
throw_error('request_store_after_await', `Could not get the request store. In environments without \`AsyncLocalStorage\`, the request store (used by e.g. remote functions) must be accessed synchronously, not after an \`await\`. If it was accessed synchronously then this is an internal error.`, options, request_store_after_await);
|
||||
}
|
||||
|
||||
/**
|
||||
* Cannot call `%name%` on the server
|
||||
* @param {{ "name": string }} _values
|
||||
* @param {ServerThrowOptions} [options]
|
||||
* @returns {never}
|
||||
*/
|
||||
export function server_api_unavailable(_values, options) {
|
||||
throw_error('server_api_unavailable', `Cannot call \`${_values.name}\` on the server`, options, server_api_unavailable);
|
||||
}
|
||||
|
||||
/**
|
||||
* Cannot use `setHeaders(...)` after the response has been generated
|
||||
* @param {void} _values
|
||||
* @param {ServerThrowOptions} [options]
|
||||
* @returns {never}
|
||||
*/
|
||||
export function set_headers_after_response(_values, options) {
|
||||
throw_error('set_headers_after_response', `Cannot use \`setHeaders(...)\` after the response has been generated`, options, set_headers_after_response);
|
||||
}
|
||||
|
||||
/**
|
||||
* Use `event.cookies.set(name, value, options)` instead of `event.setHeaders` to set cookies
|
||||
* @param {void} _values
|
||||
* @param {ServerThrowOptions} [options]
|
||||
* @returns {never}
|
||||
*/
|
||||
export function set_headers_cookie(_values, options) {
|
||||
throw_error('set_headers_cookie', `Use \`event.cookies.set(name, value, options)\` instead of \`event.setHeaders\` to set cookies`, options, set_headers_cookie);
|
||||
}
|
||||
|
||||
/**
|
||||
* Cannot call `fetch` eagerly during server-side rendering with relative URL (`%url%`) — put your `fetch` calls inside `onMount` or a `load` function instead
|
||||
* @param {{ "url": string }} _values
|
||||
* @param {ServerThrowOptions} [options]
|
||||
* @returns {never}
|
||||
*/
|
||||
export function ssr_fetch_relative_url(_values, options) {
|
||||
throw_error('ssr_fetch_relative_url', `Cannot call \`fetch\` eagerly during server-side rendering with relative URL (\`${_values.url}\`) — put your \`fetch\` calls inside \`onMount\` or a \`load\` function instead`, options, ssr_fetch_relative_url);
|
||||
}
|
||||
|
||||
/**
|
||||
* Can only read `%name%` on the server during rendering (not in e.g. `load` functions), as it is bound to the current request via component context. This prevents state from leaking between users.
|
||||
* @param {{ "name": string }} _values
|
||||
* @param {ServerThrowOptions} [options]
|
||||
* @returns {never}
|
||||
*/
|
||||
export function state_read_outside_render(_values, options) {
|
||||
throw_error('state_read_outside_render', `Can only read \`${_values.name}\` on the server during rendering (not in e.g. \`load\` functions), as it is bound to the current request via component context. This prevents state from leaking between users.`, options, state_read_outside_render);
|
||||
}
|
||||
|
||||
/**
|
||||
* Tracing is enabled (see the SvelteKit plugin `tracing.server` option in your `vite.config.js`), but `@opentelemetry/api` is not available. This error will likely resolve itself when you set up your tracing instrumentation in `instrumentation.server.js`. For more information, see https://svelte.dev/docs/kit/observability#opentelemetry-api
|
||||
* @param {void} _values
|
||||
* @param {ServerThrowOptions} [options]
|
||||
* @returns {never}
|
||||
*/
|
||||
export function tracing_api_missing(_values, options) {
|
||||
throw_error('tracing_api_missing', `Tracing is enabled (see the SvelteKit plugin \`tracing.server\` option in your \`vite.config.js\`), but \`@opentelemetry/api\` is not available. This error will likely resolve itself when you set up your tracing instrumentation in \`instrumentation.server.js\`. For more information, see https://svelte.dev/docs/kit/observability#opentelemetry-api`, options, tracing_api_missing);
|
||||
}
|
||||
|
||||
/**
|
||||
* Cannot access `url.%property%` on a page with prerendering enabled
|
||||
* @param {{ "property": string }} _values
|
||||
* @param {ServerThrowOptions} [options]
|
||||
* @returns {never}
|
||||
*/
|
||||
export function url_search_unavailable_prerender(_values, options) {
|
||||
throw_error('url_search_unavailable_prerender', `Cannot access \`url.${_values.property}\` on a page with prerendering enabled`, options, url_search_unavailable_prerender);
|
||||
}
|
||||
180
node_modules/@sveltejs/kit/src/messages/server-warnings.js
generated
vendored
Normal file
180
node_modules/@sveltejs/kit/src/messages/server-warnings.js
generated
vendored
Normal file
@@ -0,0 +1,180 @@
|
||||
/* This file is generated by scripts/process-messages/index.js. Do not edit! */
|
||||
|
||||
import { DEV } from 'esm-env';
|
||||
import { bold, normal } from './internal/shared.js';
|
||||
|
||||
/**
|
||||
* `cache-control` header contains empty directives. (While parsing `%value%`.)
|
||||
* @param {{ "value": string }} _values
|
||||
*/
|
||||
export function cache_control_empty_directive(_values) {
|
||||
if (DEV) {
|
||||
console.warn(
|
||||
`%c[sveltekit] ${'cache_control_empty_directive'}\n%c${`\`cache-control\` header contains empty directives. (While parsing \`${_values.value}\`.)`}\nhttps://svelte.dev/e/kit/${'cache_control_empty_directive'}`,
|
||||
bold,
|
||||
normal
|
||||
);
|
||||
} else {
|
||||
console.warn('https://svelte.dev/e/kit/cache_control_empty_directive');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Invalid `cache-control` directive `%directive%`. Did you mean one of: %directives%? (While parsing `%value%`.)
|
||||
* @param {{ "directive": string; "directives": string; "value": string }} _values
|
||||
*/
|
||||
export function cache_control_invalid_directive(_values) {
|
||||
if (DEV) {
|
||||
console.warn(
|
||||
`%c[sveltekit] ${'cache_control_invalid_directive'}\n%c${`Invalid \`cache-control\` directive \`${_values.directive}\`. Did you mean one of: ${_values.directives}? (While parsing \`${_values.value}\`.)`}\nhttps://svelte.dev/e/kit/${'cache_control_invalid_directive'}`,
|
||||
bold,
|
||||
normal
|
||||
);
|
||||
} else {
|
||||
console.warn('https://svelte.dev/e/kit/cache_control_invalid_directive');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Invalid `content-type` value `%type%`. (While parsing `%value%`.)
|
||||
* @param {{ "type": string; "value": string }} _values
|
||||
*/
|
||||
export function content_type_invalid(_values) {
|
||||
if (DEV) {
|
||||
console.warn(
|
||||
`%c[sveltekit] ${'content_type_invalid'}\n%c${`Invalid \`content-type\` value \`${_values.type}\`. (While parsing \`${_values.value}\`.)`}\nhttps://svelte.dev/e/kit/${'content_type_invalid'}`,
|
||||
bold,
|
||||
normal
|
||||
);
|
||||
} else {
|
||||
console.warn('https://svelte.dev/e/kit/content_type_invalid');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* `%name%` cookie does not exist for `%pathname%`, but was previously set at %paths%. Did you mean to set its `path` to `'/'` instead?
|
||||
* @param {{ "name": string; "pathname": string; "paths": string }} _values
|
||||
*/
|
||||
export function cookie_path_mismatch(_values) {
|
||||
if (DEV) {
|
||||
console.warn(
|
||||
`%c[sveltekit] ${'cookie_path_mismatch'}\n%c${`\`${_values.name}\` cookie does not exist for \`${_values.pathname}\`, but was previously set at ${_values.paths}. Did you mean to set its \`path\` to \`'/'\` instead?`}\nhttps://svelte.dev/e/kit/${'cookie_path_mismatch'}`,
|
||||
bold,
|
||||
normal
|
||||
);
|
||||
} else {
|
||||
console.warn('https://svelte.dev/e/kit/cookie_path_mismatch');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The form action returned a value, but it isn't available in `page.form`, because SSR is off. To handle the returned value in CSR, enhance your form with `use:enhance`. See https://svelte.dev/docs/kit/form-actions#Progressive-enhancement-use:enhance
|
||||
* @param {void} _values
|
||||
*/
|
||||
export function form_action_data_without_ssr(_values) {
|
||||
if (DEV) {
|
||||
console.warn(
|
||||
`%c[sveltekit] ${'form_action_data_without_ssr'}\n%c${`The form action returned a value, but it isn't available in \`page.form\`, because SSR is off. To handle the returned value in CSR, enhance your form with \`use:enhance\`. See https://svelte.dev/docs/kit/form-actions#Progressive-enhancement-use:enhance`}\nhttps://svelte.dev/e/kit/${'form_action_data_without_ssr'}`,
|
||||
bold,
|
||||
normal
|
||||
);
|
||||
} else {
|
||||
console.warn('https://svelte.dev/e/kit/form_action_data_without_ssr');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The form action returned an error, but `+error.svelte` wasn't rendered because SSR is off. To get the error page with CSR, enhance your form with `use:enhance`. See https://svelte.dev/docs/kit/form-actions#Progressive-enhancement-use:enhance
|
||||
* @param {void} _values
|
||||
*/
|
||||
export function form_action_error_without_ssr(_values) {
|
||||
if (DEV) {
|
||||
console.warn(
|
||||
`%c[sveltekit] ${'form_action_error_without_ssr'}\n%c${`The form action returned an error, but \`+error.svelte\` wasn't rendered because SSR is off. To get the error page with CSR, enhance your form with \`use:enhance\`. See https://svelte.dev/docs/kit/form-actions#Progressive-enhancement-use:enhance`}\nhttps://svelte.dev/e/kit/${'form_action_error_without_ssr'}`,
|
||||
bold,
|
||||
normal
|
||||
);
|
||||
} else {
|
||||
console.warn('https://svelte.dev/e/kit/form_action_error_without_ssr');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* To use an async `handleError` hook to handle errors that occur during rendering, you must enable `compilerOptions.experimental.async` in the SvelteKit plugin of your Vite config. The returned error has been replaced with a generic object
|
||||
* @param {void} _values
|
||||
*/
|
||||
export function handle_error_async_without_async_svelte(_values) {
|
||||
if (DEV) {
|
||||
console.warn(
|
||||
`%c[sveltekit] ${'handle_error_async_without_async_svelte'}\n%c${`To use an async \`handleError\` hook to handle errors that occur during rendering, you must enable \`compilerOptions.experimental.async\` in the SvelteKit plugin of your Vite config. The returned error has been replaced with a generic object`}\nhttps://svelte.dev/e/kit/${'handle_error_async_without_async_svelte'}`,
|
||||
bold,
|
||||
normal
|
||||
);
|
||||
} else {
|
||||
console.warn('https://svelte.dev/e/kit/handle_error_async_without_async_svelte');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* `%id%`: %usage% in a promise handler after `load(...)` has returned will not cause the function to re-run when %change%
|
||||
* @param {{ "id": string; "usage": string; "change": string }} _values
|
||||
*/
|
||||
export function load_tracking_after_return(_values) {
|
||||
if (DEV) {
|
||||
console.warn(
|
||||
`%c[sveltekit] ${'load_tracking_after_return'}\n%c${`\`${_values.id}\`: ${_values.usage} in a promise handler after \`load(...)\` has returned will not cause the function to re-run when ${_values.change}`}\nhttps://svelte.dev/e/kit/${'load_tracking_after_return'}`,
|
||||
bold,
|
||||
normal
|
||||
);
|
||||
} else {
|
||||
console.warn('https://svelte.dev/e/kit/load_tracking_after_return');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Avoid calling `fetch` eagerly during server-side rendering — put your `fetch` calls inside `onMount` or a `load` function instead
|
||||
* @param {void} _values
|
||||
*/
|
||||
export function ssr_fetch_eager(_values) {
|
||||
if (DEV) {
|
||||
console.warn(
|
||||
`%c[sveltekit] ${'ssr_fetch_eager'}\n%c${`Avoid calling \`fetch\` eagerly during server-side rendering — put your \`fetch\` calls inside \`onMount\` or a \`load\` function instead`}\nhttps://svelte.dev/e/kit/${'ssr_fetch_eager'}`,
|
||||
bold,
|
||||
normal
|
||||
);
|
||||
} else {
|
||||
console.warn('https://svelte.dev/e/kit/ssr_fetch_eager');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Returning promises from server `load` functions will only work if `csr === true`
|
||||
* @param {void} _values
|
||||
*/
|
||||
export function streaming_without_csr(_values) {
|
||||
if (DEV) {
|
||||
console.warn(
|
||||
`%c[sveltekit] ${'streaming_without_csr'}\n%c${`Returning promises from server \`load\` functions will only work if \`csr === true\``}\nhttps://svelte.dev/e/kit/${'streaming_without_csr'}`,
|
||||
bold,
|
||||
normal
|
||||
);
|
||||
} else {
|
||||
console.warn('https://svelte.dev/e/kit/streaming_without_csr');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Removing comments in `transformPageChunk` can break Svelte's hydration
|
||||
* @param {void} _values
|
||||
*/
|
||||
export function transform_page_chunk_comments(_values) {
|
||||
if (DEV) {
|
||||
console.warn(
|
||||
`%c[sveltekit] ${'transform_page_chunk_comments'}\n%c${`Removing comments in \`transformPageChunk\` can break Svelte's hydration`}\nhttps://svelte.dev/e/kit/${'transform_page_chunk_comments'}`,
|
||||
bold,
|
||||
normal
|
||||
);
|
||||
} else {
|
||||
console.warn('https://svelte.dev/e/kit/transform_page_chunk_comments');
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user