var __defProp = Object.defineProperty; var __defProps = Object.defineProperties; var __getOwnPropDescs = Object.getOwnPropertyDescriptors; var __getOwnPropSymbols = Object.getOwnPropertySymbols; var __hasOwnProp = Object.prototype.hasOwnProperty; 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 __spreadValues = (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 __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b)); 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"; // 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) { if (!logger.enabled) { return; } if (logger.isDebug) { payload !== void 0 ? logger.log(message, payload) : logger.log(message); } else { logger.log(logger.color(`${new Date().toLocaleTimeString()} [${prefix}] ${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) { if (logged.has(message)) { return; } logged.add(message); logFn.apply(null, [message, payload]); }; 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) { var _a, _b, _c; const { emitCss, onwarn, isBuild } = options; const sendViaWS = !isBuild && ((_a = options.experimental) == null ? void 0 : _a.sendWarningsToBrowser); let warn = isBuild ? warnBuild : warnDev; const handledByDefaultWarn = []; const notIgnored = warnings == null ? void 0 : 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, rawWarnings: warnings }; log.debug(`sending svelte:warnings message for ${svelteRequest.normalizedFilename}`); (_c = (_b = options.server) == null ? void 0 : _b.ws) == null ? void 0 : _c.send("svelte:warnings", message); } } function ignoreCompilerWarning(warning, isBuild, emitCss) { return !emitCss && warning.code === "css-unused-selector" || !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(__spreadProps(__spreadValues({}, 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(""); } // 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 } = 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 e; } const affectedModules = /* @__PURE__ */ new Set(); const cssModule = server.moduleGraph.getModuleById(svelteRequest.cssId); const mainModule = server.moduleGraph.getModuleById(svelteRequest.id); const cssUpdated = cssModule && cssChanged(cachedCss, compileData.compiled.css); if (cssUpdated) { log.debug(`handleHotUpdate css changed for ${svelteRequest.cssId}`); affectedModules.add(cssModule); } const jsUpdated = mainModule && jsChanged(cachedJS, compileData.compiled.js, svelteRequest.filename); if (jsUpdated) { log.debug(`handleHotUpdate js changed for ${svelteRequest.id}`); affectedModules.add(mainModule); } if (!jsUpdated) { logCompilerWarnings(svelteRequest, compileData.compiled.warnings, options); } const result = [...affectedModules].filter(Boolean); 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)); } if (result.length > 0) { log.debug(`handleHotUpdate for ${svelteRequest.id} result: ${result.map((m) => m.id).join(", ")}`); } return result; } function cssChanged(prev, next) { return !isCodeEqual(prev == null ? void 0 : prev.code, next == null ? void 0 : next.code); } function jsChanged(prev, next, filename) { const prevJs = prev == null ? void 0 : prev.code; const nextJs = next == null ? void 0 : 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/compile.ts var scriptLangRE = /