@unocss/core 0.50.8 → 0.51.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/README.md CHANGED
@@ -2,15 +2,9 @@
2
2
 
3
3
  The core engine of [UnoCSS](https://github.com/unocss/unocss) without any presets. It can be used as the engine of your own atomic CSS framework.
4
4
 
5
- ## Usage
5
+ ## Documentation
6
6
 
7
- ```ts
8
- import { createGenerator } from '@unocss/core'
9
-
10
- const generator = createGenerator({ /* user options */ }, { /* default options */ })
11
-
12
- const { css } = await generator.generate(code)
13
- ```
7
+ Please refer to the [documentation](https://unocss.dev/tools/core).
14
8
 
15
9
  ## License
16
10
 
package/dist/index.cjs CHANGED
@@ -328,47 +328,17 @@ function createValueHandler(handlers) {
328
328
 
329
329
  const defaultSplitRE = /[\\:]?[\s'"`;{}]+/g;
330
330
  const splitWithVariantGroupRE = /([\\:]?[\s"'`;<>*]|:\(|\)"|\)\s)/g;
331
- const quotedArbitraryValuesRE = /(?:[\w&:[\]-]|\[\S+=\S+\])+\[\\?['"]?\S+?['"]\]\]?[\w:-]*/g;
332
- const arbitraryPropertyRE = /\[(\\\W|[\w-])+:[^\s:]*?("\S+?"|'\S+?'|`\S+?`|[^\s:]+?)[^\s:]*?\)?\]/g;
333
- const arbitraryPropertyCandidateRE = /^\[(\\\W|[\w-])+:['"]?\S+?['"]?\]$/;
334
331
  function splitCode(code) {
335
- const result = /* @__PURE__ */ new Set();
336
- for (const match of code.matchAll(arbitraryPropertyRE)) {
337
- if (!code[match.index - 1]?.match(/^[\s'"`]/))
338
- continue;
339
- result.add(match[0]);
340
- }
341
- for (const match of code.matchAll(quotedArbitraryValuesRE))
342
- result.add(match[0]);
343
- code.split(defaultSplitRE).forEach((match) => {
344
- if (isValidSelector(match) && !arbitraryPropertyCandidateRE.test(match))
345
- result.add(match);
346
- });
347
- return [...result];
332
+ return [...new Set(code.split(defaultSplitRE))];
348
333
  }
349
334
  const extractorSplit = {
350
- name: "split",
335
+ name: "@unocss/core/extractor-split",
351
336
  order: 0,
352
337
  extract({ code }) {
353
338
  return splitCode(code);
354
339
  }
355
340
  };
356
341
 
357
- const rightTrimRe = /=$/;
358
- const extractorSvelte = {
359
- name: "svelte",
360
- order: 0,
361
- extract({ code, id }) {
362
- let result = splitCode(code);
363
- if (id && id.endsWith(".svelte")) {
364
- result = result.map((r) => {
365
- return r.startsWith("class:") ? r.slice(6).replace(rightTrimRe, "") : r;
366
- });
367
- }
368
- return new Set(result);
369
- }
370
- };
371
-
372
342
  function createNanoEvents() {
373
343
  return {
374
344
  events: {},
@@ -432,8 +402,11 @@ function resolveConfig(userConfig = {}, defaults = {}) {
432
402
  ]);
433
403
  }
434
404
  const extractors = mergePresets("extractors");
435
- if (!extractors.length)
436
- extractors.push(extractorSplit);
405
+ let extractorDefault = [...sortedPresets, config].reverse().find((i) => i.extractorDefault !== void 0)?.extractorDefault;
406
+ if (extractorDefault === void 0)
407
+ extractorDefault = extractorSplit;
408
+ if (extractorDefault && !extractors.includes(extractorDefault))
409
+ extractors.unshift(extractorDefault);
437
410
  extractors.sort((a, b) => (a.order || 0) - (b.order || 0));
438
411
  const rules = mergePresets("rules");
439
412
  const rulesStaticMap = {};
@@ -448,11 +421,13 @@ function resolveConfig(userConfig = {}, defaults = {}) {
448
421
  }
449
422
  return [i, ...rule];
450
423
  }).filter(Boolean).reverse();
451
- const theme = clone([
424
+ let theme = clone([
452
425
  ...sortedPresets.map((p) => p.theme || {}),
453
426
  config.theme || {}
454
427
  ].reduce((a, p) => mergeDeep(a, p), {}));
455
- mergePresets("extendTheme").forEach((extendTheme) => extendTheme(theme));
428
+ const extendThemes = toArray(mergePresets("extendTheme"));
429
+ for (const extendTheme of extendThemes)
430
+ theme = extendTheme(theme) || theme;
456
431
  const autocomplete = {
457
432
  templates: uniq(sortedPresets.map((p) => toArray(p.autocomplete?.templates)).flat()),
458
433
  extractors: sortedPresets.map((p) => toArray(p.autocomplete?.extractors)).flat().sort((a, b) => (a.order || 0) - (b.order || 0))
@@ -490,7 +465,7 @@ function resolveConfig(userConfig = {}, defaults = {}) {
490
465
  return resolved;
491
466
  }
492
467
 
493
- const version = "0.50.8";
468
+ const version = "0.51.0";
494
469
 
495
470
  class UnoGenerator {
496
471
  constructor(userConfig = {}, defaults = {}) {
@@ -516,22 +491,21 @@ class UnoGenerator {
516
491
  this.config = resolveConfig(userConfig, this.defaults);
517
492
  this.events.emit("config", this.config);
518
493
  }
519
- async applyExtractors(code, id, set = /* @__PURE__ */ new Set()) {
494
+ async applyExtractors(code, id, extracted = /* @__PURE__ */ new Set()) {
520
495
  const context = {
521
- get original() {
522
- return code;
523
- },
496
+ original: code,
524
497
  code,
525
- id
498
+ id,
499
+ extracted
526
500
  };
527
501
  for (const extractor of this.config.extractors) {
528
- const result = await extractor.extract(context);
502
+ const result = await extractor.extract?.(context);
529
503
  if (result) {
530
504
  for (const token of result)
531
- set.add(token);
505
+ extracted.add(token);
532
506
  }
533
507
  }
534
- return set;
508
+ return extracted;
535
509
  }
536
510
  makeContext(raw, applied) {
537
511
  const context = {
@@ -979,7 +953,6 @@ exports.BetterMap = BetterMap;
979
953
  exports.CONTROL_SHORTCUT_NO_MERGE = CONTROL_SHORTCUT_NO_MERGE;
980
954
  exports.TwoKeyMap = TwoKeyMap;
981
955
  exports.UnoGenerator = UnoGenerator;
982
- exports.arbitraryPropertyRE = arbitraryPropertyRE;
983
956
  exports.attributifyRE = attributifyRE;
984
957
  exports.clearIdenticalEntries = clearIdenticalEntries;
985
958
  exports.clone = clone;
@@ -993,8 +966,8 @@ exports.entriesToCss = entriesToCss;
993
966
  exports.escapeRegExp = escapeRegExp;
994
967
  exports.escapeSelector = escapeSelector;
995
968
  exports.expandVariantGroup = expandVariantGroup;
969
+ exports.extractorDefault = extractorSplit;
996
970
  exports.extractorSplit = extractorSplit;
997
- exports.extractorSvelte = extractorSvelte;
998
971
  exports.hasScopePlaceholder = hasScopePlaceholder;
999
972
  exports.isAttributifySelector = isAttributifySelector;
1000
973
  exports.isObject = isObject;
@@ -1011,7 +984,6 @@ exports.normalizeCSSValues = normalizeCSSValues;
1011
984
  exports.normalizeVariant = normalizeVariant;
1012
985
  exports.notNull = notNull;
1013
986
  exports.parseVariantGroup = parseVariantGroup;
1014
- exports.quotedArbitraryValuesRE = quotedArbitraryValuesRE;
1015
987
  exports.regexScopePlaceholder = regexScopePlaceholder;
1016
988
  exports.splitWithVariantGroupRE = splitWithVariantGroupRE;
1017
989
  exports.toArray = toArray;
package/dist/index.d.ts CHANGED
@@ -64,7 +64,7 @@ declare class UnoGenerator<Theme extends {} = {}> {
64
64
  }>;
65
65
  constructor(userConfig?: UserConfig<Theme>, defaults?: UserConfigDefaults<Theme>);
66
66
  setConfig(userConfig?: UserConfig<Theme>, defaults?: UserConfigDefaults<Theme>): void;
67
- applyExtractors(code: string, id?: string, set?: Set<string>): Promise<Set<string>>;
67
+ applyExtractors(code: string, id?: string, extracted?: Set<string>): Promise<Set<string>>;
68
68
  makeContext(raw: string, applied: VariantMatchedResult<Theme>): RuleContext<Theme>;
69
69
  parseToken(raw: string, alias?: string): Promise<StringifiedUtil<Theme>[] | null | undefined>;
70
70
  generate(input: string | Set<string> | string[], options?: GenerateOptions): Promise<GenerateResult>;
@@ -263,6 +263,7 @@ interface ExtractorContext {
263
263
  readonly original: string;
264
264
  code: string;
265
265
  id?: string;
266
+ extracted: Set<string>;
266
267
  }
267
268
  interface PreflightContext<Theme extends {} = {}> {
268
269
  /**
@@ -276,8 +277,13 @@ interface PreflightContext<Theme extends {} = {}> {
276
277
  }
277
278
  interface Extractor {
278
279
  name: string;
279
- extract(ctx: ExtractorContext): Awaitable<Set<string> | string[] | undefined>;
280
280
  order?: number;
281
+ /**
282
+ * Extract the code and return a list of selectors.
283
+ *
284
+ * Return `undefined` to skip this extractor.
285
+ */
286
+ extract?(ctx: ExtractorContext): Awaitable<Set<string> | string[] | undefined | void>;
281
287
  }
282
288
  interface RuleMeta {
283
289
  /**
@@ -428,7 +434,7 @@ interface VariantObject<Theme extends {} = {}> {
428
434
  type Variant<Theme extends {} = {}> = VariantFunction<Theme> | VariantObject<Theme>;
429
435
  type Preprocessor = (matcher: string) => string | undefined;
430
436
  type Postprocessor = (util: UtilObject) => void;
431
- type ThemeExtender<T> = (theme: T) => void;
437
+ type ThemeExtender<T> = (theme: T) => T | void;
432
438
  interface ConfigBase<Theme extends {} = {}> {
433
439
  /**
434
440
  * Rules to generate CSS utilities.
@@ -468,6 +474,20 @@ interface ConfigBase<Theme extends {} = {}> {
468
474
  * Can be language-aware.
469
475
  */
470
476
  extractors?: Extractor[];
477
+ /**
478
+ * Default extractor that are always applied.
479
+ * By default it split the source code by whitespace and quotes.
480
+ *
481
+ * It maybe be replaced by preset or user config,
482
+ * only one default extractor can be presented,
483
+ * later one will override the previous one.
484
+ *
485
+ * Pass `null` or `false` to disable the default extractor.
486
+ *
487
+ * @see https://github.com/antfu/unocss/blob/main/packages/core/src/extractors/split.ts
488
+ * @default import('@unocss/core').defaultExtractor
489
+ */
490
+ extractorDefault?: Extractor | null | false;
471
491
  /**
472
492
  * Raw CSS injections.
473
493
  */
@@ -493,7 +513,9 @@ interface ConfigBase<Theme extends {} = {}> {
493
513
  */
494
514
  postprocess?: Arrayable<Postprocessor>;
495
515
  /**
496
- * Custom functions to extend the theme object
516
+ * Custom functions mutate the theme object.
517
+ *
518
+ * It's also possible to return a new theme object to completely replace the original one.
497
519
  */
498
520
  extendTheme?: Arrayable<ThemeExtender<Theme>>;
499
521
  /**
@@ -836,10 +858,6 @@ interface GenerateOptions {
836
858
 
837
859
  declare const defaultSplitRE: RegExp;
838
860
  declare const splitWithVariantGroupRE: RegExp;
839
- declare const quotedArbitraryValuesRE: RegExp;
840
- declare const arbitraryPropertyRE: RegExp;
841
861
  declare const extractorSplit: Extractor;
842
862
 
843
- declare const extractorSvelte: Extractor;
844
-
845
- export { ArgumentType, Arrayable, AutoCompleteExtractor, AutoCompleteExtractorContext, AutoCompleteExtractorResult, AutoCompleteFunction, AutoCompleteTemplate, Awaitable, BetterMap, BlocklistRule, CONTROL_SHORTCUT_NO_MERGE, CSSColorValue, CSSEntries, CSSObject, CSSValue, CSSValues, CliEntryItem, CliOptions, ConfigBase, DeepPartial, DynamicMatcher, DynamicRule, DynamicShortcut, DynamicShortcutMatcher, ExtraContentOptions, Extractor, ExtractorContext, FilterPattern, FlatObjectTuple, GenerateOptions, GenerateResult, GeneratorOptions, ParsedColorValue, ParsedUtil, PartialByKeys, PluginOptions, Postprocessor, Preflight, PreflightContext, PreparedRule, Preprocessor, Preset, PresetOptions, RGBAColorValue, RawUtil, Replacement, RequiredByKey, ResolvedConfig, RestArgs, Rule, RuleContext, RuleMeta, Shift, Shortcut, ShortcutValue, SourceCodeTransformer, SourceCodeTransformerEnforce, SourceMap, StaticRule, StaticShortcut, StaticShortcutMap, StringifiedUtil, SuggestResult, ThemeExtender, TransformResult, TwoKeyMap, UnoGenerator, UnocssPluginContext, UserConfig, UserConfigDefaults, UserOnlyOptions, UserShortcuts, UtilObject, ValueHandler, ValueHandlerCallback, Variant, VariantContext, VariantFunction, VariantHandler, VariantHandlerContext, VariantMatchedResult, VariantObject, arbitraryPropertyRE, attributifyRE, clearIdenticalEntries, clone, collapseVariantGroup, createGenerator, createValueHandler, cssIdRE, defaultSplitRE, e, entriesToCss, escapeRegExp, escapeSelector, expandVariantGroup, extractorSplit, extractorSvelte, hasScopePlaceholder, isAttributifySelector, isObject, isRawUtil, isStaticRule, isStaticShortcut, isString, isValidSelector, makeRegexClassGroup, mergeDeep, noop, normalizeCSSEntries, normalizeCSSValues, normalizeVariant, notNull, parseVariantGroup, quotedArbitraryValuesRE, regexScopePlaceholder, splitWithVariantGroupRE, toArray, toEscapedSelector, uniq, validateFilterRE, warnOnce, withLayer };
863
+ export { ArgumentType, Arrayable, AutoCompleteExtractor, AutoCompleteExtractorContext, AutoCompleteExtractorResult, AutoCompleteFunction, AutoCompleteTemplate, Awaitable, BetterMap, BlocklistRule, CONTROL_SHORTCUT_NO_MERGE, CSSColorValue, CSSEntries, CSSObject, CSSValue, CSSValues, CliEntryItem, CliOptions, ConfigBase, DeepPartial, DynamicMatcher, DynamicRule, DynamicShortcut, DynamicShortcutMatcher, ExtraContentOptions, Extractor, ExtractorContext, FilterPattern, FlatObjectTuple, GenerateOptions, GenerateResult, GeneratorOptions, ParsedColorValue, ParsedUtil, PartialByKeys, PluginOptions, Postprocessor, Preflight, PreflightContext, PreparedRule, Preprocessor, Preset, PresetOptions, RGBAColorValue, RawUtil, Replacement, RequiredByKey, ResolvedConfig, RestArgs, Rule, RuleContext, RuleMeta, Shift, Shortcut, ShortcutValue, SourceCodeTransformer, SourceCodeTransformerEnforce, SourceMap, StaticRule, StaticShortcut, StaticShortcutMap, StringifiedUtil, SuggestResult, ThemeExtender, TransformResult, TwoKeyMap, UnoGenerator, UnocssPluginContext, UserConfig, UserConfigDefaults, UserOnlyOptions, UserShortcuts, UtilObject, ValueHandler, ValueHandlerCallback, Variant, VariantContext, VariantFunction, VariantHandler, VariantHandlerContext, VariantMatchedResult, VariantObject, attributifyRE, clearIdenticalEntries, clone, collapseVariantGroup, createGenerator, createValueHandler, cssIdRE, defaultSplitRE, e, entriesToCss, escapeRegExp, escapeSelector, expandVariantGroup, extractorSplit as extractorDefault, extractorSplit, hasScopePlaceholder, isAttributifySelector, isObject, isRawUtil, isStaticRule, isStaticShortcut, isString, isValidSelector, makeRegexClassGroup, mergeDeep, noop, normalizeCSSEntries, normalizeCSSValues, normalizeVariant, notNull, parseVariantGroup, regexScopePlaceholder, splitWithVariantGroupRE, toArray, toEscapedSelector, uniq, validateFilterRE, warnOnce, withLayer };
package/dist/index.mjs CHANGED
@@ -324,47 +324,17 @@ function createValueHandler(handlers) {
324
324
 
325
325
  const defaultSplitRE = /[\\:]?[\s'"`;{}]+/g;
326
326
  const splitWithVariantGroupRE = /([\\:]?[\s"'`;<>*]|:\(|\)"|\)\s)/g;
327
- const quotedArbitraryValuesRE = /(?:[\w&:[\]-]|\[\S+=\S+\])+\[\\?['"]?\S+?['"]\]\]?[\w:-]*/g;
328
- const arbitraryPropertyRE = /\[(\\\W|[\w-])+:[^\s:]*?("\S+?"|'\S+?'|`\S+?`|[^\s:]+?)[^\s:]*?\)?\]/g;
329
- const arbitraryPropertyCandidateRE = /^\[(\\\W|[\w-])+:['"]?\S+?['"]?\]$/;
330
327
  function splitCode(code) {
331
- const result = /* @__PURE__ */ new Set();
332
- for (const match of code.matchAll(arbitraryPropertyRE)) {
333
- if (!code[match.index - 1]?.match(/^[\s'"`]/))
334
- continue;
335
- result.add(match[0]);
336
- }
337
- for (const match of code.matchAll(quotedArbitraryValuesRE))
338
- result.add(match[0]);
339
- code.split(defaultSplitRE).forEach((match) => {
340
- if (isValidSelector(match) && !arbitraryPropertyCandidateRE.test(match))
341
- result.add(match);
342
- });
343
- return [...result];
328
+ return [...new Set(code.split(defaultSplitRE))];
344
329
  }
345
330
  const extractorSplit = {
346
- name: "split",
331
+ name: "@unocss/core/extractor-split",
347
332
  order: 0,
348
333
  extract({ code }) {
349
334
  return splitCode(code);
350
335
  }
351
336
  };
352
337
 
353
- const rightTrimRe = /=$/;
354
- const extractorSvelte = {
355
- name: "svelte",
356
- order: 0,
357
- extract({ code, id }) {
358
- let result = splitCode(code);
359
- if (id && id.endsWith(".svelte")) {
360
- result = result.map((r) => {
361
- return r.startsWith("class:") ? r.slice(6).replace(rightTrimRe, "") : r;
362
- });
363
- }
364
- return new Set(result);
365
- }
366
- };
367
-
368
338
  function createNanoEvents() {
369
339
  return {
370
340
  events: {},
@@ -428,8 +398,11 @@ function resolveConfig(userConfig = {}, defaults = {}) {
428
398
  ]);
429
399
  }
430
400
  const extractors = mergePresets("extractors");
431
- if (!extractors.length)
432
- extractors.push(extractorSplit);
401
+ let extractorDefault = [...sortedPresets, config].reverse().find((i) => i.extractorDefault !== void 0)?.extractorDefault;
402
+ if (extractorDefault === void 0)
403
+ extractorDefault = extractorSplit;
404
+ if (extractorDefault && !extractors.includes(extractorDefault))
405
+ extractors.unshift(extractorDefault);
433
406
  extractors.sort((a, b) => (a.order || 0) - (b.order || 0));
434
407
  const rules = mergePresets("rules");
435
408
  const rulesStaticMap = {};
@@ -444,11 +417,13 @@ function resolveConfig(userConfig = {}, defaults = {}) {
444
417
  }
445
418
  return [i, ...rule];
446
419
  }).filter(Boolean).reverse();
447
- const theme = clone([
420
+ let theme = clone([
448
421
  ...sortedPresets.map((p) => p.theme || {}),
449
422
  config.theme || {}
450
423
  ].reduce((a, p) => mergeDeep(a, p), {}));
451
- mergePresets("extendTheme").forEach((extendTheme) => extendTheme(theme));
424
+ const extendThemes = toArray(mergePresets("extendTheme"));
425
+ for (const extendTheme of extendThemes)
426
+ theme = extendTheme(theme) || theme;
452
427
  const autocomplete = {
453
428
  templates: uniq(sortedPresets.map((p) => toArray(p.autocomplete?.templates)).flat()),
454
429
  extractors: sortedPresets.map((p) => toArray(p.autocomplete?.extractors)).flat().sort((a, b) => (a.order || 0) - (b.order || 0))
@@ -486,7 +461,7 @@ function resolveConfig(userConfig = {}, defaults = {}) {
486
461
  return resolved;
487
462
  }
488
463
 
489
- const version = "0.50.8";
464
+ const version = "0.51.0";
490
465
 
491
466
  class UnoGenerator {
492
467
  constructor(userConfig = {}, defaults = {}) {
@@ -512,22 +487,21 @@ class UnoGenerator {
512
487
  this.config = resolveConfig(userConfig, this.defaults);
513
488
  this.events.emit("config", this.config);
514
489
  }
515
- async applyExtractors(code, id, set = /* @__PURE__ */ new Set()) {
490
+ async applyExtractors(code, id, extracted = /* @__PURE__ */ new Set()) {
516
491
  const context = {
517
- get original() {
518
- return code;
519
- },
492
+ original: code,
520
493
  code,
521
- id
494
+ id,
495
+ extracted
522
496
  };
523
497
  for (const extractor of this.config.extractors) {
524
- const result = await extractor.extract(context);
498
+ const result = await extractor.extract?.(context);
525
499
  if (result) {
526
500
  for (const token of result)
527
- set.add(token);
501
+ extracted.add(token);
528
502
  }
529
503
  }
530
- return set;
504
+ return extracted;
531
505
  }
532
506
  makeContext(raw, applied) {
533
507
  const context = {
@@ -971,4 +945,4 @@ function defaultVariantHandler(input, next) {
971
945
  return next(input);
972
946
  }
973
947
 
974
- export { BetterMap, CONTROL_SHORTCUT_NO_MERGE, TwoKeyMap, UnoGenerator, arbitraryPropertyRE, attributifyRE, clearIdenticalEntries, clone, collapseVariantGroup, createGenerator, createValueHandler, cssIdRE, defaultSplitRE, e, entriesToCss, escapeRegExp, escapeSelector, expandVariantGroup, extractorSplit, extractorSvelte, hasScopePlaceholder, isAttributifySelector, isObject, isRawUtil, isStaticRule, isStaticShortcut, isString, isValidSelector, makeRegexClassGroup, mergeDeep, noop, normalizeCSSEntries, normalizeCSSValues, normalizeVariant, notNull, parseVariantGroup, quotedArbitraryValuesRE, regexScopePlaceholder, splitWithVariantGroupRE, toArray, toEscapedSelector, uniq, validateFilterRE, warnOnce, withLayer };
948
+ export { BetterMap, CONTROL_SHORTCUT_NO_MERGE, TwoKeyMap, UnoGenerator, attributifyRE, clearIdenticalEntries, clone, collapseVariantGroup, createGenerator, createValueHandler, cssIdRE, defaultSplitRE, e, entriesToCss, escapeRegExp, escapeSelector, expandVariantGroup, extractorSplit as extractorDefault, extractorSplit, hasScopePlaceholder, isAttributifySelector, isObject, isRawUtil, isStaticRule, isStaticShortcut, isString, isValidSelector, makeRegexClassGroup, mergeDeep, noop, normalizeCSSEntries, normalizeCSSValues, normalizeVariant, notNull, parseVariantGroup, regexScopePlaceholder, splitWithVariantGroupRE, toArray, toEscapedSelector, uniq, validateFilterRE, warnOnce, withLayer };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@unocss/core",
3
- "version": "0.50.8",
3
+ "version": "0.51.0",
4
4
  "description": "The instant on-demand Atomic CSS engine.",
5
5
  "author": "Anthony Fu <anthonyfu117@hotmail.com>",
6
6
  "license": "MIT",