UNPKG

sortier

Version:
65 lines (64 loc) 2.42 kB
import { parse as lessParse } from "postcss-less"; // @ts-ignore the types are all messed up for this package // - https://arethetypeswrong.github.io/?p=postcss-scss import { parse as scssParse } from "postcss-scss"; import { StringUtils } from "../../utilities/string-utils.js"; import { sortDeclarations } from "../sortDeclarations/index.js"; export class Reprinter { static LESS_EXTENSIONS = [".less", ".less.txt"]; static SCSS_EXTENSIONS = [".css", ".css.txt", ".scss", ".scss.txt"]; getRewrittenContents(filename, fileContents, options) { const validatedOptions = this.getValidatedOptions(options); const parser = this.getParser(validatedOptions, filename); const ast = parser(fileContents, { // sourcesContent: true, }); return this.sortNode(validatedOptions, ast, fileContents); } isFileSupported(filename) { return StringUtils.stringEndsWithAny(filename, [...Reprinter.SCSS_EXTENSIONS, ...Reprinter.LESS_EXTENSIONS]); } getValidatedOptions(appOptions) { const partialOptions = appOptions.css; return { sortDeclarations: { overrides: [], }, ...partialOptions, }; } getParser(options, filename) { // If the options overide the parser type if (options.parser === "less") { return lessParse; } if (options.parser === "scss") { return scssParse; } // If the user didn't override the parser type, try to infer it const isLess = StringUtils.stringEndsWithAny(filename, Reprinter.LESS_EXTENSIONS); if (isLess) { return lessParse; } const isScss = StringUtils.stringEndsWithAny(filename, Reprinter.SCSS_EXTENSIONS); if (isScss) { return scssParse; } throw new Error("File not supported"); } sortNode(options, node, fileContents) { const rules = []; for (const child of node.nodes) { switch (child.type) { case "rule": rules.push(child); break; } } for (const rule of rules) { fileContents = this.sortNode(options, rule, fileContents); } fileContents = sortDeclarations(node, fileContents, options.sortDeclarations); return fileContents; } }