@unocss/vite 0.62.3 → 0.63.0

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.d.mts CHANGED
@@ -1,6 +1,6 @@
1
+ import { UserConfig, UnocssPluginContext, UserConfigDefaults } from '@unocss/core';
1
2
  import * as vite from 'vite';
2
3
  import { Plugin } from 'vite';
3
- import { UserConfig, UnocssPluginContext, UserConfigDefaults } from '@unocss/core';
4
4
 
5
5
  interface VitePluginConfig<Theme extends object = object> extends UserConfig<Theme> {
6
6
  /**
@@ -58,10 +58,10 @@ interface VitePluginConfig<Theme extends object = object> extends UserConfig<The
58
58
 
59
59
  declare function ChunkModeBuildPlugin({ uno, filter }: UnocssPluginContext): Plugin;
60
60
 
61
- declare function GlobalModeDevPlugin({ uno, tokens, tasks, flushTasks, affectedModules, onInvalidate, extract, filter, getConfig }: UnocssPluginContext): Plugin[];
62
-
63
61
  declare function GlobalModeBuildPlugin(ctx: UnocssPluginContext<VitePluginConfig>): Plugin[];
64
62
 
63
+ declare function GlobalModeDevPlugin({ uno, tokens, tasks, flushTasks, affectedModules, onInvalidate, extract, filter, getConfig }: UnocssPluginContext): Plugin[];
64
+
65
65
  declare function GlobalModePlugin(ctx: UnocssPluginContext): vite.Plugin<any>[];
66
66
 
67
67
  declare function PerModuleModePlugin({ uno, filter }: UnocssPluginContext): Plugin[];
package/dist/index.d.ts CHANGED
@@ -1,6 +1,6 @@
1
+ import { UserConfig, UnocssPluginContext, UserConfigDefaults } from '@unocss/core';
1
2
  import * as vite from 'vite';
2
3
  import { Plugin } from 'vite';
3
- import { UserConfig, UnocssPluginContext, UserConfigDefaults } from '@unocss/core';
4
4
 
5
5
  interface VitePluginConfig<Theme extends object = object> extends UserConfig<Theme> {
6
6
  /**
@@ -58,10 +58,10 @@ interface VitePluginConfig<Theme extends object = object> extends UserConfig<The
58
58
 
59
59
  declare function ChunkModeBuildPlugin({ uno, filter }: UnocssPluginContext): Plugin;
60
60
 
61
- declare function GlobalModeDevPlugin({ uno, tokens, tasks, flushTasks, affectedModules, onInvalidate, extract, filter, getConfig }: UnocssPluginContext): Plugin[];
62
-
63
61
  declare function GlobalModeBuildPlugin(ctx: UnocssPluginContext<VitePluginConfig>): Plugin[];
64
62
 
63
+ declare function GlobalModeDevPlugin({ uno, tokens, tasks, flushTasks, affectedModules, onInvalidate, extract, filter, getConfig }: UnocssPluginContext): Plugin[];
64
+
65
65
  declare function GlobalModePlugin(ctx: UnocssPluginContext): vite.Plugin<any>[];
66
66
 
67
67
  declare function PerModuleModePlugin({ uno, filter }: UnocssPluginContext): Plugin[];
package/dist/index.mjs CHANGED
@@ -1,49 +1,224 @@
1
1
  import process$1 from 'node:process';
2
2
  import UnocssInspector from '@unocss/inspector';
3
- import { resolve, isAbsolute, dirname } from 'node:path';
4
- import fs from 'node:fs/promises';
3
+ import fs from 'node:fs';
4
+ import { dirname, resolve, isAbsolute } from 'node:path';
5
+ import { fileURLToPath } from 'node:url';
6
+ import { toEscapedSelector, cssIdRE, createGenerator, BetterMap, notNull } from '@unocss/core';
7
+ import fs$1 from 'node:fs/promises';
5
8
  import { glob } from 'tinyglobby';
6
- import MagicString from 'magic-string';
7
9
  import remapping from '@ampproject/remapping';
8
- import { cssIdRE, createGenerator, BetterMap, notNull, toEscapedSelector } from '@unocss/core';
10
+ import MagicString from 'magic-string';
9
11
  import { createHash } from 'node:crypto';
10
12
  import { Buffer } from 'node:buffer';
11
13
  import { createFilter } from '@rollup/pluginutils';
12
- import fs$1 from 'node:fs';
13
- import { fileURLToPath } from 'node:url';
14
14
  import { createRecoveryConfigLoader } from '@unocss/config';
15
15
 
16
- const defaultPipelineExclude = [cssIdRE];
17
- const defaultPipelineInclude = [/\.(vue|svelte|[jt]sx|mdx?|astro|elm|php|phtml|html)($|\?)/];
16
+ function ConfigHMRPlugin(ctx) {
17
+ const { ready, uno } = ctx;
18
+ return {
19
+ name: "unocss:config",
20
+ async configResolved(config) {
21
+ await ctx.updateRoot(config.root);
22
+ },
23
+ async configureServer(server) {
24
+ uno.config.envMode = "dev";
25
+ const { sources } = await ready;
26
+ if (!sources.length)
27
+ return;
28
+ server.watcher.add(sources);
29
+ server.watcher.on("change", async (p) => {
30
+ if (!sources.includes(p))
31
+ return;
32
+ await ctx.reloadConfig();
33
+ server.ws.send({
34
+ type: "custom",
35
+ event: "unocss:config-changed"
36
+ });
37
+ });
38
+ }
39
+ };
40
+ }
18
41
 
19
- const VIRTUAL_ENTRY_ALIAS = [
20
- /^(?:virtual:)?uno(?::(.+))?\.css(\?.*)?$/
21
- ];
22
- const LAYER_MARK_ALL = "__ALL__";
23
- const RESOLVED_ID_WITH_QUERY_RE = /[/\\]__uno(_.*?)?\.css(\?.*)?$/;
24
- const RESOLVED_ID_RE = /[/\\]__uno(?:_(.*?))?\.css$/;
25
- function resolveId(id) {
26
- if (id.match(RESOLVED_ID_WITH_QUERY_RE))
27
- return id;
28
- for (const alias of VIRTUAL_ENTRY_ALIAS) {
29
- const match = id.match(alias);
30
- if (match) {
31
- return match[1] ? `/__uno_${match[1]}.css` : "/__uno.css";
42
+ const _dirname = typeof __dirname !== "undefined" ? __dirname : dirname(fileURLToPath(import.meta.url));
43
+ const DEVTOOLS_MODULE_ID = "virtual:unocss-devtools";
44
+ const MOCK_CLASSES_MODULE_ID = "virtual:unocss-mock-classes";
45
+ const MOCK_CLASSES_PATH = "/@unocss/mock-classes";
46
+ const DEVTOOLS_PATH = "/@unocss/devtools";
47
+ const DEVTOOLS_CSS_PATH = "/@unocss/devtools.css";
48
+ const devtoolCss = /* @__PURE__ */ new Set();
49
+ const MODULES_MAP = {
50
+ [DEVTOOLS_MODULE_ID]: DEVTOOLS_PATH,
51
+ [MOCK_CLASSES_MODULE_ID]: MOCK_CLASSES_PATH
52
+ };
53
+ const BASE_POST_PATH = "/@unocss-devtools-update";
54
+ function getBodyJson(req) {
55
+ return new Promise((resolve2, reject) => {
56
+ let body = "";
57
+ req.on("data", (chunk) => body += chunk);
58
+ req.on("error", reject);
59
+ req.on("end", () => {
60
+ try {
61
+ resolve2(JSON.parse(body) || {});
62
+ } catch (e) {
63
+ reject(e);
64
+ }
65
+ });
66
+ });
67
+ }
68
+ function createDevtoolsPlugin(ctx, pluginConfig) {
69
+ let config;
70
+ let server;
71
+ let clientCode = "";
72
+ let devtoolTimer;
73
+ let lastUpdate = Date.now();
74
+ let postPath = BASE_POST_PATH;
75
+ function toClass(name) {
76
+ return `${toEscapedSelector(name)}{}`;
77
+ }
78
+ function updateDevtoolClass() {
79
+ clearTimeout(devtoolTimer);
80
+ devtoolTimer = setTimeout(() => {
81
+ lastUpdate = Date.now();
82
+ if (!server)
83
+ return;
84
+ const mod = server.moduleGraph.getModuleById(DEVTOOLS_CSS_PATH);
85
+ if (!mod)
86
+ return;
87
+ server.moduleGraph.invalidateModule(mod);
88
+ server.ws.send({
89
+ type: "update",
90
+ updates: [{
91
+ acceptedPath: DEVTOOLS_CSS_PATH,
92
+ path: DEVTOOLS_CSS_PATH,
93
+ timestamp: lastUpdate,
94
+ type: "js-update"
95
+ }]
96
+ });
97
+ }, 100);
98
+ }
99
+ async function getMockClassesInjector() {
100
+ const suggest = Object.keys(ctx.uno.config.rulesStaticMap);
101
+ const comment = "/* unocss CSS mock class names for devtools auto-completion */\n";
102
+ const css = suggest.map(toClass).join("");
103
+ return `
104
+ const style = document.createElement('style')
105
+ style.setAttribute('type', 'text/css')
106
+ style.innerHTML = ${JSON.stringify(comment + css)}
107
+ document.head.prepend(style)
108
+ `;
109
+ }
110
+ return [
111
+ {
112
+ name: "unocss:devtools",
113
+ configResolved(_config) {
114
+ config = _config;
115
+ postPath = `${config.base?.replace(/\/$/, "") ?? ""}${BASE_POST_PATH}`;
116
+ },
117
+ configureServer(_server) {
118
+ server = _server;
119
+ server.middlewares.use(async (req, res, next) => {
120
+ if (req.url !== postPath)
121
+ return next();
122
+ try {
123
+ const data = await getBodyJson(req);
124
+ const type = data?.type;
125
+ let changed = false;
126
+ switch (type) {
127
+ case "add-classes":
128
+ data.data.forEach((key) => {
129
+ if (!devtoolCss.has(key)) {
130
+ devtoolCss.add(key);
131
+ changed = true;
132
+ }
133
+ });
134
+ if (changed)
135
+ updateDevtoolClass();
136
+ }
137
+ res.statusCode = 200;
138
+ } catch (e) {
139
+ console.error(e);
140
+ res.statusCode = 500;
141
+ }
142
+ res.end();
143
+ });
144
+ },
145
+ resolveId(id) {
146
+ if (id === DEVTOOLS_CSS_PATH)
147
+ return DEVTOOLS_CSS_PATH;
148
+ return MODULES_MAP[id];
149
+ },
150
+ async load(id) {
151
+ if (id === DEVTOOLS_PATH) {
152
+ if (!clientCode) {
153
+ clientCode = [
154
+ await fs.promises.readFile(resolve(_dirname, "client.mjs"), "utf-8"),
155
+ `import('${MOCK_CLASSES_MODULE_ID}')`,
156
+ `import('${DEVTOOLS_CSS_PATH}')`
157
+ ].join("\n").replace("__POST_PATH__", `${config.server?.origin ?? ""}${postPath}`).replace("__POST_FETCH_MODE__", pluginConfig.fetchMode ?? "cors");
158
+ }
159
+ return config.command === "build" ? "" : clientCode;
160
+ } else if (id === MOCK_CLASSES_PATH) {
161
+ return await getMockClassesInjector();
162
+ } else if (id === DEVTOOLS_CSS_PATH) {
163
+ const { css } = await ctx.uno.generate(devtoolCss);
164
+ return css;
165
+ }
166
+ }
32
167
  }
168
+ ];
169
+ }
170
+
171
+ function getPath(id) {
172
+ return id.replace(/\?.*$/, "");
173
+ }
174
+ function hash(str) {
175
+ let i;
176
+ let l;
177
+ let hval = 2166136261;
178
+ for (i = 0, l = str.length; i < l; i++) {
179
+ hval ^= str.charCodeAt(i);
180
+ hval += (hval << 1) + (hval << 4) + (hval << 7) + (hval << 8) + (hval << 24);
33
181
  }
182
+ return `00000${(hval >>> 0).toString(36)}`.slice(-6);
34
183
  }
35
- function resolveLayer(id) {
36
- const match = id.match(RESOLVED_ID_RE);
37
- if (match)
38
- return match[1] || LAYER_MARK_ALL;
184
+ function transformSkipCode(code, map, SKIP_RULES_RE, keyFlag) {
185
+ for (const item of Array.from(code.matchAll(SKIP_RULES_RE))) {
186
+ if (item != null) {
187
+ const matched = item[0];
188
+ const withHashKey = `${keyFlag}${hash(matched)}`;
189
+ map.set(withHashKey, matched);
190
+ code = code.replace(matched, withHashKey);
191
+ }
192
+ }
193
+ return code;
39
194
  }
40
- const LAYER_PLACEHOLDER_RE = /#--unocss--\s*\{\s*layer\s*:\s*(.+?)\s*(?:;\s*escape-view\s*:\s*(.+?)\s*)?;?\s*\}/g;
41
- function getLayerPlaceholder(layer) {
42
- return `#--unocss--{layer:${layer};escape-view:\\"\\'\\\`\\\\}`;
195
+ function restoreSkipCode(code, map) {
196
+ for (const [withHashKey, matched] of map.entries())
197
+ code = code.replaceAll(withHashKey, matched);
198
+ return code;
43
199
  }
44
- const HASH_PLACEHOLDER_RE = /#--unocss-hash--\s*\{\s*content\s*:\s*\\*"([^\\"]+)\\*";?\s*\}/g;
45
- function getHashPlaceholder(hash) {
46
- return `#--unocss-hash--{content:"${hash}"}`;
200
+
201
+ function replaceAsync(string, searchValue, replacer) {
202
+ try {
203
+ if (typeof replacer === "function") {
204
+ const values = [];
205
+ String.prototype.replace.call(string, searchValue, (...args) => {
206
+ values.push(replacer(...args));
207
+ return "";
208
+ });
209
+ return Promise.all(values).then((resolvedValues) => {
210
+ return String.prototype.replace.call(string, searchValue, () => {
211
+ return resolvedValues.shift() || "";
212
+ });
213
+ });
214
+ } else {
215
+ return Promise.resolve(
216
+ String.prototype.replace.call(string, searchValue, replacer)
217
+ );
218
+ }
219
+ } catch (error) {
220
+ return Promise.reject(error);
221
+ }
47
222
  }
48
223
 
49
224
  const INCLUDE_COMMENT = "@unocss-include";
@@ -53,6 +228,9 @@ const SKIP_START_COMMENT = "@unocss-skip-start";
53
228
  const SKIP_END_COMMENT = "@unocss-skip-end";
54
229
  const SKIP_COMMENT_RE = new RegExp(`(//\\s*?${SKIP_START_COMMENT}\\s*?|\\/\\*\\s*?${SKIP_START_COMMENT}\\s*?\\*\\/|<!--\\s*?${SKIP_START_COMMENT}\\s*?-->)[\\s\\S]*?(//\\s*?${SKIP_END_COMMENT}\\s*?|\\/\\*\\s*?${SKIP_END_COMMENT}\\s*?\\*\\/|<!--\\s*?${SKIP_END_COMMENT}\\s*?-->)`, "g");
55
230
 
231
+ const defaultPipelineExclude = [cssIdRE];
232
+ const defaultPipelineInclude = [/\.(vue|svelte|[jt]sx|mdx?|astro|elm|php|phtml|html)($|\?)/];
233
+
56
234
  function deprecationCheck(config) {
57
235
  let warned = false;
58
236
  function warn(msg) {
@@ -183,62 +361,39 @@ function createContext(configOrPath, defaults = {}, extraConfigSources = [], res
183
361
  };
184
362
  }
185
363
 
186
- function getPath(id) {
187
- return id.replace(/\?.*$/, "");
188
- }
189
- function hash(str) {
190
- let i;
191
- let l;
192
- let hval = 2166136261;
193
- for (i = 0, l = str.length; i < l; i++) {
194
- hval ^= str.charCodeAt(i);
195
- hval += (hval << 1) + (hval << 4) + (hval << 7) + (hval << 8) + (hval << 24);
196
- }
197
- return `00000${(hval >>> 0).toString(36)}`.slice(-6);
198
- }
199
- function transformSkipCode(code, map, SKIP_RULES_RE, keyFlag) {
200
- for (const item of Array.from(code.matchAll(SKIP_RULES_RE))) {
201
- if (item != null) {
202
- const matched = item[0];
203
- const withHashKey = `${keyFlag}${hash(matched)}`;
204
- map.set(withHashKey, matched);
205
- code = code.replace(matched, withHashKey);
206
- }
207
- }
208
- return code;
209
- }
210
- function restoreSkipCode(code, map) {
211
- for (const [withHashKey, matched] of map.entries())
212
- code = code.replaceAll(withHashKey, matched);
213
- return code;
214
- }
215
-
216
364
  function getHash(input, length = 8) {
217
365
  return createHash("sha256").update(input).digest("hex").slice(0, length);
218
366
  }
219
367
 
220
- function replaceAsync(string, searchValue, replacer) {
221
- try {
222
- if (typeof replacer === "function") {
223
- const values = [];
224
- String.prototype.replace.call(string, searchValue, (...args) => {
225
- values.push(replacer(...args));
226
- return "";
227
- });
228
- return Promise.all(values).then((resolvedValues) => {
229
- return String.prototype.replace.call(string, searchValue, () => {
230
- return resolvedValues.shift() || "";
231
- });
232
- });
233
- } else {
234
- return Promise.resolve(
235
- String.prototype.replace.call(string, searchValue, replacer)
236
- );
368
+ const VIRTUAL_ENTRY_ALIAS = [
369
+ /^(?:virtual:)?uno(?::(.+))?\.css(\?.*)?$/
370
+ ];
371
+ const LAYER_MARK_ALL = "__ALL__";
372
+ const RESOLVED_ID_WITH_QUERY_RE = /[/\\]__uno(_.*?)?\.css(\?.*)?$/;
373
+ const RESOLVED_ID_RE = /[/\\]__uno(?:_(.*?))?\.css$/;
374
+ function resolveId(id) {
375
+ if (id.match(RESOLVED_ID_WITH_QUERY_RE))
376
+ return id;
377
+ for (const alias of VIRTUAL_ENTRY_ALIAS) {
378
+ const match = id.match(alias);
379
+ if (match) {
380
+ return match[1] ? `/__uno_${match[1]}.css` : "/__uno.css";
237
381
  }
238
- } catch (error) {
239
- return Promise.reject(error);
240
382
  }
241
383
  }
384
+ function resolveLayer(id) {
385
+ const match = id.match(RESOLVED_ID_RE);
386
+ if (match)
387
+ return match[1] || LAYER_MARK_ALL;
388
+ }
389
+ const LAYER_PLACEHOLDER_RE = /#--unocss--\s*\{\s*layer\s*:\s*(.+?)\s*(?:;\s*escape-view\s*:\s*(.+?)\s*)?;?\s*\}/g;
390
+ function getLayerPlaceholder(layer) {
391
+ return `#--unocss--{layer:${layer};escape-view:\\"\\'\\\`\\\\}`;
392
+ }
393
+ const HASH_PLACEHOLDER_RE = /#--unocss-hash--\s*\{\s*content\s*:\s*\\*"([^\\"]+)\\*";?\s*\}/g;
394
+ function getHashPlaceholder(hash) {
395
+ return `#--unocss-hash--{content:"${hash}"}`;
396
+ }
242
397
 
243
398
  function ChunkModeBuildPlugin({ uno, filter }) {
244
399
  let cssPlugin;
@@ -282,6 +437,9 @@ function ChunkModeBuildPlugin({ uno, filter }) {
282
437
  };
283
438
  }
284
439
 
440
+ const LAYER_PREFLIGHTS = "preflights";
441
+ const LAYER_IMPORTS = "imports";
442
+
285
443
  async function applyTransformers(ctx, original, id, enforce = "default") {
286
444
  if (original.includes(IGNORE_COMMENT))
287
445
  return;
@@ -335,7 +493,7 @@ async function setupContentExtractor(ctx, shouldWatch = false) {
335
493
  const files = await glob(content.filesystem, { cwd: root, expandDirectories: false });
336
494
  async function extractFile(file) {
337
495
  file = isAbsolute(file) ? file : resolve(root, file);
338
- const code = await fs.readFile(file, "utf-8");
496
+ const code = await fs$1.readFile(file, "utf-8");
339
497
  if (!filter(code, file))
340
498
  return;
341
499
  const preTransform = await applyTransformers(ctx, code, file, "pre");
@@ -363,8 +521,6 @@ async function setupContentExtractor(ctx, shouldWatch = false) {
363
521
  }
364
522
  }
365
523
 
366
- const LAYER_IMPORTS = "imports";
367
-
368
524
  function isLegacyChunk(chunk, options) {
369
525
  return options.format === "system" && chunk.fileName.includes("-legacy");
370
526
  }
@@ -535,11 +691,27 @@ function GlobalModeBuildPlugin(ctx) {
535
691
  return null;
536
692
  }
537
693
  const result = await generateAll();
538
- const mappedVfsLayer = Array.from(vfsLayers).map((layer) => layer === LAYER_MARK_ALL ? layer : layer.replace(/^_/, ""));
539
- const importStatements = result.getLayer(LAYER_IMPORTS);
540
- const cssWithLayers = Array.from(vfsLayers).map((layer) => `${importStatements ?? ""}#--unocss-layer-start--${layer}--{start:${layer}} ${layer === LAYER_MARK_ALL ? result.getLayers(void 0, [...mappedVfsLayer, LAYER_IMPORTS]) : result.getLayer(layer.replace(/^_/, "")) || ""} #--unocss-layer-end--${layer}--{end:${layer}}`).join("");
694
+ const importsLayer = result.getLayer(LAYER_IMPORTS) ?? "";
541
695
  const fakeCssId = `${viteConfig.root}/${chunk.fileName}-unocss-hash.css`;
542
- const css = await applyCssTransform(cssWithLayers, fakeCssId, options.dir, this);
696
+ const preflightLayers = ctx.uno.config.preflights?.map((i) => i.layer).concat(LAYER_PREFLIGHTS).filter(Boolean);
697
+ await Promise.all(preflightLayers.map((i) => result.setLayer(i, async (layerContent) => {
698
+ const preTransform = await applyTransformers(ctx, layerContent, fakeCssId, "pre");
699
+ const defaultTransform = await applyTransformers(ctx, preTransform?.code || layerContent, fakeCssId);
700
+ const postTransform = await applyTransformers(ctx, defaultTransform?.code || preTransform?.code || layerContent, fakeCssId, "post");
701
+ return postTransform?.code || defaultTransform?.code || preTransform?.code || layerContent;
702
+ })));
703
+ const cssWithLayers = await Promise.all(Array.from(vfsLayers).map(async (layer) => {
704
+ const layerStart = `#--unocss-layer-start--${layer}--{start:${layer}}`;
705
+ const layerEnd = `#--unocss-layer-end--${layer}--{end:${layer}}`;
706
+ let layerContent;
707
+ if (layer === LAYER_MARK_ALL) {
708
+ layerContent = result.getLayers(void 0, [...vfsLayers, LAYER_IMPORTS]);
709
+ } else {
710
+ layerContent = result.getLayer(layer) || "";
711
+ }
712
+ return `${importsLayer}${layerStart} ${layerContent} ${layerEnd}`;
713
+ }));
714
+ const css = await applyCssTransform(cssWithLayers.join(""), fakeCssId, options.dir, this);
543
715
  const transformHandler = "handler" in cssPost.transform ? cssPost.transform.handler : cssPost.transform;
544
716
  await transformHandler.call({}, css, fakeCssId);
545
717
  }
@@ -893,48 +1065,6 @@ ${css}`;
893
1065
  ];
894
1066
  }
895
1067
 
896
- function VueScopedPlugin({ uno, ready }) {
897
- let filter = createFilter([/\.vue$/], defaultPipelineExclude);
898
- async function transformSFC(code) {
899
- const { css } = await uno.generate(code);
900
- if (!css)
901
- return null;
902
- return `${code}
903
- <style scoped>${css}</style>`;
904
- }
905
- return {
906
- name: "unocss:vue-scoped",
907
- enforce: "pre",
908
- async configResolved() {
909
- const { config } = await ready;
910
- filter = config.content?.pipeline === false ? () => false : createFilter(
911
- config.content?.pipeline?.include ?? config.include ?? [/\.vue$/],
912
- config.content?.pipeline?.exclude ?? config.exclude ?? defaultPipelineExclude
913
- );
914
- },
915
- async transform(code, id) {
916
- if (!filter(id) || !id.endsWith(".vue"))
917
- return;
918
- const css = await transformSFC(code);
919
- if (css) {
920
- return {
921
- code: css,
922
- map: null
923
- };
924
- }
925
- },
926
- handleHotUpdate(ctx) {
927
- const read = ctx.read;
928
- if (filter(ctx.file)) {
929
- ctx.read = async () => {
930
- const code = await read();
931
- return await transformSFC(code) || code;
932
- };
933
- }
934
- }
935
- };
936
- }
937
-
938
1068
  function ShadowDomModuleModePlugin({ uno }) {
939
1069
  const partExtractorRegex = /^part-\[(.+)\]:/;
940
1070
  const nameRegexp = /<([^\s^!>]+)\s*([^>]*)>/;
@@ -1040,28 +1170,44 @@ function ShadowDomModuleModePlugin({ uno }) {
1040
1170
  };
1041
1171
  }
1042
1172
 
1043
- function ConfigHMRPlugin(ctx) {
1044
- const { ready, uno } = ctx;
1173
+ function VueScopedPlugin({ uno, ready }) {
1174
+ let filter = createFilter([/\.vue$/], defaultPipelineExclude);
1175
+ async function transformSFC(code) {
1176
+ const { css } = await uno.generate(code);
1177
+ if (!css)
1178
+ return null;
1179
+ return `${code}
1180
+ <style scoped>${css}</style>`;
1181
+ }
1045
1182
  return {
1046
- name: "unocss:config",
1047
- async configResolved(config) {
1048
- await ctx.updateRoot(config.root);
1183
+ name: "unocss:vue-scoped",
1184
+ enforce: "pre",
1185
+ async configResolved() {
1186
+ const { config } = await ready;
1187
+ filter = config.content?.pipeline === false ? () => false : createFilter(
1188
+ config.content?.pipeline?.include ?? config.include ?? [/\.vue$/],
1189
+ config.content?.pipeline?.exclude ?? config.exclude ?? defaultPipelineExclude
1190
+ );
1049
1191
  },
1050
- async configureServer(server) {
1051
- uno.config.envMode = "dev";
1052
- const { sources } = await ready;
1053
- if (!sources.length)
1192
+ async transform(code, id) {
1193
+ if (!filter(id) || !id.endsWith(".vue"))
1054
1194
  return;
1055
- server.watcher.add(sources);
1056
- server.watcher.on("change", async (p) => {
1057
- if (!sources.includes(p))
1058
- return;
1059
- await ctx.reloadConfig();
1060
- server.ws.send({
1061
- type: "custom",
1062
- event: "unocss:config-changed"
1063
- });
1064
- });
1195
+ const css = await transformSFC(code);
1196
+ if (css) {
1197
+ return {
1198
+ code: css,
1199
+ map: null
1200
+ };
1201
+ }
1202
+ },
1203
+ handleHotUpdate(ctx) {
1204
+ const read = ctx.read;
1205
+ if (filter(ctx.file)) {
1206
+ ctx.read = async () => {
1207
+ const code = await read();
1208
+ return await transformSFC(code) || code;
1209
+ };
1210
+ }
1065
1211
  }
1066
1212
  };
1067
1213
  }
@@ -1090,135 +1236,6 @@ function createTransformerPlugins(ctx) {
1090
1236
  });
1091
1237
  }
1092
1238
 
1093
- const _dirname = typeof __dirname !== "undefined" ? __dirname : dirname(fileURLToPath(import.meta.url));
1094
- const DEVTOOLS_MODULE_ID = "virtual:unocss-devtools";
1095
- const MOCK_CLASSES_MODULE_ID = "virtual:unocss-mock-classes";
1096
- const MOCK_CLASSES_PATH = "/@unocss/mock-classes";
1097
- const DEVTOOLS_PATH = "/@unocss/devtools";
1098
- const DEVTOOLS_CSS_PATH = "/@unocss/devtools.css";
1099
- const devtoolCss = /* @__PURE__ */ new Set();
1100
- const MODULES_MAP = {
1101
- [DEVTOOLS_MODULE_ID]: DEVTOOLS_PATH,
1102
- [MOCK_CLASSES_MODULE_ID]: MOCK_CLASSES_PATH
1103
- };
1104
- const BASE_POST_PATH = "/@unocss-devtools-update";
1105
- function getBodyJson(req) {
1106
- return new Promise((resolve2, reject) => {
1107
- let body = "";
1108
- req.on("data", (chunk) => body += chunk);
1109
- req.on("error", reject);
1110
- req.on("end", () => {
1111
- try {
1112
- resolve2(JSON.parse(body) || {});
1113
- } catch (e) {
1114
- reject(e);
1115
- }
1116
- });
1117
- });
1118
- }
1119
- function createDevtoolsPlugin(ctx, pluginConfig) {
1120
- let config;
1121
- let server;
1122
- let clientCode = "";
1123
- let devtoolTimer;
1124
- let lastUpdate = Date.now();
1125
- let postPath = BASE_POST_PATH;
1126
- function toClass(name) {
1127
- return `${toEscapedSelector(name)}{}`;
1128
- }
1129
- function updateDevtoolClass() {
1130
- clearTimeout(devtoolTimer);
1131
- devtoolTimer = setTimeout(() => {
1132
- lastUpdate = Date.now();
1133
- if (!server)
1134
- return;
1135
- const mod = server.moduleGraph.getModuleById(DEVTOOLS_CSS_PATH);
1136
- if (!mod)
1137
- return;
1138
- server.moduleGraph.invalidateModule(mod);
1139
- server.ws.send({
1140
- type: "update",
1141
- updates: [{
1142
- acceptedPath: DEVTOOLS_CSS_PATH,
1143
- path: DEVTOOLS_CSS_PATH,
1144
- timestamp: lastUpdate,
1145
- type: "js-update"
1146
- }]
1147
- });
1148
- }, 100);
1149
- }
1150
- async function getMockClassesInjector() {
1151
- const suggest = Object.keys(ctx.uno.config.rulesStaticMap);
1152
- const comment = "/* unocss CSS mock class names for devtools auto-completion */\n";
1153
- const css = suggest.map(toClass).join("");
1154
- return `
1155
- const style = document.createElement('style')
1156
- style.setAttribute('type', 'text/css')
1157
- style.innerHTML = ${JSON.stringify(comment + css)}
1158
- document.head.prepend(style)
1159
- `;
1160
- }
1161
- return [
1162
- {
1163
- name: "unocss:devtools",
1164
- configResolved(_config) {
1165
- config = _config;
1166
- postPath = `${config.base?.replace(/\/$/, "") ?? ""}${BASE_POST_PATH}`;
1167
- },
1168
- configureServer(_server) {
1169
- server = _server;
1170
- server.middlewares.use(async (req, res, next) => {
1171
- if (req.url !== postPath)
1172
- return next();
1173
- try {
1174
- const data = await getBodyJson(req);
1175
- const type = data?.type;
1176
- let changed = false;
1177
- switch (type) {
1178
- case "add-classes":
1179
- data.data.forEach((key) => {
1180
- if (!devtoolCss.has(key)) {
1181
- devtoolCss.add(key);
1182
- changed = true;
1183
- }
1184
- });
1185
- if (changed)
1186
- updateDevtoolClass();
1187
- }
1188
- res.statusCode = 200;
1189
- } catch (e) {
1190
- console.error(e);
1191
- res.statusCode = 500;
1192
- }
1193
- res.end();
1194
- });
1195
- },
1196
- resolveId(id) {
1197
- if (id === DEVTOOLS_CSS_PATH)
1198
- return DEVTOOLS_CSS_PATH;
1199
- return MODULES_MAP[id];
1200
- },
1201
- async load(id) {
1202
- if (id === DEVTOOLS_PATH) {
1203
- if (!clientCode) {
1204
- clientCode = [
1205
- await fs$1.promises.readFile(resolve(_dirname, "client.mjs"), "utf-8"),
1206
- `import('${MOCK_CLASSES_MODULE_ID}')`,
1207
- `import('${DEVTOOLS_CSS_PATH}')`
1208
- ].join("\n").replace("__POST_PATH__", `${config.server?.origin ?? ""}${postPath}`).replace("__POST_FETCH_MODE__", pluginConfig.fetchMode ?? "cors");
1209
- }
1210
- return config.command === "build" ? "" : clientCode;
1211
- } else if (id === MOCK_CLASSES_PATH) {
1212
- return await getMockClassesInjector();
1213
- } else if (id === DEVTOOLS_CSS_PATH) {
1214
- const { css } = await ctx.uno.generate(devtoolCss);
1215
- return css;
1216
- }
1217
- }
1218
- }
1219
- ];
1220
- }
1221
-
1222
1239
  function defineConfig(config) {
1223
1240
  return config;
1224
1241
  }
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@unocss/vite",
3
3
  "type": "module",
4
- "version": "0.62.3",
4
+ "version": "0.63.0",
5
5
  "description": "The Vite plugin for UnoCSS",
6
6
  "author": "Anthony Fu <anthonyfu117@hotmail.com>",
7
7
  "license": "MIT",
@@ -50,19 +50,17 @@
50
50
  },
51
51
  "dependencies": {
52
52
  "@ampproject/remapping": "^2.3.0",
53
- "@rollup/pluginutils": "^5.1.0",
53
+ "@rollup/pluginutils": "^5.1.2",
54
54
  "chokidar": "^3.6.0",
55
55
  "magic-string": "^0.30.11",
56
- "tinyglobby": "^0.2.5",
57
- "@unocss/config": "0.62.3",
58
- "@unocss/inspector": "0.62.3",
59
- "@unocss/core": "0.62.3",
60
- "@unocss/transformer-directives": "0.62.3",
61
- "@unocss/scope": "0.62.3"
56
+ "tinyglobby": "^0.2.6",
57
+ "@unocss/config": "0.63.0",
58
+ "@unocss/core": "0.63.0",
59
+ "@unocss/inspector": "0.63.0"
62
60
  },
63
61
  "devDependencies": {
64
- "vite": "^5.4.2",
65
- "@unocss/shared-integration": "0.62.3"
62
+ "vite": "^5.4.8",
63
+ "@unocss/shared-integration": "0.63.0"
66
64
  },
67
65
  "scripts": {
68
66
  "build": "unbuild",