feat(planning): grille hebdomadaire complète avec API et filtres

- Connexion API via proxy Angular (résolution CORS, base path /api)
- Import CSS ng-zorro global pour les modales et composants
- Filtres Camion/Show câblés sur l'affichage de la grille
- Camions affichés via TrucksService (linkés au show du même créneau)
- Panneau de détails : spectacles + camions du jour sélectionné
- Modale de création de spectacle stylisée avec fond et centrage
- Positionnement précis des events à la minute dans leur créneau
- Auto-scroll vers l'heure courante au chargement
- Ligne "maintenant" sur la colonne du jour actuel
- Régénération des services OpenAPI (nouveaux noms de types)

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
2026-05-27 20:36:03 +02:00
parent 150b97cd2e
commit 654b297e2e
3131 changed files with 149304 additions and 104334 deletions
+13 -23
View File
@@ -1,19 +1,14 @@
import {addDataAttr} from './utils.js';
import browser from './browser.js';
/**
* @param {Window} window
* @param {Record<string, *>} options
*/
export default (window, options) => {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var tslib_1 = require("tslib");
var utils_1 = require("./utils");
var browser_1 = tslib_1.__importDefault(require("./browser"));
exports.default = (function (window, options) {
// use options from the current script tag data attribues
addDataAttr(options, browser.currentScript(window));
(0, utils_1.addDataAttr)(options, browser_1.default.currentScript(window));
if (options.isFileProtocol === undefined) {
options.isFileProtocol = /^(file|(chrome|safari)(-extension)?|resource|qrc|app):/.test(window.location.protocol);
}
// Load styles asynchronously (default: false)
//
// This is set to `false` by default, so that the body
@@ -22,32 +17,27 @@ export default (window, options) => {
//
options.async = options.async || false;
options.fileAsync = options.fileAsync || false;
// Interval between watch polls
options.poll = options.poll || (options.isFileProtocol ? 1000 : 1500);
options.env = options.env || (window.location.hostname == '127.0.0.1' ||
window.location.hostname == '0.0.0.0' ||
window.location.hostname == '0.0.0.0' ||
window.location.hostname == 'localhost' ||
(window.location.port &&
window.location.port.length > 0) ||
options.isFileProtocol ? 'development'
window.location.port.length > 0) ||
options.isFileProtocol ? 'development'
: 'production');
const dumpLineNumbers = /!dumpLineNumbers:(comments|mediaquery|all)/.exec(window.location.hash);
var dumpLineNumbers = /!dumpLineNumbers:(comments|mediaquery|all)/.exec(window.location.hash);
if (dumpLineNumbers) {
options.dumpLineNumbers = dumpLineNumbers[1];
}
if (options.useFileCache === undefined) {
options.useFileCache = true;
}
if (options.onReady === undefined) {
options.onReady = true;
}
if (options.relativeUrls) {
options.rewriteUrls = 'all';
}
};
});
//# sourceMappingURL=add-default-options.js.map
+17 -23
View File
@@ -1,38 +1,33 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var tslib_1 = require("tslib");
/**
* Kicks off less and compiles any stylesheets
* used in the browser distributed version of less
* to kick-start less using the browser api
*/
import defaultOptions from '../less/default-options.js';
import addDefaultOptions from './add-default-options.js';
import root from './index.js';
const options = defaultOptions();
var default_options_1 = tslib_1.__importDefault(require("../less/default-options"));
var add_default_options_1 = tslib_1.__importDefault(require("./add-default-options"));
var index_1 = tslib_1.__importDefault(require("./index"));
var options = (0, default_options_1.default)();
if (window.less) {
for (const key in window.less) {
for (var key in window.less) {
if (Object.prototype.hasOwnProperty.call(window.less, key)) {
options[key] = window.less[key];
}
}
}
addDefaultOptions(window, options);
(0, add_default_options_1.default)(window, options);
options.plugins = options.plugins || [];
if (window.LESS_PLUGINS) {
options.plugins = options.plugins.concat(window.LESS_PLUGINS);
}
const less = root(window, options);
export default less;
var less = (0, index_1.default)(window, options);
exports.default = less;
window.less = less;
let css;
let head;
let style;
var css;
var head;
var style;
// Always restore page visibility
function resolveOrReject(data) {
if (data.filename) {
@@ -42,7 +37,6 @@ function resolveOrReject(data) {
head.removeChild(style);
}
}
if (options.onReady) {
if (/!watch/.test(window.location.hash)) {
less.watch();
@@ -52,16 +46,16 @@ if (options.onReady) {
css = 'body { display: none !important }';
head = document.head || document.getElementsByTagName('head')[0];
style = document.createElement('style');
style.type = 'text/css';
if (style.styleSheet) {
style.styleSheet.cssText = css;
} else {
}
else {
style.appendChild(document.createTextNode(css));
}
head.appendChild(style);
}
less.registerStylesheetsImmediately();
less.pageLoadFinished = less.refresh(less.env === 'development').then(resolveOrReject, resolveOrReject);
}
//# sourceMappingURL=bootstrap.js.map
+21 -24
View File
@@ -1,65 +1,62 @@
import * as utils from './utils.js';
export default {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var tslib_1 = require("tslib");
var utils = tslib_1.__importStar(require("./utils"));
exports.default = {
createCSS: function (document, styles, sheet) {
// Strip the query-string
const href = sheet.href || '';
var href = sheet.href || '';
// If there is no title set, use the filename, minus the extension
const id = `less:${sheet.title || utils.extractId(href)}`;
var id = "less:".concat(sheet.title || utils.extractId(href));
// If this has already been inserted into the DOM, we may need to replace it
const oldStyleNode = document.getElementById(id);
let keepOldStyleNode = false;
var oldStyleNode = document.getElementById(id);
var keepOldStyleNode = false;
// Create a new stylesheet node for insertion or (if necessary) replacement
const styleNode = document.createElement('style');
var styleNode = document.createElement('style');
styleNode.setAttribute('type', 'text/css');
if (sheet.media) {
styleNode.setAttribute('media', sheet.media);
}
styleNode.id = id;
if (!styleNode.styleSheet) {
styleNode.appendChild(document.createTextNode(styles));
// If new contents match contents of oldStyleNode, don't replace oldStyleNode
keepOldStyleNode = (oldStyleNode !== null && oldStyleNode.childNodes.length > 0 && styleNode.childNodes.length > 0 &&
oldStyleNode.firstChild.nodeValue === styleNode.firstChild.nodeValue);
}
const head = document.getElementsByTagName('head')[0];
var head = document.getElementsByTagName('head')[0];
// If there is no oldStyleNode, just append; otherwise, only append if we need
// to replace oldStyleNode with an updated stylesheet
if (oldStyleNode === null || keepOldStyleNode === false) {
const nextEl = sheet && sheet.nextSibling || null;
var nextEl = sheet && sheet.nextSibling || null;
if (nextEl) {
nextEl.parentNode.insertBefore(styleNode, nextEl);
} else {
}
else {
head.appendChild(styleNode);
}
}
if (oldStyleNode && keepOldStyleNode === false) {
oldStyleNode.parentNode.removeChild(oldStyleNode);
}
// For IE.
// This needs to happen *after* the style element is added to the DOM, otherwise IE 7 and 8 may crash.
// See http://social.msdn.microsoft.com/Forums/en-US/7e081b65-878a-4c22-8e68-c10d39c2ed32/internet-explorer-crashes-appending-style-element-to-head
if (styleNode.styleSheet) {
try {
styleNode.styleSheet.cssText = styles;
} catch (e) {
}
catch (e) {
throw new Error('Couldn\'t reassign styleSheet.cssText.');
}
}
},
currentScript: function(window) {
const document = window.document;
return document.currentScript || (() => {
const scripts = document.getElementsByTagName('script');
currentScript: function (window) {
var document = window.document;
return document.currentScript || (function () {
var scripts = document.getElementsByTagName('script');
return scripts[scripts.length - 1];
})();
}
};
//# sourceMappingURL=browser.js.map
+19 -17
View File
@@ -1,36 +1,37 @@
"use strict";
// Cache system is a bit outdated and could do with work
export default (window, options, logger) => {
let cache = null;
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = (function (window, options, logger) {
var cache = null;
if (options.env !== 'development') {
try {
cache = (typeof window.localStorage === 'undefined') ? null : window.localStorage;
} catch (_) {}
}
catch (_) { }
}
return {
setCSS: function(path, lastModified, modifyVars, styles) {
setCSS: function (path, lastModified, modifyVars, styles) {
if (cache) {
logger.info(`saving ${path} to cache.`);
logger.info("saving ".concat(path, " to cache."));
try {
cache.setItem(path, styles);
cache.setItem(`${path}:timestamp`, lastModified);
cache.setItem("".concat(path, ":timestamp"), lastModified);
if (modifyVars) {
cache.setItem(`${path}:vars`, JSON.stringify(modifyVars));
cache.setItem("".concat(path, ":vars"), JSON.stringify(modifyVars));
}
} catch (e) {
}
catch (e) {
// TODO - could do with adding more robust error handling
logger.error(`failed to save "${path}" to local storage for caching.`);
logger.error("failed to save \"".concat(path, "\" to local storage for caching."));
}
}
},
getCSS: function(path, webInfo, modifyVars) {
const css = cache && cache.getItem(path);
const timestamp = cache && cache.getItem(`${path}:timestamp`);
let vars = cache && cache.getItem(`${path}:vars`);
getCSS: function (path, webInfo, modifyVars) {
var css = cache && cache.getItem(path);
var timestamp = cache && cache.getItem("".concat(path, ":timestamp"));
var vars = cache && cache.getItem("".concat(path, ":vars"));
modifyVars = modifyVars || {};
vars = vars || '{}'; // if not set, treat as the JSON representation of an empty object
if (timestamp && webInfo.lastModified &&
(new Date(webInfo.lastModified).valueOf() ===
new Date(timestamp).valueOf()) &&
@@ -40,4 +41,5 @@ export default (window, options, logger) => {
}
}
};
};
});
//# sourceMappingURL=cache.js.map
+44 -52
View File
@@ -1,45 +1,41 @@
import * as utils from './utils.js';
import browser from './browser.js';
export default (window, less, options) => {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var tslib_1 = require("tslib");
var utils = tslib_1.__importStar(require("./utils"));
var browser_1 = tslib_1.__importDefault(require("./browser"));
exports.default = (function (window, less, options) {
function errorHTML(e, rootHref) {
const id = `less-error-message:${utils.extractId(rootHref || '')}`;
const template = '<li><label>{line}</label><pre class="{class}">{content}</pre></li>';
const elem = window.document.createElement('div');
let timer;
let content;
const errors = [];
const filename = e.filename || rootHref;
const filenameNoPath = filename.match(/([^/]+(\?.*)?)$/)[1];
elem.id = id;
var id = "less-error-message:".concat(utils.extractId(rootHref || ''));
var template = '<li><label>{line}</label><pre class="{class}">{content}</pre></li>';
var elem = window.document.createElement('div');
var timer;
var content;
var errors = [];
var filename = e.filename || rootHref;
var filenameNoPath = filename.match(/([^/]+(\?.*)?)$/)[1];
elem.id = id;
elem.className = 'less-error-message';
content = `<h3>${e.type || 'Syntax'}Error: ${e.message || 'There is an error in your .less file'}` +
`</h3><p>in <a href="${filename}">${filenameNoPath}</a> `;
const errorline = (e, i, classname) => {
content = "<h3>".concat(e.type || 'Syntax', "Error: ").concat(e.message || 'There is an error in your .less file') +
"</h3><p>in <a href=\"".concat(filename, "\">").concat(filenameNoPath, "</a> ");
var errorline = function (e, i, classname) {
if (e.extract[i] !== undefined) {
errors.push(template.replace(/\{line\}/, (parseInt(e.line, 10) || 0) + (i - 1))
.replace(/\{class\}/, classname)
.replace(/\{content\}/, e.extract[i]));
}
};
if (e.line) {
errorline(e, 0, '');
errorline(e, 1, 'line');
errorline(e, 2, '');
content += `on line ${e.line}, column ${e.column + 1}:</p><ul>${errors.join('')}</ul>`;
content += "on line ".concat(e.line, ", column ").concat(e.column + 1, ":</p><ul>").concat(errors.join(''), "</ul>");
}
if (e.stack && (e.extract || options.logLevel >= 4)) {
content += `<br/>Stack Trace</br />${e.stack.split('\n').slice(1).join('<br/>')}`;
content += "<br/>Stack Trace</br />".concat(e.stack.split('\n').slice(1).join('<br/>'));
}
elem.innerHTML = content;
// CSS for error messages
browser.createCSS(window.document, [
browser_1.default.createCSS(window.document, [
'.less-error-message ul, .less-error-message li {',
'list-style-type: none;',
'margin-right: 15px;',
@@ -77,7 +73,6 @@ export default (window, less, options) => {
'border-bottom: 1px dashed red;',
'}'
].join('\n'), { title: 'error-message' });
elem.style.cssText = [
'font-family: Arial, sans-serif',
'border: 1px solid #e00',
@@ -89,15 +84,15 @@ export default (window, less, options) => {
'padding: 15px',
'margin-bottom: 15px'
].join(';');
if (options.env === 'development') {
timer = setInterval(() => {
const document = window.document;
const body = document.body;
timer = setInterval(function () {
var document = window.document;
var body = document.body;
if (body) {
if (document.getElementById(id)) {
body.replaceChild(elem, document.getElementById(id));
} else {
}
else {
body.insertBefore(elem, body.firstChild);
}
clearInterval(timer);
@@ -105,66 +100,63 @@ export default (window, less, options) => {
}, 10);
}
}
function removeErrorHTML(path) {
const node = window.document.getElementById(`less-error-message:${utils.extractId(path)}`);
var node = window.document.getElementById("less-error-message:".concat(utils.extractId(path)));
if (node) {
node.parentNode.removeChild(node);
}
}
function removeErrorConsole() {
// no action
}
function removeError(path) {
if (!options.errorReporting || options.errorReporting === 'html') {
removeErrorHTML(path);
} else if (options.errorReporting === 'console') {
}
else if (options.errorReporting === 'console') {
removeErrorConsole(path);
} else if (typeof options.errorReporting === 'function') {
}
else if (typeof options.errorReporting === 'function') {
options.errorReporting('remove', path);
}
}
function errorConsole(e, rootHref) {
const template = '{line} {content}';
const filename = e.filename || rootHref;
const errors = [];
let content = `${e.type || 'Syntax'}Error: ${e.message || 'There is an error in your .less file'} in ${filename}`;
const errorline = (e, i, classname) => {
var template = '{line} {content}';
var filename = e.filename || rootHref;
var errors = [];
var content = "".concat(e.type || 'Syntax', "Error: ").concat(e.message || 'There is an error in your .less file', " in ").concat(filename);
var errorline = function (e, i, classname) {
if (e.extract[i] !== undefined) {
errors.push(template.replace(/\{line\}/, (parseInt(e.line, 10) || 0) + (i - 1))
.replace(/\{class\}/, classname)
.replace(/\{content\}/, e.extract[i]));
}
};
if (e.line) {
errorline(e, 0, '');
errorline(e, 1, 'line');
errorline(e, 2, '');
content += ` on line ${e.line}, column ${e.column + 1}:\n${errors.join('\n')}`;
content += " on line ".concat(e.line, ", column ").concat(e.column + 1, ":\n").concat(errors.join('\n'));
}
if (e.stack && (e.extract || options.logLevel >= 4)) {
content += `\nStack Trace\n${e.stack}`;
content += "\nStack Trace\n".concat(e.stack);
}
less.logger.error(content);
}
function error(e, rootHref) {
if (!options.errorReporting || options.errorReporting === 'html') {
errorHTML(e, rootHref);
} else if (options.errorReporting === 'console') {
}
else if (options.errorReporting === 'console') {
errorConsole(e, rootHref);
} else if (typeof options.errorReporting === 'function') {
}
else if (typeof options.errorReporting === 'function') {
options.errorReporting('add', e, rootHref);
}
}
return {
add: error,
remove: removeError
};
};
});
//# sourceMappingURL=error-reporting.js.map
+42 -52
View File
@@ -1,112 +1,102 @@
import AbstractFileManager from '../less/environment/abstract-file-manager.js';
let options;
let logger;
let fileCache = {};
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var tslib_1 = require("tslib");
var abstract_file_manager_js_1 = tslib_1.__importDefault(require("../less/environment/abstract-file-manager.js"));
var options;
var logger;
var fileCache = {};
// TODOS - move log somewhere. pathDiff and doing something similar in node. use pathDiff in the other browser file for the initial load
const FileManager = function() {}
FileManager.prototype = Object.assign(new AbstractFileManager(), {
alwaysMakePathsAbsolute() {
var FileManager = function () { };
FileManager.prototype = Object.assign(new abstract_file_manager_js_1.default(), {
alwaysMakePathsAbsolute: function () {
return true;
},
join(basePath, laterPath) {
join: function (basePath, laterPath) {
if (!basePath) {
return laterPath;
}
return this.extractUrlParts(laterPath, basePath).path;
},
doXHR(url, type, callback, errback) {
const xhr = new XMLHttpRequest();
const async = options.isFileProtocol ? options.fileAsync : true;
doXHR: function (url, type, callback, errback) {
var xhr = new XMLHttpRequest();
var async = options.isFileProtocol ? options.fileAsync : true;
if (typeof xhr.overrideMimeType === 'function') {
xhr.overrideMimeType('text/css');
}
logger.debug(`XHR: Getting '${url}'`);
logger.debug("XHR: Getting '".concat(url, "'"));
xhr.open('GET', url, async);
xhr.setRequestHeader('Accept', type || 'text/x-less, text/css; q=0.9, */*; q=0.5');
xhr.send(null);
function handleResponse(xhr, callback, errback) {
if (xhr.status >= 200 && xhr.status < 300) {
callback(xhr.responseText,
xhr.getResponseHeader('Last-Modified'));
} else if (typeof errback === 'function') {
callback(xhr.responseText, xhr.getResponseHeader('Last-Modified'));
}
else if (typeof errback === 'function') {
errback(xhr.status, url);
}
}
if (options.isFileProtocol && !options.fileAsync) {
if (xhr.status === 0 || (xhr.status >= 200 && xhr.status < 300)) {
callback(xhr.responseText);
} else {
}
else {
errback(xhr.status, url);
}
} else if (async) {
xhr.onreadystatechange = () => {
}
else if (async) {
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) {
handleResponse(xhr, callback, errback);
}
};
} else {
}
else {
handleResponse(xhr, callback, errback);
}
},
supports() {
supports: function () {
return true;
},
clearFileCache() {
clearFileCache: function () {
fileCache = {};
},
loadFile(filename, currentDirectory, options) {
loadFile: function (filename, currentDirectory, options) {
// TODO: Add prefix support like less-node?
// What about multiple paths?
if (currentDirectory && !this.isPathAbsolute(filename)) {
filename = currentDirectory + filename;
}
filename = options.ext ? this.tryAppendExtension(filename, options.ext) : filename;
options = options || {};
// sheet may be set to the stylesheet for the initial load or a collection of properties including
// some context variables for imports
const hrefParts = this.extractUrlParts(filename, window.location.href);
const href = hrefParts.url;
const self = this;
return new Promise((resolve, reject) => {
var hrefParts = this.extractUrlParts(filename, window.location.href);
var href = hrefParts.url;
var self = this;
return new Promise(function (resolve, reject) {
if (options.useFileCache && fileCache[href]) {
try {
const lessText = fileCache[href];
return resolve({ contents: lessText, filename: href, webInfo: { lastModified: new Date() }});
} catch (e) {
return reject({ filename: href, message: `Error loading file ${href} error was ${e.message}` });
var lessText = fileCache[href];
return resolve({ contents: lessText, filename: href, webInfo: { lastModified: new Date() } });
}
catch (e) {
return reject({ filename: href, message: "Error loading file ".concat(href, " error was ").concat(e.message) });
}
}
self.doXHR(href, options.mime, function doXHRCallback(data, lastModified) {
// per file cache
fileCache[href] = data;
// Use remote copy (re-parse)
resolve({ contents: data, filename: href, webInfo: { lastModified }});
resolve({ contents: data, filename: href, webInfo: { lastModified: lastModified } });
}, function doXHRError(status, url) {
reject({ type: 'File', message: `'${url}' wasn't found (${status})`, href });
reject({ type: 'File', message: "'".concat(url, "' wasn't found (").concat(status, ")"), href: href });
});
});
}
});
export default (opts, log) => {
exports.default = (function (opts, log) {
options = opts;
logger = log;
return FileManager;
}
});
//# sourceMappingURL=file-manager.js.map
+12 -12
View File
@@ -1,28 +1,28 @@
import functionRegistry from './../less/functions/function-registry.js';
export default () => {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var tslib_1 = require("tslib");
var function_registry_1 = tslib_1.__importDefault(require("./../less/functions/function-registry"));
exports.default = (function () {
function imageSize() {
throw {
type: 'Runtime',
message: 'Image size functions are not supported in browser version of less'
};
}
const imageFunctions = {
'image-size': function(filePathNode) {
var imageFunctions = {
'image-size': function (filePathNode) {
imageSize(this, filePathNode);
return -1;
},
'image-width': function(filePathNode) {
'image-width': function (filePathNode) {
imageSize(this, filePathNode);
return -1;
},
'image-height': function(filePathNode) {
'image-height': function (filePathNode) {
imageSize(this, filePathNode);
return -1;
}
};
functionRegistry.addMultiple(imageFunctions);
};
function_registry_1.default.addMultiple(imageFunctions);
});
//# sourceMappingURL=image-size.js.map
+105 -131
View File
@@ -1,284 +1,258 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var tslib_1 = require("tslib");
//
// index.js
// Should expose the additional browser functions on to the less object
//
import {addDataAttr} from './utils.js';
import lessRoot from '../less/index.js';
import browser from './browser.js';
import FM from './file-manager.js';
import PluginLoader from './plugin-loader.js';
import LogListener from './log-listener.js';
import ErrorReporting from './error-reporting.js';
import Cache from './cache.js';
import ImageSize from './image-size.js';
import pkg from '../../package.json';
/**
* @param {Window} window
* @param {Object} options
*/
export default (window, options) => {
const document = window.document;
const less = lessRoot(undefined, undefined, pkg.version);
var utils_1 = require("./utils");
var less_1 = tslib_1.__importDefault(require("../less"));
var browser_1 = tslib_1.__importDefault(require("./browser"));
var file_manager_1 = tslib_1.__importDefault(require("./file-manager"));
var plugin_loader_1 = tslib_1.__importDefault(require("./plugin-loader"));
var log_listener_1 = tslib_1.__importDefault(require("./log-listener"));
var error_reporting_1 = tslib_1.__importDefault(require("./error-reporting"));
var cache_1 = tslib_1.__importDefault(require("./cache"));
var image_size_1 = tslib_1.__importDefault(require("./image-size"));
exports.default = (function (window, options) {
var document = window.document;
var less = (0, less_1.default)();
less.options = options;
const environment = less.environment;
const FileManager = FM(options, less.logger);
const fileManager = new FileManager();
var environment = less.environment;
var FileManager = (0, file_manager_1.default)(options, less.logger);
var fileManager = new FileManager();
environment.addFileManager(fileManager);
less.FileManager = FileManager;
less.PluginLoader = PluginLoader;
LogListener(less, options);
const errors = ErrorReporting(window, less, options);
const cache = less.cache = options.cache || Cache(window, options, less.logger);
ImageSize(less.environment);
less.PluginLoader = plugin_loader_1.default;
(0, log_listener_1.default)(less, options);
var errors = (0, error_reporting_1.default)(window, less, options);
var cache = less.cache = options.cache || (0, cache_1.default)(window, options, less.logger);
(0, image_size_1.default)(less.environment);
// Setup user functions - Deprecate?
if (options.functions) {
less.functions.functionRegistry.addMultiple(options.functions);
}
const typePattern = /^text\/(x-)?less$/;
var typePattern = /^text\/(x-)?less$/;
function clone(obj) {
const cloned = {};
for (const prop in obj) {
var cloned = {};
for (var prop in obj) {
if (Object.prototype.hasOwnProperty.call(obj, prop)) {
cloned[prop] = obj[prop];
}
}
return cloned;
}
// only really needed for phantom
function bind(func, thisArg) {
var curryArgs = Array.prototype.slice.call(arguments, 2);
return function () {
var args = curryArgs.concat(Array.prototype.slice.call(arguments, 0));
return func.apply(thisArg, args);
};
}
function loadStyles(modifyVars) {
const styles = document.getElementsByTagName('style');
for (let style of styles) {
var styles = document.getElementsByTagName('style');
var style;
for (var i = 0; i < styles.length; i++) {
style = styles[i];
if (style.type.match(typePattern)) {
const instanceOptions = {
...clone(options),
modifyVars,
filename: document.location.href.replace(/#.*$/, '')
}
const lessText = style.innerHTML || '';
var instanceOptions = clone(options);
instanceOptions.modifyVars = modifyVars;
var lessText = style.innerHTML || '';
instanceOptions.filename = document.location.href.replace(/#.*$/, '');
/* jshint loopfunc:true */
less.render(lessText, instanceOptions, (err, result) => {
if (err) {
errors.add(err, 'inline');
} else {
// use closure to store current style
less.render(lessText, instanceOptions, bind(function (style, e, result) {
if (e) {
errors.add(e, 'inline');
}
else {
style.type = 'text/css';
if (style.styleSheet) {
style.styleSheet.cssText = result.css;
} else {
}
else {
style.innerHTML = result.css;
}
}
});
}, null, style));
}
}
}
function loadStyleSheet(sheet, callback, reload, remaining, modifyVars) {
const instanceOptions = clone(options);
addDataAttr(instanceOptions, sheet);
var instanceOptions = clone(options);
(0, utils_1.addDataAttr)(instanceOptions, sheet);
instanceOptions.mime = sheet.type;
if (modifyVars) {
instanceOptions.modifyVars = modifyVars;
}
function loadInitialFileCallback(loadedFile) {
const data = loadedFile.contents;
const path = loadedFile.filename;
const webInfo = loadedFile.webInfo;
const newFileInfo = {
var data = loadedFile.contents;
var path = loadedFile.filename;
var webInfo = loadedFile.webInfo;
var newFileInfo = {
currentDirectory: fileManager.getPath(path),
filename: path,
rootFilename: path,
rewriteUrls: instanceOptions.rewriteUrls
};
newFileInfo.entryPath = newFileInfo.currentDirectory;
newFileInfo.rootpath = instanceOptions.rootpath || newFileInfo.currentDirectory;
if (webInfo) {
webInfo.remaining = remaining;
const css = cache.getCSS(path, webInfo, instanceOptions.modifyVars);
var css = cache.getCSS(path, webInfo, instanceOptions.modifyVars);
if (!reload && css) {
webInfo.local = true;
callback(null, css, data, sheet, webInfo, path);
return;
}
}
// TODO add tests around how this behaves when reloading
errors.remove(path);
instanceOptions.rootFileInfo = newFileInfo;
less.render(data, instanceOptions, (e, result) => {
less.render(data, instanceOptions, function (e, result) {
if (e) {
e.href = path;
callback(e);
} else {
}
else {
cache.setCSS(sheet.href, webInfo.lastModified, instanceOptions.modifyVars, result.css);
callback(null, result.css, data, sheet, webInfo, path);
}
});
}
fileManager.loadFile(sheet.href, null, instanceOptions, environment)
.then(loadedFile => {
loadInitialFileCallback(loadedFile);
}).catch(err => {
console.log(err);
callback(err);
});
.then(function (loadedFile) {
loadInitialFileCallback(loadedFile);
}).catch(function (err) {
console.log(err);
callback(err);
});
}
function loadStyleSheets(callback, reload, modifyVars) {
for (let i = 0; i < less.sheets.length; i++) {
for (var i = 0; i < less.sheets.length; i++) {
loadStyleSheet(less.sheets[i], callback, reload, less.sheets.length - (i + 1), modifyVars);
}
}
function initRunningMode() {
if (less.env === 'development') {
less.watchTimer = setInterval(() => {
less.watchTimer = setInterval(function () {
if (less.watchMode) {
fileManager.clearFileCache();
/**
* @todo remove when this is typed with JSDoc
*/
// eslint-disable-next-line no-unused-vars
loadStyleSheets((e, css, _, sheet, webInfo) => {
loadStyleSheets(function (e, css, _, sheet, webInfo) {
if (e) {
errors.add(e, e.href || sheet.href);
} else if (css) {
browser.createCSS(window.document, css, sheet);
}
else if (css) {
browser_1.default.createCSS(window.document, css, sheet);
}
});
}
}, options.poll);
}
}
//
// Watch mode
//
less.watch = function () {
if (!less.watchMode ) {
if (!less.watchMode) {
less.env = 'development';
initRunningMode();
}
this.watchMode = true;
return true;
};
less.unwatch = function () {clearInterval(less.watchTimer); this.watchMode = false; return false; };
less.unwatch = function () { clearInterval(less.watchTimer); this.watchMode = false; return false; };
//
// Synchronously get all <link> tags with the 'rel' attribute set to
// "stylesheet/less".
//
less.registerStylesheetsImmediately = () => {
const links = document.getElementsByTagName('link');
less.registerStylesheetsImmediately = function () {
var links = document.getElementsByTagName('link');
less.sheets = [];
for (let i = 0; i < links.length; i++) {
for (var i = 0; i < links.length; i++) {
if (links[i].rel === 'stylesheet/less' || (links[i].rel.match(/stylesheet/) &&
(links[i].type.match(typePattern)))) {
less.sheets.push(links[i]);
}
}
};
//
// Asynchronously get all <link> tags with the 'rel' attribute set to
// "stylesheet/less", returning a Promise.
//
less.registerStylesheets = () => new Promise((resolve) => {
less.registerStylesheets = function () { return new Promise(function (resolve) {
less.registerStylesheetsImmediately();
resolve();
});
}); };
//
// With this function, it's possible to alter variables and re-render
// CSS without reloading less-files
//
less.modifyVars = record => less.refresh(true, record, false);
less.refresh = (reload, modifyVars, clearFileCache) => {
less.modifyVars = function (record) { return less.refresh(true, record, false); };
less.refresh = function (reload, modifyVars, clearFileCache) {
if ((reload || clearFileCache) && clearFileCache !== false) {
fileManager.clearFileCache();
}
return new Promise((resolve, reject) => {
let startTime;
let endTime;
let totalMilliseconds;
let remainingSheets;
return new Promise(function (resolve, reject) {
var startTime;
var endTime;
var totalMilliseconds;
var remainingSheets;
startTime = endTime = new Date();
// Set counter for remaining unprocessed sheets
remainingSheets = less.sheets.length;
if (remainingSheets === 0) {
endTime = new Date();
totalMilliseconds = endTime - startTime;
less.logger.info('Less has finished and no sheets were loaded.');
resolve({
startTime,
endTime,
totalMilliseconds,
startTime: startTime,
endTime: endTime,
totalMilliseconds: totalMilliseconds,
sheets: less.sheets.length
});
} else {
}
else {
// Relies on less.sheets array, callback seems to be guaranteed to be called for every element of the array
loadStyleSheets((e, css, _, sheet, webInfo) => {
loadStyleSheets(function (e, css, _, sheet, webInfo) {
if (e) {
errors.add(e, e.href || sheet.href);
reject(e);
return;
}
if (webInfo.local) {
less.logger.info(`Loading ${sheet.href} from cache.`);
} else {
less.logger.info(`Rendered ${sheet.href} successfully.`);
less.logger.info("Loading ".concat(sheet.href, " from cache."));
}
browser.createCSS(window.document, css, sheet);
less.logger.info(`CSS for ${sheet.href} generated in ${new Date() - endTime}ms`);
else {
less.logger.info("Rendered ".concat(sheet.href, " successfully."));
}
browser_1.default.createCSS(window.document, css, sheet);
less.logger.info("CSS for ".concat(sheet.href, " generated in ").concat(new Date() - endTime, "ms"));
// Count completed sheet
remainingSheets--;
// Check if the last remaining sheet was processed and then call the promise
if (remainingSheets === 0) {
totalMilliseconds = new Date() - startTime;
less.logger.info(`Less has finished. CSS generated in ${totalMilliseconds}ms`);
less.logger.info("Less has finished. CSS generated in ".concat(totalMilliseconds, "ms"));
resolve({
startTime,
endTime,
totalMilliseconds,
startTime: startTime,
endTime: endTime,
totalMilliseconds: totalMilliseconds,
sheets: less.sheets.length
});
}
endTime = new Date();
}, reload, modifyVars);
}
loadStyles(modifyVars);
});
};
less.refreshStyles = loadStyles;
return less;
};
});
//# sourceMappingURL=index.js.map
+31 -30
View File
@@ -1,42 +1,43 @@
export default (less, options) => {
const logLevel_debug = 4;
const logLevel_info = 3;
const logLevel_warn = 2;
const logLevel_error = 1;
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = (function (less, options) {
var logLevel_debug = 4;
var logLevel_info = 3;
var logLevel_warn = 2;
var logLevel_error = 1;
// The amount of logging in the javascript console.
// 3 - Debug, information and errors
// 2 - Information and errors
// 1 - Errors
// 0 - None
// Defaults to 2
options.logLevel = typeof options.logLevel !== 'undefined' ? options.logLevel : (options.env === 'development' ? logLevel_info : logLevel_error);
options.logLevel = typeof options.logLevel !== 'undefined' ? options.logLevel : (options.env === 'development' ? logLevel_info : logLevel_error);
if (!options.loggers) {
options.loggers = [{
debug: function(msg) {
if (options.logLevel >= logLevel_debug) {
console.log(msg);
debug: function (msg) {
if (options.logLevel >= logLevel_debug) {
console.log(msg);
}
},
info: function (msg) {
if (options.logLevel >= logLevel_info) {
console.log(msg);
}
},
warn: function (msg) {
if (options.logLevel >= logLevel_warn) {
console.warn(msg);
}
},
error: function (msg) {
if (options.logLevel >= logLevel_error) {
console.error(msg);
}
}
},
info: function(msg) {
if (options.logLevel >= logLevel_info) {
console.log(msg);
}
},
warn: function(msg) {
if (options.logLevel >= logLevel_warn) {
console.warn(msg);
}
},
error: function(msg) {
if (options.logLevel >= logLevel_error) {
console.error(msg);
}
}
}];
}];
}
for (let i = 0; i < options.loggers.length; i++) {
for (var i = 0; i < options.loggers.length; i++) {
less.logger.addListener(options.loggers[i]);
}
};
});
//# sourceMappingURL=log-listener.js.map
+10 -10
View File
@@ -1,24 +1,24 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var tslib_1 = require("tslib");
/**
* @todo Add tests for browser `@plugin`
*/
import AbstractPluginLoader from '../less/environment/abstract-plugin-loader.js';
var abstract_plugin_loader_js_1 = tslib_1.__importDefault(require("../less/environment/abstract-plugin-loader.js"));
/**
* Browser Plugin Loader
*/
const PluginLoader = function(less) {
var PluginLoader = function (less) {
this.less = less;
// Should we shim this.require for browser? Probably not?
};
PluginLoader.prototype = Object.assign(new AbstractPluginLoader(), {
loadPlugin(filename, basePath, context, environment, fileManager) {
return new Promise((fulfill, reject) => {
PluginLoader.prototype = Object.assign(new abstract_plugin_loader_js_1.default(), {
loadPlugin: function (filename, basePath, context, environment, fileManager) {
return new Promise(function (fulfill, reject) {
fileManager.loadFile(filename, basePath, context, environment)
.then(fulfill).catch(reject);
});
}
});
export default PluginLoader;
exports.default = PluginLoader;
//# sourceMappingURL=plugin-loader.js.map
+21 -19
View File
@@ -1,30 +1,32 @@
/** @param {string} href */
export function extractId(href) {
return href.replace(/^[a-z-]+:\/+?[^/]+/, '') // Remove protocol & domain
.replace(/[?&]livereload=\w+/, '') // Remove LiveReload cachebuster
.replace(/^\//, '') // Remove root /
.replace(/\.[a-zA-Z]+$/, '') // Remove simple extension
.replace(/[^.\w-]+/g, '-') // Replace illegal characters
.replace(/\./g, ':'); // Replace dots with colons(for valid id)
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.addDataAttr = exports.extractId = void 0;
function extractId(href) {
return href.replace(/^[a-z-]+:\/+?[^/]+/, '') // Remove protocol & domain
.replace(/[?&]livereload=\w+/, '') // Remove LiveReload cachebuster
.replace(/^\//, '') // Remove root /
.replace(/\.[a-zA-Z]+$/, '') // Remove simple extension
.replace(/[^.\w-]+/g, '-') // Replace illegal characters
.replace(/\./g, ':'); // Replace dots with colons(for valid id)
}
/**
* @param {Record<string, *>} options
* @param {HTMLElement | null} tag
*/
export function addDataAttr(options, tag) {
if (!tag) {return;} // in case of tag is null or undefined
for (const opt in tag.dataset) {
exports.extractId = extractId;
function addDataAttr(options, tag) {
if (!tag) {
return;
} // in case of tag is null or undefined
for (var opt in tag.dataset) {
if (Object.prototype.hasOwnProperty.call(tag.dataset, opt)) {
if (opt === 'env' || opt === 'dumpLineNumbers' || opt === 'rootpath' || opt === 'errorReporting') {
options[opt] = tag.dataset[opt];
} else {
}
else {
try {
options[opt] = JSON.parse(tag.dataset[opt]);
}
catch (_) {}
catch (_) { }
}
}
}
}
exports.addDataAttr = addDataAttr;
//# sourceMappingURL=utils.js.map
+8 -32
View File
@@ -1,43 +1,19 @@
import { createRequire } from 'module';
const require = createRequire(import.meta.url);
class SourceMapGeneratorFallback {
addMapping(){}
setSourceContent(){}
toJSON(){
return null;
}
};
export default {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = {
encodeBase64: function encodeBase64(str) {
// Avoid Buffer constructor on newer versions of Node.js.
const buffer = (Buffer.from ? Buffer.from(str) : (new Buffer(str)));
var buffer = (Buffer.from ? Buffer.from(str) : (new Buffer(str)));
return buffer.toString('base64');
},
mimeLookup: function (filename) {
try {
const mimeModule = require('mime');
return mimeModule ? mimeModule.lookup(filename) : "application/octet-stream";
} catch (e) {
return "application/octet-stream";
}
return require('mime').lookup(filename);
},
charsetLookup: function (mime) {
try {
const mimeModule = require('mime');
return mimeModule ? mimeModule.charsets.lookup(mime) : undefined;
} catch (e) {
return undefined;
}
return require('mime').charsets.lookup(mime);
},
getSourceMapGenerator: function getSourceMapGenerator() {
try {
const sourceMapModule = require('source-map');
return sourceMapModule ? sourceMapModule.SourceMapGenerator : SourceMapGeneratorFallback;
} catch (e) {
return SourceMapGeneratorFallback;
}
return require('source-map').SourceMapGenerator;
}
};
//# sourceMappingURL=environment.js.map
+45 -62
View File
@@ -1,42 +1,37 @@
import path from 'path';
import { createRequire } from 'module';
import fs from './fs.js';
import AbstractFileManager from '../less/environment/abstract-file-manager.js';
const require = createRequire(import.meta.url);
const FileManager = function() {}
FileManager.prototype = Object.assign(new AbstractFileManager(), {
supports() {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var tslib_1 = require("tslib");
var path_1 = tslib_1.__importDefault(require("path"));
var fs_1 = tslib_1.__importDefault(require("./fs"));
var abstract_file_manager_js_1 = tslib_1.__importDefault(require("../less/environment/abstract-file-manager.js"));
var FileManager = function () { };
FileManager.prototype = Object.assign(new abstract_file_manager_js_1.default(), {
supports: function () {
return true;
},
supportsSync() {
supportsSync: function () {
return true;
},
loadFile(filename, currentDirectory, options, environment, callback) {
let fullFilename;
const isAbsoluteFilename = this.isPathAbsolute(filename);
const filenamesTried = [];
const self = this;
const prefix = filename.slice(0, 1);
const explicit = prefix === '.' || prefix === '/';
let result = null;
let isNodeModule = false;
const npmPrefix = 'npm://';
loadFile: function (filename, currentDirectory, options, environment, callback) {
var fullFilename;
var isAbsoluteFilename = this.isPathAbsolute(filename);
var filenamesTried = [];
var self = this;
var prefix = filename.slice(0, 1);
var explicit = prefix === '.' || prefix === '/';
var result = null;
var isNodeModule = false;
var npmPrefix = 'npm://';
options = options || {};
const paths = isAbsoluteFilename ? [''] : [currentDirectory];
if (options.paths) { paths.push.apply(paths, options.paths); }
if (!isAbsoluteFilename && paths.indexOf('.') === -1) { paths.push('.'); }
const prefixes = options.prefixes || [''];
const fileParts = this.extractUrlParts(filename);
var paths = isAbsoluteFilename ? [''] : [currentDirectory];
if (options.paths) {
paths.push.apply(paths, options.paths);
}
if (!isAbsoluteFilename && paths.indexOf('.') === -1) {
paths.push('.');
}
var prefixes = options.prefixes || [''];
var fileParts = this.extractUrlParts(filename);
if (options.syncImport) {
getFileData(returnData, returnData);
if (callback) {
@@ -52,7 +47,6 @@ FileManager.prototype = Object.assign(new AbstractFileManager(), {
// to be closed before it continues with the next file
return new Promise(getFileData);
}
function returnData(data) {
if (!data.filename) {
result = { error: data };
@@ -61,12 +55,10 @@ FileManager.prototype = Object.assign(new AbstractFileManager(), {
result = data;
}
}
function getFileData(fulfill, reject) {
(function tryPathIndex(i) {
function tryWithExtension() {
const extFilename = options.ext ? self.tryAppendExtension(fullFilename, options.ext) : fullFilename;
var extFilename = options.ext ? self.tryAppendExtension(fullFilename, options.ext) : fullFilename;
if (extFilename !== fullFilename && !explicit && paths[i] === '.') {
try {
fullFilename = require.resolve(extFilename);
@@ -86,16 +78,9 @@ FileManager.prototype = Object.assign(new AbstractFileManager(), {
if (j < prefixes.length) {
isNodeModule = false;
fullFilename = fileParts.rawPath + prefixes[j] + fileParts.filename;
if (paths[i]) {
if (paths[i].startsWith('#')) {
// Handling paths starting with '#'
fullFilename = paths[i].substr(1) + fullFilename;
}else{
fullFilename = path.join(paths[i], fullFilename);
}
fullFilename = path_1.default.join(paths[i], fullFilename);
}
if (!explicit && paths[i] === '.') {
try {
fullFilename = require.resolve(fullFilename);
@@ -108,16 +93,15 @@ FileManager.prototype = Object.assign(new AbstractFileManager(), {
}
else {
tryWithExtension();
}
const readFileArgs = [fullFilename];
}
var readFileArgs = [fullFilename];
if (!options.rawBuffer) {
readFileArgs.push('utf-8');
}
if (options.syncImport) {
try {
const data = fs.readFileSync.apply(this, readFileArgs);
fulfill({ contents: data, filename: fullFilename});
var data = fs_1.default.readFileSync.apply(this, readFileArgs);
fulfill({ contents: data, filename: fullFilename });
}
catch (e) {
filenamesTried.push(isNodeModule ? npmPrefix + fullFilename : fullFilename);
@@ -125,32 +109,31 @@ FileManager.prototype = Object.assign(new AbstractFileManager(), {
}
}
else {
readFileArgs.push(function(e, data) {
readFileArgs.push(function (e, data) {
if (e) {
filenamesTried.push(isNodeModule ? npmPrefix + fullFilename : fullFilename);
return tryPrefix(j + 1);
}
fulfill({ contents: data, filename: fullFilename});
}
fulfill({ contents: data, filename: fullFilename });
});
fs.readFile.apply(this, readFileArgs);
fs_1.default.readFile.apply(this, readFileArgs);
}
}
else {
tryPathIndex(i + 1);
}
})(0);
} else {
reject({ type: 'File', message: `'${filename}' wasn't found. Tried - ${filenamesTried.join(',')}` });
}
else {
reject({ type: 'File', message: "'".concat(filename, "' wasn't found. Tried - ").concat(filenamesTried.join(',')) });
}
}(0));
}
},
loadFileSync(filename, currentDirectory, options, environment) {
loadFileSync: function (filename, currentDirectory, options, environment) {
options.syncImport = true;
return this.loadFile(filename, currentDirectory, options, environment);
}
});
export default FileManager;
exports.default = FileManager;
//# sourceMappingURL=file-manager.js.map
+8 -11
View File
@@ -1,14 +1,11 @@
/** @typedef {import('fs')} FS */
import nodeFs from 'fs';
import { createRequire } from 'module';
const require = createRequire(import.meta.url);
/** @type {FS} */
let fs;
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var fs;
try {
fs = require('graceful-fs');
} catch (e) {
fs = nodeFs;
}
export default fs;
catch (e) {
fs = require('fs');
}
exports.default = fs;
//# sourceMappingURL=fs.js.map
+31 -40
View File
@@ -1,59 +1,50 @@
import { createRequire } from 'module';
import Dimension from '../less/tree/dimension.js';
import Expression from '../less/tree/expression.js';
import functionRegistry from './../less/functions/function-registry.js';
const require = createRequire(import.meta.url);
export default environment => {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var tslib_1 = require("tslib");
var dimension_1 = tslib_1.__importDefault(require("../less/tree/dimension"));
var expression_1 = tslib_1.__importDefault(require("../less/tree/expression"));
var function_registry_1 = tslib_1.__importDefault(require("./../less/functions/function-registry"));
exports.default = (function (environment) {
function imageSize(functionContext, filePathNode) {
let filePath = filePathNode.value;
const currentFileInfo = functionContext.currentFileInfo;
const currentDirectory = currentFileInfo.rewriteUrls ?
var filePath = filePathNode.value;
var currentFileInfo = functionContext.currentFileInfo;
var currentDirectory = currentFileInfo.rewriteUrls ?
currentFileInfo.currentDirectory : currentFileInfo.entryPath;
const fragmentStart = filePath.indexOf('#');
var fragmentStart = filePath.indexOf('#');
if (fragmentStart !== -1) {
filePath = filePath.slice(0, fragmentStart);
}
const fileManager = environment.getFileManager(filePath, currentDirectory, functionContext.context, environment, true);
var fileManager = environment.getFileManager(filePath, currentDirectory, functionContext.context, environment, true);
if (!fileManager) {
throw {
type: 'File',
message: `Can not set up FileManager for ${filePathNode}`
message: "Can not set up FileManager for ".concat(filePathNode)
};
}
const fileSync = fileManager.loadFileSync(filePath, currentDirectory, functionContext.context, environment);
var fileSync = fileManager.loadFileSync(filePath, currentDirectory, functionContext.context, environment);
if (fileSync.error) {
throw fileSync.error;
}
const sizeOf = require('image-size');
return sizeOf ? sizeOf(fileSync.filename) : {width: 0, height: 0};
var sizeOf = require('image-size');
return sizeOf(fileSync.filename);
}
const imageFunctions = {
'image-size': function(filePathNode) {
const size = imageSize(this, filePathNode);
return new Expression([
new Dimension(size.width, 'px'),
new Dimension(size.height, 'px')
var imageFunctions = {
'image-size': function (filePathNode) {
var size = imageSize(this, filePathNode);
return new expression_1.default([
new dimension_1.default(size.width, 'px'),
new dimension_1.default(size.height, 'px')
]);
},
'image-width': function(filePathNode) {
const size = imageSize(this, filePathNode);
return new Dimension(size.width, 'px');
'image-width': function (filePathNode) {
var size = imageSize(this, filePathNode);
return new dimension_1.default(size.width, 'px');
},
'image-height': function(filePathNode) {
const size = imageSize(this, filePathNode);
return new Dimension(size.height, 'px');
'image-height': function (filePathNode) {
var size = imageSize(this, filePathNode);
return new dimension_1.default(size.height, 'px');
}
};
functionRegistry.addMultiple(imageFunctions);
};
function_registry_1.default.addMultiple(imageFunctions);
});
//# sourceMappingURL=image-size.js.map
+19 -28
View File
@@ -1,31 +1,22 @@
import { createRequire } from 'module';
import environment from './environment.js';
import FileManager from './file-manager.js';
import UrlFileManager from './url-file-manager.js';
import createFromEnvironment from '../less/index.js';
import lesscHelper from './lessc-helper.js';
import PluginLoader from './plugin-loader.js';
import fs from './fs.js';
import defaultOptions from '../less/default-options.js';
import imageSize from './image-size.js';
const require = createRequire(import.meta.url);
const { version } = require('../../package.json');
const less = createFromEnvironment(environment, [new FileManager(), new UrlFileManager()], version);
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var tslib_1 = require("tslib");
var environment_1 = tslib_1.__importDefault(require("./environment"));
var file_manager_1 = tslib_1.__importDefault(require("./file-manager"));
var url_file_manager_1 = tslib_1.__importDefault(require("./url-file-manager"));
var less_1 = tslib_1.__importDefault(require("../less"));
var less = (0, less_1.default)(environment_1.default, [new file_manager_1.default(), new url_file_manager_1.default()]);
var lessc_helper_1 = tslib_1.__importDefault(require("./lessc-helper"));
// allow people to create less with their own environment
less.createFromEnvironment = createFromEnvironment;
less.lesscHelper = lesscHelper;
less.PluginLoader = PluginLoader;
less.fs = fs;
less.FileManager = FileManager;
less.UrlFileManager = UrlFileManager;
less.createFromEnvironment = less_1.default;
less.lesscHelper = lessc_helper_1.default;
less.PluginLoader = require('./plugin-loader').default;
less.fs = require('./fs').default;
less.FileManager = file_manager_1.default;
less.UrlFileManager = url_file_manager_1.default;
// Set up options
less.options = defaultOptions();
less.options = require('../less/default-options').default();
// provide image-size functionality
imageSize(less.environment);
export default less;
require('./image-size').default(less.environment);
exports.default = less;
//# sourceMappingURL=index.js.map
+28 -28
View File
@@ -1,25 +1,23 @@
// lessc_helper.js
//
// helper functions for lessc
const lessc_helper = {
var lessc_helper = {
// Stylize a string
stylize : function(str, style) {
const styles = {
'reset' : [0, 0],
'bold' : [1, 22],
'inverse' : [7, 27],
'underline' : [4, 24],
'yellow' : [33, 39],
'green' : [32, 39],
'red' : [31, 39],
'grey' : [90, 39]
stylize: function (str, style) {
var styles = {
'reset': [0, 0],
'bold': [1, 22],
'inverse': [7, 27],
'underline': [4, 24],
'yellow': [33, 39],
'green': [32, 39],
'red': [31, 39],
'grey': [90, 39]
};
return `\x1b[${styles[style][0]}m${str}\x1b[${styles[style][1]}m`;
return "\u001B[".concat(styles[style][0], "m").concat(str, "\u001B[").concat(styles[style][1], "m");
},
// Print command line options
printUsage: function() {
printUsage: function () {
console.log('usage: lessc [option option=parameter ...] <source> [destination]');
console.log('');
console.log('If source is set to `-\' (dash or hyphen-minus), input is read from stdin.');
@@ -34,7 +32,7 @@ const lessc_helper = {
console.log(' -l, --lint Syntax check only (lint).');
console.log(' -s, --silent Suppresses output of error messages.');
console.log(' --quiet Suppresses output of warnings.');
console.log(' --strict-imports (DEPRECATED) Ignores .less imports inside selector blocks. Has confusing behavior.');
console.log(' --strict-imports Forces evaluation of imports.');
console.log(' --insecure Allows imports from insecure https hosts.');
console.log(' -v, --version Prints version number and exit.');
console.log(' --verbose Be verbose.');
@@ -70,19 +68,16 @@ const lessc_helper = {
console.log(' or --clean-css="advanced"');
console.log(' --disable-plugin-rule Disallow @plugin statements');
console.log('');
console.log(' --quiet-deprecations Suppress deprecation warnings only (keeps other warnings).');
console.log('');
console.log('-------------------------- Deprecated ----------------');
console.log(' -sm=on|off Legacy parens-only math. Use --math');
console.log(' --strict-math=on|off ');
console.log('');
console.log(' --line-numbers=TYPE (DEPRECATED) Outputs filename and line numbers.');
console.log(' TYPE can be either \'comments\', \'mediaquery\', or \'all\'.');
console.log(' The entire dumpLineNumbers option is deprecated.');
console.log(' Use sourcemaps (--source-map) instead.');
console.log(' All modes will be removed in a future version.');
console.log(' Note: \'mediaquery\' and \'all\' modes generate @media -sass-debug-info');
console.log(' which had short-lived usage and is no longer recommended.');
console.log(' --line-numbers=TYPE Outputs filename and line numbers.');
console.log(' TYPE can be either \'comments\', which will output');
console.log(' the debug info within comments, \'mediaquery\'');
console.log(' that will output the information within a fake');
console.log(' media query which is compatible with the SASS');
console.log(' format, and \'all\' which will do both.');
console.log(' -x, --compress Compresses output by removing some whitespaces.');
console.log(' We recommend you use a dedicated minifer like less-plugin-clean-css');
console.log('');
@@ -90,6 +85,11 @@ const lessc_helper = {
console.log('Home page: <http://lesscss.org/>');
}
};
export const { stylize, printUsage } = lessc_helper;
export default lessc_helper;
// Exports helper functions
// eslint-disable-next-line no-prototype-builtins
for (var h in lessc_helper) {
if (lessc_helper.hasOwnProperty(h)) {
exports[h] = lessc_helper[h];
}
}
//# sourceMappingURL=lessc-helper.js.map
+27 -35
View File
@@ -1,20 +1,19 @@
import path from 'path';
import { createRequire } from 'module';
import AbstractPluginLoader from '../less/environment/abstract-plugin-loader.js';
const require = createRequire(import.meta.url);
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var tslib_1 = require("tslib");
var path_1 = tslib_1.__importDefault(require("path"));
var abstract_plugin_loader_js_1 = tslib_1.__importDefault(require("../less/environment/abstract-plugin-loader.js"));
/**
* Node Plugin Loader
*/
const PluginLoader = function(less) {
var PluginLoader = function (less) {
this.less = less;
this.require = prefix => {
prefix = path.dirname(prefix);
return id => {
const str = id.slice(0, 2);
this.require = function (prefix) {
prefix = path_1.default.dirname(prefix);
return function (id) {
var str = id.substr(0, 2);
if (str === '..' || str === './') {
return require(path.join(prefix, id));
return require(path_1.default.join(prefix, id));
}
else {
return require(id);
@@ -22,41 +21,34 @@ const PluginLoader = function(less) {
};
};
};
PluginLoader.prototype = Object.assign(new AbstractPluginLoader(), {
loadPlugin(filename, basePath, context, environment, fileManager) {
const prefix = filename.slice(0, 1);
const explicit = prefix === '.' || prefix === '/' || filename.slice(-3).toLowerCase() === '.js';
PluginLoader.prototype = Object.assign(new abstract_plugin_loader_js_1.default(), {
loadPlugin: function (filename, basePath, context, environment, fileManager) {
var prefix = filename.slice(0, 1);
var explicit = prefix === '.' || prefix === '/' || filename.slice(-3).toLowerCase() === '.js';
if (!explicit) {
context.prefixes = ['less-plugin-', ''];
}
if (context.syncImport) {
return fileManager.loadFileSync(filename, basePath, context, environment);
}
return new Promise((fulfill, reject) => {
fileManager.loadFile(filename, basePath, context, environment).then(
data => {
try {
fulfill(data);
}
catch (e) {
console.log(e);
reject(e);
}
return new Promise(function (fulfill, reject) {
fileManager.loadFile(filename, basePath, context, environment).then(function (data) {
try {
fulfill(data);
}
).catch(err => {
catch (e) {
console.log(e);
reject(e);
}
}).catch(function (err) {
reject(err);
});
});
},
loadPluginSync(filename, basePath, context, environment, fileManager) {
loadPluginSync: function (filename, basePath, context, environment, fileManager) {
context.syncImport = true;
return this.loadPlugin(filename, basePath, context, environment, fileManager);
}
});
export default PluginLoader;
exports.default = PluginLoader;
//# sourceMappingURL=plugin-loader.js.map
+31 -33
View File
@@ -1,60 +1,58 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var tslib_1 = require("tslib");
/* eslint-disable no-unused-vars */
/**
* @todo - remove top eslint rule when FileManagers have JSDoc type
* and are TS-type-checked
*/
import { createRequire } from 'module';
const require = createRequire(import.meta.url);
const isUrlRe = /^(?:https?:)?\/\//i;
import url from 'url';
let request;
import AbstractFileManager from '../less/environment/abstract-file-manager.js';
import logger from '../less/logger.js';
const UrlFileManager = function() {}
UrlFileManager.prototype = Object.assign(new AbstractFileManager(), {
supports(filename, currentDirectory, options, environment) {
return isUrlRe.test( filename ) || isUrlRe.test(currentDirectory);
var isUrlRe = /^(?:https?:)?\/\//i;
var url_1 = tslib_1.__importDefault(require("url"));
var request;
var abstract_file_manager_js_1 = tslib_1.__importDefault(require("../less/environment/abstract-file-manager.js"));
var logger_1 = tslib_1.__importDefault(require("../less/logger"));
var UrlFileManager = function () { };
UrlFileManager.prototype = Object.assign(new abstract_file_manager_js_1.default(), {
supports: function (filename, currentDirectory, options, environment) {
return isUrlRe.test(filename) || isUrlRe.test(currentDirectory);
},
loadFile(filename, currentDirectory, options, environment) {
return new Promise((fulfill, reject) => {
loadFile: function (filename, currentDirectory, options, environment) {
return new Promise(function (fulfill, reject) {
if (request === undefined) {
try { request = require('needle'); }
catch (e) { request = null; }
try {
request = require('needle');
}
catch (e) {
request = null;
}
}
if (!request) {
reject({ type: 'File', message: 'optional dependency \'needle\' required to import over http(s)\n' });
return;
}
let urlStr = isUrlRe.test( filename ) ? filename : url.resolve(currentDirectory, filename);
var urlStr = isUrlRe.test(filename) ? filename : url_1.default.resolve(currentDirectory, filename);
/** native-request currently has a bug */
const hackUrlStr = urlStr.indexOf('?') === -1 ? urlStr + '?' : urlStr
request.get(hackUrlStr, { follow_max: 5 }, (err, resp, body) => {
var hackUrlStr = urlStr.indexOf('?') === -1 ? urlStr + '?' : urlStr;
request.get(hackUrlStr, { follow_max: 5 }, function (err, resp, body) {
if (err || resp && resp.statusCode >= 400) {
const message = resp && resp.statusCode === 404
? `resource '${urlStr}' was not found\n`
: `resource '${urlStr}' gave this Error:\n ${err || resp.statusMessage || resp.statusCode}\n`;
reject({ type: 'File', message });
var message = resp && resp.statusCode === 404
? "resource '".concat(urlStr, "' was not found\n")
: "resource '".concat(urlStr, "' gave this Error:\n ").concat(err || resp.statusMessage || resp.statusCode, "\n");
reject({ type: 'File', message: message });
return;
}
if (resp.statusCode >= 300) {
reject({ type: 'File', message: `resource '${urlStr}' caused too many redirects` });
reject({ type: 'File', message: "resource '".concat(urlStr, "' caused too many redirects") });
return;
}
body = body.toString('utf8');
if (!body) {
logger.warn(`Warning: Empty body (HTTP ${resp.statusCode}) returned by "${urlStr}"`);
logger_1.default.warn("Warning: Empty body (HTTP ".concat(resp.statusCode, ") returned by \"").concat(urlStr, "\""));
}
fulfill({ contents: body || '', filename: urlStr });
});
});
}
});
export default UrlFileManager;
exports.default = UrlFileManager;
//# sourceMappingURL=url-file-manager.js.map
+7 -5
View File
@@ -1,13 +1,15 @@
export const Math = {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.RewriteUrls = exports.Math = void 0;
exports.Math = {
ALWAYS: 0,
PARENS_DIVISION: 1,
PARENS: 2
// removed - STRICT_LEGACY: 3
};
export const RewriteUrls = {
exports.RewriteUrls = {
OFF: 0,
LOCAL: 1,
ALL: 2
};
};
//# sourceMappingURL=constants.js.map
+56 -71
View File
@@ -1,69 +1,68 @@
const contexts = {};
export default contexts;
import * as Constants from './constants.js';
const copyFromOriginal = function copyFromOriginal(original, destination, propertiesToCopy) {
if (!original) { return; }
for (let i = 0; i < propertiesToCopy.length; i++) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var tslib_1 = require("tslib");
var contexts = {};
exports.default = contexts;
var Constants = tslib_1.__importStar(require("./constants"));
var copyFromOriginal = function copyFromOriginal(original, destination, propertiesToCopy) {
if (!original) {
return;
}
for (var i = 0; i < propertiesToCopy.length; i++) {
if (Object.prototype.hasOwnProperty.call(original, propertiesToCopy[i])) {
destination[propertiesToCopy[i]] = original[propertiesToCopy[i]];
}
}
};
/*
parse is used whilst parsing
*/
const parseCopyProperties = [
var parseCopyProperties = [
// options
'paths', // option - unmodified - paths to search for imports on
'rewriteUrls', // option - whether to adjust URL's to be relative
'rootpath', // option - rootpath to append to URL's
'strictImports', // option -
'insecure', // option - whether to allow imports from insecure ssl hosts
'dumpLineNumbers', // option - @deprecated The dumpLineNumbers option is deprecated. Use sourcemaps instead. All modes ('comments', 'mediaquery', 'all') will be removed in a future version.
'compress', // option - whether to compress
'syncImport', // option - whether to import synchronously
'mime', // browser only - mime type for sheet import
'useFileCache', // browser only - whether to use the per file session cache
'paths',
'rewriteUrls',
'rootpath',
'strictImports',
'insecure',
'dumpLineNumbers',
'compress',
'syncImport',
'chunkInput',
'mime',
'useFileCache',
// context
'processImports', // option & context - whether to process imports. if false then imports will not be imported.
'processImports',
// Used by the import manager to stop multiple import visitors being created.
'pluginManager', // Used as the plugin manager for the session
'quiet', // option - whether to log warnings
'quietDeprecations', // option - whether to suppress deprecation warnings only
'pluginManager',
'quiet', // option - whether to log warnings
];
contexts.Parse = function(options) {
contexts.Parse = function (options) {
copyFromOriginal(options, this, parseCopyProperties);
if (typeof this.paths === 'string') { this.paths = [this.paths]; }
if (typeof this.paths === 'string') {
this.paths = [this.paths];
}
};
const evalCopyProperties = [
'paths', // additional include paths
'compress', // whether to compress
'math', // whether math has to be within parenthesis
'strictUnits', // whether units need to evaluate correctly
'sourceMap', // whether to output a source map
'importMultiple', // whether we are currently importing multiple copies
'urlArgs', // whether to add args into url tokens
'javascriptEnabled', // option - whether Inline JavaScript is enabled. if undefined, defaults to false
'pluginManager', // Used as the plugin manager for the session
'importantScope', // used to bubble up !important statements
'rewriteUrls' // option - whether to adjust URL's to be relative
var evalCopyProperties = [
'paths',
'compress',
'math',
'strictUnits',
'sourceMap',
'importMultiple',
'urlArgs',
'javascriptEnabled',
'pluginManager',
'importantScope',
'rewriteUrls' // option - whether to adjust URL's to be relative
];
contexts.Eval = function(options, frames) {
contexts.Eval = function (options, frames) {
copyFromOriginal(options, this, evalCopyProperties);
if (typeof this.paths === 'string') { this.paths = [this.paths]; }
if (typeof this.paths === 'string') {
this.paths = [this.paths];
}
this.frames = frames || [];
this.importantScope = this.importantScope || [];
};
contexts.Eval.prototype.enterCalc = function () {
if (!this.calcStack) {
this.calcStack = [];
@@ -71,25 +70,21 @@ contexts.Eval.prototype.enterCalc = function () {
this.calcStack.push(true);
this.inCalc = true;
};
contexts.Eval.prototype.exitCalc = function () {
this.calcStack.pop();
if (!this.calcStack.length) {
this.inCalc = false;
}
};
contexts.Eval.prototype.inParenthesis = function () {
if (!this.parensStack) {
this.parensStack = [];
}
this.parensStack.push(true);
};
contexts.Eval.prototype.outOfParenthesis = function () {
this.parensStack.pop();
};
contexts.Eval.prototype.inCalc = false;
contexts.Eval.prototype.mathOn = true;
contexts.Eval.prototype.isMathOn = function (op) {
@@ -104,44 +99,37 @@ contexts.Eval.prototype.isMathOn = function (op) {
}
return true;
};
contexts.Eval.prototype.pathRequiresRewrite = function (path) {
const isRelative = this.rewriteUrls === Constants.RewriteUrls.LOCAL ? isPathLocalRelative : isPathRelative;
var isRelative = this.rewriteUrls === Constants.RewriteUrls.LOCAL ? isPathLocalRelative : isPathRelative;
return isRelative(path);
};
contexts.Eval.prototype.rewritePath = function (path, rootpath) {
let newPath;
var newPath;
rootpath = rootpath || '';
newPath = this.normalizePath(rootpath + path);
// If a path was explicit relative and the rootpath was not an absolute path
// we must ensure that the new path is also explicit relative.
if (isPathLocalRelative(path) &&
isPathRelative(rootpath) &&
isPathLocalRelative(newPath) === false) {
newPath = `./${newPath}`;
newPath = "./".concat(newPath);
}
return newPath;
};
contexts.Eval.prototype.normalizePath = function (path) {
const segments = path.split('/').reverse();
let segment;
var segments = path.split('/').reverse();
var segment;
path = [];
while (segments.length !== 0) {
segment = segments.pop();
switch ( segment ) {
switch (segment) {
case '.':
break;
case '..':
if ((path.length === 0) || (path[path.length - 1] === '..')) {
path.push( segment );
} else {
path.push(segment);
}
else {
path.pop();
}
break;
@@ -150,16 +138,13 @@ contexts.Eval.prototype.normalizePath = function (path) {
break;
}
}
return path.join('/');
};
function isPathRelative(path) {
return !/^(?:[a-z-]+:|\/|#)/i.test(path);
}
function isPathLocalRelative(path) {
return path.charAt(0) === '.';
}
// todo - do the same for the toCSS ?
//# sourceMappingURL=contexts.js.map
+153 -150
View File
@@ -1,150 +1,153 @@
export default {
'aliceblue':'#f0f8ff',
'antiquewhite':'#faebd7',
'aqua':'#00ffff',
'aquamarine':'#7fffd4',
'azure':'#f0ffff',
'beige':'#f5f5dc',
'bisque':'#ffe4c4',
'black':'#000000',
'blanchedalmond':'#ffebcd',
'blue':'#0000ff',
'blueviolet':'#8a2be2',
'brown':'#a52a2a',
'burlywood':'#deb887',
'cadetblue':'#5f9ea0',
'chartreuse':'#7fff00',
'chocolate':'#d2691e',
'coral':'#ff7f50',
'cornflowerblue':'#6495ed',
'cornsilk':'#fff8dc',
'crimson':'#dc143c',
'cyan':'#00ffff',
'darkblue':'#00008b',
'darkcyan':'#008b8b',
'darkgoldenrod':'#b8860b',
'darkgray':'#a9a9a9',
'darkgrey':'#a9a9a9',
'darkgreen':'#006400',
'darkkhaki':'#bdb76b',
'darkmagenta':'#8b008b',
'darkolivegreen':'#556b2f',
'darkorange':'#ff8c00',
'darkorchid':'#9932cc',
'darkred':'#8b0000',
'darksalmon':'#e9967a',
'darkseagreen':'#8fbc8f',
'darkslateblue':'#483d8b',
'darkslategray':'#2f4f4f',
'darkslategrey':'#2f4f4f',
'darkturquoise':'#00ced1',
'darkviolet':'#9400d3',
'deeppink':'#ff1493',
'deepskyblue':'#00bfff',
'dimgray':'#696969',
'dimgrey':'#696969',
'dodgerblue':'#1e90ff',
'firebrick':'#b22222',
'floralwhite':'#fffaf0',
'forestgreen':'#228b22',
'fuchsia':'#ff00ff',
'gainsboro':'#dcdcdc',
'ghostwhite':'#f8f8ff',
'gold':'#ffd700',
'goldenrod':'#daa520',
'gray':'#808080',
'grey':'#808080',
'green':'#008000',
'greenyellow':'#adff2f',
'honeydew':'#f0fff0',
'hotpink':'#ff69b4',
'indianred':'#cd5c5c',
'indigo':'#4b0082',
'ivory':'#fffff0',
'khaki':'#f0e68c',
'lavender':'#e6e6fa',
'lavenderblush':'#fff0f5',
'lawngreen':'#7cfc00',
'lemonchiffon':'#fffacd',
'lightblue':'#add8e6',
'lightcoral':'#f08080',
'lightcyan':'#e0ffff',
'lightgoldenrodyellow':'#fafad2',
'lightgray':'#d3d3d3',
'lightgrey':'#d3d3d3',
'lightgreen':'#90ee90',
'lightpink':'#ffb6c1',
'lightsalmon':'#ffa07a',
'lightseagreen':'#20b2aa',
'lightskyblue':'#87cefa',
'lightslategray':'#778899',
'lightslategrey':'#778899',
'lightsteelblue':'#b0c4de',
'lightyellow':'#ffffe0',
'lime':'#00ff00',
'limegreen':'#32cd32',
'linen':'#faf0e6',
'magenta':'#ff00ff',
'maroon':'#800000',
'mediumaquamarine':'#66cdaa',
'mediumblue':'#0000cd',
'mediumorchid':'#ba55d3',
'mediumpurple':'#9370d8',
'mediumseagreen':'#3cb371',
'mediumslateblue':'#7b68ee',
'mediumspringgreen':'#00fa9a',
'mediumturquoise':'#48d1cc',
'mediumvioletred':'#c71585',
'midnightblue':'#191970',
'mintcream':'#f5fffa',
'mistyrose':'#ffe4e1',
'moccasin':'#ffe4b5',
'navajowhite':'#ffdead',
'navy':'#000080',
'oldlace':'#fdf5e6',
'olive':'#808000',
'olivedrab':'#6b8e23',
'orange':'#ffa500',
'orangered':'#ff4500',
'orchid':'#da70d6',
'palegoldenrod':'#eee8aa',
'palegreen':'#98fb98',
'paleturquoise':'#afeeee',
'palevioletred':'#d87093',
'papayawhip':'#ffefd5',
'peachpuff':'#ffdab9',
'peru':'#cd853f',
'pink':'#ffc0cb',
'plum':'#dda0dd',
'powderblue':'#b0e0e6',
'purple':'#800080',
'rebeccapurple':'#663399',
'red':'#ff0000',
'rosybrown':'#bc8f8f',
'royalblue':'#4169e1',
'saddlebrown':'#8b4513',
'salmon':'#fa8072',
'sandybrown':'#f4a460',
'seagreen':'#2e8b57',
'seashell':'#fff5ee',
'sienna':'#a0522d',
'silver':'#c0c0c0',
'skyblue':'#87ceeb',
'slateblue':'#6a5acd',
'slategray':'#708090',
'slategrey':'#708090',
'snow':'#fffafa',
'springgreen':'#00ff7f',
'steelblue':'#4682b4',
'tan':'#d2b48c',
'teal':'#008080',
'thistle':'#d8bfd8',
'tomato':'#ff6347',
'turquoise':'#40e0d0',
'violet':'#ee82ee',
'wheat':'#f5deb3',
'white':'#ffffff',
'whitesmoke':'#f5f5f5',
'yellow':'#ffff00',
'yellowgreen':'#9acd32'
};
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = {
'aliceblue': '#f0f8ff',
'antiquewhite': '#faebd7',
'aqua': '#00ffff',
'aquamarine': '#7fffd4',
'azure': '#f0ffff',
'beige': '#f5f5dc',
'bisque': '#ffe4c4',
'black': '#000000',
'blanchedalmond': '#ffebcd',
'blue': '#0000ff',
'blueviolet': '#8a2be2',
'brown': '#a52a2a',
'burlywood': '#deb887',
'cadetblue': '#5f9ea0',
'chartreuse': '#7fff00',
'chocolate': '#d2691e',
'coral': '#ff7f50',
'cornflowerblue': '#6495ed',
'cornsilk': '#fff8dc',
'crimson': '#dc143c',
'cyan': '#00ffff',
'darkblue': '#00008b',
'darkcyan': '#008b8b',
'darkgoldenrod': '#b8860b',
'darkgray': '#a9a9a9',
'darkgrey': '#a9a9a9',
'darkgreen': '#006400',
'darkkhaki': '#bdb76b',
'darkmagenta': '#8b008b',
'darkolivegreen': '#556b2f',
'darkorange': '#ff8c00',
'darkorchid': '#9932cc',
'darkred': '#8b0000',
'darksalmon': '#e9967a',
'darkseagreen': '#8fbc8f',
'darkslateblue': '#483d8b',
'darkslategray': '#2f4f4f',
'darkslategrey': '#2f4f4f',
'darkturquoise': '#00ced1',
'darkviolet': '#9400d3',
'deeppink': '#ff1493',
'deepskyblue': '#00bfff',
'dimgray': '#696969',
'dimgrey': '#696969',
'dodgerblue': '#1e90ff',
'firebrick': '#b22222',
'floralwhite': '#fffaf0',
'forestgreen': '#228b22',
'fuchsia': '#ff00ff',
'gainsboro': '#dcdcdc',
'ghostwhite': '#f8f8ff',
'gold': '#ffd700',
'goldenrod': '#daa520',
'gray': '#808080',
'grey': '#808080',
'green': '#008000',
'greenyellow': '#adff2f',
'honeydew': '#f0fff0',
'hotpink': '#ff69b4',
'indianred': '#cd5c5c',
'indigo': '#4b0082',
'ivory': '#fffff0',
'khaki': '#f0e68c',
'lavender': '#e6e6fa',
'lavenderblush': '#fff0f5',
'lawngreen': '#7cfc00',
'lemonchiffon': '#fffacd',
'lightblue': '#add8e6',
'lightcoral': '#f08080',
'lightcyan': '#e0ffff',
'lightgoldenrodyellow': '#fafad2',
'lightgray': '#d3d3d3',
'lightgrey': '#d3d3d3',
'lightgreen': '#90ee90',
'lightpink': '#ffb6c1',
'lightsalmon': '#ffa07a',
'lightseagreen': '#20b2aa',
'lightskyblue': '#87cefa',
'lightslategray': '#778899',
'lightslategrey': '#778899',
'lightsteelblue': '#b0c4de',
'lightyellow': '#ffffe0',
'lime': '#00ff00',
'limegreen': '#32cd32',
'linen': '#faf0e6',
'magenta': '#ff00ff',
'maroon': '#800000',
'mediumaquamarine': '#66cdaa',
'mediumblue': '#0000cd',
'mediumorchid': '#ba55d3',
'mediumpurple': '#9370d8',
'mediumseagreen': '#3cb371',
'mediumslateblue': '#7b68ee',
'mediumspringgreen': '#00fa9a',
'mediumturquoise': '#48d1cc',
'mediumvioletred': '#c71585',
'midnightblue': '#191970',
'mintcream': '#f5fffa',
'mistyrose': '#ffe4e1',
'moccasin': '#ffe4b5',
'navajowhite': '#ffdead',
'navy': '#000080',
'oldlace': '#fdf5e6',
'olive': '#808000',
'olivedrab': '#6b8e23',
'orange': '#ffa500',
'orangered': '#ff4500',
'orchid': '#da70d6',
'palegoldenrod': '#eee8aa',
'palegreen': '#98fb98',
'paleturquoise': '#afeeee',
'palevioletred': '#d87093',
'papayawhip': '#ffefd5',
'peachpuff': '#ffdab9',
'peru': '#cd853f',
'pink': '#ffc0cb',
'plum': '#dda0dd',
'powderblue': '#b0e0e6',
'purple': '#800080',
'rebeccapurple': '#663399',
'red': '#ff0000',
'rosybrown': '#bc8f8f',
'royalblue': '#4169e1',
'saddlebrown': '#8b4513',
'salmon': '#fa8072',
'sandybrown': '#f4a460',
'seagreen': '#2e8b57',
'seashell': '#fff5ee',
'sienna': '#a0522d',
'silver': '#c0c0c0',
'skyblue': '#87ceeb',
'slateblue': '#6a5acd',
'slategray': '#708090',
'slategrey': '#708090',
'snow': '#fffafa',
'springgreen': '#00ff7f',
'steelblue': '#4682b4',
'tan': '#d2b48c',
'teal': '#008080',
'thistle': '#d8bfd8',
'tomato': '#ff6347',
'turquoise': '#40e0d0',
'violet': '#ee82ee',
'wheat': '#f5deb3',
'white': '#ffffff',
'whitesmoke': '#f5f5f5',
'yellow': '#ffff00',
'yellowgreen': '#9acd32'
};
//# sourceMappingURL=colors.js.map
+7 -4
View File
@@ -1,4 +1,7 @@
import colors from './colors.js';
import unitConversions from './unit-conversions.js';
export default { colors, unitConversions };
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var tslib_1 = require("tslib");
var colors_1 = tslib_1.__importDefault(require("./colors"));
var unit_conversions_1 = tslib_1.__importDefault(require("./unit-conversions"));
exports.default = { colors: colors_1.default, unitConversions: unit_conversions_1.default };
//# sourceMappingURL=index.js.map
+5 -2
View File
@@ -1,4 +1,6 @@
export default {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = {
length: {
'm': 1,
'cm': 0.01,
@@ -18,4 +20,5 @@ export default {
'grad': 1 / 400,
'turn': 1
}
};
};
//# sourceMappingURL=unit-conversions.js.map
+23 -52
View File
@@ -1,89 +1,60 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
// Export a new default each time
export default function() {
function default_1() {
return {
/* Inline Javascript - @plugin still allowed */
javascriptEnabled: false,
/* Outputs a makefile import dependency list to stdout. */
depends: false,
/* (DEPRECATED) Compress using less built-in compression.
* This does an okay job but does not utilise all the tricks of
/* (DEPRECATED) Compress using less built-in compression.
* This does an okay job but does not utilise all the tricks of
* dedicated css compression. */
compress: false,
/* Runs the less parser and just reports errors without any output. */
lint: false,
/* Sets available include paths.
* If the file in an @import rule does not exist at that exact location,
* less will look for it at the location(s) passed to this option.
* You might use this for instance to specify a path to a library which
* If the file in an @import rule does not exist at that exact location,
* less will look for it at the location(s) passed to this option.
* You might use this for instance to specify a path to a library which
* you want to be referenced simply and relatively in the less files. */
paths: [],
/* color output in the terminal */
color: true,
/**
* @deprecated This option has confusing behavior and may be removed in a future version.
*
* When true, prevents @import statements for .less files from being evaluated inside
* selector blocks (rulesets). The imports are silently ignored and not output.
*
* Behavior:
* - @import at root level: Always processed
* - @import inside @-rules (@media, @supports, etc.): Processed (these are not selector blocks)
* - @import inside selector blocks (.class, #id, etc.): NOT processed (silently ignored)
*
* When false (default): All @import statements are processed regardless of context.
*
* Note: Despite the name "strict", this option does NOT throw an error when imports
* are used in selector blocks - it silently ignores them. This is confusing
* behavior that may catch users off guard.
*
* Note: Only affects .less file imports. CSS imports (url(...) or .css files) are
* always output as CSS @import statements regardless of this setting.
*
* @see https://github.com/less/less.js/issues/656
*/
/* The strictImports controls whether the compiler will allow an @import inside of either
* @media blocks or (a later addition) other selector blocks.
* See: https://github.com/less/less.js/issues/656 */
strictImports: false,
/* Allow Imports from Insecure HTTPS Hosts */
insecure: false,
/* Allows you to add a path to every generated import and url in your css.
* This does not affect less import statements that are processed, just ones
/* Allows you to add a path to every generated import and url in your css.
* This does not affect less import statements that are processed, just ones
* that are left in the output css. */
rootpath: '',
/* By default URLs are kept as-is, so if you import a file in a sub-directory
* that references an image, exactly the same URL will be output in the css.
* This option allows you to re-write URL's in imported files so that the
/* By default URLs are kept as-is, so if you import a file in a sub-directory
* that references an image, exactly the same URL will be output in the css.
* This option allows you to re-write URL's in imported files so that the
* URL is always relative to the base imported file */
rewriteUrls: false,
/* How to process math
/* How to process math
* 0 always - eagerly try to solve all operations
* 1 parens-division - require parens for division "/"
* 2 parens | strict - require parens for all operations
* 3 strict-legacy - legacy strict behavior (super-strict)
*/
math: 1,
/* Without this option, less attempts to guess at the output unit when it does maths. */
strictUnits: false,
/* Effectively the declaration is put at the top of your base Less file,
* meaning it can be used but it also can be overridden if this variable
/* Effectively the declaration is put at the top of your base Less file,
* meaning it can be used but it also can be overridden if this variable
* is defined in the file. */
globalVars: null,
/* As opposed to the global variable option, this puts the declaration at the
* end of your base file, meaning it will override anything defined in your Less file. */
modifyVars: null,
/* This option allows you to specify a argument to go on to every URL. */
urlArgs: ''
}
}
};
}
exports.default = default_1;
//# sourceMappingURL=default-options.js.map
+50 -62
View File
@@ -1,6 +1,10 @@
class AbstractFileManager {
getPath(filename) {
let j = filename.lastIndexOf('?');
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var AbstractFileManager = /** @class */ (function () {
function AbstractFileManager() {
}
AbstractFileManager.prototype.getPath = function (filename) {
var j = filename.lastIndexOf('?');
if (j > 0) {
filename = filename.slice(0, j);
}
@@ -12,53 +16,46 @@ class AbstractFileManager {
return '';
}
return filename.slice(0, j + 1);
}
tryAppendExtension(path, ext) {
};
AbstractFileManager.prototype.tryAppendExtension = function (path, ext) {
return /(\.[a-z]*$)|([?;].*)$/.test(path) ? path : path + ext;
}
tryAppendLessExtension(path) {
};
AbstractFileManager.prototype.tryAppendLessExtension = function (path) {
return this.tryAppendExtension(path, '.less');
}
supportsSync() {
};
AbstractFileManager.prototype.supportsSync = function () {
return false;
}
alwaysMakePathsAbsolute() {
};
AbstractFileManager.prototype.alwaysMakePathsAbsolute = function () {
return false;
}
isPathAbsolute(filename) {
};
AbstractFileManager.prototype.isPathAbsolute = function (filename) {
return (/^(?:[a-z-]+:|\/|\\|#)/i).test(filename);
}
};
// TODO: pull out / replace?
join(basePath, laterPath) {
AbstractFileManager.prototype.join = function (basePath, laterPath) {
if (!basePath) {
return laterPath;
}
return basePath + laterPath;
}
pathDiff(url, baseUrl) {
};
AbstractFileManager.prototype.pathDiff = function (url, baseUrl) {
// diff between two paths to create a relative path
const urlParts = this.extractUrlParts(url);
const baseUrlParts = this.extractUrlParts(baseUrl);
let i;
let max;
let urlDirectories;
let baseUrlDirectories;
let diff = '';
var urlParts = this.extractUrlParts(url);
var baseUrlParts = this.extractUrlParts(baseUrl);
var i;
var max;
var urlDirectories;
var baseUrlDirectories;
var diff = '';
if (urlParts.hostPart !== baseUrlParts.hostPart) {
return '';
}
max = Math.max(baseUrlParts.directories.length, urlParts.directories.length);
for (i = 0; i < max; i++) {
if (baseUrlParts.directories[i] !== urlParts.directories[i]) { break; }
if (baseUrlParts.directories[i] !== urlParts.directories[i]) {
break;
}
}
baseUrlDirectories = baseUrlParts.directories.slice(i);
urlDirectories = urlParts.directories.slice(i);
@@ -66,66 +63,56 @@ class AbstractFileManager {
diff += '../';
}
for (i = 0; i < urlDirectories.length - 1; i++) {
diff += `${urlDirectories[i]}/`;
diff += "".concat(urlDirectories[i], "/");
}
return diff;
}
};
/**
* Helper function, not part of API.
* This should be replaceable by newer Node / Browser APIs
*
* @param {string} url
*
* @param {string} url
* @param {string} baseUrl
*/
extractUrlParts(url, baseUrl) {
AbstractFileManager.prototype.extractUrlParts = function (url, baseUrl) {
// urlParts[1] = protocol://hostname/ OR /
// urlParts[2] = / if path relative to host base
// urlParts[3] = directories
// urlParts[4] = filename
// urlParts[5] = parameters
const urlPartsRegex = /^((?:[a-z-]+:)?\/{2}(?:[^/?#]*\/)|([/\\]))?((?:[^/\\?#]*[/\\])*)([^/\\?#]*)([#?].*)?$/i;
const urlParts = url.match(urlPartsRegex);
const returner = {};
let rawDirectories = [];
const directories = [];
let i;
let baseUrlParts;
var urlPartsRegex = /^((?:[a-z-]+:)?\/{2}(?:[^/?#]*\/)|([/\\]))?((?:[^/\\?#]*[/\\])*)([^/\\?#]*)([#?].*)?$/i;
var urlParts = url.match(urlPartsRegex);
var returner = {};
var rawDirectories = [];
var directories = [];
var i;
var baseUrlParts;
if (!urlParts) {
throw new Error(`Could not parse sheet href - '${url}'`);
throw new Error("Could not parse sheet href - '".concat(url, "'"));
}
// Stylesheets in IE don't always return the full path
if (baseUrl && (!urlParts[1] || urlParts[2])) {
baseUrlParts = baseUrl.match(urlPartsRegex);
if (!baseUrlParts) {
throw new Error(`Could not parse page url - '${baseUrl}'`);
throw new Error("Could not parse page url - '".concat(baseUrl, "'"));
}
urlParts[1] = urlParts[1] || baseUrlParts[1] || '';
if (!urlParts[2]) {
urlParts[3] = baseUrlParts[3] + urlParts[3];
}
}
if (urlParts[3]) {
rawDirectories = urlParts[3].replace(/\\/g, '/').split('/');
// collapse '..' and skip '.'
for (i = 0; i < rawDirectories.length; i++) {
if (rawDirectories[i] === '..') {
directories.pop();
}
else if (rawDirectories[i] !== '.') {
directories.push(rawDirectories[i]);
}
}
}
returner.hostPart = urlParts[1];
returner.directories = directories;
returner.rawPath = (urlParts[1] || '') + rawDirectories.join('/');
@@ -134,7 +121,8 @@ class AbstractFileManager {
returner.fileUrl = returner.path + (urlParts[4] || '');
returner.url = returner.fileUrl + (urlParts[5] || '');
return returner;
}
}
export default AbstractFileManager;
};
return AbstractFileManager;
}());
exports.default = AbstractFileManager;
//# sourceMappingURL=abstract-file-manager.js.map
+46 -69
View File
@@ -1,20 +1,18 @@
import functionRegistry from '../functions/function-registry.js';
import LessError from '../less-error.js';
class AbstractPluginLoader {
constructor() {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var tslib_1 = require("tslib");
var function_registry_1 = tslib_1.__importDefault(require("../functions/function-registry"));
var less_error_1 = tslib_1.__importDefault(require("../less-error"));
var AbstractPluginLoader = /** @class */ (function () {
function AbstractPluginLoader() {
// Implemented by Node.js plugin loader
this.require = function() {
this.require = function () {
return null;
}
};
}
evalPlugin(contents, context, imports, pluginOptions, fileInfo) {
let loader, registry, pluginObj, localModule, pluginManager, filename, result;
AbstractPluginLoader.prototype.evalPlugin = function (contents, context, imports, pluginOptions, fileInfo) {
var loader, registry, pluginObj, localModule, pluginManager, filename, result;
pluginManager = context.pluginManager;
if (fileInfo) {
if (typeof fileInfo === 'string') {
filename = fileInfo;
@@ -23,11 +21,9 @@ class AbstractPluginLoader {
filename = fileInfo.filename;
}
}
const shortname = (new this.less.FileManager()).extractUrlParts(filename).filename;
var shortname = (new this.less.FileManager()).extractUrlParts(filename).filename;
if (filename) {
pluginObj = pluginManager.get(filename);
if (pluginObj) {
result = this.trySetOptions(pluginObj, filename, shortname, pluginOptions);
if (result) {
@@ -40,62 +36,52 @@ class AbstractPluginLoader {
}
catch (e) {
e.message = e.message || 'Error during @plugin call';
return new LessError(e, imports, filename);
return new less_error_1.default(e, imports, filename);
}
return pluginObj;
}
}
localModule = {
exports: {},
pluginManager,
fileInfo
pluginManager: pluginManager,
fileInfo: fileInfo
};
registry = functionRegistry.create();
const registerPlugin = function(obj) {
registry = function_registry_1.default.create();
var registerPlugin = function (obj) {
pluginObj = obj;
};
try {
loader = new Function('module', 'require', 'registerPlugin', 'functions', 'tree', 'less', 'fileInfo', contents);
loader(localModule, this.require(filename), registerPlugin, registry, this.less.tree, this.less, fileInfo);
}
catch (e) {
return new LessError(e, imports, filename);
return new less_error_1.default(e, imports, filename);
}
if (!pluginObj) {
pluginObj = localModule.exports;
}
pluginObj = this.validatePlugin(pluginObj, filename, shortname);
if (pluginObj instanceof LessError) {
if (pluginObj instanceof less_error_1.default) {
return pluginObj;
}
if (pluginObj) {
pluginObj.imports = imports;
pluginObj.filename = filename;
// For < 3.x (or unspecified minVersion) - setOptions() before install()
if (!pluginObj.minVersion || this.compareVersion('3.0.0', pluginObj.minVersion) < 0) {
result = this.trySetOptions(pluginObj, filename, shortname, pluginOptions);
if (result) {
return result;
}
}
// Run on first load
pluginManager.addPlugin(pluginObj, fileInfo.filename, registry);
pluginObj.functions = registry.getLocalFunctions();
// Need to call setOptions again because the pluginObj might have functions
result = this.trySetOptions(pluginObj, filename, shortname, pluginOptions);
if (result) {
return result;
}
// Run every @plugin call
try {
if (pluginObj.use) {
@@ -104,82 +90,73 @@ class AbstractPluginLoader {
}
catch (e) {
e.message = e.message || 'Error during @plugin call';
return new LessError(e, imports, filename);
return new less_error_1.default(e, imports, filename);
}
}
else {
return new LessError({ message: 'Not a valid plugin' }, imports, filename);
return new less_error_1.default({ message: 'Not a valid plugin' }, imports, filename);
}
return pluginObj;
}
trySetOptions(plugin, filename, name, options) {
};
AbstractPluginLoader.prototype.trySetOptions = function (plugin, filename, name, options) {
if (options && !plugin.setOptions) {
return new LessError({
message: `Options have been provided but the plugin ${name} does not support any options.`
return new less_error_1.default({
message: "Options have been provided but the plugin ".concat(name, " does not support any options.")
});
}
try {
plugin.setOptions && plugin.setOptions(options);
}
catch (e) {
return new LessError(e);
return new less_error_1.default(e);
}
}
validatePlugin(plugin, filename, name) {
};
AbstractPluginLoader.prototype.validatePlugin = function (plugin, filename, name) {
if (plugin) {
// support plugins being a function
// so that the plugin can be more usable programmatically
if (typeof plugin === 'function') {
plugin = new plugin();
}
if (plugin.minVersion) {
if (this.compareVersion(plugin.minVersion, this.less.version) < 0) {
return new LessError({
message: `Plugin ${name} requires version ${this.versionToString(plugin.minVersion)}`
return new less_error_1.default({
message: "Plugin ".concat(name, " requires version ").concat(this.versionToString(plugin.minVersion))
});
}
}
return plugin;
}
return null;
}
compareVersion(aVersion, bVersion) {
};
AbstractPluginLoader.prototype.compareVersion = function (aVersion, bVersion) {
if (typeof aVersion === 'string') {
aVersion = aVersion.match(/^(\d+)\.?(\d+)?\.?(\d+)?/);
aVersion.shift();
}
for (let i = 0; i < aVersion.length; i++) {
for (var i = 0; i < aVersion.length; i++) {
if (aVersion[i] !== bVersion[i]) {
return parseInt(aVersion[i]) > parseInt(bVersion[i]) ? -1 : 1;
}
}
return 0;
}
versionToString(version) {
let versionString = '';
for (let i = 0; i < version.length; i++) {
};
AbstractPluginLoader.prototype.versionToString = function (version) {
var versionString = '';
for (var i = 0; i < version.length; i++) {
versionString += (versionString ? '.' : '') + version[i];
}
return versionString;
}
printUsage(plugins) {
for (let i = 0; i < plugins.length; i++) {
const plugin = plugins[i];
};
AbstractPluginLoader.prototype.printUsage = function (plugins) {
for (var i = 0; i < plugins.length; i++) {
var plugin = plugins[i];
if (plugin.printUsage) {
plugin.printUsage();
}
}
}
}
export default AbstractPluginLoader;
};
return AbstractPluginLoader;
}());
exports.default = AbstractPluginLoader;
//# sourceMappingURL=abstract-plugin-loader.js.map
+30 -34
View File
@@ -1,59 +1,55 @@
"use strict";
/**
* @todo Document why this abstraction exists, and the relationship between
* environment, file managers, and plugin manager
*/
import logger from '../logger.js';
class Environment {
constructor(externalEnvironment, fileManagers) {
Object.defineProperty(exports, "__esModule", { value: true });
var tslib_1 = require("tslib");
var logger_1 = tslib_1.__importDefault(require("../logger"));
var Environment = /** @class */ (function () {
function Environment(externalEnvironment, fileManagers) {
this.fileManagers = fileManagers || [];
externalEnvironment = externalEnvironment || {};
const optionalFunctions = ['encodeBase64', 'mimeLookup', 'charsetLookup', 'getSourceMapGenerator'];
const requiredFunctions = [];
const functions = requiredFunctions.concat(optionalFunctions);
for (let i = 0; i < functions.length; i++) {
const propName = functions[i];
const environmentFunc = externalEnvironment[propName];
var optionalFunctions = ['encodeBase64', 'mimeLookup', 'charsetLookup', 'getSourceMapGenerator'];
var requiredFunctions = [];
var functions = requiredFunctions.concat(optionalFunctions);
for (var i = 0; i < functions.length; i++) {
var propName = functions[i];
var environmentFunc = externalEnvironment[propName];
if (environmentFunc) {
this[propName] = environmentFunc.bind(externalEnvironment);
} else if (i < requiredFunctions.length) {
this.warn(`missing required function in environment - ${propName}`);
}
else if (i < requiredFunctions.length) {
this.warn("missing required function in environment - ".concat(propName));
}
}
}
getFileManager(filename, currentDirectory, options, environment, isSync) {
Environment.prototype.getFileManager = function (filename, currentDirectory, options, environment, isSync) {
if (!filename) {
logger.warn('getFileManager called with no filename.. Please report this issue. continuing.');
logger_1.default.warn('getFileManager called with no filename.. Please report this issue. continuing.');
}
if (currentDirectory === undefined) {
logger.warn('getFileManager called with null directory.. Please report this issue. continuing.');
logger_1.default.warn('getFileManager called with null directory.. Please report this issue. continuing.');
}
let fileManagers = this.fileManagers;
var fileManagers = this.fileManagers;
if (options.pluginManager) {
fileManagers = [].concat(fileManagers).concat(options.pluginManager.getFileManagers());
}
for (let i = fileManagers.length - 1; i >= 0 ; i--) {
const fileManager = fileManagers[i];
for (var i = fileManagers.length - 1; i >= 0; i--) {
var fileManager = fileManagers[i];
if (fileManager[isSync ? 'supportsSync' : 'supports'](filename, currentDirectory, options, environment)) {
return fileManager;
}
}
return null;
}
addFileManager(fileManager) {
};
Environment.prototype.addFileManager = function (fileManager) {
this.fileManagers.push(fileManager);
}
clearFileManagers() {
};
Environment.prototype.clearFileManagers = function () {
this.fileManagers = [];
}
}
export default Environment;
};
return Environment;
}());
exports.default = Environment;
//# sourceMappingURL=environment.js.map
+13 -13
View File
@@ -1,29 +1,29 @@
import Anonymous from '../tree/anonymous.js';
import Keyword from '../tree/keyword.js';
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var tslib_1 = require("tslib");
var anonymous_1 = tslib_1.__importDefault(require("../tree/anonymous"));
var keyword_1 = tslib_1.__importDefault(require("../tree/keyword"));
function boolean(condition) {
return condition ? Keyword.True : Keyword.False;
return condition ? keyword_1.default.True : keyword_1.default.False;
}
/**
* Functions with evalArgs set to false are sent context
* as the first argument.
*/
function If(context, condition, trueValue, falseValue) {
return condition.eval(context) ? trueValue.eval(context)
: (falseValue ? falseValue.eval(context) : new Anonymous);
: (falseValue ? falseValue.eval(context) : new anonymous_1.default);
}
If.evalArgs = false;
function isdefined(context, variable) {
try {
variable.eval(context);
return Keyword.True;
} catch (e) {
return Keyword.False;
return keyword_1.default.True;
}
catch (e) {
return keyword_1.default.False;
}
}
isdefined.evalArgs = false;
export default { isdefined, boolean, 'if': If };
exports.default = { isdefined: isdefined, boolean: boolean, 'if': If };
//# sourceMappingURL=boolean.js.map
+31 -39
View File
@@ -1,54 +1,48 @@
import Color from '../tree/color.js';
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var tslib_1 = require("tslib");
var color_1 = tslib_1.__importDefault(require("../tree/color"));
// Color Blending
// ref: http://www.w3.org/TR/compositing-1
function colorBlend(mode, color1, color2) {
const ab = color1.alpha; // result
let // backdrop
cb;
const as = color2.alpha;
let // source
cs;
let ar;
let cr;
const r = [];
var ab = color1.alpha; // result
var // backdrop
cb;
var as = color2.alpha;
var // source
cs;
var ar;
var cr;
var r = [];
ar = as + ab * (1 - as);
for (let i = 0; i < 3; i++) {
for (var i = 0; i < 3; i++) {
cb = color1.rgb[i] / 255;
cs = color2.rgb[i] / 255;
cr = mode(cb, cs);
if (ar) {
cr = (as * cs + ab * (cb -
as * (cb + cs - cr))) / ar;
as * (cb + cs - cr))) / ar;
}
r[i] = cr * 255;
}
return new Color(r, ar);
return new color_1.default(r, ar);
}
const colorBlendModeFunctions = {
multiply: function(cb, cs) {
var colorBlendModeFunctions = {
multiply: function (cb, cs) {
return cb * cs;
},
screen: function(cb, cs) {
screen: function (cb, cs) {
return cb + cs - cb * cs;
},
overlay: function(cb, cs) {
overlay: function (cb, cs) {
cb *= 2;
return (cb <= 1) ?
colorBlendModeFunctions.multiply(cb, cs) :
colorBlendModeFunctions.screen(cb - 1, cs);
},
softlight: function(cb, cs) {
let d = 1;
let e = cb;
softlight: function (cb, cs) {
var d = 1;
var e = cb;
if (cs > 0.5) {
e = 1;
d = (cb > 0.25) ? Math.sqrt(cb)
@@ -56,30 +50,28 @@ const colorBlendModeFunctions = {
}
return cb - (1 - 2 * cs) * e * (d - cb);
},
hardlight: function(cb, cs) {
hardlight: function (cb, cs) {
return colorBlendModeFunctions.overlay(cs, cb);
},
difference: function(cb, cs) {
difference: function (cb, cs) {
return Math.abs(cb - cs);
},
exclusion: function(cb, cs) {
exclusion: function (cb, cs) {
return cb + cs - 2 * cb * cs;
},
// non-w3c functions:
average: function(cb, cs) {
average: function (cb, cs) {
return (cb + cs) / 2;
},
negation: function(cb, cs) {
negation: function (cb, cs) {
return 1 - Math.abs(cb + cs - 1);
}
};
for (const f in colorBlendModeFunctions) {
for (var f in colorBlendModeFunctions) {
// eslint-disable-next-line no-prototype-builtins
if (colorBlendModeFunctions.hasOwnProperty(f)) {
colorBlend[f] = colorBlend.bind(null, colorBlendModeFunctions[f]);
}
}
export default colorBlend;
exports.default = colorBlend;
//# sourceMappingURL=color-blending.js.map
+136 -152
View File
@@ -1,21 +1,24 @@
import Dimension from '../tree/dimension.js';
import Color from '../tree/color.js';
import Quoted from '../tree/quoted.js';
import Anonymous from '../tree/anonymous.js';
import Expression from '../tree/expression.js';
import Operation from '../tree/operation.js';
let colorFunctions;
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var tslib_1 = require("tslib");
var dimension_1 = tslib_1.__importDefault(require("../tree/dimension"));
var color_1 = tslib_1.__importDefault(require("../tree/color"));
var quoted_1 = tslib_1.__importDefault(require("../tree/quoted"));
var anonymous_1 = tslib_1.__importDefault(require("../tree/anonymous"));
var expression_1 = tslib_1.__importDefault(require("../tree/expression"));
var operation_1 = tslib_1.__importDefault(require("../tree/operation"));
var colorFunctions;
function clamp(val) {
return Math.min(1, Math.max(0, val));
}
function hsla(origColor, hsl) {
const color = colorFunctions.hsla(hsl.h, hsl.s, hsl.l, hsl.a);
var color = colorFunctions.hsla(hsl.h, hsl.s, hsl.l, hsl.a);
if (color) {
if (origColor.value &&
if (origColor.value &&
/^(rgb|hsl)/.test(origColor.value)) {
color.value = origColor.value;
} else {
}
else {
color.value = 'rgb';
}
return color;
@@ -24,25 +27,27 @@ function hsla(origColor, hsl) {
function toHSL(color) {
if (color.toHSL) {
return color.toHSL();
} else {
}
else {
throw new Error('Argument cannot be evaluated to a color');
}
}
function toHSV(color) {
if (color.toHSV) {
return color.toHSV();
} else {
}
else {
throw new Error('Argument cannot be evaluated to a color');
}
}
function number(n) {
if (n instanceof Dimension) {
if (n instanceof dimension_1.default) {
return parseFloat(n.unit.is('%') ? n.value / 100 : n.value);
} else if (typeof n === 'number') {
}
else if (typeof n === 'number') {
return n;
} else {
}
else {
throw {
type: 'Argument',
message: 'color functions take numbers as parameters'
@@ -50,35 +55,36 @@ function number(n) {
}
}
function scaled(n, size) {
if (n instanceof Dimension && n.unit.is('%')) {
if (n instanceof dimension_1.default && n.unit.is('%')) {
return parseFloat(n.value * size / 100);
} else {
}
else {
return number(n);
}
}
colorFunctions = {
rgb: function (r, g, b) {
let a = 1
var a = 1;
/**
* Comma-less syntax
* e.g. rgb(0 128 255 / 50%)
*/
if (r instanceof Expression) {
const val = r.value
r = val[0]
g = val[1]
b = val[2]
/**
if (r instanceof expression_1.default) {
var val = r.value;
r = val[0];
g = val[1];
b = val[2];
/**
* @todo - should this be normalized in
* function caller? Or parsed differently?
*/
if (b instanceof Operation) {
const op = b
b = op.operands[0]
a = op.operands[1]
if (b instanceof operation_1.default) {
var op = b;
b = op.operands[0];
a = op.operands[1];
}
}
const color = colorFunctions.rgba(r, g, b, a);
var color = colorFunctions.rgba(r, g, b, a);
if (color) {
color.value = 'rgb';
return color;
@@ -86,44 +92,43 @@ colorFunctions = {
},
rgba: function (r, g, b, a) {
try {
if (r instanceof Color) {
if (r instanceof color_1.default) {
if (g) {
a = number(g);
} else {
}
else {
a = r.alpha;
}
return new Color(r.rgb, a, 'rgba');
return new color_1.default(r.rgb, a, 'rgba');
}
const rgb = [r, g, b].map(c => scaled(c, 255));
var rgb = [r, g, b].map(function (c) { return scaled(c, 255); });
a = number(a);
return new Color(rgb, a, 'rgba');
return new color_1.default(rgb, a, 'rgba');
}
catch (e) {}
catch (e) { }
},
hsl: function (h, s, l) {
let a = 1
if (h instanceof Expression) {
const val = h.value
h = val[0]
s = val[1]
l = val[2]
if (l instanceof Operation) {
const op = l
l = op.operands[0]
a = op.operands[1]
var a = 1;
if (h instanceof expression_1.default) {
var val = h.value;
h = val[0];
s = val[1];
l = val[2];
if (l instanceof operation_1.default) {
var op = l;
l = op.operands[0];
a = op.operands[1];
}
}
const color = colorFunctions.hsla(h, s, l, a);
var color = colorFunctions.hsla(h, s, l, a);
if (color) {
color.value = 'hsl';
return color;
}
},
hsla: function (h, s, l, a) {
let m1;
let m2;
var m1;
var m2;
function hue(h) {
h = h < 0 ? h + 1 : (h > 1 ? h - 1 : h);
if (h * 6 < 1) {
@@ -139,104 +144,94 @@ colorFunctions = {
return m1;
}
}
try {
if (h instanceof Color) {
if (h instanceof color_1.default) {
if (s) {
a = number(s);
} else {
}
else {
a = h.alpha;
}
return new Color(h.rgb, a, 'hsla');
return new color_1.default(h.rgb, a, 'hsla');
}
h = (number(h) % 360) / 360;
s = clamp(number(s));l = clamp(number(l));a = clamp(number(a));
s = clamp(number(s));
l = clamp(number(l));
a = clamp(number(a));
m2 = l <= 0.5 ? l * (s + 1) : l + s - l * s;
m1 = l * 2 - m2;
const rgb = [
var rgb = [
hue(h + 1 / 3) * 255,
hue(h) * 255,
hue(h) * 255,
hue(h - 1 / 3) * 255
];
a = number(a);
return new Color(rgb, a, 'hsla');
return new color_1.default(rgb, a, 'hsla');
}
catch (e) {}
catch (e) { }
},
hsv: function(h, s, v) {
hsv: function (h, s, v) {
return colorFunctions.hsva(h, s, v, 1.0);
},
hsva: function(h, s, v, a) {
hsva: function (h, s, v, a) {
h = ((number(h) % 360) / 360) * 360;
s = number(s);v = number(v);a = number(a);
let i;
let f;
s = number(s);
v = number(v);
a = number(a);
var i;
var f;
i = Math.floor((h / 60) % 6);
f = (h / 60) - i;
const vs = [v,
var vs = [v,
v * (1 - s),
v * (1 - f * s),
v * (1 - (1 - f) * s)];
const perm = [[0, 3, 1],
var perm = [[0, 3, 1],
[2, 0, 1],
[1, 0, 3],
[1, 2, 0],
[3, 1, 0],
[0, 1, 2]];
return colorFunctions.rgba(vs[perm[i][0]] * 255,
vs[perm[i][1]] * 255,
vs[perm[i][2]] * 255,
a);
return colorFunctions.rgba(vs[perm[i][0]] * 255, vs[perm[i][1]] * 255, vs[perm[i][2]] * 255, a);
},
hue: function (color) {
return new Dimension(toHSL(color).h);
return new dimension_1.default(toHSL(color).h);
},
saturation: function (color) {
return new Dimension(toHSL(color).s * 100, '%');
return new dimension_1.default(toHSL(color).s * 100, '%');
},
lightness: function (color) {
return new Dimension(toHSL(color).l * 100, '%');
return new dimension_1.default(toHSL(color).l * 100, '%');
},
hsvhue: function(color) {
return new Dimension(toHSV(color).h);
hsvhue: function (color) {
return new dimension_1.default(toHSV(color).h);
},
hsvsaturation: function (color) {
return new Dimension(toHSV(color).s * 100, '%');
return new dimension_1.default(toHSV(color).s * 100, '%');
},
hsvvalue: function (color) {
return new Dimension(toHSV(color).v * 100, '%');
return new dimension_1.default(toHSV(color).v * 100, '%');
},
red: function (color) {
return new Dimension(color.rgb[0]);
return new dimension_1.default(color.rgb[0]);
},
green: function (color) {
return new Dimension(color.rgb[1]);
return new dimension_1.default(color.rgb[1]);
},
blue: function (color) {
return new Dimension(color.rgb[2]);
return new dimension_1.default(color.rgb[2]);
},
alpha: function (color) {
return new Dimension(toHSL(color).a);
return new dimension_1.default(toHSL(color).a);
},
luma: function (color) {
return new Dimension(color.luma() * color.alpha * 100, '%');
return new dimension_1.default(color.luma() * color.alpha * 100, '%');
},
luminance: function (color) {
const luminance =
(0.2126 * color.rgb[0] / 255) +
(0.7152 * color.rgb[1] / 255) +
(0.0722 * color.rgb[2] / 255);
return new Dimension(luminance * color.alpha * 100, '%');
var luminance = (0.2126 * color.rgb[0] / 255) +
(0.7152 * color.rgb[1] / 255) +
(0.0722 * color.rgb[2] / 255);
return new dimension_1.default(luminance * color.alpha * 100, '%');
},
saturate: function (color, amount, method) {
// filter: saturate(3.2);
@@ -244,10 +239,9 @@ colorFunctions = {
if (!color.rgb) {
return null;
}
const hsl = toHSL(color);
var hsl = toHSL(color);
if (typeof method !== 'undefined' && method.value === 'relative') {
hsl.s += hsl.s * amount.value / 100;
hsl.s += hsl.s * amount.value / 100;
}
else {
hsl.s += amount.value / 100;
@@ -256,10 +250,9 @@ colorFunctions = {
return hsla(color, hsl);
},
desaturate: function (color, amount, method) {
const hsl = toHSL(color);
var hsl = toHSL(color);
if (typeof method !== 'undefined' && method.value === 'relative') {
hsl.s -= hsl.s * amount.value / 100;
hsl.s -= hsl.s * amount.value / 100;
}
else {
hsl.s -= amount.value / 100;
@@ -268,10 +261,9 @@ colorFunctions = {
return hsla(color, hsl);
},
lighten: function (color, amount, method) {
const hsl = toHSL(color);
var hsl = toHSL(color);
if (typeof method !== 'undefined' && method.value === 'relative') {
hsl.l += hsl.l * amount.value / 100;
hsl.l += hsl.l * amount.value / 100;
}
else {
hsl.l += amount.value / 100;
@@ -280,10 +272,9 @@ colorFunctions = {
return hsla(color, hsl);
},
darken: function (color, amount, method) {
const hsl = toHSL(color);
var hsl = toHSL(color);
if (typeof method !== 'undefined' && method.value === 'relative') {
hsl.l -= hsl.l * amount.value / 100;
hsl.l -= hsl.l * amount.value / 100;
}
else {
hsl.l -= amount.value / 100;
@@ -292,10 +283,9 @@ colorFunctions = {
return hsla(color, hsl);
},
fadein: function (color, amount, method) {
const hsl = toHSL(color);
var hsl = toHSL(color);
if (typeof method !== 'undefined' && method.value === 'relative') {
hsl.a += hsl.a * amount.value / 100;
hsl.a += hsl.a * amount.value / 100;
}
else {
hsl.a += amount.value / 100;
@@ -304,10 +294,9 @@ colorFunctions = {
return hsla(color, hsl);
},
fadeout: function (color, amount, method) {
const hsl = toHSL(color);
var hsl = toHSL(color);
if (typeof method !== 'undefined' && method.value === 'relative') {
hsl.a -= hsl.a * amount.value / 100;
hsl.a -= hsl.a * amount.value / 100;
}
else {
hsl.a -= amount.value / 100;
@@ -316,18 +305,15 @@ colorFunctions = {
return hsla(color, hsl);
},
fade: function (color, amount) {
const hsl = toHSL(color);
var hsl = toHSL(color);
hsl.a = amount.value / 100;
hsl.a = clamp(hsl.a);
return hsla(color, hsl);
},
spin: function (color, amount) {
const hsl = toHSL(color);
const hue = (hsl.h + amount.value) % 360;
var hsl = toHSL(color);
var hue = (hsl.h + amount.value) % 360;
hsl.h = hue < 0 ? 360 + hue : hue;
return hsla(color, hsl);
},
//
@@ -336,25 +322,21 @@ colorFunctions = {
//
mix: function (color1, color2, weight) {
if (!weight) {
weight = new Dimension(50);
weight = new dimension_1.default(50);
}
const p = weight.value / 100.0;
const w = p * 2 - 1;
const a = toHSL(color1).a - toHSL(color2).a;
const w1 = (((w * a == -1) ? w : (w + a) / (1 + w * a)) + 1) / 2.0;
const w2 = 1 - w1;
const rgb = [color1.rgb[0] * w1 + color2.rgb[0] * w2,
var p = weight.value / 100.0;
var w = p * 2 - 1;
var a = toHSL(color1).a - toHSL(color2).a;
var w1 = (((w * a == -1) ? w : (w + a) / (1 + w * a)) + 1) / 2.0;
var w2 = 1 - w1;
var rgb = [color1.rgb[0] * w1 + color2.rgb[0] * w2,
color1.rgb[1] * w1 + color2.rgb[1] * w2,
color1.rgb[2] * w1 + color2.rgb[2] * w2];
const alpha = color1.alpha * p + color2.alpha * (1 - p);
return new Color(rgb, alpha);
var alpha = color1.alpha * p + color2.alpha * (1 - p);
return new color_1.default(rgb, alpha);
},
greyscale: function (color) {
return colorFunctions.desaturate(color, new Dimension(100));
return colorFunctions.desaturate(color, new dimension_1.default(100));
},
contrast: function (color, dark, light, threshold) {
// filter: contrast(3.2);
@@ -370,18 +352,20 @@ colorFunctions = {
}
// Figure out which is actually light and dark:
if (dark.luma() > light.luma()) {
const t = light;
var t = light;
light = dark;
dark = t;
}
if (typeof threshold === 'undefined') {
threshold = 0.43;
} else {
}
else {
threshold = number(threshold);
}
if (color.luma() < threshold) {
return light;
} else {
}
else {
return dark;
}
},
@@ -424,29 +408,29 @@ colorFunctions = {
// }
// },
argb: function (color) {
return new Anonymous(color.toARGB());
return new anonymous_1.default(color.toARGB());
},
color: function(c) {
if ((c instanceof Quoted) &&
color: function (c) {
if ((c instanceof quoted_1.default) &&
(/^#([A-Fa-f0-9]{8}|[A-Fa-f0-9]{6}|[A-Fa-f0-9]{3,4})$/i.test(c.value))) {
const val = c.value.slice(1);
return new Color(val, undefined, `#${val}`);
var val = c.value.slice(1);
return new color_1.default(val, undefined, "#".concat(val));
}
if ((c instanceof Color) || (c = Color.fromKeyword(c.value))) {
if ((c instanceof color_1.default) || (c = color_1.default.fromKeyword(c.value))) {
c.value = undefined;
return c;
}
throw {
type: 'Argument',
type: 'Argument',
message: 'argument must be a color keyword or 3|4|6|8 digit hex e.g. #FFF'
};
},
tint: function(color, amount) {
tint: function (color, amount) {
return colorFunctions.mix(colorFunctions.rgb(255, 255, 255), color, amount);
},
shade: function(color, amount) {
shade: function (color, amount) {
return colorFunctions.mix(colorFunctions.rgb(0, 0, 0), color, amount);
}
};
export default colorFunctions;
exports.default = colorFunctions;
//# sourceMappingURL=color.js.map
+64 -73
View File
@@ -1,74 +1,65 @@
import Quoted from '../tree/quoted.js';
import URL from '../tree/url.js';
import * as utils from '../utils.js';
import logger from '../logger.js';
export default environment => {
const fallback = (functionThis, node) => new URL(node, functionThis.index, functionThis.currentFileInfo).eval(functionThis.context);
return { 'data-uri': function(mimetypeNode, filePathNode) {
if (!filePathNode) {
filePathNode = mimetypeNode;
mimetypeNode = null;
}
let mimetype = mimetypeNode && mimetypeNode.value;
let filePath = filePathNode.value;
const currentFileInfo = this.currentFileInfo;
const currentDirectory = currentFileInfo.rewriteUrls ?
currentFileInfo.currentDirectory : currentFileInfo.entryPath;
const fragmentStart = filePath.indexOf('#');
let fragment = '';
if (fragmentStart !== -1) {
fragment = filePath.slice(fragmentStart);
filePath = filePath.slice(0, fragmentStart);
}
const context = utils.clone(this.context);
context.rawBuffer = true;
const fileManager = environment.getFileManager(filePath, currentDirectory, context, environment, true);
if (!fileManager) {
return fallback(this, filePathNode);
}
let useBase64 = false;
// detect the mimetype if not given
if (!mimetypeNode) {
mimetype = environment.mimeLookup(filePath);
if (mimetype === 'image/svg+xml') {
useBase64 = false;
} else {
// use base 64 unless it's an ASCII or UTF-8 format
const charset = environment.charsetLookup(mimetype);
useBase64 = ['US-ASCII', 'UTF-8'].indexOf(charset) < 0;
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var tslib_1 = require("tslib");
var quoted_1 = tslib_1.__importDefault(require("../tree/quoted"));
var url_1 = tslib_1.__importDefault(require("../tree/url"));
var utils = tslib_1.__importStar(require("../utils"));
var logger_1 = tslib_1.__importDefault(require("../logger"));
exports.default = (function (environment) {
var fallback = function (functionThis, node) { return new url_1.default(node, functionThis.index, functionThis.currentFileInfo).eval(functionThis.context); };
return { 'data-uri': function (mimetypeNode, filePathNode) {
if (!filePathNode) {
filePathNode = mimetypeNode;
mimetypeNode = null;
}
if (useBase64) { mimetype += ';base64'; }
}
else {
useBase64 = /;base64$/.test(mimetype);
}
const fileSync = fileManager.loadFileSync(filePath, currentDirectory, context, environment);
if (!fileSync.contents) {
logger.warn(`Skipped data-uri embedding of ${filePath} because file not found`);
return fallback(this, filePathNode || mimetypeNode);
}
let buf = fileSync.contents;
if (useBase64 && !environment.encodeBase64) {
return fallback(this, filePathNode);
}
buf = useBase64 ? environment.encodeBase64(buf) : encodeURIComponent(buf);
const uri = `data:${mimetype},${buf}${fragment}`;
return new URL(new Quoted(`"${uri}"`, uri, false, this.index, this.currentFileInfo), this.index, this.currentFileInfo);
}};
};
var mimetype = mimetypeNode && mimetypeNode.value;
var filePath = filePathNode.value;
var currentFileInfo = this.currentFileInfo;
var currentDirectory = currentFileInfo.rewriteUrls ?
currentFileInfo.currentDirectory : currentFileInfo.entryPath;
var fragmentStart = filePath.indexOf('#');
var fragment = '';
if (fragmentStart !== -1) {
fragment = filePath.slice(fragmentStart);
filePath = filePath.slice(0, fragmentStart);
}
var context = utils.clone(this.context);
context.rawBuffer = true;
var fileManager = environment.getFileManager(filePath, currentDirectory, context, environment, true);
if (!fileManager) {
return fallback(this, filePathNode);
}
var useBase64 = false;
// detect the mimetype if not given
if (!mimetypeNode) {
mimetype = environment.mimeLookup(filePath);
if (mimetype === 'image/svg+xml') {
useBase64 = false;
}
else {
// use base 64 unless it's an ASCII or UTF-8 format
var charset = environment.charsetLookup(mimetype);
useBase64 = ['US-ASCII', 'UTF-8'].indexOf(charset) < 0;
}
if (useBase64) {
mimetype += ';base64';
}
}
else {
useBase64 = /;base64$/.test(mimetype);
}
var fileSync = fileManager.loadFileSync(filePath, currentDirectory, context, environment);
if (!fileSync.contents) {
logger_1.default.warn("Skipped data-uri embedding of ".concat(filePath, " because file not found"));
return fallback(this, filePathNode || mimetypeNode);
}
var buf = fileSync.contents;
if (useBase64 && !environment.encodeBase64) {
return fallback(this, filePathNode);
}
buf = useBase64 ? environment.encodeBase64(buf) : encodeURIComponent(buf);
var uri = "data:".concat(mimetype, ",").concat(buf).concat(fragment);
return new url_1.default(new quoted_1.default("\"".concat(uri, "\""), uri, false, this.index, this.currentFileInfo), this.index, this.currentFileInfo);
} };
});
//# sourceMappingURL=data-uri.js.map
+11 -9
View File
@@ -1,15 +1,17 @@
import Keyword from '../tree/keyword.js';
import * as utils from '../utils.js';
const defaultFunc = {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var tslib_1 = require("tslib");
var keyword_1 = tslib_1.__importDefault(require("../tree/keyword"));
var utils = tslib_1.__importStar(require("../utils"));
var defaultFunc = {
eval: function () {
const v = this.value_;
const e = this.error_;
var v = this.value_;
var e = this.error_;
if (e) {
throw e;
}
if (!utils.isNullOrUndefined(v)) {
return v ? Keyword.True : Keyword.False;
return v ? keyword_1.default.True : keyword_1.default.False;
}
},
value: function (v) {
@@ -22,5 +24,5 @@ const defaultFunc = {
this.value_ = this.error_ = null;
}
};
export default defaultFunc;
exports.default = defaultFunc;
//# sourceMappingURL=default.js.map
+34 -35
View File
@@ -1,55 +1,54 @@
import Expression from '../tree/expression.js';
class functionCaller {
constructor(name, context, index, currentFileInfo) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var tslib_1 = require("tslib");
var expression_1 = tslib_1.__importDefault(require("../tree/expression"));
var functionCaller = /** @class */ (function () {
function functionCaller(name, context, index, currentFileInfo) {
this.name = name.toLowerCase();
this.index = index;
this.context = context;
this.currentFileInfo = currentFileInfo;
this.func = context.frames[0].functionRegistry.get(this.name);
}
isValid() {
functionCaller.prototype.isValid = function () {
return Boolean(this.func);
}
call(args) {
};
functionCaller.prototype.call = function (args) {
var _this = this;
if (!(Array.isArray(args))) {
args = [args];
}
const evalArgs = this.func.evalArgs;
var evalArgs = this.func.evalArgs;
if (evalArgs !== false) {
args = args.map(a => a.eval(this.context));
args = args.map(function (a) { return a.eval(_this.context); });
}
const commentFilter = item => !(item.type === 'Comment');
var commentFilter = function (item) { return !(item.type === 'Comment'); };
// This code is terrible and should be replaced as per this issue...
// https://github.com/less/less.js/issues/2477
args = args
.filter(commentFilter)
.map(item => {
if (item.type === 'Expression') {
const subNodes = item.value.filter(commentFilter);
if (subNodes.length === 1) {
// https://github.com/less/less.js/issues/3616
if (item.parens && subNodes[0].op === '/') {
return item;
}
return subNodes[0];
} else {
return new Expression(subNodes);
.map(function (item) {
if (item.type === 'Expression') {
var subNodes = item.value.filter(commentFilter);
if (subNodes.length === 1) {
// https://github.com/less/less.js/issues/3616
if (item.parens && subNodes[0].op === '/') {
return item;
}
return subNodes[0];
}
return item;
});
else {
return new expression_1.default(subNodes);
}
}
return item;
});
if (evalArgs === false) {
return this.func(this.context, ...args);
return this.func.apply(this, tslib_1.__spreadArray([this.context], args, false));
}
return this.func(...args);
}
}
export default functionCaller;
return this.func.apply(this, args);
};
return functionCaller;
}());
exports.default = functionCaller;
//# sourceMappingURL=function-caller.js.map
+17 -16
View File
@@ -1,36 +1,37 @@
function makeRegistry( base ) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
function makeRegistry(base) {
return {
_data: {},
add: function(name, func) {
add: function (name, func) {
// precautionary case conversion, as later querying of
// the registry by function-caller uses lower case as well.
name = name.toLowerCase();
// eslint-disable-next-line no-prototype-builtins
if (this._data.hasOwnProperty(name)) {
// TODO warn
}
this._data[name] = func;
},
addMultiple: function(functions) {
Object.keys(functions).forEach(
name => {
this.add(name, functions[name]);
});
addMultiple: function (functions) {
var _this = this;
Object.keys(functions).forEach(function (name) {
_this.add(name, functions[name]);
});
},
get: function(name) {
return this._data[name] || ( base && base.get( name ));
get: function (name) {
return this._data[name] || (base && base.get(name));
},
getLocalFunctions: function() {
getLocalFunctions: function () {
return this._data;
},
inherit: function() {
return makeRegistry( this );
inherit: function () {
return makeRegistry(this);
},
create: function(base) {
create: function (base) {
return makeRegistry(base);
}
};
}
export default makeRegistry( null );
exports.default = makeRegistry(null);
//# sourceMappingURL=function-registry.js.map
+33 -33
View File
@@ -1,35 +1,35 @@
import functionRegistry from './function-registry.js';
import functionCaller from './function-caller.js';
import boolean from './boolean.js';
import defaultFunc from './default.js';
import color from './color.js';
import colorBlending from './color-blending.js';
import dataUri from './data-uri.js';
import list from './list.js';
import math from './math.js';
import number from './number.js';
import string from './string.js';
import svg from './svg.js';
import types from './types.js';
import style from './style.js';
export default environment => {
const functions = { functionRegistry, functionCaller };
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var tslib_1 = require("tslib");
var function_registry_1 = tslib_1.__importDefault(require("./function-registry"));
var function_caller_1 = tslib_1.__importDefault(require("./function-caller"));
var boolean_1 = tslib_1.__importDefault(require("./boolean"));
var default_1 = tslib_1.__importDefault(require("./default"));
var color_1 = tslib_1.__importDefault(require("./color"));
var color_blending_1 = tslib_1.__importDefault(require("./color-blending"));
var data_uri_1 = tslib_1.__importDefault(require("./data-uri"));
var list_1 = tslib_1.__importDefault(require("./list"));
var math_1 = tslib_1.__importDefault(require("./math"));
var number_1 = tslib_1.__importDefault(require("./number"));
var string_1 = tslib_1.__importDefault(require("./string"));
var svg_1 = tslib_1.__importDefault(require("./svg"));
var types_1 = tslib_1.__importDefault(require("./types"));
var style_1 = tslib_1.__importDefault(require("./style"));
exports.default = (function (environment) {
var functions = { functionRegistry: function_registry_1.default, functionCaller: function_caller_1.default };
// register functions
functionRegistry.addMultiple(boolean);
functionRegistry.add('default', defaultFunc.eval.bind(defaultFunc));
functionRegistry.addMultiple(color);
functionRegistry.addMultiple(colorBlending);
functionRegistry.addMultiple(dataUri(environment));
functionRegistry.addMultiple(list);
functionRegistry.addMultiple(math);
functionRegistry.addMultiple(number);
functionRegistry.addMultiple(string);
functionRegistry.addMultiple(svg(environment));
functionRegistry.addMultiple(types);
functionRegistry.addMultiple(style);
function_registry_1.default.addMultiple(boolean_1.default);
function_registry_1.default.add('default', default_1.default.eval.bind(default_1.default));
function_registry_1.default.addMultiple(color_1.default);
function_registry_1.default.addMultiple(color_blending_1.default);
function_registry_1.default.addMultiple((0, data_uri_1.default)(environment));
function_registry_1.default.addMultiple(list_1.default);
function_registry_1.default.addMultiple(math_1.default);
function_registry_1.default.addMultiple(number_1.default);
function_registry_1.default.addMultiple(string_1.default);
function_registry_1.default.addMultiple((0, svg_1.default)(environment));
function_registry_1.default.addMultiple(types_1.default);
function_registry_1.default.addMultiple(style_1.default);
return functions;
};
});
//# sourceMappingURL=index.js.map
+75 -88
View File
@@ -1,55 +1,58 @@
import Comment from '../tree/comment.js';
import Node from '../tree/node.js';
import Dimension from '../tree/dimension.js';
import Declaration from '../tree/declaration.js';
import Expression from '../tree/expression.js';
import Ruleset from '../tree/ruleset.js';
import Selector from '../tree/selector.js';
import Element from '../tree/element.js';
import Quote from '../tree/quoted.js';
import Value from '../tree/value.js';
const getItemsFromNode = node => {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var tslib_1 = require("tslib");
var comment_1 = tslib_1.__importDefault(require("../tree/comment"));
var node_1 = tslib_1.__importDefault(require("../tree/node"));
var dimension_1 = tslib_1.__importDefault(require("../tree/dimension"));
var declaration_1 = tslib_1.__importDefault(require("../tree/declaration"));
var expression_1 = tslib_1.__importDefault(require("../tree/expression"));
var ruleset_1 = tslib_1.__importDefault(require("../tree/ruleset"));
var selector_1 = tslib_1.__importDefault(require("../tree/selector"));
var element_1 = tslib_1.__importDefault(require("../tree/element"));
var quoted_1 = tslib_1.__importDefault(require("../tree/quoted"));
var value_1 = tslib_1.__importDefault(require("../tree/value"));
var getItemsFromNode = function (node) {
// handle non-array values as an array of length 1
// return 'undefined' if index is invalid
const items = Array.isArray(node.value) ?
var items = Array.isArray(node.value) ?
node.value : Array(node);
return items;
};
export default {
_SELF: function(n) {
exports.default = {
_SELF: function (n) {
return n;
},
'~': function(...expr) {
'~': function () {
var expr = [];
for (var _i = 0; _i < arguments.length; _i++) {
expr[_i] = arguments[_i];
}
if (expr.length === 1) {
return expr[0];
}
return new Value(expr);
return new value_1.default(expr);
},
extract: function(values, index) {
extract: function (values, index) {
// (1-based index)
index = index.value - 1;
return getItemsFromNode(values)[index];
},
length: function(values) {
return new Dimension(getItemsFromNode(values).length);
length: function (values) {
return new dimension_1.default(getItemsFromNode(values).length);
},
/**
* Creates a Less list of incremental values.
* Modeled after Lodash's range function, also exists natively in PHP
*
*
* @param {Dimension} [start=1]
* @param {Dimension} end - e.g. 10 or 10px - unit is added to output
* @param {Dimension} [step=1]
* @param {Dimension} [step=1]
*/
range: function(start, end, step) {
let from;
let to;
let stepValue = 1;
const list = [];
range: function (start, end, step) {
var from;
var to;
var stepValue = 1;
var list = [];
if (end) {
to = end;
from = start.value;
@@ -61,98 +64,82 @@ export default {
from = 1;
to = start;
}
for (let i = from; i <= to.value; i += stepValue) {
list.push(new Dimension(i, to.unit));
for (var i = from; i <= to.value; i += stepValue) {
list.push(new dimension_1.default(i, to.unit));
}
return new Expression(list);
return new expression_1.default(list);
},
each: function(list, rs) {
const rules = [];
let newRules;
let iterator;
const tryEval = val => {
if (val instanceof Node) {
return val.eval(this.context);
each: function (list, rs) {
var _this = this;
var rules = [];
var newRules;
var iterator;
var tryEval = function (val) {
if (val instanceof node_1.default) {
return val.eval(_this.context);
}
return val;
};
if (list.value && !(list instanceof Quote)) {
if (list.value && !(list instanceof quoted_1.default)) {
if (Array.isArray(list.value)) {
iterator = list.value.map(tryEval);
} else {
}
else {
iterator = [tryEval(list.value)];
}
} else if (list.ruleset) {
}
else if (list.ruleset) {
iterator = tryEval(list.ruleset).rules;
} else if (list.rules) {
}
else if (list.rules) {
iterator = list.rules.map(tryEval);
} else if (Array.isArray(list)) {
}
else if (Array.isArray(list)) {
iterator = list.map(tryEval);
} else {
}
else {
iterator = [tryEval(list)];
}
let valueName = '@value';
let keyName = '@key';
let indexName = '@index';
var valueName = '@value';
var keyName = '@key';
var indexName = '@index';
if (rs.params) {
valueName = rs.params[0] && rs.params[0].name;
keyName = rs.params[1] && rs.params[1].name;
indexName = rs.params[2] && rs.params[2].name;
rs = rs.rules;
} else {
}
else {
rs = rs.ruleset;
}
for (let i = 0; i < iterator.length; i++) {
let key;
let value;
const item = iterator[i];
if (item instanceof Declaration) {
for (var i = 0; i < iterator.length; i++) {
var key = void 0;
var value = void 0;
var item = iterator[i];
if (item instanceof declaration_1.default) {
key = typeof item.name === 'string' ? item.name : item.name[0].value;
value = item.value;
} else {
key = new Dimension(i + 1);
}
else {
key = new dimension_1.default(i + 1);
value = item;
}
if (item instanceof Comment) {
if (item instanceof comment_1.default) {
continue;
}
newRules = rs.rules.slice(0);
if (valueName) {
newRules.push(new Declaration(valueName,
value,
false, false, this.index, this.currentFileInfo));
newRules.push(new declaration_1.default(valueName, value, false, false, this.index, this.currentFileInfo));
}
if (indexName) {
newRules.push(new Declaration(indexName,
new Dimension(i + 1),
false, false, this.index, this.currentFileInfo));
newRules.push(new declaration_1.default(indexName, new dimension_1.default(i + 1), false, false, this.index, this.currentFileInfo));
}
if (keyName) {
newRules.push(new Declaration(keyName,
key,
false, false, this.index, this.currentFileInfo));
newRules.push(new declaration_1.default(keyName, key, false, false, this.index, this.currentFileInfo));
}
rules.push(new Ruleset([ new(Selector)([ new Element('', '&') ]) ],
newRules,
rs.strictImports,
rs.visibilityInfo()
));
rules.push(new ruleset_1.default([new (selector_1.default)([new element_1.default('', '&')])], newRules, rs.strictImports, rs.visibilityInfo()));
}
return new Ruleset([ new(Selector)([ new Element('', '&') ]) ],
rules,
rs.strictImports,
rs.visibilityInfo()
).eval(this.context);
return new ruleset_1.default([new (selector_1.default)([new element_1.default('', '&')])], rules, rs.strictImports, rs.visibilityInfo()).eval(this.context);
}
};
//# sourceMappingURL=list.js.map
+11 -8
View File
@@ -1,15 +1,18 @@
import Dimension from '../tree/dimension.js';
const MathHelper = (fn, unit, n) => {
if (!(n instanceof Dimension)) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var tslib_1 = require("tslib");
var dimension_1 = tslib_1.__importDefault(require("../tree/dimension"));
var MathHelper = function (fn, unit, n) {
if (!(n instanceof dimension_1.default)) {
throw { type: 'Argument', message: 'argument must be a number' };
}
if (unit === null) {
unit = n.unit;
} else {
}
else {
n = n.unify();
}
return new Dimension(fn(parseFloat(n.value)), unit);
return new dimension_1.default(fn(parseFloat(n.value)), unit);
};
export default MathHelper;
exports.default = MathHelper;
//# sourceMappingURL=math-helper.js.map
+21 -21
View File
@@ -1,29 +1,29 @@
import mathHelper from './math-helper.js';
const mathFunctions = {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var tslib_1 = require("tslib");
var math_helper_js_1 = tslib_1.__importDefault(require("./math-helper.js"));
var mathFunctions = {
// name, unit
ceil: null,
ceil: null,
floor: null,
sqrt: null,
abs: null,
tan: '',
sin: '',
cos: '',
atan: 'rad',
asin: 'rad',
acos: 'rad'
sqrt: null,
abs: null,
tan: '',
sin: '',
cos: '',
atan: 'rad',
asin: 'rad',
acos: 'rad'
};
for (const f in mathFunctions) {
for (var f in mathFunctions) {
// eslint-disable-next-line no-prototype-builtins
if (mathFunctions.hasOwnProperty(f)) {
mathFunctions[f] = mathHelper.bind(null, Math[f], mathFunctions[f]);
mathFunctions[f] = math_helper_js_1.default.bind(null, Math[f], mathFunctions[f]);
}
}
mathFunctions.round = (n, f) => {
const fraction = typeof f === 'undefined' ? 0 : f.value;
return mathHelper(num => num.toFixed(fraction), null, n);
mathFunctions.round = function (n, f) {
var fraction = typeof f === 'undefined' ? 0 : f.value;
return (0, math_helper_js_1.default)(function (num) { return num.toFixed(fraction); }, null, n);
};
export default mathFunctions;
exports.default = mathFunctions;
//# sourceMappingURL=math.js.map
+53 -42
View File
@@ -1,37 +1,39 @@
import Dimension from '../tree/dimension.js';
import Anonymous from '../tree/anonymous.js';
import mathHelper from './math-helper.js';
const minMax = function (isMin, args) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var tslib_1 = require("tslib");
var dimension_1 = tslib_1.__importDefault(require("../tree/dimension"));
var anonymous_1 = tslib_1.__importDefault(require("../tree/anonymous"));
var math_helper_js_1 = tslib_1.__importDefault(require("./math-helper.js"));
var minMax = function (isMin, args) {
var _this = this;
args = Array.prototype.slice.call(args);
switch (args.length) {
case 0: throw { type: 'Argument', message: 'one or more arguments required' };
}
let i; // key is the unit.toString() for unified Dimension values,
let j;
let current;
let currentUnified;
let referenceUnified;
let unit;
let unitStatic;
let unitClone;
const // elems only contains original argument values.
order = [];
const values = {};
var i; // key is the unit.toString() for unified Dimension values,
var j;
var current;
var currentUnified;
var referenceUnified;
var unit;
var unitStatic;
var unitClone;
var // elems only contains original argument values.
order = [];
var values = {};
// value is the index into the order array.
for (i = 0; i < args.length; i++) {
current = args[i];
if (!(current instanceof Dimension)) {
if (!(current instanceof dimension_1.default)) {
if (Array.isArray(args[i].value)) {
Array.prototype.push.apply(args, Array.prototype.slice.call(args[i].value));
continue;
} else {
}
else {
throw { type: 'Argument', message: 'incompatible types' };
}
}
currentUnified = current.unit.toString() === '' && unitClone !== undefined ? new Dimension(current.value, unitClone).unify() : current.unify();
currentUnified = current.unit.toString() === '' && unitClone !== undefined ? new dimension_1.default(current.value, unitClone).unify() : current.unify();
unit = currentUnified.unit.toString() === '' && unitStatic !== undefined ? unitStatic : currentUnified.unit.toString();
unitStatic = unit !== '' && unitStatic === undefined || unit !== '' && order[0].unify().unit.toString() === '' ? unit : unitStatic;
unitClone = unit !== '' && unitClone === undefined ? current.unit.toString() : unitClone;
@@ -44,8 +46,8 @@ const minMax = function (isMin, args) {
order.push(current);
continue;
}
referenceUnified = order[j].unit.toString() === '' && unitClone !== undefined ? new Dimension(order[j].value, unitClone).unify() : order[j].unify();
if ( isMin && currentUnified.value < referenceUnified.value ||
referenceUnified = order[j].unit.toString() === '' && unitClone !== undefined ? new dimension_1.default(order[j].value, unitClone).unify() : order[j].unify();
if (isMin && currentUnified.value < referenceUnified.value ||
!isMin && currentUnified.value > referenceUnified.value) {
order[j] = current;
}
@@ -53,43 +55,52 @@ const minMax = function (isMin, args) {
if (order.length == 1) {
return order[0];
}
args = order.map(a => { return a.toCSS(this.context); }).join(this.context.compress ? ',' : ', ');
return new Anonymous(`${isMin ? 'min' : 'max'}(${args})`);
args = order.map(function (a) { return a.toCSS(_this.context); }).join(this.context.compress ? ',' : ', ');
return new anonymous_1.default("".concat(isMin ? 'min' : 'max', "(").concat(args, ")"));
};
export default {
min: function(...args) {
exports.default = {
min: function () {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
try {
return minMax.call(this, true, args);
} catch (e) {}
}
catch (e) { }
},
max: function(...args) {
max: function () {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
try {
return minMax.call(this, false, args);
} catch (e) {}
}
catch (e) { }
},
convert: function (val, unit) {
return val.convertTo(unit.value);
},
pi: function () {
return new Dimension(Math.PI);
return new dimension_1.default(Math.PI);
},
mod: function(a, b) {
return new Dimension(a.value % b.value, a.unit);
mod: function (a, b) {
return new dimension_1.default(a.value % b.value, a.unit);
},
pow: function(x, y) {
pow: function (x, y) {
if (typeof x === 'number' && typeof y === 'number') {
x = new Dimension(x);
y = new Dimension(y);
} else if (!(x instanceof Dimension) || !(y instanceof Dimension)) {
x = new dimension_1.default(x);
y = new dimension_1.default(y);
}
else if (!(x instanceof dimension_1.default) || !(y instanceof dimension_1.default)) {
throw { type: 'Argument', message: 'arguments must be numbers' };
}
return new Dimension(Math.pow(x.value, y.value), x.unit);
return new dimension_1.default(Math.pow(x.value, y.value), x.unit);
},
percentage: function (n) {
const result = mathHelper(num => num * 100, '%', n);
var result = (0, math_helper_js_1.default)(function (num) { return num * 100; }, '%', n);
return result;
}
};
//# sourceMappingURL=number.js.map
+22 -18
View File
@@ -1,36 +1,40 @@
import Quoted from '../tree/quoted.js';
import Anonymous from '../tree/anonymous.js';
import JavaScript from '../tree/javascript.js';
export default {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var tslib_1 = require("tslib");
var quoted_1 = tslib_1.__importDefault(require("../tree/quoted"));
var anonymous_1 = tslib_1.__importDefault(require("../tree/anonymous"));
var javascript_1 = tslib_1.__importDefault(require("../tree/javascript"));
exports.default = {
e: function (str) {
return new Quoted('"', str instanceof JavaScript ? str.evaluated : str.value, true);
return new quoted_1.default('"', str instanceof javascript_1.default ? str.evaluated : str.value, true);
},
escape: function (str) {
return new Anonymous(
encodeURI(str.value).replace(/=/g, '%3D').replace(/:/g, '%3A').replace(/#/g, '%23').replace(/;/g, '%3B')
.replace(/\(/g, '%28').replace(/\)/g, '%29'));
return new anonymous_1.default(encodeURI(str.value).replace(/=/g, '%3D').replace(/:/g, '%3A').replace(/#/g, '%23').replace(/;/g, '%3B')
.replace(/\(/g, '%28').replace(/\)/g, '%29'));
},
replace: function (string, pattern, replacement, flags) {
let result = string.value;
var result = string.value;
replacement = (replacement.type === 'Quoted') ?
replacement.value : replacement.toCSS();
result = result.replace(new RegExp(pattern.value, flags ? flags.value : ''), replacement);
return new Quoted(string.quote || '', result, string.escaped);
return new quoted_1.default(string.quote || '', result, string.escaped);
},
'%': function (string /* arg, arg, ... */) {
const args = Array.prototype.slice.call(arguments, 1);
let result = string.value;
for (let i = 0; i < args.length; i++) {
var args = Array.prototype.slice.call(arguments, 1);
var result = string.value;
var _loop_1 = function (i) {
/* jshint loopfunc:true */
result = result.replace(/%[sda]/i, token => {
const value = ((args[i].type === 'Quoted') &&
result = result.replace(/%[sda]/i, function (token) {
var value = ((args[i].type === 'Quoted') &&
token.match(/s/i)) ? args[i].value : args[i].toCSS();
return token.match(/[A-Z]$/) ? encodeURIComponent(value) : value;
});
};
for (var i = 0; i < args.length; i++) {
_loop_1(i);
}
result = result.replace(/%%/g, '%');
return new Quoted(string.quote || '', result, string.escaped);
return new quoted_1.default(string.quote || '', result, string.escaped);
}
};
//# sourceMappingURL=string.js.map
+20 -21
View File
@@ -1,29 +1,28 @@
import Variable from '../tree/variable.js';
import Anonymous from '../tree/anonymous.js';
/** @param {*[]} args */
const styleExpression = function (args) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var tslib_1 = require("tslib");
var variable_1 = tslib_1.__importDefault(require("../tree/variable"));
var variable_2 = tslib_1.__importDefault(require("../tree/variable"));
var styleExpression = function (args) {
var _this = this;
args = Array.prototype.slice.call(args);
if (args.length === 0) {
throw { type: 'Argument', message: 'one or more arguments required' };
switch (args.length) {
case 0: throw { type: 'Argument', message: 'one or more arguments required' };
}
const entityList = [new Variable(args[0].value, this.index, this.currentFileInfo).eval(this.context)];
const result = entityList.map(a => { return a.toCSS(this.context); }).join(this.context.compress ? ',' : ', ');
return new Anonymous(`style(${result})`);
var entityList = [new variable_1.default(args[0].value, this.index, this.currentFileInfo).eval(this.context)];
args = entityList.map(function (a) { return a.toCSS(_this.context); }).join(this.context.compress ? ',' : ', ');
return new variable_2.default("style(".concat(args, ")"));
};
export default {
/** @param {...*} args */
style: function(...args) {
exports.default = {
style: function () {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
try {
return styleExpression.call(this, args);
} catch (e) {
// When style() is used as a CSS function (e.g. @container style(--responsive: true)),
// arguments won't be valid Less variables. Return undefined to let the
// parser fall through and treat it as plain CSS.
}
catch (e) { }
},
};
//# sourceMappingURL=style.js.map
+82 -83
View File
@@ -1,87 +1,86 @@
import Dimension from '../tree/dimension.js';
import Color from '../tree/color.js';
import Expression from '../tree/expression.js';
import Quoted from '../tree/quoted.js';
import URL from '../tree/url.js';
export default () => {
return { 'svg-gradient': function(direction) {
let stops;
let gradientDirectionSvg;
let gradientType = 'linear';
let rectangleDimension = 'x="0" y="0" width="1" height="1"';
const renderEnv = {compress: false};
let returner;
const directionValue = direction.toCSS(renderEnv);
let i;
let color;
let position;
let positionValue;
let alpha;
function throwArgumentDescriptor() {
throw { type: 'Argument',
message: 'svg-gradient expects direction, start_color [start_position], [color position,]...,' +
' end_color [end_position] or direction, color list' };
}
if (arguments.length == 2) {
if (arguments[1].value.length < 2) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var tslib_1 = require("tslib");
var dimension_1 = tslib_1.__importDefault(require("../tree/dimension"));
var color_1 = tslib_1.__importDefault(require("../tree/color"));
var expression_1 = tslib_1.__importDefault(require("../tree/expression"));
var quoted_1 = tslib_1.__importDefault(require("../tree/quoted"));
var url_1 = tslib_1.__importDefault(require("../tree/url"));
exports.default = (function () {
return { 'svg-gradient': function (direction) {
var stops;
var gradientDirectionSvg;
var gradientType = 'linear';
var rectangleDimension = 'x="0" y="0" width="1" height="1"';
var renderEnv = { compress: false };
var returner;
var directionValue = direction.toCSS(renderEnv);
var i;
var color;
var position;
var positionValue;
var alpha;
function throwArgumentDescriptor() {
throw { type: 'Argument',
message: 'svg-gradient expects direction, start_color [start_position], [color position,]...,' +
' end_color [end_position] or direction, color list' };
}
if (arguments.length == 2) {
if (arguments[1].value.length < 2) {
throwArgumentDescriptor();
}
stops = arguments[1].value;
}
else if (arguments.length < 3) {
throwArgumentDescriptor();
}
stops = arguments[1].value;
} else if (arguments.length < 3) {
throwArgumentDescriptor();
} else {
stops = Array.prototype.slice.call(arguments, 1);
}
switch (directionValue) {
case 'to bottom':
gradientDirectionSvg = 'x1="0%" y1="0%" x2="0%" y2="100%"';
break;
case 'to right':
gradientDirectionSvg = 'x1="0%" y1="0%" x2="100%" y2="0%"';
break;
case 'to bottom right':
gradientDirectionSvg = 'x1="0%" y1="0%" x2="100%" y2="100%"';
break;
case 'to top right':
gradientDirectionSvg = 'x1="0%" y1="100%" x2="100%" y2="0%"';
break;
case 'ellipse':
case 'ellipse at center':
gradientType = 'radial';
gradientDirectionSvg = 'cx="50%" cy="50%" r="75%"';
rectangleDimension = 'x="-50" y="-50" width="101" height="101"';
break;
default:
throw { type: 'Argument', message: 'svg-gradient direction must be \'to bottom\', \'to right\',' +
' \'to bottom right\', \'to top right\' or \'ellipse at center\'' };
}
returner = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1 1"><${gradientType}Gradient id="g" ${gradientDirectionSvg}>`;
for (i = 0; i < stops.length; i += 1) {
if (stops[i] instanceof Expression) {
color = stops[i].value[0];
position = stops[i].value[1];
} else {
color = stops[i];
position = undefined;
else {
stops = Array.prototype.slice.call(arguments, 1);
}
if (!(color instanceof Color) || (!((i === 0 || i + 1 === stops.length) && position === undefined) && !(position instanceof Dimension))) {
throwArgumentDescriptor();
switch (directionValue) {
case 'to bottom':
gradientDirectionSvg = 'x1="0%" y1="0%" x2="0%" y2="100%"';
break;
case 'to right':
gradientDirectionSvg = 'x1="0%" y1="0%" x2="100%" y2="0%"';
break;
case 'to bottom right':
gradientDirectionSvg = 'x1="0%" y1="0%" x2="100%" y2="100%"';
break;
case 'to top right':
gradientDirectionSvg = 'x1="0%" y1="100%" x2="100%" y2="0%"';
break;
case 'ellipse':
case 'ellipse at center':
gradientType = 'radial';
gradientDirectionSvg = 'cx="50%" cy="50%" r="75%"';
rectangleDimension = 'x="-50" y="-50" width="101" height="101"';
break;
default:
throw { type: 'Argument', message: 'svg-gradient direction must be \'to bottom\', \'to right\',' +
' \'to bottom right\', \'to top right\' or \'ellipse at center\'' };
}
positionValue = position ? position.toCSS(renderEnv) : i === 0 ? '0%' : '100%';
alpha = color.alpha;
returner += `<stop offset="${positionValue}" stop-color="${color.toRGB()}"${alpha < 1 ? ` stop-opacity="${alpha}"` : ''}/>`;
}
returner += `</${gradientType}Gradient><rect ${rectangleDimension} fill="url(#g)" /></svg>`;
returner = encodeURIComponent(returner);
returner = `data:image/svg+xml,${returner}`;
return new URL(new Quoted(`'${returner}'`, returner, false, this.index, this.currentFileInfo), this.index, this.currentFileInfo);
}};
};
returner = "<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 1 1\"><".concat(gradientType, "Gradient id=\"g\" ").concat(gradientDirectionSvg, ">");
for (i = 0; i < stops.length; i += 1) {
if (stops[i] instanceof expression_1.default) {
color = stops[i].value[0];
position = stops[i].value[1];
}
else {
color = stops[i];
position = undefined;
}
if (!(color instanceof color_1.default) || (!((i === 0 || i + 1 === stops.length) && position === undefined) && !(position instanceof dimension_1.default))) {
throwArgumentDescriptor();
}
positionValue = position ? position.toCSS(renderEnv) : i === 0 ? '0%' : '100%';
alpha = color.alpha;
returner += "<stop offset=\"".concat(positionValue, "\" stop-color=\"").concat(color.toRGB(), "\"").concat(alpha < 1 ? " stop-opacity=\"".concat(alpha, "\"") : '', "/>");
}
returner += "</".concat(gradientType, "Gradient><rect ").concat(rectangleDimension, " fill=\"url(#g)\" /></svg>");
returner = encodeURIComponent(returner);
returner = "data:image/svg+xml,".concat(returner);
return new url_1.default(new quoted_1.default("'".concat(returner, "'"), returner, false, this.index, this.currentFileInfo), this.index, this.currentFileInfo);
} };
});
//# sourceMappingURL=svg.js.map
+32 -28
View File
@@ -1,14 +1,16 @@
import Keyword from '../tree/keyword.js';
import DetachedRuleset from '../tree/detached-ruleset.js';
import Dimension from '../tree/dimension.js';
import Color from '../tree/color.js';
import Quoted from '../tree/quoted.js';
import Anonymous from '../tree/anonymous.js';
import URL from '../tree/url.js';
import Operation from '../tree/operation.js';
const isa = (n, Type) => (n instanceof Type) ? Keyword.True : Keyword.False;
const isunit = (n, unit) => {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var tslib_1 = require("tslib");
var keyword_1 = tslib_1.__importDefault(require("../tree/keyword"));
var detached_ruleset_1 = tslib_1.__importDefault(require("../tree/detached-ruleset"));
var dimension_1 = tslib_1.__importDefault(require("../tree/dimension"));
var color_1 = tslib_1.__importDefault(require("../tree/color"));
var quoted_1 = tslib_1.__importDefault(require("../tree/quoted"));
var anonymous_1 = tslib_1.__importDefault(require("../tree/anonymous"));
var url_1 = tslib_1.__importDefault(require("../tree/url"));
var operation_1 = tslib_1.__importDefault(require("../tree/operation"));
var isa = function (n, Type) { return (n instanceof Type) ? keyword_1.default.True : keyword_1.default.False; };
var isunit = function (n, unit) {
if (unit === undefined) {
throw { type: 'Argument', message: 'missing the required second argument to isunit.' };
}
@@ -16,27 +18,26 @@ const isunit = (n, unit) => {
if (typeof unit !== 'string') {
throw { type: 'Argument', message: 'Second argument to isunit should be a unit or a string.' };
}
return (n instanceof Dimension) && n.unit.is(unit) ? Keyword.True : Keyword.False;
return (n instanceof dimension_1.default) && n.unit.is(unit) ? keyword_1.default.True : keyword_1.default.False;
};
export default {
exports.default = {
isruleset: function (n) {
return isa(n, DetachedRuleset);
return isa(n, detached_ruleset_1.default);
},
iscolor: function (n) {
return isa(n, Color);
return isa(n, color_1.default);
},
isnumber: function (n) {
return isa(n, Dimension);
return isa(n, dimension_1.default);
},
isstring: function (n) {
return isa(n, Quoted);
return isa(n, quoted_1.default);
},
iskeyword: function (n) {
return isa(n, Keyword);
return isa(n, keyword_1.default);
},
isurl: function (n) {
return isa(n, URL);
return isa(n, url_1.default);
},
ispixel: function (n) {
return isunit(n, 'px');
@@ -47,24 +48,27 @@ export default {
isem: function (n) {
return isunit(n, 'em');
},
isunit,
isunit: isunit,
unit: function (val, unit) {
if (!(val instanceof Dimension)) {
if (!(val instanceof dimension_1.default)) {
throw { type: 'Argument',
message: `the first argument to unit must be a number${val instanceof Operation ? '. Have you forgotten parenthesis?' : ''}` };
message: "the first argument to unit must be a number".concat(val instanceof operation_1.default ? '. Have you forgotten parenthesis?' : '') };
}
if (unit) {
if (unit instanceof Keyword) {
if (unit instanceof keyword_1.default) {
unit = unit.value;
} else {
}
else {
unit = unit.toCSS();
}
} else {
}
else {
unit = '';
}
return new Dimension(val.value, unit);
return new dimension_1.default(val.value, unit);
},
'get-unit': function (n) {
return new Anonymous(n.unit);
return new anonymous_1.default(n.unit);
}
};
//# sourceMappingURL=types.js.map
+64 -73
View File
@@ -1,10 +1,12 @@
import contexts from './contexts.js';
import Parser from './parser/parser.js';
import LessError from './less-error.js';
import * as utils from './utils.js';
import logger from './logger.js';
export default function(environment) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var tslib_1 = require("tslib");
var contexts_1 = tslib_1.__importDefault(require("./contexts"));
var parser_1 = tslib_1.__importDefault(require("./parser/parser"));
var less_error_1 = tslib_1.__importDefault(require("./less-error"));
var utils = tslib_1.__importStar(require("./utils"));
var logger_1 = tslib_1.__importDefault(require("./logger"));
function default_1(environment) {
// FileInfo = {
// 'rewriteUrls' - option - whether to adjust URL's to be relative
// 'filename' - full resolved filename of current file
@@ -13,22 +15,20 @@ export default function(environment) {
// 'rootFilename' - filename of the base file
// 'entryPath' - absolute path to the entry file
// 'reference' - whether the file should not be output and only output parts that are referenced
class ImportManager {
constructor(less, context, rootFileInfo) {
var ImportManager = /** @class */ (function () {
function ImportManager(less, context, rootFileInfo) {
this.less = less;
this.rootFilename = rootFileInfo.filename;
this.paths = context.paths || []; // Search paths, when importing
this.contents = {}; // map - filename to contents of all the files
this.paths = context.paths || []; // Search paths, when importing
this.contents = {}; // map - filename to contents of all the files
this.contentsIgnoredChars = {}; // map - filename to lines at the beginning of each file to ignore
this.mime = context.mime;
this.error = null;
this.context = context;
// Deprecated? Unused outside of here, could be useful.
this.queue = []; // Files which haven't been imported yet
this.files = {}; // Holds the imported parse trees.
this.queue = []; // Files which haven't been imported yet
this.files = {}; // Holds the imported parse trees.
}
/**
* Add an import to be imported
* @param path - the raw path
@@ -37,50 +37,44 @@ export default function(environment) {
* @param importOptions - import options
* @param callback - callback for when it is imported
*/
push(path, tryAppendExtension, currentFileInfo, importOptions, callback) {
const importManager = this, pluginLoader = this.context.pluginManager.Loader;
ImportManager.prototype.push = function (path, tryAppendExtension, currentFileInfo, importOptions, callback) {
var importManager = this, pluginLoader = this.context.pluginManager.Loader;
this.queue.push(path);
const fileParsedFunc = function (e, root, fullPath) {
var fileParsedFunc = function (e, root, fullPath) {
importManager.queue.splice(importManager.queue.indexOf(path), 1); // Remove the path from the queue
const importedEqualsRoot = fullPath === importManager.rootFilename;
var importedEqualsRoot = fullPath === importManager.rootFilename;
if (importOptions.optional && e) {
callback(null, {rules:[]}, false, null);
logger.info(`The file ${fullPath} was skipped because it was not found and the import was marked optional.`);
callback(null, { rules: [] }, false, null);
logger_1.default.info("The file ".concat(fullPath, " was skipped because it was not found and the import was marked optional."));
}
else {
// Inline imports aren't cached here.
// If we start to cache them, please make sure they won't conflict with non-inline imports of the
// same name as they used to do before this comment and the condition below have been added.
if (!importManager.files[fullPath] && !importOptions.inline) {
importManager.files[fullPath] = { root, options: importOptions };
importManager.files[fullPath] = { root: root, options: importOptions };
}
if (e && !importManager.error) {
importManager.error = e;
}
if (e && !importManager.error) { importManager.error = e; }
callback(e, root, importedEqualsRoot, fullPath);
}
};
const newFileInfo = {
var newFileInfo = {
rewriteUrls: this.context.rewriteUrls,
entryPath: currentFileInfo.entryPath,
rootpath: currentFileInfo.rootpath,
rootFilename: currentFileInfo.rootFilename
};
const fileManager = environment.getFileManager(path, currentFileInfo.currentDirectory, this.context, environment);
var fileManager = environment.getFileManager(path, currentFileInfo.currentDirectory, this.context, environment);
if (!fileManager) {
fileParsedFunc({ message: `Could not find a file-manager for ${path}` });
fileParsedFunc({ message: "Could not find a file-manager for ".concat(path) });
return;
}
const loadFileCallback = function(loadedFile) {
let plugin;
const resolvedFilename = loadedFile.filename;
const contents = loadedFile.contents.replace(/^\uFEFF/, '');
var loadFileCallback = function (loadedFile) {
var plugin;
var resolvedFilename = loadedFile.filename;
var contents = loadedFile.contents.replace(/^\uFEFF/, '');
// Pass on an updated rootpath if path of imported file is relative and file
// is in a (sub|sup) directory
//
@@ -91,93 +85,90 @@ export default function(environment) {
// then rootpath should become 'less/../'
newFileInfo.currentDirectory = fileManager.getPath(resolvedFilename);
if (newFileInfo.rewriteUrls) {
newFileInfo.rootpath = fileManager.join(
(importManager.context.rootpath || ''),
fileManager.pathDiff(newFileInfo.currentDirectory, newFileInfo.entryPath));
newFileInfo.rootpath = fileManager.join((importManager.context.rootpath || ''), fileManager.pathDiff(newFileInfo.currentDirectory, newFileInfo.entryPath));
if (!fileManager.isPathAbsolute(newFileInfo.rootpath) && fileManager.alwaysMakePathsAbsolute()) {
newFileInfo.rootpath = fileManager.join(newFileInfo.entryPath, newFileInfo.rootpath);
}
}
newFileInfo.filename = resolvedFilename;
const newEnv = new contexts.Parse(importManager.context);
var newEnv = new contexts_1.default.Parse(importManager.context);
newEnv.processImports = false;
importManager.contents[resolvedFilename] = contents;
if (currentFileInfo.reference || importOptions.reference) {
newFileInfo.reference = true;
}
if (importOptions.isPlugin) {
plugin = pluginLoader.evalPlugin(contents, newEnv, importManager, importOptions.pluginArgs, newFileInfo);
if (plugin instanceof LessError) {
if (plugin instanceof less_error_1.default) {
fileParsedFunc(plugin, null, resolvedFilename);
}
else {
fileParsedFunc(null, plugin, resolvedFilename);
}
} else if (importOptions.inline) {
}
else if (importOptions.inline) {
fileParsedFunc(null, contents, resolvedFilename);
} else {
}
else {
// import (multiple) parse trees apparently get altered and can't be cached.
// TODO: investigate why this is
if (importManager.files[resolvedFilename]
&& !importManager.files[resolvedFilename].options.multiple
&& !importOptions.multiple) {
fileParsedFunc(null, importManager.files[resolvedFilename].root, resolvedFilename);
}
else {
new Parser(newEnv, importManager, newFileInfo).parse(contents, function (e, root) {
new parser_1.default(newEnv, importManager, newFileInfo).parse(contents, function (e, root) {
fileParsedFunc(e, root, resolvedFilename);
});
}
}
};
let loadedFile;
let promise;
const context = utils.clone(this.context);
var loadedFile;
var promise;
var context = utils.clone(this.context);
if (tryAppendExtension) {
context.ext = importOptions.isPlugin ? '.js' : '.less';
}
if (importOptions.isPlugin) {
context.mime = 'application/javascript';
if (context.syncImport) {
loadedFile = pluginLoader.loadPluginSync(path, currentFileInfo.currentDirectory, context, environment, fileManager);
} else {
}
else {
promise = pluginLoader.loadPlugin(path, currentFileInfo.currentDirectory, context, environment, fileManager);
}
}
else {
if (context.syncImport) {
loadedFile = fileManager.loadFileSync(path, currentFileInfo.currentDirectory, context, environment);
} else {
promise = fileManager.loadFile(path, currentFileInfo.currentDirectory, context, environment,
(err, loadedFile) => {
if (err) {
fileParsedFunc(err);
} else {
loadFileCallback(loadedFile);
}
});
}
else {
promise = fileManager.loadFile(path, currentFileInfo.currentDirectory, context, environment, function (err, loadedFile) {
if (err) {
fileParsedFunc(err);
}
else {
loadFileCallback(loadedFile);
}
});
}
}
if (loadedFile) {
if (!loadedFile.filename) {
fileParsedFunc(loadedFile);
} else {
}
else {
loadFileCallback(loadedFile);
}
} else if (promise) {
}
else if (promise) {
promise.then(loadFileCallback, fileParsedFunc);
}
}
}
};
return ImportManager;
}());
return ImportManager;
}
exports.default = default_1;
//# sourceMappingURL=import-manager.js.map
+65 -65
View File
@@ -1,73 +1,73 @@
import Environment from './environment/environment.js';
import data from './data/index.js';
import tree from './tree/index.js';
import AbstractFileManager from './environment/abstract-file-manager.js';
import AbstractPluginLoader from './environment/abstract-plugin-loader.js';
import visitors from './visitors/index.js';
import Parser from './parser/parser.js';
import functions from './functions/index.js';
import contexts from './contexts.js';
import LessError from './less-error.js';
import transformTree from './transform-tree.js';
import * as utils from './utils.js';
import PluginManager from './plugin-manager.js';
import logger from './logger.js';
import SourceMapOutput from './source-map-output.js';
import SourceMapBuilder from './source-map-builder.js';
import ParseTree from './parse-tree.js';
import ImportManager from './import-manager.js';
import Parse from './parse.js';
import Render from './render.js';
import parseVersion from 'parse-node-version';
export default function(environment, fileManagers, version = '0.0.0') {
let sourceMapOutput, sourceMapBuilder, parseTree, importManager;
environment = new Environment(environment, fileManagers);
sourceMapOutput = SourceMapOutput(environment);
sourceMapBuilder = SourceMapBuilder(sourceMapOutput, environment);
parseTree = ParseTree(sourceMapBuilder);
importManager = ImportManager(environment);
const render = Render(environment, parseTree, importManager);
const parse = Parse(environment, parseTree, importManager);
const v = parseVersion(`v${version}`);
const initial = {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var tslib_1 = require("tslib");
var environment_1 = tslib_1.__importDefault(require("./environment/environment"));
var data_1 = tslib_1.__importDefault(require("./data"));
var tree_1 = tslib_1.__importDefault(require("./tree"));
var abstract_file_manager_1 = tslib_1.__importDefault(require("./environment/abstract-file-manager"));
var abstract_plugin_loader_1 = tslib_1.__importDefault(require("./environment/abstract-plugin-loader"));
var visitors_1 = tslib_1.__importDefault(require("./visitors"));
var parser_1 = tslib_1.__importDefault(require("./parser/parser"));
var functions_1 = tslib_1.__importDefault(require("./functions"));
var contexts_1 = tslib_1.__importDefault(require("./contexts"));
var less_error_1 = tslib_1.__importDefault(require("./less-error"));
var transform_tree_1 = tslib_1.__importDefault(require("./transform-tree"));
var utils = tslib_1.__importStar(require("./utils"));
var plugin_manager_1 = tslib_1.__importDefault(require("./plugin-manager"));
var logger_1 = tslib_1.__importDefault(require("./logger"));
var source_map_output_1 = tslib_1.__importDefault(require("./source-map-output"));
var source_map_builder_1 = tslib_1.__importDefault(require("./source-map-builder"));
var parse_tree_1 = tslib_1.__importDefault(require("./parse-tree"));
var import_manager_1 = tslib_1.__importDefault(require("./import-manager"));
var parse_1 = tslib_1.__importDefault(require("./parse"));
var render_1 = tslib_1.__importDefault(require("./render"));
var package_json_1 = require("../../package.json");
var parse_node_version_1 = tslib_1.__importDefault(require("parse-node-version"));
function default_1(environment, fileManagers) {
var sourceMapOutput, sourceMapBuilder, parseTree, importManager;
environment = new environment_1.default(environment, fileManagers);
sourceMapOutput = (0, source_map_output_1.default)(environment);
sourceMapBuilder = (0, source_map_builder_1.default)(sourceMapOutput, environment);
parseTree = (0, parse_tree_1.default)(sourceMapBuilder);
importManager = (0, import_manager_1.default)(environment);
var render = (0, render_1.default)(environment, parseTree, importManager);
var parse = (0, parse_1.default)(environment, parseTree, importManager);
var v = (0, parse_node_version_1.default)("v".concat(package_json_1.version));
var initial = {
version: [v.major, v.minor, v.patch],
data,
tree,
Environment,
AbstractFileManager,
AbstractPluginLoader,
environment,
visitors,
Parser,
functions: functions(environment),
contexts,
data: data_1.default,
tree: tree_1.default,
Environment: environment_1.default,
AbstractFileManager: abstract_file_manager_1.default,
AbstractPluginLoader: abstract_plugin_loader_1.default,
environment: environment,
visitors: visitors_1.default,
Parser: parser_1.default,
functions: (0, functions_1.default)(environment),
contexts: contexts_1.default,
SourceMapOutput: sourceMapOutput,
SourceMapBuilder: sourceMapBuilder,
ParseTree: parseTree,
ImportManager: importManager,
render,
parse,
LessError,
transformTree,
utils,
PluginManager,
logger
render: render,
parse: parse,
LessError: less_error_1.default,
transformTree: transform_tree_1.default,
utils: utils,
PluginManager: plugin_manager_1.default,
logger: logger_1.default
};
// Create a public API
const ctor = function(t) {
return function(...args) {
return new t(...args);
var ctor = function (t) {
return function () {
var obj = Object.create(t.prototype);
t.apply(obj, Array.prototype.slice.call(arguments, 0));
return obj;
};
};
let t;
const api = Object.create(initial);
for (const n in initial.tree) {
var t;
var api = Object.create(initial);
for (var n in initial.tree) {
/* eslint guard-for-in: 0 */
t = initial.tree[n];
if (typeof t === 'function') {
@@ -75,21 +75,21 @@ export default function(environment, fileManagers, version = '0.0.0') {
}
else {
api[n] = Object.create(null);
for (const o in t) {
for (var o in t) {
/* eslint guard-for-in: 0 */
api[n][o.toLowerCase()] = ctor(t[o]);
}
}
}
/**
* Some of the functions assume a `this` context of the API object,
* which causes it to fail when wrapped for ES6 imports.
*
*
* An assumed `this` should be removed in the future.
*/
initial.parse = initial.parse.bind(api);
initial.render = initial.render.bind(api);
return api;
}
exports.default = default_1;
//# sourceMappingURL=index.js.map
+46 -65
View File
@@ -1,7 +1,8 @@
import * as utils from './utils.js';
const anonymousFunc = /(<anonymous>|Function):(\d+):(\d+)/;
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var tslib_1 = require("tslib");
var utils = tslib_1.__importStar(require("./utils"));
var anonymousFunc = /(<anonymous>|Function):(\d+):(\d+)/;
/**
* This is a centralized class of any error that could be thrown internally (mostly by the parser).
* Besides standard .message it keeps some additional data like a path to the file where the error
@@ -24,33 +25,25 @@ const anonymousFunc = /(<anonymous>|Function):(\d+):(\d+)/;
* @param {Object} fileContentMap - An object with file contents in 'contents' property (like importManager) @todo - move to fileManager?
* @param {string} [currentFilename]
*/
const LessError = function(e, fileContentMap, currentFilename) {
var LessError = function (e, fileContentMap, currentFilename) {
Error.call(this);
const filename = e.filename || currentFilename;
var filename = e.filename || currentFilename;
this.message = e.message;
this.stack = e.stack;
// Set type early so it's always available, even if fileContentMap is missing
this.type = e.type || 'Syntax';
if (fileContentMap && filename) {
const input = fileContentMap.contents[filename];
const loc = utils.getLocation(e.index, input);
var input = fileContentMap.contents[filename];
var loc = utils.getLocation(e.index, input);
var line = loc.line;
const col = loc.column;
const callLine = e.call && utils.getLocation(e.call, input).line;
const lines = input ? input.split('\n') : '';
var col = loc.column;
var callLine = e.call && utils.getLocation(e.call, input).line;
var lines = input ? input.split('\n') : '';
this.type = e.type || 'Syntax';
this.filename = filename;
this.index = e.index;
this.line = typeof line === 'number' ? line + 1 : null;
this.column = col;
if (!this.line && this.stack) {
const found = this.stack.match(anonymousFunc);
var found = this.stack.match(anonymousFunc);
/**
* We have to figure out how this environment stringifies anonymous functions
* so we can correctly map plugin errors.
@@ -58,15 +51,15 @@ const LessError = function(e, fileContentMap, currentFilename) {
* Note, in Node 8, the output of anonymous funcs varied based on parameters
* being present or not, so we inject dummy params.
*/
const func = new Function('a', 'throw new Error()');
let lineAdjust = 0;
var func = new Function('a', 'throw new Error()');
var lineAdjust = 0;
try {
func();
} catch (e) {
const match = e.stack.match(anonymousFunc);
}
catch (e) {
var match = e.stack.match(anonymousFunc);
lineAdjust = 1 - parseInt(match[2]);
}
if (found) {
if (found[2]) {
this.line = parseInt(found[2]) + lineAdjust;
@@ -76,29 +69,24 @@ const LessError = function(e, fileContentMap, currentFilename) {
}
}
}
this.callLine = callLine + 1;
this.callExtract = lines[callLine];
this.extract = [
lines[this.line - 2],
lines[this.line - 1],
lines[this.line]
];
}
};
if (typeof Object.create === 'undefined') {
const F = function () {};
var F = function () { };
F.prototype = Error.prototype;
LessError.prototype = new F();
} else {
}
else {
LessError.prototype = Object.create(Error.prototype);
}
LessError.prototype.constructor = LessError;
/**
* An overridden version of the default Object.prototype.toString
* which uses additional information to create a helpful message.
@@ -106,61 +94,54 @@ LessError.prototype.constructor = LessError;
* @param {Object} options
* @returns {string}
*/
LessError.prototype.toString = function(options) {
LessError.prototype.toString = function (options) {
var _a;
options = options || {};
const isWarning = (this.type ?? '').toLowerCase().includes('warning');
const type = isWarning ? this.type : `${this.type}Error`;
const color = isWarning ? 'yellow' : 'red';
let message = '';
const extract = this.extract || [];
let error = [];
let stylize = function (str) { return str; };
var isWarning = ((_a = this.type) !== null && _a !== void 0 ? _a : '').toLowerCase().includes('warning');
var type = isWarning ? this.type : "".concat(this.type, "Error");
var color = isWarning ? 'yellow' : 'red';
var message = '';
var extract = this.extract || [];
var error = [];
var stylize = function (str) { return str; };
if (options.stylize) {
const type = typeof options.stylize;
if (type !== 'function') {
throw Error(`options.stylize should be a function, got a ${type}!`);
var type_1 = typeof options.stylize;
if (type_1 !== 'function') {
throw Error("options.stylize should be a function, got a ".concat(type_1, "!"));
}
stylize = options.stylize;
}
if (this.line !== null) {
if (!isWarning && typeof extract[0] === 'string') {
error.push(stylize(`${this.line - 1} ${extract[0]}`, 'grey'));
error.push(stylize("".concat(this.line - 1, " ").concat(extract[0]), 'grey'));
}
if (typeof extract[1] === 'string') {
let errorTxt = `${this.line} `;
var errorTxt = "".concat(this.line, " ");
if (extract[1]) {
errorTxt += extract[1].slice(0, this.column) +
stylize(stylize(stylize(extract[1].slice(this.column, this.column + 1), 'bold') +
stylize(stylize(stylize(extract[1].substr(this.column, 1), 'bold') +
extract[1].slice(this.column + 1), 'red'), 'inverse');
}
error.push(errorTxt);
}
if (!isWarning && typeof extract[2] === 'string') {
error.push(stylize(`${this.line + 1} ${extract[2]}`, 'grey'));
error.push(stylize("".concat(this.line + 1, " ").concat(extract[2]), 'grey'));
}
error = `${error.join('\n') + stylize('', 'reset')}\n`;
error = "".concat(error.join('\n') + stylize('', 'reset'), "\n");
}
message += stylize(`${type}: ${this.message}`, color);
message += stylize("".concat(type, ": ").concat(this.message), color);
if (this.filename) {
message += stylize(' in ', color) + this.filename;
}
if (this.line) {
message += stylize(` on line ${this.line}, column ${this.column + 1}:`, 'grey');
message += stylize(" on line ".concat(this.line, ", column ").concat(this.column + 1, ":"), 'grey');
}
message += `\n${error}`;
message += "\n".concat(error);
if (this.callLine) {
message += `${stylize('from ', color) + (this.filename || '')}/n`;
message += `${stylize(this.callLine, 'grey')} ${this.callExtract}/n`;
message += "".concat(stylize('from ', color) + (this.filename || ''), "/n");
message += "".concat(stylize(this.callLine, 'grey'), " ").concat(this.callExtract, "/n");
}
return message;
};
export default LessError;
exports.default = LessError;
//# sourceMappingURL=less-error.js.map
+14 -11
View File
@@ -1,30 +1,32 @@
export default {
error: function(msg) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = {
error: function (msg) {
this._fireEvent('error', msg);
},
warn: function(msg) {
warn: function (msg) {
this._fireEvent('warn', msg);
},
info: function(msg) {
info: function (msg) {
this._fireEvent('info', msg);
},
debug: function(msg) {
debug: function (msg) {
this._fireEvent('debug', msg);
},
addListener: function(listener) {
addListener: function (listener) {
this._listeners.push(listener);
},
removeListener: function(listener) {
for (let i = 0; i < this._listeners.length; i++) {
removeListener: function (listener) {
for (var i = 0; i < this._listeners.length; i++) {
if (this._listeners[i] === listener) {
this._listeners.splice(i, 1);
return;
}
}
},
_fireEvent: function(type, msg) {
for (let i = 0; i < this._listeners.length; i++) {
const logFunction = this._listeners[i][type];
_fireEvent: function (type, msg) {
for (var i = 0; i < this._listeners.length; i++) {
var logFunction = this._listeners[i][type];
if (logFunction) {
logFunction(msg);
}
@@ -32,3 +34,4 @@ export default {
},
_listeners: []
};
//# sourceMappingURL=logger.js.map
+38 -94
View File
@@ -1,124 +1,68 @@
import LessError from './less-error.js';
import transformTree from './transform-tree.js';
import logger from './logger.js';
export default function(SourceMapBuilder) {
class ParseTree {
constructor(root, imports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var tslib_1 = require("tslib");
var less_error_1 = tslib_1.__importDefault(require("./less-error"));
var transform_tree_1 = tslib_1.__importDefault(require("./transform-tree"));
var logger_1 = tslib_1.__importDefault(require("./logger"));
function default_1(SourceMapBuilder) {
var ParseTree = /** @class */ (function () {
function ParseTree(root, imports) {
this.root = root;
this.imports = imports;
}
toCSS(options) {
let evaldRoot;
const result = {};
let sourceMapBuilder;
ParseTree.prototype.toCSS = function (options) {
var evaldRoot;
var result = {};
var sourceMapBuilder;
try {
evaldRoot = transformTree(this.root, options);
} catch (e) {
throw new LessError(e, this.imports);
evaldRoot = (0, transform_tree_1.default)(this.root, options);
}
catch (e) {
throw new less_error_1.default(e, this.imports);
}
try {
const compress = Boolean(options.compress);
var compress = Boolean(options.compress);
if (compress) {
logger.warn('The compress option has been deprecated. ' +
logger_1.default.warn('The compress option has been deprecated. ' +
'We recommend you use a dedicated css minifier, for instance see less-plugin-clean-css.');
}
const toCSSOptions = {
compress,
// @deprecated The dumpLineNumbers option is deprecated. Use sourcemaps instead. All modes will be removed in a future version.
var toCSSOptions = {
compress: compress,
dumpLineNumbers: options.dumpLineNumbers,
strictUnits: Boolean(options.strictUnits),
numPrecision: 8};
numPrecision: 8
};
if (options.sourceMap) {
// Normalize sourceMap option: if it's just true, convert to object
if (options.sourceMap === true) {
options.sourceMap = {};
}
const sourceMapOpts = options.sourceMap;
// Set sourceMapInputFilename if not set and filename is available
if (!sourceMapOpts.sourceMapInputFilename && options.filename) {
sourceMapOpts.sourceMapInputFilename = options.filename;
}
// Default sourceMapBasepath to the input file's directory if not set
// This matches the behavior documented and implemented in bin/lessc
if (sourceMapOpts.sourceMapBasepath === undefined && options.filename) {
// Get directory from filename using string manipulation (works cross-platform)
const lastSlash = Math.max(options.filename.lastIndexOf('/'), options.filename.lastIndexOf('\\'));
if (lastSlash >= 0) {
sourceMapOpts.sourceMapBasepath = options.filename.substring(0, lastSlash);
} else {
// No directory separator found, use current directory
sourceMapOpts.sourceMapBasepath = '.';
}
}
// Handle sourceMapFullFilename (CLI-specific: --source-map=filename)
// This is converted to sourceMapFilename and sourceMapOutputFilename
if (sourceMapOpts.sourceMapFullFilename && !sourceMapOpts.sourceMapFileInline) {
// This case is handled by lessc before calling render
// We just need to ensure sourceMapFilename is set if sourceMapFullFilename is provided
if (!sourceMapOpts.sourceMapFilename && !sourceMapOpts.sourceMapURL) {
// Extract just the basename for the sourceMappingURL comment
const mapBase = sourceMapOpts.sourceMapFullFilename.split(/[/\\]/).pop();
sourceMapOpts.sourceMapFilename = mapBase;
}
} else if (!sourceMapOpts.sourceMapFilename && !sourceMapOpts.sourceMapURL) {
// If sourceMapFilename is not set and sourceMapURL is not set,
// derive it from the output filename (if available) or input filename
if (sourceMapOpts.sourceMapOutputFilename) {
// Use output filename + .map
sourceMapOpts.sourceMapFilename = sourceMapOpts.sourceMapOutputFilename + '.map';
} else if (options.filename) {
// Fallback to input filename + .css.map (basename only)
const inputBasename = options.filename.split(/[/\\]/).pop().replace(/\.[^/.]+$/, '');
sourceMapOpts.sourceMapFilename = inputBasename + '.css.map';
}
}
// Default sourceMapOutputFilename if not set
if (!sourceMapOpts.sourceMapOutputFilename) {
if (options.filename) {
const inputBasename = options.filename.split(/[/\\]/).pop().replace(/\.[^/.]+$/, '');
sourceMapOpts.sourceMapOutputFilename = inputBasename + '.css';
} else {
sourceMapOpts.sourceMapOutputFilename = 'output.css';
}
}
sourceMapBuilder = new SourceMapBuilder(sourceMapOpts);
sourceMapBuilder = new SourceMapBuilder(options.sourceMap);
result.css = sourceMapBuilder.toCSS(evaldRoot, toCSSOptions, this.imports);
} else {
}
else {
result.css = evaldRoot.toCSS(toCSSOptions);
}
} catch (e) {
throw new LessError(e, this.imports);
}
catch (e) {
throw new less_error_1.default(e, this.imports);
}
if (options.pluginManager) {
const postProcessors = options.pluginManager.getPostProcessors();
for (let i = 0; i < postProcessors.length; i++) {
result.css = postProcessors[i].process(result.css, { sourceMap: sourceMapBuilder, options, imports: this.imports });
var postProcessors = options.pluginManager.getPostProcessors();
for (var i = 0; i < postProcessors.length; i++) {
result.css = postProcessors[i].process(result.css, { sourceMap: sourceMapBuilder, options: options, imports: this.imports });
}
}
if (options.sourceMap) {
result.map = sourceMapBuilder.getExternalSourceMap();
}
result.imports = [];
for (const file in this.imports.files) {
for (var file in this.imports.files) {
if (Object.prototype.hasOwnProperty.call(this.imports.files, file) && file !== this.imports.rootFilename) {
result.imports.push(file);
}
}
return result;
}
}
};
return ParseTree;
}());
return ParseTree;
}
exports.default = default_1;
//# sourceMappingURL=parse-tree.js.map
+44 -44
View File
@@ -1,12 +1,13 @@
import contexts from './contexts.js';
import Parser from './parser/parser.js';
import PluginManager from './plugin-manager.js';
import LessError from './less-error.js';
import * as utils from './utils.js';
export default function(environment, ParseTree, ImportManager) {
const parse = function (input, options, callback) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var tslib_1 = require("tslib");
var contexts_1 = tslib_1.__importDefault(require("./contexts"));
var parser_1 = tslib_1.__importDefault(require("./parser/parser"));
var plugin_manager_1 = tslib_1.__importDefault(require("./plugin-manager"));
var less_error_1 = tslib_1.__importDefault(require("./less-error"));
var utils = tslib_1.__importStar(require("./utils"));
function default_1(environment, ParseTree, ImportManager) {
var parse = function (input, options, callback) {
if (typeof options === 'function') {
callback = options;
options = utils.copyOptions(this.options, {});
@@ -14,38 +15,37 @@ export default function(environment, ParseTree, ImportManager) {
else {
options = utils.copyOptions(this.options, options || {});
}
if (!callback) {
const self = this;
var self_1 = this;
return new Promise(function (resolve, reject) {
parse.call(self, input, options, function(err, output) {
parse.call(self_1, input, options, function (err, output) {
if (err) {
reject(err);
} else {
}
else {
resolve(output);
}
});
});
} else {
let context;
let rootFileInfo;
const pluginManager = new PluginManager(this, !options.reUsePluginManager);
options.pluginManager = pluginManager;
context = new contexts.Parse(options);
}
else {
var context_1;
var rootFileInfo = void 0;
var pluginManager_1 = new plugin_manager_1.default(this, !options.reUsePluginManager);
options.pluginManager = pluginManager_1;
context_1 = new contexts_1.default.Parse(options);
if (options.rootFileInfo) {
rootFileInfo = options.rootFileInfo;
} else {
const filename = options.filename || 'input';
const entryPath = filename.replace(/[^/\\]*$/, '');
}
else {
var filename = options.filename || 'input';
var entryPath = filename.replace(/[^/\\]*$/, '');
rootFileInfo = {
filename,
rewriteUrls: context.rewriteUrls,
rootpath: context.rootpath || '',
filename: filename,
rewriteUrls: context_1.rewriteUrls,
rootpath: context_1.rootpath || '',
currentDirectory: entryPath,
entryPath,
entryPath: entryPath,
rootFilename: filename
};
// add in a missing trailing slash
@@ -53,35 +53,35 @@ export default function(environment, ParseTree, ImportManager) {
rootFileInfo.rootpath += '/';
}
}
const imports = new ImportManager(this, context, rootFileInfo);
this.importManager = imports;
var imports_1 = new ImportManager(this, context_1, rootFileInfo);
this.importManager = imports_1;
// TODO: allow the plugins to be just a list of paths or names
// Do an async plugin queue like lessc
if (options.plugins) {
options.plugins.forEach(function(plugin) {
let evalResult, contents;
options.plugins.forEach(function (plugin) {
var evalResult, contents;
if (plugin.fileContent) {
contents = plugin.fileContent.replace(/^\uFEFF/, '');
evalResult = pluginManager.Loader.evalPlugin(contents, context, imports, plugin.options, plugin.filename);
if (evalResult instanceof LessError) {
evalResult = pluginManager_1.Loader.evalPlugin(contents, context_1, imports_1, plugin.options, plugin.filename);
if (evalResult instanceof less_error_1.default) {
return callback(evalResult);
}
}
else {
pluginManager.addPlugin(plugin);
pluginManager_1.addPlugin(plugin);
}
});
}
new Parser(context, imports, rootFileInfo)
new parser_1.default(context_1, imports_1, rootFileInfo)
.parse(input, function (e, root) {
if (e) { return callback(e); }
callback(null, root, imports, options);
}, options);
if (e) {
return callback(e);
}
callback(null, root, imports_1, options);
}, options);
}
};
return parse;
}
exports.default = default_1;
//# sourceMappingURL=parse.js.map
+131 -152
View File
@@ -1,70 +1,64 @@
export default () => {
let // Less input string
input;
let // current chunk
j;
const // holds state for backtracking
saveStack = [];
let // furthest index the parser has gone to
furthest;
let // if this is furthest we got to, this is the probably cause
furthestPossibleErrorMessage;
let // chunkified input
chunks;
let // current chunk
current;
let // index of current chunk, in `input`
currentPos;
const parserInput = {};
const CHARCODE_SPACE = 32;
const CHARCODE_TAB = 9;
const CHARCODE_LF = 10;
const CHARCODE_CR = 13;
const CHARCODE_PLUS = 43;
const CHARCODE_COMMA = 44;
const CHARCODE_FORWARD_SLASH = 47;
const CHARCODE_9 = 57;
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var tslib_1 = require("tslib");
var chunker_1 = tslib_1.__importDefault(require("./chunker"));
exports.default = (function () {
var // Less input string
input;
var // current chunk
j;
var // holds state for backtracking
saveStack = [];
var // furthest index the parser has gone to
furthest;
var // if this is furthest we got to, this is the probably cause
furthestPossibleErrorMessage;
var // chunkified input
chunks;
var // current chunk
current;
var // index of current chunk, in `input`
currentPos;
var parserInput = {};
var CHARCODE_SPACE = 32;
var CHARCODE_TAB = 9;
var CHARCODE_LF = 10;
var CHARCODE_CR = 13;
var CHARCODE_PLUS = 43;
var CHARCODE_COMMA = 44;
var CHARCODE_FORWARD_SLASH = 47;
var CHARCODE_9 = 57;
function skipWhitespace(length) {
const oldi = parserInput.i;
const oldj = j;
const curr = parserInput.i - currentPos;
const endIndex = parserInput.i + current.length - curr;
const mem = (parserInput.i += length);
const inp = input;
let c;
let nextChar;
let comment;
var oldi = parserInput.i;
var oldj = j;
var curr = parserInput.i - currentPos;
var endIndex = parserInput.i + current.length - curr;
var mem = (parserInput.i += length);
var inp = input;
var c;
var nextChar;
var comment;
for (; parserInput.i < endIndex; parserInput.i++) {
c = inp.charCodeAt(parserInput.i);
if (parserInput.autoCommentAbsorb && c === CHARCODE_FORWARD_SLASH) {
nextChar = inp.charAt(parserInput.i + 1);
if (nextChar === '/') {
comment = {index: parserInput.i, isLineComment: true};
let nextNewLine = inp.indexOf('\n', parserInput.i + 2);
comment = { index: parserInput.i, isLineComment: true };
var nextNewLine = inp.indexOf('\n', parserInput.i + 2);
if (nextNewLine < 0) {
nextNewLine = endIndex;
}
parserInput.i = nextNewLine;
comment.text = inp.slice(comment.index, parserInput.i);
comment.text = inp.substr(comment.index, parserInput.i - comment.index);
parserInput.commentStore.push(comment);
continue;
} else if (nextChar === '*') {
const nextStarSlash = inp.indexOf('*/', parserInput.i + 2);
}
else if (nextChar === '*') {
var nextStarSlash = inp.indexOf('*/', parserInput.i + 2);
if (nextStarSlash >= 0) {
comment = {
index: parserInput.i,
text: inp.slice(parserInput.i, nextStarSlash + 2),
text: inp.substr(parserInput.i, nextStarSlash + 2 - parserInput.i),
isLineComment: false
};
parserInput.i += comment.text.length - 1;
@@ -74,15 +68,12 @@ export default () => {
}
break;
}
if ((c !== CHARCODE_SPACE) && (c !== CHARCODE_LF) && (c !== CHARCODE_TAB) && (c !== CHARCODE_CR)) {
break;
}
}
current = current.slice(length + parserInput.i - mem + curr);
currentPos = parserInput.i;
if (!current.length) {
if (j < chunks.length - 1) {
current = chunks[++j];
@@ -91,95 +82,80 @@ export default () => {
}
parserInput.finished = true;
}
return oldi !== parserInput.i || oldj !== j;
}
parserInput.save = () => {
parserInput.save = function () {
currentPos = parserInput.i;
saveStack.push( { current, i: parserInput.i, j });
saveStack.push({ current: current, i: parserInput.i, j: j });
};
parserInput.restore = possibleErrorMessage => {
parserInput.restore = function (possibleErrorMessage) {
if (parserInput.i > furthest || (parserInput.i === furthest && possibleErrorMessage && !furthestPossibleErrorMessage)) {
furthest = parserInput.i;
furthestPossibleErrorMessage = possibleErrorMessage;
}
const state = saveStack.pop();
var state = saveStack.pop();
current = state.current;
currentPos = parserInput.i = state.i;
j = state.j;
};
parserInput.forget = () => {
parserInput.forget = function () {
saveStack.pop();
};
parserInput.isWhitespace = offset => {
const pos = parserInput.i + (offset || 0);
const code = input.charCodeAt(pos);
parserInput.isWhitespace = function (offset) {
var pos = parserInput.i + (offset || 0);
var code = input.charCodeAt(pos);
return (code === CHARCODE_SPACE || code === CHARCODE_CR || code === CHARCODE_TAB || code === CHARCODE_LF);
};
// Specialization of $(tok)
parserInput.$re = tok => {
parserInput.$re = function (tok) {
if (parserInput.i > currentPos) {
current = current.slice(parserInput.i - currentPos);
currentPos = parserInput.i;
}
const m = tok.exec(current);
var m = tok.exec(current);
if (!m) {
return null;
}
skipWhitespace(m[0].length);
if (typeof m === 'string') {
return m;
}
return m.length === 1 ? m[0] : m;
};
parserInput.$char = tok => {
parserInput.$char = function (tok) {
if (input.charAt(parserInput.i) !== tok) {
return null;
}
skipWhitespace(1);
return tok;
};
parserInput.$peekChar = tok => {
parserInput.$peekChar = function (tok) {
if (input.charAt(parserInput.i) !== tok) {
return null;
}
return tok;
};
parserInput.$str = tok => {
const tokLength = tok.length;
parserInput.$str = function (tok) {
var tokLength = tok.length;
// https://jsperf.com/string-startswith/21
for (let i = 0; i < tokLength; i++) {
for (var i = 0; i < tokLength; i++) {
if (input.charAt(parserInput.i + i) !== tok.charAt(i)) {
return null;
}
}
skipWhitespace(tokLength);
return tok;
};
parserInput.$quoted = loc => {
const pos = loc || parserInput.i;
const startChar = input.charAt(pos);
parserInput.$quoted = function (loc) {
var pos = loc || parserInput.i;
var startChar = input.charAt(pos);
if (startChar !== '\'' && startChar !== '"') {
return;
}
const length = input.length;
const currentPosition = pos;
for (let i = 1; i + currentPosition < length; i++) {
const nextChar = input.charAt(i + currentPosition);
var length = input.length;
var currentPosition = pos;
for (var i = 1; i + currentPosition < length; i++) {
var nextChar = input.charAt(i + currentPosition);
switch (nextChar) {
case '\\':
i++;
@@ -188,10 +164,10 @@ export default () => {
case '\n':
break;
case startChar: {
const str = input.slice(currentPosition, currentPosition + i + 1);
var str = input.substr(currentPosition, i + 1);
if (!loc && loc !== 0) {
skipWhitespace(i + 1);
return str
return str;
}
return [startChar, str];
}
@@ -200,35 +176,33 @@ export default () => {
}
return null;
};
/**
* Permissive parsing. Ignores everything except matching {} [] () and quotes
* until matching token (outside of blocks)
*/
parserInput.$parseUntil = tok => {
let quote = '';
let returnVal = null;
let inComment = false;
let blockDepth = 0;
const blockStack = [];
const parseGroups = [];
const length = input.length;
const startPos = parserInput.i;
let lastPos = parserInput.i;
let i = parserInput.i;
let loop = true;
let testChar;
parserInput.$parseUntil = function (tok) {
var quote = '';
var returnVal = null;
var inComment = false;
var blockDepth = 0;
var blockStack = [];
var parseGroups = [];
var length = input.length;
var startPos = parserInput.i;
var lastPos = parserInput.i;
var i = parserInput.i;
var loop = true;
var testChar;
if (typeof tok === 'string') {
testChar = char => char === tok
} else {
testChar = char => tok.test(char)
testChar = function (char) { return char === tok; };
}
else {
testChar = function (char) { return tok.test(char); };
}
do {
let nextChar = input.charAt(i);
var nextChar = input.charAt(i);
if (blockDepth === 0 && testChar(nextChar)) {
returnVal = input.slice(lastPos, i);
returnVal = input.substr(lastPos, i - lastPos);
if (returnVal) {
parseGroups.push(returnVal);
}
@@ -237,8 +211,9 @@ export default () => {
}
returnVal = parseGroups;
skipWhitespace(i - startPos);
loop = false
} else {
loop = false;
}
else {
if (inComment) {
if (nextChar === '*' &&
input.charAt(i + 1) === '/') {
@@ -253,7 +228,7 @@ export default () => {
case '\\':
i++;
nextChar = input.charAt(i);
parseGroups.push(input.slice(lastPos, i + 1));
parseGroups.push(input.substr(lastPos, i - lastPos + 1));
lastPos = i + 1;
break;
case '/':
@@ -267,7 +242,7 @@ export default () => {
case '"':
quote = parserInput.$quoted(i);
if (quote) {
parseGroups.push(input.slice(lastPos, i), quote);
parseGroups.push(input.substr(lastPos, i - lastPos), quote);
i += quote[1].length - 1;
lastPos = i + 1;
}
@@ -292,10 +267,11 @@ export default () => {
case '}':
case ')':
case ']': {
const expected = blockStack.pop();
var expected = blockStack.pop();
if (nextChar === expected) {
blockDepth--;
} else {
}
else {
// move the parser to the error and return expected
skipWhitespace(i - startPos);
returnVal = expected;
@@ -309,72 +285,75 @@ export default () => {
}
}
} while (loop);
return returnVal ? returnVal : null;
}
};
parserInput.autoCommentAbsorb = true;
parserInput.commentStore = [];
parserInput.finished = false;
// Same as $(), but don't change the state of the parser,
// just return the match.
parserInput.peek = tok => {
parserInput.peek = function (tok) {
if (typeof tok === 'string') {
// https://jsperf.com/string-startswith/21
for (let i = 0; i < tok.length; i++) {
for (var i = 0; i < tok.length; i++) {
if (input.charAt(parserInput.i + i) !== tok.charAt(i)) {
return false;
}
}
return true;
} else {
}
else {
return tok.test(current);
}
};
// Specialization of peek()
// TODO remove or change some currentChar calls to peekChar
parserInput.peekChar = tok => input.charAt(parserInput.i) === tok;
parserInput.currentChar = () => input.charAt(parserInput.i);
parserInput.prevChar = () => input.charAt(parserInput.i - 1);
parserInput.getInput = () => input;
parserInput.peekNotNumeric = () => {
const c = input.charCodeAt(parserInput.i);
parserInput.peekChar = function (tok) { return input.charAt(parserInput.i) === tok; };
parserInput.currentChar = function () { return input.charAt(parserInput.i); };
parserInput.prevChar = function () { return input.charAt(parserInput.i - 1); };
parserInput.getInput = function () { return input; };
parserInput.peekNotNumeric = function () {
var c = input.charCodeAt(parserInput.i);
// Is the first char of the dimension 0-9, '.', '+' or '-'
return (c > CHARCODE_9 || c < CHARCODE_PLUS) || c === CHARCODE_FORWARD_SLASH || c === CHARCODE_COMMA;
};
parserInput.start = (str) => {
parserInput.start = function (str, chunkInput, failFunction) {
input = str;
parserInput.i = j = currentPos = furthest = 0;
chunks = [str];
// chunking apparently makes things quicker (but my tests indicate
// it might actually make things slower in node at least)
// and it is a non-perfect parse - it can't recognise
// unquoted urls, meaning it can't distinguish comments
// meaning comments with quotes or {}() in them get 'counted'
// and then lead to parse errors.
// In addition if the chunking chunks in the wrong place we might
// not be able to parse a parser statement in one go
// this is officially deprecated but can be switched on via an option
// in the case it causes too much performance issues.
if (chunkInput) {
chunks = (0, chunker_1.default)(str, failFunction);
}
else {
chunks = [str];
}
current = chunks[0];
skipWhitespace(0);
};
parserInput.end = () => {
let message;
const isFinished = parserInput.i >= input.length;
parserInput.end = function () {
var message;
var isFinished = parserInput.i >= input.length;
if (parserInput.i < furthest) {
message = furthestPossibleErrorMessage;
parserInput.i = furthest;
}
return {
isFinished,
isFinished: isFinished,
furthest: parserInput.i,
furthestPossibleErrorMessage: message,
furthestReachedEnd: parserInput.i >= input.length - 1,
furthestChar: input[parserInput.i]
};
};
return parserInput;
};
});
//# sourceMappingURL=parser-input.js.map
+672 -866
View File
File diff suppressed because it is too large Load Diff
+46 -57
View File
@@ -1,8 +1,10 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
/**
* Plugin Manager
*/
class PluginManager {
constructor(less) {
var PluginManager = /** @class */ (function () {
function PluginManager(less) {
this.less = less;
this.visitors = [];
this.preProcessors = [];
@@ -13,25 +15,23 @@ class PluginManager {
this.pluginCache = {};
this.Loader = new less.PluginLoader(less);
}
/**
* Adds all the plugins in the array
* @param {Array} plugins
*/
addPlugins(plugins) {
PluginManager.prototype.addPlugins = function (plugins) {
if (plugins) {
for (let i = 0; i < plugins.length; i++) {
for (var i = 0; i < plugins.length; i++) {
this.addPlugin(plugins[i]);
}
}
}
};
/**
*
* @param plugin
* @param {String} filename
*/
addPlugin(plugin, filename, functionRegistry) {
PluginManager.prototype.addPlugin = function (plugin, filename, functionRegistry) {
this.installedPlugins.push(plugin);
if (filename) {
this.pluginCache[filename] = plugin;
@@ -39,130 +39,119 @@ class PluginManager {
if (plugin.install) {
plugin.install(this.less, this, functionRegistry || this.less.functions.functionRegistry);
}
}
};
/**
*
* @param filename
*/
get(filename) {
PluginManager.prototype.get = function (filename) {
return this.pluginCache[filename];
}
};
/**
* Adds a visitor. The visitor object has options on itself to determine
* when it should run.
* @param visitor
*/
addVisitor(visitor) {
PluginManager.prototype.addVisitor = function (visitor) {
this.visitors.push(visitor);
}
};
/**
* Adds a pre processor object
* @param {object} preProcessor
* @param {number} priority - guidelines 1 = before import, 1000 = import, 2000 = after import
*/
addPreProcessor(preProcessor, priority) {
let indexToInsertAt;
PluginManager.prototype.addPreProcessor = function (preProcessor, priority) {
var indexToInsertAt;
for (indexToInsertAt = 0; indexToInsertAt < this.preProcessors.length; indexToInsertAt++) {
if (this.preProcessors[indexToInsertAt].priority >= priority) {
break;
}
}
this.preProcessors.splice(indexToInsertAt, 0, {preProcessor, priority});
}
this.preProcessors.splice(indexToInsertAt, 0, { preProcessor: preProcessor, priority: priority });
};
/**
* Adds a post processor object
* @param {object} postProcessor
* @param {number} priority - guidelines 1 = before compression, 1000 = compression, 2000 = after compression
*/
addPostProcessor(postProcessor, priority) {
let indexToInsertAt;
PluginManager.prototype.addPostProcessor = function (postProcessor, priority) {
var indexToInsertAt;
for (indexToInsertAt = 0; indexToInsertAt < this.postProcessors.length; indexToInsertAt++) {
if (this.postProcessors[indexToInsertAt].priority >= priority) {
break;
}
}
this.postProcessors.splice(indexToInsertAt, 0, {postProcessor, priority});
}
this.postProcessors.splice(indexToInsertAt, 0, { postProcessor: postProcessor, priority: priority });
};
/**
*
* @param manager
*/
addFileManager(manager) {
PluginManager.prototype.addFileManager = function (manager) {
this.fileManagers.push(manager);
}
};
/**
*
* @returns {Array}
* @private
*/
getPreProcessors() {
const preProcessors = [];
for (let i = 0; i < this.preProcessors.length; i++) {
PluginManager.prototype.getPreProcessors = function () {
var preProcessors = [];
for (var i = 0; i < this.preProcessors.length; i++) {
preProcessors.push(this.preProcessors[i].preProcessor);
}
return preProcessors;
}
};
/**
*
* @returns {Array}
* @private
*/
getPostProcessors() {
const postProcessors = [];
for (let i = 0; i < this.postProcessors.length; i++) {
PluginManager.prototype.getPostProcessors = function () {
var postProcessors = [];
for (var i = 0; i < this.postProcessors.length; i++) {
postProcessors.push(this.postProcessors[i].postProcessor);
}
return postProcessors;
}
};
/**
*
* @returns {Array}
* @private
*/
getVisitors() {
PluginManager.prototype.getVisitors = function () {
return this.visitors;
}
visitor() {
const self = this;
};
PluginManager.prototype.visitor = function () {
var self = this;
return {
first: function() {
first: function () {
self.iterator = -1;
return self.visitors[self.iterator];
},
get: function() {
get: function () {
self.iterator += 1;
return self.visitors[self.iterator];
}
};
}
};
/**
*
* @returns {Array}
* @private
*/
getFileManagers() {
PluginManager.prototype.getFileManagers = function () {
return this.fileManagers;
}
}
let pm;
const PluginManagerFactory = function(less, newFactory) {
};
return PluginManager;
}());
var pm;
var PluginManagerFactory = function (less, newFactory) {
if (newFactory || !pm) {
pm = new PluginManager(less);
}
return pm;
};
//
export default PluginManagerFactory;
exports.default = PluginManagerFactory;
//# sourceMappingURL=plugin-manager.js.map
+23 -17
View File
@@ -1,7 +1,9 @@
import * as utils from './utils.js';
export default function(environment, ParseTree) {
const render = function (input, options, callback) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var tslib_1 = require("tslib");
var utils = tslib_1.__importStar(require("./utils"));
function default_1(environment, ParseTree) {
var render = function (input, options, callback) {
if (typeof options === 'function') {
callback = options;
options = utils.copyOptions(this.options, {});
@@ -9,33 +11,37 @@ export default function(environment, ParseTree) {
else {
options = utils.copyOptions(this.options, options || {});
}
if (!callback) {
const self = this;
var self_1 = this;
return new Promise(function (resolve, reject) {
render.call(self, input, options, function(err, output) {
render.call(self_1, input, options, function (err, output) {
if (err) {
reject(err);
} else {
}
else {
resolve(output);
}
});
});
} else {
this.parse(input, options, function(err, root, imports, options) {
if (err) { return callback(err); }
let result;
}
else {
this.parse(input, options, function (err, root, imports, options) {
if (err) {
return callback(err);
}
var result;
try {
const parseTree = new ParseTree(root, imports);
var parseTree = new ParseTree(root, imports);
result = parseTree.toCSS(options);
}
catch (err) { return callback(err); }
catch (err) {
return callback(err);
}
callback(null, result);
});
}
};
return render;
}
exports.default = default_1;
//# sourceMappingURL=render.js.map
+43 -52
View File
@@ -1,27 +1,26 @@
export default function (SourceMapOutput, environment) {
class SourceMapBuilder {
constructor(options) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
function default_1(SourceMapOutput, environment) {
var SourceMapBuilder = /** @class */ (function () {
function SourceMapBuilder(options) {
this.options = options;
}
toCSS(rootNode, options, imports) {
const sourceMapOutput = new SourceMapOutput(
{
contentsIgnoredCharsMap: imports.contentsIgnoredChars,
rootNode,
contentsMap: imports.contents,
sourceMapFilename: this.options.sourceMapFilename,
sourceMapURL: this.options.sourceMapURL,
outputFilename: this.options.sourceMapOutputFilename,
sourceMapBasepath: this.options.sourceMapBasepath,
sourceMapRootpath: this.options.sourceMapRootpath,
outputSourceFiles: this.options.outputSourceFiles,
sourceMapGenerator: this.options.sourceMapGenerator,
sourceMapFileInline: this.options.sourceMapFileInline,
disableSourcemapAnnotation: this.options.disableSourcemapAnnotation
});
const css = sourceMapOutput.toCSS(options);
SourceMapBuilder.prototype.toCSS = function (rootNode, options, imports) {
var sourceMapOutput = new SourceMapOutput({
contentsIgnoredCharsMap: imports.contentsIgnoredChars,
rootNode: rootNode,
contentsMap: imports.contents,
sourceMapFilename: this.options.sourceMapFilename,
sourceMapURL: this.options.sourceMapURL,
outputFilename: this.options.sourceMapOutputFilename,
sourceMapBasepath: this.options.sourceMapBasepath,
sourceMapRootpath: this.options.sourceMapRootpath,
outputSourceFiles: this.options.outputSourceFiles,
sourceMapGenerator: this.options.sourceMapGenerator,
sourceMapFileInline: this.options.sourceMapFileInline,
disableSourcemapAnnotation: this.options.disableSourcemapAnnotation
});
var css = sourceMapOutput.toCSS(options);
this.sourceMap = sourceMapOutput.sourceMap;
this.sourceMapURL = sourceMapOutput.sourceMapURL;
if (this.options.sourceMapInputFilename) {
@@ -31,52 +30,44 @@ export default function (SourceMapOutput, environment) {
this.sourceMapURL = sourceMapOutput.removeBasepath(this.sourceMapURL);
}
return css + this.getCSSAppendage();
}
getCSSAppendage() {
let sourceMapURL = this.sourceMapURL;
};
SourceMapBuilder.prototype.getCSSAppendage = function () {
var sourceMapURL = this.sourceMapURL;
if (this.options.sourceMapFileInline) {
if (this.sourceMap === undefined) {
return '';
}
sourceMapURL = `data:application/json;base64,${environment.encodeBase64(this.sourceMap)}`;
sourceMapURL = "data:application/json;base64,".concat(environment.encodeBase64(this.sourceMap));
}
if (this.options.disableSourcemapAnnotation) {
return '';
}
if (sourceMapURL) {
return `/*# sourceMappingURL=${sourceMapURL} */`;
return "/*# sourceMappingURL=".concat(sourceMapURL, " */");
}
return '';
}
getExternalSourceMap() {
};
SourceMapBuilder.prototype.getExternalSourceMap = function () {
return this.sourceMap;
}
setExternalSourceMap(sourceMap) {
};
SourceMapBuilder.prototype.setExternalSourceMap = function (sourceMap) {
this.sourceMap = sourceMap;
}
isInline() {
};
SourceMapBuilder.prototype.isInline = function () {
return this.options.sourceMapFileInline;
}
getSourceMapURL() {
};
SourceMapBuilder.prototype.getSourceMapURL = function () {
return this.sourceMapURL;
}
getOutputFilename() {
};
SourceMapBuilder.prototype.getOutputFilename = function () {
return this.options.sourceMapOutputFilename;
}
getInputFilename() {
};
SourceMapBuilder.prototype.getInputFilename = function () {
return this.sourceMapInputFilename;
}
}
};
return SourceMapBuilder;
}());
return SourceMapBuilder;
}
exports.default = default_1;
//# sourceMappingURL=source-map-builder.js.map
+44 -57
View File
@@ -1,6 +1,8 @@
export default function (environment) {
class SourceMapOutput {
constructor(options) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
function default_1(environment) {
var SourceMapOutput = /** @class */ (function () {
function SourceMapOutput(options) {
this._css = [];
this._rootNode = options.rootNode;
this._contentsMap = options.contentsMap;
@@ -8,7 +10,7 @@ export default function (environment) {
if (options.sourceMapFilename) {
this._sourceMapFilename = options.sourceMapFilename.replace(/\\/g, '/');
}
this._outputFilename = options.outputFilename ? options.outputFilename.replace(/\\/g, '/') : options.outputFilename;
this._outputFilename = options.outputFilename;
this.sourceMapURL = options.sourceMapURL;
if (options.sourceMapBasepath) {
this._sourceMapBasepath = options.sourceMapBasepath.replace(/\\/g, '/');
@@ -18,55 +20,48 @@ export default function (environment) {
if (this._sourceMapRootpath.charAt(this._sourceMapRootpath.length - 1) !== '/') {
this._sourceMapRootpath += '/';
}
} else {
}
else {
this._sourceMapRootpath = '';
}
this._outputSourceFiles = options.outputSourceFiles;
this._sourceMapGeneratorConstructor = environment.getSourceMapGenerator();
this._lineNumber = 0;
this._column = 0;
}
removeBasepath(path) {
SourceMapOutput.prototype.removeBasepath = function (path) {
if (this._sourceMapBasepath && path.indexOf(this._sourceMapBasepath) === 0) {
path = path.substring(this._sourceMapBasepath.length);
if (path.charAt(0) === '\\' || path.charAt(0) === '/') {
path = path.substring(1);
}
}
return path;
}
normalizeFilename(filename) {
};
SourceMapOutput.prototype.normalizeFilename = function (filename) {
filename = filename.replace(/\\/g, '/');
filename = this.removeBasepath(filename);
return (this._sourceMapRootpath || '') + filename;
}
add(chunk, fileInfo, index, mapLines) {
};
SourceMapOutput.prototype.add = function (chunk, fileInfo, index, mapLines) {
// ignore adding empty strings
if (!chunk) {
return;
}
let lines, sourceLines, columns, sourceColumns, i;
var lines, sourceLines, columns, sourceColumns, i;
if (fileInfo && fileInfo.filename) {
let inputSource = this._contentsMap[fileInfo.filename];
var inputSource = this._contentsMap[fileInfo.filename];
// remove vars/banner added to the top of the file
if (this._contentsIgnoredCharsMap[fileInfo.filename]) {
// adjust the index
index -= this._contentsIgnoredCharsMap[fileInfo.filename];
if (index < 0) { index = 0; }
if (index < 0) {
index = 0;
}
// adjust the source
inputSource = inputSource.slice(this._contentsIgnoredCharsMap[fileInfo.filename]);
}
/**
/**
* ignore empty content, or failsafe
* if contents map is incorrect
*/
@@ -74,51 +69,45 @@ export default function (environment) {
this._css.push(chunk);
return;
}
inputSource = inputSource.substring(0, index);
sourceLines = inputSource.split('\n');
sourceColumns = sourceLines[sourceLines.length - 1];
}
lines = chunk.split('\n');
columns = lines[lines.length - 1];
if (fileInfo && fileInfo.filename) {
if (!mapLines) {
this._sourceMapGenerator.addMapping({ generated: { line: this._lineNumber + 1, column: this._column},
original: { line: sourceLines.length, column: sourceColumns.length},
source: this.normalizeFilename(fileInfo.filename)});
} else {
this._sourceMapGenerator.addMapping({ generated: { line: this._lineNumber + 1, column: this._column },
original: { line: sourceLines.length, column: sourceColumns.length },
source: this.normalizeFilename(fileInfo.filename) });
}
else {
for (i = 0; i < lines.length; i++) {
this._sourceMapGenerator.addMapping({ generated: { line: this._lineNumber + i + 1, column: i === 0 ? this._column : 0},
original: { line: sourceLines.length + i, column: i === 0 ? sourceColumns.length : 0},
source: this.normalizeFilename(fileInfo.filename)});
this._sourceMapGenerator.addMapping({ generated: { line: this._lineNumber + i + 1, column: i === 0 ? this._column : 0 },
original: { line: sourceLines.length + i, column: i === 0 ? sourceColumns.length : 0 },
source: this.normalizeFilename(fileInfo.filename) });
}
}
}
if (lines.length === 1) {
this._column += columns.length;
} else {
}
else {
this._lineNumber += lines.length - 1;
this._column = columns.length;
}
this._css.push(chunk);
}
isEmpty() {
};
SourceMapOutput.prototype.isEmpty = function () {
return this._css.length === 0;
}
toCSS(context) {
};
SourceMapOutput.prototype.toCSS = function (context) {
this._sourceMapGenerator = new this._sourceMapGeneratorConstructor({ file: this._outputFilename, sourceRoot: null });
if (this._outputSourceFiles) {
for (const filename in this._contentsMap) {
for (var filename in this._contentsMap) {
// eslint-disable-next-line no-prototype-builtins
if (this._contentsMap.hasOwnProperty(filename)) {
let source = this._contentsMap[filename];
var source = this._contentsMap[filename];
if (this._contentsIgnoredCharsMap[filename]) {
source = source.slice(this._contentsIgnoredCharsMap[filename]);
}
@@ -126,26 +115,24 @@ export default function (environment) {
}
}
}
this._rootNode.genCSS(context, this);
if (this._css.length > 0) {
let sourceMapURL;
const sourceMapContent = JSON.stringify(this._sourceMapGenerator.toJSON());
var sourceMapURL = void 0;
var sourceMapContent = JSON.stringify(this._sourceMapGenerator.toJSON());
if (this.sourceMapURL) {
sourceMapURL = this.sourceMapURL;
} else if (this._sourceMapFilename) {
}
else if (this._sourceMapFilename) {
sourceMapURL = this._sourceMapFilename;
}
this.sourceMapURL = sourceMapURL;
this.sourceMap = sourceMapContent;
}
return this._css.join('');
}
}
};
return SourceMapOutput;
}());
return SourceMapOutput;
}
exports.default = default_1;
//# sourceMappingURL=source-map-output.js.map
+30 -40
View File
@@ -1,18 +1,14 @@
import contexts from './contexts.js';
import visitor from './visitors/index.js';
import tree from './tree/index.js';
/**
* @param {import('./tree/node.js').default} root
* @param {{ variables?: Record<string, *>, compress?: boolean, pluginManager?: *, frames?: *[] }} options
* @returns {import('./tree/node.js').default}
*/
export default function(root, options) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var tslib_1 = require("tslib");
var contexts_1 = tslib_1.__importDefault(require("./contexts"));
var visitors_1 = tslib_1.__importDefault(require("./visitors"));
var tree_1 = tslib_1.__importDefault(require("./tree"));
function default_1(root, options) {
options = options || {};
let evaldRoot;
let variables = options.variables;
const evalEnv = new contexts.Eval(options);
var evaldRoot;
var variables = options.variables;
var evalEnv = new contexts_1.default.Eval(options);
//
// Allows setting variables with a hash, so:
//
@@ -28,38 +24,34 @@ export default function(root, options) {
//
if (typeof variables === 'object' && !Array.isArray(variables)) {
variables = Object.keys(variables).map(function (k) {
let value = variables[k];
if (!(value instanceof tree.Value)) {
if (!(value instanceof tree.Expression)) {
value = new tree.Expression([value]);
var value = variables[k];
if (!(value instanceof tree_1.default.Value)) {
if (!(value instanceof tree_1.default.Expression)) {
value = new tree_1.default.Expression([value]);
}
value = new tree.Value([value]);
value = new tree_1.default.Value([value]);
}
return new tree.Declaration(`@${k}`, value, false, null, 0);
return new tree_1.default.Declaration("@".concat(k), value, false, null, 0);
});
evalEnv.frames = [new tree.Ruleset(null, variables)];
evalEnv.frames = [new tree_1.default.Ruleset(null, variables)];
}
const visitors = [
new visitor.JoinSelectorVisitor(),
new visitor.MarkVisibleSelectorsVisitor(true),
new visitor.ExtendVisitor(),
new visitor.ToCSSVisitor({compress: Boolean(options.compress)})
var visitors = [
new visitors_1.default.JoinSelectorVisitor(),
new visitors_1.default.MarkVisibleSelectorsVisitor(true),
new visitors_1.default.ExtendVisitor(),
new visitors_1.default.ToCSSVisitor({ compress: Boolean(options.compress) })
];
const preEvalVisitors = [];
let v;
let visitorIterator;
var preEvalVisitors = [];
var v;
var visitorIterator;
/**
* first() / get() allows visitors to be added while visiting
*
*
* @todo Add scoping for visitors just like functions for @plugin; right now they're global
*/
if (options.pluginManager) {
visitorIterator = options.pluginManager.visitor();
for (let i = 0; i < 2; i++) {
for (var i = 0; i < 2; i++) {
visitorIterator.first();
while ((v = visitorIterator.get())) {
if (v.isPreEvalVisitor) {
@@ -81,13 +73,10 @@ export default function(root, options) {
}
}
}
evaldRoot = root.eval(evalEnv);
for (let i = 0; i < visitors.length; i++) {
for (var i = 0; i < visitors.length; i++) {
visitors[i].run(evaldRoot);
}
// Run any remaining visitors added after eval pass
if (options.pluginManager) {
visitorIterator.first();
@@ -97,6 +86,7 @@ export default function(root, options) {
}
}
}
return evaldRoot;
}
exports.default = default_1;
//# sourceMappingURL=transform-tree.js.map
+28 -52
View File
@@ -1,57 +1,33 @@
// @ts-check
/** @import { EvalContext, CSSOutput, FileInfo, VisibilityInfo } from './node.js' */
import Node from './node.js';
class Anonymous extends Node {
get type() { return 'Anonymous'; }
/**
* @param {string | null} value
* @param {number} [index]
* @param {FileInfo} [currentFileInfo]
* @param {boolean} [mapLines]
* @param {boolean} [rulesetLike]
* @param {VisibilityInfo} [visibilityInfo]
*/
constructor(value, index, currentFileInfo, mapLines, rulesetLike, visibilityInfo) {
super();
this.value = value;
this._index = index;
this._fileInfo = currentFileInfo;
this.mapLines = mapLines;
this.rulesetLike = (typeof rulesetLike === 'undefined') ? false : rulesetLike;
this.allowRoot = true;
this.copyVisibilityInfo(visibilityInfo);
}
/** @returns {Anonymous} */
eval() {
return new Anonymous(/** @type {string | null} */ (this.value), this._index, this._fileInfo, this.mapLines, this.rulesetLike, this.visibilityInfo());
}
/**
* @param {Node} other
* @returns {number | undefined}
*/
compare(other) {
return other.toCSS && this.toCSS(/** @type {EvalContext} */ ({})) === other.toCSS(/** @type {EvalContext} */ ({})) ? 0 : undefined;
}
/** @returns {boolean} */
isRulesetLike() {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var tslib_1 = require("tslib");
var node_1 = tslib_1.__importDefault(require("./node"));
var Anonymous = function (value, index, currentFileInfo, mapLines, rulesetLike, visibilityInfo) {
this.value = value;
this._index = index;
this._fileInfo = currentFileInfo;
this.mapLines = mapLines;
this.rulesetLike = (typeof rulesetLike === 'undefined') ? false : rulesetLike;
this.allowRoot = true;
this.copyVisibilityInfo(visibilityInfo);
};
Anonymous.prototype = Object.assign(new node_1.default(), {
type: 'Anonymous',
eval: function () {
return new Anonymous(this.value, this._index, this._fileInfo, this.mapLines, this.rulesetLike, this.visibilityInfo());
},
compare: function (other) {
return other.toCSS && this.toCSS() === other.toCSS() ? 0 : undefined;
},
isRulesetLike: function () {
return this.rulesetLike;
}
/**
* @param {EvalContext} context
* @param {CSSOutput} output
*/
genCSS(context, output) {
},
genCSS: function (context, output) {
this.nodeVisible = Boolean(this.value);
if (this.nodeVisible) {
output.add(/** @type {string} */ (this.value), this._fileInfo, this._index, this.mapLines);
output.add(this.value, this._fileInfo, this._index, this.mapLines);
}
}
}
export default Anonymous;
});
exports.default = Anonymous;
//# sourceMappingURL=anonymous.js.map
+27 -44
View File
@@ -1,48 +1,31 @@
// @ts-check
/** @import { EvalContext, CSSOutput, TreeVisitor } from './node.js' */
import Node from './node.js';
class Assignment extends Node {
get type() { return 'Assignment'; }
/**
* @param {string} key
* @param {Node} val
*/
constructor(key, val) {
super();
this.key = key;
this.value = val;
}
/** @param {TreeVisitor} visitor */
accept(visitor) {
this.value = visitor.visit(/** @type {Node} */ (this.value));
}
/**
* @param {EvalContext} context
* @returns {Assignment}
*/
eval(context) {
if (/** @type {Node} */ (this.value).eval) {
return new Assignment(this.key, /** @type {Node} */ (this.value).eval(context));
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var tslib_1 = require("tslib");
var node_1 = tslib_1.__importDefault(require("./node"));
var Assignment = function (key, val) {
this.key = key;
this.value = val;
};
Assignment.prototype = Object.assign(new node_1.default(), {
type: 'Assignment',
accept: function (visitor) {
this.value = visitor.visit(this.value);
},
eval: function (context) {
if (this.value.eval) {
return new Assignment(this.key, this.value.eval(context));
}
return this;
}
/**
* @param {EvalContext} context
* @param {CSSOutput} output
*/
genCSS(context, output) {
output.add(`${this.key}=`);
if (/** @type {Node} */ (this.value).genCSS) {
/** @type {Node} */ (this.value).genCSS(context, output);
} else {
output.add(/** @type {string} */ (/** @type {unknown} */ (this.value)));
},
genCSS: function (context, output) {
output.add("".concat(this.key, "="));
if (this.value.genCSS) {
this.value.genCSS(context, output);
}
else {
output.add(this.value);
}
}
}
export default Assignment;
});
exports.default = Assignment;
//# sourceMappingURL=assignment.js.map
+6 -4
View File
@@ -1,8 +1,10 @@
// @ts-check
export const MediaSyntaxOptions = {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ContainerSyntaxOptions = exports.MediaSyntaxOptions = void 0;
exports.MediaSyntaxOptions = {
queryInParens: true
};
export const ContainerSyntaxOptions = {
exports.ContainerSyntaxOptions = {
queryInParens: true
};
//# sourceMappingURL=atrule-syntax.js.map
+141 -248
View File
@@ -1,188 +1,111 @@
// @ts-check
/** @import { EvalContext, CSSOutput, TreeVisitor, FileInfo, VisibilityInfo } from './node.js' */
/** @import { FunctionRegistry } from './nested-at-rule.js' */
import Node from './node.js';
import Selector from './selector.js';
import Ruleset from './ruleset.js';
import Anonymous from './anonymous.js';
import NestableAtRulePrototype from './nested-at-rule.js';
import mergeRules from './merge-rules.js';
/**
* @typedef {Node & {
* rules?: Node[],
* selectors?: Selector[],
* root?: boolean,
* allowImports?: boolean,
* functionRegistry?: FunctionRegistry,
* merge?: boolean,
* debugInfo?: { lineNumber: number, fileName: string },
* elements?: import('./element.js').default[]
* }} RulesetLikeNode
*/
class AtRule extends Node {
get type() { return 'AtRule'; }
/**
* @param {string} [name]
* @param {Node | string} [value]
* @param {Node[] | Ruleset} [rules]
* @param {number} [index]
* @param {FileInfo} [currentFileInfo]
* @param {{ lineNumber: number, fileName: string }} [debugInfo]
* @param {boolean} [isRooted]
* @param {VisibilityInfo} [visibilityInfo]
*/
constructor(
name,
value,
rules,
index,
currentFileInfo,
debugInfo,
isRooted,
visibilityInfo
) {
super();
let i;
var selectors = (new Selector([], null, null, index, currentFileInfo)).createEmptySelectors();
/** @type {string | undefined} */
this.name = name;
this.value = (value instanceof Node) ? value : (value ? new Anonymous(value) : value);
/** @type {boolean | undefined} */
this.simpleBlock = undefined;
/** @type {RulesetLikeNode[] | undefined} */
this.declarations = undefined;
/** @type {RulesetLikeNode[] | undefined} */
this.rules = undefined;
if (rules) {
if (Array.isArray(rules)) {
const allDeclarations = this.declarationsBlock(rules);
let allRulesetDeclarations = true;
rules.forEach(rule => {
if (rule.type === 'Ruleset' && /** @type {RulesetLikeNode} */ (rule).rules) allRulesetDeclarations = allRulesetDeclarations && this.declarationsBlock(/** @type {Node[]} */ (/** @type {RulesetLikeNode} */ (rule).rules), true);
});
if (allDeclarations && !isRooted) {
this.simpleBlock = true;
this.declarations = rules;
} else if (allRulesetDeclarations && rules.length === 1 && !isRooted && !value) {
this.simpleBlock = true;
this.declarations = /** @type {RulesetLikeNode} */ (rules[0]).rules ? /** @type {RulesetLikeNode} */ (rules[0]).rules : rules;
} else {
this.rules = rules;
}
} else {
const allDeclarations = this.declarationsBlock(/** @type {Node[]} */ (rules.rules));
if (allDeclarations && !isRooted && !value) {
this.simpleBlock = true;
this.declarations = rules.rules;
} else {
this.rules = [rules];
/** @type {RulesetLikeNode} */ (this.rules[0]).selectors = (new Selector([], null, null, index, currentFileInfo)).createEmptySelectors();
}
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var tslib_1 = require("tslib");
var node_1 = tslib_1.__importDefault(require("./node"));
var selector_1 = tslib_1.__importDefault(require("./selector"));
var ruleset_1 = tslib_1.__importDefault(require("./ruleset"));
var anonymous_1 = tslib_1.__importDefault(require("./anonymous"));
var nested_at_rule_1 = tslib_1.__importDefault(require("./nested-at-rule"));
var AtRule = function (name, value, rules, index, currentFileInfo, debugInfo, isRooted, visibilityInfo) {
var _this = this;
var i;
var selectors = (new selector_1.default([], null, null, this._index, this._fileInfo)).createEmptySelectors();
this.name = name;
this.value = (value instanceof node_1.default) ? value : (value ? new anonymous_1.default(value) : value);
if (rules) {
if (Array.isArray(rules)) {
var allDeclarations = this.declarationsBlock(rules);
var allRulesetDeclarations_1 = true;
rules.forEach(function (rule) {
if (rule.type === 'Ruleset' && rule.rules)
allRulesetDeclarations_1 = allRulesetDeclarations_1 && _this.declarationsBlock(rule.rules, true);
});
if (allDeclarations && !isRooted) {
this.simpleBlock = true;
this.declarations = rules;
}
if (!this.simpleBlock) {
for (i = 0; i < this.rules.length; i++) {
/** @type {RulesetLikeNode} */ (this.rules[i]).allowImports = true;
}
else if (allRulesetDeclarations_1 && rules.length === 1 && !isRooted && !value) {
this.simpleBlock = true;
this.declarations = rules[0].rules ? rules[0].rules : rules;
}
if (this.declarations) {
this.setParent(this.declarations, /** @type {Node} */ (/** @type {unknown} */ (this)));
}
if (this.rules) {
this.setParent(this.rules, /** @type {Node} */ (/** @type {unknown} */ (this)));
else {
this.rules = rules;
}
}
this._index = index;
this._fileInfo = currentFileInfo;
/** @type {{ lineNumber: number, fileName: string } | undefined} */
this.debugInfo = debugInfo;
/** @type {boolean} */
this.isRooted = isRooted || false;
this.copyVisibilityInfo(visibilityInfo);
this.allowRoot = true;
else {
var allDeclarations = this.declarationsBlock(rules.rules);
if (allDeclarations && !isRooted && !value) {
this.simpleBlock = true;
this.declarations = rules.rules;
}
else {
this.rules = [rules];
this.rules[0].selectors = (new selector_1.default([], null, null, index, currentFileInfo)).createEmptySelectors();
}
}
if (!this.simpleBlock) {
for (i = 0; i < this.rules.length; i++) {
this.rules[i].allowImports = true;
}
}
this.setParent(selectors, this);
this.setParent(this.rules, this);
}
/**
* @param {Node[]} rules
* @param {boolean} [mergeable]
* @returns {boolean}
*/
declarationsBlock(rules, mergeable = false) {
this._index = index;
this._fileInfo = currentFileInfo;
this.debugInfo = debugInfo;
this.isRooted = isRooted || false;
this.copyVisibilityInfo(visibilityInfo);
this.allowRoot = true;
};
AtRule.prototype = Object.assign(new node_1.default(), tslib_1.__assign(tslib_1.__assign({ type: 'AtRule' }, nested_at_rule_1.default), { declarationsBlock: function (rules, mergeable) {
if (mergeable === void 0) { mergeable = false; }
if (!mergeable) {
return rules.filter(function (/** @type {Node & { merge?: boolean }} */ node) { return (node.type === 'Declaration' || node.type === 'Comment') && !node.merge}).length === rules.length;
} else {
return rules.filter(function (/** @type {Node} */ node) { return (node.type === 'Declaration' || node.type === 'Comment'); }).length === rules.length;
return rules.filter(function (node) { return (node.type === 'Declaration' || node.type === 'Comment') && !node.merge; }).length === rules.length;
}
}
/**
* @param {Node[]} rules
* @returns {boolean}
*/
keywordList(rules) {
else {
return rules.filter(function (node) { return (node.type === 'Declaration' || node.type === 'Comment'); }).length === rules.length;
}
}, keywordList: function (rules) {
if (!Array.isArray(rules)) {
return false;
} else {
return rules.filter(function (/** @type {Node} */ node) { return (node.type === 'Keyword' || node.type === 'Comment'); }).length === rules.length;
}
}
/** @param {TreeVisitor} visitor */
accept(visitor) {
const value = this.value, rules = this.rules, declarations = this.declarations;
else {
return rules.filter(function (node) { return (node.type === 'Keyword' || node.type === 'Comment'); }).length === rules.length;
}
}, accept: function (visitor) {
var value = this.value, rules = this.rules, declarations = this.declarations;
if (rules) {
this.rules = visitor.visitArray(rules);
} else if (declarations) {
}
else if (declarations) {
this.declarations = visitor.visitArray(declarations);
}
if (value) {
this.value = visitor.visit(/** @type {Node} */ (value));
this.value = visitor.visit(value);
}
}
/** @override @returns {boolean} */
isRulesetLike() {
return /** @type {boolean} */ (/** @type {unknown} */ (this.rules || !this.isCharset()));
}
isCharset() {
}, isRulesetLike: function () {
return this.rules || !this.isCharset();
}, isCharset: function () {
return '@charset' === this.name;
}
/**
* @param {EvalContext} context
* @param {CSSOutput} output
*/
genCSS(context, output) {
const value = this.value, rules = this.rules || this.declarations;
output.add(/** @type {string} */ (this.name), this.fileInfo(), this.getIndex());
}, genCSS: function (context, output) {
var value = this.value, rules = this.rules || this.declarations;
output.add(this.name, this.fileInfo(), this.getIndex());
if (value) {
output.add(' ');
/** @type {Node} */ (value).genCSS(context, output);
value.genCSS(context, output);
}
if (this.simpleBlock) {
this.outputRuleset(context, output, /** @type {Node[]} */ (this.declarations));
} else if (rules) {
this.outputRuleset(context, output, this.declarations);
}
else if (rules) {
this.outputRuleset(context, output, rules);
} else {
}
else {
output.add(';');
}
}
/**
* @param {EvalContext} context
* @returns {Node}
*/
eval(context) {
let mediaPathBackup, mediaBlocksBackup, value = this.value, rules = this.rules || this.declarations;
}, eval: function (context) {
var mediaPathBackup, mediaBlocksBackup, value = this.value, rules = this.rules || this.declarations;
// media stored inside other atrule should not bubble over it
// backpup media bubbling information
mediaPathBackup = context.mediaPath;
@@ -190,120 +113,96 @@ class AtRule extends Node {
// deleted media bubbling information
context.mediaPath = [];
context.mediaBlocks = [];
if (value) {
value = /** @type {Node} */ (value).eval(context);
value = value.eval(context);
if (value.value && this.keywordList(value.value)) {
value = new anonymous_1.default(value.value.map(function (keyword) { return keyword.value; }).join(', '), this.getIndex(), this.fileInfo());
}
}
if (rules) {
rules = this.evalRoot(context, rules);
}
if (Array.isArray(rules) && /** @type {RulesetLikeNode} */ (rules[0]).rules && Array.isArray(/** @type {RulesetLikeNode} */ (rules[0]).rules) && /** @type {Node[]} */ (/** @type {RulesetLikeNode} */ (rules[0]).rules).length) {
const allMergeableDeclarations = this.declarationsBlock(/** @type {Node[]} */ (/** @type {RulesetLikeNode} */ (rules[0]).rules), true);
if (Array.isArray(rules) && rules[0].rules && Array.isArray(rules[0].rules) && rules[0].rules.length) {
var allMergeableDeclarations = this.declarationsBlock(rules[0].rules, true);
if (allMergeableDeclarations && !this.isRooted && !value) {
mergeRules(/** @type {Node[]} */ (/** @type {RulesetLikeNode} */ (rules[0]).rules));
rules = /** @type {RulesetLikeNode[]} */ (/** @type {RulesetLikeNode} */ (rules[0]).rules);
rules.forEach(/** @param {RulesetLikeNode} rule */ rule => { rule.merge = false; });
var mergeRules = context.pluginManager.less.visitors.ToCSSVisitor.prototype._mergeRules;
mergeRules(rules[0].rules);
rules = rules[0].rules;
rules.forEach(function (rule) { return rule.merge = false; });
}
}
if (this.simpleBlock && rules) {
/** @type {RulesetLikeNode} */ (rules[0]).functionRegistry = /** @type {RulesetLikeNode} */ (context.frames[0]).functionRegistry.inherit();
rules = rules.map(function (/** @type {Node} */ rule) { return rule.eval(context); });
rules[0].functionRegistry = context.frames[0].functionRegistry.inherit();
rules = rules.map(function (rule) { return rule.eval(context); });
}
// restore media bubbling information
context.mediaPath = mediaPathBackup;
context.mediaBlocks = mediaBlocksBackup;
return /** @type {Node} */ (/** @type {unknown} */ (new AtRule(this.name, value, rules, this.getIndex(), this.fileInfo(), this.debugInfo, this.isRooted, this.visibilityInfo())));
}
/**
* @param {EvalContext} context
* @param {Node[]} rules
* @returns {Node[]}
*/
evalRoot(context, rules) {
let ampersandCount = 0;
let noAmpersandCount = 0;
let noAmpersands = true;
return new AtRule(this.name, value, rules, this.getIndex(), this.fileInfo(), this.debugInfo, this.isRooted, this.visibilityInfo());
}, evalRoot: function (context, rules) {
var ampersandCount = 0;
var noAmpersandCount = 0;
var noAmpersands = true;
var allAmpersands = false;
if (!this.simpleBlock) {
rules = [rules[0].eval(context)];
}
/** @type {Selector[]} */
let precedingSelectors = [];
var precedingSelectors = [];
if (context.frames.length > 0) {
for (let index = 0; index < context.frames.length; index++) {
const frame = /** @type {RulesetLikeNode} */ (context.frames[index]);
if (
frame.type === 'Ruleset' &&
var _loop_1 = function (index) {
var frame = context.frames[index];
if (frame.type === 'Ruleset' &&
frame.rules &&
frame.rules.length > 0
) {
frame.rules.length > 0) {
if (frame && !frame.root && frame.selectors && frame.selectors.length > 0) {
precedingSelectors = precedingSelectors.concat(frame.selectors);
}
}
if (precedingSelectors.length > 0) {
const allAmpersandElements = precedingSelectors.every(
sel => sel.elements && sel.elements.length > 0 && sel.elements.every(
/** @param {import('./element.js').default} el */
el => el.value === '&'
)
);
if (allAmpersandElements) {
var value_1 = '';
var output = { add: function (s) { value_1 += s; } };
for (var i = 0; i < precedingSelectors.length; i++) {
precedingSelectors[i].genCSS(context, output);
}
if (/^&+$/.test(value_1.replace(/\s+/g, ''))) {
noAmpersands = false;
noAmpersandCount++;
} else {
}
else {
allAmpersands = false;
ampersandCount++;
}
}
};
for (var index = 0; index < context.frames.length; index++) {
_loop_1(index);
}
}
const mixedAmpersands = ampersandCount > 0 && noAmpersandCount > 0 && !noAmpersands;
if (
(this.isRooted && ampersandCount > 0 && noAmpersandCount === 0 && noAmpersands)
|| !mixedAmpersands
) {
/** @type {RulesetLikeNode} */ (rules[0]).root = true;
var mixedAmpersands = ampersandCount > 0 && noAmpersandCount > 0 && !allAmpersands && !noAmpersands;
if ((this.isRooted && ampersandCount > 0 && noAmpersandCount === 0 && !allAmpersands && noAmpersands)
|| !mixedAmpersands) {
rules[0].root = true;
}
return rules;
}
/** @param {string} name */
variable(name) {
}, variable: function (name) {
if (this.rules) {
// assuming that there is only one rule at this point - that is how parser constructs the rule
return Ruleset.prototype.variable.call(this.rules[0], name);
return ruleset_1.default.prototype.variable.call(this.rules[0], name);
}
}
find() {
}, find: function () {
if (this.rules) {
// assuming that there is only one rule at this point - that is how parser constructs the rule
return Ruleset.prototype.find.apply(this.rules[0], arguments);
return ruleset_1.default.prototype.find.apply(this.rules[0], arguments);
}
}
rulesets() {
}, rulesets: function () {
if (this.rules) {
// assuming that there is only one rule at this point - that is how parser constructs the rule
return Ruleset.prototype.rulesets.apply(this.rules[0]);
return ruleset_1.default.prototype.rulesets.apply(this.rules[0]);
}
}
/**
* @param {EvalContext} context
* @param {CSSOutput} output
* @param {Node[]} rules
*/
outputRuleset(context, output, rules) {
const ruleCnt = rules.length;
let i;
}, outputRuleset: function (context, output, rules) {
var ruleCnt = rules.length;
var i;
context.tabLevel = (context.tabLevel | 0) + 1;
// Compressed
if (context.compress) {
output.add('{');
@@ -314,27 +213,21 @@ class AtRule extends Node {
context.tabLevel--;
return;
}
// Non-compressed
const tabSetStr = `\n${Array(context.tabLevel).join(' ')}`, tabRuleStr = `${tabSetStr} `;
var tabSetStr = "\n".concat(Array(context.tabLevel).join(' ')), tabRuleStr = "".concat(tabSetStr, " ");
if (!ruleCnt) {
output.add(` {${tabSetStr}}`);
} else {
output.add(` {${tabRuleStr}`);
output.add(" {".concat(tabSetStr, "}"));
}
else {
output.add(" {".concat(tabRuleStr));
rules[0].genCSS(context, output);
for (i = 1; i < ruleCnt; i++) {
output.add(tabRuleStr);
rules[i].genCSS(context, output);
}
output.add(`${tabSetStr}}`);
output.add("".concat(tabSetStr, "}"));
}
context.tabLevel--;
}
}
// Apply shared methods from NestableAtRulePrototype that AtRule doesn't override
const { evalFunction, evalTop, evalNested, permute, bubbleSelectors } = NestableAtRulePrototype;
Object.assign(AtRule.prototype, { evalFunction, evalTop, evalNested, permute, bubbleSelectors });
export default AtRule;
} }));
exports.default = AtRule;
//# sourceMappingURL=atrule.js.map
+24 -55
View File
@@ -1,63 +1,32 @@
// @ts-check
/** @import { EvalContext, CSSOutput } from './node.js' */
import Node from './node.js';
class Attribute extends Node {
get type() { return 'Attribute'; }
/**
* @param {string | Node} key
* @param {string} op
* @param {string | Node} value
* @param {string} cif
*/
constructor(key, op, value, cif) {
super();
this.key = key;
this.op = op;
this.value = value;
this.cif = cif;
}
/**
* @param {EvalContext} context
* @returns {Attribute}
*/
eval(context) {
return new Attribute(
/** @type {Node} */ (this.key).eval ? /** @type {Node} */ (this.key).eval(context) : /** @type {string} */ (this.key),
this.op,
(this.value && /** @type {Node} */ (this.value).eval) ? /** @type {Node} */ (this.value).eval(context) : this.value,
this.cif
);
}
/**
* @param {EvalContext} context
* @param {CSSOutput} output
*/
genCSS(context, output) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var tslib_1 = require("tslib");
var node_1 = tslib_1.__importDefault(require("./node"));
var Attribute = function (key, op, value, cif) {
this.key = key;
this.op = op;
this.value = value;
this.cif = cif;
};
Attribute.prototype = Object.assign(new node_1.default(), {
type: 'Attribute',
eval: function (context) {
return new Attribute(this.key.eval ? this.key.eval(context) : this.key, this.op, (this.value && this.value.eval) ? this.value.eval(context) : this.value, this.cif);
},
genCSS: function (context, output) {
output.add(this.toCSS(context));
}
/**
* @param {EvalContext} context
* @returns {string}
*/
toCSS(context) {
let value = /** @type {Node} */ (this.key).toCSS ? /** @type {Node} */ (this.key).toCSS(context) : /** @type {string} */ (this.key);
},
toCSS: function (context) {
var value = this.key.toCSS ? this.key.toCSS(context) : this.key;
if (this.op) {
value += this.op;
value += (/** @type {Node} */ (this.value).toCSS ? /** @type {Node} */ (this.value).toCSS(context) : /** @type {string} */ (this.value));
value += (this.value.toCSS ? this.value.toCSS(context) : this.value);
}
if (this.cif) {
value = value + ' ' + this.cif;
}
return `[${value}]`;
return "[".concat(value, "]");
}
}
export default Attribute;
});
exports.default = Attribute;
//# sourceMappingURL=attribute.js.map
+42 -70
View File
@@ -1,37 +1,26 @@
// @ts-check
/** @import { EvalContext, CSSOutput, TreeVisitor, FileInfo } from './node.js' */
import Node from './node.js';
import Anonymous from './anonymous.js';
import FunctionCaller from '../functions/function-caller.js';
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var tslib_1 = require("tslib");
var node_1 = tslib_1.__importDefault(require("./node"));
var anonymous_1 = tslib_1.__importDefault(require("./anonymous"));
var function_caller_1 = tslib_1.__importDefault(require("../functions/function-caller"));
//
// A function call node.
//
class Call extends Node {
get type() { return 'Call'; }
/**
* @param {string} name
* @param {Node[]} args
* @param {number} index
* @param {FileInfo} currentFileInfo
*/
constructor(name, args, index, currentFileInfo) {
super();
this.name = name;
this.args = args;
this.calc = name === 'calc';
this._index = index;
this._fileInfo = currentFileInfo;
}
/** @param {TreeVisitor} visitor */
accept(visitor) {
var Call = function (name, args, index, currentFileInfo) {
this.name = name;
this.args = args;
this.calc = name === 'calc';
this._index = index;
this._fileInfo = currentFileInfo;
};
Call.prototype = Object.assign(new node_1.default(), {
type: 'Call',
accept: function (visitor) {
if (this.args) {
this.args = visitor.visitArray(this.args);
}
}
},
//
// When evaluating a function call,
// we either find the function in the functionRegistry,
@@ -43,90 +32,73 @@ class Call extends Node {
// we try to pass a variable to a function, like: `saturate(@color)`.
// The function should receive the value, not the variable.
//
/**
* @param {EvalContext} context
* @returns {Node}
*/
eval(context) {
eval: function (context) {
var _this = this;
/**
* Turn off math for calc(), and switch back on for evaluating nested functions
*/
const currentMathContext = context.mathOn;
var currentMathContext = context.mathOn;
context.mathOn = !this.calc;
if (this.calc || context.inCalc) {
context.enterCalc();
}
const exitCalc = () => {
if (this.calc || context.inCalc) {
var exitCalc = function () {
if (_this.calc || context.inCalc) {
context.exitCalc();
}
context.mathOn = currentMathContext;
};
/** @type {Node | string | boolean | null | undefined} */
let result;
const funcCaller = new FunctionCaller(this.name, context, this.getIndex(), this.fileInfo());
var result;
var funcCaller = new function_caller_1.default(this.name, context, this.getIndex(), this.fileInfo());
if (funcCaller.isValid()) {
try {
result = funcCaller.call(this.args);
exitCalc();
} catch (e) {
}
catch (e) {
// eslint-disable-next-line no-prototype-builtins
if (/** @type {Record<string, unknown>} */ (e).hasOwnProperty('line') && /** @type {Record<string, unknown>} */ (e).hasOwnProperty('column')) {
if (e.hasOwnProperty('line') && e.hasOwnProperty('column')) {
throw e;
}
throw {
type: /** @type {Record<string, string>} */ (e).type || 'Runtime',
message: `Error evaluating function \`${this.name}\`${/** @type {Error} */ (e).message ? `: ${/** @type {Error} */ (e).message}` : ''}`,
type: e.type || 'Runtime',
message: "Error evaluating function `".concat(this.name, "`").concat(e.message ? ": ".concat(e.message) : ''),
index: this.getIndex(),
filename: this.fileInfo().filename,
line: /** @type {Record<string, number>} */ (e).lineNumber,
column: /** @type {Record<string, number>} */ (e).columnNumber
line: e.lineNumber,
column: e.columnNumber
};
}
}
if (result !== null && result !== undefined) {
// Results that that are not nodes are cast as Anonymous nodes
// Falsy values or booleans are returned as empty nodes
if (!(result instanceof Node)) {
if (!(result instanceof node_1.default)) {
if (!result || result === true) {
result = new Anonymous(null);
result = new anonymous_1.default(null);
}
else {
result = new Anonymous(result.toString());
result = new anonymous_1.default(result.toString());
}
}
result._index = this._index;
result._fileInfo = this._fileInfo;
return result;
}
const args = this.args.map(a => a.eval(context));
var args = this.args.map(function (a) { return a.eval(context); });
exitCalc();
return new Call(this.name, args, this.getIndex(), this.fileInfo());
}
/**
* @param {EvalContext} context
* @param {CSSOutput} output
*/
genCSS(context, output) {
output.add(`${this.name}(`, this.fileInfo(), this.getIndex());
for (let i = 0; i < this.args.length; i++) {
},
genCSS: function (context, output) {
output.add("".concat(this.name, "("), this.fileInfo(), this.getIndex());
for (var i = 0; i < this.args.length; i++) {
this.args[i].genCSS(context, output);
if (i + 1 < this.args.length) {
output.add(', ');
}
}
output.add(')');
}
}
export default Call;
});
exports.default = Call;
//# sourceMappingURL=call.js.map
+150 -199
View File
@@ -1,119 +1,94 @@
// @ts-check
import Node from './node.js';
import colors from '../data/colors.js';
/** @import { EvalContext, CSSOutput } from './node.js' */
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var tslib_1 = require("tslib");
var node_1 = tslib_1.__importDefault(require("./node"));
var colors_1 = tslib_1.__importDefault(require("../data/colors"));
//
// RGB Colors - #ff0014, #eee
//
class Color extends Node {
get type() { return 'Color'; }
/**
* @param {number[] | string} rgb
* @param {number} [a]
* @param {string} [originalForm]
*/
constructor(rgb, a, originalForm) {
super();
const self = this;
//
// The end goal here, is to parse the arguments
// into an integer triplet, such as `128, 255, 0`
//
// This facilitates operations and conversions.
//
if (Array.isArray(rgb)) {
/** @type {number[]} */
this.rgb = rgb;
} else if (rgb.length >= 6) {
/** @type {number[]} */
this.rgb = [];
/** @type {RegExpMatchArray} */ (rgb.match(/.{2}/g)).map(function (c, i) {
if (i < 3) {
self.rgb.push(parseInt(c, 16));
} else {
self.alpha = (parseInt(c, 16)) / 255;
}
});
} else {
/** @type {number[]} */
this.rgb = [];
rgb.split('').map(function (c, i) {
if (i < 3) {
self.rgb.push(parseInt(c + c, 16));
} else {
self.alpha = (parseInt(c + c, 16)) / 255;
}
});
}
/** @type {number} */
if (typeof this.alpha === 'undefined') {
this.alpha = (typeof a === 'number') ? a : 1;
}
if (typeof originalForm !== 'undefined') {
this.value = originalForm;
}
var Color = function (rgb, a, originalForm) {
var self = this;
//
// The end goal here, is to parse the arguments
// into an integer triplet, such as `128, 255, 0`
//
// This facilitates operations and conversions.
//
if (Array.isArray(rgb)) {
this.rgb = rgb;
}
luma() {
let r = this.rgb[0] / 255, g = this.rgb[1] / 255, b = this.rgb[2] / 255;
else if (rgb.length >= 6) {
this.rgb = [];
rgb.match(/.{2}/g).map(function (c, i) {
if (i < 3) {
self.rgb.push(parseInt(c, 16));
}
else {
self.alpha = (parseInt(c, 16)) / 255;
}
});
}
else {
this.rgb = [];
rgb.split('').map(function (c, i) {
if (i < 3) {
self.rgb.push(parseInt(c + c, 16));
}
else {
self.alpha = (parseInt(c + c, 16)) / 255;
}
});
}
this.alpha = this.alpha || (typeof a === 'number' ? a : 1);
if (typeof originalForm !== 'undefined') {
this.value = originalForm;
}
};
Color.prototype = Object.assign(new node_1.default(), {
type: 'Color',
luma: function () {
var r = this.rgb[0] / 255, g = this.rgb[1] / 255, b = this.rgb[2] / 255;
r = (r <= 0.03928) ? r / 12.92 : Math.pow(((r + 0.055) / 1.055), 2.4);
g = (g <= 0.03928) ? g / 12.92 : Math.pow(((g + 0.055) / 1.055), 2.4);
b = (b <= 0.03928) ? b / 12.92 : Math.pow(((b + 0.055) / 1.055), 2.4);
return 0.2126 * r + 0.7152 * g + 0.0722 * b;
}
/**
* @param {EvalContext} context
* @param {CSSOutput} output
*/
genCSS(context, output) {
},
genCSS: function (context, output) {
output.add(this.toCSS(context));
}
/**
* @param {EvalContext} context
* @param {boolean} [doNotCompress]
* @returns {string}
*/
toCSS(context, doNotCompress) {
const compress = context && context.compress && !doNotCompress;
let color;
let alpha;
/** @type {string | undefined} */
let colorFunction;
/** @type {(string | number)[]} */
let args = [];
},
toCSS: function (context, doNotCompress) {
var compress = context && context.compress && !doNotCompress;
var color;
var alpha;
var colorFunction;
var args = [];
// `value` is set if this color was originally
// converted from a named color string so we need
// to respect this and try to output named color too.
alpha = this.fround(context, this.alpha);
if (this.value) {
if (/** @type {string} */ (this.value).indexOf('rgb') === 0) {
if (this.value.indexOf('rgb') === 0) {
if (alpha < 1) {
colorFunction = 'rgba';
}
} else if (/** @type {string} */ (this.value).indexOf('hsl') === 0) {
}
else if (this.value.indexOf('hsl') === 0) {
if (alpha < 1) {
colorFunction = 'hsla';
} else {
}
else {
colorFunction = 'hsl';
}
} else {
return /** @type {string} */ (this.value);
}
} else {
else {
return this.value;
}
}
else {
if (alpha < 1) {
colorFunction = 'rgba';
}
}
switch (colorFunction) {
case 'rgba':
args = this.rgb.map(function (c) {
@@ -127,159 +102,135 @@ class Color extends Node {
color = this.toHSL();
args = [
this.fround(context, color.h),
`${this.fround(context, color.s * 100)}%`,
`${this.fround(context, color.l * 100)}%`
"".concat(this.fround(context, color.s * 100), "%"),
"".concat(this.fround(context, color.l * 100), "%")
].concat(args);
}
if (colorFunction) {
// Values are capped between `0` and `255`, rounded and zero-padded.
return `${colorFunction}(${args.join(`,${compress ? '' : ' '}`)})`;
return "".concat(colorFunction, "(").concat(args.join(",".concat(compress ? '' : ' ')), ")");
}
color = this.toRGB();
if (compress) {
const splitcolor = color.split('');
var splitcolor = color.split('');
// Convert color to short format
if (splitcolor[1] === splitcolor[2] && splitcolor[3] === splitcolor[4] && splitcolor[5] === splitcolor[6]) {
color = `#${splitcolor[1]}${splitcolor[3]}${splitcolor[5]}`;
color = "#".concat(splitcolor[1]).concat(splitcolor[3]).concat(splitcolor[5]);
}
}
return color;
}
},
//
// Operations have to be done per-channel, if not,
// channels will spill onto each other. Once we have
// our result, in the form of an integer triplet,
// we create a new Color node to hold the result.
//
/**
* @param {EvalContext} context
* @param {string} op
* @param {Color} other
*/
operate(context, op, other) {
const rgb = new Array(3);
const alpha = this.alpha * (1 - other.alpha) + other.alpha;
for (let c = 0; c < 3; c++) {
operate: function (context, op, other) {
var rgb = new Array(3);
var alpha = this.alpha * (1 - other.alpha) + other.alpha;
for (var c = 0; c < 3; c++) {
rgb[c] = this._operate(context, op, this.rgb[c], other.rgb[c]);
}
return new Color(rgb, alpha);
}
toRGB() {
},
toRGB: function () {
return toHex(this.rgb);
}
toHSL() {
const r = this.rgb[0] / 255, g = this.rgb[1] / 255, b = this.rgb[2] / 255, a = this.alpha;
const max = Math.max(r, g, b), min = Math.min(r, g, b);
/** @type {number} */
let h;
let s;
const l = (max + min) / 2;
const d = max - min;
},
toHSL: function () {
var r = this.rgb[0] / 255, g = this.rgb[1] / 255, b = this.rgb[2] / 255, a = this.alpha;
var max = Math.max(r, g, b), min = Math.min(r, g, b);
var h;
var s;
var l = (max + min) / 2;
var d = max - min;
if (max === min) {
h = s = 0;
} else {
s = l > 0.5 ? d / (2 - max - min) : d / (max + min);
switch (max) {
case r: h = (g - b) / d + (g < b ? 6 : 0); break;
case g: h = (b - r) / d + 2; break;
case b: h = (r - g) / d + 4; break;
}
/** @type {number} */ (h) /= 6;
}
return { h: /** @type {number} */ (h) * 360, s, l, a };
}
else {
s = l > 0.5 ? d / (2 - max - min) : d / (max + min);
switch (max) {
case r:
h = (g - b) / d + (g < b ? 6 : 0);
break;
case g:
h = (b - r) / d + 2;
break;
case b:
h = (r - g) / d + 4;
break;
}
h /= 6;
}
return { h: h * 360, s: s, l: l, a: a };
},
// Adapted from http://mjijackson.com/2008/02/rgb-to-hsl-and-rgb-to-hsv-color-model-conversion-algorithms-in-javascript
toHSV() {
const r = this.rgb[0] / 255, g = this.rgb[1] / 255, b = this.rgb[2] / 255, a = this.alpha;
const max = Math.max(r, g, b), min = Math.min(r, g, b);
/** @type {number} */
let h;
let s;
const v = max;
const d = max - min;
toHSV: function () {
var r = this.rgb[0] / 255, g = this.rgb[1] / 255, b = this.rgb[2] / 255, a = this.alpha;
var max = Math.max(r, g, b), min = Math.min(r, g, b);
var h;
var s;
var v = max;
var d = max - min;
if (max === 0) {
s = 0;
} else {
}
else {
s = d / max;
}
if (max === min) {
h = 0;
} else {
switch (max) {
case r: h = (g - b) / d + (g < b ? 6 : 0); break;
case g: h = (b - r) / d + 2; break;
case b: h = (r - g) / d + 4; break;
}
/** @type {number} */ (h) /= 6;
}
return { h: /** @type {number} */ (h) * 360, s, v, a };
}
toARGB() {
else {
switch (max) {
case r:
h = (g - b) / d + (g < b ? 6 : 0);
break;
case g:
h = (b - r) / d + 2;
break;
case b:
h = (r - g) / d + 4;
break;
}
h /= 6;
}
return { h: h * 360, s: s, v: v, a: a };
},
toARGB: function () {
return toHex([this.alpha * 255].concat(this.rgb));
}
/**
* @param {Node & { rgb?: number[], alpha?: number }} x
* @returns {0 | undefined}
*/
compare(x) {
},
compare: function (x) {
return (x.rgb &&
x.rgb[0] === this.rgb[0] &&
x.rgb[1] === this.rgb[1] &&
x.rgb[2] === this.rgb[2] &&
x.alpha === this.alpha) ? 0 : undefined;
x.alpha === this.alpha) ? 0 : undefined;
}
/** @param {string} keyword */
static fromKeyword(keyword) {
/** @type {Color | undefined} */
let c;
const key = keyword.toLowerCase();
// eslint-disable-next-line no-prototype-builtins
if (colors.hasOwnProperty(key)) {
c = new Color(/** @type {string} */ (colors[/** @type {keyof typeof colors} */ (key)]).slice(1));
}
else if (key === 'transparent') {
c = new Color([0, 0, 0], 0);
}
if (c) {
c.value = keyword;
return c;
}
});
Color.fromKeyword = function (keyword) {
var c;
var key = keyword.toLowerCase();
// eslint-disable-next-line no-prototype-builtins
if (colors_1.default.hasOwnProperty(key)) {
c = new Color(colors_1.default[key].slice(1));
}
}
/**
* @param {number} v
* @param {number} max
*/
else if (key === 'transparent') {
c = new Color([0, 0, 0], 0);
}
if (c) {
c.value = keyword;
return c;
}
};
function clamp(v, max) {
return Math.min(Math.max(v, 0), max);
}
/** @param {number[]} v */
function toHex(v) {
return `#${v.map(function (c) {
return "#".concat(v.map(function (c) {
c = clamp(Math.round(c), 255);
return (c < 16 ? '0' : '') + c.toString(16);
}).join('')}`;
}).join(''));
}
export default Color;
exports.default = Color;
//# sourceMappingURL=color.js.map
+21 -31
View File
@@ -1,38 +1,28 @@
// @ts-check
import Node from './node.js';
/** @import { EvalContext, CSSOutput } from './node.js' */
/** @type {Record<string, boolean>} */
const _noSpaceCombinators = {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var tslib_1 = require("tslib");
var node_1 = tslib_1.__importDefault(require("./node"));
var _noSpaceCombinators = {
'': true,
' ': true,
'|': true
};
class Combinator extends Node {
get type() { return 'Combinator'; }
/** @param {string} value */
constructor(value) {
super();
if (value === ' ') {
this.value = ' ';
this.emptyOrWhitespace = true;
} else {
this.value = value ? value.trim() : '';
this.emptyOrWhitespace = this.value === '';
}
var Combinator = function (value) {
if (value === ' ') {
this.value = ' ';
this.emptyOrWhitespace = true;
}
/**
* @param {EvalContext} context
* @param {CSSOutput} output
*/
genCSS(context, output) {
const spaceOrEmpty = (context.compress || _noSpaceCombinators[/** @type {string} */ (this.value)]) ? '' : ' ';
else {
this.value = value ? value.trim() : '';
this.emptyOrWhitespace = this.value === '';
}
};
Combinator.prototype = Object.assign(new node_1.default(), {
type: 'Combinator',
genCSS: function (context, output) {
var spaceOrEmpty = (context.compress || _noSpaceCombinators[this.value]) ? '' : ' ';
output.add(spaceOrEmpty + this.value + spaceOrEmpty);
}
}
export default Combinator;
});
exports.default = Combinator;
//# sourceMappingURL=combinator.js.map
+23 -44
View File
@@ -1,48 +1,27 @@
// @ts-check
/** @import { EvalContext, CSSOutput, FileInfo } from './node.js' */
/** @import { DebugInfoContext } from './debug-info.js' */
import Node from './node.js';
import getDebugInfo from './debug-info.js';
class Comment extends Node {
get type() { return 'Comment'; }
/**
* @param {string} value
* @param {boolean} isLineComment
* @param {number} index
* @param {FileInfo} currentFileInfo
*/
constructor(value, isLineComment, index, currentFileInfo) {
super();
this.value = value;
this.isLineComment = isLineComment;
this._index = index;
this._fileInfo = currentFileInfo;
this.allowRoot = true;
/** @type {{ lineNumber: number, fileName: string } | undefined} */
this.debugInfo = undefined;
}
/**
* @param {EvalContext} context
* @param {CSSOutput} output
*/
genCSS(context, output) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var tslib_1 = require("tslib");
var node_1 = tslib_1.__importDefault(require("./node"));
var debug_info_1 = tslib_1.__importDefault(require("./debug-info"));
var Comment = function (value, isLineComment, index, currentFileInfo) {
this.value = value;
this.isLineComment = isLineComment;
this._index = index;
this._fileInfo = currentFileInfo;
this.allowRoot = true;
};
Comment.prototype = Object.assign(new node_1.default(), {
type: 'Comment',
genCSS: function (context, output) {
if (this.debugInfo) {
output.add(getDebugInfo(context, /** @type {DebugInfoContext} */ (this)), this.fileInfo(), this.getIndex());
output.add((0, debug_info_1.default)(context, this), this.fileInfo(), this.getIndex());
}
output.add(/** @type {string} */ (this.value));
}
/**
* @param {EvalContext} context
* @returns {boolean}
*/
isSilent(context) {
const isCompressed = context.compress && /** @type {string} */ (this.value)[2] !== '!';
output.add(this.value);
},
isSilent: function (context) {
var isCompressed = context.compress && this.value[2] !== '!';
return this.isLineComment || isCompressed;
}
}
export default Comment;
});
exports.default = Comment;
//# sourceMappingURL=comment.js.map
+36 -61
View File
@@ -1,65 +1,40 @@
// @ts-check
/** @import { EvalContext, TreeVisitor } from './node.js' */
import Node from './node.js';
class Condition extends Node {
get type() { return 'Condition'; }
/**
* @param {string} op
* @param {Node} l
* @param {Node} r
* @param {number} i
* @param {boolean} negate
*/
constructor(op, l, r, i, negate) {
super();
this.op = op.trim();
this.lvalue = l;
this.rvalue = r;
this._index = i;
this.negate = negate;
}
/** @param {TreeVisitor} visitor */
accept(visitor) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var tslib_1 = require("tslib");
var node_1 = tslib_1.__importDefault(require("./node"));
var Condition = function (op, l, r, i, negate) {
this.op = op.trim();
this.lvalue = l;
this.rvalue = r;
this._index = i;
this.negate = negate;
};
Condition.prototype = Object.assign(new node_1.default(), {
type: 'Condition',
accept: function (visitor) {
this.lvalue = visitor.visit(this.lvalue);
this.rvalue = visitor.visit(this.rvalue);
}
/**
* @param {EvalContext} context
* @returns {boolean}
* @suppress {checkTypes}
*/
// @ts-ignore - Condition.eval returns boolean, not Node (used as guard condition)
eval(context) {
const a = this.lvalue.eval(context);
const b = this.rvalue.eval(context);
/** @type {boolean} */
let result;
switch (this.op) {
case 'and': result = Boolean(a && b); break;
case 'or': result = Boolean(a || b); break;
default:
switch (Node.compare(a, b)) {
case -1:
result = this.op === '<' || this.op === '=<' || this.op === '<=';
break;
case 0:
result = this.op === '=' || this.op === '>=' || this.op === '=<' || this.op === '<=';
break;
case 1:
result = this.op === '>' || this.op === '>=';
break;
default:
result = false;
}
}
},
eval: function (context) {
var result = (function (op, a, b) {
switch (op) {
case 'and': return a && b;
case 'or': return a || b;
default:
switch (node_1.default.compare(a, b)) {
case -1:
return op === '<' || op === '=<' || op === '<=';
case 0:
return op === '=' || op === '>=' || op === '=<' || op === '<=';
case 1:
return op === '>' || op === '>=';
default:
return false;
}
}
})(this.op, this.lvalue.eval(context), this.rvalue.eval(context));
return this.negate ? !result : result;
}
}
export default Condition;
});
exports.default = Condition;
//# sourceMappingURL=condition.js.map
+34 -90
View File
@@ -1,104 +1,48 @@
// @ts-check
/** @import { EvalContext, CSSOutput, FileInfo, VisibilityInfo } from './node.js' */
/** @import { FunctionRegistry, NestableAtRuleThis } from './nested-at-rule.js' */
import Node from './node.js';
import Ruleset from './ruleset.js';
import Value from './value.js';
import Selector from './selector.js';
import AtRule from './atrule.js';
import NestableAtRulePrototype from './nested-at-rule.js';
/**
* @typedef {Ruleset & {
* allowImports?: boolean,
* debugInfo?: { lineNumber: number, fileName: string },
* functionRegistry?: FunctionRegistry
* }} RulesetWithExtras
*/
class Container extends AtRule {
get type() { return 'Container'; }
/**
* @param {Node[] | null} value
* @param {Node[]} features
* @param {number} index
* @param {FileInfo} currentFileInfo
* @param {VisibilityInfo} visibilityInfo
*/
constructor(value, features, index, currentFileInfo, visibilityInfo) {
super();
this._index = index;
this._fileInfo = currentFileInfo;
const selectors = (new Selector([], null, null, this._index, this._fileInfo)).createEmptySelectors();
/** @type {Value} */
this.features = new Value(features);
/** @type {RulesetWithExtras[]} */
this.rules = [new Ruleset(selectors, value)];
this.rules[0].allowImports = true;
this.copyVisibilityInfo(visibilityInfo);
this.allowRoot = true;
this.setParent(selectors, /** @type {Node} */ (/** @type {unknown} */ (this)));
this.setParent(this.features, /** @type {Node} */ (/** @type {unknown} */ (this)));
this.setParent(this.rules, /** @type {Node} */ (/** @type {unknown} */ (this)));
/** @type {boolean | undefined} */
this._evaluated = undefined;
}
/**
* @param {EvalContext} context
* @param {CSSOutput} output
*/
genCSS(context, output) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var tslib_1 = require("tslib");
var ruleset_1 = tslib_1.__importDefault(require("./ruleset"));
var value_1 = tslib_1.__importDefault(require("./value"));
var selector_1 = tslib_1.__importDefault(require("./selector"));
var atrule_1 = tslib_1.__importDefault(require("./atrule"));
var nested_at_rule_1 = tslib_1.__importDefault(require("./nested-at-rule"));
var Container = function (value, features, index, currentFileInfo, visibilityInfo) {
this._index = index;
this._fileInfo = currentFileInfo;
var selectors = (new selector_1.default([], null, null, this._index, this._fileInfo)).createEmptySelectors();
this.features = new value_1.default(features);
this.rules = [new ruleset_1.default(selectors, value)];
this.rules[0].allowImports = true;
this.copyVisibilityInfo(visibilityInfo);
this.allowRoot = true;
this.setParent(selectors, this);
this.setParent(this.features, this);
this.setParent(this.rules, this);
};
Container.prototype = Object.assign(new atrule_1.default(), tslib_1.__assign(tslib_1.__assign({ type: 'Container' }, nested_at_rule_1.default), { genCSS: function (context, output) {
output.add('@container ', this._fileInfo, this._index);
this.features.genCSS(context, output);
this.outputRuleset(context, output, this.rules);
}
/**
* @param {EvalContext} context
* @returns {Node}
*/
eval(context) {
if (this._evaluated) {
return /** @type {Node} */ (/** @type {unknown} */ (this));
}
}, eval: function (context) {
if (!context.mediaBlocks) {
context.mediaBlocks = [];
context.mediaPath = [];
}
const media = new Container(null, [], this._index, this._fileInfo, this.visibilityInfo());
media._evaluated = true;
var media = new Container(null, [], this._index, this._fileInfo, this.visibilityInfo());
if (this.debugInfo) {
this.rules[0].debugInfo = this.debugInfo;
media.debugInfo = this.debugInfo;
}
media.features = /** @type {Value} */ (this.features.eval(context));
context.mediaPath.push(/** @type {Node} */ (/** @type {unknown} */ (media)));
context.mediaBlocks.push(/** @type {Node} */ (/** @type {unknown} */ (media)));
const fr = /** @type {RulesetWithExtras} */ (context.frames[0]).functionRegistry;
if (fr) {
this.rules[0].functionRegistry = fr.inherit();
}
media.features = this.features.eval(context);
context.mediaPath.push(media);
context.mediaBlocks.push(media);
this.rules[0].functionRegistry = context.frames[0].functionRegistry.inherit();
context.frames.unshift(this.rules[0]);
media.rules = [/** @type {RulesetWithExtras} */ (this.rules[0].eval(context))];
media.rules = [this.rules[0].eval(context)];
context.frames.shift();
context.mediaPath.pop();
return context.mediaPath.length === 0 ? /** @type {NestableAtRuleThis} */ (/** @type {unknown} */ (media)).evalTop(context) :
/** @type {NestableAtRuleThis} */ (/** @type {unknown} */ (media)).evalNested(context);
}
}
// Apply NestableAtRulePrototype methods (accept, isRulesetLike override AtRule's versions)
Object.assign(Container.prototype, NestableAtRulePrototype);
export default Container;
return context.mediaPath.length === 0 ? media.evalTop(context) :
media.evalNested(context);
} }));
exports.default = Container;
//# sourceMappingURL=container.js.map
+11 -53
View File
@@ -1,64 +1,22 @@
// @ts-check
/**
* @typedef {object} DebugInfoData
* @property {number} lineNumber
* @property {string} fileName
*/
/**
* @typedef {object} DebugInfoContext
* @property {DebugInfoData} debugInfo
*/
/**
* @deprecated The dumpLineNumbers option is deprecated. Use sourcemaps instead.
* This will be removed in a future version.
*
* @param {DebugInfoContext} ctx - Context object with debugInfo
* @returns {string} Debug info as CSS comment
*/
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
function asComment(ctx) {
return `/* line ${ctx.debugInfo.lineNumber}, ${ctx.debugInfo.fileName} */\n`;
return "/* line ".concat(ctx.debugInfo.lineNumber, ", ").concat(ctx.debugInfo.fileName, " */\n");
}
/**
* @deprecated The dumpLineNumbers option is deprecated. Use sourcemaps instead.
* This function generates Sass-compatible debug info using @media -sass-debug-info syntax.
* This format had short-lived usage and is no longer recommended.
* This will be removed in a future version.
*
* @param {DebugInfoContext} ctx - Context object with debugInfo
* @returns {string} Sass-compatible debug info as @media query
*/
function asMediaQuery(ctx) {
let filenameWithProtocol = ctx.debugInfo.fileName;
var filenameWithProtocol = ctx.debugInfo.fileName;
if (!/^[a-z]+:\/\//i.test(filenameWithProtocol)) {
filenameWithProtocol = `file://${filenameWithProtocol}`;
filenameWithProtocol = "file://".concat(filenameWithProtocol);
}
return `@media -sass-debug-info{filename{font-family:${filenameWithProtocol.replace(/([.:/\\])/g, function (a) {
return "@media -sass-debug-info{filename{font-family:".concat(filenameWithProtocol.replace(/([.:/\\])/g, function (a) {
if (a == '\\') {
a = '/';
}
return `\\${a}`;
})}}line{font-family:\\00003${ctx.debugInfo.lineNumber}}}\n`;
return "\\".concat(a);
}), "}line{font-family:\\00003").concat(ctx.debugInfo.lineNumber, "}}\n");
}
/**
* Generates debug information (line numbers) for CSS output.
*
* @param {{ dumpLineNumbers?: string, compress?: boolean }} context - Context object with dumpLineNumbers option
* @param {DebugInfoContext} ctx - Context object with debugInfo
* @param {string} [lineSeparator] - Separator between comment and media query (for 'all' mode)
* @returns {string} Debug info string
*
* @deprecated The dumpLineNumbers option is deprecated. Use sourcemaps instead.
* All modes ('comments', 'mediaquery', 'all') are deprecated and will be removed in a future version.
* The 'mediaquery' and 'all' modes generate Sass-compatible @media -sass-debug-info output
* which had short-lived usage and is no longer recommended.
*/
function debugInfo(context, ctx, lineSeparator) {
let result = '';
var result = '';
if (context.dumpLineNumbers && !context.compress) {
switch (context.dumpLineNumbers) {
case 'comments':
@@ -74,5 +32,5 @@ function debugInfo(context, ctx, lineSeparator) {
}
return result;
}
export default debugInfo;
exports.default = debugInfo;
//# sourceMappingURL=debug-info.js.map
+52 -97
View File
@@ -1,90 +1,58 @@
// @ts-check
/** @import { EvalContext, CSSOutput, FileInfo } from './node.js' */
import Node from './node.js';
import Value from './value.js';
import Keyword from './keyword.js';
import Anonymous from './anonymous.js';
import * as Constants from '../constants.js';
const MATH = Constants.Math;
/**
* @param {EvalContext} context
* @param {Node[]} name
* @returns {string}
*/
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var tslib_1 = require("tslib");
var node_1 = tslib_1.__importDefault(require("./node"));
var value_1 = tslib_1.__importDefault(require("./value"));
var keyword_1 = tslib_1.__importDefault(require("./keyword"));
var anonymous_1 = tslib_1.__importDefault(require("./anonymous"));
var Constants = tslib_1.__importStar(require("../constants"));
var MATH = Constants.Math;
function evalName(context, name) {
let value = '';
let i;
const n = name.length;
/** @type {CSSOutput} */
const output = {add: function (s) {value += s;}, isEmpty: function() { return value === ''; }};
var value = '';
var i;
var n = name.length;
var output = { add: function (s) { value += s; } };
for (i = 0; i < n; i++) {
name[i].eval(context).genCSS(context, output);
}
return value;
}
class Declaration extends Node {
get type() { return 'Declaration'; }
/**
* @param {string | Node[]} name
* @param {Node | string | null} value
* @param {string} [important]
* @param {string} [merge]
* @param {number} [index]
* @param {FileInfo} [currentFileInfo]
* @param {boolean} [inline]
* @param {boolean} [variable]
*/
constructor(name, value, important, merge, index, currentFileInfo, inline, variable) {
super();
this.name = name;
this.value = (value instanceof Node) ? value : new Value([value ? new Anonymous(value) : null]);
this.important = important ? ` ${important.trim()}` : '';
/** @type {string | undefined} */
this.merge = merge;
this._index = index;
this._fileInfo = currentFileInfo;
/** @type {boolean} */
this.inline = inline || false;
/** @type {boolean} */
this.variable = (variable !== undefined) ? variable
: (typeof name === 'string' && name.charAt(0) === '@');
/** @type {boolean} */
this.allowRoot = true;
this.setParent(this.value, this);
}
/**
* @param {EvalContext} context
* @param {CSSOutput} output
*/
genCSS(context, output) {
output.add(/** @type {string} */ (this.name) + (context.compress ? ':' : ': '), this.fileInfo(), this.getIndex());
var Declaration = function (name, value, important, merge, index, currentFileInfo, inline, variable) {
this.name = name;
this.value = (value instanceof node_1.default) ? value : new value_1.default([value ? new anonymous_1.default(value) : null]);
this.important = important ? " ".concat(important.trim()) : '';
this.merge = merge;
this._index = index;
this._fileInfo = currentFileInfo;
this.inline = inline || false;
this.variable = (variable !== undefined) ? variable
: (name.charAt && (name.charAt(0) === '@'));
this.allowRoot = true;
this.setParent(this.value, this);
};
Declaration.prototype = Object.assign(new node_1.default(), {
type: 'Declaration',
genCSS: function (context, output) {
output.add(this.name + (context.compress ? ':' : ': '), this.fileInfo(), this.getIndex());
try {
/** @type {Node} */ (this.value).genCSS(context, output);
this.value.genCSS(context, output);
}
catch (e) {
const err = /** @type {{ index?: number, filename?: string }} */ (e);
err.index = this._index;
err.filename = this._fileInfo && this._fileInfo.filename;
e.index = this._index;
e.filename = this._fileInfo.filename;
throw e;
}
output.add(this.important + ((this.inline || (context.lastRule && context.compress)) ? '' : ';'), this._fileInfo, this._index);
}
/** @param {EvalContext} context */
eval(context) {
let mathBypass = false, prevMath, name = this.name, evaldValue, variable = this.variable;
},
eval: function (context) {
var mathBypass = false, prevMath, name = this.name, evaldValue, variable = this.variable;
if (typeof name !== 'string') {
// expand 'primitive' name directly to get
// things faster (~10% for benchmark.less):
name = (/** @type {Node[]} */ (name).length === 1) && (/** @type {Node[]} */ (name)[0] instanceof Keyword) ?
/** @type {string} */ (/** @type {Node[]} */ (name)[0].value) : evalName(context, /** @type {Node[]} */ (name));
name = (name.length === 1) && (name[0] instanceof keyword_1.default) ?
name[0].value : evalName(context, name);
variable = false; // never treat expanded interpolation as new variable name
}
// @todo remove when parens-division is default
if (name === 'font' && context.math === MATH.ALWAYS) {
mathBypass = true;
@@ -93,30 +61,22 @@ class Declaration extends Node {
}
try {
context.importantScope.push({});
evaldValue = /** @type {Node} */ (this.value).eval(context);
evaldValue = this.value.eval(context);
if (!this.variable && evaldValue.type === 'DetachedRuleset') {
throw { message: 'Rulesets cannot be evaluated on a property.',
index: this.getIndex(), filename: this.fileInfo().filename };
}
let important = this.important;
const importantResult = context.importantScope.pop();
if (!important && importantResult && importantResult.important) {
var important = this.important;
var importantResult = context.importantScope.pop();
if (!important && importantResult.important) {
important = importantResult.important;
}
return new Declaration(/** @type {string} */ (name),
evaldValue,
important,
this.merge,
this.getIndex(), this.fileInfo(), this.inline,
variable);
return new Declaration(name, evaldValue, important, this.merge, this.getIndex(), this.fileInfo(), this.inline, variable);
}
catch (e) {
const err = /** @type {{ index?: number, filename?: string }} */ (e);
if (typeof err.index !== 'number') {
err.index = this.getIndex();
err.filename = this.fileInfo().filename;
if (typeof e.index !== 'number') {
e.index = this.getIndex();
e.filename = this.fileInfo().filename;
}
throw e;
}
@@ -125,15 +85,10 @@ class Declaration extends Node {
context.math = prevMath;
}
}
},
makeImportant: function () {
return new Declaration(this.name, this.value, '!important', this.merge, this.getIndex(), this.fileInfo(), this.inline);
}
makeImportant() {
return new Declaration(this.name,
/** @type {Node} */ (this.value),
'!important',
this.merge,
this.getIndex(), this.fileInfo(), this.inline);
}
}
export default Declaration;
});
exports.default = Declaration;
//# sourceMappingURL=declaration.js.map
+24 -42
View File
@@ -1,45 +1,27 @@
// @ts-check
/** @import { EvalContext, TreeVisitor } from './node.js' */
import Node from './node.js';
import contexts from '../contexts.js';
import * as utils from '../utils.js';
class DetachedRuleset extends Node {
get type() { return 'DetachedRuleset'; }
/**
* @param {Node} ruleset
* @param {Node[]} [frames]
*/
constructor(ruleset, frames) {
super();
this.ruleset = ruleset;
this.frames = frames;
this.evalFirst = true;
this.setParent(this.ruleset, this);
}
/** @param {TreeVisitor} visitor */
accept(visitor) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var tslib_1 = require("tslib");
var node_1 = tslib_1.__importDefault(require("./node"));
var contexts_1 = tslib_1.__importDefault(require("../contexts"));
var utils = tslib_1.__importStar(require("../utils"));
var DetachedRuleset = function (ruleset, frames) {
this.ruleset = ruleset;
this.frames = frames;
this.setParent(this.ruleset, this);
};
DetachedRuleset.prototype = Object.assign(new node_1.default(), {
type: 'DetachedRuleset',
evalFirst: true,
accept: function (visitor) {
this.ruleset = visitor.visit(this.ruleset);
}
/**
* @param {EvalContext} context
* @returns {DetachedRuleset}
*/
eval(context) {
const frames = this.frames || utils.copyArray(context.frames);
},
eval: function (context) {
var frames = this.frames || utils.copyArray(context.frames);
return new DetachedRuleset(this.ruleset, frames);
},
callEval: function (context) {
return this.ruleset.eval(this.frames ? new contexts_1.default.Eval(context, this.frames.concat(context.frames)) : context);
}
/**
* @param {EvalContext} context
* @returns {Node}
*/
callEval(context) {
return this.ruleset.eval(this.frames ? new contexts.Eval(context, this.frames.concat(context.frames)) : context);
}
}
export default DetachedRuleset;
});
exports.default = DetachedRuleset;
//# sourceMappingURL=detached-ruleset.js.map
+71 -127
View File
@@ -1,182 +1,131 @@
// @ts-check
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var tslib_1 = require("tslib");
/* eslint-disable no-prototype-builtins */
import Node from './node.js';
import unitConversions from '../data/unit-conversions.js';
import Unit from './unit.js';
import Color from './color.js';
/** @import { EvalContext, CSSOutput } from './node.js' */
var node_1 = tslib_1.__importDefault(require("./node"));
var unit_conversions_1 = tslib_1.__importDefault(require("../data/unit-conversions"));
var unit_1 = tslib_1.__importDefault(require("./unit"));
var color_1 = tslib_1.__importDefault(require("./color"));
//
// A number with a unit
//
class Dimension extends Node {
get type() { return 'Dimension'; }
/**
* @param {number | string} value
* @param {Unit | string} [unit]
*/
constructor(value, unit) {
super();
/** @type {number} */
this.value = parseFloat(/** @type {string} */ (value));
if (isNaN(this.value)) {
throw new Error('Dimension is not a number.');
}
/** @type {Unit} */
this.unit = (unit && unit instanceof Unit) ? unit :
new Unit(unit ? [/** @type {string} */ (unit)] : undefined);
this.setParent(this.unit, this);
var Dimension = function (value, unit) {
this.value = parseFloat(value);
if (isNaN(this.value)) {
throw new Error('Dimension is not a number.');
}
/**
* @param {import('./node.js').TreeVisitor} visitor
*/
accept(visitor) {
this.unit = /** @type {Unit} */ (visitor.visit(this.unit));
}
this.unit = (unit && unit instanceof unit_1.default) ? unit :
new unit_1.default(unit ? [unit] : undefined);
this.setParent(this.unit, this);
};
Dimension.prototype = Object.assign(new node_1.default(), {
type: 'Dimension',
accept: function (visitor) {
this.unit = visitor.visit(this.unit);
},
// remove when Nodes have JSDoc types
// eslint-disable-next-line no-unused-vars
/** @param {EvalContext} context */
eval(context) {
eval: function (context) {
return this;
}
toColor() {
const v = /** @type {number} */ (this.value);
return new Color([v, v, v]);
}
/**
* @param {EvalContext} context
* @param {CSSOutput} output
*/
genCSS(context, output) {
},
toColor: function () {
return new color_1.default([this.value, this.value, this.value]);
},
genCSS: function (context, output) {
if ((context && context.strictUnits) && !this.unit.isSingular()) {
throw new Error(`Multiple units in dimension. Correct the units or use the unit function. Bad unit: ${this.unit.toString()}`);
throw new Error("Multiple units in dimension. Correct the units or use the unit function. Bad unit: ".concat(this.unit.toString()));
}
const value = this.fround(context, /** @type {number} */ (this.value));
let strValue = String(value);
var value = this.fround(context, this.value);
var strValue = String(value);
if (value !== 0 && value < 0.000001 && value > -0.000001) {
// would be output 1e-6 etc.
strValue = value.toFixed(20).replace(/0+$/, '');
}
if (context && context.compress) {
// Zero values doesn't need a unit
if (value === 0 && this.unit.isLength()) {
output.add(strValue);
return;
}
// Float values doesn't need a leading zero
if (value > 0 && value < 1) {
strValue = (strValue).slice(1);
strValue = (strValue).substr(1);
}
}
output.add(strValue);
this.unit.genCSS(context, output);
}
},
// In an operation between two Dimensions,
// we default to the first Dimension's unit,
// so `1px + 2` will yield `3px`.
/**
* @param {EvalContext} context
* @param {string} op
* @param {Dimension} other
*/
operate(context, op, other) {
operate: function (context, op, other) {
/* jshint noempty:false */
let value = this._operate(context, op, /** @type {number} */ (this.value), /** @type {number} */ (other.value));
let unit = this.unit.clone();
var value = this._operate(context, op, this.value, other.value);
var unit = this.unit.clone();
if (op === '+' || op === '-') {
if (unit.numerator.length === 0 && unit.denominator.length === 0) {
unit = other.unit.clone();
if (this.unit.backupUnit) {
unit.backupUnit = this.unit.backupUnit;
}
} else if (other.unit.numerator.length === 0 && unit.denominator.length === 0) {
}
else if (other.unit.numerator.length === 0 && unit.denominator.length === 0) {
// do nothing
} else {
}
else {
other = other.convertTo(this.unit.usedUnits());
if (context.strictUnits && other.unit.toString() !== unit.toString()) {
throw new Error('Incompatible units. Change the units or use the unit function. '
+ `Bad units: '${unit.toString()}' and '${other.unit.toString()}'.`);
+ "Bad units: '".concat(unit.toString(), "' and '").concat(other.unit.toString(), "'."));
}
value = this._operate(context, op, /** @type {number} */ (this.value), /** @type {number} */ (other.value));
value = this._operate(context, op, this.value, other.value);
}
} else if (op === '*') {
}
else if (op === '*') {
unit.numerator = unit.numerator.concat(other.unit.numerator).sort();
unit.denominator = unit.denominator.concat(other.unit.denominator).sort();
unit.cancel();
} else if (op === '/') {
}
else if (op === '/') {
unit.numerator = unit.numerator.concat(other.unit.denominator).sort();
unit.denominator = unit.denominator.concat(other.unit.numerator).sort();
unit.cancel();
}
return new Dimension(/** @type {number} */ (value), unit);
}
/**
* @param {Node} other
* @returns {number | undefined}
*/
compare(other) {
let a, b;
return new Dimension(value, unit);
},
compare: function (other) {
var a, b;
if (!(other instanceof Dimension)) {
return undefined;
}
if (this.unit.isEmpty() || other.unit.isEmpty()) {
a = this;
b = other;
} else {
}
else {
a = this.unify();
b = other.unify();
if (a.unit.compare(b.unit) !== 0) {
return undefined;
}
}
return Node.numericCompare(/** @type {number} */ (a.value), /** @type {number} */ (b.value));
}
unify() {
return node_1.default.numericCompare(a.value, b.value);
},
unify: function () {
return this.convertTo({ length: 'px', duration: 's', angle: 'rad' });
}
/**
* @param {string | { [groupName: string]: string }} conversions
* @returns {Dimension}
*/
convertTo(conversions) {
let value = /** @type {number} */ (this.value);
const unit = this.unit.clone();
let i;
/** @type {string} */
let groupName;
/** @type {{ [unitName: string]: number }} */
let group;
/** @type {string} */
let targetUnit;
/** @type {{ [groupName: string]: string }} */
let derivedConversions = {};
/** @type {(atomicUnit: string, denominator: boolean) => string} */
let applyUnit;
},
convertTo: function (conversions) {
var value = this.value;
var unit = this.unit.clone();
var i;
var groupName;
var group;
var targetUnit;
var derivedConversions = {};
var applyUnit;
if (typeof conversions === 'string') {
for (i in unitConversions) {
if (unitConversions[/** @type {keyof typeof unitConversions} */ (i)].hasOwnProperty(conversions)) {
for (i in unit_conversions_1.default) {
if (unit_conversions_1.default[i].hasOwnProperty(conversions)) {
derivedConversions = {};
derivedConversions[i] = conversions;
}
@@ -187,29 +136,24 @@ class Dimension extends Node {
if (group.hasOwnProperty(atomicUnit)) {
if (denominator) {
value = value / (group[atomicUnit] / group[targetUnit]);
} else {
}
else {
value = value * (group[atomicUnit] / group[targetUnit]);
}
return targetUnit;
}
return atomicUnit;
};
for (groupName in conversions) {
if (conversions.hasOwnProperty(groupName)) {
targetUnit = conversions[groupName];
group = /** @type {{ [unitName: string]: number }} */ (unitConversions[/** @type {keyof typeof unitConversions} */ (groupName)]);
group = unit_conversions_1.default[groupName];
unit.map(applyUnit);
}
}
unit.cancel();
return new Dimension(value, unit);
}
}
export default Dimension;
});
exports.default = Dimension;
//# sourceMappingURL=dimension.js.map
+52 -82
View File
@@ -1,93 +1,63 @@
// @ts-check
/** @import { EvalContext, CSSOutput, TreeVisitor, FileInfo, VisibilityInfo } from './node.js' */
import Node from './node.js';
import Paren from './paren.js';
import Combinator from './combinator.js';
class Element extends Node {
get type() { return 'Element'; }
/**
* @param {Combinator | string} combinator
* @param {string | Node} value
* @param {boolean} [isVariable]
* @param {number} [index]
* @param {FileInfo} [currentFileInfo]
* @param {VisibilityInfo} [visibilityInfo]
*/
constructor(combinator, value, isVariable, index, currentFileInfo, visibilityInfo) {
super();
this.combinator = combinator instanceof Combinator ?
combinator : new Combinator(combinator);
if (typeof value === 'string') {
this.value = value.trim();
} else if (value) {
this.value = value;
} else {
this.value = '';
}
/** @type {boolean | undefined} */
this.isVariable = isVariable;
this._index = index;
this._fileInfo = currentFileInfo;
this.copyVisibilityInfo(visibilityInfo);
this.setParent(this.combinator, this);
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var tslib_1 = require("tslib");
var node_1 = tslib_1.__importDefault(require("./node"));
var paren_1 = tslib_1.__importDefault(require("./paren"));
var combinator_1 = tslib_1.__importDefault(require("./combinator"));
var Element = function (combinator, value, isVariable, index, currentFileInfo, visibilityInfo) {
this.combinator = combinator instanceof combinator_1.default ?
combinator : new combinator_1.default(combinator);
if (typeof value === 'string') {
this.value = value.trim();
}
/** @param {TreeVisitor} visitor */
accept(visitor) {
const value = this.value;
this.combinator = /** @type {Combinator} */ (visitor.visit(this.combinator));
else if (value) {
this.value = value;
}
else {
this.value = '';
}
this.isVariable = isVariable;
this._index = index;
this._fileInfo = currentFileInfo;
this.copyVisibilityInfo(visibilityInfo);
this.setParent(this.combinator, this);
};
Element.prototype = Object.assign(new node_1.default(), {
type: 'Element',
accept: function (visitor) {
var value = this.value;
this.combinator = visitor.visit(this.combinator);
if (typeof value === 'object') {
this.value = visitor.visit(/** @type {Node} */ (value));
this.value = visitor.visit(value);
}
}
/** @param {EvalContext} context */
eval(context) {
return new Element(this.combinator,
/** @type {Node} */ (this.value).eval ? /** @type {Node} */ (this.value).eval(context) : /** @type {string} */ (this.value),
this.isVariable,
this.getIndex(),
this.fileInfo(), this.visibilityInfo());
}
clone() {
return new Element(this.combinator,
/** @type {string | Node} */ (this.value),
this.isVariable,
this.getIndex(),
this.fileInfo(), this.visibilityInfo());
}
/**
* @param {EvalContext} context
* @param {CSSOutput} output
*/
genCSS(context, output) {
},
eval: function (context) {
return new Element(this.combinator, this.value.eval ? this.value.eval(context) : this.value, this.isVariable, this.getIndex(), this.fileInfo(), this.visibilityInfo());
},
clone: function () {
return new Element(this.combinator, this.value, this.isVariable, this.getIndex(), this.fileInfo(), this.visibilityInfo());
},
genCSS: function (context, output) {
output.add(this.toCSS(context), this.fileInfo(), this.getIndex());
}
/** @param {EvalContext} [context] */
toCSS(context) {
/** @type {EvalContext & { firstSelector?: boolean }} */
const ctx = context || {};
let value = this.value;
const firstSelector = ctx.firstSelector;
if (value instanceof Paren) {
},
toCSS: function (context) {
context = context || {};
var value = this.value;
var firstSelector = context.firstSelector;
if (value instanceof paren_1.default) {
// selector in parens should not be affected by outer selector
// flags (breaks only interpolated selectors - see #1973)
ctx.firstSelector = true;
context.firstSelector = true;
}
value = /** @type {Node} */ (value).toCSS ? /** @type {Node} */ (value).toCSS(ctx) : /** @type {string} */ (value);
ctx.firstSelector = firstSelector;
value = value.toCSS ? value.toCSS(context) : value;
context.firstSelector = firstSelector;
if (value === '' && this.combinator.value.charAt(0) === '&') {
return '';
} else {
return this.combinator.toCSS(ctx) + value;
}
else {
return this.combinator.toCSS(context) + value;
}
}
}
export default Element;
});
exports.default = Element;
//# sourceMappingURL=element.js.map
+50 -75
View File
@@ -1,100 +1,75 @@
// @ts-check
/** @import { EvalContext, CSSOutput, TreeVisitor } from './node.js' */
import Node from './node.js';
import Paren from './paren.js';
import Comment from './comment.js';
import Dimension from './dimension.js';
import Anonymous from './anonymous.js';
class Expression extends Node {
get type() { return 'Expression'; }
/**
* @param {Node[]} value
* @param {boolean} [noSpacing]
*/
constructor(value, noSpacing) {
super();
this.value = value;
/** @type {boolean | undefined} */
this.noSpacing = noSpacing;
/** @type {boolean | undefined} */
this.parens = undefined;
/** @type {boolean | undefined} */
this.parensInOp = undefined;
if (!value) {
throw new Error('Expression requires an array parameter');
}
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var tslib_1 = require("tslib");
var node_1 = tslib_1.__importDefault(require("./node"));
var paren_1 = tslib_1.__importDefault(require("./paren"));
var comment_1 = tslib_1.__importDefault(require("./comment"));
var dimension_1 = tslib_1.__importDefault(require("./dimension"));
var anonymous_1 = tslib_1.__importDefault(require("./anonymous"));
var Expression = function (value, noSpacing) {
this.value = value;
this.noSpacing = noSpacing;
if (!value) {
throw new Error('Expression requires an array parameter');
}
/** @param {TreeVisitor} visitor */
accept(visitor) {
this.value = visitor.visitArray(/** @type {Node[]} */ (this.value));
}
/** @param {EvalContext} context */
eval(context) {
const noSpacing = this.noSpacing;
/** @type {Node | Expression} */
let returnValue;
const mathOn = context.isMathOn();
const inParenthesis = this.parens;
let doubleParen = false;
};
Expression.prototype = Object.assign(new node_1.default(), {
type: 'Expression',
accept: function (visitor) {
this.value = visitor.visitArray(this.value);
},
eval: function (context) {
var noSpacing = this.noSpacing;
var returnValue;
var mathOn = context.isMathOn();
var inParenthesis = this.parens;
var doubleParen = false;
if (inParenthesis) {
context.inParenthesis();
}
const value = /** @type {Node[]} */ (this.value);
if (value.length > 1) {
returnValue = new Expression(value.map(function (e) {
if (this.value.length > 1) {
returnValue = new Expression(this.value.map(function (e) {
if (!e.eval) {
return e;
}
return e.eval(context);
}), this.noSpacing);
} else if (value.length === 1) {
const first = /** @type {Expression} */ (value[0]);
if (first.parens && !first.parensInOp && !context.inCalc) {
}
else if (this.value.length === 1) {
if (this.value[0].parens && !this.value[0].parensInOp && !context.inCalc) {
doubleParen = true;
}
returnValue = value[0].eval(context);
} else {
returnValue = this.value[0].eval(context);
}
else {
returnValue = this;
}
if (inParenthesis) {
context.outOfParenthesis();
}
if (this.parens && this.parensInOp && !mathOn && !doubleParen
&& (!(returnValue instanceof Dimension))) {
returnValue = new Paren(returnValue);
&& (!(returnValue instanceof dimension_1.default))) {
returnValue = new paren_1.default(returnValue);
}
/** @type {Expression} */ (returnValue).noSpacing =
/** @type {Expression} */ (returnValue).noSpacing || noSpacing;
returnValue.noSpacing = returnValue.noSpacing || noSpacing;
return returnValue;
}
/**
* @param {EvalContext} context
* @param {CSSOutput} output
*/
genCSS(context, output) {
const value = /** @type {Node[]} */ (this.value);
for (let i = 0; i < value.length; i++) {
value[i].genCSS(context, output);
if (!this.noSpacing && i + 1 < value.length) {
if (!(value[i + 1] instanceof Anonymous) ||
value[i + 1] instanceof Anonymous && /** @type {string} */ (value[i + 1].value) !== ',') {
},
genCSS: function (context, output) {
for (var i = 0; i < this.value.length; i++) {
this.value[i].genCSS(context, output);
if (!this.noSpacing && i + 1 < this.value.length) {
if (i + 1 < this.value.length && !(this.value[i + 1] instanceof anonymous_1.default) ||
this.value[i + 1] instanceof anonymous_1.default && this.value[i + 1].value !== ',') {
output.add(' ');
}
}
}
}
throwAwayComments() {
this.value = /** @type {Node[]} */ (this.value).filter(function(v) {
return !(v instanceof Comment);
},
throwAwayComments: function () {
this.value = this.value.filter(function (v) {
return !(v instanceof comment_1.default);
});
}
}
export default Expression;
});
exports.default = Expression;
//# sourceMappingURL=expression.js.map
+42 -71
View File
@@ -1,73 +1,46 @@
// @ts-check
/** @import { EvalContext, TreeVisitor, FileInfo, VisibilityInfo } from './node.js' */
import Node from './node.js';
import Selector from './selector.js';
class Extend extends Node {
get type() { return 'Extend'; }
/**
* @param {Selector} selector
* @param {string} option
* @param {number} index
* @param {FileInfo} currentFileInfo
* @param {VisibilityInfo} [visibilityInfo]
*/
constructor(selector, option, index, currentFileInfo, visibilityInfo) {
super();
this.selector = selector;
this.option = option;
this.object_id = Extend.next_id++;
/** @type {number[]} */
this.parent_ids = [this.object_id];
this._index = index;
this._fileInfo = currentFileInfo;
this.copyVisibilityInfo(visibilityInfo);
/** @type {boolean} */
this.allowRoot = true;
/** @type {boolean} */
this.allowBefore = false;
/** @type {boolean} */
this.allowAfter = false;
switch (option) {
case '!all':
case 'all':
this.allowBefore = true;
this.allowAfter = true;
break;
default:
this.allowBefore = false;
this.allowAfter = false;
break;
}
this.setParent(this.selector, this);
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var tslib_1 = require("tslib");
var node_1 = tslib_1.__importDefault(require("./node"));
var selector_1 = tslib_1.__importDefault(require("./selector"));
var Extend = function (selector, option, index, currentFileInfo, visibilityInfo) {
this.selector = selector;
this.option = option;
this.object_id = Extend.next_id++;
this.parent_ids = [this.object_id];
this._index = index;
this._fileInfo = currentFileInfo;
this.copyVisibilityInfo(visibilityInfo);
this.allowRoot = true;
switch (option) {
case '!all':
case 'all':
this.allowBefore = true;
this.allowAfter = true;
break;
default:
this.allowBefore = false;
this.allowAfter = false;
break;
}
/** @param {TreeVisitor} visitor */
accept(visitor) {
this.selector = /** @type {Selector} */ (visitor.visit(this.selector));
}
/** @param {EvalContext} context */
eval(context) {
return new Extend(/** @type {Selector} */ (this.selector.eval(context)), this.option, this.getIndex(), this.fileInfo(), this.visibilityInfo());
}
this.setParent(this.selector, this);
};
Extend.prototype = Object.assign(new node_1.default(), {
type: 'Extend',
accept: function (visitor) {
this.selector = visitor.visit(this.selector);
},
eval: function (context) {
return new Extend(this.selector.eval(context), this.option, this.getIndex(), this.fileInfo(), this.visibilityInfo());
},
// remove when Nodes have JSDoc types
// eslint-disable-next-line no-unused-vars
/** @param {EvalContext} [context] */
clone(context) {
clone: function (context) {
return new Extend(this.selector, this.option, this.getIndex(), this.fileInfo(), this.visibilityInfo());
}
},
// it concatenates (joins) all selectors in selector array
/** @param {Selector[]} selectors */
findSelfSelectors(selectors) {
/** @type {import('./element.js').default[]} */
let selfElements = [];
let i, selectorElements;
findSelfSelectors: function (selectors) {
var selfElements = [], i, selectorElements;
for (i = 0; i < selectors.length; i++) {
selectorElements = selectors[i].elements;
// duplicate the logic in genCSS function inside the selector node.
@@ -77,12 +50,10 @@ class Extend extends Node {
}
selfElements = selfElements.concat(selectors[i].elements);
}
/** @type {Selector[]} */
this.selfSelectors = [new Selector(selfElements)];
this.selfSelectors = [new selector_1.default(selfElements)];
this.selfSelectors[0].copyVisibilityInfo(this.visibilityInfo());
}
}
});
Extend.next_id = 0;
export default Extend;
exports.default = Extend;
//# sourceMappingURL=extend.js.map
+111 -185
View File
@@ -1,23 +1,15 @@
// @ts-check
/** @import { EvalContext, CSSOutput, TreeVisitor, FileInfo, VisibilityInfo } from './node.js' */
import Node from './node.js';
import Media from './media.js';
import URL from './url.js';
import Quoted from './quoted.js';
import Ruleset from './ruleset.js';
import Anonymous from './anonymous.js';
import Expression from './expression.js';
import * as utils from '../utils.js';
import LessError from '../less-error.js';
/**
* @typedef {object} ImportOptions
* @property {boolean} [less]
* @property {boolean} [inline]
* @property {boolean} [isPlugin]
* @property {boolean} [reference]
*/
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var tslib_1 = require("tslib");
var node_1 = tslib_1.__importDefault(require("./node"));
var media_1 = tslib_1.__importDefault(require("./media"));
var url_1 = tslib_1.__importDefault(require("./url"));
var quoted_1 = tslib_1.__importDefault(require("./quoted"));
var ruleset_1 = tslib_1.__importDefault(require("./ruleset"));
var anonymous_1 = tslib_1.__importDefault(require("./anonymous"));
var utils = tslib_1.__importStar(require("../utils"));
var less_error_1 = tslib_1.__importDefault(require("../less-error"));
var expression_1 = tslib_1.__importDefault(require("./expression"));
//
// CSS @import node
//
@@ -30,73 +22,38 @@ import LessError from '../less-error.js';
// `import,push`, we also pass it a callback, which it'll call once
// the file has been fetched, and parsed.
//
class Import extends Node {
get type() { return 'Import'; }
/**
* @param {Node} path
* @param {Node | null} features
* @param {ImportOptions} options
* @param {number} index
* @param {FileInfo} [currentFileInfo]
* @param {VisibilityInfo} [visibilityInfo]
*/
constructor(path, features, options, index, currentFileInfo, visibilityInfo) {
super();
/** @type {ImportOptions} */
this.options = options;
this._index = index;
this._fileInfo = currentFileInfo;
this.path = path;
/** @type {Node | null} */
this.features = features;
/** @type {boolean} */
this.allowRoot = true;
/** @type {boolean | undefined} */
this.css = undefined;
/** @type {boolean | undefined} */
this.layerCss = undefined;
/** @type {(Ruleset & { imports?: object, filename?: string, functions?: object, functionRegistry?: { addMultiple: (fns: object) => void } }) | undefined} */
this.root = undefined;
/** @type {string | undefined} */
this.importedFilename = undefined;
/** @type {boolean | (() => boolean) | undefined} */
this.skip = undefined;
/** @type {{ message: string, index: number, filename: string } | undefined} */
this.error = undefined;
if (this.options.less !== undefined || this.options.inline) {
this.css = !this.options.less || this.options.inline;
} else {
const pathValue = this.getPath();
if (pathValue && /[#.&?]css([?;].*)?$/.test(pathValue)) {
this.css = true;
}
}
this.copyVisibilityInfo(visibilityInfo);
if (this.features) {
this.setParent(this.features, /** @type {Node} */ (this));
}
this.setParent(this.path, /** @type {Node} */ (this));
var Import = function (path, features, options, index, currentFileInfo, visibilityInfo) {
this.options = options;
this._index = index;
this._fileInfo = currentFileInfo;
this.path = path;
this.features = features;
this.allowRoot = true;
if (this.options.less !== undefined || this.options.inline) {
this.css = !this.options.less || this.options.inline;
}
/** @param {TreeVisitor} visitor */
accept(visitor) {
else {
var pathValue = this.getPath();
if (pathValue && /[#.&?]css([?;].*)?$/.test(pathValue)) {
this.css = true;
}
}
this.copyVisibilityInfo(visibilityInfo);
this.setParent(this.features, this);
this.setParent(this.path, this);
};
Import.prototype = Object.assign(new node_1.default(), {
type: 'Import',
accept: function (visitor) {
if (this.features) {
this.features = visitor.visit(this.features);
}
this.path = visitor.visit(this.path);
if (!this.options.isPlugin && !this.options.inline && this.root) {
this.root = /** @type {Ruleset} */ (visitor.visit(this.root));
this.root = visitor.visit(this.root);
}
}
/**
* @param {EvalContext} context
* @param {CSSOutput} output
*/
genCSS(context, output) {
},
genCSS: function (context, output) {
if (this.css && this.path._fileInfo.reference === undefined) {
output.add('@import ', this._fileInfo, this._index);
this.path.genCSS(context, output);
@@ -106,105 +63,79 @@ class Import extends Node {
}
output.add(';');
}
}
/** @returns {string | undefined} */
getPath() {
return (this.path instanceof URL) ?
/** @type {string} */ (/** @type {Node} */ (this.path.value).value) :
/** @type {string | undefined} */ (this.path.value);
}
/** @returns {boolean | RegExpMatchArray | null} */
isVariableImport() {
let path = this.path;
if (path instanceof URL) {
path = /** @type {Node} */ (path.value);
},
getPath: function () {
return (this.path instanceof url_1.default) ?
this.path.value.value : this.path.value;
},
isVariableImport: function () {
var path = this.path;
if (path instanceof url_1.default) {
path = path.value;
}
if (path instanceof Quoted) {
if (path instanceof quoted_1.default) {
return path.containsVariables();
}
return true;
}
/** @param {EvalContext} context */
evalForImport(context) {
let path = this.path;
if (path instanceof URL) {
path = /** @type {Node} */ (path.value);
},
evalForImport: function (context) {
var path = this.path;
if (path instanceof url_1.default) {
path = path.value;
}
return new Import(path.eval(context), this.features, this.options, this._index || 0, this._fileInfo, this.visibilityInfo());
}
/** @param {EvalContext} context */
evalPath(context) {
const path = this.path.eval(context);
const fileInfo = this._fileInfo;
if (!(path instanceof URL)) {
return new Import(path.eval(context), this.features, this.options, this._index, this._fileInfo, this.visibilityInfo());
},
evalPath: function (context) {
var path = this.path.eval(context);
var fileInfo = this._fileInfo;
if (!(path instanceof url_1.default)) {
// Add the rootpath if the URL requires a rewrite
const pathValue = /** @type {string} */ (path.value);
var pathValue = path.value;
if (fileInfo &&
pathValue &&
context.pathRequiresRewrite(pathValue)) {
path.value = context.rewritePath(pathValue, fileInfo.rootpath);
} else {
path.value = context.normalizePath(/** @type {string} */ (path.value));
}
else {
path.value = context.normalizePath(path.value);
}
}
return path;
}
/** @param {EvalContext} context */
// @ts-ignore - Import.eval returns Node | Node[] | Import (wider than Node.eval's Node return)
eval(context) {
const result = this.doEval(context);
},
eval: function (context) {
var result = this.doEval(context);
if (this.options.reference || this.blocksVisibility()) {
if (Array.isArray(result)) {
if (result.length || result.length === 0) {
result.forEach(function (node) {
node.addVisibilityBlock();
});
} else {
/** @type {Node} */ (result).addVisibilityBlock();
}
else {
result.addVisibilityBlock();
}
}
return result;
}
/** @param {EvalContext} context */
doEval(context) {
/** @type {Ruleset | undefined} */
let ruleset;
const features = this.features && this.features.eval(context);
},
doEval: function (context) {
var ruleset;
var registry;
var features = this.features && this.features.eval(context);
if (this.options.isPlugin) {
if (this.root && this.root.eval) {
try {
this.root.eval(context);
}
catch (e) {
const err = /** @type {{ message: string }} */ (e);
err.message = 'Plugin error during evaluation';
throw new LessError(
/** @type {{ message: string, index?: number, filename?: string }} */ (e),
/** @type {{ imports: object }} */ (/** @type {unknown} */ (this.root)).imports,
/** @type {{ filename: string }} */ (/** @type {unknown} */ (this.root)).filename
);
e.message = 'Plugin error during evaluation';
throw new less_error_1.default(e, this.root.imports, this.root.filename);
}
}
const frame0 = /** @type {Ruleset & { functionRegistry?: { addMultiple: (fns: object) => void } }} */ (context.frames[0]);
const registry = frame0 && frame0.functionRegistry;
registry = context.frames[0] && context.frames[0].functionRegistry;
if (registry && this.root && this.root.functions) {
registry.addMultiple(this.root.functions);
}
return [];
}
if (this.skip) {
if (typeof this.skip === 'function') {
this.skip = this.skip();
@@ -214,12 +145,12 @@ class Import extends Node {
}
}
if (this.features) {
let featureValue = /** @type {Node[]} */ (this.features.value);
var featureValue = this.features.value;
if (Array.isArray(featureValue) && featureValue.length >= 1) {
const expr = featureValue[0];
if (expr.type === 'Expression' && Array.isArray(expr.value) && /** @type {Node[]} */ (expr.value).length >= 2) {
featureValue = /** @type {Node[]} */ (expr.value);
const isLayer = featureValue[0].type === 'Keyword' && featureValue[0].value === 'layer'
var expr = featureValue[0];
if (expr.type === 'Expression' && Array.isArray(expr.value) && expr.value.length >= 2) {
featureValue = expr.value;
var isLayer = featureValue[0].type === 'Keyword' && featureValue[0].value === 'layer'
&& featureValue[1].type === 'Paren';
if (isLayer) {
this.css = false;
@@ -228,20 +159,14 @@ class Import extends Node {
}
}
if (this.options.inline) {
const contents = new Anonymous(
/** @type {string} */ (/** @type {unknown} */ (this.root)),
0,
{
filename: this.importedFilename,
reference: this.path._fileInfo && this.path._fileInfo.reference
},
true,
true
);
return this.features ? new Media([contents], /** @type {Node[]} */ (this.features.value)) : [contents];
} else if (this.css || this.layerCss) {
const newImport = new Import(this.evalPath(context), features, this.options, this._index || 0);
var contents = new anonymous_1.default(this.root, 0, {
filename: this.importedFilename,
reference: this.path._fileInfo && this.path._fileInfo.reference
}, true, true);
return this.features ? new media_1.default([contents], this.features.value) : [contents];
}
else if (this.css || this.layerCss) {
var newImport = new Import(this.evalPath(context), features, this.options, this._index);
if (this.layerCss) {
newImport.css = this.layerCss;
newImport.path._fileInfo = this._fileInfo;
@@ -250,42 +175,43 @@ class Import extends Node {
throw this.error;
}
return newImport;
} else if (this.root) {
}
else if (this.root) {
if (this.features) {
let featureValue = /** @type {Node[]} */ (this.features.value);
var featureValue = this.features.value;
if (Array.isArray(featureValue) && featureValue.length === 1) {
const expr = featureValue[0];
if (expr.type === 'Expression' && Array.isArray(expr.value) && /** @type {Node[]} */ (expr.value).length >= 2) {
featureValue = /** @type {Node[]} */ (expr.value);
const isLayer = featureValue[0].type === 'Keyword' && featureValue[0].value === 'layer'
var expr = featureValue[0];
if (expr.type === 'Expression' && Array.isArray(expr.value) && expr.value.length >= 2) {
featureValue = expr.value;
var isLayer = featureValue[0].type === 'Keyword' && featureValue[0].value === 'layer'
&& featureValue[1].type === 'Paren';
if (isLayer) {
this.layerCss = true;
featureValue[0] = new Expression(/** @type {Node[]} */ (featureValue.slice(0, 2)));
featureValue[0] = new expression_1.default(featureValue.slice(0, 2));
featureValue.splice(1, 1);
/** @type {Expression} */ (featureValue[0]).noSpacing = true;
featureValue[0].noSpacing = true;
return this;
}
}
}
}
ruleset = new Ruleset(null, utils.copyArray(this.root.rules));
ruleset = new ruleset_1.default(null, utils.copyArray(this.root.rules));
ruleset.evalImports(context);
return this.features ? new Media(ruleset.rules, /** @type {Node[]} */ (this.features.value)) : ruleset.rules;
} else {
return this.features ? new media_1.default(ruleset.rules, this.features.value) : ruleset.rules;
}
else {
if (this.features) {
let featureValue = /** @type {Node[]} */ (this.features.value);
var featureValue = this.features.value;
if (Array.isArray(featureValue) && featureValue.length >= 1) {
featureValue = /** @type {Node[]} */ (featureValue[0].value);
featureValue = featureValue[0].value;
if (Array.isArray(featureValue) && featureValue.length >= 2) {
const isLayer = featureValue[0].type === 'Keyword' && featureValue[0].value === 'layer'
var isLayer = featureValue[0].type === 'Keyword' && featureValue[0].value === 'layer'
&& featureValue[1].type === 'Paren';
if (isLayer) {
this.css = true;
featureValue[0] = new Expression(/** @type {Node[]} */ (featureValue.slice(0, 2)));
featureValue[0] = new expression_1.default(featureValue.slice(0, 2));
featureValue.splice(1, 1);
/** @type {Expression} */ (featureValue[0]).noSpacing = true;
featureValue[0].noSpacing = true;
return this;
}
}
@@ -294,6 +220,6 @@ class Import extends Node {
return [];
}
}
}
export default Import;
});
exports.default = Import;
//# sourceMappingURL=import.js.map
+81 -52
View File
@@ -1,56 +1,85 @@
// @ts-check
import Node from './node.js';
import Color from './color.js';
import AtRule from './atrule.js';
import DetachedRuleset from './detached-ruleset.js';
import Operation from './operation.js';
import Dimension from './dimension.js';
import Unit from './unit.js';
import Keyword from './keyword.js';
import Variable from './variable.js';
import Property from './property.js';
import Ruleset from './ruleset.js';
import Element from './element.js';
import Attribute from './attribute.js';
import Combinator from './combinator.js';
import Selector from './selector.js';
import Quoted from './quoted.js';
import Expression from './expression.js';
import Declaration from './declaration.js';
import Call from './call.js';
import URL from './url.js';
import Import from './import.js';
import Comment from './comment.js';
import Anonymous from './anonymous.js';
import Value from './value.js';
import JavaScript from './javascript.js';
import Assignment from './assignment.js';
import Condition from './condition.js';
import QueryInParens from './query-in-parens.js';
import Paren from './paren.js';
import Media from './media.js';
import Container from './container.js';
import UnicodeDescriptor from './unicode-descriptor.js';
import Negative from './negative.js';
import Extend from './extend.js';
import VariableCall from './variable-call.js';
import NamespaceValue from './namespace-value.js';
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var tslib_1 = require("tslib");
var node_1 = tslib_1.__importDefault(require("./node"));
var color_1 = tslib_1.__importDefault(require("./color"));
var atrule_1 = tslib_1.__importDefault(require("./atrule"));
var detached_ruleset_1 = tslib_1.__importDefault(require("./detached-ruleset"));
var operation_1 = tslib_1.__importDefault(require("./operation"));
var dimension_1 = tslib_1.__importDefault(require("./dimension"));
var unit_1 = tslib_1.__importDefault(require("./unit"));
var keyword_1 = tslib_1.__importDefault(require("./keyword"));
var variable_1 = tslib_1.__importDefault(require("./variable"));
var property_1 = tslib_1.__importDefault(require("./property"));
var ruleset_1 = tslib_1.__importDefault(require("./ruleset"));
var element_1 = tslib_1.__importDefault(require("./element"));
var attribute_1 = tslib_1.__importDefault(require("./attribute"));
var combinator_1 = tslib_1.__importDefault(require("./combinator"));
var selector_1 = tslib_1.__importDefault(require("./selector"));
var quoted_1 = tslib_1.__importDefault(require("./quoted"));
var expression_1 = tslib_1.__importDefault(require("./expression"));
var declaration_1 = tslib_1.__importDefault(require("./declaration"));
var call_1 = tslib_1.__importDefault(require("./call"));
var url_1 = tslib_1.__importDefault(require("./url"));
var import_1 = tslib_1.__importDefault(require("./import"));
var comment_1 = tslib_1.__importDefault(require("./comment"));
var anonymous_1 = tslib_1.__importDefault(require("./anonymous"));
var value_1 = tslib_1.__importDefault(require("./value"));
var javascript_1 = tslib_1.__importDefault(require("./javascript"));
var assignment_1 = tslib_1.__importDefault(require("./assignment"));
var condition_1 = tslib_1.__importDefault(require("./condition"));
var query_in_parens_1 = tslib_1.__importDefault(require("./query-in-parens"));
var paren_1 = tslib_1.__importDefault(require("./paren"));
var media_1 = tslib_1.__importDefault(require("./media"));
var container_1 = tslib_1.__importDefault(require("./container"));
var unicode_descriptor_1 = tslib_1.__importDefault(require("./unicode-descriptor"));
var negative_1 = tslib_1.__importDefault(require("./negative"));
var extend_1 = tslib_1.__importDefault(require("./extend"));
var variable_call_1 = tslib_1.__importDefault(require("./variable-call"));
var namespace_value_1 = tslib_1.__importDefault(require("./namespace-value"));
// mixins
import MixinCall from './mixin-call.js';
import MixinDefinition from './mixin-definition.js';
export default {
Node, Color, AtRule, DetachedRuleset, Operation,
Dimension, Unit, Keyword, Variable, Property,
Ruleset, Element, Attribute, Combinator, Selector,
Quoted, Expression, Declaration, Call, URL, Import,
Comment, Anonymous, Value, JavaScript, Assignment,
Condition, Paren, Media, Container, QueryInParens,
UnicodeDescriptor, Negative, Extend, VariableCall,
NamespaceValue,
var mixin_call_1 = tslib_1.__importDefault(require("./mixin-call"));
var mixin_definition_1 = tslib_1.__importDefault(require("./mixin-definition"));
exports.default = {
Node: node_1.default,
Color: color_1.default,
AtRule: atrule_1.default,
DetachedRuleset: detached_ruleset_1.default,
Operation: operation_1.default,
Dimension: dimension_1.default,
Unit: unit_1.default,
Keyword: keyword_1.default,
Variable: variable_1.default,
Property: property_1.default,
Ruleset: ruleset_1.default,
Element: element_1.default,
Attribute: attribute_1.default,
Combinator: combinator_1.default,
Selector: selector_1.default,
Quoted: quoted_1.default,
Expression: expression_1.default,
Declaration: declaration_1.default,
Call: call_1.default,
URL: url_1.default,
Import: import_1.default,
Comment: comment_1.default,
Anonymous: anonymous_1.default,
Value: value_1.default,
JavaScript: javascript_1.default,
Assignment: assignment_1.default,
Condition: condition_1.default,
Paren: paren_1.default,
Media: media_1.default,
Container: container_1.default,
QueryInParens: query_in_parens_1.default,
UnicodeDescriptor: unicode_descriptor_1.default,
Negative: negative_1.default,
Extend: extend_1.default,
VariableCall: variable_call_1.default,
NamespaceValue: namespace_value_1.default,
mixin: {
Call: MixinCall,
Definition: MixinDefinition
Call: mixin_call_1.default,
Definition: mixin_definition_1.default
}
};
//# sourceMappingURL=index.js.map
+32 -43
View File
@@ -1,45 +1,34 @@
// @ts-check
/** @import { EvalContext, FileInfo } from './node.js' */
import JsEvalNode from './js-eval-node.js';
import Dimension from './dimension.js';
import Quoted from './quoted.js';
import Anonymous from './anonymous.js';
class JavaScript extends JsEvalNode {
get type() { return 'JavaScript'; }
/**
* @param {string} string
* @param {boolean} escaped
* @param {number} index
* @param {FileInfo} currentFileInfo
*/
constructor(string, escaped, index, currentFileInfo) {
super();
this.escaped = escaped;
this.expression = string;
this._index = index;
this._fileInfo = currentFileInfo;
}
/**
* @param {EvalContext} context
* @returns {Dimension | Quoted | Anonymous}
*/
eval(context) {
const result = this.evaluateJavaScript(this.expression, context);
const type = typeof result;
if (type === 'number' && !isNaN(/** @type {number} */ (result))) {
return new Dimension(/** @type {number} */ (result));
} else if (type === 'string') {
return new Quoted(`"${result}"`, /** @type {string} */ (result), this.escaped, this._index);
} else if (Array.isArray(result)) {
return new Anonymous(/** @type {string[]} */ (result).join(', '));
} else {
return new Anonymous(/** @type {string} */ (result));
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var tslib_1 = require("tslib");
var js_eval_node_1 = tslib_1.__importDefault(require("./js-eval-node"));
var dimension_1 = tslib_1.__importDefault(require("./dimension"));
var quoted_1 = tslib_1.__importDefault(require("./quoted"));
var anonymous_1 = tslib_1.__importDefault(require("./anonymous"));
var JavaScript = function (string, escaped, index, currentFileInfo) {
this.escaped = escaped;
this.expression = string;
this._index = index;
this._fileInfo = currentFileInfo;
};
JavaScript.prototype = Object.assign(new js_eval_node_1.default(), {
type: 'JavaScript',
eval: function (context) {
var result = this.evaluateJavaScript(this.expression, context);
var type = typeof result;
if (type === 'number' && !isNaN(result)) {
return new dimension_1.default(result);
}
else if (type === 'string') {
return new quoted_1.default("\"".concat(result, "\""), result, this.escaped, this._index);
}
else if (Array.isArray(result)) {
return new anonymous_1.default(result.join(', '));
}
else {
return new anonymous_1.default(result);
}
}
}
export default JavaScript;
});
exports.default = JavaScript;
//# sourceMappingURL=javascript.js.map
+32 -46
View File
@@ -1,74 +1,60 @@
// @ts-check
/** @import { EvalContext } from './node.js' */
import Node from './node.js';
import Variable from './variable.js';
class JsEvalNode extends Node {
/**
* @param {string} expression
* @param {EvalContext} context
* @returns {string | number | boolean}
*/
evaluateJavaScript(expression, context) {
let result;
const that = this;
/** @type {Record<string, { value: Node, toJS: () => string }>} */
const evalContext = {};
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var tslib_1 = require("tslib");
var node_1 = tslib_1.__importDefault(require("./node"));
var variable_1 = tslib_1.__importDefault(require("./variable"));
var JsEvalNode = function () { };
JsEvalNode.prototype = Object.assign(new node_1.default(), {
evaluateJavaScript: function (expression, context) {
var result;
var that = this;
var evalContext = {};
if (!context.javascriptEnabled) {
throw { message: 'Inline JavaScript is not enabled. Is it set in your options?',
filename: this.fileInfo().filename,
index: this.getIndex() };
}
expression = expression.replace(/@\{([\w-]+)\}/g, function (_, name) {
return that.jsify(new Variable(`@${name}`, that.getIndex(), that.fileInfo()).eval(context));
return that.jsify(new variable_1.default("@".concat(name), that.getIndex(), that.fileInfo()).eval(context));
});
/** @type {Function} */
let expressionFunc;
try {
expressionFunc = new Function(`return (${expression})`);
} catch (e) {
throw { message: `JavaScript evaluation error: ${/** @type {Error} */ (e).message} from \`${expression}\`` ,
expression = new Function("return (".concat(expression, ")"));
}
catch (e) {
throw { message: "JavaScript evaluation error: ".concat(e.message, " from `").concat(expression, "`"),
filename: this.fileInfo().filename,
index: this.getIndex() };
}
const variables = /** @type {Node & { variables: () => Record<string, { value: Node }> }} */ (context.frames[0]).variables();
for (const k in variables) {
var variables = context.frames[0].variables();
for (var k in variables) {
// eslint-disable-next-line no-prototype-builtins
if (variables.hasOwnProperty(k)) {
evalContext[k.slice(1)] = {
value: variables[k].value,
toJS: function () {
return this.value.eval(context).toCSS(context);
return this.value.eval(context).toCSS();
}
};
}
}
try {
result = expressionFunc.call(evalContext);
} catch (e) {
throw { message: `JavaScript evaluation error: '${/** @type {Error} */ (e).name}: ${/** @type {Error} */ (e).message.replace(/["]/g, '\'')}'` ,
result = expression.call(evalContext);
}
catch (e) {
throw { message: "JavaScript evaluation error: '".concat(e.name, ": ").concat(e.message.replace(/["]/g, '\''), "'"),
filename: this.fileInfo().filename,
index: this.getIndex() };
}
return result;
}
/**
* @param {Node} obj
* @returns {string}
*/
jsify(obj) {
},
jsify: function (obj) {
if (Array.isArray(obj.value) && (obj.value.length > 1)) {
return `[${obj.value.map(function (v) { return v.toCSS(/** @type {EvalContext} */ (undefined)); }).join(', ')}]`;
} else {
return obj.toCSS(/** @type {EvalContext} */ (undefined));
return "[".concat(obj.value.map(function (v) { return v.toCSS(); }).join(', '), "]");
}
else {
return obj.toCSS();
}
}
}
export default JsEvalNode;
});
exports.default = JsEvalNode;
//# sourceMappingURL=js-eval-node.js.map
+17 -25
View File
@@ -1,28 +1,20 @@
// @ts-check
import Node from './node.js';
/** @import { EvalContext, CSSOutput } from './node.js' */
class Keyword extends Node {
get type() { return 'Keyword'; }
/** @param {string} value */
constructor(value) {
super();
this.value = value;
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var tslib_1 = require("tslib");
var node_1 = tslib_1.__importDefault(require("./node"));
var Keyword = function (value) {
this.value = value;
};
Keyword.prototype = Object.assign(new node_1.default(), {
type: 'Keyword',
genCSS: function (context, output) {
if (this.value === '%') {
throw { type: 'Syntax', message: 'Invalid % without number' };
}
output.add(this.value);
}
/**
* @param {EvalContext} context
* @param {CSSOutput} output
*/
genCSS(context, output) {
if (this.value === '%') { throw { type: 'Syntax', message: 'Invalid % without number' }; }
output.add(/** @type {string} */ (this.value));
}
}
});
Keyword.True = new Keyword('true');
Keyword.False = new Keyword('false');
export default Keyword;
exports.default = Keyword;
//# sourceMappingURL=keyword.js.map
+35 -77
View File
@@ -1,90 +1,48 @@
// @ts-check
/** @import { EvalContext, CSSOutput, FileInfo, VisibilityInfo } from './node.js' */
/** @import { NestableAtRuleThis } from './nested-at-rule.js' */
/** @import { RulesetLikeNode } from './atrule.js' */
import Node from './node.js';
import Ruleset from './ruleset.js';
import Value from './value.js';
import Selector from './selector.js';
import AtRule from './atrule.js';
import NestableAtRulePrototype from './nested-at-rule.js';
class Media extends AtRule {
get type() { return 'Media'; }
/**
* @param {Node[] | null} value
* @param {Node[]} features
* @param {number} [index]
* @param {FileInfo} [currentFileInfo]
* @param {VisibilityInfo} [visibilityInfo]
*/
constructor(value, features, index, currentFileInfo, visibilityInfo) {
super();
this._index = index;
this._fileInfo = currentFileInfo;
const selectors = (new Selector([], null, null, this._index, this._fileInfo)).createEmptySelectors();
/** @type {Value} */
this.features = new Value(features);
/** @type {RulesetLikeNode[]} */
this.rules = [new Ruleset(selectors, value)];
/** @type {RulesetLikeNode} */ (this.rules[0]).allowImports = true;
this.copyVisibilityInfo(visibilityInfo);
this.allowRoot = true;
this.setParent(selectors, /** @type {Node} */ (/** @type {unknown} */ (this)));
this.setParent(this.features, /** @type {Node} */ (/** @type {unknown} */ (this)));
this.setParent(this.rules, /** @type {Node} */ (/** @type {unknown} */ (this)));
}
/**
* @param {EvalContext} context
* @param {CSSOutput} output
*/
genCSS(context, output) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var tslib_1 = require("tslib");
var ruleset_1 = tslib_1.__importDefault(require("./ruleset"));
var value_1 = tslib_1.__importDefault(require("./value"));
var selector_1 = tslib_1.__importDefault(require("./selector"));
var atrule_1 = tslib_1.__importDefault(require("./atrule"));
var nested_at_rule_1 = tslib_1.__importDefault(require("./nested-at-rule"));
var Media = function (value, features, index, currentFileInfo, visibilityInfo) {
this._index = index;
this._fileInfo = currentFileInfo;
var selectors = (new selector_1.default([], null, null, this._index, this._fileInfo)).createEmptySelectors();
this.features = new value_1.default(features);
this.rules = [new ruleset_1.default(selectors, value)];
this.rules[0].allowImports = true;
this.copyVisibilityInfo(visibilityInfo);
this.allowRoot = true;
this.setParent(selectors, this);
this.setParent(this.features, this);
this.setParent(this.rules, this);
};
Media.prototype = Object.assign(new atrule_1.default(), tslib_1.__assign(tslib_1.__assign({ type: 'Media' }, nested_at_rule_1.default), { genCSS: function (context, output) {
output.add('@media ', this._fileInfo, this._index);
this.features.genCSS(context, output);
this.outputRuleset(context, output, this.rules);
}
/**
* @param {EvalContext} context
* @returns {Node}
*/
eval(context) {
}, eval: function (context) {
if (!context.mediaBlocks) {
context.mediaBlocks = [];
context.mediaPath = [];
}
const media = new Media(null, [], this._index, this._fileInfo, this.visibilityInfo());
var media = new Media(null, [], this._index, this._fileInfo, this.visibilityInfo());
if (this.debugInfo) {
/** @type {RulesetLikeNode} */ (this.rules[0]).debugInfo = this.debugInfo;
this.rules[0].debugInfo = this.debugInfo;
media.debugInfo = this.debugInfo;
}
media.features = /** @type {Value} */ (this.features.eval(context));
context.mediaPath.push(/** @type {Node} */ (/** @type {unknown} */ (media)));
context.mediaBlocks.push(/** @type {Node} */ (/** @type {unknown} */ (media)));
const fr = /** @type {RulesetLikeNode} */ (context.frames[0]).functionRegistry;
if (fr) {
/** @type {RulesetLikeNode} */ (this.rules[0]).functionRegistry = fr.inherit();
}
media.features = this.features.eval(context);
context.mediaPath.push(media);
context.mediaBlocks.push(media);
this.rules[0].functionRegistry = context.frames[0].functionRegistry.inherit();
context.frames.unshift(this.rules[0]);
media.rules = [/** @type {RulesetLikeNode} */ (this.rules[0].eval(context))];
media.rules = [this.rules[0].eval(context)];
context.frames.shift();
context.mediaPath.pop();
return context.mediaPath.length === 0 ? /** @type {NestableAtRuleThis} */ (/** @type {unknown} */ (media)).evalTop(context) :
/** @type {NestableAtRuleThis} */ (/** @type {unknown} */ (media)).evalNested(context);
}
}
// Apply NestableAtRulePrototype methods (accept, isRulesetLike override AtRule's versions)
Object.assign(Media.prototype, NestableAtRulePrototype);
export default Media;
return context.mediaPath.length === 0 ? media.evalTop(context) :
media.evalNested(context);
} }));
exports.default = Media;
//# sourceMappingURL=media.js.map
+98 -181
View File
@@ -1,127 +1,60 @@
// @ts-check
/** @import { EvalContext, TreeVisitor, FileInfo } from './node.js' */
/** @import { FunctionRegistry } from './nested-at-rule.js' */
import Node from './node.js';
import Selector from './selector.js';
import MixinDefinition from './mixin-definition.js';
import defaultFunc from '../functions/default.js';
/**
* @typedef {{ name?: string, value: Node, expand?: boolean }} MixinArg
*/
/**
* @typedef {Node & {
* rules?: Node[],
* selectors?: Selector[],
* originalRuleset?: Node,
* matchArgs: (args: MixinArg[] | null, context: EvalContext) => boolean,
* matchCondition?: (args: MixinArg[] | null, context: EvalContext) => boolean,
* find: (selector: Selector, self?: Node | null, filter?: (rule: Node) => boolean) => Array<{ rule: Node & { rules?: Node[], originalRuleset?: Node, matchArgs: Function, matchCondition?: Function, evalCall?: Function }, path: Node[] }>,
* functionRegistry?: FunctionRegistry
* }} MixinSearchFrame
*/
class MixinCall extends Node {
get type() { return 'MixinCall'; }
/**
* @param {import('./element.js').default[]} elements
* @param {MixinArg[]} [args]
* @param {number} [index]
* @param {FileInfo} [currentFileInfo]
* @param {string} [important]
*/
constructor(elements, args, index, currentFileInfo, important) {
super();
/** @type {Selector} */
this.selector = new Selector(elements);
/** @type {MixinArg[]} */
this.arguments = args || [];
this._index = index;
this._fileInfo = currentFileInfo;
/** @type {string | undefined} */
this.important = important;
this.allowRoot = true;
this.setParent(this.selector, /** @type {Node} */ (/** @type {unknown} */ (this)));
}
/** @param {TreeVisitor} visitor */
accept(visitor) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var tslib_1 = require("tslib");
var node_1 = tslib_1.__importDefault(require("./node"));
var selector_1 = tslib_1.__importDefault(require("./selector"));
var mixin_definition_1 = tslib_1.__importDefault(require("./mixin-definition"));
var default_1 = tslib_1.__importDefault(require("../functions/default"));
var MixinCall = function (elements, args, index, currentFileInfo, important) {
this.selector = new selector_1.default(elements);
this.arguments = args || [];
this._index = index;
this._fileInfo = currentFileInfo;
this.important = important;
this.allowRoot = true;
this.setParent(this.selector, this);
};
MixinCall.prototype = Object.assign(new node_1.default(), {
type: 'MixinCall',
accept: function (visitor) {
if (this.selector) {
this.selector = /** @type {Selector} */ (visitor.visit(this.selector));
this.selector = visitor.visit(this.selector);
}
if (this.arguments.length) {
this.arguments = /** @type {MixinArg[]} */ (/** @type {unknown} */ (visitor.visitArray(/** @type {Node[]} */ (/** @type {unknown} */ (this.arguments)))));
this.arguments = visitor.visitArray(this.arguments);
}
}
/**
* @param {EvalContext} context
* @returns {Node}
*/
eval(context) {
/** @type {{ rule: Node & { rules?: Node[], originalRuleset?: Node, matchArgs: Function, matchCondition?: Function, evalCall?: Function }, path: Node[] }[] | undefined} */
let mixins;
/** @type {Node & { rules?: Node[], originalRuleset?: Node, matchArgs: Function, matchCondition?: Function, evalCall?: Function }} */
let mixin;
/** @type {Node[]} */
let mixinPath;
/** @type {MixinArg[]} */
const args = [];
/** @type {MixinArg} */
let arg;
/** @type {Node} */
let argValue;
/** @type {Node[]} */
const rules = [];
let match = false;
/** @type {number} */
let i;
/** @type {number} */
let m;
/** @type {number} */
let f;
/** @type {boolean} */
let isRecursive;
/** @type {boolean | undefined} */
let isOneFound;
/** @type {{ mixin: Node & { rules?: Node[], originalRuleset?: Node, matchArgs: Function, matchCondition?: Function, evalCall?: Function }, group: number }[]} */
const candidates = [];
/** @type {{ mixin: Node & { rules?: Node[], originalRuleset?: Node, matchArgs: Function, matchCondition?: Function, evalCall?: Function }, group: number } | number} */
let candidate;
/** @type {boolean[]} */
const conditionResult = [];
/** @type {number | undefined} */
let defaultResult;
const defFalseEitherCase = -1;
const defNone = 0;
const defTrue = 1;
const defFalse = 2;
/** @type {number[]} */
let count;
/** @type {Node | undefined} */
let originalRuleset;
/** @type {((rule: MixinSearchFrame) => boolean) | undefined} */
let noArgumentsFilter;
this.selector = /** @type {Selector} */ (this.selector.eval(context));
/**
* @param {Node & { matchCondition?: Function }} mixin
* @param {Node[]} mixinPath
*/
},
eval: function (context) {
var mixins;
var mixin;
var mixinPath;
var args = [];
var arg;
var argValue;
var rules = [];
var match = false;
var i;
var m;
var f;
var isRecursive;
var isOneFound;
var candidates = [];
var candidate;
var conditionResult = [];
var defaultResult;
var defFalseEitherCase = -1;
var defNone = 0;
var defTrue = 1;
var defFalse = 2;
var count;
var originalRuleset;
var noArgumentsFilter;
this.selector = this.selector.eval(context);
function calcDefGroup(mixin, mixinPath) {
/** @type {number} */
let f;
/** @type {number} */
let p;
/** @type {Node & { matchCondition?: Function }} */
let namespace;
var f, p, namespace;
for (f = 0; f < 2; f++) {
conditionResult[f] = true;
defaultFunc.value(f);
default_1.default.value(f);
for (p = 0; p < mixinPath.length && conditionResult[f]; p++) {
namespace = mixinPath[p];
if (namespace.matchCondition) {
@@ -137,42 +70,37 @@ class MixinCall extends Node {
return conditionResult[1] ?
defTrue : defFalse;
}
return defNone;
}
return defFalseEitherCase;
}
for (i = 0; i < this.arguments.length; i++) {
arg = this.arguments[i];
argValue = arg.value.eval(context);
if (arg.expand && Array.isArray(argValue.value)) {
const expandedValues = /** @type {Node[]} */ (argValue.value);
for (m = 0; m < expandedValues.length; m++) {
args.push({value: expandedValues[m]});
argValue = argValue.value;
for (m = 0; m < argValue.length; m++) {
args.push({ value: argValue[m] });
}
} else {
args.push({name: arg.name, value: argValue});
}
else {
args.push({ name: arg.name, value: argValue });
}
}
noArgumentsFilter = function(/** @type {MixinSearchFrame} */ rule) {return rule.matchArgs(null, context);};
noArgumentsFilter = function (rule) { return rule.matchArgs(null, context); };
for (i = 0; i < context.frames.length; i++) {
if ((mixins = /** @type {MixinSearchFrame} */ (context.frames[i]).find(this.selector, null, /** @type {(rule: Node) => boolean} */ (/** @type {unknown} */ (noArgumentsFilter)))).length > 0) {
if ((mixins = context.frames[i].find(this.selector, null, noArgumentsFilter)).length > 0) {
isOneFound = true;
// To make `default()` function independent of definition order we have two "subpasses" here.
// At first we evaluate each guard *twice* (with `default() == true` and `default() == false`),
// and build candidate list with corresponding flags. Then, when we know all possible matches,
// we make a final decision.
for (m = 0; m < mixins.length; m++) {
mixin = mixins[m].rule;
mixinPath = mixins[m].path;
isRecursive = false;
for (f = 0; f < context.frames.length; f++) {
if ((!(mixin instanceof MixinDefinition)) && mixin === (/** @type {Node & { originalRuleset?: Node }} */ (context.frames[f]).originalRuleset || context.frames[f])) {
if ((!(mixin instanceof mixin_definition_1.default)) && mixin === (context.frames[f].originalRuleset || context.frames[f])) {
isRecursive = true;
break;
}
@@ -180,100 +108,89 @@ class MixinCall extends Node {
if (isRecursive) {
continue;
}
if (mixin.matchArgs(args, context)) {
candidate = {mixin, group: calcDefGroup(mixin, mixinPath)};
if (/** @type {{ mixin: Node, group: number }} */ (candidate).group !== defFalseEitherCase) {
candidates.push(/** @type {{ mixin: Node & { rules?: Node[], originalRuleset?: Node, matchArgs: Function, matchCondition?: Function, evalCall?: Function }, group: number }} */ (candidate));
candidate = { mixin: mixin, group: calcDefGroup(mixin, mixinPath) };
if (candidate.group !== defFalseEitherCase) {
candidates.push(candidate);
}
match = true;
}
}
defaultFunc.reset();
default_1.default.reset();
count = [0, 0, 0];
for (m = 0; m < candidates.length; m++) {
count[candidates[m].group]++;
}
if (count[defNone] > 0) {
defaultResult = defFalse;
} else {
}
else {
defaultResult = defTrue;
if ((count[defTrue] + count[defFalse]) > 1) {
throw { type: 'Runtime',
message: `Ambiguous use of \`default()\` found when matching for \`${this.format(args)}\``,
message: "Ambiguous use of `default()` found when matching for `".concat(this.format(args), "`"),
index: this.getIndex(), filename: this.fileInfo().filename };
}
}
for (m = 0; m < candidates.length; m++) {
candidate = candidates[m].group;
if ((candidate === defNone) || (candidate === defaultResult)) {
try {
mixin = candidates[m].mixin;
if (!(mixin instanceof MixinDefinition)) {
originalRuleset = /** @type {Node & { originalRuleset?: Node }} */ (mixin).originalRuleset || mixin;
mixin = new MixinDefinition('', [], mixin.rules, null, false, null, originalRuleset.visibilityInfo());
/** @type {Node & { originalRuleset?: Node }} */ (mixin).originalRuleset = originalRuleset;
if (!(mixin instanceof mixin_definition_1.default)) {
originalRuleset = mixin.originalRuleset || mixin;
mixin = new mixin_definition_1.default('', [], mixin.rules, null, false, null, originalRuleset.visibilityInfo());
mixin.originalRuleset = originalRuleset;
}
const newRules = /** @type {MixinDefinition} */ (mixin).evalCall(context, args, this.important).rules;
var newRules = mixin.evalCall(context, args, this.important).rules;
this._setVisibilityToReplacement(newRules);
Array.prototype.push.apply(rules, newRules);
} catch (e) {
throw { .../** @type {object} */ (e), index: this.getIndex(), filename: this.fileInfo().filename };
}
catch (e) {
throw { message: e.message, index: this.getIndex(), filename: this.fileInfo().filename, stack: e.stack };
}
}
}
if (match) {
return /** @type {Node} */ (/** @type {unknown} */ (rules));
return rules;
}
}
}
if (isOneFound) {
throw { type: 'Runtime',
message: `No matching definition was found for \`${this.format(args)}\``,
index: this.getIndex(), filename: this.fileInfo().filename };
} else {
throw { type: 'Name',
message: `${this.selector.toCSS(/** @type {EvalContext} */ ({})).trim()} is undefined`,
index: this.getIndex(), filename: this.fileInfo().filename };
throw { type: 'Runtime',
message: "No matching definition was found for `".concat(this.format(args), "`"),
index: this.getIndex(), filename: this.fileInfo().filename };
}
}
/** @param {Node[]} replacement */
_setVisibilityToReplacement(replacement) {
/** @type {number} */
let i;
/** @type {Node} */
let rule;
else {
throw { type: 'Name',
message: "".concat(this.selector.toCSS().trim(), " is undefined"),
index: this.getIndex(), filename: this.fileInfo().filename };
}
},
_setVisibilityToReplacement: function (replacement) {
var i, rule;
if (this.blocksVisibility()) {
for (i = 0; i < replacement.length; i++) {
rule = replacement[i];
rule.addVisibilityBlock();
}
}
}
/** @param {MixinArg[]} args */
format(args) {
return `${this.selector.toCSS(/** @type {EvalContext} */ ({})).trim()}(${args ? args.map(function (/** @type {MixinArg} */ a) {
let argValue = '';
},
format: function (args) {
return "".concat(this.selector.toCSS().trim(), "(").concat(args ? args.map(function (a) {
var argValue = '';
if (a.name) {
argValue += `${a.name}:`;
argValue += "".concat(a.name, ":");
}
if (a.value.toCSS) {
argValue += a.value.toCSS(/** @type {EvalContext} */ ({}));
} else {
argValue += a.value.toCSS();
}
else {
argValue += '???';
}
return argValue;
}).join(', ') : ''})`;
}).join(', ') : '', ")");
}
}
export default MixinCall;
});
exports.default = MixinCall;
//# sourceMappingURL=mixin-call.js.map
+118 -212
View File
@@ -1,130 +1,70 @@
// @ts-check
/** @import { EvalContext, TreeVisitor, VisibilityInfo } from './node.js' */
/** @import { FunctionRegistry } from './nested-at-rule.js' */
/** @import { MixinArg } from './mixin-call.js' */
import Node from './node.js';
import Selector from './selector.js';
import Element from './element.js';
import Ruleset from './ruleset.js';
import Declaration from './declaration.js';
import DetachedRuleset from './detached-ruleset.js';
import Expression from './expression.js';
import contexts from '../contexts.js';
import * as utils from '../utils.js';
/**
* @typedef {object} MixinParam
* @property {string} [name]
* @property {Node} [value]
* @property {boolean} [variadic]
*/
/**
* @typedef {Ruleset & {
* functionRegistry?: FunctionRegistry,
* originalRuleset?: Node
* }} RulesetWithRegistry
*/
class Definition extends Ruleset {
get type() { return 'MixinDefinition'; }
/**
* @param {string | undefined} name
* @param {MixinParam[]} params
* @param {Node[]} rules
* @param {Node | null} [condition]
* @param {boolean} [variadic]
* @param {Node[] | null} [frames]
* @param {VisibilityInfo} [visibilityInfo]
*/
constructor(name, params, rules, condition, variadic, frames, visibilityInfo) {
super(null, null);
/** @type {string} */
this.name = name || 'anonymous mixin';
this.selectors = [new Selector([new Element(null, name, false, this._index, this._fileInfo)])];
/** @type {MixinParam[]} */
this.params = params;
/** @type {Node | null | undefined} */
this.condition = condition;
/** @type {boolean | undefined} */
this.variadic = variadic;
/** @type {number} */
this.arity = params.length;
this.rules = rules;
this._lookups = {};
/** @type {string[]} */
const optionalParameters = [];
/** @type {number} */
this.required = params.reduce(function (/** @type {number} */ count, /** @type {MixinParam} */ p) {
if (!p.name || (p.name && !p.value)) {
return count + 1;
}
else {
optionalParameters.push(p.name);
return count;
}
}, 0);
/** @type {string[]} */
this.optionalParameters = optionalParameters;
/** @type {Node[] | null | undefined} */
this.frames = frames;
this.copyVisibilityInfo(visibilityInfo);
this.allowRoot = true;
/** @type {boolean} */
this.evalFirst = true;
}
/** @param {TreeVisitor} visitor */
accept(visitor) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var tslib_1 = require("tslib");
var selector_1 = tslib_1.__importDefault(require("./selector"));
var element_1 = tslib_1.__importDefault(require("./element"));
var ruleset_1 = tslib_1.__importDefault(require("./ruleset"));
var declaration_1 = tslib_1.__importDefault(require("./declaration"));
var detached_ruleset_1 = tslib_1.__importDefault(require("./detached-ruleset"));
var expression_1 = tslib_1.__importDefault(require("./expression"));
var contexts_1 = tslib_1.__importDefault(require("../contexts"));
var utils = tslib_1.__importStar(require("../utils"));
var Definition = function (name, params, rules, condition, variadic, frames, visibilityInfo) {
this.name = name || 'anonymous mixin';
this.selectors = [new selector_1.default([new element_1.default(null, name, false, this._index, this._fileInfo)])];
this.params = params;
this.condition = condition;
this.variadic = variadic;
this.arity = params.length;
this.rules = rules;
this._lookups = {};
var optionalParameters = [];
this.required = params.reduce(function (count, p) {
if (!p.name || (p.name && !p.value)) {
return count + 1;
}
else {
optionalParameters.push(p.name);
return count;
}
}, 0);
this.optionalParameters = optionalParameters;
this.frames = frames;
this.copyVisibilityInfo(visibilityInfo);
this.allowRoot = true;
};
Definition.prototype = Object.assign(new ruleset_1.default(), {
type: 'MixinDefinition',
evalFirst: true,
accept: function (visitor) {
if (this.params && this.params.length) {
this.params = /** @type {MixinParam[]} */ (/** @type {unknown} */ (visitor.visitArray(/** @type {Node[]} */ (/** @type {unknown} */ (this.params)))));
this.params = visitor.visitArray(this.params);
}
this.rules = visitor.visitArray(this.rules);
if (this.condition) {
this.condition = visitor.visit(this.condition);
}
}
/**
* @param {EvalContext} context
* @param {EvalContext} mixinEnv
* @param {MixinArg[] | null} args
* @param {Node[]} evaldArguments
* @returns {Ruleset}
*/
evalParams(context, mixinEnv, args, evaldArguments) {
},
evalParams: function (context, mixinEnv, args, evaldArguments) {
/* jshint boss:true */
const frame = new Ruleset(null, null);
/** @type {Node[] | undefined} */
let varargs;
/** @type {MixinArg | undefined} */
let arg;
const params = /** @type {MixinParam[]} */ (utils.copyArray(this.params));
/** @type {number} */
let i;
/** @type {number} */
let j;
/** @type {Node | undefined} */
let val;
/** @type {string | undefined} */
let name;
/** @type {boolean} */
let isNamedFound;
/** @type {number} */
let argIndex;
let argsLength = 0;
if (mixinEnv.frames && mixinEnv.frames[0] && /** @type {RulesetWithRegistry} */ (mixinEnv.frames[0]).functionRegistry) {
/** @type {RulesetWithRegistry} */ (frame).functionRegistry = /** @type {FunctionRegistry} */ (/** @type {RulesetWithRegistry} */ (mixinEnv.frames[0]).functionRegistry).inherit();
var frame = new ruleset_1.default(null, null);
var varargs;
var arg;
var params = utils.copyArray(this.params);
var i;
var j;
var val;
var name;
var isNamedFound;
var argIndex;
var argsLength = 0;
if (mixinEnv.frames && mixinEnv.frames[0] && mixinEnv.frames[0].functionRegistry) {
frame.functionRegistry = mixinEnv.frames[0].functionRegistry.inherit();
}
mixinEnv = new contexts.Eval(mixinEnv, /** @type {Node[]} */ ([frame]).concat(/** @type {Node[]} */ (mixinEnv.frames)));
mixinEnv = new contexts_1.default.Eval(mixinEnv, [frame].concat(mixinEnv.frames));
if (args) {
args = /** @type {MixinArg[]} */ (utils.copyArray(args));
args = utils.copyArray(args);
argsLength = args.length;
for (i = 0; i < argsLength; i++) {
arg = args[i];
if (name = (arg && arg.name)) {
@@ -132,7 +72,7 @@ class Definition extends Ruleset {
for (j = 0; j < params.length; j++) {
if (!evaldArguments[j] && name === params[j].name) {
evaldArguments[j] = arg.value.eval(context);
frame.prependRule(new Declaration(name, arg.value.eval(context)));
frame.prependRule(new declaration_1.default(name, arg.value.eval(context)));
isNamedFound = true;
break;
}
@@ -141,47 +81,49 @@ class Definition extends Ruleset {
args.splice(i, 1);
i--;
continue;
} else {
throw { type: 'Runtime', message: `Named argument for ${this.name} ${args[i].name} not found` };
}
else {
throw { type: 'Runtime', message: "Named argument for ".concat(this.name, " ").concat(args[i].name, " not found") };
}
}
}
}
argIndex = 0;
for (i = 0; i < params.length; i++) {
if (evaldArguments[i]) { continue; }
if (evaldArguments[i]) {
continue;
}
arg = args && args[argIndex];
if (name = params[i].name) {
if (params[i].variadic) {
varargs = [];
for (j = argIndex; j < argsLength; j++) {
varargs.push(/** @type {MixinArg[]} */ (args)[j].value.eval(context));
varargs.push(args[j].value.eval(context));
}
frame.prependRule(new Declaration(name, new Expression(varargs).eval(context)));
} else {
frame.prependRule(new declaration_1.default(name, new expression_1.default(varargs).eval(context)));
}
else {
val = arg && arg.value;
if (val) {
// This was a mixin call, pass in a detached ruleset of it's eval'd rules
if (Array.isArray(val)) {
val = /** @type {Node} */ (/** @type {unknown} */ (new DetachedRuleset(new Ruleset(null, /** @type {Node[]} */ (val)))));
val = new detached_ruleset_1.default(new ruleset_1.default('', val));
}
else {
val = val.eval(context);
}
} else if (params[i].value) {
val = /** @type {Node} */ (params[i].value).eval(mixinEnv);
frame.resetCache();
} else {
throw { type: 'Runtime', message: `wrong number of arguments for ${this.name} (${argsLength} for ${this.arity})` };
}
frame.prependRule(new Declaration(name, val));
else if (params[i].value) {
val = params[i].value.eval(mixinEnv);
frame.resetCache();
}
else {
throw { type: 'Runtime', message: "wrong number of arguments for ".concat(this.name, " (").concat(argsLength, " for ").concat(this.arity, ")") };
}
frame.prependRule(new declaration_1.default(name, val));
evaldArguments[i] = val;
}
}
if (params[i].variadic && args) {
for (j = argIndex; j < argsLength; j++) {
evaldArguments[j] = args[j].value.eval(context);
@@ -189,94 +131,59 @@ class Definition extends Ruleset {
}
argIndex++;
}
return frame;
}
/** @returns {Ruleset} */
makeImportant() {
const rules = !this.rules ? this.rules : this.rules.map(function (/** @type {Node & { makeImportant?: (important?: boolean) => Node }} */ r) {
},
makeImportant: function () {
var rules = !this.rules ? this.rules : this.rules.map(function (r) {
if (r.makeImportant) {
return r.makeImportant(true);
} else {
}
else {
return r;
}
});
const result = new Definition(this.name, this.params, rules, this.condition, this.variadic, this.frames);
return /** @type {Ruleset} */ (/** @type {unknown} */ (result));
}
/**
* @param {EvalContext} context
* @returns {Definition}
*/
eval(context) {
var result = new Definition(this.name, this.params, rules, this.condition, this.variadic, this.frames);
return result;
},
eval: function (context) {
return new Definition(this.name, this.params, this.rules, this.condition, this.variadic, this.frames || utils.copyArray(context.frames));
}
/**
* @param {EvalContext} context
* @param {MixinArg[]} args
* @param {string | undefined} important
* @returns {Ruleset}
*/
evalCall(context, args, important) {
/** @type {Node[]} */
const _arguments = [];
const mixinFrames = this.frames ? /** @type {Node[]} */ (this.frames).concat(/** @type {Node[]} */ (context.frames)) : /** @type {Node[]} */ (context.frames);
const frame = this.evalParams(context, new contexts.Eval(context, mixinFrames), args, _arguments);
/** @type {Node[]} */
let rules;
/** @type {Ruleset} */
let ruleset;
frame.prependRule(new Declaration('@arguments', new Expression(_arguments).eval(context)));
},
evalCall: function (context, args, important) {
var _arguments = [];
var mixinFrames = this.frames ? this.frames.concat(context.frames) : context.frames;
var frame = this.evalParams(context, new contexts_1.default.Eval(context, mixinFrames), args, _arguments);
var rules;
var ruleset;
frame.prependRule(new declaration_1.default('@arguments', new expression_1.default(_arguments).eval(context)));
rules = utils.copyArray(this.rules);
ruleset = new Ruleset(null, rules);
/** @type {RulesetWithRegistry} */ (ruleset).originalRuleset = this;
ruleset = /** @type {Ruleset} */ (ruleset.eval(new contexts.Eval(context, /** @type {Node[]} */ ([this, frame]).concat(mixinFrames))));
ruleset = new ruleset_1.default(null, rules);
ruleset.originalRuleset = this;
ruleset = ruleset.eval(new contexts_1.default.Eval(context, [this, frame].concat(mixinFrames)));
if (important) {
ruleset = /** @type {Ruleset} */ (ruleset.makeImportant());
ruleset = ruleset.makeImportant();
}
return ruleset;
}
/**
* @param {MixinArg[] | null} args
* @param {EvalContext} context
* @returns {boolean}
*/
matchCondition(args, context) {
if (this.condition && !this.condition.eval(
new contexts.Eval(context,
/** @type {Node[]} */ ([this.evalParams(context, /* the parameter variables */
new contexts.Eval(context, this.frames ? /** @type {Node[]} */ (this.frames).concat(/** @type {Node[]} */ (context.frames)) : context.frames), args, [])])
.concat(/** @type {Node[]} */ (this.frames || [])) // the parent namespace/mixin frames
.concat(/** @type {Node[]} */ (context.frames))))) { // the current environment frames
},
matchCondition: function (args, context) {
if (this.condition && !this.condition.eval(new contexts_1.default.Eval(context, [this.evalParams(context, /* the parameter variables */ new contexts_1.default.Eval(context, this.frames ? this.frames.concat(context.frames) : context.frames), args, [])]
.concat(this.frames || []) // the parent namespace/mixin frames
.concat(context.frames)))) { // the current environment frames
return false;
}
return true;
}
/**
* @param {MixinArg[] | null} args
* @param {EvalContext} [context]
* @returns {boolean}
*/
matchArgs(args, context) {
const allArgsCnt = (args && args.length) || 0;
let len;
const optionalParameters = this.optionalParameters;
const requiredArgsCnt = !args ? 0 : args.reduce(function (/** @type {number} */ count, /** @type {MixinArg} */ p) {
},
matchArgs: function (args, context) {
var allArgsCnt = (args && args.length) || 0;
var len;
var optionalParameters = this.optionalParameters;
var requiredArgsCnt = !args ? 0 : args.reduce(function (count, p) {
if (optionalParameters.indexOf(p.name) < 0) {
return count + 1;
} else {
}
else {
return count;
}
}, 0);
if (!this.variadic) {
if (requiredArgsCnt < this.required) {
return false;
@@ -284,24 +191,23 @@ class Definition extends Ruleset {
if (allArgsCnt > this.params.length) {
return false;
}
} else {
}
else {
if (requiredArgsCnt < (this.required - 1)) {
return false;
}
}
// check patterns
len = Math.min(requiredArgsCnt, this.arity);
for (let i = 0; i < len; i++) {
for (var i = 0; i < len; i++) {
if (!this.params[i].name && !this.params[i].variadic) {
if (/** @type {MixinArg[]} */ (args)[i].value.eval(context).toCSS(/** @type {EvalContext} */ ({})) != /** @type {Node} */ (this.params[i].value).eval(context).toCSS(/** @type {EvalContext} */ ({}))) {
if (args[i].value.eval(context).toCSS() != this.params[i].value.eval(context).toCSS()) {
return false;
}
}
}
return true;
}
}
export default Definition;
});
exports.default = Definition;
//# sourceMappingURL=mixin-definition.js.map
+44 -63
View File
@@ -1,95 +1,76 @@
// @ts-check
/** @import { EvalContext, FileInfo } from './node.js' */
import Node from './node.js';
import Variable from './variable.js';
import Ruleset from './ruleset.js';
import Selector from './selector.js';
class NamespaceValue extends Node {
get type() { return 'NamespaceValue'; }
/**
* @param {Node} ruleCall
* @param {string[]} lookups
* @param {number} index
* @param {FileInfo} fileInfo
*/
constructor(ruleCall, lookups, index, fileInfo) {
super();
this.value = ruleCall;
this.lookups = lookups;
this._index = index;
this._fileInfo = fileInfo;
}
/**
* @param {EvalContext} context
* @returns {Node}
*/
eval(context) {
let i, name;
/** @type {Ruleset | Node | Node[]} */
let rules = this.value.eval(context);
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var tslib_1 = require("tslib");
var node_1 = tslib_1.__importDefault(require("./node"));
var variable_1 = tslib_1.__importDefault(require("./variable"));
var ruleset_1 = tslib_1.__importDefault(require("./ruleset"));
var selector_1 = tslib_1.__importDefault(require("./selector"));
var NamespaceValue = function (ruleCall, lookups, index, fileInfo) {
this.value = ruleCall;
this.lookups = lookups;
this._index = index;
this._fileInfo = fileInfo;
};
NamespaceValue.prototype = Object.assign(new node_1.default(), {
type: 'NamespaceValue',
eval: function (context) {
var i, name, rules = this.value.eval(context);
for (i = 0; i < this.lookups.length; i++) {
name = this.lookups[i];
/**
* Eval'd DRs return rulesets.
* Eval'd mixins return rules, so let's make a ruleset if we need it.
* We need to do this because of late parsing of values
*/
if (Array.isArray(rules)) {
rules = new Ruleset([new Selector()], rules);
rules = new ruleset_1.default([new selector_1.default()], rules);
}
const rs = /** @type {Ruleset} */ (rules);
if (name === '') {
rules = rs.lastDeclaration();
rules = rules.lastDeclaration();
}
else if (name.charAt(0) === '@') {
if (name.charAt(1) === '@') {
name = `@${new Variable(name.slice(1)).eval(context).value}`;
name = "@".concat(new variable_1.default(name.substr(1)).eval(context).value);
}
if (rs.variables) {
rules = rs.variable(name);
if (rules.variables) {
rules = rules.variable(name);
}
if (!rules) {
throw { type: 'Name',
message: `variable ${name} not found`,
message: "variable ".concat(name, " not found"),
filename: this.fileInfo().filename,
index: this.getIndex() };
}
}
else {
if (name.substring(0, 2) === '$@') {
name = `$${new Variable(name.slice(1)).eval(context).value}`;
name = "$".concat(new variable_1.default(name.substr(1)).eval(context).value);
}
else {
name = name.charAt(0) === '$' ? name : `$${name}`;
name = name.charAt(0) === '$' ? name : "$".concat(name);
}
if (rs.properties) {
rules = rs.property(name);
if (rules.properties) {
rules = rules.property(name);
}
if (!rules) {
throw { type: 'Name',
message: `property "${name.slice(1)}" not found`,
message: "property \"".concat(name.substr(1), "\" not found"),
filename: this.fileInfo().filename,
index: this.getIndex() };
}
const rulesArr = /** @type {Node[]} */ (rules);
rules = rulesArr[rulesArr.length - 1];
// Properties are an array of values, since a ruleset can have multiple props.
// We pick the last one (the "cascaded" value)
rules = rules[rules.length - 1];
}
const current = /** @type {Node} */ (rules);
if (current.value) {
rules = /** @type {Node} */ (current.eval(context).value);
if (rules.value) {
rules = rules.eval(context).value;
}
const currentNode = /** @type {Node & { ruleset?: Node }} */ (rules);
if (currentNode.ruleset) {
rules = currentNode.ruleset.eval(context);
if (rules.ruleset) {
rules = rules.ruleset.eval(context);
}
}
return /** @type {Node} */ (rules);
return rules;
}
}
export default NamespaceValue;
});
exports.default = NamespaceValue;
//# sourceMappingURL=namespace-value.js.map
+21 -34
View File
@@ -1,37 +1,24 @@
// @ts-check
/** @import { EvalContext, CSSOutput } from './node.js' */
import Node from './node.js';
import Operation from './operation.js';
import Dimension from './dimension.js';
class Negative extends Node {
get type() { return 'Negative'; }
/** @param {Node} node */
constructor(node) {
super();
this.value = node;
}
/**
* @param {EvalContext} context
* @param {CSSOutput} output
*/
genCSS(context, output) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var tslib_1 = require("tslib");
var node_1 = tslib_1.__importDefault(require("./node"));
var operation_1 = tslib_1.__importDefault(require("./operation"));
var dimension_1 = tslib_1.__importDefault(require("./dimension"));
var Negative = function (node) {
this.value = node;
};
Negative.prototype = Object.assign(new node_1.default(), {
type: 'Negative',
genCSS: function (context, output) {
output.add('-');
/** @type {Node} */ (this.value).genCSS(context, output);
}
/**
* @param {EvalContext} context
* @returns {Node}
*/
eval(context) {
if (context.isMathOn('*')) {
return (new Operation('*', [new Dimension(-1), /** @type {Node} */ (this.value)], false)).eval(context);
this.value.genCSS(context, output);
},
eval: function (context) {
if (context.isMathOn()) {
return (new operation_1.default('*', [new dimension_1.default(-1), this.value])).eval(context);
}
return new Negative(/** @type {Node} */ (this.value).eval(context));
return new Negative(this.value.eval(context));
}
}
export default Negative;
});
exports.default = Negative;
//# sourceMappingURL=negative.js.map
+66 -149
View File
@@ -1,140 +1,72 @@
// @ts-check
/** @import { EvalContext, CSSOutput, TreeVisitor, FileInfo, VisibilityInfo } from './node.js' */
import Ruleset from './ruleset.js';
import Value from './value.js';
import Selector from './selector.js';
import Anonymous from './anonymous.js';
import Expression from './expression.js';
import * as utils from '../utils.js';
import Node from './node.js';
/**
* @typedef {object} FunctionRegistry
* @property {(name: string, func: Function) => void} add
* @property {(functions: Object) => void} addMultiple
* @property {(name: string) => Function} get
* @property {() => Object} getLocalFunctions
* @property {() => FunctionRegistry} inherit
* @property {(base: FunctionRegistry) => FunctionRegistry} create
*/
/**
* @typedef {Node & {
* features: Value,
* rules: Ruleset[],
* type: string,
* functionRegistry?: FunctionRegistry,
* multiMedia?: boolean,
* debugInfo?: { lineNumber: number, fileName: string },
* allowRoot?: boolean,
* _evaluated?: boolean,
* evalFunction: () => void,
* evalTop: (context: EvalContext) => Node | Ruleset,
* evalNested: (context: EvalContext) => Node | Ruleset,
* permute: (arr: Node[][]) => Node[][],
* bubbleSelectors: (selectors: Selector[] | undefined) => void,
* outputRuleset: (context: EvalContext, output: CSSOutput, rules: Node[]) => void
* }} NestableAtRuleThis
*/
const NestableAtRulePrototype = {
isRulesetLike() {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var tslib_1 = require("tslib");
var ruleset_1 = tslib_1.__importDefault(require("./ruleset"));
var value_1 = tslib_1.__importDefault(require("./value"));
var selector_1 = tslib_1.__importDefault(require("./selector"));
var anonymous_1 = tslib_1.__importDefault(require("./anonymous"));
var expression_1 = tslib_1.__importDefault(require("./expression"));
var utils = tslib_1.__importStar(require("../utils"));
var NestableAtRulePrototype = {
isRulesetLike: function () {
return true;
},
/** @param {TreeVisitor} visitor */
accept(visitor) {
/** @type {NestableAtRuleThis} */
const self = /** @type {NestableAtRuleThis} */ (/** @type {unknown} */ (this));
if (self.features) {
self.features = /** @type {Value} */ (visitor.visit(self.features));
accept: function (visitor) {
if (this.features) {
this.features = visitor.visit(this.features);
}
if (self.rules) {
self.rules = /** @type {Ruleset[]} */ (visitor.visitArray(self.rules));
if (this.rules) {
this.rules = visitor.visitArray(this.rules);
}
},
evalFunction: function () {
/** @type {NestableAtRuleThis} */
const self = /** @type {NestableAtRuleThis} */ (/** @type {unknown} */ (this));
if (!self.features || !Array.isArray(self.features.value) || self.features.value.length < 1) {
if (!this.features || !Array.isArray(this.features.value) || this.features.value.length < 1) {
return;
}
const exprValues = /** @type {Node[]} */ (self.features.value);
/** @type {Node | undefined} */
let expr;
/** @type {Node | undefined} */
let paren;
for (let index = 0; index < exprValues.length; ++index) {
var exprValues = this.features.value;
var expr, paren;
for (var index = 0; index < exprValues.length; ++index) {
expr = exprValues[index];
if ((expr.type === 'Keyword' || expr.type === 'Variable')
&& index + 1 < exprValues.length
&& (/** @type {Node & { noSpacing?: boolean }} */ (expr).noSpacing || /** @type {Node & { noSpacing?: boolean }} */ (expr).noSpacing == null)) {
paren = exprValues[index + 1];
if (paren.type === 'Paren' && /** @type {Node & { noSpacing?: boolean }} */ (paren).noSpacing) {
exprValues[index]= new Expression([expr, paren]);
if (expr.type === 'Keyword' && index + 1 < exprValues.length && (expr.noSpacing || expr.noSpacing == null)) {
paren = exprValues[index + 1];
if (paren.type === 'Paren' && paren.noSpacing) {
exprValues[index] = new expression_1.default([expr, paren]);
exprValues.splice(index + 1, 1);
/** @type {Node & { noSpacing?: boolean }} */ (exprValues[index]).noSpacing = true;
exprValues[index].noSpacing = true;
}
}
}
},
/** @param {EvalContext} context */
evalTop(context) {
/** @type {NestableAtRuleThis} */
const self = /** @type {NestableAtRuleThis} */ (/** @type {unknown} */ (this));
self.evalFunction();
/** @type {Node | Ruleset} */
let result = self;
evalTop: function (context) {
this.evalFunction();
var result = this;
// Render all dependent Media blocks.
if (context.mediaBlocks.length > 1) {
const selectors = (new Selector([], null, null, self.getIndex(), self.fileInfo())).createEmptySelectors();
result = new Ruleset(selectors, context.mediaBlocks);
/** @type {Ruleset & { multiMedia?: boolean }} */ (result).multiMedia = true;
result.copyVisibilityInfo(self.visibilityInfo());
self.setParent(result, self);
var selectors = (new selector_1.default([], null, null, this.getIndex(), this.fileInfo())).createEmptySelectors();
result = new ruleset_1.default(selectors, context.mediaBlocks);
result.multiMedia = true;
result.copyVisibilityInfo(this.visibilityInfo());
this.setParent(result, this);
}
delete context.mediaBlocks;
delete context.mediaPath;
return result;
},
/** @param {EvalContext} context */
evalNested(context) {
/** @type {NestableAtRuleThis} */
const self = /** @type {NestableAtRuleThis} */ (/** @type {unknown} */ (this));
self.evalFunction();
let i;
/** @type {Node | Node[]} */
let value;
const path = context.mediaPath.concat([self]);
evalNested: function (context) {
this.evalFunction();
var i;
var value;
var path = context.mediaPath.concat([this]);
// Extract the media-query conditions separated with `,` (OR).
for (i = 0; i < path.length; i++) {
if (path[i].type !== self.type) {
const blockIndex = context.mediaBlocks.indexOf(self);
if (blockIndex > -1) {
context.mediaBlocks.splice(blockIndex, 1);
}
return self;
if (path[i].type !== this.type) {
context.mediaBlocks.splice(i, 1);
return this;
}
value = /** @type {NestableAtRuleThis} */ (path[i]).features instanceof Value ?
/** @type {Node[]} */ (/** @type {NestableAtRuleThis} */ (path[i]).features.value) : /** @type {NestableAtRuleThis} */ (path[i]).features;
path[i] = /** @type {Node} */ (/** @type {unknown} */ (Array.isArray(value) ? value : [value]));
value = path[i].features instanceof value_1.default ?
path[i].features.value : path[i].features;
path[i] = Array.isArray(value) ? value : [value];
}
// Trace all permutations to generate the resulting media-query.
//
// (a, b and c) with nested (d, e) ->
@@ -142,57 +74,42 @@ const NestableAtRulePrototype = {
// a and e
// b and c and d
// b and c and e
self.features = new Value(self.permute(/** @type {Node[][]} */ (/** @type {unknown} */ (path))).map(
/** @param {Node | Node[]} path */
path => {
path = /** @type {Node[]} */ (path).map(
/** @param {Node & { toCSS?: Function }} fragment */
fragment => fragment.toCSS ? fragment : new Anonymous(/** @type {string} */ (/** @type {unknown} */ (fragment))));
for (i = /** @type {Node[]} */ (path).length - 1; i > 0; i--) {
/** @type {Node[]} */ (path).splice(i, 0, new Anonymous('and'));
this.features = new value_1.default(this.permute(path).map(function (path) {
path = path.map(function (fragment) { return fragment.toCSS ? fragment : new anonymous_1.default(fragment); });
for (i = path.length - 1; i > 0; i--) {
path.splice(i, 0, new anonymous_1.default('and'));
}
return new Expression(/** @type {Node[]} */ (path));
return new expression_1.default(path);
}));
self.setParent(self.features, self);
this.setParent(this.features, this);
// Fake a tree-node that doesn't output anything.
return new Ruleset([], []);
return new ruleset_1.default([], []);
},
/**
* @param {Node[][]} arr
* @returns {Node[][]}
*/
permute(arr) {
permute: function (arr) {
if (arr.length === 0) {
return [];
} else if (arr.length === 1) {
return /** @type {Node[][]} */ (/** @type {unknown} */ (arr[0]));
} else {
/** @type {Node[][]} */
const result = [];
const rest = this.permute(arr.slice(1));
for (let i = 0; i < rest.length; i++) {
for (let j = 0; j < arr[0].length; j++) {
}
else if (arr.length === 1) {
return arr[0];
}
else {
var result = [];
var rest = this.permute(arr.slice(1));
for (var i = 0; i < rest.length; i++) {
for (var j = 0; j < arr[0].length; j++) {
result.push([arr[0][j]].concat(rest[i]));
}
}
return result;
}
},
/** @param {Selector[] | undefined} selectors */
bubbleSelectors(selectors) {
/** @type {NestableAtRuleThis} */
const self = /** @type {NestableAtRuleThis} */ (/** @type {unknown} */ (this));
bubbleSelectors: function (selectors) {
if (!selectors) {
return;
}
self.rules = [new Ruleset(utils.copyArray(selectors), [self.rules[0]])];
self.setParent(self.rules, self);
this.rules = [new ruleset_1.default(utils.copyArray(selectors), [this.rules[0]])];
this.setParent(this.rules, this);
}
};
export default NestableAtRulePrototype;
exports.default = NestableAtRulePrototype;
//# sourceMappingURL=nested-at-rule.js.map
+90 -225
View File
@@ -1,108 +1,34 @@
// @ts-check
/**
* @typedef {object} FileInfo
* @property {string} [filename]
* @property {string} [rootpath]
* @property {string} [currentDirectory]
* @property {string} [rootFilename]
* @property {string} [entryPath]
* @property {boolean} [reference]
*/
/**
* @typedef {object} VisibilityInfo
* @property {number} [visibilityBlocks]
* @property {boolean} [nodeVisible]
*/
/**
* @typedef {object} CSSOutput
* @property {(chunk: string, fileInfo?: FileInfo, index?: number, mapLines?: boolean) => void} add
* @property {() => boolean} isEmpty
*/
/**
* @typedef {object} EvalContext
* @property {number} [numPrecision]
* @property {(op?: string) => boolean} [isMathOn]
* @property {number} [math]
* @property {Node[]} [frames]
* @property {Array<{important?: string}>} [importantScope]
* @property {string[]} [paths]
* @property {boolean} [compress]
* @property {boolean} [strictUnits]
* @property {boolean} [sourceMap]
* @property {boolean} [importMultiple]
* @property {string} [urlArgs]
* @property {boolean} [javascriptEnabled]
* @property {object} [pluginManager]
* @property {number} [rewriteUrls]
* @property {boolean} [inCalc]
* @property {boolean} [mathOn]
* @property {boolean[]} [calcStack]
* @property {boolean[]} [parensStack]
* @property {Node[]} [mediaBlocks]
* @property {Node[]} [mediaPath]
* @property {() => void} [inParenthesis]
* @property {() => void} [outOfParenthesis]
* @property {() => void} [enterCalc]
* @property {() => void} [exitCalc]
* @property {(path: string) => boolean} [pathRequiresRewrite]
* @property {(path: string, rootpath?: string) => string} [rewritePath]
* @property {(path: string) => string} [normalizePath]
* @property {number} [tabLevel]
* @property {boolean} [lastRule]
*/
/**
* @typedef {object} TreeVisitor
* @property {(node: Node) => Node} visit
* @property {(nodes: Node[], nonReplacing?: boolean) => Node[]} visitArray
*/
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
/**
* The reason why Node is a class and other nodes simply do not extend
* from Node (since we're transpiling) is due to this issue:
*
* @see https://github.com/less/less.js/issues/3434
*/
class Node {
get type() { return ''; }
constructor() {
/** @type {Node | null} */
var Node = /** @class */ (function () {
function Node() {
this.parent = null;
/** @type {number | undefined} */
this.visibilityBlocks = undefined;
/** @type {boolean | undefined} */
this.nodeVisible = undefined;
/** @type {Node | null} */
this.rootNode = null;
/** @type {Node | null} */
this.parsed = null;
/** @type {Node | Node[] | string | number | undefined} */
this.value = undefined;
/** @type {number | undefined} */
this._index = undefined;
/** @type {FileInfo | undefined} */
this._fileInfo = undefined;
}
get currentFileInfo() {
return this.fileInfo();
}
get index() {
return this.getIndex();
}
/**
* @param {Node | Node[]} nodes
* @param {Node} parent
*/
setParent(nodes, parent) {
/** @param {Node} node */
Object.defineProperty(Node.prototype, "currentFileInfo", {
get: function () {
return this.fileInfo();
},
enumerable: false,
configurable: true
});
Object.defineProperty(Node.prototype, "index", {
get: function () {
return this.getIndex();
},
enumerable: false,
configurable: true
});
Node.prototype.setParent = function (nodes, parent) {
function set(node) {
if (node && node instanceof Node) {
node.parent = parent;
@@ -114,30 +40,20 @@ class Node {
else {
set(nodes);
}
}
/** @returns {number} */
getIndex() {
};
Node.prototype.getIndex = function () {
return this._index || (this.parent && this.parent.getIndex()) || 0;
}
/** @returns {FileInfo} */
fileInfo() {
};
Node.prototype.fileInfo = function () {
return this._fileInfo || (this.parent && this.parent.fileInfo()) || {};
}
/** @returns {boolean} */
isRulesetLike() { return false; }
/**
* @param {EvalContext} context
* @returns {string}
*/
toCSS(context) {
/** @type {string[]} */
const strs = [];
};
Node.prototype.isRulesetLike = function () { return false; };
Node.prototype.toCSS = function (context) {
var strs = [];
this.genCSS(context, {
add: function(chunk, fileInfo, index) {
// remove when genCSS has JSDoc types
// eslint-disable-next-line no-unused-vars
add: function (chunk, fileInfo, index) {
strs.push(chunk);
},
isEmpty: function () {
@@ -145,166 +61,115 @@ class Node {
}
});
return strs.join('');
}
/**
* @param {EvalContext} context
* @param {CSSOutput} output
*/
genCSS(context, output) {
output.add(/** @type {string} */ (this.value));
}
/**
* @param {TreeVisitor} visitor
*/
accept(visitor) {
this.value = visitor.visit(/** @type {Node} */ (this.value));
}
/**
* @param {EvalContext} [context]
* @returns {Node}
*/
eval(context) { return this; }
/**
* @param {EvalContext} context
* @param {string} op
* @param {number} a
* @param {number} b
* @returns {number | undefined}
*/
_operate(context, op, a, b) {
};
Node.prototype.genCSS = function (context, output) {
output.add(this.value);
};
Node.prototype.accept = function (visitor) {
this.value = visitor.visit(this.value);
};
Node.prototype.eval = function () { return this; };
Node.prototype._operate = function (context, op, a, b) {
switch (op) {
case '+': return a + b;
case '-': return a - b;
case '*': return a * b;
case '/': return a / b;
}
}
/**
* @param {EvalContext} context
* @param {number} value
* @returns {number}
*/
fround(context, value) {
const precision = context && context.numPrecision;
};
Node.prototype.fround = function (context, value) {
var precision = context && context.numPrecision;
// add "epsilon" to ensure numbers like 1.000000005 (represented as 1.000000004999...) are properly rounded:
return (precision) ? Number((value + 2e-16).toFixed(precision)) : value;
}
/**
* @param {Node & { compare?: (other: Node) => number | undefined }} a
* @param {Node & { compare?: (other: Node) => number | undefined }} b
* @returns {number | undefined}
*/
static compare(a, b) {
};
Node.compare = function (a, b) {
/* returns:
-1: a < b
0: a = b
1: a > b
and *any* other value for a != b (e.g. undefined, NaN, -2 etc.) */
if ((a.compare) &&
// for "symmetric results" force toCSS-based comparison
// of Quoted or Anonymous if either value is one of those
!(b.type === 'Quoted' || b.type === 'Anonymous')) {
return a.compare(b);
} else if (b.compare) {
}
else if (b.compare) {
return -b.compare(a);
} else if (a.type !== b.type) {
}
else if (a.type !== b.type) {
return undefined;
}
let aVal = a.value;
let bVal = b.value;
if (!Array.isArray(aVal)) {
return aVal === bVal ? 0 : undefined;
a = a.value;
b = b.value;
if (!Array.isArray(a)) {
return a === b ? 0 : undefined;
}
if (!Array.isArray(bVal)) {
if (a.length !== b.length) {
return undefined;
}
if (aVal.length !== bVal.length) {
return undefined;
}
for (let i = 0; i < aVal.length; i++) {
if (Node.compare(aVal[i], bVal[i]) !== 0) {
for (var i = 0; i < a.length; i++) {
if (Node.compare(a[i], b[i]) !== 0) {
return undefined;
}
}
return 0;
}
/**
* @param {number | string} a
* @param {number | string} b
* @returns {number | undefined}
*/
static numericCompare(a, b) {
return a < b ? -1
: a === b ? 0
: a > b ? 1 : undefined;
}
/** @returns {boolean} */
blocksVisibility() {
};
Node.numericCompare = function (a, b) {
return a < b ? -1
: a === b ? 0
: a > b ? 1 : undefined;
};
// Returns true if this node represents root of ast imported by reference
Node.prototype.blocksVisibility = function () {
if (this.visibilityBlocks === undefined) {
this.visibilityBlocks = 0;
}
return this.visibilityBlocks !== 0;
}
addVisibilityBlock() {
};
Node.prototype.addVisibilityBlock = function () {
if (this.visibilityBlocks === undefined) {
this.visibilityBlocks = 0;
}
this.visibilityBlocks = this.visibilityBlocks + 1;
}
removeVisibilityBlock() {
};
Node.prototype.removeVisibilityBlock = function () {
if (this.visibilityBlocks === undefined) {
this.visibilityBlocks = 0;
}
this.visibilityBlocks = this.visibilityBlocks - 1;
}
ensureVisibility() {
};
// Turns on node visibility - if called node will be shown in output regardless
// of whether it comes from import by reference or not
Node.prototype.ensureVisibility = function () {
this.nodeVisible = true;
}
ensureInvisibility() {
};
// Turns off node visibility - if called node will NOT be shown in output regardless
// of whether it comes from import by reference or not
Node.prototype.ensureInvisibility = function () {
this.nodeVisible = false;
}
/** @returns {boolean | undefined} */
isVisible() {
};
// return values:
// false - the node must not be visible
// true - the node must be visible
// undefined or null - the node has the same visibility as its parent
Node.prototype.isVisible = function () {
return this.nodeVisible;
}
/** @returns {VisibilityInfo} */
visibilityInfo() {
};
Node.prototype.visibilityInfo = function () {
return {
visibilityBlocks: this.visibilityBlocks,
nodeVisible: this.nodeVisible
};
}
/** @param {VisibilityInfo} info */
copyVisibilityInfo(info) {
};
Node.prototype.copyVisibilityInfo = function (info) {
if (!info) {
return;
}
this.visibilityBlocks = info.visibilityBlocks;
this.nodeVisible = info.nodeVisible;
}
}
/**
* Set by the parser at runtime on Node.prototype.
* @type {{ context: EvalContext, importManager: object, imports: object } | undefined}
*/
Node.prototype.parse = undefined;
export default Node;
};
return Node;
}());
exports.default = Node;
//# sourceMappingURL=node.js.map
+34 -59
View File
@@ -1,71 +1,46 @@
// @ts-check
/** @import { EvalContext, CSSOutput, TreeVisitor } from './node.js' */
import Node from './node.js';
import Color from './color.js';
import Dimension from './dimension.js';
import * as Constants from '../constants.js';
const MATH = Constants.Math;
class Operation extends Node {
get type() { return 'Operation'; }
/**
* @param {string} op
* @param {Node[]} operands
* @param {boolean} isSpaced
*/
constructor(op, operands, isSpaced) {
super();
this.op = op.trim();
this.operands = operands;
this.isSpaced = isSpaced;
}
/** @param {TreeVisitor} visitor */
accept(visitor) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var tslib_1 = require("tslib");
var node_1 = tslib_1.__importDefault(require("./node"));
var color_1 = tslib_1.__importDefault(require("./color"));
var dimension_1 = tslib_1.__importDefault(require("./dimension"));
var Constants = tslib_1.__importStar(require("../constants"));
var MATH = Constants.Math;
var Operation = function (op, operands, isSpaced) {
this.op = op.trim();
this.operands = operands;
this.isSpaced = isSpaced;
};
Operation.prototype = Object.assign(new node_1.default(), {
type: 'Operation',
accept: function (visitor) {
this.operands = visitor.visitArray(this.operands);
}
/**
* @param {EvalContext} context
* @returns {Node}
*/
eval(context) {
let a = this.operands[0].eval(context), b = this.operands[1].eval(context), op;
},
eval: function (context) {
var a = this.operands[0].eval(context), b = this.operands[1].eval(context), op;
if (context.isMathOn(this.op)) {
op = this.op === './' ? '/' : this.op;
if (a instanceof Dimension && b instanceof Color) {
a = /** @type {Dimension} */ (a).toColor();
if (a instanceof dimension_1.default && b instanceof color_1.default) {
a = a.toColor();
}
if (b instanceof Dimension && a instanceof Color) {
b = /** @type {Dimension} */ (b).toColor();
if (b instanceof dimension_1.default && a instanceof color_1.default) {
b = b.toColor();
}
if (!/** @type {Dimension | Color} */ (a).operate || !/** @type {Dimension | Color} */ (b).operate) {
if (
(a instanceof Operation || b instanceof Operation)
&& /** @type {Operation} */ (a).op === '/' && context.math === MATH.PARENS_DIVISION
) {
if (!a.operate || !b.operate) {
if ((a instanceof Operation || b instanceof Operation)
&& a.op === '/' && context.math === MATH.PARENS_DIVISION) {
return new Operation(this.op, [a, b], this.isSpaced);
}
throw { type: 'Operation',
message: 'Operation on an invalid type' };
}
if (a instanceof Dimension) {
return a.operate(context, op, /** @type {Dimension} */ (b));
}
return /** @type {Color} */ (a).operate(context, op, /** @type {Color} */ (b));
} else {
return a.operate(context, op, b);
}
else {
return new Operation(this.op, [a, b], this.isSpaced);
}
}
/**
* @param {EvalContext} context
* @param {CSSOutput} output
*/
genCSS(context, output) {
},
genCSS: function (context, output) {
this.operands[0].genCSS(context, output);
if (this.isSpaced) {
output.add(' ');
@@ -76,6 +51,6 @@ class Operation extends Node {
}
this.operands[1].genCSS(context, output);
}
}
export default Operation;
});
exports.default = Operation;
//# sourceMappingURL=operation.js.map
+17 -34
View File
@@ -1,41 +1,24 @@
// @ts-check
/** @import { EvalContext, CSSOutput } from './node.js' */
import Node from './node.js';
class Paren extends Node {
get type() { return 'Paren'; }
/** @param {Node} node */
constructor(node) {
super();
this.value = node;
/** @type {boolean | undefined} */
this.noSpacing = undefined;
}
/**
* @param {EvalContext} context
* @param {CSSOutput} output
*/
genCSS(context, output) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var tslib_1 = require("tslib");
var node_1 = tslib_1.__importDefault(require("./node"));
var Paren = function (node) {
this.value = node;
};
Paren.prototype = Object.assign(new node_1.default(), {
type: 'Paren',
genCSS: function (context, output) {
output.add('(');
/** @type {Node} */ (this.value).genCSS(context, output);
this.value.genCSS(context, output);
output.add(')');
}
/**
* @param {EvalContext} context
* @returns {Paren}
*/
eval(context) {
const paren = new Paren(/** @type {Node} */ (this.value).eval(context));
},
eval: function (context) {
var paren = new Paren(this.value.eval(context));
if (this.noSpacing) {
paren.noSpacing = true;
}
return paren;
}
}
export default Paren;
});
exports.default = Paren;
//# sourceMappingURL=paren.js.map
+35 -66
View File
@@ -1,67 +1,39 @@
// @ts-check
/** @import { EvalContext, FileInfo } from './node.js' */
import Node from './node.js';
import Declaration from './declaration.js';
import Ruleset from './ruleset.js';
class Property extends Node {
get type() { return 'Property'; }
/**
* @param {string} name
* @param {number} index
* @param {FileInfo} currentFileInfo
*/
constructor(name, index, currentFileInfo) {
super();
this.name = name;
this._index = index;
this._fileInfo = currentFileInfo;
/** @type {boolean | undefined} */
this.evaluating = undefined;
}
/**
* @param {EvalContext} context
* @returns {Node}
*/
eval(context) {
let property;
const name = this.name;
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var tslib_1 = require("tslib");
var node_1 = tslib_1.__importDefault(require("./node"));
var declaration_1 = tslib_1.__importDefault(require("./declaration"));
var Property = function (name, index, currentFileInfo) {
this.name = name;
this._index = index;
this._fileInfo = currentFileInfo;
};
Property.prototype = Object.assign(new node_1.default(), {
type: 'Property',
eval: function (context) {
var property;
var name = this.name;
// TODO: shorten this reference
const mergeRules = /** @type {{ less: { visitors: { ToCSSVisitor: { prototype: { _mergeRules: (rules: Declaration[]) => void } } } } }} */ (context.pluginManager).less.visitors.ToCSSVisitor.prototype._mergeRules;
var mergeRules = context.pluginManager.less.visitors.ToCSSVisitor.prototype._mergeRules;
if (this.evaluating) {
throw { type: 'Name',
message: `Recursive property reference for ${name}`,
message: "Recursive property reference for ".concat(name),
filename: this.fileInfo().filename,
index: this.getIndex() };
}
this.evaluating = true;
property = this.find(context.frames, function (/** @type {Node} */ frame) {
let v;
const vArr = /** @type {Ruleset} */ (frame).property(name);
property = this.find(context.frames, function (frame) {
var v;
var vArr = frame.property(name);
if (vArr) {
for (let i = 0; i < vArr.length; i++) {
for (var i = 0; i < vArr.length; i++) {
v = vArr[i];
vArr[i] = new Declaration(v.name,
v.value,
v.important,
v.merge,
v.index,
v.currentFileInfo,
v.inline,
v.variable
);
vArr[i] = new declaration_1.default(v.name, v.value, v.important, v.merge, v.index, v.currentFileInfo, v.inline, v.variable);
}
mergeRules(vArr);
v = vArr[vArr.length - 1];
if (v.important) {
const importantScope = context.importantScope[context.importantScope.length - 1];
var importantScope = context.importantScope[context.importantScope.length - 1];
importantScope.important = v.important;
}
v = v.value.eval(context);
@@ -71,26 +43,23 @@ class Property extends Node {
if (property) {
this.evaluating = false;
return property;
} else {
}
else {
throw { type: 'Name',
message: `Property '${name}' is undefined`,
message: "Property '".concat(name, "' is undefined"),
filename: this.currentFileInfo.filename,
index: this.index };
}
}
/**
* @param {Node[]} obj
* @param {(frame: Node) => Node | undefined} fun
* @returns {Node | null}
*/
find(obj, fun) {
for (let i = 0, r; i < obj.length; i++) {
},
find: function (obj, fun) {
for (var i = 0, r = void 0; i < obj.length; i++) {
r = fun.call(obj, obj[i]);
if (r) { return r; }
if (r) {
return r;
}
}
return null;
}
}
export default Property;
});
exports.default = Property;
//# sourceMappingURL=property.js.map
+60 -52
View File
@@ -1,64 +1,72 @@
// @ts-check
/** @import { EvalContext, CSSOutput, TreeVisitor } from './node.js' */
import Node from './node.js';
class QueryInParens extends Node {
get type() { return 'QueryInParens'; }
/**
* @param {string} op
* @param {Node} l
* @param {Node} m
* @param {string | null} op2
* @param {Node | null} r
* @param {number} i
*/
constructor(op, l, m, op2, r, i) {
super();
this.op = op.trim();
this.lvalue = l;
this.mvalue = m;
this.op2 = op2 ? op2.trim() : null;
/** @type {Node | null} */
this.rvalue = r;
this._index = i;
}
/** @param {TreeVisitor} visitor */
accept(visitor) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var tslib_1 = require("tslib");
var copy_anything_1 = require("copy-anything");
var declaration_1 = tslib_1.__importDefault(require("./declaration"));
var node_1 = tslib_1.__importDefault(require("./node"));
var QueryInParens = function (op, l, m, op2, r, i) {
this.op = op.trim();
this.lvalue = l;
this.mvalue = m;
this.op2 = op2 ? op2.trim() : null;
this.rvalue = r;
this._index = i;
this.mvalues = [];
};
QueryInParens.prototype = Object.assign(new node_1.default(), {
type: 'QueryInParens',
accept: function (visitor) {
this.lvalue = visitor.visit(this.lvalue);
this.mvalue = visitor.visit(this.mvalue);
if (this.rvalue) {
this.rvalue = visitor.visit(this.rvalue);
}
}
/** @param {EvalContext} context */
eval(context) {
const node = new QueryInParens(
this.op,
this.lvalue.eval(context),
this.mvalue.eval(context),
this.op2,
this.rvalue ? this.rvalue.eval(context) : null,
this._index || 0
);
return node;
}
/**
* @param {EvalContext} context
* @param {CSSOutput} output
*/
genCSS(context, output) {
},
eval: function (context) {
this.lvalue = this.lvalue.eval(context);
var variableDeclaration;
var rule;
for (var i = 0; (rule = context.frames[i]); i++) {
if (rule.type === 'Ruleset') {
variableDeclaration = rule.rules.find(function (r) {
if ((r instanceof declaration_1.default) && r.variable) {
return true;
}
return false;
});
if (variableDeclaration) {
break;
}
}
}
if (!this.mvalueCopy) {
this.mvalueCopy = (0, copy_anything_1.copy)(this.mvalue);
}
if (variableDeclaration) {
this.mvalue = this.mvalueCopy;
this.mvalue = this.mvalue.eval(context);
this.mvalues.push(this.mvalue);
}
else {
this.mvalue = this.mvalue.eval(context);
}
if (this.rvalue) {
this.rvalue = this.rvalue.eval(context);
}
return this;
},
genCSS: function (context, output) {
this.lvalue.genCSS(context, output);
output.add(' ' + this.op + ' ');
if (this.mvalues.length > 0) {
this.mvalue = this.mvalues.shift();
}
this.mvalue.genCSS(context, output);
if (this.rvalue) {
output.add(' ' + this.op2 + ' ');
this.rvalue.genCSS(context, output);
}
}
}
export default QueryInParens;
},
});
exports.default = QueryInParens;
//# sourceMappingURL=query-in-parens.js.map
+44 -93
View File
@@ -1,88 +1,46 @@
// @ts-check
/** @import { EvalContext, CSSOutput, FileInfo } from './node.js' */
import Node from './node.js';
import Variable from './variable.js';
import Property from './property.js';
class Quoted extends Node {
get type() { return 'Quoted'; }
/**
* @param {string} str
* @param {string} [content]
* @param {boolean} [escaped]
* @param {number} [index]
* @param {FileInfo} [currentFileInfo]
*/
constructor(str, content, escaped, index, currentFileInfo) {
super();
/** @type {boolean} */
this.escaped = (escaped === undefined) ? true : escaped;
/** @type {string} */
this.value = content || '';
/** @type {string} */
this.quote = str.charAt(0);
this._index = index;
this._fileInfo = currentFileInfo;
/** @type {RegExp} */
this.variableRegex = /@\{([\w-]+)\}/g;
/** @type {RegExp} */
this.propRegex = /\$\{([\w-]+)\}/g;
/** @type {boolean | undefined} */
this.allowRoot = escaped;
}
/**
* @param {EvalContext} context
* @param {CSSOutput} output
*/
genCSS(context, output) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var tslib_1 = require("tslib");
var node_1 = tslib_1.__importDefault(require("./node"));
var variable_1 = tslib_1.__importDefault(require("./variable"));
var property_1 = tslib_1.__importDefault(require("./property"));
var Quoted = function (str, content, escaped, index, currentFileInfo) {
this.escaped = (escaped === undefined) ? true : escaped;
this.value = content || '';
this.quote = str.charAt(0);
this._index = index;
this._fileInfo = currentFileInfo;
this.variableRegex = /@\{([\w-]+)\}/g;
this.propRegex = /\$\{([\w-]+)\}/g;
this.allowRoot = escaped;
};
Quoted.prototype = Object.assign(new node_1.default(), {
type: 'Quoted',
genCSS: function (context, output) {
if (!this.escaped) {
output.add(this.quote, this.fileInfo(), this.getIndex());
}
output.add(/** @type {string} */ (this.value));
output.add(this.value);
if (!this.escaped) {
output.add(this.quote);
}
}
/** @returns {RegExpMatchArray | null} */
containsVariables() {
return /** @type {string} */ (this.value).match(this.variableRegex);
}
/** @param {EvalContext} context */
eval(context) {
const that = this;
let value = /** @type {string} */ (this.value);
/**
* @param {string} _
* @param {string} name1
* @param {string} name2
* @returns {string}
*/
const variableReplacement = function (_, name1, name2) {
const v = new Variable(`@${name1 ?? name2}`, that.getIndex(), that.fileInfo()).eval(context);
return (v instanceof Quoted) ? /** @type {string} */ (v.value) : v.toCSS(context);
},
containsVariables: function () {
return this.value.match(this.variableRegex);
},
eval: function (context) {
var that = this;
var value = this.value;
var variableReplacement = function (_, name1, name2) {
var v = new variable_1.default("@".concat(name1 !== null && name1 !== void 0 ? name1 : name2), that.getIndex(), that.fileInfo()).eval(context, true);
return (v instanceof Quoted) ? v.value : v.toCSS();
};
/**
* @param {string} _
* @param {string} name1
* @param {string} name2
* @returns {string}
*/
const propertyReplacement = function (_, name1, name2) {
const v = new Property(`$${name1 ?? name2}`, that.getIndex(), that.fileInfo()).eval(context);
return (v instanceof Quoted) ? /** @type {string} */ (v.value) : v.toCSS(context);
var propertyReplacement = function (_, name1, name2) {
var v = new property_1.default("$".concat(name1 !== null && name1 !== void 0 ? name1 : name2), that.getIndex(), that.fileInfo()).eval(context, true);
return (v instanceof Quoted) ? v.value : v.toCSS();
};
/**
* @param {string} value
* @param {RegExp} regexp
* @param {(substring: string, ...args: string[]) => string} replacementFnc
* @returns {string}
*/
function iterativeReplace(value, regexp, replacementFnc) {
let evaluatedValue = value;
var evaluatedValue = value;
do {
value = evaluatedValue.toString();
evaluatedValue = value.replace(regexp, replacementFnc);
@@ -92,23 +50,16 @@ class Quoted extends Node {
value = iterativeReplace(value, this.variableRegex, variableReplacement);
value = iterativeReplace(value, this.propRegex, propertyReplacement);
return new Quoted(this.quote + value + this.quote, value, this.escaped, this.getIndex(), this.fileInfo());
}
/**
* @param {Node} other
* @returns {number | undefined}
*/
compare(other) {
},
compare: function (other) {
// when comparing quoted strings allow the quote to differ
if (other.type === 'Quoted' && !this.escaped && !/** @type {Quoted} */ (other).escaped) {
return Node.numericCompare(
/** @type {string} */ (this.value),
/** @type {string} */ (other.value)
);
} else {
return other.toCSS && this.toCSS(/** @type {EvalContext} */ ({})) === other.toCSS(/** @type {EvalContext} */ ({})) ? 0 : undefined;
if (other.type === 'Quoted' && !this.escaped && !other.escaped) {
return node_1.default.numericCompare(this.value, other.value);
}
else {
return other.toCSS && this.toCSS() === other.toCSS() ? 0 : undefined;
}
}
}
export default Quoted;
});
exports.default = Quoted;
//# sourceMappingURL=quoted.js.map
+320 -634
View File
File diff suppressed because it is too large Load Diff
+77 -151
View File
@@ -1,47 +1,27 @@
// @ts-check
import Node from './node.js';
import Element from './element.js';
import LessError from '../less-error.js';
import * as utils from '../utils.js';
import Parser from '../parser/parser.js';
/** @import { EvalContext, CSSOutput, FileInfo, VisibilityInfo, TreeVisitor } from './node.js' */
class Selector extends Node {
get type() { return 'Selector'; }
/**
* @param {(Element | Selector)[] | string} [elements]
* @param {Node[] | null} [extendList]
* @param {Node | null} [condition]
* @param {number} [index]
* @param {FileInfo} [currentFileInfo]
* @param {VisibilityInfo} [visibilityInfo]
*/
constructor(elements, extendList, condition, index, currentFileInfo, visibilityInfo) {
super();
/** @type {Node[] | null | undefined} */
this.extendList = extendList;
/** @type {Node | null | undefined} */
this.condition = condition;
/** @type {boolean | Node} */
this.evaldCondition = !condition;
this._index = index;
this._fileInfo = currentFileInfo;
/** @type {Element[]} */
this.elements = this.getElements(elements);
/** @type {string[] | undefined} */
this.mixinElements_ = undefined;
/** @type {boolean | undefined} */
this.mediaEmpty = undefined;
this.copyVisibilityInfo(visibilityInfo);
this.setParent(this.elements, this);
}
/** @param {TreeVisitor} visitor */
accept(visitor) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var tslib_1 = require("tslib");
var node_1 = tslib_1.__importDefault(require("./node"));
var element_1 = tslib_1.__importDefault(require("./element"));
var less_error_1 = tslib_1.__importDefault(require("../less-error"));
var utils = tslib_1.__importStar(require("../utils"));
var parser_1 = tslib_1.__importDefault(require("../parser/parser"));
var Selector = function (elements, extendList, condition, index, currentFileInfo, visibilityInfo) {
this.extendList = extendList;
this.condition = condition;
this.evaldCondition = !condition;
this._index = index;
this._fileInfo = currentFileInfo;
this.elements = this.getElements(elements);
this.mixinElements_ = undefined;
this.copyVisibilityInfo(visibilityInfo);
this.setParent(this.elements, this);
};
Selector.prototype = Object.assign(new node_1.default(), {
type: 'Selector',
accept: function (visitor) {
if (this.elements) {
this.elements = /** @type {Element[]} */ (visitor.visitArray(this.elements));
this.elements = visitor.visitArray(this.elements);
}
if (this.extendList) {
this.extendList = visitor.visitArray(this.extendList);
@@ -49,153 +29,99 @@ class Selector extends Node {
if (this.condition) {
this.condition = visitor.visit(this.condition);
}
}
/**
* @param {Element[]} elements
* @param {Node[] | null} [extendList]
* @param {boolean | Node} [evaldCondition]
*/
createDerived(elements, extendList, evaldCondition) {
},
createDerived: function (elements, extendList, evaldCondition) {
elements = this.getElements(elements);
const newSelector = new Selector(elements, extendList || this.extendList,
null, this.getIndex(), this.fileInfo(), this.visibilityInfo());
var newSelector = new Selector(elements, extendList || this.extendList, null, this.getIndex(), this.fileInfo(), this.visibilityInfo());
newSelector.evaldCondition = (!utils.isNullOrUndefined(evaldCondition)) ? evaldCondition : this.evaldCondition;
newSelector.mediaEmpty = this.mediaEmpty;
return newSelector;
}
/**
* @param {(Element | Selector)[] | string | null | undefined} els
* @returns {Element[]}
*/
getElements(els) {
},
getElements: function (els) {
if (!els) {
return [new Element('', '&', false, this._index, this._fileInfo)];
return [new element_1.default('', '&', false, this._index, this._fileInfo)];
}
if (typeof els === 'string') {
const fileInfo = this._fileInfo;
const parse = this.parse;
new (/** @type {new (...args: unknown[]) => { parseNode: Function }} */ (/** @type {unknown} */ (Parser)))(parse.context, parse.importManager, fileInfo, this._index).parseNode(
els,
['selector'],
function(/** @type {{ index: number, message: string } | null} */ err, /** @type {Selector[]} */ result) {
if (err) {
throw new LessError({
index: err.index,
message: err.message
}, parse.imports, /** @type {string} */ (/** @type {FileInfo} */ (fileInfo).filename));
}
els = result[0].elements;
});
new parser_1.default(this.parse.context, this.parse.importManager, this._fileInfo, this._index).parseNode(els, ['selector'], function (err, result) {
if (err) {
throw new less_error_1.default({
index: err.index,
message: err.message
}, this.parse.imports, this._fileInfo.filename);
}
els = result[0].elements;
});
}
return /** @type {Element[]} */ (els);
}
createEmptySelectors() {
const el = new Element('', '&', false, this._index, this._fileInfo), sels = [new Selector([el], null, null, this._index, this._fileInfo)];
return els;
},
createEmptySelectors: function () {
var el = new element_1.default('', '&', false, this._index, this._fileInfo), sels = [new Selector([el], null, null, this._index, this._fileInfo)];
sels[0].mediaEmpty = true;
return sels;
}
/**
* @param {Selector} other
* @returns {number}
*/
match(other) {
const elements = this.elements;
const len = elements.length;
let olen;
let i;
/** @type {string[]} */
const mixinEls = other.mixinElements();
olen = mixinEls.length;
},
match: function (other) {
var elements = this.elements;
var len = elements.length;
var olen;
var i;
other = other.mixinElements();
olen = other.length;
if (olen === 0 || len < olen) {
return 0;
} else {
}
else {
for (i = 0; i < olen; i++) {
if (elements[i].value !== mixinEls[i]) {
if (elements[i].value !== other[i]) {
return 0;
}
}
}
return olen; // return number of matched elements
}
/** @returns {string[]} */
mixinElements() {
},
mixinElements: function () {
if (this.mixinElements_) {
return this.mixinElements_;
}
/** @type {string[] | null} */
let elements = this.elements.map( function(v) {
return /** @type {string} */ (v.combinator.value) + (/** @type {{ value: string }} */ (v.value).value || v.value);
var elements = this.elements.map(function (v) {
return v.combinator.value + (v.value.value || v.value);
}).join('').match(/[,&#*.\w-]([\w-]|(\\.))*/g);
if (elements) {
if (elements[0] === '&') {
elements.shift();
}
} else {
}
else {
elements = [];
}
return (this.mixinElements_ = elements);
}
isJustParentSelector() {
},
isJustParentSelector: function () {
return !this.mediaEmpty &&
this.elements.length === 1 &&
this.elements[0].value === '&' &&
(this.elements[0].combinator.value === ' ' || this.elements[0].combinator.value === '');
}
/** @param {EvalContext} context */
eval(context) {
const evaldCondition = this.condition && this.condition.eval(context);
let elements = this.elements;
/** @type {Node[] | null | undefined} */
let extendList = this.extendList;
if (elements) {
const evaldElements = new Array(elements.length);
for (let i = 0; i < elements.length; i++) {
evaldElements[i] = elements[i].eval(context);
}
elements = evaldElements;
}
if (extendList) {
const evaldExtends = new Array(extendList.length);
for (let i = 0; i < extendList.length; i++) {
evaldExtends[i] = extendList[i].eval(context);
}
extendList = evaldExtends;
}
},
eval: function (context) {
var evaldCondition = this.condition && this.condition.eval(context);
var elements = this.elements;
var extendList = this.extendList;
elements = elements && elements.map(function (e) { return e.eval(context); });
extendList = extendList && extendList.map(function (extend) { return extend.eval(context); });
return this.createDerived(elements, extendList, evaldCondition);
}
/**
* @param {EvalContext} context
* @param {CSSOutput} output
*/
genCSS(context, output) {
let i, element;
if ((!context || !/** @type {EvalContext & { firstSelector?: boolean }} */ (context).firstSelector) && this.elements[0].combinator.value === '') {
},
genCSS: function (context, output) {
var i, element;
if ((!context || !context.firstSelector) && this.elements[0].combinator.value === '') {
output.add(' ', this.fileInfo(), this.getIndex());
}
for (i = 0; i < this.elements.length; i++) {
element = this.elements[i];
element.genCSS(context, output);
}
}
getIsOutput() {
},
getIsOutput: function () {
return this.evaldCondition;
}
}
export default Selector;
});
exports.default = Selector;
//# sourceMappingURL=selector.js.map
+12 -14
View File
@@ -1,14 +1,12 @@
// @ts-check
import Node from './node.js';
class UnicodeDescriptor extends Node {
get type() { return 'UnicodeDescriptor'; }
/** @param {string} value */
constructor(value) {
super();
this.value = value;
}
}
export default UnicodeDescriptor;
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var tslib_1 = require("tslib");
var node_1 = tslib_1.__importDefault(require("./node"));
var UnicodeDescriptor = function (value) {
this.value = value;
};
UnicodeDescriptor.prototype = Object.assign(new node_1.default(), {
type: 'UnicodeDescriptor'
});
exports.default = UnicodeDescriptor;
//# sourceMappingURL=unicode-descriptor.js.map
+63 -111
View File
@@ -1,170 +1,122 @@
// @ts-check
import Node from './node.js';
import unitConversions from '../data/unit-conversions.js';
import * as utils from '../utils.js';
/** @import { EvalContext, CSSOutput } from './node.js' */
class Unit extends Node {
get type() { return 'Unit'; }
/**
* @param {string[]} [numerator]
* @param {string[]} [denominator]
* @param {string} [backupUnit]
*/
constructor(numerator, denominator, backupUnit) {
super();
/** @type {string[]} */
this.numerator = numerator ? utils.copyArray(numerator).sort() : [];
/** @type {string[]} */
this.denominator = denominator ? utils.copyArray(denominator).sort() : [];
if (backupUnit) {
/** @type {string | undefined} */
this.backupUnit = backupUnit;
} else if (numerator && numerator.length) {
this.backupUnit = numerator[0];
}
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var tslib_1 = require("tslib");
var node_1 = tslib_1.__importDefault(require("./node"));
var unit_conversions_1 = tslib_1.__importDefault(require("../data/unit-conversions"));
var utils = tslib_1.__importStar(require("../utils"));
var Unit = function (numerator, denominator, backupUnit) {
this.numerator = numerator ? utils.copyArray(numerator).sort() : [];
this.denominator = denominator ? utils.copyArray(denominator).sort() : [];
if (backupUnit) {
this.backupUnit = backupUnit;
}
clone() {
else if (numerator && numerator.length) {
this.backupUnit = numerator[0];
}
};
Unit.prototype = Object.assign(new node_1.default(), {
type: 'Unit',
clone: function () {
return new Unit(utils.copyArray(this.numerator), utils.copyArray(this.denominator), this.backupUnit);
}
/**
* @param {EvalContext} context
* @param {CSSOutput} output
*/
genCSS(context, output) {
},
genCSS: function (context, output) {
// Dimension checks the unit is singular and throws an error if in strict math mode.
const strictUnits = context && context.strictUnits;
var strictUnits = context && context.strictUnits;
if (this.numerator.length === 1) {
output.add(this.numerator[0]); // the ideal situation
} else if (!strictUnits && this.backupUnit) {
}
else if (!strictUnits && this.backupUnit) {
output.add(this.backupUnit);
} else if (!strictUnits && this.denominator.length) {
}
else if (!strictUnits && this.denominator.length) {
output.add(this.denominator[0]);
}
}
toString() {
let i, returnStr = this.numerator.join('*');
},
toString: function () {
var i, returnStr = this.numerator.join('*');
for (i = 0; i < this.denominator.length; i++) {
returnStr += `/${this.denominator[i]}`;
returnStr += "/".concat(this.denominator[i]);
}
return returnStr;
}
/**
* @param {Unit} other
* @returns {0 | undefined}
*/
compare(other) {
},
compare: function (other) {
return this.is(other.toString()) ? 0 : undefined;
}
/** @param {string} unitString */
is(unitString) {
},
is: function (unitString) {
return this.toString().toUpperCase() === unitString.toUpperCase();
}
isLength() {
return RegExp('^(px|em|ex|ch|rem|in|cm|mm|pc|pt|ex|vw|vh|vmin|vmax)$', 'gi').test(this.toCSS(/** @type {import('./node.js').EvalContext} */ ({})));
}
isEmpty() {
},
isLength: function () {
return RegExp('^(px|em|ex|ch|rem|in|cm|mm|pc|pt|ex|vw|vh|vmin|vmax)$', 'gi').test(this.toCSS());
},
isEmpty: function () {
return this.numerator.length === 0 && this.denominator.length === 0;
}
isSingular() {
},
isSingular: function () {
return this.numerator.length <= 1 && this.denominator.length === 0;
}
/** @param {(atomicUnit: string, denominator: boolean) => string} callback */
map(callback) {
let i;
},
map: function (callback) {
var i;
for (i = 0; i < this.numerator.length; i++) {
this.numerator[i] = callback(this.numerator[i], false);
}
for (i = 0; i < this.denominator.length; i++) {
this.denominator[i] = callback(this.denominator[i], true);
}
}
/** @returns {{ [groupName: string]: string }} */
usedUnits() {
/** @type {{ [unitName: string]: number }} */
let group;
/** @type {{ [groupName: string]: string }} */
const result = {};
/** @type {(atomicUnit: string) => string} */
let mapUnit;
/** @type {string} */
let groupName;
},
usedUnits: function () {
var group;
var result = {};
var mapUnit;
var groupName;
mapUnit = function (atomicUnit) {
// eslint-disable-next-line no-prototype-builtins
if (group.hasOwnProperty(atomicUnit) && !result[groupName]) {
result[groupName] = atomicUnit;
}
return atomicUnit;
};
for (groupName in unitConversions) {
for (groupName in unit_conversions_1.default) {
// eslint-disable-next-line no-prototype-builtins
if (unitConversions.hasOwnProperty(groupName)) {
group = /** @type {{ [unitName: string]: number }} */ (unitConversions[/** @type {keyof typeof unitConversions} */ (groupName)]);
if (unit_conversions_1.default.hasOwnProperty(groupName)) {
group = unit_conversions_1.default[groupName];
this.map(mapUnit);
}
}
return result;
}
cancel() {
/** @type {{ [unit: string]: number }} */
const counter = {};
/** @type {string} */
let atomicUnit;
let i;
},
cancel: function () {
var counter = {};
var atomicUnit;
var i;
for (i = 0; i < this.numerator.length; i++) {
atomicUnit = this.numerator[i];
counter[atomicUnit] = (counter[atomicUnit] || 0) + 1;
}
for (i = 0; i < this.denominator.length; i++) {
atomicUnit = this.denominator[i];
counter[atomicUnit] = (counter[atomicUnit] || 0) - 1;
}
this.numerator = [];
this.denominator = [];
for (atomicUnit in counter) {
// eslint-disable-next-line no-prototype-builtins
if (counter.hasOwnProperty(atomicUnit)) {
const count = counter[atomicUnit];
var count = counter[atomicUnit];
if (count > 0) {
for (i = 0; i < count; i++) {
this.numerator.push(atomicUnit);
}
} else if (count < 0) {
}
else if (count < 0) {
for (i = 0; i < -count; i++) {
this.denominator.push(atomicUnit);
}
}
}
}
this.numerator.sort();
this.denominator.sort();
}
}
export default Unit;
});
exports.default = Unit;
//# sourceMappingURL=unit.js.map
+38 -62
View File
@@ -1,83 +1,59 @@
// @ts-check
/** @import { EvalContext, CSSOutput, TreeVisitor, FileInfo } from './node.js' */
import Node from './node.js';
/**
* @param {string} path
* @returns {string}
*/
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var tslib_1 = require("tslib");
var node_1 = tslib_1.__importDefault(require("./node"));
function escapePath(path) {
return path.replace(/[()'"\s]/g, function(match) { return `\\${match}`; });
return path.replace(/[()'"\s]/g, function (match) { return "\\".concat(match); });
}
class URL extends Node {
get type() { return 'Url'; }
/**
* @param {Node} val
* @param {number} index
* @param {FileInfo} currentFileInfo
* @param {boolean} [isEvald]
*/
constructor(val, index, currentFileInfo, isEvald) {
super();
this.value = val;
this._index = index;
this._fileInfo = currentFileInfo;
/** @type {boolean | undefined} */
this.isEvald = isEvald;
}
/** @param {TreeVisitor} visitor */
accept(visitor) {
this.value = visitor.visit(/** @type {Node} */ (this.value));
}
/**
* @param {EvalContext} context
* @param {CSSOutput} output
*/
genCSS(context, output) {
var URL = function (val, index, currentFileInfo, isEvald) {
this.value = val;
this._index = index;
this._fileInfo = currentFileInfo;
this.isEvald = isEvald;
};
URL.prototype = Object.assign(new node_1.default(), {
type: 'Url',
accept: function (visitor) {
this.value = visitor.visit(this.value);
},
genCSS: function (context, output) {
output.add('url(');
/** @type {Node} */ (this.value).genCSS(context, output);
this.value.genCSS(context, output);
output.add(')');
}
/** @param {EvalContext} context */
eval(context) {
const val = /** @type {Node} */ (this.value).eval(context);
let rootpath;
},
eval: function (context) {
var val = this.value.eval(context);
var rootpath;
if (!this.isEvald) {
// Add the rootpath if the URL requires a rewrite
rootpath = this.fileInfo() && this.fileInfo().rootpath;
if (typeof rootpath === 'string' &&
typeof val.value === 'string' &&
context.pathRequiresRewrite(/** @type {string} */ (val.value))) {
if (!/** @type {import('./quoted.js').default} */ (val).quote) {
context.pathRequiresRewrite(val.value)) {
if (!val.quote) {
rootpath = escapePath(rootpath);
}
val.value = context.rewritePath(/** @type {string} */ (val.value), rootpath);
} else {
val.value = context.normalizePath(/** @type {string} */ (val.value));
val.value = context.rewritePath(val.value, rootpath);
}
else {
val.value = context.normalizePath(val.value);
}
// Add url args if enabled
if (context.urlArgs) {
if (!/** @type {string} */ (val.value).match(/^\s*data:/)) {
const delimiter = /** @type {string} */ (val.value).indexOf('?') === -1 ? '?' : '&';
const urlArgs = delimiter + context.urlArgs;
if (/** @type {string} */ (val.value).indexOf('#') !== -1) {
val.value = /** @type {string} */ (val.value).replace('#', `${urlArgs}#`);
} else {
if (!val.value.match(/^\s*data:/)) {
var delimiter = val.value.indexOf('?') === -1 ? '?' : '&';
var urlArgs = delimiter + context.urlArgs;
if (val.value.indexOf('#') !== -1) {
val.value = val.value.replace('#', "".concat(urlArgs, "#"));
}
else {
val.value += urlArgs;
}
}
}
}
return new URL(val, this.getIndex(), this.fileInfo(), true);
}
}
export default URL;
});
exports.default = URL;
//# sourceMappingURL=url.js.map
+34 -50
View File
@@ -1,60 +1,44 @@
// @ts-check
/** @import { EvalContext, CSSOutput, TreeVisitor } from './node.js' */
import Node from './node.js';
class Value extends Node {
get type() { return 'Value'; }
/** @param {Node[] | Node} value */
constructor(value) {
super();
if (!value) {
throw new Error('Value requires an array argument');
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var tslib_1 = require("tslib");
var node_1 = tslib_1.__importDefault(require("./node"));
var Value = function (value) {
if (!value) {
throw new Error('Value requires an array argument');
}
if (!Array.isArray(value)) {
this.value = [value];
}
else {
this.value = value;
}
};
Value.prototype = Object.assign(new node_1.default(), {
type: 'Value',
accept: function (visitor) {
if (this.value) {
this.value = visitor.visitArray(this.value);
}
if (!Array.isArray(value)) {
this.value = [ value ];
},
eval: function (context) {
if (this.value.length === 1) {
return this.value[0].eval(context);
}
else {
this.value = value;
}
}
/** @param {TreeVisitor} visitor */
accept(visitor) {
if (this.value) {
this.value = visitor.visitArray(/** @type {Node[]} */ (this.value));
}
}
/**
* @param {EvalContext} context
* @returns {Node}
*/
eval(context) {
const value = /** @type {Node[]} */ (this.value);
if (value.length === 1) {
return value[0].eval(context);
} else {
return new Value(value.map(function (v) {
return new Value(this.value.map(function (v) {
return v.eval(context);
}));
}
}
/**
* @param {EvalContext} context
* @param {CSSOutput} output
*/
genCSS(context, output) {
const value = /** @type {Node[]} */ (this.value);
let i;
for (i = 0; i < value.length; i++) {
value[i].genCSS(context, output);
if (i + 1 < value.length) {
},
genCSS: function (context, output) {
var i;
for (i = 0; i < this.value.length; i++) {
this.value[i].genCSS(context, output);
if (i + 1 < this.value.length) {
output.add((context && context.compress) ? ',' : ', ');
}
}
}
}
export default Value;
});
exports.default = Value;
//# sourceMappingURL=value.js.map
+30 -47
View File
@@ -1,60 +1,43 @@
// @ts-check
/** @import { EvalContext, FileInfo } from './node.js' */
import Node from './node.js';
import Variable from './variable.js';
import Ruleset from './ruleset.js';
import DetachedRuleset from './detached-ruleset.js';
import LessError from '../less-error.js';
class VariableCall extends Node {
get type() { return 'VariableCall'; }
/**
* @param {string} variable
* @param {number} index
* @param {FileInfo} currentFileInfo
*/
constructor(variable, index, currentFileInfo) {
super();
this.variable = variable;
this._index = index;
this._fileInfo = currentFileInfo;
this.allowRoot = true;
}
/**
* @param {EvalContext} context
* @returns {Node}
*/
eval(context) {
let rules;
/** @type {DetachedRuleset | Node} */
let detachedRuleset = new Variable(this.variable, this.getIndex(), this.fileInfo()).eval(context);
const error = new LessError({message: `Could not evaluate variable call ${this.variable}`});
if (!(/** @type {DetachedRuleset} */ (detachedRuleset)).ruleset) {
const dr = /** @type {Node & { rules?: Node[] }} */ (detachedRuleset);
if (dr.rules) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var tslib_1 = require("tslib");
var node_1 = tslib_1.__importDefault(require("./node"));
var variable_1 = tslib_1.__importDefault(require("./variable"));
var ruleset_1 = tslib_1.__importDefault(require("./ruleset"));
var detached_ruleset_1 = tslib_1.__importDefault(require("./detached-ruleset"));
var less_error_1 = tslib_1.__importDefault(require("../less-error"));
var VariableCall = function (variable, index, currentFileInfo) {
this.variable = variable;
this._index = index;
this._fileInfo = currentFileInfo;
this.allowRoot = true;
};
VariableCall.prototype = Object.assign(new node_1.default(), {
type: 'VariableCall',
eval: function (context) {
var rules;
var detachedRuleset = new variable_1.default(this.variable, this.getIndex(), this.fileInfo()).eval(context);
var error = new less_error_1.default({ message: "Could not evaluate variable call ".concat(this.variable) });
if (!detachedRuleset.ruleset) {
if (detachedRuleset.rules) {
rules = detachedRuleset;
}
else if (Array.isArray(detachedRuleset)) {
rules = new Ruleset(null, detachedRuleset);
rules = new ruleset_1.default('', detachedRuleset);
}
else if (Array.isArray(detachedRuleset.value)) {
rules = new Ruleset(null, detachedRuleset.value);
rules = new ruleset_1.default('', detachedRuleset.value);
}
else {
throw error;
}
detachedRuleset = new DetachedRuleset(rules);
detachedRuleset = new detached_ruleset_1.default(rules);
}
const dr = /** @type {DetachedRuleset} */ (detachedRuleset);
if (dr.ruleset) {
return dr.callEval(context);
if (detachedRuleset.ruleset) {
return detachedRuleset.callEval(context);
}
throw error;
}
}
export default VariableCall;
});
exports.default = VariableCall;
//# sourceMappingURL=variable-call.js.map
+31 -53
View File
@@ -1,56 +1,37 @@
// @ts-check
/** @import { EvalContext, FileInfo } from './node.js' */
import Node from './node.js';
import Call from './call.js';
import Ruleset from './ruleset.js';
class Variable extends Node {
get type() { return 'Variable'; }
/**
* @param {string} name
* @param {number} [index]
* @param {FileInfo} [currentFileInfo]
*/
constructor(name, index, currentFileInfo) {
super();
this.name = name;
this._index = index;
this._fileInfo = currentFileInfo;
/** @type {boolean | undefined} */
this.evaluating = undefined;
}
/**
* @param {EvalContext} context
* @returns {Node}
*/
eval(context) {
let variable, name = this.name;
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var tslib_1 = require("tslib");
var node_1 = tslib_1.__importDefault(require("./node"));
var call_1 = tslib_1.__importDefault(require("./call"));
var Variable = function (name, index, currentFileInfo) {
this.name = name;
this._index = index;
this._fileInfo = currentFileInfo;
};
Variable.prototype = Object.assign(new node_1.default(), {
type: 'Variable',
eval: function (context) {
var variable, name = this.name;
if (name.indexOf('@@') === 0) {
name = `@${new Variable(name.slice(1), this.getIndex(), this.fileInfo()).eval(context).value}`;
name = "@".concat(new Variable(name.slice(1), this.getIndex(), this.fileInfo()).eval(context).value);
}
if (this.evaluating) {
throw { type: 'Name',
message: `Recursive variable definition for ${name}`,
message: "Recursive variable definition for ".concat(name),
filename: this.fileInfo().filename,
index: this.getIndex() };
}
this.evaluating = true;
variable = this.find(context.frames, function (frame) {
const v = /** @type {Ruleset} */ (frame).variable(name);
var v = frame.variable(name);
if (v) {
if (v.important) {
const importantScope = context.importantScope[context.importantScope.length - 1];
var importantScope = context.importantScope[context.importantScope.length - 1];
importantScope.important = v.important;
}
// If in calc, wrap vars in a function call to cascade evaluate args first
if (context.inCalc) {
return (new Call('_SELF', [v.value], 0, undefined)).eval(context);
return (new call_1.default('_SELF', [v.value])).eval(context);
}
else {
return v.value.eval(context);
@@ -60,26 +41,23 @@ class Variable extends Node {
if (variable) {
this.evaluating = false;
return variable;
} else {
}
else {
throw { type: 'Name',
message: `variable ${name} is undefined`,
message: "variable ".concat(name, " is undefined"),
filename: this.fileInfo().filename,
index: this.getIndex() };
}
}
/**
* @param {Node[]} obj
* @param {(frame: Node) => Node | undefined} fun
* @returns {Node | null}
*/
find(obj, fun) {
for (let i = 0, r; i < obj.length; i++) {
},
find: function (obj, fun) {
for (var i = 0, r = void 0; i < obj.length; i++) {
r = fun.call(obj, obj[i]);
if (r) { return r; }
if (r) {
return r;
}
}
return null;
}
}
export default Variable;
});
exports.default = Variable;
//# sourceMappingURL=variable.js.map

Some files were not shown because too many files have changed in this diff Show More