@wyw-in-js/processor-utils 0.1.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/LICENSE +21 -0
- package/esm/BaseProcessor.js +70 -0
- package/esm/BaseProcessor.js.map +1 -0
- package/esm/TaggedTemplateProcessor.js +43 -0
- package/esm/TaggedTemplateProcessor.js.map +1 -0
- package/esm/index.js +7 -0
- package/esm/index.js.map +1 -0
- package/esm/types.js +2 -0
- package/esm/types.js.map +1 -0
- package/esm/utils/buildSlug.js +6 -0
- package/esm/utils/buildSlug.js.map +1 -0
- package/esm/utils/getClassNameAndSlug.js +42 -0
- package/esm/utils/getClassNameAndSlug.js.map +1 -0
- package/esm/utils/getVariableName.js +12 -0
- package/esm/utils/getVariableName.js.map +1 -0
- package/esm/utils/stripLines.js +16 -0
- package/esm/utils/stripLines.js.map +1 -0
- package/esm/utils/templateProcessor.js +125 -0
- package/esm/utils/templateProcessor.js.map +1 -0
- package/esm/utils/throwIfInvalid.js +29 -0
- package/esm/utils/throwIfInvalid.js.map +1 -0
- package/esm/utils/toCSS.js +50 -0
- package/esm/utils/toCSS.js.map +1 -0
- package/esm/utils/toValidCSSIdentifier.js +4 -0
- package/esm/utils/toValidCSSIdentifier.js.map +1 -0
- package/esm/utils/types.js +2 -0
- package/esm/utils/types.js.map +1 -0
- package/esm/utils/units.js +65 -0
- package/esm/utils/units.js.map +1 -0
- package/esm/utils/validateParams.js +40 -0
- package/esm/utils/validateParams.js.map +1 -0
- package/lib/BaseProcessor.js +78 -0
- package/lib/BaseProcessor.js.map +1 -0
- package/lib/TaggedTemplateProcessor.js +51 -0
- package/lib/TaggedTemplateProcessor.js.map +1 -0
- package/lib/index.js +67 -0
- package/lib/index.js.map +1 -0
- package/lib/types.js +2 -0
- package/lib/types.js.map +1 -0
- package/lib/utils/buildSlug.js +12 -0
- package/lib/utils/buildSlug.js.map +1 -0
- package/lib/utils/getClassNameAndSlug.js +49 -0
- package/lib/utils/getClassNameAndSlug.js.map +1 -0
- package/lib/utils/getVariableName.js +18 -0
- package/lib/utils/getVariableName.js.map +1 -0
- package/lib/utils/stripLines.js +22 -0
- package/lib/utils/stripLines.js.map +1 -0
- package/lib/utils/templateProcessor.js +135 -0
- package/lib/utils/templateProcessor.js.map +1 -0
- package/lib/utils/throwIfInvalid.js +35 -0
- package/lib/utils/throwIfInvalid.js.map +1 -0
- package/lib/utils/toCSS.js +58 -0
- package/lib/utils/toCSS.js.map +1 -0
- package/lib/utils/toValidCSSIdentifier.js +10 -0
- package/lib/utils/toValidCSSIdentifier.js.map +1 -0
- package/lib/utils/types.js +2 -0
- package/lib/utils/types.js.map +1 -0
- package/lib/utils/units.js +71 -0
- package/lib/utils/units.js.map +1 -0
- package/lib/utils/validateParams.js +54 -0
- package/lib/utils/validateParams.js.map +1 -0
- package/package.json +40 -0
- package/types/BaseProcessor.d.ts +66 -0
- package/types/BaseProcessor.js +59 -0
- package/types/TaggedTemplateProcessor.d.ts +20 -0
- package/types/TaggedTemplateProcessor.js +40 -0
- package/types/index.d.ts +9 -0
- package/types/index.js +29 -0
- package/types/types.d.ts +32 -0
- package/types/types.js +2 -0
- package/types/utils/buildSlug.d.ts +3 -0
- package/types/utils/buildSlug.js +9 -0
- package/types/utils/getClassNameAndSlug.d.ts +5 -0
- package/types/utils/getClassNameAndSlug.js +43 -0
- package/types/utils/getVariableName.d.ts +2 -0
- package/types/utils/getVariableName.js +15 -0
- package/types/utils/stripLines.d.ts +5 -0
- package/types/utils/stripLines.js +18 -0
- package/types/utils/templateProcessor.d.ts +10 -0
- package/types/utils/templateProcessor.js +140 -0
- package/types/utils/throwIfInvalid.d.ts +5 -0
- package/types/utils/throwIfInvalid.js +32 -0
- package/types/utils/toCSS.d.ts +3 -0
- package/types/utils/toCSS.js +61 -0
- package/types/utils/toValidCSSIdentifier.d.ts +1 -0
- package/types/utils/toValidCSSIdentifier.js +7 -0
- package/types/utils/types.d.ts +9 -0
- package/types/utils/types.js +2 -0
- package/types/utils/units.d.ts +44 -0
- package/types/utils/units.js +94 -0
- package/types/utils/validateParams.d.ts +16 -0
- package/types/utils/validateParams.js +39 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"units.js","names":["units","unitless","animationIterationCount","borderImageOutset","borderImageSlice","borderImageWidth","boxFlex","boxFlexGroup","boxOrdinalGroup","columnCount","columns","flex","flexGrow","flexPositive","flexShrink","flexNegative","flexOrder","gridRow","gridRowEnd","gridRowSpan","gridRowStart","gridColumn","gridColumnEnd","gridColumnSpan","gridColumnStart","fontWeight","lineClamp","lineHeight","opacity","order","orphans","tabSize","widows","zIndex","zoom","fillOpacity","floodOpacity","stopOpacity","strokeDasharray","strokeDashoffset","strokeMiterlimit","strokeOpacity","strokeWidth"],"sources":["../../src/utils/units.ts"],"sourcesContent":["// https://www.w3.org/TR/css-values-4/\nexport const units = [\n // font relative lengths\n 'em',\n 'ex',\n 'cap',\n 'ch',\n 'ic',\n 'rem',\n 'lh',\n 'rlh',\n\n // viewport percentage lengths\n 'vw',\n 'vh',\n 'vi',\n 'vb',\n 'vmin',\n 'vmax',\n\n // absolute lengths\n 'cm',\n 'mm',\n 'Q',\n 'in',\n 'pc',\n 'pt',\n 'px',\n\n // angle units\n 'deg',\n 'grad',\n 'rad',\n 'turn',\n\n // duration units\n 's',\n 'ms',\n\n // frequency units\n 'Hz',\n 'kHz',\n\n // resolution units\n 'dpi',\n 'dpcm',\n 'dppx',\n 'x',\n\n // https://www.w3.org/TR/css-grid-1/#fr-unit\n 'fr',\n\n // percentages\n '%',\n];\n\nexport const unitless = {\n animationIterationCount: true,\n borderImageOutset: true,\n borderImageSlice: true,\n borderImageWidth: true,\n boxFlex: true,\n boxFlexGroup: true,\n boxOrdinalGroup: true,\n columnCount: true,\n columns: true,\n flex: true,\n flexGrow: true,\n flexPositive: true,\n flexShrink: true,\n flexNegative: true,\n flexOrder: true,\n gridRow: true,\n gridRowEnd: true,\n gridRowSpan: true,\n gridRowStart: true,\n gridColumn: true,\n gridColumnEnd: true,\n gridColumnSpan: true,\n gridColumnStart: true,\n fontWeight: true,\n lineClamp: true,\n lineHeight: true,\n opacity: true,\n order: true,\n orphans: true,\n tabSize: true,\n widows: true,\n zIndex: true,\n zoom: true,\n\n // SVG-related properties\n fillOpacity: true,\n floodOpacity: true,\n stopOpacity: true,\n strokeDasharray: true,\n strokeDashoffset: true,\n strokeMiterlimit: true,\n strokeOpacity: true,\n strokeWidth: true,\n};\n"],"mappings":"AAAA;AACA,OAAO,MAAMA,KAAK,GAAG;AACnB;AACA,IAAI,EACJ,IAAI,EACJ,KAAK,EACL,IAAI,EACJ,IAAI,EACJ,KAAK,EACL,IAAI,EACJ,KAAK;AAEL;AACA,IAAI,EACJ,IAAI,EACJ,IAAI,EACJ,IAAI,EACJ,MAAM,EACN,MAAM;AAEN;AACA,IAAI,EACJ,IAAI,EACJ,GAAG,EACH,IAAI,EACJ,IAAI,EACJ,IAAI,EACJ,IAAI;AAEJ;AACA,KAAK,EACL,MAAM,EACN,KAAK,EACL,MAAM;AAEN;AACA,GAAG,EACH,IAAI;AAEJ;AACA,IAAI,EACJ,KAAK;AAEL;AACA,KAAK,EACL,MAAM,EACN,MAAM,EACN,GAAG;AAEH;AACA,IAAI;AAEJ;AACA,GAAG,CACJ;AAED,OAAO,MAAMC,QAAQ,GAAG;EACtBC,uBAAuB,EAAE,IAAI;EAC7BC,iBAAiB,EAAE,IAAI;EACvBC,gBAAgB,EAAE,IAAI;EACtBC,gBAAgB,EAAE,IAAI;EACtBC,OAAO,EAAE,IAAI;EACbC,YAAY,EAAE,IAAI;EAClBC,eAAe,EAAE,IAAI;EACrBC,WAAW,EAAE,IAAI;EACjBC,OAAO,EAAE,IAAI;EACbC,IAAI,EAAE,IAAI;EACVC,QAAQ,EAAE,IAAI;EACdC,YAAY,EAAE,IAAI;EAClBC,UAAU,EAAE,IAAI;EAChBC,YAAY,EAAE,IAAI;EAClBC,SAAS,EAAE,IAAI;EACfC,OAAO,EAAE,IAAI;EACbC,UAAU,EAAE,IAAI;EAChBC,WAAW,EAAE,IAAI;EACjBC,YAAY,EAAE,IAAI;EAClBC,UAAU,EAAE,IAAI;EAChBC,aAAa,EAAE,IAAI;EACnBC,cAAc,EAAE,IAAI;EACpBC,eAAe,EAAE,IAAI;EACrBC,UAAU,EAAE,IAAI;EAChBC,SAAS,EAAE,IAAI;EACfC,UAAU,EAAE,IAAI;EAChBC,OAAO,EAAE,IAAI;EACbC,KAAK,EAAE,IAAI;EACXC,OAAO,EAAE,IAAI;EACbC,OAAO,EAAE,IAAI;EACbC,MAAM,EAAE,IAAI;EACZC,MAAM,EAAE,IAAI;EACZC,IAAI,EAAE,IAAI;EAEV;EACAC,WAAW,EAAE,IAAI;EACjBC,YAAY,EAAE,IAAI;EAClBC,WAAW,EAAE,IAAI;EACjBC,eAAe,EAAE,IAAI;EACrBC,gBAAgB,EAAE,IAAI;EACtBC,gBAAgB,EAAE,IAAI;EACtBC,aAAa,EAAE,IAAI;EACnBC,WAAW,EAAE;AACf,CAAC"}
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
// ParamMapping maps each ParamName to its corresponding Param type.
|
|
2
|
+
|
|
3
|
+
// GetParamByName returns the Param type based on the input type T.
|
|
4
|
+
|
|
5
|
+
// If T is none of the above, return never.
|
|
6
|
+
// MapParams iteratively maps the input ParamConstraints to their corresponding Param types.
|
|
7
|
+
// If TNames is an empty tuple, return the result tuple.
|
|
8
|
+
export function isValidParams(params, constraints) {
|
|
9
|
+
const length = Math.max(params.length, constraints.length);
|
|
10
|
+
for (let i = 0; i < length; i++) {
|
|
11
|
+
if (params[i] === undefined || constraints[i] === undefined) {
|
|
12
|
+
return false;
|
|
13
|
+
}
|
|
14
|
+
const constraint = constraints[i];
|
|
15
|
+
if (constraint === '...') {
|
|
16
|
+
return true;
|
|
17
|
+
}
|
|
18
|
+
if (constraint === '*') {
|
|
19
|
+
if (params[i] === undefined) {
|
|
20
|
+
return false;
|
|
21
|
+
}
|
|
22
|
+
} else if (Array.isArray(constraint)) {
|
|
23
|
+
if (constraint.every(c => c !== params[i]?.[0])) {
|
|
24
|
+
return false;
|
|
25
|
+
}
|
|
26
|
+
} else if (constraint !== params[i]?.[0]) {
|
|
27
|
+
return false;
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
return true;
|
|
31
|
+
}
|
|
32
|
+
export function validateParams(params, constraints, messageOrError) {
|
|
33
|
+
if (!isValidParams(params, constraints)) {
|
|
34
|
+
if (typeof messageOrError === 'string') {
|
|
35
|
+
throw new Error(messageOrError);
|
|
36
|
+
}
|
|
37
|
+
throw messageOrError;
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
//# sourceMappingURL=validateParams.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"validateParams.js","names":["isValidParams","params","constraints","length","Math","max","i","undefined","constraint","Array","isArray","every","c","validateParams","messageOrError","Error"],"sources":["../../src/utils/validateParams.ts"],"sourcesContent":["import type { Param, Params } from '../types';\n\ntype ParamName = Param[0];\ntype ParamConstraint = ParamName | [...ParamName[]] | '*';\n\nexport type ParamConstraints =\n | [...ParamConstraint[]]\n | [...ParamConstraint[], '...'];\n\n// ParamMapping maps each ParamName to its corresponding Param type.\ntype ParamMapping = {\n [K in ParamName]: Extract<Param, readonly [K, ...unknown[]]>; // For each ParamName K, extract the corresponding Param type.\n};\n\n// GetParamByName returns the Param type based on the input type T.\ntype GetParamByName<T> = T extends '*'\n ? Param // If T is '*', return Param type.\n : T extends keyof ParamMapping // If T is a key in ParamMapping (i.e., a ParamName).\n ? ParamMapping[T] // Return the corresponding Param type from ParamMapping.\n : T extends Array<infer TNames> // If T is an array of names.\n ? TNames extends ParamName // If TNames is a ParamName.\n ? Extract<Param, readonly [TNames, ...unknown[]]> // Return the corresponding Param type.\n : never // If TNames is not a ParamName, return never.\n : never; // If T is none of the above, return never.\n\n// MapParams iteratively maps the input ParamConstraints to their corresponding Param types.\nexport type MapParams<\n TNames extends ParamConstraints,\n TRes extends Param[] = [],\n> = TNames extends [infer THead, ...infer TTail] // If TNames is a non-empty tuple.\n ? THead extends '...' // If the first element in the tuple is '...'.\n ? [...TRes, ...Params] // Append all Params to the result tuple.\n : MapParams<\n Extract<TTail, ParamConstraints>, // Extract the remaining ParamConstraints.\n [...TRes, GetParamByName<Extract<THead, ParamName | '*' | ParamName[]>>] // Append the mapped Param to the result tuple and recurse.\n >\n : TRes; // If TNames is an empty tuple, return the result tuple.\n\nexport function isValidParams<T extends ParamConstraints>(\n params: Params,\n constraints: T\n): params is MapParams<T> {\n const length = Math.max(params.length, constraints.length);\n for (let i = 0; i < length; i++) {\n if (params[i] === undefined || constraints[i] === undefined) {\n return false;\n }\n\n const constraint = constraints[i];\n if (constraint === '...') {\n return true;\n }\n\n if (constraint === '*') {\n if (params[i] === undefined) {\n return false;\n }\n } else if (Array.isArray(constraint)) {\n if (constraint.every((c) => c !== params[i]?.[0])) {\n return false;\n }\n } else if (constraint !== params[i]?.[0]) {\n return false;\n }\n }\n\n return true;\n}\n\nexport function validateParams<T extends ParamConstraints>(\n params: Params,\n constraints: T,\n messageOrError: unknown\n): asserts params is MapParams<T> {\n if (!isValidParams(params, constraints)) {\n if (typeof messageOrError === 'string') {\n throw new Error(messageOrError);\n }\n\n throw messageOrError;\n }\n}\n"],"mappings":"AASA;;AAKA;;AASW;AAEX;AAWU;AAEV,OAAO,SAASA,aAAaA,CAC3BC,MAAc,EACdC,WAAc,EACU;EACxB,MAAMC,MAAM,GAAGC,IAAI,CAACC,GAAG,CAACJ,MAAM,CAACE,MAAM,EAAED,WAAW,CAACC,MAAM,CAAC;EAC1D,KAAK,IAAIG,CAAC,GAAG,CAAC,EAAEA,CAAC,GAAGH,MAAM,EAAEG,CAAC,EAAE,EAAE;IAC/B,IAAIL,MAAM,CAACK,CAAC,CAAC,KAAKC,SAAS,IAAIL,WAAW,CAACI,CAAC,CAAC,KAAKC,SAAS,EAAE;MAC3D,OAAO,KAAK;IACd;IAEA,MAAMC,UAAU,GAAGN,WAAW,CAACI,CAAC,CAAC;IACjC,IAAIE,UAAU,KAAK,KAAK,EAAE;MACxB,OAAO,IAAI;IACb;IAEA,IAAIA,UAAU,KAAK,GAAG,EAAE;MACtB,IAAIP,MAAM,CAACK,CAAC,CAAC,KAAKC,SAAS,EAAE;QAC3B,OAAO,KAAK;MACd;IACF,CAAC,MAAM,IAAIE,KAAK,CAACC,OAAO,CAACF,UAAU,CAAC,EAAE;MACpC,IAAIA,UAAU,CAACG,KAAK,CAAEC,CAAC,IAAKA,CAAC,KAAKX,MAAM,CAACK,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE;QACjD,OAAO,KAAK;MACd;IACF,CAAC,MAAM,IAAIE,UAAU,KAAKP,MAAM,CAACK,CAAC,CAAC,GAAG,CAAC,CAAC,EAAE;MACxC,OAAO,KAAK;IACd;EACF;EAEA,OAAO,IAAI;AACb;AAEA,OAAO,SAASO,cAAcA,CAC5BZ,MAAc,EACdC,WAAc,EACdY,cAAuB,EACS;EAChC,IAAI,CAACd,aAAa,CAACC,MAAM,EAAEC,WAAW,CAAC,EAAE;IACvC,IAAI,OAAOY,cAAc,KAAK,QAAQ,EAAE;MACtC,MAAM,IAAIC,KAAK,CAACD,cAAc,CAAC;IACjC;IAEA,MAAMA,cAAc;EACtB;AACF"}
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
|
|
3
|
+
Object.defineProperty(exports, "__esModule", {
|
|
4
|
+
value: true
|
|
5
|
+
});
|
|
6
|
+
exports.BaseProcessor = void 0;
|
|
7
|
+
var _generator = _interopRequireDefault(require("@babel/generator"));
|
|
8
|
+
var _shared = require("@wyw-in-js/shared");
|
|
9
|
+
var _getClassNameAndSlug = _interopRequireDefault(require("./utils/getClassNameAndSlug"));
|
|
10
|
+
var _toCSS = require("./utils/toCSS");
|
|
11
|
+
var _validateParams = require("./utils/validateParams");
|
|
12
|
+
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
|
|
13
|
+
/* eslint-disable class-methods-use-this */
|
|
14
|
+
|
|
15
|
+
class BaseProcessor {
|
|
16
|
+
static SKIP = Symbol('skip');
|
|
17
|
+
artifacts = [];
|
|
18
|
+
dependencies = [];
|
|
19
|
+
interpolations = [];
|
|
20
|
+
constructor(params, tagSource, astService, location, replacer, displayName, isReferenced, idx, options, context) {
|
|
21
|
+
this.tagSource = tagSource;
|
|
22
|
+
this.astService = astService;
|
|
23
|
+
this.location = location;
|
|
24
|
+
this.replacer = replacer;
|
|
25
|
+
this.displayName = displayName;
|
|
26
|
+
this.isReferenced = isReferenced;
|
|
27
|
+
this.idx = idx;
|
|
28
|
+
this.options = options;
|
|
29
|
+
this.context = context;
|
|
30
|
+
(0, _validateParams.validateParams)(params, ['callee'], 'Unknown error: a callee param is not specified');
|
|
31
|
+
const {
|
|
32
|
+
className,
|
|
33
|
+
slug
|
|
34
|
+
} = (0, _getClassNameAndSlug.default)(this.displayName, this.idx, this.options, this.context);
|
|
35
|
+
this.className = className;
|
|
36
|
+
this.slug = slug;
|
|
37
|
+
[[, this.callee]] = params;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* A replacement for tag referenced in a template literal.
|
|
42
|
+
*/
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* A replacement for the tag in evaluation time.
|
|
46
|
+
* For example, `css` tag will be replaced with its className,
|
|
47
|
+
* whereas `styled` tag will be replaced with an object with metadata.
|
|
48
|
+
*/
|
|
49
|
+
|
|
50
|
+
isValidValue(value) {
|
|
51
|
+
return typeof value === 'function' || (0, _toCSS.isCSSable)(value) || (0, _shared.hasEvalMeta)(value);
|
|
52
|
+
}
|
|
53
|
+
toString() {
|
|
54
|
+
return this.tagSourceCode();
|
|
55
|
+
}
|
|
56
|
+
tagSourceCode() {
|
|
57
|
+
if (this.callee.type === 'Identifier') {
|
|
58
|
+
return this.callee.name;
|
|
59
|
+
}
|
|
60
|
+
return (0, _generator.default)(this.callee).code;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/**
|
|
64
|
+
* Perform a replacement for the tag in evaluation time.
|
|
65
|
+
* For example, `css` tag will be replaced with its className,
|
|
66
|
+
* whereas `styled` tag will be replaced with an object with metadata.
|
|
67
|
+
*/
|
|
68
|
+
|
|
69
|
+
/**
|
|
70
|
+
* Perform a replacement for the tag with its runtime version.
|
|
71
|
+
* For example, `css` tag will be replaced with its className,
|
|
72
|
+
* whereas `styled` tag will be replaced with a component.
|
|
73
|
+
* If some parts require evaluated data for render,
|
|
74
|
+
* they will be replaced with placeholders.
|
|
75
|
+
*/
|
|
76
|
+
}
|
|
77
|
+
exports.BaseProcessor = BaseProcessor;
|
|
78
|
+
//# sourceMappingURL=BaseProcessor.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"BaseProcessor.js","names":["_generator","_interopRequireDefault","require","_shared","_getClassNameAndSlug","_toCSS","_validateParams","obj","__esModule","default","BaseProcessor","SKIP","Symbol","artifacts","dependencies","interpolations","constructor","params","tagSource","astService","location","replacer","displayName","isReferenced","idx","options","context","validateParams","className","slug","getClassNameAndSlug","callee","isValidValue","value","isCSSable","hasEvalMeta","toString","tagSourceCode","type","name","generator","code","exports"],"sources":["../src/BaseProcessor.ts"],"sourcesContent":["/* eslint-disable class-methods-use-this */\nimport type { types as t } from '@babel/core';\nimport generator from '@babel/generator';\nimport type {\n Expression,\n Identifier,\n SourceLocation,\n MemberExpression,\n} from '@babel/types';\n\nimport type { Artifact, ExpressionValue } from '@wyw-in-js/shared';\nimport { hasEvalMeta } from '@wyw-in-js/shared';\n\nimport type { IInterpolation, Params, Value, ValueCache } from './types';\nimport getClassNameAndSlug from './utils/getClassNameAndSlug';\nimport { isCSSable } from './utils/toCSS';\nimport type { IFileContext, IOptions } from './utils/types';\nimport { validateParams } from './utils/validateParams';\n\nexport { Expression };\n\nexport type ProcessorParams = ConstructorParameters<typeof BaseProcessor>;\nexport type TailProcessorParams = ProcessorParams extends [Params, ...infer T]\n ? T\n : never;\n\nexport type TagSource = {\n imported: string;\n source: string;\n};\n\nexport abstract class BaseProcessor {\n public static SKIP = Symbol('skip');\n\n public readonly artifacts: Artifact[] = [];\n\n public readonly className: string;\n\n public readonly dependencies: ExpressionValue[] = [];\n\n public interpolations: IInterpolation[] = [];\n\n public readonly slug: string;\n\n protected callee: Identifier | MemberExpression;\n\n protected evaluated:\n | Record<'dependencies' | 'expression', Value[]>\n | undefined;\n\n public constructor(\n params: Params,\n public tagSource: TagSource,\n protected readonly astService: typeof t & {\n addDefaultImport: (source: string, nameHint?: string) => Identifier;\n addNamedImport: (\n name: string,\n source: string,\n nameHint?: string\n ) => Identifier;\n },\n public readonly location: SourceLocation | null,\n protected readonly replacer: (\n replacement: Expression,\n isPure: boolean\n ) => void,\n public readonly displayName: string,\n public readonly isReferenced: boolean,\n protected readonly idx: number,\n protected readonly options: IOptions,\n protected readonly context: IFileContext\n ) {\n validateParams(\n params,\n ['callee'],\n 'Unknown error: a callee param is not specified'\n );\n\n const { className, slug } = getClassNameAndSlug(\n this.displayName,\n this.idx,\n this.options,\n this.context\n );\n\n this.className = className;\n this.slug = slug;\n\n [[, this.callee]] = params;\n }\n\n /**\n * A replacement for tag referenced in a template literal.\n */\n public abstract get asSelector(): string;\n\n /**\n * A replacement for the tag in evaluation time.\n * For example, `css` tag will be replaced with its className,\n * whereas `styled` tag will be replaced with an object with metadata.\n */\n public abstract get value(): Expression;\n\n public isValidValue(value: unknown): value is Value {\n return (\n typeof value === 'function' || isCSSable(value) || hasEvalMeta(value)\n );\n }\n\n public toString(): string {\n return this.tagSourceCode();\n }\n\n protected tagSourceCode(): string {\n if (this.callee.type === 'Identifier') {\n return this.callee.name;\n }\n\n return generator(this.callee).code;\n }\n\n public abstract build(values: ValueCache): void;\n\n /**\n * Perform a replacement for the tag in evaluation time.\n * For example, `css` tag will be replaced with its className,\n * whereas `styled` tag will be replaced with an object with metadata.\n */\n public abstract doEvaltimeReplacement(): void;\n\n /**\n * Perform a replacement for the tag with its runtime version.\n * For example, `css` tag will be replaced with its className,\n * whereas `styled` tag will be replaced with a component.\n * If some parts require evaluated data for render,\n * they will be replaced with placeholders.\n */\n public abstract doRuntimeReplacement(): void;\n}\n"],"mappings":";;;;;;AAEA,IAAAA,UAAA,GAAAC,sBAAA,CAAAC,OAAA;AASA,IAAAC,OAAA,GAAAD,OAAA;AAGA,IAAAE,oBAAA,GAAAH,sBAAA,CAAAC,OAAA;AACA,IAAAG,MAAA,GAAAH,OAAA;AAEA,IAAAI,eAAA,GAAAJ,OAAA;AAAwD,SAAAD,uBAAAM,GAAA,WAAAA,GAAA,IAAAA,GAAA,CAAAC,UAAA,GAAAD,GAAA,KAAAE,OAAA,EAAAF,GAAA;AAjBxD;;AA+BO,MAAeG,aAAa,CAAC;EAClC,OAAcC,IAAI,GAAGC,MAAM,CAAC,MAAM,CAAC;EAEnBC,SAAS,GAAe,EAAE;EAI1BC,YAAY,GAAsB,EAAE;EAE7CC,cAAc,GAAqB,EAAE;EAUrCC,WAAWA,CAChBC,MAAc,EACPC,SAAoB,EACRC,UAOlB,EACeC,QAA+B,EAC5BC,QAGV,EACOC,WAAmB,EACnBC,YAAqB,EAClBC,GAAW,EACXC,OAAiB,EACjBC,OAAqB,EACxC;IAAA,KAnBOR,SAAoB,GAApBA,SAAoB;IAAA,KACRC,UAOlB,GAPkBA,UAOlB;IAAA,KACeC,QAA+B,GAA/BA,QAA+B;IAAA,KAC5BC,QAGV,GAHUA,QAGV;IAAA,KACOC,WAAmB,GAAnBA,WAAmB;IAAA,KACnBC,YAAqB,GAArBA,YAAqB;IAAA,KAClBC,GAAW,GAAXA,GAAW;IAAA,KACXC,OAAiB,GAAjBA,OAAiB;IAAA,KACjBC,OAAqB,GAArBA,OAAqB;IAExC,IAAAC,8BAAc,EACZV,MAAM,EACN,CAAC,QAAQ,CAAC,EACV,gDACF,CAAC;IAED,MAAM;MAAEW,SAAS;MAAEC;IAAK,CAAC,GAAG,IAAAC,4BAAmB,EAC7C,IAAI,CAACR,WAAW,EAChB,IAAI,CAACE,GAAG,EACR,IAAI,CAACC,OAAO,EACZ,IAAI,CAACC,OACP,CAAC;IAED,IAAI,CAACE,SAAS,GAAGA,SAAS;IAC1B,IAAI,CAACC,IAAI,GAAGA,IAAI;IAEhB,CAAC,GAAG,IAAI,CAACE,MAAM,CAAC,CAAC,GAAGd,MAAM;EAC5B;;EAEA;AACF;AACA;;EAGE;AACF;AACA;AACA;AACA;;EAGSe,YAAYA,CAACC,KAAc,EAAkB;IAClD,OACE,OAAOA,KAAK,KAAK,UAAU,IAAI,IAAAC,gBAAS,EAACD,KAAK,CAAC,IAAI,IAAAE,mBAAW,EAACF,KAAK,CAAC;EAEzE;EAEOG,QAAQA,CAAA,EAAW;IACxB,OAAO,IAAI,CAACC,aAAa,CAAC,CAAC;EAC7B;EAEUA,aAAaA,CAAA,EAAW;IAChC,IAAI,IAAI,CAACN,MAAM,CAACO,IAAI,KAAK,YAAY,EAAE;MACrC,OAAO,IAAI,CAACP,MAAM,CAACQ,IAAI;IACzB;IAEA,OAAO,IAAAC,kBAAS,EAAC,IAAI,CAACT,MAAM,CAAC,CAACU,IAAI;EACpC;;EAIA;AACF;AACA;AACA;AACA;;EAGE;AACF;AACA;AACA;AACA;AACA;AACA;AAEA;AAACC,OAAA,CAAAhC,aAAA,GAAAA,aAAA"}
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
|
|
3
|
+
Object.defineProperty(exports, "__esModule", {
|
|
4
|
+
value: true
|
|
5
|
+
});
|
|
6
|
+
exports.TaggedTemplateProcessor = void 0;
|
|
7
|
+
var _shared = require("@wyw-in-js/shared");
|
|
8
|
+
var _BaseProcessor = require("./BaseProcessor");
|
|
9
|
+
var _templateProcessor = _interopRequireDefault(require("./utils/templateProcessor"));
|
|
10
|
+
var _validateParams = require("./utils/validateParams");
|
|
11
|
+
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
|
|
12
|
+
class TaggedTemplateProcessor extends _BaseProcessor.BaseProcessor {
|
|
13
|
+
#template;
|
|
14
|
+
constructor(params, ...args) {
|
|
15
|
+
// Should have at least two params and the first one should be a callee.
|
|
16
|
+
(0, _validateParams.validateParams)(params, ['callee', '...'], TaggedTemplateProcessor.SKIP);
|
|
17
|
+
(0, _validateParams.validateParams)(params, ['callee', 'template'], 'Invalid usage of template tag');
|
|
18
|
+
const [tag, [, template]] = params;
|
|
19
|
+
super([tag], ...args);
|
|
20
|
+
template.forEach(element => {
|
|
21
|
+
if ('kind' in element && element.kind !== _shared.ValueType.FUNCTION) {
|
|
22
|
+
this.dependencies.push(element);
|
|
23
|
+
}
|
|
24
|
+
});
|
|
25
|
+
this.#template = template;
|
|
26
|
+
}
|
|
27
|
+
build(values) {
|
|
28
|
+
if (this.artifacts.length > 0) {
|
|
29
|
+
// FIXME: why it was called twice?
|
|
30
|
+
throw new Error('Tag is already built');
|
|
31
|
+
}
|
|
32
|
+
const artifact = (0, _templateProcessor.default)(this, this.#template, values, this.options.variableNameConfig);
|
|
33
|
+
if (artifact) {
|
|
34
|
+
this.artifacts.push(['css', artifact]);
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
toString() {
|
|
38
|
+
return `${super.toString()}\`…\``;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* It is called for each resolved expression in a template literal.
|
|
43
|
+
* @param node
|
|
44
|
+
* @param precedingCss
|
|
45
|
+
* @param source
|
|
46
|
+
* @param unit
|
|
47
|
+
* @return chunk of CSS that should be added to extracted CSS
|
|
48
|
+
*/
|
|
49
|
+
}
|
|
50
|
+
exports.TaggedTemplateProcessor = TaggedTemplateProcessor;
|
|
51
|
+
//# sourceMappingURL=TaggedTemplateProcessor.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"TaggedTemplateProcessor.js","names":["_shared","require","_BaseProcessor","_templateProcessor","_interopRequireDefault","_validateParams","obj","__esModule","default","TaggedTemplateProcessor","BaseProcessor","template","constructor","params","args","validateParams","SKIP","tag","forEach","element","kind","ValueType","FUNCTION","dependencies","push","build","values","artifacts","length","Error","artifact","templateProcessor","options","variableNameConfig","toString","exports"],"sources":["../src/TaggedTemplateProcessor.ts"],"sourcesContent":["import type { TemplateElement, Expression, SourceLocation } from '@babel/types';\n\nimport type { ExpressionValue } from '@wyw-in-js/shared';\nimport { ValueType } from '@wyw-in-js/shared';\n\nimport type { TailProcessorParams } from './BaseProcessor';\nimport { BaseProcessor } from './BaseProcessor';\nimport type { ValueCache, Rules, Params } from './types';\nimport templateProcessor from './utils/templateProcessor';\nimport { validateParams } from './utils/validateParams';\n\nexport abstract class TaggedTemplateProcessor extends BaseProcessor {\n readonly #template: (TemplateElement | ExpressionValue)[];\n\n protected constructor(params: Params, ...args: TailProcessorParams) {\n // Should have at least two params and the first one should be a callee.\n validateParams(params, ['callee', '...'], TaggedTemplateProcessor.SKIP);\n\n validateParams(\n params,\n ['callee', 'template'],\n 'Invalid usage of template tag'\n );\n const [tag, [, template]] = params;\n\n super([tag], ...args);\n\n template.forEach((element) => {\n if ('kind' in element && element.kind !== ValueType.FUNCTION) {\n this.dependencies.push(element);\n }\n });\n\n this.#template = template;\n }\n\n public override build(values: ValueCache) {\n if (this.artifacts.length > 0) {\n // FIXME: why it was called twice?\n throw new Error('Tag is already built');\n }\n\n const artifact = templateProcessor(\n this,\n this.#template,\n values,\n this.options.variableNameConfig\n );\n if (artifact) {\n this.artifacts.push(['css', artifact]);\n }\n }\n\n public override toString(): string {\n return `${super.toString()}\\`…\\``;\n }\n\n /**\n * It is called for each resolved expression in a template literal.\n * @param node\n * @param precedingCss\n * @param source\n * @param unit\n * @return chunk of CSS that should be added to extracted CSS\n */\n public abstract addInterpolation(\n node: Expression,\n precedingCss: string,\n source: string,\n unit?: string\n ): string;\n\n public abstract extractRules(\n valueCache: ValueCache,\n cssText: string,\n loc?: Sour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,QAAQ,EACde,MAAM,EACN,IAAI,CAACM,OAAO,CAACC,kBACf,CAAC;IACD,IAAIH,QAAQ,EAAE;MACZ,IAAI,CAACH,SAAS,CAACH,IAAI,CAAC,CAAC,KAAK,EAAEM,QAAQ,CAAC,CAAC;IACxC;EACF;EAEgBI,QAAQA,CAAA,EAAW;IACjC,OAAQ,GAAE,KAAK,CAACA,QAAQ,CAAC,CAAE,OAAM;EACnC;;EAEA;AACF;AACA;AACA;AACA;AACA;AACA;AACA;AAaA;AAACC,OAAA,CAAA1B,uBAAA,GAAAA,uBAAA"}
|
package/lib/index.js
ADDED
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
|
|
3
|
+
Object.defineProperty(exports, "__esModule", {
|
|
4
|
+
value: true
|
|
5
|
+
});
|
|
6
|
+
var _exportNames = {
|
|
7
|
+
BaseProcessor: true,
|
|
8
|
+
buildSlug: true,
|
|
9
|
+
isValidParams: true,
|
|
10
|
+
validateParams: true,
|
|
11
|
+
TaggedTemplateProcessor: true,
|
|
12
|
+
toValidCSSIdentifier: true
|
|
13
|
+
};
|
|
14
|
+
Object.defineProperty(exports, "BaseProcessor", {
|
|
15
|
+
enumerable: true,
|
|
16
|
+
get: function () {
|
|
17
|
+
return _BaseProcessor.BaseProcessor;
|
|
18
|
+
}
|
|
19
|
+
});
|
|
20
|
+
Object.defineProperty(exports, "TaggedTemplateProcessor", {
|
|
21
|
+
enumerable: true,
|
|
22
|
+
get: function () {
|
|
23
|
+
return _TaggedTemplateProcessor.TaggedTemplateProcessor;
|
|
24
|
+
}
|
|
25
|
+
});
|
|
26
|
+
Object.defineProperty(exports, "buildSlug", {
|
|
27
|
+
enumerable: true,
|
|
28
|
+
get: function () {
|
|
29
|
+
return _buildSlug.buildSlug;
|
|
30
|
+
}
|
|
31
|
+
});
|
|
32
|
+
Object.defineProperty(exports, "isValidParams", {
|
|
33
|
+
enumerable: true,
|
|
34
|
+
get: function () {
|
|
35
|
+
return _validateParams.isValidParams;
|
|
36
|
+
}
|
|
37
|
+
});
|
|
38
|
+
Object.defineProperty(exports, "toValidCSSIdentifier", {
|
|
39
|
+
enumerable: true,
|
|
40
|
+
get: function () {
|
|
41
|
+
return _toValidCSSIdentifier.toValidCSSIdentifier;
|
|
42
|
+
}
|
|
43
|
+
});
|
|
44
|
+
Object.defineProperty(exports, "validateParams", {
|
|
45
|
+
enumerable: true,
|
|
46
|
+
get: function () {
|
|
47
|
+
return _validateParams.validateParams;
|
|
48
|
+
}
|
|
49
|
+
});
|
|
50
|
+
var _BaseProcessor = require("./BaseProcessor");
|
|
51
|
+
var _types = require("./types");
|
|
52
|
+
Object.keys(_types).forEach(function (key) {
|
|
53
|
+
if (key === "default" || key === "__esModule") return;
|
|
54
|
+
if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return;
|
|
55
|
+
if (key in exports && exports[key] === _types[key]) return;
|
|
56
|
+
Object.defineProperty(exports, key, {
|
|
57
|
+
enumerable: true,
|
|
58
|
+
get: function () {
|
|
59
|
+
return _types[key];
|
|
60
|
+
}
|
|
61
|
+
});
|
|
62
|
+
});
|
|
63
|
+
var _buildSlug = require("./utils/buildSlug");
|
|
64
|
+
var _validateParams = require("./utils/validateParams");
|
|
65
|
+
var _TaggedTemplateProcessor = require("./TaggedTemplateProcessor");
|
|
66
|
+
var _toValidCSSIdentifier = require("./utils/toValidCSSIdentifier");
|
|
67
|
+
//# sourceMappingURL=index.js.map
|
package/lib/index.js.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","names":["_BaseProcessor","require","_types","Object","keys","forEach","key","prototype","hasOwnProperty","call","_exportNames","exports","defineProperty","enumerable","get","_buildSlug","_validateParams","_TaggedTemplateProcessor","_toValidCSSIdentifier"],"sources":["../src/index.ts"],"sourcesContent":["export { BaseProcessor } from './BaseProcessor';\nexport type {\n Expression,\n TagSource,\n ProcessorParams,\n TailProcessorParams,\n} from './BaseProcessor';\nexport * from './types';\nexport { buildSlug } from './utils/buildSlug';\nexport type { IOptions, IFileContext } from './utils/types';\nexport { isValidParams, validateParams } from './utils/validateParams';\nexport type { MapParams, ParamConstraints } from './utils/validateParams';\nexport { TaggedTemplateProcessor } from './TaggedTemplateProcessor';\nexport { toValidCSSIdentifier } from './utils/toValidCSSIdentifier';\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,IAAAA,cAAA,GAAAC,OAAA;AAOA,IAAAC,MAAA,GAAAD,OAAA;AAAAE,MAAA,CAAAC,IAAA,CAAAF,MAAA,EAAAG,OAAA,WAAAC,GAAA;EAAA,IAAAA,GAAA,kBAAAA,GAAA;EAAA,IAAAH,MAAA,CAAAI,SAAA,CAAAC,cAAA,CAAAC,IAAA,CAAAC,YAAA,EAAAJ,GAAA;EAAA,IAAAA,GAAA,IAAAK,OAAA,IAAAA,OAAA,CAAAL,GAAA,MAAAJ,MAAA,CAAAI,GAAA;EAAAH,MAAA,CAAAS,cAAA,CAAAD,OAAA,EAAAL,GAAA;IAAAO,UAAA;IAAAC,GAAA,WAAAA,CAAA;MAAA,OAAAZ,MAAA,CAAAI,GAAA;IAAA;EAAA;AAAA;AACA,IAAAS,UAAA,GAAAd,OAAA;AAEA,IAAAe,eAAA,GAAAf,OAAA;AAEA,IAAAgB,wBAAA,GAAAhB,OAAA;AACA,IAAAiB,qBAAA,GAAAjB,OAAA"}
|
package/lib/types.js
ADDED
package/lib/types.js.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"types.js","names":[],"sources":["../src/types.ts"],"sourcesContent":["import type {\n Expression,\n Identifier,\n TemplateElement,\n MemberExpression,\n} from '@babel/types';\n\nimport type { ExpressionValue, Location, WYWEvalMeta } from '@wyw-in-js/shared';\n\nexport type CSSPropertyValue = string | number;\n\nexport type ObjectWithSelectors = {\n [key: string]:\n | ObjectWithSelectors\n | CSSPropertyValue\n | (ObjectWithSelectors | CSSPropertyValue)[];\n};\n\nexport type CSSable = ObjectWithSelectors[string];\n\nexport type Value = (() => void) | WYWEvalMeta | CSSable;\n\nexport type ValueCache = Map<string | number | boolean | null, unknown>;\n\nexport interface ICSSRule {\n atom?: boolean;\n className: string;\n cssText: string;\n displayName: string;\n start: Location | null | undefined;\n}\n\nexport interface IInterpolation {\n id: string;\n node: Expression;\n source: string;\n unit: string;\n}\n\nexport type Rules = Record<string, ICSSRule>;\n\nexport type CalleeParam = readonly ['callee', Identifier | MemberExpression];\nexport type CallParam = readonly ['call', ...ExpressionValue[]];\nexport type MemberParam = readonly ['member', string];\nexport type TemplateParam = readonly [\n 'template',\n (TemplateElement | ExpressionValue)[],\n];\n\nexport type Param = CalleeParam | CallParam | MemberParam | TemplateParam;\nexport type Params = readonly Param[];\n"],"mappings":""}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
|
|
3
|
+
Object.defineProperty(exports, "__esModule", {
|
|
4
|
+
value: true
|
|
5
|
+
});
|
|
6
|
+
exports.buildSlug = buildSlug;
|
|
7
|
+
const PLACEHOLDER = /\[(.*?)]/g;
|
|
8
|
+
const isValidArgName = (key, args) => key in args;
|
|
9
|
+
function buildSlug(pattern, args) {
|
|
10
|
+
return pattern.replace(PLACEHOLDER, (_, name) => isValidArgName(name, args) ? args[name].toString() : '');
|
|
11
|
+
}
|
|
12
|
+
//# sourceMappingURL=buildSlug.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"buildSlug.js","names":["PLACEHOLDER","isValidArgName","key","args","buildSlug","pattern","replace","_","name","toString"],"sources":["../../src/utils/buildSlug.ts"],"sourcesContent":["const PLACEHOLDER = /\\[(.*?)]/g;\n\nconst isValidArgName = <TArgs extends Record<string, { toString(): string }>>(\n key: string | number | symbol,\n args: TArgs\n): key is keyof TArgs => key in args;\n\nexport function buildSlug<TArgs extends Record<string, { toString(): string }>>(\n pattern: string,\n args: TArgs\n) {\n return pattern.replace(PLACEHOLDER, (_, name: string) =>\n isValidArgName(name, args) ? args[name].toString() : ''\n );\n}\n"],"mappings":";;;;;;AAAA,MAAMA,WAAW,GAAG,WAAW;AAE/B,MAAMC,cAAc,GAAGA,CACrBC,GAA6B,EAC7BC,IAAW,KACYD,GAAG,IAAIC,IAAI;AAE7B,SAASC,SAASA,CACvBC,OAAe,EACfF,IAAW,EACX;EACA,OAAOE,OAAO,CAACC,OAAO,CAACN,WAAW,EAAE,CAACO,CAAC,EAAEC,IAAY,KAClDP,cAAc,CAACO,IAAI,EAAEL,IAAI,CAAC,GAAGA,IAAI,CAACK,IAAI,CAAC,CAACC,QAAQ,CAAC,CAAC,GAAG,EACvD,CAAC;AACH"}
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
|
|
3
|
+
Object.defineProperty(exports, "__esModule", {
|
|
4
|
+
value: true
|
|
5
|
+
});
|
|
6
|
+
exports.default = getClassNameAndSlug;
|
|
7
|
+
var _path = require("path");
|
|
8
|
+
var _shared = require("@wyw-in-js/shared");
|
|
9
|
+
var _buildSlug = require("./buildSlug");
|
|
10
|
+
var _toValidCSSIdentifier = require("./toValidCSSIdentifier");
|
|
11
|
+
function getClassNameAndSlug(displayName, idx, options, context) {
|
|
12
|
+
var _context$filename;
|
|
13
|
+
const relativeFilename = (context.root && context.filename ? (0, _path.relative)(context.root, context.filename) : (_context$filename = context.filename) !== null && _context$filename !== void 0 ? _context$filename : 'unknown').replace(/\\/g, _path.posix.sep);
|
|
14
|
+
|
|
15
|
+
// Custom properties need to start with a letter, so we prefix the slug
|
|
16
|
+
// Also use append the index of the class to the filename for uniqueness in the file
|
|
17
|
+
const slug = (0, _toValidCSSIdentifier.toValidCSSIdentifier)(`${displayName.charAt(0).toLowerCase()}${(0, _shared.slugify)(`${relativeFilename}:${idx}`)}`);
|
|
18
|
+
|
|
19
|
+
// Collect some useful replacement patterns from the filename
|
|
20
|
+
// Available variables for the square brackets used in `classNameSlug` options
|
|
21
|
+
const ext = (0, _path.extname)(relativeFilename);
|
|
22
|
+
const slugVars = {
|
|
23
|
+
hash: slug,
|
|
24
|
+
title: displayName,
|
|
25
|
+
file: relativeFilename,
|
|
26
|
+
ext,
|
|
27
|
+
name: (0, _path.basename)(relativeFilename, ext),
|
|
28
|
+
dir: (0, _path.dirname)(relativeFilename).split(_path.sep).pop()
|
|
29
|
+
};
|
|
30
|
+
let className = options.displayName ? `${(0, _toValidCSSIdentifier.toValidCSSIdentifier)(displayName)}_${slug}` : slug;
|
|
31
|
+
|
|
32
|
+
// The className can be defined by the user either as fn or a string
|
|
33
|
+
if (typeof options.classNameSlug === 'function') {
|
|
34
|
+
try {
|
|
35
|
+
className = (0, _toValidCSSIdentifier.toValidCSSIdentifier)(options.classNameSlug(slug, displayName, slugVars));
|
|
36
|
+
} catch {
|
|
37
|
+
throw new Error('classNameSlug option must return a string');
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
if (typeof options.classNameSlug === 'string') {
|
|
41
|
+
className = (0, _toValidCSSIdentifier.toValidCSSIdentifier)((0, _buildSlug.buildSlug)(options.classNameSlug, slugVars));
|
|
42
|
+
}
|
|
43
|
+
_shared.logger.extend('template-parse:generated-meta')(`slug: ${slug}, displayName: ${displayName}, className: ${className}`);
|
|
44
|
+
return {
|
|
45
|
+
className,
|
|
46
|
+
slug
|
|
47
|
+
};
|
|
48
|
+
}
|
|
49
|
+
//# sourceMappingURL=getClassNameAndSlug.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"getClassNameAndSlug.js","names":["_path","require","_shared","_buildSlug","_toValidCSSIdentifier","getClassNameAndSlug","displayName","idx","options","context","_context$filename","relativeFilename","root","filename","relative","replace","posix","sep","slug","toValidCSSIdentifier","charAt","toLowerCase","slugify","ext","extname","slugVars","hash","title","file","name","basename","dir","dirname","split","pop","className","classNameSlug","Error","buildSlug","logger","extend"],"sources":["../../src/utils/getClassNameAndSlug.ts"],"sourcesContent":["import { basename, dirname, extname, relative, sep, posix } from 'path';\n\nimport type { ClassNameSlugVars } from '@wyw-in-js/shared';\nimport { logger, slugify } from '@wyw-in-js/shared';\n\nimport { buildSlug } from './buildSlug';\nimport { toValidCSSIdentifier } from './toValidCSSIdentifier';\nimport type { IFileContext, IOptions } from './types';\n\nexport default function getClassNameAndSlug(\n displayName: string,\n idx: number,\n options: IOptions,\n context: IFileContext\n): { className: string; slug: string } {\n const relativeFilename = (\n context.root && context.filename\n ? relative(context.root, context.filename)\n : context.filename ?? 'unknown'\n ).replace(/\\\\/g, posix.sep);\n\n // Custom properties need to start with a letter, so we prefix the slug\n // Also use append the index of the class to the filename for uniqueness in the file\n const slug = toValidCSSIdentifier(\n `${displayName.charAt(0).toLowerCase()}${slugify(\n `${relativeFilename}:${idx}`\n )}`\n );\n\n // Collect some useful replacement patterns from the filename\n // Available variables for the square brackets used in `classNameSlug` options\n const ext = extname(relativeFilename);\n const slugVars: ClassNameSlugVars = {\n hash: slug,\n title: displayName,\n file: relativeFilename,\n ext,\n name: basename(relativeFilename, ext),\n dir: dirname(relativeFilename).split(sep).pop() as string,\n };\n\n let className = options.displayName\n ? `${toValidCSSIdentifier(displayName!)}_${slug!}`\n : slug!;\n\n // The className can be defined by the user either as fn or a string\n if (typeof options.classNameSlug === 'function') {\n try {\n className = toValidCSSIdentifier(\n options.classNameSlug(slug, displayName, slugVars)\n );\n } catch {\n throw new Error('classNameSlug option must return a string');\n }\n }\n\n if (typeof options.classNameSlug === 'string') {\n className = toValidCSSIdentifier(\n buildSlug(options.classNameSlug, slugVars)\n );\n }\n\n logger.extend('template-parse:generated-meta')(\n `slug: ${slug}, displayName: ${displayName}, className: ${className}`\n );\n\n return { className, slug };\n}\n"],"mappings":";;;;;;AAAA,IAAAA,KAAA,GAAAC,OAAA;AAGA,IAAAC,OAAA,GAAAD,OAAA;AAEA,IAAAE,UAAA,GAAAF,OAAA;AACA,IAAAG,qBAAA,GAAAH,OAAA;AAGe,SAASI,mBAAmBA,CACzCC,WAAmB,EAC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,WAAW,EAAEmB,QAAQ,CACnD,CAAC;IACH,CAAC,CAAC,MAAM;MACN,MAAM,IAAIY,KAAK,CAAC,2CAA2C,CAAC;IAC9D;EACF;EAEA,IAAI,OAAO7B,OAAO,CAAC4B,aAAa,KAAK,QAAQ,EAAE;IAC7CD,SAAS,GAAG,IAAAhB,0CAAoB,EAC9B,IAAAmB,oBAAS,EAAC9B,OAAO,CAAC4B,aAAa,EAAEX,QAAQ,CAC3C,CAAC;EACH;EAEAc,cAAM,CAACC,MAAM,CAAC,+BAA+B,CAAC,CAC3C,SAAQtB,IAAK,kBAAiBZ,WAAY,gBAAe6B,SAAU,EACtE,CAAC;EAED,OAAO;IAAEA,SAAS;IAAEjB;EAAK,CAAC;AAC5B"}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
|
|
3
|
+
Object.defineProperty(exports, "__esModule", {
|
|
4
|
+
value: true
|
|
5
|
+
});
|
|
6
|
+
exports.getVariableName = getVariableName;
|
|
7
|
+
function getVariableName(varId, rawVariableName) {
|
|
8
|
+
switch (rawVariableName) {
|
|
9
|
+
case 'raw':
|
|
10
|
+
return varId;
|
|
11
|
+
case 'dashes':
|
|
12
|
+
return `--${varId}`;
|
|
13
|
+
case 'var':
|
|
14
|
+
default:
|
|
15
|
+
return `var(--${varId})`;
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
//# sourceMappingURL=getVariableName.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"getVariableName.js","names":["getVariableName","varId","rawVariableName"],"sources":["../../src/utils/getVariableName.ts"],"sourcesContent":["import type { IOptions } from './types';\n\nexport function getVariableName(\n varId: string,\n rawVariableName: IOptions['variableNameConfig'] | undefined\n) {\n switch (rawVariableName) {\n case 'raw':\n return varId;\n case 'dashes':\n return `--${varId}`;\n case 'var':\n default:\n return `var(--${varId})`;\n }\n}\n"],"mappings":";;;;;;AAEO,SAASA,eAAeA,CAC7BC,KAAa,EACbC,eAA2D,EAC3D;EACA,QAAQA,eAAe;IACrB,KAAK,KAAK;MACR,OAAOD,KAAK;IACd,KAAK,QAAQ;MACX,OAAQ,KAAIA,KAAM,EAAC;IACrB,KAAK,KAAK;IACV;MACE,OAAQ,SAAQA,KAAM,GAAE;EAC5B;AACF"}
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
|
|
3
|
+
Object.defineProperty(exports, "__esModule", {
|
|
4
|
+
value: true
|
|
5
|
+
});
|
|
6
|
+
exports.default = stripLines;
|
|
7
|
+
// Stripping away the new lines ensures that we preserve line numbers
|
|
8
|
+
// This is useful in case of tools such as the stylelint pre-processor
|
|
9
|
+
// This should be safe because strings cannot contain newline: https://www.w3.org/TR/CSS2/syndata.html#strings
|
|
10
|
+
function stripLines(loc, text) {
|
|
11
|
+
let result = String(text).replace(/[\r\n]+/g, ' ').trim();
|
|
12
|
+
|
|
13
|
+
// If the start and end line numbers aren't same, add new lines to span the text across multiple lines
|
|
14
|
+
if (loc.start.line !== loc.end.line) {
|
|
15
|
+
result += '\n'.repeat(loc.end.line - loc.start.line);
|
|
16
|
+
|
|
17
|
+
// Add extra spaces to offset the column
|
|
18
|
+
result += ' '.repeat(loc.end.column);
|
|
19
|
+
}
|
|
20
|
+
return result;
|
|
21
|
+
}
|
|
22
|
+
//# sourceMappingURL=stripLines.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"stripLines.js","names":["stripLines","loc","text","result","String","replace","trim","start","line","end","repeat","column"],"sources":["../../src/utils/stripLines.ts"],"sourcesContent":["import type { Location } from '@wyw-in-js/shared';\n\n// Stripping away the new lines ensures that we preserve line numbers\n// This is useful in case of tools such as the stylelint pre-processor\n// This should be safe because strings cannot contain newline: https://www.w3.org/TR/CSS2/syndata.html#strings\nexport default function stripLines(\n loc: { end: Location; start: Location },\n text: string | number\n) {\n let result = String(text)\n .replace(/[\\r\\n]+/g, ' ')\n .trim();\n\n // If the start and end line numbers aren't same, add new lines to span the text across multiple lines\n if (loc.start.line !== loc.end.line) {\n result += '\\n'.repeat(loc.end.line - loc.start.line);\n\n // Add extra spaces to offset the column\n result += ' '.repeat(loc.end.column);\n }\n\n return result;\n}\n"],"mappings":";;;;;;AAEA;AACA;AACA;AACe,SAASA,UAAUA,CAChCC,GAAuC,EACvCC,IAAqB,EACrB;EACA,IAAIC,MAAM,GAAGC,MAAM,CAACF,IAAI,CAAC,CACtBG,OAAO,CAAC,UAAU,EAAE,GAAG,CAAC,CACxBC,IAAI,CAAC,CAAC;;EAET;EACA,IAAIL,GAAG,CAACM,KAAK,CAACC,IAAI,KAAKP,GAAG,CAACQ,GAAG,CAACD,IAAI,EAAE;IACnCL,MAAM,IAAI,IAAI,CAACO,MAAM,CAACT,GAAG,CAACQ,GAAG,CAACD,IAAI,GAAGP,GAAG,CAACM,KAAK,CAACC,IAAI,CAAC;;IAEpD;IACAL,MAAM,IAAI,GAAG,CAACO,MAAM,CAACT,GAAG,CAACQ,GAAG,CAACE,MAAM,CAAC;EACtC;EAEA,OAAOR,MAAM;AACf"}
|
|
@@ -0,0 +1,135 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
|
|
3
|
+
Object.defineProperty(exports, "__esModule", {
|
|
4
|
+
value: true
|
|
5
|
+
});
|
|
6
|
+
exports.default = templateProcessor;
|
|
7
|
+
var _shared = require("@wyw-in-js/shared");
|
|
8
|
+
var _getVariableName = require("./getVariableName");
|
|
9
|
+
var _stripLines = _interopRequireDefault(require("./stripLines"));
|
|
10
|
+
var _throwIfInvalid = _interopRequireDefault(require("./throwIfInvalid"));
|
|
11
|
+
var _toCSS = _interopRequireWildcard(require("./toCSS"));
|
|
12
|
+
var _units = require("./units");
|
|
13
|
+
function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function (nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }
|
|
14
|
+
function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
|
|
15
|
+
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
|
|
16
|
+
/* eslint-disable no-continue */
|
|
17
|
+
/**
|
|
18
|
+
* This file handles transforming template literals to class names or styled components and generates CSS content.
|
|
19
|
+
* It uses CSS code from template literals and evaluated values of lazy dependencies stored in ValueCache.
|
|
20
|
+
*/
|
|
21
|
+
|
|
22
|
+
// Match any valid CSS units followed by a separator such as ;, newline etc.
|
|
23
|
+
const unitRegex = new RegExp(`^(?:${_units.units.join('|')})\\b`);
|
|
24
|
+
function templateProcessor(tagProcessor, [...template], valueCache, variableNameConfig) {
|
|
25
|
+
const sourceMapReplacements = [];
|
|
26
|
+
// Check if the variable is referenced anywhere for basic DCE
|
|
27
|
+
// Only works when it's assigned to a variable
|
|
28
|
+
const {
|
|
29
|
+
isReferenced
|
|
30
|
+
} = tagProcessor;
|
|
31
|
+
|
|
32
|
+
// Serialize the tagged template literal to a string
|
|
33
|
+
let cssText = '';
|
|
34
|
+
let item;
|
|
35
|
+
let lastTemplateElementLocation;
|
|
36
|
+
// eslint-disable-next-line no-cond-assign
|
|
37
|
+
while (item = template.shift()) {
|
|
38
|
+
if ('type' in item) {
|
|
39
|
+
// It's a template element
|
|
40
|
+
cssText += item.value.cooked;
|
|
41
|
+
lastTemplateElementLocation = item.loc;
|
|
42
|
+
continue;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
// It's an expression
|
|
46
|
+
const {
|
|
47
|
+
ex
|
|
48
|
+
} = item;
|
|
49
|
+
const {
|
|
50
|
+
end
|
|
51
|
+
} = ex.loc;
|
|
52
|
+
const beforeLength = cssText.length;
|
|
53
|
+
|
|
54
|
+
// The location will be end of the current string to start of next string
|
|
55
|
+
const next = template[0]; // template[0] is the next template element
|
|
56
|
+
const loc = {
|
|
57
|
+
// +1 because an expression location always shows 1 column before
|
|
58
|
+
start: {
|
|
59
|
+
line: lastTemplateElementLocation.end.line,
|
|
60
|
+
column: lastTemplateElementLocation.end.column + 1
|
|
61
|
+
},
|
|
62
|
+
end: next ? {
|
|
63
|
+
line: next.loc.start.line,
|
|
64
|
+
column: next.loc.start.column
|
|
65
|
+
} : {
|
|
66
|
+
line: end.line,
|
|
67
|
+
column: end.column + 1
|
|
68
|
+
}
|
|
69
|
+
};
|
|
70
|
+
const value = 'value' in item ? item.value : valueCache.get(item.ex.name);
|
|
71
|
+
|
|
72
|
+
// Is it props based interpolation?
|
|
73
|
+
if (item.kind === _shared.ValueType.FUNCTION || typeof value === 'function') {
|
|
74
|
+
var _next$value$cooked;
|
|
75
|
+
// Check if previous expression was a CSS variable that we replaced
|
|
76
|
+
// If it has a unit after it, we need to move the unit into the interpolation
|
|
77
|
+
// e.g. `var(--size)px` should actually be `var(--size)`
|
|
78
|
+
// So we check if the current text starts with a unit, and add the unit to the previous interpolation
|
|
79
|
+
// Another approach would be `calc(var(--size) * 1px), but some browsers don't support all units
|
|
80
|
+
// https://bugzilla.mozilla.org/show_bug.cgi?id=956573
|
|
81
|
+
const matches = (_next$value$cooked = next.value.cooked) === null || _next$value$cooked === void 0 ? void 0 : _next$value$cooked.match(unitRegex);
|
|
82
|
+
try {
|
|
83
|
+
if (matches) {
|
|
84
|
+
var _next$value$cooked$su, _next$value$cooked2, _unit$length;
|
|
85
|
+
template.shift();
|
|
86
|
+
const [unit] = matches;
|
|
87
|
+
const varId = tagProcessor.addInterpolation(item.ex, cssText, item.source, unit);
|
|
88
|
+
cssText += (0, _getVariableName.getVariableName)(varId, variableNameConfig);
|
|
89
|
+
cssText += (_next$value$cooked$su = (_next$value$cooked2 = next.value.cooked) === null || _next$value$cooked2 === void 0 ? void 0 : _next$value$cooked2.substring((_unit$length = unit === null || unit === void 0 ? void 0 : unit.length) !== null && _unit$length !== void 0 ? _unit$length : 0)) !== null && _next$value$cooked$su !== void 0 ? _next$value$cooked$su : '';
|
|
90
|
+
} else {
|
|
91
|
+
const varId = tagProcessor.addInterpolation(item.ex, cssText, item.source);
|
|
92
|
+
cssText += (0, _getVariableName.getVariableName)(varId, variableNameConfig);
|
|
93
|
+
}
|
|
94
|
+
} catch (e) {
|
|
95
|
+
if (e instanceof Error) {
|
|
96
|
+
throw item.buildCodeFrameError(e.message);
|
|
97
|
+
}
|
|
98
|
+
throw e;
|
|
99
|
+
}
|
|
100
|
+
} else {
|
|
101
|
+
(0, _throwIfInvalid.default)(tagProcessor.isValidValue.bind(tagProcessor), value, item, item.source);
|
|
102
|
+
if (value !== undefined && typeof value !== 'function') {
|
|
103
|
+
// Skip the blank string instead of throw ing an error
|
|
104
|
+
if (value === '') {
|
|
105
|
+
continue;
|
|
106
|
+
}
|
|
107
|
+
if ((0, _shared.hasEvalMeta)(value)) {
|
|
108
|
+
// If it's a React component wrapped in styled, get the class name
|
|
109
|
+
// Useful for interpolating components
|
|
110
|
+
cssText += `.${value.__wyw_meta.className}`;
|
|
111
|
+
} else if ((0, _toCSS.isCSSable)(value)) {
|
|
112
|
+
// If it's a plain object or an array, convert it to a CSS string
|
|
113
|
+
cssText += (0, _stripLines.default)(loc, (0, _toCSS.default)(value));
|
|
114
|
+
} else {
|
|
115
|
+
// For anything else, assume it'll be stringified
|
|
116
|
+
cssText += (0, _stripLines.default)(loc, value);
|
|
117
|
+
}
|
|
118
|
+
sourceMapReplacements.push({
|
|
119
|
+
original: loc,
|
|
120
|
+
length: cssText.length - beforeLength
|
|
121
|
+
});
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
const rules = tagProcessor.extractRules(valueCache, cssText, tagProcessor.location);
|
|
126
|
+
|
|
127
|
+
// tagProcessor.doRuntimeReplacement(classes);
|
|
128
|
+
if (!isReferenced && !cssText.includes(':global')) {
|
|
129
|
+
return null;
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
// eslint-disable-next-line no-param-reassign
|
|
133
|
+
return [rules, sourceMapReplacements];
|
|
134
|
+
}
|
|
135
|
+
//# sourceMappingURL=templateProcessor.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"templateProcessor.js","names":["_shared","require","_getVariableName","_stripLines","_interopRequireDefault","_throwIfInvalid","_toCSS","_interopRequireWildcard","_units","_getRequireWildcardCache","nodeInterop","WeakMap","cacheBabelInterop","cacheNodeInterop","obj","__esModule","default","cache","has","get","newObj","hasPropertyDescriptor","Object","defineProperty","getOwnPropertyDescriptor","key","prototype","hasOwnProperty","call","desc","set","unitRegex","RegExp","units","join","templateProcessor","tagProcessor","template","valueCache","variableNameConfig","sourceMapReplacements","isReferenced","cssText","item","lastTemplateElementLocation","shift","value","cooked","loc","ex","end","beforeLength","length","next","start","line","column","name","kind","ValueType","FUNCTION","_next$value$cooked","matches","match","_next$value$cooked$su","_next$value$cooked2","_unit$length","unit","varId","addInterpolation","source","getVariableName","substring","e","Error","buildCodeFrameError","message","throwIfInvalid","isValidValue","bind","undefined","hasEvalMeta","__wyw_meta","className","isCSSable","stripLines","toCSS","push","original","rules","extractRules","location","includes"],"sources":["../../src/utils/templateProcessor.ts"],"sourcesContent":["/* eslint-disable no-continue */\n/**\n * This file handles transforming template literals to class names or styled components and generates CSS content.\n * It uses CSS code from template literals and evaluated values of lazy dependencies stored in ValueCache.\n */\n\nimport type { TemplateElement, SourceLocation } from '@babel/types';\n\nimport type { ExpressionValue, Replacements } from '@wyw-in-js/shared';\nimport { hasEvalMeta, ValueType } from '@wyw-in-js/shared';\n\nimport type { TaggedTemplateProcessor } from '../TaggedTemplateProcessor';\nimport type { ValueCache, Rules } from '../types';\n\nimport { getVariableName } from './getVariableName';\nimport stripLines from './stripLines';\nimport throwIfInvalid from './throwIfInvalid';\nimport toCSS, { isCSSable } from './toCSS';\nimport type { IOptions } from './types';\nimport { units } from './units';\n\n// Match any valid CSS units followed by a separator such as ;, newline etc.\nconst unitRegex = new RegExp(`^(?:${units.join('|')})\\\\b`);\n\nexport default function templateProcessor(\n tagProcessor: TaggedTemplateProcessor,\n [...template]: (TemplateElement | ExpressionValue)[],\n valueCache: ValueCache,\n variableNameConfig: IOptions['variableNameConfig'] | undefined\n): [rules: Rules, sourceMapReplacements: Replacements] | null {\n const sourceMapReplacements: Replacements = [];\n // Check if the variable is referenced anywhere for basic DCE\n // Only works when it's assigned to a variable\n const { isReferenced } = tagProcessor;\n\n // Serialize the tagged template literal to a string\n let cssText = '';\n\n let item: TemplateElement | ExpressionValue | undefined;\n let lastTemplateElementLocation: SourceLocation | null | undefined;\n // eslint-disable-next-line no-cond-assign\n while ((item = template.shift())) {\n if ('type' in item) {\n // It's a template element\n cssText += item.value.cooked;\n lastTemplateElementLocation = item.loc;\n continue;\n }\n\n // It's an expression\n const { ex } = item;\n\n const { end } = ex.loc!;\n const beforeLength = cssText.length;\n\n // The location will be end of the current string to start of next string\n const next = template[0] as TemplateElement; // template[0] is the next template element\n const loc = {\n // +1 because an expression location always shows 1 column before\n start: {\n line: lastTemplateElementLocation!.end.line,\n column: lastTemplateElementLocation!.end.column + 1,\n },\n end: next\n ? { line: next.loc!.start.line, column: next.loc!.start.column }\n : { line: end.line, column: end.column + 1 },\n };\n\n const value = 'value' in item ? item.value : valueCache.get(item.ex.name);\n\n // Is it props based interpolation?\n if (item.kind === ValueType.FUNCTION || typeof value === 'function') {\n // Check if previous expression was a CSS variable that we replaced\n // If it has a unit after it, we need to move the unit into the interpolation\n // e.g. `var(--size)px` should actually be `var(--size)`\n // So we check if the current text starts with a unit, and add the unit to the previous interpolation\n // Another approach would be `calc(var(--size) * 1px), but some browsers don't support all units\n // https://bugzilla.mozilla.org/show_bug.cgi?id=956573\n const matches = next.value.cooked?.match(unitRegex);\n\n try {\n if (matches) {\n template.shift();\n const [unit] = matches;\n\n const varId = tagProcessor.addInterpolation(\n item.ex,\n cssText,\n item.source,\n unit\n );\n cssText += getVariableName(varId, variableNameConfig);\n\n cssText += next.value.cooked?.substring(unit?.length ?? 0) ?? '';\n } else {\n const varId = tagProcessor.addInterpolation(\n item.ex,\n cssText,\n item.source\n );\n cssText += getVariableName(varId, variableNameConfig);\n }\n } catch (e) {\n if (e instanceof Error) {\n throw item.buildCodeFrameError(e.message);\n }\n\n throw e;\n }\n } else {\n throwIfInvalid(\n tagProcessor.isValidValue.bind(tagProcessor),\n value,\n item,\n item.source\n );\n\n if (value !== undefined && typeof value !== 'function') {\n // Skip the blank string instead of throw ing an error\n if (value === '') {\n continue;\n }\n\n if (hasEvalMeta(value)) {\n // If it's a React component wrapped in styled, get the class name\n // Useful for interpolating components\n cssText += `.${value.__wyw_meta.className}`;\n } else if (isCSSable(value)) {\n // If it's a plain object or an array, convert it to a CSS string\n cssText += stripLines(loc, toCSS(value));\n } else {\n // For anything else, assume it'll be stringified\n cssText += stripLines(loc, value);\n }\n\n sourceMapReplacements.push({\n original: loc,\n length: cssText.length - beforeLength,\n });\n }\n }\n }\n\n const rules = tagProcessor.extractRules(\n valueCache,\n cssText,\n tagProcessor.location\n );\n\n // tagProcessor.doRuntimeReplacement(classes);\n if (!isReferenced && !cssText.includes(':global')) {\n return null;\n }\n\n // eslint-disable-next-line no-param-reassign\n return [rules, sourceMapReplacements];\n}\n"],"mappings":";;;;;;AASA,IAAAA,OAAA,GAAAC,OAAA;AAKA,IAAAC,gBAAA,GAAAD,OAAA;AACA,IAAAE,WAAA,GAAAC,sBAAA,CAAAH,OAA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