@unocss/svelte-scoped 0.58.9 → 0.59.0-beta.1
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/package.json +8 -10
- package/dist/preprocess.cjs +0 -13
- package/dist/preprocess.d.cts +0 -9
- package/dist/shared/svelte-scoped.BJnJpFJ9.d.cts +0 -45
- package/dist/shared/svelte-scoped.pPNrJCJJ.cjs +0 -491
- package/dist/vite.cjs +0 -304
- package/dist/vite.d.cts +0 -42
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@unocss/svelte-scoped",
|
|
3
3
|
"type": "module",
|
|
4
|
-
"version": "0.
|
|
4
|
+
"version": "0.59.0-beta.1",
|
|
5
5
|
"description": "Use UnoCSS in a modular fashion with styles being stored only in the Svelte component they are used in: Vite plugin for apps, Svelte preprocessor for component libraries",
|
|
6
6
|
"author": "Jacob Bowdoin",
|
|
7
7
|
"license": "MIT",
|
|
@@ -25,17 +25,15 @@
|
|
|
25
25
|
"sideEffects": false,
|
|
26
26
|
"exports": {
|
|
27
27
|
"./preprocess": {
|
|
28
|
-
"types": "./dist/preprocess.d.
|
|
29
|
-
"
|
|
30
|
-
"require": "./dist/preprocess.cjs"
|
|
28
|
+
"types": "./dist/preprocess.d.mts",
|
|
29
|
+
"default": "./dist/preprocess.mjs"
|
|
31
30
|
},
|
|
32
31
|
"./vite": {
|
|
33
|
-
"types": "./dist/vite.d.
|
|
34
|
-
"
|
|
35
|
-
"require": "./dist/vite.cjs"
|
|
32
|
+
"types": "./dist/vite.d.mts",
|
|
33
|
+
"default": "./dist/vite.mjs"
|
|
36
34
|
}
|
|
37
35
|
},
|
|
38
|
-
"main": "./dist/vite.
|
|
36
|
+
"main": "./dist/vite.mjs",
|
|
39
37
|
"module": "./dist/vite.mjs",
|
|
40
38
|
"types": "./dist/vite.d.ts",
|
|
41
39
|
"typesVersions": {
|
|
@@ -54,8 +52,8 @@
|
|
|
54
52
|
"dependencies": {
|
|
55
53
|
"css-tree": "^2.3.1",
|
|
56
54
|
"magic-string": "^0.30.8",
|
|
57
|
-
"@unocss/
|
|
58
|
-
"@unocss/
|
|
55
|
+
"@unocss/reset": "0.59.0-beta.1",
|
|
56
|
+
"@unocss/config": "0.59.0-beta.1"
|
|
59
57
|
},
|
|
60
58
|
"devDependencies": {
|
|
61
59
|
"prettier-plugin-svelte": "^2.10.1",
|
package/dist/preprocess.cjs
DELETED
|
@@ -1,13 +0,0 @@
|
|
|
1
|
-
'use strict';
|
|
2
|
-
|
|
3
|
-
const index = require('./shared/svelte-scoped.pPNrJCJJ.cjs');
|
|
4
|
-
require('node:process');
|
|
5
|
-
require('@unocss/core');
|
|
6
|
-
require('@unocss/preset-uno');
|
|
7
|
-
require('@unocss/config');
|
|
8
|
-
require('magic-string');
|
|
9
|
-
require('css-tree');
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
module.exports = index.UnocssSveltePreprocess;
|
package/dist/preprocess.d.cts
DELETED
|
@@ -1,9 +0,0 @@
|
|
|
1
|
-
import { PreprocessorGroup } from 'svelte/types/compiler/preprocess';
|
|
2
|
-
import { U as UnocssSveltePreprocessOptions, S as SvelteScopedContext } from './shared/svelte-scoped.BJnJpFJ9.cjs';
|
|
3
|
-
export { a as TransformApplyOptions, T as TransformClassesOptions } from './shared/svelte-scoped.BJnJpFJ9.cjs';
|
|
4
|
-
import '@unocss/core';
|
|
5
|
-
import '@unocss/config';
|
|
6
|
-
|
|
7
|
-
declare function UnocssSveltePreprocess(options?: UnocssSveltePreprocessOptions, unoContextFromVite?: SvelteScopedContext, isViteBuild?: () => boolean): PreprocessorGroup;
|
|
8
|
-
|
|
9
|
-
export { SvelteScopedContext, UnocssSveltePreprocessOptions, UnocssSveltePreprocess as default };
|
|
@@ -1,45 +0,0 @@
|
|
|
1
|
-
import { UserConfig, UnoGenerator } from '@unocss/core';
|
|
2
|
-
import { LoadConfigResult } from '@unocss/config';
|
|
3
|
-
|
|
4
|
-
interface UnocssSveltePreprocessOptions extends TransformClassesOptions, TransformApplyOptions {
|
|
5
|
-
/**
|
|
6
|
-
* UnoCSS config or path to config file. If not provided, will load unocss.config.ts/js. It's recommended to use the separate config file if you are having trouble with the UnoCSS extension in VSCode.
|
|
7
|
-
*/
|
|
8
|
-
configOrPath?: UserConfig | string
|
|
9
|
-
}
|
|
10
|
-
|
|
11
|
-
interface TransformClassesOptions {
|
|
12
|
-
/**
|
|
13
|
-
* Prefix for compiled class names. Distinct between `@unocss/svelte-scoped/vite` and `@unocss/svelte-scoped/preprocessor` to avoid bugs when using a component library built with `@unocss/svelte-scoped/preprocessor` in a project using `@unocss/svelte-scoped/vite`.
|
|
14
|
-
* @default 'uno-' // `@unocss/svelte-scoped/vite`
|
|
15
|
-
* @default 'usp-' // `@unocss/svelte-scoped/preprocessor`
|
|
16
|
-
*/
|
|
17
|
-
classPrefix?: string
|
|
18
|
-
/**
|
|
19
|
-
* Add hash and combine recognized tokens (optimal for production); set false in dev mode for easy dev tools toggling to allow for design adjustments in the browser
|
|
20
|
-
* @default true
|
|
21
|
-
*/
|
|
22
|
-
combine?: boolean
|
|
23
|
-
/**
|
|
24
|
-
* Used to generate hash for compiled class names
|
|
25
|
-
*/
|
|
26
|
-
hashFn?: (str: string) => string
|
|
27
|
-
}
|
|
28
|
-
|
|
29
|
-
interface TransformApplyOptions {
|
|
30
|
-
/**
|
|
31
|
-
* Transform CSS custom properties (recommended for CSS syntax compatibility) or @apply directives.
|
|
32
|
-
*
|
|
33
|
-
* Pass `false` to disable.
|
|
34
|
-
*
|
|
35
|
-
* @default ['--at-apply', '@apply']
|
|
36
|
-
*/
|
|
37
|
-
applyVariables?: string | string[] | false
|
|
38
|
-
}
|
|
39
|
-
|
|
40
|
-
interface SvelteScopedContext {
|
|
41
|
-
uno: UnoGenerator
|
|
42
|
-
ready: Promise<LoadConfigResult<UserConfig>>
|
|
43
|
-
}
|
|
44
|
-
|
|
45
|
-
export type { SvelteScopedContext as S, TransformClassesOptions as T, UnocssSveltePreprocessOptions as U, TransformApplyOptions as a };
|
|
@@ -1,491 +0,0 @@
|
|
|
1
|
-
'use strict';
|
|
2
|
-
|
|
3
|
-
const process = require('node:process');
|
|
4
|
-
const core = require('@unocss/core');
|
|
5
|
-
const presetUno = require('@unocss/preset-uno');
|
|
6
|
-
const config = require('@unocss/config');
|
|
7
|
-
const MagicString = require('magic-string');
|
|
8
|
-
const cssTree = require('css-tree');
|
|
9
|
-
|
|
10
|
-
function _interopDefaultCompat (e) { return e && typeof e === 'object' && 'default' in e ? e.default : e; }
|
|
11
|
-
|
|
12
|
-
const process__default = /*#__PURE__*/_interopDefaultCompat(process);
|
|
13
|
-
const presetUno__default = /*#__PURE__*/_interopDefaultCompat(presetUno);
|
|
14
|
-
const MagicString__default = /*#__PURE__*/_interopDefaultCompat(MagicString);
|
|
15
|
-
|
|
16
|
-
const NOT_PRECEEDED_BY_DIGIT_OR_OPEN_PARENTHESIS_RE = /(?<![\d(])/;
|
|
17
|
-
const SELECTOR_STARTING_WITH_BRACKET_OR_PERIOD_RE = /([[\.][\S\s]+?)/;
|
|
18
|
-
const STYLES_RE = /({[\S\s]+?})/;
|
|
19
|
-
const EXTRACT_SELECTOR_RE = new RegExp(NOT_PRECEEDED_BY_DIGIT_OR_OPEN_PARENTHESIS_RE.source + SELECTOR_STARTING_WITH_BRACKET_OR_PERIOD_RE.source + STYLES_RE.source, "g");
|
|
20
|
-
function wrapSelectorsWithGlobal(css) {
|
|
21
|
-
return css.replace(EXTRACT_SELECTOR_RE, ":global($1)$2");
|
|
22
|
-
}
|
|
23
|
-
|
|
24
|
-
const classesRE$1 = /class=(["'\`])([\S\s]*?)\1/g;
|
|
25
|
-
const classDirectivesRE = /class:([\S]+?)="?{/g;
|
|
26
|
-
const classDirectivesShorthandRE = /class:([^=>\s/]+)[{>\s/]/g;
|
|
27
|
-
function findClasses(code) {
|
|
28
|
-
const matchedClasses = [...code.matchAll(classesRE$1)];
|
|
29
|
-
const matchedClassDirectives = [...code.matchAll(classDirectivesRE)];
|
|
30
|
-
const matchedClassDirectivesShorthand = [...code.matchAll(classDirectivesShorthandRE)];
|
|
31
|
-
const classes = parseMatches(matchedClasses, "regular", 'class="'.length);
|
|
32
|
-
const classDirectives = parseMatches(matchedClassDirectives, "directive", "class:".length);
|
|
33
|
-
const classDirectivesShorthand = parseMatches(matchedClassDirectivesShorthand, "directiveShorthand", "class:".length);
|
|
34
|
-
return [...classes, ...classDirectives, ...classDirectivesShorthand];
|
|
35
|
-
}
|
|
36
|
-
function parseMatches(matches, type, prefixLength) {
|
|
37
|
-
return matches.map((match) => {
|
|
38
|
-
const body = match[type === "regular" ? 2 : 1];
|
|
39
|
-
const start = match.index + prefixLength;
|
|
40
|
-
return {
|
|
41
|
-
body: body.trim(),
|
|
42
|
-
start,
|
|
43
|
-
end: start + body.length,
|
|
44
|
-
type
|
|
45
|
-
};
|
|
46
|
-
}).filter(hasBody);
|
|
47
|
-
}
|
|
48
|
-
function hasBody(foundClass) {
|
|
49
|
-
return foundClass.body;
|
|
50
|
-
}
|
|
51
|
-
|
|
52
|
-
const notInCommentRE = /(?<!<!--\s*)/;
|
|
53
|
-
const stylesTagWithCapturedDirectivesRE = /<style([^>]*)>[\s\S]*?<\/style\s*>/;
|
|
54
|
-
const actualStylesTagWithCapturedDirectivesRE = new RegExp(notInCommentRE.source + stylesTagWithCapturedDirectivesRE.source, "g");
|
|
55
|
-
const captureOpeningStyleTagWithAttributesRE = /(<style[^>]*>)/;
|
|
56
|
-
function addGeneratedStylesIntoStyleBlock(code, styles) {
|
|
57
|
-
const preExistingStylesTag = code.match(actualStylesTagWithCapturedDirectivesRE);
|
|
58
|
-
if (preExistingStylesTag)
|
|
59
|
-
return code.replace(captureOpeningStyleTagWithAttributesRE, `$1${styles}`);
|
|
60
|
-
return `${code}
|
|
61
|
-
<style>${styles}</style>`;
|
|
62
|
-
}
|
|
63
|
-
|
|
64
|
-
async function needsGenerated(token, uno) {
|
|
65
|
-
const inSafelist = uno.config.safelist.includes(token);
|
|
66
|
-
if (inSafelist)
|
|
67
|
-
return false;
|
|
68
|
-
const result = await uno.parseToken(token);
|
|
69
|
-
return !!result;
|
|
70
|
-
}
|
|
71
|
-
|
|
72
|
-
function hash(str) {
|
|
73
|
-
let i;
|
|
74
|
-
let l;
|
|
75
|
-
let hval = 2166136261;
|
|
76
|
-
for (i = 0, l = str.length; i < l; i++) {
|
|
77
|
-
hval ^= str.charCodeAt(i);
|
|
78
|
-
hval += (hval << 1) + (hval << 4) + (hval << 7) + (hval << 8) + (hval << 24);
|
|
79
|
-
}
|
|
80
|
-
return `00000${(hval >>> 0).toString(36)}`.slice(-6);
|
|
81
|
-
}
|
|
82
|
-
|
|
83
|
-
function generateClassName(body, options, filename) {
|
|
84
|
-
const {
|
|
85
|
-
classPrefix = "uno-",
|
|
86
|
-
combine = true,
|
|
87
|
-
hashFn = hash
|
|
88
|
-
} = options;
|
|
89
|
-
if (combine) {
|
|
90
|
-
const classPlusFilenameHash = hashFn(body + filename);
|
|
91
|
-
return `${classPrefix}${classPlusFilenameHash}`;
|
|
92
|
-
} else {
|
|
93
|
-
const filenameHash = hashFn(filename);
|
|
94
|
-
return `_${body}_${filenameHash}`;
|
|
95
|
-
}
|
|
96
|
-
}
|
|
97
|
-
|
|
98
|
-
function isShortcut(token, shortcuts) {
|
|
99
|
-
return shortcuts.some((s) => s[0] === token);
|
|
100
|
-
}
|
|
101
|
-
|
|
102
|
-
async function processDirective({ body: token, start, end, type }, options, uno, filename) {
|
|
103
|
-
const isShortcutOrUtility = isShortcut(token, uno.config.shortcuts) || await needsGenerated(token, uno);
|
|
104
|
-
if (!isShortcutOrUtility)
|
|
105
|
-
return;
|
|
106
|
-
const generatedClassName = generateClassName(token, options, filename);
|
|
107
|
-
const content = type === "directiveShorthand" ? `${generatedClassName}={${token}}` : generatedClassName;
|
|
108
|
-
return {
|
|
109
|
-
rulesToGenerate: { [generatedClassName]: [token] },
|
|
110
|
-
codeUpdate: { content, start, end }
|
|
111
|
-
};
|
|
112
|
-
}
|
|
113
|
-
|
|
114
|
-
async function sortClassesIntoCategories(body, options, uno, filename) {
|
|
115
|
-
const { combine = true } = options;
|
|
116
|
-
const rulesToGenerate = {};
|
|
117
|
-
const ignore = [];
|
|
118
|
-
const classes = body.trim().split(/\s+/);
|
|
119
|
-
const knownClassesToCombine = [];
|
|
120
|
-
for (const token of classes) {
|
|
121
|
-
const isShortcutOrUtility = isShortcut(token, uno.config.shortcuts) || await needsGenerated(token, uno);
|
|
122
|
-
if (!isShortcutOrUtility) {
|
|
123
|
-
ignore.push(token);
|
|
124
|
-
continue;
|
|
125
|
-
}
|
|
126
|
-
if (combine) {
|
|
127
|
-
knownClassesToCombine.push(token);
|
|
128
|
-
} else {
|
|
129
|
-
const generatedClassName = generateClassName(token, options, filename);
|
|
130
|
-
rulesToGenerate[generatedClassName] = [token];
|
|
131
|
-
}
|
|
132
|
-
}
|
|
133
|
-
if (knownClassesToCombine.length) {
|
|
134
|
-
const generatedClassName = generateClassName(knownClassesToCombine.join(" "), options, filename);
|
|
135
|
-
rulesToGenerate[generatedClassName] = knownClassesToCombine;
|
|
136
|
-
}
|
|
137
|
-
return { rulesToGenerate, ignore };
|
|
138
|
-
}
|
|
139
|
-
|
|
140
|
-
const expressionsRE = /\S*{[^{}]+?}\S*/g;
|
|
141
|
-
const classesRE = /(["'\`])([\S\s]*?)\1/g;
|
|
142
|
-
async function processExpressions(body, options, uno, filename) {
|
|
143
|
-
const rulesToGenerate = {};
|
|
144
|
-
const updatedExpressions = [];
|
|
145
|
-
let restOfBody = body;
|
|
146
|
-
const expressions = [...body.matchAll(expressionsRE)];
|
|
147
|
-
for (let [expression] of expressions) {
|
|
148
|
-
restOfBody = restOfBody.replace(expression, "").trim();
|
|
149
|
-
const classes = [...expression.matchAll(classesRE)];
|
|
150
|
-
for (const [withQuotes, quoteMark, withoutQuotes] of classes) {
|
|
151
|
-
const { rulesToGenerate: rulesFromExpression, ignore } = await sortClassesIntoCategories(withoutQuotes, options, uno, filename);
|
|
152
|
-
Object.assign(rulesToGenerate, rulesFromExpression);
|
|
153
|
-
const updatedClasses = Object.keys(rulesFromExpression).concat(ignore).join(" ");
|
|
154
|
-
expression = expression.replace(withQuotes, quoteMark + updatedClasses + quoteMark);
|
|
155
|
-
}
|
|
156
|
-
updatedExpressions.push(expression);
|
|
157
|
-
}
|
|
158
|
-
return { rulesToGenerate, updatedExpressions, restOfBody };
|
|
159
|
-
}
|
|
160
|
-
|
|
161
|
-
async function processClassBody({ body, start, end }, options, uno, filename) {
|
|
162
|
-
const expandedBody = core.expandVariantGroup(body);
|
|
163
|
-
const { rulesToGenerate: rulesFromExpressions, restOfBody, updatedExpressions } = await processExpressions(expandedBody, options, uno, filename);
|
|
164
|
-
const { rulesToGenerate: rulesFromRegularClasses, ignore } = await sortClassesIntoCategories(restOfBody, options, uno, filename);
|
|
165
|
-
const rulesToGenerate = { ...rulesFromExpressions, ...rulesFromRegularClasses };
|
|
166
|
-
if (!Object.keys(rulesToGenerate).length)
|
|
167
|
-
return {};
|
|
168
|
-
const content = Object.keys(rulesFromRegularClasses).concat(ignore).concat(updatedExpressions).join(" ");
|
|
169
|
-
const codeUpdate = {
|
|
170
|
-
content,
|
|
171
|
-
start,
|
|
172
|
-
end
|
|
173
|
-
};
|
|
174
|
-
return { rulesToGenerate, codeUpdate };
|
|
175
|
-
}
|
|
176
|
-
|
|
177
|
-
async function processClasses(classes, options, uno, filename) {
|
|
178
|
-
const result = {
|
|
179
|
-
rulesToGenerate: {},
|
|
180
|
-
codeUpdates: []
|
|
181
|
-
};
|
|
182
|
-
for (const foundClass of classes) {
|
|
183
|
-
if (foundClass.type === "regular") {
|
|
184
|
-
const { rulesToGenerate, codeUpdate } = await processClassBody(foundClass, options, uno, filename);
|
|
185
|
-
if (rulesToGenerate)
|
|
186
|
-
Object.assign(result.rulesToGenerate, rulesToGenerate);
|
|
187
|
-
if (codeUpdate)
|
|
188
|
-
result.codeUpdates.push(codeUpdate);
|
|
189
|
-
} else {
|
|
190
|
-
const { rulesToGenerate, codeUpdate } = await processDirective(foundClass, options, uno, filename) || {};
|
|
191
|
-
if (rulesToGenerate)
|
|
192
|
-
Object.assign(result.rulesToGenerate, rulesToGenerate);
|
|
193
|
-
if (codeUpdate)
|
|
194
|
-
result.codeUpdates.push(codeUpdate);
|
|
195
|
-
}
|
|
196
|
-
}
|
|
197
|
-
return result;
|
|
198
|
-
}
|
|
199
|
-
|
|
200
|
-
async function transformClasses({ content, filename, uno, options }) {
|
|
201
|
-
const classesToProcess = findClasses(content);
|
|
202
|
-
if (!classesToProcess.length)
|
|
203
|
-
return;
|
|
204
|
-
const { rulesToGenerate, codeUpdates } = await processClasses(classesToProcess, options, uno, filename);
|
|
205
|
-
if (!Object.keys(rulesToGenerate).length)
|
|
206
|
-
return;
|
|
207
|
-
const { map, code } = updateTemplateCodeIfNeeded(codeUpdates, content, filename);
|
|
208
|
-
const generatedStyles = await generateStyles(rulesToGenerate, uno);
|
|
209
|
-
const codeWithGeneratedStyles = addGeneratedStylesIntoStyleBlock(code, generatedStyles);
|
|
210
|
-
return {
|
|
211
|
-
code: codeWithGeneratedStyles,
|
|
212
|
-
map
|
|
213
|
-
};
|
|
214
|
-
}
|
|
215
|
-
function updateTemplateCodeIfNeeded(codeUpdates, source, filename) {
|
|
216
|
-
if (!codeUpdates.length)
|
|
217
|
-
return { code: source, map: void 0 };
|
|
218
|
-
const s = new MagicString__default(source);
|
|
219
|
-
for (const { start, end, content } of codeUpdates)
|
|
220
|
-
s.overwrite(start, end, content);
|
|
221
|
-
return {
|
|
222
|
-
code: s.toString(),
|
|
223
|
-
map: s.generateMap({ hires: true, source: filename })
|
|
224
|
-
};
|
|
225
|
-
}
|
|
226
|
-
const REMOVE_COMMENTS_TO_MAKE_GLOBAL_WRAPPING_EASY = true;
|
|
227
|
-
async function generateStyles(rulesToGenerate, uno) {
|
|
228
|
-
const shortcutsForThisComponent = Object.entries(rulesToGenerate);
|
|
229
|
-
uno.config.shortcuts.push(...shortcutsForThisComponent);
|
|
230
|
-
const selectorsToGenerate = Object.keys(rulesToGenerate);
|
|
231
|
-
const { css } = await uno.generate(selectorsToGenerate, {
|
|
232
|
-
preflights: false,
|
|
233
|
-
safelist: false,
|
|
234
|
-
minify: REMOVE_COMMENTS_TO_MAKE_GLOBAL_WRAPPING_EASY
|
|
235
|
-
});
|
|
236
|
-
const cssPreparedForSvelteCompiler = wrapSelectorsWithGlobal(css);
|
|
237
|
-
return cssPreparedForSvelteCompiler;
|
|
238
|
-
}
|
|
239
|
-
|
|
240
|
-
function removeOuterQuotes(input) {
|
|
241
|
-
if (!input)
|
|
242
|
-
return "";
|
|
243
|
-
return /^(['"]).*\1$/.test(input) ? input.slice(1, -1) : input;
|
|
244
|
-
}
|
|
245
|
-
|
|
246
|
-
function writeUtilStyles([, selector, body, parent], s, node, childNode) {
|
|
247
|
-
if (!selector)
|
|
248
|
-
return;
|
|
249
|
-
const selectorChanged = selector !== ".\\-";
|
|
250
|
-
if (!parent && !selectorChanged)
|
|
251
|
-
return s.appendRight(childNode.loc.end.offset, body);
|
|
252
|
-
const originalSelector = cssTree.generate(node.prelude);
|
|
253
|
-
if (parent && !selectorChanged) {
|
|
254
|
-
const css2 = `${parent}{${originalSelector}{${body}}}`;
|
|
255
|
-
return s.appendLeft(node.loc.end.offset, css2);
|
|
256
|
-
}
|
|
257
|
-
const utilSelector = selector.replace(core.regexScopePlaceholder, " ");
|
|
258
|
-
const updatedSelector = generateUpdatedSelector(utilSelector, node.prelude);
|
|
259
|
-
const svelteCompilerReadySelector = surroundAllButOriginalSelectorWithGlobal(originalSelector, updatedSelector);
|
|
260
|
-
const rule = `${svelteCompilerReadySelector}{${body}}`;
|
|
261
|
-
const css = parent ? `${parent}{${rule}}` : rule;
|
|
262
|
-
s.appendLeft(node.loc.end.offset, css);
|
|
263
|
-
}
|
|
264
|
-
function generateUpdatedSelector(selector, _prelude) {
|
|
265
|
-
const selectorAST = cssTree.parse(selector, {
|
|
266
|
-
context: "selector"
|
|
267
|
-
});
|
|
268
|
-
const prelude = cssTree.clone(_prelude);
|
|
269
|
-
prelude.children.forEach((child) => {
|
|
270
|
-
const parentSelectorAst = cssTree.clone(selectorAST);
|
|
271
|
-
parentSelectorAst.children.forEach((i) => {
|
|
272
|
-
if (i.type === "ClassSelector" && i.name === "\\-")
|
|
273
|
-
Object.assign(i, cssTree.clone(child));
|
|
274
|
-
});
|
|
275
|
-
Object.assign(child, parentSelectorAst);
|
|
276
|
-
});
|
|
277
|
-
return cssTree.generate(prelude);
|
|
278
|
-
}
|
|
279
|
-
function surroundAllButOriginalSelectorWithGlobal(originalSelector, updatedSelector) {
|
|
280
|
-
const wrapWithGlobal = (str) => `:global(${str})`;
|
|
281
|
-
const originalSelectors = originalSelector.split(",").map((s) => s.trim());
|
|
282
|
-
const updatedSelectors = updatedSelector.split(",").map((s) => s.trim());
|
|
283
|
-
const resultSelectors = originalSelectors.map((original, index) => {
|
|
284
|
-
const updated = updatedSelectors[index];
|
|
285
|
-
const [prefix, suffix] = updated.split(original).map((s) => s.trim());
|
|
286
|
-
const wrappedPrefix = prefix ? wrapWithGlobal(prefix) : "";
|
|
287
|
-
if (!suffix)
|
|
288
|
-
return `${wrappedPrefix} ${original}`.trim();
|
|
289
|
-
const indexOfFirstCombinator = findFirstCombinatorIndex(suffix);
|
|
290
|
-
if (indexOfFirstCombinator === -1)
|
|
291
|
-
return `${wrappedPrefix} ${original}${suffix}`.trim();
|
|
292
|
-
const pseudo = suffix.substring(0, indexOfFirstCombinator).trim();
|
|
293
|
-
const siblingsOrDescendants = suffix.substring(indexOfFirstCombinator).trim();
|
|
294
|
-
return `${wrappedPrefix} ${original}${pseudo} ${wrapWithGlobal(siblingsOrDescendants)}`.trim();
|
|
295
|
-
});
|
|
296
|
-
return resultSelectors.join(", ");
|
|
297
|
-
}
|
|
298
|
-
function findFirstCombinatorIndex(input) {
|
|
299
|
-
const combinators = [" ", ">", "~", "+"];
|
|
300
|
-
for (const c of combinators) {
|
|
301
|
-
const indexOfFirstCombinator = input.indexOf(c);
|
|
302
|
-
if (indexOfFirstCombinator !== -1)
|
|
303
|
-
return indexOfFirstCombinator;
|
|
304
|
-
}
|
|
305
|
-
return -1;
|
|
306
|
-
}
|
|
307
|
-
|
|
308
|
-
async function getUtils(body, uno) {
|
|
309
|
-
const classNames = core.expandVariantGroup(body).split(/\s+/g).map((className) => className.trim().replace(/\\/, ""));
|
|
310
|
-
const utils = await parseUtils(classNames, uno);
|
|
311
|
-
const sortedByRankIndex = utils.sort(([aIndex], [bIndex]) => aIndex - bIndex);
|
|
312
|
-
const sortedByParentOrders = sortedByRankIndex.sort(([, , , aParent], [, , , bParent]) => (aParent ? uno.parentOrders.get(aParent) ?? 0 : 0) - (bParent ? uno.parentOrders.get(bParent) ?? 0 : 0));
|
|
313
|
-
return sortedByParentOrders.reduce((acc, item) => {
|
|
314
|
-
const [, selector, body2, parent] = item;
|
|
315
|
-
const sibling = acc.find(([, targetSelector, , targetParent]) => targetSelector === selector && targetParent === parent);
|
|
316
|
-
if (sibling)
|
|
317
|
-
sibling[2] += body2;
|
|
318
|
-
else
|
|
319
|
-
acc.push([...item]);
|
|
320
|
-
return acc;
|
|
321
|
-
}, []);
|
|
322
|
-
}
|
|
323
|
-
async function parseUtils(classNames, uno) {
|
|
324
|
-
const foundUtils = [];
|
|
325
|
-
for (const token of classNames) {
|
|
326
|
-
const util = await uno.parseToken(token, "-");
|
|
327
|
-
if (util)
|
|
328
|
-
foundUtils.push(util);
|
|
329
|
-
else
|
|
330
|
-
core.warnOnce(`'${token}' not found. You have a typo or need to add a preset.`);
|
|
331
|
-
}
|
|
332
|
-
return foundUtils.flat();
|
|
333
|
-
}
|
|
334
|
-
|
|
335
|
-
async function transformApply(ctx) {
|
|
336
|
-
const ast = cssTree.parse(ctx.s.original, {
|
|
337
|
-
parseAtrulePrelude: false,
|
|
338
|
-
positions: true
|
|
339
|
-
});
|
|
340
|
-
if (ast.type !== "StyleSheet")
|
|
341
|
-
return ctx.s;
|
|
342
|
-
const stack = [];
|
|
343
|
-
cssTree.walk(ast, (node) => {
|
|
344
|
-
if (node.type === "Rule")
|
|
345
|
-
stack.push(handleApply(ctx, node));
|
|
346
|
-
});
|
|
347
|
-
await Promise.all(stack);
|
|
348
|
-
return ctx.s;
|
|
349
|
-
}
|
|
350
|
-
async function handleApply(ctx, node) {
|
|
351
|
-
const parsePromises = node.block.children.map(async (childNode) => {
|
|
352
|
-
await parseApply(ctx, node, childNode);
|
|
353
|
-
});
|
|
354
|
-
await Promise.all(parsePromises);
|
|
355
|
-
}
|
|
356
|
-
async function parseApply({ s, uno, applyVariables }, node, childNode) {
|
|
357
|
-
const body = getChildNodeValue(childNode, applyVariables);
|
|
358
|
-
if (!body)
|
|
359
|
-
return;
|
|
360
|
-
const utils = await getUtils(body, uno);
|
|
361
|
-
if (!utils.length)
|
|
362
|
-
return;
|
|
363
|
-
for (const util of utils)
|
|
364
|
-
writeUtilStyles(util, s, node, childNode);
|
|
365
|
-
s.remove(childNode.loc.start.offset, childNode.loc.end.offset);
|
|
366
|
-
}
|
|
367
|
-
function getChildNodeValue(childNode, applyVariables) {
|
|
368
|
-
if (childNode.type === "Atrule" && childNode.name === "apply" && childNode.prelude && childNode.prelude.type === "Raw")
|
|
369
|
-
return childNode.prelude.value.trim();
|
|
370
|
-
if (childNode.type === "Declaration" && applyVariables.includes(childNode.property) && childNode.value.type === "Raw")
|
|
371
|
-
return removeOuterQuotes(childNode.value.value.trim());
|
|
372
|
-
}
|
|
373
|
-
|
|
374
|
-
const themeRE = /theme\((.+?)\)/g;
|
|
375
|
-
function transformTheme(s, theme) {
|
|
376
|
-
return s.replace(themeRE, (_, match) => {
|
|
377
|
-
const argumentsWithoutQuotes = match.slice(1, -1);
|
|
378
|
-
return getThemeValue(argumentsWithoutQuotes, theme);
|
|
379
|
-
});
|
|
380
|
-
}
|
|
381
|
-
function getThemeValue(rawArguments, theme) {
|
|
382
|
-
const keys = rawArguments.split(".");
|
|
383
|
-
let current = theme;
|
|
384
|
-
for (const key of keys) {
|
|
385
|
-
if (current[key] === void 0)
|
|
386
|
-
throw new Error(`"${rawArguments}" is not found in your theme`);
|
|
387
|
-
else
|
|
388
|
-
current = current[key];
|
|
389
|
-
}
|
|
390
|
-
return current;
|
|
391
|
-
}
|
|
392
|
-
|
|
393
|
-
const DEFAULT_APPLY_VARIABLES = ["--at-apply"];
|
|
394
|
-
function checkForApply(content, _applyVariables) {
|
|
395
|
-
if (_applyVariables === false)
|
|
396
|
-
return { hasApply: false, applyVariables: [] };
|
|
397
|
-
const applyVariables = core.toArray(_applyVariables || DEFAULT_APPLY_VARIABLES);
|
|
398
|
-
return {
|
|
399
|
-
hasApply: content.includes("@apply") || applyVariables.some((v) => content.includes(v)),
|
|
400
|
-
applyVariables
|
|
401
|
-
};
|
|
402
|
-
}
|
|
403
|
-
async function transformStyle({
|
|
404
|
-
content,
|
|
405
|
-
uno,
|
|
406
|
-
prepend,
|
|
407
|
-
filename,
|
|
408
|
-
applyVariables,
|
|
409
|
-
hasThemeFn
|
|
410
|
-
}) {
|
|
411
|
-
const s = new MagicString__default(content);
|
|
412
|
-
if (applyVariables?.length)
|
|
413
|
-
await transformApply({ s, uno, applyVariables });
|
|
414
|
-
if (hasThemeFn)
|
|
415
|
-
transformTheme(s, uno.config.theme);
|
|
416
|
-
if (!s.hasChanged())
|
|
417
|
-
return;
|
|
418
|
-
if (prepend)
|
|
419
|
-
s.prepend(prepend);
|
|
420
|
-
return {
|
|
421
|
-
code: s.toString(),
|
|
422
|
-
map: s.generateMap({ hires: true, source: filename || "" })
|
|
423
|
-
};
|
|
424
|
-
}
|
|
425
|
-
|
|
426
|
-
function UnocssSveltePreprocess(options = {}, unoContextFromVite, isViteBuild) {
|
|
427
|
-
if (!options.classPrefix)
|
|
428
|
-
options.classPrefix = "usp-";
|
|
429
|
-
let uno;
|
|
430
|
-
return {
|
|
431
|
-
markup: async ({ content, filename }) => {
|
|
432
|
-
if (!uno)
|
|
433
|
-
uno = await getGenerator(options.configOrPath, unoContextFromVite);
|
|
434
|
-
if (isViteBuild && options.combine === void 0)
|
|
435
|
-
options.combine = isViteBuild();
|
|
436
|
-
return await transformClasses({ content, filename: filename || "", uno, options });
|
|
437
|
-
},
|
|
438
|
-
style: async ({ content, attributes, filename }) => {
|
|
439
|
-
const svelte3AddPreflights = attributes["uno:preflights"];
|
|
440
|
-
const svelte3AddSafelist = attributes["uno:safelist"];
|
|
441
|
-
const svelte4DeprecatedAddPreflights = attributes.uno && attributes.preflights;
|
|
442
|
-
const svelte4DeprecatedAddSafelist = attributes.uno && attributes.safelist;
|
|
443
|
-
let addPreflights = attributes["uno-preflights"] || svelte3AddPreflights || svelte4DeprecatedAddPreflights;
|
|
444
|
-
let addSafelist = attributes["uno-safelist"] || svelte3AddSafelist || svelte4DeprecatedAddSafelist;
|
|
445
|
-
if (unoContextFromVite && (addPreflights || addSafelist)) {
|
|
446
|
-
addPreflights = false;
|
|
447
|
-
addSafelist = false;
|
|
448
|
-
core.warnOnce("Notice for those transitioning to @unocss/svelte-scoped/vite: uno-preflights and uno-safelist are only for use in component libraries. Please see the documentation for how to add preflights and safelist into your head tag. If you are consuming a component library built by @unocss/svelte-scoped/preprocess, you can ignore this upgrade notice.");
|
|
449
|
-
}
|
|
450
|
-
const { hasApply, applyVariables } = checkForApply(content, options.applyVariables);
|
|
451
|
-
const hasThemeFn = !!content.match(themeRE);
|
|
452
|
-
const changeNeeded = addPreflights || addSafelist || hasApply || hasThemeFn;
|
|
453
|
-
if (!changeNeeded)
|
|
454
|
-
return;
|
|
455
|
-
if (!uno)
|
|
456
|
-
uno = await getGenerator(options.configOrPath);
|
|
457
|
-
let preflightsSafelistCss = "";
|
|
458
|
-
if (addPreflights || addSafelist) {
|
|
459
|
-
const { css } = await uno.generate([], { preflights: !!addPreflights, safelist: !!addSafelist, minify: true });
|
|
460
|
-
preflightsSafelistCss = wrapSelectorsWithGlobal(css);
|
|
461
|
-
}
|
|
462
|
-
if (hasApply || hasThemeFn) {
|
|
463
|
-
return await transformStyle({
|
|
464
|
-
content,
|
|
465
|
-
uno,
|
|
466
|
-
filename,
|
|
467
|
-
prepend: preflightsSafelistCss,
|
|
468
|
-
applyVariables,
|
|
469
|
-
hasThemeFn
|
|
470
|
-
});
|
|
471
|
-
}
|
|
472
|
-
if (preflightsSafelistCss)
|
|
473
|
-
return { code: preflightsSafelistCss + content };
|
|
474
|
-
}
|
|
475
|
-
};
|
|
476
|
-
}
|
|
477
|
-
async function getGenerator(configOrPath, unoContextFromVite) {
|
|
478
|
-
if (unoContextFromVite) {
|
|
479
|
-
await unoContextFromVite.ready;
|
|
480
|
-
return unoContextFromVite.uno;
|
|
481
|
-
}
|
|
482
|
-
const defaults = {
|
|
483
|
-
presets: [
|
|
484
|
-
presetUno__default()
|
|
485
|
-
]
|
|
486
|
-
};
|
|
487
|
-
const { config: config$1 } = await config.loadConfig(process__default.cwd(), configOrPath);
|
|
488
|
-
return core.createGenerator(config$1, defaults);
|
|
489
|
-
}
|
|
490
|
-
|
|
491
|
-
exports.UnocssSveltePreprocess = UnocssSveltePreprocess;
|
package/dist/vite.cjs
DELETED
|
@@ -1,304 +0,0 @@
|
|
|
1
|
-
'use strict';
|
|
2
|
-
|
|
3
|
-
const process = require('node:process');
|
|
4
|
-
const core = require('@unocss/core');
|
|
5
|
-
const config = require('@unocss/config');
|
|
6
|
-
const presetUno = require('@unocss/preset-uno');
|
|
7
|
-
const index = require('./shared/svelte-scoped.pPNrJCJJ.cjs');
|
|
8
|
-
const node_fs = require('node:fs');
|
|
9
|
-
const node_path = require('node:path');
|
|
10
|
-
const node_url = require('node:url');
|
|
11
|
-
const MagicString = require('magic-string');
|
|
12
|
-
const remapping = require('@ampproject/remapping');
|
|
13
|
-
require('node:crypto');
|
|
14
|
-
require('css-tree');
|
|
15
|
-
|
|
16
|
-
var _documentCurrentScript = typeof document !== 'undefined' ? document.currentScript : null;
|
|
17
|
-
function _interopDefaultCompat (e) { return e && typeof e === 'object' && 'default' in e ? e.default : e; }
|
|
18
|
-
|
|
19
|
-
const process__default = /*#__PURE__*/_interopDefaultCompat(process);
|
|
20
|
-
const presetUno__default = /*#__PURE__*/_interopDefaultCompat(presetUno);
|
|
21
|
-
const MagicString__default = /*#__PURE__*/_interopDefaultCompat(MagicString);
|
|
22
|
-
const remapping__default = /*#__PURE__*/_interopDefaultCompat(remapping);
|
|
23
|
-
|
|
24
|
-
function PassPreprocessToSveltePlugin(context, options = {}) {
|
|
25
|
-
let commandIsBuild = true;
|
|
26
|
-
const isBuild = () => commandIsBuild;
|
|
27
|
-
return {
|
|
28
|
-
name: "unocss:svelte-scoped:pass-preprocess",
|
|
29
|
-
enforce: "pre",
|
|
30
|
-
configResolved({ command }) {
|
|
31
|
-
commandIsBuild = command === "build";
|
|
32
|
-
},
|
|
33
|
-
api: {
|
|
34
|
-
sveltePreprocess: index.UnocssSveltePreprocess(options, context, isBuild)
|
|
35
|
-
}
|
|
36
|
-
};
|
|
37
|
-
}
|
|
38
|
-
|
|
39
|
-
const PLACEHOLDER_USER_SETS_IN_INDEX_HTML = "%unocss-svelte-scoped.global%";
|
|
40
|
-
const GLOBAL_STYLES_PLACEHOLDER = "unocss_svelte_scoped_global_styles";
|
|
41
|
-
const DEV_GLOBAL_STYLES_DATA_TITLE = "unocss-svelte-scoped global styles";
|
|
42
|
-
|
|
43
|
-
const _dirname = typeof __dirname !== "undefined" ? __dirname : node_path.dirname(node_url.fileURLToPath((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.src || new URL('vite.cjs', document.baseURI).href))));
|
|
44
|
-
function getReset(injectReset) {
|
|
45
|
-
if (injectReset.startsWith("@unocss/reset")) {
|
|
46
|
-
const resolvedPNPM = node_path.resolve(node_path.resolve(_dirname, `../../../${injectReset}`));
|
|
47
|
-
if (isFile(resolvedPNPM))
|
|
48
|
-
return node_fs.readFileSync(resolvedPNPM, "utf-8");
|
|
49
|
-
const resolvedPNPM_in_uno_repo = node_path.resolve(node_path.resolve(_dirname, `../node_modules/${injectReset}`));
|
|
50
|
-
if (isFile(resolvedPNPM_in_uno_repo))
|
|
51
|
-
return node_fs.readFileSync(resolvedPNPM_in_uno_repo, "utf-8");
|
|
52
|
-
const resolvedNPM = node_path.resolve(process__default.cwd(), "node_modules", injectReset);
|
|
53
|
-
if (isFile(resolvedNPM))
|
|
54
|
-
return node_fs.readFileSync(resolvedNPM, "utf-8");
|
|
55
|
-
throw new Error(`"${injectReset}" given as your injectReset value is not found. Please make sure it is one of the five supported @unocss/reset options. If it is, file a bug report detailing your environment and package manager`);
|
|
56
|
-
}
|
|
57
|
-
if (injectReset.startsWith(".")) {
|
|
58
|
-
const resolved = node_path.resolve(process__default.cwd(), injectReset);
|
|
59
|
-
if (!isFile(resolved))
|
|
60
|
-
throw new Error(`"${injectReset}" given as your injectReset value is not a valid file path relative to the root of your project, where your vite config file sits. To give an example, if you placed a reset.css in your src directory, "./src/reset.css" would work.`);
|
|
61
|
-
return node_fs.readFileSync(resolved, "utf-8");
|
|
62
|
-
}
|
|
63
|
-
if (injectReset.startsWith("/"))
|
|
64
|
-
throw new Error(`Your injectReset value: "${injectReset}" is not a valid file path. To give an example, if you placed a reset.css in your src directory, "./src/reset.css" would work.`);
|
|
65
|
-
const resolvedFromNodeModules = node_path.resolve(process__default.cwd(), "node_modules", injectReset);
|
|
66
|
-
if (!isFile(resolvedFromNodeModules))
|
|
67
|
-
throw new Error(`"${injectReset}" given as your injectReset value is not a valid file path relative to your project's node_modules folder. Can you confirm that you've installed "${injectReset}"?`);
|
|
68
|
-
return node_fs.readFileSync(resolvedFromNodeModules, "utf-8");
|
|
69
|
-
}
|
|
70
|
-
function isFile(path) {
|
|
71
|
-
return node_fs.existsSync(path) && node_fs.statSync(path).isFile();
|
|
72
|
-
}
|
|
73
|
-
|
|
74
|
-
function isServerHooksFile(path) {
|
|
75
|
-
return path.includes("hooks") && path.includes("server");
|
|
76
|
-
}
|
|
77
|
-
function replaceGlobalStylesPlaceholder(code, stylesTag) {
|
|
78
|
-
const captureQuoteMark = "([\"'`])";
|
|
79
|
-
const matchCapturedQuoteMark = "\\1";
|
|
80
|
-
const QUOTES_WITH_PLACEHOLDER_RE = new RegExp(captureQuoteMark + GLOBAL_STYLES_PLACEHOLDER + matchCapturedQuoteMark);
|
|
81
|
-
const escapedStylesTag = stylesTag.replaceAll(/\\(?![`$])/g, "\\\\").replaceAll(/(?<!\\)([`$])/g, "\\$1");
|
|
82
|
-
return code.replace(QUOTES_WITH_PLACEHOLDER_RE, `\`${escapedStylesTag}\``);
|
|
83
|
-
}
|
|
84
|
-
async function generateGlobalCss(uno, injectReset) {
|
|
85
|
-
const { css } = await uno.generate("", { preflights: true, safelist: true, minify: true });
|
|
86
|
-
const reset = injectReset ? getReset(injectReset) : "";
|
|
87
|
-
return reset + css;
|
|
88
|
-
}
|
|
89
|
-
const SVELTE_ERROR = `[unocss] You have not setup the svelte-scoped global styles correctly. You must place '${PLACEHOLDER_USER_SETS_IN_INDEX_HTML}' in your index.html file.
|
|
90
|
-
`;
|
|
91
|
-
const SVELTE_KIT_ERROR = `[unocss] You have not setup the svelte-scoped global styles correctly. You must place '${PLACEHOLDER_USER_SETS_IN_INDEX_HTML}' in your app.html file. You also need to have a transformPageChunk hook in your hooks.server.js file with: \`html.replace('${PLACEHOLDER_USER_SETS_IN_INDEX_HTML}', '${GLOBAL_STYLES_PLACEHOLDER}')\`. You can see an example of the usage at https://github.com/unocss/unocss/tree/main/examples/sveltekit-scoped.`;
|
|
92
|
-
function checkTransformPageChunkHook(server, isSvelteKit) {
|
|
93
|
-
server.middlewares.use((req, res, next) => {
|
|
94
|
-
const originalWrite = res.write;
|
|
95
|
-
res.write = function(chunk, ...rest) {
|
|
96
|
-
const str = typeof chunk === "string" ? chunk : chunk instanceof Buffer ? chunk.toString() : Array.isArray(chunk) || "at" in chunk ? Buffer.from(chunk).toString() : `${chunk}`;
|
|
97
|
-
if (str.includes("<head>") && !str.includes(DEV_GLOBAL_STYLES_DATA_TITLE))
|
|
98
|
-
server.config.logger.error(isSvelteKit ? SVELTE_KIT_ERROR : SVELTE_ERROR, { timestamp: true });
|
|
99
|
-
return originalWrite.call(this, chunk, ...rest);
|
|
100
|
-
};
|
|
101
|
-
next();
|
|
102
|
-
});
|
|
103
|
-
}
|
|
104
|
-
|
|
105
|
-
function GlobalStylesPlugin({ ready, uno }, injectReset) {
|
|
106
|
-
let isSvelteKit;
|
|
107
|
-
let viteConfig;
|
|
108
|
-
let unoCssFileReferenceId;
|
|
109
|
-
let unoCssHashedLinkTag;
|
|
110
|
-
return {
|
|
111
|
-
name: "unocss:svelte-scoped:global-styles",
|
|
112
|
-
async configResolved(_viteConfig) {
|
|
113
|
-
viteConfig = _viteConfig;
|
|
114
|
-
await ready;
|
|
115
|
-
isSvelteKit = viteConfig.plugins.some((p) => p.name.includes("sveltekit"));
|
|
116
|
-
},
|
|
117
|
-
// serve
|
|
118
|
-
configureServer: (server) => checkTransformPageChunkHook(server, isSvelteKit),
|
|
119
|
-
// serve
|
|
120
|
-
async transform(code, id) {
|
|
121
|
-
if (isSvelteKit && viteConfig.command === "serve" && isServerHooksFile(id)) {
|
|
122
|
-
const css = await generateGlobalCss(uno, injectReset);
|
|
123
|
-
return {
|
|
124
|
-
code: replaceGlobalStylesPlaceholder(code, `<style type="text/css" data-title="${DEV_GLOBAL_STYLES_DATA_TITLE}">${css}</style>`)
|
|
125
|
-
};
|
|
126
|
-
}
|
|
127
|
-
},
|
|
128
|
-
// build
|
|
129
|
-
async buildStart() {
|
|
130
|
-
if (viteConfig.command === "build") {
|
|
131
|
-
const css = await generateGlobalCss(uno, injectReset);
|
|
132
|
-
unoCssFileReferenceId = this.emitFile({
|
|
133
|
-
type: "asset",
|
|
134
|
-
name: "unocss-svelte-scoped-global.css",
|
|
135
|
-
source: css
|
|
136
|
-
});
|
|
137
|
-
}
|
|
138
|
-
},
|
|
139
|
-
// build
|
|
140
|
-
renderStart() {
|
|
141
|
-
const unoCssFileName = this.getFileName(unoCssFileReferenceId);
|
|
142
|
-
const base = viteConfig.base ?? "/";
|
|
143
|
-
unoCssHashedLinkTag = `<link href="${base}${unoCssFileName}" rel="stylesheet" />`;
|
|
144
|
-
},
|
|
145
|
-
// build
|
|
146
|
-
renderChunk(code, chunk) {
|
|
147
|
-
if (isSvelteKit && chunk.moduleIds.some((id) => isServerHooksFile(id)))
|
|
148
|
-
return replaceGlobalStylesPlaceholder(code, unoCssHashedLinkTag);
|
|
149
|
-
},
|
|
150
|
-
// serve and build
|
|
151
|
-
async transformIndexHtml(html) {
|
|
152
|
-
if (!isSvelteKit) {
|
|
153
|
-
if (viteConfig.command === "build")
|
|
154
|
-
return html.replace(PLACEHOLDER_USER_SETS_IN_INDEX_HTML, unoCssHashedLinkTag);
|
|
155
|
-
if (viteConfig.command === "serve") {
|
|
156
|
-
const css = await generateGlobalCss(uno, injectReset);
|
|
157
|
-
return html.replace(PLACEHOLDER_USER_SETS_IN_INDEX_HTML, `<style type="text/css" data-title="${DEV_GLOBAL_STYLES_DATA_TITLE}">${css}</style>`);
|
|
158
|
-
}
|
|
159
|
-
}
|
|
160
|
-
}
|
|
161
|
-
};
|
|
162
|
-
}
|
|
163
|
-
|
|
164
|
-
const IGNORE_COMMENT = "@unocss-ignore";
|
|
165
|
-
const SKIP_START_COMMENT = "@unocss-skip-start";
|
|
166
|
-
const SKIP_END_COMMENT = "@unocss-skip-end";
|
|
167
|
-
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");
|
|
168
|
-
|
|
169
|
-
function hash(str) {
|
|
170
|
-
let i;
|
|
171
|
-
let l;
|
|
172
|
-
let hval = 2166136261;
|
|
173
|
-
for (i = 0, l = str.length; i < l; i++) {
|
|
174
|
-
hval ^= str.charCodeAt(i);
|
|
175
|
-
hval += (hval << 1) + (hval << 4) + (hval << 7) + (hval << 8) + (hval << 24);
|
|
176
|
-
}
|
|
177
|
-
return `00000${(hval >>> 0).toString(36)}`.slice(-6);
|
|
178
|
-
}
|
|
179
|
-
|
|
180
|
-
async function applyTransformers(ctx, original, id, enforce = "default") {
|
|
181
|
-
if (original.includes(IGNORE_COMMENT))
|
|
182
|
-
return;
|
|
183
|
-
const transformers = (ctx.uno.config.transformers || []).filter((i) => (i.enforce || "default") === enforce);
|
|
184
|
-
if (!transformers.length)
|
|
185
|
-
return;
|
|
186
|
-
const skipMap = /* @__PURE__ */ new Map();
|
|
187
|
-
let code = original;
|
|
188
|
-
let s = new MagicString__default(transformSkipCode(code, skipMap));
|
|
189
|
-
const maps = [];
|
|
190
|
-
for (const t of transformers) {
|
|
191
|
-
if (t.idFilter) {
|
|
192
|
-
if (!t.idFilter(id))
|
|
193
|
-
continue;
|
|
194
|
-
} else if (!ctx.filter(code, id)) {
|
|
195
|
-
continue;
|
|
196
|
-
}
|
|
197
|
-
await t.transform(s, id, ctx);
|
|
198
|
-
if (s.hasChanged()) {
|
|
199
|
-
code = restoreSkipCode(s.toString(), skipMap);
|
|
200
|
-
maps.push(s.generateMap({ hires: true, source: id }));
|
|
201
|
-
s = new MagicString__default(code);
|
|
202
|
-
}
|
|
203
|
-
}
|
|
204
|
-
if (code !== original) {
|
|
205
|
-
ctx.affectedModules.add(id);
|
|
206
|
-
return {
|
|
207
|
-
code,
|
|
208
|
-
map: remapping__default(maps, (_, ctx2) => {
|
|
209
|
-
ctx2.content = code;
|
|
210
|
-
return null;
|
|
211
|
-
})
|
|
212
|
-
};
|
|
213
|
-
}
|
|
214
|
-
}
|
|
215
|
-
function transformSkipCode(code, map) {
|
|
216
|
-
for (const item of Array.from(code.matchAll(SKIP_COMMENT_RE))) {
|
|
217
|
-
if (item != null) {
|
|
218
|
-
const matched = item[0];
|
|
219
|
-
const withHashKey = `@unocss-skip-placeholder-${hash(matched)}`;
|
|
220
|
-
map.set(withHashKey, matched);
|
|
221
|
-
code = code.replace(matched, withHashKey);
|
|
222
|
-
}
|
|
223
|
-
}
|
|
224
|
-
return code;
|
|
225
|
-
}
|
|
226
|
-
function restoreSkipCode(code, map) {
|
|
227
|
-
for (const [withHashKey, matched] of map.entries())
|
|
228
|
-
code = code.replace(withHashKey, matched);
|
|
229
|
-
return code;
|
|
230
|
-
}
|
|
231
|
-
|
|
232
|
-
const svelteIdRE = /[&?]svelte/;
|
|
233
|
-
function createCssTransformerPlugins(context, cssTransformers) {
|
|
234
|
-
const enforces = ["default", "pre", "post"];
|
|
235
|
-
return enforces.map((enforce) => ({
|
|
236
|
-
name: `unocss:svelte-scoped-transformers:${enforce}`,
|
|
237
|
-
enforce: enforce === "default" ? void 0 : enforce,
|
|
238
|
-
async transform(code, id) {
|
|
239
|
-
if (!core.cssIdRE.test(id) || svelteIdRE.test(id))
|
|
240
|
-
return;
|
|
241
|
-
context.uno.config.transformers = cssTransformers ?? [];
|
|
242
|
-
return applyTransformers({
|
|
243
|
-
...context,
|
|
244
|
-
affectedModules: /* @__PURE__ */ new Set()
|
|
245
|
-
}, code, id, enforce);
|
|
246
|
-
}
|
|
247
|
-
}));
|
|
248
|
-
}
|
|
249
|
-
|
|
250
|
-
function ConfigHMRPlugin({ ready }) {
|
|
251
|
-
return {
|
|
252
|
-
name: "unocss:svelte-scoped:config",
|
|
253
|
-
async configureServer(server) {
|
|
254
|
-
const { sources } = await ready;
|
|
255
|
-
if (!sources.length)
|
|
256
|
-
return;
|
|
257
|
-
server.watcher.add(sources);
|
|
258
|
-
server.watcher.on("add", handleFileChange);
|
|
259
|
-
server.watcher.on("change", handleFileChange);
|
|
260
|
-
server.watcher.on("unlink", handleFileChange);
|
|
261
|
-
function handleFileChange(filepath) {
|
|
262
|
-
if (sources.includes(filepath))
|
|
263
|
-
server.restart();
|
|
264
|
-
}
|
|
265
|
-
}
|
|
266
|
-
};
|
|
267
|
-
}
|
|
268
|
-
|
|
269
|
-
function UnocssSvelteScopedVite(options = {}) {
|
|
270
|
-
const context = createSvelteScopedContext(options.configOrPath);
|
|
271
|
-
if (context.uno.config.transformers)
|
|
272
|
-
throw new Error('Due to the differences in normal UnoCSS global usage and Svelte Scoped usage, "config.transformers" will be ignored. You can still use transformers in CSS files with the "cssFileTransformers" option.');
|
|
273
|
-
if (!options.classPrefix)
|
|
274
|
-
options.classPrefix = "uno-";
|
|
275
|
-
const plugins = [
|
|
276
|
-
GlobalStylesPlugin(context, options.injectReset),
|
|
277
|
-
ConfigHMRPlugin(context)
|
|
278
|
-
];
|
|
279
|
-
if (!options.onlyGlobal)
|
|
280
|
-
plugins.push(PassPreprocessToSveltePlugin(context, options));
|
|
281
|
-
if (options.cssFileTransformers)
|
|
282
|
-
plugins.push(...createCssTransformerPlugins(context, options.cssFileTransformers));
|
|
283
|
-
return plugins;
|
|
284
|
-
}
|
|
285
|
-
const defaults = {
|
|
286
|
-
presets: [
|
|
287
|
-
presetUno__default()
|
|
288
|
-
]
|
|
289
|
-
};
|
|
290
|
-
function createSvelteScopedContext(configOrPath) {
|
|
291
|
-
const uno = core.createGenerator();
|
|
292
|
-
const ready = reloadConfig();
|
|
293
|
-
async function reloadConfig() {
|
|
294
|
-
const { config: config$1, sources } = await config.loadConfig(process__default.cwd(), configOrPath);
|
|
295
|
-
uno.setConfig(config$1, defaults);
|
|
296
|
-
return { config: config$1, sources };
|
|
297
|
-
}
|
|
298
|
-
return {
|
|
299
|
-
uno,
|
|
300
|
-
ready
|
|
301
|
-
};
|
|
302
|
-
}
|
|
303
|
-
|
|
304
|
-
module.exports = UnocssSvelteScopedVite;
|
package/dist/vite.d.cts
DELETED
|
@@ -1,42 +0,0 @@
|
|
|
1
|
-
import { Plugin } from 'vite';
|
|
2
|
-
import { PluginOptions } from '@unocss/core';
|
|
3
|
-
import { U as UnocssSveltePreprocessOptions } from './shared/svelte-scoped.BJnJpFJ9.cjs';
|
|
4
|
-
import '@unocss/config';
|
|
5
|
-
|
|
6
|
-
interface UnocssSvelteScopedViteOptions extends UnocssSveltePreprocessOptions {
|
|
7
|
-
/**
|
|
8
|
-
* Prefix for compiled class names
|
|
9
|
-
* @default 'uno-'
|
|
10
|
-
*/
|
|
11
|
-
classPrefix?: string
|
|
12
|
-
/**
|
|
13
|
-
* Inject reset to the beginning of the global stylesheet.
|
|
14
|
-
*
|
|
15
|
-
* You can pass one of the included resets from [@unocss/reset](https://unocss.dev/guide/style-reset):
|
|
16
|
-
* - `@unocss/reset/normalize.css`
|
|
17
|
-
* - `@unocss/reset/eric-meyer.css`
|
|
18
|
-
* - `@unocss/reset/sanitize/sanitize.css`
|
|
19
|
-
* - `@unocss/reset/tailwind.css`
|
|
20
|
-
* - `@unocss/reset/tailwind-compat.css`
|
|
21
|
-
*
|
|
22
|
-
* You can pass your own custom reset by passing the filepath relative to your project root as in `./src/reset.css`
|
|
23
|
-
*
|
|
24
|
-
* You can install a package then pass a path to the CSS file in your node_modules as in `@bob/my-tools/reset.css`.
|
|
25
|
-
* @default undefined
|
|
26
|
-
*/
|
|
27
|
-
injectReset?: string
|
|
28
|
-
/**
|
|
29
|
-
* When building a component library using `@unocss/svelte-scoped/preprocessor` you can also use `@unocss/svelte-scoped/vite` with this set to `true` to add needed global styles for your library demo app: resets, preflights, and safelist
|
|
30
|
-
* @default false
|
|
31
|
-
*/
|
|
32
|
-
onlyGlobal?: boolean
|
|
33
|
-
/**
|
|
34
|
-
* Process CSS files using UnoCSS transformers.
|
|
35
|
-
* @default undefined
|
|
36
|
-
*/
|
|
37
|
-
cssFileTransformers?: PluginOptions['transformers']
|
|
38
|
-
}
|
|
39
|
-
|
|
40
|
-
declare function UnocssSvelteScopedVite(options?: UnocssSvelteScopedViteOptions): Plugin[];
|
|
41
|
-
|
|
42
|
-
export { UnocssSvelteScopedVite as default };
|