758 lines
26 KiB
Plaintext
758 lines
26 KiB
Plaintext
var __create = Object.create;
|
|
var __defProp = Object.defineProperty;
|
|
var __getProtoOf = Object.getPrototypeOf;
|
|
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
var __getOwnPropSymbols = Object.getOwnPropertySymbols;
|
|
var __propIsEnum = Object.prototype.propertyIsEnumerable;
|
|
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, {enumerable: true, configurable: true, writable: true, value}) : obj[key] = value;
|
|
var __assign = (a, b) => {
|
|
for (var prop in b || (b = {}))
|
|
if (__hasOwnProp.call(b, prop))
|
|
__defNormalProp(a, prop, b[prop]);
|
|
if (__getOwnPropSymbols)
|
|
for (var prop of __getOwnPropSymbols(b)) {
|
|
if (__propIsEnum.call(b, prop))
|
|
__defNormalProp(a, prop, b[prop]);
|
|
}
|
|
return a;
|
|
};
|
|
var __markAsModule = (target) => __defProp(target, "__esModule", {value: true});
|
|
var __export = (target, all) => {
|
|
for (var name in all)
|
|
__defProp(target, name, {get: all[name], enumerable: true});
|
|
};
|
|
var __exportStar = (target, module2, desc) => {
|
|
if (module2 && typeof module2 === "object" || typeof module2 === "function") {
|
|
for (let key of __getOwnPropNames(module2))
|
|
if (!__hasOwnProp.call(target, key) && key !== "default")
|
|
__defProp(target, key, {get: () => module2[key], enumerable: !(desc = __getOwnPropDesc(module2, key)) || desc.enumerable});
|
|
}
|
|
return target;
|
|
};
|
|
var __toModule = (module2) => {
|
|
return __exportStar(__markAsModule(__defProp(module2 != null ? __create(__getProtoOf(module2)) : {}, "default", module2 && module2.__esModule && "default" in module2 ? {get: () => module2.default, enumerable: true} : {value: module2, enumerable: true})), module2);
|
|
};
|
|
|
|
// src/index.ts
|
|
__markAsModule(exports);
|
|
__export(exports, {
|
|
default: () => vitePluginSvelte
|
|
});
|
|
var path2 = __toModule(require("path"));
|
|
var relative = __toModule(require("require-relative"));
|
|
|
|
// src/utils/log.ts
|
|
var import_chalk = __toModule(require("chalk"));
|
|
var import_debug = __toModule(require("debug"));
|
|
var levels = ["debug", "info", "warn", "error", "silent"];
|
|
var prefix = "vite-plugin-svelte";
|
|
var loggers = {
|
|
debug: {
|
|
log: (0, import_debug.default)(`vite:${prefix}`),
|
|
enabled: false,
|
|
isDebug: true
|
|
},
|
|
info: {
|
|
color: import_chalk.default.cyan,
|
|
log: console.log,
|
|
enabled: true
|
|
},
|
|
warn: {
|
|
color: import_chalk.default.yellow,
|
|
log: console.warn,
|
|
enabled: true
|
|
},
|
|
error: {
|
|
color: import_chalk.default.red,
|
|
log: console.error,
|
|
enabled: true
|
|
},
|
|
silent: {
|
|
enabled: false
|
|
}
|
|
};
|
|
var _level = "info";
|
|
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} `);
|
|
}
|
|
}
|
|
var _viteLogOverwriteProtection = false;
|
|
function setViteLogOverwriteProtection(viteLogOverwriteProtection) {
|
|
_viteLogOverwriteProtection = viteLogOverwriteProtection;
|
|
}
|
|
function _log(logger, message, payload) {
|
|
if (!logger.enabled) {
|
|
return;
|
|
}
|
|
if (logger.isDebug) {
|
|
payload !== void 0 ? logger.log(message, payload) : logger.log(message);
|
|
} else {
|
|
logger.log(logger.color(`[${prefix}] ${message}`));
|
|
if (payload) {
|
|
logger.log(payload);
|
|
}
|
|
}
|
|
if (_viteLogOverwriteProtection) {
|
|
logger.log("");
|
|
}
|
|
}
|
|
function createLogger(level) {
|
|
const logger = loggers[level];
|
|
const logFn = _log.bind(null, logger);
|
|
Object.defineProperty(logFn, "enabled", {
|
|
get() {
|
|
return logger.enabled;
|
|
}
|
|
});
|
|
return logFn;
|
|
}
|
|
var log = {
|
|
debug: createLogger("debug"),
|
|
info: createLogger("info"),
|
|
warn: createLogger("warn"),
|
|
error: createLogger("error"),
|
|
setLevel,
|
|
setViteLogOverwriteProtection
|
|
};
|
|
|
|
// src/handleHotUpdate.ts
|
|
async function handleHotUpdate(compileSvelte, ctx, svelteRequest, cache) {
|
|
const {read, server} = ctx;
|
|
const cachedCompileData = cache.getCompileData(svelteRequest, false);
|
|
if (!cachedCompileData) {
|
|
log.debug(`handleHotUpdate first call ${svelteRequest.id}`);
|
|
return;
|
|
}
|
|
const content = await read();
|
|
const compileData = await compileSvelte(svelteRequest, content, cachedCompileData.options);
|
|
cache.setCompileData(compileData);
|
|
const affectedModules = new Set();
|
|
const cssModule = server.moduleGraph.getModuleById(svelteRequest.cssId);
|
|
const mainModule = server.moduleGraph.getModuleById(svelteRequest.id);
|
|
if (cssModule && cssChanged(cachedCompileData, compileData)) {
|
|
log.debug("handleHotUpdate css changed");
|
|
affectedModules.add(cssModule);
|
|
}
|
|
if (mainModule && jsChanged(cachedCompileData, compileData)) {
|
|
log.debug("handleHotUpdate js changed");
|
|
affectedModules.add(mainModule);
|
|
}
|
|
const result = [...affectedModules].filter(Boolean);
|
|
log.debug(`handleHotUpdate result for ${svelteRequest.id}`, result);
|
|
const ssrModulesToInvalidate = result.filter((m) => !!m.ssrTransformResult);
|
|
if (ssrModulesToInvalidate.length > 0) {
|
|
log.debug(`invalidating modules ${ssrModulesToInvalidate.map((m) => m.id).join(", ")}`);
|
|
ssrModulesToInvalidate.forEach((moduleNode) => server.moduleGraph.invalidateModule(moduleNode));
|
|
}
|
|
return result;
|
|
}
|
|
function cssChanged(prev, next) {
|
|
var _a, _b;
|
|
return !isCodeEqual((_a = prev.compiled.css) == null ? void 0 : _a.code, (_b = next.compiled.css) == null ? void 0 : _b.code);
|
|
}
|
|
function jsChanged(prev, next) {
|
|
const prevJs = prev.compiled.js.code;
|
|
const nextJs = next.compiled.js.code;
|
|
const isStrictEqual = isCodeEqual(prevJs, nextJs);
|
|
if (isStrictEqual) {
|
|
return false;
|
|
}
|
|
const isLooseEqual = isCodeEqual(normalizeJsCode(prevJs), normalizeJsCode(nextJs));
|
|
if (!isStrictEqual && isLooseEqual) {
|
|
log.warn(`ignoring compiler output js change for ${next.filename} as it is equal to previous output after normalization`);
|
|
}
|
|
return !isLooseEqual;
|
|
}
|
|
function isCodeEqual(prev, next) {
|
|
if (!prev && !next) {
|
|
return true;
|
|
}
|
|
if (!prev && next || prev && !next) {
|
|
return false;
|
|
}
|
|
return prev === next;
|
|
}
|
|
function normalizeJsCode(code) {
|
|
if (!code) {
|
|
return code;
|
|
}
|
|
return code.replace(/\s*\badd_location\s*\([^)]*\)\s*;?/g, "");
|
|
}
|
|
|
|
// src/utils/compile.ts
|
|
var import_compiler = __toModule(require("svelte/compiler"));
|
|
var import_svelte_hmr = __toModule(require("svelte-hmr"));
|
|
|
|
// src/utils/hash.ts
|
|
var crypto = __toModule(require("crypto"));
|
|
var hashes = Object.create(null);
|
|
var hash_length = 12;
|
|
function safeBase64Hash(input) {
|
|
if (hashes[input]) {
|
|
return hashes[input];
|
|
}
|
|
const md5 = crypto.createHash("md5");
|
|
md5.update(input);
|
|
const hash = toSafe(md5.digest("base64")).substr(0, hash_length);
|
|
hashes[input] = hash;
|
|
return hash;
|
|
}
|
|
var replacements = {
|
|
"+": "-",
|
|
"/": "_",
|
|
"=": ""
|
|
};
|
|
var replaceRE = new RegExp(`[${Object.keys(replacements).join("")}]`, "g");
|
|
function toSafe(base64) {
|
|
return base64.replace(replaceRE, (x) => replacements[x]);
|
|
}
|
|
|
|
// src/utils/preprocess.ts
|
|
var supportedStyleLangs = ["css", "less", "sass", "scss", "styl", "stylus", "postcss"];
|
|
var supportedScriptLangs = ["ts"];
|
|
function createPreprocessorFromVitePlugin(config, options, pluginName, supportedLangs) {
|
|
const plugin = config.plugins.find((p) => p.name === pluginName);
|
|
if (!plugin) {
|
|
throw new Error(`failed to find plugin ${pluginName}`);
|
|
}
|
|
if (!plugin.transform) {
|
|
throw new Error(`plugin ${pluginName} has no transform`);
|
|
}
|
|
const pluginTransform = plugin.transform.bind(null);
|
|
return async ({attributes, content, filename}) => {
|
|
var _a, _b, _c, _d;
|
|
const lang = attributes.lang;
|
|
if (!supportedLangs.includes(lang)) {
|
|
return {code: content};
|
|
}
|
|
const moduleId = `${filename}.${lang}`;
|
|
const moduleGraph = (_a = options.server) == null ? void 0 : _a.moduleGraph;
|
|
if (moduleGraph && !moduleGraph.getModuleById(moduleId)) {
|
|
await moduleGraph.ensureEntryFromUrl(moduleId);
|
|
}
|
|
const transformResult = await pluginTransform(content, moduleId);
|
|
const hasMap = !!((_b = transformResult.map) == null ? void 0 : _b.mappings);
|
|
if (((_d = (_c = transformResult.map) == null ? void 0 : _c.sources) == null ? void 0 : _d[0]) === moduleId) {
|
|
transformResult.map.sources[0] = filename;
|
|
}
|
|
return {
|
|
code: transformResult.code,
|
|
map: hasMap ? transformResult.map : null,
|
|
dependencies: transformResult.deps
|
|
};
|
|
};
|
|
}
|
|
function createVitePreprocessorGroup(config, options) {
|
|
return {
|
|
script: createPreprocessorFromVitePlugin(config, options, "vite:esbuild", supportedScriptLangs),
|
|
style: createPreprocessorFromVitePlugin(config, options, "vite:css", supportedStyleLangs)
|
|
};
|
|
}
|
|
function createInjectScopeEverythingRulePreprocessorGroup() {
|
|
return {
|
|
style({content}) {
|
|
return {
|
|
code: `${content} *{}`
|
|
};
|
|
}
|
|
};
|
|
}
|
|
function buildExtraPreprocessors(options, config) {
|
|
const extraPreprocessors = [];
|
|
if (options.useVitePreprocess) {
|
|
log.debug("adding vite preprocessor");
|
|
extraPreprocessors.push(createVitePreprocessorGroup(config, options));
|
|
}
|
|
const pluginsWithPreprocessors = config.plugins.filter((p) => p == null ? void 0 : p.sveltePreprocess);
|
|
if (pluginsWithPreprocessors.length > 0) {
|
|
log.debug(`adding preprocessors from other vite plugins: ${pluginsWithPreprocessors.map((p) => p.name).join(", ")}`);
|
|
extraPreprocessors.push(...pluginsWithPreprocessors.map((p) => p.sveltePreprocess));
|
|
}
|
|
if (options.hot && !options.disableCssHmr) {
|
|
extraPreprocessors.push(createInjectScopeEverythingRulePreprocessorGroup());
|
|
}
|
|
return extraPreprocessors;
|
|
}
|
|
|
|
// src/utils/compile.ts
|
|
var _createCompileSvelte = (makeHot, extraPreprocessors) => async function compileSvelte(svelteRequest, code, options) {
|
|
const {filename, normalizedFilename, cssId, ssr} = svelteRequest;
|
|
const {onwarn, emitCss = true} = options;
|
|
const dependencies = [];
|
|
const finalCompilerOptions = __assign(__assign({}, options.compilerOptions), {
|
|
filename,
|
|
generate: ssr ? "ssr" : "dom",
|
|
css: !emitCss,
|
|
hydratable: true
|
|
});
|
|
if (options.hot) {
|
|
const hash = `s-${safeBase64Hash(normalizedFilename)}`;
|
|
log.debug(`setting cssHash ${hash} for ${normalizedFilename}`);
|
|
finalCompilerOptions.cssHash = () => hash;
|
|
}
|
|
let preprocessed;
|
|
const preprocessors = [];
|
|
if (options.preprocess) {
|
|
if (Array.isArray(options.preprocess)) {
|
|
preprocessors.push(...options.preprocess);
|
|
} else {
|
|
preprocessors.push(options.preprocess);
|
|
}
|
|
}
|
|
preprocessors.push(...extraPreprocessors || []);
|
|
if (preprocessors.length > 0) {
|
|
preprocessed = await (0, import_compiler.preprocess)(code, preprocessors, {filename});
|
|
if (preprocessed.dependencies)
|
|
dependencies.push(...preprocessed.dependencies);
|
|
if (preprocessed.map)
|
|
finalCompilerOptions.sourcemap = preprocessed.map;
|
|
}
|
|
const compiled = (0, import_compiler.compile)(preprocessed ? preprocessed.code : code, finalCompilerOptions);
|
|
(compiled.warnings || []).forEach((warning) => {
|
|
if (!emitCss && warning.code === "css-unused-selector")
|
|
return;
|
|
if (onwarn)
|
|
onwarn(warning);
|
|
});
|
|
if (emitCss && compiled.css.code) {
|
|
compiled.js.code += `
|
|
import ${JSON.stringify(cssId)};
|
|
`;
|
|
}
|
|
if (!ssr && makeHot) {
|
|
compiled.js.code = makeHot({
|
|
id: filename,
|
|
compiledCode: compiled.js.code,
|
|
hotOptions: options.hot,
|
|
compiled,
|
|
originalCode: code,
|
|
compileOptions: finalCompilerOptions
|
|
});
|
|
}
|
|
compiled.js.dependencies = dependencies;
|
|
const result = {
|
|
filename,
|
|
normalizedFilename,
|
|
cssId,
|
|
code,
|
|
preprocessed,
|
|
compiled,
|
|
compilerOptions: finalCompilerOptions,
|
|
options,
|
|
ssr
|
|
};
|
|
return result;
|
|
};
|
|
function buildMakeHot(options) {
|
|
var _a, _b;
|
|
const needsMakeHot = options.hot !== false && options.isServe && !options.isProduction;
|
|
if (needsMakeHot) {
|
|
const hotApi = (_a = options == null ? void 0 : options.hot) == null ? void 0 : _a.hotApi;
|
|
const adapter = (_b = options == null ? void 0 : options.hot) == null ? void 0 : _b.adapter;
|
|
return (0, import_svelte_hmr.createMakeHot)({
|
|
walk: import_compiler.walk,
|
|
hotApi,
|
|
adapter,
|
|
hotOptions: __assign({noOverlay: true}, options.hot)
|
|
});
|
|
}
|
|
}
|
|
function createCompileSvelte(options, config) {
|
|
const makeHot = buildMakeHot(options);
|
|
const extraPreprocessors = buildExtraPreprocessors(options, config);
|
|
return _createCompileSvelte(makeHot, extraPreprocessors);
|
|
}
|
|
|
|
// src/utils/id.ts
|
|
var import_querystring = __toModule(require("querystring"));
|
|
var import_pluginutils = __toModule(require("@rollup/pluginutils"));
|
|
var import_vite = __toModule(require("vite"));
|
|
var fs = __toModule(require("fs"));
|
|
var VITE_FS_PREFIX = "/@fs/";
|
|
var IS_WINDOWS = process.platform === "win32";
|
|
function splitId(id) {
|
|
const parts = id.split(`?`, 2);
|
|
const filename = parts[0];
|
|
const rawQuery = parts[1];
|
|
return {filename, rawQuery};
|
|
}
|
|
function parseToSvelteRequest(id, filename, rawQuery, root, timestamp, ssr) {
|
|
const query = import_querystring.default.parse(rawQuery);
|
|
if (query.svelte != null) {
|
|
query.svelte = true;
|
|
}
|
|
const normalizedFilename = normalize(filename, root);
|
|
const cssId = createVirtualImportId(filename, root, "style");
|
|
return {
|
|
id,
|
|
filename,
|
|
normalizedFilename,
|
|
cssId,
|
|
query,
|
|
timestamp,
|
|
ssr
|
|
};
|
|
}
|
|
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) : filename.slice(VITE_FS_PREFIX.length - 1);
|
|
}
|
|
return `${filename}?${parts.join("&")}`;
|
|
}
|
|
function normalize(filename, normalizedRoot) {
|
|
return stripRoot((0, import_vite.normalizePath)(filename), normalizedRoot);
|
|
}
|
|
function existsInRoot(filename, root) {
|
|
if (filename.startsWith(VITE_FS_PREFIX)) {
|
|
return false;
|
|
}
|
|
return fs.existsSync(root + filename);
|
|
}
|
|
function stripRoot(normalizedFilename, normalizedRoot) {
|
|
return normalizedFilename.startsWith(normalizedRoot + "/") ? normalizedFilename.slice(normalizedRoot.length) : normalizedFilename;
|
|
}
|
|
function buildFilter(include, exclude, extensions) {
|
|
const rollupFilter = (0, import_pluginutils.createFilter)(include, exclude);
|
|
return (filename) => rollupFilter(filename) && extensions.some((ext) => filename.endsWith(ext));
|
|
}
|
|
function buildIdParser(options) {
|
|
const {include, exclude, extensions, root} = options;
|
|
const normalizedRoot = (0, import_vite.normalizePath)(root);
|
|
const filter = buildFilter(include, exclude, extensions);
|
|
return (id, ssr, timestamp = Date.now()) => {
|
|
const {filename, rawQuery} = splitId(id);
|
|
if (filter(filename)) {
|
|
return parseToSvelteRequest(id, filename, rawQuery, normalizedRoot, timestamp, ssr);
|
|
}
|
|
};
|
|
}
|
|
|
|
// src/utils/loadSvelteConfig.ts
|
|
var import_path = __toModule(require("path"));
|
|
var import_fs = __toModule(require("fs"));
|
|
var knownSvelteConfigNames = ["svelte.config.js", "svelte.config.cjs"];
|
|
function loadSvelteConfig(root = process.cwd()) {
|
|
const foundConfigs = knownSvelteConfigNames.map((candidate) => import_path.default.resolve(root, candidate)).filter((file) => import_fs.default.existsSync(file));
|
|
if (foundConfigs.length === 0) {
|
|
log.debug(`no svelte config found at ${root}`);
|
|
return;
|
|
} else if (foundConfigs.length > 1) {
|
|
log.warn(`found more than one svelte config file, using ${foundConfigs[0]}. you should only have one!`, foundConfigs);
|
|
}
|
|
try {
|
|
const config = require(foundConfigs[0]);
|
|
log.debug(`loaded svelte config ${foundConfigs[0]}`, config);
|
|
return config;
|
|
} catch (e) {
|
|
log.error(`failed to load config ${foundConfigs[0]}`, e);
|
|
}
|
|
}
|
|
|
|
// src/utils/options.ts
|
|
var knownOptions = new Set([
|
|
"include",
|
|
"exclude",
|
|
"extensions",
|
|
"emitCss",
|
|
"compilerOptions",
|
|
"preprocess",
|
|
"hot",
|
|
"disableTransformCache",
|
|
"disableCssHmr",
|
|
"useVitePreprocess"
|
|
]);
|
|
function buildDefaultOptions({isProduction}, options) {
|
|
const disableCssHmr = !!(options == null ? void 0 : options.disableCssHmr);
|
|
const emitCss = isProduction || !disableCssHmr;
|
|
const hot = isProduction ? false : {
|
|
injectCss: !emitCss
|
|
};
|
|
const defaultOptions = {
|
|
extensions: [".svelte"],
|
|
hot,
|
|
emitCss,
|
|
compilerOptions: {
|
|
format: "esm",
|
|
css: !emitCss,
|
|
dev: !isProduction
|
|
}
|
|
};
|
|
log.debug(`default options for ${isProduction ? "production" : "development"} ${!isProduction && disableCssHmr ? " with css hmr disabled" : ""}`, defaultOptions);
|
|
return defaultOptions;
|
|
}
|
|
function validateInlineOptions(inlineOptions) {
|
|
const invalidKeys = Object.keys(inlineOptions || {}).filter((key) => !knownOptions.has(key));
|
|
if (invalidKeys.length) {
|
|
log.warn(`invalid plugin options "${invalidKeys.join(", ")}" in config`, inlineOptions);
|
|
}
|
|
}
|
|
function enforceOptionsForHmr(options) {
|
|
if (options.hot) {
|
|
if (!options.compilerOptions.dev) {
|
|
log.warn("hmr is enabled but compilerOptions.dev is false, forcing it to true");
|
|
options.compilerOptions.dev = true;
|
|
}
|
|
if (options.emitCss) {
|
|
if (options.hot !== true && options.hot.injectCss) {
|
|
log.warn("hmr and emitCss are enabled but hot.injectCss is true, forcing it to false");
|
|
options.hot.injectCss = false;
|
|
}
|
|
if (options.compilerOptions.css) {
|
|
log.warn("hmr and emitCss are enabled but compilerOptions.css is true, forcing it to false");
|
|
options.compilerOptions.css = false;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
function enforceOptionsForProduction(options) {
|
|
if (options.isProduction) {
|
|
if (options.hot) {
|
|
log.warn("options.hot is enabled but does not work on production build, forcing it to false");
|
|
options.hot = false;
|
|
}
|
|
if (!options.emitCss) {
|
|
log.warn("you are building for production but emitCss is disabled. forcing it to true");
|
|
options.emitCss = true;
|
|
}
|
|
if (options.compilerOptions.dev) {
|
|
log.warn("you are building for production but compilerOptions.dev is true, forcing it to false");
|
|
options.compilerOptions.dev = false;
|
|
}
|
|
}
|
|
}
|
|
function mergeOptions(defaultOptions, svelteConfig, inlineOptions, viteConfig) {
|
|
return __assign(__assign(__assign(__assign({}, defaultOptions), svelteConfig), inlineOptions), {
|
|
compilerOptions: __assign(__assign(__assign({}, defaultOptions.compilerOptions), (svelteConfig == null ? void 0 : svelteConfig.compilerOptions) || {}), (inlineOptions == null ? void 0 : inlineOptions.compilerOptions) || {}),
|
|
root: viteConfig.root,
|
|
isProduction: viteConfig.isProduction,
|
|
isBuild: viteConfig.command === "build",
|
|
isServe: viteConfig.command === "serve"
|
|
});
|
|
}
|
|
function resolveOptions(inlineOptions = {}, viteConfig) {
|
|
const defaultOptions = buildDefaultOptions(viteConfig, inlineOptions);
|
|
const svelteConfig = loadSvelteConfig(viteConfig.root) || {};
|
|
const resolvedOptions = mergeOptions(defaultOptions, svelteConfig, inlineOptions, viteConfig);
|
|
enforceOptionsForProduction(resolvedOptions);
|
|
enforceOptionsForHmr(resolvedOptions);
|
|
log.debug("resolved options", resolvedOptions);
|
|
return resolvedOptions;
|
|
}
|
|
|
|
// src/utils/VitePluginSvelteCache.ts
|
|
var VitePluginSvelteCache = class {
|
|
constructor() {
|
|
this._compile = new Map();
|
|
this._compileSSR = new Map();
|
|
}
|
|
selectCache(ssr) {
|
|
return ssr ? this._compileSSR : this._compile;
|
|
}
|
|
getCompileData(svelteRequest, errorOnMissing = true) {
|
|
const cache = this.selectCache(svelteRequest.ssr);
|
|
const id = svelteRequest.normalizedFilename;
|
|
if (cache.has(id)) {
|
|
return cache.get(id);
|
|
}
|
|
if (errorOnMissing) {
|
|
throw new Error(`${id} has no corresponding entry in the ${svelteRequest.ssr ? "ssr" : ""}cache. This is a @sveltejs/vite-plugin-svelte internal error, please open an issue.`);
|
|
}
|
|
}
|
|
setCompileData(compileData) {
|
|
const cache = this.selectCache(!!compileData.ssr);
|
|
const id = compileData.normalizedFilename;
|
|
cache.set(id, compileData);
|
|
}
|
|
};
|
|
|
|
// src/utils/constants.ts
|
|
var VITE_RESOLVE_MAIN_FIELDS = ["module", "jsnext:main", "jsnext"];
|
|
var SVELTE_RESOLVE_MAIN_FIELDS = ["svelte", ...VITE_RESOLVE_MAIN_FIELDS];
|
|
var SVELTE_IMPORTS = [
|
|
"svelte/animate",
|
|
"svelte/easing",
|
|
"svelte/internal",
|
|
"svelte/motion",
|
|
"svelte/store",
|
|
"svelte/transition",
|
|
"svelte",
|
|
"svelte-hmr/runtime/hot-api-esm.js",
|
|
"svelte-hmr/runtime/proxy-adapter-dom.js",
|
|
"svelte-hmr"
|
|
];
|
|
|
|
// src/index.ts
|
|
var pkg_export_errors = new Set();
|
|
function vitePluginSvelte(inlineOptions) {
|
|
if (process.env.DEBUG != null) {
|
|
log.setLevel("debug");
|
|
}
|
|
validateInlineOptions(inlineOptions);
|
|
const cache = new VitePluginSvelteCache();
|
|
let requestParser;
|
|
let options;
|
|
let compileSvelte;
|
|
return {
|
|
name: "vite-plugin-svelte",
|
|
enforce: "pre",
|
|
config(config) {
|
|
if (process.env.DEBUG) {
|
|
log.setLevel("debug");
|
|
} else if (config.logLevel) {
|
|
log.setLevel(config.logLevel);
|
|
}
|
|
const extraViteConfig = {
|
|
optimizeDeps: {
|
|
exclude: [...SVELTE_IMPORTS]
|
|
},
|
|
resolve: {
|
|
mainFields: [...SVELTE_RESOLVE_MAIN_FIELDS],
|
|
dedupe: [...SVELTE_IMPORTS]
|
|
}
|
|
};
|
|
if (inlineOptions == null ? void 0 : inlineOptions.useVitePreprocess) {
|
|
extraViteConfig.esbuild = {
|
|
tsconfigRaw: {
|
|
compilerOptions: {
|
|
importsNotUsedAsValues: "preserve"
|
|
}
|
|
}
|
|
};
|
|
}
|
|
log.debug("additional vite config", extraViteConfig);
|
|
return extraViteConfig;
|
|
},
|
|
configResolved(config) {
|
|
options = resolveOptions(inlineOptions, config);
|
|
requestParser = buildIdParser(options);
|
|
compileSvelte = createCompileSvelte(options, config);
|
|
},
|
|
configureServer(server) {
|
|
options.server = server;
|
|
},
|
|
load(id, ssr) {
|
|
var _a;
|
|
const svelteRequest = requestParser(id, !!ssr);
|
|
if (!svelteRequest) {
|
|
return;
|
|
}
|
|
log.debug("load", svelteRequest);
|
|
const {filename, query} = svelteRequest;
|
|
if (query.svelte) {
|
|
if (query.type === "style") {
|
|
const compileData = cache.getCompileData(svelteRequest, false);
|
|
if ((_a = compileData == null ? void 0 : compileData.compiled) == null ? void 0 : _a.css) {
|
|
log.debug(`load returns css for ${filename}`);
|
|
return compileData.compiled.css;
|
|
}
|
|
}
|
|
}
|
|
},
|
|
async resolveId(importee, importer, customOptions, ssr) {
|
|
const svelteRequest = requestParser(importee, !!ssr);
|
|
log.debug("resolveId", svelteRequest || importee);
|
|
if (svelteRequest == null ? void 0 : svelteRequest.query.svelte) {
|
|
if (svelteRequest.query.type === "style") {
|
|
log.debug(`resolveId resolved virtual css module ${svelteRequest.cssId}`);
|
|
return svelteRequest.cssId;
|
|
}
|
|
log.debug(`resolveId resolved ${importee}`);
|
|
return importee;
|
|
}
|
|
if (!importer || importee[0] === "." || importee[0] === "\0" || path2.isAbsolute(importee)) {
|
|
return null;
|
|
}
|
|
const parts = importee.split("/");
|
|
let dir, pkg, name = parts.shift();
|
|
if (name && name[0] === "@") {
|
|
name += `/${parts.shift()}`;
|
|
}
|
|
try {
|
|
const file = `${name}/package.json`;
|
|
const resolved = relative.resolve(file, path2.dirname(importer));
|
|
dir = path2.dirname(resolved);
|
|
pkg = require(resolved);
|
|
} catch (err) {
|
|
if (err.code === "MODULE_NOT_FOUND")
|
|
return null;
|
|
if (err.code === "ERR_PACKAGE_PATH_NOT_EXPORTED") {
|
|
pkg_export_errors.add(name);
|
|
return null;
|
|
}
|
|
throw err;
|
|
}
|
|
if (parts.length === 0 && pkg.svelte) {
|
|
return path2.resolve(dir, pkg.svelte);
|
|
}
|
|
log.debug(`resolveId did not resolve ${importee}`);
|
|
},
|
|
async transform(code, id, ssr) {
|
|
var _a;
|
|
const svelteRequest = requestParser(id, !!ssr);
|
|
if (!svelteRequest) {
|
|
return;
|
|
}
|
|
log.debug("transform", svelteRequest);
|
|
const {filename, query} = svelteRequest;
|
|
const cachedCompileData = cache.getCompileData(svelteRequest, false);
|
|
if (query.svelte) {
|
|
if (query.type === "style" && ((_a = cachedCompileData == null ? void 0 : cachedCompileData.compiled) == null ? void 0 : _a.css)) {
|
|
log.debug(`transform returns css for ${filename}`);
|
|
return cachedCompileData.compiled.css;
|
|
}
|
|
log.error("failed to transform tagged svelte request", svelteRequest);
|
|
throw new Error(`failed to transform tagged svelte request for id ${id}`);
|
|
}
|
|
if (cachedCompileData && !options.disableTransformCache) {
|
|
log.debug(`transform returns cached js for ${filename}`);
|
|
return cachedCompileData.compiled.js;
|
|
}
|
|
const compileData = await compileSvelte(svelteRequest, code, options);
|
|
cache.setCompileData(compileData);
|
|
log.debug(`transform returns compiled js for ${filename}`);
|
|
return compileData.compiled.js;
|
|
},
|
|
handleHotUpdate(ctx) {
|
|
if (!options.emitCss || options.disableCssHmr) {
|
|
return;
|
|
}
|
|
const svelteRequest = requestParser(ctx.file, false, ctx.timestamp);
|
|
if (!svelteRequest) {
|
|
return;
|
|
}
|
|
log.debug("handleHotUpdate", svelteRequest);
|
|
return handleHotUpdate(compileSvelte, ctx, svelteRequest, cache);
|
|
},
|
|
transformIndexHtml(html, ctx) {
|
|
log.debug("transformIndexHtml", html);
|
|
},
|
|
buildEnd() {
|
|
if (pkg_export_errors.size > 0) {
|
|
log.warn(`The following packages did not export their \`package.json\` file so we could not check the "svelte" field.If you had difficulties importing svelte components from a package, then please contact the author and ask them to export the package.json file.`, Array.from(pkg_export_errors, (s) => `- ${s}`).join("\n"));
|
|
}
|
|
}
|
|
};
|
|
}
|
|
module.exports = vitePluginSvelte;
|
|
vitePluginSvelte["default"] = vitePluginSvelte;
|
|
// Annotate the CommonJS export names for ESM import in node:
|
|
0 && (module.exports = {});
|