@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.
Files changed (92) hide show
  1. package/LICENSE +21 -0
  2. package/esm/BaseProcessor.js +70 -0
  3. package/esm/BaseProcessor.js.map +1 -0
  4. package/esm/TaggedTemplateProcessor.js +43 -0
  5. package/esm/TaggedTemplateProcessor.js.map +1 -0
  6. package/esm/index.js +7 -0
  7. package/esm/index.js.map +1 -0
  8. package/esm/types.js +2 -0
  9. package/esm/types.js.map +1 -0
  10. package/esm/utils/buildSlug.js +6 -0
  11. package/esm/utils/buildSlug.js.map +1 -0
  12. package/esm/utils/getClassNameAndSlug.js +42 -0
  13. package/esm/utils/getClassNameAndSlug.js.map +1 -0
  14. package/esm/utils/getVariableName.js +12 -0
  15. package/esm/utils/getVariableName.js.map +1 -0
  16. package/esm/utils/stripLines.js +16 -0
  17. package/esm/utils/stripLines.js.map +1 -0
  18. package/esm/utils/templateProcessor.js +125 -0
  19. package/esm/utils/templateProcessor.js.map +1 -0
  20. package/esm/utils/throwIfInvalid.js +29 -0
  21. package/esm/utils/throwIfInvalid.js.map +1 -0
  22. package/esm/utils/toCSS.js +50 -0
  23. package/esm/utils/toCSS.js.map +1 -0
  24. package/esm/utils/toValidCSSIdentifier.js +4 -0
  25. package/esm/utils/toValidCSSIdentifier.js.map +1 -0
  26. package/esm/utils/types.js +2 -0
  27. package/esm/utils/types.js.map +1 -0
  28. package/esm/utils/units.js +65 -0
  29. package/esm/utils/units.js.map +1 -0
  30. package/esm/utils/validateParams.js +40 -0
  31. package/esm/utils/validateParams.js.map +1 -0
  32. package/lib/BaseProcessor.js +78 -0
  33. package/lib/BaseProcessor.js.map +1 -0
  34. package/lib/TaggedTemplateProcessor.js +51 -0
  35. package/lib/TaggedTemplateProcessor.js.map +1 -0
  36. package/lib/index.js +67 -0
  37. package/lib/index.js.map +1 -0
  38. package/lib/types.js +2 -0
  39. package/lib/types.js.map +1 -0
  40. package/lib/utils/buildSlug.js +12 -0
  41. package/lib/utils/buildSlug.js.map +1 -0
  42. package/lib/utils/getClassNameAndSlug.js +49 -0
  43. package/lib/utils/getClassNameAndSlug.js.map +1 -0
  44. package/lib/utils/getVariableName.js +18 -0
  45. package/lib/utils/getVariableName.js.map +1 -0
  46. package/lib/utils/stripLines.js +22 -0
  47. package/lib/utils/stripLines.js.map +1 -0
  48. package/lib/utils/templateProcessor.js +135 -0
  49. package/lib/utils/templateProcessor.js.map +1 -0
  50. package/lib/utils/throwIfInvalid.js +35 -0
  51. package/lib/utils/throwIfInvalid.js.map +1 -0
  52. package/lib/utils/toCSS.js +58 -0
  53. package/lib/utils/toCSS.js.map +1 -0
  54. package/lib/utils/toValidCSSIdentifier.js +10 -0
  55. package/lib/utils/toValidCSSIdentifier.js.map +1 -0
  56. package/lib/utils/types.js +2 -0
  57. package/lib/utils/types.js.map +1 -0
  58. package/lib/utils/units.js +71 -0
  59. package/lib/utils/units.js.map +1 -0
  60. package/lib/utils/validateParams.js +54 -0
  61. package/lib/utils/validateParams.js.map +1 -0
  62. package/package.json +40 -0
  63. package/types/BaseProcessor.d.ts +66 -0
  64. package/types/BaseProcessor.js +59 -0
  65. package/types/TaggedTemplateProcessor.d.ts +20 -0
  66. package/types/TaggedTemplateProcessor.js +40 -0
  67. package/types/index.d.ts +9 -0
  68. package/types/index.js +29 -0
  69. package/types/types.d.ts +32 -0
  70. package/types/types.js +2 -0
  71. package/types/utils/buildSlug.d.ts +3 -0
  72. package/types/utils/buildSlug.js +9 -0
  73. package/types/utils/getClassNameAndSlug.d.ts +5 -0
  74. package/types/utils/getClassNameAndSlug.js +43 -0
  75. package/types/utils/getVariableName.d.ts +2 -0
  76. package/types/utils/getVariableName.js +15 -0
  77. package/types/utils/stripLines.d.ts +5 -0
  78. package/types/utils/stripLines.js +18 -0
  79. package/types/utils/templateProcessor.d.ts +10 -0
  80. package/types/utils/templateProcessor.js +140 -0
  81. package/types/utils/throwIfInvalid.d.ts +5 -0
  82. package/types/utils/throwIfInvalid.js +32 -0
  83. package/types/utils/toCSS.d.ts +3 -0
  84. package/types/utils/toCSS.js +61 -0
  85. package/types/utils/toValidCSSIdentifier.d.ts +1 -0
  86. package/types/utils/toValidCSSIdentifier.js +7 -0
  87. package/types/utils/types.d.ts +9 -0
  88. package/types/utils/types.js +2 -0
  89. package/types/utils/units.d.ts +44 -0
  90. package/types/utils/units.js +94 -0
  91. package/types/utils/validateParams.d.ts +16 -0
  92. package/types/utils/validateParams.js +39 -0
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2023 Anton Evzhakov
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,70 @@
1
+ /* eslint-disable class-methods-use-this */
2
+
3
+ import generator from '@babel/generator';
4
+ import { hasEvalMeta } from '@wyw-in-js/shared';
5
+ import getClassNameAndSlug from './utils/getClassNameAndSlug';
6
+ import { isCSSable } from './utils/toCSS';
7
+ import { validateParams } from './utils/validateParams';
8
+ export class BaseProcessor {
9
+ static SKIP = Symbol('skip');
10
+ artifacts = [];
11
+ dependencies = [];
12
+ interpolations = [];
13
+ constructor(params, tagSource, astService, location, replacer, displayName, isReferenced, idx, options, context) {
14
+ this.tagSource = tagSource;
15
+ this.astService = astService;
16
+ this.location = location;
17
+ this.replacer = replacer;
18
+ this.displayName = displayName;
19
+ this.isReferenced = isReferenced;
20
+ this.idx = idx;
21
+ this.options = options;
22
+ this.context = context;
23
+ validateParams(params, ['callee'], 'Unknown error: a callee param is not specified');
24
+ const {
25
+ className,
26
+ slug
27
+ } = getClassNameAndSlug(this.displayName, this.idx, this.options, this.context);
28
+ this.className = className;
29
+ this.slug = slug;
30
+ [[, this.callee]] = params;
31
+ }
32
+
33
+ /**
34
+ * A replacement for tag referenced in a template literal.
35
+ */
36
+
37
+ /**
38
+ * A replacement for the tag in evaluation time.
39
+ * For example, `css` tag will be replaced with its className,
40
+ * whereas `styled` tag will be replaced with an object with metadata.
41
+ */
42
+
43
+ isValidValue(value) {
44
+ return typeof value === 'function' || isCSSable(value) || hasEvalMeta(value);
45
+ }
46
+ toString() {
47
+ return this.tagSourceCode();
48
+ }
49
+ tagSourceCode() {
50
+ if (this.callee.type === 'Identifier') {
51
+ return this.callee.name;
52
+ }
53
+ return generator(this.callee).code;
54
+ }
55
+
56
+ /**
57
+ * Perform a replacement for the tag in evaluation time.
58
+ * For example, `css` tag will be replaced with its className,
59
+ * whereas `styled` tag will be replaced with an object with metadata.
60
+ */
61
+
62
+ /**
63
+ * Perform a replacement for the tag with its runtime version.
64
+ * For example, `css` tag will be replaced with its className,
65
+ * whereas `styled` tag will be replaced with a component.
66
+ * If some parts require evaluated data for render,
67
+ * they will be replaced with placeholders.
68
+ */
69
+ }
70
+ //# sourceMappingURL=BaseProcessor.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"BaseProcessor.js","names":["generator","hasEvalMeta","getClassNameAndSlug","isCSSable","validateParams","BaseProcessor","SKIP","Symbol","artifacts","dependencies","interpolations","constructor","params","tagSource","astService","location","replacer","displayName","isReferenced","idx","options","context","className","slug","callee","isValidValue","value","toString","tagSourceCode","type","name","code"],"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":"AAAA;;AAEA,OAAOA,SAAS,MAAM,kBAAkB;AASxC,SAASC,WAAW,QAAQ,mBAAmB;AAG/C,OAAOC,mBAAmB,MAAM,6BAA6B;AAC7D,SAASC,SAAS,QAAQ,eAAe;AAEzC,SAASC,cAAc,QAAQ,wBAAwB;AAcvD,OAAO,MAAeC,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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ACA;AACA;AACA;AACA;AACA;AAEA"}
@@ -0,0 +1,43 @@
1
+ import { ValueType } from '@wyw-in-js/shared';
2
+ import { BaseProcessor } from './BaseProcessor';
3
+ import templateProcessor from './utils/templateProcessor';
4
+ import { validateParams } from './utils/validateParams';
5
+ export class TaggedTemplateProcessor extends BaseProcessor {
6
+ #template;
7
+ constructor(params, ...args) {
8
+ // Should have at least two params and the first one should be a callee.
9
+ validateParams(params, ['callee', '...'], TaggedTemplateProcessor.SKIP);
10
+ validateParams(params, ['callee', 'template'], 'Invalid usage of template tag');
11
+ const [tag, [, template]] = params;
12
+ super([tag], ...args);
13
+ template.forEach(element => {
14
+ if ('kind' in element && element.kind !== ValueType.FUNCTION) {
15
+ this.dependencies.push(element);
16
+ }
17
+ });
18
+ this.#template = template;
19
+ }
20
+ build(values) {
21
+ if (this.artifacts.length > 0) {
22
+ // FIXME: why it was called twice?
23
+ throw new Error('Tag is already built');
24
+ }
25
+ const artifact = templateProcessor(this, this.#template, values, this.options.variableNameConfig);
26
+ if (artifact) {
27
+ this.artifacts.push(['css', artifact]);
28
+ }
29
+ }
30
+ toString() {
31
+ return `${super.toString()}\`…\``;
32
+ }
33
+
34
+ /**
35
+ * It is called for each resolved expression in a template literal.
36
+ * @param node
37
+ * @param precedingCss
38
+ * @param source
39
+ * @param unit
40
+ * @return chunk of CSS that should be added to extracted CSS
41
+ */
42
+ }
43
+ //# sourceMappingURL=TaggedTemplateProcessor.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"TaggedTemplateProcessor.js","names":["ValueType","BaseProcessor","templateProcessor","validateParams","TaggedTemplateProcessor","template","constructor","params","args","SKIP","tag","forEach","element","kind","FUNCTION","dependencies","push","build","values","artifacts","length","Error","artifact","options","variableNameConfig","toString"],"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?: SourceLocation | null\n ): Rules;\n}\n"],"mappings":"AAGA,SAASA,SAAS,QAAQ,mBAAmB;AAG7C,SAASC,aAAa,QAAQ,iBAAiB;AAE/C,OAAOC,iBAAiB,MAAM,2BAA2B;AACzD,SAASC,cAAc,QAAQ,wBAAwB;AAEvD,OAAO,MAAeC,uBAAuB,SAASH,aAAa,CAAC;EACzD,CAACI,QAAQ;EAERC,WAAWA,CAACC,MAAc,EAAE,GAAGC,IAAyB,EAAE;IAClE;IACAL,cAAc,CAACI,MAAM,EAAE,CAAC,QAAQ,EAAE,KAAK,CAAC,EAAEH,uBAAuB,CAACK,IAAI,CAAC;IAEvEN,cAAc,CACZI,MAAM,EACN,CAAC,QAAQ,EAAE,UAAU,CAAC,EACtB,+BACF,CAAC;IACD,MAAM,CAACG,GAAG,EAAE,GAAGL,QAAQ,CAAC,CAAC,GAAGE,MAAM;IAElC,KAAK,CAAC,CAACG,GAAG,CAAC,EAAE,GAAGF,IAAI,CAAC;IAErBH,QAAQ,CAACM,OAAO,CAAEC,OAAO,IAAK;MAC5B,IAAI,MAAM,IAAIA,OAAO,IAAIA,OAAO,CAACC,IAAI,KAAKb,SAAS,CAACc,QAAQ,EAAE;QAC5D,IAAI,CAACC,YAAY,CAACC,IAAI,CAACJ,OAAO,CAAC;MACjC;IACF,CAAC,CAAC;IAEF,IAAI,CAAC,CAACP,QAAQ,GAAGA,QAAQ;EAC3B;EAEgBY,KAAKA,CAACC,MAAkB,EAAE;IACxC,IAAI,IAAI,CAACC,SAAS,CAACC,MAAM,GAAG,CAAC,EAAE;MAC7B;MACA,MAAM,IAAIC,KAAK,CAAC,sBAAsB,CAAC;IACzC;IAEA,MAAMC,QAAQ,GAAGpB,iBAAiB,CAChC,IAAI,EACJ,IAAI,CAAC,CAACG,QAAQ,EACda,MAAM,EACN,IAAI,CAACK,OAAO,CAACC,kBACf,CAAC;IACD,IAAIF,QAAQ,EAAE;MACZ,IAAI,CAACH,SAAS,CAACH,IAAI,CAAC,CAAC,KAAK,EAAEM,QAAQ,CAAC,CAAC;IACxC;EACF;EAEgBG,QAAQA,CAAA,EAAW;IACjC,OAAQ,GAAE,KAAK,CAACA,QAAQ,CAAC,CAAE,OAAM;EACnC;;EAEA;AACF;AACA;AACA;AACA;AACA;AACA;AACA;AAaA"}
package/esm/index.js ADDED
@@ -0,0 +1,7 @@
1
+ export { BaseProcessor } from './BaseProcessor';
2
+ export * from './types';
3
+ export { buildSlug } from './utils/buildSlug';
4
+ export { isValidParams, validateParams } from './utils/validateParams';
5
+ export { TaggedTemplateProcessor } from './TaggedTemplateProcessor';
6
+ export { toValidCSSIdentifier } from './utils/toValidCSSIdentifier';
7
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","names":["BaseProcessor","buildSlug","isValidParams","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,SAASA,aAAa,QAAQ,iBAAiB;AAO/C,cAAc,SAAS;AACvB,SAASC,SAAS,QAAQ,mBAAmB;AAE7C,SAASC,aAAa,EAAEC,cAAc,QAAQ,wBAAwB;AAEtE,SAASC,uBAAuB,QAAQ,2BAA2B;AACnE,SAASC,oBAAoB,QAAQ,8BAA8B"}
package/esm/types.js ADDED
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=types.js.map
@@ -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,6 @@
1
+ const PLACEHOLDER = /\[(.*?)]/g;
2
+ const isValidArgName = (key, args) => key in args;
3
+ export function buildSlug(pattern, args) {
4
+ return pattern.replace(PLACEHOLDER, (_, name) => isValidArgName(name, args) ? args[name].toString() : '');
5
+ }
6
+ //# 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;AAEpC,OAAO,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,42 @@
1
+ import { basename, dirname, extname, relative, sep, posix } from 'path';
2
+ import { logger, slugify } from '@wyw-in-js/shared';
3
+ import { buildSlug } from './buildSlug';
4
+ import { toValidCSSIdentifier } from './toValidCSSIdentifier';
5
+ export default function getClassNameAndSlug(displayName, idx, options, context) {
6
+ const relativeFilename = (context.root && context.filename ? relative(context.root, context.filename) : context.filename ?? 'unknown').replace(/\\/g, posix.sep);
7
+
8
+ // Custom properties need to start with a letter, so we prefix the slug
9
+ // Also use append the index of the class to the filename for uniqueness in the file
10
+ const slug = toValidCSSIdentifier(`${displayName.charAt(0).toLowerCase()}${slugify(`${relativeFilename}:${idx}`)}`);
11
+
12
+ // Collect some useful replacement patterns from the filename
13
+ // Available variables for the square brackets used in `classNameSlug` options
14
+ const ext = extname(relativeFilename);
15
+ const slugVars = {
16
+ hash: slug,
17
+ title: displayName,
18
+ file: relativeFilename,
19
+ ext,
20
+ name: basename(relativeFilename, ext),
21
+ dir: dirname(relativeFilename).split(sep).pop()
22
+ };
23
+ let className = options.displayName ? `${toValidCSSIdentifier(displayName)}_${slug}` : slug;
24
+
25
+ // The className can be defined by the user either as fn or a string
26
+ if (typeof options.classNameSlug === 'function') {
27
+ try {
28
+ className = toValidCSSIdentifier(options.classNameSlug(slug, displayName, slugVars));
29
+ } catch {
30
+ throw new Error('classNameSlug option must return a string');
31
+ }
32
+ }
33
+ if (typeof options.classNameSlug === 'string') {
34
+ className = toValidCSSIdentifier(buildSlug(options.classNameSlug, slugVars));
35
+ }
36
+ logger.extend('template-parse:generated-meta')(`slug: ${slug}, displayName: ${displayName}, className: ${className}`);
37
+ return {
38
+ className,
39
+ slug
40
+ };
41
+ }
42
+ //# sourceMappingURL=getClassNameAndSlug.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"getClassNameAndSlug.js","names":["basename","dirname","extname","relative","sep","posix","logger","slugify","buildSlug","toValidCSSIdentifier","getClassNameAndSlug","displayName","idx","options","context","relativeFilename","root","filename","replace","slug","charAt","toLowerCase","ext","slugVars","hash","title","file","name","dir","split","pop","className","classNameSlug","Error","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,SAASA,QAAQ,EAAEC,OAAO,EAAEC,OAAO,EAAEC,QAAQ,EAAEC,GAAG,EAAEC,KAAK,QAAQ,MAAM;AAGvE,SAASC,MAAM,EAAEC,OAAO,QAAQ,mBAAmB;AAEnD,SAASC,SAAS,QAAQ,aAAa;AACvC,SAASC,oBAAoB,QAAQ,wBAAwB;AAG7D,eAAe,SAASC,mBAAmBA,CACzCC,WAAmB,EACnBC,GAAW,EACXC,OAAiB,EACjBC,OAAqB,EACgB;EACrC,MAAMC,gBAAgB,GAAG,CACvBD,OAAO,CAACE,IAAI,IAAIF,OAAO,CAACG,QAAQ,GAC5Bd,QAAQ,CAACW,OAAO,CAACE,IAAI,EAAEF,OAAO,CAACG,QAAQ,CAAC,GACxCH,OAAO,CAACG,QAAQ,IAAI,SAAS,EACjCC,OAAO,CAAC,KAAK,EAAEb,KAAK,CAACD,GAAG,CAAC;;EAE3B;EACA;EACA,MAAMe,IAAI,GAAGV,oBAAoB,CAC9B,GAAEE,WAAW,CAACS,MAAM,CAAC,CAAC,CAAC,CAACC,WAAW,CAAC,CAAE,GAAEd,OAAO,CAC7C,GAAEQ,gBAAiB,IAAGH,GAAI,EAC7B,CAAE,EACJ,CAAC;;EAED;EACA;EACA,MAAMU,GAAG,GAAGpB,OAAO,CAACa,gBAAgB,CAAC;EACrC,MAAMQ,QAA2B,GAAG;IAClCC,IAAI,EAAEL,IAAI;IACVM,KAAK,EAAEd,WAAW;IAClBe,IAAI,EAAEX,gBAAgB;IACtBO,GAAG;IACHK,IAAI,EAAE3B,QAAQ,CAACe,gBAAgB,EAAEO,GAAG,CAAC;IACrCM,GAAG,EAAE3B,OAAO,CAACc,gBAAgB,CAAC,CAACc,KAAK,CAACzB,GAAG,CAAC,CAAC0B,GAAG,CAAC;EAChD,CAAC;EAED,IAAIC,SAAS,GAAGlB,OAAO,CAACF,WAAW,GAC9B,GAAEF,oBAAoB,CAACE,WAAY,CAAE,IAAGQ,IAAM,EAAC,GAChDA,IAAK;;EAET;EACA,IAAI,OAAON,OAAO,CAACmB,aAAa,KAAK,UAAU,EAAE;IAC/C,IAAI;MACFD,SAAS,GAAGtB,oBAAoB,CAC9BI,OAAO,CAACmB,aAAa,CAACb,IAAI,EAAER,WAAW,EAAEY,QAAQ,CACnD,CAAC;IACH,CAAC,CAAC,MAAM;MACN,MAAM,IAAIU,KAAK,CAAC,2CAA2C,CAAC;IAC9D;EACF;EAEA,IAAI,OAAOpB,OAAO,CAACmB,aAAa,KAAK,QAAQ,EAAE;IAC7CD,SAAS,GAAGtB,oBAAoB,CAC9BD,SAAS,CAACK,OAAO,CAACmB,aAAa,EAAET,QAAQ,CAC3C,CAAC;EACH;EAEAjB,MAAM,CAAC4B,MAAM,CAAC,+BAA+B,CAAC,CAC3C,SAAQf,IAAK,kBAAiBR,WAAY,gBAAeoB,SAAU,EACtE,CAAC;EAED,OAAO;IAAEA,SAAS;IAAEZ;EAAK,CAAC;AAC5B"}
@@ -0,0 +1,12 @@
1
+ export function getVariableName(varId, rawVariableName) {
2
+ switch (rawVariableName) {
3
+ case 'raw':
4
+ return varId;
5
+ case 'dashes':
6
+ return `--${varId}`;
7
+ case 'var':
8
+ default:
9
+ return `var(--${varId})`;
10
+ }
11
+ }
12
+ //# 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":"AAEA,OAAO,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,16 @@
1
+ // Stripping away the new lines ensures that we preserve line numbers
2
+ // This is useful in case of tools such as the stylelint pre-processor
3
+ // This should be safe because strings cannot contain newline: https://www.w3.org/TR/CSS2/syndata.html#strings
4
+ export default function stripLines(loc, text) {
5
+ let result = String(text).replace(/[\r\n]+/g, ' ').trim();
6
+
7
+ // If the start and end line numbers aren't same, add new lines to span the text across multiple lines
8
+ if (loc.start.line !== loc.end.line) {
9
+ result += '\n'.repeat(loc.end.line - loc.start.line);
10
+
11
+ // Add extra spaces to offset the column
12
+ result += ' '.repeat(loc.end.column);
13
+ }
14
+ return result;
15
+ }
16
+ //# 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;AACA,eAAe,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,125 @@
1
+ /* eslint-disable no-continue */
2
+ /**
3
+ * This file handles transforming template literals to class names or styled components and generates CSS content.
4
+ * It uses CSS code from template literals and evaluated values of lazy dependencies stored in ValueCache.
5
+ */
6
+
7
+ import { hasEvalMeta, ValueType } from '@wyw-in-js/shared';
8
+ import { getVariableName } from './getVariableName';
9
+ import stripLines from './stripLines';
10
+ import throwIfInvalid from './throwIfInvalid';
11
+ import toCSS, { isCSSable } from './toCSS';
12
+ import { units } from './units';
13
+
14
+ // Match any valid CSS units followed by a separator such as ;, newline etc.
15
+ const unitRegex = new RegExp(`^(?:${units.join('|')})\\b`);
16
+ export default function templateProcessor(tagProcessor, [...template], valueCache, variableNameConfig) {
17
+ const sourceMapReplacements = [];
18
+ // Check if the variable is referenced anywhere for basic DCE
19
+ // Only works when it's assigned to a variable
20
+ const {
21
+ isReferenced
22
+ } = tagProcessor;
23
+
24
+ // Serialize the tagged template literal to a string
25
+ let cssText = '';
26
+ let item;
27
+ let lastTemplateElementLocation;
28
+ // eslint-disable-next-line no-cond-assign
29
+ while (item = template.shift()) {
30
+ if ('type' in item) {
31
+ // It's a template element
32
+ cssText += item.value.cooked;
33
+ lastTemplateElementLocation = item.loc;
34
+ continue;
35
+ }
36
+
37
+ // It's an expression
38
+ const {
39
+ ex
40
+ } = item;
41
+ const {
42
+ end
43
+ } = ex.loc;
44
+ const beforeLength = cssText.length;
45
+
46
+ // The location will be end of the current string to start of next string
47
+ const next = template[0]; // template[0] is the next template element
48
+ const loc = {
49
+ // +1 because an expression location always shows 1 column before
50
+ start: {
51
+ line: lastTemplateElementLocation.end.line,
52
+ column: lastTemplateElementLocation.end.column + 1
53
+ },
54
+ end: next ? {
55
+ line: next.loc.start.line,
56
+ column: next.loc.start.column
57
+ } : {
58
+ line: end.line,
59
+ column: end.column + 1
60
+ }
61
+ };
62
+ const value = 'value' in item ? item.value : valueCache.get(item.ex.name);
63
+
64
+ // Is it props based interpolation?
65
+ if (item.kind === ValueType.FUNCTION || typeof value === 'function') {
66
+ // Check if previous expression was a CSS variable that we replaced
67
+ // If it has a unit after it, we need to move the unit into the interpolation
68
+ // e.g. `var(--size)px` should actually be `var(--size)`
69
+ // So we check if the current text starts with a unit, and add the unit to the previous interpolation
70
+ // Another approach would be `calc(var(--size) * 1px), but some browsers don't support all units
71
+ // https://bugzilla.mozilla.org/show_bug.cgi?id=956573
72
+ const matches = next.value.cooked?.match(unitRegex);
73
+ try {
74
+ if (matches) {
75
+ template.shift();
76
+ const [unit] = matches;
77
+ const varId = tagProcessor.addInterpolation(item.ex, cssText, item.source, unit);
78
+ cssText += getVariableName(varId, variableNameConfig);
79
+ cssText += next.value.cooked?.substring(unit?.length ?? 0) ?? '';
80
+ } else {
81
+ const varId = tagProcessor.addInterpolation(item.ex, cssText, item.source);
82
+ cssText += getVariableName(varId, variableNameConfig);
83
+ }
84
+ } catch (e) {
85
+ if (e instanceof Error) {
86
+ throw item.buildCodeFrameError(e.message);
87
+ }
88
+ throw e;
89
+ }
90
+ } else {
91
+ throwIfInvalid(tagProcessor.isValidValue.bind(tagProcessor), value, item, item.source);
92
+ if (value !== undefined && typeof value !== 'function') {
93
+ // Skip the blank string instead of throw ing an error
94
+ if (value === '') {
95
+ continue;
96
+ }
97
+ if (hasEvalMeta(value)) {
98
+ // If it's a React component wrapped in styled, get the class name
99
+ // Useful for interpolating components
100
+ cssText += `.${value.__wyw_meta.className}`;
101
+ } else if (isCSSable(value)) {
102
+ // If it's a plain object or an array, convert it to a CSS string
103
+ cssText += stripLines(loc, toCSS(value));
104
+ } else {
105
+ // For anything else, assume it'll be stringified
106
+ cssText += stripLines(loc, value);
107
+ }
108
+ sourceMapReplacements.push({
109
+ original: loc,
110
+ length: cssText.length - beforeLength
111
+ });
112
+ }
113
+ }
114
+ }
115
+ const rules = tagProcessor.extractRules(valueCache, cssText, tagProcessor.location);
116
+
117
+ // tagProcessor.doRuntimeReplacement(classes);
118
+ if (!isReferenced && !cssText.includes(':global')) {
119
+ return null;
120
+ }
121
+
122
+ // eslint-disable-next-line no-param-reassign
123
+ return [rules, sourceMapReplacements];
124
+ }
125
+ //# sourceMappingURL=templateProcessor.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"templateProcessor.js","names":["hasEvalMeta","ValueType","getVariableName","stripLines","throwIfInvalid","toCSS","isCSSable","units","unitRegex","RegExp","join","templateProcessor","tagProcessor","template","valueCache","variableNameConfig","sourceMapReplacements","isReferenced","cssText","item","lastTemplateElementLocation","shift","value","cooked","loc","ex","end","beforeLength","length","next","start","line","column","get","name","kind","FUNCTION","matches","match","unit","varId","addInterpolation","source","substring","e","Error","buildCodeFrameError","message","isValidValue","bind","undefined","__wyw_meta","className","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":"AAAA;AACA;AACA;AACA;AACA;;AAKA,SAASA,WAAW,EAAEC,SAAS,QAAQ,mBAAmB;AAK1D,SAASC,eAAe,QAAQ,mBAAmB;AACnD,OAAOC,UAAU,MAAM,cAAc;AACrC,OAAOC,cAAc,MAAM,kBAAkB;AAC7C,OAAOC,KAAK,IAAIC,SAAS,QAAQ,SAAS;AAE1C,SAASC,KAAK,QAAQ,SAAS;;AAE/B;AACA,MAAMC,SAAS,GAAG,IAAIC,MAAM,CAAE,OAAMF,KAAK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I,CAACrC,YAAY,CAAC,EAC5CU,KAAK,EACLH,IAAI,EACJA,IAAI,CAACuB,MACP,CAAC;MAED,IAAIpB,KAAK,KAAK4B,SAAS,IAAI,OAAO5B,KAAK,KAAK,UAAU,EAAE;QACtD;QACA,IAAIA,KAAK,KAAK,EAAE,EAAE;UAChB;QACF;QAEA,IAAItB,WAAW,CAACsB,KAAK,CAAC,EAAE;UACtB;UACA;UACAJ,OAAO,IAAK,IAAGI,KAAK,CAAC6B,UAAU,CAACC,SAAU,EAAC;QAC7C,CAAC,MAAM,IAAI9C,SAAS,CAACgB,KAAK,CAAC,EAAE;UAC3B;UACAJ,OAAO,IAAIf,UAAU,CAACqB,GAAG,EAAEnB,KAAK,CAACiB,KAAK,CAAC,CAAC;QAC1C,CAAC,MAAM;UACL;UACAJ,OAAO,IAAIf,UAAU,CAACqB,GAAG,EAAEF,KAAK,CAAC;QACnC;QAEAN,qBAAqB,CAACqC,IAAI,CAAC;UACzBC,QAAQ,EAAE9B,GAAG;UACbI,MAAM,EAAEV,OAAO,CAACU,MAAM,GAAGD;QAC3B,CAAC,CAAC;MACJ;IACF;EACF;EAEA,MAAM4B,KAAK,GAAG3C,YAAY,CAAC4C,YAAY,CACrC1C,UAAU,EACVI,OAAO,EACPN,YAAY,CAAC6C,QACf,CAAC;;EAED;EACA,IAAI,CAACxC,YAAY,IAAI,CAACC,OAAO,CAACwC,QAAQ,CAAC,SAAS,CAAC,EAAE;IACjD,OAAO,IAAI;EACb;;EAEA;EACA,OAAO,CAACH,KAAK,EAAEvC,qBAAqB,CAAC;AACvC"}
@@ -0,0 +1,29 @@
1
+ const isLikeError = value => typeof value === 'object' && value !== null && 'stack' in value && 'message' in value;
2
+
3
+ // Throw if we can't handle the interpolated value
4
+ function throwIfInvalid(checker, value, ex, source) {
5
+ // We can't use instanceof here so let's use duck typing
6
+ if (isLikeError(value) && value.stack && value.message) {
7
+ throw ex.buildCodeFrameError(`An error occurred when evaluating the expression:
8
+
9
+ > ${value.message}.
10
+
11
+ Make sure you are not using a browser or Node specific API and all the variables are available in static context.
12
+ Linaria have to extract pieces of your code to resolve the interpolated values.
13
+ Defining styled component or class will not work inside:
14
+ - function,
15
+ - class,
16
+ - method,
17
+ - loop,
18
+ because it cannot be statically determined in which context you use them.
19
+ That's why some variables may be not defined during evaluation.
20
+ `);
21
+ }
22
+ if (checker(value)) {
23
+ return;
24
+ }
25
+ const stringified = typeof value === 'object' ? JSON.stringify(value) : String(value);
26
+ throw ex.buildCodeFrameError(`The expression evaluated to '${stringified}', which is probably a mistake. If you want it to be inserted into CSS, explicitly cast or transform the value to a string, e.g. - 'String(${source})'.`);
27
+ }
28
+ export default throwIfInvalid;
29
+ //# sourceMappingURL=throwIfInvalid.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"throwIfInvalid.js","names":["isLikeError","value","throwIfInvalid","checker","ex","source","stack","message","buildCodeFrameError","stringified","JSON","stringify","String"],"sources":["../../src/utils/throwIfInvalid.ts"],"sourcesContent":["import type { BuildCodeFrameErrorFn } from '@wyw-in-js/shared';\n\nconst isLikeError = (value: unknown): value is Error =>\n typeof value === 'object' &&\n value !== null &&\n 'stack' in value &&\n 'message' in value;\n\n// Throw if we can't handle the interpolated value\nfunction throwIfInvalid<T>(\n checker: (value: unknown) => value is T,\n value: Error | unknown,\n ex: { buildCodeFrameError: BuildCodeFrameErrorFn },\n source: string\n): asserts value is T {\n // We can't use instanceof here so let's use duck typing\n if (isLikeError(value) && value.stack && value.message) {\n throw ex.buildCodeFrameError(\n `An error occurred when evaluating the expression:\n\n > ${value.message}.\n\n Make sure you are not using a browser or Node specific API and all the variables are available in static context.\n Linaria have to extract pieces of your code to resolve the interpolated values.\n Defining styled component or class will not work inside:\n - function,\n - class,\n - method,\n - loop,\n because it cannot be statically determined in which context you use them.\n That's why some variables may be not defined during evaluation.\n `\n );\n }\n\n if (checker(value)) {\n return;\n }\n\n const stringified =\n typeof value === 'object' ? JSON.stringify(value) : String(value);\n\n throw ex.buildCodeFrameError(\n `The expression evaluated to '${stringified}', which is probably a mistake. If you want it to be inserted into CSS, explicitly cast or transform the value to a string, e.g. - 'String(${source})'.`\n );\n}\n\nexport default throwIfInvalid;\n"],"mappings":"AAEA,MAAMA,WAAW,GAAIC,KAAc,IACjC,OAAOA,KAAK,KAAK,QAAQ,IACzBA,KAAK,KAAK,IAAI,IACd,OAAO,IAAIA,KAAK,IAChB,SAAS,IAAIA,KAAK;;AAEpB;AACA,SAASC,cAAcA,CACrBC,OAAuC,EACvCF,KAAsB,EACtBG,EAAkD,EAClDC,MAAc,EACM;EACpB;EACA,IAAIL,WAAW,CAACC,KAAK,CAAC,IAAIA,KAAK,CAACK,KAAK,IAAIL,KAAK,CAACM,OAAO,EAAE;IACtD,MAAMH,EAAE,CAACI,mBAAmB,CACzB;AACP;AACA,MAAMP,KAAK,CAACM,OAAQ;AACpB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OACI,CAAC;EACH;EAEA,IAAIJ,OAAO,CAACF,KAAK,CAAC,EAAE;IAClB;EACF;EAEA,MAAMQ,WAAW,GACf,OAAOR,KAAK,KAAK,QAAQ,GAAGS,IAAI,CAACC,SAAS,CAACV,KAAK,CAAC,GAAGW,MAAM,CAACX,KAAK,CAAC;EAEnE,MAAMG,EAAE,CAACI,mBAAmB,CACzB,gCAA+BC,WAAY,8IAA6IJ,MAAO,KAClM,CAAC;AACH;AAEA,eAAeH,cAAc"}
@@ -0,0 +1,50 @@
1
+ import { isBoxedPrimitive } from '@wyw-in-js/shared';
2
+ import { unitless } from './units';
3
+ const isCSSPropertyValue = o => {
4
+ return isBoxedPrimitive(o) || typeof o === 'string' || typeof o === 'number' && Number.isFinite(o);
5
+ };
6
+ export const isCSSable = o => {
7
+ if (isCSSPropertyValue(o)) {
8
+ return true;
9
+ }
10
+ if (Array.isArray(o)) {
11
+ return o.every(isCSSable);
12
+ }
13
+ if (typeof o === 'object') {
14
+ return o !== null && Object.values(o).every(isCSSable);
15
+ }
16
+ return false;
17
+ };
18
+ const hyphenate = s => {
19
+ if (s.startsWith('--')) {
20
+ // It's a custom property which is already well formatted.
21
+ return s;
22
+ }
23
+ return s
24
+ // Hyphenate CSS property names from camelCase version from JS string
25
+ .replace(/([A-Z])/g, (match, p1) => `-${p1.toLowerCase()}`)
26
+ // Special case for `-ms` because in JS it starts with `ms` unlike `Webkit`
27
+ .replace(/^ms-/, '-ms-');
28
+ };
29
+
30
+ // Some tools such as polished.js output JS objects
31
+ // To support them transparently, we convert JS objects to CSS strings
32
+ export default function toCSS(o) {
33
+ if (Array.isArray(o)) {
34
+ return o.map(toCSS).join('\n');
35
+ }
36
+ if (isCSSPropertyValue(o)) {
37
+ return o.valueOf().toString();
38
+ }
39
+ return Object.entries(o).filter(([, value]) =>
40
+ // Ignore all falsy values except numbers
41
+ typeof value === 'number' || value).map(([key, value]) => {
42
+ if (!isCSSPropertyValue(value)) {
43
+ return `${key} { ${toCSS(value)} }`;
44
+ }
45
+ return `${hyphenate(key)}: ${typeof value === 'number' && value !== 0 &&
46
+ // Strip vendor prefixes when checking if the value is unitless
47
+ !(key.replace(/^(Webkit|Moz|O|ms)([A-Z])(.+)$/, (match, p1, p2, p3) => `${p2.toLowerCase()}${p3}`) in unitless) ? `${value}px` : value};`;
48
+ }).join(' ');
49
+ }
50
+ //# sourceMappingURL=toCSS.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"toCSS.js","names":["isBoxedPrimitive","unitless","isCSSPropertyValue","o","Number","isFinite","isCSSable","Array","isArray","every","Object","values","hyphenate","s","startsWith","replace","match","p1","toLowerCase","toCSS","map","join","valueOf","toString","entries","filter","value","key","p2","p3"],"sources":["../../src/utils/toCSS.ts"],"sourcesContent":["import { isBoxedPrimitive } from '@wyw-in-js/shared';\n\nimport type { CSSPropertyValue, CSSable } from '../types';\n\nimport { unitless } from './units';\n\nconst isCSSPropertyValue = (o: unknown): o is CSSPropertyValue => {\n return (\n isBoxedPrimitive(o) ||\n typeof o === 'string' ||\n (typeof o === 'number' && Number.isFinite(o))\n );\n};\n\nexport const isCSSable = (o: unknown): o is CSSable => {\n if (isCSSPropertyValue(o)) {\n return true;\n }\n\n if (Array.isArray(o)) {\n return o.every(isCSSable);\n }\n\n if (typeof o === 'object') {\n return o !== null && Object.values(o).every(isCSSable);\n }\n\n return false;\n};\n\nconst hyphenate = (s: string) => {\n if (s.startsWith('--')) {\n // It's a custom property which is already well formatted.\n return s;\n }\n return (\n s\n // Hyphenate CSS property names from camelCase version from JS string\n .replace(/([A-Z])/g, (match, p1) => `-${p1.toLowerCase()}`)\n // Special case for `-ms` because in JS it starts with `ms` unlike `Webkit`\n .replace(/^ms-/, '-ms-')\n );\n};\n\n// Some tools such as polished.js output JS objects\n// To support them transparently, we convert JS objects to CSS strings\nexport default function toCSS(o: CSSable): string {\n if (Array.isArray(o)) {\n return o.map(toCSS).join('\\n');\n }\n\n if (isCSSPropertyValue(o)) {\n return o.valueOf().toString();\n }\n\n return Object.entries(o)\n .filter(\n ([, value]) =>\n // Ignore all falsy values except numbers\n typeof value === 'number' || value\n )\n .map(([key, value]) => {\n if (!isCSSPropertyValue(value)) {\n return `${key} { ${toCSS(value)} }`;\n }\n\n return `${hyphenate(key)}: ${\n typeof value === 'number' &&\n value !== 0 &&\n // Strip vendor prefixes when checking if the value is unitless\n !(\n key.replace(\n /^(Webkit|Moz|O|ms)([A-Z])(.+)$/,\n (match, p1, p2, p3) => `${p2.toLowerCase()}${p3}`\n ) in unitless\n )\n ? `${value}px`\n : value\n };`;\n })\n .join(' ');\n}\n"],"mappings":"AAAA,SAASA,gBAAgB,QAAQ,mBAAmB;AAIpD,SAASC,QAAQ,QAAQ,SAAS;AAElC,MAAMC,kBAAkB,GAAIC,CAAU,IAA4B;EAChE,OACEH,gBAAgB,CAACG,CAAC,CAAC,IACnB,OAAOA,CAAC,KAAK,QAAQ,IACpB,OAAOA,CAAC,KAAK,QAAQ,IAAIC,MAAM,CAACC,QAAQ,CAACF,CAAC,CAAE;AAE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GAAG,EAAED,KAAK,CAAC,KAAK;IACrB,IAAI,CAACxB,kBAAkB,CAACwB,KAAK,CAAC,EAAE;MAC9B,OAAQ,GAAEC,GAAI,MAAKR,KAAK,CAACO,KAAK,CAAE,IAAG;IACrC;IAEA,OAAQ,GAAEd,SAAS,CAACe,GAAG,CAAE,KACvB,OAAOD,KAAK,KAAK,QAAQ,IACzBA,KAAK,KAAK,CAAC;IACX;IACA,EACEC,GAAG,CAACZ,OAAO,CACT,gCAAgC,EAChC,CAACC,KAAK,EAAEC,EAAE,EAAEW,EAAE,EAAEC,EAAE,KAAM,GAAED,EAAE,CAACV,WAAW,CAAC,CAAE,GAAEW,EAAG,EAClD,CAAC,IAAI5B,QAAQ,CACd,GACI,GAAEyB,KAAM,IAAG,GACZA,KACL,GAAE;EACL,CAAC,CAAC,CACDL,IAAI,CAAC,GAAG,CAAC;AACd"}
@@ -0,0 +1,4 @@
1
+ export function toValidCSSIdentifier(s) {
2
+ return s.replace(/[^-_a-z0-9\u00A0-\uFFFF]/gi, '_').replace(/^\d/, '_');
3
+ }
4
+ //# sourceMappingURL=toValidCSSIdentifier.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"toValidCSSIdentifier.js","names":["toValidCSSIdentifier","s","replace"],"sources":["../../src/utils/toValidCSSIdentifier.ts"],"sourcesContent":["export function toValidCSSIdentifier(s: string) {\n return s.replace(/[^-_a-z0-9\\u00A0-\\uFFFF]/gi, '_').replace(/^\\d/, '_');\n}\n"],"mappings":"AAAA,OAAO,SAASA,oBAAoBA,CAACC,CAAS,EAAE;EAC9C,OAAOA,CAAC,CAACC,OAAO,CAAC,4BAA4B,EAAE,GAAG,CAAC,CAACA,OAAO,CAAC,KAAK,EAAE,GAAG,CAAC;AACzE"}
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=types.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.js","names":[],"sources":["../../src/utils/types.ts"],"sourcesContent":["import type { TransformOptions } from '@babel/core';\n\nimport type { ClassNameFn, VariableNameFn } from '@wyw-in-js/shared';\n\nexport interface IOptions {\n classNameSlug?: string | ClassNameFn;\n displayName: boolean;\n variableNameConfig?: 'var' | 'dashes' | 'raw';\n variableNameSlug?: string | VariableNameFn;\n}\n\nexport type IFileContext = Pick<TransformOptions, 'root' | 'filename'>;\n"],"mappings":""}
@@ -0,0 +1,65 @@
1
+ // https://www.w3.org/TR/css-values-4/
2
+ export const units = [
3
+ // font relative lengths
4
+ 'em', 'ex', 'cap', 'ch', 'ic', 'rem', 'lh', 'rlh',
5
+ // viewport percentage lengths
6
+ 'vw', 'vh', 'vi', 'vb', 'vmin', 'vmax',
7
+ // absolute lengths
8
+ 'cm', 'mm', 'Q', 'in', 'pc', 'pt', 'px',
9
+ // angle units
10
+ 'deg', 'grad', 'rad', 'turn',
11
+ // duration units
12
+ 's', 'ms',
13
+ // frequency units
14
+ 'Hz', 'kHz',
15
+ // resolution units
16
+ 'dpi', 'dpcm', 'dppx', 'x',
17
+ // https://www.w3.org/TR/css-grid-1/#fr-unit
18
+ 'fr',
19
+ // percentages
20
+ '%'];
21
+ export const unitless = {
22
+ animationIterationCount: true,
23
+ borderImageOutset: true,
24
+ borderImageSlice: true,
25
+ borderImageWidth: true,
26
+ boxFlex: true,
27
+ boxFlexGroup: true,
28
+ boxOrdinalGroup: true,
29
+ columnCount: true,
30
+ columns: true,
31
+ flex: true,
32
+ flexGrow: true,
33
+ flexPositive: true,
34
+ flexShrink: true,
35
+ flexNegative: true,
36
+ flexOrder: true,
37
+ gridRow: true,
38
+ gridRowEnd: true,
39
+ gridRowSpan: true,
40
+ gridRowStart: true,
41
+ gridColumn: true,
42
+ gridColumnEnd: true,
43
+ gridColumnSpan: true,
44
+ gridColumnStart: true,
45
+ fontWeight: true,
46
+ lineClamp: true,
47
+ lineHeight: true,
48
+ opacity: true,
49
+ order: true,
50
+ orphans: true,
51
+ tabSize: true,
52
+ widows: true,
53
+ zIndex: true,
54
+ zoom: true,
55
+ // SVG-related properties
56
+ fillOpacity: true,
57
+ floodOpacity: true,
58
+ stopOpacity: true,
59
+ strokeDasharray: true,
60
+ strokeDashoffset: true,
61
+ strokeMiterlimit: true,
62
+ strokeOpacity: true,
63
+ strokeWidth: true
64
+ };
65
+ //# sourceMappingURL=units.js.map