var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, { get: (a, b) => (typeof require !== "undefined" ? require : a)[b] }) : x)(function(x) { if (typeof require !== "undefined") return require.apply(this, arguments); throw new Error('Dynamic require of "' + x + '" is not supported'); }); // src/index.ts import fs8 from "fs"; import { VERSION as svelteVersion } from "svelte/compiler"; import { version as viteVersion } from "vite"; import { isDepExcluded as isDepExcluded2 } from "vitefu"; // src/utils/log.ts import { cyan, yellow, red } from "kleur/colors"; import debug from "debug"; var levels = ["debug", "info", "warn", "error", "silent"]; var prefix = "vite-plugin-svelte"; var loggers = { debug: { log: debug(`vite:${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 } }; 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} `); } } function _log(logger, message, payload, namespace) { if (!logger.enabled) { return; } if (logger.isDebug) { const log2 = namespace ? logger.log.extend(namespace) : logger.log; payload !== void 0 ? log2(message, payload) : log2(message); } else { logger.log( logger.color( `${(/* @__PURE__ */ new Date()).toLocaleTimeString()} [${prefix}${namespace ? `:${namespace}` : ""}] ${message}` ) ); if (payload) { logger.log(payload); } } } function createLogger(level) { const logger = loggers[level]; const logFn = _log.bind(null, logger); const logged = /* @__PURE__ */ new Set(); 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; } var log = { debug: createLogger("debug"), info: createLogger("info"), warn: createLogger("warn"), error: createLogger("error"), setLevel }; function logCompilerWarnings(svelteRequest, warnings, options) { const { emitCss, onwarn, isBuild } = options; const sendViaWS = !isBuild && options.experimental?.sendWarningsToBrowser; let warn = isBuild ? warnBuild : warnDev; const handledByDefaultWarn = []; const notIgnored = warnings?.filter((w) => !ignoreCompilerWarning(w, isBuild, emitCss)); const extra = buildExtraWarnings(warnings, isBuild); const allWarnings = [...notIgnored, ...extra]; if (sendViaWS) { const _warn = warn; warn = (w) => { handledByDefaultWarn.push(w); _warn(w); }; } allWarnings.forEach((warning) => { if (onwarn) { onwarn(warning, warn); } else { warn(warning); } }); if (sendViaWS) { 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); } } function ignoreCompilerWarning(warning, isBuild, emitCss) { return !emitCss && warning.code === "css-unused-selector" || // same as rollup-plugin-svelte !isBuild && isNoScopableElementWarning(warning); } function isNoScopableElementWarning(warning) { return warning.code === "css-unused-selector" && warning.message.includes('"*"'); } function buildExtraWarnings(warnings, isBuild) { const extraWarnings = []; if (!isBuild) { const noScopableElementWarnings = warnings.filter((w) => isNoScopableElementWarning(w)); if (noScopableElementWarnings.length > 0) { const noScopableElementWarning = noScopableElementWarnings[noScopableElementWarnings.length - 1]; extraWarnings.push({ ...noScopableElementWarning, code: "vite-plugin-svelte-css-no-scopable-elements", message: `No scopable elements found in template. If you're using global styles in the style tag, you should move it into an external stylesheet file and import it in JS. See https://github.com/sveltejs/vite-plugin-svelte/blob/main/docs/faq.md#where-should-i-put-my-global-styles.` }); } } return extraWarnings; } function warnDev(w) { log.info.enabled && log.info(buildExtendedLogMessage(w)); } function warnBuild(w) { log.warn.enabled && log.warn(buildExtendedLogMessage(w), w.frame); } 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(""); } function isDebugNamespaceEnabled(namespace) { return debug.enabled(`vite:${prefix}:${namespace}`); } // src/utils/error.ts function toRollupError(error, options) { const { filename, frame, start, code, name, stack } = error; 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; } function toESBuildError(error, options) { const { filename, frame, start, stack } = error; 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; } 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) : ""; } function formatFrameForVite(frame) { if (!frame) { return ""; } return frame.split("\n").map((line) => line.match(/^\s+\^/) ? " " + line : " " + line.replace(":", " | ")).join("\n"); } // src/handle-hot-update.ts async function handleHotUpdate(compileSvelte2, ctx, svelteRequest, cache, options) { if (!cache.has(svelteRequest)) { log.debug(`handleHotUpdate called before initial transform for ${svelteRequest.id}`); return; } const { read, server, modules } = ctx; const cachedJS = cache.getJS(svelteRequest); const cachedCss = cache.getCSS(svelteRequest); const content = await read(); let compileData; try { compileData = await compileSvelte2(svelteRequest, content, options); cache.update(compileData); } catch (e) { cache.setError(svelteRequest, e); throw toRollupError(e, options); } const affectedModules = [...modules]; const cssIdx = modules.findIndex((m) => m.id === svelteRequest.cssId); if (cssIdx > -1) { const cssUpdated = cssChanged(cachedCss, compileData.compiled.css); if (!cssUpdated) { log.debug(`skipping unchanged css for ${svelteRequest.cssId}`); affectedModules.splice(cssIdx, 1); } } const jsIdx = modules.findIndex((m) => m.id === svelteRequest.id); if (jsIdx > -1) { const jsUpdated = jsChanged(cachedJS, compileData.compiled.js, svelteRequest.filename); if (!jsUpdated) { log.debug(`skipping unchanged js for ${svelteRequest.id}`); affectedModules.splice(jsIdx, 1); logCompilerWarnings(svelteRequest, compileData.compiled.warnings, options); } } const ssrModulesToInvalidate = affectedModules.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)); } if (affectedModules.length > 0) { log.debug( `handleHotUpdate for ${svelteRequest.id} result: ${affectedModules.map((m) => m.id).join(", ")}` ); } return affectedModules; } function cssChanged(prev, next) { return !isCodeEqual(prev?.code, next?.code); } function jsChanged(prev, next, filename) { const prevJs = prev?.code; const nextJs = next?.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 ${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 import { compile, preprocess, walk } from "svelte/compiler"; import { createMakeHot } from "svelte-hmr"; // src/utils/hash.ts import * as crypto from "crypto"; var hashes = /* @__PURE__ */ 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")).slice(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 import MagicString from "magic-string"; import path from "path"; function createInjectScopeEverythingRulePreprocessorGroup() { return { style({ content, filename }) { const s = new MagicString(content); s.append(" *{}"); return { code: s.toString(), map: s.generateDecodedMap({ source: filename ? path.basename(filename) : void 0, hires: true }) }; } }; } function buildExtraPreprocessors(options, config) { const prependPreprocessors = []; const appendPreprocessors = []; const pluginsWithPreprocessorsDeprecated = config.plugins.filter((p) => p?.sveltePreprocess); if (pluginsWithPreprocessorsDeprecated.length > 0) { log.warn( `The following plugins use the deprecated 'plugin.sveltePreprocess' field. Please contact their maintainers and ask them to move it to 'plugin.api.sveltePreprocess': ${pluginsWithPreprocessorsDeprecated.map((p) => p.name).join(", ")}` ); pluginsWithPreprocessorsDeprecated.forEach((p) => { if (!p.api) { p.api = {}; } if (p.api.sveltePreprocess === void 0) { p.api.sveltePreprocess = p.sveltePreprocess; } else { log.error( `ignoring plugin.sveltePreprocess of ${p.name} because it already defined plugin.api.sveltePreprocess.` ); } }); } const pluginsWithPreprocessors = config.plugins.filter((p) => p?.api?.sveltePreprocess); const ignored = [], included = []; for (const p of pluginsWithPreprocessors) { if (options.ignorePluginPreprocessors === true || Array.isArray(options.ignorePluginPreprocessors) && options.ignorePluginPreprocessors?.includes(p.name)) { ignored.push(p); } else { included.push(p); } } if (ignored.length > 0) { log.debug( `Ignoring svelte preprocessors defined by these vite plugins: ${ignored.map((p) => p.name).join(", ")}` ); } if (included.length > 0) { log.debug( `Adding svelte preprocessors defined by these vite plugins: ${included.map((p) => p.name).join(", ")}` ); appendPreprocessors.push(...pluginsWithPreprocessors.map((p) => p.api.sveltePreprocess)); } return { prependPreprocessors, appendPreprocessors }; } function addExtraPreprocessors(options, config) { const { prependPreprocessors, appendPreprocessors } = buildExtraPreprocessors(options, config); if (prependPreprocessors.length > 0 || appendPreprocessors.length > 0) { if (!options.preprocess) { options.preprocess = [...prependPreprocessors, ...appendPreprocessors]; } else if (Array.isArray(options.preprocess)) { options.preprocess.unshift(...prependPreprocessors); options.preprocess.push(...appendPreprocessors); } else { options.preprocess = [...prependPreprocessors, options.preprocess, ...appendPreprocessors]; } } } // src/utils/sourcemaps.ts import path2 from "path"; var IS_WINDOWS = process.platform === "win32"; function mapToRelative(map, filename) { if (!map) { return; } const sourceRoot = map.sourceRoot; const dirname2 = path2.dirname(filename); const toRelative = (s) => { if (!s) { return s; } let sourcePath; if (s.startsWith("file:///")) { 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 path2.isAbsolute(sourcePath) ? path2.relative(dirname2, sourcePath) : sourcePath; }; if (map.file) { map.file = path2.basename(filename); } if (map.sources) { map.sources = map.sources.map(toRelative); } if (map.sourceRoot) { delete map.sourceRoot; } } function removeLangSuffix(map, suffix) { if (!map) { return; } 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); } } // src/utils/compile.ts var scriptLangRE = /