UNPKG

sortier

Version:
69 lines (68 loc) 2.66 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.Reprinter = void 0; const postcss_less_1 = require("postcss-less"); // @ts-ignore the types are all messed up for this package // - https://arethetypeswrong.github.io/?p=postcss-scss const postcss_scss_1 = require("postcss-scss"); const string_utils_js_1 = require("../../utilities/string-utils.js"); const index_js_1 = require("../sortDeclarations/index.js"); 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 string_utils_js_1.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 postcss_less_1.parse; } if (options.parser === "scss") { return postcss_scss_1.parse; } // If the user didn't override the parser type, try to infer it const isLess = string_utils_js_1.StringUtils.stringEndsWithAny(filename, Reprinter.LESS_EXTENSIONS); if (isLess) { return postcss_less_1.parse; } const isScss = string_utils_js_1.StringUtils.stringEndsWithAny(filename, Reprinter.SCSS_EXTENSIONS); if (isScss) { return postcss_scss_1.parse; } 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 = (0, index_js_1.sortDeclarations)(node, fileContents, options.sortDeclarations); return fileContents; } } exports.Reprinter = Reprinter;