@angular/ssr
Version:
Angular server side rendering utilities
1,861 lines (1,657 loc) • 423 kB
JavaScript
function createNotImplementedError(name) {
throw new Error(`[unenv] ${name} is not implemented yet!`);
}
function notImplemented(name) {
const fn = () => {
throw createNotImplementedError(name);
};
return Object.assign(fn, { __unenv__: true });
}
const access = notImplemented("fs.access");
const copyFile = notImplemented("fs.copyFile");
const cp = notImplemented("fs.cp");
const open = notImplemented("fs.open");
const opendir = notImplemented("fs.opendir");
const rename = notImplemented("fs.rename");
const truncate = notImplemented("fs.truncate");
const rm = notImplemented("fs.rm");
const rmdir = notImplemented("fs.rmdir");
const mkdir = notImplemented("fs.mkdir");
const readdir = notImplemented("fs.readdir");
const readlink = notImplemented("fs.readlink");
const symlink = notImplemented("fs.symlink");
const lstat = notImplemented("fs.lstat");
const stat = notImplemented("fs.stat");
const link = notImplemented("fs.link");
const unlink = notImplemented("fs.unlink");
const chmod = notImplemented("fs.chmod");
const lchmod = notImplemented("fs.lchmod");
const lchown = notImplemented("fs.lchown");
const chown = notImplemented("fs.chown");
const utimes = notImplemented("fs.utimes");
const lutimes = notImplemented("fs.lutimes");
const realpath = notImplemented("fs.realpath");
const mkdtemp = notImplemented("fs.mkdtemp");
const writeFile$1 = notImplemented("fs.writeFile");
const appendFile = notImplemented("fs.appendFile");
const readFile$1 = notImplemented("fs.readFile");
notImplemented("fs.watch");
const statfs = notImplemented("fs.statfs");
function notImplementedAsync(name) {
const fn = notImplemented(name);
fn.__promisify__ = () => notImplemented(name + ".__promisify__");
fn.native = fn;
return fn;
}
function callbackify(fn) {
const fnc = function(...args) {
const cb = args.pop();
fn().catch((error) => cb(error)).then((val) => cb(void 0, val));
};
fnc.__promisify__ = fn;
fnc.native = fnc;
return fnc;
}
callbackify(access);
callbackify(appendFile);
callbackify(chown);
callbackify(chmod);
callbackify(copyFile);
callbackify(cp);
callbackify(lchown);
callbackify(lchmod);
callbackify(link);
callbackify(lstat);
callbackify(lutimes);
callbackify(mkdir);
callbackify(mkdtemp);
callbackify(realpath);
callbackify(open);
callbackify(opendir);
callbackify(readdir);
const readFile = callbackify(readFile$1);
callbackify(readlink);
callbackify(rename);
callbackify(rm);
callbackify(rmdir);
callbackify(stat);
callbackify(symlink);
callbackify(truncate);
callbackify(unlink);
callbackify(utimes);
const writeFile = callbackify(writeFile$1);
callbackify(statfs);
notImplementedAsync("fs.close");
notImplementedAsync(
"fs.createReadStream"
);
notImplementedAsync("fs.createWriteStream");
notImplementedAsync("fs.exists");
notImplementedAsync("fs.fchown");
notImplementedAsync("fs.fchmod");
notImplementedAsync("fs.fdatasync");
notImplementedAsync("fs.fstat");
notImplementedAsync("fs.fsync");
notImplementedAsync("fs.ftruncate");
notImplementedAsync("fs.futimes");
notImplementedAsync("fs.lstatSync");
notImplementedAsync("fs.read");
notImplementedAsync("fs.readv");
notImplementedAsync("fs.realpathSync");
notImplementedAsync("fs.statSync");
notImplementedAsync("fs.unwatchFile");
notImplementedAsync("fs.watch");
notImplementedAsync("fs.watchFile");
notImplementedAsync("fs.write");
notImplementedAsync("fs.writev");
notImplementedAsync("fs._toUnixTimestamp");
notImplementedAsync("fs.openAsBlob");
notImplemented("fs.appendFileSync");
notImplemented("fs.accessSync");
notImplemented("fs.chownSync");
notImplemented("fs.chmodSync");
notImplemented("fs.closeSync");
notImplemented("fs.copyFileSync");
notImplemented("fs.cpSync");
notImplemented("fs.fchownSync");
notImplemented("fs.fchmodSync");
notImplemented("fs.fdatasyncSync");
notImplemented("fs.fstatSync");
notImplemented("fs.fsyncSync");
notImplemented("fs.ftruncateSync");
notImplemented("fs.futimesSync");
notImplemented("fs.lchownSync");
notImplemented("fs.lchmodSync");
notImplemented("fs.linkSync");
notImplemented("fs.lutimesSync");
notImplemented("fs.mkdirSync");
notImplemented("fs.mkdtempSync");
notImplemented("fs.openSync");
notImplemented("fs.opendirSync");
notImplemented("fs.readdirSync");
notImplemented("fs.readSync");
notImplemented("fs.readvSync");
notImplemented("fs.readFileSync");
notImplemented("fs.readlinkSync");
notImplemented("fs.renameSync");
notImplemented("fs.rmSync");
notImplemented("fs.rmdirSync");
notImplemented("fs.symlinkSync");
notImplemented("fs.truncateSync");
notImplemented("fs.unlinkSync");
notImplemented("fs.utimesSync");
notImplemented("fs.writeFileSync");
notImplemented("fs.writeSync");
notImplemented("fs.writevSync");
notImplemented("fs.statfsSync");
const _DRIVE_LETTER_START_RE = /^[A-Za-z]:\//;
function normalizeWindowsPath(input = "") {
if (!input) {
return input;
}
return input.replace(/\\/g, "/").replace(_DRIVE_LETTER_START_RE, (r) => r.toUpperCase());
}
const _UNC_REGEX = /^[/\\]{2}/;
const _IS_ABSOLUTE_RE = /^[/\\](?![/\\])|^[/\\]{2}(?!\.)|^[A-Za-z]:[/\\]/;
const _DRIVE_LETTER_RE = /^[A-Za-z]:$/;
const _ROOT_FOLDER_RE = /^\/([A-Za-z]:)?$/;
const sep = "/";
const delimiter = ":";
const normalize = function(path) {
if (path.length === 0) {
return ".";
}
path = normalizeWindowsPath(path);
const isUNCPath = path.match(_UNC_REGEX);
const isPathAbsolute = isAbsolute(path);
const trailingSeparator = path[path.length - 1] === "/";
path = normalizeString(path, !isPathAbsolute);
if (path.length === 0) {
if (isPathAbsolute) {
return "/";
}
return trailingSeparator ? "./" : ".";
}
if (trailingSeparator) {
path += "/";
}
if (_DRIVE_LETTER_RE.test(path)) {
path += "/";
}
if (isUNCPath) {
if (!isPathAbsolute) {
return `//./${path}`;
}
return `//${path}`;
}
return isPathAbsolute && !isAbsolute(path) ? `/${path}` : path;
};
const join = function(...arguments_) {
if (arguments_.length === 0) {
return ".";
}
let joined;
for (const argument of arguments_) {
if (argument && argument.length > 0) {
if (joined === void 0) {
joined = argument;
} else {
joined += `/${argument}`;
}
}
}
if (joined === void 0) {
return ".";
}
return normalize(joined.replace(/\/\/+/g, "/"));
};
function cwd() {
if (typeof process !== "undefined" && typeof process.cwd === "function") {
return process.cwd().replace(/\\/g, "/");
}
return "/";
}
const resolve = function(...arguments_) {
arguments_ = arguments_.map((argument) => normalizeWindowsPath(argument));
let resolvedPath = "";
let resolvedAbsolute = false;
for (let index = arguments_.length - 1; index >= -1 && !resolvedAbsolute; index--) {
const path = index >= 0 ? arguments_[index] : cwd();
if (!path || path.length === 0) {
continue;
}
resolvedPath = `${path}/${resolvedPath}`;
resolvedAbsolute = isAbsolute(path);
}
resolvedPath = normalizeString(resolvedPath, !resolvedAbsolute);
if (resolvedAbsolute && !isAbsolute(resolvedPath)) {
return `/${resolvedPath}`;
}
return resolvedPath.length > 0 ? resolvedPath : ".";
};
function normalizeString(path, allowAboveRoot) {
let res = "";
let lastSegmentLength = 0;
let lastSlash = -1;
let dots = 0;
let char = null;
for (let index = 0; index <= path.length; ++index) {
if (index < path.length) {
char = path[index];
} else if (char === "/") {
break;
} else {
char = "/";
}
if (char === "/") {
if (lastSlash === index - 1 || dots === 1) ; else if (dots === 2) {
if (res.length < 2 || lastSegmentLength !== 2 || res[res.length - 1] !== "." || res[res.length - 2] !== ".") {
if (res.length > 2) {
const lastSlashIndex = res.lastIndexOf("/");
if (lastSlashIndex === -1) {
res = "";
lastSegmentLength = 0;
} else {
res = res.slice(0, lastSlashIndex);
lastSegmentLength = res.length - 1 - res.lastIndexOf("/");
}
lastSlash = index;
dots = 0;
continue;
} else if (res.length > 0) {
res = "";
lastSegmentLength = 0;
lastSlash = index;
dots = 0;
continue;
}
}
if (allowAboveRoot) {
res += res.length > 0 ? "/.." : "..";
lastSegmentLength = 2;
}
} else {
if (res.length > 0) {
res += `/${path.slice(lastSlash + 1, index)}`;
} else {
res = path.slice(lastSlash + 1, index);
}
lastSegmentLength = index - lastSlash - 1;
}
lastSlash = index;
dots = 0;
} else if (char === "." && dots !== -1) {
++dots;
} else {
dots = -1;
}
}
return res;
}
const isAbsolute = function(p) {
return _IS_ABSOLUTE_RE.test(p);
};
const toNamespacedPath = function(p) {
return normalizeWindowsPath(p);
};
const _EXTNAME_RE = /.(\.[^./]+)$/;
const extname = function(p) {
const match = _EXTNAME_RE.exec(normalizeWindowsPath(p));
return match && match[1] || "";
};
const relative = function(from, to) {
const _from = resolve(from).replace(_ROOT_FOLDER_RE, "$1").split("/");
const _to = resolve(to).replace(_ROOT_FOLDER_RE, "$1").split("/");
if (_to[0][1] === ":" && _from[0][1] === ":" && _from[0] !== _to[0]) {
return _to.join("/");
}
const _fromCopy = [..._from];
for (const segment of _fromCopy) {
if (_to[0] !== segment) {
break;
}
_from.shift();
_to.shift();
}
return [..._from.map(() => ".."), ..._to].join("/");
};
const dirname = function(p) {
const segments = normalizeWindowsPath(p).replace(/\/$/, "").split("/").slice(0, -1);
if (segments.length === 1 && _DRIVE_LETTER_RE.test(segments[0])) {
segments[0] += "/";
}
return segments.join("/") || (isAbsolute(p) ? "/" : ".");
};
const format = function(p) {
const segments = [p.root, p.dir, p.base ?? p.name + p.ext].filter(Boolean);
return normalizeWindowsPath(
p.root ? resolve(...segments) : segments.join("/")
);
};
const basename = function(p, extension) {
const lastSegment = normalizeWindowsPath(p).split("/").pop();
return extension && lastSegment.endsWith(extension) ? lastSegment.slice(0, -extension.length) : lastSegment;
};
const parse$3 = function(p) {
const root = normalizeWindowsPath(p).split("/").shift() || "/";
const base = basename(p);
const extension = extname(base);
return {
root,
dir: dirname(p),
base,
ext: extension,
name: base.slice(0, base.length - extension.length)
};
};
const path = {
__proto__: null,
basename: basename,
delimiter: delimiter,
dirname: dirname,
extname: extname,
format: format,
isAbsolute: isAbsolute,
join: join,
normalize: normalize,
normalizeString: normalizeString,
parse: parse$3,
relative: relative,
resolve: resolve,
sep: sep,
toNamespacedPath: toNamespacedPath
};
var _path = /*#__PURE__*/Object.freeze({
__proto__: null,
basename: basename,
default: path,
delimiter: delimiter,
dirname: dirname,
extname: extname,
format: format,
isAbsolute: isAbsolute,
join: join,
normalize: normalize,
normalizeString: normalizeString,
parse: parse$3,
relative: relative,
resolve: resolve,
sep: sep,
toNamespacedPath: toNamespacedPath
});
const _pathModule = {
..._path,
platform: "posix",
posix: void 0,
win32: void 0
};
_pathModule.posix = _pathModule;
_pathModule.win32 = _pathModule;
function getDefaultExportFromCjs (x) {
return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
}
function getAugmentedNamespace(n) {
if (Object.prototype.hasOwnProperty.call(n, '__esModule')) return n;
var f = n.default;
if (typeof f == "function") {
var a = function a () {
var isInstance = false;
try {
isInstance = this instanceof a;
} catch (e) {}
if (isInstance) {
return Reflect.construct(f, arguments, this.constructor);
}
return f.apply(this, arguments);
};
a.prototype = f.prototype;
} else a = {};
Object.defineProperty(a, '__esModule', {value: true});
Object.keys(n).forEach(function (k) {
var d = Object.getOwnPropertyDescriptor(n, k);
Object.defineProperty(a, k, d.get ? d : {
enumerable: true,
get: function () {
return n[k];
}
});
});
return a;
}
var picocolors_browser = {exports: {}};
var hasRequiredPicocolors_browser;
function requirePicocolors_browser () {
if (hasRequiredPicocolors_browser) return picocolors_browser.exports;
hasRequiredPicocolors_browser = 1;
var x=String;
var create=function() {return {isColorSupported:false,reset:x,bold:x,dim:x,italic:x,underline:x,inverse:x,hidden:x,strikethrough:x,black:x,red:x,green:x,yellow:x,blue:x,magenta:x,cyan:x,white:x,gray:x,bgBlack:x,bgRed:x,bgGreen:x,bgYellow:x,bgBlue:x,bgMagenta:x,bgCyan:x,bgWhite:x,blackBright:x,redBright:x,greenBright:x,yellowBright:x,blueBright:x,magentaBright:x,cyanBright:x,whiteBright:x,bgBlackBright:x,bgRedBright:x,bgGreenBright:x,bgYellowBright:x,bgBlueBright:x,bgMagentaBright:x,bgCyanBright:x,bgWhiteBright:x}};
picocolors_browser.exports=create();
picocolors_browser.exports.createColors = create;
return picocolors_browser.exports;
}
var _nodeResolve_empty = {};
var _nodeResolve_empty$1 = /*#__PURE__*/Object.freeze({
__proto__: null,
default: _nodeResolve_empty
});
var require$$2 = /*@__PURE__*/getAugmentedNamespace(_nodeResolve_empty$1);
var cssSyntaxError;
var hasRequiredCssSyntaxError;
function requireCssSyntaxError () {
if (hasRequiredCssSyntaxError) return cssSyntaxError;
hasRequiredCssSyntaxError = 1;
let pico = /*@__PURE__*/ requirePicocolors_browser();
let terminalHighlight = require$$2;
class CssSyntaxError extends Error {
constructor(message, line, column, source, file, plugin) {
super(message);
this.name = 'CssSyntaxError';
this.reason = message;
if (file) {
this.file = file;
}
if (source) {
this.source = source;
}
if (plugin) {
this.plugin = plugin;
}
if (typeof line !== 'undefined' && typeof column !== 'undefined') {
if (typeof line === 'number') {
this.line = line;
this.column = column;
} else {
this.line = line.line;
this.column = line.column;
this.endLine = column.line;
this.endColumn = column.column;
}
}
this.setMessage();
if (Error.captureStackTrace) {
Error.captureStackTrace(this, CssSyntaxError);
}
}
setMessage() {
this.message = this.plugin ? this.plugin + ': ' : '';
this.message += this.file ? this.file : '<css input>';
if (typeof this.line !== 'undefined') {
this.message += ':' + this.line + ':' + this.column;
}
this.message += ': ' + this.reason;
}
showSourceCode(color) {
if (!this.source) return ''
let css = this.source;
if (color == null) color = pico.isColorSupported;
let aside = text => text;
let mark = text => text;
let highlight = text => text;
if (color) {
let { bold, gray, red } = pico.createColors(true);
mark = text => bold(red(text));
aside = text => gray(text);
if (terminalHighlight) {
highlight = text => terminalHighlight(text);
}
}
let lines = css.split(/\r?\n/);
let start = Math.max(this.line - 3, 0);
let end = Math.min(this.line + 2, lines.length);
let maxWidth = String(end).length;
return lines
.slice(start, end)
.map((line, index) => {
let number = start + 1 + index;
let gutter = ' ' + (' ' + number).slice(-maxWidth) + ' | ';
if (number === this.line) {
if (line.length > 160) {
let padding = 20;
let subLineStart = Math.max(0, this.column - padding);
let subLineEnd = Math.max(
this.column + padding,
this.endColumn + padding
);
let subLine = line.slice(subLineStart, subLineEnd);
let spacing =
aside(gutter.replace(/\d/g, ' ')) +
line
.slice(0, Math.min(this.column - 1, padding - 1))
.replace(/[^\t]/g, ' ');
return (
mark('>') +
aside(gutter) +
highlight(subLine) +
'\n ' +
spacing +
mark('^')
)
}
let spacing =
aside(gutter.replace(/\d/g, ' ')) +
line.slice(0, this.column - 1).replace(/[^\t]/g, ' ');
return (
mark('>') +
aside(gutter) +
highlight(line) +
'\n ' +
spacing +
mark('^')
)
}
return ' ' + aside(gutter) + highlight(line)
})
.join('\n')
}
toString() {
let code = this.showSourceCode();
if (code) {
code = '\n\n' + code + '\n';
}
return this.name + ': ' + this.message + code
}
}
cssSyntaxError = CssSyntaxError;
CssSyntaxError.default = CssSyntaxError;
return cssSyntaxError;
}
var stringifier;
var hasRequiredStringifier;
function requireStringifier () {
if (hasRequiredStringifier) return stringifier;
hasRequiredStringifier = 1;
// Escapes sequences that could break out of an HTML <style> context.
// Uses CSS unicode escaping (\3c = '<') which is valid CSS and parsed
// correctly by all compliant CSS consumers.
const STYLE_TAG = /(<)(\/?style\b)/gi;
const COMMENT_OPEN = /(<)(!--)/g;
function escapeHTMLInCSS(str) {
if (typeof str !== 'string') return str
if (!str.includes('<')) return str
return str.replace(STYLE_TAG, '\\3c $2').replace(COMMENT_OPEN, '\\3c $2')
}
const DEFAULT_RAW = {
after: '\n',
beforeClose: '\n',
beforeComment: '\n',
beforeDecl: '\n',
beforeOpen: ' ',
beforeRule: '\n',
colon: ': ',
commentLeft: ' ',
commentRight: ' ',
emptyBody: '',
indent: ' ',
semicolon: false
};
function capitalize(str) {
return str[0].toUpperCase() + str.slice(1)
}
function atruleStart(str, node) {
let name = '@' + node.name;
let params = node.params ? str.rawValue(node, 'params') : '';
if (typeof node.raws.afterName !== 'undefined') {
name += node.raws.afterName;
} else if (params) {
name += ' ';
}
return name + params
}
function pushBody(str, stack, node) {
let nodes = node.nodes;
let last = nodes.length - 1;
while (last > 0) {
if (nodes[last].type !== 'comment') break
last -= 1;
}
let semicolon = str.raw(node, 'semicolon');
let isDocument = node.type === 'document';
for (let i = nodes.length - 1; i >= 0; i--) {
stack.push({
document: isDocument,
node: nodes[i],
semicolon: last !== i || semicolon
});
}
}
function pushBlock(str, stack, node, start) {
let between = str.raw(node, 'between', 'beforeOpen');
str.builder(escapeHTMLInCSS(start + between) + '{', node, 'start');
let hasNodes = node.nodes && node.nodes.length;
let close = () => {
let after = hasNodes
? str.raw(node, 'after')
: str.raw(node, 'after', 'emptyBody');
if (after) str.builder(escapeHTMLInCSS(after));
str.builder('}', node, 'end');
if (node.type === 'rule' && node.raws.ownSemicolon) {
str.builder(escapeHTMLInCSS(node.raws.ownSemicolon), node, 'end');
}
};
if (hasNodes) {
stack.push(close);
pushBody(str, stack, node);
} else {
close();
}
}
class Stringifier {
constructor(builder) {
this.builder = builder;
}
atrule(node, semicolon) {
let start = atruleStart(this, node);
if (node.nodes) {
this.block(node, start);
} else {
let end = (node.raws.between || '') + (semicolon ? ';' : '');
this.builder(escapeHTMLInCSS(start + end), node);
}
}
beforeAfter(node, detect) {
let value;
if (node.type === 'decl') {
value = this.raw(node, null, 'beforeDecl');
} else if (node.type === 'comment') {
value = this.raw(node, null, 'beforeComment');
} else if (detect === 'before') {
value = this.raw(node, null, 'beforeRule');
} else {
value = this.raw(node, null, 'beforeClose');
}
let buf = node.parent;
let depth = 0;
while (buf && buf.type !== 'root') {
depth += 1;
buf = buf.parent;
}
if (value.includes('\n')) {
let indent = this.raw(node, null, 'indent');
if (indent.length) {
for (let step = 0; step < depth; step++) value += indent;
}
}
return value
}
block(node, start) {
let between = this.raw(node, 'between', 'beforeOpen');
this.builder(escapeHTMLInCSS(start + between) + '{', node, 'start');
let after;
if (node.nodes && node.nodes.length) {
this.body(node);
after = this.raw(node, 'after');
} else {
after = this.raw(node, 'after', 'emptyBody');
}
if (after) this.builder(escapeHTMLInCSS(after));
this.builder('}', node, 'end');
}
body(node) {
// Rules and at-rules are expanded into an explicit stack instead of
// recursive `stringify()` calls to survive deeply nested trees.
// If a subclass changes the traversal methods, its children go
// through `stringify()` to keep the override in charge.
let proto = Stringifier.prototype;
let expandable = ['atrule', 'block', 'body', 'rule', 'stringify'].every(
method => this[method] === proto[method]
);
let stack = [];
pushBody(this, stack, node);
while (stack.length > 0) {
let entry = stack.pop();
if (typeof entry === 'function') {
entry();
continue
}
let child = entry.node;
let before = this.raw(child, 'before');
if (before) {
this.builder(entry.document ? before : escapeHTMLInCSS(before));
}
if (expandable && child.type === 'rule') {
pushBlock(this, stack, child, this.rawValue(child, 'selector'));
} else if (expandable && child.type === 'atrule' && child.nodes) {
pushBlock(this, stack, child, atruleStart(this, child));
} else {
this.stringify(child, entry.semicolon);
}
}
}
comment(node) {
let left = this.raw(node, 'left', 'commentLeft');
let right = this.raw(node, 'right', 'commentRight');
this.builder(escapeHTMLInCSS('/*' + left + node.text + right + '*/'), node);
}
decl(node, semicolon) {
let raws = node.raws;
let between = this.raw(node, 'between', 'colon');
let string = node.prop + between + this.rawValue(node, 'value');
if (node.important) {
string += raws.important || ' !important';
}
if (semicolon) string += ';';
this.builder(escapeHTMLInCSS(string), node);
}
document(node) {
this.body(node);
}
raw(node, own, detect) {
let value;
if (!detect) detect = own;
// Already had
if (own) {
value = node.raws[own];
if (typeof value !== 'undefined') return value
}
let parent = node.parent;
if (detect === 'before') {
// Hack for first rule in CSS
if (!parent || (parent.type === 'root' && parent.first === node)) {
return ''
}
// `root` nodes in `document` should use only their own raws
if (parent && parent.type === 'document') {
return ''
}
}
// Floating child without parent
if (!parent) return DEFAULT_RAW[detect]
// Detect style by other nodes
let root = node.root();
let cache = root.rawCache || (root.rawCache = {});
if (typeof cache[detect] !== 'undefined') {
return cache[detect]
}
if (detect === 'before' || detect === 'after') {
return this.beforeAfter(node, detect)
} else {
let method = 'raw' + capitalize(detect);
if (this[method]) {
value = this[method](root, node);
} else {
root.walk(i => {
value = i.raws[own];
if (typeof value !== 'undefined') return false
});
}
}
if (typeof value === 'undefined') value = DEFAULT_RAW[detect];
cache[detect] = value;
return value
}
rawBeforeClose(root) {
let value;
root.walk(i => {
if (i.nodes && i.nodes.length > 0) {
if (typeof i.raws.after !== 'undefined') {
value = i.raws.after;
if (value.includes('\n')) {
value = value.replace(/[^\n]+$/, '');
}
return false
}
}
});
if (value) value = value.replace(/\S/g, '');
return value
}
rawBeforeComment(root, node) {
let value;
root.walkComments(i => {
if (typeof i.raws.before !== 'undefined') {
value = i.raws.before;
if (value.includes('\n')) {
value = value.replace(/[^\n]+$/, '');
}
return false
}
});
if (typeof value === 'undefined') {
value = this.raw(node, null, 'beforeDecl');
} else if (value) {
value = value.replace(/\S/g, '');
}
return value
}
rawBeforeDecl(root, node) {
let value;
root.walkDecls(i => {
if (typeof i.raws.before !== 'undefined') {
value = i.raws.before;
if (value.includes('\n')) {
value = value.replace(/[^\n]+$/, '');
}
return false
}
});
if (typeof value === 'undefined') {
value = this.raw(node, null, 'beforeRule');
} else if (value) {
value = value.replace(/\S/g, '');
}
return value
}
rawBeforeOpen(root) {
let value;
root.walk(i => {
if (i.type !== 'decl') {
value = i.raws.between;
if (typeof value !== 'undefined') return false
}
});
return value
}
rawBeforeRule(root) {
let value;
root.walk(i => {
if (i.nodes && (i.parent !== root || root.first !== i)) {
if (typeof i.raws.before !== 'undefined') {
value = i.raws.before;
if (value.includes('\n')) {
value = value.replace(/[^\n]+$/, '');
}
return false
}
}
});
if (value) value = value.replace(/\S/g, '');
return value
}
rawColon(root) {
let value;
root.walkDecls(i => {
if (typeof i.raws.between !== 'undefined') {
value = i.raws.between.replace(/[^\s:]/g, '');
return false
}
});
return value
}
rawEmptyBody(root) {
let value;
root.walk(i => {
if (i.nodes && i.nodes.length === 0) {
value = i.raws.after;
if (typeof value !== 'undefined') return false
}
});
return value
}
rawIndent(root) {
if (root.raws.indent) return root.raws.indent
let value;
root.walk(i => {
let p = i.parent;
if (p && p !== root && p.parent && p.parent === root) {
if (typeof i.raws.before !== 'undefined') {
let parts = i.raws.before.split('\n');
value = parts[parts.length - 1];
value = value.replace(/\S/g, '');
return false
}
}
});
return value
}
rawSemicolon(root) {
let value;
root.walk(i => {
if (i.nodes && i.nodes.length && i.last.type === 'decl') {
value = i.raws.semicolon;
if (typeof value !== 'undefined') return false
}
});
return value
}
rawValue(node, prop) {
let value = node[prop];
let raw = node.raws[prop];
if (raw && raw.value === value) {
return raw.raw
}
return value
}
root(node) {
this.body(node);
if (node.raws.after) {
let after = node.raws.after;
let isDocument = node.parent && node.parent.type === 'document';
this.builder(isDocument ? after : escapeHTMLInCSS(after));
}
}
rule(node) {
this.block(node, this.rawValue(node, 'selector'));
if (node.raws.ownSemicolon) {
this.builder(escapeHTMLInCSS(node.raws.ownSemicolon), node, 'end');
}
}
stringify(node, semicolon) {
/* c8 ignore start */
if (!this[node.type]) {
throw new Error(
'Unknown AST node type ' +
node.type +
'. ' +
'Maybe you need to change PostCSS stringifier.'
)
}
/* c8 ignore stop */
this[node.type](node, semicolon);
}
}
stringifier = Stringifier;
Stringifier.default = Stringifier;
return stringifier;
}
var stringify_1;
var hasRequiredStringify;
function requireStringify () {
if (hasRequiredStringify) return stringify_1;
hasRequiredStringify = 1;
let Stringifier = requireStringifier();
function stringify(node, builder) {
let str = new Stringifier(builder);
str.stringify(node);
}
stringify_1 = stringify;
stringify.default = stringify;
return stringify_1;
}
var symbols = {};
var hasRequiredSymbols;
function requireSymbols () {
if (hasRequiredSymbols) return symbols;
hasRequiredSymbols = 1;
symbols.isClean = Symbol('isClean');
symbols.my = Symbol('my');
return symbols;
}
var node;
var hasRequiredNode$1;
function requireNode$1 () {
if (hasRequiredNode$1) return node;
hasRequiredNode$1 = 1;
let CssSyntaxError = requireCssSyntaxError();
let Stringifier = requireStringifier();
let stringify = requireStringify();
let { isClean, my } = requireSymbols();
function cloneNode(obj, parent) {
let cloned = new obj.constructor();
// An explicit stack instead of recursive calls to survive deeply
// nested trees. Each entry is [source, its clone, clone's parent].
let stack = [[obj, cloned, parent]];
while (stack.length > 0) {
let [source, target, targetParent] = stack.pop();
for (let i in source) {
if (!Object.prototype.hasOwnProperty.call(source, i)) {
/* c8 ignore next 2 */
continue
}
if (i === 'proxyCache') continue
let value = source[i];
let type = typeof value;
if (i === 'parent' && type === 'object') {
if (targetParent) target[i] = targetParent;
} else if (i === 'source') {
target[i] = value;
} else if (Array.isArray(value)) {
let children = [];
target[i] = children;
for (let j of value) {
let childClone = new j.constructor();
children.push(childClone);
stack.push([j, childClone, target]);
}
} else {
if (type === 'object' && value !== null) {
let valueClone = new value.constructor();
stack.push([value, valueClone, undefined]);
value = valueClone;
}
target[i] = value;
}
}
}
return cloned
}
function sourceOffset(inputCSS, position) {
// Not all custom syntaxes support `offset` in `source.start` and `source.end`
if (position && typeof position.offset !== 'undefined') {
return position.offset
}
let column = 1;
let line = 1;
let offset = 0;
for (let i = 0; i < inputCSS.length; i++) {
if (line === position.line && column === position.column) {
offset = i;
break
}
if (inputCSS[i] === '\n') {
column = 1;
line += 1;
} else {
column += 1;
}
}
return offset
}
class Node {
get proxyOf() {
return this
}
constructor(defaults = {}) {
this.raws = {};
this[isClean] = false;
this[my] = true;
for (let name of Object.keys(defaults)) {
if (name === '__proto__') continue
if (name === 'nodes') {
this.nodes = [];
for (let node of defaults[name]) {
// Clone only nodes that already belong to another tree, so passing a
// freshly created (parent-less) node adopts that instance instead of
// a copy and keeps the caller's reference usable. See #1987.
if (typeof node.clone === 'function' && node.parent) {
this.append(node.clone());
} else {
this.append(node);
}
}
} else {
this[name] = defaults[name];
}
}
}
addToError(error) {
error.postcssNode = this;
if (error.stack && this.source && /\n\s{4}at /.test(error.stack)) {
let s = this.source;
error.stack = error.stack.replace(
/\n\s{4}at /,
`$&${s.input.from}:${s.start.line}:${s.start.column}$&`
);
}
return error
}
after(add) {
this.parent.insertAfter(this, add);
return this
}
assign(overrides = {}) {
for (let name in overrides) {
this[name] = overrides[name];
}
return this
}
before(add) {
this.parent.insertBefore(this, add);
return this
}
cleanRaws(keepBetween) {
delete this.raws.before;
delete this.raws.after;
if (!keepBetween) delete this.raws.between;
}
clone(overrides = {}) {
let cloned = cloneNode(this);
for (let name in overrides) {
cloned[name] = overrides[name];
}
return cloned
}
cloneAfter(overrides = {}) {
let cloned = this.clone(overrides);
this.parent.insertAfter(this, cloned);
return cloned
}
cloneBefore(overrides = {}) {
let cloned = this.clone(overrides);
this.parent.insertBefore(this, cloned);
return cloned
}
error(message, opts = {}) {
if (this.source) {
let { end, start } = this.rangeBy(opts);
return this.source.input.error(
message,
{ column: start.column, line: start.line },
{ column: end.column, line: end.line },
opts
)
}
return new CssSyntaxError(message)
}
getProxyProcessor() {
return {
get(node, prop) {
if (prop === 'proxyOf') {
return node
} else if (prop === 'root') {
return () => node.root().toProxy()
} else {
return node[prop]
}
},
set(node, prop, value) {
if (node[prop] === value) return true
node[prop] = value;
if (
prop === 'prop' ||
prop === 'value' ||
prop === 'name' ||
prop === 'params' ||
prop === 'important' ||
/* c8 ignore next */
prop === 'text'
) {
node.markDirty();
}
return true
}
}
}
/* c8 ignore next 3 */
markClean() {
this[isClean] = true;
}
markDirty() {
if (this[isClean]) {
this[isClean] = false;
let next = this;
while ((next = next.parent)) {
next[isClean] = false;
}
}
}
next() {
if (!this.parent) return undefined
let index = this.parent.index(this);
return this.parent.nodes[index + 1]
}
positionBy(opts = {}) {
let inputString =
'document' in this.source.input
? this.source.input.document
: this.source.input.css;
let pos = {
column: this.source.start.column,
line: this.source.start.line,
offset: sourceOffset(inputString, this.source.start)
};
if (opts.index) {
pos = this.positionInside(opts.index);
} else if (opts.word) {
let stringRepresentation = inputString.slice(
sourceOffset(inputString, this.source.start),
sourceOffset(inputString, this.source.end)
);
let index = stringRepresentation.indexOf(opts.word);
if (index !== -1) pos = this.positionInside(index);
}
return pos
}
positionInside(index) {
let column = this.source.start.column;
let line = this.source.start.line;
let inputString =
'document' in this.source.input
? this.source.input.document
: this.source.input.css;
let offset = sourceOffset(inputString, this.source.start);
let end = offset + index;
for (let i = offset; i < end; i++) {
if (inputString[i] === '\n') {
column = 1;
line += 1;
} else {
column += 1;
}
}
return { column, line, offset: end }
}
prev() {
if (!this.parent) return undefined
let index = this.parent.index(this);
return this.parent.nodes[index - 1]
}
rangeBy(opts = {}) {
let inputString =
'document' in this.source.input
? this.source.input.document
: this.source.input.css;
let start = {
column: this.source.start.column,
line: this.source.start.line,
offset: sourceOffset(inputString, this.source.start)
};
let end = this.source.end
? {
column: this.source.end.column + 1,
line: this.source.end.line,
offset:
typeof this.source.end.offset === 'number'
? // `source.end.offset` is exclusive, so we don't need to add 1
this.source.end.offset
: // Since line/column in this.source.end is inclusive,
// the `sourceOffset(... , this.source.end)` returns an inclusive offset.
// So, we add 1 to convert it to exclusive.
sourceOffset(inputString, this.source.end) + 1
}
: {
column: start.column + 1,
line: start.line,
offset: start.offset + 1
};
if (opts.word) {
let stringRepresentation = inputString.slice(
sourceOffset(inputString, this.source.start),
sourceOffset(inputString, this.source.end)
);
let index = stringRepresentation.indexOf(opts.word);
if (index !== -1) {
start = this.positionInside(index);
end = this.positionInside(index + opts.word.length);
}
} else {
if (opts.start) {
start = {
column: opts.start.column,
line: opts.start.line,
offset: sourceOffset(inputString, opts.start)
};
} else if (typeof opts.index === 'number') {
start = this.positionInside(opts.index);
}
if (opts.end) {
end = {
column: opts.end.column,
line: opts.end.line,
offset: sourceOffset(inputString, opts.end)
};
} else if (typeof opts.endIndex === 'number') {
end = this.positionInside(opts.endIndex);
} else if (typeof opts.index === 'number') {
end = this.positionInside(opts.index + 1);
}
}
if (
end.line < start.line ||
(end.line === start.line && end.column <= start.column)
) {
end = {
column: start.column + 1,
line: start.line,
offset: start.offset + 1
};
}
return { end, start }
}
raw(prop, defaultType) {
let str = new Stringifier();
return str.raw(this, prop, defaultType)
}
remove() {
if (this.parent) {
this.parent.removeChild(this);
}
this.parent = undefined;
return this
}
replaceWith(...nodes) {
if (this.parent) {
let bookmark = this;
let foundSelf = false;
for (let node of nodes) {
if (node === this) {
foundSelf = true;
} else if (foundSelf) {
this.parent.insertAfter(bookmark, node);
bookmark = node;
} else {
this.parent.insertBefore(bookmark, node);
}
}
if (!foundSelf) {
this.remove();
}
}
return this
}
root() {
let result = this;
while (result.parent && result.parent.type !== 'document') {
result = result.parent;
}
return result
}
toJSON(_, inputs) {
let emitInputs = inputs == null;
inputs = inputs || new Map();
// A worklist instead of recursive `toJSON()` calls to survive deeply
// nested trees. Each entry converts one node and writes the result
// into the already converted parent by [holder, key].
let holderOfRoot = [];
let queue = [[this, holderOfRoot, 0]];
for (let step = 0; step < queue.length; step++) {
let [node, holder, key] = queue[step];
let fixed = {};
holder[key] = fixed;
for (let name in node) {
if (!Object.prototype.hasOwnProperty.call(node, name)) {
/* c8 ignore next 2 */
continue
}
if (name === 'parent' || name === 'proxyCache') continue
let value = node[name];
if (Array.isArray(value)) {
let fixedArray = [];
fixed[name] = fixedArray;
for (let i = 0; i < value.length; i++) {
let item = value[i];
if (typeof item === 'object' && item.toJSON) {
if (item.toJSON === Node.prototype.toJSON) {
queue.push([item, fixedArray, i]);
} else {
fixedArray[i] = item.toJSON(null, inputs);
}
} else {
fixedArray[i] = item;
}
}
} else if (typeof value === 'object' && value.toJSON) {
if (value.toJSON === Node.prototype.toJSON) {
queue.push([value, fixed, name]);
} else {
fixed[name] = value.toJSON(null, inputs);
}
} else if (name === 'source') {
if (value == null) continue
let inputId = inputs.get(value.input);
if (inputId == null) {
inputId = inputs.size;
inputs.set(value.input, inputId);
}
fixed[name] = {
end: value.end,
inputId,
start: value.start
};
} else {
fixed[name] = value;
}
}
}
let fixed = holderOfRoot[0];
if (emitInputs) {
fixed.inputs = [...inputs.keys()].map(input => input.toJSON());
}
return fixed
}
toProxy() {
if (!this.proxyCache) {
this.proxyCache = new Proxy(this, this.getProxyProcessor());
}
return this.proxyCache
}
toString(stringifier = stringify) {
if (stringifier.stringify) stringifier = stringifier.stringify;
let result = '';
stringifier(this, i => {
result += i;
});
return result
}
warn(result, text, opts = {}) {
let data = { node: this };
for (let i in opts) data[i] = opts[i];
return result.warn(text, data)
}
}
node = Node;
Node.default = Node;
return node;
}
var comment;
var hasRequiredComment;
function requireComment () {
if (hasRequiredComment) return comment;
hasRequiredComment = 1;
let Node = requireNode$1();
class Comment extends Node {
constructor(defaults) {
super(defaults);
this.type = 'comment';
}
}
comment = Comment;
Comment.default = Comment;
return comment;
}
var declaration;
var hasRequiredDeclaration;
function requireDeclaration () {
if (hasRequiredDeclaration) return declaration;
hasRequiredDeclaration = 1;
let Node = requireNode$1();
class Declaration extends Node {
get variable() {
return this.prop.startsWith('--') || this.prop[0] === '$'
}
constructor(defaults) {
if (
defaults &&
typeof defaults.value !== 'undefined' &&
typeof defaults.value !== 'string'
) {
defaults = { ...defaults, value: String(defaults.value) };
}
super(defaults);
this.type = 'decl';
}
}
declaration = Declaration;
Declaration.default = Declaration;
return declaration;
}
var container;
var hasRequiredContainer$1;
function requireContainer$1 () {
if (hasRequiredContainer$1) return container;
hasRequiredContainer$1 = 1;
let Comment = requireComment();
let Declaration = requireDeclaration();
let Node = requireNode$1();
let { isClean, my } = requireSymbols();
let AtRule, parse, Root, Rule;
function cleanSource(nodes) {
let stack = nodes.slice();
while (stack.length > 0) {
let node = stack.pop();
delete node.source;
if (node.nodes) {
node.nodes = node.nodes.slice();
for (let i of node.nodes) stack.push(i);
}
}
return nodes.slice()
}
function markTreeDirty(node) {
let stack = [node];
while (stack.length > 0) {
let next = stack.pop();
next[isClean] = false;
if (next.proxyOf.nodes) {
for (let i of next.proxyOf.nodes) stack.push(i);
}
}
}
class Container extends Node {
get first() {
if (!this.proxyOf.nodes) return undefined
return this.proxyOf.nodes[0]
}
get last() {
if (!this.proxyOf.nodes) return undefined
return this.proxyOf.nodes[this.proxyOf.nodes.length - 1]
}
append(...children) {
for (let child of children) {
let nodes = this.normalize(child, this.last);
for (let node of nodes) this.proxyOf.nodes.push(node);
}
this.markDirty();
return this
}
cleanRaws(keepBetween) {
let stack = [this];
while (stack.length > 0) {
let node = stack.pop();
if (node !== this && node.cleanRaws !== Container.prototype.cleanRaws) {
// Subclass with own logic; let it handle its subtree
node.cleanRaws(keepBetween);
continue
}
Node.prototype.cleanRaws.call(node, keepBetween);
if (node.nodes) {
for (let child of node.nodes) stack.push(child);
}
}
}
each(callback) {
if (!this.proxyOf.nodes) return undefined
let iterator = this.getIterator();
let index, result;
while (this.indexes[iterator] < this.proxyOf.nodes.length) {
index = this.indexes[iterator];
result = callback(this.proxyOf.nodes[index], index);
if (result === false) break
this.indexes[iterator] += 1;
}
delete this.indexes[iterator];
return result
}
every(condition) {
return this.nodes.every(condition)
}
getIterator() {
if (!this.lastEach) this.lastEach = 0;
if (!this.indexes) this.indexes = {};
this.lastEach += 1;
let iterator = this.lastEach;
this.indexes[iterator] = 0;
return iterator
}
getProxyProcessor() {
return {
get(node, prop) {
if (prop === 'proxyOf') {
return node
} else if (!node[prop]) {
return node[prop]
} else if (
prop === 'each' ||
(typeof prop === 'string' && prop.startsWith('walk'))
) {
return (...args) => {
return node[prop](
...args.map(i => {
if (typeof i === 'function') {
return (child, index) => i(child.toProxy(), index)
} else {
return i
}
})
)
}
} else if (prop === 'every' || prop === 'some') {
return cb => {
return node[prop]((child, ...other) =>
cb(child.toProxy(), ...other)
)
}
} else if (prop === 'root') {
return () => node.root().toProxy()
} else if (prop === 'nodes') {
return node.nodes.map(i => i.toProxy())
} else if (prop === 'first' || prop === 'last') {
return node[prop].toProxy()
} else {
return node[prop]
}
},
set(node, prop, value) {
if (node[prop] === value) return true
node[prop] = value;
if (prop === 'name' || prop === 'params' || prop === 'selector') {
node.markDirty();
}
return true
}
}
}
index(child) {
if (typeof child === 'number') return child
if (child.proxyOf) child = child.proxyOf;
return this.proxyOf.nodes.indexOf(child)
}
insertAfter(exist, add) {
let existIndex = this.index(exist);
let nodes = this.normalize(add, this.proxyOf.nodes[existIndex]).reverse();
existIndex = this.index(exist);
for (let node of nodes) this.proxyOf.nodes.splice(existIndex + 1, 0, node);
let index;
for (let id in this.indexes) {
index = this.indexes[id];
if (existIndex < index) {
this.indexes[id] = index + nodes.length;
}
}
this.markDirty();
return this
}
insertBefore(exist, add) {
let existIndex = this.index(exist);
let type = existIndex === 0 ? 'prepend' : false;
let nodes = this.normalize(
add,
this.proxyOf.nodes[existIndex],
type
).reverse();
existIndex = this.index(exist);
for (let node of nodes) this.proxyOf.nodes.splice(existIndex, 0, node);
let index;
for (let id in this.indexes) {
index = this.indexes[id];
if (existIndex <= index) {
this.indexes[id] = index + nodes.length;
}
}
this.markDirty();
return this
}
normalize(nodes, sample) {
if (typeof nodes === 'string') {
nodes = cleanSource(parse(nodes).nodes);
} else if (typeof nodes === 'undefined') {
nodes = [];
} else if (Array.isArray(nodes)) {
nodes = nodes.slice(0);
for (let i of nodes) {
if (i.parent) i.parent.removeChild(i, 'ignore');
}
} else if (nodes.type === 'root' && this.type !== 'document') {
nodes = nodes.nodes.slice(0);
for (let i of nodes) {
if (i.parent) i.parent.removeChild(i, 'ignore');
}
} else if (nodes.type) {
nodes = [nodes];
} else if (nodes.prop) {
if (typeof nodes.value === 'undefined') {
throw new Error('Value field is missed in node creation')
} else if (typeof nodes.value !== 'string') {
nodes.value = String(nodes.value);
}
nodes = [new Declaration(nodes)];
} else if (nodes.selecto