From 89645b63b660c5c53ff31cf73007659c55b9c17e Mon Sep 17 00:00:00 2001 From: Thierry Bela Nanga Date: Mon, 15 Jun 2026 08:24:24 -0400 Subject: [PATCH 01/26] update documentation --- CHANGELOG.md | 5 +- dist/config.json.js | 45 +- dist/index-umd-web.js | 225 ++++- dist/index.cjs | 225 ++++- dist/index.d.ts | 981 +++++++++--------- dist/lib/ast/clone.js | 7 +- dist/lib/ast/features/if.js | 3 +- dist/lib/parser/declaration/list.js | 67 +- dist/lib/parser/parse.js | 14 +- dist/lib/parser/tokenize.js | 58 +- dist/lib/parser/utils/at-rule.js | 6 - dist/lib/parser/utils/declaration.js | 9 + files/about.md | 2 +- files/assets/typedoc-custom.css | 5 + files/ast.md | 18 +- files/css-module.md | 78 +- files/features.md | 34 +- files/index.md | 4 + files/install.md | 12 +- files/minification.md | 86 +- files/parsing.md | 92 ++ files/rendering.md | 94 ++ files/transform.md | 18 +- files/usage.md | 172 +--- files/validation.md | 14 +- package.json | 1 + src/@types/config.d.ts | 324 +++--- src/@types/index.d.ts | 304 +++--- src/@types/shorthand.d.ts | 34 +- src/config.json | 2 +- src/lib/ast/clone.ts | 17 +- src/lib/ast/features/if.ts | 4 +- src/lib/parser/declaration/list.ts | 98 +- src/lib/parser/parse.ts | 32 +- src/lib/parser/tokenize.ts | 84 +- src/lib/parser/utils/at-rule-generic.ts | 2 +- src/lib/parser/utils/at-rule.ts | 14 +- src/lib/parser/utils/declaration.ts | 14 + test/specs/code/at-rules.js | 2 +- test/specs/code/block.js | 14 + test/specs/code/validation.js | 18 + tools/index.ts | 3 - tools/shorthand.ts | 1215 +++++++++++++---------- typedoc.json | 33 +- 44 files changed, 2689 insertions(+), 1800 deletions(-) create mode 100644 files/assets/typedoc-custom.css create mode 100644 files/parsing.md create mode 100644 files/rendering.md delete mode 100644 tools/index.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index 7cdd71b3..c4bf28b4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,7 +1,10 @@ # Changelog -## v1.4.3 +## v1.4.4 + +- [x] minify transform-origin property +## v1.4.3 ### CSS Modules diff --git a/dist/config.json.js b/dist/config.json.js index 1db687dc..12c7300d 100644 --- a/dist/config.json.js +++ b/dist/config.json.js @@ -1503,9 +1503,50 @@ var map = { shorthand: "background" } }; +var property = { + "transform-origin": { + pattern: [ + [ + "left|center|right", + "top|center|bottom", + "" + ], + [ + "left|center|right", + "top|center|bottom" + ], + [ + "center|left|right|center|top|bottom|" + ] + ], + mapping: { + center: { + typ: "Perc", + val: 50 + }, + left: { + typ: "Perc", + val: 0 + }, + right: { + typ: "Perc", + val: 100 + }, + top: { + typ: "Perc", + val: 0 + }, + bottom: { + typ: "Perc", + val: 100 + } + } + } +}; var config = { properties: properties, - map: map + map: map, + property: property }; -export { config as default, map, properties }; +export { config as default, map, properties, property }; diff --git a/dist/index-umd-web.js b/dist/index-umd-web.js index bc6dd52d..1b0d1ed6 100644 --- a/dist/index-umd-web.js +++ b/dist/index-umd-web.js @@ -15334,9 +15334,50 @@ shorthand: "background" } }; + var property = { + "transform-origin": { + pattern: [ + [ + "left|center|right", + "top|center|bottom", + "" + ], + [ + "left|center|right", + "top|center|bottom" + ], + [ + "center|left|right|center|top|bottom|" + ] + ], + mapping: { + center: { + typ: "Perc", + val: 50 + }, + left: { + typ: "Perc", + val: 0 + }, + right: { + typ: "Perc", + val: 100 + }, + top: { + typ: "Perc", + val: 0 + }, + bottom: { + typ: "Perc", + val: 100 + } + } + } + }; var config$2 = { properties: properties, - map: map + map: map, + property: property }; Object.freeze(config$2); @@ -16087,7 +16128,7 @@ } let propertyName = declaration.nam; let shortHandType; - let shorthand; + let shorthand = null; if (propertyName in config$1.properties) { // @ts-ignore if ("map" in config$1.properties[propertyName]) { @@ -16106,6 +16147,11 @@ // @ts-ignore shorthand = config$1.map[propertyName].shorthand; } + else if (propertyName in config$1.property) { + shortHandType = "single"; + // @ts-ignore + shorthand = config$1.property[propertyName]; + } // @ts-ignore if (shortHandType == "map") { // @ts-ignore @@ -16131,11 +16177,71 @@ this.declarations.get(shorthand).add(declaration); } else { + if (shorthand != null) { + this.mapValues(declaration, shorthand); + } this.declarations.set(propertyName, declaration); } } return this; } + mapValues(declaration, mapping) { + let name; + let values = declaration.val; + if (mapping.pattern != null) { + // match pattern + for (const patterns of mapping.pattern) { + const set = new Set(values.filter((v) => v.typ !== exports.EnumToken.CommentTokenType && v.typ !== exports.EnumToken.WhitespaceTokenType)); + const val = []; + for (const pattern of patterns) { + switch (pattern) { + case "": + for (const v of set) { + if (v.typ === exports.EnumToken.LengthTokenType || + (v.typ === exports.EnumToken.NumberTokenType && v.val === 0)) { + val.push(v); + set.delete(v); + } + } + default: { + for (const v of set) { + if (v.typ === exports.EnumToken.IdenTokenType) { + const value = v.val.toLowerCase(); + if (value === pattern || new RegExp(`(^|\|)${pattern}(\||$)`).test(value)) { + val.push(v); + set.delete(v); + } + } + } + } + } + } + if (set.size === 0) { + values = val.reduce((acc, curr) => { + if (acc.length > 0) { + acc.push({ typ: exports.EnumToken.WhitespaceTokenType }); + } + acc.push(curr); + return acc; + }, []); + break; + } + } + } + for (const val of declaration.val) { + if (val.typ === exports.EnumToken.IdenTokenType) { + name = val.val.toLowerCase(); + if (mapping.mapping[name] != null) { + // @ts-expect-error + Object.assign(val, mapping.mapping[name], { typ: exports.EnumToken[mapping.mapping[name].typ] }); + } + } + } + if (values != declaration.val) { + declaration.val.length = 0; + declaration.val.push(...values); + } + } [Symbol.iterator]() { let iterator = this.declarations.values(); const iterators = []; @@ -17425,9 +17531,10 @@ /** * - * @param node he nod to clone - * @param cloneChildren deep clone - * @param cloneMap a map of existing children as keys and their clones as values + * clone an ast node or value + * @param node + * @param cloneChildren + * @param cloneMap * @returns */ function cloneNode(node, cloneChildren = false, cloneMap = null) { @@ -17974,6 +18081,15 @@ if (value.typ === exports.EnumToken.IdenTokenType && isColor(value)) { parseColor(value); } + // else if (value.typ === EnumToken.UrlFunctionTokenType) { + // const token = (value as FunctionToken).chi.find((t: Token) => t.typ === EnumToken.StringTokenType) as StringToken; + // if (token != null && urlTokenMatcher.test((token as StringToken).val)) { + // Object.assign(token, { + // typ: EnumToken.UrlTokenTokenType, + // val: (token as StringToken).val.slice(1, -1), + // }); + // } + // } } if (name.val === "grid" || name.val === "grid-template-areas" || @@ -21374,8 +21490,7 @@ } } run(declaration) { - const cache = new Set(); - const result = processNode(declaration, cache); + const result = processNode(declaration, new Set()); let i; for (const n of result) { for (const { node } of walk(n)) { @@ -21818,10 +21933,62 @@ break; } else if (isIdent(buffer)) { - result.push(yieldResult(buffer, parseInfo, buffer.startsWith("--") + const hint = buffer.startsWith("--") ? exports.EnumToken.CustomFunctionTokenDefType - : (SymbolsMapTokens[buffer.toLowerCase() + "("] ?? exports.EnumToken.FunctionTokenDefType))); + : (SymbolsMapTokens[buffer.toLowerCase() + "("] ?? exports.EnumToken.FunctionTokenDefType); + result.push(yieldResult(buffer, parseInfo, hint)); buffer = ""; + if (hint === exports.EnumToken.UrlFunctionTokenDefType) { + value = peek(parseInfo); + // consume an + while (isWhiteSpace((charCode = value.charCodeAt(0)))) { + buffer += next(parseInfo); + value = peek(parseInfo); + charCode = value.charCodeAt(0); + if (value === "/" && match(parseInfo, "/*")) { + if (buffer.length > 0) { + result.push(yieldResult(buffer, parseInfo)); + buffer = ""; + } + buffer += next(parseInfo, 2); + while ((value = next(parseInfo))) { + if (value == "*") { + buffer += value; + if (match(parseInfo, "/")) { + result.push(yieldResult(buffer + next(parseInfo), parseInfo, exports.EnumToken.CommentTokenType)); + buffer = ""; + break; + } + } + else { + buffer += value; + } + } + if (buffer.length > 0) { + result.push(yieldResult(buffer, parseInfo, exports.EnumToken.BadCommentTokenType)); + buffer = ""; + } + value = peek(parseInfo); + charCode = value.charCodeAt(0); + } + } + if (buffer.length > 0) { + result.push(yieldResult(buffer, parseInfo, exports.EnumToken.WhitespaceTokenType)); + buffer = ""; + } + if (value === ")" || value === '"' || value === "'") { + break; + } + do { + buffer += next(parseInfo); + value = peek(parseInfo); + charCode = value.charCodeAt(0); + } while (value !== ")" && !isWhiteSpace(charCode) && !(value === '/' && match(parseInfo, "/*"))); + if (buffer.length > 0) { + result.push(yieldResult(buffer, parseInfo, peek(parseInfo) === "" ? exports.EnumToken.BadUrlTokenType : exports.EnumToken.UrlTokenTokenType)); + buffer = ""; + } + } break; } } @@ -27411,12 +27578,6 @@ }; } - // export const mediaQueryConditionEnum: Set = new Set([ - // EnumToken.ParensTokenType, - // EnumToken.IdenTokenType, - // EnumToken.MediaQueryConditionTokenType, - // EnumToken.MediaQueryUnaryFeatureTokenType, - // ]); function matchAtRuleSyntax(atRule, stream, options) { const syntaxRules = getSyntaxRule(ValidationSyntaxGroupEnum.AtRules, "@" + atRule.nam); const syntax = syntaxRules?.getPreludeRules()?.slice?.(1); @@ -27442,27 +27603,6 @@ return { success, errors }; } - function parseAtRulePage(context, stream, options, errors) { - const syntaxRules = getSyntaxRule(ValidationSyntaxGroupEnum.AtRules, "@page"); - const syntax = syntaxRules?.getPreludeRules?.()?.slice?.(1); - let validate = false; - for (const token of stream) { - if (token.typ !== exports.EnumToken.WhitespaceTokenType && token.typ !== exports.EnumToken.CommentTokenType) { - validate = true; - break; - } - } - if (!validate) { - return { - success: true, - errors, - }; - } - const result = matchAllSyntax(trimSyntaxArray(syntax), createValidationContext(stream), options); - errors.push(...result.errors); - return { success: result.success, errors }; - } - function parseAtRuleFontFeatureValues(stream, context, options = {}) { const syntaxRules = getSyntaxRule(ValidationSyntaxGroupEnum.AtRules, "@" + context.nam); const syntax = syntaxRules?.getPreludeRules()?.slice?.(1); @@ -29153,7 +29293,6 @@ * @param parseAsBlock */ function parseAtRule(stream, context, options, errors, parseAsBlock = null) { - // const rules = getSyntaxRule(ValidationSyntaxGroupEnum.AtRules, "@" + (stream[0] as AtRuleToken).nam); let success = true; let atRuleName = stream[0].nam; if (atRuleName.startsWith("-")) { @@ -29413,6 +29552,9 @@ if (!result.success) { errors.push(...result.errors); } + // else { + // parseUrlToken(stream); + // } const valid = blockAllowed === parseAsBlock && result.success; if (valid) { let start = 0; @@ -29465,7 +29607,7 @@ } else { if (stream[0]?.typ == exports.EnumToken.UrlFunctionTokenType && - stream[0].chi.some((t) => t.typ == exports.EnumToken.StringTokenType)) { + stream[0].chi.some((t) => t.typ == exports.EnumToken.StringTokenType || t.typ == exports.EnumToken.UrlTokenTokenType)) { stream.splice(0, 1, ...stream[0].chi); } } @@ -29681,7 +29823,6 @@ } case "page": { trimArray(stream); - parseAtRulePage(atRule, stream, options, errors); // @ts-expect-error return Object.defineProperties(Object.assign(atRule, { typ: success ? exports.EnumToken.AtRuleNodeType : exports.EnumToken.InvalidRuleNodeType, @@ -29836,6 +29977,12 @@ } else { result = matchAtRuleSyntax(atRule, stream, options); + if (result.errors.length > 0) { + errors.push(...result.errors); + } + // else if (atRuleName === "document") { + // parseUrlToken(stream); + // } if (result.success) { let i = 0; const stack = []; diff --git a/dist/index.cjs b/dist/index.cjs index 919948ec..6b95725b 100644 --- a/dist/index.cjs +++ b/dist/index.cjs @@ -15335,9 +15335,50 @@ var map = { shorthand: "background" } }; +var property = { + "transform-origin": { + pattern: [ + [ + "left|center|right", + "top|center|bottom", + "" + ], + [ + "left|center|right", + "top|center|bottom" + ], + [ + "center|left|right|center|top|bottom|" + ] + ], + mapping: { + center: { + typ: "Perc", + val: 50 + }, + left: { + typ: "Perc", + val: 0 + }, + right: { + typ: "Perc", + val: 100 + }, + top: { + typ: "Perc", + val: 0 + }, + bottom: { + typ: "Perc", + val: 100 + } + } + } +}; var config$2 = { properties: properties, - map: map + map: map, + property: property }; Object.freeze(config$2); @@ -16088,7 +16129,7 @@ class PropertyList { } let propertyName = declaration.nam; let shortHandType; - let shorthand; + let shorthand = null; if (propertyName in config$1.properties) { // @ts-ignore if ("map" in config$1.properties[propertyName]) { @@ -16107,6 +16148,11 @@ class PropertyList { // @ts-ignore shorthand = config$1.map[propertyName].shorthand; } + else if (propertyName in config$1.property) { + shortHandType = "single"; + // @ts-ignore + shorthand = config$1.property[propertyName]; + } // @ts-ignore if (shortHandType == "map") { // @ts-ignore @@ -16132,11 +16178,71 @@ class PropertyList { this.declarations.get(shorthand).add(declaration); } else { + if (shorthand != null) { + this.mapValues(declaration, shorthand); + } this.declarations.set(propertyName, declaration); } } return this; } + mapValues(declaration, mapping) { + let name; + let values = declaration.val; + if (mapping.pattern != null) { + // match pattern + for (const patterns of mapping.pattern) { + const set = new Set(values.filter((v) => v.typ !== exports.EnumToken.CommentTokenType && v.typ !== exports.EnumToken.WhitespaceTokenType)); + const val = []; + for (const pattern of patterns) { + switch (pattern) { + case "": + for (const v of set) { + if (v.typ === exports.EnumToken.LengthTokenType || + (v.typ === exports.EnumToken.NumberTokenType && v.val === 0)) { + val.push(v); + set.delete(v); + } + } + default: { + for (const v of set) { + if (v.typ === exports.EnumToken.IdenTokenType) { + const value = v.val.toLowerCase(); + if (value === pattern || new RegExp(`(^|\|)${pattern}(\||$)`).test(value)) { + val.push(v); + set.delete(v); + } + } + } + } + } + } + if (set.size === 0) { + values = val.reduce((acc, curr) => { + if (acc.length > 0) { + acc.push({ typ: exports.EnumToken.WhitespaceTokenType }); + } + acc.push(curr); + return acc; + }, []); + break; + } + } + } + for (const val of declaration.val) { + if (val.typ === exports.EnumToken.IdenTokenType) { + name = val.val.toLowerCase(); + if (mapping.mapping[name] != null) { + // @ts-expect-error + Object.assign(val, mapping.mapping[name], { typ: exports.EnumToken[mapping.mapping[name].typ] }); + } + } + } + if (values != declaration.val) { + declaration.val.length = 0; + declaration.val.push(...values); + } + } [Symbol.iterator]() { let iterator = this.declarations.values(); const iterators = []; @@ -17426,9 +17532,10 @@ function trimWhiteSpaceTokens(tokens) { /** * - * @param node he nod to clone - * @param cloneChildren deep clone - * @param cloneMap a map of existing children as keys and their clones as values + * clone an ast node or value + * @param node + * @param cloneChildren + * @param cloneMap * @returns */ function cloneNode(node, cloneChildren = false, cloneMap = null) { @@ -17975,6 +18082,15 @@ function parseDeclaration(tokens, parent, options, errors) { if (value.typ === exports.EnumToken.IdenTokenType && isColor(value)) { parseColor(value); } + // else if (value.typ === EnumToken.UrlFunctionTokenType) { + // const token = (value as FunctionToken).chi.find((t: Token) => t.typ === EnumToken.StringTokenType) as StringToken; + // if (token != null && urlTokenMatcher.test((token as StringToken).val)) { + // Object.assign(token, { + // typ: EnumToken.UrlTokenTokenType, + // val: (token as StringToken).val.slice(1, -1), + // }); + // } + // } } if (name.val === "grid" || name.val === "grid-template-areas" || @@ -21375,8 +21491,7 @@ class ExpandIfFeature { } } run(declaration) { - const cache = new Set(); - const result = processNode(declaration, cache); + const result = processNode(declaration, new Set()); let i; for (const n of result) { for (const { node } of walk(n)) { @@ -21819,10 +21934,62 @@ function tokenize(parseInfo, yieldEOFToken = true) { break; } else if (isIdent(buffer)) { - result.push(yieldResult(buffer, parseInfo, buffer.startsWith("--") + const hint = buffer.startsWith("--") ? exports.EnumToken.CustomFunctionTokenDefType - : (SymbolsMapTokens[buffer.toLowerCase() + "("] ?? exports.EnumToken.FunctionTokenDefType))); + : (SymbolsMapTokens[buffer.toLowerCase() + "("] ?? exports.EnumToken.FunctionTokenDefType); + result.push(yieldResult(buffer, parseInfo, hint)); buffer = ""; + if (hint === exports.EnumToken.UrlFunctionTokenDefType) { + value = peek(parseInfo); + // consume an + while (isWhiteSpace((charCode = value.charCodeAt(0)))) { + buffer += next(parseInfo); + value = peek(parseInfo); + charCode = value.charCodeAt(0); + if (value === "/" && match(parseInfo, "/*")) { + if (buffer.length > 0) { + result.push(yieldResult(buffer, parseInfo)); + buffer = ""; + } + buffer += next(parseInfo, 2); + while ((value = next(parseInfo))) { + if (value == "*") { + buffer += value; + if (match(parseInfo, "/")) { + result.push(yieldResult(buffer + next(parseInfo), parseInfo, exports.EnumToken.CommentTokenType)); + buffer = ""; + break; + } + } + else { + buffer += value; + } + } + if (buffer.length > 0) { + result.push(yieldResult(buffer, parseInfo, exports.EnumToken.BadCommentTokenType)); + buffer = ""; + } + value = peek(parseInfo); + charCode = value.charCodeAt(0); + } + } + if (buffer.length > 0) { + result.push(yieldResult(buffer, parseInfo, exports.EnumToken.WhitespaceTokenType)); + buffer = ""; + } + if (value === ")" || value === '"' || value === "'") { + break; + } + do { + buffer += next(parseInfo); + value = peek(parseInfo); + charCode = value.charCodeAt(0); + } while (value !== ")" && !isWhiteSpace(charCode) && !(value === '/' && match(parseInfo, "/*"))); + if (buffer.length > 0) { + result.push(yieldResult(buffer, parseInfo, peek(parseInfo) === "" ? exports.EnumToken.BadUrlTokenType : exports.EnumToken.UrlTokenTokenType)); + buffer = ""; + } + } break; } } @@ -27412,12 +27579,6 @@ function parseAtRuleContainerQueryList(stream, context, options = {}) { }; } -// export const mediaQueryConditionEnum: Set = new Set([ -// EnumToken.ParensTokenType, -// EnumToken.IdenTokenType, -// EnumToken.MediaQueryConditionTokenType, -// EnumToken.MediaQueryUnaryFeatureTokenType, -// ]); function matchAtRuleSyntax(atRule, stream, options) { const syntaxRules = getSyntaxRule(ValidationSyntaxGroupEnum.AtRules, "@" + atRule.nam); const syntax = syntaxRules?.getPreludeRules()?.slice?.(1); @@ -27443,27 +27604,6 @@ function matchAtRuleSyntax(atRule, stream, options) { return { success, errors }; } -function parseAtRulePage(context, stream, options, errors) { - const syntaxRules = getSyntaxRule(ValidationSyntaxGroupEnum.AtRules, "@page"); - const syntax = syntaxRules?.getPreludeRules?.()?.slice?.(1); - let validate = false; - for (const token of stream) { - if (token.typ !== exports.EnumToken.WhitespaceTokenType && token.typ !== exports.EnumToken.CommentTokenType) { - validate = true; - break; - } - } - if (!validate) { - return { - success: true, - errors, - }; - } - const result = matchAllSyntax(trimSyntaxArray(syntax), createValidationContext(stream), options); - errors.push(...result.errors); - return { success: result.success, errors }; -} - function parseAtRuleFontFeatureValues(stream, context, options = {}) { const syntaxRules = getSyntaxRule(ValidationSyntaxGroupEnum.AtRules, "@" + context.nam); const syntax = syntaxRules?.getPreludeRules()?.slice?.(1); @@ -29154,7 +29294,6 @@ vbbnkit;;;jmjhyg77 * @param options * @param parseAsBlock */ function parseAtRule(stream, context, options, errors, parseAsBlock = null) { - // const rules = getSyntaxRule(ValidationSyntaxGroupEnum.AtRules, "@" + (stream[0] as AtRuleToken).nam); let success = true; let atRuleName = stream[0].nam; if (atRuleName.startsWith("-")) { @@ -29414,6 +29553,9 @@ function parseAtRule(stream, context, options, errors, parseAsBlock = null) { if (!result.success) { errors.push(...result.errors); } + // else { + // parseUrlToken(stream); + // } const valid = blockAllowed === parseAsBlock && result.success; if (valid) { let start = 0; @@ -29466,7 +29608,7 @@ function parseAtRule(stream, context, options, errors, parseAsBlock = null) { } else { if (stream[0]?.typ == exports.EnumToken.UrlFunctionTokenType && - stream[0].chi.some((t) => t.typ == exports.EnumToken.StringTokenType)) { + stream[0].chi.some((t) => t.typ == exports.EnumToken.StringTokenType || t.typ == exports.EnumToken.UrlTokenTokenType)) { stream.splice(0, 1, ...stream[0].chi); } } @@ -29682,7 +29824,6 @@ function parseAtRule(stream, context, options, errors, parseAsBlock = null) { } case "page": { trimArray(stream); - parseAtRulePage(atRule, stream, options, errors); // @ts-expect-error return Object.defineProperties(Object.assign(atRule, { typ: success ? exports.EnumToken.AtRuleNodeType : exports.EnumToken.InvalidRuleNodeType, @@ -29837,6 +29978,12 @@ function parseAtRule(stream, context, options, errors, parseAsBlock = null) { } else { result = matchAtRuleSyntax(atRule, stream, options); + if (result.errors.length > 0) { + errors.push(...result.errors); + } + // else if (atRuleName === "document") { + // parseUrlToken(stream); + // } if (result.success) { let i = 0; const stack = []; diff --git a/dist/index.d.ts b/dist/index.d.ts index 03c3c87d..ec33c529 100644 --- a/dist/index.d.ts +++ b/dist/index.d.ts @@ -898,7 +898,7 @@ declare enum ModuleScopeEnumOptions { /** * Literal token */ -export declare interface LiteralToken extends BaseToken { +declare interface LiteralToken extends BaseToken { typ: EnumToken.LiteralTokenType; val: string; } @@ -906,7 +906,7 @@ export declare interface LiteralToken extends BaseToken { /** * Class selector token */ -export declare interface ClassSelectorToken extends BaseToken { +declare interface ClassSelectorToken extends BaseToken { typ: EnumToken.ClassSelectorTokenType; val: string; } @@ -914,7 +914,7 @@ export declare interface ClassSelectorToken extends BaseToken { /** * Invalid class selector token */ -export declare interface InvalidClassSelectorToken extends BaseToken { +declare interface InvalidClassSelectorToken extends BaseToken { typ: EnumToken.InvalidClassSelectorTokenType; val: string; } @@ -922,14 +922,14 @@ export declare interface InvalidClassSelectorToken extends BaseToken { /** * Universal selector token */ -export declare interface UniversalSelectorToken extends BaseToken { +declare interface UniversalSelectorToken extends BaseToken { typ: EnumToken.UniversalSelectorTokenType; } /** * Ident token */ -export declare interface IdentToken extends BaseToken { +declare interface IdentToken extends BaseToken { typ: EnumToken.IdenTokenType; val: string; } @@ -937,7 +937,7 @@ export declare interface IdentToken extends BaseToken { /** * Ident list token */ -export declare interface IdentListToken extends BaseToken { +declare interface IdentListToken extends BaseToken { typ: EnumToken.IdenListTokenType; val: string; } @@ -945,7 +945,7 @@ export declare interface IdentListToken extends BaseToken { /** * Dashed ident token */ -export declare interface DashedIdentToken extends BaseToken { +declare interface DashedIdentToken extends BaseToken { typ: EnumToken.DashedIdenTokenType; val: string; } @@ -953,35 +953,35 @@ export declare interface DashedIdentToken extends BaseToken { /** * Comma token */ -export declare interface CommaToken extends BaseToken { +declare interface CommaToken extends BaseToken { typ: EnumToken.CommaTokenType; } /** * Colon token */ -export declare interface ColonToken extends BaseToken { +declare interface ColonToken extends BaseToken { typ: EnumToken.ColonTokenType; } /** * Semicolon token */ -export declare interface SemiColonToken extends BaseToken { +declare interface SemiColonToken extends BaseToken { typ: EnumToken.SemiColonTokenType; } /** * Nesting selector token */ -export declare interface NestingSelectorToken extends BaseToken { +declare interface NestingSelectorToken extends BaseToken { typ: EnumToken.NestingSelectorTokenType; } /** * Number token */ -export declare interface NumberToken extends BaseToken { +declare interface NumberToken extends BaseToken { typ: EnumToken.NumberTokenType; sign?: "-" | "+"; val: number | FractionToken; @@ -990,7 +990,7 @@ export declare interface NumberToken extends BaseToken { /** * At rule token */ -export declare interface AtRuleToken extends BaseToken { +declare interface AtRuleToken extends BaseToken { typ: EnumToken.AtRuleTokenType; nam: string; val?: string; @@ -999,7 +999,7 @@ export declare interface AtRuleToken extends BaseToken { /** * Percentage token */ -export declare interface PercentageToken extends BaseToken { +declare interface PercentageToken extends BaseToken { typ: EnumToken.PercentageTokenType; val: number | FractionToken; } @@ -1007,7 +1007,7 @@ export declare interface PercentageToken extends BaseToken { /** * Flex token */ -export declare interface FlexToken extends BaseToken { +declare interface FlexToken extends BaseToken { typ: EnumToken.FlexTokenType; val: number | FractionToken; } @@ -1015,7 +1015,7 @@ export declare interface FlexToken extends BaseToken { /** * Function token */ -export declare interface FunctionToken extends BaseToken { +declare interface FunctionToken extends BaseToken { typ: | EnumToken.FunctionTokenType | EnumToken.UrlFunctionTokenType @@ -1034,7 +1034,7 @@ export declare interface FunctionToken extends BaseToken { /** * Grid template function token */ -export declare interface GridTemplateFuncToken extends BaseToken { +declare interface GridTemplateFuncToken extends BaseToken { typ: EnumToken.GridTemplateFuncTokenType; val: string; chi: Token$1[]; @@ -1043,7 +1043,7 @@ export declare interface GridTemplateFuncToken extends BaseToken { /** * Function URL token */ -export declare interface FunctionURLToken extends BaseToken { +declare interface FunctionURLToken extends BaseToken { typ: EnumToken.UrlFunctionTokenType; val: "url"; chi: Array; @@ -1052,7 +1052,7 @@ export declare interface FunctionURLToken extends BaseToken { /** * Function image token */ -export declare interface FunctionImageToken extends BaseToken { +declare interface FunctionImageToken extends BaseToken { typ: EnumToken.ImageFunctionTokenType; val: | "linear-gradient" @@ -1070,7 +1070,7 @@ export declare interface FunctionImageToken extends BaseToken { /** * Timing function token */ -export declare interface TimingFunctionToken extends BaseToken { +declare interface TimingFunctionToken extends BaseToken { typ: EnumToken.TimingFunctionTokenType; val: string; chi: Token$1[]; @@ -1079,7 +1079,7 @@ export declare interface TimingFunctionToken extends BaseToken { /** * Timeline function token */ -export declare interface TimelineFunctionToken extends BaseToken { +declare interface TimelineFunctionToken extends BaseToken { typ: EnumToken.TimelineFunctionTokenType; val: string; chi: Token$1[]; @@ -1088,7 +1088,7 @@ export declare interface TimelineFunctionToken extends BaseToken { /** * String token */ -export declare interface StringToken extends BaseToken { +declare interface StringToken extends BaseToken { typ: EnumToken.StringTokenType; val: string; } @@ -1096,7 +1096,7 @@ export declare interface StringToken extends BaseToken { /** * Bad string token */ -export declare interface BadStringToken extends BaseToken { +declare interface BadStringToken extends BaseToken { typ: EnumToken.BadStringTokenType; val: string; } @@ -1104,7 +1104,7 @@ export declare interface BadStringToken extends BaseToken { /** * Unclosed string token */ -export declare interface UnclosedStringToken extends BaseToken { +declare interface UnclosedStringToken extends BaseToken { typ: EnumToken.UnclosedStringTokenType; val: string; } @@ -1112,7 +1112,7 @@ export declare interface UnclosedStringToken extends BaseToken { /** * Dimension token */ -export declare interface DimensionToken extends BaseToken { +declare interface DimensionToken extends BaseToken { typ: EnumToken.DimensionTokenType; val: number | FractionToken; unit: string; @@ -1121,7 +1121,7 @@ export declare interface DimensionToken extends BaseToken { /** * Length token */ -export declare interface LengthToken extends BaseToken { +declare interface LengthToken extends BaseToken { typ: EnumToken.LengthTokenType; val: number | FractionToken; unit: string; @@ -1130,7 +1130,7 @@ export declare interface LengthToken extends BaseToken { /** * Angle token */ -export declare interface AngleToken extends BaseToken { +declare interface AngleToken extends BaseToken { typ: EnumToken.AngleTokenType; val: number | FractionToken; unit: string; @@ -1139,7 +1139,7 @@ export declare interface AngleToken extends BaseToken { /** * Time token */ -export declare interface TimeToken extends BaseToken { +declare interface TimeToken extends BaseToken { typ: EnumToken.TimeTokenType; val: number | FractionToken; unit: "ms" | "s"; @@ -1148,7 +1148,7 @@ export declare interface TimeToken extends BaseToken { /** * Frequency token */ -export declare interface FrequencyToken extends BaseToken { +declare interface FrequencyToken extends BaseToken { typ: EnumToken.FrequencyTokenType; val: number | FractionToken; unit: "Hz" | "Khz"; @@ -1157,7 +1157,7 @@ export declare interface FrequencyToken extends BaseToken { /** * Resolution token */ -export declare interface ResolutionToken extends BaseToken { +declare interface ResolutionToken extends BaseToken { typ: EnumToken.ResolutionTokenType; val: number | FractionToken; unit: "dpi" | "dpcm" | "dppx" | "x"; @@ -1166,7 +1166,7 @@ export declare interface ResolutionToken extends BaseToken { /** * Hash token */ -export declare interface HashToken extends BaseToken { +declare interface HashToken extends BaseToken { typ: EnumToken.HashTokenType; val: string; } @@ -1174,21 +1174,21 @@ export declare interface HashToken extends BaseToken { /** * Block start token */ -export declare interface BlockStartToken extends BaseToken { +declare interface BlockStartToken extends BaseToken { typ: EnumToken.BlockStartTokenType; } /** * Block end token */ -export declare interface BlockEndToken extends BaseToken { +declare interface BlockEndToken extends BaseToken { typ: EnumToken.BlockEndTokenType; } /** * Attribute start token */ -export declare interface AttrStartToken extends BaseToken { +declare interface AttrStartToken extends BaseToken { typ: EnumToken.AttrStartTokenType; chi?: Token$1[]; } @@ -1196,28 +1196,28 @@ export declare interface AttrStartToken extends BaseToken { /** * Attribute end token */ -export declare interface AttrEndToken extends BaseToken { +declare interface AttrEndToken extends BaseToken { typ: EnumToken.AttrEndTokenType; } /** * Parenthesis start token */ -export declare interface ParensStartToken extends BaseToken { +declare interface ParensStartToken extends BaseToken { typ: EnumToken.StartParensTokenType; } /** * Parenthesis end token */ -export declare interface ParensEndToken extends BaseToken { +declare interface ParensEndToken extends BaseToken { typ: EnumToken.EndParensTokenType; } /** * Parenthesis token */ -export declare interface ParensToken extends BaseToken { +declare interface ParensToken extends BaseToken { typ: EnumToken.ParensTokenType; chi: Token$1[]; } @@ -1225,7 +1225,7 @@ export declare interface ParensToken extends BaseToken { /** * Whitespace token */ -export declare interface WhitespaceToken extends BaseToken { +declare interface WhitespaceToken extends BaseToken { typ: EnumToken.WhitespaceTokenType; val?: string; } @@ -1233,7 +1233,7 @@ export declare interface WhitespaceToken extends BaseToken { /** * Comment token */ -export declare interface CommentToken extends BaseToken { +declare interface CommentToken extends BaseToken { typ: EnumToken.CommentTokenType; val: string; } @@ -1241,7 +1241,7 @@ export declare interface CommentToken extends BaseToken { /** * Bad comment token */ -export declare interface BadCommentToken extends BaseToken { +declare interface BadCommentToken extends BaseToken { typ: EnumToken.BadCommentTokenType; val: string; } @@ -1249,7 +1249,7 @@ export declare interface BadCommentToken extends BaseToken { /** * CDO comment token */ -export declare interface CDOCommentToken extends BaseToken { +declare interface CDOCommentToken extends BaseToken { typ: EnumToken.CDOCOMMTokenType; val: string; } @@ -1257,7 +1257,7 @@ export declare interface CDOCommentToken extends BaseToken { /** * Bad CDO comment token */ -export declare interface BadCDOCommentToken extends BaseToken { +declare interface BadCDOCommentToken extends BaseToken { typ: EnumToken.BadCdoTokenType; val: string; } @@ -1265,7 +1265,7 @@ export declare interface BadCDOCommentToken extends BaseToken { /** * Include match token */ -export declare interface IncludeMatchToken extends BaseToken { +declare interface IncludeMatchToken extends BaseToken { typ: EnumToken.IncludeMatchTokenType; // val: '~='; } @@ -1273,7 +1273,7 @@ export declare interface IncludeMatchToken extends BaseToken { /** * Dash match token */ -export declare interface DashMatchToken extends BaseToken { +declare interface DashMatchToken extends BaseToken { typ: EnumToken.DashMatchTokenType; // val: '|='; } @@ -1281,7 +1281,7 @@ export declare interface DashMatchToken extends BaseToken { /** * Equal match token */ -export declare interface EqualMatchToken extends BaseToken { +declare interface EqualMatchToken extends BaseToken { typ: EnumToken.EqualMatchTokenType; // val: '|='; } @@ -1289,7 +1289,7 @@ export declare interface EqualMatchToken extends BaseToken { /** * Start match token */ -export declare interface StartMatchToken extends BaseToken { +declare interface StartMatchToken extends BaseToken { typ: EnumToken.StartMatchTokenType; // val: '^='; } @@ -1297,7 +1297,7 @@ export declare interface StartMatchToken extends BaseToken { /** * End match token */ -export declare interface EndMatchToken extends BaseToken { +declare interface EndMatchToken extends BaseToken { typ: EnumToken.EndMatchTokenType; // val: '|='; } @@ -1305,7 +1305,7 @@ export declare interface EndMatchToken extends BaseToken { /** * Contain match token */ -export declare interface ContainMatchToken extends BaseToken { +declare interface ContainMatchToken extends BaseToken { typ: EnumToken.ContainMatchTokenType; // val: '|='; } @@ -1313,42 +1313,42 @@ export declare interface ContainMatchToken extends BaseToken { /** * Less than token */ -export declare interface LessThanToken extends BaseToken { +declare interface LessThanToken extends BaseToken { typ: EnumToken.LtTokenType; } /** * Less than or equal token */ -export declare interface LessThanOrEqualToken extends BaseToken { +declare interface LessThanOrEqualToken extends BaseToken { typ: EnumToken.LteTokenType; } /** * Greater than token */ -export declare interface GreaterThanToken extends BaseToken { +declare interface GreaterThanToken extends BaseToken { typ: EnumToken.GtTokenType; } /** * Greater than or equal token */ -export declare interface GreaterThanOrEqualToken extends BaseToken { +declare interface GreaterThanOrEqualToken extends BaseToken { typ: EnumToken.GteTokenType; } /** * Column combinator token */ -export declare interface ColumnCombinatorToken extends BaseToken { +declare interface ColumnCombinatorToken extends BaseToken { typ: EnumToken.ColumnCombinatorTokenType; } /** * Pseudo class token */ -export declare interface PseudoClassToken extends BaseToken { +declare interface PseudoClassToken extends BaseToken { typ: EnumToken.PseudoClassTokenType; val: string; } @@ -1356,7 +1356,7 @@ export declare interface PseudoClassToken extends BaseToken { /** * Pseudo element token */ -export declare interface PseudoElementToken extends BaseToken { +declare interface PseudoElementToken extends BaseToken { typ: EnumToken.PseudoElementTokenType; val: string; } @@ -1364,7 +1364,7 @@ export declare interface PseudoElementToken extends BaseToken { /** * Pseudo page token */ -export declare interface PseudoPageToken extends BaseToken { +declare interface PseudoPageToken extends BaseToken { typ: EnumToken.PseudoPageTokenType; val: string; } @@ -1372,7 +1372,7 @@ export declare interface PseudoPageToken extends BaseToken { /** * Pseudo class function token */ -export declare interface PseudoClassFunctionToken extends BaseToken { +declare interface PseudoClassFunctionToken extends BaseToken { typ: EnumToken.PseudoClassFuncTokenType; val: string; chi: Token$1[]; @@ -1381,14 +1381,14 @@ export declare interface PseudoClassFunctionToken extends BaseToken { /** * Delim token */ -export declare interface DelimToken extends BaseToken { +declare interface DelimToken extends BaseToken { typ: EnumToken.DelimTokenType; } /** * Bad URL token */ -export declare interface BadUrlToken extends BaseToken { +declare interface BadUrlToken extends BaseToken { typ: EnumToken.BadUrlTokenType; val: string; } @@ -1396,7 +1396,7 @@ export declare interface BadUrlToken extends BaseToken { /** * URL token */ -export declare interface UrlToken extends BaseToken { +declare interface UrlToken extends BaseToken { typ: EnumToken.UrlTokenTokenType; val: string; } @@ -1404,21 +1404,21 @@ export declare interface UrlToken extends BaseToken { /** * EOF token */ -export declare interface EOFToken extends BaseToken { +declare interface EOFToken extends BaseToken { typ: EnumToken.EOFTokenType; } /** * Important token */ -export declare interface ImportantToken extends BaseToken { +declare interface ImportantToken extends BaseToken { typ: EnumToken.ImportantTokenType; } /** * Color token */ -export declare interface ColorToken extends BaseToken { +declare interface ColorToken extends BaseToken { typ: EnumToken.ColorTokenType; val: string; kin: ColorType$1; @@ -1430,7 +1430,7 @@ export declare interface ColorToken extends BaseToken { /** * Attribute token */ -export declare interface AttrToken extends BaseToken { +declare interface AttrToken extends BaseToken { typ: EnumToken.AttrTokenType; chi: Token$1[]; } @@ -1438,7 +1438,7 @@ export declare interface AttrToken extends BaseToken { /** * Invalid attribute token */ -export declare interface InvalidAttrToken extends BaseToken { +declare interface InvalidAttrToken extends BaseToken { typ: EnumToken.InvalidAttrTokenType; chi: Token$1[]; } @@ -1446,14 +1446,14 @@ export declare interface InvalidAttrToken extends BaseToken { /** * Child combinator token */ -export declare interface ChildCombinatorToken extends BaseToken { +declare interface ChildCombinatorToken extends BaseToken { typ: EnumToken.ChildCombinatorTokenType; } /** * Media feature token */ -export declare interface MediaFeatureToken extends BaseToken { +declare interface MediaFeatureToken extends BaseToken { typ: EnumToken.MediaFeatureTokenType; val: string; } @@ -1461,7 +1461,7 @@ export declare interface MediaFeatureToken extends BaseToken { /** * Media feature not token */ -export declare interface NotToken extends BaseToken { +declare interface NotToken extends BaseToken { typ: EnumToken.NotTokenType; val: Token$1; } @@ -1469,7 +1469,7 @@ export declare interface NotToken extends BaseToken { /** * Media feature only token */ -export declare interface MediaFeatureOnlyToken extends BaseToken { +declare interface MediaFeatureOnlyToken extends BaseToken { typ: EnumToken.OnlyTokenType; val: Token$1; } @@ -1477,53 +1477,53 @@ export declare interface MediaFeatureOnlyToken extends BaseToken { /** * Media feature and token */ -export declare interface AndToken extends BaseToken { +declare interface AndToken extends BaseToken { typ: EnumToken.AndTokenType; } /** * Media feature or token */ -export declare interface OrToken extends BaseToken { +declare interface OrToken extends BaseToken { typ: EnumToken.OrTokenType; } /** * Media query condition token */ -export declare interface MediaQueryUnaryFeatureToken extends BaseToken { +declare interface MediaQueryUnaryFeatureToken extends BaseToken { typ: EnumToken.MediaQueryUnaryFeatureTokenType; l: Token$1; r: Token$1[]; } -export declare interface SupportsQueryUnaryConditionToken extends BaseToken { +declare interface SupportsQueryUnaryConditionToken extends BaseToken { typ: EnumToken.SupportsQueryUnaryConditionTokenType; l: Token$1; r: Token$1[]; } -export declare interface SupportsQueryConditionToken extends BaseToken { +declare interface SupportsQueryConditionToken extends BaseToken { typ: EnumToken.SupportsQueryConditionTokenType; op: AndToken | OrToken; l: Token$1[]; r: Token$1[]; } -export declare interface WhenElseQueryConditionToken extends BaseToken { +declare interface WhenElseQueryConditionToken extends BaseToken { typ: EnumToken.WhenElseQueryConditionTokenType; op: AndToken | OrToken; l: Token$1[]; r: Token$1[]; } -export declare interface WhenElseUnaryConditionToken extends BaseToken { +declare interface WhenElseUnaryConditionToken extends BaseToken { typ: EnumToken.WhenElseUnaryConditionTokenType; l: Token$1; r: Token$1[]; } -export declare interface MediaQueryConditionToken extends BaseToken { +declare interface MediaQueryConditionToken extends BaseToken { typ: EnumToken.MediaQueryConditionTokenType; l: Token$1[]; op: @@ -1538,26 +1538,26 @@ export declare interface MediaQueryConditionToken extends BaseToken { r: Token$1[]; } -export declare interface IfConditionToken extends BaseToken { +declare interface IfConditionToken extends BaseToken { typ: EnumToken.IfConditionTokenType; l: Token$1[]; r: Token$1[]; } -export declare interface IfElseConditionToken extends BaseToken { +declare interface IfElseConditionToken extends BaseToken { typ: EnumToken.IfElseConditionTokenType; l: IfConditionToken; r: IfConditionToken; } -export declare interface ContainerStyleRangeToken extends BaseToken { +declare interface ContainerStyleRangeToken extends BaseToken { typ: EnumToken.ContainerStyleRangeTokenType; l: Token$1[]; op: Token$1[]; r: Token$1[]; } -export declare interface MediaRangeQueryToken extends BaseToken { +declare interface MediaRangeQueryToken extends BaseToken { typ: EnumToken.MediaRangeQueryTokenType; l: Token$1[]; val: Token$1[]; @@ -1566,7 +1566,7 @@ export declare interface MediaRangeQueryToken extends BaseToken { r: Token$1[]; } -export declare interface InvalidMediaQueryToken extends BaseToken { +declare interface InvalidMediaQueryToken extends BaseToken { typ: EnumToken.InvalidMediaQueryTokenType; chi: Token$1[]; } @@ -1574,56 +1574,56 @@ export declare interface InvalidMediaQueryToken extends BaseToken { /** * Descendant combinator token */ -export declare interface DescendantCombinatorToken extends BaseToken { +declare interface DescendantCombinatorToken extends BaseToken { typ: EnumToken.DescendantCombinatorTokenType; } /** * Next sibling combinator token */ -export declare interface NextSiblingCombinatorToken extends BaseToken { +declare interface NextSiblingCombinatorToken extends BaseToken { typ: EnumToken.NextSiblingCombinatorTokenType; } /** * Subsequent sibling combinator token */ -export declare interface SubsequentCombinatorToken extends BaseToken { +declare interface SubsequentCombinatorToken extends BaseToken { typ: EnumToken.SubsequentSiblingCombinatorTokenType; } /** * Add token */ -export declare interface AddToken extends BaseToken { +declare interface AddToken extends BaseToken { typ: EnumToken.Add; } /** * Sub token */ -export declare interface SubToken extends BaseToken { +declare interface SubToken extends BaseToken { typ: EnumToken.Sub; } /** * Div token */ -export declare interface DivToken extends BaseToken { +declare interface DivToken extends BaseToken { typ: EnumToken.Div; } /** * Mul token */ -export declare interface MulToken extends BaseToken { +declare interface MulToken extends BaseToken { typ: EnumToken.Mul; } /** * Unary expression token */ -export declare interface UnaryExpression extends BaseToken { +declare interface UnaryExpression extends BaseToken { typ: EnumToken.UnaryExpressionTokenType; sign: EnumToken.Add | EnumToken.Sub; val: UnaryExpressionNode; @@ -1632,7 +1632,7 @@ export declare interface UnaryExpression extends BaseToken { /** * Fraction token */ -export declare interface FractionToken extends BaseToken { +declare interface FractionToken extends BaseToken { typ: EnumToken.FractionTokenType; l: NumberToken; r: NumberToken; @@ -1641,7 +1641,7 @@ export declare interface FractionToken extends BaseToken { /** * Binary expression token */ -export declare interface BinaryExpressionToken extends BaseToken { +declare interface BinaryExpressionToken extends BaseToken { typ: EnumToken.BinaryExpressionTokenType; op: EnumToken.Add | EnumToken.Sub | EnumToken.Div | EnumToken.Mul; l: BinaryExpressionNode | Token$1; @@ -1651,7 +1651,7 @@ export declare interface BinaryExpressionToken extends BaseToken { /** * Match expression token */ -export declare interface MatchExpressionToken extends BaseToken { +declare interface MatchExpressionToken extends BaseToken { typ: EnumToken.MatchExpressionTokenType; op: EqualMatchToken | DashMatchToken | StartMatchToken | ContainMatchToken | EndMatchToken | IncludeMatchToken; l: Token$1; @@ -1662,7 +1662,7 @@ export declare interface MatchExpressionToken extends BaseToken { /** * Name space attribute token */ -export declare interface NameSpaceAttributeToken extends BaseToken { +declare interface NameSpaceAttributeToken extends BaseToken { typ: EnumToken.NameSpaceAttributeTokenType; l?: Token$1; r: Token$1; @@ -1671,7 +1671,7 @@ export declare interface NameSpaceAttributeToken extends BaseToken { /** * List token */ -export declare interface ListToken extends BaseToken { +declare interface ListToken extends BaseToken { typ: EnumToken.ListToken; chi: Token$1[]; } @@ -1679,7 +1679,7 @@ export declare interface ListToken extends BaseToken { /** * Composes selector token */ -export declare interface ComposesSelectorToken extends BaseToken { +declare interface ComposesSelectorToken extends BaseToken { typ: EnumToken.ComposesSelectorTokenType; l: Token$1[]; r: Token$1 | null; @@ -1688,25 +1688,25 @@ export declare interface ComposesSelectorToken extends BaseToken { /** * Css variable token */ -export declare interface CssVariableToken$1 extends BaseToken { +declare interface CssVariableToken$1 extends BaseToken { typ: EnumToken.CssVariableTokenType; nam: string; val: Token$1[]; } -export declare interface CssVariableImportTokenType$1 extends BaseToken { +declare interface CssVariableImportTokenType$1 extends BaseToken { typ: EnumToken.CssVariableImportTokenType; nam: string; val: Token$1[]; } -export declare interface CssVariableMapTokenType extends BaseToken { +declare interface CssVariableMapTokenType extends BaseToken { typ: EnumToken.CssVariableDeclarationMapTokenType; vars: Token$1[]; from: Token$1[]; } -export declare interface FunctionDefToken extends BaseToken { +declare interface FunctionDefToken extends BaseToken { typ: | EnumToken.FunctionDefTokenType | EnumToken.UrlFunctionTokenDefType @@ -1722,7 +1722,7 @@ export declare interface FunctionDefToken extends BaseToken { val: string; } -export declare interface RawNodeToken extends BaseToken { +declare interface RawNodeToken extends BaseToken { typ: EnumToken.RawNodeTokenType; chi: Token$1[]; } @@ -1730,7 +1730,7 @@ export declare interface RawNodeToken extends BaseToken { /** * Unary expression node */ -export declare type UnaryExpressionNode = +declare type UnaryExpressionNode = | BinaryExpressionNode | NumberToken | DimensionToken @@ -1742,7 +1742,7 @@ export declare type UnaryExpressionNode = /** * Binary expression node */ -export declare type BinaryExpressionNode = +declare type BinaryExpressionNode = | NumberToken | DimensionToken | PercentageToken @@ -1758,7 +1758,7 @@ export declare type BinaryExpressionNode = /** * Token */ -export declare type Token$1 = +declare type Token$1 = | InvalidClassSelectorToken | InvalidAttrToken | LiteralToken @@ -1864,7 +1864,7 @@ export declare type Token$1 = /** * Position */ -export declare interface Position$1 { +declare interface Position$1 { /** * index in the source */ @@ -1882,7 +1882,7 @@ export declare interface Position$1 { /** * token or node location */ -export declare interface Location { +declare interface Location { /** * start position */ @@ -1897,7 +1897,7 @@ export declare interface Location { src: string; } -export declare interface BaseToken { +declare interface BaseToken { /** * token type */ @@ -1923,7 +1923,7 @@ export declare interface BaseToken { /** * comment node */ -export declare interface AstComment extends BaseToken { +declare interface AstComment extends BaseToken { typ: EnumToken.CommentNodeType | EnumToken.CDOCOMMNodeType; tokens?: null; val: string; @@ -1932,7 +1932,7 @@ export declare interface AstComment extends BaseToken { /** * declaration node */ -export declare interface AstDeclaration extends BaseToken { +declare interface AstDeclaration extends BaseToken { nam: string; tokens?: null; val: Token$1[]; @@ -1942,7 +1942,7 @@ export declare interface AstDeclaration extends BaseToken { /** * rule node */ -export declare interface AstRule extends BaseToken { +declare interface AstRule extends BaseToken { typ: EnumToken.RuleNodeType; sel: string; chi: Array< @@ -1955,7 +1955,7 @@ export declare interface AstRule extends BaseToken { /** * invalid rule node */ -export declare interface AstInvalidRule extends BaseToken { +declare interface AstInvalidRule extends BaseToken { typ: EnumToken.InvalidRuleNodeType; sel: string; chi: Array; @@ -1964,7 +1964,7 @@ export declare interface AstInvalidRule extends BaseToken { /** * invalid declaration node */ -export declare interface AstInvalidDeclaration extends BaseToken { +declare interface AstInvalidDeclaration extends BaseToken { typ: EnumToken.InvalidDeclarationNodeType; tokens?: null; val: Array; @@ -1973,7 +1973,7 @@ export declare interface AstInvalidDeclaration extends BaseToken { /** * invalid at rule node */ -export declare interface AstInvalidAtRule extends BaseToken { +declare interface AstInvalidAtRule extends BaseToken { typ: EnumToken.InvalidAtRuleNodeType; nam: string; val: string; @@ -1983,7 +1983,7 @@ export declare interface AstInvalidAtRule extends BaseToken { /** * keyframe rule node */ -export declare interface AstKeyFrameRule extends BaseToken { +declare interface AstKeyFrameRule extends BaseToken { typ: EnumToken.KeyFramesRuleNodeType; sel: string; chi: Array; @@ -1995,14 +1995,14 @@ export declare interface AstKeyFrameRule extends BaseToken { /** * raw selector tokens */ -export declare type RawSelectorTokens = string[][]; +declare type RawSelectorTokens = string[][]; /** * optimized selector * * @private */ -export declare interface OptimizedSelector { +declare interface OptimizedSelector { match: boolean; optimized: string[]; selector: string[][]; @@ -2014,7 +2014,7 @@ export declare interface OptimizedSelector { * * @private */ -export declare interface OptimizedSelectorToken { +declare interface OptimizedSelectorToken { match: boolean; optimized: Token$1[]; selector: Token$1[][]; @@ -2024,7 +2024,7 @@ export declare interface OptimizedSelectorToken { /** * at rule node */ -export declare interface AstAtRule extends BaseToken { +declare interface AstAtRule extends BaseToken { typ: EnumToken.AtRuleNodeType; nam: string; val: string; @@ -2034,7 +2034,7 @@ export declare interface AstAtRule extends BaseToken { /** * keyframe rule node */ -export declare interface AstKeyframesRule extends BaseToken { +declare interface AstKeyframesRule extends BaseToken { typ: EnumToken.KeyFramesRuleNodeType; sel: string; chi: Array; @@ -2045,7 +2045,7 @@ export declare interface AstKeyframesRule extends BaseToken { /** * keyframe at rule node */ -export declare interface AstKeyframesAtRule extends BaseToken { +declare interface AstKeyframesAtRule extends BaseToken { typ: EnumToken.KeyframesAtRuleNodeType; nam: string; val: string; @@ -2055,7 +2055,7 @@ export declare interface AstKeyframesAtRule extends BaseToken { /** * rule list node */ -export declare type AstRuleList = +declare type AstRuleList = | AstStyleSheet | AstAtRule | AstRule @@ -2066,7 +2066,7 @@ export declare type AstRuleList = /** * stylesheet node */ -export declare interface AstStyleSheet extends BaseToken { +declare interface AstStyleSheet extends BaseToken { typ: EnumToken.StyleSheetNodeType; chi: Array; tokens?: null; @@ -2075,7 +2075,7 @@ export declare interface AstStyleSheet extends BaseToken { /** * ast node */ -export declare type AstNode$1 = +declare type AstNode$1 = | AstStyleSheet | AstRuleList | AstComment @@ -2261,39 +2261,39 @@ declare function walkValues(values: Token$1[], root?: AstNode$1 | Token$1 | null type?: EnumToken | EnumToken[] | ((token: Token$1) => boolean); }, reverse?: boolean): Generator; -export declare type GenericVisitorResult = T | T[] | Promise | Promise | null | Promise; -export declare type GenericVisitorHandler = ( +declare type GenericVisitorResult = T | T[] | Promise | Promise | null | Promise; +declare type GenericVisitorHandler = ( node: T, parent?: AstNode | Token, root?: AstNode | Token, ) => GenericVisitorResult; -export declare type GenericVisitorAstNodeHandlerMap = +declare type GenericVisitorAstNodeHandlerMap = | Record> | GenericVisitorHandler | { type: WalkerEvent; handler: GenericVisitorHandler } | { type: WalkerEvent; handler: Record> }; -export declare type ValueVisitorHandler = GenericVisitorHandler; +declare type ValueVisitorHandler = GenericVisitorHandler; /** * Declaration visitor handler */ -export declare type DeclarationVisitorHandler = GenericVisitorHandler; +declare type DeclarationVisitorHandler = GenericVisitorHandler; /** * Rule visitor handler */ -export declare type RuleVisitorHandler = GenericVisitorHandler; +declare type RuleVisitorHandler = GenericVisitorHandler; /** * AtRule visitor handler */ -export declare type AtRuleVisitorHandler = GenericVisitorHandler; +declare type AtRuleVisitorHandler = GenericVisitorHandler; /** * node visitor callback map * */ -export declare interface VisitorNodeMap { +declare interface VisitorNodeMap { /** * at rule visitor * @@ -2567,7 +2567,7 @@ declare class SourceMap { toJSON(): SourceMapObject; } -export declare interface PropertyListOptions { +declare interface PropertyListOptions { removeDuplicateDeclarations?: boolean | string | string[]; computeShorthand?: boolean; @@ -2576,7 +2576,7 @@ export declare interface PropertyListOptions { /** * parse info */ -export declare interface ParseInfo$1 { +declare interface ParseInfo$1 { /** * source file or url @@ -2788,12 +2788,20 @@ interface ValidationDimensionToken extends ValidationToken$1 { } interface PropertyType { - shorthand: string; } -interface ShorthandPropertyType { +interface SinglePropertyType { + typ: keyof EnumToken; + val: string | number; +} + +interface SinglePropertyTypeMapping { + pattern?: string[][]; + mapping: Record; +} +interface ShorthandPropertyType { shorthand: string; map?: string; properties: string[]; @@ -2801,22 +2809,20 @@ interface ShorthandPropertyType { multiple: boolean; separator: { typ: keyof EnumToken; - val: string + val: string; }; valueSeparator?: { typ: keyof EnumToken; - val: string + val: string; }; keywords: string[]; } interface PropertySetType { - [key: string]: PropertyType | ShorthandPropertyType; } interface PropertyMapType { - default: string[]; types: string[]; keywords: string[]; @@ -2824,23 +2830,21 @@ interface PropertyMapType { multiple?: boolean; prefix?: { typ: keyof EnumToken; - val: string + val: string; }; previous?: string; separator?: { - typ: keyof EnumToken; }; constraints?: { [key: string]: { [key: string]: any; - } + }; }; - mapping?: Record + mapping?: Record; } interface ShorthandMapType { - shorthand: string; pattern: string; keywords: string[]; @@ -2848,10 +2852,10 @@ interface ShorthandMapType { mapping?: Record; multiple?: boolean; separator?: { typ: keyof EnumToken; val?: string }; - set?: Record + set?: Record; properties: { [property: string]: PropertyMapType; - } + }; } interface ShorthandProperties { @@ -2889,52 +2893,62 @@ interface ShorthandType { /** * @private */ -export declare interface PropertiesConfig { +declare interface PropertiesConfig { + /** + * shorthand property minification rules + */ properties: PropertiesConfigProperties; - map: Map$1; + /** + * shorthand property minification rules + */ + map: Map$1; + /** + * single property minification rules + */ + property: Record; } /** * @private */ interface Map$1 { - border: Border; - "border-color": BackgroundPositionClass; - "border-style": BackgroundPositionClass; - "border-width": BackgroundPositionClass; - outline: Outline; - "outline-color": BackgroundPositionClass; - "outline-style": BackgroundPositionClass; - "outline-width": BackgroundPositionClass; - font: Font; - "font-weight": BackgroundPositionClass; - "font-style": BackgroundPositionClass; - "font-size": BackgroundPositionClass; - "line-height": BackgroundPositionClass; - "font-stretch": BackgroundPositionClass; - "font-variant": BackgroundPositionClass; - "font-family": BackgroundPositionClass; - background: Background; - "background-repeat": BackgroundPositionClass; - "background-color": BackgroundPositionClass; - "background-image": BackgroundPositionClass; + border: Border; + "border-color": BackgroundPositionClass; + "border-style": BackgroundPositionClass; + "border-width": BackgroundPositionClass; + outline: Outline; + "outline-color": BackgroundPositionClass; + "outline-style": BackgroundPositionClass; + "outline-width": BackgroundPositionClass; + font: Font; + "font-weight": BackgroundPositionClass; + "font-style": BackgroundPositionClass; + "font-size": BackgroundPositionClass; + "line-height": BackgroundPositionClass; + "font-stretch": BackgroundPositionClass; + "font-variant": BackgroundPositionClass; + "font-family": BackgroundPositionClass; + background: Background; + "background-repeat": BackgroundPositionClass; + "background-color": BackgroundPositionClass; + "background-image": BackgroundPositionClass; "background-attachment": BackgroundPositionClass; - "background-clip": BackgroundPositionClass; - "background-origin": BackgroundPositionClass; - "background-position": BackgroundPositionClass; - "background-size": BackgroundPositionClass; + "background-clip": BackgroundPositionClass; + "background-origin": BackgroundPositionClass; + "background-position": BackgroundPositionClass; + "background-size": BackgroundPositionClass; } /** * @private */ interface Background { - shorthand: string; - pattern: string; - keywords: string[]; - default: any[]; - multiple: boolean; - separator: Separator; + shorthand: string; + pattern: string; + keywords: string[]; + default: any[]; + multiple: boolean; + separator: Separator; properties: BackgroundProperties; } @@ -2942,25 +2956,25 @@ interface Background { * @private */ interface BackgroundProperties { - "background-repeat": BackgroundRepeat; - "background-color": PurpleBackgroundAttachment; - "background-image": PurpleBackgroundAttachment; + "background-repeat": BackgroundRepeat; + "background-color": PurpleBackgroundAttachment; + "background-image": PurpleBackgroundAttachment; "background-attachment": PurpleBackgroundAttachment; - "background-clip": PurpleBackgroundAttachment; - "background-origin": PurpleBackgroundAttachment; - "background-position": BackgroundPosition; - "background-size": BackgroundSize; + "background-clip": PurpleBackgroundAttachment; + "background-origin": PurpleBackgroundAttachment; + "background-position": BackgroundPosition; + "background-size": BackgroundSize; } /** * @private */ interface PurpleBackgroundAttachment { - types: string[]; - default: string[]; - keywords: string[]; + types: string[]; + default: string[]; + keywords: string[]; required?: boolean; - mapping?: BackgroundAttachmentMapping; + mapping?: BackgroundAttachmentMapping; } /** @@ -2969,24 +2983,24 @@ interface PurpleBackgroundAttachment { interface BackgroundAttachmentMapping { "ultra-condensed": string; "extra-condensed": string; - condensed: string; - "semi-condensed": string; - normal: string; - "semi-expanded": string; - expanded: string; - "extra-expanded": string; - "ultra-expanded": string; + condensed: string; + "semi-condensed": string; + normal: string; + "semi-expanded": string; + expanded: string; + "extra-expanded": string; + "ultra-expanded": string; } /** * @private */ interface BackgroundPosition { - multiple: boolean; - types: string[]; - default: string[]; - keywords: string[]; - mapping: BackgroundPositionMapping; + multiple: boolean; + types: string[]; + default: string[]; + keywords: string[]; + mapping: BackgroundPositionMapping; constraints: BackgroundPositionConstraints; } @@ -3008,33 +3022,33 @@ interface ConstraintsMapping { * @private */ interface BackgroundPositionMapping { - left: string; - top: string; + left: string; + top: string; center: string; bottom: string; - right: string; + right: string; } /** * @private */ interface BackgroundRepeat { - types: any[]; - default: string[]; + types: any[]; + default: string[]; multiple: boolean; keywords: string[]; - mapping: BackgroundRepeatMapping; + mapping: BackgroundRepeatMapping; } /** * @private */ interface BackgroundRepeatMapping { - "repeat no-repeat": string; - "no-repeat repeat": string; - "repeat repeat": string; - "space space": string; - "round round": string; + "repeat no-repeat": string; + "no-repeat repeat": string; + "repeat repeat": string; + "space space": string; + "round round": string; "no-repeat no-repeat": string; } @@ -3044,11 +3058,11 @@ interface BackgroundRepeatMapping { interface BackgroundSize { multiple: boolean; previous: string; - prefix: Prefix; - types: string[]; - default: string[]; + prefix: Prefix; + types: string[]; + default: string[]; keywords: string[]; - mapping: BackgroundSizeMapping; + mapping: BackgroundSizeMapping; } /** @@ -3084,10 +3098,10 @@ interface BackgroundPositionClass { * @private */ interface Border { - shorthand: string; - pattern: string; - keywords: string[]; - default: string[]; + shorthand: string; + pattern: string; + keywords: string[]; + default: string[]; properties: BorderProperties; } @@ -3103,17 +3117,16 @@ interface BorderProperties { /** * @private */ -interface BorderColorClass { -} +interface BorderColorClass {} /** * @private */ interface Font { - shorthand: string; - pattern: string; - keywords: string[]; - default: any[]; + shorthand: string; + pattern: string; + keywords: string[]; + default: any[]; properties: FontProperties; } @@ -3121,24 +3134,24 @@ interface Font { * @private */ interface FontProperties { - "font-weight": FontWeight; - "font-style": PurpleBackgroundAttachment; - "font-size": PurpleBackgroundAttachment; - "line-height": LineHeight; + "font-weight": FontWeight; + "font-style": PurpleBackgroundAttachment; + "font-size": PurpleBackgroundAttachment; + "line-height": LineHeight; "font-stretch": PurpleBackgroundAttachment; "font-variant": PurpleBackgroundAttachment; - "font-family": FontFamily; + "font-family": FontFamily; } /** * @private */ interface FontFamily { - types: string[]; - default: any[]; - keywords: string[]; - required: boolean; - multiple: boolean; + types: string[]; + default: any[]; + keywords: string[]; + required: boolean; + multiple: boolean; separator: Separator; } @@ -3146,11 +3159,11 @@ interface FontFamily { * @private */ interface FontWeight { - types: string[]; - default: string[]; - keywords: string[]; + types: string[]; + default: string[]; + keywords: string[]; constraints: FontWeightConstraints; - mapping: FontWeightMapping; + mapping: FontWeightMapping; } /** @@ -3172,21 +3185,21 @@ interface Value { * @private */ interface FontWeightMapping { - thin: string; - hairline: string; + thin: string; + hairline: string; "extra light": string; "ultra light": string; - light: string; - normal: string; - regular: string; - medium: string; - "semi bold": string; - "demi bold": string; - bold: string; - "extra bold": string; - "ultra bold": string; - black: string; - heavy: string; + light: string; + normal: string; + regular: string; + medium: string; + "semi bold": string; + "demi bold": string; + bold: string; + "extra bold": string; + "ultra bold": string; + black: string; + heavy: string; "extra black": string; "ultra black": string; } @@ -3195,21 +3208,21 @@ interface FontWeightMapping { * @private */ interface LineHeight { - types: string[]; - default: string[]; + types: string[]; + default: string[]; keywords: string[]; previous: string; - prefix: Prefix; + prefix: Prefix; } /** * @private */ interface Outline { - shorthand: string; - pattern: string; - keywords: string[]; - default: string[]; + shorthand: string; + pattern: string; + keywords: string[]; + default: string[]; properties: OutlineProperties; } @@ -3226,70 +3239,70 @@ interface OutlineProperties { * @private */ interface PropertiesConfigProperties { - inset: BorderRadius; - top: BackgroundPositionClass; - right: BackgroundPositionClass; - bottom: BackgroundPositionClass; - left: BackgroundPositionClass; - margin: BorderRadius; - "margin-top": BackgroundPositionClass; - "margin-right": BackgroundPositionClass; - "margin-bottom": BackgroundPositionClass; - "margin-left": BackgroundPositionClass; - padding: BorderColor; - "padding-top": BackgroundPositionClass; - "padding-right": BackgroundPositionClass; - "padding-bottom": BackgroundPositionClass; - "padding-left": BackgroundPositionClass; - "border-radius": BorderRadius; - "border-top-left-radius": BackgroundPositionClass; - "border-top-right-radius": BackgroundPositionClass; + inset: BorderRadius; + top: BackgroundPositionClass; + right: BackgroundPositionClass; + bottom: BackgroundPositionClass; + left: BackgroundPositionClass; + margin: BorderRadius; + "margin-top": BackgroundPositionClass; + "margin-right": BackgroundPositionClass; + "margin-bottom": BackgroundPositionClass; + "margin-left": BackgroundPositionClass; + padding: BorderColor; + "padding-top": BackgroundPositionClass; + "padding-right": BackgroundPositionClass; + "padding-bottom": BackgroundPositionClass; + "padding-left": BackgroundPositionClass; + "border-radius": BorderRadius; + "border-top-left-radius": BackgroundPositionClass; + "border-top-right-radius": BackgroundPositionClass; "border-bottom-right-radius": BackgroundPositionClass; - "border-bottom-left-radius": BackgroundPositionClass; - "border-width": BorderColor; - "border-top-width": BackgroundPositionClass; - "border-right-width": BackgroundPositionClass; - "border-bottom-width": BackgroundPositionClass; - "border-left-width": BackgroundPositionClass; - "border-style": BorderColor; - "border-top-style": BackgroundPositionClass; - "border-right-style": BackgroundPositionClass; - "border-bottom-style": BackgroundPositionClass; - "border-left-style": BackgroundPositionClass; - "border-color": BorderColor; - "border-top-color": BackgroundPositionClass; - "border-right-color": BackgroundPositionClass; - "border-bottom-color": BackgroundPositionClass; - "border-left-color": BackgroundPositionClass; + "border-bottom-left-radius": BackgroundPositionClass; + "border-width": BorderColor; + "border-top-width": BackgroundPositionClass; + "border-right-width": BackgroundPositionClass; + "border-bottom-width": BackgroundPositionClass; + "border-left-width": BackgroundPositionClass; + "border-style": BorderColor; + "border-top-style": BackgroundPositionClass; + "border-right-style": BackgroundPositionClass; + "border-bottom-style": BackgroundPositionClass; + "border-left-style": BackgroundPositionClass; + "border-color": BorderColor; + "border-top-color": BackgroundPositionClass; + "border-right-color": BackgroundPositionClass; + "border-bottom-color": BackgroundPositionClass; + "border-left-color": BackgroundPositionClass; } /** * @private */ interface BorderColor { - shorthand: string; - map?: string; + shorthand: string; + map?: string; properties: string[]; - types: string[]; - keywords: string[]; + types: string[]; + keywords: string[]; } /** * @private */ interface BorderRadius { - shorthand: string; + shorthand: string; properties: string[]; - types: string[]; - multiple: boolean; - separator: null | string; - keywords: string[]; + types: string[]; + multiple: boolean; + separator: null | string; + keywords: string[]; } /** * node walker option */ -export declare type WalkerOption = WalkerOptionEnum | AstNode$1 | Token$1 | null; +declare type WalkerOption = WalkerOptionEnum | AstNode$1 | Token$1 | null; /** * returned value: * - {@link WalkerOptionEnum.Ignore}: ignore this node and its children @@ -3299,7 +3312,7 @@ export declare type WalkerOption = WalkerOptionEnum | AstNode$1 | Token$1 | null * - {@link AstNode}: * - {@link Token}: */ -export declare type WalkerFilter = (node: AstNode$1) => WalkerOption; +declare type WalkerFilter = (node: AstNode$1) => WalkerOption; /** * returned value: @@ -3310,21 +3323,21 @@ export declare type WalkerFilter = (node: AstNode$1) => WalkerOption; * - {@link AstNode}: * - {@link Token}: */ -export declare type WalkerValueFilter = ( +declare type WalkerValueFilter = ( node: AstNode$1 | Token$1, parent?: AstNode$1 | Token$1 | AstNode$1[] | Token$1[] | null, event?: WalkerEvent, parents?: Generator, ) => WalkerOption | null; -export declare interface WalkResult { +declare interface WalkResult { node: AstNode$1; parent?: AstRuleList; root?: AstNode$1; parents: Generator; } -export declare interface WalkAttributesResult { +declare interface WalkAttributesResult { value: Token$1; previousValue: Token$1 | null; nextValue: Token$1 | null; @@ -3334,99 +3347,99 @@ export declare interface WalkAttributesResult { } /** - * error description + * Error description */ -export declare interface ErrorDescription { +declare interface ErrorDescription { /** - * drop rule or declaration + * Drop rule or declaration */ action: "drop" | "ignore"; /** - * error message + * Error message */ message: string; /** - * syntax error description + * Syntax error description */ syntax?: string | ValidationToken$1 | null; /** - * error node + * Error node */ node?: Token$1 | AstNode$1 | null; /** - * error location + * Error location */ location?: Location; /** - * error object + * Error object */ error?: Error; /** - * raw tokens + * Raw tokens */ rawTokens?: TokenizeResult[]; } /** - * css validation options + * CSS validation options */ interface ValidationOptions { - /** * nested rule context + * @internal */ nestedRule?: boolean; /** - * enable css validation + * enable CSS validation * * see {@link ValidationLevel} */ validation?: boolean | ValidationLevel; /** - * lenient validation. retain nodes that failed validation + * Lenient validation. retain nodes that failed validation */ lenient?: boolean; /** - * visited tokens + * Visited tokens * * @private */ visited?: Map>; - + /** - * is optional + * Is optional * * @private */ isOptional?: boolean | null; /** - * is repeatable + * Is repeatable * * @private */ isRepeatable?: boolean | null; /** - * is list + * Is list * * @private */ isList?: boolean | null; /** - * occurence + * Occurence * * @private */ occurrence?: boolean | null; /** - * at least once + * At least once * * @private */ @@ -3434,23 +3447,23 @@ interface ValidationOptions { } /** - * minify options + * Minify options */ interface MinifyOptions { /** - * enable minification + * Enable minification */ minify?: boolean; /** - * parse color tokens + * Parse color tokens */ parseColor?: boolean; /** - * generate nested rules + * Generate nested rules */ nestingRules?: boolean; /** - * remove duplicate declarations from the same rule. if passed as a string array, duplicated declarations are removed, except for those in the array + * Remove duplicate declarations from the same rule. if passed as a string array, duplicated declarations are removed, except for those in the array * * * ```ts @@ -3482,61 +3495,59 @@ interface MinifyOptions { */ removeDuplicateDeclarations?: boolean | string | string[]; /** - * compute shorthand properties + * Compute shorthand properties */ computeShorthand?: boolean; /** - * compute transform functions - * see supported functions {@link transformFunctions} + * Compute css transform functions */ computeTransform?: boolean; /** - * compute math functions - * see supported functions {@link mathFuncs} + * Compute css math functions */ computeCalcExpression?: boolean; /** - * inline css variables + * Inline css variables */ inlineCssVariables?: boolean; /** - * remove empty ast nodes + * Remove empty ast nodes */ removeEmpty?: boolean; /** - * remove css prefix + * Remove css prefix */ removePrefix?: boolean; /** - * define minification passes. + * Define minification passes. */ pass?: number; } -export declare type LoadResult = +declare type LoadResult = | Promise> | ReadableStream | string | Promise; -export declare interface ModuleOptions { +declare interface ModuleOptions { /** - * use local scope vs global scope + * Use local scope vs global scope */ scoped?: boolean | ModuleScopeEnumOptions; /** - * module output file path. it is used to generate the scoped name. if not provided, [options.src](../docs/interfaces/node.ParserOptions.html#src) will be used + * Module output file path. it is used to generate the scoped name. if not provided, [options.src](../docs/interfaces/node.ParserOptions.html#src) will be used */ filePath?: string; /** - * generated scope hash length. the default is 5 + * Generated scope hash length. the default is 5 */ hashLength?: number; /** - * the pattern used to generate scoped names. the supported placeholders are: + * The pattern used to generate scoped names. the supported placeholders are: * - name: the file base name without the extension * - hash: the file path hash * - local: the local name @@ -3624,7 +3635,7 @@ export declare interface ModuleOptions { naming?: ModuleCaseTransformEnum; /** - * optional function to generate scoped name + * Function to generate scoped name * @param localName * @param filePath * @param pattern see {@link ModuleOptions.pattern} @@ -3639,44 +3650,44 @@ export declare interface ModuleOptions { } /** - * parser options + * Parser options */ -export declare interface ParserOptions +declare interface ParserOptions extends MinifyOptions, MinifyFeatureOptions, ValidationOptions, PropertyListOptions { /** - * source file to be used for sourcemap + * Source file to be used for sourcemap */ src?: string; /** - * include sourcemap in the ast. sourcemap info is always generated + * Include sourcemap in the ast. Sourcemap info is always generated */ sourcemap?: boolean | "inline"; /** - * remove at-rule charset + * Remove at-rule charset */ removeCharset?: boolean; /** - * resolve import + * Resolve import */ resolveImport?: boolean; /** - * current working directory + * Current working directory * * @internal */ cwd?: string; /** - * expand nested rules + * Expand nested rules */ expandNestingRules?: boolean; /** - * experimental, convert css if() function into legacy syntax. + * Experimental, convert css if() function into legacy syntax. */ expandIfSyntax?: boolean; /** - * url and file loader + * Url and file loader * @param url * @param currentDirectory * @param responseType @@ -3688,18 +3699,18 @@ export declare interface ParserOptions responseType?: boolean | ResponseType, ) => Promise>>; /** - * get directory name + * Get directory name * @param path * * @private */ dirname?: (path: string) => string; /** - * resolve urls + * Resolve urls */ resolveUrls?: boolean; /** - * url and path resolver + * Url and path resolver * @param url * @param currentUrl * @param currentWorkingDirectory @@ -3715,12 +3726,12 @@ export declare interface ParserOptions }; /** - * node visitor + * Node visitor * {@link VisitorNodeMap | VisitorNodeMap[]} */ visitor?: VisitorNodeMap | VisitorNodeMap[]; /** - * abort signal + * Abort signal * * Example: abort after 10 seconds * ```ts @@ -3733,38 +3744,38 @@ export declare interface ParserOptions */ signal?: AbortSignal; /** - * set parent node + * Set parent node * * @private */ setParent?: boolean; /** - * cache + * Cache * * @private */ cache?: WeakMap; /** - * css modules options + * CSS modules options */ module?: boolean | ModuleCaseTransformEnum | ModuleScopeEnumOptions | ModuleOptions; /** - * tokenizing info + * Tokenizing info * @private */ parseInfo?: ParseInfo; } /** - * minify feature options + * Minify feature options * * @internal */ -export declare interface MinifyFeatureOptions { +declare interface MinifyFeatureOptions { /** - * minify features + * Minify features * * @private */ @@ -3772,31 +3783,31 @@ export declare interface MinifyFeatureOptions { } /** - * minify feature + * Minify feature * * @internal */ -export declare interface MinifyFeature { +declare interface MinifyFeature { /** - * accepted tokens + * Accepted tokens */ accept?: Set; /** - * ordering + * Ordering */ ordering: number; /** - * process mode + * Process mode */ processMode: FeatureWalkMode; /** - * register feature + * Register feature * @param options */ register: (options: MinifyFeatureOptions | ParserOptions) => void; /** - * run feature + * Run feature * @param ast * @param options * @param parent @@ -3815,30 +3826,30 @@ export declare interface MinifyFeature { } /** - * resolved path + * Resolved path * @internal */ -export declare interface ResolvedPath { +declare interface ResolvedPath { /** - * absolute path + * Absolute path */ absolute: string; /** - * relative path + * Relative path */ relative: string; } /** - * ast node render options + * Ast node render options */ -export declare interface RenderOptions { +declare interface RenderOptions { /** - * minify css values. + * Minify css values. */ minify?: boolean; /** - * pretty print css + * Pretty print css * * ```ts * const result = await transform(css, {beautify: true}); @@ -3846,7 +3857,7 @@ export declare interface RenderOptions { */ beautify?: boolean; /** - * remove empty nodes. empty nodes are removed by default + * Remove empty nodes. Empty nodes are removed by default * * ```ts * @@ -3862,305 +3873,334 @@ export declare interface RenderOptions { */ removeEmpty?: boolean; /** - * expand nesting rules + * Expand nesting rules */ expandNestingRules?: boolean; /** - * preserve license comments. license comments are comments that start with /*! + * Preserve license comments. License comments are comments that start with '/*!' */ preserveLicense?: boolean; /** - * generate sourcemap object. 'inline' will embed it in the css + * Generate sourcemap object. 'inline' will embed it in the css */ sourcemap?: boolean | "inline"; /** - * indent string + * Indention string */ indent?: string; /** - * new line string + * New line string */ newLine?: string; /** - * remove comments + * Remove comments */ removeComments?: boolean; /** - * convert color to the specified color space. 'true' will convert to HEX + * Convert color to the specified color space. 'true' will convert to HEX */ convertColor?: boolean | ColorType; /** - * render the node along with its parents + * Render the node along with its parents */ withParents?: boolean; /** - * output file. used for url resolution + * Output file. Used for url resolution * @internal */ output?: string; /** - * current working directory + * Current working directory * @internal */ cwd?: string; /** - * resolve path + * Resolve path * @internal */ resolve?: (url: string, currentUrl: string, currentWorkingDirectory?: string) => ResolvedPath; } /** - * transform options + * Transform options */ -export declare interface TransformOptions extends ParserOptions, RenderOptions {} +declare interface TransformOptions extends ParserOptions, RenderOptions {} /** - * parse result stats object + * Parse result stats object */ -export declare interface ParseResultStats { +declare interface ParseResultStats { /** - * source file + * Source file */ src: string; /** - * bytes read + * Bytes read */ bytesIn: number; /** - * bytes read from imported files + * Bytes read from imported files */ importedBytesIn: number; /** - * tokenizing processing time + * Tokenizing processing time */ tokenize: string; /** - * parsing processing time + * Parsing processing time */ parse: string; /** - * minification processing time + * Minification processing time */ minify: string; /** - * module processing time + * Module processing time */ module?: string; /** - * total time + * Total time */ total: string; /** - * imported files stats + * Imported files stats */ imports: ParseResultStats[]; /** - * nodes count + * Nodes count */ nodesCount: number; /** - * tokens count + * Tokens count */ tokensCount: number; } /** - * parse result object + * Parse result object */ -export declare interface ParseResult { +declare interface ParseResult { /** - * parsed ast tree + * Parsed ast tree */ ast: AstStyleSheet; /** - * parse errors + * Parse errors */ errors: ErrorDescription[]; /** - * parse stats + * Parse stats */ stats: ParseResultStats; /** - * css module mapping + * CSS module mapping */ mapping?: Record; + /** + * CSS module variables + * @private + */ cssModuleVariables?: Record; + /** + * css module import mapping + * @private + */ importMapping?: Record>; /** - * css module reverse mapping + * CSS module reverse mapping * @private */ revMapping?: Record; } /** - * render result object + * Render result object */ -export declare interface RenderResult { +declare interface RenderResult { /** - * rendered css + * Rendered CSS */ code: string; /** - * render errors + * Render errors */ errors: ErrorDescription[]; /** - * render stats + * Render stats */ stats: { /** - * render time + * Render time */ total: string; }; /** - * source map + * Source map */ map?: SourceMap; } /** - * transform result object + * Transform result object */ -export declare interface TransformResult extends ParseResult, RenderResult { +declare interface TransformResult extends ParseResult, RenderResult { /** - * transform stats + * Transform stats */ stats: { /** - * source file + * Source file */ src: string; /** - * bytes read + * Bytes read */ bytesIn: number; /** - * generated css size + * Generated CSS size */ bytesOut: number; /** - * bytes read from imported files + * Bytes read from imported files */ importedBytesIn: number; /** - * parse time + * Parse time */ parse: string; /** - * minify time + * Minify time */ minify: string; /** - * render time + * Render time */ render: string; /** - * total time + * Total time */ total: string; /** - * imported files stats + * Imported files stats */ imports: ParseResultStats[]; }; } /** - * parse token options + * Parse token options */ -export declare interface ParseTokenOptions extends ParserOptions {} +declare interface ParseTokenOptions extends ParserOptions {} /** - * tokenize result object + * Tokenize result object * @internal */ -export declare interface TokenizeResult { +declare interface TokenizeResult { /** - * token + * Token */ token: Token$1; /** - * bytes in + * Bytes in */ bytesIn: number; } /** - * matched selector object + * Matched selector object * @internal */ -export declare interface MatchedSelector { +declare interface MatchedSelector { /** - * matched selector + * Matched selector */ match: string[][]; /** - * selector 1 + * Selector 1 */ selector1: string[][]; /** - * selector 2 + * Selector 2 */ selector2: string[][]; /** - * selectors partially match + * Selectors partially match */ eq: boolean; } /** - * variable scope info object + * Variable scope info object * @internal */ -export declare interface VariableScopeInfo { +declare interface VariableScopeInfo { /** - * global scope + * Global scope */ globalScope: boolean; /** - * parent nodes + * Parent nodes */ parent: Set; /** - * declaration count + * Declaration count */ declarationCount: number; /** - * replaceable + * Replaceable */ replaceable: boolean; /** - * declaration node + * Declaration node */ node: AstDeclaration; /** - * declaration values + * Declaration values */ values: Token$1[]; } /** - * source map object + * Source map object * @internal */ -export declare interface SourceMapObject { +declare interface SourceMapObject { + /** + * Source map version + */ version: number; + /** + * Source file + */ file?: string; + /** + * Source root + */ sourceRoot?: string; + /** + * Source files + */ sources?: string[]; + /** + * Source files content + */ sourcesContent?: Array; + /** + * Variable names + */ names?: string[]; + /** + * Mappings + */ mappings: string; } @@ -4202,7 +4242,7 @@ declare enum ResponseType$1 { ArrayBuffer = 2 } -export declare interface ValidationSyntaxNode { +declare interface ValidationSyntaxNode { syntax: string; ast?: ValidationToken[]; descriptors?: Record>; @@ -4212,14 +4252,14 @@ interface ValidationSelectorOptions extends ValidationOptions { nestedSelector?: boolean; } -export declare interface ValidationMediaFeature { +declare interface ValidationMediaFeature { type: MediaFeatureType; status?: string; category: string; values?: Array | Array; } -export declare type ValidationConfiguration = Record< +declare type ValidationConfiguration = Record< ValidationSyntaxGroupEnum, ValidationSyntaxNode | Record | Record >; @@ -4502,12 +4542,13 @@ declare function findLast(ast: AstNode$1, matcher: (node: AstNode$1) => boolean) /** * - * @param node he nod to clone - * @param cloneChildren deep clone - * @param cloneMap a map of existing children as keys and their clones as values + * clone an ast node or value + * @param node + * @param cloneChildren + * @param cloneMap * @returns */ -declare function cloneNode(node: AstNode$1, cloneChildren?: boolean, cloneMap?: Map | null): AstNode$1; +declare function cloneNode(node: AstNode$1 | Token$1, cloneChildren?: boolean, cloneMap?: Map | null): AstNode$1 | Token$1; /** * load file or url @@ -4693,4 +4734,4 @@ declare function transformFile(file: string, options?: TransformOptions, asStrea declare function transform(css: string | ReadableStream, options?: TransformOptions): Promise; export { ColorType$1 as ColorType, EnumToken, FeatureWalkMode, ModuleCaseTransformEnum, ModuleScopeEnumOptions, ResponseType$1 as ResponseType, SourceMap, ValidationLevel, WalkerEvent, WalkerOptionEnum, cloneNode, convertColor, dirname, expand, find, findAll, findByValue, findLast, isOkLabClose, load, minify, okLabDistance, parse, parseDeclarations, parseFile, parseString, render, renderToken, resolve, transform, transformFile, walk, walkValues }; -export type { AddToken, AndToken, AngleToken, AstAtRule, AstComment, AstDeclaration, AstInvalidAtRule, AstInvalidDeclaration, AstInvalidRule, AstKeyFrameRule, AstKeyframesAtRule, AstKeyframesRule, AstNode$1 as AstNode, AstRule, AstRuleList, AstStyleSheet, AstValueMatcher, AtRuleToken, AtRuleVisitorHandler, AttrEndToken, AttrStartToken, AttrToken, Background, BackgroundAttachmentMapping, BackgroundPosition, BackgroundPositionClass, BackgroundPositionConstraints, BackgroundPositionMapping, BackgroundProperties, BackgroundRepeat, BackgroundRepeatMapping, BackgroundSize, BackgroundSizeMapping, BadCDOCommentToken, BadCommentToken, BadStringToken, BadUrlToken, BaseToken, BinaryExpressionNode, BinaryExpressionToken, BlockEndToken, BlockStartToken, Border, BorderColor, BorderColorClass, BorderProperties, BorderRadius, CDOCommentToken, ChildCombinatorToken, ClassSelectorToken, ColonToken, ColorToken, ColumnCombinatorToken, CommaToken, CommentToken, ComposesSelectorToken, ConstraintsMapping, ContainMatchToken, ContainerStyleRangeToken, Context, CssVariableImportTokenType$1 as CssVariableImportTokenType, CssVariableMapTokenType, CssVariableToken$1 as CssVariableToken, DashMatchToken, DashedIdentToken, DeclarationVisitorHandler, DelimToken, DescendantCombinatorToken, DimensionToken, DivToken, EOFToken, EndMatchToken, EqualMatchToken, ErrorDescription, FlexToken, Font, FontFamily, FontProperties, FontWeight, FontWeightConstraints, FontWeightMapping, FractionToken, FrequencyToken, FunctionDefToken, FunctionImageToken, FunctionToken, FunctionURLToken, GenericVisitorAstNodeHandlerMap, GenericVisitorHandler, GenericVisitorResult, GreaterThanOrEqualToken, GreaterThanToken, GridTemplateFuncToken, HashToken, IdentListToken, IdentToken, IfConditionToken, IfElseConditionToken, ImportantToken, IncludeMatchToken, InvalidAttrToken, InvalidClassSelectorToken, InvalidMediaQueryToken, LengthToken, LessThanOrEqualToken, LessThanToken, LineHeight, ListToken, LiteralToken, LoadResult, Location, Map$1 as Map, MatchExpressionToken, MatchedSelector, MediaFeatureOnlyToken, MediaFeatureToken, MediaQueryConditionToken, MediaQueryUnaryFeatureToken, MediaRangeQueryToken, MinifyFeature, MinifyFeatureOptions, MinifyOptions, ModuleOptions, MulToken, NameSpaceAttributeToken, NestingSelectorToken, NextSiblingCombinatorToken, NotToken, NumberToken, OptimizedSelector, OptimizedSelectorToken, OrToken, Outline, OutlineProperties, ParensEndToken, ParensStartToken, ParensToken, ParseInfo$1 as ParseInfo, ParseResult, ParseResultStats, ParseTokenOptions, ParserOptions, PercentageToken, Position$1 as Position, Prefix, PropertiesConfig, PropertiesConfigProperties, PropertyListOptions, PropertyMapType, PropertySetType, PropertyType, PseudoClassFunctionToken, PseudoClassToken, PseudoElementToken, PseudoPageToken, PurpleBackgroundAttachment, RawNodeToken, RawSelectorTokens, RenderOptions, RenderResult, ResolutionToken, ResolvedPath, RuleVisitorHandler, SemiColonToken, Separator, ShorthandDef, ShorthandMapType, ShorthandProperties, ShorthandPropertyType, ShorthandType, SourceMapObject, StartMatchToken, StringToken, SubToken, SubsequentCombinatorToken, SupportsQueryConditionToken, SupportsQueryUnaryConditionToken, TimeToken, TimelineFunctionToken, TimingFunctionToken, Token$1 as Token, TokenSearchResult, TokenizeResult, TransformOptions, TransformResult, UnaryExpression, UnaryExpressionNode, UnclosedStringToken, UniversalSelectorToken, UrlToken, ValidationConfiguration, ValidationMediaFeature, ValidationOptions, ValidationResult, ValidationSelectorOptions, ValidationSyntaxNode, ValidationSyntaxResult, ValidationToken$1 as ValidationToken, Value, ValueVisitorHandler, VariableScopeInfo, VisitorNodeMap, WalkAttributesResult, WalkResult, WalkerFilter, WalkerOption, WalkerValueFilter, WhenElseQueryConditionToken, WhenElseUnaryConditionToken, WhitespaceToken }; +export type { AddToken, AndToken, AngleToken, AstAtRule, AstComment, AstDeclaration, AstInvalidAtRule, AstInvalidDeclaration, AstInvalidRule, AstKeyFrameRule, AstKeyframesAtRule, AstKeyframesRule, AstNode$1 as AstNode, AstRule, AstRuleList, AstStyleSheet, AstValueMatcher, AtRuleToken, AtRuleVisitorHandler, AttrEndToken, AttrStartToken, AttrToken, Background, BackgroundAttachmentMapping, BackgroundPosition, BackgroundPositionClass, BackgroundPositionConstraints, BackgroundPositionMapping, BackgroundProperties, BackgroundRepeat, BackgroundRepeatMapping, BackgroundSize, BackgroundSizeMapping, BadCDOCommentToken, BadCommentToken, BadStringToken, BadUrlToken, BaseToken, BinaryExpressionNode, BinaryExpressionToken, BlockEndToken, BlockStartToken, Border, BorderColor, BorderColorClass, BorderProperties, BorderRadius, CDOCommentToken, ChildCombinatorToken, ClassSelectorToken, ColonToken, ColorToken, ColumnCombinatorToken, CommaToken, CommentToken, ComposesSelectorToken, ConstraintsMapping, ContainMatchToken, ContainerStyleRangeToken, Context, CssVariableImportTokenType$1 as CssVariableImportTokenType, CssVariableMapTokenType, CssVariableToken$1 as CssVariableToken, DashMatchToken, DashedIdentToken, DeclarationVisitorHandler, DelimToken, DescendantCombinatorToken, DimensionToken, DivToken, EOFToken, EndMatchToken, EqualMatchToken, ErrorDescription, FlexToken, Font, FontFamily, FontProperties, FontWeight, FontWeightConstraints, FontWeightMapping, FractionToken, FrequencyToken, FunctionDefToken, FunctionImageToken, FunctionToken, FunctionURLToken, GenericVisitorAstNodeHandlerMap, GenericVisitorHandler, GenericVisitorResult, GreaterThanOrEqualToken, GreaterThanToken, GridTemplateFuncToken, HashToken, IdentListToken, IdentToken, IfConditionToken, IfElseConditionToken, ImportantToken, IncludeMatchToken, InvalidAttrToken, InvalidClassSelectorToken, InvalidMediaQueryToken, LengthToken, LessThanOrEqualToken, LessThanToken, LineHeight, ListToken, LiteralToken, LoadResult, Location, Map$1 as Map, MatchExpressionToken, MatchedSelector, MediaFeatureOnlyToken, MediaFeatureToken, MediaQueryConditionToken, MediaQueryUnaryFeatureToken, MediaRangeQueryToken, MinifyFeature, MinifyFeatureOptions, MinifyOptions, ModuleOptions, MulToken, NameSpaceAttributeToken, NestingSelectorToken, NextSiblingCombinatorToken, NotToken, NumberToken, OptimizedSelector, OptimizedSelectorToken, OrToken, Outline, OutlineProperties, ParensEndToken, ParensStartToken, ParensToken, ParseInfo$1 as ParseInfo, ParseResult, ParseResultStats, ParseTokenOptions, ParserOptions, PercentageToken, Position$1 as Position, Prefix, PropertiesConfig, PropertiesConfigProperties, PropertyListOptions, PropertyMapType, PropertySetType, PropertyType, PseudoClassFunctionToken, PseudoClassToken, PseudoElementToken, PseudoPageToken, PurpleBackgroundAttachment, RawNodeToken, RawSelectorTokens, RenderOptions, RenderResult, ResolutionToken, ResolvedPath, RuleVisitorHandler, SemiColonToken, Separator, ShorthandDef, ShorthandMapType, ShorthandProperties, ShorthandPropertyType, ShorthandType, SinglePropertyType, SinglePropertyTypeMapping, SourceMapObject, StartMatchToken, StringToken, SubToken, SubsequentCombinatorToken, SupportsQueryConditionToken, SupportsQueryUnaryConditionToken, TimeToken, TimelineFunctionToken, TimingFunctionToken, Token$1 as Token, TokenSearchResult, TokenizeResult, TransformOptions, TransformResult, UnaryExpression, UnaryExpressionNode, UnclosedStringToken, UniversalSelectorToken, UrlToken, ValidationConfiguration, ValidationMediaFeature, ValidationOptions, ValidationResult, ValidationSelectorOptions, ValidationSyntaxNode, ValidationSyntaxResult, ValidationToken$1 as ValidationToken, Value, ValueVisitorHandler, VariableScopeInfo, VisitorNodeMap, WalkAttributesResult, WalkResult, WalkerFilter, WalkerOption, WalkerValueFilter, WhenElseQueryConditionToken, WhenElseUnaryConditionToken, WhitespaceToken }; diff --git a/dist/lib/ast/clone.js b/dist/lib/ast/clone.js index bd2f74e5..6a66ae11 100644 --- a/dist/lib/ast/clone.js +++ b/dist/lib/ast/clone.js @@ -2,9 +2,10 @@ import { EnumToken } from './types.js'; /** * - * @param node he nod to clone - * @param cloneChildren deep clone - * @param cloneMap a map of existing children as keys and their clones as values + * clone an ast node or value + * @param node + * @param cloneChildren + * @param cloneMap * @returns */ function cloneNode(node, cloneChildren = false, cloneMap = null) { diff --git a/dist/lib/ast/features/if.js b/dist/lib/ast/features/if.js index 89431211..2d51908b 100644 --- a/dist/lib/ast/features/if.js +++ b/dist/lib/ast/features/if.js @@ -184,8 +184,7 @@ class ExpandIfFeature { } } run(declaration) { - const cache = new Set(); - const result = processNode(declaration, cache); + const result = processNode(declaration, new Set()); let i; for (const n of result) { for (const { node } of walk(n)) { diff --git a/dist/lib/parser/declaration/list.js b/dist/lib/parser/declaration/list.js index af4c052b..f608b652 100644 --- a/dist/lib/parser/declaration/list.js +++ b/dist/lib/parser/declaration/list.js @@ -42,7 +42,7 @@ class PropertyList { } let propertyName = declaration.nam; let shortHandType; - let shorthand; + let shorthand = null; if (propertyName in config.properties) { // @ts-ignore if ("map" in config.properties[propertyName]) { @@ -61,6 +61,11 @@ class PropertyList { // @ts-ignore shorthand = config.map[propertyName].shorthand; } + else if (propertyName in config.property) { + shortHandType = "single"; + // @ts-ignore + shorthand = config.property[propertyName]; + } // @ts-ignore if (shortHandType == "map") { // @ts-ignore @@ -86,11 +91,71 @@ class PropertyList { this.declarations.get(shorthand).add(declaration); } else { + if (shorthand != null) { + this.mapValues(declaration, shorthand); + } this.declarations.set(propertyName, declaration); } } return this; } + mapValues(declaration, mapping) { + let name; + let values = declaration.val; + if (mapping.pattern != null) { + // match pattern + for (const patterns of mapping.pattern) { + const set = new Set(values.filter((v) => v.typ !== EnumToken.CommentTokenType && v.typ !== EnumToken.WhitespaceTokenType)); + const val = []; + for (const pattern of patterns) { + switch (pattern) { + case "": + for (const v of set) { + if (v.typ === EnumToken.LengthTokenType || + (v.typ === EnumToken.NumberTokenType && v.val === 0)) { + val.push(v); + set.delete(v); + } + } + default: { + for (const v of set) { + if (v.typ === EnumToken.IdenTokenType) { + const value = v.val.toLowerCase(); + if (value === pattern || new RegExp(`(^|\|)${pattern}(\||$)`).test(value)) { + val.push(v); + set.delete(v); + } + } + } + } + } + } + if (set.size === 0) { + values = val.reduce((acc, curr) => { + if (acc.length > 0) { + acc.push({ typ: EnumToken.WhitespaceTokenType }); + } + acc.push(curr); + return acc; + }, []); + break; + } + } + } + for (const val of declaration.val) { + if (val.typ === EnumToken.IdenTokenType) { + name = val.val.toLowerCase(); + if (mapping.mapping[name] != null) { + // @ts-expect-error + Object.assign(val, mapping.mapping[name], { typ: EnumToken[mapping.mapping[name].typ] }); + } + } + } + if (values != declaration.val) { + declaration.val.length = 0; + declaration.val.push(...values); + } + } [Symbol.iterator]() { let iterator = this.declarations.values(); const iterators = []; diff --git a/dist/lib/parser/parse.js b/dist/lib/parser/parse.js index ffcf7177..9458764a 100644 --- a/dist/lib/parser/parse.js +++ b/dist/lib/parser/parse.js @@ -22,7 +22,6 @@ import { replaceToken, trimWhiteSpaceTokens } from './utils/token.js'; import { parseAtRuleContainerQueryList } from './utils/at-rule-container.js'; import { parseMediaqueryList } from './utils/at-rule-media.js'; import { matchAtRuleSyntax } from './utils/at-rule.js'; -import { parseAtRulePage } from './utils/at-rule-page.js'; import { parseAtRuleFontFeatureValues } from './utils/at-rule-font-feature-values.js'; import { matchGenericSyntax } from './utils/at-rule-generic.js'; import { memoize } from './utils/cache.js'; @@ -1596,7 +1595,6 @@ vbbnkit;;;jmjhyg77 * @param options * @param parseAsBlock */ function parseAtRule(stream, context, options, errors, parseAsBlock = null) { - // const rules = getSyntaxRule(ValidationSyntaxGroupEnum.AtRules, "@" + (stream[0] as AtRuleToken).nam); let success = true; let atRuleName = stream[0].nam; if (atRuleName.startsWith("-")) { @@ -1856,6 +1854,9 @@ function parseAtRule(stream, context, options, errors, parseAsBlock = null) { if (!result.success) { errors.push(...result.errors); } + // else { + // parseUrlToken(stream); + // } const valid = blockAllowed === parseAsBlock && result.success; if (valid) { let start = 0; @@ -1908,7 +1909,7 @@ function parseAtRule(stream, context, options, errors, parseAsBlock = null) { } else { if (stream[0]?.typ == EnumToken.UrlFunctionTokenType && - stream[0].chi.some((t) => t.typ == EnumToken.StringTokenType)) { + stream[0].chi.some((t) => t.typ == EnumToken.StringTokenType || t.typ == EnumToken.UrlTokenTokenType)) { stream.splice(0, 1, ...stream[0].chi); } } @@ -2124,7 +2125,6 @@ function parseAtRule(stream, context, options, errors, parseAsBlock = null) { } case "page": { trimArray(stream); - parseAtRulePage(atRule, stream, options, errors); // @ts-expect-error return Object.defineProperties(Object.assign(atRule, { typ: success ? EnumToken.AtRuleNodeType : EnumToken.InvalidRuleNodeType, @@ -2279,6 +2279,12 @@ function parseAtRule(stream, context, options, errors, parseAsBlock = null) { } else { result = matchAtRuleSyntax(atRule, stream, options); + if (result.errors.length > 0) { + errors.push(...result.errors); + } + // else if (atRuleName === "document") { + // parseUrlToken(stream); + // } if (result.success) { let i = 0; const stack = []; diff --git a/dist/lib/parser/tokenize.js b/dist/lib/parser/tokenize.js index d1911eef..69e64351 100644 --- a/dist/lib/parser/tokenize.js +++ b/dist/lib/parser/tokenize.js @@ -1,6 +1,6 @@ import { EnumToken, ColorType } from '../ast/types.js'; import { definedPropertySettings, wildCardFuncs, whenElseFunc, transformFunctions, mathFuncs, colorsFunc, timingFunc, supportFunc, generalEnclosedFunc, timelineFunc, imageFunc, gridTemplateFunc, urlFunc, containerFunc } from '../syntax/constants.js'; -import { isDigit, isPseudo, isIdent, isNumber, isWhiteSpace, isNewLine, isHexColor, isHash, isPercentage, parseDimension } from '../syntax/syntax.js'; +import { isDigit, isPseudo, isIdent, isWhiteSpace, isNumber, isNewLine, isHexColor, isHash, isPercentage, parseDimension } from '../syntax/syntax.js'; const SymbolsMapTokens = { "+": EnumToken.Plus, @@ -408,10 +408,62 @@ function tokenize(parseInfo, yieldEOFToken = true) { break; } else if (isIdent(buffer)) { - result.push(yieldResult(buffer, parseInfo, buffer.startsWith("--") + const hint = buffer.startsWith("--") ? EnumToken.CustomFunctionTokenDefType - : (SymbolsMapTokens[buffer.toLowerCase() + "("] ?? EnumToken.FunctionTokenDefType))); + : (SymbolsMapTokens[buffer.toLowerCase() + "("] ?? EnumToken.FunctionTokenDefType); + result.push(yieldResult(buffer, parseInfo, hint)); buffer = ""; + if (hint === EnumToken.UrlFunctionTokenDefType) { + value = peek(parseInfo); + // consume an + while (isWhiteSpace((charCode = value.charCodeAt(0)))) { + buffer += next(parseInfo); + value = peek(parseInfo); + charCode = value.charCodeAt(0); + if (value === "/" && match(parseInfo, "/*")) { + if (buffer.length > 0) { + result.push(yieldResult(buffer, parseInfo)); + buffer = ""; + } + buffer += next(parseInfo, 2); + while ((value = next(parseInfo))) { + if (value == "*") { + buffer += value; + if (match(parseInfo, "/")) { + result.push(yieldResult(buffer + next(parseInfo), parseInfo, EnumToken.CommentTokenType)); + buffer = ""; + break; + } + } + else { + buffer += value; + } + } + if (buffer.length > 0) { + result.push(yieldResult(buffer, parseInfo, EnumToken.BadCommentTokenType)); + buffer = ""; + } + value = peek(parseInfo); + charCode = value.charCodeAt(0); + } + } + if (buffer.length > 0) { + result.push(yieldResult(buffer, parseInfo, EnumToken.WhitespaceTokenType)); + buffer = ""; + } + if (value === ")" || value === '"' || value === "'") { + break; + } + do { + buffer += next(parseInfo); + value = peek(parseInfo); + charCode = value.charCodeAt(0); + } while (value !== ")" && !isWhiteSpace(charCode) && !(value === '/' && match(parseInfo, "/*"))); + if (buffer.length > 0) { + result.push(yieldResult(buffer, parseInfo, peek(parseInfo) === "" ? EnumToken.BadUrlTokenType : EnumToken.UrlTokenTokenType)); + buffer = ""; + } + } break; } } diff --git a/dist/lib/parser/utils/at-rule.js b/dist/lib/parser/utils/at-rule.js index 37d5a986..fdf1a023 100644 --- a/dist/lib/parser/utils/at-rule.js +++ b/dist/lib/parser/utils/at-rule.js @@ -3,12 +3,6 @@ import { ValidationSyntaxGroupEnum } from '../../validation/parser/typedef.js'; import { getSyntaxRule } from '../../validation/config.js'; import { trimArray, matchAllSyntax, createValidationContext } from '../../validation/match.js'; -// export const mediaQueryConditionEnum: Set = new Set([ -// EnumToken.ParensTokenType, -// EnumToken.IdenTokenType, -// EnumToken.MediaQueryConditionTokenType, -// EnumToken.MediaQueryUnaryFeatureTokenType, -// ]); function matchAtRuleSyntax(atRule, stream, options) { const syntaxRules = getSyntaxRule(ValidationSyntaxGroupEnum.AtRules, "@" + atRule.nam); const syntax = syntaxRules?.getPreludeRules()?.slice?.(1); diff --git a/dist/lib/parser/utils/declaration.js b/dist/lib/parser/utils/declaration.js index 5b95ade2..3c1b5ad3 100644 --- a/dist/lib/parser/utils/declaration.js +++ b/dist/lib/parser/utils/declaration.js @@ -518,6 +518,15 @@ function parseDeclaration(tokens, parent, options, errors) { if (value.typ === EnumToken.IdenTokenType && isColor(value)) { parseColor(value); } + // else if (value.typ === EnumToken.UrlFunctionTokenType) { + // const token = (value as FunctionToken).chi.find((t: Token) => t.typ === EnumToken.StringTokenType) as StringToken; + // if (token != null && urlTokenMatcher.test((token as StringToken).val)) { + // Object.assign(token, { + // typ: EnumToken.UrlTokenTokenType, + // val: (token as StringToken).val.slice(1, -1), + // }); + // } + // } } if (name.val === "grid" || name.val === "grid-template-areas" || diff --git a/files/about.md b/files/about.md index ac681cea..1ece8cad 100644 --- a/files/about.md +++ b/files/about.md @@ -6,7 +6,7 @@ category: Guides ## About -css‑parser is a fast, fault‑tolerant and dependency‑free CSS toolkit for Node.js & browsers. +Css‑Parser is a fast, fault‑tolerant and dependency‑free CSS toolkit for Node.js & browsers. It follows [CSS Syntax Module Level 3](https://www.w3.org/TR/css-syntax-3/) and validation using syntax rules from [MDN Data](https://github.com/mdn/data). According to [this benchmark](https://tbela99.github.io/css-parser/benchmark/index.html), it is one of the most diff --git a/files/assets/typedoc-custom.css b/files/assets/typedoc-custom.css new file mode 100644 index 00000000..b7727214 --- /dev/null +++ b/files/assets/typedoc-custom.css @@ -0,0 +1,5 @@ +.default { + .tsd-typography { + line-height: 1.45em; + } +} diff --git a/files/ast.md b/files/ast.md index ce501c85..84c790fe 100644 --- a/files/ast.md +++ b/files/ast.md @@ -6,8 +6,8 @@ category: Guides ## Ast node types -the ast root node returned by the parser is always a [AstStyleSheet](../docs/interfaces/node.AstStyleSheet.html) node. -the other node types +The ast root node returned by the parser is always a [AstStyleSheet](../docs/interfaces/node.AstStyleSheet.html) node. +The other node types are [AstRule](../docs/interfaces/node.AstRule.html), [AstAtRule](../docs/interfaces/node.AstAtRule.html), [AstDeclaration](../docs/interfaces/node.AstDeclaration.html), [AstComment](../docs/interfaces/node.AstComment.html), [AstInvalidRule](../docs/interfaces/node.AstInvalidRule.html), [AstInvalidAtRule](../docs/interfaces/node.AstInvalidAtRule.html), [AstInvalidDeclaration](../docs/interfaces/node.AstInvalidDeclaration.html) ## Ast node attributes @@ -16,8 +16,8 @@ are [AstRule](../docs/interfaces/node.AstRule.html), [AstAtRule](../docs/interfa [Ast rule](../docs/interfaces/node.AstRule.html) _tokens_ attribute is an array of [Token](../docs/types/node.Token.html) representing the parsed selector. -the _sel_ attribute string that contains the rule's selector. -modifying the sel attribute does not affect the tokens attribute, and similarly, changes to the tokens attribute do not +The _sel_ attribute string that contains the rule's selector. +Modifying the sel attribute does not affect the tokens attribute, and similarly, changes to the tokens attribute do not update the sel attribute. ```ts @@ -56,9 +56,9 @@ console.debug(result.code); [Ast at-rule](../docs/interfaces/node.AstAtRule.html) _tokens_ attribute is either null or an array of [Token](../docs/types/node.Token.html) representing the parsed prelude. -the _val_ attribute string that contains the at-rule's prelude. +The _val_ attribute string that contains the at-rule's prelude. -modifying the _val_ attribute does not affect the _tokens_ attribute, and similarly, changes to the _tokens_ attribute do not +Modifying the _val_ attribute does not affect the _tokens_ attribute, and similarly, changes to the _tokens_ attribute do not update the _val_ attribute. ```ts @@ -153,7 +153,7 @@ console.debug(result.code); ## Ast traversal -ast traversal is achieved using [walk()](../docs/functions/node.walk.html) +Ast traversal is achieved using [walk()](../docs/functions/node.walk.html) ```ts @@ -179,7 +179,7 @@ for (const {node, parent, root} of walk(ast)) { } ``` -ast traversal can be controlled using a [filter](../docs/media/node.walk.html#walk) function. the filter function returns a value of type [WalkerOption](../docs/types/node.WalkerOption.html). +Ast traversal can be controlled using a [filter](../docs/media/node.walk.html#walk) function. the filter function returns a value of type [WalkerOption](../docs/types/node.WalkerOption.html). if the filter function returns new nodes, those will also be visited. ```ts @@ -227,7 +227,7 @@ for (const {node} of walk(result.ast, filter)) { ### Ast node values traversal -the function [walkValues()](../docs/functions/node.walkValues.html) is used to walk the node attribute's tokens. +The function [walkValues()](../docs/functions/node.walkValues.html) is used to walk the node attribute's tokens. ```ts diff --git a/files/css-module.md b/files/css-module.md index e3761c50..d37ad29a 100644 --- a/files/css-module.md +++ b/files/css-module.md @@ -7,8 +7,8 @@ category: Guides # CSS Modules CSS module is a feature that allows you to use CSS classes in a way that is safe from conflicts with other classes in the same project. -to enable CSS module support, pass the `module` option to the parse() or transform() function. -for a detailed explanation of the module options, see the [module options](../docs/interfaces/node.ParserOptions.html#module) section. +To enable CSS module support, pass the `module` option to the parse() or transform() function. +For a detailed explanation of the module options, see the [module options](../docs/interfaces/node.ParserOptions.html#module) section. ```typescript @@ -22,11 +22,11 @@ transformFile(css, {module: boolean | ModuleCaseTransformEnum | ModuleScopeEnumO ## Scope -the `scoped` option is used to configure the scope of the generated class names. +The `scoped` option is used to configure the scope of the generated class names. ### Local scope -this is the default scope. +This is the default scope. ```typescript @@ -55,7 +55,7 @@ let result: TransformResult = await transform(css, { console.log(result.code); ``` -output +Output: ```css .className_vjnt1 { @@ -69,7 +69,7 @@ output ### Global scope -the class names are not scoped unless they are scoped using :local or :local() +The class names are not scoped unless they are scoped using :local or :local() ```typescript @@ -84,7 +84,7 @@ result = await transform(css, { console.log(result.code); ``` -output +Output: ```css .className { @@ -98,7 +98,7 @@ output ### ICSS scope -export css using ICSS format +Export CSS using ICSS format ```typescript result = await transform(css, { @@ -112,7 +112,7 @@ export css using ICSS format console.log(result.code); ``` -output +Output: ```css :export { @@ -130,7 +130,7 @@ output ### Pure scope -require to use at least one id or class in selectors. it will throw an error it there are no id or class name in the selector. +Require the use at least one id or class in selectors. It will throw an error it there are no id or class name in the selector. ```typescript @@ -145,7 +145,7 @@ require to use at least one id or class in selectors. it will throw an error it console.log(result.code); ``` -output +Output: ```css .className { @@ -159,7 +159,7 @@ output ### Shortest Scope -produce short scope names. +Produce short scope names. ```typescript @@ -174,7 +174,7 @@ result = await transform(css, { console.log(result.code); ``` -output +Output: ```css .a { @@ -188,7 +188,7 @@ output ### Mixing scopes -scopes can be mixed using the bitwise OR operator '|' +Scopes can be mixed using the bitwise OR operator '|' ```typescript @@ -205,7 +205,7 @@ console.log(result.code); ## Class composition -class composition is supported using the `composes` property. +Class composition is supported using the `composes` property. ```typescript @@ -234,7 +234,7 @@ console.log(result.mapping); ``` -generated css code +Generated css code: ```css .goal_r7bhp .bg-indigo_gy28g { @@ -244,7 +244,7 @@ generated css code color: #fff } ``` -generated class mapping +Generated class mapping: ```json @@ -256,7 +256,7 @@ generated class mapping } ``` -classes can be composed from other files as well as the global scope +Classes can be composed from other files as well as the global scope ```typescript @@ -285,11 +285,11 @@ const result = await transform(` ## Naming -the `naming` option is used to configure the case of the generated class names as well as the class mapping. +The `naming` option is used to configure the case of the generated class names as well as the class mapping. ### Ignore Case -no case transformation +No case transformation ```typescript @@ -320,7 +320,7 @@ console.log(result.code); ``` ### Camel case -use camel case for the mapping key names +Use camel case for the mapping key names ```typescript @@ -349,7 +349,7 @@ let result = await transform(css, { console.log(result.code); ``` -generated css +Generated css: ```css .class-name_agkqy { background: red; @@ -359,7 +359,7 @@ generated css background: blue } ``` -generated mapping +Generated mapping: ```ts console.log(result.mapping); @@ -373,7 +373,7 @@ console.log(result.mapping); ### Camel case only -use camel case key names and the scoped class names +Use camel case key names and the scoped class names. ```typescript @@ -402,7 +402,7 @@ let result = await transform(css, { console.log(result.code); ``` -generated css +Generated css: ```css .className_agkqy { @@ -413,7 +413,7 @@ generated css background: blue } ``` -generated mapping +Generated mapping: ```ts console.log(result.mapping); @@ -427,7 +427,7 @@ console.log(result.mapping); ### Dash case -use dash case for the mapping key names +Use dash case for the mapping key names ```typescript @@ -457,7 +457,7 @@ let result = await transform(css, { console.log(result.code); ``` -generated css +Generated css: ```css .className_vjnt1 { @@ -468,7 +468,7 @@ generated css background: blue } ``` -generated mapping +Generated mapping: ```ts console.log(result.mapping); @@ -482,7 +482,7 @@ console.log(result.mapping); ### Dash case only -use dash case key names and the scoped class names +Use dash case key names and the scoped class names. ```typescript @@ -512,7 +512,7 @@ let result = await transform(css, { console.log(result.code); ``` -generated css +Generated css: ```css .class-name_vjnt1 { @@ -523,7 +523,7 @@ generated css background: blue } ``` -generated mapping +Generated mapping: ```ts console.log(result.mapping); @@ -537,7 +537,7 @@ console.log(result.mapping); ## Pattern -the `pattern` option is used to configure the generated scoped names. +The `pattern` option is used to configure the generated scoped names. ```typescript @@ -567,7 +567,7 @@ let result: TransformResult = await transform(css, { console.log(result.code); ``` -generated css +Generated css: ```css .className-b629f { @@ -578,7 +578,7 @@ generated css background: blue } ``` -generated mapping +Generated mapping: ```ts console.log(result.mapping); @@ -589,7 +589,7 @@ console.log(result.mapping); "subClass": "subClass-a0c35 className-b629f" } ``` -the supported placeholders are: +The supported placeholders are: - name: the file base name without the extension - hash: the file path hash - local: the local name @@ -597,11 +597,11 @@ the supported placeholders are: - folder: the folder name - ext: the file extension -the pattern placeholders can optionally have a maximum number of characters: +The pattern placeholders can optionally have a maximum number of characters: ``` pattern: '[local:2]-[hash:5]' ``` -the hash pattern can take an algorithm, a maximum number of characters or both: +The hash pattern can take an algorithm, a maximum number of characters or both: ``` pattern: '[local]-[hash:base64:5]' ``` @@ -614,7 +614,7 @@ or pattern: '[local]-[hash:sha1]' ``` -supported hash algorithms are: +Supported hash algorithms are: - base64 - hex - base64url diff --git a/files/features.md b/files/features.md index a89c843e..787dbfd4 100644 --- a/files/features.md +++ b/files/features.md @@ -6,9 +6,9 @@ category: Guides ## Features -a non-exhaustive list of features is provided below: +A non-exhaustive list of features is provided below: -- no dependency +- No dependency - CSS validation based upon mdn-data - CSS modules support - CSS Media Queries Level 4 @@ -16,23 +16,23 @@ a non-exhaustive list of features is provided below: - CSS Color Module Level 5 - Media Queries Level 5 - CSS Conditional Rules Module Level 5 -- fault-tolerant parser implementing the CSS syntax module 3 recommendations. -- fast and efficient minification without unsafe transforms, - see [benchmark](https://tbela99.github.io/css-parser/benchmark/index.html) -- colors minification: color(), lab(), lch(), oklab(), oklch(), color-mix(), light-dark(), system colors and +- Fault-tolerant parser implementing the CSS syntax module 3 recommendations. +- Fast and efficient minification without unsafe transforms, + See [benchmark](https://tbela99.github.io/css-parser/benchmark/index.html) +- Colors minification: color(), lab(), lch(), oklab(), oklch(), color-mix(), light-dark(), system colors and relative color -- color conversion to any supported color format -- automatic nested css rules generation -- nested css rules conversion to legacy syntax -- experimental, convert css if() function into legacy syntax. -- sourcemap generation -- css shorthands computation. see the supported properties list below -- css transform functions minification -- css math functions evaluation: calc(), clamp(), min(), max(), etc. -- css variables inlining -- duplicate properties removal +- Color conversion to any supported color format +- Automatic nested css rules generation +- Nested css rules conversion to legacy syntax +- Experimental, convert css if() function into legacy syntax. +- Sourcemap generation +- CSS shorthands computation. see the supported properties list below +- CSS transform functions minification +- CSS math functions evaluation: calc(), clamp(), min(), max(), etc. +- CSS variables inlining +- Duplicate properties removal - @import rules flattening -- experimental CSS prefix removal +- Experimental CSS prefix removal ------ [← About](./about.md) | [Getting Started →](./install.md) \ No newline at end of file diff --git a/files/index.md b/files/index.md index 8a925703..36c2113c 100644 --- a/files/index.md +++ b/files/index.md @@ -7,6 +7,8 @@ children: - ./features.md - ./install.md - ./usage.md + - ./parsing.md + - ./rendering.md - ./css-module.md - ./minification.md - ./transform.md @@ -20,6 +22,8 @@ children: - [Features](./features.md) - [Installation](./install.md) - [Usage](./usage.md) +- [Parsing](./parsing.md) +- [Rendering](./rendering.md) - [CSS module](./css-module.md) - [Minification](./minification.md) - [Transform](./transform.md) diff --git a/files/install.md b/files/install.md index 7f69ad15..045779ab 100644 --- a/files/install.md +++ b/files/install.md @@ -6,20 +6,20 @@ category: Guides ## Installation -### From npm +### From NPM ```shell $ npm install @tbela99/css-parser ``` -### From jsr +### From JSR ```shell $ deno add @tbela99/css-parser ``` -### As web module +### As Web module -the library can be imported as a module in the browser +The library can be imported as a module in the browser. ```html ``` -### As umd module +### As UMD module -it can also be imported as an umd module +It can also be imported as an umd module ```html diff --git a/files/minification.md b/files/minification.md index 738298fc..5ec2b866 100644 --- a/files/minification.md +++ b/files/minification.md @@ -6,14 +6,14 @@ category: Guides ## Minification -the minification process is the default behavior. it applies to both the ast and the css output. -it can be disabled by setting `{minify:false}` in the options. +The minification process is enabled by default. The minification process is applied to the ast as well as the generated CSS code. +It can be disabled by setting `{minify:false}` in the options. -individual flags can be set to control specific minification features. +Flags are used to control specific minification features. ### Keyframes -keyframes rules are minified. +Keyframes rules are minified. ```ts @@ -41,7 +41,7 @@ console.debug(result.code); ``` -output +Output: ```css @keyframes slide-in { 0% { @@ -55,9 +55,9 @@ output ### CSS variables inlining -this feature is disabled by default. -it can be enabled using `{inlineCssVariables: true}`. -the CSS variables must be defined only once, and they must be defined in 'html' or ':root' selectors. +This feature is disabled by default. +It is enabled using `{inlineCssVariables: true}`. +The CSS variables must be defined only once, and they must be defined in 'html' or ':root' selectors. ```ts @@ -82,7 +82,7 @@ console.log(result.code); ``` -output +Output: ```css ._19_u :focus { color: hsl(from green calc((h*2)) s l) @@ -91,8 +91,8 @@ output ### Math functions -this feature is enabled by default. it can be disabled using `{computeCalcExpression: false}`. -[math functions](../variables/node.mathFuncs.html) such as `calc()` are evaluated when enabled using `{computeCalcExpression: true}`. +This feature is enabled by default. It is disabled using `{computeCalcExpression: false}`. +Math functions such as `calc()` are evaluated when enabled using `{computeCalcExpression: true}`. ```ts @@ -116,7 +116,7 @@ console.log(result.code); ``` -output +Output: ```css ._19_u :focus { @@ -126,8 +126,8 @@ output ### Color minification -CSS colors level 4&5 are fully supported. the library will convert between all supported color formats. -it can also compute relative colors and color-mix() functions. +CSS colors level 4&5 are fully supported. The library will convert between all supported color formats. +It can also compute relative colors and color-mix() functions. ```ts @@ -157,7 +157,7 @@ console.debug(result.code); ``` -output +Output: ```css .color1 { @@ -170,7 +170,7 @@ output } ``` -the color result color format can be specified using the `convertColor` option. +The color result color format can be specified using the `convertColor` option. ```ts @@ -201,7 +201,7 @@ console.debug(result.code); ``` -output +Output: ```css .color1 { @@ -216,7 +216,7 @@ output ### Transform functions -compute css transform functions and preserve the shortest possible value. this feature is enabled by default. it can be disabled using `{computeTransform: false}`. +Compute CSS transform functions and preserve the shortest possible value. This feature is enabled by default. It is disabled using `{computeTransform: false}`. ```ts @@ -238,14 +238,15 @@ console.log(result.code); ``` -output +Output: + ```css .now{transform:none}.now1{transform:scale(1.5,2)} ``` ### CSS values -dimension and numeric values are minified. +Dimension and numeric values are minified. ```ts @@ -263,7 +264,7 @@ console.log(result.code); ``` -output +Output: ```css .now{width:0} @@ -271,8 +272,8 @@ output ### Redundant declarations -by default, only the last declaration is preserved. -to preserve all declarations, pass the option `{removeDuplicateDeclarations: false}`. +By default, only the last declaration is preserved. +To preserve all declarations, pass the option `{removeDuplicateDeclarations: false}`. ```ts @@ -300,7 +301,7 @@ const result = await transform(css, { console.log(result.code); ``` -output +Output: ```css .table { @@ -311,7 +312,7 @@ output } ``` -to preserve only specific declarations, pass an array of declaration names to preserve +To preserve only specific declarations, pass an array of declaration names. ```ts @@ -339,7 +340,7 @@ const result = await transform(css, { console.log(result.code); ``` -output +Output: ```css .table { @@ -351,7 +352,7 @@ output ### Merging adjacent rules -adjacent rules with common declarations and at-rules with the same name and prelude are merged. +Adjacent rules with common declarations and at-rules with the same name and prelude are merged. ```ts @@ -394,7 +395,7 @@ console.debug(result.code); ``` -output +Output: ```css @media tv { @@ -414,8 +415,8 @@ output ### Conditional wrapping or unwrapping selectors using :is() -this feature is enabled by default. it can be disabled by turning off minification using `{minify: false}`. -it will attempt to wrap or unwrap rules using :is() and use the shortest possible selector. +This feature is enabled by default. It is disabled by turning off minification using `{minify: false}`. +It will attempt to wrap or unwrap rules using :is() and use the shortest possible selector. ```ts @@ -444,7 +445,8 @@ console.log(result.code); ``` -output +Output: + ```css .table { border-collapse: collapse; @@ -456,10 +458,10 @@ output } ``` -### CSS Nesting +### CSS nesting -this feature is enabled by default. it can be disabled using `{nestingRules: false}`. -when enabled, css rules are automatically nested. +Chis feature is enabled by default. it is disabled using `{nestingRules: false}`. +When enabled, css rules are automatically nested whenever possible. ```ts @@ -500,7 +502,8 @@ console.log(result.code); ``` -output +Output: + ```css .table { border-collapse: collapse; @@ -529,11 +532,11 @@ output ### UTF-8 escape sequence -utf-8 escape sequences are decoded and replaced by their corresponding characters. +UTF-8 escape sequences are decoded and replaced by their corresponding characters. ### Experimental CSS prefix removal -this feature is disabled by default. the prefixed versions of the css gradient functions are not supported. +This feature is disabled by default. The prefixed versions of the css gradient functions are not supported. ```ts @@ -658,7 +661,8 @@ const result = await transform(css, { console.log(result.code); ``` -output +Output: + ```css ::placeholder { color: grey @@ -728,7 +732,7 @@ output ### Shorthands -shorthand properties are computed and default values are removed. +Shorthand properties are computed and default values are removed. ```ts import {transform} from '@tbela99/css-parser'; @@ -754,7 +758,7 @@ console.log(result.code); ``` -output +Output: ```css .table { @@ -764,7 +768,7 @@ output #### Computed shorthands properties -list of computed shorthands properties: +List of computed shorthands properties: - [ ] ~all~ - [x] animation diff --git a/files/parsing.md b/files/parsing.md new file mode 100644 index 00000000..66c3c79b --- /dev/null +++ b/files/parsing.md @@ -0,0 +1,92 @@ +--- +title: Parsing +group: Documents +category: Guides +--- + +## Parsing CSS + +### Parsing + +Parsing will turn the input css into an AST (Abstract Syntax Tree). It is achieved using the functions `parse()` and `transform()` or by using the corresponding functions `parseFile()` and `transformFile()`. `parse()` and `parseFile()` will not produce any css. To the contrary, the `transform()` and `transformFile()` functions will parse and also produce the CSS code, which comes handing if you do not want an additional step to render the ast. + +```ts +import {parse, render} from '@tbela99/css-parser'; + +const css = `...`; + +const result = await parse(css); +console.debug(result.ast); +console.debug(result.stats); + +const rendered = render(result.ast); +console.debug(rendered.code); +console.debug(result.stats); +```` + +or + +```ts +import {transform} from '@tbela99/css-parser'; + +const css = `...`; + +const result = await transform(css); +console.debug(result.ast); +console.debug(result.code); +console.debug(result.stats); +```` + +### Parsing files + +The parseFile() and transformFile() functions can be used to parse files. +They both accept a file url or path as first argument. + +```ts +import {transformFile} from '@tbela99/css-parser'; + +const css = `https://docs.deno.com/styles.css`; + +let result = await transformFile(css); +console.debug(result.code); + +// load file as readable stream +result = await transformFile(css, true); +console.debug(result.code); +``` + +### Parsing from a Readable Stream + +The parse() and transform() functions accept a string or readable stream as first argument. + +```ts +import {parse} from '@tbela99/css-parser'; +import {Readable} from "node:stream"; + +// usage: node index.ts < styles.css or cat styles.css | node index.ts + +const readableStream = Readable.toWeb(process.stdin); +const result = await parse(readableStream, {beautify: true}); + +console.log(result.ast); +``` + +A response body object can also be passed to parseFile() or transformFile() functions + +```ts + +import {transformFile} from '@tbela99/css-parser'; + +const response = await fetch(`https://docs.deno.com/styles.css`); +const result = await transformFile(response.body); // or parse(response.body) +console.debug(result.code); + +``` + +### Parsing Options + +See [ParserOptions](../interfaces/node.ParserOptions.html) + +------ +[← Usage](../documents/Guide.Usage.html) | [Rendering →](../documents/Guide.Rendering.html) + diff --git a/files/rendering.md b/files/rendering.md new file mode 100644 index 00000000..2029e805 --- /dev/null +++ b/files/rendering.md @@ -0,0 +1,94 @@ +--- +title: Rendering +group: Documents +category: Guides +--- + +## Rendering CSS + +[Rendering options](../interfaces/node.RenderOptions.html) can be passed to both transform() and render() functions. + +#### Pretty printing +By default, CSS output is minified. That behavior can be changed by passing the option `{beautify:true}`. + +```ts + +const result = await transform(css, {beautify: true}); +// or render(ast, {beautify: true}) + +console.log(result.code); + +``` + +#### Preserving license comments + +By default all comments are removed from the output. They can be preserved by passing the `{removeComments:false}` option, + +If you only want to preserve license comments, and remove other comments, you can pass `{preserveLicense:true}` instead. + +```ts + +const css = `/*! + * Bootstrap v5.3.3 (https://getbootstrap.com/) + * Copyright 2011-2024 The Bootstrap Authors + * Licensed under MIT (https://github.com/twbs/bootstrap/blob/main/LICENSE) + */ +[data-bs-theme=dark] { + color-scheme: dark; + + ...`; + +const result = await transform(css, {preserveLicense: true}); +``` + +#### Converting colors + +Color conversion is controlled by the `convertColor` option. Colors are converted to the HEX format by default. +That behavior can be changed by passing the chosen color type to the convertColor option: + +- ColorType.HEX +- ColorType.RGB or ColorType.RGBA +- ColorType.HSL or ColorType.HSLA +- ColorType.HWB or ColorType.HWBA +- ColorType.CMYK or ColorType.DEVICE_CMYK +- ColorType.SRGB +- ColorType.SRGB_LINEAR +- ColorType.DISPLAY_P3 +- ColorType.PROPHOTO_RGB +- ColorType.A98_RGB +- ColorType.REC2020 +- ColorType.XYZ or ColorType.XYZ_D65 +- ColorType.XYZ_D50 +- ColorType.LAB +- ColorType.LCH +- ColorType.OKLAB +- ColorType.OKLCH + +```ts +import {transform, ColorType} from '@tbela99/css-parser'; + +const css = ` +.color-map { + +color: lab(from #123456 calc(l + 10) a b); +background-color: lab(from hsl(180 100% 50%) calc(l - 10) a b); +} +`; +const result = await transform(css, { + beautify: true, + convertColor: ColorType.RGB, + computeCalcExpression: true +}); + +console.log(result.code); + +// .color-map { +// color: rgb(45 74 111); +// background-color: rgb(0 226 226) +// } +``` +. + +------ +[← Parsing](../documents/Guide.Parsing.html) | [CSS Modules →](../documents/Guide.CSS_modules.html) + diff --git a/files/transform.md b/files/transform.md index 38f112b8..3dd659a1 100644 --- a/files/transform.md +++ b/files/transform.md @@ -6,11 +6,11 @@ category: Guides ## Custom transform -visitors are used to alter the ast tree produced by the parser. for more information about the visitor object see the [typescript definition](../docs/interfaces/node.VisitorNodeMap.html) +Visitors are used to transform the ast tree produced by the parser. For more information about the visitor object see the [typescript definition](../docs/interfaces/node.VisitorNodeMap.html) -## Visitors order +## Visitors execution order -visitors can be called when the node is entered, visited or left. +Visitors can be called when the node is entered, visited or left. ```ts @@ -126,7 +126,7 @@ console.debug(result.code); ``` -## At rule visitor +## At-rule visitor Example: change media at-rule prelude @@ -304,11 +304,11 @@ console.debug(await transform(css, options)); ### KeyframesRule visitor -keyframes rule visitor is called on each keyframes rule node. +Keyframes rule visitor is called on each keyframes rule node. ### KeyframesAtRule visitor -the keyframes at-rule visitor is called on each keyframes at-rule node. the visitor can be a function or an object with a property named after the keyframes at-rule prelude. +The keyframes at-rule visitor is called on each keyframes at-rule node. The visitor can be a function or an object with a property named after the keyframes at-rule prelude. ```ts @@ -359,7 +359,7 @@ const result = await transform(css, { ### Value visitor -the value visitor is called on each token of the selector node, declaration value and the at-rule prelude, etc. +The value visitor is called on each token of the selector node, declaration value and the at-rule prelude, etc. ```ts @@ -378,7 +378,7 @@ const options: ParserOptions = { ``` ### Generic visitor -generic token visitor is a function whose name is a keyof [EnumToken](../docs/enums/node.EnumToken.html). it is called for every token of the specified type. +Generic token visitor is a function whose name is a keyof [EnumToken](../docs/enums/node.EnumToken.html). it is called for every token of the specified type. ```ts @@ -424,7 +424,7 @@ console.debug(await transform(css, options)); ### Example of visitor that inlines images -a visitor that inlines all images under a specific size +A visitor that inlines all images under a specific size ```ts import { diff --git a/files/usage.md b/files/usage.md index bea2df21..7649827a 100644 --- a/files/usage.md +++ b/files/usage.md @@ -5,6 +5,7 @@ category: Guides --- ## Usage + ### From node, bun or deno ```ts @@ -30,17 +31,17 @@ const result = await transform(css, { console.debug(result.code); ``` -the library exposes three entry points +The library exposes three entry points: - `@tbela99/css-parser` or `@tbela99/css-parser/node` which relies on node fs and fs/promises to read files - `@tbela99/css-parser/cjs` same as the previous except it is exported as a commonjs module - `@tbela99/css-parser/web` which relies on the web fetch api to read files -the default file loader can be overridden via the options [ParseOptions.load](../interfaces/node.ParserOptions.html#load) or [TransformOptions.load](../interfaces/node.TransformOptions.html#load) of parse() and transform() functions +The default file loader can be overridden via the options [ParseOptions.load](../interfaces/node.ParserOptions.html#load) or [TransformOptions.load](../interfaces/node.TransformOptions.html#load) of parse() and transform() functions ### From the web browser -load as javascript module +Load as javascript module ```html ``` -load as an umd module +Load as an UMD module ```html @@ -108,167 +109,6 @@ load as an umd module ``` -### Parsing - -parsing is achieved using the parse() or transform() or the corresponding parseFile() and transformFile() functions. the transform() function will also provide the css code as a result which comes handing if you do not want an additional step of rendering the ast. - -```ts -import {parse, render} from '@tbela99/css-parser'; - -const css = `...`; - -const result = await parse(css); -console.debug(result.ast); -console.debug(result.stats); - -const rendered = render(result.ast); -console.debug(rendered.code); -console.debug(result.stats); -```` - -or - -```ts -import {transform} from '@tbela99/css-parser'; - -const css = `...`; - -const result = await transform(css); -console.debug(result.ast); -console.debug(result.code); -console.debug(result.stats); -```` - -### Parsing files - -the parseFile() and transformFile() functions can be used to parse files. -they both accept a file url or path as first argument. - -```ts -import {transformFile} from '@tbela99/css-parser'; - -const css = `https://docs.deno.com/styles.css`; - -let result = await transformFile(css); -console.debug(result.code); - -// load file as readable stream -result = await transformFile(css, true); -console.debug(result.code); -``` - -### Parsing from a Readable Stream - -the parse() and transform() functions accept a string or readable stream as first argument. - -```ts -import {parse} from '@tbela99/css-parser'; -import {Readable} from "node:stream"; - -// usage: node index.ts < styles.css or cat styles.css | node index.ts - -const readableStream = Readable.toWeb(process.stdin); -const result = await parse(readableStream, {beautify: true}); - -console.log(result.ast); -``` - -a response body object can also be passed to parseFile() or transformFile() functions - -```ts - -import {transformFile} from '@tbela99/css-parser'; - -const response = await fetch(`https://docs.deno.com/styles.css`); -const result = await transformFile(response.body); // or parse(response.body) -console.debug(result.code); - -``` -### Rendering css - -[rendering options](../interfaces/node.RenderOptions.html) can be passed to both transform() and render() functions. - -#### Pretty printing -by default css output is minified. that behavior can be changed by passing the `{beautify:true}` option. - -```ts - -const result = await transform(css, {beautify: true}); -// or render(ast, {beautify: true}) - -console.log(result.code); - -``` - -#### Preserving license comments - -by default all comments are removed. they can be preserved by passing the `{removeComments:false}` option, - -if you only want to preserve license comments, and remove other comments, you can pass `{preserveLicense:true}` instead. - -```ts - -const css = `/*! - * Bootstrap v5.3.3 (https://getbootstrap.com/) - * Copyright 2011-2024 The Bootstrap Authors - * Licensed under MIT (https://github.com/twbs/bootstrap/blob/main/LICENSE) - */ -[data-bs-theme=dark] { - color-scheme: dark; - - ...`; - -const result = await transform(css, {preserveLicense: true}); -``` - -#### Converting colors - -color conversion is controlled by the `convertColor` option. colors are converted to the HEX format by default. -that behavior can be changed by passing the chosen color type to the convertColor option: - -- ColorType.HEX -- ColorType.RGB or ColorType.RGBA -- ColorType.HSL or ColorType.HSLA -- ColorType.HWB or ColorType.HWBA -- ColorType.CMYK or ColorType.DEVICE_CMYK -- ColorType.SRGB -- ColorType.SRGB_LINEAR -- ColorType.DISPLAY_P3 -- ColorType.PROPHOTO_RGB -- ColorType.A98_RGB -- ColorType.REC2020 -- ColorType.XYZ or ColorType.XYZ_D65 -- ColorType.XYZ_D50 -- ColorType.LAB -- ColorType.LCH -- ColorType.OKLAB -- ColorType.OKLCH - -```ts -import {transform, ColorType} from '@tbela99/css-parser'; - -const css = ` -.color-map { - -color: lab(from #123456 calc(l + 10) a b); -background-color: lab(from hsl(180 100% 50%) calc(l - 10) a b); -} -`; -const result = await transform(css, { - beautify: true, - convertColor: ColorType.RGB, - computeCalcExpression: true -}); - -console.log(result.code); - -// .color-map { -// color: rgb(45 74 111); -// background-color: rgb(0 226 226) -// } -``` -. - ------ -[← Getting started](../documents/Guide.Getting_started.html) | [CSS Modules →](../documents/Guide.CSS_modules.html) +[← Getting started](../documents/Guide.Getting_started.html) | [Parsing →](../documents/Guide.Parsing.html) diff --git a/files/validation.md b/files/validation.md index e2828b2f..2842e900 100644 --- a/files/validation.md +++ b/files/validation.md @@ -6,8 +6,8 @@ category: Guides ## Validation -validation is performed using [mdn-data](https://github.com/mdn/data). the validation level can be configured using the [validation](../docs/interfaces/node.ParserOptions.html#validation) option. -possible values are _boolean_ or [ValidationLevel](../docs/enums/node.ValidationLevel.html): +Validation is performed using [mdn-data](https://github.com/mdn/data). The validation level can be configured using the [validation](../docs/interfaces/node.ParserOptions.html#validation) option. +Possible values are _boolean_ or [ValidationLevel](../docs/enums/node.ValidationLevel.html): - _true_ or [ValidationLevel.All](../docs/media/node.ValidationLevel.html#all): validates all nodes - _false_ or [ValidationLevel.None](../docs/media/node.ValidationLevel.html#none): no validation @@ -53,13 +53,13 @@ console.debug(result.code); ## Lenient validation -the parser is lenient. this means that invalid nodes are kept in the ast but they are not rendered. -this behavior can be changed using the [lenient](../docs/interfaces/node.ParserOptions.html#lenient) option. +The parser is lenient. This means that invalid nodes are kept in the ast but they are not rendered. +This behavior can be changed using the [lenient](../docs/interfaces/node.ParserOptions.html#lenient) option. ## Validation errors -validation errors are returned with [parse result](../docs/interfaces/node.ParseResult.html) or [transform result](../docs/interfaces/node.TransformResult.html). -check the [typescript definition](../docs/interfaces/node.ErrorDescription.html) of ErrorDescription for more details. +Validation errors are returned with [parse result](../docs/interfaces/node.ParseResult.html) or [transform result](../docs/interfaces/node.TransformResult.html). +Check the [typescript definition](../docs/interfaces/node.ErrorDescription.html) of ErrorDescription for more details. ```ts @@ -69,7 +69,7 @@ console.debug(result.errors); ## Invalid tokens handling -[bad tokens](../docs/enums/node.EnumToken.html#badcdotokentype) are thrown out during parsing. visitor functions can be used to catch and fix invalid tokens. +[Bad tokens](../docs/enums/node.EnumToken.html#badcdotokentype) are thrown out during parsing. visitor functions can be used to catch and fix invalid tokens. ```ts diff --git a/package.json b/package.json index 85d17808..8b3938d0 100644 --- a/package.json +++ b/package.json @@ -24,6 +24,7 @@ "test:cov": "c8 -x 'test/specs/**/*.js' --reporter=html --reporter=text --reporter=json-summary mocha --reporter-options='maxDiffSize=1801920' --timeout=10000 \"test/**/node.spec.js\"", "test:web-cov": "web-test-runner -x 'test/specs/**/*.js' \"test/**/web.spec.js\" --node-resolve --playwright --browsers chromium firefox webkit --root-dir=. --coverage", "profile": "node --enable-source-maps --inspect-brk test/inspect.js", + "config-update": "esno tools/shorthand.ts", "syntax-update": "esno tools/validation.ts", "debug": "web-test-runner \"./test/**/web.spec.js\" --manual --open --node-resolve --root-dir=." }, diff --git a/src/@types/config.d.ts b/src/@types/config.d.ts index ccbf1c10..41129a6b 100644 --- a/src/@types/config.d.ts +++ b/src/@types/config.d.ts @@ -1,55 +1,64 @@ - // generated from config.json at https://app.quicktype.io/?l=ts - +import type { SinglePropertyTypeMapping } from "./index.d.ts"; /** * @private */ export declare interface PropertiesConfig { + /** + * shorthand property minification rules + */ properties: PropertiesConfigProperties; - map: Map; + /** + * shorthand property minification rules + */ + map: Map; + /** + * single property minification rules + */ + property: Record; } /** * @private */ export interface Map { - border: Border; - "border-color": BackgroundPositionClass; - "border-style": BackgroundPositionClass; - "border-width": BackgroundPositionClass; - outline: Outline; - "outline-color": BackgroundPositionClass; - "outline-style": BackgroundPositionClass; - "outline-width": BackgroundPositionClass; - font: Font; - "font-weight": BackgroundPositionClass; - "font-style": BackgroundPositionClass; - "font-size": BackgroundPositionClass; - "line-height": BackgroundPositionClass; - "font-stretch": BackgroundPositionClass; - "font-variant": BackgroundPositionClass; - "font-family": BackgroundPositionClass; - background: Background; - "background-repeat": BackgroundPositionClass; - "background-color": BackgroundPositionClass; - "background-image": BackgroundPositionClass; + border: Border; + "border-color": BackgroundPositionClass; + "border-style": BackgroundPositionClass; + "border-width": BackgroundPositionClass; + outline: Outline; + "outline-color": BackgroundPositionClass; + "outline-style": BackgroundPositionClass; + "outline-width": BackgroundPositionClass; + font: Font; + "font-weight": BackgroundPositionClass; + "font-style": BackgroundPositionClass; + "font-size": BackgroundPositionClass; + "line-height": BackgroundPositionClass; + "font-stretch": BackgroundPositionClass; + "font-variant": BackgroundPositionClass; + "font-family": BackgroundPositionClass; + background: Background; + "background-repeat": BackgroundPositionClass; + "background-color": BackgroundPositionClass; + "background-image": BackgroundPositionClass; "background-attachment": BackgroundPositionClass; - "background-clip": BackgroundPositionClass; - "background-origin": BackgroundPositionClass; - "background-position": BackgroundPositionClass; - "background-size": BackgroundPositionClass; + "background-clip": BackgroundPositionClass; + "background-origin": BackgroundPositionClass; + "background-position": BackgroundPositionClass; + "background-size": BackgroundPositionClass; } /** * @private */ export interface Background { - shorthand: string; - pattern: string; - keywords: string[]; - default: any[]; - multiple: boolean; - separator: Separator; + shorthand: string; + pattern: string; + keywords: string[]; + default: any[]; + multiple: boolean; + separator: Separator; properties: BackgroundProperties; } @@ -57,25 +66,25 @@ export interface Background { * @private */ export interface BackgroundProperties { - "background-repeat": BackgroundRepeat; - "background-color": PurpleBackgroundAttachment; - "background-image": PurpleBackgroundAttachment; + "background-repeat": BackgroundRepeat; + "background-color": PurpleBackgroundAttachment; + "background-image": PurpleBackgroundAttachment; "background-attachment": PurpleBackgroundAttachment; - "background-clip": PurpleBackgroundAttachment; - "background-origin": PurpleBackgroundAttachment; - "background-position": BackgroundPosition; - "background-size": BackgroundSize; + "background-clip": PurpleBackgroundAttachment; + "background-origin": PurpleBackgroundAttachment; + "background-position": BackgroundPosition; + "background-size": BackgroundSize; } /** * @private */ export interface PurpleBackgroundAttachment { - types: string[]; - default: string[]; - keywords: string[]; + types: string[]; + default: string[]; + keywords: string[]; required?: boolean; - mapping?: BackgroundAttachmentMapping; + mapping?: BackgroundAttachmentMapping; } /** @@ -84,24 +93,24 @@ export interface PurpleBackgroundAttachment { export interface BackgroundAttachmentMapping { "ultra-condensed": string; "extra-condensed": string; - condensed: string; - "semi-condensed": string; - normal: string; - "semi-expanded": string; - expanded: string; - "extra-expanded": string; - "ultra-expanded": string; + condensed: string; + "semi-condensed": string; + normal: string; + "semi-expanded": string; + expanded: string; + "extra-expanded": string; + "ultra-expanded": string; } /** * @private */ export interface BackgroundPosition { - multiple: boolean; - types: string[]; - default: string[]; - keywords: string[]; - mapping: BackgroundPositionMapping; + multiple: boolean; + types: string[]; + default: string[]; + keywords: string[]; + mapping: BackgroundPositionMapping; constraints: BackgroundPositionConstraints; } @@ -123,33 +132,33 @@ export interface ConstraintsMapping { * @private */ export interface BackgroundPositionMapping { - left: string; - top: string; + left: string; + top: string; center: string; bottom: string; - right: string; + right: string; } /** * @private */ export interface BackgroundRepeat { - types: any[]; - default: string[]; + types: any[]; + default: string[]; multiple: boolean; keywords: string[]; - mapping: BackgroundRepeatMapping; + mapping: BackgroundRepeatMapping; } /** * @private */ export interface BackgroundRepeatMapping { - "repeat no-repeat": string; - "no-repeat repeat": string; - "repeat repeat": string; - "space space": string; - "round round": string; + "repeat no-repeat": string; + "no-repeat repeat": string; + "repeat repeat": string; + "space space": string; + "round round": string; "no-repeat no-repeat": string; } @@ -159,11 +168,11 @@ export interface BackgroundRepeatMapping { export interface BackgroundSize { multiple: boolean; previous: string; - prefix: Prefix; - types: string[]; - default: string[]; + prefix: Prefix; + types: string[]; + default: string[]; keywords: string[]; - mapping: BackgroundSizeMapping; + mapping: BackgroundSizeMapping; } /** @@ -199,10 +208,10 @@ export interface BackgroundPositionClass { * @private */ export interface Border { - shorthand: string; - pattern: string; - keywords: string[]; - default: string[]; + shorthand: string; + pattern: string; + keywords: string[]; + default: string[]; properties: BorderProperties; } @@ -218,17 +227,16 @@ export interface BorderProperties { /** * @private */ -export interface BorderColorClass { -} +export interface BorderColorClass {} /** * @private */ export interface Font { - shorthand: string; - pattern: string; - keywords: string[]; - default: any[]; + shorthand: string; + pattern: string; + keywords: string[]; + default: any[]; properties: FontProperties; } @@ -236,24 +244,24 @@ export interface Font { * @private */ export interface FontProperties { - "font-weight": FontWeight; - "font-style": PurpleBackgroundAttachment; - "font-size": PurpleBackgroundAttachment; - "line-height": LineHeight; + "font-weight": FontWeight; + "font-style": PurpleBackgroundAttachment; + "font-size": PurpleBackgroundAttachment; + "line-height": LineHeight; "font-stretch": PurpleBackgroundAttachment; "font-variant": PurpleBackgroundAttachment; - "font-family": FontFamily; + "font-family": FontFamily; } /** * @private */ export interface FontFamily { - types: string[]; - default: any[]; - keywords: string[]; - required: boolean; - multiple: boolean; + types: string[]; + default: any[]; + keywords: string[]; + required: boolean; + multiple: boolean; separator: Separator; } @@ -261,11 +269,11 @@ export interface FontFamily { * @private */ export interface FontWeight { - types: string[]; - default: string[]; - keywords: string[]; + types: string[]; + default: string[]; + keywords: string[]; constraints: FontWeightConstraints; - mapping: FontWeightMapping; + mapping: FontWeightMapping; } /** @@ -287,21 +295,21 @@ export interface Value { * @private */ export interface FontWeightMapping { - thin: string; - hairline: string; + thin: string; + hairline: string; "extra light": string; "ultra light": string; - light: string; - normal: string; - regular: string; - medium: string; - "semi bold": string; - "demi bold": string; - bold: string; - "extra bold": string; - "ultra bold": string; - black: string; - heavy: string; + light: string; + normal: string; + regular: string; + medium: string; + "semi bold": string; + "demi bold": string; + bold: string; + "extra bold": string; + "ultra bold": string; + black: string; + heavy: string; "extra black": string; "ultra black": string; } @@ -310,21 +318,21 @@ export interface FontWeightMapping { * @private */ export interface LineHeight { - types: string[]; - default: string[]; + types: string[]; + default: string[]; keywords: string[]; previous: string; - prefix: Prefix; + prefix: Prefix; } /** * @private */ export interface Outline { - shorthand: string; - pattern: string; - keywords: string[]; - default: string[]; + shorthand: string; + pattern: string; + keywords: string[]; + default: string[]; properties: OutlineProperties; } @@ -341,62 +349,62 @@ export interface OutlineProperties { * @private */ export interface PropertiesConfigProperties { - inset: BorderRadius; - top: BackgroundPositionClass; - right: BackgroundPositionClass; - bottom: BackgroundPositionClass; - left: BackgroundPositionClass; - margin: BorderRadius; - "margin-top": BackgroundPositionClass; - "margin-right": BackgroundPositionClass; - "margin-bottom": BackgroundPositionClass; - "margin-left": BackgroundPositionClass; - padding: BorderColor; - "padding-top": BackgroundPositionClass; - "padding-right": BackgroundPositionClass; - "padding-bottom": BackgroundPositionClass; - "padding-left": BackgroundPositionClass; - "border-radius": BorderRadius; - "border-top-left-radius": BackgroundPositionClass; - "border-top-right-radius": BackgroundPositionClass; + inset: BorderRadius; + top: BackgroundPositionClass; + right: BackgroundPositionClass; + bottom: BackgroundPositionClass; + left: BackgroundPositionClass; + margin: BorderRadius; + "margin-top": BackgroundPositionClass; + "margin-right": BackgroundPositionClass; + "margin-bottom": BackgroundPositionClass; + "margin-left": BackgroundPositionClass; + padding: BorderColor; + "padding-top": BackgroundPositionClass; + "padding-right": BackgroundPositionClass; + "padding-bottom": BackgroundPositionClass; + "padding-left": BackgroundPositionClass; + "border-radius": BorderRadius; + "border-top-left-radius": BackgroundPositionClass; + "border-top-right-radius": BackgroundPositionClass; "border-bottom-right-radius": BackgroundPositionClass; - "border-bottom-left-radius": BackgroundPositionClass; - "border-width": BorderColor; - "border-top-width": BackgroundPositionClass; - "border-right-width": BackgroundPositionClass; - "border-bottom-width": BackgroundPositionClass; - "border-left-width": BackgroundPositionClass; - "border-style": BorderColor; - "border-top-style": BackgroundPositionClass; - "border-right-style": BackgroundPositionClass; - "border-bottom-style": BackgroundPositionClass; - "border-left-style": BackgroundPositionClass; - "border-color": BorderColor; - "border-top-color": BackgroundPositionClass; - "border-right-color": BackgroundPositionClass; - "border-bottom-color": BackgroundPositionClass; - "border-left-color": BackgroundPositionClass; + "border-bottom-left-radius": BackgroundPositionClass; + "border-width": BorderColor; + "border-top-width": BackgroundPositionClass; + "border-right-width": BackgroundPositionClass; + "border-bottom-width": BackgroundPositionClass; + "border-left-width": BackgroundPositionClass; + "border-style": BorderColor; + "border-top-style": BackgroundPositionClass; + "border-right-style": BackgroundPositionClass; + "border-bottom-style": BackgroundPositionClass; + "border-left-style": BackgroundPositionClass; + "border-color": BorderColor; + "border-top-color": BackgroundPositionClass; + "border-right-color": BackgroundPositionClass; + "border-bottom-color": BackgroundPositionClass; + "border-left-color": BackgroundPositionClass; } /** * @private */ export interface BorderColor { - shorthand: string; - map?: string; + shorthand: string; + map?: string; properties: string[]; - types: string[]; - keywords: string[]; + types: string[]; + keywords: string[]; } /** * @private */ export interface BorderRadius { - shorthand: string; + shorthand: string; properties: string[]; - types: string[]; - multiple: boolean; - separator: null | string; - keywords: string[]; + types: string[]; + multiple: boolean; + separator: null | string; + keywords: string[]; } diff --git a/src/@types/index.d.ts b/src/@types/index.d.ts index 0d38f22f..3531416c 100644 --- a/src/@types/index.d.ts +++ b/src/@types/index.d.ts @@ -2,12 +2,7 @@ import type { VisitorNodeMap } from "./visitor.d.ts"; import type { AstAtRule, AstDeclaration, AstNode, AstRule, AstStyleSheet, Location } from "./ast.d.ts"; import { SourceMap } from "../lib/renderer/sourcemap/sourcemap.ts"; import type { PropertyListOptions } from "./parse.d.ts"; -import { - EnumToken, - ModuleCaseTransformEnum, - ModuleScopeEnumOptions, - ValidationLevel, -} from "../lib/ast/types.ts"; +import { EnumToken, ModuleCaseTransformEnum, ModuleScopeEnumOptions, ValidationLevel } from "../lib/ast/types.ts"; import type { CssVariableToken, Token } from "./token.d.ts"; import { FeatureWalkMode } from "../lib/ast/features/type.ts"; import { mathFuncs } from "../lib/syntax/constants.ts"; @@ -22,99 +17,99 @@ export * from "./walker.d.ts"; export * from "./parse.d.ts"; /** - * error description + * Error description */ export declare interface ErrorDescription { /** - * drop rule or declaration + * Drop rule or declaration */ action: "drop" | "ignore"; /** - * error message + * Error message */ message: string; /** - * syntax error description + * Syntax error description */ syntax?: string | ValidationToken | null; /** - * error node + * Error node */ node?: Token | AstNode | null; /** - * error location + * Error location */ location?: Location; /** - * error object + * Error object */ error?: Error; /** - * raw tokens + * Raw tokens */ rawTokens?: TokenizeResult[]; } /** - * css validation options + * CSS validation options */ export interface ValidationOptions { - /** * nested rule context + * @internal */ nestedRule?: boolean; /** - * enable css validation + * enable CSS validation * * see {@link ValidationLevel} */ validation?: boolean | ValidationLevel; /** - * lenient validation. retain nodes that failed validation + * Lenient validation. retain nodes that failed validation */ lenient?: boolean; /** - * visited tokens + * Visited tokens * * @private */ visited?: Map>; - + /** - * is optional + * Is optional * * @private */ isOptional?: boolean | null; /** - * is repeatable + * Is repeatable * * @private */ isRepeatable?: boolean | null; /** - * is list + * Is list * * @private */ isList?: boolean | null; /** - * occurence + * Occurence * * @private */ occurrence?: boolean | null; /** - * at least once + * At least once * * @private */ @@ -122,23 +117,23 @@ export interface ValidationOptions { } /** - * minify options + * Minify options */ export interface MinifyOptions { /** - * enable minification + * Enable minification */ minify?: boolean; /** - * parse color tokens + * Parse color tokens */ parseColor?: boolean; /** - * generate nested rules + * Generate nested rules */ nestingRules?: boolean; /** - * remove duplicate declarations from the same rule. if passed as a string array, duplicated declarations are removed, except for those in the array + * Remove duplicate declarations from the same rule. if passed as a string array, duplicated declarations are removed, except for those in the array * * * ```ts @@ -170,33 +165,31 @@ export interface MinifyOptions { */ removeDuplicateDeclarations?: boolean | string | string[]; /** - * compute shorthand properties + * Compute shorthand properties */ computeShorthand?: boolean; /** - * compute transform functions - * see supported functions {@link transformFunctions} + * Compute css transform functions */ computeTransform?: boolean; /** - * compute math functions - * see supported functions {@link mathFuncs} + * Compute css math functions */ computeCalcExpression?: boolean; /** - * inline css variables + * Inline css variables */ inlineCssVariables?: boolean; /** - * remove empty ast nodes + * Remove empty ast nodes */ removeEmpty?: boolean; /** - * remove css prefix + * Remove css prefix */ removePrefix?: boolean; /** - * define minification passes. + * Define minification passes. */ pass?: number; } @@ -209,22 +202,22 @@ export declare type LoadResult = export declare interface ModuleOptions { /** - * use local scope vs global scope + * Use local scope vs global scope */ scoped?: boolean | ModuleScopeEnumOptions; /** - * module output file path. it is used to generate the scoped name. if not provided, [options.src](../docs/interfaces/node.ParserOptions.html#src) will be used + * Module output file path. it is used to generate the scoped name. if not provided, [options.src](../docs/interfaces/node.ParserOptions.html#src) will be used */ filePath?: string; /** - * generated scope hash length. the default is 5 + * Generated scope hash length. the default is 5 */ hashLength?: number; /** - * the pattern used to generate scoped names. the supported placeholders are: + * The pattern used to generate scoped names. the supported placeholders are: * - name: the file base name without the extension * - hash: the file path hash * - local: the local name @@ -312,7 +305,7 @@ export declare interface ModuleOptions { naming?: ModuleCaseTransformEnum; /** - * optional function to generate scoped name + * Function to generate scoped name * @param localName * @param filePath * @param pattern see {@link ModuleOptions.pattern} @@ -327,44 +320,44 @@ export declare interface ModuleOptions { } /** - * parser options + * Parser options */ export declare interface ParserOptions extends MinifyOptions, MinifyFeatureOptions, ValidationOptions, PropertyListOptions { /** - * source file to be used for sourcemap + * Source file to be used for sourcemap */ src?: string; /** - * include sourcemap in the ast. sourcemap info is always generated + * Include sourcemap in the ast. Sourcemap info is always generated */ sourcemap?: boolean | "inline"; /** - * remove at-rule charset + * Remove at-rule charset */ removeCharset?: boolean; /** - * resolve import + * Resolve import */ resolveImport?: boolean; /** - * current working directory + * Current working directory * * @internal */ cwd?: string; /** - * expand nested rules + * Expand nested rules */ expandNestingRules?: boolean; /** - * experimental, convert css if() function into legacy syntax. + * Experimental, convert css if() function into legacy syntax. */ expandIfSyntax?: boolean; /** - * url and file loader + * Url and file loader * @param url * @param currentDirectory * @param responseType @@ -376,18 +369,18 @@ export declare interface ParserOptions responseType?: boolean | ResponseType, ) => Promise>>; /** - * get directory name + * Get directory name * @param path * * @private */ dirname?: (path: string) => string; /** - * resolve urls + * Resolve urls */ resolveUrls?: boolean; /** - * url and path resolver + * Url and path resolver * @param url * @param currentUrl * @param currentWorkingDirectory @@ -403,12 +396,12 @@ export declare interface ParserOptions }; /** - * node visitor + * Node visitor * {@link VisitorNodeMap | VisitorNodeMap[]} */ visitor?: VisitorNodeMap | VisitorNodeMap[]; /** - * abort signal + * Abort signal * * Example: abort after 10 seconds * ```ts @@ -421,38 +414,38 @@ export declare interface ParserOptions */ signal?: AbortSignal; /** - * set parent node + * Set parent node * * @private */ setParent?: boolean; /** - * cache + * Cache * * @private */ cache?: WeakMap; /** - * css modules options + * CSS modules options */ module?: boolean | ModuleCaseTransformEnum | ModuleScopeEnumOptions | ModuleOptions; /** - * tokenizing info + * Tokenizing info * @private */ parseInfo?: ParseInfo; } /** - * minify feature options + * Minify feature options * * @internal */ export declare interface MinifyFeatureOptions { /** - * minify features + * Minify features * * @private */ @@ -460,31 +453,31 @@ export declare interface MinifyFeatureOptions { } /** - * minify feature + * Minify feature * * @internal */ export declare interface MinifyFeature { /** - * accepted tokens + * Accepted tokens */ accept?: Set; /** - * ordering + * Ordering */ ordering: number; /** - * process mode + * Process mode */ processMode: FeatureWalkMode; /** - * register feature + * Register feature * @param options */ register: (options: MinifyFeatureOptions | ParserOptions) => void; /** - * run feature + * Run feature * @param ast * @param options * @param parent @@ -503,30 +496,30 @@ export declare interface MinifyFeature { } /** - * resolved path + * Resolved path * @internal */ export declare interface ResolvedPath { /** - * absolute path + * Absolute path */ absolute: string; /** - * relative path + * Relative path */ relative: string; } /** - * ast node render options + * Ast node render options */ export declare interface RenderOptions { /** - * minify css values. + * Minify css values. */ minify?: boolean; /** - * pretty print css + * Pretty print css * * ```ts * const result = await transform(css, {beautify: true}); @@ -534,7 +527,7 @@ export declare interface RenderOptions { */ beautify?: boolean; /** - * remove empty nodes. empty nodes are removed by default + * Remove empty nodes. Empty nodes are removed by default * * ```ts * @@ -550,304 +543,333 @@ export declare interface RenderOptions { */ removeEmpty?: boolean; /** - * expand nesting rules + * Expand nesting rules */ expandNestingRules?: boolean; /** - * preserve license comments. license comments are comments that start with /*! + * Preserve license comments. License comments are comments that start with '/*!' */ preserveLicense?: boolean; /** - * generate sourcemap object. 'inline' will embed it in the css + * Generate sourcemap object. 'inline' will embed it in the css */ sourcemap?: boolean | "inline"; /** - * indent string + * Indention string */ indent?: string; /** - * new line string + * New line string */ newLine?: string; /** - * remove comments + * Remove comments */ removeComments?: boolean; /** - * convert color to the specified color space. 'true' will convert to HEX + * Convert color to the specified color space. 'true' will convert to HEX */ convertColor?: boolean | ColorType; /** - * render the node along with its parents + * Render the node along with its parents */ withParents?: boolean; /** - * output file. used for url resolution + * Output file. Used for url resolution * @internal */ output?: string; /** - * current working directory + * Current working directory * @internal */ cwd?: string; /** - * resolve path + * Resolve path * @internal */ resolve?: (url: string, currentUrl: string, currentWorkingDirectory?: string) => ResolvedPath; } /** - * transform options + * Transform options */ export declare interface TransformOptions extends ParserOptions, RenderOptions {} /** - * parse result stats object + * Parse result stats object */ export declare interface ParseResultStats { /** - * source file + * Source file */ src: string; /** - * bytes read + * Bytes read */ bytesIn: number; /** - * bytes read from imported files + * Bytes read from imported files */ importedBytesIn: number; /** - * tokenizing processing time + * Tokenizing processing time */ tokenize: string; /** - * parsing processing time + * Parsing processing time */ parse: string; /** - * minification processing time + * Minification processing time */ minify: string; /** - * module processing time + * Module processing time */ module?: string; /** - * total time + * Total time */ total: string; /** - * imported files stats + * Imported files stats */ imports: ParseResultStats[]; /** - * nodes count + * Nodes count */ nodesCount: number; /** - * tokens count + * Tokens count */ tokensCount: number; } /** - * parse result object + * Parse result object */ export declare interface ParseResult { /** - * parsed ast tree + * Parsed ast tree */ ast: AstStyleSheet; /** - * parse errors + * Parse errors */ errors: ErrorDescription[]; /** - * parse stats + * Parse stats */ stats: ParseResultStats; /** - * css module mapping + * CSS module mapping */ mapping?: Record; + /** + * CSS module variables + * @private + */ cssModuleVariables?: Record; + /** + * css module import mapping + * @private + */ importMapping?: Record>; /** - * css module reverse mapping + * CSS module reverse mapping * @private */ revMapping?: Record; } /** - * render result object + * Render result object */ export declare interface RenderResult { /** - * rendered css + * Rendered CSS */ code: string; /** - * render errors + * Render errors */ errors: ErrorDescription[]; /** - * render stats + * Render stats */ stats: { /** - * render time + * Render time */ total: string; }; /** - * source map + * Source map */ map?: SourceMap; } /** - * transform result object + * Transform result object */ export declare interface TransformResult extends ParseResult, RenderResult { /** - * transform stats + * Transform stats */ stats: { /** - * source file + * Source file */ src: string; /** - * bytes read + * Bytes read */ bytesIn: number; /** - * generated css size + * Generated CSS size */ bytesOut: number; /** - * bytes read from imported files + * Bytes read from imported files */ importedBytesIn: number; /** - * parse time + * Parse time */ parse: string; /** - * minify time + * Minify time */ minify: string; /** - * render time + * Render time */ render: string; /** - * total time + * Total time */ total: string; /** - * imported files stats + * Imported files stats */ imports: ParseResultStats[]; }; } /** - * parse token options + * Parse token options */ export declare interface ParseTokenOptions extends ParserOptions {} /** - * tokenize result object + * Tokenize result object * @internal */ export declare interface TokenizeResult { /** - * token + * Token */ token: Token; /** - * bytes in + * Bytes in */ bytesIn: number; } /** - * matched selector object + * Matched selector object * @internal */ export declare interface MatchedSelector { /** - * matched selector + * Matched selector */ match: string[][]; /** - * selector 1 + * Selector 1 */ selector1: string[][]; /** - * selector 2 + * Selector 2 */ selector2: string[][]; /** - * selectors partially match + * Selectors partially match */ eq: boolean; } /** - * variable scope info object + * Variable scope info object * @internal */ export declare interface VariableScopeInfo { /** - * global scope + * Global scope */ globalScope: boolean; /** - * parent nodes + * Parent nodes */ parent: Set; /** - * declaration count + * Declaration count */ declarationCount: number; /** - * replaceable + * Replaceable */ replaceable: boolean; /** - * declaration node + * Declaration node */ node: AstDeclaration; /** - * declaration values + * Declaration values */ values: Token[]; } /** - * source map object + * Source map object * @internal */ export declare interface SourceMapObject { + /** + * Source map version + */ version: number; + /** + * Source file + */ file?: string; + /** + * Source root + */ sourceRoot?: string; + /** + * Source files + */ sources?: string[]; + /** + * Source files content + */ sourcesContent?: Array; + /** + * Variable names + */ names?: string[]; + /** + * Mappings + */ mappings: string; } diff --git a/src/@types/shorthand.d.ts b/src/@types/shorthand.d.ts index f1428f39..601c6220 100644 --- a/src/@types/shorthand.d.ts +++ b/src/@types/shorthand.d.ts @@ -1,12 +1,20 @@ -import {EnumToken} from "../lib/ast/types.ts"; +import { EnumToken } from "../lib/ast/types.ts"; export interface PropertyType { - shorthand: string; } -export interface ShorthandPropertyType { +export interface SinglePropertyType { + typ: keyof EnumToken; + val: string | number; +} +export interface SinglePropertyTypeMapping { + pattern?: string[][]; + mapping: Record; +} + +export interface ShorthandPropertyType { shorthand: string; map?: string; properties: string[]; @@ -14,22 +22,20 @@ export interface ShorthandPropertyType { multiple: boolean; separator: { typ: keyof EnumToken; - val: string + val: string; }; valueSeparator?: { typ: keyof EnumToken; - val: string + val: string; }; keywords: string[]; } export interface PropertySetType { - [key: string]: PropertyType | ShorthandPropertyType; } export interface PropertyMapType { - default: string[]; types: string[]; keywords: string[]; @@ -37,23 +43,21 @@ export interface PropertyMapType { multiple?: boolean; prefix?: { typ: keyof EnumToken; - val: string + val: string; }; previous?: string; separator?: { - typ: keyof EnumToken; }; constraints?: { [key: string]: { [key: string]: any; - } + }; }; - mapping?: Record + mapping?: Record; } export interface ShorthandMapType { - shorthand: string; pattern: string; keywords: string[]; @@ -61,10 +65,10 @@ export interface ShorthandMapType { mapping?: Record; multiple?: boolean; separator?: { typ: keyof EnumToken; val?: string }; - set?: Record + set?: Record; properties: { [property: string]: PropertyMapType; - } + }; } export interface ShorthandProperties { @@ -95,4 +99,4 @@ export interface ShorthandDef { export interface ShorthandType { shorthand: string; properties: ShorthandProperties; -} \ No newline at end of file +} diff --git a/src/config.json b/src/config.json index ed5350ec..efd48706 100644 --- a/src/config.json +++ b/src/config.json @@ -1 +1 @@ -{"properties":{"gap":{"shorthand":"gap","properties":["row-gap","column-gap"],"types":["Length","Perc"],"multiple":false,"separator":null,"keywords":["normal"]},"row-gap":{"shorthand":"gap"},"column-gap":{"shorthand":"gap"},"inset":{"shorthand":"inset","properties":["top","right","bottom","left"],"types":["Length","Perc"],"multiple":false,"separator":null,"keywords":["auto"]},"top":{"shorthand":"inset"},"right":{"shorthand":"inset"},"bottom":{"shorthand":"inset"},"left":{"shorthand":"inset"},"margin":{"shorthand":"margin","properties":["margin-top","margin-right","margin-bottom","margin-left"],"types":["Length","Perc"],"multiple":false,"separator":null,"keywords":["auto"]},"margin-top":{"shorthand":"margin"},"margin-right":{"shorthand":"margin"},"margin-bottom":{"shorthand":"margin"},"margin-left":{"shorthand":"margin"},"padding":{"shorthand":"padding","properties":["padding-top","padding-right","padding-bottom","padding-left"],"types":["Length","Perc"],"keywords":[]},"padding-top":{"shorthand":"padding"},"padding-right":{"shorthand":"padding"},"padding-bottom":{"shorthand":"padding"},"padding-left":{"shorthand":"padding"},"border-radius":{"shorthand":"border-radius","properties":["border-top-left-radius","border-top-right-radius","border-bottom-right-radius","border-bottom-left-radius"],"types":["Length","Perc"],"multiple":true,"separator":{"typ":"Literal","val":"/"},"keywords":[]},"border-top-left-radius":{"shorthand":"border-radius"},"border-top-right-radius":{"shorthand":"border-radius"},"border-bottom-right-radius":{"shorthand":"border-radius"},"border-bottom-left-radius":{"shorthand":"border-radius"},"border-width":{"shorthand":"border-width","map":"border","properties":["border-top-width","border-right-width","border-bottom-width","border-left-width"],"types":["Length","Perc"],"default":["medium"],"keywords":["thin","medium","thick"]},"border-top-width":{"map":"border","shorthand":"border-width"},"border-right-width":{"map":"border","shorthand":"border-width"},"border-bottom-width":{"map":"border","shorthand":"border-width"},"border-left-width":{"map":"border","shorthand":"border-width"},"border-style":{"shorthand":"border-style","map":"border","properties":["border-top-style","border-right-style","border-bottom-style","border-left-style"],"types":[],"default":["none"],"keywords":["none","hidden","dotted","dashed","solid","double","groove","ridge","inset","outset"]},"border-top-style":{"map":"border","shorthand":"border-style"},"border-right-style":{"map":"border","shorthand":"border-style"},"border-bottom-style":{"map":"border","shorthand":"border-style"},"border-left-style":{"map":"border","shorthand":"border-style"},"border-color":{"shorthand":"border-color","map":"border","properties":["border-top-color","border-right-color","border-bottom-color","border-left-color"],"types":["Color"],"default":["currentcolor"],"keywords":[]},"border-top-color":{"map":"border","shorthand":"border-color"},"border-right-color":{"map":"border","shorthand":"border-color"},"border-bottom-color":{"map":"border","shorthand":"border-color"},"border-left-color":{"map":"border","shorthand":"border-color"},"grid-row":{"shorthand":"grid-row","properties":["grid-row-start","grid-row-end"],"types":["Iden","Number"],"multiple":true,"valueSeparator":{"typ":"Literal","val":"/"},"default":["auto"],"keywords":["auto","span"]},"grid-row-start":{"shorthand":"grid-row"},"grid-row-end":{"shorthand":"grid-row"}},"map":{"flex-flow":{"shorthand":"flex-flow","pattern":"flex-direction flex-wrap","keywords":[],"default":["row","nowrap"],"properties":{"flex-direction":{"keywords":["row","row-reverse","column","column-reverse"],"default":["row"],"types":[]},"flex-wrap":{"keywords":["wrap","nowrap","wrap-reverse"],"default":["nowrap"],"types":[]}}},"flex-direction":{"shorthand":"flex-flow"},"flex-wrap":{"shorthand":"flex-flow"},"container":{"shorthand":"container","pattern":"container-name container-type","keywords":[],"default":[],"properties":{"container-name":{"required":true,"multiple":true,"keywords":["none"],"default":["none"],"types":["Iden","DashedIden"]},"container-type":{"previous":"container-name","prefix":{"typ":"Literal","val":"/"},"keywords":["size","inline-size","normal"],"default":["normal"],"types":[]}}},"container-name":{"shorthand":"container"},"container-type":{"shorthand":"container"},"flex":{"shorthand":"flex","pattern":"flex-grow flex-shrink flex-basis","keywords":["auto","none","initial"],"default":[],"mapping":{"0 1 auto":"initial","0 0 auto":"none","1 1 auto":"auto"},"properties":{"flex-grow":{"required":true,"keywords":[],"default":[],"types":["Number"]},"flex-shrink":{"keywords":[],"default":[],"types":["Number"]},"flex-basis":{"keywords":["max-content","min-content","fit-content","fit-content","content","auto"],"default":[],"types":["Length","Perc"]}}},"flex-grow":{"shorthand":"flex"},"flex-shrink":{"shorthand":"flex"},"flex-basis":{"shorthand":"flex"},"columns":{"shorthand":"columns","pattern":"column-count column-width","keywords":["auto"],"default":["auto","auto auto"],"properties":{"column-count":{"keywords":["auto"],"default":["auto"],"types":["Number"]},"column-width":{"keywords":["auto"],"default":["auto"],"types":["Length"]}}},"column-count":{"shorthand":"columns"},"column-width":{"shorthand":"columns"},"transition":{"shorthand":"transition","multiple":true,"separator":{"typ":"Comma"},"pattern":"transition-property transition-duration transition-timing-function transition-delay transition-behavior","keywords":["none","all"],"default":["0s","0ms","all","ease","none","normal"],"mapping":{"cubic-bezier(.25,.1,.25,1)":"ease","cubic-bezier(0,0,1,1)":"linear","cubic-bezier(.42,0,1,1)":"ease-in","cubic-bezier(0,0,.58,1)":"ease-out","cubic-bezier(.42,0,.58,.42)":"ease-in-out"},"properties":{"transition-property":{"keywords":["none","all"],"default":["all"],"types":["Iden"]},"transition-duration":{"keywords":[],"default":["0s","0ms","normal"],"types":["Time"]},"transition-timing-function":{"keywords":["ease","ease-in","ease-out","ease-in-out","linear","step-start","step-end"],"default":["ease"],"types":["TimingFunction"],"mapping":{"cubic-bezier(.25,.1,.25,1)":"ease","cubic-bezier(0,0,1,1)":"linear","cubic-bezier(.42,0,1,1)":"ease-in","cubic-bezier(0,0,.58,1)":"ease-out","cubic-bezier(.42,0,.58,.42)":"ease-in-out"}},"transition-delay":{"keywords":[],"default":["0s"],"types":["Time"]},"transition-behavior":{"keywords":["normal","allow-discrete"],"default":["normal"],"types":[]}}},"transition-property":{"shorthand":"transition"},"transition-duration":{"shorthand":"transition"},"transition-timing-function":{"shorthand":"transition"},"transition-delay":{"shorthand":"transition"},"transition-behavior":{"shorthand":"transition"},"animation":{"shorthand":"animation","separator":{"typ":"Comma"},"pattern":"animation-name animation-duration animation-timing-function animation-delay animation-iteration-count animation-direction animation-fill-mode animation-play-state animation-timeline","default":["1","0s","0ms","none","ease","normal","running","auto"],"properties":{"animation-name":{"keywords":["none"],"default":["none"],"types":["Iden"]},"animation-duration":{"keywords":["auto"],"default":["0s","0ms","auto"],"types":["Time"],"mapping":{"auto":"0s"}},"animation-timing-function":{"keywords":["ease","ease-in","ease-out","ease-in-out","linear","step-start","step-end"],"default":["ease"],"types":["TimingFunction"],"mapping":{"cubic-bezier(.25,.1,.25,1)":"ease","cubic-bezier(0,0,1,1)":"linear","cubic-bezier(.42,0,1,1)":"ease-in","cubic-bezier(0,0,.58,1)":"ease-out","cubic-bezier(.42,0,.58,.42)":"ease-in-out"}},"animation-delay":{"keywords":[],"default":["0s","0ms"],"types":["Time"]},"animation-iteration-count":{"keywords":["infinite"],"default":["1"],"types":["Number"]},"animation-direction":{"keywords":["normal","reverse","alternate","alternate-reverse"],"default":["normal"],"types":[]},"animation-fill-mode":{"keywords":["none","forwards","backwards","both"],"default":["none"],"types":[]},"animation-play-state":{"keywords":["running","paused"],"default":["running"],"types":[]},"animation-timeline":{"keywords":["none","auto"],"default":["auto"],"types":["DashedIden","TimelineFunction"]}}},"animation-name":{"shorthand":"animation"},"animation-duration":{"shorthand":"animation"},"animation-timing-function":{"shorthand":"animation"},"animation-delay":{"shorthand":"animation"},"animation-iteration-count":{"shorthand":"animation"},"animation-direction":{"shorthand":"animation"},"animation-fill-mode":{"shorthand":"animation"},"animation-play-state":{"shorthand":"animation"},"animation-timeline":{"shorthand":"animation"},"text-emphasis":{"shorthand":"text-emphasis","pattern":"text-emphasis-color text-emphasis-style","default":["none","currentcolor"],"properties":{"text-emphasis-style":{"keywords":["none","filled","open","dot","circle","double-circle","triangle","sesame"],"default":["none"],"types":["String"]},"text-emphasis-color":{"default":["currentcolor"],"types":["Color"]}}},"text-emphasis-style":{"shorthand":"text-emphasis"},"text-emphasis-color":{"shorthand":"text-emphasis"},"border":{"shorthand":"border","pattern":"border-color border-style border-width","keywords":["none"],"default":["0","none"],"properties":{"border-color":{"types":["Color"],"default":["currentcolor"],"keywords":[]},"border-style":{"types":[],"default":["none"],"keywords":["none","hidden","dotted","dashed","solid","double","groove","ridge","inset","outset"]},"border-width":{"types":["Length","Perc"],"default":["medium"],"keywords":["thin","medium","thick"]}}},"border-color":{"shorthand":"border"},"border-style":{"shorthand":"border"},"border-width":{"shorthand":"border"},"list-style":{"shorthand":"list-style","pattern":"list-style-type list-style-position list-style-image","keywords":["none","outside"],"default":["none","outside"],"properties":{"list-style-position":{"types":[],"default":["outside"],"keywords":["inside","outside"]},"list-style-image":{"default":["none"],"keywords":["node"],"types":["UrlFunc","ImageFunc"]},"list-style-type":{"types":["String","Iden","Symbols"],"default":["disc"],"keywords":["disc","circle","square","decimal","decimal-leading-zero","lower-roman","upper-roman","lower-greek","lower-latin","upper-latin","none"]}}},"list-style-position":{"shorthand":"list-style"},"list-style-image":{"shorthand":"list-style"},"list-style-type":{"shorthand":"list-style"},"overflow":{"shorthand":"overflow","pattern":"overflow-x overflow-y","keywords":["auto","visible","hidden","clip","scroll"],"default":[],"mapping":{"visible visible":"visible","auto auto":"auto","hidden hidden":"hidden","scroll scroll":"scroll"},"properties":{"overflow-x":{"default":[],"types":[],"keywords":["auto","visible","hidden","clip","scroll"]},"overflow-y":{"default":[],"types":[],"keywords":["auto","visible","hidden","clip","scroll"]}}},"overflow-x":{"shorthand":"overflow"},"overflow-y":{"shorthand":"overflow"},"outline":{"shorthand":"outline","pattern":"outline-color outline-style outline-width","keywords":["none"],"default":["0","none","currentcolor"],"properties":{"outline-color":{"types":["Color"],"default":["currentcolor"],"keywords":["currentcolor"]},"outline-style":{"types":[],"default":["none"],"keywords":["auto","none","dotted","dashed","solid","double","groove","ridge","inset","outset"]},"outline-width":{"types":["Length","Perc"],"default":["medium"],"keywords":["thin","medium","thick"]}}},"outline-color":{"shorthand":"outline"},"outline-style":{"shorthand":"outline"},"outline-width":{"shorthand":"outline"},"font":{"shorthand":"font","pattern":"font-weight font-style font-size line-height font-stretch font-variant font-family","keywords":["caption","icon","menu","message-box","small-caption","status-bar","-moz-window, ","-moz-document, ","-moz-desktop, ","-moz-info, ","-moz-dialog","-moz-button","-moz-pull-down-menu","-moz-list","-moz-field"],"default":[],"properties":{"font-weight":{"types":["Number"],"default":["400","normal"],"keywords":["normal","bold","lighter","bolder"],"constraints":{"value":{"min":"1","max":"1000"}},"mapping":{"thin":"100","hairline":"100","extra light":"200","ultra light":"200","light":"300","normal":"400","regular":"400","medium":"500","semi bold":"600","demi bold":"600","bold":"700","extra bold":"800","ultra bold":"800","black":"900","heavy":"900","extra black":"950","ultra black":"950"}},"font-style":{"types":["Angle"],"default":["normal"],"keywords":["normal","italic","oblique"]},"font-size":{"types":["Length","Perc"],"default":[],"keywords":["xx-small","x-small","small","medium","large","x-large","xx-large","xxx-large","larger","smaller"],"required":true},"line-height":{"types":["Length","Perc","Number"],"default":["normal"],"keywords":["normal"],"previous":"font-size","prefix":{"typ":"Literal","val":"/"}},"font-stretch":{"types":["Perc"],"default":["normal"],"keywords":["ultra-condensed","extra-condensed","condensed","semi-condensed","normal","semi-expanded","expanded","extra-expanded","ultra-expanded"],"mapping":{"ultra-condensed":"50%","extra-condensed":"62.5%","condensed":"75%","semi-condensed":"87.5%","normal":"100%","semi-expanded":"112.5%","expanded":"125%","extra-expanded":"150%","ultra-expanded":"200%"}},"font-variant":{"types":[],"default":["normal"],"keywords":["normal","none","common-ligatures","no-common-ligatures","discretionary-ligatures","no-discretionary-ligatures","historical-ligatures","no-historical-ligatures","contextual","no-contextual","historical-forms","small-caps","all-small-caps","petite-caps","all-petite-caps","unicase","titling-caps","ordinal","slashed-zero","lining-nums","oldstyle-nums","proportional-nums","tabular-nums","diagonal-fractions","stacked-fractions","ordinal","slashed-zero","ruby","jis78","jis83","jis90","jis04","simplified","traditional","full-width","proportional-width","ruby","sub","super","text","emoji","unicode"]},"font-family":{"types":["String","Iden"],"default":[],"keywords":["serif","sans-serif","monospace","cursive","fantasy","system-ui","ui-serif","ui-sans-serif","ui-monospace","ui-rounded","math","emoji","fangsong"],"required":true,"multiple":true,"separator":{"typ":"Comma"}}}},"font-weight":{"shorthand":"font"},"font-style":{"shorthand":"font"},"font-size":{"shorthand":"font"},"line-height":{"shorthand":"font"},"font-stretch":{"shorthand":"font"},"font-variant":{"shorthand":"font"},"font-family":{"shorthand":"font"},"background":{"shorthand":"background","pattern":"background-attachment background-origin background-clip background-color background-image background-repeat background-position background-size","keywords":["none"],"default":["0 0","none","auto","repeat","transparent","#0000","scroll","padding-box","border-box"],"multiple":true,"set":{"background-origin":["background-clip"]},"separator":{"typ":"Comma"},"properties":{"background-repeat":{"types":[],"default":["repeat"],"multiple":true,"keywords":["repeat-x","repeat-y","repeat","space","round","no-repeat"],"mapping":{"repeat no-repeat":"repeat-x","no-repeat repeat":"repeat-y","repeat repeat":"repeat","space space":"space","round round":"round","no-repeat no-repeat":"no-repeat"}},"background-color":{"types":["Color"],"default":["#0000","transparent"],"multiple":true,"keywords":[]},"background-image":{"types":["UrlFunc","ImageFunc"],"default":["none"],"keywords":["none"]},"background-attachment":{"types":[],"default":["scroll"],"multiple":true,"keywords":["scroll","fixed","local"]},"background-clip":{"types":[],"default":["border-box"],"multiple":true,"keywords":["border-box","padding-box","content-box","text"]},"background-origin":{"types":[],"default":["padding-box"],"multiple":true,"keywords":["border-box","padding-box","content-box"]},"background-position":{"multiple":true,"types":["Perc","Length"],"default":["0 0","top left","left top"],"keywords":["top","left","center","bottom","right"],"mapping":{"left":"0","top":"0","center":"50%","center center":"50%","50% 50%":"50%","bottom":"100%","right":"100%"},"constraints":{"mapping":{"max":2}}},"background-size":{"multiple":true,"previous":"background-position","prefix":{"typ":"Literal","val":"/"},"types":["Perc","Length"],"default":["auto","auto auto"],"keywords":["auto","cover","contain"],"mapping":{"auto auto":"auto"}}}},"background-repeat":{"shorthand":"background"},"background-color":{"shorthand":"background"},"background-image":{"shorthand":"background"},"background-attachment":{"shorthand":"background"},"background-clip":{"shorthand":"background"},"background-origin":{"shorthand":"background"},"background-position":{"shorthand":"background"},"background-size":{"shorthand":"background"}}} \ No newline at end of file +{"properties":{"gap":{"shorthand":"gap","properties":["row-gap","column-gap"],"types":["Length","Perc"],"multiple":false,"separator":null,"keywords":["normal"]},"row-gap":{"shorthand":"gap"},"column-gap":{"shorthand":"gap"},"inset":{"shorthand":"inset","properties":["top","right","bottom","left"],"types":["Length","Perc"],"multiple":false,"separator":null,"keywords":["auto"]},"top":{"shorthand":"inset"},"right":{"shorthand":"inset"},"bottom":{"shorthand":"inset"},"left":{"shorthand":"inset"},"margin":{"shorthand":"margin","properties":["margin-top","margin-right","margin-bottom","margin-left"],"types":["Length","Perc"],"multiple":false,"separator":null,"keywords":["auto"]},"margin-top":{"shorthand":"margin"},"margin-right":{"shorthand":"margin"},"margin-bottom":{"shorthand":"margin"},"margin-left":{"shorthand":"margin"},"padding":{"shorthand":"padding","properties":["padding-top","padding-right","padding-bottom","padding-left"],"types":["Length","Perc"],"keywords":[]},"padding-top":{"shorthand":"padding"},"padding-right":{"shorthand":"padding"},"padding-bottom":{"shorthand":"padding"},"padding-left":{"shorthand":"padding"},"border-radius":{"shorthand":"border-radius","properties":["border-top-left-radius","border-top-right-radius","border-bottom-right-radius","border-bottom-left-radius"],"types":["Length","Perc"],"multiple":true,"separator":{"typ":"Literal","val":"/"},"keywords":[]},"border-top-left-radius":{"shorthand":"border-radius"},"border-top-right-radius":{"shorthand":"border-radius"},"border-bottom-right-radius":{"shorthand":"border-radius"},"border-bottom-left-radius":{"shorthand":"border-radius"},"border-width":{"shorthand":"border-width","map":"border","properties":["border-top-width","border-right-width","border-bottom-width","border-left-width"],"types":["Length","Perc"],"default":["medium"],"keywords":["thin","medium","thick"]},"border-top-width":{"map":"border","shorthand":"border-width"},"border-right-width":{"map":"border","shorthand":"border-width"},"border-bottom-width":{"map":"border","shorthand":"border-width"},"border-left-width":{"map":"border","shorthand":"border-width"},"border-style":{"shorthand":"border-style","map":"border","properties":["border-top-style","border-right-style","border-bottom-style","border-left-style"],"types":[],"default":["none"],"keywords":["none","hidden","dotted","dashed","solid","double","groove","ridge","inset","outset"]},"border-top-style":{"map":"border","shorthand":"border-style"},"border-right-style":{"map":"border","shorthand":"border-style"},"border-bottom-style":{"map":"border","shorthand":"border-style"},"border-left-style":{"map":"border","shorthand":"border-style"},"border-color":{"shorthand":"border-color","map":"border","properties":["border-top-color","border-right-color","border-bottom-color","border-left-color"],"types":["Color"],"default":["currentcolor"],"keywords":[]},"border-top-color":{"map":"border","shorthand":"border-color"},"border-right-color":{"map":"border","shorthand":"border-color"},"border-bottom-color":{"map":"border","shorthand":"border-color"},"border-left-color":{"map":"border","shorthand":"border-color"},"grid-row":{"shorthand":"grid-row","properties":["grid-row-start","grid-row-end"],"types":["Iden","Number"],"multiple":true,"valueSeparator":{"typ":"Literal","val":"/"},"default":["auto"],"keywords":["auto","span"]},"grid-row-start":{"shorthand":"grid-row"},"grid-row-end":{"shorthand":"grid-row"}},"map":{"flex-flow":{"shorthand":"flex-flow","pattern":"flex-direction flex-wrap","keywords":[],"default":["row","nowrap"],"properties":{"flex-direction":{"keywords":["row","row-reverse","column","column-reverse"],"default":["row"],"types":[]},"flex-wrap":{"keywords":["wrap","nowrap","wrap-reverse"],"default":["nowrap"],"types":[]}}},"flex-direction":{"shorthand":"flex-flow"},"flex-wrap":{"shorthand":"flex-flow"},"container":{"shorthand":"container","pattern":"container-name container-type","keywords":[],"default":[],"properties":{"container-name":{"required":true,"multiple":true,"keywords":["none"],"default":["none"],"types":["Iden","DashedIden"]},"container-type":{"previous":"container-name","prefix":{"typ":"Literal","val":"/"},"keywords":["size","inline-size","normal"],"default":["normal"],"types":[]}}},"container-name":{"shorthand":"container"},"container-type":{"shorthand":"container"},"flex":{"shorthand":"flex","pattern":"flex-grow flex-shrink flex-basis","keywords":["auto","none","initial"],"default":[],"mapping":{"0 1 auto":"initial","0 0 auto":"none","1 1 auto":"auto"},"properties":{"flex-grow":{"required":true,"keywords":[],"default":[],"types":["Number"]},"flex-shrink":{"keywords":[],"default":[],"types":["Number"]},"flex-basis":{"keywords":["max-content","min-content","fit-content","fit-content","content","auto"],"default":[],"types":["Length","Perc"]}}},"flex-grow":{"shorthand":"flex"},"flex-shrink":{"shorthand":"flex"},"flex-basis":{"shorthand":"flex"},"columns":{"shorthand":"columns","pattern":"column-count column-width","keywords":["auto"],"default":["auto","auto auto"],"properties":{"column-count":{"keywords":["auto"],"default":["auto"],"types":["Number"]},"column-width":{"keywords":["auto"],"default":["auto"],"types":["Length"]}}},"column-count":{"shorthand":"columns"},"column-width":{"shorthand":"columns"},"transition":{"shorthand":"transition","multiple":true,"separator":{"typ":"Comma"},"pattern":"transition-property transition-duration transition-timing-function transition-delay transition-behavior","keywords":["none","all"],"default":["0s","0ms","all","ease","none","normal"],"mapping":{"cubic-bezier(.25,.1,.25,1)":"ease","cubic-bezier(0,0,1,1)":"linear","cubic-bezier(.42,0,1,1)":"ease-in","cubic-bezier(0,0,.58,1)":"ease-out","cubic-bezier(.42,0,.58,.42)":"ease-in-out"},"properties":{"transition-property":{"keywords":["none","all"],"default":["all"],"types":["Iden"]},"transition-duration":{"keywords":[],"default":["0s","0ms","normal"],"types":["Time"]},"transition-timing-function":{"keywords":["ease","ease-in","ease-out","ease-in-out","linear","step-start","step-end"],"default":["ease"],"types":["TimingFunction"],"mapping":{"cubic-bezier(.25,.1,.25,1)":"ease","cubic-bezier(0,0,1,1)":"linear","cubic-bezier(.42,0,1,1)":"ease-in","cubic-bezier(0,0,.58,1)":"ease-out","cubic-bezier(.42,0,.58,.42)":"ease-in-out"}},"transition-delay":{"keywords":[],"default":["0s"],"types":["Time"]},"transition-behavior":{"keywords":["normal","allow-discrete"],"default":["normal"],"types":[]}}},"transition-property":{"shorthand":"transition"},"transition-duration":{"shorthand":"transition"},"transition-timing-function":{"shorthand":"transition"},"transition-delay":{"shorthand":"transition"},"transition-behavior":{"shorthand":"transition"},"animation":{"shorthand":"animation","separator":{"typ":"Comma"},"pattern":"animation-name animation-duration animation-timing-function animation-delay animation-iteration-count animation-direction animation-fill-mode animation-play-state animation-timeline","default":["1","0s","0ms","none","ease","normal","running","auto"],"properties":{"animation-name":{"keywords":["none"],"default":["none"],"types":["Iden"]},"animation-duration":{"keywords":["auto"],"default":["0s","0ms","auto"],"types":["Time"],"mapping":{"auto":"0s"}},"animation-timing-function":{"keywords":["ease","ease-in","ease-out","ease-in-out","linear","step-start","step-end"],"default":["ease"],"types":["TimingFunction"],"mapping":{"cubic-bezier(.25,.1,.25,1)":"ease","cubic-bezier(0,0,1,1)":"linear","cubic-bezier(.42,0,1,1)":"ease-in","cubic-bezier(0,0,.58,1)":"ease-out","cubic-bezier(.42,0,.58,.42)":"ease-in-out"}},"animation-delay":{"keywords":[],"default":["0s","0ms"],"types":["Time"]},"animation-iteration-count":{"keywords":["infinite"],"default":["1"],"types":["Number"]},"animation-direction":{"keywords":["normal","reverse","alternate","alternate-reverse"],"default":["normal"],"types":[]},"animation-fill-mode":{"keywords":["none","forwards","backwards","both"],"default":["none"],"types":[]},"animation-play-state":{"keywords":["running","paused"],"default":["running"],"types":[]},"animation-timeline":{"keywords":["none","auto"],"default":["auto"],"types":["DashedIden","TimelineFunction"]}}},"animation-name":{"shorthand":"animation"},"animation-duration":{"shorthand":"animation"},"animation-timing-function":{"shorthand":"animation"},"animation-delay":{"shorthand":"animation"},"animation-iteration-count":{"shorthand":"animation"},"animation-direction":{"shorthand":"animation"},"animation-fill-mode":{"shorthand":"animation"},"animation-play-state":{"shorthand":"animation"},"animation-timeline":{"shorthand":"animation"},"text-emphasis":{"shorthand":"text-emphasis","pattern":"text-emphasis-color text-emphasis-style","default":["none","currentcolor"],"properties":{"text-emphasis-style":{"keywords":["none","filled","open","dot","circle","double-circle","triangle","sesame"],"default":["none"],"types":["String"]},"text-emphasis-color":{"default":["currentcolor"],"types":["Color"]}}},"text-emphasis-style":{"shorthand":"text-emphasis"},"text-emphasis-color":{"shorthand":"text-emphasis"},"border":{"shorthand":"border","pattern":"border-color border-style border-width","keywords":["none"],"default":["0","none"],"properties":{"border-color":{"types":["Color"],"default":["currentcolor"],"keywords":[]},"border-style":{"types":[],"default":["none"],"keywords":["none","hidden","dotted","dashed","solid","double","groove","ridge","inset","outset"]},"border-width":{"types":["Length","Perc"],"default":["medium"],"keywords":["thin","medium","thick"]}}},"border-color":{"shorthand":"border"},"border-style":{"shorthand":"border"},"border-width":{"shorthand":"border"},"list-style":{"shorthand":"list-style","pattern":"list-style-type list-style-position list-style-image","keywords":["none","outside"],"default":["none","outside"],"properties":{"list-style-position":{"types":[],"default":["outside"],"keywords":["inside","outside"]},"list-style-image":{"default":["none"],"keywords":["node"],"types":["UrlFunc","ImageFunc"]},"list-style-type":{"types":["String","Iden","Symbols"],"default":["disc"],"keywords":["disc","circle","square","decimal","decimal-leading-zero","lower-roman","upper-roman","lower-greek","lower-latin","upper-latin","none"]}}},"list-style-position":{"shorthand":"list-style"},"list-style-image":{"shorthand":"list-style"},"list-style-type":{"shorthand":"list-style"},"overflow":{"shorthand":"overflow","pattern":"overflow-x overflow-y","keywords":["auto","visible","hidden","clip","scroll"],"default":[],"mapping":{"visible visible":"visible","auto auto":"auto","hidden hidden":"hidden","scroll scroll":"scroll"},"properties":{"overflow-x":{"default":[],"types":[],"keywords":["auto","visible","hidden","clip","scroll"]},"overflow-y":{"default":[],"types":[],"keywords":["auto","visible","hidden","clip","scroll"]}}},"overflow-x":{"shorthand":"overflow"},"overflow-y":{"shorthand":"overflow"},"outline":{"shorthand":"outline","pattern":"outline-color outline-style outline-width","keywords":["none"],"default":["0","none","currentcolor"],"properties":{"outline-color":{"types":["Color"],"default":["currentcolor"],"keywords":["currentcolor"]},"outline-style":{"types":[],"default":["none"],"keywords":["auto","none","dotted","dashed","solid","double","groove","ridge","inset","outset"]},"outline-width":{"types":["Length","Perc"],"default":["medium"],"keywords":["thin","medium","thick"]}}},"outline-color":{"shorthand":"outline"},"outline-style":{"shorthand":"outline"},"outline-width":{"shorthand":"outline"},"font":{"shorthand":"font","pattern":"font-weight font-style font-size line-height font-stretch font-variant font-family","keywords":["caption","icon","menu","message-box","small-caption","status-bar","-moz-window, ","-moz-document, ","-moz-desktop, ","-moz-info, ","-moz-dialog","-moz-button","-moz-pull-down-menu","-moz-list","-moz-field"],"default":[],"properties":{"font-weight":{"types":["Number"],"default":["400","normal"],"keywords":["normal","bold","lighter","bolder"],"constraints":{"value":{"min":"1","max":"1000"}},"mapping":{"thin":"100","hairline":"100","extra light":"200","ultra light":"200","light":"300","normal":"400","regular":"400","medium":"500","semi bold":"600","demi bold":"600","bold":"700","extra bold":"800","ultra bold":"800","black":"900","heavy":"900","extra black":"950","ultra black":"950"}},"font-style":{"types":["Angle"],"default":["normal"],"keywords":["normal","italic","oblique"]},"font-size":{"types":["Length","Perc"],"default":[],"keywords":["xx-small","x-small","small","medium","large","x-large","xx-large","xxx-large","larger","smaller"],"required":true},"line-height":{"types":["Length","Perc","Number"],"default":["normal"],"keywords":["normal"],"previous":"font-size","prefix":{"typ":"Literal","val":"/"}},"font-stretch":{"types":["Perc"],"default":["normal"],"keywords":["ultra-condensed","extra-condensed","condensed","semi-condensed","normal","semi-expanded","expanded","extra-expanded","ultra-expanded"],"mapping":{"ultra-condensed":"50%","extra-condensed":"62.5%","condensed":"75%","semi-condensed":"87.5%","normal":"100%","semi-expanded":"112.5%","expanded":"125%","extra-expanded":"150%","ultra-expanded":"200%"}},"font-variant":{"types":[],"default":["normal"],"keywords":["normal","none","common-ligatures","no-common-ligatures","discretionary-ligatures","no-discretionary-ligatures","historical-ligatures","no-historical-ligatures","contextual","no-contextual","historical-forms","small-caps","all-small-caps","petite-caps","all-petite-caps","unicase","titling-caps","ordinal","slashed-zero","lining-nums","oldstyle-nums","proportional-nums","tabular-nums","diagonal-fractions","stacked-fractions","ordinal","slashed-zero","ruby","jis78","jis83","jis90","jis04","simplified","traditional","full-width","proportional-width","ruby","sub","super","text","emoji","unicode"]},"font-family":{"types":["String","Iden"],"default":[],"keywords":["serif","sans-serif","monospace","cursive","fantasy","system-ui","ui-serif","ui-sans-serif","ui-monospace","ui-rounded","math","emoji","fangsong"],"required":true,"multiple":true,"separator":{"typ":"Comma"}}}},"font-weight":{"shorthand":"font"},"font-style":{"shorthand":"font"},"font-size":{"shorthand":"font"},"line-height":{"shorthand":"font"},"font-stretch":{"shorthand":"font"},"font-variant":{"shorthand":"font"},"font-family":{"shorthand":"font"},"background":{"shorthand":"background","pattern":"background-attachment background-origin background-clip background-color background-image background-repeat background-position background-size","keywords":["none"],"default":["0 0","none","auto","repeat","transparent","#0000","scroll","padding-box","border-box"],"multiple":true,"set":{"background-origin":["background-clip"]},"separator":{"typ":"Comma"},"properties":{"background-repeat":{"types":[],"default":["repeat"],"multiple":true,"keywords":["repeat-x","repeat-y","repeat","space","round","no-repeat"],"mapping":{"repeat no-repeat":"repeat-x","no-repeat repeat":"repeat-y","repeat repeat":"repeat","space space":"space","round round":"round","no-repeat no-repeat":"no-repeat"}},"background-color":{"types":["Color"],"default":["#0000","transparent"],"multiple":true,"keywords":[]},"background-image":{"types":["UrlFunc","ImageFunc"],"default":["none"],"keywords":["none"]},"background-attachment":{"types":[],"default":["scroll"],"multiple":true,"keywords":["scroll","fixed","local"]},"background-clip":{"types":[],"default":["border-box"],"multiple":true,"keywords":["border-box","padding-box","content-box","text"]},"background-origin":{"types":[],"default":["padding-box"],"multiple":true,"keywords":["border-box","padding-box","content-box"]},"background-position":{"multiple":true,"types":["Perc","Length"],"default":["0 0","top left","left top"],"keywords":["top","left","center","bottom","right"],"mapping":{"left":"0","top":"0","center":"50%","center center":"50%","50% 50%":"50%","bottom":"100%","right":"100%"},"constraints":{"mapping":{"max":2}}},"background-size":{"multiple":true,"previous":"background-position","prefix":{"typ":"Literal","val":"/"},"types":["Perc","Length"],"default":["auto","auto auto"],"keywords":["auto","cover","contain"],"mapping":{"auto auto":"auto"}}}},"background-repeat":{"shorthand":"background"},"background-color":{"shorthand":"background"},"background-image":{"shorthand":"background"},"background-attachment":{"shorthand":"background"},"background-clip":{"shorthand":"background"},"background-origin":{"shorthand":"background"},"background-position":{"shorthand":"background"},"background-size":{"shorthand":"background"}},"property":{"transform-origin":{"pattern":[["left|center|right","top|center|bottom",""],["left|center|right","top|center|bottom"],["center|left|right|center|top|bottom|"]],"mapping":{"center":{"typ":"Perc","val":50},"left":{"typ":"Perc","val":0},"right":{"typ":"Perc","val":100},"top":{"typ":"Perc","val":0},"bottom":{"typ":"Perc","val":100}}}}} \ No newline at end of file diff --git a/src/lib/ast/clone.ts b/src/lib/ast/clone.ts index 12cf3edc..96982975 100644 --- a/src/lib/ast/clone.ts +++ b/src/lib/ast/clone.ts @@ -3,20 +3,21 @@ import type { Token } from "../../@types/token.d.ts"; import { EnumToken } from "../ast/types.ts"; /** - * - * @param node he nod to clone - * @param cloneChildren deep clone - * @param cloneMap a map of existing children as keys and their clones as values - * @returns + * + * clone an ast node or value + * @param node + * @param cloneChildren + * @param cloneMap + * @returns */ export function cloneNode( - node: AstNode, + node: AstNode | Token, cloneChildren: boolean = false, cloneMap: Map | null = null, -): AstNode { +): AstNode | Token { const checkNode = node.typ == EnumToken.DeclarationNodeType ? "val" : "chi"; - const clone = {} as Token; + const clone = {} as Token | AstNode; const properties = {}; cloneMap?.set?.(node, clone); diff --git a/src/lib/ast/features/if.ts b/src/lib/ast/features/if.ts index aca29bde..95870d1e 100644 --- a/src/lib/ast/features/if.ts +++ b/src/lib/ast/features/if.ts @@ -310,8 +310,8 @@ export class ExpandIfFeature { } run(declaration: AstDeclaration): AstNode | null { - const cache = new Set(); - const result = processNode(declaration, cache); + + const result = processNode(declaration, new Set()); let i: number; diff --git a/src/lib/parser/declaration/list.ts b/src/lib/parser/declaration/list.ts index a60a2d47..5d077281 100644 --- a/src/lib/parser/declaration/list.ts +++ b/src/lib/parser/declaration/list.ts @@ -1,10 +1,14 @@ import type { AstDeclaration, AstNode, + IdentToken, + NumberToken, PropertiesConfig, PropertyListOptions, ShorthandMapType, ShorthandPropertyType, + SinglePropertyType, + SinglePropertyTypeMapping, Token, } from "../../../@types/index.d.ts"; import { PropertySet } from "./set.ts"; @@ -12,6 +16,7 @@ import { getConfig } from "../utils/config.ts"; import { PropertyMap } from "./map.ts"; import { parseString } from "../parse.ts"; import { EnumToken } from "../../ast/types.ts"; +import { walk } from "../../ast/walk.ts"; const config: PropertiesConfig = getConfig(); @@ -60,8 +65,8 @@ export class PropertyList { } let propertyName: string = (declaration).nam; - let shortHandType: "map" | "set"; - let shorthand: string; + let shortHandType: "map" | "set" | "single"; + let shorthand: any = null; if (propertyName in config.properties) { // @ts-ignore @@ -78,6 +83,10 @@ export class PropertyList { shortHandType = "map"; // @ts-ignore shorthand = config.map[propertyName].shorthand; + } else if (propertyName in config.property) { + shortHandType = "single"; + // @ts-ignore + shorthand = config.property[propertyName]; } // @ts-ignore @@ -99,9 +108,9 @@ export class PropertyList { if (!this.declarations.has(shorthand)) { // @ts-ignore this.declarations.set( - // @ts-ignore + // @ts-ignore shorthand, - // @ts-ignore + // @ts-ignore new PropertySet(config.properties[shorthand]), ); } @@ -109,6 +118,10 @@ export class PropertyList { // @ts-ignore (this.declarations.get(shorthand)).add(declaration); } else { + if (shorthand != null) { + this.mapValues(declaration as AstDeclaration, shorthand as SinglePropertyTypeMapping); + } + this.declarations.set(propertyName, declaration); } } @@ -116,6 +129,83 @@ export class PropertyList { return this; } + mapValues(declaration: AstDeclaration, mapping: SinglePropertyTypeMapping) { + let name: string | null; + + let values = declaration.val; + + if (mapping.pattern != null) { + // match pattern + for (const patterns of mapping.pattern) { + const set: Set = new Set( + values.filter( + (v) => v.typ !== EnumToken.CommentTokenType && v.typ !== EnumToken.WhitespaceTokenType, + ), + ); + const val: Token[] = []; + + for (const pattern of patterns) { + switch (pattern) { + case "": + for (const v of set) { + if ( + v.typ === EnumToken.LengthTokenType || + (v.typ === EnumToken.NumberTokenType && (v as NumberToken).val === 0) + ) { + val.push(v); + set.delete(v); + } + } + + default: { + for (const v of set) { + if (v.typ === EnumToken.IdenTokenType) { + const value: string = (v as IdentToken).val.toLowerCase(); + + if (value === pattern || new RegExp(`(^|\|)${pattern}(\||$)`).test(value)) { + val.push(v); + set.delete(v); + } + } + } + } + } + } + + if (set.size === 0) { + + values = val.reduce((acc: Token[], curr: Token): Token[] => { + if (acc.length > 0) { + acc.push({ typ: EnumToken.WhitespaceTokenType }); + } + + acc.push(curr); + + return acc; + }, [] as Token[]); + + break; + } + } + } + + for (const val of declaration.val) { + if (val.typ === EnumToken.IdenTokenType) { + name = (val as IdentToken).val.toLowerCase(); + + if (mapping.mapping[name] != null) { + // @ts-expect-error + Object.assign(val, mapping.mapping[name], { typ: EnumToken[mapping.mapping[name].typ] }); + } + } + } + + if (values != declaration.val) { + declaration.val.length = 0; + declaration.val.push(...values); + } + } + [Symbol.iterator]() { let iterator: IterableIterator = this.declarations.values(); const iterators: Array> = []; diff --git a/src/lib/parser/parse.ts b/src/lib/parser/parse.ts index 945d5128..cb10340e 100644 --- a/src/lib/parser/parse.ts +++ b/src/lib/parser/parse.ts @@ -593,7 +593,6 @@ export async function doParse( : // @ts-expect-error ((iter as Iterator).next().value as TokenizeResult)) ) { - stats.bytesIn = item.bytesIn; stats.tokensCount++; @@ -716,7 +715,6 @@ export async function doParse( context = node as AstRuleList; } } - } if (imports.length > 0 && options.resolveImport) { @@ -726,7 +724,6 @@ export async function doParse( const url: string = token.typ == EnumToken.StringTokenType ? token.val.slice(1, -1) : token.val; try { - const result = options.load!(url, options.src) as LoadResult; const stream = result instanceof Promise || Object.getPrototypeOf(result).constructor.name == "AsyncFunction" @@ -737,7 +734,7 @@ export async function doParse( ? tokenizeStream(stream) : tokenize({ stream, - src: options.resolve!(url, options.src || options.cwd as string).relative, + src: options.resolve!(url, options.src || (options.cwd as string)).relative, buffer: "", offset: 0, position: { ind: 0, lin: 1, col: 1 }, @@ -746,7 +743,7 @@ export async function doParse( Object.assign({}, options, { minify: false, setParent: false, - src: options.resolve!(url, options.src || options.cwd as string).relative, + src: options.resolve!(url, options.src || (options.cwd as string)).relative, }) as ParserOptions, ); @@ -1326,7 +1323,6 @@ export async function doParse( for (const token of node.val) { if (token.typ == EnumToken.ComposesSelectorNodeType) { - tokens.push(token as ComposesSelectorToken); } } @@ -1339,7 +1335,6 @@ export async function doParse( } if (/* !isValid || */ tokens.length == 0) { - errors.push({ action: "drop", message: `composes is empty`, @@ -2146,7 +2141,6 @@ function parseNode( context.chi!.push(node); // @ts-expect-error return Object.defineProperty(node, "parent", { ...definedPropertySettings, value: context }); - } else { stats.nodesCount++; @@ -2194,8 +2188,6 @@ export function parseAtRule( errors: ErrorDescription[], parseAsBlock: boolean | null = null, ): AstAtRule | AstInvalidAtRule | CssVariableImportTokenType | CssVariableToken | null { - // const rules = getSyntaxRule(ValidationSyntaxGroupEnum.AtRules, "@" + (stream[0] as AtRuleToken).nam); - let success: boolean = true; let atRuleName = (stream[0] as AtRuleToken).nam; @@ -2467,8 +2459,6 @@ export function parseAtRule( ) as AstKeyframesAtRule; } case "keyframes": { - - const tokens = trimArray(stream.slice(1)); const filtered: Token[] = stream.filter( (t) => t.typ !== EnumToken.WhitespaceTokenType && t.typ !== EnumToken.CommentTokenType, @@ -2519,6 +2509,9 @@ export function parseAtRule( if (!result.success) { errors.push(...result.errors); } + // else { + // parseUrlToken(stream); + // } const valid: boolean = blockAllowed === parseAsBlock && result.success; @@ -2587,7 +2580,9 @@ export function parseAtRule( } else { if ( stream[0]?.typ == EnumToken.UrlFunctionTokenType && - (stream[0] as FunctionToken).chi.some((t) => t.typ == EnumToken.StringTokenType) + (stream[0] as FunctionToken).chi.some( + (t) => t.typ == EnumToken.StringTokenType || t.typ == EnumToken.UrlTokenTokenType, + ) ) { stream.splice(0, 1, ...(stream[0] as FunctionToken).chi); } @@ -2730,7 +2725,6 @@ export function parseAtRule( ) as AstAtRule | AstInvalidAtRule; } case "scope": { - let context = createValidationContext(trimArray(stream)); let success: boolean = true; @@ -2848,8 +2842,6 @@ export function parseAtRule( case "page": { trimArray(stream); - const result = parseAtRulePage(atRule, stream, options, errors); - // @ts-expect-error return Object.defineProperties( Object.assign(atRule, { @@ -2931,7 +2923,6 @@ export function parseAtRule( let isVarDeclaration: boolean = false; for (; index < stream.length; index++) { - if (stream[index].typ == EnumToken.PseudoClassTokenType) { Object.assign(stream[index], { typ: EnumToken.IdenTokenType, @@ -3050,6 +3041,13 @@ export function parseAtRule( } else { result = matchAtRuleSyntax(atRule, stream, options); + if (result.errors.length > 0) { + errors.push(...result.errors); + } + // else if (atRuleName === "document") { + // parseUrlToken(stream); + // } + if (result.success) { let i: number = 0; const stack: Token[] = []; diff --git a/src/lib/parser/tokenize.ts b/src/lib/parser/tokenize.ts index 3d2ab5cf..045c9a35 100644 --- a/src/lib/parser/tokenize.ts +++ b/src/lib/parser/tokenize.ts @@ -391,7 +391,6 @@ export function match(parseInfo: ParseInfo, input: string): boolean { } return true; - } export function peek(parseInfo: ParseInfo, count: number = 1): string { @@ -520,16 +519,81 @@ export function tokenize(parseInfo: ParseInfo | string, yieldEOFToken: boolean = buffer = ""; break; } else if (isIdent(buffer)) { - result.push( - yieldResult( - buffer, - parseInfo, - buffer.startsWith("--") - ? EnumToken.CustomFunctionTokenDefType - : (SymbolsMapTokens[buffer.toLowerCase() + "("] ?? EnumToken.FunctionTokenDefType), - ), - ); + const hint: EnumToken = buffer.startsWith("--") + ? EnumToken.CustomFunctionTokenDefType + : (SymbolsMapTokens[buffer.toLowerCase() + "("] ?? EnumToken.FunctionTokenDefType); + result.push(yieldResult(buffer, parseInfo, hint)); buffer = ""; + + if (hint === EnumToken.UrlFunctionTokenDefType) { + value = peek(parseInfo); + // consume an + while (isWhiteSpace((charCode = value.charCodeAt(0)))) { + buffer += next(parseInfo); + value = peek(parseInfo); + charCode = value.charCodeAt(0); + + if (value === "/" && match(parseInfo, "/*")) { + if (buffer.length > 0) { + result.push(yieldResult(buffer, parseInfo)); + buffer = ""; + } + + buffer += next(parseInfo, 2); + + while ((value = next(parseInfo))) { + if (value == "*") { + buffer += value; + + if (match(parseInfo, "/")) { + result.push( + yieldResult( + buffer + next(parseInfo), + parseInfo, + EnumToken.CommentTokenType, + ), + ); + buffer = ""; + break; + } + } else { + buffer += value; + } + } + + if (buffer.length > 0) { + result.push(yieldResult(buffer, parseInfo, EnumToken.BadCommentTokenType)); + buffer = ""; + } + + value = peek(parseInfo); + charCode = value.charCodeAt(0); + } + } + + if (buffer.length > 0) { + result.push(yieldResult(buffer, parseInfo, EnumToken.WhitespaceTokenType)); + buffer = ""; + } + + if (value === ")" || value === '"' || value === "'") { + break; + } + + do { + buffer += next(parseInfo); + value = peek(parseInfo); + charCode = value.charCodeAt(0); + } + + while(value !== ")" && !isWhiteSpace(charCode) && !(value === '/' && match(parseInfo, "/*"))); + + if (buffer.length > 0) { + result.push(yieldResult(buffer, parseInfo, peek(parseInfo) === "" ? EnumToken.BadUrlTokenType : EnumToken.UrlTokenTokenType)); + buffer = ""; + } + } + break; } } diff --git a/src/lib/parser/utils/at-rule-generic.ts b/src/lib/parser/utils/at-rule-generic.ts index bfdd3204..e22fc6cb 100644 --- a/src/lib/parser/utils/at-rule-generic.ts +++ b/src/lib/parser/utils/at-rule-generic.ts @@ -7,7 +7,7 @@ import type { ValidationOptions, } from "../../../@types/index.d.ts"; import { EnumToken } from "../../ast/types.ts"; -import { tokensfuncDefMap, tokensMap } from "../../syntax/constants.ts"; +import { tokensfuncDefMap } from "../../syntax/constants.ts"; import { equalsIgnoreCase } from "./text.ts"; export function matchGenericSyntax( diff --git a/src/lib/parser/utils/at-rule.ts b/src/lib/parser/utils/at-rule.ts index 6bf44162..86691e7e 100644 --- a/src/lib/parser/utils/at-rule.ts +++ b/src/lib/parser/utils/at-rule.ts @@ -1,18 +1,14 @@ -import type { AtRuleToken, Token, ParserOptions, ValidationOptions } from "../../../@types/index.d.ts"; +import type { AtRuleToken, Token, ParserOptions, ValidationOptions, ErrorDescription } from "../../../@types/index.d.ts"; import { EnumToken } from "../../ast/types.ts"; import { ValidationSyntaxGroupEnum } from "../../validation/parser/typedef.ts"; import type { ValidationToken } from "../../validation/parser/types.d.ts"; import { getSyntaxRule } from "../../validation/config.ts"; import { createValidationContext, matchAllSyntax, trimArray } from "../../validation/match.ts"; -// export const mediaQueryConditionEnum: Set = new Set([ -// EnumToken.ParensTokenType, -// EnumToken.IdenTokenType, -// EnumToken.MediaQueryConditionTokenType, -// EnumToken.MediaQueryUnaryFeatureTokenType, -// ]); - -export function matchAtRuleSyntax(atRule: AtRuleToken, stream: Token[], options: ParserOptions | ValidationOptions) { +export function matchAtRuleSyntax(atRule: AtRuleToken, stream: Token[], options: ParserOptions | ValidationOptions): { + success: boolean; + errors: ErrorDescription[] +} { const syntaxRules = getSyntaxRule(ValidationSyntaxGroupEnum.AtRules, "@" + atRule.nam); const syntax: ValidationToken[] = syntaxRules?.getPreludeRules()?.slice?.(1) as ValidationToken[]; diff --git a/src/lib/parser/utils/declaration.ts b/src/lib/parser/utils/declaration.ts index de6f8e61..a22af6bf 100644 --- a/src/lib/parser/utils/declaration.ts +++ b/src/lib/parser/utils/declaration.ts @@ -33,6 +33,7 @@ import { tokensMap, definedPropertySettings, trimTokenSpace, + urlTokenMatcher, } from "../../syntax/constants.ts"; import { isColor, isValue, isWhiteSpace, parseColor, renamedStandardProperties } from "../../syntax/syntax.ts"; import { getSyntaxRule, getParsedSyntax, ValidationSyntaxRule } from "../../validation/config.ts"; @@ -703,6 +704,19 @@ export function parseDeclaration( if (value.typ === EnumToken.IdenTokenType && isColor(value)) { parseColor(value); } + + // else if (value.typ === EnumToken.UrlFunctionTokenType) { + + // const token = (value as FunctionToken).chi.find((t: Token) => t.typ === EnumToken.StringTokenType) as StringToken; + + // if (token != null && urlTokenMatcher.test((token as StringToken).val)) { + + // Object.assign(token, { + // typ: EnumToken.UrlTokenTokenType, + // val: (token as StringToken).val.slice(1, -1), + // }); + // } + // } } if ( diff --git a/test/specs/code/at-rules.js b/test/specs/code/at-rules.js index d6d74e0b..f9120a29 100644 --- a/test/specs/code/at-rules.js +++ b/test/specs/code/at-rules.js @@ -414,7 +414,7 @@ supports((selector(h2 > p)) and (font-tech(color-COLRv1))) { `).then((result) => expect(result.code).equals(``)); }); - it('import #28', function () { + it('import #29', function () { return transform(` @import "theme.css" layer("bar"); diff --git a/test/specs/code/block.js b/test/specs/code/block.js index 23d91a5a..7f5d437e 100644 --- a/test/specs/code/block.js +++ b/test/specs/code/block.js @@ -946,6 +946,20 @@ div-2 { div-4 { background-image: if() } +}`)); + }); + + it('transform-origin #47', function () { + const file = ` + + .xl\:origin-bottom-left { + transform-origin: bottom left; + } +`; + return transform(file, { + beautify: true + }).then(result => expect(result.code).equals(`.xl:origin-bottom-left { + transform-origin: 0 100% }`)); }); } diff --git a/test/specs/code/validation.js b/test/specs/code/validation.js index cfcf2a0a..1ace4019 100644 --- a/test/specs/code/validation.js +++ b/test/specs/code/validation.js @@ -578,6 +578,24 @@ html, body, div, span, applet, object, iframe, validation: true }).then(result => expect(result.code).equals(`.markdown-body .highlight pre:has(>.zeroclipboard-container,~.zeroclipboard-container,+.zeroclipboard-container ) { min-height: 52px +}`)).then(() => done(), () => done()); + }); + + it('selector validation #29', function (done) { + + transform(` +@document url(https://www.example.com/) { + h1 { + color: green + } +} +`, { + beautify: true, + validation: true + }).then(result => expect(result.code).equals(`@document https://www.example.com/ { + h1 { + color: green + } }`)).then(() => done(), () => done()); }); }); diff --git a/tools/index.ts b/tools/index.ts deleted file mode 100644 index d8263dbe..00000000 --- a/tools/index.ts +++ /dev/null @@ -1,3 +0,0 @@ - -// @ts-ignore -export * from './properties'; \ No newline at end of file diff --git a/tools/shorthand.ts b/tools/shorthand.ts index b0b67a1d..d132c679 100644 --- a/tools/shorthand.ts +++ b/tools/shorthand.ts @@ -4,758 +4,863 @@ import type { ShorthandDef, ShorthandMapType, ShorthandPropertyType, - ShorthandType + ShorthandType, + SinglePropertyTypeMapping, } from "../src/@types/index.d.ts"; -import {writeFile} from "node:fs/promises"; +import { writeFile } from "node:fs/promises"; function createProperties(data: ShorthandPropertyType) { - const map: string = data.map; return { - [data.shorthand]: {...data}, ...data.properties.reduce((acc, property: string) => { - - return Object.assign(acc, { - [property]: { - map, - shorthand: data.shorthand - } - }); - }, {}) - } + [data.shorthand]: { ...data }, + ...data.properties.reduce( + (acc, property: string) => { + return Object.assign(acc, { + [property]: { + map, + shorthand: data.shorthand, + }, + }); + }, + {}, + ), + }; } function createMap(data: ShorthandDef, fields: Array) { + return fields.reduce( + (acc, curr: ShorthandType) => { + Object.assign(acc[data.shorthand].properties, { + [curr.shorthand]: { ...(curr).properties }, + }); - return fields.reduce((acc, curr: ShorthandType) => { - - Object.assign(acc[data.shorthand].properties, { - [curr.shorthand]: {...(curr).properties} - }); - - return Object.assign(acc, { - - [curr.shorthand]: { - shorthand: data.shorthand - } - }); - }, { - [data.shorthand]: { - ...data, - properties: {} - } - }) + return Object.assign(acc, { + [curr.shorthand]: { + shorthand: data.shorthand, + }, + }); + }, + { + [data.shorthand]: { + ...data, + properties: {}, + }, + }, + ); } export const map: ShorthandMapType = ([ - [ { - shorthand: 'flex-flow', + shorthand: "flex-flow", pattern: `flex-direction flex-wrap`, keywords: [], - default: ['row', 'nowrap'] + default: ["row", "nowrap"], }, [ { - shorthand: 'flex-direction', + shorthand: "flex-direction", properties: { - - keywords: ['row', 'row-reverse', 'column', 'column-reverse'], - default: ['row'], - types: [] - } + keywords: ["row", "row-reverse", "column", "column-reverse"], + default: ["row"], + types: [], + }, }, { - shorthand: 'flex-wrap', + shorthand: "flex-wrap", properties: { - - keywords: ['wrap', 'nowrap', 'wrap-reverse'], - default: ['nowrap'], - types: [] - } - } - ] + keywords: ["wrap", "nowrap", "wrap-reverse"], + default: ["nowrap"], + types: [], + }, + }, + ], ], [ { - shorthand: 'flex-flow', + shorthand: "flex-flow", pattern: `flex-direction flex-wrap`, keywords: [], - default: ['row', 'nowrap'] + default: ["row", "nowrap"], }, [ { - shorthand: 'flex-direction', + shorthand: "flex-direction", properties: { - - keywords: ['row', 'row-reverse', 'column', 'column-reverse'], - default: ['row'], - types: [] - } + keywords: ["row", "row-reverse", "column", "column-reverse"], + default: ["row"], + types: [], + }, }, { - shorthand: 'flex-wrap', + shorthand: "flex-wrap", properties: { - - keywords: ['wrap', 'nowrap', 'wrap-reverse'], - default: ['nowrap'], - types: [] - } - } - ] + keywords: ["wrap", "nowrap", "wrap-reverse"], + default: ["nowrap"], + types: [], + }, + }, + ], ], [ { - shorthand: 'container', - pattern: 'container-name container-type', + shorthand: "container", + pattern: "container-name container-type", keywords: [], - default: [] + default: [], }, [ { - shorthand: 'container-name', + shorthand: "container-name", properties: { - required: true, multiple: true, - keywords: ['none'], - default: ['none'], - types: ['Iden', 'DashedIden'] - } + keywords: ["none"], + default: ["none"], + types: ["Iden", "DashedIden"], + }, }, { - shorthand: 'container-type', + shorthand: "container-type", properties: { - - previous: 'container-name', + previous: "container-name", prefix: { - typ: 'Literal', - val: '/' + typ: "Literal", + val: "/", }, - keywords: ['size', 'inline-size', 'normal'], - default: ['normal'], - types: [] - } - } - ] + keywords: ["size", "inline-size", "normal"], + default: ["normal"], + types: [], + }, + }, + ], ], [ { - shorthand: 'flex', + shorthand: "flex", pattern: `flex-grow flex-shrink flex-basis`, - keywords: ['auto', 'none', 'initial'], + keywords: ["auto", "none", "initial"], default: [], mapping: { - '0 1 auto': 'initial', - '0 0 auto': 'none', - '1 1 auto': 'auto', - } + "0 1 auto": "initial", + "0 0 auto": "none", + "1 1 auto": "auto", + }, }, [ { - shorthand: 'flex-grow', + shorthand: "flex-grow", properties: { - required: true, keywords: [], default: [], - types: ['Number'] - } + types: ["Number"], + }, }, { - shorthand: 'flex-shrink', + shorthand: "flex-shrink", properties: { - keywords: [], default: [], - types: ['Number'] - } + types: ["Number"], + }, }, { - shorthand: 'flex-basis', + shorthand: "flex-basis", properties: { - - keywords: ['max-content', 'min-content', 'fit-content', 'fit-content', 'content', 'auto'], + keywords: ["max-content", "min-content", "fit-content", "fit-content", "content", "auto"], default: [], - types: ['Length', 'Perc'], - } - } - ] + types: ["Length", "Perc"], + }, + }, + ], ], [ { - shorthand: 'columns', - pattern: 'column-count column-width', - keywords: ['auto'], - default: ['auto', 'auto auto'], + shorthand: "columns", + pattern: "column-count column-width", + keywords: ["auto"], + default: ["auto", "auto auto"], }, [ { - shorthand: 'column-count', + shorthand: "column-count", properties: { - - keywords: ['auto'], - default: ['auto'], - types: ['Number'] - } + keywords: ["auto"], + default: ["auto"], + types: ["Number"], + }, }, { - shorthand: 'column-width', + shorthand: "column-width", properties: { - - keywords: ['auto'], - default: ['auto'], - types: ['Length'] - } - } - ] + keywords: ["auto"], + default: ["auto"], + types: ["Length"], + }, + }, + ], ], [ { - shorthand: 'transition', + shorthand: "transition", multiple: true, separator: { - typ: 'Comma' + typ: "Comma", }, - pattern: 'transition-property transition-duration transition-timing-function transition-delay transition-behavior', - keywords: ['none', 'all'], - default: ['0s', '0ms', 'all', 'ease', 'none', 'normal'], + pattern: + "transition-property transition-duration transition-timing-function transition-delay transition-behavior", + keywords: ["none", "all"], + default: ["0s", "0ms", "all", "ease", "none", "normal"], mapping: { - 'cubic-bezier(.25,.1,.25,1)': 'ease', - 'cubic-bezier(0,0,1,1)': 'linear', - 'cubic-bezier(.42,0,1,1)': 'ease-in', - 'cubic-bezier(0,0,.58,1)': 'ease-out', - 'cubic-bezier(.42,0,.58,.42)': 'ease-in-out' - } + "cubic-bezier(.25,.1,.25,1)": "ease", + "cubic-bezier(0,0,1,1)": "linear", + "cubic-bezier(.42,0,1,1)": "ease-in", + "cubic-bezier(0,0,.58,1)": "ease-out", + "cubic-bezier(.42,0,.58,.42)": "ease-in-out", + }, }, [ { - shorthand: 'transition-property', + shorthand: "transition-property", properties: { - - keywords: ['none', 'all'], - default: ['all'], - types: ['Iden'] - } + keywords: ["none", "all"], + default: ["all"], + types: ["Iden"], + }, }, { - shorthand: 'transition-duration', + shorthand: "transition-duration", properties: { - keywords: [], - default: ['0s', '0ms', 'normal'], - types: ['Time'] - } + default: ["0s", "0ms", "normal"], + types: ["Time"], + }, }, { - shorthand: 'transition-timing-function', + shorthand: "transition-timing-function", properties: { - - keywords: ['ease', 'ease-in', 'ease-out', 'ease-in-out', 'linear', 'step-start', 'step-end'], - default: ['ease'], - types: ['TimingFunction'], + keywords: ["ease", "ease-in", "ease-out", "ease-in-out", "linear", "step-start", "step-end"], + default: ["ease"], + types: ["TimingFunction"], mapping: { - 'cubic-bezier(.25,.1,.25,1)': 'ease', - 'cubic-bezier(0,0,1,1)': 'linear', - 'cubic-bezier(.42,0,1,1)': 'ease-in', - 'cubic-bezier(0,0,.58,1)': 'ease-out', - 'cubic-bezier(.42,0,.58,.42)': 'ease-in-out' - } - } + "cubic-bezier(.25,.1,.25,1)": "ease", + "cubic-bezier(0,0,1,1)": "linear", + "cubic-bezier(.42,0,1,1)": "ease-in", + "cubic-bezier(0,0,.58,1)": "ease-out", + "cubic-bezier(.42,0,.58,.42)": "ease-in-out", + }, + }, }, { - shorthand: 'transition-delay', + shorthand: "transition-delay", properties: { - keywords: [], - default: ['0s'], - types: ['Time'] - } + default: ["0s"], + types: ["Time"], + }, }, { - shorthand: 'transition-behavior', + shorthand: "transition-behavior", properties: { - - keywords: ['normal', 'allow-discrete'], - default: ['normal'], - types: [] - } - } - ] + keywords: ["normal", "allow-discrete"], + default: ["normal"], + types: [], + }, + }, + ], ], [ { - shorthand: 'animation', + shorthand: "animation", separator: { - typ: 'Comma' + typ: "Comma", }, - pattern: 'animation-name animation-duration animation-timing-function animation-delay animation-iteration-count animation-direction animation-fill-mode animation-play-state animation-timeline', - default: ['1', '0s', '0ms', 'none', 'ease', 'normal', 'running', 'auto'] + pattern: + "animation-name animation-duration animation-timing-function animation-delay animation-iteration-count animation-direction animation-fill-mode animation-play-state animation-timeline", + default: ["1", "0s", "0ms", "none", "ease", "normal", "running", "auto"], }, [ { - shorthand: 'animation-name', + shorthand: "animation-name", properties: { - - keywords: ['none'], - default: ['none'], - types: ['Iden'] - } + keywords: ["none"], + default: ["none"], + types: ["Iden"], + }, }, { - shorthand: 'animation-duration', + shorthand: "animation-duration", properties: { - keywords: ['auto'], - default: ['0s', '0ms', 'auto'], - types: ['Time'], + keywords: ["auto"], + default: ["0s", "0ms", "auto"], + types: ["Time"], mapping: { - 'auto': '0s' - } - } + auto: "0s", + }, + }, }, { - shorthand: 'animation-timing-function', + shorthand: "animation-timing-function", properties: { - keywords: ['ease', 'ease-in', 'ease-out', 'ease-in-out', 'linear', 'step-start', 'step-end'], - default: ['ease'], - types: ['TimingFunction'], + keywords: ["ease", "ease-in", "ease-out", "ease-in-out", "linear", "step-start", "step-end"], + default: ["ease"], + types: ["TimingFunction"], mapping: { - 'cubic-bezier(.25,.1,.25,1)': 'ease', - 'cubic-bezier(0,0,1,1)': 'linear', - 'cubic-bezier(.42,0,1,1)': 'ease-in', - 'cubic-bezier(0,0,.58,1)': 'ease-out', - 'cubic-bezier(.42,0,.58,.42)': 'ease-in-out' - } - } + "cubic-bezier(.25,.1,.25,1)": "ease", + "cubic-bezier(0,0,1,1)": "linear", + "cubic-bezier(.42,0,1,1)": "ease-in", + "cubic-bezier(0,0,.58,1)": "ease-out", + "cubic-bezier(.42,0,.58,.42)": "ease-in-out", + }, + }, }, { - shorthand: 'animation-delay', + shorthand: "animation-delay", properties: { keywords: [], - default: ['0s', '0ms'], - types: ['Time'] - } + default: ["0s", "0ms"], + types: ["Time"], + }, }, { - shorthand: 'animation-iteration-count', + shorthand: "animation-iteration-count", properties: { - keywords: ['infinite'], - default: ['1'], - types: ['Number'] - } + keywords: ["infinite"], + default: ["1"], + types: ["Number"], + }, }, { - shorthand: 'animation-direction', + shorthand: "animation-direction", properties: { - keywords: ['normal', 'reverse', 'alternate', 'alternate-reverse'], - default: ['normal'], - types: [] - } + keywords: ["normal", "reverse", "alternate", "alternate-reverse"], + default: ["normal"], + types: [], + }, }, { - shorthand: 'animation-fill-mode', + shorthand: "animation-fill-mode", properties: { - keywords: ['none', 'forwards', 'backwards', 'both'], - default: ['none'], - types: [] - } + keywords: ["none", "forwards", "backwards", "both"], + default: ["none"], + types: [], + }, }, { - shorthand: 'animation-play-state', + shorthand: "animation-play-state", properties: { - keywords: ['running', 'paused'], - default: ['running'], - types: [] - } + keywords: ["running", "paused"], + default: ["running"], + types: [], + }, }, { - shorthand: 'animation-timeline', + shorthand: "animation-timeline", properties: { - keywords: ['none', 'auto'], - default: ['auto'], - types: ['DashedIden', 'TimelineFunction'] - } - } - ] + keywords: ["none", "auto"], + default: ["auto"], + types: ["DashedIden", "TimelineFunction"], + }, + }, + ], ], [ { - shorthand: 'text-emphasis', - pattern: 'text-emphasis-color text-emphasis-style', - default: ['none', 'currentcolor'] + shorthand: "text-emphasis", + pattern: "text-emphasis-color text-emphasis-style", + default: ["none", "currentcolor"], }, [ { - shorthand: 'text-emphasis-style', + shorthand: "text-emphasis-style", properties: { - - keywords: ['none', 'filled', 'open', 'dot', 'circle', 'double-circle', 'triangle', 'sesame'], - default: ['none'], - types: ['String'] - } + keywords: ["none", "filled", "open", "dot", "circle", "double-circle", "triangle", "sesame"], + default: ["none"], + types: ["String"], + }, }, { - shorthand: 'text-emphasis-color', + shorthand: "text-emphasis-color", properties: { - default: ['currentcolor'], - types: ['Color'] - } - } - ] + default: ["currentcolor"], + types: ["Color"], + }, + }, + ], ], [ { - shorthand: 'border', - pattern: 'border-color border-style border-width', - keywords: ['none'], - default: ['0', 'none'] + shorthand: "border", + pattern: "border-color border-style border-width", + keywords: ["none"], + default: ["0", "none"], }, [ { - shorthand: 'border-color', - properties: {} + shorthand: "border-color", + properties: {}, }, { - shorthand: 'border-style', - properties: {} + shorthand: "border-style", + properties: {}, }, { - shorthand: 'border-width', - properties: {} - } - ] + shorthand: "border-width", + properties: {}, + }, + ], ], [ { - shorthand: 'list-style', - pattern: 'list-style-type list-style-position list-style-image', - keywords: ['none', 'outside'], - default: ['none', 'outside'] + shorthand: "list-style", + pattern: "list-style-type list-style-position list-style-image", + keywords: ["none", "outside"], + default: ["none", "outside"], }, [ { - shorthand: 'list-style-position', + shorthand: "list-style-position", properties: { types: [], - default: ['outside'], - keywords: ['inside', 'outside'], - } + default: ["outside"], + keywords: ["inside", "outside"], + }, }, { - shorthand: 'list-style-image', + shorthand: "list-style-image", properties: { - default: ['none'], - keywords: ['node'], - types: ['UrlFunc', 'ImageFunc'] - } + default: ["none"], + keywords: ["node"], + types: ["UrlFunc", "ImageFunc"], + }, }, { - shorthand: 'list-style-type', - properties: - { - types: ['String', 'Iden', 'Symbols'], - default: ['disc'], - keywords: ['disc', 'circle', 'square', 'decimal', 'decimal-leading-zero', 'lower-roman', 'upper-roman', 'lower-greek', 'lower-latin', 'upper-latin', 'none'] - } - } - ] + shorthand: "list-style-type", + properties: { + types: ["String", "Iden", "Symbols"], + default: ["disc"], + keywords: [ + "disc", + "circle", + "square", + "decimal", + "decimal-leading-zero", + "lower-roman", + "upper-roman", + "lower-greek", + "lower-latin", + "upper-latin", + "none", + ], + }, + }, + ], ], [ { - shorthand: 'overflow', - pattern: 'overflow-x overflow-y', - keywords: ['auto', 'visible', 'hidden', 'clip', 'scroll'], + shorthand: "overflow", + pattern: "overflow-x overflow-y", + keywords: ["auto", "visible", "hidden", "clip", "scroll"], default: [], mapping: { - 'visible visible': 'visible', - 'auto auto': 'auto', - 'hidden hidden': 'hidden', - 'scroll scroll': 'scroll' - } + "visible visible": "visible", + "auto auto": "auto", + "hidden hidden": "hidden", + "scroll scroll": "scroll", + }, }, [ { - shorthand: 'overflow-x', + shorthand: "overflow-x", properties: { - default: [], types: [], - keywords: ['auto', 'visible', 'hidden', 'clip', 'scroll'] - } + keywords: ["auto", "visible", "hidden", "clip", "scroll"], + }, }, { - shorthand: 'overflow-y', + shorthand: "overflow-y", properties: { default: [], types: [], - keywords: ['auto', 'visible', 'hidden', 'clip', 'scroll'] - } - } - ] + keywords: ["auto", "visible", "hidden", "clip", "scroll"], + }, + }, + ], ], [ { - shorthand: 'outline', - pattern: 'outline-color outline-style outline-width', - keywords: ['none'], - default: ['0', 'none', 'currentcolor'] + shorthand: "outline", + pattern: "outline-color outline-style outline-width", + keywords: ["none"], + default: ["0", "none", "currentcolor"], }, [ { - shorthand: 'outline-color', + shorthand: "outline-color", properties: { - types: ['Color'], - default: ['currentcolor'], - keywords: ['currentcolor'], - } + types: ["Color"], + default: ["currentcolor"], + keywords: ["currentcolor"], + }, }, { - shorthand: 'outline-style', + shorthand: "outline-style", properties: { types: [], - default: ['none'], - keywords: ['auto', 'none', 'dotted', 'dashed', 'solid', 'double', 'groove', 'ridge', 'inset', 'outset'] - } + default: ["none"], + keywords: [ + "auto", + "none", + "dotted", + "dashed", + "solid", + "double", + "groove", + "ridge", + "inset", + "outset", + ], + }, }, { - shorthand: 'outline-width', + shorthand: "outline-width", properties: { - types: ['Length', 'Perc'], - default: ['medium'], - keywords: ['thin', 'medium', 'thick'] - } - } - ] + types: ["Length", "Perc"], + default: ["medium"], + keywords: ["thin", "medium", "thick"], + }, + }, + ], ], [ { - shorthand: 'font', - pattern: 'font-weight font-style font-size line-height font-stretch font-variant font-family', - keywords: ['caption', 'icon', 'menu', 'message-box', 'small-caption', 'status-bar', '-moz-window, ', '-moz-document, ', '-moz-desktop, ', '-moz-info, ', '-moz-dialog', '-moz-button', '-moz-pull-down-menu', '-moz-list', '-moz-field'], - default: [] + shorthand: "font", + pattern: "font-weight font-style font-size line-height font-stretch font-variant font-family", + keywords: [ + "caption", + "icon", + "menu", + "message-box", + "small-caption", + "status-bar", + "-moz-window, ", + "-moz-document, ", + "-moz-desktop, ", + "-moz-info, ", + "-moz-dialog", + "-moz-button", + "-moz-pull-down-menu", + "-moz-list", + "-moz-field", + ], + default: [], }, [ { - shorthand: 'font-weight', + shorthand: "font-weight", properties: { - types: ['Number'], - default: ['400', 'normal'], - keywords: ['normal', 'bold', 'lighter', 'bolder'], + types: ["Number"], + default: ["400", "normal"], + keywords: ["normal", "bold", "lighter", "bolder"], constraints: { value: { - min: '1', max: '1000' - } + min: "1", + max: "1000", + }, }, mapping: { - thin: '100', - hairline: '100', - 'extra light': '200', - 'ultra light': '200', - 'light': '300', - 'normal': '400', - regular: '400', - 'medium': '500', - 'semi bold': '600', - 'demi bold': '600', - 'bold': '700', - 'extra bold': '800', - 'ultra bold': '800', - 'black': '900', - 'heavy': '900', - 'extra black': '950', - 'ultra black': '950' - } - } - }, - { - shorthand: 'font-style', - properties: { - types: ['Angle'], - default: ['normal'], - keywords: ['normal', 'italic', 'oblique'] - } - }, - { - shorthand: 'font-size', - properties: { - types: ['Length', 'Perc'], + thin: "100", + hairline: "100", + "extra light": "200", + "ultra light": "200", + light: "300", + normal: "400", + regular: "400", + medium: "500", + "semi bold": "600", + "demi bold": "600", + bold: "700", + "extra bold": "800", + "ultra bold": "800", + black: "900", + heavy: "900", + "extra black": "950", + "ultra black": "950", + }, + }, + }, + { + shorthand: "font-style", + properties: { + types: ["Angle"], + default: ["normal"], + keywords: ["normal", "italic", "oblique"], + }, + }, + { + shorthand: "font-size", + properties: { + types: ["Length", "Perc"], default: [], - keywords: ['xx-small', 'x-small', 'small', 'medium', 'large', 'x-large', 'xx-large', 'xxx-large', 'larger', 'smaller'], - required: true - } + keywords: [ + "xx-small", + "x-small", + "small", + "medium", + "large", + "x-large", + "xx-large", + "xxx-large", + "larger", + "smaller", + ], + required: true, + }, }, { - shorthand: 'line-height', + shorthand: "line-height", properties: { - types: ['Length', 'Perc', 'Number'], - default: ['normal'], - keywords: ['normal'], - previous: 'font-size', + types: ["Length", "Perc", "Number"], + default: ["normal"], + keywords: ["normal"], + previous: "font-size", prefix: { - typ: 'Literal', - val: '/' - } - } + typ: "Literal", + val: "/", + }, + }, }, { - shorthand: 'font-stretch', + shorthand: "font-stretch", properties: { - types: ['Perc'], - default: ['normal'], - keywords: ['ultra-condensed', 'extra-condensed', 'condensed', 'semi-condensed', 'normal', 'semi-expanded', 'expanded', 'extra-expanded', 'ultra-expanded'], + types: ["Perc"], + default: ["normal"], + keywords: [ + "ultra-condensed", + "extra-condensed", + "condensed", + "semi-condensed", + "normal", + "semi-expanded", + "expanded", + "extra-expanded", + "ultra-expanded", + ], mapping: { - 'ultra-condensed': '50%', - 'extra-condensed': '62.5%', - 'condensed': '75%', - 'semi-condensed': '87.5%', - 'normal': '100%', - 'semi-expanded': '112.5%', - 'expanded': '125%', - 'extra-expanded': '150%', - 'ultra-expanded': '200%' - } - } + "ultra-condensed": "50%", + "extra-condensed": "62.5%", + condensed: "75%", + "semi-condensed": "87.5%", + normal: "100%", + "semi-expanded": "112.5%", + expanded: "125%", + "extra-expanded": "150%", + "ultra-expanded": "200%", + }, + }, }, { - shorthand: 'font-variant', + shorthand: "font-variant", properties: { types: [], - default: ['normal'], - keywords: ['normal', 'none', 'common-ligatures', 'no-common-ligatures', 'discretionary-ligatures', 'no-discretionary-ligatures', 'historical-ligatures', 'no-historical-ligatures', 'contextual', 'no-contextual', 'historical-forms', 'small-caps', 'all-small-caps', 'petite-caps', 'all-petite-caps', 'unicase', 'titling-caps', 'ordinal', 'slashed-zero', 'lining-nums', 'oldstyle-nums', 'proportional-nums', 'tabular-nums', 'diagonal-fractions', 'stacked-fractions', 'ordinal', 'slashed-zero', 'ruby', 'jis78', 'jis83', 'jis90', 'jis04', 'simplified', 'traditional', 'full-width', 'proportional-width', 'ruby', 'sub', 'super', 'text', 'emoji', 'unicode'] - } + default: ["normal"], + keywords: [ + "normal", + "none", + "common-ligatures", + "no-common-ligatures", + "discretionary-ligatures", + "no-discretionary-ligatures", + "historical-ligatures", + "no-historical-ligatures", + "contextual", + "no-contextual", + "historical-forms", + "small-caps", + "all-small-caps", + "petite-caps", + "all-petite-caps", + "unicase", + "titling-caps", + "ordinal", + "slashed-zero", + "lining-nums", + "oldstyle-nums", + "proportional-nums", + "tabular-nums", + "diagonal-fractions", + "stacked-fractions", + "ordinal", + "slashed-zero", + "ruby", + "jis78", + "jis83", + "jis90", + "jis04", + "simplified", + "traditional", + "full-width", + "proportional-width", + "ruby", + "sub", + "super", + "text", + "emoji", + "unicode", + ], + }, }, { - shorthand: 'font-family', + shorthand: "font-family", properties: { - types: ['String', 'Iden'], + types: ["String", "Iden"], default: [], - keywords: ['serif', 'sans-serif', 'monospace', 'cursive', 'fantasy', 'system-ui', 'ui-serif', 'ui-sans-serif', 'ui-monospace', 'ui-rounded', 'math', 'emoji', 'fangsong'], + keywords: [ + "serif", + "sans-serif", + "monospace", + "cursive", + "fantasy", + "system-ui", + "ui-serif", + "ui-sans-serif", + "ui-monospace", + "ui-rounded", + "math", + "emoji", + "fangsong", + ], required: true, multiple: true, separator: { - typ: 'Comma' - } - } - } - ] + typ: "Comma", + }, + }, + }, + ], ], [ { - shorthand: 'background', - pattern: 'background-attachment background-origin background-clip background-color background-image background-repeat background-position background-size', - keywords: ['none'], - default: ['0 0', 'none', 'auto', 'repeat', 'transparent', '#0000', 'scroll', 'padding-box', 'border-box'], + shorthand: "background", + pattern: + "background-attachment background-origin background-clip background-color background-image background-repeat background-position background-size", + keywords: ["none"], + default: ["0 0", "none", "auto", "repeat", "transparent", "#0000", "scroll", "padding-box", "border-box"], multiple: true, set: { - - 'background-origin': ['background-clip'] + "background-origin": ["background-clip"], }, - separator: {typ: 'Comma'} + separator: { typ: "Comma" }, }, [ { - shorthand: 'background-repeat', + shorthand: "background-repeat", properties: { types: [], - default: ['repeat'], + default: ["repeat"], multiple: true, - keywords: ['repeat-x', 'repeat-y', 'repeat', 'space', 'round', 'no-repeat'], + keywords: ["repeat-x", "repeat-y", "repeat", "space", "round", "no-repeat"], mapping: { - 'repeat no-repeat': 'repeat-x', - 'no-repeat repeat': 'repeat-y', - 'repeat repeat': 'repeat', - 'space space': 'space', - 'round round': 'round', - 'no-repeat no-repeat': 'no-repeat' - } - } + "repeat no-repeat": "repeat-x", + "no-repeat repeat": "repeat-y", + "repeat repeat": "repeat", + "space space": "space", + "round round": "round", + "no-repeat no-repeat": "no-repeat", + }, + }, }, { - shorthand: 'background-color', + shorthand: "background-color", properties: { - types: ['Color'], - default: ['#0000', 'transparent'], + types: ["Color"], + default: ["#0000", "transparent"], multiple: true, - keywords: [] - } + keywords: [], + }, }, { - shorthand: 'background-image', + shorthand: "background-image", properties: { - types: ['UrlFunc', 'ImageFunc'], - default: ['none'], - keywords: ['none'] - } + types: ["UrlFunc", "ImageFunc"], + default: ["none"], + keywords: ["none"], + }, }, { - shorthand: 'background-attachment', + shorthand: "background-attachment", properties: { types: [], - default: ['scroll'], + default: ["scroll"], multiple: true, - keywords: ['scroll', 'fixed', 'local'] - } + keywords: ["scroll", "fixed", "local"], + }, }, { - shorthand: 'background-clip', + shorthand: "background-clip", properties: { types: [], - default: ['border-box'], + default: ["border-box"], multiple: true, - keywords: ['border-box', 'padding-box', 'content-box', 'text'] - } + keywords: ["border-box", "padding-box", "content-box", "text"], + }, }, { - shorthand: 'background-origin', + shorthand: "background-origin", properties: { types: [], - default: ['padding-box'], + default: ["padding-box"], multiple: true, - keywords: ['border-box', 'padding-box', 'content-box'] - } + keywords: ["border-box", "padding-box", "content-box"], + }, }, { - shorthand: 'background-position', + shorthand: "background-position", properties: { multiple: true, - types: ['Perc', 'Length'], - default: ['0 0', 'top left', 'left top'], - keywords: ['top', 'left', 'center', 'bottom', 'right'], + types: ["Perc", "Length"], + default: ["0 0", "top left", "left top"], + keywords: ["top", "left", "center", "bottom", "right"], mapping: { - left: '0', - top: '0', - center: '50%', - 'center center': '50%', - '50% 50%': '50%', - bottom: '100%', - right: '100%' + left: "0", + top: "0", + center: "50%", + "center center": "50%", + "50% 50%": "50%", + bottom: "100%", + right: "100%", }, constraints: { mapping: { - max: 2 - } - } - } + max: 2, + }, + }, + }, }, { - shorthand: 'background-size', + shorthand: "background-size", properties: { multiple: true, - previous: 'background-position', - prefix: {typ: 'Literal', val: '/'}, - types: ['Perc', 'Length'], - default: ['auto', 'auto auto'], - keywords: ['auto', 'cover', 'contain'], + previous: "background-position", + prefix: { typ: "Literal", val: "/" }, + types: ["Perc", "Length"], + default: ["auto", "auto auto"], + keywords: ["auto", "cover", "contain"], mapping: { - 'auto auto': 'auto' - } - } - } - ] - ] + "auto auto": "auto", + }, + }, + }, + ], + ], // @ts-ignore -]).reduce((acc: ShorthandMapType, data: ShorthandMapType[]) => Object.assign(acc, createMap(...data)), {}); +]).reduce( + (acc: ShorthandMapType, data: ShorthandMapType[]) => Object.assign(acc, createMap(...data)), + {}, +); /* @@ -769,123 +874,153 @@ export const map: ShorthandMapType = ([ */ export const properties: PropertySetType = [ { - shorthand: 'gap', - properties: ['row-gap', 'column-gap'], - types: ['Length', 'Perc'], + shorthand: "gap", + properties: ["row-gap", "column-gap"], + types: ["Length", "Perc"], multiple: false, separator: null, - keywords: ['normal'] + keywords: ["normal"], }, { - shorthand: 'inset', - properties: ['top', 'right', 'bottom', 'left'], - types: ['Length', 'Perc'], + shorthand: "inset", + properties: ["top", "right", "bottom", "left"], + types: ["Length", "Perc"], multiple: false, separator: null, - keywords: ['auto'] + keywords: ["auto"], }, { - shorthand: 'margin', - properties: ['margin-top', 'margin-right', 'margin-bottom', 'margin-left'], - types: ['Length', 'Perc'], + shorthand: "margin", + properties: ["margin-top", "margin-right", "margin-bottom", "margin-left"], + types: ["Length", "Perc"], multiple: false, separator: null, - keywords: ['auto'] + keywords: ["auto"], }, { - shorthand: 'padding', - properties: ['padding-top', 'padding-right', 'padding-bottom', 'padding-left'], - types: ['Length', 'Perc'], + shorthand: "padding", + properties: ["padding-top", "padding-right", "padding-bottom", "padding-left"], + types: ["Length", "Perc"], // multiple: false, // separator:null , - keywords: [] + keywords: [], }, { - shorthand: 'border-radius', - properties: ['border-top-left-radius', 'border-top-right-radius', 'border-bottom-right-radius', 'border-bottom-left-radius'], - types: ['Length', 'Perc'], + shorthand: "border-radius", + properties: [ + "border-top-left-radius", + "border-top-right-radius", + "border-bottom-right-radius", + "border-bottom-left-radius", + ], + types: ["Length", "Perc"], multiple: true, separator: { - typ: 'Literal', - val: '/' + typ: "Literal", + val: "/", }, - keywords: [] + keywords: [], }, { - shorthand: 'border-width', - map: 'border', - properties: [ - 'border-top-width', - 'border-right-width', - 'border-bottom-width', - 'border-left-width' - ], - types: ['Length', 'Perc'], + shorthand: "border-width", + map: "border", + properties: ["border-top-width", "border-right-width", "border-bottom-width", "border-left-width"], + types: ["Length", "Perc"], // multiple: false, // separator: null, - default: ['medium'], - keywords: ['thin', 'medium', 'thick'] + default: ["medium"], + keywords: ["thin", "medium", "thick"], }, { - shorthand: 'border-style', - map: 'border', - properties: ['border-top-style', 'border-right-style', 'border-bottom-style', 'border-left-style'], + shorthand: "border-style", + map: "border", + properties: ["border-top-style", "border-right-style", "border-bottom-style", "border-left-style"], types: [], // multiple: false, // separator: null, - default: ['none'], - keywords: ['none', 'hidden', 'dotted', 'dashed', 'solid', 'double', 'groove', 'ridge', 'inset', 'outset'] + default: ["none"], + keywords: ["none", "hidden", "dotted", "dashed", "solid", "double", "groove", "ridge", "inset", "outset"], }, { - shorthand: 'border-color', - map: 'border', - properties: ['border-top-color', 'border-right-color', 'border-bottom-color', 'border-left-color'], - types: ['Color'], + shorthand: "border-color", + map: "border", + properties: ["border-top-color", "border-right-color", "border-bottom-color", "border-left-color"], + types: ["Color"], // multiple: false, // separator: null, - default: ['currentcolor'], - keywords: [] + default: ["currentcolor"], + keywords: [], }, { - shorthand: 'grid-row', - properties: [ - 'grid-row-start', - 'grid-row-end' - ], - types: ['Iden', 'Number'], + shorthand: "grid-row", + properties: ["grid-row-start", "grid-row-end"], + types: ["Iden", "Number"], multiple: true, valueSeparator: { - typ: 'Literal', - val: '/' + typ: "Literal", + val: "/", }, - default: ['auto'], - keywords: ['auto', 'span'] - } -].reduce((acc: PropertySetType, data) => { - - if (data.map) { - - // console.debug({data}); + default: ["auto"], + keywords: ["auto", "span"], + }, +].reduce( + (acc: PropertySetType, data) => { + if (data.map) { + // console.debug({data}); - // @ts-ignore - (map[data.map].properties[data.shorthand]).types = data.types; - // @ts-ignore - (map[data.map].properties[data.shorthand]).default = data.default; - // @ts-ignore - (map[data.map].properties[data.shorthand]).keywords = data.keywords; + // @ts-ignore + (map[data.map].properties[data.shorthand]).types = data.types; + // @ts-ignore + (map[data.map].properties[data.shorthand]).default = data.default; + // @ts-ignore + (map[data.map].properties[data.shorthand]).keywords = data.keywords; - // @ts-ignore - // (map[data.shorthand]).types = data.types; - // @ts-ignore - // (map[data.shorthand]).keywords = data.keywords; + // @ts-ignore + // (map[data.shorthand]).types = data.types; + // @ts-ignore + // (map[data.shorthand]).keywords = data.keywords; + } - } + return Object.assign(acc, createProperties(data)); + }, + {}, +); - return Object.assign(acc, createProperties(data)); -}, {}); +// @ts-expect-error +export const property = { + "transform-origin": { + pattern: [ + ['left|center|right', 'top|center|bottom', ''], + ['left|center|right', 'top|center|bottom'], + ['center|left|right|center|top|bottom|'], + ], + mapping: { + "center": { + typ: "Perc", + val: 50, + }, + "left": { + typ: "Perc", + val: 0, + }, + "right": { + typ: "Perc", + val: 100, + }, + "top": { + typ: "Perc", + val: 0, + }, + "bottom": { + typ: "Perc", + val: 100, + } + }, + }, +} as Record; -const result = JSON.stringify({properties, map}); +const result = JSON.stringify({ properties, map, property }); -await writeFile(import.meta.dirname + '/../src/config.json', result); +await writeFile(import.meta.dirname + "/../src/config.json", result); -console.debug(result); \ No newline at end of file +console.debug(result); diff --git a/typedoc.json b/typedoc.json index 71588150..a0d525e6 100644 --- a/typedoc.json +++ b/typedoc.json @@ -1,8 +1,6 @@ { "$schema": "https://typedoc.org/schema.json", - "entryPoints": [ - "./src" - ], + "entryPoints": ["./src"], "readme": "files/index.md", "entryPointStrategy": "resolve", "navigationLinks": { @@ -11,27 +9,11 @@ "Playground": "https://tbela99.github.io/css-parser/playground/", "GitHub": "https://github.com/tbela99/css-parser" }, - "plugin": [ - "typedoc-material-theme" - ], + "plugin": ["typedoc-material-theme"], "out": "docs", - "projectDocuments": [ - "files/index.md" - ], - "groupOrder": [ - "Functions", - "Classes", - "TypeAlias", - "Enumerations", - "*" - ], - "categoryOrder": [ - "Functions", - "Classes", - "TypeAlias", - "Enumerations", - "*" - ], + "projectDocuments": ["files/index.md"], + "groupOrder": ["Functions", "Classes", "TypeAlias", "Enumerations", "*"], + "categoryOrder": ["Functions", "Classes", "TypeAlias", "Enumerations", "*"], "kindSortOrder": [ "Document", "Project", @@ -58,5 +40,6 @@ "Interface", "Reference" ], - "json": "docs/typedoc.json" -} \ No newline at end of file + "json": "docs/typedoc.json", + "customCss": "./files/assets/typedoc-custom.css" +} From cef61ef2eaa428badb69bc766e070a97969e0688 Mon Sep 17 00:00:00 2001 From: Thierry Bela Nanga Date: Mon, 15 Jun 2026 16:57:09 -0400 Subject: [PATCH 02/26] reorganize documentation #127 --- README.md | 1065 +---------------- dist/index-umd-web.js | 8 +- dist/index.cjs | 8 +- dist/index.d.ts | 8 +- dist/lib/ast/clone.d.ts | 11 + dist/lib/ast/expand.d.ts | 14 + dist/lib/ast/features/calc.d.ts | 10 + dist/lib/ast/features/if.d.ts | 10 + dist/lib/ast/features/index.d.ts | 6 + dist/lib/ast/features/inlinecssvariables.d.ts | 15 + dist/lib/ast/features/prefix.d.ts | 8 + dist/lib/ast/features/shorthand.d.ts | 12 + dist/lib/ast/features/transform.d.ts | 10 + dist/lib/ast/features/type.d.ts | 15 + dist/lib/ast/find.d.ts | 165 +++ dist/lib/ast/find.js | 8 +- dist/lib/ast/math/expression.d.ts | 18 + dist/lib/ast/math/math.d.ts | 6 + dist/lib/ast/minify.d.ts | 19 + dist/lib/ast/transform/compute.d.ts | 8 + dist/lib/ast/transform/matrix.d.ts | 22 + dist/lib/ast/transform/minify.d.ts | 5 + dist/lib/ast/transform/perspective.d.ts | 3 + dist/lib/ast/transform/rotate.d.ts | 12 + dist/lib/ast/transform/scale.d.ts | 6 + dist/lib/ast/transform/skew.d.ts | 4 + dist/lib/ast/transform/translate.d.ts | 6 + dist/lib/ast/transform/utils.d.ts | 9 + dist/lib/ast/types.d.ts | 903 ++++++++++++++ dist/lib/ast/walk.d.ts | 162 +++ dist/lib/fs/resolve.d.ts | 20 + dist/lib/parser/declaration/list.d.ts | 17 + dist/lib/parser/declaration/map.d.ts | 15 + dist/lib/parser/declaration/set.d.ts | 9 + dist/lib/parser/node.d.ts | 7 + dist/lib/parser/parse.d.ts | 107 ++ dist/lib/parser/tokenize.d.ts | 57 + dist/lib/parser/utils/at-rule-container.d.ts | 5 + .../utils/at-rule-font-feature-values.d.ts | 5 + dist/lib/parser/utils/at-rule-generic.d.ts | 5 + dist/lib/parser/utils/at-rule-import.d.ts | 5 + dist/lib/parser/utils/at-rule-media.d.ts | 5 + dist/lib/parser/utils/at-rule-page.d.ts | 5 + dist/lib/parser/utils/at-rule-support.d.ts | 5 + dist/lib/parser/utils/at-rule-token.d.ts | 1 + dist/lib/parser/utils/at-rule-when-else.d.ts | 5 + dist/lib/parser/utils/at-rule.d.ts | 5 + dist/lib/parser/utils/cache.d.ts | 6 + dist/lib/parser/utils/config.d.ts | 2 + dist/lib/parser/utils/declaration-list.d.ts | 5 + dist/lib/parser/utils/declaration.d.ts | 18 + dist/lib/parser/utils/eq.d.ts | 1 + dist/lib/parser/utils/hash.d.ts | 21 + dist/lib/parser/utils/selector.d.ts | 5 + dist/lib/parser/utils/text.d.ts | 3 + dist/lib/parser/utils/token.d.ts | 14 + dist/lib/parser/utils/type.d.ts | 2 + dist/lib/renderer/render.d.ts | 28 + dist/lib/renderer/sourcemap/lib/encode.d.ts | 1 + dist/lib/renderer/sourcemap/sourcemap.d.ts | 26 + dist/lib/syntax/color/a98rgb.d.ts | 2 + dist/lib/syntax/color/cmyk.d.ts | 10 + dist/lib/syntax/color/color-mix.d.ts | 2 + dist/lib/syntax/color/color.d.ts | 42 + dist/lib/syntax/color/hex.d.ts | 16 + dist/lib/syntax/color/hsl.d.ts | 20 + dist/lib/syntax/color/hsv.d.ts | 2 + dist/lib/syntax/color/hwb.d.ts | 21 + dist/lib/syntax/color/lab.d.ts | 25 + dist/lib/syntax/color/lch.d.ts | 23 + dist/lib/syntax/color/oklab.d.ts | 22 + dist/lib/syntax/color/oklch.d.ts | 20 + dist/lib/syntax/color/p3.d.ts | 6 + dist/lib/syntax/color/prophotorgb.d.ts | 2 + dist/lib/syntax/color/rec2020.d.ts | 2 + dist/lib/syntax/color/relativecolor.d.ts | 13 + dist/lib/syntax/color/rgb.d.ts | 20 + dist/lib/syntax/color/srgb.d.ts | 23 + dist/lib/syntax/color/utils/components.d.ts | 2 + dist/lib/syntax/color/utils/distance.d.ts | 18 + dist/lib/syntax/color/utils/matrix.d.ts | 6 + dist/lib/syntax/color/xyz.d.ts | 5 + dist/lib/syntax/color/xyzd50.d.ts | 4 + dist/lib/syntax/constants.d.ts | 67 ++ dist/lib/syntax/syntax.d.ts | 38 + dist/lib/validation/config.d.ts | 14 + dist/lib/validation/json.d.ts | 2 + dist/lib/validation/match.d.ts | 38 + dist/lib/validation/parser/parse.d.ts | 8 + dist/lib/validation/parser/typedef.d.ts | 95 ++ dist/lib/validation/utils/list.d.ts | 4 + dist/lib/validation/utils/whitespace.d.ts | 2 + dist/node.d.ts | 207 ++++ dist/web.d.ts | 169 +++ files/assets/typedoc-custom.css | 1 + files/ast.md | 145 ++- files/css-module.md | 2 +- files/features.md | 2 +- files/index.md | 4 +- files/install.md | 2 +- files/minification.md | 137 +++ files/parsing.md | 145 ++- files/rendering.md | 90 +- files/usage.md | 2 +- files/validation.md | 110 +- src/lib/ast/find.ts | 16 +- src/lib/parser/node.ts | 8 - 107 files changed, 3476 insertions(+), 1104 deletions(-) create mode 100644 dist/lib/ast/clone.d.ts create mode 100644 dist/lib/ast/expand.d.ts create mode 100644 dist/lib/ast/features/calc.d.ts create mode 100644 dist/lib/ast/features/if.d.ts create mode 100644 dist/lib/ast/features/index.d.ts create mode 100644 dist/lib/ast/features/inlinecssvariables.d.ts create mode 100644 dist/lib/ast/features/prefix.d.ts create mode 100644 dist/lib/ast/features/shorthand.d.ts create mode 100644 dist/lib/ast/features/transform.d.ts create mode 100644 dist/lib/ast/features/type.d.ts create mode 100644 dist/lib/ast/find.d.ts create mode 100644 dist/lib/ast/math/expression.d.ts create mode 100644 dist/lib/ast/math/math.d.ts create mode 100644 dist/lib/ast/minify.d.ts create mode 100644 dist/lib/ast/transform/compute.d.ts create mode 100644 dist/lib/ast/transform/matrix.d.ts create mode 100644 dist/lib/ast/transform/minify.d.ts create mode 100644 dist/lib/ast/transform/perspective.d.ts create mode 100644 dist/lib/ast/transform/rotate.d.ts create mode 100644 dist/lib/ast/transform/scale.d.ts create mode 100644 dist/lib/ast/transform/skew.d.ts create mode 100644 dist/lib/ast/transform/translate.d.ts create mode 100644 dist/lib/ast/transform/utils.d.ts create mode 100644 dist/lib/ast/types.d.ts create mode 100644 dist/lib/ast/walk.d.ts create mode 100644 dist/lib/fs/resolve.d.ts create mode 100644 dist/lib/parser/declaration/list.d.ts create mode 100644 dist/lib/parser/declaration/map.d.ts create mode 100644 dist/lib/parser/declaration/set.d.ts create mode 100644 dist/lib/parser/node.d.ts create mode 100644 dist/lib/parser/parse.d.ts create mode 100644 dist/lib/parser/tokenize.d.ts create mode 100644 dist/lib/parser/utils/at-rule-container.d.ts create mode 100644 dist/lib/parser/utils/at-rule-font-feature-values.d.ts create mode 100644 dist/lib/parser/utils/at-rule-generic.d.ts create mode 100644 dist/lib/parser/utils/at-rule-import.d.ts create mode 100644 dist/lib/parser/utils/at-rule-media.d.ts create mode 100644 dist/lib/parser/utils/at-rule-page.d.ts create mode 100644 dist/lib/parser/utils/at-rule-support.d.ts create mode 100644 dist/lib/parser/utils/at-rule-token.d.ts create mode 100644 dist/lib/parser/utils/at-rule-when-else.d.ts create mode 100644 dist/lib/parser/utils/at-rule.d.ts create mode 100644 dist/lib/parser/utils/cache.d.ts create mode 100644 dist/lib/parser/utils/config.d.ts create mode 100644 dist/lib/parser/utils/declaration-list.d.ts create mode 100644 dist/lib/parser/utils/declaration.d.ts create mode 100644 dist/lib/parser/utils/eq.d.ts create mode 100644 dist/lib/parser/utils/hash.d.ts create mode 100644 dist/lib/parser/utils/selector.d.ts create mode 100644 dist/lib/parser/utils/text.d.ts create mode 100644 dist/lib/parser/utils/token.d.ts create mode 100644 dist/lib/parser/utils/type.d.ts create mode 100644 dist/lib/renderer/render.d.ts create mode 100644 dist/lib/renderer/sourcemap/lib/encode.d.ts create mode 100644 dist/lib/renderer/sourcemap/sourcemap.d.ts create mode 100644 dist/lib/syntax/color/a98rgb.d.ts create mode 100644 dist/lib/syntax/color/cmyk.d.ts create mode 100644 dist/lib/syntax/color/color-mix.d.ts create mode 100644 dist/lib/syntax/color/color.d.ts create mode 100644 dist/lib/syntax/color/hex.d.ts create mode 100644 dist/lib/syntax/color/hsl.d.ts create mode 100644 dist/lib/syntax/color/hsv.d.ts create mode 100644 dist/lib/syntax/color/hwb.d.ts create mode 100644 dist/lib/syntax/color/lab.d.ts create mode 100644 dist/lib/syntax/color/lch.d.ts create mode 100644 dist/lib/syntax/color/oklab.d.ts create mode 100644 dist/lib/syntax/color/oklch.d.ts create mode 100644 dist/lib/syntax/color/p3.d.ts create mode 100644 dist/lib/syntax/color/prophotorgb.d.ts create mode 100644 dist/lib/syntax/color/rec2020.d.ts create mode 100644 dist/lib/syntax/color/relativecolor.d.ts create mode 100644 dist/lib/syntax/color/rgb.d.ts create mode 100644 dist/lib/syntax/color/srgb.d.ts create mode 100644 dist/lib/syntax/color/utils/components.d.ts create mode 100644 dist/lib/syntax/color/utils/distance.d.ts create mode 100644 dist/lib/syntax/color/utils/matrix.d.ts create mode 100644 dist/lib/syntax/color/xyz.d.ts create mode 100644 dist/lib/syntax/color/xyzd50.d.ts create mode 100644 dist/lib/syntax/constants.d.ts create mode 100644 dist/lib/syntax/syntax.d.ts create mode 100644 dist/lib/validation/config.d.ts create mode 100644 dist/lib/validation/json.d.ts create mode 100644 dist/lib/validation/match.d.ts create mode 100644 dist/lib/validation/parser/parse.d.ts create mode 100644 dist/lib/validation/parser/typedef.d.ts create mode 100644 dist/lib/validation/utils/list.d.ts create mode 100644 dist/lib/validation/utils/whitespace.d.ts create mode 100644 dist/node.d.ts create mode 100644 dist/web.d.ts delete mode 100644 src/lib/parser/node.ts diff --git a/README.md b/README.md index 80817d8f..8f56cb81 100644 --- a/README.md +++ b/README.md @@ -43,126 +43,21 @@ $ deno add @tbela99/css-parser - @import rules flattening - experimental CSS prefix removal -## Online documentation - -See the full documentation at the [CSS Parser](https://tbela99.github.io/css-parser/docs) documentation site - ## Playground Try it [online](https://tbela99.github.io/css-parser/playground/) -## Import - -There are several ways to import the library into your application. - -### Node - -import as a module - -```javascript - -import {transform} from '@tbela99/css-parser'; - -// ... -``` - -### Deno - -import as a module - -```javascript - -import {transform} from '@tbela99/css-parser'; - -// ... -``` - -import as a CommonJS module - -```javascript - -const {transform} = require('@tbela99/css-parser/cjs'); - -// ... -``` - -### Web - -Programmatic import - -```javascript - -import {transform} from '@tbela99/css-parser/web'; - -// ... -``` - -Javascript module from cdn - -```html - - -``` - -Javascript module - -```javascript - - -``` - -Javascript umd module from cdn - -```html - - - -``` +- [Installation](https://tbela99.github.io/css-parser/docs/documents/Guide.Getting_Started.html) +- [Usage](https://tbela99.github.io/css-parser/docs/documents/Guide.Usage.html) +- [Parsing](https://tbela99.github.io/css-parser/docs/documents/Guide.Parsing.html) +- [Rendering](https://tbela99.github.io/css-parser/docs/documents/Guide.Rendering.html) +- [Validation](https://tbela99.github.io/css-parser/docs/documents/Guide.Validation.html) +- [CSS Modules](https://tbela99.github.io/css-parser/docs/documents/Guide.CSS_Modules.html) +- [Minification](https://tbela99.github.io/css-parser/docs/documents/Guide.Minification.html) +- [Custom Transform](https://tbela99.github.io/css-parser/docs/documents/Guide.Custom_Transform.html) +- [Ast](https://tbela99.github.io/css-parser/docs/documents/Guide.Ast.html) ## Exported functions @@ -181,693 +76,6 @@ parseFile(filePathOrUrl: string, options?: ParseOptions = {}, asStream?: boolean ``` -## Transform - -Parse and render css in a single pass. - -### Example - -```javascript - -import {transform} from '@tbela99/css-parser'; - -const {ast, code, map, errors, stats} = await transform(css, {minify: true, resolveImport: true, cwd: 'files/css'}); -``` - -### Example - -Read from stdin with node using readable stream - -```typescript -import {transform} from "../src/node"; -import {Readable} from "node:stream"; -import type {TransformResult} from '../src/@types/index.d.ts'; - -const readableStream: ReadableStream = Readable.toWeb(process.stdin) as ReadableStream; -const result: TransformResult = await transform(readableStream, {beautify: true}); - -console.log(result.code); -``` - -### TransformOptions - -Include ParseOptions and RenderOptions - -#### ParseOptions - -> Minify Options - -- minify: boolean, optional. default to _true_. optimize ast. -- pass: number, optional. minification passes. default to 1 -- nestingRules: boolean, optional. automatically generated nested rules. -- expandNestingRules: boolean, optional. convert nesting rules into separate rules. will automatically set nestingRules - to false. -- expandIfSyntax: experimental, convert css if() function into legacy syntax. -- removeDuplicateDeclarations: boolean, optional. remove duplicate declarations. -- computeTransform: boolean, optional. compute css transform functions. -- computeShorthand: boolean, optional. compute shorthand properties. -- computeCalcExpression: boolean, optional. evaluate calc() expression -- inlineCssVariables: boolean, optional. replace some css variables with their actual value. they must be declared once - in the :root {} or html {} rule. -- removeEmpty: boolean, optional. remove empty rule lists from the ast. - -> CSS modules Options - -- module: boolean | ModuleCaseTransformEnum | ModuleScopeEnumOptions | ModuleOptions, optional. css modules options. - -> CSS Prefix Removal Options - -- removePrefix: boolean, optional. remove CSS prefixes. - -> Validation Options - -- validation: ValidationLevel | boolean, optional. enable validation. permitted values are: - - ValidationLevel.None: no validation - - ValidationLevel.Default: validate selectors and at-rules (default) - - ValidationLevel.All. validate all nodes - - true: same as ValidationLevel.All. - - false: same as ValidationLevel.None -- lenient: boolean, optional. preserve invalid tokens. - -> Sourcemap Options - -- src: string, optional. original css file location to be used with sourcemap, also used to resolve url(). -- sourcemap: boolean, optional. preserve node location data. - -> Ast Traversal Options - -- visitor: VisitorNodeMap, optional. node visitor used to transform the ast. - -> Urls and \@import Options - -- resolveImport: boolean, optional. replace @import rule by the content of the referenced stylesheet. -- resolveUrls: boolean, optional. resolve css 'url()' according to the parameters 'src' and 'cwd' - -> Misc Options -- removeCharset: boolean, optional. remove @charset. -- cwd: string, optional. destination directory used to resolve url(). -- signal: AbortSignal, optional. abort parsing. - -#### RenderOptions - -> Minify Options - -- beautify: boolean, optional. default to _false_. beautify css output. -- minify: boolean, optional. default to _true_. minify css values. -- withParents: boolean, optional. render this node and its parents. -- removeEmpty: boolean, optional. remove empty rule lists from the ast. -- expandNestingRules: boolean, optional. expand nesting rules. -- preserveLicense: boolean, force preserving comments starting with '/\*!' when minify is enabled. -- removeComments: boolean, remove comments in generated css. -- convertColor: boolean | ColorType, convert colors to the specified color. default to ColorType.HEX. supported values are: - - true: same as ColorType.HEX - - false: no color conversion - - ColorType.HEX - - ColorType.RGB or ColorType.RGBA - - ColorType.HSL - - ColorType.HWB - - ColorType.CMYK or ColorType.DEVICE_CMYK - - ColorType.SRGB - - ColorType.SRGB_LINEAR - - ColorType.DISPLAY_P3 - - ColorType.PROPHOTO_RGB - - ColorType.A98_RGB - - ColorType.REC2020 - - ColorType.XYZ or ColorType.XYZ_D65 - - ColorType.XYZ_D50 - - ColorType.LAB - - ColorType.LCH - - ColorType.OKLAB - - ColorType.OKLCH - -> Sourcemap Options - -- sourcemap: boolean | 'inline', optional. generate sourcemap. - -> Misc Options - -- indent: string, optional. css indention string. uses space character by default. -- newLine: string, optional. new line character. -- output: string, optional. file where to store css. url() are resolved according to the specified value. no file is - created though. -- cwd: string, optional. destination directory used to resolve url(). - -## Parsing - -### Usage - -```javascript - -parse(css, parseOptions = {}) -``` - -### Example - -````javascript - -const {ast, errors, stats} = await parse(css); -```` - -## Rendering - -### Usage - -```javascript -render(ast, RenderOptions = {}); -``` - -### Examples - -Rendering ast - -```javascript -import {parse, render} from '@tbela99/css-parser'; - -const css = ` -@media screen and (min-width: 40em) { - .featurette-heading { - font-size: 50px; - } - .a { - color: red; - width: 3px; - } -} -`; - -const result = await parse(css, options); - -// print declaration without parents -console.error(render(result.ast.chi[0].chi[1].chi[1], {withParents: false})); -// -> width:3px - -// print declaration with parents -console.debug(render(result.ast.chi[0].chi[1].chi[1], {withParents: true})); -// -> @media screen and (min-width:40em){.a{width:3px}} - -``` - -### CSS Modules - -CSS modules features are fully supported. refer to the [CSS modules](https://tbela99.github.io/css-parser/docs/documents/Guide.CSS_modules.html) documentation for more information. - -```javascript -import {transform} from '@tbela99/css-parser'; - -const css = ` -.table { - border-collapse: collapse; - width: 100%; -} - -.table td, .table th { - border: 1px solid #ddd; - padding: 8px; -} - -.table tr:nth-child(even){background-color: #f2f2f2;} - -.table tr:hover {background-color: #ddd;} - -.table th { - padding-top: 12px; - padding-bottom: 12px; - text-align: left; - background-color: #4CAF50; - color: white; -} -`; - -const result = await transform(css, {module: true}); - -// css code -console.log(result.code); -// css mapping -console.log(result.mapping); -``` - -### Convert colors - -```javascript -import {transform, ColorType} from '@tbela99/css-parser'; - - -const css = ` -.hsl { color: #b3222280; } -`; -const result: TransformResult = await transform(css, { - beautify: true, - convertColor: ColorType.SRGB -}); - -console.log(result.css); - -``` - -result - -```css -.hsl { - color: color(srgb .7019607843137254 .13333333333333333 .13333333333333333/50%) -} -``` - -### Merge similar rules - -CSS - -```css - -.clear { - width: 0; - height: 0; - color: transparent; -} - -.clearfix:before { - - height: 0; - width: 0; -} -``` - -```javascript - -import {transform} from '@tbela99/css-parser'; - -const result = await transform(css); - -``` - -Result - -```css -.clear, .clearfix:before { - height: 0; - width: 0 -} - -.clear { - color: #0000 -} -``` - -### Automatic CSS Nesting - -CSS - -```javascript -const {parse, render} = require("@tbela99/css-parser/cjs"); - -const css = ` -table.colortable td { - text-align:center; -} -table.colortable td.c { - text-transform:uppercase; -} -table.colortable td:first-child, table.colortable td:first-child+td { - border:1px solid black; -} -table.colortable th { - text-align:center; - background:black; - color:white; -} -`; - -const result = await parse(css, {nestingRules: true}).then(result => render(result.ast, {minify: false}).code); -``` - -Result - -```css -table.colortable { - & td { - text-align: center; - - &.c { - text-transform: uppercase - } - - &:first-child, &:first-child + td { - border: 1px solid #000 - } - } - - & th { - text-align: center; - background: #000; - color: #fff - } -} -``` - -### CSS Validation - -CSS - -```css - -#404 { - --animate-duration: 1s; -} - -.s, #404 { - --animate-duration: 1s; -} - -.s [type="text" { - --animate-duration: 1s; -} - -.s [type="text"]] -{ - --animate-duration: 1s; -} - -.s [type="text"] { - --animate-duration: 1s; -} - -.s [type="text" i] { - --animate-duration: 1s; -} - -.s [type="text" s] -{ - --animate-duration: 1s -; -} - -.s [type="text" b] -{ - --animate-duration: 1s; -} - -.s [type="text" b],{ - --animate-duration: 1s -; -} - -.s [type="text" b] -+ { - --animate-duration: 1s; -} - -.s [type="text" b] -+ b { - --animate-duration: 1s; -} - -.s [type="text" i] + b { - --animate-duration: 1s; -} - - -.s [type="text"())]{ - --animate-duration: 1s; -} -.s(){ - --animate-duration: 1s; -} -.s:focus { - --animate-duration: 1s; -} -``` - -with validation enabled - -```javascript -import {parse, render} from '@tbela99/css-parser'; - -const options = {minify: true, validate: true}; -const {code} = await parse(css, options).then(result => render(result.ast, {minify: false})); -// -console.debug(code); -``` - -```css -.s:is([type=text],[type=text i],[type=text s],[type=text i]+b,:focus) { - --animate-duration: 1s -} -``` - -with validation disabled - -```javascript -import {parse, render} from '@tbela99/css-parser'; - -const options = {minify: true, validate: false}; -const {code} = await parse(css, options).then(result => render(result.ast, {minify: false})); -// -console.debug(code); -``` - -```css -.s:is([type=text],[type=text i],[type=text s],[type=text b],[type=text b]+b,[type=text i]+b,:focus) { - --animate-duration: 1s -} -``` - -### Nested CSS Expansion - -CSS - -```css -table.colortable { - & td { - text-align: center; - - &.c { - text-transform: uppercase - } - - &:first-child, &:first-child + td { - border: 1px solid #000 - } - } - - & th { - text-align: center; - background: #000; - color: #fff - } -} -``` - -Javascript - -```javascript -import {parse, render} from '@tbela99/css-parser'; - -const options = {minify: true}; -const {code} = await parse(css, options).then(result => render(result.ast, {minify: false, expandNestingRules: true})); -// -console.debug(code); -``` - -Result - -```css - -table.colortable td { - text-align: center; -} - -table.colortable td.c { - text-transform: uppercase; -} - -table.colortable td:first-child, table.colortable td:first-child + td { - border: 1px solid black; -} - -table.colortable th { - text-align: center; - background: black; - color: white; -} -``` - -### CSS if() function expansion - -```typescript - -const css = ` -button { - background: linear-gradient( - if(media(min-width: 768px): to right; else: to bottom), - if(style(--dark-mode): #333; else: #fff), - if(style(--dark-mode): #000; else: #ccc) - ); -}`; - -result = await transform(css, { - - beautify: true, - expandIfSyntax: true - } - -}); - -console.log(result.code); -``` - -output - -```css -button { - background: linear-gradient(to bottom,#fff,#ccc); - @media (min-width:768px) { - background: linear-gradient(to right,#fff,#ccc); - @container style(--dark-mode) { - background: linear-gradient(to right,#333,#000) - } - } - @container style(--dark-mode) { - background: linear-gradient(to bottom,#333,#000) - } -} -``` - -### Calc() resolution - -```javascript - -import {parse, render} from '@tbela99/css-parser'; - -const css = ` -a { - -width: calc(100px * log(625, 5)); -} -.foo-bar { - width: calc(100px * 2); - height: calc(((75.37% - 63.5px) - 900px) + (2 * 100px)); - max-width: calc(3.5rem + calc(var(--bs-border-width) * 2)); -} -`; - -const prettyPrint = await parse(css).then(result => render(result.ast, {minify: false}).code); - -``` - -result - -```css -a { - width: 400px; -} - -.foo-bar { - width: 200px; - height: calc(75.37% - 763.5px); - max-width: calc(3.5rem + var(--bs-border-width) * 2) -} -``` - -### CSS variable inlining - -```javascript - -import {parse, render} from '@tbela99/css-parser'; - -const css = ` - -:root { - ---preferred-width: 20px; -} -.foo-bar { - - width: calc(calc(var(--preferred-width) + 1px) / 3 + 5px); - height: calc(100% / 4);} -` - -const prettyPrint = await parse(css, {inlineCssVariables: true}).then(result => render(result.ast, {minify: false}).code); - -``` - -result - -```css -.foo-bar { - width: 12px; - height: 25% -} - -``` - -### CSS variable inlining and relative color - -```javascript - -import {parse, render} from '@tbela99/css-parser'; - -const css = ` - -:root { ---color: green; -} -._19_u :focus { - color: hsl(from var(--color) calc(h * 2) s l); - -} -` - -const prettyPrint = await parse(css, {inlineCssVariables: true}).then(result => render(result.ast, {minify: false}).code); - -``` - -result - -```css -._19_u :focus { - color: navy -} - -``` - -### CSS variable inlining and relative color - -```javascript - -import {parse, render} from '@tbela99/css-parser'; - -const css = ` - -html { --bluegreen: oklab(54.3% -22.5% -5%); } -.overlay { - background: oklab(from var(--bluegreen) calc(1.0 - l) calc(a * 0.8) b); -} -` - -const prettyPrint = await parse(css, {inlineCssVariables: true}).then(result => render(result.ast, {minify: false}).code); - -``` - -result - -```css -.overlay { - background: #0c6464 -} - -``` - -# Node Walker - -```javascript - -import {walk} from '@tbela99/css-parser'; - -for (const {node, parent, root} of walk(ast)) { - - // do something -} -``` - ## AST ### Comment @@ -985,256 +193,3 @@ for (const {node, parent, root} of walk(ast)) { ## Performance - [x] flatten @import - -## Node Transformation - -Ast can be transformed using node visitors - -### Example 1: Declaration - -the visitor is called for any declaration encountered - -```typescript - -import {AstDeclaration, ParserOptions} from "../src/@types"; - -const options: ParserOptions = { - - visitor: { - - Declaration: (node: AstDeclaration) => { - - if (node.nam == '-webkit-transform') { - - node.nam = 'transform' - } - } - } -} - -const css = ` - -.foo { - -webkit-transform: scale(calc(100 * 2/ 15)); -} -`; - -const result = await transform(css, options); -console.debug(result.code); - -// .foo{transform:scale(calc(40/3))} -``` - -### Example 2: Declaration - -the visitor is called only on 'height' declarations - -```typescript - -import {AstDeclaration, EnumToken, LengthToken, ParserOptions, transform} from '@tbela99/css-parser'; - -const options: ParserOptions = { - - visitor: { - - Declaration: { - - // called only for height declaration - height: (node: AstDeclaration): AstDeclaration[] => { - - - return [ - node, - { - - typ: EnumToken.DeclarationNodeType, - nam: 'width', - val: [ - { - typ: EnumToken.LengthTokenType, - val: 3, - unit: 'px' - } - ] - } - ]; - } - } - } -}; - -const css = ` - -.foo { - height: calc(100px * 2/ 15); -} -.selector { -color: lch(from peru calc(l * 0.8) calc(c * 0.7) calc(h + 180)) -} -`; - -const result = await transform(css, options); -console.debug(result.code); - -// .foo{height:calc(40px/3);width:3px}.selector{color:#0880b0} - -``` - -### Example 3: At-Rule - -the visitor is called on any at-rule - -```typescript - -import {AstAtRule, ParserOptions} from "../src/@types"; -import {transform} from "../src/node"; - - -const options: ParserOptions = { - - visitor: { - - AtRule: (node: AstAtRule): AstAtRule => { - - if (node.nam == 'media') { - - return {...node, val: 'all'} - } - } - } -}; - -const css = ` - -@media screen { - - .foo { - - height: calc(100px * 2/ 15); - } -} -`; - -const result = await transform(css, options); -console.debug(result.code); - -// .foo{height:calc(40px/3)} - -``` - -### Example 4: At-Rule - -the visitor is called only for at-rule media - -```typescript - -import {AstAtRule, ParserOptions} from "../src/@types"; -import {transform} from "../src/node"; - -const options: ParserOptions = { - - visitor: { - - AtRule: { - - media: (node: AstAtRule): AstAtRule => { - - node.val = 'all'; - return node - } - } - } -}; - -const css = ` - -@media screen { - - .foo { - - height: calc(100px * 2/ 15); - } -} -`; - -const result = await transform(css, options); -console.debug(result.code); - -// .foo{height:calc(40px/3)} - -``` - -### Example 5: Rule - -the visitor is called on any Rule - -```typescript - -import {AstAtRule, ParserOptions} from "../src/@types"; -import {transform} from "../src/node"; - -const options: ParserOptions = { - - visitor: { - - Rule(node: AstRule): AstRule { - - node.sel = '.foo,.bar,.fubar' - return node; - } - } -}; - -const css = ` - - .foo { - - height: calc(100px * 2/ 15); - } -`; - -const result = await transform(css, options); -console.debug(result.code); - -// .foo,.bar,.fubar{height:calc(40px/3)} - -``` - -### Example 6: Rule - -Adding declarations to any rule - -```typescript - -import {AstRule, parseDeclarations, ParserOptions, transform} from '@tbela99/css-parser'; - -const options: ParserOptions = { - - removeEmpty: false, - visitor: { - - Rule: async (node: AstRule): Promise => { - - if (node.sel == '.foo') { - - node.chi.push(...await parseDeclarations('width: 3px')); - return node; - } - - return null; - } - } -}; - -const css = ` - -.foo { -} -`; - -const result = await transform(css, options); -console.debug(result.code); - -// .foo{width:3px} - -``` diff --git a/dist/index-umd-web.js b/dist/index-umd-web.js index 1b0d1ed6..5715db1d 100644 --- a/dist/index-umd-web.js +++ b/dist/index-umd-web.js @@ -21146,7 +21146,7 @@ } /** - * search the ast tree and return the first match + * Search the ast tree and return the first match * * ```ts * // find the first ast declaration node which name is 'aspect-ratio' @@ -21185,7 +21185,7 @@ return null; } /** - * search the ast tree by checking each node's value and return the first match + * search the ast tree by checking each node's value token and return the first match * * ```ts * // find the first ast node which contains the length token '30px' @@ -21200,7 +21200,7 @@ } `; - // find declaration which contain a '30px' + // find declaration which contain the length token '30px' const nodeMatcher = (value: Token) => return value.typ == EnumToken.LengthTokenType && (value as LengthToken).val == 30 && (value as LengthToken).unit == 'px' ; @@ -21277,7 +21277,7 @@ return result; } /** - * search the ast tree and return the last match + * Search the ast tree and return the last match. * * ```ts * // find the first ast declaration node which name is 'aspect-ratio' diff --git a/dist/index.cjs b/dist/index.cjs index 6b95725b..ab9fb212 100644 --- a/dist/index.cjs +++ b/dist/index.cjs @@ -21147,7 +21147,7 @@ function matchRepeatableSyntax(syntax, context, options) { } /** - * search the ast tree and return the first match + * Search the ast tree and return the first match * * ```ts * // find the first ast declaration node which name is 'aspect-ratio' @@ -21186,7 +21186,7 @@ function find(ast, matcher) { return null; } /** - * search the ast tree by checking each node's value and return the first match + * search the ast tree by checking each node's value token and return the first match * * ```ts * // find the first ast node which contains the length token '30px' @@ -21201,7 +21201,7 @@ button { } `; - // find declaration which contain a '30px' + // find declaration which contain the length token '30px' const nodeMatcher = (value: Token) => return value.typ == EnumToken.LengthTokenType && (value as LengthToken).val == 30 && (value as LengthToken).unit == 'px' ; @@ -21278,7 +21278,7 @@ function findAll(ast, matcher) { return result; } /** - * search the ast tree and return the last match + * Search the ast tree and return the last match. * * ```ts * // find the first ast declaration node which name is 'aspect-ratio' diff --git a/dist/index.d.ts b/dist/index.d.ts index ec33c529..f5303d64 100644 --- a/dist/index.d.ts +++ b/dist/index.d.ts @@ -4409,7 +4409,7 @@ declare function okLabDistance(okLab1: [number, number, number], okLab2: [number declare function isOkLabClose(color1: ColorToken, color2: ColorToken, threshold?: number): boolean; /** - * search the ast tree and return the first match + * Search the ast tree and return the first match * * ```ts * // find the first ast declaration node which name is 'aspect-ratio' @@ -4441,7 +4441,7 @@ button { */ declare function find(ast: AstNode$1, matcher: (node: AstNode$1) => boolean): AstNode$1 | null; /** - * search the ast tree by checking each node's value and return the first match + * search the ast tree by checking each node's value token and return the first match * * ```ts * // find the first ast node which contains the length token '30px' @@ -4456,7 +4456,7 @@ button { } `; - // find declaration which contain a '30px' + // find declaration which contain the length token '30px' const nodeMatcher = (value: Token) => return value.typ == EnumToken.LengthTokenType && (value as LengthToken).val == 30 && (value as LengthToken).unit == 'px' ; @@ -4508,7 +4508,7 @@ button { */ declare function findAll(ast: AstNode$1, matcher: (node: AstNode$1) => boolean): AstNode$1[]; /** - * search the ast tree and return the last match + * Search the ast tree and return the last match. * * ```ts * // find the first ast declaration node which name is 'aspect-ratio' diff --git a/dist/lib/ast/clone.d.ts b/dist/lib/ast/clone.d.ts new file mode 100644 index 00000000..9ccb71f0 --- /dev/null +++ b/dist/lib/ast/clone.d.ts @@ -0,0 +1,11 @@ +import type { AstNode } from "../../@types/index.d.ts"; +import type { Token } from "../../@types/token.d.ts"; +/** + * + * clone an ast node or value + * @param node + * @param cloneChildren + * @param cloneMap + * @returns + */ +export declare function cloneNode(node: AstNode | Token, cloneChildren?: boolean, cloneMap?: Map | null): AstNode | Token; diff --git a/dist/lib/ast/expand.d.ts b/dist/lib/ast/expand.d.ts new file mode 100644 index 00000000..4289f764 --- /dev/null +++ b/dist/lib/ast/expand.d.ts @@ -0,0 +1,14 @@ +import type { AstAtRule, AstNode, AstRule, AstStyleSheet } from "../../@types/index.d.ts"; +/** + * expand css nesting ast nodes + * @param ast + * + * @private + */ +export declare function expand(ast: AstStyleSheet | AstAtRule | AstRule): AstNode; +/** + * replace compound selector + * @param input + * @param replace + */ +export declare function replaceCompound(input: string, replace: string): string; diff --git a/dist/lib/ast/features/calc.d.ts b/dist/lib/ast/features/calc.d.ts new file mode 100644 index 00000000..5b9a7105 --- /dev/null +++ b/dist/lib/ast/features/calc.d.ts @@ -0,0 +1,10 @@ +import type { AstAtRule, AstNode, AstRule, ParserOptions } from "../../../@types/index.d.ts"; +import { EnumToken } from "../types.ts"; +import { FeatureWalkMode } from "./type.ts"; +export declare class ComputeCalcExpressionFeature { + accept: Set; + get ordering(): number; + get processMode(): FeatureWalkMode; + static register(options: ParserOptions): void; + run(ast: AstRule | AstAtRule): AstNode | null; +} diff --git a/dist/lib/ast/features/if.d.ts b/dist/lib/ast/features/if.d.ts new file mode 100644 index 00000000..5b9b0c9f --- /dev/null +++ b/dist/lib/ast/features/if.d.ts @@ -0,0 +1,10 @@ +import type { AstDeclaration, AstNode, ParserOptions } from "../../../@types/index.d.ts"; +import { EnumToken } from "../types.ts"; +import { FeatureWalkMode } from "./type.ts"; +export declare class ExpandIfFeature { + accept: Set; + get ordering(): number; + get processMode(): FeatureWalkMode; + static register(options: ParserOptions): void; + run(declaration: AstDeclaration): AstNode | null; +} diff --git a/dist/lib/ast/features/index.d.ts b/dist/lib/ast/features/index.d.ts new file mode 100644 index 00000000..c99d1db4 --- /dev/null +++ b/dist/lib/ast/features/index.d.ts @@ -0,0 +1,6 @@ +export * from './prefix.ts'; +export * from './inlinecssvariables.ts'; +export * from './shorthand.ts'; +export * from './calc.ts'; +export * from './transform.ts'; +export * from './if.ts'; diff --git a/dist/lib/ast/features/inlinecssvariables.d.ts b/dist/lib/ast/features/inlinecssvariables.d.ts new file mode 100644 index 00000000..c7121669 --- /dev/null +++ b/dist/lib/ast/features/inlinecssvariables.d.ts @@ -0,0 +1,15 @@ +import type { AstAtRule, AstNode, AstRule, AstStyleSheet, ParserOptions } from "../../../@types/index.d.ts"; +import { EnumToken } from "../types.ts"; +import { FeatureWalkMode } from "./type.ts"; +export declare class InlineCssVariablesFeature { + accept: Set; + get ordering(): number; + get processMode(): FeatureWalkMode; + static register(options: ParserOptions): void; + run(ast: AstRule | AstAtRule, options: ParserOptions | undefined, parent: AstRule | AstAtRule | AstStyleSheet, context: { + [key: string]: any; + }): AstNode | null; + cleanup(ast: AstStyleSheet, options: ParserOptions | undefined, context: { + [key: string]: any; + }): void; +} diff --git a/dist/lib/ast/features/prefix.d.ts b/dist/lib/ast/features/prefix.d.ts new file mode 100644 index 00000000..41470b70 --- /dev/null +++ b/dist/lib/ast/features/prefix.d.ts @@ -0,0 +1,8 @@ +import type { AstNode, ParserOptions } from "../../../@types/index.d.ts"; +import { FeatureWalkMode } from "./type.ts"; +export declare class ComputePrefixFeature { + get ordering(): number; + get processMode(): FeatureWalkMode; + static register(options: ParserOptions): void; + run(node: AstNode): AstNode | null; +} diff --git a/dist/lib/ast/features/shorthand.d.ts b/dist/lib/ast/features/shorthand.d.ts new file mode 100644 index 00000000..9f6112c9 --- /dev/null +++ b/dist/lib/ast/features/shorthand.d.ts @@ -0,0 +1,12 @@ +import { EnumToken } from "../types.ts"; +import type { AstAtRule, AstNode, AstRule, AstStyleSheet, ParserOptions, PropertyListOptions } from "../../../@types/index.d.ts"; +import { FeatureWalkMode } from "./type.ts"; +export declare class ComputeShorthandFeature { + accept: Set; + get ordering(): number; + get processMode(): FeatureWalkMode; + static register(options: ParserOptions): void; + run(ast: AstRule | AstAtRule, options: PropertyListOptions | undefined, parent: AstRule | AstAtRule | AstStyleSheet, context: { + [key: string]: any; + }): AstNode | null; +} diff --git a/dist/lib/ast/features/transform.d.ts b/dist/lib/ast/features/transform.d.ts new file mode 100644 index 00000000..dfad3ade --- /dev/null +++ b/dist/lib/ast/features/transform.d.ts @@ -0,0 +1,10 @@ +import type { AstAtRule, AstNode, AstRule, ParserOptions } from "../../../@types/index.d.ts"; +import { EnumToken } from "../types.ts"; +import { FeatureWalkMode } from "./type.ts"; +export declare class TransformCssFeature { + accept: Set; + get ordering(): number; + get processMode(): FeatureWalkMode; + static register(options: ParserOptions): void; + run(ast: AstRule | AstAtRule): AstNode | null; +} diff --git a/dist/lib/ast/features/type.d.ts b/dist/lib/ast/features/type.d.ts new file mode 100644 index 00000000..2aa322f2 --- /dev/null +++ b/dist/lib/ast/features/type.d.ts @@ -0,0 +1,15 @@ +/** + * feature walk mode + * + * @private + */ +export declare enum FeatureWalkMode { + /** + * pre process + */ + Pre = 1, + /** + * post process + */ + Post = 2 +} diff --git a/dist/lib/ast/find.d.ts b/dist/lib/ast/find.d.ts new file mode 100644 index 00000000..91be663d --- /dev/null +++ b/dist/lib/ast/find.d.ts @@ -0,0 +1,165 @@ +import type { Token } from "../../@types/token.d.ts"; +import type { AstNode, AstValueMatcher, TokenSearchResult } from "../../@types/ast.d.ts"; +/** + * Search the ast tree and return the first match + * + * ```ts + * // find the first ast declaration node which name is 'aspect-ratio' +import { find, EnumToken, transform } from "@tbela99/css-parser"; +import type { AstNode } from "@tbela99/css-parser"; + + * const css = ` + +button { + aspect-ratio: 1; + width: if(media(any-pointer: fine): 30px; else: 44px); +} + `; + + // find declaration which contain a '30px' + const nodeMatcher = (node: AstNode) => + return node.typ == EnumToken.DeclarationNodeType && (node as AstDeclaration).nam == 'aspect-ratio'; + + const result = await transform(css); + const node = find(result.ast, nodeMatcher); + + console.log({node}); + + ``` + * + * @param ast + * @param matcher + * @returns + */ +export declare function find(ast: AstNode, matcher: (node: AstNode) => boolean): AstNode | null; +/** + * search the ast tree by checking each node's value token and return the first match + * + * ```ts + * // find the first ast node which contains the length token '30px' +import { findByValue, EnumToken, transform } from "@tbela99/css-parser"; +import type { AstNode } from "@tbela99/css-parser"; + + * const css = ` + +button { + aspect-ratio: 1; + width: if(media(any-pointer: fine): 30px; else: 44px); +} + `; + + // find declaration which contain the length token '30px' + const nodeMatcher = (value: Token) => + return value.typ == EnumToken.LengthTokenType && (value as LengthToken).val == 30 && (value as LengthToken).unit == 'px' ; + + const result = await transform(css); + const { node, value } = findByValue(result.ast, nodeMatcher) ?? {}; + + console.log({node, value}); + + ``` + * + * @param ast + * @param matcher + * @returns + */ +export declare function findByValue(ast: AstNode, matcher: AstValueMatcher): { + node: AstNode; + value: TokenSearchResult; +} | null; +/** + * search the ast tree and return all matches + * + * ```ts + * // find the first ast declaration node which name is 'aspect-ratio' +import { findAll, EnumToken, transform } from "@tbela99/css-parser"; +import type { AstNode } from "@tbela99/css-parser"; + + * const css = ` + +button { + aspect-ratio: 1; + width: if(media(any-pointer: fine): 30px; else: 44px); +} + `; + + // find declaration which contain a '30px' + const nodeMatcher = (node: AstNode) => + return node.typ == EnumToken.DeclarationNodeType && (node as AstDeclaration).nam == 'aspect-ratio'; + + const result = await transform(css); + const nodes = findAll(result.ast, nodeMatcher); + + console.log({nodes}); + + ``` + * + * @param ast + * @param matcher + * @returns + */ +export declare function findAll(ast: AstNode, matcher: (node: AstNode) => boolean): AstNode[]; +/** + * Search the ast tree and return the last match. + * + * ```ts + * // find the first ast declaration node which name is 'aspect-ratio' +import { findLast, EnumToken, transform } from "@tbela99/css-parser"; +import type { AstNode } from "@tbela99/css-parser"; + + * const css = ` + +button { + aspect-ratio: 1; + width: if(media(any-pointer: fine): 30px; else: 44px); +} + `; + + // find declaration which contain a '30px' + const nodeMatcher = (node: AstNode) => + return node.typ == EnumToken.DeclarationNodeType && (node as AstDeclaration).nam == 'aspect-ratio'; + + const result = await transform(css); + const node = findLast(result.ast, nodeMatcher); + + console.log({node}); + + ``` + * + * @param ast + * @param matcher + * @returns + */ +export declare function findLast(ast: AstNode, matcher: (node: AstNode) => boolean): AstNode | null; +/** + * Find the node's value token of the specified ast node + * + * ```ts +// find the first ast declaration node which name is 'aspect-ratio' +import { findValue, EnumToken, transform } from "@tbela99/css-parser"; +import type { AstNode } from "@tbela99/css-parser"; + +const css = ` + +button { + aspect-ratio: 1; + width: if(media(any-pointer: fine): 30px; else: 44px); +} + `; + + // find declaration which contain a '30px' + const nodeMatcher = (node: AstNode) => + return node.typ == EnumToken.DeclarationNodeType && (node as AstDeclaration).nam == 'aspect-ratio'; + + const result = await transform(css); + const found = findValue(result.ast.chi[0], nodeMatcher); + + console.log({found}); // 'button' token of the selector + +``` + * + * @param ast + * @param matcher + * @returns + */ +export declare function findValue(ast: AstNode | Token, matcher: (node: AstNode, parent?: AstNode | Token | null, root?: AstNode | null, parents?: Generator | null) => boolean): TokenSearchResult | null; diff --git a/dist/lib/ast/find.js b/dist/lib/ast/find.js index fee14946..e75bdd0d 100644 --- a/dist/lib/ast/find.js +++ b/dist/lib/ast/find.js @@ -2,7 +2,7 @@ import { EnumToken } from './types.js'; import { walk, walkValues } from './walk.js'; /** - * search the ast tree and return the first match + * Search the ast tree and return the first match * * ```ts * // find the first ast declaration node which name is 'aspect-ratio' @@ -41,7 +41,7 @@ function find(ast, matcher) { return null; } /** - * search the ast tree by checking each node's value and return the first match + * search the ast tree by checking each node's value token and return the first match * * ```ts * // find the first ast node which contains the length token '30px' @@ -56,7 +56,7 @@ button { } `; - // find declaration which contain a '30px' + // find declaration which contain the length token '30px' const nodeMatcher = (value: Token) => return value.typ == EnumToken.LengthTokenType && (value as LengthToken).val == 30 && (value as LengthToken).unit == 'px' ; @@ -133,7 +133,7 @@ function findAll(ast, matcher) { return result; } /** - * search the ast tree and return the last match + * Search the ast tree and return the last match. * * ```ts * // find the first ast declaration node which name is 'aspect-ratio' diff --git a/dist/lib/ast/math/expression.d.ts b/dist/lib/ast/math/expression.d.ts new file mode 100644 index 00000000..4e2d6b5f --- /dev/null +++ b/dist/lib/ast/math/expression.d.ts @@ -0,0 +1,18 @@ +import type { BinaryExpressionToken, FunctionToken, Token } from "../../../@types/index.d.ts"; +/** + * evaluate an array of tokens + * @param tokens + */ +export declare function evaluate(tokens: Token[]): Token[]; +export declare function evaluateFunc(token: FunctionToken): Token[] | null; +/** + * convert BinaryExpression into an array + * @param token + */ +export declare function inlineExpression(token: Token): Token[]; +/** + * + * generate a binary expression tree + * @param tokens + */ +export declare function buildExpression(tokens: Token[]): BinaryExpressionToken; diff --git a/dist/lib/ast/math/math.d.ts b/dist/lib/ast/math/math.d.ts new file mode 100644 index 00000000..86574b0f --- /dev/null +++ b/dist/lib/ast/math/math.d.ts @@ -0,0 +1,6 @@ +import type { FractionToken } from "../../../@types/index.d.ts"; +import { EnumToken } from "../types.ts"; +export declare function gcd(x: number, y: number): number; +export declare function compute(a: number | FractionToken, b: number | FractionToken, op: EnumToken.Add | EnumToken.Sub | EnumToken.Mul | EnumToken.Div): number | FractionToken; +export declare function rem(...a: number[]): number; +export declare function simplify(a: number, b: number): [number, number]; diff --git a/dist/lib/ast/minify.d.ts b/dist/lib/ast/minify.d.ts new file mode 100644 index 00000000..7182265e --- /dev/null +++ b/dist/lib/ast/minify.d.ts @@ -0,0 +1,19 @@ +import type { AstNode, ErrorDescription, MinifyFeatureOptions, ParserOptions } from "../../@types/index.d.ts"; +/** + * apply minification rules to the ast tree + * @param ast + * @param options + * @param recursive + * @param errors + * @param nestingContent + * + * @private + */ +export declare function minify(ast: AstNode, options: ParserOptions | MinifyFeatureOptions, recursive: boolean, errors?: ErrorDescription[], nestingContent?: boolean): AstNode; +/** + * split selector string + * @param buffer + * + * @internal + */ +export declare function splitRule(buffer: string): string[][]; diff --git a/dist/lib/ast/transform/compute.d.ts b/dist/lib/ast/transform/compute.d.ts new file mode 100644 index 00000000..452ec746 --- /dev/null +++ b/dist/lib/ast/transform/compute.d.ts @@ -0,0 +1,8 @@ +import type { Token } from "../../../@types/token.d.ts"; +import type { Matrix } from "./type.d.ts"; +export declare function compute(transformLists: Token[]): { + matrix: Token; + cumulative: Token[]; + minified: Token[]; +} | null; +export declare function computeMatrix(transformList: Token[], matrixVar: Matrix): Matrix | null; diff --git a/dist/lib/ast/transform/matrix.d.ts b/dist/lib/ast/transform/matrix.d.ts new file mode 100644 index 00000000..c453acf8 --- /dev/null +++ b/dist/lib/ast/transform/matrix.d.ts @@ -0,0 +1,22 @@ +import type { FunctionToken, IdentToken, Token } from "../../../@types/index.d.ts"; +import type { Matrix } from "./type.d.ts"; +export declare function parseMatrix(mat: FunctionToken | IdentToken): Matrix | null; +export declare function matrix(values: [number, number, number, number, number, number] | [ + number, + number, + number, + number, + number, + number, + number, + number, + number, + number, + number, + number, + number, + number, + number, + number +]): Matrix | null; +export declare function serialize(matrix: Matrix): Token; diff --git a/dist/lib/ast/transform/minify.d.ts b/dist/lib/ast/transform/minify.d.ts new file mode 100644 index 00000000..3d424c7f --- /dev/null +++ b/dist/lib/ast/transform/minify.d.ts @@ -0,0 +1,5 @@ +import type { FunctionToken, Token } from "../../../@types/index.d.ts"; +import type { Matrix } from "./type.d.ts"; +export declare function minify(matrix: Matrix): Token[] | null; +export declare function eqMatrix(a: FunctionToken | Matrix, b: Token[]): boolean; +export declare function minifyTransformFunctions(transform: FunctionToken): FunctionToken; diff --git a/dist/lib/ast/transform/perspective.d.ts b/dist/lib/ast/transform/perspective.d.ts new file mode 100644 index 00000000..ec9f6c83 --- /dev/null +++ b/dist/lib/ast/transform/perspective.d.ts @@ -0,0 +1,3 @@ +import type { IdentToken } from "../../../@types/index.d.ts"; +import type { Matrix } from "./type.d.ts"; +export declare function perspective(x: number | IdentToken, from: Matrix): Matrix; diff --git a/dist/lib/ast/transform/rotate.d.ts b/dist/lib/ast/transform/rotate.d.ts new file mode 100644 index 00000000..d85793f0 --- /dev/null +++ b/dist/lib/ast/transform/rotate.d.ts @@ -0,0 +1,12 @@ +import type { Matrix } from "./type.d.ts"; +/** + * angle in radian + * @param angle + * @param x + * @param y + * @param z + * @param from + */ +export declare function rotate3D(angle: number, x: number, y: number, z: number, from: Matrix): Matrix; +export declare function rotate(angle: number, from: Matrix): Matrix; +export declare const rotateZ: typeof rotate; diff --git a/dist/lib/ast/transform/scale.d.ts b/dist/lib/ast/transform/scale.d.ts new file mode 100644 index 00000000..2fabbf02 --- /dev/null +++ b/dist/lib/ast/transform/scale.d.ts @@ -0,0 +1,6 @@ +import type { Matrix } from "./type.d.ts"; +export declare function scaleX(x: number, from: Matrix): Matrix; +export declare function scaleY(y: number, from: Matrix): Matrix; +export declare function scaleZ(z: number, from: Matrix): Matrix; +export declare function scale(x: number, y: number, from: Matrix): Matrix; +export declare function scale3d(x: number, y: number, z: number, from: Matrix): Matrix; diff --git a/dist/lib/ast/transform/skew.d.ts b/dist/lib/ast/transform/skew.d.ts new file mode 100644 index 00000000..689738ad --- /dev/null +++ b/dist/lib/ast/transform/skew.d.ts @@ -0,0 +1,4 @@ +import type { Matrix } from "./type.d.ts"; +export declare function skewX(x: number, from: Matrix): Matrix; +export declare function skewY(y: number, from: Matrix): Matrix; +export declare function skew(values: [number] | [number, number], from: Matrix): Matrix; diff --git a/dist/lib/ast/transform/translate.d.ts b/dist/lib/ast/transform/translate.d.ts new file mode 100644 index 00000000..e33efd9e --- /dev/null +++ b/dist/lib/ast/transform/translate.d.ts @@ -0,0 +1,6 @@ +import type { Matrix } from "./type.d.ts"; +export declare function translateX(x: number, from: Matrix): Matrix; +export declare function translateY(y: number, from: Matrix): Matrix; +export declare function translateZ(z: number, from: Matrix): Matrix; +export declare function translate(translate: [number] | [number, number], from: Matrix): Matrix; +export declare function translate3d(translate: [number, number, number], from: Matrix): Matrix; diff --git a/dist/lib/ast/transform/utils.d.ts b/dist/lib/ast/transform/utils.d.ts new file mode 100644 index 00000000..dd65b6bd --- /dev/null +++ b/dist/lib/ast/transform/utils.d.ts @@ -0,0 +1,9 @@ +import type { DecomposedMatrix3D, Matrix } from "./type.d.ts"; +export declare const epsilon = 0.00001; +export declare function identity(): Matrix; +export declare function multiply(matrixA: Matrix, matrixB: Matrix): Matrix; +export declare function round(number: number): number; +export declare function decompose(original: Matrix): DecomposedMatrix3D | null; +export declare function toZero(v: number[]): number[]; +export declare function toZero(v: Matrix): Matrix; +export declare function is2DMatrix(matrix: Matrix): boolean; diff --git a/dist/lib/ast/types.d.ts b/dist/lib/ast/types.d.ts new file mode 100644 index 00000000..a062cffe --- /dev/null +++ b/dist/lib/ast/types.d.ts @@ -0,0 +1,903 @@ +import type { LengthToken, NumberToken } from "../../@types"; +/** + * syntax validation enum + */ +export declare enum SyntaxValidationResult { + /** valid syntax */ + Valid = 0, + /** drop invalid syntax */ + Drop = 1, + /** preserve unknown at-rules, declarations and pseudo-classes */ + Lenient = 2 +} +/** + * enum of validation levels + */ +export declare enum ValidationLevel { + /** + * disable validation + */ + None = 0, + /** + * validate selectors + */ + Selector = 1, + /** + * validate at-rules + */ + AtRule = 2, + /** + * validate declarations + */ + Declaration = 4, + /** + * validate selectors and at-rules + */ + Default = 3,// selectors + at-rules + /** + * validate selectors, at-rules and declarations + */ + All = 7 +} +/** + * enum of all token types + */ +export declare enum EnumToken { + /** + * comment token + */ + CommentTokenType = 0, + /** + * cdata section token + */ + CDOCOMMTokenType = 1, + /** + * style sheet node type + */ + StyleSheetNodeType = 2, + /** + * at-rule node type + */ + AtRuleNodeType = 3, + /** + * rule node type + */ + RuleNodeType = 4, + /** + * declaration node type + */ + DeclarationNodeType = 5, + /** + * literal token type + */ + LiteralTokenType = 6, + /** + * identifier token type + */ + IdenTokenType = 7, + /** + * dashed identifier token type + */ + DashedIdenTokenType = 8, + /** + * comma token type + */ + CommaTokenType = 9, + /** + * colon token type + */ + ColonTokenType = 10, + /** + * semicolon token type + */ + SemiColonTokenType = 11, + /** + * number token type + */ + NumberTokenType = 12, + /** + * at-rule token type + */ + AtRuleTokenType = 13, + /** + * percentage token type + */ + PercentageTokenType = 14, + /** + * function token type + */ + FunctionTokenType = 15, + /** + * timeline function token type + */ + TimelineFunctionTokenType = 16, + /** + * timing function token type + */ + TimingFunctionTokenType = 17, + /** + * url function token type + */ + UrlFunctionTokenType = 18, + /** + * image function token type + */ + ImageFunctionTokenType = 19, + /** + * string token type + */ + StringTokenType = 20, + /** + * unclosed string token type + */ + UnclosedStringTokenType = 21, + /** + * dimension token type + */ + DimensionTokenType = 22, + /** + * length token type + */ + LengthTokenType = 23, + /** + * angle token type + */ + AngleTokenType = 24, + /** + * time token type + */ + TimeTokenType = 25, + /** + * frequency token type + */ + FrequencyTokenType = 26, + /** + * resolution token type + */ + ResolutionTokenType = 27, + /** + * hash token type + */ + HashTokenType = 28, + /** + * block start token type + */ + BlockStartTokenType = 29, + /** + * block end token type + */ + BlockEndTokenType = 30, + /** + * attribute start token type + */ + AttrStartTokenType = 31, + /** + * attribute end token type + */ + AttrEndTokenType = 32, + /** + * start parentheses token type + */ + StartParensTokenType = 33, + /** + * end parentheses token type + */ + EndParensTokenType = 34, + /** + * parentheses token type + */ + ParensTokenType = 35, + /** + * whitespace token type + */ + WhitespaceTokenType = 36, + /** + * include match token type + */ + IncludeMatchTokenType = 37, + /** + * dash match token type + */ + DashMatchTokenType = 38, + /** + * equal match token type + */ + EqualMatchTokenType = 39, + /** + * less than token type + */ + LtTokenType = 40, + /** + * less than or equal to token type + */ + LteTokenType = 41, + /** + * greater than token type + */ + GtTokenType = 42, + /** + * greater than or equal to token type + */ + GteTokenType = 43, + /** + * pseudo-class token type + */ + PseudoClassTokenType = 44, + /** + * pseudo-class function token type + */ + PseudoClassFuncTokenType = 45, + /** + * delimiter token type + */ + DelimTokenType = 46, + /** + * URL token type + */ + UrlTokenTokenType = 47, + /** + * end of file token type + */ + EOFTokenType = 48, + /** + * important token type + */ + ImportantTokenType = 49, + /** + * color token type + */ + ColorTokenType = 50, + /** + * attribute token type + */ + AttrTokenType = 51, + /** + * bad comment token type + */ + BadCommentTokenType = 52, + /** + * bad cdo token type + */ + BadCdoTokenType = 53, + /** + * bad URL token type + */ + BadUrlTokenType = 54, + /** + * bad string token type + */ + BadStringTokenType = 55, + /** + * binary expression token type + */ + BinaryExpressionTokenType = 56, + /** + * unary expression token type + */ + UnaryExpressionTokenType = 57, + /** + * flex token type + */ + FlexTokenType = 58, + /** + * token list token type + */ + ListToken = 59, + /** + * addition token type + */ + Add = 60, + /** + * multiplication token type + */ + Mul = 61, + /** + * division token type + */ + Div = 62, + /** + * subtraction token type + */ + Sub = 63, + /** + * column combinator token type + */ + ColumnCombinatorTokenType = 64, + /** + * contain match token type + */ + ContainMatchTokenType = 65, + /** + * start match token type + */ + StartMatchTokenType = 66, + /** + * end match token type + */ + EndMatchTokenType = 67, + /** + * match expression token type + */ + MatchExpressionTokenType = 68, + /** + * namespace attribute token type + */ + NameSpaceAttributeTokenType = 69, + /** + * fraction token type + */ + FractionTokenType = 70, + /** + * identifier list token type + */ + IdenListTokenType = 71, + /** + * grid template function token type + */ + GridTemplateFuncTokenType = 72, + /** + * keyframe rule node type + */ + KeyFramesRuleNodeType = 73, + /** + * class selector token type + */ + ClassSelectorTokenType = 74, + /** + * universal selector token type + */ + UniversalSelectorTokenType = 75, + /** + * child combinator token type + */ + ChildCombinatorTokenType = 76,// > + /** + * descendant combinator token type + */ + DescendantCombinatorTokenType = 77,// whitespace + /** + * next sibling combinator token type + */ + NextSiblingCombinatorTokenType = 78,// + + /** + * subsequent sibling combinator token type + */ + SubsequentSiblingCombinatorTokenType = 79,// ~ + /** + * nesting selector token type + */ + NestingSelectorTokenType = 80,// & + /** + * invalid rule token type + */ + InvalidRuleNodeType = 81, + /** + * invalid class selector token type + */ + InvalidClassSelectorTokenType = 82, + /** + * invalid attribute token type + */ + InvalidAttrTokenType = 83, + /** + * invalid at rule token type + */ + InvalidAtRuleNodeType = 84, + /** + * media query condition token type + */ + MediaQueryConditionTokenType = 85, + /** + * media feature token type + */ + MediaFeatureTokenType = 86, + /** + * media feature only token type + */ + OnlyTokenType = 87, + /** + * media feature not token type + */ + NotTokenType = 88, + /** + * media feature and token type + */ + AndTokenType = 89, + /** + * media feature or token type + */ + OrTokenType = 90, + /** + * pseudo page token type + */ + PseudoPageTokenType = 91, + /** + * pseudo element token type + */ + PseudoElementTokenType = 92, + /** + * keyframe at rule node type + */ + KeyframesAtRuleNodeType = 93, + /** + * invalid declaration node type + */ + InvalidDeclarationNodeType = 94, + /** + * composes token node type + */ + ComposesSelectorNodeType = 95, + /** + * css variable token type + */ + CssVariableTokenType = 96, + /** + * css variable import token type + */ + CssVariableImportTokenType = 97, + /** + * css variable declaration map token type + */ + CssVariableDeclarationMapTokenType = 98, + /** + * media range query token type + */ + MediaRangeQueryTokenType = 99, + /** + * invalid media query token type + */ + InvalidMediaQueryTokenType = 100, + /** + * supports query condition token type + */ + SupportsQueryConditionTokenType = 101, + /** + * supports query unary condition token type + */ + SupportsQueryUnaryConditionTokenType = 102, + /** + * when else query condition token type + */ + WhenElseQueryConditionTokenType = 103, + /** + * when else query unary condition token type + */ + WhenElseUnaryConditionTokenType = 104, + /** + * container style range token type + */ + ContainerStyleRangeTokenType = 105, + /** + * '*' + */ + Star = 106, + /** + * '+' + */ + Plus = 107, + /** + * '~' + */ + Tilda = 108, + /** + * '|' + */ + Pipe = 109, + /** + * '::' + */ + DoubleColonTokenType = 110, + /** + * math function token type such as'calc(' etc. + */ + MathFunctionTokenType = 111, + /** + * transform function token type such as 'translate(' etc. + */ + TransformFunctionTokenType = 112, + /** + * when function token type such as 'supports(' etc. + */ + WhenElseFunctionTokenType = 113, + /** + * general enclosed function token type 'font-tech(' etc. + */ + GeneralEnclosedFunctionTokenType = 114, + /** + * supports function token type such as 'at-rule(' + */ + SupportsFunctionTokenType = 115, + /** + * container function token type such as 'style(' or 'scroll-state(' + */ + ContainerFunctionTokenType = 116, + /** + * unrecognized node token type + */ + RawNodeTokenType = 117, + /** + * media query boolean token type + * @media not () + * @media only () + */ + MediaQueryUnaryFeatureTokenType = 118, + /** + * grid template function token type such as 'minmax(' + */ + GridTemplateFuncTokenDefType = 119, + /** + * image function token type such as 'image(' etc. + */ + ImageFunctionTokenDefType = 120, + /** + * function token type such as 'view(' etc. + */ + TimelineFunctionTokenDefType = 121, + /** + * function token type + */ + FunctionTokenDefType = 122, + /** + * timing function token type such as 'linear(' etc. + */ + TimingFunctionTokenDefType = 123, + /** + * color function token type such as 'rgb(' etc. + */ + ColorFunctionTokenDefType = 124, + /** + * math function token type such as 'calc(' etc. + */ + MathFunctionTokenDefType = 125, + /** + * container function token type such as 'style(' or 'scroll-state(' + */ + ContainerFunctionTokenDefType = 126, + /** + * url function token type 'url(' + */ + UrlFunctionTokenDefType = 127, + /** + * pseudo-class function token type + */ + PseudoClassFunctionTokenDefType = 128, + /** + * transform function token type such as 'translate(' etc. + */ + TransformFunctionTokenDefType = 129, + /** + * when function token type such as 'supports(' or 'media(' + */ + WhenElseFunctionTokenDefType = 130, + /** + * general enclosed function token type 'font-tech(' etc. + */ + GeneralEnclosedFunctionTokenDefType = 131, + /** + * supports function token type 'font-tech(' + */ + SupportsFunctionTokenDefType = 132, + /** + * CDOCOMMTokenType not allowed in this context + */ + InvalidCommentTokenType = 133, + /** + * custom function token type '--function-name(' + */ + CustomFunctionTokenDefType = 134, + /** + * custom function token type + */ + CustomFunctionTokenType = 135, + /** + * function tokens such as 'var(', 'env(', 'if(') + */ + WildCardFunctionTokenDefType = 136, + /** + * function such as 'var()', 'env()', 'if()' + */ + WildCardFunctionTokenType = 137, + /** + * if condition token + */ + IfConditionTokenType = 138, + /** + * if-Else condition token + */ + IfElseConditionTokenType = 139, + /** + * alias for time token type + */ + Time = 25, + /** + * alias for identifier token type + */ + Iden = 7, + /** + * alias for end of file token type + */ + EOF = 48, + /** + * alias for hash token type + */ + Hash = 28, + /** + * alias for flex token type + */ + Flex = 58, + /** + * alias for angle token type + */ + Angle = 24, + /** + * alias for color token type + */ + Color = 50, + /** + * alias for comma token type + */ + Comma = 9, + /** + * alias for string token type + */ + String = 20, + /** + * alias for length token type + */ + Length = 23, + /** + * alias for number token type + */ + Number = 12, + /** + * alias for percentage token type + */ + Perc = 14, + /** + * alias for literal token type + */ + Literal = 6, + /** + * alias for comment token type + */ + Comment = 0, + /** + * alias for url function token type + */ + UrlFunc = 18, + /** + * alias for dimension token type + */ + Dimension = 22, + /** + * alias for frequency token type + */ + Frequency = 26, + /** + * alias for resolution token type + */ + Resolution = 27, + /** + * alias for whitespace token type + */ + Whitespace = 36, + /** + * alias for identifier list token type + */ + IdenList = 71, + /** + * alias for dashed identifier token type + */ + DashedIden = 8, + /** + * alias for grid template function token type + */ + GridTemplateFunc = 72, + /** + * alias for image function token type + */ + ImageFunc = 19, + /** + * alias for comment node type + */ + CommentNodeType = 0, + /** + * alias for cdata section node type + */ + CDOCOMMNodeType = 1, + /** + * alias for timing function token type + */ + TimingFunction = 17, + /** + * alias for timeline function token type + */ + TimelineFunction = 16 +} +/** + * supported color types enum + */ +export declare enum ColorType { + /** + * deprecated system colors + */ + SYS = 0, + /** + * deprecated system colors + */ + DPSYS = 1, + /** + * named colors + */ + LIT = 2, + /** + * colors as hex values + */ + HEX = 3, + /** + * colors as rgb values + */ + RGBA = 4, + /** + * colors using rgb + */ + HSLA = 5, + /** + * colors using hwb + */ + HWB = 6, + /** + * colors using cmyk + */ + CMYK = 7, + /** + * colors using oklab + * */ + OKLAB = 8, + /** + * colors using oklch + * */ + OKLCH = 9, + /** + * colors using lab + */ + LAB = 10, + /** + * colors using lch + */ + LCH = 11, + /** + * colors using color() function + */ + COLOR = 12, + /** + * color using srgb + */ + SRGB = 13, + /** + * color using prophoto-rgb + */ + PROPHOTO_RGB = 14, + /** + * color using a98-rgb + */ + A98_RGB = 15, + /** + * color using rec2020 + */ + REC2020 = 16, + /** + * color using display-p3 + */ + DISPLAY_P3 = 17, + /** + * color using srgb-linear + */ + SRGB_LINEAR = 18, + /** + * color using xyz-d50 + */ + XYZ_D50 = 19, + /** + * color using xyz-d65 + */ + XYZ_D65 = 20, + /** + * light-dark() color function + */ + LIGHT_DARK = 21, + /** + * color-mix() color function + */ + COLOR_MIX = 22, + /** + * non-standard color + */ + NON_STD = 23, + /** + * custom color + */ + CUSTOM_COLOR = 24, + /** + * alias for rgba + */ + RGB = 4, + /** + * alias for hsl + */ + HSL = 5, + /** + * alias for xyz-d65 + */ + XYZ = 20, + /** + * alias for cmyk + */ + DEVICE_CMYK = 7 +} +export declare enum ModuleCaseTransformEnum { + /** + * export class names as-is + */ + IgnoreCase = 1, + /** + * transform mapping key name to camel case + */ + CamelCase = 2, + /** + * transform class names and mapping key name to camel case + */ + CamelCaseOnly = 4, + /** + * transform mapping key name to dash case + */ + DashCase = 8, + /** + * transform class names and mapping key name to dash case + */ + DashCaseOnly = 16 +} +export declare enum ModuleScopeEnumOptions { + /** + * use the global scope + */ + Global = 32, + /** + * use the local scope + */ + Local = 64, + /** + * do not allow selector without an id or class + */ + Pure = 128, + /** + * export using ICSS module format + */ + ICSS = 256, + /** + * use the shortest name possible. pattern is ignored. + * it will produce names such as + * + * ```css + * .a { + * content: 'a'; + * } + * + * .b { + * content: 'b'; + * } + * + * .c { + * content: 'c'; + * } + * ... + * ``` + */ + Shortest = 512 +} +export declare function length2Px(value: LengthToken | NumberToken): number | null; +/** + * minify number + * @param val + */ +export declare function minifyNumber(val: string | number): string; diff --git a/dist/lib/ast/walk.d.ts b/dist/lib/ast/walk.d.ts new file mode 100644 index 00000000..1c909779 --- /dev/null +++ b/dist/lib/ast/walk.d.ts @@ -0,0 +1,162 @@ +import type { AstNode, Token, WalkAttributesResult, WalkerFilter, WalkerValueFilter, WalkResult } from "../../@types/index.d.ts"; +import { EnumToken } from "./types.ts"; +/** + * options for the walk function + */ +export declare enum WalkerOptionEnum { + /** + * ignore the current node and its children + */ + Ignore = 1, + /** + * stop walking the tree + */ + Stop = 2, + /** + * ignore the current node and process its children + */ + Children = 4, + /** + * ignore the current node children + */ + IgnoreChildren = 8 +} +/** + * event types for the walkValues function + */ +export declare enum WalkerEvent { + /** + * enter node + */ + Enter = 1, + /** + * leave node + */ + Leave = 2 +} +/** + * walk ast nodes + * @param node initial node + * @param filter control the walk process + * @param reverse walk in reverse order + * + * ```ts + * + * import {walk} from '@tbela99/css-parser'; + * + * const css = ` + * body { color: color(from var(--base-color) display-p3 r calc(g + 0.24) calc(b + 0.15)); } + * + * html, + * body { + * line-height: 1.474; + * } + * + * .ruler { + * + * height: 10px; + * } + * `; + * + * for (const {node, parent, root} of walk(ast)) { + * + * // do something with node + * } + * ``` + * + * Using a {@link filter} function to control the ast traversal. the filter function returns a value of type {@link WalkerOption}. + * + * ```ts + * import {EnumToken, transform, walk, WalkerOptionEnum} from '@tbela99/css-parser'; + * + * const css = ` + * body { color: color(from var(--base-color) display-p3 r calc(g + 0.24) calc(b + 0.15)); } + * + * html, + * body { + * line-height: 1.474; + * } + * + * .ruler { + * + * height: 10px; + * } + * `; + * + * function filter(node) { + * + * if (node.typ == EnumToken.AstRule && node.sel.includes('html')) { + * + * // skip the children of the current node + * return WalkerOptionEnum.IgnoreChildren; + * } + * } + * + * const result = await transform(css); + * for (const {node} of walk(result.ast, filter)) { + * + * console.error([EnumToken[node.typ]]); + * } + * + * // [ "StyleSheetNodeType" ] + * // [ "RuleNodeType" ] + * // [ "DeclarationNodeType" ] + * // [ "RuleNodeType" ] + * // [ "DeclarationNodeType" ] + * // [ "RuleNodeType" ] + * // [ "DeclarationNodeType" ] + * ``` + */ +export declare function walk(node: AstNode, filter?: WalkerFilter | null, reverse?: boolean): Generator; +/** + * walk ast node value tokens + * @param values + * @param root + * @param filter + * @param reverse + * + * Example: + * + * ```ts + * + * import {AstDeclaration, EnumToken, transform, walkValues} from '@tbela99/css-parser'; + * + * const css = ` + * body { color: color(from var(--base-color) display-p3 r calc(g + 0.24) calc(b + 0.15)); } + * `; + * + * const result = await transform(css); + * const declaration = result.ast.chi[0].chi[0] as AstDeclaration; + * + * // walk the node attribute's tokens in reverse order + * for (const {value} of walkValues(declaration.val, null, null,true)) { + * + * console.error([EnumToken[value.typ], value.val]); + * } + * + * // [ "Color", "color" ] + * // [ "FunctionTokenType", "calc" ] + * // [ "Number", 0.15 ] + * // [ "Add", undefined ] + * // [ "Iden", "b" ] + * // [ "Whitespace", undefined ] + * // [ "FunctionTokenType", "calc" ] + * // [ "Number", 0.24 ] + * // [ "Add", undefined ] + * // [ "Iden", "g" ] + * // [ "Whitespace", undefined ] + * // [ "Iden", "r" ] + * // [ "Whitespace", undefined ] + * // [ "Iden", "display-p3" ] + * // [ "Whitespace", undefined ] + * // [ "FunctionTokenType", "var" ] + * // [ "DashedIden", "--base-color" ] + * // [ "Whitespace", undefined ] + * // [ "Iden", "from" ] + * ``` + */ +export declare function walkValues(values: Token[], root?: AstNode | Token | null, filter?: WalkerValueFilter | null | { + event?: WalkerEvent; + fn?: WalkerValueFilter; + type?: EnumToken | EnumToken[] | ((token: Token) => boolean); +}, reverse?: boolean): Generator; diff --git a/dist/lib/fs/resolve.d.ts b/dist/lib/fs/resolve.d.ts new file mode 100644 index 00000000..528d6259 --- /dev/null +++ b/dist/lib/fs/resolve.d.ts @@ -0,0 +1,20 @@ +export declare const matchUrl: RegExp; +/** + * return the directory name of a path + * @param path + * + * @private + */ +export declare function dirname(path: string): string; +/** + * resolve path + * @param url url or path to resolve + * @param currentDirectory directory used to resolve the path + * @param cwd current working directory + * + * @private + */ +export declare function resolve(url: string, currentDirectory: string, cwd?: string): { + absolute: string; + relative: string; +}; diff --git a/dist/lib/parser/declaration/list.d.ts b/dist/lib/parser/declaration/list.d.ts new file mode 100644 index 00000000..68add4d6 --- /dev/null +++ b/dist/lib/parser/declaration/list.d.ts @@ -0,0 +1,17 @@ +import type { AstDeclaration, AstNode, PropertyListOptions, SinglePropertyTypeMapping, Token } from "../../../@types/index.d.ts"; +import { PropertySet } from "./set.ts"; +import { PropertyMap } from "./map.ts"; +export declare class PropertyList { + protected options: PropertyListOptions; + protected declarations: Map; + constructor(options?: PropertyListOptions); + set(nam: string, value: string | Token[]): this; + add(...declarations: AstNode[]): this; + mapValues(declaration: AstDeclaration, mapping: SinglePropertyTypeMapping): void; + [Symbol.iterator](): { + next(): { + value: AstNode; + done: boolean; + }; + }; +} diff --git a/dist/lib/parser/declaration/map.d.ts b/dist/lib/parser/declaration/map.d.ts new file mode 100644 index 00000000..8dfad34f --- /dev/null +++ b/dist/lib/parser/declaration/map.d.ts @@ -0,0 +1,15 @@ +import type { AstDeclaration, ShorthandMapType } from "../../../@types/index.d.ts"; +import { PropertySet } from "./set.ts"; +export declare class PropertyMap { + protected config: ShorthandMapType; + protected declarations: Map; + protected requiredCount: any; + protected pattern: string[]; + constructor(config: ShorthandMapType); + add(declaration: AstDeclaration): this; + [Symbol.iterator](): ArrayIterator | { + next(): IteratorResult; + }; + private matchTypes; + private removeDefaults; +} diff --git a/dist/lib/parser/declaration/set.d.ts b/dist/lib/parser/declaration/set.d.ts new file mode 100644 index 00000000..2d3354a6 --- /dev/null +++ b/dist/lib/parser/declaration/set.d.ts @@ -0,0 +1,9 @@ +import type { AstDeclaration, ShorthandPropertyType } from "../../../@types/index.d.ts"; +export declare class PropertySet { + protected config: ShorthandPropertyType; + protected declarations: Map; + constructor(config: ShorthandPropertyType); + add(declaration: AstDeclaration): this; + isShortHand(): boolean; + [Symbol.iterator](): IterableIterator; +} diff --git a/dist/lib/parser/node.d.ts b/dist/lib/parser/node.d.ts new file mode 100644 index 00000000..efa380a7 --- /dev/null +++ b/dist/lib/parser/node.d.ts @@ -0,0 +1,7 @@ +import { EnumToken } from "../ast/types"; +export declare class AstNode { + typ: EnumToken; + value: string; + children?: AstNode[] | undefined; + constructor(typ: EnumToken, value: string, children?: AstNode[] | undefined); +} diff --git a/dist/lib/parser/parse.d.ts b/dist/lib/parser/parse.d.ts new file mode 100644 index 00000000..c8d926f9 --- /dev/null +++ b/dist/lib/parser/parse.d.ts @@ -0,0 +1,107 @@ +import { EnumToken } from "../ast/types.ts"; +import type { AstAtRule, AstComment, AstDeclaration, AstInvalidAtRule, AstRule, AstStyleSheet, CssVariableImportTokenType, CssVariableToken, ErrorDescription, ParseResult, ParserOptions, ParseTokenOptions, Token, TokenizeResult } from "../../@types/index.d.ts"; +export declare const trimWhiteSpace: EnumToken[]; +export declare const atRulesMap: Map; +/** + * short-scoped name generator. + * + * @param localName + * @param filePath + * @param pattern + * @param hashLength + * + * @returns string + */ +export declare const getShortNameGenerator: (...args: any[]) => any; +/** + * transform case of key name + * @param key + * @param how + * + * @throws Error + * @private + */ +export declare const getKeyName: (...args: any[]) => any; +/** + * generate scoped name + * @param localName + * @param filePath + * @param pattern + * @param hashLength + * + * @throws Error + * @private + */ +export declare const generateScopedName: (...args: any[]) => any; +/** + * parse css string + * @param iter + * @param options + * + * @throws Error + * @private + */ +export declare function doParse(iter: Array | Iterable | AsyncGenerator, options?: ParserOptions): Promise; +/**mjgvgyikjkml,kmbm b8790u89y70 +vbbnkit;;;jmjhyg77 * @param options + * @param errors + * @param parseAsBlock + */ +export declare function parseAtRule(stream: Token[], context: AstRule | AstAtRule | AstStyleSheet, options: ParserOptions, errors: ErrorDescription[], parseAsBlock?: boolean | null): AstAtRule | AstInvalidAtRule | CssVariableImportTokenType | CssVariableToken | null; +/** + * parse a string as an array of declaration nodes + * @param declaration + * + * Example: + * ````ts + * + * const declarations = await parseDeclarations('color: red; background: blue'); + * console.log(declarations); + * ``` + */ +export declare function parseDeclarations(declaration: string): Promise>; +/** + * parse css string and return an array of tokens + * @param src + * @param options + * + * @private + * + * Example: + * + * ```ts + * + * import {parseString} from '@tbela99/css-parser'; + * + * let tokens = parseString('body { color: red; }'); + * console.log(tokens); + * + * tokens = parseString('#c322c980'); + * console.log(tokens); + * ``` + */ +export declare function parseString(src: string, options?: { + location: boolean; + src?: string; +}): Token[]; +/** + * parse function tokens in a token array + * @param tokens + * @param options + * + * Example: + * + * ```ts + * + * import {parseString, parseTokens} from '@tbela99/css-parser'; + * + * let tokens = parseString('body { color: red; }'); + * console.log(parseTokens(tokens)); + * + * tokens = parseString('#c322c980'); + * console.log(parseTokens(tokens)); + * ``` + * + * @private + */ +export declare function parseTokens(tokens: Token[], options?: ParseTokenOptions): Token[]; diff --git a/dist/lib/parser/tokenize.d.ts b/dist/lib/parser/tokenize.d.ts new file mode 100644 index 00000000..af3540c0 --- /dev/null +++ b/dist/lib/parser/tokenize.d.ts @@ -0,0 +1,57 @@ +import type { ParseInfo, Position, Token, TokenizeResult } from "../../@types/index.d.ts"; +import { EnumToken } from "../ast/types.ts"; +export declare const SymbolsMapTokens: Record; +export declare const hintsEnum: Set; +export declare const enum TokenMap { + EXCLAMATION = 33,// '!', EXCLAMATION + SLASH = 47,// '/' + LOWERTHAN = 60,// '<', LESS THAN + HASH = 35,// '#', HASH + REVERSE_SOLIDUS = 92,// '\', REVERSE SOLIDUS + DOUBLE_QUOTE = 34,// '"', DOUBLEQ + SINGLE_QUOTE = 39,// "'", SINGLEQ + DOT = 46,// '.', DOT + AT = 64,// '@', AT + PIPE = 124,// '|', PIPE + EQUALS = 61,// '=', EQUALS + AMPERSAND = 38,// '&', AMPERSAND + STAR = 42,// '*', STAR + TILDA = 126,// '~', TILDA + CARET = 94,// '^', CARET + DOLLAR = 36,// '$', DOLLAR + COMMA = 44,// ',', COMMA + COLON = 58,// ':', COLON + SEMICOLON = 59,// ';', SEMICOLON + LEFT_PARENTHESIS = 40,// '(', LEFT PARENTHESIS + RIGHT_PARENTHESIS = 41, + LEFT_BRACKETS = 91,// '[', LEFT_BRACKETS + RIGHT_BRACKETS = 93,// ']', RIGHT_BRACKETS + LEFT_BRACE = 123,// '{', LEFT_BRACE + RIGHT_BRACE = 125, + PLUS = 43,// '+', PLUS + MINUS = 45, + GREATERTHAN = 62 +} +export declare function consumeString(quoteStr: '"' | "'", buffer: string, parseInfo: ParseInfo): Array; +export declare function getTokenType(val: string, hint?: EnumToken): Token; +export declare function yieldResult(val: string, parseInfo: ParseInfo, hint?: EnumToken): TokenizeResult; +export declare function match(parseInfo: ParseInfo, input: string): boolean; +export declare function peek(parseInfo: ParseInfo, count?: number): string; +export declare function next(parseInfo: ParseInfo, count?: number): string; +/** + * tokenize css string + * @param parseInfo + * @param yieldEOFToken + */ +export declare function tokenize(parseInfo: ParseInfo | string, yieldEOFToken?: boolean): Array; +/** + * tokenize readable stream + * @param input + */ +export declare function tokenizeStream(input: ReadableStream, parseInfo?: ParseInfo): AsyncGenerator; +/** + * Update position + * @param position + * @param str + */ +export declare function move(position: Position, str: string): void; diff --git a/dist/lib/parser/utils/at-rule-container.d.ts b/dist/lib/parser/utils/at-rule-container.d.ts new file mode 100644 index 00000000..dfa1033d --- /dev/null +++ b/dist/lib/parser/utils/at-rule-container.d.ts @@ -0,0 +1,5 @@ +import type { AstAtRule, AtRuleToken, ErrorDescription, ParserOptions, Token } from "../../../@types/index.d.ts"; +export declare function parseAtRuleContainerQueryList(stream: Token[], context: AstAtRule | AtRuleToken, options?: ParserOptions): { + success: boolean; + errors: ErrorDescription[]; +}; diff --git a/dist/lib/parser/utils/at-rule-font-feature-values.d.ts b/dist/lib/parser/utils/at-rule-font-feature-values.d.ts new file mode 100644 index 00000000..3af89662 --- /dev/null +++ b/dist/lib/parser/utils/at-rule-font-feature-values.d.ts @@ -0,0 +1,5 @@ +import type { ParserOptions, Token, AstAtRule, AtRuleToken } from "../../../@types/index.d.ts"; +export declare function parseAtRuleFontFeatureValues(stream: Token[], context: AstAtRule | AtRuleToken, options?: ParserOptions): { + success: boolean; + errors: import("../../../@types/index.d.ts").ErrorDescription[]; +}; diff --git a/dist/lib/parser/utils/at-rule-generic.d.ts b/dist/lib/parser/utils/at-rule-generic.d.ts new file mode 100644 index 00000000..dabe7665 --- /dev/null +++ b/dist/lib/parser/utils/at-rule-generic.d.ts @@ -0,0 +1,5 @@ +import type { AtRuleToken, ErrorDescription, ParserOptions, Token, ValidationOptions } from "../../../@types/index.d.ts"; +export declare function matchGenericSyntax(atRule: AtRuleToken, stream: Token[], options: ParserOptions | ValidationOptions): { + success: boolean; + errors: ErrorDescription[]; +}; diff --git a/dist/lib/parser/utils/at-rule-import.d.ts b/dist/lib/parser/utils/at-rule-import.d.ts new file mode 100644 index 00000000..301e9bc9 --- /dev/null +++ b/dist/lib/parser/utils/at-rule-import.d.ts @@ -0,0 +1,5 @@ +import type { AstAtRule, AstRule, AstStyleSheet, AtRuleToken, ErrorDescription, ParserOptions, Token } from "../../../@types/index.d.ts"; +export declare function matchAtRuleImportSyntax(atRule: AtRuleToken, stream: Token[], context: AstRule | AstAtRule | AstStyleSheet, options: ParserOptions): { + success: boolean; + errors: ErrorDescription[]; +}; diff --git a/dist/lib/parser/utils/at-rule-media.d.ts b/dist/lib/parser/utils/at-rule-media.d.ts new file mode 100644 index 00000000..b6ec8717 --- /dev/null +++ b/dist/lib/parser/utils/at-rule-media.d.ts @@ -0,0 +1,5 @@ +import type { ErrorDescription, ParserOptions, Token } from "../../../@types/index.d.ts"; +export declare function parseMediaqueryList(stream: Token[], options: ParserOptions): { + errors: ErrorDescription[]; + success: boolean; +}; diff --git a/dist/lib/parser/utils/at-rule-page.d.ts b/dist/lib/parser/utils/at-rule-page.d.ts new file mode 100644 index 00000000..59fd495a --- /dev/null +++ b/dist/lib/parser/utils/at-rule-page.d.ts @@ -0,0 +1,5 @@ +import type { AstAtRule, AtRuleToken, ErrorDescription, ParserOptions, Token } from "../../../@types/index.d.ts"; +export declare function parseAtRulePage(context: AstAtRule | AtRuleToken, stream: Token[], options: ParserOptions, errors: ErrorDescription[]): { + success: boolean; + errors: ErrorDescription[]; +}; diff --git a/dist/lib/parser/utils/at-rule-support.d.ts b/dist/lib/parser/utils/at-rule-support.d.ts new file mode 100644 index 00000000..5412c270 --- /dev/null +++ b/dist/lib/parser/utils/at-rule-support.d.ts @@ -0,0 +1,5 @@ +import type { Token, AstAtRule, ParserOptions, ErrorDescription, AtRuleToken } from "../../../@types/index.d.ts"; +export declare function parseAtRuleSupportSyntax(stream: Token[], context: AstAtRule | AtRuleToken, options?: ParserOptions): { + success: boolean; + errors: ErrorDescription[]; +}; diff --git a/dist/lib/parser/utils/at-rule-token.d.ts b/dist/lib/parser/utils/at-rule-token.d.ts new file mode 100644 index 00000000..9ebacb74 --- /dev/null +++ b/dist/lib/parser/utils/at-rule-token.d.ts @@ -0,0 +1 @@ +export declare function parseAtRuleToken(): void; diff --git a/dist/lib/parser/utils/at-rule-when-else.d.ts b/dist/lib/parser/utils/at-rule-when-else.d.ts new file mode 100644 index 00000000..ad3d960e --- /dev/null +++ b/dist/lib/parser/utils/at-rule-when-else.d.ts @@ -0,0 +1,5 @@ +import type { AstAtRule, AtRuleToken, ErrorDescription, ParserOptions, Token } from "../../../@types/index.d.ts"; +export declare function matchAtRuleWhenElseSyntax(stream: Token[], context: AstAtRule | AtRuleToken, options?: ParserOptions): { + success: boolean; + errors: ErrorDescription[]; +}; diff --git a/dist/lib/parser/utils/at-rule.d.ts b/dist/lib/parser/utils/at-rule.d.ts new file mode 100644 index 00000000..009fc604 --- /dev/null +++ b/dist/lib/parser/utils/at-rule.d.ts @@ -0,0 +1,5 @@ +import type { AtRuleToken, Token, ParserOptions, ValidationOptions, ErrorDescription } from "../../../@types/index.d.ts"; +export declare function matchAtRuleSyntax(atRule: AtRuleToken, stream: Token[], options: ParserOptions | ValidationOptions): { + success: boolean; + errors: ErrorDescription[]; +}; diff --git a/dist/lib/parser/utils/cache.d.ts b/dist/lib/parser/utils/cache.d.ts new file mode 100644 index 00000000..cbadca63 --- /dev/null +++ b/dist/lib/parser/utils/cache.d.ts @@ -0,0 +1,6 @@ +/** + * + * @param fn + * @returns + */ +export declare function memoize(fn: Function): (...args: any[]) => any; diff --git a/dist/lib/parser/utils/config.d.ts b/dist/lib/parser/utils/config.d.ts new file mode 100644 index 00000000..f7a1a1d8 --- /dev/null +++ b/dist/lib/parser/utils/config.d.ts @@ -0,0 +1,2 @@ +import type { PropertiesConfig } from "../../../@types/index.d.ts"; +export declare const getConfig: () => PropertiesConfig; diff --git a/dist/lib/parser/utils/declaration-list.d.ts b/dist/lib/parser/utils/declaration-list.d.ts new file mode 100644 index 00000000..452691d3 --- /dev/null +++ b/dist/lib/parser/utils/declaration-list.d.ts @@ -0,0 +1,5 @@ +import { AstAtRule, AtRuleToken, Token, ParserOptions, ErrorDescription } from "../../../@types"; +export declare function parseDeclarationList(context: AstAtRule | AtRuleToken, stream: Token[], options: ParserOptions, errors: ErrorDescription[]): { + success: boolean; + errors: ErrorDescription[]; +}; diff --git a/dist/lib/parser/utils/declaration.d.ts b/dist/lib/parser/utils/declaration.d.ts new file mode 100644 index 00000000..53988711 --- /dev/null +++ b/dist/lib/parser/utils/declaration.d.ts @@ -0,0 +1,18 @@ +import type { AstAtRule, AstDeclaration, AstInvalidAtRule, AstInvalidDeclaration, AstInvalidRule, AstKeyFrameRule, AstRule, AstStyleSheet, AtRuleToken, ErrorDescription, ParserOptions, RawNodeToken, Token } from "../../../@types/index.d.ts"; +/** + * + * @param tokens + * @returns + */ +export declare function isDeclarationValue(tokens: Token[]): { + success: boolean; + errors: ErrorDescription[]; +}; +/** + * parse declaration + * @param tokens + * @param parent + * @param options + * @param errors + */ +export declare function parseDeclaration(tokens: Token[], parent: AstRule | AstAtRule | AstKeyFrameRule | AstStyleSheet | AtRuleToken | AstInvalidAtRule | AstInvalidRule | null, options: ParserOptions, errors: ErrorDescription[]): AstDeclaration | AstInvalidDeclaration | RawNodeToken; diff --git a/dist/lib/parser/utils/eq.d.ts b/dist/lib/parser/utils/eq.d.ts new file mode 100644 index 00000000..d18bf3b6 --- /dev/null +++ b/dist/lib/parser/utils/eq.d.ts @@ -0,0 +1 @@ +export declare function eq(a: any, b: any): boolean; diff --git a/dist/lib/parser/utils/hash.d.ts b/dist/lib/parser/utils/hash.d.ts new file mode 100644 index 00000000..d18b3c85 --- /dev/null +++ b/dist/lib/parser/utils/hash.d.ts @@ -0,0 +1,21 @@ +export declare const LOWER = "abcdefghijklmnopqrstuvwxyz"; +export declare const DIGITS = "0123456789"; +export declare const FULL_ALPHABET: string[]; +export declare const FIRST_ALPHABET: string[]; +/** + * supported hash algorithms + */ +export declare const hashAlgorithms: string[]; +/** + * generate a hash id + * @param input + * @param length + */ +export declare function hashId(input: string, length?: number): string; +/** + * generate a hash + * @param input + * @param length + * @param algo + */ +export declare function hash(input: string, length?: number, algo?: string): Promise; diff --git a/dist/lib/parser/utils/selector.d.ts b/dist/lib/parser/utils/selector.d.ts new file mode 100644 index 00000000..5039ee40 --- /dev/null +++ b/dist/lib/parser/utils/selector.d.ts @@ -0,0 +1,5 @@ +import type { Token, AstRule, AstAtRule, AstKeyFrameRule, AstKeyframesAtRule, AstStyleSheet, ParserOptions, ErrorDescription, AstInvalidRule, AtRuleToken } from "../../../@types/index.d.ts"; +/** + * parse selector + */ +export declare function parseSelector(tokens: Token[], context: AtRuleToken | AstRule | AstAtRule | AstKeyFrameRule | AstKeyframesAtRule | AstStyleSheet | null, options: ParserOptions, errors: ErrorDescription[]): AstRule | AstInvalidRule | AstKeyFrameRule; diff --git a/dist/lib/parser/utils/text.d.ts b/dist/lib/parser/utils/text.d.ts new file mode 100644 index 00000000..6e0762a8 --- /dev/null +++ b/dist/lib/parser/utils/text.d.ts @@ -0,0 +1,3 @@ +export declare function dasherize(value: string): string; +export declare function camelize(value: string): string; +export declare function equalsIgnoreCase(a: string, b: string): boolean; diff --git a/dist/lib/parser/utils/token.d.ts b/dist/lib/parser/utils/token.d.ts new file mode 100644 index 00000000..61367212 --- /dev/null +++ b/dist/lib/parser/utils/token.d.ts @@ -0,0 +1,14 @@ +import type { AstNode } from "../../../@types/ast.d.ts"; +import type { BinaryExpressionToken, Token } from "../../../@types/token.d.ts"; +/** + * replace token in its parent node + * @param parent + * @param value + * @param replacement + */ +export declare function replaceToken(parent: BinaryExpressionToken | (AstNode & ({ + chi: Token[]; +} | { + val: Token[]; +})), value: Token, replacement: Token | Token[]): boolean; +export declare function trimWhiteSpaceTokens(tokens: Token[]): Token[]; diff --git a/dist/lib/parser/utils/type.d.ts b/dist/lib/parser/utils/type.d.ts new file mode 100644 index 00000000..2c770156 --- /dev/null +++ b/dist/lib/parser/utils/type.d.ts @@ -0,0 +1,2 @@ +import type { PropertyMapType, Token } from "../../../@types/index.d.ts"; +export declare function matchType(val: Token, properties: PropertyMapType): boolean; diff --git a/dist/lib/renderer/render.d.ts b/dist/lib/renderer/render.d.ts new file mode 100644 index 00000000..80d1451e --- /dev/null +++ b/dist/lib/renderer/render.d.ts @@ -0,0 +1,28 @@ +import type { AstNode, ErrorDescription, RenderOptions, RenderResult, Token } from "../../@types/index.d.ts"; +/** + * render ast + * @param data + * @param options + * @param mapping + * @private + */ +export declare function doRender(data: AstNode, options?: RenderOptions, mapping?: { + mapping: Record; + importMapping: Record> | null; +} | null): RenderResult; +/** + * render ast token + * @param token + * @param options + * @private + */ +export declare function renderToken(token: Token, options?: RenderOptions, cache?: { + [key: string]: any; +}, reducer?: (acc: string, curr: Token) => string, errors?: ErrorDescription[]): string; +/** + * Remove whitespace tokens that are not needed + * @param values + * + * @internal + */ +export declare function filterValues(values: Token[]): Token[]; diff --git a/dist/lib/renderer/sourcemap/lib/encode.d.ts b/dist/lib/renderer/sourcemap/lib/encode.d.ts new file mode 100644 index 00000000..92a97a5f --- /dev/null +++ b/dist/lib/renderer/sourcemap/lib/encode.d.ts @@ -0,0 +1 @@ +export declare function encode(value: number | number[]): string; diff --git a/dist/lib/renderer/sourcemap/sourcemap.d.ts b/dist/lib/renderer/sourcemap/sourcemap.d.ts new file mode 100644 index 00000000..b653cf33 --- /dev/null +++ b/dist/lib/renderer/sourcemap/sourcemap.d.ts @@ -0,0 +1,26 @@ +import type { Location, SourceMapObject } from "../../../@types/index.d.ts"; +/** + * Source map class + * @internal + */ +export declare class SourceMap { + #private; + /** + * Last location + */ + lastLocation: Location | null; + /** + * Add a location + * @param source + * @param original + */ + add(source: Location, original: Location): void; + /** + * Convert to URL encoded string + */ + toUrl(): string; + /** + * Convert to JSON object + */ + toJSON(): SourceMapObject; +} diff --git a/dist/lib/syntax/color/a98rgb.d.ts b/dist/lib/syntax/color/a98rgb.d.ts new file mode 100644 index 00000000..f978bee4 --- /dev/null +++ b/dist/lib/syntax/color/a98rgb.d.ts @@ -0,0 +1,2 @@ +export declare function a98rgb2srgbvalues(r: number, g: number, b: number, a?: number | null): number[]; +export declare function srgb2a98values(r: number, g: number, b: number, a?: number | null): number[]; diff --git a/dist/lib/syntax/color/cmyk.d.ts b/dist/lib/syntax/color/cmyk.d.ts new file mode 100644 index 00000000..54ec9ae3 --- /dev/null +++ b/dist/lib/syntax/color/cmyk.d.ts @@ -0,0 +1,10 @@ +import type { ColorToken } from "../../../@types/token.d.ts"; +export declare function rgb2cmykToken(token: ColorToken): ColorToken | null; +export declare function hsl2cmykToken(token: ColorToken): ColorToken | null; +export declare function hwb2cmykToken(token: ColorToken): ColorToken | null; +export declare function lab2cmykToken(token: ColorToken): ColorToken | null; +export declare function lch2cmykToken(token: ColorToken): ColorToken | null; +export declare function oklab2cmyk(token: ColorToken): ColorToken | null; +export declare function oklch2cmykToken(token: ColorToken): ColorToken | null; +export declare function color2cmykToken(token: ColorToken): ColorToken | null; +export declare function srgb2cmykvalues(r: number, g: number, b: number, a?: number | null): number[]; diff --git a/dist/lib/syntax/color/color-mix.d.ts b/dist/lib/syntax/color/color-mix.d.ts new file mode 100644 index 00000000..f8f9f3b1 --- /dev/null +++ b/dist/lib/syntax/color/color-mix.d.ts @@ -0,0 +1,2 @@ +import type { ColorToken, IdentToken, NumberToken, PercentageToken } from "../../../@types/index.d.ts"; +export declare function colorMix(colorSpace: IdentToken, hueInterpolationMethod: IdentToken | null, color1: ColorToken, percentage1: PercentageToken | NumberToken | null, color2: ColorToken, percentage2: PercentageToken | NumberToken | null): ColorToken | null; diff --git a/dist/lib/syntax/color/color.d.ts b/dist/lib/syntax/color/color.d.ts new file mode 100644 index 00000000..a1013acb --- /dev/null +++ b/dist/lib/syntax/color/color.d.ts @@ -0,0 +1,42 @@ +import type { AngleToken, ColorToken, FractionToken, IdentToken, NumberToken, PercentageToken } from "../../../@types/index.d.ts"; +import { ColorType } from "../../ast/types.ts"; +/** + * Converts a color to another color space + * @param token + * @param to + * + * @private + * + * ```ts + * + * const token = {typ: EnumToken.ColorTokenType, kin: ColorType.HEX, val: '#F00'} + * const result = convertColor(token, ColorType.LCH); + * + * ``` + */ +export declare function convertColor(token: ColorToken, to: ColorType): ColorToken | null; +export declare function hex2colorToken(token: ColorToken, to: ColorType): ColorToken | null; +export declare function rgb2colorToken(token: ColorToken, to: ColorType): ColorToken | null; +export declare function hsl2colorToken(token: ColorToken, to: ColorType): ColorToken | null; +export declare function hwb2colorToken(token: ColorToken, to: ColorType): ColorToken | null; +export declare function cmyk2colorToken(token: ColorToken, to: ColorType): ColorToken | null; +export declare function lab2colorToken(token: ColorToken, to: ColorType): ColorToken | null; +export declare function oklab2colorToken(token: ColorToken, to: ColorType): ColorToken | null; +export declare function lch2colorToken(token: ColorToken, to: ColorType): ColorToken | null; +export declare function oklch2colorToken(token: ColorToken, to: ColorType): ColorToken | null; +export declare function color2colorToken(token: ColorToken, to: ColorType): ColorToken | null; +export declare function minmax(value: number, min: number, max: number): number; +export declare function color2srgbvalues(token: ColorToken): number[] | null; +/** + * clamp color values + * @param token + */ +export declare function clamp(token: ColorToken): ColorToken; +export declare function getNumber(token: NumberToken | PercentageToken | IdentToken | FractionToken): number; +/** + * convert angle to turn + * @param token + */ +export declare function getAngle(token: NumberToken | AngleToken | IdentToken): number; +export declare function toPrecisionValue(value: number): number; +export declare function toPrecisionAngle(angle: number): number; diff --git a/dist/lib/syntax/color/hex.d.ts b/dist/lib/syntax/color/hex.d.ts new file mode 100644 index 00000000..be6ed6d5 --- /dev/null +++ b/dist/lib/syntax/color/hex.d.ts @@ -0,0 +1,16 @@ +import type { ColorToken } from "../../../@types/index.d.ts"; +export declare function reduceHexValue(value: string): string; +export declare function expandHexValue(value: string): string; +export declare function rgb2HexToken(token: ColorToken): ColorToken | null; +export declare function hsl2HexToken(token: ColorToken): ColorToken | null; +export declare function cmyk2HexToken(token: ColorToken): ColorToken | null; +export declare function hwb2HexToken(token: ColorToken): ColorToken | null; +export declare function color2HexToken(token: ColorToken): ColorToken | null; +export declare function oklab2HexToken(token: ColorToken): ColorToken | null; +export declare function oklch2HexToken(token: ColorToken): ColorToken | null; +export declare function lab2HexToken(token: ColorToken): ColorToken | null; +export declare function lch2HexToken(token: ColorToken): ColorToken | null; +export declare function rgb2hexvalues(token: ColorToken): string | null; +export declare function hsl2hexvalues(token: ColorToken): string | null; +export declare function hwb2hexvalues(token: ColorToken): string | null; +export declare function cmyk2hexvalues(token: ColorToken): string | null; diff --git a/dist/lib/syntax/color/hsl.d.ts b/dist/lib/syntax/color/hsl.d.ts new file mode 100644 index 00000000..6196ec76 --- /dev/null +++ b/dist/lib/syntax/color/hsl.d.ts @@ -0,0 +1,20 @@ +import type { ColorToken } from "../../../@types/index.d.ts"; +export declare function hex2HslToken(token: ColorToken): ColorToken | null; +export declare function rgb2HslToken(token: ColorToken): ColorToken | null; +export declare function hwb2HslToken(token: ColorToken): ColorToken | null; +export declare function cmyk2HslToken(token: ColorToken): ColorToken | null; +export declare function oklab2HslToken(token: ColorToken): ColorToken | null; +export declare function oklch2HslToken(token: ColorToken): ColorToken | null; +export declare function lab2HslToken(token: ColorToken): ColorToken | null; +export declare function lch2HslToken(token: ColorToken): ColorToken | null; +export declare function color2HslToken(token: ColorToken): ColorToken | null; +export declare function rgb2hslvalues(token: ColorToken): number[] | null; +export declare function hsv2hsl(h: number, s: number, v: number, a?: number): number[]; +export declare function cmyk2hslvalues(token: ColorToken): number[]; +export declare function hwb2hslvalues(token: ColorToken): [number, number, number, number]; +export declare function lab2hslvalues(token: ColorToken): number[] | null; +export declare function lch2hslvalues(token: ColorToken): number[] | null; +export declare function oklab2hslvalues(token: ColorToken): number[] | null; +export declare function oklch2hslvalues(token: ColorToken): number[] | null; +export declare function rgbvalues2hslvalues(r: number, g: number, b: number, a?: number | null): number[]; +export declare function srgb2hslvalues(r: number, g: number, b: number, a?: number | null): number[]; diff --git a/dist/lib/syntax/color/hsv.d.ts b/dist/lib/syntax/color/hsv.d.ts new file mode 100644 index 00000000..47f829fe --- /dev/null +++ b/dist/lib/syntax/color/hsv.d.ts @@ -0,0 +1,2 @@ +export declare function hwb2hsv(h: number, w: number, b: number, a?: number): [number, number, number, number | null]; +export declare function hsl2hsv(h: number, s: number, l: number, a?: number | null): number[]; diff --git a/dist/lib/syntax/color/hwb.d.ts b/dist/lib/syntax/color/hwb.d.ts new file mode 100644 index 00000000..38f31087 --- /dev/null +++ b/dist/lib/syntax/color/hwb.d.ts @@ -0,0 +1,21 @@ +import type { ColorToken } from "../../../@types/index.d.ts"; +export declare function rgb2hwbToken(token: ColorToken): ColorToken | null; +export declare function hsl2hwbToken(token: ColorToken): ColorToken | null; +export declare function cmyk2hwbToken(token: ColorToken): ColorToken | null; +export declare function oklab2hwbToken(token: ColorToken): ColorToken | null; +export declare function oklch2hwbToken(token: ColorToken): ColorToken | null; +export declare function lab2hwbToken(token: ColorToken): ColorToken | null; +export declare function lch2hwbToken(token: ColorToken): ColorToken | null; +export declare function color2hwbToken(token: ColorToken): ColorToken | null; +export declare function hwbToken(values: number[]): ColorToken; +export declare function rgb2hwbvalues(token: ColorToken): number[]; +export declare function cmyk2hwbvalues(token: ColorToken): number[]; +export declare function hsl2hwbvalues(token: ColorToken): number[]; +export declare function lab2hwbvalues(token: ColorToken): number[] | null; +export declare function lch2hwbvalues(token: ColorToken): number[] | null; +export declare function oklab2hwbvalues(token: ColorToken): number[] | null; +export declare function oklch2hwbvalues(token: ColorToken): number[]; +export declare function color2hwbvalues(token: ColorToken): number[] | null; +export declare function srgb2hwb(r: number, g: number, b: number, a?: number | null, fallback?: number): number[]; +export declare function hsv2hwb(h: number, s: number, v: number, a?: number | null): number[]; +export declare function hslvalues2hwbvalues(h: number, s: number, l: number, a?: number | null): number[]; diff --git a/dist/lib/syntax/color/lab.d.ts b/dist/lib/syntax/color/lab.d.ts new file mode 100644 index 00000000..f5de6669 --- /dev/null +++ b/dist/lib/syntax/color/lab.d.ts @@ -0,0 +1,25 @@ +import type { ColorToken } from "../../../@types/index.d.ts"; +export declare function hex2labToken(token: ColorToken): ColorToken | null; +export declare function rgb2labToken(token: ColorToken): ColorToken | null; +export declare function hsl2labToken(token: ColorToken): ColorToken | null; +export declare function hwb2labToken(token: ColorToken): ColorToken | null; +export declare function cmyk2labToken(token: ColorToken): ColorToken | null; +export declare function lch2labToken(token: ColorToken): ColorToken | null; +export declare function oklab2labToken(token: ColorToken): ColorToken | null; +export declare function oklch2labToken(token: ColorToken): ColorToken | null; +export declare function color2labToken(token: ColorToken): ColorToken | null; +export declare function hex2labvalues(token: ColorToken): number[] | null; +export declare function rgb2labvalues(token: ColorToken): number[] | null; +export declare function cmyk2labvalues(token: ColorToken): number[] | null; +export declare function hsl2labvalues(token: ColorToken): number[] | null; +export declare function hwb2labvalues(token: ColorToken): number[] | null; +export declare function lch2labvalues(token: ColorToken): number[] | null; +export declare function oklab2labvalues(token: ColorToken): number[] | null; +export declare function oklch2labvalues(token: ColorToken): number[] | null; +export declare function color2labvalues(token: ColorToken): number[] | null; +export declare function srgb2labvalues(r: number, g: number, b: number, a: number | null): number[]; +export declare function xyz2lab(x: number, y: number, z: number, a?: number | null): number[]; +export declare function lchvalues2labvalues(l: number, c: number, h: number, a?: number | null): number[]; +export declare function getLABComponents(token: ColorToken): number[] | null; +export declare function Lab_to_sRGB(l: number, a: number, b: number): number[]; +export declare function Lab_to_XYZ(l: number, a: number, b: number): number[]; diff --git a/dist/lib/syntax/color/lch.d.ts b/dist/lib/syntax/color/lch.d.ts new file mode 100644 index 00000000..5235bd1a --- /dev/null +++ b/dist/lib/syntax/color/lch.d.ts @@ -0,0 +1,23 @@ +import type { ColorToken } from "../../../@types/index.d.ts"; +export declare function hex2lchToken(token: ColorToken): ColorToken | null; +export declare function rgb2lchToken(token: ColorToken): ColorToken | null; +export declare function hsl2lchToken(token: ColorToken): ColorToken | null; +export declare function hwb2lchToken(token: ColorToken): ColorToken | null; +export declare function cmyk2lchToken(token: ColorToken): ColorToken | null; +export declare function lab2lchToken(token: ColorToken): ColorToken | null; +export declare function oklab2lchToken(token: ColorToken): ColorToken | null; +export declare function oklch2lchToken(token: ColorToken): ColorToken | null; +export declare function color2lchToken(token: ColorToken): ColorToken | null; +export declare function hex2lchvalues(token: ColorToken): number[] | null; +export declare function rgb2lchvalues(token: ColorToken): number[] | null; +export declare function hsl2lchvalues(token: ColorToken): number[] | null; +export declare function hwb2lchvalues(token: ColorToken): number[] | null; +export declare function lab2lchvalues(token: ColorToken): number[] | null; +export declare function srgb2lch(r: number, g: number, blue: number, alpha: number | null): number[]; +export declare function oklab2lchvalues(token: ColorToken): number[] | null; +export declare function cmyk2lchvalues(token: ColorToken): number[] | null; +export declare function oklch2lchvalues(token: ColorToken): number[] | null; +export declare function color2lchvalues(token: ColorToken): number[] | null; +export declare function labvalues2lchvalues(l: number, a: number, b: number, alpha?: number | null): number[]; +export declare function xyz2lchvalues(x: number, y: number, z: number, alpha?: number): number[]; +export declare function getLCHComponents(token: ColorToken): number[] | null; diff --git a/dist/lib/syntax/color/oklab.d.ts b/dist/lib/syntax/color/oklab.d.ts new file mode 100644 index 00000000..bcc4441e --- /dev/null +++ b/dist/lib/syntax/color/oklab.d.ts @@ -0,0 +1,22 @@ +import type { ColorToken } from "../../../@types/index.d.ts"; +export declare function hex2oklabToken(token: ColorToken): ColorToken | null; +export declare function rgb2oklabToken(token: ColorToken): ColorToken | null; +export declare function hsl2oklabToken(token: ColorToken): ColorToken | null; +export declare function hwb2oklabToken(token: ColorToken): ColorToken | null; +export declare function cmyk2oklabToken(token: ColorToken): ColorToken | null; +export declare function lab2oklabToken(token: ColorToken): ColorToken | null; +export declare function lch2oklabToken(token: ColorToken): ColorToken | null; +export declare function oklch2oklabToken(token: ColorToken): ColorToken | null; +export declare function color2oklabToken(token: ColorToken): ColorToken | null; +export declare function hex2oklabvalues(token: ColorToken): number[] | null; +export declare function rgb2oklabvalues(token: ColorToken): number[] | null; +export declare function hsl2oklabvalues(token: ColorToken): number[] | null; +export declare function hwb2oklabvalues(token: ColorToken): number[]; +export declare function cmyk2oklabvalues(token: ColorToken): number[] | null; +export declare function lab2oklabvalues(token: ColorToken): number[] | null; +export declare function lch2oklabvalues(token: ColorToken): number[] | null; +export declare function oklch2oklabvalues(token: ColorToken): number[] | null; +export declare function srgb2oklab(r: number, g: number, blue: number, alpha: number | null): number[]; +export declare function getOKLABComponents(token: ColorToken): number[] | null; +export declare function OKLab_to_XYZ(l: number, a: number, b: number, alpha?: number | null): number[]; +export declare function OKLab_to_sRGB(l: number, a: number, b: number): number[]; diff --git a/dist/lib/syntax/color/oklch.d.ts b/dist/lib/syntax/color/oklch.d.ts new file mode 100644 index 00000000..a6a9da4d --- /dev/null +++ b/dist/lib/syntax/color/oklch.d.ts @@ -0,0 +1,20 @@ +import type { ColorToken } from "../../../@types/index.d.ts"; +export declare function hex2oklchToken(token: ColorToken): ColorToken | null; +export declare function rgb2oklchToken(token: ColorToken): ColorToken | null; +export declare function hsl2oklchToken(token: ColorToken): ColorToken | null; +export declare function hwb2oklchToken(token: ColorToken): ColorToken | null; +export declare function cmyk2oklchToken(token: ColorToken): ColorToken | null; +export declare function lab2oklchToken(token: ColorToken): ColorToken | null; +export declare function oklab2oklchToken(token: ColorToken): ColorToken | null; +export declare function lch2oklchToken(token: ColorToken): ColorToken | null; +export declare function color2oklchToken(token: ColorToken): ColorToken | null; +export declare function hex2oklchvalues(token: ColorToken): number[]; +export declare function rgb2oklchvalues(token: ColorToken): number[] | null; +export declare function hsl2oklchvalues(token: ColorToken): number[]; +export declare function hwb2oklchvalues(token: ColorToken): number[]; +export declare function cmyk2oklchvalues(token: ColorToken): number[]; +export declare function lab2oklchvalues(token: ColorToken): number[] | null; +export declare function lch2oklchvalues(token: ColorToken): number[] | null; +export declare function oklab2oklchvalues(token: ColorToken): number[] | null; +export declare function srgb2oklch(r: number, g: number, blue: number, alpha: number | null): number[]; +export declare function getOKLCHComponents(token: ColorToken): number[] | null; diff --git a/dist/lib/syntax/color/p3.d.ts b/dist/lib/syntax/color/p3.d.ts new file mode 100644 index 00000000..5cd92b44 --- /dev/null +++ b/dist/lib/syntax/color/p3.d.ts @@ -0,0 +1,6 @@ +export declare function p32srgbvalues(r: number, g: number, b: number, alpha?: number): number[]; +export declare function srgb2p3values(r: number, g: number, b: number, alpha?: number): number[]; +export declare function p32lp3(r: number, g: number, b: number, alpha?: number): number[]; +export declare function lp32p3(r: number, g: number, b: number, alpha?: number): number[]; +export declare function lp32xyz(r: number, g: number, b: number, alpha?: number): number[]; +export declare function xyz2lp3(x: number, y: number, z: number, alpha?: number): number[]; diff --git a/dist/lib/syntax/color/prophotorgb.d.ts b/dist/lib/syntax/color/prophotorgb.d.ts new file mode 100644 index 00000000..90da68bb --- /dev/null +++ b/dist/lib/syntax/color/prophotorgb.d.ts @@ -0,0 +1,2 @@ +export declare function prophotorgb2srgbvalues(r: number, g: number, b: number, a?: number | null): number[]; +export declare function srgb2prophotorgbvalues(r: number, g: number, b: number, a?: number): number[]; diff --git a/dist/lib/syntax/color/rec2020.d.ts b/dist/lib/syntax/color/rec2020.d.ts new file mode 100644 index 00000000..ad73818f --- /dev/null +++ b/dist/lib/syntax/color/rec2020.d.ts @@ -0,0 +1,2 @@ +export declare function rec20202srgb(r: number, g: number, b: number, a?: number): number[]; +export declare function srgb2rec2020values(r: number, g: number, b: number, a?: number): number[]; diff --git a/dist/lib/syntax/color/relativecolor.d.ts b/dist/lib/syntax/color/relativecolor.d.ts new file mode 100644 index 00000000..9b42cb87 --- /dev/null +++ b/dist/lib/syntax/color/relativecolor.d.ts @@ -0,0 +1,13 @@ +import type { BinaryExpressionToken, ColorToken, FunctionToken, ParensToken, Token } from "../../../@types/index.d.ts"; +type RGBKeyType = "r" | "g" | "b" | "alpha"; +type HSLKeyType = "h" | "s" | "l" | "alpha"; +type HWBKeyType = "h" | "w" | "b" | "alpha"; +type LABKeyType = "l" | "a" | "b" | "alpha"; +type OKLABKeyType = "l" | "a" | "b" | "alpha"; +type XYZKeyType = "x" | "y" | "z" | "alpha"; +type LCHKeyType = "l" | "c" | "h" | "alpha"; +type OKLCHKeyType = "l" | "c" | "h" | "alpha"; +export type RelativeColorTypes = RGBKeyType | HSLKeyType | HWBKeyType | LABKeyType | OKLABKeyType | LCHKeyType | OKLCHKeyType | XYZKeyType; +export declare function parseRelativeColor(relativeKeys: string, original: ColorToken, rExp: Token, gExp: Token, bExp: Token, aExp: Token | null): Record | null; +export declare function replaceValue(parent: FunctionToken | ParensToken | BinaryExpressionToken, value: Token, newValue: Token): void; +export {}; diff --git a/dist/lib/syntax/color/rgb.d.ts b/dist/lib/syntax/color/rgb.d.ts new file mode 100644 index 00000000..852bb797 --- /dev/null +++ b/dist/lib/syntax/color/rgb.d.ts @@ -0,0 +1,20 @@ +import type { ColorToken } from "../../../@types/index.d.ts"; +export declare function srgb2rgb(value: number): number; +export declare function hex2RgbToken(token: ColorToken): ColorToken | null; +export declare function hsl2RgbToken(token: ColorToken): ColorToken | null; +export declare function hwb2RgbToken(token: ColorToken): ColorToken | null; +export declare function cmyk2RgbToken(token: ColorToken): ColorToken | null; +export declare function oklab2RgbToken(token: ColorToken): ColorToken | null; +export declare function oklch2RgbToken(token: ColorToken): ColorToken | null; +export declare function lab2RgbToken(token: ColorToken): ColorToken | null; +export declare function lch2RgbToken(token: ColorToken): ColorToken | null; +export declare function color2RgbToken(token: ColorToken): ColorToken | null; +export declare function hex2rgbvalues(token: ColorToken): number[]; +export declare function hwb2rgbvalues(token: ColorToken): number[] | null; +export declare function hsl2rgbvalues(token: ColorToken): number[] | null; +export declare function hsl2srgbvalues(token: ColorToken): number[] | null; +export declare function cmyk2rgbvalues(token: ColorToken): number[] | null; +export declare function oklab2rgbvalues(token: ColorToken): number[] | null; +export declare function oklch2rgbvalues(token: ColorToken): number[] | null; +export declare function lab2rgbvalues(token: ColorToken): number[] | null; +export declare function lch2rgbvalues(token: ColorToken): number[] | null; diff --git a/dist/lib/syntax/color/srgb.d.ts b/dist/lib/syntax/color/srgb.d.ts new file mode 100644 index 00000000..7a6924c0 --- /dev/null +++ b/dist/lib/syntax/color/srgb.d.ts @@ -0,0 +1,23 @@ +import type { ColorToken, IdentToken } from "../../../@types/index.d.ts"; +export declare function srgbvalues(token: ColorToken | IdentToken): number[] | null; +export declare function rgb2srgb(token: ColorToken): number[] | null; +export declare function rgb2srgbvalues(token: ColorToken): number[] | null; +export declare function rgbvalues2srgbvalues(r: number, g: number, b: number, a?: number | null): number[] | null; +export declare function hex2srgbvalues(token: ColorToken): number[]; +export declare function xyz2srgb(x: number, y: number, z: number, alpha?: number | null): number[]; +export declare function hwb2srgbvalues(token: ColorToken): number[] | null; +export declare function hsl2srgb(token: ColorToken): number[] | null; +export declare function cmyk2srgbvalues(token: ColorToken): number[] | null; +export declare function oklab2srgbvalues(token: ColorToken): number[] | null; +export declare function oklch2srgbvalues(token: ColorToken): number[] | null; +export declare function hslvalues(token: ColorToken): { + h: number; + s: number; + l: number; + a?: number | null; +} | null; +export declare function hslvalues2srgbvalues(h: number, s: number, l: number, a?: number | null): number[]; +export declare function lab2srgbvalues(token: ColorToken): number[] | null; +export declare function lch2srgbvalues(token: ColorToken): number[] | null; +export declare function srgb2lsrgbvalues(r: number, g: number, b: number, a?: number | null): number[]; +export declare function lsrgb2srgbvalues(r: number, g: number, b: number, alpha?: number | null): number[]; diff --git a/dist/lib/syntax/color/utils/components.d.ts b/dist/lib/syntax/color/utils/components.d.ts new file mode 100644 index 00000000..225c1a8c --- /dev/null +++ b/dist/lib/syntax/color/utils/components.d.ts @@ -0,0 +1,2 @@ +import type { ColorToken, IdentToken, Token } from "../../../../@types/index.d.ts"; +export declare function getComponents(token: ColorToken | IdentToken): Token[] | null; diff --git a/dist/lib/syntax/color/utils/distance.d.ts b/dist/lib/syntax/color/utils/distance.d.ts new file mode 100644 index 00000000..2393e688 --- /dev/null +++ b/dist/lib/syntax/color/utils/distance.d.ts @@ -0,0 +1,18 @@ +import type { ColorToken } from "../../../../@types/index.d.ts"; +/** + * Calculate the distance between two okLab colors. + * @param okLab1 + * @param okLab2 + * + * @private + */ +export declare function okLabDistance(okLab1: [number, number, number], okLab2: [number, number, number]): number; +/** + * Check if two colors are close in okLab space. + * @param color1 + * @param color2 + * @param threshold + * + * @private + */ +export declare function isOkLabClose(color1: ColorToken, color2: ColorToken, threshold?: number): boolean; diff --git a/dist/lib/syntax/color/utils/matrix.d.ts b/dist/lib/syntax/color/utils/matrix.d.ts new file mode 100644 index 00000000..37d267b8 --- /dev/null +++ b/dist/lib/syntax/color/utils/matrix.d.ts @@ -0,0 +1,6 @@ +/** + * Simple matrix (and vector) multiplication + * Warning: No error handling for incompatible dimensions! + * @author Lea Verou 2020 MIT License + */ +export declare function multiplyMatrices(A: number[] | number[][], B: number[] | number[][]): number[]; diff --git a/dist/lib/syntax/color/xyz.d.ts b/dist/lib/syntax/color/xyz.d.ts new file mode 100644 index 00000000..d09881ef --- /dev/null +++ b/dist/lib/syntax/color/xyz.d.ts @@ -0,0 +1,5 @@ +export declare function lab2xyz(l: number, a: number, b: number, alpha?: number): number[]; +export declare function XYZ_to_lin_sRGB(x: number, y: number, z: number, alpha?: number | null): number[]; +export declare function XYZ_D50_to_D65(x: number, y: number, z: number): number[]; +export declare function srgb2xyz(r: number, g: number, b: number, alpha?: number): number[]; +export declare function srgb2xyz_d50(r: number, g: number, b: number, alpha?: number): number[]; diff --git a/dist/lib/syntax/color/xyzd50.d.ts b/dist/lib/syntax/color/xyzd50.d.ts new file mode 100644 index 00000000..b0d0d80f --- /dev/null +++ b/dist/lib/syntax/color/xyzd50.d.ts @@ -0,0 +1,4 @@ +export declare function srgb2xyzd50values(r: number, g: number, b: number, alpha?: number | null): number[]; +export declare function xyzd502lch(x: number, y: number, z: number, alpha?: number): number[]; +export declare function XYZ_D65_to_D50(x: number, y: number, z: number, alpha?: number | null): number[]; +export declare function xyzd502srgb(x: number, y: number, z: number, alpha?: number | null): number[]; diff --git a/dist/lib/syntax/constants.d.ts b/dist/lib/syntax/constants.d.ts new file mode 100644 index 00000000..7c418ca1 --- /dev/null +++ b/dist/lib/syntax/constants.d.ts @@ -0,0 +1,67 @@ +import { EnumToken } from "../ast/types.ts"; +export declare const mFLT: Set; +export declare const mFGT: Set; +export declare const tokensMap: Map; +export declare const urlTokenMatcher: RegExp; +export declare const tokensfuncDefMap: Map; +export declare const tokensfuncSet: Set; +export declare const colorPrecision = 6; +export declare const anglePrecision = 0.001; +export declare const colorRange: { + lab: { + l: number[]; + a: number[]; + b: number[]; + }; + lch: { + l: number[]; + c: number[]; + h: number[]; + }; + oklab: { + l: number[]; + a: number[]; + b: number[]; + }; + oklch: { + l: number[]; + a: number[]; + b: number[]; + }; +}; +export declare const wildCardFuncs: string[]; +export declare const mathFuncs: string[]; +export declare const mediaTypes: string[]; +export declare const pageMarginBoxType: Set; +export declare const urlFunc: string[]; +export declare const timelineFunc: string[]; +export declare const gridTemplateFunc: string[]; +export declare const generalEnclosedFunc: string[]; +export declare const supportFunc: string[]; +export declare const whenElseFunc: string[]; +export declare const containerFunc: string[]; +export declare const timingFunc: string[]; +export declare const colorsFunc: string[]; +export declare const imageFunc: string[]; +export declare const transformFunctions: string[]; +export declare const funcLike: EnumToken[]; +export declare const colorFuncColorSpace: string[]; +export declare const D50: number[]; +export declare const k: number; +export declare const e: number; +export declare const nonStandardColors: Set; +export declare const systemColors: Set; +export declare const deprecatedSystemColors: Set; +export declare const COLORS_NAMES: { + [key: string]: string; +}; +export declare const NAMES_COLORS: { + [key: string]: string; +}; +export declare const trimTokenSpace: Set; +export declare const definedPropertySettings: { + configurable: boolean; + enumerable: boolean; + writable: boolean; +}; +export declare const combinators: string[]; diff --git a/dist/lib/syntax/syntax.d.ts b/dist/lib/syntax/syntax.d.ts new file mode 100644 index 00000000..d9031e5a --- /dev/null +++ b/dist/lib/syntax/syntax.d.ts @@ -0,0 +1,38 @@ +import type { AngleToken, DimensionToken, ErrorDescription, FlexToken, FrequencyToken, LengthToken, ResolutionToken, TimeToken, Token } from "../../@types/index.d.ts"; +export declare const dimensionUnits: Set; +export declare const pseudoElements: string[]; +export declare const pseudoAliasMap: Record; +export declare const webkitExtensions: Set; +export declare const mozExtensions: Set; +export declare const renamedStandardProperties: Map; +export declare function isLength(dimension: DimensionToken): boolean; +export declare function isResolution(dimension: DimensionToken): boolean; +export declare function isAngle(dimension: DimensionToken): boolean; +export declare function isTime(dimension: DimensionToken): boolean; +export declare function isFrequency(dimension: DimensionToken): boolean; +export declare function isColorspace(token: Token): boolean; +export declare function isRectangularOrthogonalColorspace(token: Token): boolean; +export declare function isPolarColorspace(token: Token): boolean; +export declare function isHueInterpolationMethod(token: Token | Token[]): boolean; +export declare function isIdentColor(token: Token): boolean; +export declare function isPercentageToken(token: Token): boolean; +export declare function isColor(token: Token, errors?: ErrorDescription[]): boolean; +export declare function parseColor(token: Token): Token; +export declare function isLetter(codepoint: number): boolean; +export declare function isIdentStart(codepoint: number): boolean; +export declare function isDigit(codepoint: number): boolean; +export declare function isIdentCodepoint(codepoint: number): boolean; +export declare function isIdent(name: string): boolean; +export declare function isNonPrintable(codepoint: number): boolean; +export declare function isPseudo(name: string): boolean; +export declare function isHash(name: string): boolean; +export declare function isNumber(name: string): boolean; +export declare function isPercentage(name: string): boolean; +export declare function isFlex(dimension: DimensionToken): boolean; +export declare function parseDimension(name: string): DimensionToken | LengthToken | AngleToken | FlexToken | TimeToken | ResolutionToken | FrequencyToken | null; +export declare function isHexColor(name: string): boolean; +export declare function isFunction(name: string): boolean; +export declare function isAtKeyword(name: string): boolean; +export declare function isNewLine(codepoint: number): boolean; +export declare function isWhiteSpace(codepoint: number): boolean; +export declare function isValue(token: Token): boolean; diff --git a/dist/lib/validation/config.d.ts b/dist/lib/validation/config.d.ts new file mode 100644 index 00000000..63c9e290 --- /dev/null +++ b/dist/lib/validation/config.d.ts @@ -0,0 +1,14 @@ +import type { ValidationConfiguration } from "../../@types/validation.d.ts"; +import type { ValidationToken } from "./parser/types.d.ts"; +export interface ValidationSyntaxRule { + acceptAnyDeclarations: boolean; + acceptAnyRules: boolean; + getRules: () => ValidationToken[]; + getBlockRules: () => ValidationToken[] | null; + getPreludeRules: () => ValidationToken[] | null; + getPropertyDescriptors: () => Record | null; +} +export declare function getSyntaxConfig(): ValidationConfiguration; +export declare const getSyntax: (...args: any[]) => any; +export declare const getParsedSyntax: (...args: any[]) => any; +export declare const getSyntaxRule: (...args: any[]) => any; diff --git a/dist/lib/validation/json.d.ts b/dist/lib/validation/json.d.ts new file mode 100644 index 00000000..9aff0736 --- /dev/null +++ b/dist/lib/validation/json.d.ts @@ -0,0 +1,2 @@ +import config from "./config.json"; +export { config }; diff --git a/dist/lib/validation/match.d.ts b/dist/lib/validation/match.d.ts new file mode 100644 index 00000000..1948bc2e --- /dev/null +++ b/dist/lib/validation/match.d.ts @@ -0,0 +1,38 @@ +import type { ErrorDescription, ParserOptions, Token, ValidationOptions } from "../../@types/index.d.ts"; +import { EnumToken } from "../ast/types.ts"; +import type { ValidationToken } from "./parser/types.d.ts"; +import type { ValidationContext, ValidationMatch } from "./types.d.ts"; +import type { ValidationMediaFeature } from "../../@types/validation.d.ts"; +export declare const funcTypes: EnumToken[]; +export declare function trimArray(tokens: Token[]): Token[]; +export declare function isMFName(featureName: string): boolean; +/** + * + * @param featureName + * @returns + */ +export declare function getMFInfo(featureName: string): ValidationMediaFeature | null; +/** + * + * @param featureName + * @param tokens + * @returns object with: + * - valid: boolean. true the media feaure is known or is a custom property. false otherwise + * - success: boolean. validation result + */ +export declare function isMFValue(featureName: string, tokens: Token[], isMFRange?: boolean): { + valid: boolean; + success: boolean; + isValueAllowed?: boolean; +}; +export declare function isStyleRangeValue(tokens: Token[]): { + success: boolean; + errors: ErrorDescription[]; +}; +export declare function createValidationContext(tokens: Token[]): ValidationContext; +export declare function matchSelectorSyntax(stream: Token[], errors: ErrorDescription[], options: ParserOptions | ValidationOptions, nested?: boolean): { + success: boolean; + errors: ErrorDescription[]; +}; +export declare function matchAllSyntax(syntaxes: ValidationToken[] | null, context: ValidationContext, options: ParserOptions): ValidationMatch; +export declare function matchOccurenceSyntax(syntax: ValidationToken, context: ValidationContext, options: ValidationOptions | ParserOptions): ValidationMatch; diff --git a/dist/lib/validation/parser/parse.d.ts b/dist/lib/validation/parser/parse.d.ts new file mode 100644 index 00000000..2f2f0adb --- /dev/null +++ b/dist/lib/validation/parser/parse.d.ts @@ -0,0 +1,8 @@ +import type { Position, ValidationToken } from "./types.d.ts"; +export declare function trimSyntaxArray(tokens: ValidationToken[]): ValidationToken[]; +export declare function tokenizeSyntax(syntax: string, position?: Position, currentPosition?: Position): Generator; +export declare function parseSyntax(syntax: string): ValidationToken[]; +export declare function renderSyntax(token: ValidationToken, options?: { + minify?: boolean; + indent?: number; +}): string; diff --git a/dist/lib/validation/parser/typedef.d.ts b/dist/lib/validation/parser/typedef.d.ts new file mode 100644 index 00000000..afc4d532 --- /dev/null +++ b/dist/lib/validation/parser/typedef.d.ts @@ -0,0 +1,95 @@ +export declare enum ValidationTokenEnum { + Root = 0, + Keyword = 1, + PropertyType = 2, + DeclarationType = 3, + AtRule = 4, + FunctionDefinition = 5, + OpenBracket = 6, + CloseBracket = 7, + OpenParenthesis = 8, + CloseParenthesis = 9, + Comma = 10, + Pipe = 11, + Column = 12, + Star = 13, + OpenCurlyBrace = 14, + CloseCurlyBrace = 15, + HashMark = 16, + QuestionMark = 17, + Function = 18, + Number = 19, + Whitespace = 20, + Parenthesis = 21, + Bracket = 22, + Block = 23, + Plus = 24, + Separator = 25, + Exclamation = 26, + Ampersand = 27, + PipeToken = 28, + ColumnToken = 29, + AmpersandToken = 30, + Parens = 31, + PseudoClassToken = 32, + PseudoClassFunctionToken = 33, + StringToken = 34, + AtRuleDefinition = 35, + DeclarationNameToken = 36, + DeclarationDefinitionToken = 37, + SemiColon = 38, + Character = 39, + InfinityToken = 40, + LessThan = 41, + GreaterThan = 42, + /** + * end of token stream + */ + EOF = 43, + /** + * optional group or tokens, used to group validation tokens + * + * ```ts + * // #? , -> [#? ,]? + * // , ]#? -> [, ]#?]? + * ``` + */ + OptionalGroupToken = 44, + /** + * dimension token + * + * ```ts + * //