@sveltejs/vite-plugin-svelte 1.0.0-next.3 → 1.0.0-next.33

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs ADDED
@@ -0,0 +1,1581 @@
1
+ var __create = Object.create;
2
+ var __defProp = Object.defineProperty;
3
+ var __defProps = Object.defineProperties;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
6
+ var __getOwnPropNames = Object.getOwnPropertyNames;
7
+ var __getOwnPropSymbols = Object.getOwnPropertySymbols;
8
+ var __getProtoOf = Object.getPrototypeOf;
9
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
10
+ var __propIsEnum = Object.prototype.propertyIsEnumerable;
11
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
12
+ var __spreadValues = (a, b) => {
13
+ for (var prop in b || (b = {}))
14
+ if (__hasOwnProp.call(b, prop))
15
+ __defNormalProp(a, prop, b[prop]);
16
+ if (__getOwnPropSymbols)
17
+ for (var prop of __getOwnPropSymbols(b)) {
18
+ if (__propIsEnum.call(b, prop))
19
+ __defNormalProp(a, prop, b[prop]);
20
+ }
21
+ return a;
22
+ };
23
+ var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
24
+ var __markAsModule = (target) => __defProp(target, "__esModule", { value: true });
25
+ var __export = (target, all) => {
26
+ __markAsModule(target);
27
+ for (var name in all)
28
+ __defProp(target, name, { get: all[name], enumerable: true });
29
+ };
30
+ var __reExport = (target, module2, desc) => {
31
+ if (module2 && typeof module2 === "object" || typeof module2 === "function") {
32
+ for (let key of __getOwnPropNames(module2))
33
+ if (!__hasOwnProp.call(target, key) && key !== "default")
34
+ __defProp(target, key, { get: () => module2[key], enumerable: !(desc = __getOwnPropDesc(module2, key)) || desc.enumerable });
35
+ }
36
+ return target;
37
+ };
38
+ var __toModule = (module2) => {
39
+ return __reExport(__markAsModule(__defProp(module2 != null ? __create(__getProtoOf(module2)) : {}, "default", module2 && module2.__esModule && "default" in module2 ? { get: () => module2.default, enumerable: true } : { value: module2, enumerable: true })), module2);
40
+ };
41
+
42
+ // src/index.ts
43
+ __export(exports, {
44
+ svelte: () => svelte
45
+ });
46
+
47
+ // ../../node_modules/.pnpm/tsup@5.11.9_typescript@4.5.4/node_modules/tsup/assets/cjs_shims.js
48
+ var getImportMetaUrl = () => typeof document === "undefined" ? new URL("file:" + __filename).href : document.currentScript && document.currentScript.src || new URL("main.js", document.baseURI).href;
49
+ var importMetaUrl = /* @__PURE__ */ getImportMetaUrl();
50
+
51
+ // src/index.ts
52
+ var import_fs6 = __toModule(require("fs"));
53
+
54
+ // src/utils/log.ts
55
+ var import_colors = __toModule(require("kleur/colors"));
56
+ var import_debug = __toModule(require("debug"));
57
+ var levels = ["debug", "info", "warn", "error", "silent"];
58
+ var prefix = "vite-plugin-svelte";
59
+ var loggers = {
60
+ debug: {
61
+ log: (0, import_debug.default)(`vite:${prefix}`),
62
+ enabled: false,
63
+ isDebug: true
64
+ },
65
+ info: {
66
+ color: import_colors.cyan,
67
+ log: console.log,
68
+ enabled: true
69
+ },
70
+ warn: {
71
+ color: import_colors.yellow,
72
+ log: console.warn,
73
+ enabled: true
74
+ },
75
+ error: {
76
+ color: import_colors.red,
77
+ log: console.error,
78
+ enabled: true
79
+ },
80
+ silent: {
81
+ enabled: false
82
+ }
83
+ };
84
+ var _level = "info";
85
+ function setLevel(level) {
86
+ if (level === _level) {
87
+ return;
88
+ }
89
+ const levelIndex = levels.indexOf(level);
90
+ if (levelIndex > -1) {
91
+ _level = level;
92
+ for (let i = 0; i < levels.length; i++) {
93
+ loggers[levels[i]].enabled = i >= levelIndex;
94
+ }
95
+ } else {
96
+ _log(loggers.error, `invalid log level: ${level} `);
97
+ }
98
+ }
99
+ function _log(logger, message, payload) {
100
+ if (!logger.enabled) {
101
+ return;
102
+ }
103
+ if (logger.isDebug) {
104
+ payload !== void 0 ? logger.log(message, payload) : logger.log(message);
105
+ } else {
106
+ logger.log(logger.color(`${new Date().toLocaleTimeString()} [${prefix}] ${message}`));
107
+ if (payload) {
108
+ logger.log(payload);
109
+ }
110
+ }
111
+ }
112
+ function createLogger(level) {
113
+ const logger = loggers[level];
114
+ const logFn = _log.bind(null, logger);
115
+ const logged = new Set();
116
+ const once = function(message, payload) {
117
+ if (logged.has(message)) {
118
+ return;
119
+ }
120
+ logged.add(message);
121
+ logFn.apply(null, [message, payload]);
122
+ };
123
+ Object.defineProperty(logFn, "enabled", {
124
+ get() {
125
+ return logger.enabled;
126
+ }
127
+ });
128
+ Object.defineProperty(logFn, "once", {
129
+ get() {
130
+ return once;
131
+ }
132
+ });
133
+ return logFn;
134
+ }
135
+ var log = {
136
+ debug: createLogger("debug"),
137
+ info: createLogger("info"),
138
+ warn: createLogger("warn"),
139
+ error: createLogger("error"),
140
+ setLevel
141
+ };
142
+ function logCompilerWarnings(warnings, options) {
143
+ const { emitCss, onwarn, isBuild } = options;
144
+ const warn = isBuild ? warnBuild : warnDev;
145
+ const notIgnoredWarnings = warnings == null ? void 0 : warnings.filter((w) => !ignoreCompilerWarning(w, isBuild, emitCss));
146
+ const extraWarnings = buildExtraWarnings(warnings, isBuild);
147
+ [...notIgnoredWarnings, ...extraWarnings].forEach((warning) => {
148
+ if (onwarn) {
149
+ onwarn(warning, warn);
150
+ } else {
151
+ warn(warning);
152
+ }
153
+ });
154
+ }
155
+ function ignoreCompilerWarning(warning, isBuild, emitCss) {
156
+ return !emitCss && warning.code === "css-unused-selector" || !isBuild && isNoScopableElementWarning(warning);
157
+ }
158
+ function isNoScopableElementWarning(warning) {
159
+ return warning.code === "css-unused-selector" && warning.message.includes('"*"');
160
+ }
161
+ function buildExtraWarnings(warnings, isBuild) {
162
+ const extraWarnings = [];
163
+ if (!isBuild) {
164
+ const noScopableElementWarnings = warnings.filter((w) => isNoScopableElementWarning(w));
165
+ if (noScopableElementWarnings.length > 0) {
166
+ const noScopableElementWarning = noScopableElementWarnings[noScopableElementWarnings.length - 1];
167
+ extraWarnings.push(__spreadProps(__spreadValues({}, noScopableElementWarning), {
168
+ code: "vite-plugin-svelte-css-no-scopable-elements",
169
+ 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.`
170
+ }));
171
+ }
172
+ }
173
+ return extraWarnings;
174
+ }
175
+ function warnDev(w) {
176
+ log.info.enabled && log.info(buildExtendedLogMessage(w));
177
+ }
178
+ function warnBuild(w) {
179
+ log.warn.enabled && log.warn(buildExtendedLogMessage(w), w.frame);
180
+ }
181
+ function buildExtendedLogMessage(w) {
182
+ const parts = [];
183
+ if (w.filename) {
184
+ parts.push(w.filename);
185
+ }
186
+ if (w.start) {
187
+ parts.push(":", w.start.line, ":", w.start.column);
188
+ }
189
+ if (w.message) {
190
+ parts.push(" ", w.message);
191
+ }
192
+ return parts.join("");
193
+ }
194
+
195
+ // src/handle-hot-update.ts
196
+ async function handleHotUpdate(compileSvelte2, ctx, svelteRequest, cache, options) {
197
+ const { read, server } = ctx;
198
+ const cachedJS = cache.getJS(svelteRequest);
199
+ if (!cachedJS) {
200
+ log.debug(`handleHotUpdate first call ${svelteRequest.id}`);
201
+ return;
202
+ }
203
+ const cachedCss = cache.getCSS(svelteRequest);
204
+ const content = await read();
205
+ const compileData = await compileSvelte2(svelteRequest, content, options);
206
+ cache.update(compileData);
207
+ const affectedModules = new Set();
208
+ const cssModule = server.moduleGraph.getModuleById(svelteRequest.cssId);
209
+ const mainModule = server.moduleGraph.getModuleById(svelteRequest.id);
210
+ const cssUpdated = cssModule && cssChanged(cachedCss, compileData.compiled.css);
211
+ if (cssUpdated) {
212
+ log.debug("handleHotUpdate css changed");
213
+ affectedModules.add(cssModule);
214
+ }
215
+ const jsUpdated = mainModule && jsChanged(cachedJS, compileData.compiled.js, svelteRequest.filename);
216
+ if (jsUpdated) {
217
+ log.debug("handleHotUpdate js changed");
218
+ affectedModules.add(mainModule);
219
+ }
220
+ if (!jsUpdated) {
221
+ logCompilerWarnings(compileData.compiled.warnings, options);
222
+ }
223
+ const result = [...affectedModules].filter(Boolean);
224
+ const ssrModulesToInvalidate = result.filter((m) => !!m.ssrTransformResult);
225
+ if (ssrModulesToInvalidate.length > 0) {
226
+ log.debug(`invalidating modules ${ssrModulesToInvalidate.map((m) => m.id).join(", ")}`);
227
+ ssrModulesToInvalidate.forEach((moduleNode) => server.moduleGraph.invalidateModule(moduleNode));
228
+ }
229
+ if (result.length > 0) {
230
+ log.debug(`handleHotUpdate for ${svelteRequest.id} result: ${result.map((m) => m.id).join(", ")}`);
231
+ }
232
+ return result;
233
+ }
234
+ function cssChanged(prev, next) {
235
+ return !isCodeEqual(prev == null ? void 0 : prev.code, next == null ? void 0 : next.code);
236
+ }
237
+ function jsChanged(prev, next, filename) {
238
+ const prevJs = prev == null ? void 0 : prev.code;
239
+ const nextJs = next == null ? void 0 : next.code;
240
+ const isStrictEqual = isCodeEqual(prevJs, nextJs);
241
+ if (isStrictEqual) {
242
+ return false;
243
+ }
244
+ const isLooseEqual = isCodeEqual(normalizeJsCode(prevJs), normalizeJsCode(nextJs));
245
+ if (!isStrictEqual && isLooseEqual) {
246
+ log.warn(`ignoring compiler output js change for ${filename} as it is equal to previous output after normalization`);
247
+ }
248
+ return !isLooseEqual;
249
+ }
250
+ function isCodeEqual(prev, next) {
251
+ if (!prev && !next) {
252
+ return true;
253
+ }
254
+ if (!prev && next || prev && !next) {
255
+ return false;
256
+ }
257
+ return prev === next;
258
+ }
259
+ function normalizeJsCode(code) {
260
+ if (!code) {
261
+ return code;
262
+ }
263
+ return code.replace(/\s*\badd_location\s*\([^)]*\)\s*;?/g, "");
264
+ }
265
+
266
+ // src/utils/compile.ts
267
+ var import_compiler = __toModule(require("svelte/compiler"));
268
+ var import_svelte_hmr = __toModule(require("svelte-hmr"));
269
+
270
+ // src/utils/hash.ts
271
+ var crypto = __toModule(require("crypto"));
272
+ var hashes = Object.create(null);
273
+ var hash_length = 12;
274
+ function safeBase64Hash(input) {
275
+ if (hashes[input]) {
276
+ return hashes[input];
277
+ }
278
+ const md5 = crypto.createHash("md5");
279
+ md5.update(input);
280
+ const hash = toSafe(md5.digest("base64")).substr(0, hash_length);
281
+ hashes[input] = hash;
282
+ return hash;
283
+ }
284
+ var replacements = {
285
+ "+": "-",
286
+ "/": "_",
287
+ "=": ""
288
+ };
289
+ var replaceRE = new RegExp(`[${Object.keys(replacements).join("")}]`, "g");
290
+ function toSafe(base64) {
291
+ return base64.replace(replaceRE, (x) => replacements[x]);
292
+ }
293
+
294
+ // src/utils/compile.ts
295
+ var _createCompileSvelte = (makeHot) => async function compileSvelte2(svelteRequest, code, options) {
296
+ var _a, _b;
297
+ const { filename, normalizedFilename, cssId, ssr } = svelteRequest;
298
+ const { emitCss = true } = options;
299
+ const dependencies = [];
300
+ const compileOptions = __spreadProps(__spreadValues({}, options.compilerOptions), {
301
+ filename,
302
+ generate: ssr ? "ssr" : "dom"
303
+ });
304
+ if (options.hot && options.emitCss) {
305
+ const hash = `s-${safeBase64Hash(normalizedFilename)}`;
306
+ log.debug(`setting cssHash ${hash} for ${normalizedFilename}`);
307
+ compileOptions.cssHash = () => hash;
308
+ }
309
+ if (ssr && compileOptions.enableSourcemap !== false) {
310
+ if (typeof compileOptions.enableSourcemap === "object") {
311
+ compileOptions.enableSourcemap.css = false;
312
+ } else {
313
+ compileOptions.enableSourcemap = { js: true, css: false };
314
+ }
315
+ }
316
+ let preprocessed;
317
+ if (options.preprocess) {
318
+ preprocessed = await (0, import_compiler.preprocess)(code, options.preprocess, { filename });
319
+ if (preprocessed.dependencies)
320
+ dependencies.push(...preprocessed.dependencies);
321
+ if (preprocessed.map)
322
+ compileOptions.sourcemap = preprocessed.map;
323
+ }
324
+ const finalCode = preprocessed ? preprocessed.code : code;
325
+ const dynamicCompileOptions = await ((_b = (_a = options.experimental) == null ? void 0 : _a.dynamicCompileOptions) == null ? void 0 : _b.call(_a, {
326
+ filename,
327
+ code: finalCode,
328
+ compileOptions
329
+ }));
330
+ if (dynamicCompileOptions && log.debug.enabled) {
331
+ log.debug(`dynamic compile options for ${filename}: ${JSON.stringify(dynamicCompileOptions)}`);
332
+ }
333
+ const finalCompileOptions = dynamicCompileOptions ? __spreadValues(__spreadValues({}, compileOptions), dynamicCompileOptions) : compileOptions;
334
+ const compiled = (0, import_compiler.compile)(finalCode, finalCompileOptions);
335
+ if (emitCss && compiled.css.code) {
336
+ compiled.js.code += `
337
+ import ${JSON.stringify(cssId)};
338
+ `;
339
+ }
340
+ if (!ssr && makeHot) {
341
+ compiled.js.code = makeHot({
342
+ id: filename,
343
+ compiledCode: compiled.js.code,
344
+ hotOptions: options.hot,
345
+ compiled,
346
+ originalCode: code,
347
+ compileOptions: finalCompileOptions
348
+ });
349
+ }
350
+ compiled.js.dependencies = dependencies;
351
+ return {
352
+ filename,
353
+ normalizedFilename,
354
+ compiled,
355
+ ssr,
356
+ dependencies
357
+ };
358
+ };
359
+ function buildMakeHot(options) {
360
+ var _a, _b;
361
+ const needsMakeHot = options.hot !== false && options.isServe && !options.isProduction;
362
+ if (needsMakeHot) {
363
+ const hotApi = (_a = options == null ? void 0 : options.hot) == null ? void 0 : _a.hotApi;
364
+ const adapter = (_b = options == null ? void 0 : options.hot) == null ? void 0 : _b.adapter;
365
+ return (0, import_svelte_hmr.createMakeHot)({
366
+ walk: import_compiler.walk,
367
+ hotApi,
368
+ adapter,
369
+ hotOptions: __spreadValues({ noOverlay: true }, options.hot)
370
+ });
371
+ }
372
+ }
373
+ function createCompileSvelte(options) {
374
+ const makeHot = buildMakeHot(options);
375
+ return _createCompileSvelte(makeHot);
376
+ }
377
+
378
+ // src/utils/id.ts
379
+ var import_pluginutils = __toModule(require("@rollup/pluginutils"));
380
+ var import_vite = __toModule(require("vite"));
381
+ var fs = __toModule(require("fs"));
382
+ var VITE_FS_PREFIX = "/@fs/";
383
+ var IS_WINDOWS = process.platform === "win32";
384
+ function splitId(id) {
385
+ const parts = id.split(`?`, 2);
386
+ const filename = parts[0];
387
+ const rawQuery = parts[1];
388
+ return { filename, rawQuery };
389
+ }
390
+ function parseToSvelteRequest(id, filename, rawQuery, root, timestamp, ssr) {
391
+ const query = parseRequestQuery(rawQuery);
392
+ if (query.url || query.raw) {
393
+ return;
394
+ }
395
+ const normalizedFilename = normalize(filename, root);
396
+ const cssId = createVirtualImportId(filename, root, "style");
397
+ return {
398
+ id,
399
+ filename,
400
+ normalizedFilename,
401
+ cssId,
402
+ query,
403
+ timestamp,
404
+ ssr
405
+ };
406
+ }
407
+ function createVirtualImportId(filename, root, type) {
408
+ const parts = ["svelte", `type=${type}`];
409
+ if (type === "style") {
410
+ parts.push("lang.css");
411
+ }
412
+ if (existsInRoot(filename, root)) {
413
+ filename = root + filename;
414
+ } else if (filename.startsWith(VITE_FS_PREFIX)) {
415
+ filename = IS_WINDOWS ? filename.slice(VITE_FS_PREFIX.length) : filename.slice(VITE_FS_PREFIX.length - 1);
416
+ }
417
+ return `${filename}?${parts.join("&")}`;
418
+ }
419
+ function parseRequestQuery(rawQuery) {
420
+ const query = Object.fromEntries(new URLSearchParams(rawQuery));
421
+ for (const key in query) {
422
+ if (query[key] === "") {
423
+ query[key] = true;
424
+ }
425
+ }
426
+ return query;
427
+ }
428
+ function normalize(filename, normalizedRoot) {
429
+ return stripRoot((0, import_vite.normalizePath)(filename), normalizedRoot);
430
+ }
431
+ function existsInRoot(filename, root) {
432
+ if (filename.startsWith(VITE_FS_PREFIX)) {
433
+ return false;
434
+ }
435
+ return fs.existsSync(root + filename);
436
+ }
437
+ function stripRoot(normalizedFilename, normalizedRoot) {
438
+ return normalizedFilename.startsWith(normalizedRoot + "/") ? normalizedFilename.slice(normalizedRoot.length) : normalizedFilename;
439
+ }
440
+ function buildFilter(include, exclude, extensions) {
441
+ const rollupFilter = (0, import_pluginutils.createFilter)(include, exclude);
442
+ return (filename) => rollupFilter(filename) && extensions.some((ext) => filename.endsWith(ext));
443
+ }
444
+ function buildIdParser(options) {
445
+ const { include, exclude, extensions, root } = options;
446
+ const normalizedRoot = (0, import_vite.normalizePath)(root);
447
+ const filter = buildFilter(include, exclude, extensions);
448
+ return (id, ssr, timestamp = Date.now()) => {
449
+ const { filename, rawQuery } = splitId(id);
450
+ if (filter(filename)) {
451
+ return parseToSvelteRequest(id, filename, rawQuery, normalizedRoot, timestamp, ssr);
452
+ }
453
+ };
454
+ }
455
+
456
+ // src/utils/options.ts
457
+ var import_vite3 = __toModule(require("vite"));
458
+
459
+ // src/utils/load-svelte-config.ts
460
+ var import_module = __toModule(require("module"));
461
+ var import_path = __toModule(require("path"));
462
+ var import_fs = __toModule(require("fs"));
463
+ var import_url = __toModule(require("url"));
464
+ var esmRequire;
465
+ var knownSvelteConfigNames = [
466
+ "svelte.config.js",
467
+ "svelte.config.cjs",
468
+ "svelte.config.mjs"
469
+ ];
470
+ var dynamicImportDefault = new Function("path", 'return import(path + "?t=" + Date.now()).then(m => m.default)');
471
+ async function loadSvelteConfig(viteConfig, inlineOptions) {
472
+ const configFile = findConfigToLoad(viteConfig, inlineOptions);
473
+ if (configFile) {
474
+ let err;
475
+ if (configFile.endsWith(".js") || configFile.endsWith(".mjs")) {
476
+ try {
477
+ const result = await dynamicImportDefault((0, import_url.pathToFileURL)(configFile).href);
478
+ if (result != null) {
479
+ return __spreadProps(__spreadValues({}, result), {
480
+ configFile
481
+ });
482
+ } else {
483
+ throw new Error(`invalid export in ${configFile}`);
484
+ }
485
+ } catch (e) {
486
+ log.error(`failed to import config ${configFile}`, e);
487
+ err = e;
488
+ }
489
+ }
490
+ if (!configFile.endsWith(".mjs")) {
491
+ try {
492
+ const _require = importMetaUrl ? esmRequire ?? (esmRequire = (0, import_module.createRequire)(importMetaUrl)) : require;
493
+ delete _require.cache[_require.resolve(configFile)];
494
+ const result = _require(configFile);
495
+ if (result != null) {
496
+ return __spreadProps(__spreadValues({}, result), {
497
+ configFile
498
+ });
499
+ } else {
500
+ throw new Error(`invalid export in ${configFile}`);
501
+ }
502
+ } catch (e) {
503
+ log.error(`failed to require config ${configFile}`, e);
504
+ if (!err) {
505
+ err = e;
506
+ }
507
+ }
508
+ }
509
+ throw err;
510
+ }
511
+ }
512
+ function findConfigToLoad(viteConfig, inlineOptions) {
513
+ const root = viteConfig.root || process.cwd();
514
+ if (inlineOptions.configFile) {
515
+ const abolutePath = import_path.default.isAbsolute(inlineOptions.configFile) ? inlineOptions.configFile : import_path.default.resolve(root, inlineOptions.configFile);
516
+ if (!import_fs.default.existsSync(abolutePath)) {
517
+ throw new Error(`failed to find svelte config file ${abolutePath}.`);
518
+ }
519
+ return abolutePath;
520
+ } else {
521
+ const existingKnownConfigFiles = knownSvelteConfigNames.map((candidate) => import_path.default.resolve(root, candidate)).filter((file) => import_fs.default.existsSync(file));
522
+ if (existingKnownConfigFiles.length === 0) {
523
+ log.debug(`no svelte config found at ${root}`);
524
+ return;
525
+ } else if (existingKnownConfigFiles.length > 1) {
526
+ log.warn(`found more than one svelte config file, using ${existingKnownConfigFiles[0]}. you should only have one!`, existingKnownConfigFiles);
527
+ }
528
+ return existingKnownConfigFiles[0];
529
+ }
530
+ }
531
+
532
+ // src/utils/constants.ts
533
+ var VITE_RESOLVE_MAIN_FIELDS = ["module", "jsnext:main", "jsnext"];
534
+ var SVELTE_RESOLVE_MAIN_FIELDS = ["svelte", ...VITE_RESOLVE_MAIN_FIELDS];
535
+ var SVELTE_IMPORTS = [
536
+ "svelte/animate",
537
+ "svelte/easing",
538
+ "svelte/internal",
539
+ "svelte/motion",
540
+ "svelte/ssr",
541
+ "svelte/store",
542
+ "svelte/transition",
543
+ "svelte"
544
+ ];
545
+ var SVELTE_HMR_IMPORTS = [
546
+ "svelte-hmr/runtime/hot-api-esm.js",
547
+ "svelte-hmr/runtime/proxy-adapter-dom.js",
548
+ "svelte-hmr"
549
+ ];
550
+
551
+ // src/utils/options.ts
552
+ var import_path3 = __toModule(require("path"));
553
+
554
+ // src/utils/dependencies.ts
555
+ var import_path2 = __toModule(require("path"));
556
+ var import_fs2 = __toModule(require("fs"));
557
+ var import_module2 = __toModule(require("module"));
558
+ function findRootSvelteDependencies(root, cwdFallback = true) {
559
+ log.debug(`findSvelteDependencies: searching svelte dependencies in ${root}`);
560
+ const pkgFile = import_path2.default.join(root, "package.json");
561
+ if (!import_fs2.default.existsSync(pkgFile)) {
562
+ if (cwdFallback) {
563
+ const cwd = process.cwd();
564
+ if (root !== cwd) {
565
+ log.debug(`no package.json found in vite root ${root}`);
566
+ return findRootSvelteDependencies(cwd, false);
567
+ }
568
+ }
569
+ log.warn(`no package.json found, findRootSvelteDependencies failed`);
570
+ return [];
571
+ }
572
+ const pkg = parsePkg(root);
573
+ if (!pkg) {
574
+ return [];
575
+ }
576
+ const deps = [
577
+ ...Object.keys(pkg.dependencies || {}),
578
+ ...Object.keys(pkg.devDependencies || {})
579
+ ].filter((dep) => !is_common_without_svelte_field(dep));
580
+ return getSvelteDependencies(deps, root);
581
+ }
582
+ function getSvelteDependencies(deps, pkgDir, path6 = []) {
583
+ const result = [];
584
+ const localRequire = (0, import_module2.createRequire)(`${pkgDir}/package.json`);
585
+ const resolvedDeps = deps.map((dep) => resolveDependencyData(dep, localRequire)).filter(Boolean);
586
+ for (const { pkg, dir } of resolvedDeps) {
587
+ const type = getSvelteDependencyType(pkg);
588
+ if (!type)
589
+ continue;
590
+ result.push({ name: pkg.name, type, pkg, dir, path: path6 });
591
+ if (type === "component-library" && pkg.dependencies) {
592
+ let dependencyNames = Object.keys(pkg.dependencies);
593
+ const circular = dependencyNames.filter((name) => path6.includes(name));
594
+ if (circular.length > 0) {
595
+ log.warn.enabled && log.warn(`skipping circular svelte dependencies in automated vite optimizeDeps handling`, circular.map((x) => path6.concat(x).join(">")));
596
+ dependencyNames = dependencyNames.filter((name) => !path6.includes(name));
597
+ }
598
+ if (path6.length === 3) {
599
+ log.debug.once(`encountered deep svelte dependency tree: ${path6.join(">")}`);
600
+ }
601
+ result.push(...getSvelteDependencies(dependencyNames, dir, path6.concat(pkg.name)));
602
+ }
603
+ }
604
+ return result;
605
+ }
606
+ function resolveDependencyData(dep, localRequire) {
607
+ try {
608
+ const pkgJson = `${dep}/package.json`;
609
+ const pkg = localRequire(pkgJson);
610
+ const dir = import_path2.default.dirname(localRequire.resolve(pkgJson));
611
+ return { dir, pkg };
612
+ } catch (e) {
613
+ log.debug.once(`dependency ${dep} does not export package.json`, e);
614
+ try {
615
+ let dir = import_path2.default.dirname(localRequire.resolve(dep));
616
+ while (dir) {
617
+ const pkg = parsePkg(dir, true);
618
+ if (pkg && pkg.name === dep) {
619
+ return { dir, pkg };
620
+ }
621
+ const parent = import_path2.default.dirname(dir);
622
+ if (parent === dir) {
623
+ break;
624
+ }
625
+ dir = parent;
626
+ }
627
+ } catch (e2) {
628
+ log.debug.once(`error while trying to find package.json of ${dep}`, e2);
629
+ }
630
+ }
631
+ log.debug.once(`failed to resolve ${dep}`);
632
+ }
633
+ function parsePkg(dir, silent = false) {
634
+ const pkgFile = import_path2.default.join(dir, "package.json");
635
+ try {
636
+ return JSON.parse(import_fs2.default.readFileSync(pkgFile, "utf-8"));
637
+ } catch (e) {
638
+ !silent && log.warn.enabled && log.warn(`failed to parse ${pkgFile}`, e);
639
+ }
640
+ }
641
+ function getSvelteDependencyType(pkg) {
642
+ if (isSvelteComponentLib(pkg)) {
643
+ return "component-library";
644
+ } else if (isSvelteLib(pkg)) {
645
+ return "js-library";
646
+ } else {
647
+ return void 0;
648
+ }
649
+ }
650
+ function isSvelteComponentLib(pkg) {
651
+ return !!pkg.svelte;
652
+ }
653
+ function isSvelteLib(pkg) {
654
+ var _a, _b;
655
+ return !!((_a = pkg.dependencies) == null ? void 0 : _a.svelte) || !!((_b = pkg.peerDependencies) == null ? void 0 : _b.svelte);
656
+ }
657
+ var COMMON_DEPENDENCIES_WITHOUT_SVELTE_FIELD = [
658
+ "@lukeed/uuid",
659
+ "@sveltejs/vite-plugin-svelte",
660
+ "@sveltejs/kit",
661
+ "autoprefixer",
662
+ "cookie",
663
+ "dotenv",
664
+ "esbuild",
665
+ "eslint",
666
+ "jest",
667
+ "mdsvex",
668
+ "postcss",
669
+ "prettier",
670
+ "svelte",
671
+ "svelte-check",
672
+ "svelte-hmr",
673
+ "svelte-preprocess",
674
+ "tslib",
675
+ "typescript",
676
+ "vite"
677
+ ];
678
+ var COMMON_PREFIXES_WITHOUT_SVELTE_FIELD = [
679
+ "@fontsource/",
680
+ "@postcss-plugins/",
681
+ "@rollup/",
682
+ "@sveltejs/adapter-",
683
+ "@types/",
684
+ "@typescript-eslint/",
685
+ "eslint-",
686
+ "jest-",
687
+ "postcss-plugin-",
688
+ "prettier-plugin-",
689
+ "rollup-plugin-",
690
+ "vite-plugin-"
691
+ ];
692
+ function is_common_without_svelte_field(dependency) {
693
+ return COMMON_DEPENDENCIES_WITHOUT_SVELTE_FIELD.includes(dependency) || COMMON_PREFIXES_WITHOUT_SVELTE_FIELD.some((prefix2) => prefix2.startsWith("@") ? dependency.startsWith(prefix2) : dependency.substring(dependency.lastIndexOf("/") + 1).startsWith(prefix2));
694
+ }
695
+ function needsOptimization(dep, localRequire) {
696
+ const depData = resolveDependencyData(dep, localRequire);
697
+ if (!depData)
698
+ return false;
699
+ const pkg = depData.pkg;
700
+ const isCjs = pkg.main && !pkg.module && !pkg.exports;
701
+ if (!isCjs)
702
+ return false;
703
+ const entryExt = import_path2.default.extname(pkg.main);
704
+ return !entryExt || entryExt === ".js" || entryExt === ".cjs";
705
+ }
706
+
707
+ // src/utils/options.ts
708
+ var import_module3 = __toModule(require("module"));
709
+
710
+ // src/utils/esbuild.ts
711
+ var import_fs3 = __toModule(require("fs"));
712
+ var import_compiler2 = __toModule(require("svelte/compiler"));
713
+
714
+ // src/utils/error.ts
715
+ function toRollupError(error) {
716
+ const { filename, frame, start, code, name } = error;
717
+ const rollupError = {
718
+ name,
719
+ id: filename,
720
+ message: buildExtendedLogMessage(error),
721
+ frame: formatFrameForVite(frame),
722
+ code,
723
+ stack: ""
724
+ };
725
+ if (start) {
726
+ rollupError.loc = {
727
+ line: start.line,
728
+ column: start.column,
729
+ file: filename
730
+ };
731
+ }
732
+ return rollupError;
733
+ }
734
+ function toESBuildError(error) {
735
+ const { filename, frame, start } = error;
736
+ const partialMessage = {
737
+ text: buildExtendedLogMessage(error)
738
+ };
739
+ if (start) {
740
+ partialMessage.location = {
741
+ line: start.line,
742
+ column: start.column,
743
+ file: filename,
744
+ lineText: lineFromFrame(start.line, frame)
745
+ };
746
+ }
747
+ return partialMessage;
748
+ }
749
+ function lineFromFrame(lineNo, frame) {
750
+ if (!frame) {
751
+ return "";
752
+ }
753
+ const lines = frame.split("\n");
754
+ const errorLine = lines.find((line) => line.trimStart().startsWith(`${lineNo}: `));
755
+ return errorLine ? errorLine.substring(errorLine.indexOf(": ") + 3) : "";
756
+ }
757
+ function formatFrameForVite(frame) {
758
+ if (!frame) {
759
+ return "";
760
+ }
761
+ return frame.split("\n").map((line) => line.match(/^\s+\^/) ? " " + line : " " + line.replace(":", " | ")).join("\n");
762
+ }
763
+
764
+ // src/utils/esbuild.ts
765
+ var facadeEsbuildSveltePluginName = "vite-plugin-svelte:facade";
766
+ function esbuildSveltePlugin(options) {
767
+ return {
768
+ name: "vite-plugin-svelte:optimize-svelte",
769
+ setup(build) {
770
+ disableVitePrebundleSvelte(build);
771
+ const svelteExtensions = (options.extensions ?? [".svelte"]).map((ext) => ext.slice(1));
772
+ const svelteFilter = new RegExp(`\\.(` + svelteExtensions.join("|") + `)(\\?.*)?$`);
773
+ build.onLoad({ filter: svelteFilter }, async ({ path: filename }) => {
774
+ const code = await import_fs3.promises.readFile(filename, "utf8");
775
+ try {
776
+ const contents = await compileSvelte(options, { filename, code });
777
+ return { contents };
778
+ } catch (e) {
779
+ return { errors: [toESBuildError(e)] };
780
+ }
781
+ });
782
+ }
783
+ };
784
+ }
785
+ function disableVitePrebundleSvelte(build) {
786
+ var _a;
787
+ const viteDepPrebundlePlugin = (_a = build.initialOptions.plugins) == null ? void 0 : _a.find((v) => v.name === "vite:dep-pre-bundle");
788
+ if (!viteDepPrebundlePlugin)
789
+ return;
790
+ const _setup = viteDepPrebundlePlugin.setup.bind(viteDepPrebundlePlugin);
791
+ viteDepPrebundlePlugin.setup = function(build2) {
792
+ const _onResolve = build2.onResolve.bind(build2);
793
+ build2.onResolve = function(options, callback) {
794
+ if (options.filter.source.includes("svelte")) {
795
+ options.filter = new RegExp(options.filter.source.replace("|svelte", ""), options.filter.flags);
796
+ }
797
+ return _onResolve(options, callback);
798
+ };
799
+ return _setup(build2);
800
+ };
801
+ }
802
+ async function compileSvelte(options, { filename, code }) {
803
+ var _a, _b;
804
+ const compileOptions = __spreadProps(__spreadValues({}, options.compilerOptions), {
805
+ css: true,
806
+ filename,
807
+ format: "esm",
808
+ generate: "dom"
809
+ });
810
+ let preprocessed;
811
+ if (options.preprocess) {
812
+ preprocessed = await (0, import_compiler2.preprocess)(code, options.preprocess, { filename });
813
+ if (preprocessed.map)
814
+ compileOptions.sourcemap = preprocessed.map;
815
+ }
816
+ const finalCode = preprocessed ? preprocessed.code : code;
817
+ const dynamicCompileOptions = await ((_b = (_a = options.experimental) == null ? void 0 : _a.dynamicCompileOptions) == null ? void 0 : _b.call(_a, {
818
+ filename,
819
+ code: finalCode,
820
+ compileOptions
821
+ }));
822
+ if (dynamicCompileOptions && log.debug.enabled) {
823
+ log.debug(`dynamic compile options for ${filename}: ${JSON.stringify(dynamicCompileOptions)}`);
824
+ }
825
+ const finalCompileOptions = dynamicCompileOptions ? __spreadValues(__spreadValues({}, compileOptions), dynamicCompileOptions) : compileOptions;
826
+ const compiled = (0, import_compiler2.compile)(finalCode, finalCompileOptions);
827
+ return compiled.js.code + "//# sourceMappingURL=" + compiled.js.map.toUrl();
828
+ }
829
+
830
+ // src/utils/preprocess.ts
831
+ var import_vite2 = __toModule(require("vite"));
832
+ var import_magic_string2 = __toModule(require("magic-string"));
833
+ var import_compiler3 = __toModule(require("svelte/compiler"));
834
+
835
+ // src/utils/sourcemap.ts
836
+ var import_magic_string = __toModule(require("magic-string"));
837
+ async function buildMagicString(from, to, options) {
838
+ let diff_match_patch, DIFF_DELETE, DIFF_INSERT;
839
+ try {
840
+ const dmpPkg = await import("diff-match-patch");
841
+ diff_match_patch = dmpPkg.diff_match_patch;
842
+ DIFF_INSERT = dmpPkg.DIFF_INSERT;
843
+ DIFF_DELETE = dmpPkg.DIFF_DELETE;
844
+ } catch (e) {
845
+ log.error.once('Failed to import optional dependency "diff-match-patch". Please install it to enable generated sourcemaps.');
846
+ return null;
847
+ }
848
+ const dmp = new diff_match_patch();
849
+ const diffs = dmp.diff_main(from, to);
850
+ dmp.diff_cleanupSemantic(diffs);
851
+ const m = new import_magic_string.default(from, options);
852
+ let pos = 0;
853
+ for (let i = 0; i < diffs.length; i++) {
854
+ const diff = diffs[i];
855
+ const nextDiff = diffs[i + 1];
856
+ if (diff[0] === DIFF_DELETE) {
857
+ if ((nextDiff == null ? void 0 : nextDiff[0]) === DIFF_INSERT) {
858
+ m.overwrite(pos, pos + diff[1].length, nextDiff[1]);
859
+ i++;
860
+ } else {
861
+ m.remove(pos, pos + diff[1].length);
862
+ }
863
+ pos += diff[1].length;
864
+ } else if (diff[0] === DIFF_INSERT) {
865
+ if (nextDiff) {
866
+ m.appendRight(pos, diff[1]);
867
+ } else {
868
+ m.append(diff[1]);
869
+ }
870
+ } else {
871
+ pos += diff[1].length;
872
+ }
873
+ }
874
+ return m;
875
+ }
876
+ async function buildSourceMap(from, to, filename) {
877
+ const m = await buildMagicString(from, to, { filename });
878
+ return m ? m.generateDecodedMap({ source: filename, hires: true, includeContent: false }) : null;
879
+ }
880
+
881
+ // src/utils/preprocess.ts
882
+ var supportedStyleLangs = ["css", "less", "sass", "scss", "styl", "stylus", "postcss"];
883
+ var supportedScriptLangs = ["ts"];
884
+ function createViteScriptPreprocessor() {
885
+ return async ({ attributes, content, filename = "" }) => {
886
+ const lang = attributes.lang;
887
+ if (!supportedScriptLangs.includes(lang))
888
+ return;
889
+ const transformResult = await (0, import_vite2.transformWithEsbuild)(content, filename, {
890
+ loader: lang,
891
+ tsconfigRaw: {
892
+ compilerOptions: {
893
+ importsNotUsedAsValues: "preserve"
894
+ }
895
+ }
896
+ });
897
+ return {
898
+ code: transformResult.code,
899
+ map: transformResult.map
900
+ };
901
+ };
902
+ }
903
+ function createViteStylePreprocessor(config) {
904
+ const pluginName = "vite:css";
905
+ const plugin = config.plugins.find((p) => p.name === pluginName);
906
+ if (!plugin) {
907
+ throw new Error(`failed to find plugin ${pluginName}`);
908
+ }
909
+ if (!plugin.transform) {
910
+ throw new Error(`plugin ${pluginName} has no transform`);
911
+ }
912
+ const pluginTransform = plugin.transform.bind(null);
913
+ return async ({ attributes, content, filename = "" }) => {
914
+ var _a, _b;
915
+ const lang = attributes.lang;
916
+ if (!supportedStyleLangs.includes(lang))
917
+ return;
918
+ const moduleId = `${filename}.${lang}`;
919
+ const transformResult = await pluginTransform(content, moduleId);
920
+ if (((_b = (_a = transformResult.map) == null ? void 0 : _a.sources) == null ? void 0 : _b[0]) === moduleId) {
921
+ transformResult.map.sources[0] = filename;
922
+ }
923
+ return {
924
+ code: transformResult.code,
925
+ map: transformResult.map ?? void 0
926
+ };
927
+ };
928
+ }
929
+ function createVitePreprocessorGroup(config) {
930
+ return {
931
+ markup({ content, filename }) {
932
+ return (0, import_compiler3.preprocess)(content, {
933
+ script: createViteScriptPreprocessor(),
934
+ style: createViteStylePreprocessor(config)
935
+ }, { filename });
936
+ }
937
+ };
938
+ }
939
+ function createInjectScopeEverythingRulePreprocessorGroup() {
940
+ return {
941
+ style({ content, filename }) {
942
+ const s = new import_magic_string2.default(content);
943
+ s.append(" *{}");
944
+ return {
945
+ code: s.toString(),
946
+ map: s.generateDecodedMap({ source: filename, hires: true })
947
+ };
948
+ }
949
+ };
950
+ }
951
+ function buildExtraPreprocessors(options, config) {
952
+ var _a, _b;
953
+ const prependPreprocessors = [];
954
+ const appendPreprocessors = [];
955
+ if ((_a = options.experimental) == null ? void 0 : _a.useVitePreprocess) {
956
+ log.debug("adding vite preprocessor");
957
+ prependPreprocessors.push(createVitePreprocessorGroup(config));
958
+ }
959
+ const pluginsWithPreprocessorsDeprecated = config.plugins.filter((p) => p == null ? void 0 : p.sveltePreprocess);
960
+ if (pluginsWithPreprocessorsDeprecated.length > 0) {
961
+ 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(", ")}`);
962
+ pluginsWithPreprocessorsDeprecated.forEach((p) => {
963
+ if (!p.api) {
964
+ p.api = {};
965
+ }
966
+ if (p.api.sveltePreprocess === void 0) {
967
+ p.api.sveltePreprocess = p.sveltePreprocess;
968
+ } else {
969
+ log.error(`ignoring plugin.sveltePreprocess of ${p.name} because it already defined plugin.api.sveltePreprocess.`);
970
+ }
971
+ });
972
+ }
973
+ const pluginsWithPreprocessors = config.plugins.filter((p) => {
974
+ var _a2;
975
+ return (_a2 = p == null ? void 0 : p.api) == null ? void 0 : _a2.sveltePreprocess;
976
+ });
977
+ const ignored = [], included = [];
978
+ for (const p of pluginsWithPreprocessors) {
979
+ if (options.ignorePluginPreprocessors === true || Array.isArray(options.ignorePluginPreprocessors) && ((_b = options.ignorePluginPreprocessors) == null ? void 0 : _b.includes(p.name))) {
980
+ ignored.push(p);
981
+ } else {
982
+ included.push(p);
983
+ }
984
+ }
985
+ if (ignored.length > 0) {
986
+ log.debug(`Ignoring svelte preprocessors defined by these vite plugins: ${ignored.map((p) => p.name).join(", ")}`);
987
+ }
988
+ if (included.length > 0) {
989
+ log.debug(`Adding svelte preprocessors defined by these vite plugins: ${included.map((p) => p.name).join(", ")}`);
990
+ appendPreprocessors.push(...pluginsWithPreprocessors.map((p) => p.api.sveltePreprocess));
991
+ }
992
+ if (options.hot && options.emitCss) {
993
+ appendPreprocessors.push(createInjectScopeEverythingRulePreprocessorGroup());
994
+ }
995
+ return { prependPreprocessors, appendPreprocessors };
996
+ }
997
+ function addExtraPreprocessors(options, config) {
998
+ var _a;
999
+ const { prependPreprocessors, appendPreprocessors } = buildExtraPreprocessors(options, config);
1000
+ if (prependPreprocessors.length > 0 || appendPreprocessors.length > 0) {
1001
+ if (!options.preprocess) {
1002
+ options.preprocess = [...prependPreprocessors, ...appendPreprocessors];
1003
+ } else if (Array.isArray(options.preprocess)) {
1004
+ options.preprocess.unshift(...prependPreprocessors);
1005
+ options.preprocess.push(...appendPreprocessors);
1006
+ } else {
1007
+ options.preprocess = [...prependPreprocessors, options.preprocess, ...appendPreprocessors];
1008
+ }
1009
+ }
1010
+ const generateMissingSourceMaps = !!((_a = options.experimental) == null ? void 0 : _a.generateMissingPreprocessorSourcemaps);
1011
+ if (options.preprocess && generateMissingSourceMaps) {
1012
+ options.preprocess = Array.isArray(options.preprocess) ? options.preprocess.map((p, i) => validateSourceMapOutputWrapper(p, i)) : validateSourceMapOutputWrapper(options.preprocess, 0);
1013
+ }
1014
+ }
1015
+ function validateSourceMapOutputWrapper(group, i) {
1016
+ const wrapper = {};
1017
+ for (const [processorType, processorFn] of Object.entries(group)) {
1018
+ wrapper[processorType] = async (options) => {
1019
+ var _a;
1020
+ const result = await processorFn(options);
1021
+ if (result && result.code !== options.content) {
1022
+ let invalidMap = false;
1023
+ if (!result.map) {
1024
+ invalidMap = true;
1025
+ log.warn.enabled && log.warn.once(`preprocessor at index ${i} did not return a sourcemap for ${processorType} transform`, {
1026
+ filename: options.filename,
1027
+ type: processorType,
1028
+ processor: processorFn.toString()
1029
+ });
1030
+ } else if (((_a = result.map) == null ? void 0 : _a.mappings) === "") {
1031
+ invalidMap = true;
1032
+ log.warn.enabled && log.warn.once(`preprocessor at index ${i} returned an invalid empty sourcemap for ${processorType} transform`, {
1033
+ filename: options.filename,
1034
+ type: processorType,
1035
+ processor: processorFn.toString()
1036
+ });
1037
+ }
1038
+ if (invalidMap) {
1039
+ try {
1040
+ const map = await buildSourceMap(options.content, result.code, options.filename);
1041
+ if (map) {
1042
+ log.debug.enabled && log.debug(`adding generated sourcemap to preprocesor result for ${options.filename}`);
1043
+ result.map = map;
1044
+ }
1045
+ } catch (e) {
1046
+ log.error(`failed to build sourcemap`, e);
1047
+ }
1048
+ }
1049
+ }
1050
+ return result;
1051
+ };
1052
+ }
1053
+ return wrapper;
1054
+ }
1055
+
1056
+ // src/utils/options.ts
1057
+ var knownOptions = new Set([
1058
+ "configFile",
1059
+ "include",
1060
+ "exclude",
1061
+ "extensions",
1062
+ "emitCss",
1063
+ "compilerOptions",
1064
+ "onwarn",
1065
+ "preprocess",
1066
+ "hot",
1067
+ "ignorePluginPreprocessors",
1068
+ "disableDependencyReinclusion",
1069
+ "experimental"
1070
+ ]);
1071
+ function validateInlineOptions(inlineOptions) {
1072
+ const invalidKeys = Object.keys(inlineOptions || {}).filter((key) => !knownOptions.has(key));
1073
+ if (invalidKeys.length) {
1074
+ log.warn(`invalid plugin options "${invalidKeys.join(", ")}" in config`, inlineOptions);
1075
+ }
1076
+ }
1077
+ async function preResolveOptions(inlineOptions = {}, viteUserConfig, viteEnv) {
1078
+ const viteConfigWithResolvedRoot = __spreadProps(__spreadValues({}, viteUserConfig), {
1079
+ root: resolveViteRoot(viteUserConfig)
1080
+ });
1081
+ const defaultOptions = {
1082
+ extensions: [".svelte"],
1083
+ emitCss: true,
1084
+ compilerOptions: {
1085
+ format: "esm"
1086
+ }
1087
+ };
1088
+ const svelteConfig = await loadSvelteConfig(viteConfigWithResolvedRoot, inlineOptions);
1089
+ const merged = __spreadProps(__spreadValues(__spreadValues(__spreadValues({}, defaultOptions), svelteConfig), inlineOptions), {
1090
+ compilerOptions: __spreadValues(__spreadValues(__spreadValues({}, defaultOptions == null ? void 0 : defaultOptions.compilerOptions), svelteConfig == null ? void 0 : svelteConfig.compilerOptions), inlineOptions == null ? void 0 : inlineOptions.compilerOptions),
1091
+ experimental: __spreadValues(__spreadValues(__spreadValues({}, defaultOptions == null ? void 0 : defaultOptions.experimental), svelteConfig == null ? void 0 : svelteConfig.experimental), inlineOptions == null ? void 0 : inlineOptions.experimental),
1092
+ root: viteConfigWithResolvedRoot.root,
1093
+ isBuild: viteEnv.command === "build",
1094
+ isServe: viteEnv.command === "serve"
1095
+ });
1096
+ if (svelteConfig == null ? void 0 : svelteConfig.configFile) {
1097
+ merged.configFile = svelteConfig.configFile;
1098
+ }
1099
+ return merged;
1100
+ }
1101
+ function resolveOptions(preResolveOptions2, viteConfig) {
1102
+ const defaultOptions = {
1103
+ hot: viteConfig.isProduction ? false : { injectCss: !preResolveOptions2.emitCss },
1104
+ compilerOptions: {
1105
+ css: !preResolveOptions2.emitCss,
1106
+ dev: !viteConfig.isProduction
1107
+ }
1108
+ };
1109
+ const merged = __spreadProps(__spreadValues(__spreadValues({}, defaultOptions), preResolveOptions2), {
1110
+ compilerOptions: __spreadValues(__spreadValues({}, defaultOptions.compilerOptions), preResolveOptions2.compilerOptions),
1111
+ isProduction: viteConfig.isProduction
1112
+ });
1113
+ addExtraPreprocessors(merged, viteConfig);
1114
+ enforceOptionsForHmr(merged);
1115
+ enforceOptionsForProduction(merged);
1116
+ return merged;
1117
+ }
1118
+ function enforceOptionsForHmr(options) {
1119
+ if (options.hot) {
1120
+ if (!options.compilerOptions.dev) {
1121
+ log.warn("hmr is enabled but compilerOptions.dev is false, forcing it to true");
1122
+ options.compilerOptions.dev = true;
1123
+ }
1124
+ if (options.emitCss) {
1125
+ if (options.hot !== true && options.hot.injectCss) {
1126
+ log.warn("hmr and emitCss are enabled but hot.injectCss is true, forcing it to false");
1127
+ options.hot.injectCss = false;
1128
+ }
1129
+ if (options.compilerOptions.css) {
1130
+ log.warn("hmr and emitCss are enabled but compilerOptions.css is true, forcing it to false");
1131
+ options.compilerOptions.css = false;
1132
+ }
1133
+ } else {
1134
+ if (options.hot === true || !options.hot.injectCss) {
1135
+ log.warn("hmr with emitCss disabled requires option hot.injectCss to be enabled, forcing it to true");
1136
+ if (options.hot === true) {
1137
+ options.hot = { injectCss: true };
1138
+ } else {
1139
+ options.hot.injectCss = true;
1140
+ }
1141
+ }
1142
+ if (!options.compilerOptions.css) {
1143
+ log.warn("hmr with emitCss disabled requires compilerOptions.css to be enabled, forcing it to true");
1144
+ options.compilerOptions.css = true;
1145
+ }
1146
+ }
1147
+ }
1148
+ }
1149
+ function enforceOptionsForProduction(options) {
1150
+ if (options.isProduction) {
1151
+ if (options.hot) {
1152
+ log.warn("options.hot is enabled but does not work on production build, forcing it to false");
1153
+ options.hot = false;
1154
+ }
1155
+ if (options.compilerOptions.dev) {
1156
+ log.warn("you are building for production but compilerOptions.dev is true, forcing it to false");
1157
+ options.compilerOptions.dev = false;
1158
+ }
1159
+ }
1160
+ }
1161
+ function resolveViteRoot(viteConfig) {
1162
+ return (0, import_vite3.normalizePath)(viteConfig.root ? import_path3.default.resolve(viteConfig.root) : process.cwd());
1163
+ }
1164
+ function buildExtraViteConfig(options, config, configEnv) {
1165
+ const svelteDeps = findRootSvelteDependencies(options.root);
1166
+ const extraViteConfig = {
1167
+ resolve: {
1168
+ mainFields: [...SVELTE_RESOLVE_MAIN_FIELDS],
1169
+ dedupe: [...SVELTE_IMPORTS, ...SVELTE_HMR_IMPORTS]
1170
+ }
1171
+ };
1172
+ if (configEnv.command === "serve") {
1173
+ extraViteConfig.optimizeDeps = buildOptimizeDepsForSvelte(svelteDeps, options, config.optimizeDeps);
1174
+ }
1175
+ extraViteConfig.ssr = buildSSROptionsForSvelte(svelteDeps, options, config);
1176
+ return extraViteConfig;
1177
+ }
1178
+ function buildOptimizeDepsForSvelte(svelteDeps, options, optimizeDeps) {
1179
+ const include = [];
1180
+ const exclude = ["svelte-hmr"];
1181
+ const isIncluded = (dep) => {
1182
+ var _a;
1183
+ return include.includes(dep) || ((_a = optimizeDeps == null ? void 0 : optimizeDeps.include) == null ? void 0 : _a.includes(dep));
1184
+ };
1185
+ const isExcluded = (dep) => {
1186
+ var _a;
1187
+ return exclude.includes(dep) || ((_a = optimizeDeps == null ? void 0 : optimizeDeps.exclude) == null ? void 0 : _a.some((id) => dep === id || id.startsWith(`${dep}/`)));
1188
+ };
1189
+ if (!isExcluded("svelte")) {
1190
+ const svelteImportsToInclude = SVELTE_IMPORTS.filter((x) => x !== "svelte/ssr");
1191
+ log.debug(`adding bare svelte packages to optimizeDeps.include: ${svelteImportsToInclude.join(", ")} `);
1192
+ include.push(...svelteImportsToInclude.filter((x) => !isIncluded(x)));
1193
+ } else {
1194
+ log.debug('"svelte" is excluded in optimizeDeps.exclude, skipped adding it to include.');
1195
+ }
1196
+ if (options.experimental.prebundleSvelteLibraries) {
1197
+ return {
1198
+ include,
1199
+ exclude,
1200
+ esbuildOptions: {
1201
+ plugins: [{ name: facadeEsbuildSveltePluginName, setup: () => {
1202
+ } }]
1203
+ }
1204
+ };
1205
+ }
1206
+ svelteDeps = svelteDeps.filter((dep) => dep.type === "component-library");
1207
+ const svelteDepsToExclude = Array.from(new Set(svelteDeps.map((dep) => dep.name))).filter((dep) => !isIncluded(dep));
1208
+ log.debug(`automatically excluding found svelte dependencies: ${svelteDepsToExclude.join(", ")}`);
1209
+ exclude.push(...svelteDepsToExclude.filter((x) => !isExcluded(x)));
1210
+ if (options.disableDependencyReinclusion !== true) {
1211
+ const disabledReinclusions = options.disableDependencyReinclusion || [];
1212
+ if (disabledReinclusions.length > 0) {
1213
+ log.debug(`not reincluding transitive dependencies of`, disabledReinclusions);
1214
+ }
1215
+ const transitiveDepsToInclude = svelteDeps.filter((dep) => !disabledReinclusions.includes(dep.name) && isExcluded(dep.name)).flatMap((dep) => {
1216
+ const localRequire = (0, import_module3.createRequire)(`${dep.dir}/package.json`);
1217
+ return Object.keys(dep.pkg.dependencies || {}).filter((depOfDep) => !isExcluded(depOfDep) && needsOptimization(depOfDep, localRequire)).map((depOfDep) => dep.path.concat(dep.name, depOfDep).join(" > "));
1218
+ });
1219
+ log.debug(`reincluding transitive dependencies of excluded svelte dependencies`, transitiveDepsToInclude);
1220
+ include.push(...transitiveDepsToInclude);
1221
+ }
1222
+ return { include, exclude };
1223
+ }
1224
+ function buildSSROptionsForSvelte(svelteDeps, options, config) {
1225
+ var _a, _b, _c;
1226
+ const noExternal = [];
1227
+ if (options.isBuild && ((_a = config.build) == null ? void 0 : _a.ssr)) {
1228
+ if (!((_c = (_b = config.ssr) == null ? void 0 : _b.external) == null ? void 0 : _c.includes("svelte"))) {
1229
+ noExternal.push("svelte");
1230
+ }
1231
+ } else {
1232
+ svelteDeps = svelteDeps.filter((dep) => dep.type === "component-library");
1233
+ }
1234
+ noExternal.push(...Array.from(new Set(svelteDeps.map((s) => s.name))).filter((x) => {
1235
+ var _a2, _b2, _c2, _d;
1236
+ return !((_b2 = (_a2 = config.ssr) == null ? void 0 : _a2.external) == null ? void 0 : _b2.includes(x)) && !((_d = (_c2 = config.optimizeDeps) == null ? void 0 : _c2.include) == null ? void 0 : _d.includes(x));
1237
+ }));
1238
+ return {
1239
+ noExternal
1240
+ };
1241
+ }
1242
+ function patchResolvedViteConfig(viteConfig, options) {
1243
+ var _a, _b;
1244
+ const facadeEsbuildSveltePlugin = (_b = (_a = viteConfig.optimizeDeps.esbuildOptions) == null ? void 0 : _a.plugins) == null ? void 0 : _b.find((plugin) => plugin.name === facadeEsbuildSveltePluginName);
1245
+ if (facadeEsbuildSveltePlugin) {
1246
+ Object.assign(facadeEsbuildSveltePlugin, esbuildSveltePlugin(options));
1247
+ }
1248
+ }
1249
+
1250
+ // src/utils/vite-plugin-svelte-cache.ts
1251
+ var VitePluginSvelteCache = class {
1252
+ constructor() {
1253
+ this._css = new Map();
1254
+ this._js = new Map();
1255
+ this._dependencies = new Map();
1256
+ this._dependants = new Map();
1257
+ }
1258
+ update(compileData) {
1259
+ this.updateCSS(compileData);
1260
+ this.updateJS(compileData);
1261
+ this.updateDependencies(compileData);
1262
+ }
1263
+ updateCSS(compileData) {
1264
+ this._css.set(compileData.normalizedFilename, compileData.compiled.css);
1265
+ }
1266
+ updateJS(compileData) {
1267
+ if (!compileData.ssr) {
1268
+ this._js.set(compileData.normalizedFilename, compileData.compiled.js);
1269
+ }
1270
+ }
1271
+ updateDependencies(compileData) {
1272
+ const id = compileData.normalizedFilename;
1273
+ const prevDependencies = this._dependencies.get(id) || [];
1274
+ const dependencies = compileData.dependencies;
1275
+ this._dependencies.set(id, dependencies);
1276
+ const removed = prevDependencies.filter((d) => !dependencies.includes(d));
1277
+ const added = dependencies.filter((d) => !prevDependencies.includes(d));
1278
+ added.forEach((d) => {
1279
+ if (!this._dependants.has(d)) {
1280
+ this._dependants.set(d, new Set());
1281
+ }
1282
+ this._dependants.get(d).add(compileData.filename);
1283
+ });
1284
+ removed.forEach((d) => {
1285
+ this._dependants.get(d).delete(compileData.filename);
1286
+ });
1287
+ }
1288
+ remove(svelteRequest) {
1289
+ const id = svelteRequest.normalizedFilename;
1290
+ let removed = false;
1291
+ if (this._js.delete(id)) {
1292
+ removed = true;
1293
+ }
1294
+ if (this._css.delete(id)) {
1295
+ removed = true;
1296
+ }
1297
+ const dependencies = this._dependencies.get(id);
1298
+ if (dependencies) {
1299
+ removed = true;
1300
+ dependencies.forEach((d) => {
1301
+ const dependants = this._dependants.get(d);
1302
+ if (dependants && dependants.has(svelteRequest.filename)) {
1303
+ dependants.delete(svelteRequest.filename);
1304
+ }
1305
+ });
1306
+ this._dependencies.delete(id);
1307
+ }
1308
+ return removed;
1309
+ }
1310
+ getCSS(svelteRequest) {
1311
+ return this._css.get(svelteRequest.normalizedFilename);
1312
+ }
1313
+ getJS(svelteRequest) {
1314
+ if (!svelteRequest.ssr) {
1315
+ return this._js.get(svelteRequest.normalizedFilename);
1316
+ }
1317
+ }
1318
+ getDependants(path6) {
1319
+ const dependants = this._dependants.get(path6);
1320
+ return dependants ? [...dependants] : [];
1321
+ }
1322
+ };
1323
+
1324
+ // src/utils/watch.ts
1325
+ var import_fs4 = __toModule(require("fs"));
1326
+ var import_path4 = __toModule(require("path"));
1327
+ function setupWatchers(options, cache, requestParser) {
1328
+ const { server, configFile: svelteConfigFile } = options;
1329
+ if (!server) {
1330
+ return;
1331
+ }
1332
+ const { watcher, ws } = server;
1333
+ const { root, server: serverConfig } = server.config;
1334
+ const emitChangeEventOnDependants = (filename) => {
1335
+ const dependants = cache.getDependants(filename);
1336
+ dependants.forEach((dependant) => {
1337
+ if (import_fs4.default.existsSync(dependant)) {
1338
+ log.debug(`emitting virtual change event for "${dependant}" because depdendency "${filename}" changed`);
1339
+ watcher.emit("change", dependant);
1340
+ }
1341
+ });
1342
+ };
1343
+ const removeUnlinkedFromCache = (filename) => {
1344
+ const svelteRequest = requestParser(filename, false);
1345
+ if (svelteRequest) {
1346
+ const removedFromCache = cache.remove(svelteRequest);
1347
+ if (removedFromCache) {
1348
+ log.debug(`cleared VitePluginSvelteCache for deleted file ${filename}`);
1349
+ }
1350
+ }
1351
+ };
1352
+ const triggerViteRestart = (filename) => {
1353
+ var _a;
1354
+ if (serverConfig.middlewareMode) {
1355
+ const message = "Svelte config change detected, restart your dev process to apply the changes.";
1356
+ log.info(message, filename);
1357
+ ws.send({
1358
+ type: "error",
1359
+ err: { message, stack: "", plugin: "vite-plugin-svelte", id: filename }
1360
+ });
1361
+ } else {
1362
+ log.info(`svelte config changed: restarting vite server. - file: ${filename}`);
1363
+ server.restart(!!((_a = options.experimental) == null ? void 0 : _a.prebundleSvelteLibraries));
1364
+ }
1365
+ };
1366
+ const possibleSvelteConfigs = knownSvelteConfigNames.map((cfg) => import_path4.default.join(root, cfg));
1367
+ const restartOnConfigAdd = (filename) => {
1368
+ if (possibleSvelteConfigs.includes(filename)) {
1369
+ triggerViteRestart(filename);
1370
+ }
1371
+ };
1372
+ const restartOnConfigChange = (filename) => {
1373
+ if (filename === svelteConfigFile) {
1374
+ triggerViteRestart(filename);
1375
+ }
1376
+ };
1377
+ const listenerCollection = {
1378
+ add: [],
1379
+ change: [emitChangeEventOnDependants],
1380
+ unlink: [removeUnlinkedFromCache, emitChangeEventOnDependants]
1381
+ };
1382
+ if (svelteConfigFile) {
1383
+ listenerCollection.change.push(restartOnConfigChange);
1384
+ listenerCollection.unlink.push(restartOnConfigChange);
1385
+ } else {
1386
+ listenerCollection.add.push(restartOnConfigAdd);
1387
+ }
1388
+ Object.entries(listenerCollection).forEach(([evt, listeners]) => {
1389
+ if (listeners.length > 0) {
1390
+ watcher.on(evt, (filename) => listeners.forEach((listener) => listener(filename)));
1391
+ }
1392
+ });
1393
+ }
1394
+ function ensureWatchedFile(watcher, file, root) {
1395
+ if (file && !file.startsWith(root + "/") && !file.includes("\0") && import_fs4.default.existsSync(file)) {
1396
+ watcher.add(import_path4.default.resolve(file));
1397
+ }
1398
+ }
1399
+
1400
+ // src/utils/resolve.ts
1401
+ var import_path5 = __toModule(require("path"));
1402
+ var import_fs5 = __toModule(require("fs"));
1403
+ var import_require_relative = __toModule(require("require-relative"));
1404
+ function resolveViaPackageJsonSvelte(importee, importer) {
1405
+ if (importer && isBareImport(importee)) {
1406
+ const importeePkgFile = import_require_relative.default.resolve(`${importee}/package.json`, import_path5.default.dirname(importer));
1407
+ const importeePkg = JSON.parse(import_fs5.default.readFileSync(importeePkgFile, { encoding: "utf-8" }));
1408
+ if (importeePkg.svelte) {
1409
+ return import_path5.default.resolve(import_path5.default.dirname(importeePkgFile), importeePkg.svelte);
1410
+ }
1411
+ }
1412
+ }
1413
+ function isBareImport(importee) {
1414
+ if (!importee || importee[0] === "." || importee[0] === "\0" || importee.includes(":") || import_path5.default.isAbsolute(importee)) {
1415
+ return false;
1416
+ }
1417
+ const parts = importee.split("/");
1418
+ switch (parts.length) {
1419
+ case 1:
1420
+ return true;
1421
+ case 2:
1422
+ return parts[0].startsWith("@");
1423
+ default:
1424
+ return false;
1425
+ }
1426
+ }
1427
+
1428
+ // src/index.ts
1429
+ function svelte(inlineOptions) {
1430
+ if (process.env.DEBUG != null) {
1431
+ log.setLevel("debug");
1432
+ }
1433
+ validateInlineOptions(inlineOptions);
1434
+ const cache = new VitePluginSvelteCache();
1435
+ const pkg_export_errors = new Set();
1436
+ let requestParser;
1437
+ let options;
1438
+ let viteConfig;
1439
+ let compileSvelte2;
1440
+ let resolvedSvelteSSR;
1441
+ return {
1442
+ name: "vite-plugin-svelte",
1443
+ enforce: "pre",
1444
+ async config(config, configEnv) {
1445
+ if (process.env.DEBUG) {
1446
+ log.setLevel("debug");
1447
+ } else if (config.logLevel) {
1448
+ log.setLevel(config.logLevel);
1449
+ }
1450
+ options = await preResolveOptions(inlineOptions, config, configEnv);
1451
+ const extraViteConfig = buildExtraViteConfig(options, config, configEnv);
1452
+ log.debug("additional vite config", extraViteConfig);
1453
+ return extraViteConfig;
1454
+ },
1455
+ async configResolved(config) {
1456
+ options = resolveOptions(options, config);
1457
+ patchResolvedViteConfig(config, options);
1458
+ requestParser = buildIdParser(options);
1459
+ compileSvelte2 = createCompileSvelte(options);
1460
+ viteConfig = config;
1461
+ log.debug("resolved options", options);
1462
+ },
1463
+ configureServer(server) {
1464
+ options.server = server;
1465
+ setupWatchers(options, cache, requestParser);
1466
+ },
1467
+ load(id, opts) {
1468
+ const ssr = opts === true || (opts == null ? void 0 : opts.ssr);
1469
+ const svelteRequest = requestParser(id, !!ssr);
1470
+ if (svelteRequest) {
1471
+ const { filename, query } = svelteRequest;
1472
+ if (query.svelte && query.type === "style") {
1473
+ const css = cache.getCSS(svelteRequest);
1474
+ if (css) {
1475
+ log.debug(`load returns css for ${filename}`);
1476
+ return css;
1477
+ }
1478
+ }
1479
+ if (viteConfig.assetsInclude(filename)) {
1480
+ log.debug(`load returns raw content for ${filename}`);
1481
+ return import_fs6.default.readFileSync(filename, "utf-8");
1482
+ }
1483
+ }
1484
+ },
1485
+ async resolveId(importee, importer, opts) {
1486
+ const ssr = !!(opts == null ? void 0 : opts.ssr);
1487
+ const svelteRequest = requestParser(importee, ssr);
1488
+ if (svelteRequest == null ? void 0 : svelteRequest.query.svelte) {
1489
+ if (svelteRequest.query.type === "style") {
1490
+ log.debug(`resolveId resolved virtual css module ${svelteRequest.cssId}`);
1491
+ return svelteRequest.cssId;
1492
+ }
1493
+ log.debug(`resolveId resolved ${importee}`);
1494
+ return importee;
1495
+ }
1496
+ if (ssr && importee === "svelte") {
1497
+ if (!resolvedSvelteSSR) {
1498
+ resolvedSvelteSSR = this.resolve("svelte/ssr", void 0, { skipSelf: true }).then((svelteSSR) => {
1499
+ log.debug("resolved svelte to svelte/ssr");
1500
+ return svelteSSR;
1501
+ }, (err) => {
1502
+ log.debug("failed to resolve svelte to svelte/ssr. Update svelte to a version that exports it", err);
1503
+ return null;
1504
+ });
1505
+ }
1506
+ return resolvedSvelteSSR;
1507
+ }
1508
+ try {
1509
+ const resolved = resolveViaPackageJsonSvelte(importee, importer);
1510
+ if (resolved) {
1511
+ log.debug(`resolveId resolved ${resolved} via package.json svelte field of ${importee}`);
1512
+ return resolved;
1513
+ }
1514
+ } catch (err) {
1515
+ switch (err.code) {
1516
+ case "ERR_PACKAGE_PATH_NOT_EXPORTED":
1517
+ pkg_export_errors.add(importee);
1518
+ return null;
1519
+ case "MODULE_NOT_FOUND":
1520
+ return null;
1521
+ default:
1522
+ throw err;
1523
+ }
1524
+ }
1525
+ },
1526
+ async transform(code, id, opts) {
1527
+ var _a;
1528
+ const ssr = !!(opts == null ? void 0 : opts.ssr);
1529
+ const svelteRequest = requestParser(id, ssr);
1530
+ if (!svelteRequest) {
1531
+ return;
1532
+ }
1533
+ const { filename, query } = svelteRequest;
1534
+ if (query.svelte) {
1535
+ if (query.type === "style") {
1536
+ const css = cache.getCSS(svelteRequest);
1537
+ if (css) {
1538
+ log.debug(`transform returns css for ${filename}`);
1539
+ return css;
1540
+ }
1541
+ }
1542
+ log.error("failed to transform tagged svelte request", svelteRequest);
1543
+ throw new Error(`failed to transform tagged svelte request for id ${id}`);
1544
+ }
1545
+ let compileData;
1546
+ try {
1547
+ compileData = await compileSvelte2(svelteRequest, code, options);
1548
+ } catch (e) {
1549
+ throw toRollupError(e);
1550
+ }
1551
+ logCompilerWarnings(compileData.compiled.warnings, options);
1552
+ cache.update(compileData);
1553
+ if (((_a = compileData.dependencies) == null ? void 0 : _a.length) && options.server) {
1554
+ compileData.dependencies.forEach((d) => {
1555
+ ensureWatchedFile(options.server.watcher, d, options.root);
1556
+ });
1557
+ }
1558
+ log.debug(`transform returns compiled js for ${filename}`);
1559
+ return compileData.compiled.js;
1560
+ },
1561
+ handleHotUpdate(ctx) {
1562
+ if (!options.hot || !options.emitCss) {
1563
+ return;
1564
+ }
1565
+ const svelteRequest = requestParser(ctx.file, false, ctx.timestamp);
1566
+ if (svelteRequest) {
1567
+ return handleHotUpdate(compileSvelte2, ctx, svelteRequest, cache, options);
1568
+ }
1569
+ },
1570
+ buildEnd() {
1571
+ if (pkg_export_errors.size > 0) {
1572
+ 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"));
1573
+ }
1574
+ }
1575
+ };
1576
+ }
1577
+ // Annotate the CommonJS export names for ESM import in node:
1578
+ 0 && (module.exports = {
1579
+ svelte
1580
+ });
1581
+ //# sourceMappingURL=index.cjs.map