This commit is contained in:
2026-11-02 12:42:04 +00:00
commit e4e28174bf
5498 changed files with 1735888 additions and 0 deletions

21
node_modules/@sveltejs/vite-plugin-svelte/LICENSE generated vendored Normal file
View File

@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2021 [these people](https://github.com/sveltejs/vite-plugin-svelte/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.

28
node_modules/@sveltejs/vite-plugin-svelte/README.md generated vendored Normal file
View File

@@ -0,0 +1,28 @@
# @sveltejs/vite-plugin-svelte
The official [Svelte](https://svelte.dev) plugin for [Vite](https://vitejs.dev).
## Usage
```js
// vite.config.js
import { defineConfig } from 'vite';
import { svelte } from '@sveltejs/vite-plugin-svelte';
export default defineConfig({
plugins: [
svelte({
// plugin options
})
]
});
```
## Documentation
- [Plugin options](../../docs/config.md)
- [FAQ](../../docs/faq.md)
## License
[MIT](./LICENSE)

56
node_modules/@sveltejs/vite-plugin-svelte/package.json generated vendored Normal file
View File

@@ -0,0 +1,56 @@
{
"name": "@sveltejs/vite-plugin-svelte",
"version": "7.3.1",
"license": "MIT",
"files": [
"src",
"types"
],
"type": "module",
"types": "types/index.d.ts",
"exports": {
".": {
"types": "./types/index.d.ts",
"default": "./src/index.js"
}
},
"engines": {
"node": "^20.19 || ^22.12 || >=24"
},
"repository": {
"type": "git",
"url": "git+https://github.com/sveltejs/vite-plugin-svelte.git",
"directory": "packages/vite-plugin-svelte"
},
"keywords": [
"vite-plugin",
"vite plugin",
"vite",
"svelte"
],
"bugs": {
"url": "https://github.com/sveltejs/vite-plugin-svelte/issues"
},
"homepage": "https://github.com/sveltejs/vite-plugin-svelte#readme",
"dependencies": {
"deepmerge": "^4.3.1",
"magic-string": "^1.0.0",
"obug": "^2.1.0",
"vitefu": "^1.1.2"
},
"peerDependencies": {
"svelte": "^5.46.4",
"vite": "^8.0.0-beta.7 || ^8.0.0"
},
"devDependencies": {
"@types/debug": "^4.1.12",
"sass": "^1.94.2",
"svelte": "^5.45.4",
"vite": "^8.0.9"
},
"scripts": {
"check:publint": "publint --strict",
"check:types": "tsc --noEmit",
"generate:types": "dts-buddy -m \"@sveltejs/vite-plugin-svelte:src/public.d.ts\""
}
}

46
node_modules/@sveltejs/vite-plugin-svelte/src/index.js generated vendored Normal file
View File

@@ -0,0 +1,46 @@
/** @import { Options } from './public.js' */
/** @import { PluginAPI } from './types/plugin-api.js' */
/** @import { Plugin } from 'vite' */
import process from 'node:process';
import { log } from './utils/log.js';
import { configure } from './plugins/configure.js';
import { preprocess } from './plugins/preprocess.js';
import { compile } from './plugins/compile.js';
import { loadCompiledCss } from './plugins/load-compiled-css.js';
import { setupOptimizer } from './plugins/setup-optimizer.js';
import { compileModule } from './plugins/compile-module.js';
import { svelteInspector } from './plugins/inspector/index.js';
import { loadCustom } from './plugins/load-custom.js';
import { hotUpdate } from './plugins/hot-update.js';
/**
* returns a list of plugins to handle svelte files
* plugins are named `vite-plugin-svelte:<task>`
*
* @param {Partial<Options>} [inlineOptions]
* @returns {Plugin[]}
*/
export function svelte(inlineOptions) {
if (process.env.DEBUG != null) {
log.setLevel('debug');
}
/** @type {PluginAPI} */
// @ts-expect-error initialize empty to guard against early use
const api = {}; // initialized by configure plugin, used in others
return [
{ name: 'vite-plugin-svelte' }, // marker for detection logic in other plugins that expect this name
configure(api, inlineOptions),
setupOptimizer(api),
loadCompiledCss(api),
loadCustom(api),
preprocess(api),
compile(api),
compileModule(api),
hotUpdate(api),
svelteInspector(api)
];
}
export { vitePreprocess } from './preprocess.js';
export { loadSvelteConfig } from './utils/load-svelte-config.js';

View File

@@ -0,0 +1,137 @@
/** @import { ModuleIdParser } from '../types/id.js' */
/** @import { ResolvedOptions } from '../types/options.js' */
/** @import { PluginAPI } from '../types/plugin-api.js' */
/** @import { CompileOptions, ModuleCompileOptions } from 'svelte/compiler' */
/** @import { Plugin } from 'vite' */
import { buildModuleIdFilter, buildModuleIdParser } from '../utils/id.js';
import * as svelteCompiler from 'svelte/compiler';
import { log, logCompilerWarnings } from '../utils/log.js';
import { toRollupError } from '../utils/error.js';
import { isSvelteWithAsync } from '../utils/svelte-version.js';
/**
* @param {PluginAPI} api
* @returns {Plugin}
*/
export function compileModule(api) {
/**
* @type {ResolvedOptions}
*/
let options;
/**
* @type {ModuleIdParser}
*/
let idParser;
/**
* @type {ModuleCompileOptions}
*/
let staticModuleCompileOptions;
/** @type {Plugin} */
const plugin = {
name: 'vite-plugin-svelte:compile-module',
enforce: 'post',
async configResolved() {
options = api.options;
//@ts-expect-error transform defined below but filter not in type
plugin.transform.filter = buildModuleIdFilter(options);
idParser = buildModuleIdParser(options);
staticModuleCompileOptions = filterNonModuleCompilerOptions(options.compilerOptions);
},
transform: {
async handler(code, id) {
const ssr = this.environment.config.consumer === 'server';
const moduleRequest = idParser(id, ssr);
if (!moduleRequest) {
return;
}
const filename = moduleRequest.filename;
/** @type {CompileOptions} */
const compileOptions = {
...staticModuleCompileOptions,
dev: !this.environment.config.isProduction,
generate: ssr ? 'server' : 'client',
filename
};
const dynamicCompileOptions = await options?.dynamicCompileOptions?.({
filename,
code,
compileOptions,
environment: this.environment
});
if (dynamicCompileOptions && log.debug.enabled) {
log.debug(
`dynamic compile options for ${filename}: ${JSON.stringify(dynamicCompileOptions)}`,
undefined,
'compileModule'
);
}
const finalCompileOptions = dynamicCompileOptions
? {
...compileOptions,
...dynamicCompileOptions
}
: compileOptions;
if (dynamicCompileOptions?.experimental) {
finalCompileOptions.experimental = {
...compileOptions.experimental,
...dynamicCompileOptions.experimental
};
}
const finalModuleCompileOptions = filterNonModuleCompilerOptions(finalCompileOptions);
if (log.debug.enabled) {
log.debug(
`final ModuleCompileOptions for ${filename}: ${JSON.stringify(finalModuleCompileOptions)}`,
undefined,
'compileModule'
);
}
try {
const compileResult = svelteCompiler.compileModule(code, finalModuleCompileOptions);
logCompilerWarnings(moduleRequest, compileResult.warnings, options);
return compileResult.js;
} catch (e) {
throw toRollupError(e, options);
}
}
}
};
return plugin;
}
/**
*
* @param {CompileOptions} compilerOptions
* @return {ModuleCompileOptions}
*/
function filterNonModuleCompilerOptions(compilerOptions) {
/** @type {Array<keyof ModuleCompileOptions>} */
const knownModuleCompileOptionNames = ['dev', 'generate', 'filename', 'rootDir', 'warningFilter'];
if (isSvelteWithAsync) {
knownModuleCompileOptionNames.push('experimental');
}
// not typed but this is temporary until svelte itself ignores CompileOptions passed to compileModule
const experimentalModuleCompilerOptionNames = ['async'];
/** @type {ModuleCompileOptions} */
const filtered = filterByPropNames(compilerOptions, knownModuleCompileOptionNames);
if (filtered.experimental) {
filtered.experimental = filterByPropNames(
filtered.experimental,
experimentalModuleCompilerOptionNames
);
}
return filtered;
}
/**
*
* @param {object} o
* @param {string[]} names
* @returns {object}
*/
function filterByPropNames(o, names) {
return Object.fromEntries(Object.entries(o).filter(([name]) => names.includes(name)));
}

View File

@@ -0,0 +1,71 @@
/** @import { CompileSvelte } from '../types/compile.js' */
/** @import { ResolvedOptions } from '../types/options.js' */
/** @import { PluginAPI } from '../types/plugin-api.js' */
/** @import { Plugin } from 'vite' */
import { toRollupError } from '../utils/error.js';
import { logCompilerWarnings } from '../utils/log.js';
/**
* @param {PluginAPI} api
* @returns {Plugin}
*/
export function compile(api) {
/**
* @type {ResolvedOptions}
*/
let options;
/**
* @type {CompileSvelte}
*/
let compileSvelte;
/** @type {Plugin} */
const plugin = {
name: 'vite-plugin-svelte:compile',
configResolved() {
//@ts-expect-error defined below but filter not in type
plugin.transform.filter = api.filter;
options = api.options;
compileSvelte = api.compileSvelte;
},
transform: {
async handler(code, id) {
const ssr = this.environment.config.consumer === 'server';
const svelteRequest = api.idParser(id, ssr);
if (!svelteRequest || svelteRequest.raw) {
return;
}
let compileData;
try {
compileData = await compileSvelte(
svelteRequest,
code,
options,
this.environment,
this.getCombinedSourcemap()
);
} catch (e) {
throw toRollupError(e, options);
}
if (compileData.compiled?.warnings) {
logCompilerWarnings(svelteRequest, compileData.compiled.warnings, options);
}
return {
...compileData.compiled.js,
moduleType: 'js',
meta: {
vite: {
lang: compileData.lang
},
svelte: {
css: compileData.compiled.css
}
}
};
}
}
};
return plugin;
}

View File

@@ -0,0 +1,87 @@
/** @import { Options } from '../public.js' */
/** @import { PreResolvedOptions } from '../types/options.js' */
/** @import { PluginAPI } from '../types/plugin-api.js' */
/** @import { Plugin } from 'vite' */
import process from 'node:process';
import { isDebugNamespaceEnabled, log } from '../utils/log.js';
import { VitePluginSvelteStats } from '../utils/vite-plugin-svelte-stats.js';
import {
buildExtraViteConfig,
validateInlineOptions,
resolveOptions,
preResolveOptions,
ensureConfigEnvironmentMainFields,
ensureConfigEnvironmentConditions
} from '../utils/options.js';
import { buildIdFilter, buildIdParser } from '../utils/id.js';
import { createCompileSvelte } from '../utils/compile.js';
/**
* @param {Partial<Options>} [inlineOptions]
* @param {PluginAPI} api
* @returns {Plugin}
*/
export function configure(api, inlineOptions) {
validateInlineOptions(inlineOptions);
/**
* @type {PreResolvedOptions}
*/
let preOptions;
/** @type {Plugin} */
return {
name: 'vite-plugin-svelte:config',
api,
// make sure it runs first
enforce: 'pre',
config: {
order: 'pre',
async handler(config, configEnv) {
// setup logger
if (process.env.DEBUG) {
log.setLevel('debug');
} else if (config.logLevel) {
log.setLevel(config.logLevel);
}
preOptions = await preResolveOptions(inlineOptions, config, configEnv);
// extra vite config
const extraViteConfig = await buildExtraViteConfig(preOptions, config);
log.debug('additional vite config', extraViteConfig, 'config');
return extraViteConfig;
}
},
configResolved: {
order: 'pre',
handler(config) {
const options = resolveOptions(preOptions, config);
api.options = options;
if (isDebugNamespaceEnabled('stats')) {
api.options.stats = new VitePluginSvelteStats();
}
api.filter = buildIdFilter(options);
api.idParser = buildIdParser(options);
api.compileSvelte = createCompileSvelte();
log.debug('resolved options', api.options, 'config');
}
},
configEnvironment(name, config, opts) {
ensureConfigEnvironmentMainFields(name, config, opts);
// @ts-expect-error the function above should make `resolve.mainFields` non-nullable
config.resolve.mainFields.unshift('svelte');
ensureConfigEnvironmentConditions(name, config, opts);
// @ts-expect-error the function above should make `resolve.conditions` non-nullable
config.resolve.conditions.push('svelte');
},
configureServer(server) {
const { options } = api;
options.server = server;
}
};
}

View File

@@ -0,0 +1,201 @@
/** @import { IdParser } from '../types/id.js' */
/** @import { ResolvedOptions } from '../types/options.js' */
/** @import { PluginAPI } from '../types/plugin-api.js' */
/** @import { Plugin } from 'vite' */
import { log } from '../utils/log.js';
import { setupWatchers } from '../utils/watch.js';
import { SVELTE_VIRTUAL_STYLE_ID_REGEX } from '../utils/constants.js';
/**
* @param {PluginAPI} api
* @returns {Plugin}
*/
export function hotUpdate(api) {
/**
* @type {ResolvedOptions}
*/
let options;
/**
* @type {IdParser}
*/
let idParser;
/**
*
* @type {Map<string|null,string>}
*/
const transformResultCache = new Map();
/** @type {Plugin} */
const plugin = {
name: 'vite-plugin-svelte:hot-update',
enforce: 'post',
configResolved() {
options = api.options;
idParser = api.idParser;
// @ts-expect-error
plugin.transform.filter = {
id: {
// reinclude virtual styles to get their output
include: [...api.filter.id.include, SVELTE_VIRTUAL_STYLE_ID_REGEX],
exclude: [
// ignore files in node_modules, we don't hot update them
/\/node_modules\//,
// remove style exclusion
...api.filter.id.exclude.filter((filter) => filter !== SVELTE_VIRTUAL_STYLE_ID_REGEX)
]
}
};
},
applyToEnvironment(env) {
// we only handle updates for client components
// ssr frameworks have to handle updating/reloading themselves as v-p-s can't know what they prefer
const hmrEnabled = options.compilerOptions.hmr && options.emitCss;
return hmrEnabled && env.config.consumer === 'client';
},
configureServer(server) {
const clientEnvironment = Object.values(server.environments).find(
(e) => e.config.consumer === 'client'
);
if (clientEnvironment) {
setupWatchers(options);
} else {
log.warn(
'No client environment found, not adding watchers for svelte config and preprocessor dependencies'
);
}
},
buildStart() {
transformResultCache.clear();
},
transform: {
order: 'post',
handler(code, id) {
transformResultCache.set(id, code);
}
},
hotUpdate: {
order: 'post',
async handler(ctx) {
const svelteRequest = idParser(ctx.file, false, ctx.timestamp);
if (svelteRequest) {
const { modules } = ctx;
const svelteModules = [];
const nonSvelteModules = [];
for (const mod of modules) {
if (transformResultCache.has(mod.id)) {
svelteModules.push(mod);
} else {
nonSvelteModules.push(mod);
}
}
if (svelteModules.length === 0) {
return; // nothing to do for us
}
const affectedModules = [];
const prevResults = svelteModules.map((m) => transformResultCache.get(m.id));
/** @type {Set<string>} */
const seen = new Set();
/** @param {string} url */
const transformRequest = async (url) => {
if (!seen.has(url)) {
seen.add(url);
await this.environment.transformRequest(url);
}
};
// Transform the Svelte component itself first, so that the
// CSS cache always gets updated.
await transformRequest(svelteRequest.filename);
for (let i = 0; i < svelteModules.length; i++) {
const mod = svelteModules[i];
const prev = prevResults[i];
await transformRequest(mod.url);
const next = transformResultCache.get(mod.id);
if (hasCodeChanged(prev, next, mod.id)) {
affectedModules.push(mod);
} else {
log.debug(
`skipping hot update for ${mod.id} because result is unchanged`,
undefined,
'hmr'
);
}
}
log.debug(
`hotUpdate for ${svelteRequest.id} result: [${affectedModules.map((m) => m.id).join(', ')}]`,
undefined,
'hmr'
);
return [...affectedModules, ...nonSvelteModules];
}
}
}
};
return plugin;
}
/**
* @param {string | undefined | null} prev
* @param {string | undefined | null} next
* @param {string | null} id
* @returns {boolean}
*/
function hasCodeChanged(prev, next, id) {
const isStrictEqual = nullSafeEqual(prev, next);
if (isStrictEqual) {
return false;
}
const isLooseEqual = nullSafeEqual(normalize(prev), normalize(next));
if (!isStrictEqual && isLooseEqual) {
log.debug(
`ignoring compiler output change for ${id} as it is equal to previous output after normalization`,
undefined,
'hmr'
);
}
return !isLooseEqual;
}
/**
* @param {string | null | undefined} prev
* @param {string | null | undefined} next
* @returns {boolean}
*/
function nullSafeEqual(prev, next) {
return (prev == null && next == null) || (prev != null && next != null && prev === next);
}
/**
* remove code that only changes metadata and does not require a js update for the component to keep working
*
* 1) location numbers argument from $.add_locations calls in svelte output eg [[1,2],[3,4]]
* 2) timestamp queries added to imports by vite eg ?t=0123456789123
*
* @param {string | null | undefined } code
* @returns {string | null | undefined}
*/
function normalize(code) {
if (code == null) {
return code;
}
return (
code
// svelte5 $.add_locations line numbers argument [[1,2],[3,4]]
// uses matching group replace to keep the template argument intact
.replace(/(\$\.add_locations\(.*), (\[\[[\d, [\]]+]])\)/g, '$1, []')
// vite import analysis timestamp queries, ?t=0123456789123&
.replace(/[?&]t=\d{13}\b/g, '')
);
}

View File

@@ -0,0 +1,132 @@
/** @import { InspectorOptions } from '../../public.js' */
/** @import { PluginAPI } from '../../types/plugin-api.js' */
/** @import { Plugin } from 'vite' */
import { normalizePath } from 'vite';
import fs from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import { defaultInspectorOptions, parseEnvironmentOptions } from './options.js';
import { log } from '../../utils/log.js';
/**
* @param {string} url
* @returns {string} url without query params or hash
*/
function cleanUrl(url) {
return url.replace(/[?#].*$/s, '');
}
function getInspectorPath() {
const pluginPath = normalizePath(path.dirname(fileURLToPath(import.meta.url)));
return pluginPath.replace(
/\/vite-plugin-svelte\/src\/plugins\/inspector$/,
'/vite-plugin-svelte/src/plugins/inspector/runtime/'
);
}
/**
* @param {PluginAPI} api
* @returns {Plugin}
*/
export function svelteInspector(api) {
const inspectorPath = getInspectorPath();
log.debug(`svelte inspector path: ${inspectorPath}`, null, 'inspector');
/** @type {InspectorOptions} */
let inspectorOptions;
let disabled = false;
return {
name: 'vite-plugin-svelte-inspector',
apply: 'serve',
enforce: 'pre',
applyToEnvironment(env) {
return !disabled && env.config.consumer === 'client';
},
configResolved(config) {
const environmentOptions = parseEnvironmentOptions(config);
if (environmentOptions === false) {
log.debug('environment options set to false, inspector disabled', null, 'inspector');
disabled = true;
return;
}
const configFileOptions = api.options?.inspector;
if (!configFileOptions && !environmentOptions) {
log.debug('no inspector options found, inspector disabled', null, 'inspector');
disabled = true;
return;
}
if (environmentOptions === true) {
inspectorOptions = defaultInspectorOptions;
} else {
inspectorOptions = {
...defaultInspectorOptions,
...(typeof configFileOptions === 'object' ? configFileOptions : {}),
...(environmentOptions || {})
};
}
inspectorOptions.__internal = {
base: config.base?.replace(/\/$/, '') || ''
};
},
resolveId: {
filter: {
id: /^virtual:svelte-inspector-/
},
async handler(id) {
if (disabled) {
return;
}
if (id === 'virtual:svelte-inspector-options') {
return id;
} else if (id.startsWith('virtual:svelte-inspector-path:') && !id.includes('..')) {
return id.replace('virtual:svelte-inspector-path:', inspectorPath);
}
}
},
load: {
filter: {
id: {
include: [`${inspectorPath}/**`, /^virtual:svelte-inspector-options$/],
exclude: [/style&lang\.css$/]
}
},
async handler(id) {
if (disabled) {
return;
}
if (id === 'virtual:svelte-inspector-options') {
return `export default ${JSON.stringify(inspectorOptions ?? {})}`;
} else if (id.startsWith(inspectorPath)) {
// read file ourselves to avoid getting shut out by vites fs.allow check
const file = cleanUrl(id);
if (fs.existsSync(file)) {
return await fs.promises.readFile(file, 'utf-8');
} else {
log.error(`failed to find svelte-inspector: ${id}`, null, 'inspector');
}
}
}
},
transform: {
// Vite+ projects install vite@npm:@voidzero-dev/vite-plus-core@latest which
// changes the path from `vite/dist/client/client.mjs` to `vite/dist/vite/client/client.mjs`
// TODO: inject with transformIndexHtml when it works with SSR
filter: {
id: /(?:vite\/dist|vite\/dist\/vite|vite-plus-core\/dist\/vite)\/client\/client\.mjs(?:\?|$)/
},
handler(code) {
if (disabled) {
return;
}
return { code: `${code}\nimport('virtual:svelte-inspector-path:load-inspector.js')` };
}
}
};
}

View File

@@ -0,0 +1,69 @@
/** @import { InspectorOptions } from '../../public.js' */
/** @import { ResolvedConfig } from 'vite' */
import process from 'node:process';
import { loadEnv } from 'vite';
import { log } from '../../utils/log.js';
/** @type {InspectorOptions} */
export const defaultInspectorOptions = {
toggleKeyCombo: 'alt-x',
navKeys: { parent: 'ArrowUp', child: 'ArrowDown', next: 'ArrowRight', prev: 'ArrowLeft' },
escapeKeys: ['Backspace', 'Escape'],
openKey: 'Enter',
openMenuKey: ' ',
holdMode: true,
showToggleButton: 'active',
toggleButtonPos: 'top-right',
customStyles: true
};
/**
* @param {ResolvedConfig} config
* @returns {Partial<InspectorOptions> | boolean | void}
*/
export function parseEnvironmentOptions(config) {
const env = loadEnv(config.mode, config.envDir ?? process.cwd(), 'SVELTE_INSPECTOR');
const options = env?.SVELTE_INSPECTOR_OPTIONS;
const toggle = env?.SVELTE_INSPECTOR_TOGGLE;
if (options) {
try {
const parsed = JSON.parse(options);
const parsedType = typeof parsed;
if (parsedType === 'boolean') {
return parsed;
} else if (parsedType === 'object') {
if (Array.isArray(parsed)) {
throw new Error('invalid type, expected object map but got array');
}
const parsedKeys = Object.keys(parsed);
const defaultKeys = Object.keys(defaultInspectorOptions);
const unknownKeys = parsedKeys.filter((k) => !defaultKeys.includes(k));
if (unknownKeys.length) {
log.warn(
`[vite-plugin-svelte-inspector] ignoring unknown options in environment SVELTE_INSPECTOR_OPTIONS: ${unknownKeys.join(
', '
)}`,
null,
'inspector'
);
for (const key of unknownKeys) {
delete parsed[key];
}
}
log.debug('loaded environment config', parsed, 'inspector');
return parsed;
}
} catch (e) {
config.logger.error(
`[vite-plugin-svelte-inspector] failed to parse inspector options from environment SVELTE_INSPECTOR_OPTIONS="${options}"\n${e}`
);
}
} else if (toggle) {
const keyConfig = {
toggleKeyCombo: toggle
};
log.debug('loaded environment config', keyConfig, 'inspector');
return keyConfig;
}
}

View File

@@ -0,0 +1,644 @@
<script lang="ts">
import { onMount } from 'svelte';
import options from 'virtual:svelte-inspector-options';
// Copied from Svelte's internal types
interface DevStackEntry {
file: string;
type: 'component' | 'if' | 'each' | 'await' | 'key' | 'render';
line: number;
column: number;
parent: DevStackEntry | null;
componentTag?: string;
}
interface Metadata {
loc: Loc;
parent?: DevStackEntry;
}
interface Loc {
file: string;
line: number;
column: number;
}
interface ElementWithMetadata extends Element {
__svelte_meta: Metadata;
}
const toggle_combo = options.toggleKeyCombo.toLowerCase().split('-');
const escape_keys = options.escapeKeys.map((k) => k.toLowerCase());
const nav_keys = Object.values(options.navKeys).map((k) => k.toLowerCase());
const open_key = options.openKey.toLowerCase();
const open_menu_key = options.openMenuKey.toLowerCase();
let enabled = $state(false);
let has_opened = $state(false);
const icon = `data:image/svg+xml;base64,${btoa(
`
<svg xmlns="http://www.w3.org/2000/svg" width="21" height="25" viewBox="0 0 107 128">
<title>svelte-inspector-logo</title>
<path d="M94.1566,22.8189c-10.4-14.8851-30.94-19.2971-45.7914-9.8348L22.2825,29.6078A29.9234,29.9234,0,0,0,8.7639,49.6506a31.5136,31.5136,0,0,0,3.1076,20.2318A30.0061,30.0061,0,0,0,7.3953,81.0653a31.8886,31.8886,0,0,0,5.4473,24.1157c10.4022,14.8865,30.9423,19.2966,45.7914,9.8348L84.7167,98.3921A29.9177,29.9177,0,0,0,98.2353,78.3493,31.5263,31.5263,0,0,0,95.13,58.117a30,30,0,0,0,4.4743-11.1824,31.88,31.88,0,0,0-5.4473-24.1157" style="fill:#ff3e00"/><path d="M45.8171,106.5815A20.7182,20.7182,0,0,1,23.58,98.3389a19.1739,19.1739,0,0,1-3.2766-14.5025,18.1886,18.1886,0,0,1,.6233-2.4357l.4912-1.4978,1.3363.9815a33.6443,33.6443,0,0,0,10.203,5.0978l.9694.2941-.0893.9675a5.8474,5.8474,0,0,0,1.052,3.8781,6.2389,6.2389,0,0,0,6.6952,2.485,5.7449,5.7449,0,0,0,1.6021-.7041L69.27,76.281a5.4306,5.4306,0,0,0,2.4506-3.631,5.7948,5.7948,0,0,0-.9875-4.3712,6.2436,6.2436,0,0,0-6.6978-2.4864,5.7427,5.7427,0,0,0-1.6.7036l-9.9532,6.3449a19.0329,19.0329,0,0,1-5.2965,2.3259,20.7181,20.7181,0,0,1-22.2368-8.2427,19.1725,19.1725,0,0,1-3.2766-14.5024,17.9885,17.9885,0,0,1,8.13-12.0513L55.8833,23.7472a19.0038,19.0038,0,0,1,5.3-2.3287A20.7182,20.7182,0,0,1,83.42,29.6611a19.1739,19.1739,0,0,1,3.2766,14.5025,18.4,18.4,0,0,1-.6233,2.4357l-.4912,1.4978-1.3356-.98a33.6175,33.6175,0,0,0-10.2037-5.1l-.9694-.2942.0893-.9675a5.8588,5.8588,0,0,0-1.052-3.878,6.2389,6.2389,0,0,0-6.6952-2.485,5.7449,5.7449,0,0,0-1.6021.7041L37.73,51.719a5.4218,5.4218,0,0,0-2.4487,3.63,5.7862,5.7862,0,0,0,.9856,4.3717,6.2437,6.2437,0,0,0,6.6978,2.4864,5.7652,5.7652,0,0,0,1.602-.7041l9.9519-6.3425a18.978,18.978,0,0,1,5.2959-2.3278,20.7181,20.7181,0,0,1,22.2368,8.2427,19.1725,19.1725,0,0,1,3.2766,14.5024,17.9977,17.9977,0,0,1-8.13,12.0532L51.1167,104.2528a19.0038,19.0038,0,0,1-5.3,2.3287" style="fill:#fff"/>
<polygon points="0,0 15,40 40,20" stroke="#ff3e00" fill="#ff3e00"></polygon>
</svg>
`
.replace(/[\n\r\t\s]+/g, ' ')
.trim()
)}`;
// overlay positioning
let x = $state(0),
y = $state(0),
w = $state(0),
h = $state(0);
let active_el = $state<ElementWithMetadata | undefined>();
let menu = $state<{ x: number; y: number; stack: Array<Loc & { tag: string }> } | null>(null);
let hold_start_ts = $state<number | null>(null);
let show_toggle = $derived(
options.showToggleButton === 'always' || (options.showToggleButton === 'active' && enabled)
);
function mousemove(e: MouseEvent) {
if (menu) return;
x = e.x;
y = e.y;
}
function find_selectable_parent(el: Element | undefined, include_self = false) {
let candidate: Element | undefined = el;
if (!include_self) {
candidate = (candidate?.parentNode as Element) ?? undefined;
}
while (candidate) {
if (is_selectable(candidate)) {
return candidate;
}
candidate = candidate.parentNode as Element;
}
}
function find_selectable_child(el: Element) {
return [...el.querySelectorAll('*')].find(is_selectable);
}
function find_selectable_sibling(el: Element, prev = false) {
let candidate: Element | null = el;
do {
candidate = prev ? candidate.previousElementSibling : candidate.nextElementSibling;
if (is_selectable(candidate)) {
return candidate;
}
} while (candidate);
}
function find_selectable_for_nav(key: string) {
const el = active_el;
if (!el) {
return find_selectable_child(document?.body);
}
switch (key) {
case options.navKeys.parent:
return find_selectable_parent(el);
case options.navKeys.child:
return find_selectable_child(el);
case options.navKeys.next:
return find_selectable_sibling(el) || find_selectable_parent(el);
case options.navKeys.prev:
return find_selectable_sibling(el, true) || find_selectable_parent(el);
default:
return;
}
}
function is_selectable(el: Element | null): el is ElementWithMetadata {
if (!el) return false;
const file = (el as ElementWithMetadata)?.__svelte_meta?.loc?.file;
if (!file || file.includes('node_modules/')) {
return false; // no file or 3rd party
}
const id = el.getAttribute('id');
if (id === 'svelte-announcer' || id?.startsWith('svelte-inspector-')) {
return false; // ignore some elements by id that would be selectable from keyboard nav otherwise
}
return true;
}
function mouseover(e: MouseEvent) {
if (menu) return;
const el = find_selectable_parent(e.target as ElementWithMetadata, true);
activate(el, false);
}
function activate(el: ElementWithMetadata | undefined, set_bubble_pos = true) {
if (options.customStyles && el !== active_el) {
if (active_el) {
active_el.classList.remove('svelte-inspector-active-target');
}
if (el) {
el.classList.add('svelte-inspector-active-target');
}
}
active_el = el;
if (set_bubble_pos) {
const pos = el!.getBoundingClientRect();
x = Math.ceil(pos.left);
y = Math.ceil(pos.bottom - 20);
}
}
function open_editor(e: Event) {
if (menu) return;
if (active_el) {
stop(e);
send(active_el.__svelte_meta.loc);
}
}
function get_stack(target: ElementWithMetadata) {
const el = find_selectable_parent(target, true)!;
const meta = el.__svelte_meta;
const stack = [
{
file: meta.loc.file,
line: meta.loc.line,
column: meta.loc.column,
tag: el.tagName.toLowerCase()
}
];
let entry: Metadata | DevStackEntry | undefined = meta;
while ((entry = entry.parent ?? undefined)) {
if (entry.type !== 'component') continue;
if (/(^|\/)(node_modules|\.svelte-kit)\//.test(entry.file)) continue;
stack.push({
file: entry.file,
line: entry.line,
column: entry.column,
tag: entry.componentTag!
});
}
return stack;
}
function on_contextmenu(e: Event) {
e.preventDefault();
active_el ??= find_selectable_parent(e.target as Element);
if (!active_el) return;
stop(e);
menu = { x, y, stack: get_stack(active_el) };
}
function send(loc: Loc) {
fetch(
`${options.__internal.base}/__open-in-editor?file=${encodeURIComponent(
`${loc.file}:${loc.line}:${loc.column + 1}`
)}`
);
has_opened = true;
menu = null;
if (options.holdMode && is_holding()) {
disable();
}
}
function is_active(key: string, e: KeyboardEvent) {
switch (key) {
case 'shift':
case 'control':
case 'alt':
case 'meta':
return e.getModifierState(key.charAt(0).toUpperCase() + key.slice(1));
default:
return key === e.code.replace(/^Key/, '').toLowerCase() || key === e.key.toLowerCase();
}
}
function is_combo(e: KeyboardEvent) {
return toggle_combo?.every((k) => is_active(k, e));
}
function is_escape(e: KeyboardEvent) {
return escape_keys?.some((k) => is_active(k, e));
}
function is_toggle(e: KeyboardEvent) {
return toggle_combo?.some((k) => is_active(k, e));
}
function is_nav(e: KeyboardEvent) {
return nav_keys?.some((k) => is_active(k, e));
}
function is_open(e: KeyboardEvent) {
return open_key && is_active(open_key, e);
}
function is_open_menu(e: KeyboardEvent) {
return open_menu_key && is_active(open_menu_key, e);
}
function is_holding() {
return hold_start_ts && Date.now() - hold_start_ts > 250;
}
function stop(e: Event) {
e.preventDefault();
e.stopPropagation();
e.stopImmediatePropagation();
}
function keydown(e: KeyboardEvent) {
if (e.repeat || e.key == null || (!enabled && !is_toggle(e))) {
return;
}
if (is_combo(e)) {
toggle();
if (options.holdMode && enabled) {
hold_start_ts = Date.now();
}
} else if (enabled) {
if (is_nav(e)) {
const el = find_selectable_for_nav(e.key);
if (el) {
activate(el);
stop(e);
}
} else if (is_open(e)) {
open_editor(e);
} else if (is_open_menu(e)) {
on_contextmenu(e);
} else if (is_holding() || is_escape(e)) {
// is_holding() checks for unhandled additional key pressed
// while holding the toggle keys, which is possibly another
// shortcut (e.g. 'meta-shift-x'), so disable again.
disable();
}
}
}
function keyup(e: KeyboardEvent) {
if (e.repeat || e.key == null || !enabled) {
return;
}
if (is_toggle(e)) {
if (is_holding()) {
disable();
} else {
hold_start_ts = null;
}
}
}
function toggle() {
if (enabled) {
disable();
} else {
enable();
}
}
function listeners(body: HTMLBodyElement, enabled: boolean) {
const l = enabled ? body.addEventListener : body.removeEventListener;
l('mousemove', mousemove);
l('mouseover', mouseover);
l('click', open_editor, true);
l('contextmenu', on_contextmenu, true);
}
function enable() {
enabled = true;
const b = document.body as HTMLBodyElement;
if (options.customStyles) {
b.classList.add('svelte-inspector-enabled');
}
listeners(b, enabled);
activate_initial_el();
}
function activate_initial_el() {
const hov = innermost_hover_el();
let el = find_selectable_parent(hov, true);
if (!el) {
const act = document.activeElement ?? undefined;
el = find_selectable_parent(act, true);
}
if (!el) {
el = find_selectable_child(document.body);
}
if (el) {
activate(el);
}
}
function innermost_hover_el() {
let e = document.body.querySelector(':hover');
let result;
while (e) {
result = e;
e = e.querySelector(':hover');
}
return result;
}
function disable() {
enabled = false;
has_opened = false;
hold_start_ts = null;
menu = null;
const b = document.body as HTMLBodyElement;
listeners(b, enabled);
if (options.customStyles) {
b.classList.remove('svelte-inspector-enabled');
active_el?.classList.remove('svelte-inspector-active-target');
}
active_el = undefined;
}
function visibilityChange() {
if (document.visibilityState === 'hidden') {
onLeave();
}
}
function onLeave() {
// disable if a file has been opened or combo is held
if (enabled && (has_opened || hold_start_ts)) {
disable();
}
}
onMount(() => {
const s = document.createElement('style');
s.setAttribute('type', 'text/css');
s.setAttribute('id', 'svelte-inspector-style');
s.textContent = `:root { --svelte-inspector-icon: url(${icon})};`;
document.head.append(s);
if (toggle_combo) {
document.body.addEventListener('keydown', keydown);
if (options.holdMode) {
document.body.addEventListener('keyup', keyup);
}
}
document.addEventListener('visibilitychange', visibilityChange);
document.documentElement.addEventListener('mouseleave', onLeave);
return () => {
// make sure we get rid of everything
disable();
const s = document.head.querySelector('#svelte-inspector-style');
if (s) {
document.head.removeChild(s);
}
if (toggle_combo) {
document.body.removeEventListener('keydown', keydown);
if (options.holdMode) {
document.body.removeEventListener('keyup', keyup);
}
}
document.removeEventListener('visibilitychange', visibilityChange);
document.documentElement.removeEventListener('mouseleave', onLeave);
};
});
</script>
<svelte:window
onclick={disable}
onkeydown={(e) => {
if (e.key === 'Escape') {
disable();
}
}}
/>
{#if show_toggle}
<button
id="svelte-inspector-toggle"
class:enabled
style={`background-image: var(--svelte-inspector-icon);${options.toggleButtonPos
.split('-')
.map((p) => `${p}: 8px;`)
.join('')}`}
onclick={() => toggle()}
aria-label={`${enabled ? 'disable' : 'enable'} svelte-inspector`}
></button>
{/if}
{#if enabled && (menu || active_el)}
<div
id="svelte-inspector-overlay"
style:left="{Math.min(x + 3, document.documentElement.clientWidth - w - 10)}px"
style:top="{document.documentElement.clientHeight < y + h + 40 ? y - h - 10 : y + 30}px"
bind:offsetWidth={w}
bind:offsetHeight={h}
>
{#if menu}
<button aria-label="close" class="svelte-inspector-button" {@attach (node) => node.focus()}>
<span>close</span>
<svg
xmlns="http://www.w3.org/2000/svg"
role="img"
width="1em"
height="1em"
viewBox="0 0 24 24"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"><path d="M18 6 6 18" /><path d="m6 6 12 12" /></svg
>
</button>
<hr />
<ul class="svelte-inspector-grid">
{#each menu.stack as item, i (item.file + item.line + i)}
<li>
<button type="button" class="svelte-inspector-menu-row" onclick={() => send(item)}>
<span class="svelte-inspector-tag">&lt;{item.tag}&gt;</span>
<span class="svelte-inspector-file">{item.file}:{item.line}</span>
</button>
</li>
{/each}
</ul>
{:else if active_el}
{@const loc = active_el.__svelte_meta.loc}
<div class="svelte-inspector-grid">
<div class="svelte-inspector-menu-row">
<span class="svelte-inspector-tag">&lt;{active_el.tagName.toLowerCase()}&gt;</span>
<span class="svelte-inspector-file">{loc.file}:{loc.line}</span>
</div>
</div>
<div id="svelte-inspector-announcer" aria-live="assertive" aria-atomic="true">
{active_el.tagName.toLowerCase()} in file {loc.file} on line {loc.line} column {loc.column +
1}
</div>
{/if}
</div>
{/if}
<style>
:global(body.svelte-inspector-enabled *) {
cursor: var(--svelte-inspector-icon), crosshair !important;
}
:global(.svelte-inspector-active-target) {
outline: 2px dashed #ff3e00 !important;
}
:global(#svelte-inspector-host) {
direction: ltr;
}
*:not(svg *) {
all: unset;
box-sizing: border-box;
}
#svelte-inspector-overlay {
position: fixed;
padding: 2px;
margin: 0;
border-radius: 2px;
filter: drop-shadow(2px 2px 4px rgb(0 0 0 / 0.1));
font-family: ui-monospace, 'SF Mono', Menlo, monospace;
font-size: 12px;
line-height: 1.4;
z-index: 999999;
background-color: #fff;
color: #222;
cursor: auto;
user-select: none;
}
.svelte-inspector-grid {
display: grid;
grid-template-columns: max-content 1fr;
column-gap: 8px;
/* row-gap: 4px; */
}
#svelte-inspector-toggle {
border: 1px solid #ff3e00;
border-radius: 8px;
position: fixed;
height: 32px;
width: 32px;
background-color: white;
background-position: center;
background-repeat: no-repeat;
cursor: pointer;
}
#svelte-inspector-announcer {
position: absolute;
left: 0px;
top: 0px;
clip: rect(0px, 0px, 0px, 0px);
clip-path: inset(50%);
overflow: hidden;
white-space: nowrap;
width: 1px;
height: 1px;
}
#svelte-inspector-toggle:not(.enabled) {
filter: grayscale(1);
}
#svelte-inspector-toggle:hover {
background-color: #facece;
}
.svelte-inspector-tag {
white-space: nowrap;
font-weight: 600;
}
.svelte-inspector-file {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
color: #444;
}
ul {
max-width: 480px;
list-style: none;
margin: 0;
padding: 0;
display: contents;
li {
display: contents;
}
}
button {
background: transparent;
border: none;
color: inherit;
pointer-events: all;
font: inherit;
align-items: center;
cursor: pointer;
&:focus-visible {
outline: 2px solid #ff3e00;
}
&:hover,
&:focus-visible {
background-color: rgb(0 0 0 / 0.05);
}
}
hr {
margin: 2px;
background: rgb(0 0 0 / 0.05);
border: none;
height: 1px;
width: 100%;
display: block;
}
svg path {
stroke: currentColor;
}
.svelte-inspector-button {
display: flex;
justify-content: space-between;
width: 100%;
padding: 4px 8px;
}
.svelte-inspector-menu-row {
display: grid;
grid-column: 1 / 3;
grid-template-columns: subgrid;
box-sizing: border-box;
align-items: baseline;
width: 100%;
padding: 4px 8px;
cursor: pointer;
&:hover,
&:focus-visible {
background-color: rgb(0 0 0 / 0.05);
}
}
</style>

View File

@@ -0,0 +1,4 @@
declare module 'virtual:svelte-inspector-options' {
const options: Required<import('../../../public.d.ts').InspectorOptions>;
export default options;
}

View File

@@ -0,0 +1,14 @@
// eslint-disable-next-line n/no-missing-import
import Inspector from 'virtual:svelte-inspector-path:Inspector.svelte';
import { mount } from 'svelte';
function create_inspector_host() {
const id = 'svelte-inspector-host';
if (document.getElementById(id) != null) {
throw new Error('svelte-inspector-host element already exists');
}
const el = document.createElement('div');
el.setAttribute('id', id);
document.documentElement.appendChild(el);
return el;
}
mount(Inspector, { target: create_inspector_host() });

View File

@@ -0,0 +1,79 @@
/** @import { PluginAPI } from '../types/plugin-api.js' */
/** @import { Plugin } from 'vite' */
import { log } from '../utils/log.js';
import { SVELTE_VIRTUAL_STYLE_ID_REGEX } from '../utils/constants.js';
const filter = { id: SVELTE_VIRTUAL_STYLE_ID_REGEX };
/**
* @param {PluginAPI} api
* @returns {Plugin}
*/
export function loadCompiledCss(api) {
let useLocalCache = false;
/** @type{Map<string,any>} */
const buildWatchCssCache = new Map();
return {
name: 'vite-plugin-svelte:load-compiled-css',
configResolved(c) {
const isDev = c.command === 'serve';
const isBuildWatch = !!c.build?.watch;
useLocalCache = isDev || isBuildWatch;
},
resolveId: {
filter, // same filter in load to ensure minimal work
handler(id) {
log.debug(`resolveId resolved virtual css module ${id}`, undefined, 'resolve');
return id;
}
},
load: {
filter,
async handler(id) {
const ssr = this.environment.config.consumer === 'server';
const svelteRequest = api.idParser(id, ssr);
if (!svelteRequest) {
return;
}
let cachedCss = this.getModuleInfo(svelteRequest.filename)?.meta.svelte?.css;
if (!cachedCss) {
// some module IDs have a ?v=... query string suffix in addition to the
// filename. We can retrieve this by running resolve again
const resolvedId = await this.resolve(svelteRequest.filename);
if (resolvedId?.id) {
cachedCss = this.getModuleInfo(resolvedId.id)?.meta.svelte?.css;
}
}
// in `build --watch` or dev ssr reloads getModuleInfo only returns changed module data.
// To ensure virtual css is loaded unchanged, we cache it here separately
if (useLocalCache) {
if (cachedCss) {
buildWatchCssCache.set(svelteRequest.filename, cachedCss);
} else {
cachedCss = buildWatchCssCache.get(svelteRequest.filename);
}
}
if (cachedCss) {
const { hasGlobal, ...css } = cachedCss;
if (hasGlobal === false) {
// hasGlobal was added in svelte 5.26.0, so make sure it is boolean false
css.meta ??= {};
css.meta.vite ??= {};
css.meta.vite.cssScopeTo = [svelteRequest.filename, 'default'];
}
css.moduleType = 'css';
return css;
} else {
log.warn(`failed to load virtual css module ${id}`, undefined, 'load');
}
}
}
};
}

View File

@@ -0,0 +1,45 @@
/** @import { PluginAPI } from '../types/plugin-api.js' */
/** @import { Plugin } from 'vite' */
import fs from 'node:fs';
import { log } from '../utils/log.js';
/**
* if svelte config includes files that vite treats as assets (e.g. .svg)
* we have to manually load them to avoid getting urls
*
* @param {PluginAPI} api
* @returns {Plugin}
*/
export function loadCustom(api) {
/** @type {Plugin} */
const plugin = {
name: 'vite-plugin-svelte:load-custom',
enforce: 'pre', // must come before vites own asset handling or custom extensions like .svg won't work
configResolved() {
//@ts-expect-error load defined below but filter not in type
plugin.load.filter = api.filter;
},
load: {
//filter: is set in configResolved
async handler(id) {
const config = this.environment.config;
const ssr = config.consumer === 'server';
const svelteRequest = api.idParser(id, ssr);
if (svelteRequest) {
const { filename, query } = svelteRequest;
if (!query.url && config.assetsInclude(filename)) {
log.debug(
`loading ${filename} to prevent vite asset handling to turn it into a url by default`,
undefined,
'load'
);
return fs.readFileSync(filename, 'utf-8');
}
}
}
}
};
return plugin;
}

View File

@@ -0,0 +1,215 @@
/** @import { PreprocessSvelte } from '../types/compile.js' */
/** @import { SvelteRequest } from '../types/id.js' */
/** @import { ResolvedOptions } from '../types/options.js' */
/** @import { PluginAPI } from '../types/plugin-api.js' */
/** @import { PreprocessorGroup } from 'svelte/compiler' */
/** @import { Plugin, ResolvedConfig, Rollup, ViteDevServer } from 'vite' */
import { toRollupError } from '../utils/error.js';
import { mapToRelative } from '../utils/sourcemaps.js';
import * as svelte from 'svelte/compiler';
import { log } from '../utils/log.js';
import { arraify } from '../utils/options.js';
import fs from 'node:fs';
import path from 'node:path';
/**
* @param {PluginAPI} api
* @returns {Plugin}
*/
export function preprocess(api) {
/**
* @type {ResolvedOptions}
*/
let options;
/**
* @type {DependenciesCache}
*/
let dependenciesCache;
/**
* @type {PreprocessSvelte}
*/
let preprocessSvelte;
/** @type {Plugin} */
const plugin = {
name: 'vite-plugin-svelte:preprocess',
enforce: 'pre',
configResolved(c) {
options = api.options;
if (arraify(options.preprocess).length > 0) {
preprocessSvelte = createPreprocessSvelte(options, c);
// @ts-expect-error defined below but filter not in type
plugin.transform.filter = api.filter;
} else {
log.debug(
`disabling ${plugin.name} because no preprocessor is configured`,
undefined,
'preprocess'
);
// @ts-expect-error force set undefined to clear memory
preprocessSvelte = undefined;
// @ts-expect-error defined below but filter not in type
plugin.transform.filter = { id: /$./ }; // never match
}
},
configureServer(server) {
dependenciesCache = new DependenciesCache(server);
},
buildStart() {
dependenciesCache?.clear();
},
transform: {
async handler(code, id) {
const ssr = this.environment.config.consumer === 'server';
const svelteRequest = api.idParser(id, ssr);
if (!svelteRequest) {
return;
}
try {
const preprocessed = await preprocessSvelte(svelteRequest, code, options);
dependenciesCache?.update(svelteRequest, preprocessed?.dependencies ?? []);
if (!preprocessed) {
return;
}
if (options.isBuild && this.environment.config.build.watch && preprocessed.dependencies) {
for (const dep of preprocessed.dependencies) {
this.addWatchFile(dep);
}
}
/** @type {Rollup.SourceDescription}*/
const result = { code: preprocessed.code };
if (preprocessed.map) {
// @ts-expect-error type differs but should work
result.map = preprocessed.map;
}
return result;
} catch (e) {
throw toRollupError(e, options);
}
}
}
};
return plugin;
}
/**
* @param {ResolvedOptions} options
* @param {ResolvedConfig} resolvedConfig
* @returns {PreprocessSvelte}
*/
function createPreprocessSvelte(options, resolvedConfig) {
/** @type {Array<PreprocessorGroup>} */
const preprocessors = arraify(options.preprocess);
for (const preprocessor of preprocessors) {
if (preprocessor.style && '__resolvedConfig' in preprocessor.style) {
preprocessor.style.__resolvedConfig = resolvedConfig;
}
}
/** @type {PreprocessSvelte} */
return async function preprocessSvelte(svelteRequest, code) {
const { filename } = svelteRequest;
let preprocessed;
if (preprocessors && preprocessors.length > 0) {
try {
preprocessed = await svelte.preprocess(code, preprocessors, { filename }); // full filename here so postcss works
} catch (e) {
e.message = `Error while preprocessing ${filename}${e.message ? ` - ${e.message}` : ''}`;
throw e;
}
if (typeof preprocessed?.map === 'object') {
mapToRelative(preprocessed?.map, filename);
}
return preprocessed;
}
};
}
/**
* @class
*
* caches dependencies of preprocessed files and emit change events on dependants
*/
class DependenciesCache {
/** @type {Map<string, string[]>} */
#dependencies = new Map();
/** @type {Map<string, Set<string>>} */
#dependants = new Map();
/** @type {ViteDevServer} */
#server;
/**
*
* @param {ViteDevServer} server
*/
constructor(server) {
this.#server = server;
/** @type {(filename: string) => void} */
const emitChangeEventOnDependants = (filename) => {
const dependants = this.#dependants.get(filename);
dependants?.forEach((dependant) => {
if (fs.existsSync(dependant)) {
log.debug(
`emitting virtual change event for "${dependant}" because dependency "${filename}" changed`,
undefined,
'hmr'
);
server.watcher.emit('change', dependant);
}
});
};
server.watcher.on('change', emitChangeEventOnDependants);
server.watcher.on('unlink', emitChangeEventOnDependants);
}
/**
* @param {string} file
*/
#ensureWatchedFile(file) {
const root = this.#server.config.root;
if (
file &&
// only need to watch if out of root
!file.startsWith(root + '/') &&
// some rollup plugins use null bytes for private resolved Ids
!file.includes('\0') &&
fs.existsSync(file)
) {
// resolve file to normalized system path
this.#server.watcher.add(path.resolve(file));
}
}
clear() {
this.#dependencies.clear();
this.#dependants.clear();
}
/**
*
* @param {SvelteRequest} svelteRequest
* @param {string[]} dependencies
*/
update(svelteRequest, dependencies) {
const id = svelteRequest.normalizedFilename;
const prevDependencies = this.#dependencies.get(id) || [];
this.#dependencies.set(id, dependencies);
const removed = prevDependencies.filter((d) => !dependencies.includes(d));
const added = dependencies.filter((d) => !prevDependencies.includes(d));
added.forEach((d) => {
this.#ensureWatchedFile(d);
if (!this.#dependants.has(d)) {
this.#dependants.set(d, new Set());
}
/** @type {Set<string>} */ (this.#dependants.get(d)).add(svelteRequest.filename);
});
removed.forEach((d) => {
/** @type {Set<string>} */ (this.#dependants.get(d)).delete(svelteRequest.filename);
});
}
}

View File

@@ -0,0 +1,294 @@
/** @import { Code } from '../types/compile.js' */
/** @import { ResolvedOptions } from '../types/options.js' */
/** @import { PluginAPI } from '../types/plugin-api.js' */
/** @import { StatCollection } from '../types/vite-plugin-svelte-stats.js' */
/** @import { CompileOptions } from 'svelte/compiler' */
/** @import { Plugin, ResolvedConfig, Rolldown, UserConfig } from 'vite' */
import fs from 'node:fs/promises';
import path from 'node:path';
import * as svelte from 'svelte/compiler';
import { log } from '../utils/log.js';
import { toRollupError } from '../utils/error.js';
import { SVELTE_IMPORTS } from '../utils/constants.js';
import { isDepExcluded } from 'vitefu';
/**
* @typedef {NonNullable<Rolldown.Plugin>} RollupPlugin
*/
const optimizeSveltePluginName = 'vite-plugin-svelte:optimize';
const optimizeSvelteModulePluginName = 'vite-plugin-svelte:optimize-module';
/**
* @param {PluginAPI} api
* @returns {Plugin}
*/
export function setupOptimizer(api) {
/** @type {ResolvedConfig} */
let viteConfig;
return {
name: 'vite-plugin-svelte:setup-optimizer',
apply: 'serve',
configEnvironment(name, config) {
// fall back to vite behavior when consumer isn't set
const consumer = (config.consumer ?? name === 'client') ? 'client' : 'server';
/** @type {UserConfig['optimizeDeps']} */
const optimizeDeps = {
// Experimental Vite API to allow these extensions to be scanned and prebundled
extensions: ['.svelte']
};
// Add optimizer plugins to prebundle Svelte files.
optimizeDeps.rolldownOptions = {
plugins: [
rolldownOptimizerPlugin(api, name, consumer, true),
rolldownOptimizerPlugin(api, name, consumer, false)
]
};
if (consumer === 'server' && !isDepExcluded('svelte', config.optimizeDeps?.exclude ?? [])) {
optimizeDeps.include = [...SVELTE_IMPORTS];
}
return { optimizeDeps };
},
configResolved(c) {
viteConfig = c;
},
async buildStart() {
if (!api.options.prebundleSvelteLibraries) return;
const changed = await svelteMetadataChanged(viteConfig.cacheDir, api.options);
if (changed) {
// Force Vite to optimize again. Although we mutate the config here, it works because
// Vite's optimizer runs after `buildStart()`.
viteConfig.optimizeDeps.force = true;
}
}
};
}
/**
* @param {import('../types/plugin-api.d.ts').PluginAPI} api
* @param {string} environmentName
* @param {'server'|'client'} consumer
* @param {boolean} components
* @return {Rolldown.Plugin}
*/
function rolldownOptimizerPlugin(api, environmentName, consumer, components) {
const name = components ? optimizeSveltePluginName : optimizeSvelteModulePluginName;
const statsName = components ? 'prebundle library components' : 'prebundle library modules';
const includeRe = components ? /^[^?#]+\.svelte(?:[?#]|$)/ : /^[^?#]+\.svelte\.[jt]s(?:[?#]|$)/;
const generate = consumer === 'server' ? 'server' : 'client';
/** @type {StatCollection | undefined} */
let statsCollection;
/**@type {Rolldown.Plugin}*/
const plugin = {
name
};
plugin.options = (opts) => {
// @ts-expect-error plugins is an array here
const isScanner = opts.plugins.some(
(/** @type {{ name: string; } | undefined} */ p) => p?.name === 'vite:dep-scan:resolve'
);
if (isScanner) {
delete plugin.buildStart;
delete plugin.transform;
delete plugin.buildEnd;
} else {
plugin.transform = {
filter: { id: includeRe },
/**
* @param {string} code
* @param {string} filename
*/
async handler(code, filename) {
try {
if (components) {
const environment =
/**
* Given the order of plugin execution, we can be sure that the environment is already there.
* @type {import("vite").Environment}
*/ (api.options.server?.environments[environmentName]);
return await compileSvelte(
api.options,
{ filename, code },
generate,
environment,
statsCollection
);
}
return await compileSvelteModule(
api.options,
{ filename, code },
generate,
statsCollection
);
} catch (e) {
throw toRollupError(e, api.options);
}
}
};
plugin.buildStart = () => {
statsCollection = api.options.stats?.startCollection(statsName, {
logResult: (c) => c.stats.length > 1
});
};
plugin.buildEnd = () => {
statsCollection?.finish();
};
}
};
return plugin;
}
/**
* @param {ResolvedOptions} options
* @param {{ filename: string, code: string }} input
* @param {'client'|'server'} generate
* @param {import('vite').Environment} environment
* @param {StatCollection} [statsCollection]
* @returns {Promise<Code>}
*/
async function compileSvelte(options, { filename, code }, generate, environment, statsCollection) {
let css = options.compilerOptions.css;
if (css !== 'injected') {
// TODO ideally we'd be able to externalize prebundled styles too, but for now always put them in the js
css = 'injected';
}
/** @type {CompileOptions} */
const compileOptions = {
dev: true, // default to dev: true because prebundling is only used in dev
...options.compilerOptions,
css,
filename,
generate
};
let preprocessed;
if (options.preprocess) {
try {
preprocessed = await svelte.preprocess(code, options.preprocess, { filename });
} catch (e) {
e.message = `Error while preprocessing ${filename}${e.message ? ` - ${e.message}` : ''}`;
throw e;
}
if (preprocessed.map) compileOptions.sourcemap = preprocessed.map;
}
const finalCode = preprocessed ? preprocessed.code : code;
let dynamicCompileOptions;
if (options.dynamicCompileOptions) {
dynamicCompileOptions = await options.dynamicCompileOptions({
filename,
code: finalCode,
compileOptions,
environment
});
}
if (dynamicCompileOptions && log.debug.enabled) {
log.debug(
`dynamic compile options for ${filename}: ${JSON.stringify(dynamicCompileOptions)}`,
undefined,
'compile'
);
}
const finalCompileOptions = dynamicCompileOptions
? {
...compileOptions,
...dynamicCompileOptions
}
: compileOptions;
const endStat = statsCollection?.start(filename);
const compiled = svelte.compile(finalCode, finalCompileOptions);
if (endStat) {
endStat();
}
return {
...compiled.js,
moduleType: 'js'
};
}
/**
* @param {ResolvedOptions} options
* @param {{ filename: string; code: string }} input
* @param {'client'|'server'} generate
* @param {StatCollection} [statsCollection]
* @returns {Promise<Code>}
*/
async function compileSvelteModule(options, { filename, code }, generate, statsCollection) {
const endStat = statsCollection?.start(filename);
const compiled = svelte.compileModule(code, {
dev: options.compilerOptions?.dev ?? true, // default to dev: true because prebundling is only used in dev
filename,
generate
});
if (endStat) {
endStat();
}
return {
...compiled.js,
moduleType: 'js'
};
}
// List of options that changes the prebundling result
/** @type {(keyof ResolvedOptions)[]} */
const PREBUNDLE_SENSITIVE_OPTIONS = [
'compilerOptions',
'configFile',
'experimental',
'extensions',
'preprocess'
];
/**
* stores svelte metadata in cache dir and compares if it has changed
*
* @param {string} cacheDir
* @param {ResolvedOptions} options
* @returns {Promise<boolean>} Whether the Svelte metadata has changed
*/
async function svelteMetadataChanged(cacheDir, options) {
const svelteMetadata = generateSvelteMetadata(options);
const svelteMetadataPath = path.resolve(cacheDir, '_svelte_metadata.json');
const currentSvelteMetadata = JSON.stringify(svelteMetadata, (_, value) => {
// Handle preprocessors
return typeof value === 'function' ? value.toString() : value;
});
/** @type {string | undefined} */
let existingSvelteMetadata;
try {
existingSvelteMetadata = await fs.readFile(svelteMetadataPath, 'utf8');
} catch {
// ignore
}
await fs.mkdir(cacheDir, { recursive: true });
await fs.writeFile(svelteMetadataPath, currentSvelteMetadata);
return currentSvelteMetadata !== existingSvelteMetadata;
}
/**
* @param {ResolvedOptions} options
* @returns {Partial<ResolvedOptions>}
*/
function generateSvelteMetadata(options) {
/** @type {Record<string, any>} */
const metadata = {};
for (const key of PREBUNDLE_SENSITIVE_OPTIONS) {
metadata[key] = options[key];
}
return metadata;
}

View File

@@ -0,0 +1,135 @@
/** @import { VitePreprocessOptions } from './public.js' */
/** @import { Preprocessor as SveltePreprocessor, PreprocessorGroup } from 'svelte/compiler' */
/** @import { InlineConfig, ResolvedConfig } from 'vite' */
import process from 'node:process';
import * as vite from 'vite';
import { mapToRelative, removeLangSuffix } from './utils/sourcemaps.js';
const {
isCSSRequest,
preprocessCSS,
resolveConfig,
//@ts-ignore rolldown types don't exist
transformWithOxc
} = vite;
/**
* @typedef {(code: string, filename: string) => Promise<{ code: string; map?: any; deps?: Set<string> }>} CssTransform
*/
const supportedScriptLangs = ['ts'];
export const lang_sep = '.vite-preprocess';
/**
* @param {VitePreprocessOptions} [opts]
* @returns {PreprocessorGroup}
*/
export function vitePreprocess(opts) {
/** @type {PreprocessorGroup} */
const preprocessor = { name: 'vite-preprocess' };
if (opts?.script === true) {
preprocessor.script = viteScript().script;
}
if (opts?.style !== false) {
const styleOpts = typeof opts?.style == 'object' ? opts?.style : undefined;
preprocessor.style = viteStyle(styleOpts).style;
}
return preprocessor;
}
/**
* @returns {{ script: SveltePreprocessor }}
*/
function viteScript() {
return {
async script({ attributes, content, filename = '' }) {
if (typeof attributes.lang !== 'string' || !supportedScriptLangs.includes(attributes.lang)) {
return;
}
const lang = /** @type {'ts'} */ (attributes.lang);
const { code, map } = await transformWithOxc(content, filename, {
lang,
target: 'esnext',
// oxc strips value imports it considers unused, but in Svelte files
// these imports may be referenced in the template which oxc cannot see.
// onlyRemoveTypeImports tells oxc to only strip type-only imports
// (import type {...}, import { type X }) and preserve all value imports.
typescript: { onlyRemoveTypeImports: true }
});
mapToRelative(map, filename);
return {
code,
map
};
}
};
}
/**
* @param {ResolvedConfig | InlineConfig} config
* @returns {{ style: SveltePreprocessor }}
*/
function viteStyle(config = {}) {
/** @type {Promise<CssTransform> | CssTransform} */
let cssTransform;
const style = /** @type {SveltePreprocessor} */ (
async ({ attributes, content, filename = '' }) => {
const ext = attributes.lang ? `.${attributes.lang}` : '.css';
if (attributes.lang && !isCSSRequest(ext)) return;
if (!cssTransform) {
cssTransform = createCssTransform(style, config).then((t) => (cssTransform = t));
}
const transform = await cssTransform;
const suffix = `${lang_sep}${ext}`;
const moduleId = `${filename}${suffix}`;
const { code, map, deps } = await transform(content, moduleId);
removeLangSuffix(map, suffix);
mapToRelative(map, filename);
const dependencies = deps ? Array.from(deps).filter((d) => !d.endsWith(suffix)) : undefined;
return {
code,
map: map ?? undefined,
dependencies
};
}
);
// @ts-expect-error tag so can be found by v-p-s
style.__resolvedConfig = null;
return { style };
}
/**
* @param {SveltePreprocessor} style
* @param {ResolvedConfig | InlineConfig} config
* @returns {Promise<CssTransform>}
*/
async function createCssTransform(style, config) {
/** @type {ResolvedConfig} */
let resolvedConfig;
// @ts-expect-error special prop added if running in v-p-s
if (style.__resolvedConfig) {
// @ts-expect-error not typed
resolvedConfig = style.__resolvedConfig;
} else if (isResolvedConfig(config)) {
resolvedConfig = config;
} else {
// default to "build" if no NODE_ENV is set to avoid running in dev mode for svelte-check etc.
const useBuild = !process.env.NODE_ENV || process.env.NODE_ENV === 'production';
const command = useBuild ? 'build' : 'serve';
const defaultMode = useBuild ? 'production' : 'development';
resolvedConfig = await resolveConfig(config, command, defaultMode, defaultMode, false);
}
return async (code, filename) => {
return preprocessCSS(code, filename, resolvedConfig);
};
}
/**
* @param {any} config
* @returns {config is ResolvedConfig}
*/
function isResolvedConfig(config) {
return !!config.inlineConfig;
}

View File

@@ -0,0 +1,280 @@
import type { Environment, InlineConfig, ResolvedConfig } from 'vite';
import type { CompileOptions, Warning, PreprocessorGroup } from 'svelte/compiler';
export type Options = Omit<SvelteConfig, 'vitePlugin'> & PluginOptionsInline;
interface PluginOptionsInline extends PluginOptions {
/**
* Path to a svelte config file, either absolute or relative to Vite root
*
* set to `false` to ignore the svelte config file
*
* @see https://vitejs.dev/config/#root
*/
configFile?: string | false;
}
export interface PluginOptions {
/**
* A `picomatch` pattern, or array of patterns, which specifies the files the plugin should
* operate on. By default, all svelte files are included.
*
* @see https://github.com/micromatch/picomatch
*/
include?: Arrayable<string | RegExp>;
/**
* A `picomatch` pattern, or array of patterns, which specifies the files to be ignored by the
* plugin. By default, no files are ignored.
*
* @see https://github.com/micromatch/picomatch
*/
exclude?: Arrayable<string | RegExp>;
/**
* Emit Svelte styles as virtual CSS files for Vite and other plugins to process
*
* @default true
*/
emitCss?: boolean;
/**
* vite-plugin-svelte automatically handles excluding svelte libraries and reinclusion of their dependencies
* in vite.optimizeDeps.
*
* `disableDependencyReinclusion: true` disables all reinclusions
* `disableDependencyReinclusion: ['foo','bar']` disables reinclusions for dependencies of foo and bar
*
* This should be used for hybrid packages that contain both node and browser dependencies, eg Routify
*
* @default false
*/
disableDependencyReinclusion?: boolean | string[];
/**
* Enable support for Vite's dependency optimization to prebundle Svelte libraries.
*
* To disable prebundling for a specific library, add it to `optimizeDeps.exclude`.
*
* @default true for dev, false for build
*/
prebundleSvelteLibraries?: boolean;
/**
* toggle/configure Svelte Inspector
*
* @default unset for dev, always false for build
*/
inspector?: InspectorOptions | boolean;
/**
* A function to update `compilerOptions` before compilation
*
* `data.filename` - The file to be compiled
* `data.code` - The preprocessed Svelte code
* `data.compileOptions` - The current compiler options
* `data.environment` - The current Vite environment
*
* To change part of the compiler options, return an object with the changes you need.
*
* @example
* ```
* ({ filename, compileOptions }) => {
* // Dynamically set runes mode per Svelte file
* if (forceRunesMode(filename) && !compileOptions.runes) {
* return { runes: true };
* }
* }
* ```
*/
dynamicCompileOptions?: (data: {
filename: string;
code: string;
compileOptions: Partial<CompileOptions>;
environment: Environment;
}) => Promise<Partial<CompileOptions> | void> | Partial<CompileOptions> | void;
/**
* These options are considered experimental and breaking changes to them can occur in any release
*/
experimental?: ExperimentalOptions;
}
export interface SvelteConfig {
/**
* A list of file extensions to be compiled by Svelte
*
* @default ['.svelte']
*/
extensions?: string[];
/**
* An array of preprocessors to transform the Svelte source code before compilation
*
* @see https://svelte.dev/docs/svelte/svelte-compiler#PreprocessorGroup
*/
preprocess?: Arrayable<PreprocessorGroup>;
/**
* The options to be passed to the Svelte compiler. A few options are set by default,
* including `dev` and `css`. However, some options are non-configurable, like
* `filename`, `format`, `generate`, and `cssHash` (in dev).
*
* @see https://svelte.dev/docs/svelte/svelte-compiler#CompileOptions
*/
compilerOptions?: Omit<CompileOptions, 'filename' | 'format' | 'generate'>;
/**
* Handles warning emitted from the Svelte compiler
*
* warnings emitted for files in node_modules are logged at the debug level, to see them run
* `DEBUG=vite-plugin-svelte:node-modules-onwarn pnpm build`
*
* @example
* ```
* (warning, defaultHandler) => {
* // ignore some warnings
* if (!['foo','bar'].includes(warning.code)) {
* defaultHandler(warning);
* }
* }
* ```
*
*/
onwarn?: (warning: Warning, defaultHandler: (warning: Warning) => void) => void;
/**
* Options for vite-plugin-svelte
*/
vitePlugin?: PluginOptions;
}
/**
* These options are considered experimental and breaking changes to them can occur in any release
*/
interface ExperimentalOptions {
/**
* send a websocket message with svelte compiler warnings during dev
*
*/
sendWarningsToBrowser?: boolean;
/**
* disable svelte field resolve warnings
*
* @default false
*/
disableSvelteResolveWarnings?: boolean;
compileModule?: CompileModuleOptions;
}
interface CompileModuleOptions {
/**
* infix that must be present in filename
* @default ['.svelte.']
*/
infixes?: string[];
/**
* module extensions
* @default ['.ts','.js']
*/
extensions?: string[];
include?: Arrayable<string | RegExp>;
exclude?: Arrayable<string | RegExp>;
}
type Arrayable<T> = T | T[];
export interface VitePreprocessOptions {
/**
* preprocess script block with vite pipeline.
* Since svelte5 this is not needed for typescript anymore
*
* @default false
*/
script?: boolean;
/**
* preprocess style blocks with vite pipeline
*/
style?: boolean | InlineConfig | ResolvedConfig;
}
export interface InspectorOptions {
/**
* define a key combo to toggle inspector,
* @default 'alt-x'
*
* any number of modifiers `control` `shift` `alt` `meta` followed by zero or one regular key, separated by -
* examples: control-shift, control-o, control-alt-s meta-x control-meta
* Some keys have native behavior (e.g. alt-s opens history menu on firefox).
* To avoid conflicts or accidentally typing into inputs, modifier only combinations are recommended.
*/
toggleKeyCombo?: string;
/**
* define keys to select elements with via keyboard
* @default {parent: 'ArrowUp', child: 'ArrowDown', next: 'ArrowRight', prev: 'ArrowLeft' }
*
* improves accessibility and also helps when you want to select elements that do not have a hoverable surface area
* due to tight wrapping
*
* A note for users of screen-readers:
* If you are using arrow keys to navigate the page itself, change the navKeys to avoid conflicts.
* e.g. navKeys: {parent: 'w', prev: 'a', child: 's', next: 'd'}
*
*
* parent: select closest parent
* child: select first child (or grandchild)
* next: next sibling (or parent if no next sibling exists)
* prev: previous sibling (or parent if no prev sibling exists)
*/
navKeys?: { parent: string; child: string; next: string; prev: string };
/**
* define key to open the editor for the currently selected dom node
*
* @default 'Enter'
*/
openKey?: string;
/**
* define key to open the context menu for the currently selected dom node
*
* @default ' '
*/
openMenuKey?: string;
/**
* define keys to close the inspector
* @default ['Backspace', 'Escape']
*/
escapeKeys?: string[];
/**
* inspector is automatically disabled when releasing toggleKeyCombo after holding it for a longpress
* @default true
*/
holdMode?: boolean;
/**
* when to show the toggle button
* @default 'active'
*/
showToggleButton?: 'always' | 'active' | 'never';
/**
* where to display the toggle button
* @default 'top-right'
*/
toggleButtonPos?: 'top-right' | 'top-left' | 'bottom-right' | 'bottom-left';
/**
* inject custom styles when inspector is active
*/
customStyles?: boolean;
/**
* internal options that are automatically set, not to be set or used by users
* @internal
*/
__internal?: {
// vite base url
base: string;
};
}
// eslint-disable-next-line n/no-missing-import
export * from './index.js';

View File

@@ -0,0 +1,38 @@
import type { Processed, CompileResult } from 'svelte/compiler';
import type { SvelteRequest } from './id.d.ts';
import type { ResolvedOptions } from './options.d.ts';
import type { CustomPluginOptionsVite, Environment, Rollup } from 'vite';
export type CompileSvelte = (
svelteRequest: SvelteRequest,
code: string,
options: Partial<ResolvedOptions>,
environment: Environment,
sourcemap?: Rollup.SourceMap
) => Promise<CompileData>;
export type PreprocessSvelte = (
svelteRequest: SvelteRequest,
code: string,
options: Partial<ResolvedOptions>
) => Promise<Processed | undefined>;
export interface Code {
code: string;
map?: any;
dependencies?: any[];
hasGlobal?: boolean;
moduleType?: string; //vite-8 beta
meta?: {
vite?: CustomPluginOptionsVite;
};
}
export interface CompileData {
filename: string;
normalizedFilename: string;
cssId: string;
lang: string;
compiled: CompileResult;
ssr: boolean | undefined;
}

View File

@@ -0,0 +1,46 @@
export type SvelteQueryTypes = 'style';
export interface RequestQuery {
// our own
svelte?: boolean;
type?: SvelteQueryTypes;
// vite specific
url?: boolean;
raw?: boolean;
direct?: boolean;
inline?: boolean;
}
export interface SvelteRequest {
id: string;
cssId: string;
filename: string;
normalizedFilename: string;
query: RequestQuery;
timestamp: number;
ssr: boolean;
raw: boolean;
}
export interface SvelteModuleRequest {
id: string;
filename: string;
normalizedFilename: string;
query: RequestQuery;
timestamp: number;
ssr: boolean;
}
export type IdParser = (id: string, ssr: boolean, timestamp?: number) => SvelteRequest | undefined;
export type IdFilter = {
id: {
include: Array<string | RegExp>;
exclude: Array<string | RegExp>;
};
};
export type ModuleIdParser = (
id: string,
ssr: boolean,
timestamp?: number
) => SvelteModuleRequest | undefined;

View File

@@ -0,0 +1,24 @@
import type { Warning } from 'svelte/compiler';
export interface LogFn extends SimpleLogFn {
(message: string, payload?: unknown, namespace?: string): void;
enabled: boolean;
once: SimpleLogFn;
}
export interface SimpleLogFn {
(message: string, payload?: unknown, namespace?: string): void;
}
export type SvelteWarningsMessage = {
id: string;
filename: string;
normalizedFilename: string;
timestamp: number;
warnings: Warning[]; // allWarnings filtered by warnings where onwarn did not call the default handler
allWarnings: Warning[]; // includes warnings filtered by onwarn and our extra vite plugin svelte warnings
rawWarnings: Warning[]; // raw compiler output
};
export type LogLevel = 'debug' | 'info' | 'warn' | 'error' | 'silent';

View File

@@ -0,0 +1,21 @@
import type { CompileOptions } from 'svelte/compiler';
import type { ViteDevServer } from 'vite';
// eslint-disable-next-line n/no-missing-import
import { VitePluginSvelteStats } from '../utils/vite-plugin-svelte-stats.js';
import type { Options } from '../public.d.ts';
export interface PreResolvedOptions extends Options {
// these options are non-nullable after resolve
compilerOptions: CompileOptions;
// extra options
root: string;
isBuild: boolean;
isServe: boolean;
isDebug: boolean;
}
export interface ResolvedOptions extends PreResolvedOptions {
isProduction: boolean;
server?: ViteDevServer;
stats?: VitePluginSvelteStats;
}

View File

@@ -0,0 +1,10 @@
import type { ResolvedOptions } from './options.d.ts';
import type { IdFilter, IdParser } from './id.d.ts';
import type { CompileSvelte } from './compile.d.ts';
export interface PluginAPI {
options: ResolvedOptions;
filter: IdFilter;
idParser: IdParser;
compileSvelte: CompileSvelte;
}

View File

@@ -0,0 +1,30 @@
export interface Stat {
file: string;
pkg?: string;
start: number;
end: number;
}
export interface StatCollection {
name: string;
options: CollectionOptions;
start: (file: string) => () => void;
stats: Stat[];
packageStats?: PackageStats[];
collectionStart: number;
duration?: number;
finish: () => Promise<void> | void;
finished: boolean;
}
export interface PackageStats {
pkg: string;
files: number;
duration: number;
}
export interface CollectionOptions {
logInProgress: (collection: StatCollection, now: number) => boolean;
logResult: (collection: StatCollection) => boolean;
}

View File

@@ -0,0 +1,154 @@
/** @import { CompileSvelte } from '../types/compile.js' */
/** @import { StatCollection } from '../types/vite-plugin-svelte-stats.js' */
/** @import { CompileOptions, CompileResult, Warning } from 'svelte/compiler' */
import * as svelte from 'svelte/compiler';
import { log } from './log.js';
import { mapToRelative } from './sourcemaps.js';
import { enhanceCompileError } from './error.js';
// TODO this is a patched version of https://github.com/sveltejs/vite-plugin-svelte/pull/796/files#diff-3bce0b33034aad4b35ca094893671f7e7ddf4d27254ae7b9b0f912027a001b15R10
// which is closer to the other regexes in at least not falling into commented script
// but ideally would be shared exactly with svelte and other tools that use it
const scriptLangRE =
/<!--[^]*?-->|<script\s+(?:[^>]*|(?:[^=>'"/]+=(?:"[^"]*"|'[^']*'|[^>\s]+)\s+)*)lang=(["'])?([^"' >]+)\1[^>]*>/g;
/**
* @returns {CompileSvelte}
*/
export function createCompileSvelte() {
/** @type {StatCollection | undefined} */
let stats;
/** @type {CompileSvelte} */
return async function compileSvelte(svelteRequest, code, options, environment, sourcemap) {
const { filename, normalizedFilename, cssId, ssr, raw } = svelteRequest;
const { emitCss = true } = options;
/** @type {Warning[]} */
const warnings = [];
if (options.stats) {
if (options.isBuild) {
if (!stats) {
// build is either completely ssr or csr, create stats collector on first compile
// it is then finished in the buildEnd hook.
stats = options.stats.startCollection(`${ssr ? 'ssr' : 'dom'} compile`, {
logInProgress: () => false
});
}
} else {
// dev time ssr, it's a ssr request and there are no stats, assume new page load and start collecting
if (ssr && !stats) {
stats = options.stats.startCollection('ssr compile');
}
// stats are being collected but this isn't an ssr request, assume page loaded and stop collecting
if (!ssr && stats) {
stats.finish();
stats = undefined;
}
// TODO find a way to trace dom compile during dev
// problem: we need to call finish at some point but have no way to tell if page load finished
// also they for hmr updates too
}
}
/** @type {CompileOptions} */
const compileOptions = {
...options.compilerOptions,
filename,
generate: ssr ? 'server' : 'client'
};
let finalCode = code;
if (compileOptions.hmr && options.emitCss) {
const closeStylePos = code.lastIndexOf('</style>');
if (closeStylePos > -1) {
// inject rule that forces compile to attach scope class to every node in the template
// this reduces the amount of js hot updates when editing css in .svelte files
finalCode = finalCode.slice(0, closeStylePos) + ' *{}' + finalCode.slice(closeStylePos);
}
}
const dynamicCompileOptions = await options?.dynamicCompileOptions?.({
filename,
code: finalCode,
compileOptions,
environment
});
if (dynamicCompileOptions && log.debug.enabled) {
log.debug(
`dynamic compile options for ${filename}: ${JSON.stringify(dynamicCompileOptions)}`,
undefined,
'compile'
);
}
const finalCompileOptions = dynamicCompileOptions
? {
...compileOptions,
...dynamicCompileOptions
}
: compileOptions;
if (sourcemap) {
finalCompileOptions.sourcemap = sourcemap;
}
const endStat = stats?.start(filename);
/** @type {CompileResult} */
let compiled;
try {
compiled = svelte.compile(finalCode, { ...finalCompileOptions, filename });
// patch output with partial accept until svelte does it
// TODO remove later
if (
options.server?.config.experimental.hmrPartialAccept &&
compiled.js.code.includes('import.meta.hot.accept(')
) {
compiled.js.code = compiled.js.code.replaceAll(
'import.meta.hot.accept(',
'import.meta.hot.acceptExports(["default"],'
);
}
} catch (e) {
enhanceCompileError(e, code, options.preprocess);
throw e;
}
if (endStat) {
endStat();
}
mapToRelative(compiled.js?.map, filename);
mapToRelative(compiled.css?.map, filename);
if (warnings.length) {
if (!compiled.warnings) {
compiled.warnings = [];
}
compiled.warnings.push(...warnings);
}
if (!raw) {
// wire css import and code for hmr
const hasCss = compiled.css?.code?.trim()?.length ?? 0 > 0;
// compiler might not emit css with mode none or it may be empty
if (emitCss && hasCss) {
// TODO properly update sourcemap?
compiled.js.code += `\nimport ${JSON.stringify(cssId)};\n`;
}
}
let lang = 'js';
for (const match of code.matchAll(scriptLangRE)) {
if (match[2]) {
lang = match[2];
break;
}
}
return {
filename,
normalizedFilename,
cssId,
lang,
compiled,
ssr
};
};
}

View File

@@ -0,0 +1,59 @@
import { createRequire } from 'node:module';
/** @type {import('svelte/package.json')} */
const sveltePkg = createRequire(import.meta.url)('svelte/package.json');
// list of svelte runtime dependencies to optimize together with svelte itself
export const SVELTE_RUNTIME_DEPENDENCIES = /** @type {const} */ ([
'clsx' // avoids dev server restart after page load with npm + vite6 (see #1067)
]).filter((dep) => !!sveltePkg.dependencies?.[dep]);
export const SVELTE_IMPORTS = Object.entries(sveltePkg.exports)
.filter(([name, config]) => {
// ignore names
if (name === './package.json') {
return '';
}
// ignore type only
return !(
typeof config === 'object' &&
Object.keys(config).length === 1 &&
'types' in config &&
config.types
);
})
.map(([name]) => {
return name.replace(/^\./, 'svelte');
});
export const SVELTE_DEDUPED_IMPORTS = SVELTE_IMPORTS.map((name) => {
if (name === 'svelte/compiler') {
return '';
}
return name;
}).filter((s) => s.length > 0);
export const SVELTE_CLIENT_IMPORTS = SVELTE_IMPORTS.map((name) => {
// ignore names
if (name === 'svelte/compiler' || name.endsWith('/server') || name.includes('/server/')) {
return '';
}
return name;
}).filter((s) => s.length > 0);
export const SVELTE_EXPORT_CONDITIONS = ['svelte'];
const FAQ_URL = 'https://github.com/sveltejs/vite-plugin-svelte/blob/main/docs/faq.md';
export const FAQ_LINK_MISSING_EXPORTS_CONDITION = `${FAQ_URL}#missing-exports-condition`;
export const FAQ_LINK_CSSHASH = `${FAQ_URL}#why-should-csshash-be-calculated-from-filename-during-dev`;
export const LINK_TRANSFORM_WITH_PLUGIN =
'https://github.com/sveltejs/vite-plugin-svelte/blob/main/docs/advanced-usage.md#transform-svelte-files-with-vite-plugins';
export const DEFAULT_SVELTE_EXT = ['.svelte'];
export const DEFAULT_SVELTE_MODULE_INFIX = ['.svelte.'];
export const DEFAULT_SVELTE_MODULE_EXT = ['.js', '.ts'];
export const SVELTE_VIRTUAL_STYLE_ID_REGEX = /[?&]svelte&type=style&lang.css$/;

View File

@@ -0,0 +1,60 @@
const COMMON_DEPENDENCIES_WITHOUT_SVELTE_FIELD = [
'@lukeed/uuid',
'@playwright/test',
'@sveltejs/kit',
'@sveltejs/package',
'@sveltejs/vite-plugin-svelte',
'autoprefixer',
'cookie',
'dotenv',
'esbuild',
'eslint',
'jest',
'mdsvex',
'playwright',
'postcss',
'prettier',
'svelte',
'svelte2tsx',
'svelte-check',
'svelte-preprocess',
'tslib',
'typescript',
'vite',
'vitest',
'__vite-browser-external' // see https://github.com/sveltejs/vite-plugin-svelte/issues/362
];
const COMMON_PREFIXES_WITHOUT_SVELTE_FIELD = [
'@fontsource/',
'@postcss-plugins/',
'@rollup/',
'@sveltejs/adapter-',
'@types/',
'@typescript-eslint/',
'eslint-',
'jest-',
'postcss-plugin-',
'prettier-plugin-',
'rollup-plugin-',
'vite-plugin-'
];
/**
* Test for common dependency names that tell us it is not a package including a svelte field, eg. eslint + plugins.
*
* This speeds up the find process as we don't have to try and require the package.json for all of them
*
* @param {string} dependency
* @returns {boolean} true if it is a dependency without a svelte field
*/
export function isCommonDepWithoutSvelteField(dependency) {
return (
COMMON_DEPENDENCIES_WITHOUT_SVELTE_FIELD.includes(dependency) ||
COMMON_PREFIXES_WITHOUT_SVELTE_FIELD.some(
(prefix) =>
prefix.startsWith('@')
? dependency.startsWith(prefix)
: dependency.substring(dependency.lastIndexOf('/') + 1).startsWith(prefix) // check prefix omitting @scope/
)
);
}

View File

@@ -0,0 +1,172 @@
/** @import { Options } from '../public.js' */
/** @import { ResolvedOptions } from '../types/options.js' */
/** @import { Warning } from 'svelte/compiler' */
/** @import { Rollup } from 'vite' */
import { buildExtendedLogMessage } from './log.js';
/**
* convert an error thrown by svelte.compile to a RollupError so that vite displays it in a user friendly way
* @param {Warning & Error & {frame?: string}} error a svelte compiler error, which is a mix of Warning and an error
* @param {ResolvedOptions} options
* @returns {Rollup.RollupError} the converted error
*/
export function toRollupError(error, options) {
const { filename, frame, start, code, name, stack } = error;
/** @type {Rollup.RollupError} */
const rollupError = {
name, // needed otherwise sveltekit coalesce_to_error turns it into a string
id: filename,
message: buildExtendedLogMessage(error), // include filename:line:column so that it's clickable
frame: formatFrameForVite(frame),
code,
stack: options.isBuild || options.isDebug || !frame ? stack : ''
};
if (start) {
rollupError.loc = {
line: start.line,
column: start.column,
file: filename
};
}
return rollupError;
}
/**
* convert an error thrown by svelte.compile to an esbuild PartialMessage
* @param {Warning & Error & {frame?: string}} error a svelte compiler error, which is a mix of Warning and an error
* @param {ResolvedOptions} options
* @returns {any} the converted error as esbuild PartialMessage
*
* note: typed any to avoid esbuild devDependency for a single internal type import
*/
export function toESBuildError(error, options) {
const { filename, frame, start, stack } = error;
/** @type any */
const partialMessage = {
text: buildExtendedLogMessage(error)
};
if (start) {
partialMessage.location = {
line: start.line,
column: start.column,
file: filename,
lineText: lineFromFrame(start.line, frame) // needed to get a meaningful error message on cli
};
}
if (options.isBuild || options.isDebug || !frame) {
partialMessage.detail = stack;
}
return partialMessage;
}
/**
* extract line with number from codeframe
*
* @param {number} lineNo
* @param {string} [frame]
* @returns {string}
*/
function lineFromFrame(lineNo, frame) {
if (!frame) {
return '';
}
const lines = frame.split('\n');
const errorLine = lines.find((line) => line.trimStart().startsWith(`${lineNo}: `));
return errorLine ? errorLine.substring(errorLine.indexOf(': ') + 3) : '';
}
/**
* vite error overlay expects a specific format to show frames
* this reformats svelte frame (colon separated, less whitespace)
* to one that vite displays on overlay ( pipe separated, more whitespace)
* e.g.
* ```
* 1: foo
* 2: bar;
* ^
* 3: baz
* ```
* to
* ```
* 1 | foo
* 2 | bar;
* ^
* 3 | baz
* ```
* @see https://github.com/vitejs/vite/blob/96591bf9989529de839ba89958755eafe4c445ae/packages/vite/src/client/overlay.ts#L116
* @param {string} [frame]
* @returns {string}
*/
function formatFrameForVite(frame) {
if (!frame) {
return '';
}
return frame
.split('\n')
.map((line) => (line.match(/^\s+\^/) ? ' ' + line : ' ' + line.replace(':', ' | ')))
.join('\n');
}
/**
*
* @param {string} code the svelte error code
* @see https://github.com/sveltejs/svelte/blob/main/packages/svelte/src/compiler/errors.js
* @returns {boolean}
*/
function couldBeFixedByCssPreprocessor(code) {
return code === 'expected_token' || code === 'unexpected_eof' || code?.startsWith('css_');
}
/**
* @param {Warning & Error} err a svelte compiler error, which is a mix of Warning and an error
* @param {string} originalCode
* @param {Options['preprocess']} [preprocessors]
*/
export function enhanceCompileError(err, originalCode, preprocessors) {
preprocessors = arraify(preprocessors ?? []);
/** @type {string[]} */
const additionalMessages = [];
// Handle incorrect CSS preprocessor usage
if (couldBeFixedByCssPreprocessor(err.code)) {
// Reference from Svelte: https://github.com/sveltejs/svelte/blob/9926347ad9dbdd0f3324d5538e25dcb7f5e442f8/packages/svelte/src/compiler/preprocess/index.js#L257
const styleRe =
/<!--[^]*?-->|<style((?:\s+[^=>'"/]+=(?:"[^"]*"|'[^']*'|[^>\s]+)|\s+[^=>'"/]+)*\s*)(?:\/>|>([\S\s]*?)<\/style>)/g;
let m;
while ((m = styleRe.exec(originalCode))) {
if (m[0]?.startsWith('<!--')) {
continue;
}
// Warn missing lang attribute
if (!m[1]?.includes('lang=')) {
additionalMessages.push('Did you forget to add a lang attribute to your style tag?');
}
// Warn missing style preprocessor
if (
preprocessors.every((p) => p.style == null || p.name === 'inject-scope-everything-rule')
) {
const preprocessorType = m[1]?.match(/lang="(.+?)"/)?.[1] ?? 'style';
additionalMessages.push(
`Did you forget to add a ${preprocessorType} preprocessor? See https://github.com/sveltejs/vite-plugin-svelte/blob/main/docs/preprocess.md for more information.`
);
}
}
}
if (additionalMessages.length) {
err.message += '\n\n- ' + additionalMessages.join('\n- ');
}
return err;
}
/**
* @param {T | T[]} value
* @template T
*/
function arraify(value) {
return Array.isArray(value) ? value : [value];
}

View File

@@ -0,0 +1,277 @@
/** @import { IdFilter, IdParser, ModuleIdParser, RequestQuery, SvelteModuleRequest, SvelteQueryTypes, SvelteRequest } from '../types/id.js' */
/** @import { ResolvedOptions } from '../types/options.js' */
import { normalizePath } from 'vite';
import fs from 'node:fs';
import process from 'node:process';
import { log } from './log.js';
import {
DEFAULT_SVELTE_EXT,
DEFAULT_SVELTE_MODULE_EXT,
DEFAULT_SVELTE_MODULE_INFIX,
SVELTE_VIRTUAL_STYLE_ID_REGEX
} from './constants.js';
import { arraify } from './options.js';
const VITE_FS_PREFIX = '/@fs/';
const IS_WINDOWS = process.platform === 'win32';
const SUPPORTED_COMPILER_OPTIONS = ['generate', 'dev', 'css', 'customElement', 'immutable'];
const TYPES_WITH_COMPILER_OPTIONS = ['style', 'script', 'all'];
/**
* @param {string} id
* @returns {{ filename: string, rawQuery: string }}
*/
function splitId(id) {
const parts = id.split('?', 2);
const filename = parts[0];
const rawQuery = parts[1];
return { filename, rawQuery };
}
/**
* @param {string} id
* @param {string} filename
* @param {string} rawQuery
* @param {string} root
* @param {number} timestamp
* @param {boolean} ssr
* @returns {SvelteRequest | undefined}
*/
function parseToSvelteRequest(id, filename, rawQuery, root, timestamp, ssr) {
const query = parseRequestQuery(rawQuery);
const rawOrDirect = !!(query.raw || query.direct);
if (query.url || (!query.svelte && rawOrDirect)) {
// skip requests with special vite tags
return;
}
const raw = rawOrDirect;
const normalizedFilename = normalize(filename, root);
const cssId = createVirtualImportId(filename, root, 'style');
return {
id,
filename,
normalizedFilename,
cssId,
query,
timestamp,
ssr,
raw
};
}
/**
* @param {string} filename
* @param {string} root
* @param {SvelteQueryTypes} type
* @returns {string}
*/
function createVirtualImportId(filename, root, type) {
const parts = ['svelte', `type=${type}`];
if (type === 'style') {
parts.push('lang.css');
}
if (existsInRoot(filename, root)) {
filename = root + filename;
} else if (filename.startsWith(VITE_FS_PREFIX)) {
filename = IS_WINDOWS
? filename.slice(VITE_FS_PREFIX.length) // remove /@fs/ from /@fs/C:/...
: filename.slice(VITE_FS_PREFIX.length - 1); // remove /@fs from /@fs/home/user
}
// return same virtual id format as vite-plugin-vue eg ...App.svelte?svelte&type=style&lang.css
return `${filename}?${parts.join('&')}`;
}
/**
* @param {string} rawQuery
* @returns {RequestQuery}
*/
function parseRequestQuery(rawQuery) {
const query = Object.fromEntries(new URLSearchParams(rawQuery));
for (const key in query) {
if (query[key] === '') {
// @ts-expect-error not boolean
query[key] = true;
}
}
const compilerOptions = query.compilerOptions;
if (compilerOptions) {
if (!((query.raw || query.direct) && TYPES_WITH_COMPILER_OPTIONS.includes(query.type))) {
throw new Error(
`Invalid compilerOptions in query ${rawQuery}. CompilerOptions are only supported for raw or direct queries with type in "${TYPES_WITH_COMPILER_OPTIONS.join(
', '
)}" e.g. '?svelte&raw&type=script&compilerOptions={"generate":"server","dev":false}`
);
}
try {
const parsed = JSON.parse(compilerOptions);
const invalid = Object.keys(parsed).filter(
(key) => !SUPPORTED_COMPILER_OPTIONS.includes(key)
);
if (invalid.length) {
throw new Error(
`Invalid compilerOptions in query ${rawQuery}: ${invalid.join(
', '
)}. Supported: ${SUPPORTED_COMPILER_OPTIONS.join(', ')}`
);
}
query.compilerOptions = parsed;
} catch (e) {
log.error('failed to parse request query compilerOptions', e);
throw e;
}
}
return /** @type {RequestQuery}*/ query;
}
/**
* posixify and remove root at start
*
* @param {string} filename
* @param {string} normalizedRoot
* @returns {string}
*/
export function normalize(filename, normalizedRoot) {
return stripRoot(normalizePath(filename), normalizedRoot);
}
/**
* @param {string} filename
* @param {string} root
* @returns {boolean}
*/
function existsInRoot(filename, root) {
if (filename.startsWith(VITE_FS_PREFIX)) {
return false; // vite already tagged it as out of root
}
return fs.existsSync(root + filename);
}
/**
* @param {string} normalizedFilename
* @param {string} normalizedRoot
* @returns {string}
*/
function stripRoot(normalizedFilename, normalizedRoot) {
return normalizedFilename.startsWith(normalizedRoot + '/')
? normalizedFilename.slice(normalizedRoot.length)
: normalizedFilename;
}
/**
*
* @param {string} s
* @returns {string}
*/
function escapeRE(s) {
return s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
}
/**
* @param {ResolvedOptions} options
* @returns {IdFilter}
*/
export function buildIdFilter(options) {
const { include = [], exclude = [], extensions = DEFAULT_SVELTE_EXT } = options;
// this regex combines configured extensions and looks for them at the end of the string or directly before first ? or #
const extensionsRE = new RegExp(
`^[^?#]+\\.(?:${extensions
.map((e) => (e.startsWith('.') ? e.slice(1) : e))
.map(escapeRE)
.join('|')})(?:[?#]|$)`
);
return {
id: {
include: [extensionsRE, .../**@type {Array<string|RegExp>}*/ arraify(include)],
exclude: /**@type {Array<string|RegExp>}*/ [
'\0',
SVELTE_VIRTUAL_STYLE_ID_REGEX, // exclude from regular pipeline, we load it in a separate plugin
...arraify(exclude)
]
}
};
}
/**
* @param {ResolvedOptions} options
* @returns {IdParser}
*/
export function buildIdParser(options) {
const normalizedRoot = normalizePath(options.root);
return (id, ssr, timestamp = Date.now()) => {
const { filename, rawQuery } = splitId(id);
return parseToSvelteRequest(id, filename, rawQuery, normalizedRoot, timestamp, ssr);
};
}
/**
* @param {ResolvedOptions} options
* @returns {IdFilter}
*/
export function buildModuleIdFilter(options) {
const {
infixes = DEFAULT_SVELTE_MODULE_INFIX,
include = [],
exclude = [],
extensions = DEFAULT_SVELTE_MODULE_EXT
} = options.experimental?.compileModule ?? {};
// this regex combines configured infixes and extensions
// and looks for them at the end of the string or directly before first ? or #
const infixWithExtRE = new RegExp(
`^[^?#]+(?:${infixes.map(escapeRE).join('|')})(?:[^.\\\\/]+\\.)*(?:${extensions
.map((e) => (e.startsWith('.') ? e.slice(1) : e))
.map(escapeRE)
.join('|')})(?:[?#]|$)`
);
return {
id: {
include: [infixWithExtRE, .../**@type {Array<string|RegExp>}*/ arraify(include)],
exclude: ['\0', .../**@type {Array<string|RegExp>}*/ arraify(exclude)]
}
};
}
/**
* @param {ResolvedOptions} options
* @returns {ModuleIdParser}
*/
export function buildModuleIdParser(options) {
const root = options.root;
const normalizedRoot = normalizePath(root);
return (id, ssr, timestamp = Date.now()) => {
const { filename, rawQuery } = splitId(id);
return parseToSvelteModuleRequest(id, filename, rawQuery, normalizedRoot, timestamp, ssr);
};
}
/**
* @param {string} id
* @param {string} filename
* @param {string} rawQuery
* @param {string} root
* @param {number} timestamp
* @param {boolean} ssr
* @returns {SvelteModuleRequest | undefined}
*/
function parseToSvelteModuleRequest(id, filename, rawQuery, root, timestamp, ssr) {
const query = parseRequestQuery(rawQuery);
if (query.url || query.raw || query.direct) {
// skip requests with special vite tags
return;
}
const normalizedFilename = normalize(filename, root);
return {
id,
filename,
normalizedFilename,
query,
timestamp,
ssr
};
}

View File

@@ -0,0 +1,83 @@
/** @import { Options, SvelteConfig } from '../public.js' */
/** @import { UserConfig } from 'vite' */
import path from 'node:path';
import process from 'node:process';
import fs from 'node:fs';
import { pathToFileURL } from 'node:url';
import { log } from './log.js';
export const knownSvelteConfigNames = ['js', 'ts', 'mjs', 'mts'].map(
(ext) => `svelte.config.${ext}`
);
/**
* @param {string} filePath
* @param {number} timestamp
*/
async function dynamicImportDefault(filePath, timestamp) {
return await import(filePath + '?t=' + timestamp).then((m) => m.default);
}
/**
* @param {UserConfig} [viteConfig]
* @param {Partial<Options>} [inlineOptions]
* @returns {Promise<Partial<SvelteConfig> | undefined>}
*/
export async function loadSvelteConfig(viteConfig, inlineOptions) {
if (inlineOptions?.configFile === false) {
return;
}
const configFile = findConfigToLoad(viteConfig, inlineOptions);
if (configFile) {
try {
const result = await dynamicImportDefault(
pathToFileURL(configFile).href,
fs.statSync(configFile).mtimeMs
);
if (result != null) {
return {
...result,
configFile
};
} else {
throw new Error(`invalid export in ${configFile}`);
}
} catch (e) {
log.error(`failed to import config ${configFile}`, e);
throw e;
}
}
}
/**
* @param {UserConfig | undefined} viteConfig
* @param {Partial<Options> | undefined} inlineOptions
* @returns {string | undefined}
*/
function findConfigToLoad(viteConfig, inlineOptions) {
const root = viteConfig?.root || process.cwd();
if (inlineOptions?.configFile) {
const abolutePath = path.isAbsolute(inlineOptions.configFile)
? inlineOptions.configFile
: path.resolve(root, inlineOptions.configFile);
if (!fs.existsSync(abolutePath)) {
throw new Error(`failed to find svelte config file ${abolutePath}.`);
}
return abolutePath;
} else {
const existingKnownConfigFiles = knownSvelteConfigNames
.map((candidate) => path.resolve(root, candidate))
.filter((file) => fs.existsSync(file));
if (existingKnownConfigFiles.length === 0) {
log.info(`no Svelte config found at ${root} - using default configuration.`);
return;
} else if (existingKnownConfigFiles.length > 1) {
log.warn(
`found more than one svelte config file, using ${existingKnownConfigFiles[0]}. you should only have one!`,
existingKnownConfigFiles
);
}
return existingKnownConfigFiles[0];
}
}

View File

@@ -0,0 +1,261 @@
/** @import { SvelteModuleRequest, SvelteRequest } from '../types/id.js' */
/** @import { LogFn, LogLevel, SimpleLogFn, SvelteWarningsMessage } from '../types/log.js' */
/** @import { ResolvedOptions } from '../types/options.js' */
/** @import { Warning } from 'svelte/compiler' */
/* eslint-disable no-console */
// eslint-disable-next-line n/no-unsupported-features/node-builtins
import { styleText } from 'node:util';
const cyan = (/** @type {string} */ txt) => styleText('cyan', txt);
const yellow = (/** @type {string} */ txt) => styleText('yellow', txt);
const red = (/** @type {string} */ txt) => styleText('red', txt);
import { createDebug, enabled } from 'obug';
/** @type {LogLevel[]} */
const levels = ['debug', 'info', 'warn', 'error', 'silent'];
const prefix = 'vite-plugin-svelte';
/** @type {Record<LogLevel, any>} */
const loggers = {
debug: {
log: createDebug(`${prefix}`),
enabled: false,
isDebug: true
},
info: {
color: cyan,
log: console.log,
enabled: true
},
warn: {
color: yellow,
log: console.warn,
enabled: true
},
error: {
color: red,
log: console.error,
enabled: true
},
silent: {
enabled: false
}
};
/** @type {LogLevel} */
let _level = 'info';
/**
* @param {LogLevel} level
* @returns {void}
*/
function setLevel(level) {
if (level === _level) {
return;
}
const levelIndex = levels.indexOf(level);
if (levelIndex > -1) {
_level = level;
for (let i = 0; i < levels.length; i++) {
loggers[levels[i]].enabled = i >= levelIndex;
}
} else {
_log(loggers.error, `invalid log level: ${level} `);
}
}
/**
* @param {any} logger
* @param {string} message
* @param {any} [payload]
* @param {string} [namespace]
* @returns
*/
function _log(logger, message, payload, namespace) {
if (!logger.enabled) {
return;
}
if (logger.isDebug) {
let log = logger.log;
if (namespace) {
if (!isDebugNamespaceEnabled(namespace)) {
return;
}
log = logger.log.extend(namespace);
}
if (payload !== undefined) {
log(message, payload);
} else {
log(message);
}
} else {
logger.log(
logger.color(
`${new Date().toLocaleTimeString()} [${prefix}${
namespace ? `:${namespace}` : ''
}] ${message}`
)
);
if (payload) {
logger.log(payload);
}
}
}
/**
* @param {LogLevel} level
* @returns {LogFn}
*/
function createLogger(level) {
const logger = loggers[level];
const logFn = /** @type {LogFn} */ (_log.bind(null, logger));
/** @type {Set<string>} */
const logged = new Set();
/** @type {SimpleLogFn} */
const once = function (message, payload, namespace) {
if (!logger.enabled || logged.has(message)) {
return;
}
logged.add(message);
logFn.apply(null, [message, payload, namespace]);
};
Object.defineProperty(logFn, 'enabled', {
get() {
return logger.enabled;
}
});
Object.defineProperty(logFn, 'once', {
get() {
return once;
}
});
return logFn;
}
export const log = {
debug: createLogger('debug'),
info: createLogger('info'),
warn: createLogger('warn'),
error: createLogger('error'),
setLevel
};
/**
* @param {SvelteRequest | SvelteModuleRequest} svelteRequest
* @param {Warning[]} warnings
* @param {ResolvedOptions} options
*/
export function logCompilerWarnings(svelteRequest, warnings, options) {
const { emitCss, onwarn, isBuild } = options;
const sendViaWS = !isBuild && options.experimental?.sendWarningsToBrowser;
let warn = isBuild ? warnBuild : warnDev;
/** @type {Warning[]} */
const handledByDefaultWarn = [];
const allWarnings = warnings?.filter((w) => !ignoreCompilerWarning(w, isBuild, emitCss));
if (sendViaWS) {
const _warn = warn;
/** @type {(w: Warning) => void} */
warn = (w) => {
handledByDefaultWarn.push(w);
_warn(w);
};
}
allWarnings.forEach((warning) => {
if (onwarn) {
onwarn(warning, warn);
} else {
warn(warning);
}
});
if (sendViaWS) {
/** @type {SvelteWarningsMessage} */
const message = {
id: svelteRequest.id,
filename: svelteRequest.filename,
normalizedFilename: svelteRequest.normalizedFilename,
timestamp: svelteRequest.timestamp,
warnings: handledByDefaultWarn, // allWarnings filtered by warnings where onwarn did not call the default handler
allWarnings, // includes warnings filtered by onwarn and our extra vite plugin svelte warnings
rawWarnings: warnings // raw compiler output
};
log.debug(`sending svelte:warnings message for ${svelteRequest.normalizedFilename}`);
options.server?.ws?.send('svelte:warnings', message);
}
}
/**
* @param {Warning} warning
* @param {boolean} isBuild
* @param {boolean} [emitCss]
* @returns {boolean}
*/
function ignoreCompilerWarning(warning, isBuild, emitCss) {
return (
(!emitCss && warning.code === 'css_unused_selector') || // same as rollup-plugin-svelte
(!isBuild && isNoScopableElementWarning(warning))
);
}
/**
*
* @param {Warning} warning
* @returns {boolean}
*/
function isNoScopableElementWarning(warning) {
// see https://github.com/sveltejs/vite-plugin-svelte/issues/153
return warning.code === 'css_unused_selector' && warning.message.includes('"*"');
}
/**
* @param {Warning} w
*/
function warnDev(w) {
if (w.filename?.includes('node_modules')) {
if (isDebugNamespaceEnabled('node-modules-onwarn')) {
log.debug(buildExtendedLogMessage(w), undefined, 'node-modules-onwarn');
}
} else if (log.info.enabled) {
log.info(buildExtendedLogMessage(w));
}
}
/**
* @param {Warning & {frame?: string}} w
*/
function warnBuild(w) {
if (w.filename?.includes('node_modules')) {
if (isDebugNamespaceEnabled('node-modules-onwarn')) {
log.debug(buildExtendedLogMessage(w), w.frame, 'node-modules-onwarn');
}
} else if (log.warn.enabled) {
log.warn(buildExtendedLogMessage(w), w.frame);
}
}
/**
* @param {Warning} w
*/
export function buildExtendedLogMessage(w) {
const parts = [];
if (w.filename) {
parts.push(w.filename);
}
if (w.start) {
parts.push(':', w.start.line, ':', w.start.column);
}
if (w.message) {
if (parts.length > 0) {
parts.push(' ');
}
parts.push(w.message);
}
return parts.join('');
}
/**
* @param {string} namespace
* @returns {boolean}
*/
export function isDebugNamespaceEnabled(namespace) {
return enabled(`${prefix}:${namespace}`);
}

View File

@@ -0,0 +1,654 @@
/** @import { Options, SvelteConfig } from '../public.js' */
/** @import { PreResolvedOptions, ResolvedOptions } from '../types/options.js' */
/** @import { ConfigEnv, EnvironmentOptions, Plugin, ResolvedConfig, UserConfig } from 'vite' */
/** @import { CrawlFrameworkPkgsResult } from 'vitefu' */
import process from 'node:process';
import * as vite from 'vite';
const {
defaultClientMainFields,
defaultServerMainFields,
defaultClientConditions,
defaultServerConditions,
normalizePath,
searchForWorkspaceRoot
} = vite;
import { log } from './log.js';
import { loadSvelteConfig } from './load-svelte-config.js';
import {
DEFAULT_SVELTE_EXT,
FAQ_LINK_CSSHASH,
FAQ_LINK_MISSING_EXPORTS_CONDITION,
LINK_TRANSFORM_WITH_PLUGIN,
SVELTE_EXPORT_CONDITIONS,
SVELTE_CLIENT_IMPORTS,
SVELTE_DEDUPED_IMPORTS,
SVELTE_RUNTIME_DEPENDENCIES
} from './constants.js';
import path from 'node:path';
import deepmerge from 'deepmerge';
import {
crawlFrameworkPkgs,
isDepExcluded,
isDepExternaled,
isDepIncluded,
isDepNoExternaled
} from 'vitefu';
import { isCommonDepWithoutSvelteField } from './dependencies.js';
const allowedPluginOptions = new Set([
'include',
'exclude',
'emitCss',
'disableDependencyReinclusion',
'prebundleSvelteLibraries',
'inspector',
'dynamicCompileOptions',
'experimental'
]);
const knownRootOptions = new Set(['extensions', 'compilerOptions', 'preprocess', 'onwarn']);
const allowedInlineOptions = new Set(['configFile', ...allowedPluginOptions, ...knownRootOptions]);
/**
* @param {Partial<Options>} [inlineOptions]
*/
export function validateInlineOptions(inlineOptions) {
const invalidKeys = Object.keys(inlineOptions || {}).filter(
(key) => !allowedInlineOptions.has(key)
);
const n = invalidKeys.length;
if (n > 0) {
log.warn(
`invalid plugin ${n === 1 ? 'option' : 'options'} ${invalidKeys.map((k) => `\`${k}\``).join(', ')} in inline config`
);
}
}
/**
* @param {Partial<SvelteConfig>} [config]
* @returns {Partial<Options> | undefined}
*/
function convertPluginOptions(config) {
if (!config) {
return;
}
const invalidRootOptions = Object.keys(config).filter((key) => allowedPluginOptions.has(key));
if (invalidRootOptions.length > 0) {
throw new Error(
`Invalid options in svelte config. Move the following options into 'vitePlugin:{...}': ${invalidRootOptions.join(
', '
)}`
);
}
if (!config.vitePlugin) {
return config;
}
const pluginOptions = config.vitePlugin;
const pluginOptionKeys = Object.keys(pluginOptions);
const rootOptionsInPluginOptions = pluginOptionKeys.filter((key) => knownRootOptions.has(key));
if (rootOptionsInPluginOptions.length > 0) {
throw new Error(
`Invalid options in svelte config under vitePlugin:{...}', move them to the config root : ${rootOptionsInPluginOptions.join(
', '
)}`
);
}
const duplicateOptions = pluginOptionKeys.filter((key) =>
Object.prototype.hasOwnProperty.call(config, key)
);
if (duplicateOptions.length > 0) {
throw new Error(
`Invalid duplicate options in svelte config under vitePlugin:{...}', they are defined in root too and must only exist once: ${duplicateOptions.join(
', '
)}`
);
}
const unknownPluginOptions = pluginOptionKeys.filter((key) => !allowedPluginOptions.has(key));
if (unknownPluginOptions.length > 0) {
log.warn(
`ignoring unknown plugin options in svelte config under vitePlugin:{...}: ${unknownPluginOptions.join(
', '
)}`
);
unknownPluginOptions.forEach((unkownOption) => {
// @ts-expect-error not typed
delete pluginOptions[unkownOption];
});
}
/** @type {Options} */
const result = {
...config,
...pluginOptions
};
// @ts-expect-error it exists
delete result.vitePlugin;
return result;
}
/**
* used in config phase, merges the default options, svelte config, and inline options
* @param {Partial<Options> | undefined} inlineOptions
* @param {UserConfig} viteUserConfig
* @param {ConfigEnv} viteEnv
* @returns {Promise<PreResolvedOptions>}
*/
export async function preResolveOptions(inlineOptions, viteUserConfig, viteEnv) {
if (!inlineOptions) {
inlineOptions = {};
}
/** @type {UserConfig} */
const viteConfigWithResolvedRoot = {
...viteUserConfig,
root: resolveViteRoot(viteUserConfig)
};
const isBuild = viteEnv.command === 'build';
/** @type {Partial<PreResolvedOptions>} */
const defaultOptions = {
extensions: DEFAULT_SVELTE_EXT,
emitCss: true,
prebundleSvelteLibraries: !isBuild
};
const svelteConfig = convertPluginOptions(
await loadSvelteConfig(viteConfigWithResolvedRoot, inlineOptions)
);
/** @type {Partial<PreResolvedOptions>} */
const extraOptions = {
root: viteConfigWithResolvedRoot.root,
isBuild,
isServe: viteEnv.command === 'serve',
isDebug: process.env.DEBUG != null
};
const merged = /** @type {PreResolvedOptions} */ (
mergeConfigs(defaultOptions, svelteConfig, inlineOptions, extraOptions)
);
// configFile of svelteConfig contains the absolute path it was loaded from,
// prefer it over the possibly relative inline path
if (svelteConfig?.configFile) {
merged.configFile = svelteConfig.configFile;
}
return merged;
}
/**
* @template T
* @param {(Partial<T> | undefined)[]} configs
* @returns T
*/
function mergeConfigs(...configs) {
/** @type {Partial<T>} */
let result = {};
for (const config of configs.filter((x) => x != null)) {
result = deepmerge(result, /** @type {Partial<T>} */ (config), {
// replace arrays
arrayMerge: (target, source) => source ?? target
});
}
return /** @type {T} */ result;
}
/**
* used in configResolved phase, merges a contextual default config, pre-resolved options, and some preprocessors. also validates the final config.
*
* @param {PreResolvedOptions} preResolveOptions
* @param {ResolvedConfig} viteConfig
* @returns {ResolvedOptions}
*/
export function resolveOptions(preResolveOptions, viteConfig) {
const css = preResolveOptions.emitCss ? 'external' : 'injected';
/** @type {Partial<Options>} */
const defaultOptions = {
compilerOptions: {
css,
dev: !viteConfig.isProduction,
hmr:
!viteConfig.isProduction &&
!preResolveOptions.isBuild &&
viteConfig.server &&
viteConfig.server.hmr !== false
}
};
/** @type {Partial<ResolvedOptions>} */
const extraOptions = {
root: viteConfig.root,
isProduction: viteConfig.isProduction
};
const merged = /** @type {ResolvedOptions}*/ (
mergeConfigs(defaultOptions, preResolveOptions, extraOptions)
);
removeIgnoredOptions(merged);
handleDeprecatedOptions(merged);
logRemovedPluginAPI(viteConfig);
enforceOptionsForHmr(merged, viteConfig);
enforceOptionsForProduction(merged);
return merged;
}
/**
* @param {ResolvedOptions} options
* @param {ResolvedConfig} viteConfig
*/
function enforceOptionsForHmr(options, viteConfig) {
if (options.compilerOptions.hmr && viteConfig.server?.hmr === false) {
log.warn(
'vite config server.hmr is false but compilerOptions.hmr is true. Forcing compilerOptions.hmr to false as it would not work.'
);
options.compilerOptions.hmr = false;
}
if (
options.isServe &&
options.compilerOptions.hmr &&
options.emitCss &&
options.compilerOptions.cssHash
) {
let usesFilename = false;
let usesCss = false;
options.compilerOptions.cssHash({
get filename() {
usesFilename = true;
return 'Foo.svelte';
},
get css() {
usesCss = true;
return '.foo{}';
},
name: 'Foo',
hash: /** @type{(x: string) => string} */ (x) => x
});
if (!usesFilename || usesCss) {
log.warn(
`The custom compilerOptions.cssHash in your svelte config can degrade your DX. See ${FAQ_LINK_CSSHASH} for more information.`
);
}
}
}
/**
* @param {ResolvedOptions} options
*/
function enforceOptionsForProduction(options) {
if (options.isProduction) {
if (options.compilerOptions.hmr) {
log.warn(
'you are building for production but compilerOptions.hmr is true, forcing it to false'
);
options.compilerOptions.hmr = false;
}
if (options.compilerOptions.dev) {
log.warn(
'you are building for production but compilerOptions.dev is true, forcing it to false'
);
options.compilerOptions.dev = false;
}
}
}
/**
* @param {ResolvedOptions} options
*/
function removeIgnoredOptions(options) {
const ignoredCompilerOptions = ['generate', 'format', 'filename'];
const passedCompilerOptions = Object.keys(options.compilerOptions || {});
const passedIgnored = passedCompilerOptions.filter((o) => ignoredCompilerOptions.includes(o));
if (passedIgnored.length) {
log.warn(
`The following Svelte compilerOptions are controlled by vite-plugin-svelte and essential to its functionality. User-specified values are ignored. Please remove them from your configuration: ${passedIgnored.join(
', '
)}`
);
passedIgnored.forEach((ignored) => {
// @ts-expect-error string access
delete options.compilerOptions[ignored];
});
}
}
/**
* @param {ResolvedOptions} options
*/
function handleDeprecatedOptions(options) {
const experimental = /** @type {Record<string, any>} */ (options.experimental);
if (experimental) {
for (const promoted of ['prebundleSvelteLibraries', 'inspector', 'dynamicCompileOptions']) {
if (experimental[promoted]) {
//@ts-expect-error untyped assign
options[promoted] = experimental[promoted];
delete experimental[promoted];
log.warn(
`Option "experimental.${promoted}" is no longer experimental and has moved to "${promoted}". Please update your Svelte or Vite config.`
);
}
}
}
}
/**
* @param {ResolvedConfig} config
*/
function logRemovedPluginAPI(config) {
/** @type {Plugin[]} */
const pluginsWithPreprocessors = config.plugins.filter((p) => p?.api?.sveltePreprocess);
if (pluginsWithPreprocessors.length > 0) {
log.error.once(
`The following vite plugins use the removed 'plugin.api.sveltePreprocess' api: ${pluginsWithPreprocessors
.map((p) => p.name)
.join(', ')}
These preprocessors are no longer added to your svelte config and if your application depends on them it breaks.
Update the plugins or contact their maintainers. See ${LINK_TRANSFORM_WITH_PLUGIN} for more information.
`.replace(/\t+/g, '\t')
);
}
}
/**
* vite passes unresolved `root`option to config hook but we need the resolved value, so do it here
*
* @see https://github.com/sveltejs/vite-plugin-svelte/issues/113
* @see https://github.com/vitejs/vite/blob/43c957de8a99bb326afd732c962f42127b0a4d1e/packages/vite/src/node/config.ts#L293
*
* @param {UserConfig} viteConfig
* @returns {string | undefined}
*/
function resolveViteRoot(viteConfig) {
return normalizePath(viteConfig.root ? path.resolve(viteConfig.root) : process.cwd());
}
/**
* @param {PreResolvedOptions} options
* @param {UserConfig} config
* @returns {Promise<Partial<UserConfig>>}
*/
export async function buildExtraViteConfig(options, config) {
/** @type {Partial<UserConfig>} */
const extraViteConfig = {
resolve: {
dedupe: [...SVELTE_DEDUPED_IMPORTS]
}
// this option is still awaiting a PR in vite to be supported
// see https://github.com/sveltejs/vite-plugin-svelte/issues/60
// knownJsSrcExtensions: options.extensions
};
const extraSvelteConfig = buildExtraConfigForSvelte(config);
const extraDepsConfig = await buildExtraConfigForDependencies(options, config);
// merge extra svelte and deps config, but make sure dep values are not contradicting svelte
extraViteConfig.optimizeDeps = {
include: [
...extraSvelteConfig.optimizeDeps.include,
...extraDepsConfig.optimizeDeps.include.filter(
(dep) => !isDepExcluded(dep, extraSvelteConfig.optimizeDeps.exclude)
)
],
exclude: [
...extraSvelteConfig.optimizeDeps.exclude,
...extraDepsConfig.optimizeDeps.exclude.filter(
(dep) => !isDepIncluded(dep, extraSvelteConfig.optimizeDeps.include)
)
]
};
extraViteConfig.ssr = {
external: [
...extraSvelteConfig.ssr.external,
...extraDepsConfig.ssr.external.filter(
(dep) => !isDepNoExternaled(dep, extraSvelteConfig.ssr.noExternal)
)
],
noExternal: [
...extraSvelteConfig.ssr.noExternal,
...extraDepsConfig.ssr.noExternal.filter(
(dep) => !isDepExternaled(dep, extraSvelteConfig.ssr.external)
)
]
};
// enable hmrPartialAccept if not explicitly disabled
if (config.experimental?.hmrPartialAccept !== false) {
log.debug('enabling "experimental.hmrPartialAccept" in vite config', undefined, 'config');
extraViteConfig.experimental = { hmrPartialAccept: true };
}
validateViteConfig(extraViteConfig, config, options);
return extraViteConfig;
}
/**
* @param {Partial<UserConfig>} extraViteConfig
* @param {UserConfig} config
* @param {PreResolvedOptions} options
*/
function validateViteConfig(extraViteConfig, config, options) {
const { prebundleSvelteLibraries, isBuild } = options;
if (prebundleSvelteLibraries) {
/** @type {(option: 'dev' | 'build' | boolean)=> boolean} */
const isEnabled = (option) => option !== true && option !== (isBuild ? 'build' : 'dev');
/** @type {(name: string, value: 'dev' | 'build' | boolean, recommendation: string)=> void} */
const logWarning = (name, value, recommendation) =>
log.warn.once(
`Incompatible options: \`prebundleSvelteLibraries: true\` and vite \`${name}: ${JSON.stringify(
value
)}\` ${isBuild ? 'during build.' : '.'} ${recommendation}`
);
const viteOptimizeDepsDisabled = config.optimizeDeps?.disabled ?? 'build'; // fall back to vite default
const isOptimizeDepsEnabled = isEnabled(viteOptimizeDepsDisabled);
if (!isBuild && !isOptimizeDepsEnabled) {
logWarning(
'optimizeDeps.disabled',
viteOptimizeDepsDisabled,
'Forcing `optimizeDeps.disabled: "build"`. Disable prebundleSvelteLibraries or update your vite config to enable optimizeDeps during dev.'
);
if (!extraViteConfig.optimizeDeps) {
extraViteConfig.optimizeDeps = {};
}
extraViteConfig.optimizeDeps.disabled = 'build';
} else if (isBuild && isOptimizeDepsEnabled) {
logWarning(
'optimizeDeps.disabled',
viteOptimizeDepsDisabled,
'Disable optimizeDeps or prebundleSvelteLibraries for build if you experience errors.'
);
}
}
if (isBuild) {
// read user config inlineConst value
const inlineConst =
config.build?.rolldownOptions?.optimization?.inlineConst ??
config.build?.rollupOptions?.optimization?.inlineConst;
if (inlineConst === false) {
log.warn(
'Your rolldown config contains `optimization.inlineConst: false`. This can lead to increased bundle size and leaked server code in client build.'
);
}
}
}
/**
* @param {PreResolvedOptions} options
* @param {UserConfig} config
* @returns {Promise<CrawlFrameworkPkgsResult>}
*/
async function buildExtraConfigForDependencies(options, config) {
// extra handling for svelte dependencies in the project
const packagesWithoutSvelteExportsCondition = new Set();
const depsConfig = await crawlFrameworkPkgs({
root: options.root,
workspaceRoot: searchForWorkspaceRoot(options.root),
isBuild: options.isBuild,
viteUserConfig: config,
isFrameworkPkgByJson(pkgJson) {
let hasSvelteCondition = false;
if (typeof pkgJson.exports === 'object') {
// use replacer as a simple way to iterate over nested keys
JSON.stringify(pkgJson.exports, (key, value) => {
if (SVELTE_EXPORT_CONDITIONS.includes(key)) {
hasSvelteCondition = true;
}
return value;
});
}
const hasSvelteField = !!pkgJson.svelte;
if (hasSvelteField && !hasSvelteCondition) {
packagesWithoutSvelteExportsCondition.add(`${pkgJson.name}@${pkgJson.version}`);
}
return hasSvelteCondition || hasSvelteField;
},
isSemiFrameworkPkgByJson(pkgJson) {
return !!pkgJson.dependencies?.svelte || !!pkgJson.peerDependencies?.svelte;
},
isFrameworkPkgByName(pkgName) {
const isNotSveltePackage = isCommonDepWithoutSvelteField(pkgName);
if (isNotSveltePackage) {
return false;
} else {
return undefined;
}
}
});
if (
!options.isBuild &&
!options.experimental?.disableSvelteResolveWarnings &&
packagesWithoutSvelteExportsCondition?.size > 0
) {
log.info.once(
`The following packages have a svelte field in their package.json but no exports condition for svelte.\n\n${[
...packagesWithoutSvelteExportsCondition
].join('\n')}\n\nPlease see ${FAQ_LINK_MISSING_EXPORTS_CONDITION} for details.`
);
}
log.debug('extra config for dependencies generated by vitefu', depsConfig, 'config');
if (options.prebundleSvelteLibraries) {
// prebundling enabled, so we don't need extra dependency excludes
depsConfig.optimizeDeps.exclude = [];
// but keep dependency reinclusions of explicit user excludes
const userExclude = config.optimizeDeps?.exclude;
depsConfig.optimizeDeps.include = !userExclude
? []
: depsConfig.optimizeDeps.include.filter((dep) => {
// reincludes look like this: foo > bar > baz
// in case foo or bar are excluded, we have to retain the reinclude even with prebundling
return (
dep.includes('>') &&
dep
.split('>')
.slice(0, -1)
.some((d) => isDepExcluded(d.trim(), userExclude))
);
});
}
if (options.disableDependencyReinclusion === true) {
depsConfig.optimizeDeps.include = depsConfig.optimizeDeps.include.filter(
(dep) => !dep.includes('>')
);
} else if (Array.isArray(options.disableDependencyReinclusion)) {
const disabledDeps = options.disableDependencyReinclusion;
depsConfig.optimizeDeps.include = depsConfig.optimizeDeps.include.filter((dep) => {
if (!dep.includes('>')) return true;
const trimDep = dep.replace(/\s+/g, '');
return disabledDeps.some((disabled) => trimDep.includes(`${disabled}>`));
});
}
log.debug('post-processed extra config for dependencies', depsConfig, 'config');
return depsConfig;
}
/**
* @param {UserConfig} config
* @returns {UserConfig & { optimizeDeps: { include: string[], exclude:string[] }, ssr: { noExternal:(string|RegExp)[], external: string[] } } }
*/
function buildExtraConfigForSvelte(config) {
// include svelte imports for optimization unless explicitly excluded
/** @type {string[]} */
const include = [];
/** @type {string[]} */
const exclude = [];
if (!isDepExcluded('svelte', config.optimizeDeps?.exclude ?? [])) {
const svelteImportsToInclude = [...SVELTE_CLIENT_IMPORTS];
svelteImportsToInclude.push(...SVELTE_RUNTIME_DEPENDENCIES.map((dep) => `svelte > ${dep}`));
log.debug(
`adding bare svelte packages and runtime dependencies to optimizeDeps.include: ${svelteImportsToInclude.join(', ')} `,
undefined,
'config'
);
include.push(...svelteImportsToInclude);
} else {
log.debug(
'"svelte" is excluded in optimizeDeps.exclude, skipped adding it to include.',
undefined,
'config'
);
}
/** @type {(string | RegExp)[]} */
const noExternal = [];
/** @type {string[]} */
const external = [];
// add svelte to ssr.noExternal unless it is present in ssr.external
// so it is correctly resolving according to the conditions in sveltes exports map
if (!isDepExternaled('svelte', config.ssr?.external ?? [])) {
noExternal.push('svelte', /^svelte\//);
}
// esm-env needs to be bundled by default for the development/production condition
// be properly used by svelte
if (!isDepExternaled('esm-env', config.ssr?.external ?? [])) {
noExternal.push('esm-env');
}
return { optimizeDeps: { include, exclude }, ssr: { noExternal, external } };
}
/**
* Mutates `config` to ensure `resolve.mainFields` is set. If unset, it emulates Vite's default fallback.
* @param {string} name
* @param {EnvironmentOptions} config
* @param {{ isSsrTargetWebworker?: boolean }} opts
*/
export function ensureConfigEnvironmentMainFields(name, config, opts) {
config.resolve ??= {};
if (config.resolve.mainFields == null) {
if (config.consumer === 'client' || name === 'client' || opts.isSsrTargetWebworker) {
config.resolve.mainFields = [...defaultClientMainFields];
} else {
config.resolve.mainFields = [...defaultServerMainFields];
}
}
return true;
}
/**
* Mutates `config` to ensure `resolve.conditions` is set. If unset, it emulates Vite's default fallback.
* @param {string} name
* @param {EnvironmentOptions} config
* @param {{ isSsrTargetWebworker?: boolean }} opts
*/
export function ensureConfigEnvironmentConditions(name, config, opts) {
config.resolve ??= {};
if (config.resolve.conditions == null) {
if (config.consumer === 'client' || name === 'client' || opts.isSsrTargetWebworker) {
config.resolve.conditions = [...defaultClientConditions];
} else {
config.resolve.conditions = [...defaultServerConditions];
}
}
}
/**
* @template T
* @param {T | T[] | null | undefined } value
* @returns {T[]}
*/
export function arraify(value) {
return value == null ? [] : Array.isArray(value) ? value : [value];
}

View File

@@ -0,0 +1,82 @@
import path from 'node:path';
import process from 'node:process';
const IS_WINDOWS = process.platform === 'win32';
/**
* @typedef {{
* file?: string;
* sources?: string[];
* sourceRoot?: string;
* }} SourceMapFileRefs
*/
/**
* convert absolute paths in sourcemap file refs to their relative equivalents to avoid leaking fs info
*
* map is modified in place.
*
* @param {SourceMapFileRefs | undefined} map sourcemap
* @param {string} filename absolute path to file the sourcemap is for
*/
export function mapToRelative(map, filename) {
if (!map) {
return;
}
const sourceRoot = map.sourceRoot;
const dirname = path.dirname(filename);
/** @type {(s: string) => string} */
const toRelative = (s) => {
if (!s) {
return s;
}
/** @type {string} */
let sourcePath;
if (s.startsWith('file:///')) {
// windows has file:///C:/foo and posix has file:///foo, so we have to remove one extra on windows
sourcePath = s.slice(IS_WINDOWS ? 8 : 7);
} else if (sourceRoot) {
const sep = sourceRoot[sourceRoot.length - 1] === '/' || s[0] === '/' ? '' : '/';
sourcePath = `${sourceRoot}${sep}${s}`;
} else {
sourcePath = s;
}
return path.isAbsolute(sourcePath) ? path.relative(dirname, sourcePath) : sourcePath;
};
if (map.file) {
map.file = path.basename(filename);
}
if (map.sources) {
map.sources = map.sources.map(toRelative);
}
if (map.sourceRoot) {
// we have prepended sourceRoot and computed relative paths from it
// remove it here to avoid downstream processing prepending it again
delete map.sourceRoot;
}
}
/**
* vitePreprocess uses an extra lang extension to tell vite about the type of preprocessor to use
* This function removes it afterwards to get back working file refs
*
* map is modified in place.
*
* @param {SourceMapFileRefs | undefined} map the output sourcemap
* @param {string} suffix the suffix to remove
*/
export function removeLangSuffix(map, suffix) {
if (!map) {
return;
}
/** @type {(s:string)=> string} */
const removeSuffix = (s) => (s?.endsWith(suffix) ? s.slice(0, -1 * suffix.length) : s);
if (map.file) {
map.file = removeSuffix(map.file);
}
if (map.sources) {
map.sources = map.sources.map(removeSuffix);
}
}

View File

@@ -0,0 +1,46 @@
import { VERSION } from 'svelte/compiler';
/**
* @type {boolean}
*/
export const isSvelteWithAsync = gte(VERSION, '5.36.0');
/**
* split semver string and convert to number, ignores non digits in tag
* @param {string} semver
* @return {number[]} [major,minor,patch,tag]
*/
function splitToNumbers(semver) {
const num = semver
.replace(/[^\d.-]/g, '')
.split(/[.-]+/, 4)
.map(Number);
while (num.length < 3) {
num.push(0);
}
if (num.length < 4) {
num.push(Infinity);
}
return num;
}
/**
* compare semver versions, tags are compared by their numeric part only
*
* @param {string} a semver version
* @param {string} b semver version
* @return {boolean} true if a is greater or equal to b
*/
export function gte(a, b) {
const aNum = splitToNumbers(a);
const bNum = splitToNumbers(b);
for (let i = 0; i < aNum.length; i++) {
if (aNum[i] < bNum[i]) {
return false;
}
if (aNum[i] > bNum[i]) {
return true;
}
}
return true;
}

View File

@@ -0,0 +1,248 @@
/** @import { CollectionOptions, PackageStats, Stat, StatCollection } from '../types/vite-plugin-svelte-stats.js' */
import { log } from './log.js';
import { performance } from 'node:perf_hooks';
import { normalizePath } from 'vite';
import { findClosestPkgJsonPath } from 'vitefu';
import { readFileSync } from 'node:fs';
import { dirname } from 'node:path';
/** @type {CollectionOptions} */
const defaultCollectionOptions = {
// log after 500ms and more than one file processed
logInProgress: (c, now) => now - c.collectionStart > 500 && c.stats.length > 1,
// always log results
logResult: () => true
};
/**
* @param {number} n
* @returns
*/
function humanDuration(n) {
// 99.9ms 0.10s
return n < 100 ? `${n.toFixed(1)}ms` : `${(n / 1000).toFixed(2)}s`;
}
/**
* @param {PackageStats[]} pkgStats
* @returns {string}
*/
function formatPackageStats(pkgStats) {
const statLines = pkgStats.map((pkgStat) => {
const duration = pkgStat.duration;
const avg = duration / pkgStat.files;
return [pkgStat.pkg, `${pkgStat.files}`, humanDuration(duration), humanDuration(avg)];
});
statLines.unshift(['package', 'files', 'time', 'avg']);
const columnWidths = statLines.reduce(
(widths, row) => {
for (let i = 0; i < row.length; i++) {
const cell = row[i];
if (widths[i] < cell.length) {
widths[i] = cell.length;
}
}
return widths;
},
statLines[0].map(() => 0)
);
const table = statLines
.map((row) =>
row
.map((cell, i) => {
if (i === 0) {
return cell.padEnd(columnWidths[i], ' ');
} else {
return cell.padStart(columnWidths[i], ' ');
}
})
.join('\t')
)
.join('\n');
return table;
}
/**
* @class
*/
export class VitePluginSvelteStats {
/** @type {PackageInfo[]} */
#packageInfos = [];
/** @type {StatCollection[]} */
#collections = [];
/**
* @param {string} name
* @param {Partial<CollectionOptions>} [opts]
* @returns {StatCollection}
*/
startCollection(name, opts) {
const options = {
...defaultCollectionOptions,
...opts
};
/** @type {Stat[]} */
const stats = [];
const collectionStart = performance.now();
const _this = this;
let hasLoggedProgress = false;
/** @type {StatCollection} */
const collection = {
name,
options,
stats,
collectionStart,
finished: false,
start(file) {
if (collection.finished) {
throw new Error('called after finish() has been used');
}
file = normalizePath(file);
const start = performance.now();
/** @type {Stat} */
const stat = { file, start, end: start };
return () => {
const now = performance.now();
stat.end = now;
stats.push(stat);
if (!hasLoggedProgress && options.logInProgress(collection, now)) {
hasLoggedProgress = true;
log.debug(`${name} in progress ...`, undefined, 'stats');
}
};
},
async finish() {
await _this.#finish(collection);
}
};
_this.#collections.push(collection);
return collection;
}
async finishAll() {
await Promise.all(this.#collections.map((c) => c.finish()));
}
/**
* @param {StatCollection} collection
*/
async #finish(collection) {
try {
collection.finished = true;
const now = performance.now();
collection.duration = now - collection.collectionStart;
const logResult = collection.options.logResult(collection);
if (logResult) {
await this.#aggregateStatsResult(collection);
log.debug(
`${collection.name} done.\n${formatPackageStats(
/** @type {PackageStats[]}*/ (collection.packageStats)
)}`,
undefined,
'stats'
);
}
// cut some ties to free it for garbage collection
const index = this.#collections.indexOf(collection);
this.#collections.splice(index, 1);
collection.stats.length = 0;
collection.stats = [];
if (collection.packageStats) {
collection.packageStats.length = 0;
collection.packageStats = [];
}
collection.start = () => () => {};
collection.finish = () => {};
} catch (e) {
// this should not happen, but stats taking also should not break the process
log.debug.once(`failed to finish stats for ${collection.name}\n`, e, 'stats');
}
}
/**
* @param {StatCollection} collection
*/
async #aggregateStatsResult(collection) {
const stats = collection.stats;
for (const stat of stats) {
stat.pkg = (await this.#getPackageInfo(stat.file)).name;
}
// group stats
/** @type {Record<string, PackageStats>} */
const grouped = {};
stats.forEach((stat) => {
const pkg = /** @type {string} */ (stat.pkg);
let group = grouped[pkg];
if (!group) {
group = grouped[pkg] = {
files: 0,
duration: 0,
pkg
};
}
group.files += 1;
group.duration += stat.end - stat.start;
});
const groups = Object.values(grouped);
groups.sort((a, b) => b.duration - a.duration);
collection.packageStats = groups;
}
/**
* @param {string} file
* @returns {Promise<PackageInfo>}
*/
async #getPackageInfo(file) {
let info = this.#packageInfos.find((pi) => file.startsWith(pi.path));
if (!info) {
info = await findPackageInfo(file);
this.#packageInfos.push(info);
}
return info;
}
}
/**
* @typedef {{
* name: string;
* version: string;
* svelte?: string;
* path: string;
* }} PackageInfo
*/
/**
* utility to get some info from the closest package.json with a "name" set
*
* @param {string} file to find info for
* @returns {Promise<PackageInfo>}
*/
async function findPackageInfo(file) {
/** @type {PackageInfo} */
const info = {
name: '$unknown',
version: '0.0.0-unknown',
path: '$unknown'
};
let path = await findClosestPkgJsonPath(file, (pkgPath) => {
const pkg = JSON.parse(readFileSync(pkgPath, 'utf-8'));
if (pkg.name != null) {
info.name = pkg.name;
if (pkg.version != null) {
info.version = pkg.version;
}
info.svelte = pkg.svelte;
return true;
}
return false;
});
// return normalized path with appended '/' so .startsWith works for future file checks
path = normalizePath(dirname(path ?? file)) + '/';
info.path = path;
return info;
}

View File

@@ -0,0 +1,98 @@
/** @import { ResolvedOptions } from '../types/options.js' */
/** @import { FSWatcher } from 'vite' */
import fs from 'node:fs';
import { log } from './log.js';
import { knownSvelteConfigNames } from './load-svelte-config.js';
import path from 'node:path';
/**
* @param {ResolvedOptions} options
* @returns {void}
*/
export function setupWatchers(options) {
const { server, configFile: svelteConfigFile } = options;
if (!server) {
return;
}
const { watcher, ws } = server;
const { root, server: serverConfig } = server.config;
/** @type {(filename: string) => void} */
const triggerViteRestart = (filename) => {
if (serverConfig.middlewareMode) {
// in middlewareMode we can't restart the server automatically
// show the user an overlay instead
const message =
'Svelte config change detected, restart your dev process to apply the changes.';
log.info(message, filename);
ws.send({
type: 'error',
err: { message, stack: '', plugin: 'vite-plugin-svelte', id: filename }
});
} else {
log.info(`svelte config changed: restarting vite server. - file: ${filename}`);
server.restart();
}
};
// collection of watcher listeners by event
/** @type {Record<string, Function[]>} */
const listenerCollection = {
add: [],
change: [],
unlink: []
};
if (svelteConfigFile !== false) {
// configFile false means we ignore the file and external process is responsible
const possibleSvelteConfigs = knownSvelteConfigNames.map((cfg) => path.join(root, cfg));
/** @type {(filename: string) => void} */
const restartOnConfigAdd = (filename) => {
if (possibleSvelteConfigs.includes(filename)) {
triggerViteRestart(filename);
}
};
/** @type {(filename: string) => void} */
const restartOnConfigChange = (filename) => {
if (filename === svelteConfigFile) {
triggerViteRestart(filename);
}
};
if (svelteConfigFile) {
listenerCollection.change.push(restartOnConfigChange);
listenerCollection.unlink.push(restartOnConfigChange);
} else {
listenerCollection.add.push(restartOnConfigAdd);
}
}
Object.entries(listenerCollection).forEach(([evt, listeners]) => {
if (listeners.length > 0) {
watcher.on(evt, (filename) => listeners.forEach((listener) => listener(filename)));
}
});
}
/**
* taken from vite utils
* @param {FSWatcher} watcher
* @param {string | null} file
* @param {string} root
* @returns {void}
*/
export function ensureWatchedFile(watcher, file, root) {
if (
file &&
// only need to watch if out of root
!file.startsWith(root + '/') &&
// some rollup plugins use null bytes for private resolved Ids
!file.includes('\0') &&
fs.existsSync(file)
) {
// resolve file to normalized system path
watcher.add(path.resolve(file));
}
}

View File

@@ -0,0 +1,289 @@
declare module '@sveltejs/vite-plugin-svelte' {
import type { Environment, InlineConfig, ResolvedConfig, Plugin, UserConfig } from 'vite';
import type { CompileOptions, Warning, PreprocessorGroup } from 'svelte/compiler';
export type Options = Omit<SvelteConfig, 'vitePlugin'> & PluginOptionsInline;
interface PluginOptionsInline extends PluginOptions {
/**
* Path to a svelte config file, either absolute or relative to Vite root
*
* set to `false` to ignore the svelte config file
*
* @see https://vitejs.dev/config/#root
*/
configFile?: string | false;
}
export interface PluginOptions {
/**
* A `picomatch` pattern, or array of patterns, which specifies the files the plugin should
* operate on. By default, all svelte files are included.
*
* @see https://github.com/micromatch/picomatch
*/
include?: Arrayable<string | RegExp>;
/**
* A `picomatch` pattern, or array of patterns, which specifies the files to be ignored by the
* plugin. By default, no files are ignored.
*
* @see https://github.com/micromatch/picomatch
*/
exclude?: Arrayable<string | RegExp>;
/**
* Emit Svelte styles as virtual CSS files for Vite and other plugins to process
*
* @default true
*/
emitCss?: boolean;
/**
* vite-plugin-svelte automatically handles excluding svelte libraries and reinclusion of their dependencies
* in vite.optimizeDeps.
*
* `disableDependencyReinclusion: true` disables all reinclusions
* `disableDependencyReinclusion: ['foo','bar']` disables reinclusions for dependencies of foo and bar
*
* This should be used for hybrid packages that contain both node and browser dependencies, eg Routify
*
* @default false
*/
disableDependencyReinclusion?: boolean | string[];
/**
* Enable support for Vite's dependency optimization to prebundle Svelte libraries.
*
* To disable prebundling for a specific library, add it to `optimizeDeps.exclude`.
*
* @default true for dev, false for build
*/
prebundleSvelteLibraries?: boolean;
/**
* toggle/configure Svelte Inspector
*
* @default unset for dev, always false for build
*/
inspector?: InspectorOptions | boolean;
/**
* A function to update `compilerOptions` before compilation
*
* `data.filename` - The file to be compiled
* `data.code` - The preprocessed Svelte code
* `data.compileOptions` - The current compiler options
* `data.environment` - The current Vite environment
*
* To change part of the compiler options, return an object with the changes you need.
*
* @example
* ```
* ({ filename, compileOptions }) => {
* // Dynamically set runes mode per Svelte file
* if (forceRunesMode(filename) && !compileOptions.runes) {
* return { runes: true };
* }
* }
* ```
*/
dynamicCompileOptions?: (data: {
filename: string;
code: string;
compileOptions: Partial<CompileOptions>;
environment: Environment;
}) => Promise<Partial<CompileOptions> | void> | Partial<CompileOptions> | void;
/**
* These options are considered experimental and breaking changes to them can occur in any release
*/
experimental?: ExperimentalOptions;
}
export interface SvelteConfig {
/**
* A list of file extensions to be compiled by Svelte
*
* @default ['.svelte']
*/
extensions?: string[];
/**
* An array of preprocessors to transform the Svelte source code before compilation
*
* @see https://svelte.dev/docs/svelte/svelte-compiler#PreprocessorGroup
*/
preprocess?: Arrayable<PreprocessorGroup>;
/**
* The options to be passed to the Svelte compiler. A few options are set by default,
* including `dev` and `css`. However, some options are non-configurable, like
* `filename`, `format`, `generate`, and `cssHash` (in dev).
*
* @see https://svelte.dev/docs/svelte/svelte-compiler#CompileOptions
*/
compilerOptions?: Omit<CompileOptions, 'filename' | 'format' | 'generate'>;
/**
* Handles warning emitted from the Svelte compiler
*
* warnings emitted for files in node_modules are logged at the debug level, to see them run
* `DEBUG=vite-plugin-svelte:node-modules-onwarn pnpm build`
*
* @example
* ```
* (warning, defaultHandler) => {
* // ignore some warnings
* if (!['foo','bar'].includes(warning.code)) {
* defaultHandler(warning);
* }
* }
* ```
*
*/
onwarn?: (warning: Warning, defaultHandler: (warning: Warning) => void) => void;
/**
* Options for vite-plugin-svelte
*/
vitePlugin?: PluginOptions;
}
/**
* These options are considered experimental and breaking changes to them can occur in any release
*/
interface ExperimentalOptions {
/**
* send a websocket message with svelte compiler warnings during dev
*
*/
sendWarningsToBrowser?: boolean;
/**
* disable svelte field resolve warnings
*
* @default false
*/
disableSvelteResolveWarnings?: boolean;
compileModule?: CompileModuleOptions;
}
interface CompileModuleOptions {
/**
* infix that must be present in filename
* @default ['.svelte.']
*/
infixes?: string[];
/**
* module extensions
* @default ['.ts','.js']
*/
extensions?: string[];
include?: Arrayable<string | RegExp>;
exclude?: Arrayable<string | RegExp>;
}
type Arrayable<T> = T | T[];
export interface VitePreprocessOptions {
/**
* preprocess script block with vite pipeline.
* Since svelte5 this is not needed for typescript anymore
*
* @default false
*/
script?: boolean;
/**
* preprocess style blocks with vite pipeline
*/
style?: boolean | InlineConfig | ResolvedConfig;
}
export interface InspectorOptions {
/**
* define a key combo to toggle inspector,
* @default 'alt-x'
*
* any number of modifiers `control` `shift` `alt` `meta` followed by zero or one regular key, separated by -
* examples: control-shift, control-o, control-alt-s meta-x control-meta
* Some keys have native behavior (e.g. alt-s opens history menu on firefox).
* To avoid conflicts or accidentally typing into inputs, modifier only combinations are recommended.
*/
toggleKeyCombo?: string;
/**
* define keys to select elements with via keyboard
* @default {parent: 'ArrowUp', child: 'ArrowDown', next: 'ArrowRight', prev: 'ArrowLeft' }
*
* improves accessibility and also helps when you want to select elements that do not have a hoverable surface area
* due to tight wrapping
*
* A note for users of screen-readers:
* If you are using arrow keys to navigate the page itself, change the navKeys to avoid conflicts.
* e.g. navKeys: {parent: 'w', prev: 'a', child: 's', next: 'd'}
*
*
* parent: select closest parent
* child: select first child (or grandchild)
* next: next sibling (or parent if no next sibling exists)
* prev: previous sibling (or parent if no prev sibling exists)
*/
navKeys?: { parent: string; child: string; next: string; prev: string };
/**
* define key to open the editor for the currently selected dom node
*
* @default 'Enter'
*/
openKey?: string;
/**
* define key to open the context menu for the currently selected dom node
*
* @default ' '
*/
openMenuKey?: string;
/**
* define keys to close the inspector
* @default ['Backspace', 'Escape']
*/
escapeKeys?: string[];
/**
* inspector is automatically disabled when releasing toggleKeyCombo after holding it for a longpress
* @default true
*/
holdMode?: boolean;
/**
* when to show the toggle button
* @default 'active'
*/
showToggleButton?: 'always' | 'active' | 'never';
/**
* where to display the toggle button
* @default 'top-right'
*/
toggleButtonPos?: 'top-right' | 'top-left' | 'bottom-right' | 'bottom-left';
/**
* inject custom styles when inspector is active
*/
customStyles?: boolean;
/**
* internal options that are automatically set, not to be set or used by users
* */
__internal?: {
// vite base url
base: string;
};
}
/**
* returns a list of plugins to handle svelte files
* plugins are named `vite-plugin-svelte:<task>`
*
* */
export function svelte(inlineOptions?: Partial<Options>): Plugin[];
export function vitePreprocess(opts?: VitePreprocessOptions): PreprocessorGroup;
export function loadSvelteConfig(viteConfig?: UserConfig, inlineOptions?: Partial<Options>): Promise<Partial<SvelteConfig> | undefined>;
export {};
}
//# sourceMappingURL=index.d.ts.map

View File

@@ -0,0 +1,32 @@
{
"version": 3,
"file": "index.d.ts",
"names": [
"Options",
"PluginOptionsInline",
"PluginOptions",
"SvelteConfig",
"ExperimentalOptions",
"CompileModuleOptions",
"Arrayable",
"VitePreprocessOptions",
"InspectorOptions",
"svelte",
"vitePreprocess",
"loadSvelteConfig"
],
"sources": [
"../src/public.d.ts",
"../src/index.js",
"../src/preprocess.js",
"../src/utils/load-svelte-config.js"
],
"sourcesContent": [
null,
null,
null,
null
],
"mappings": ";;;aAGYA,OAAOA;;WAETC,mBAAmBA;;;;;;;;;;;kBAWZC,aAAaA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;kBAkFbC,YAAYA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;WAiDnBC,mBAAmBA;;;;;;;;;;;;;;;;WAgBnBC,oBAAoBA;;;;;;;;;;;;;;;MAezBC,SAASA;;kBAEGC,qBAAqBA;;;;;;;;;;;;;;kBAcrBC,gBAAgBA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBC3KjBC,MAAMA;iBCGNC,cAAcA;iBCARC,gBAAgBA",
"ignoreList": []
}