flow like the river

This commit is contained in:
root 2025-11-07 00:06:12 +01:00
commit 013fe673f3
42435 changed files with 5764238 additions and 0 deletions

View file

@ -0,0 +1,170 @@
'use strict';
function _asyncToGenerator(fn) { return function () { var gen = fn.apply(this, arguments); return new Promise(function (resolve, reject) { function step(key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { return Promise.resolve(value).then(function (value) { step("next", value); }, function (err) { step("throw", err); }); } } return step("next"); }); }; }
function _toArray(arr) { return Array.isArray(arr) ? arr : Array.from(arr); }
const Asset = require('../Asset');
const postcss = require('postcss');
const valueParser = require('postcss-value-parser');
const postcssTransform = require('../transforms/postcss');
const CssSyntaxError = require('postcss/lib/css-syntax-error');
const URL_RE = /url\s*\("?(?![a-z]+:)/;
const IMPORT_RE = /@import/;
const PROTOCOL_RE = /^[a-z]+:/;
class CSSAsset extends Asset {
constructor(name, pkg, options) {
super(name, pkg, options);
this.type = 'css';
}
mightHaveDependencies() {
return !/\.css$/.test(this.name) || IMPORT_RE.test(this.contents) || URL_RE.test(this.contents);
}
parse(code) {
let root = postcss.parse(code, { from: this.name, to: this.name });
return new CSSAst(code, root);
}
collectDependencies() {
this.ast.root.walkAtRules('import', rule => {
let params = valueParser(rule.params).nodes;
var _params = _toArray(params);
let name = _params[0],
media = _params.slice(1);
let dep;
if (name.type === 'string') {
dep = name.value;
} else if (name.type === 'function' && name.value === 'url' && name.nodes.length) {
dep = name.nodes[0].value;
}
if (!dep) {
throw new Error('Could not find import name for ' + rule);
}
if (PROTOCOL_RE.test(dep)) {
return;
}
media = valueParser.stringify(media).trim();
this.addDependency(dep, { media, loc: rule.source.start });
rule.remove();
this.ast.dirty = true;
});
this.ast.root.walkDecls(decl => {
if (URL_RE.test(decl.value)) {
let parsed = valueParser(decl.value);
let dirty = false;
parsed.walk(node => {
if (node.type === 'function' && node.value === 'url' && node.nodes.length) {
let url = this.addURLDependency(node.nodes[0].value, {
loc: decl.source.start
});
dirty = node.nodes[0].value !== url;
node.nodes[0].value = url;
}
});
if (dirty) {
decl.value = parsed.toString();
this.ast.dirty = true;
}
}
});
}
transform() {
var _this = this;
return _asyncToGenerator(function* () {
yield postcssTransform(_this);
})();
}
getCSSAst() {
// Converts the ast to a CSS ast if needed, so we can apply postcss transforms.
if (!(this.ast instanceof CSSAst)) {
this.ast = CSSAsset.prototype.parse.call(this, this.ast.render());
}
return this.ast.root;
}
generate() {
let css = this.ast ? this.ast.render() : this.contents;
let js = '';
if (this.options.hmr) {
this.addDependency('_css_loader');
js = `
var reloadCSS = require('_css_loader');
module.hot.dispose(reloadCSS);
module.hot.accept(reloadCSS);
`;
}
if (this.cssModules) {
js += 'module.exports = ' + JSON.stringify(this.cssModules, false, 2) + ';';
}
return [{
type: 'css',
value: css,
cssModules: this.cssModules
}, {
type: 'js',
value: js,
final: true
}];
}
generateErrorMessage(err) {
// Wrap the error in a CssSyntaxError if needed so we can generate a code frame
if (err.loc && !err.showSourceCode) {
err = new CssSyntaxError(err.message, err.loc.line, err.loc.column, this.contents);
}
err.message = err.reason || err.message;
err.loc = {
line: err.line,
column: err.column
};
if (err.showSourceCode) {
err.codeFrame = err.showSourceCode();
err.highlightedCodeFrame = err.showSourceCode(true);
}
return err;
}
}
class CSSAst {
constructor(css, root) {
this.css = css;
this.root = root;
this.dirty = false;
}
render() {
if (this.dirty) {
this.css = '';
postcss.stringify(this.root, c => this.css += c);
}
return this.css;
}
}
module.exports = CSSAsset;

View file

@ -0,0 +1,42 @@
'use strict';
function _asyncToGenerator(fn) { return function () { var gen = fn.apply(this, arguments); return new Promise(function (resolve, reject) { function step(key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { return Promise.resolve(value).then(function (value) { step("next", value); }, function (err) { step("throw", err); }); } } return step("next"); }); }; }
const Asset = require('../Asset');
const localRequire = require('../utils/localRequire');
class CoffeeScriptAsset extends Asset {
constructor(name, pkg, options) {
super(name, pkg, options);
this.type = 'js';
}
generate() {
var _this = this;
return _asyncToGenerator(function* () {
// require coffeescript, installed locally in the app
let coffee = yield localRequire('coffeescript', _this.name);
// Transpile Module using CoffeeScript and parse result as ast format through babylon
let transpiled = coffee.compile(_this.contents, {
sourceMap: _this.options.sourceMaps
});
let sourceMap;
if (transpiled.sourceMap) {
sourceMap = transpiled.sourceMap.generate();
sourceMap.sources = [_this.relativeName];
sourceMap.sourcesContent = [_this.contents];
}
return [{
type: 'js',
value: _this.options.sourceMaps ? transpiled.js : transpiled,
sourceMap
}];
})();
}
}
module.exports = CoffeeScriptAsset;

View file

@ -0,0 +1,98 @@
'use strict';
function _asyncToGenerator(fn) { return function () { var gen = fn.apply(this, arguments); return new Promise(function (resolve, reject) { function step(key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { return Promise.resolve(value).then(function (value) { step("next", value); }, function (err) { step("throw", err); }); } } return step("next"); }); }; }
const Asset = require('../Asset');
const localRequire = require('../utils/localRequire');
const path = require('path');
const promisify = require('../utils/promisify');
const Resolver = require('../Resolver');
class GLSLAsset extends Asset {
constructor(name, pkg, options) {
super(name, pkg, options);
this.type = 'js';
}
parse() {
var _this = this;
return _asyncToGenerator(function* () {
const glslifyDeps = yield localRequire('glslify-deps', _this.name);
// Use the Parcel resolver rather than the default glslify one.
// This adds support for parcel features like alises, and tilde paths.
const resolver = new Resolver({
extensions: ['.glsl', '.vert', '.frag'],
rootDir: _this.options.rootDir
});
// Parse and collect dependencies with glslify-deps
let cwd = path.dirname(_this.name);
let depper = glslifyDeps({
cwd,
resolve: (() => {
var _ref = _asyncToGenerator(function* (target, opts, next) {
try {
let res = yield resolver.resolve(target, path.join(opts.basedir, 'index'));
next(null, res.path);
} catch (err) {
next(err);
}
});
return function resolve(_x, _x2, _x3) {
return _ref.apply(this, arguments);
};
})()
});
return yield promisify(depper.inline.bind(depper))(_this.contents, cwd);
})();
}
collectDependencies() {
var _iteratorNormalCompletion = true;
var _didIteratorError = false;
var _iteratorError = undefined;
try {
for (var _iterator = this.ast[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
let dep = _step.value;
if (!dep.entry) {
this.addDependency(dep.file, { includedInParent: true });
}
}
} catch (err) {
_didIteratorError = true;
_iteratorError = err;
} finally {
try {
if (!_iteratorNormalCompletion && _iterator.return) {
_iterator.return();
}
} finally {
if (_didIteratorError) {
throw _iteratorError;
}
}
}
}
generate() {
var _this2 = this;
return _asyncToGenerator(function* () {
// Generate the bundled glsl file
const glslifyBundle = yield localRequire('glslify-bundle', _this2.name);
let glsl = glslifyBundle(_this2.ast);
return {
js: `module.exports=${JSON.stringify(glsl)};`
};
})();
}
}
module.exports = GLSLAsset;

View file

@ -0,0 +1,107 @@
'use strict';
function _asyncToGenerator(fn) { return function () { var gen = fn.apply(this, arguments); return new Promise(function (resolve, reject) { function step(key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { return Promise.resolve(value).then(function (value) { step("next", value); }, function (err) { step("throw", err); }); } } return step("next"); }); }; }
const Asset = require('../Asset');
const glob = require('glob');
const micromatch = require('micromatch');
const path = require('path');
class GlobAsset extends Asset {
constructor(name, pkg, options) {
super(name, pkg, options);
this.type = null; // allows this asset to be included in any type bundle
}
load() {
var _this = this;
return _asyncToGenerator(function* () {
let regularExpressionSafeName = _this.name;
if (process.platform === 'win32') regularExpressionSafeName = regularExpressionSafeName.replace(/\\/g, '/');
let files = glob.sync(regularExpressionSafeName, {
strict: true,
nodir: true
});
let re = micromatch.makeRe(regularExpressionSafeName, { capture: true });
let matches = {};
var _iteratorNormalCompletion = true;
var _didIteratorError = false;
var _iteratorError = undefined;
try {
for (var _iterator = files[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
let file = _step.value;
let match = file.match(re);
let parts = match.slice(1).filter(Boolean).reduce(function (a, p) {
return a.concat(p.split('/'));
}, []);
let relative = './' + path.relative(path.dirname(_this.name), file.normalize('NFC'));
set(matches, parts, relative);
_this.addDependency(relative);
}
} catch (err) {
_didIteratorError = true;
_iteratorError = err;
} finally {
try {
if (!_iteratorNormalCompletion && _iterator.return) {
_iterator.return();
}
} finally {
if (_didIteratorError) {
throw _iteratorError;
}
}
}
return matches;
})();
}
generate() {
return {
js: 'module.exports = ' + generate(this.contents) + ';'
};
}
}
function generate(matches, indent = '') {
if (typeof matches === 'string') {
return `require(${JSON.stringify(matches)})`;
}
let res = indent + '{';
let first = true;
for (let key in matches) {
if (!first) {
res += ',';
}
res += `\n${indent} ${JSON.stringify(key)}: ${generate(matches[key], indent + ' ')}`;
first = false;
}
res += '\n' + indent + '}';
return res;
}
function set(obj, path, value) {
for (let i = 0; i < path.length - 1; i++) {
let part = path[i];
if (obj[part] == null) {
obj[part] = {};
}
obj = obj[part];
}
obj[path[path.length - 1]] = value;
}
module.exports = GlobAsset;

View file

@ -0,0 +1,30 @@
'use strict';
function _asyncToGenerator(fn) { return function () { var gen = fn.apply(this, arguments); return new Promise(function (resolve, reject) { function step(key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { return Promise.resolve(value).then(function (value) { step("next", value); }, function (err) { step("throw", err); }); } } return step("next"); }); }; }
const Asset = require('../Asset');
const localRequire = require('../utils/localRequire');
class GraphqlAsset extends Asset {
constructor(name, pkg, options) {
super(name, pkg, options);
this.type = 'js';
}
parse(code) {
var _this = this;
return _asyncToGenerator(function* () {
let gql = yield localRequire('graphql-tag', _this.name);
return gql(code);
})();
}
generate() {
return {
js: `module.exports=${JSON.stringify(this.ast, false, 2)};`
};
}
}
module.exports = GraphqlAsset;

View file

@ -0,0 +1,165 @@
'use strict';
function _asyncToGenerator(fn) { return function () { var gen = fn.apply(this, arguments); return new Promise(function (resolve, reject) { function step(key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { return Promise.resolve(value).then(function (value) { step("next", value); }, function (err) { step("throw", err); }); } } return step("next"); }); }; }
const Asset = require('../Asset');
const parse = require('posthtml-parser');
const api = require('posthtml/lib/api');
const urlJoin = require('../utils/urlJoin');
const render = require('posthtml-render');
const posthtmlTransform = require('../transforms/posthtml');
const htmlnanoTransform = require('../transforms/htmlnano');
const isURL = require('../utils/is-url');
// A list of all attributes that may produce a dependency
// Based on https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes
const ATTRS = {
src: ['script', 'img', 'audio', 'video', 'source', 'track', 'iframe', 'embed'],
href: ['link', 'a', 'use'],
srcset: ['img', 'source'],
poster: ['video'],
'xlink:href': ['use'],
content: ['meta'],
data: ['object']
};
// A list of metadata that should produce a dependency
// Based on:
// - http://schema.org/
// - http://ogp.me
// - https://developer.twitter.com/en/docs/tweets/optimize-with-cards/overview/markup
// - https://msdn.microsoft.com/en-us/library/dn255024.aspx
const META = {
property: ['og:image', 'og:image:url', 'og:image:secure_url', 'og:audio', 'og:audio:secure_url', 'og:video', 'og:video:secure_url'],
name: ['twitter:image', 'msapplication-square150x150logo', 'msapplication-square310x310logo', 'msapplication-square70x70logo', 'msapplication-wide310x150logo', 'msapplication-TileImage'],
itemprop: ['image', 'logo', 'screenshot', 'thumbnailUrl', 'contentUrl', 'downloadUrl']
};
// Options to be passed to `addURLDependency` for certain tags + attributes
const OPTIONS = {
a: {
href: { entry: true }
},
iframe: {
src: { entry: true }
}
};
class HTMLAsset extends Asset {
constructor(name, pkg, options) {
super(name, pkg, options);
this.type = 'html';
this.isAstDirty = false;
}
parse(code) {
let res = parse(code, { lowerCaseAttributeNames: true });
res.walk = api.walk;
res.match = api.match;
return res;
}
processSingleDependency(path, opts) {
let assetPath = this.addURLDependency(path, opts);
if (!isURL(assetPath)) {
assetPath = urlJoin(this.options.publicURL, assetPath);
}
return assetPath;
}
collectSrcSetDependencies(srcset, opts) {
const newSources = [];
var _iteratorNormalCompletion = true;
var _didIteratorError = false;
var _iteratorError = undefined;
try {
for (var _iterator = srcset.split(',')[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
const source = _step.value;
const pair = source.trim().split(' ');
if (pair.length === 0) continue;
pair[0] = this.processSingleDependency(pair[0], opts);
newSources.push(pair.join(' '));
}
} catch (err) {
_didIteratorError = true;
_iteratorError = err;
} finally {
try {
if (!_iteratorNormalCompletion && _iterator.return) {
_iterator.return();
}
} finally {
if (_didIteratorError) {
throw _iteratorError;
}
}
}
return newSources.join(',');
}
getAttrDepHandler(attr) {
if (attr === 'srcset') {
return this.collectSrcSetDependencies;
}
return this.processSingleDependency;
}
collectDependencies() {
this.ast.walk(node => {
if (node.attrs) {
if (node.tag === 'meta') {
if (!Object.keys(node.attrs).some(attr => {
let values = META[attr];
return values && values.includes(node.attrs[attr]);
})) {
return node;
}
}
for (let attr in node.attrs) {
let elements = ATTRS[attr];
// Check for virtual paths
if (node.tag === 'a' && node.attrs[attr].lastIndexOf('.') < 1) {
continue;
}
if (elements && elements.includes(node.tag)) {
let depHandler = this.getAttrDepHandler(attr);
let options = OPTIONS[node.tag];
node.attrs[attr] = depHandler.call(this, node.attrs[attr], options && options[attr]);
this.isAstDirty = true;
}
}
}
return node;
});
}
pretransform() {
var _this = this;
return _asyncToGenerator(function* () {
yield posthtmlTransform(_this);
})();
}
transform() {
var _this2 = this;
return _asyncToGenerator(function* () {
if (_this2.options.minify) {
yield htmlnanoTransform(_this2);
}
})();
}
generate() {
return this.isAstDirty ? render(this.ast) : this.contents;
}
}
module.exports = HTMLAsset;

View file

@ -0,0 +1,209 @@
'use strict';
function _asyncToGenerator(fn) { return function () { var gen = fn.apply(this, arguments); return new Promise(function (resolve, reject) { function step(key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { return Promise.resolve(value).then(function (value) { step("next", value); }, function (err) { step("throw", err); }); } } return step("next"); }); }; }
var _require = require('babel-core');
const BabelFile = _require.File;
const traverse = require('babel-traverse').default;
const codeFrame = require('babel-code-frame');
const collectDependencies = require('../visitors/dependencies');
const walk = require('babylon-walk');
const Asset = require('../Asset');
const babylon = require('babylon');
const insertGlobals = require('../visitors/globals');
const fsVisitor = require('../visitors/fs');
const envVisitor = require('../visitors/env');
const babel = require('../transforms/babel');
const generate = require('babel-generator').default;
const uglify = require('../transforms/uglify');
const SourceMap = require('../SourceMap');
const IMPORT_RE = /\b(?:import\b|export\b|require\s*\()/;
const ENV_RE = /\b(?:process\.env)\b/;
const GLOBAL_RE = /\b(?:process|__dirname|__filename|global|Buffer|define)\b/;
const FS_RE = /\breadFileSync\b/;
const SW_RE = /\bnavigator\s*\.\s*serviceWorker\s*\.\s*register\s*\(/;
const WORKER_RE = /\bnew\s*Worker\s*\(/;
class JSAsset extends Asset {
constructor(name, pkg, options) {
super(name, pkg, options);
this.type = 'js';
this.globals = new Map();
this.isAstDirty = false;
this.isES6Module = false;
this.outputCode = null;
this.cacheData.env = {};
this.sourceMap = options.rendition ? options.rendition.sourceMap : null;
}
shouldInvalidate(cacheData) {
for (let key in cacheData.env) {
if (cacheData.env[key] !== process.env[key]) {
return true;
}
}
return false;
}
mightHaveDependencies() {
return this.isAstDirty || !/.js$/.test(this.name) || IMPORT_RE.test(this.contents) || GLOBAL_RE.test(this.contents) || SW_RE.test(this.contents) || WORKER_RE.test(this.contents);
}
getParserOptions() {
var _this = this;
return _asyncToGenerator(function* () {
// Babylon options. We enable a few plugins by default.
const options = {
filename: _this.name,
allowReturnOutsideFunction: true,
allowHashBang: true,
ecmaVersion: Infinity,
strictMode: false,
sourceType: 'module',
locations: true,
plugins: ['exportExtensions', 'dynamicImport']
};
// Check if there is a babel config file. If so, determine which parser plugins to enable
_this.babelConfig = yield babel.getConfig(_this);
if (_this.babelConfig) {
const file = new BabelFile(_this.babelConfig);
options.plugins.push(...file.parserOpts.plugins);
}
return options;
})();
}
parse(code) {
var _this2 = this;
return _asyncToGenerator(function* () {
const options = yield _this2.getParserOptions();
return babylon.parse(code, options);
})();
}
traverse(visitor) {
return traverse(this.ast, visitor, null, this);
}
traverseFast(visitor) {
return walk.simple(this.ast, visitor, this);
}
collectDependencies() {
walk.ancestor(this.ast, collectDependencies, this);
}
pretransform() {
var _this3 = this;
return _asyncToGenerator(function* () {
yield babel(_this3);
// Inline environment variables
if (ENV_RE.test(_this3.contents)) {
yield _this3.parseIfNeeded();
_this3.traverseFast(envVisitor);
}
})();
}
transform() {
var _this4 = this;
return _asyncToGenerator(function* () {
if (_this4.options.target === 'browser') {
if (_this4.dependencies.has('fs') && FS_RE.test(_this4.contents)) {
yield _this4.parseIfNeeded();
_this4.traverse(fsVisitor);
}
if (GLOBAL_RE.test(_this4.contents)) {
yield _this4.parseIfNeeded();
walk.ancestor(_this4.ast, insertGlobals, _this4);
}
}
if (_this4.isES6Module) {
yield babel(_this4);
}
if (_this4.options.minify) {
yield uglify(_this4);
}
})();
}
generate() {
var _this5 = this;
return _asyncToGenerator(function* () {
let code;
if (_this5.isAstDirty) {
let opts = {
sourceMaps: _this5.options.sourceMaps,
sourceFileName: _this5.relativeName
};
let generated = generate(_this5.ast, opts, _this5.contents);
if (_this5.options.sourceMaps && generated.rawMappings) {
let rawMap = new SourceMap(generated.rawMappings, {
[_this5.relativeName]: _this5.contents
});
// Check if we already have a source map (e.g. from TypeScript or CoffeeScript)
// In that case, we need to map the original source map to the babel generated one.
if (_this5.sourceMap) {
_this5.sourceMap = yield new SourceMap().extendSourceMap(_this5.sourceMap, rawMap);
} else {
_this5.sourceMap = rawMap;
}
}
code = generated.code;
} else {
code = _this5.outputCode || _this5.contents;
}
if (_this5.options.sourceMaps && !_this5.sourceMap) {
_this5.sourceMap = new SourceMap().generateEmptyMap(_this5.relativeName, _this5.contents);
}
if (_this5.globals.size > 0) {
code = Array.from(_this5.globals.values()).join('\n') + '\n' + code;
if (_this5.options.sourceMaps) {
if (!(_this5.sourceMap instanceof SourceMap)) {
_this5.sourceMap = yield new SourceMap().addMap(_this5.sourceMap);
}
_this5.sourceMap.offset(_this5.globals.size);
}
}
return {
js: code,
map: _this5.sourceMap
};
})();
}
generateErrorMessage(err) {
const loc = err.loc;
if (loc) {
err.codeFrame = codeFrame(this.contents, loc.line, loc.column + 1);
err.highlightedCodeFrame = codeFrame(this.contents, loc.line, loc.column + 1, { highlightCode: true });
}
return err;
}
}
module.exports = JSAsset;

View file

@ -0,0 +1,40 @@
'use strict';
const Asset = require('../Asset');
const path = require('path');
const json5 = require('json5');
var _require = require('uglify-es');
const minify = _require.minify;
class JSONAsset extends Asset {
constructor(name, pkg, options) {
super(name, pkg, options);
this.type = 'js';
}
parse(code) {
return path.extname(this.name) === '.json5' ? json5.parse(code) : null;
}
generate() {
let code = `module.exports = ${this.ast ? JSON.stringify(this.ast, null, 2) : this.contents};`;
if (this.options.minify) {
let minified = minify(code);
if (minified.error) {
throw minified.error;
}
code = minified.code;
}
return {
js: code
};
}
}
module.exports = JSONAsset;

View file

@ -0,0 +1,83 @@
'use strict';
function _asyncToGenerator(fn) { return function () { var gen = fn.apply(this, arguments); return new Promise(function (resolve, reject) { function step(key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { return Promise.resolve(value).then(function (value) { step("next", value); }, function (err) { step("throw", err); }); } } return step("next"); }); }; }
const Asset = require('../Asset');
const localRequire = require('../utils/localRequire');
const promisify = require('../utils/promisify');
class LESSAsset extends Asset {
constructor(name, pkg, options) {
super(name, pkg, options);
this.type = 'css';
}
parse(code) {
var _this = this;
return _asyncToGenerator(function* () {
// less should be installed locally in the module that's being required
let less = yield localRequire('less', _this.name);
let render = promisify(less.render.bind(less));
let opts = Object.assign({}, _this.package.less || (yield _this.getConfig(['.lessrc', '.lessrc.js'])));
opts.filename = _this.name;
opts.plugins = (opts.plugins || []).concat(urlPlugin(_this));
return yield render(code, opts);
})();
}
collectDependencies() {
var _iteratorNormalCompletion = true;
var _didIteratorError = false;
var _iteratorError = undefined;
try {
for (var _iterator = this.ast.imports[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
let dep = _step.value;
this.addDependency(dep, { includedInParent: true });
}
} catch (err) {
_didIteratorError = true;
_iteratorError = err;
} finally {
try {
if (!_iteratorNormalCompletion && _iterator.return) {
_iterator.return();
}
} finally {
if (_didIteratorError) {
throw _iteratorError;
}
}
}
}
generate() {
return [{
type: 'css',
value: this.ast ? this.ast.css : '',
hasDependencies: false
}];
}
}
function urlPlugin(asset) {
return {
install: (less, pluginManager) => {
let visitor = new less.visitors.Visitor({
visitUrl: node => {
node.value.value = asset.addURLDependency(node.value.value, node.currentFileInfo.filename);
return node;
}
});
visitor.run = visitor.visit;
pluginManager.addVisitor(visitor);
}
};
}
module.exports = LESSAsset;

View file

@ -0,0 +1,67 @@
'use strict';
function _asyncToGenerator(fn) { return function () { var gen = fn.apply(this, arguments); return new Promise(function (resolve, reject) { function step(key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { return Promise.resolve(value).then(function (value) { step("next", value); }, function (err) { step("throw", err); }); } } return step("next"); }); }; }
const path = require('path');
const Asset = require('../Asset');
const localRequire = require('../utils/localRequire');
class PugAsset extends Asset {
constructor(name, pkg, options) {
super(name, pkg, options);
this.type = 'html';
}
generate() {
var _this = this;
return _asyncToGenerator(function* () {
const pug = yield localRequire('pug', _this.name);
const config = (yield _this.getConfig(['.pugrc', '.pugrc.js', 'pug.config.js'])) || {};
const compiled = pug.compile(_this.contents, {
compileDebug: false,
filename: _this.name,
basedir: path.dirname(_this.name),
pretty: !_this.options.minify,
templateName: path.basename(_this.basename, path.extname(_this.basename)),
filters: config.filters,
filterOptions: config.filterOptions,
filterAliases: config.filterAliases
});
if (compiled.dependencies) {
var _iteratorNormalCompletion = true;
var _didIteratorError = false;
var _iteratorError = undefined;
try {
for (var _iterator = compiled.dependencies[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
let item = _step.value;
_this.addDependency(item, {
includedInParent: true
});
}
} catch (err) {
_didIteratorError = true;
_iteratorError = err;
} finally {
try {
if (!_iteratorNormalCompletion && _iterator.return) {
_iterator.return();
}
} finally {
if (_didIteratorError) {
throw _iteratorError;
}
}
}
}
return compiled();
})();
}
}
module.exports = PugAsset;

View file

@ -0,0 +1,36 @@
'use strict';
function _asyncToGenerator(fn) { return function () { var gen = fn.apply(this, arguments); return new Promise(function (resolve, reject) { function step(key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { return Promise.resolve(value).then(function (value) { step("next", value); }, function (err) { step("throw", err); }); } } return step("next"); }); }; }
const Asset = require('../Asset');
const urlJoin = require('../utils/urlJoin');
const md5 = require('../utils/md5');
class RawAsset extends Asset {
// Don't load raw assets. They will be copied by the RawPackager directly.
load() {}
generate() {
// Don't return a URL to the JS bundle if there is a bundle loader defined for this asset type.
// This will cause the actual asset to be automatically preloaded prior to the JS bundle running.
if (this.options.bundleLoaders[this.type]) {
return {};
}
const pathToAsset = urlJoin(this.options.publicURL, this.generateBundleName());
return {
js: `module.exports=${JSON.stringify(pathToAsset)};`
};
}
generateHash() {
var _this = this;
return _asyncToGenerator(function* () {
return yield md5.file(_this.name);
})();
}
}
module.exports = RawAsset;

View file

@ -0,0 +1,38 @@
'use strict';
function _asyncToGenerator(fn) { return function () { var gen = fn.apply(this, arguments); return new Promise(function (resolve, reject) { function step(key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { return Promise.resolve(value).then(function (value) { step("next", value); }, function (err) { step("throw", err); }); } } return step("next"); }); }; }
const Asset = require('../Asset');
const fs = require('../utils/fs');
const localRequire = require('../utils/localRequire');
class ReasonAsset extends Asset {
constructor(name, pkg, options) {
super(name, pkg, options);
this.type = 'js';
}
generate() {
var _this = this;
return _asyncToGenerator(function* () {
const bsb = yield localRequire('bsb-js', _this.name);
// This runs BuckleScript - the Reason to JS compiler.
// Other Asset types use `localRequire` but the `bsb-js` package already
// does that internally. This should also take care of error handling in
// the Reason compilation process.
if (process.env.NODE_ENV !== 'test') {
yield bsb.runBuild();
}
// This is a simplified use-case for Reason - it only loads the recommended
// BuckleScript configuration to simplify the file processing.
const outputFile = _this.name.replace(/\.(re|ml)$/, '.bs.js');
const outputContent = yield fs.readFile(outputFile);
return outputContent.toString();
})();
}
}
module.exports = ReasonAsset;

View file

@ -0,0 +1,245 @@
'use strict';
var _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }();
function _asyncToGenerator(fn) { return function () { var gen = fn.apply(this, arguments); return new Promise(function (resolve, reject) { function step(key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { return Promise.resolve(value).then(function (value) { step("next", value); }, function (err) { step("throw", err); }); } } return step("next"); }); }; }
const path = require('path');
const commandExists = require('command-exists');
const childProcess = require('child_process');
const promisify = require('../utils/promisify');
const exec = promisify(childProcess.execFile);
const tomlify = require('tomlify-j0.4');
const fs = require('../utils/fs');
const Asset = require('../Asset');
const config = require('../utils/config');
const pipeSpawn = require('../utils/pipeSpawn');
const md5 = require('../utils/md5');
const RUST_TARGET = 'wasm32-unknown-unknown';
const MAIN_FILES = ['src/lib.rs', 'src/main.rs'];
// Track installation status so we don't need to check more than once
let rustInstalled = false;
let wasmGCInstalled = false;
class RustAsset extends Asset {
constructor(name, pkg, options) {
super(name, pkg, options);
this.type = 'wasm';
}
process() {
// We don't want to process this asset if the worker is in a warm up phase
// since the asset will also be processed by the main process, which
// may cause errors since rust writes to the filesystem.
if (this.options.isWarmUp) {
return;
}
return super.process();
}
parse() {
var _this = this;
return _asyncToGenerator(function* () {
// Install rust toolchain and target if needed
yield _this.installRust();
// See if there is a Cargo config in the project
let cargoConfig = yield _this.getConfig(['Cargo.toml']);
let cargoDir;
let isMainFile = false;
if (cargoConfig) {
const mainFiles = MAIN_FILES.slice();
if (cargoConfig.lib && cargoConfig.lib.path) {
mainFiles.push(cargoConfig.lib.path);
}
cargoDir = path.dirname((yield config.resolve(_this.name, ['Cargo.toml'])));
isMainFile = mainFiles.some(function (file) {
return path.join(cargoDir, file) === _this.name;
});
}
// If this is the main file of a Cargo build, use the cargo command to compile.
// Otherwise, use rustc directly.
if (isMainFile) {
yield _this.cargoBuild(cargoConfig, cargoDir);
} else {
yield _this.rustcBuild();
}
// If this is a prod build, use wasm-gc to remove unused code
if (_this.options.minify) {
yield _this.installWasmGC();
yield exec('wasm-gc', [_this.wasmPath, _this.wasmPath]);
}
})();
}
installRust() {
return _asyncToGenerator(function* () {
if (rustInstalled) {
return;
}
// Check for rustup
try {
yield commandExists('rustup');
} catch (e) {
throw new Error("Rust isn't installed. Visit https://www.rustup.rs/ for more info");
}
// Ensure nightly toolchain is installed
var _ref = yield exec('rustup', ['show']),
_ref2 = _slicedToArray(_ref, 1);
let stdout = _ref2[0];
if (!stdout.includes('nightly')) {
yield pipeSpawn('rustup', ['update']);
yield pipeSpawn('rustup', ['toolchain', 'install', 'nightly']);
}
// Ensure wasm target is installed
var _ref3 = yield exec('rustup', ['target', 'list', '--toolchain', 'nightly']);
var _ref4 = _slicedToArray(_ref3, 1);
stdout = _ref4[0];
if (!stdout.includes(RUST_TARGET + ' (installed)')) {
yield pipeSpawn('rustup', ['target', 'add', RUST_TARGET, '--toolchain', 'nightly']);
}
rustInstalled = true;
})();
}
installWasmGC() {
return _asyncToGenerator(function* () {
if (wasmGCInstalled) {
return;
}
try {
yield commandExists('wasm-gc');
} catch (e) {
yield pipeSpawn('cargo', ['install', '--git', 'https://github.com/alexcrichton/wasm-gc']);
}
wasmGCInstalled = true;
})();
}
cargoBuild(cargoConfig, cargoDir) {
var _this2 = this;
return _asyncToGenerator(function* () {
// Ensure the cargo config has cdylib as the crate-type
if (!cargoConfig.lib) {
cargoConfig.lib = {};
}
if (!Array.isArray(cargoConfig.lib['crate-type'])) {
cargoConfig.lib['crate-type'] = [];
}
if (!cargoConfig.lib['crate-type'].includes('cdylib')) {
cargoConfig.lib['crate-type'].push('cdylib');
yield fs.writeFile(path.join(cargoDir, 'Cargo.toml'), tomlify.toToml(cargoConfig));
}
// Run cargo
let args = ['+nightly', 'build', '--target', RUST_TARGET, '--release'];
yield exec('cargo', args, { cwd: cargoDir });
// Get output file paths
let outDir = path.join(cargoDir, 'target', RUST_TARGET, 'release');
// Rust converts '-' to '_' when outputting files.
let rustName = cargoConfig.package.name.replace(/-/g, '_');
_this2.wasmPath = path.join(outDir, rustName + '.wasm');
_this2.depsPath = path.join(outDir, rustName + '.d');
})();
}
rustcBuild() {
var _this3 = this;
return _asyncToGenerator(function* () {
// Get output filename
yield fs.mkdirp(_this3.options.cacheDir);
let name = md5(_this3.name);
_this3.wasmPath = path.join(_this3.options.cacheDir, name + '.wasm');
// Run rustc to compile the code
const args = ['+nightly', '--target', RUST_TARGET, '-O', '--crate-type=cdylib', _this3.name, '-o', _this3.wasmPath];
yield exec('rustc', args);
// Run again to collect dependencies
_this3.depsPath = path.join(_this3.options.cacheDir, name + '.d');
yield exec('rustc', [_this3.name, '--emit=dep-info', '-o', _this3.depsPath]);
})();
}
collectDependencies() {
var _this4 = this;
return _asyncToGenerator(function* () {
// Read deps file
let contents = yield fs.readFile(_this4.depsPath, 'utf8');
let dir = path.dirname(_this4.name);
let deps = contents.split('\n').filter(Boolean).slice(1);
var _iteratorNormalCompletion = true;
var _didIteratorError = false;
var _iteratorError = undefined;
try {
for (var _iterator = deps[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
let dep = _step.value;
dep = path.resolve(dir, dep.slice(0, dep.indexOf(':')));
if (dep !== _this4.name) {
_this4.addDependency(dep, { includedInParent: true });
}
}
} catch (err) {
_didIteratorError = true;
_iteratorError = err;
} finally {
try {
if (!_iteratorNormalCompletion && _iterator.return) {
_iterator.return();
}
} finally {
if (_didIteratorError) {
throw _iteratorError;
}
}
}
})();
}
generate() {
var _this5 = this;
return _asyncToGenerator(function* () {
return {
wasm: {
path: _this5.wasmPath, // pass output path to RawPackager
mtime: Date.now() // force re-bundling since otherwise the hash would never change
}
};
})();
}
}
module.exports = RustAsset;

View file

@ -0,0 +1,95 @@
'use strict';
function _asyncToGenerator(fn) { return function () { var gen = fn.apply(this, arguments); return new Promise(function (resolve, reject) { function step(key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { return Promise.resolve(value).then(function (value) { step("next", value); }, function (err) { step("throw", err); }); } } return step("next"); }); }; }
const Asset = require('../Asset');
const localRequire = require('../utils/localRequire');
const promisify = require('../utils/promisify');
const path = require('path');
const os = require('os');
const Resolver = require('../Resolver');
const syncPromise = require('../utils/syncPromise');
class SASSAsset extends Asset {
constructor(name, pkg, options) {
super(name, pkg, options);
this.type = 'css';
}
parse(code) {
var _this = this;
return _asyncToGenerator(function* () {
// node-sass should be installed locally in the module that's being required
let sass = yield localRequire('node-sass', _this.name);
let render = promisify(sass.render.bind(sass));
const resolver = new Resolver({
extensions: ['.scss', '.sass'],
rootDir: _this.options.rootDir
});
let opts = Object.assign({}, _this.package.sass || (yield _this.getConfig(['.sassrc', '.sassrc.js'])));
opts.includePaths = (opts.includePaths || []).concat(path.dirname(_this.name));
opts.data = opts.data ? opts.data + os.EOL + code : code;
opts.indentedSyntax = typeof opts.indentedSyntax === 'boolean' ? opts.indentedSyntax : path.extname(_this.name).toLowerCase() === '.sass';
opts.functions = Object.assign({}, opts.functions, {
url: function url(node) {
let filename = _this.addURLDependency(node.getValue());
return new sass.types.String(`url(${JSON.stringify(filename)})`);
}
});
opts.importer = function (url, prev, done) {
let resolved;
try {
resolved = syncPromise(resolver.resolve(url, prev === 'stdin' ? _this.name : prev)).path;
} catch (e) {
resolved = url;
}
return done({
file: resolved
});
};
return yield render(opts);
})();
}
collectDependencies() {
var _iteratorNormalCompletion = true;
var _didIteratorError = false;
var _iteratorError = undefined;
try {
for (var _iterator = this.ast.stats.includedFiles[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
let dep = _step.value;
this.addDependency(dep, { includedInParent: true });
}
} catch (err) {
_didIteratorError = true;
_iteratorError = err;
} finally {
try {
if (!_iteratorNormalCompletion && _iterator.return) {
_iterator.return();
}
} finally {
if (_didIteratorError) {
throw _iteratorError;
}
}
}
}
generate() {
return [{
type: 'css',
value: this.ast ? this.ast.css.toString() : '',
hasDependencies: false
}];
}
}
module.exports = SASSAsset;

View file

@ -0,0 +1,138 @@
'use strict';
let createEvaluator = (() => {
var _ref = _asyncToGenerator(function* (asset) {
const Evaluator = yield localRequire('stylus/lib/visitor/evaluator', asset.name);
const utils = yield localRequire('stylus/lib/utils', asset.name);
const resolver = new Resolver(Object.assign({}, asset.options, {
extensions: ['.styl', '.css']
}));
// This is a custom stylus evaluator that extends stylus with support for the node
// require resolution algorithm. It also adds all dependencies to the parcel asset
// tree so the file watcher works correctly, etc.
class CustomEvaluator extends Evaluator {
visitImport(imported) {
let node = this.visit(imported.path).first;
let path = node.string;
if (node.name !== 'url' && path && !URL_RE.test(path)) {
try {
// First try resolving using the node require resolution algorithm.
// This allows stylus files in node_modules to be resolved properly.
// If we find something, update the AST so stylus gets the absolute path to load later.
node.string = syncPromise(resolver.resolve(path, imported.filename)).path;
asset.addDependency(node.string, { includedInParent: true });
} catch (err) {
// If we couldn't resolve, try the normal stylus resolver.
// We just need to do this to keep track of the dependencies - stylus does the real work.
// support optional .styl
if (!/\.styl$/i.test(path)) {
path += '.styl';
}
let found = utils.find(path, this.paths, this.filename);
if (!found) {
found = utils.lookupIndex(node.string, this.paths, this.filename);
}
if (!found) {
let nodeName = imported.once ? 'require' : 'import';
throw new Error('failed to locate @' + nodeName + ' file ' + node.string);
}
var _iteratorNormalCompletion = true;
var _didIteratorError = false;
var _iteratorError = undefined;
try {
for (var _iterator = found[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
let file = _step.value;
asset.addDependency(file, { includedInParent: true });
}
} catch (err) {
_didIteratorError = true;
_iteratorError = err;
} finally {
try {
if (!_iteratorNormalCompletion && _iterator.return) {
_iterator.return();
}
} finally {
if (_didIteratorError) {
throw _iteratorError;
}
}
}
}
}
// Done. Let stylus do its thing.
return super.visitImport(imported);
}
}
return CustomEvaluator;
});
return function createEvaluator(_x) {
return _ref.apply(this, arguments);
};
})();
function _asyncToGenerator(fn) { return function () { var gen = fn.apply(this, arguments); return new Promise(function (resolve, reject) { function step(key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { return Promise.resolve(value).then(function (value) { step("next", value); }, function (err) { step("throw", err); }); } } return step("next"); }); }; }
// const CSSAsset = require('./CSSAsset');
const Asset = require('../Asset');
const localRequire = require('../utils/localRequire');
const Resolver = require('../Resolver');
const syncPromise = require('../utils/syncPromise');
const URL_RE = /^(?:url\s*\(\s*)?['"]?(?:[#/]|(?:https?:)?\/\/)/i;
class StylusAsset extends Asset {
constructor(name, pkg, options) {
super(name, pkg, options);
this.type = 'css';
}
parse(code) {
var _this = this;
return _asyncToGenerator(function* () {
// stylus should be installed locally in the module that's being required
let stylus = yield localRequire('stylus', _this.name);
let opts = _this.package.stylus || (yield _this.getConfig(['.stylusrc', '.stylusrc.js']));
let style = stylus(code, opts);
style.set('filename', _this.name);
style.set('include css', true);
style.set('Evaluator', (yield createEvaluator(_this)));
// Setup a handler for the URL function so we add dependencies for linked assets.
style.define('url', function (node) {
let filename = _this.addURLDependency(node.val, node.filename);
return new stylus.nodes.Literal(`url(${JSON.stringify(filename)})`);
});
return style;
})();
}
generate() {
return [{
type: 'css',
value: this.ast.render(),
hasDependencies: false
}];
}
generateErrorMessage(err) {
let index = err.message.indexOf('\n');
err.codeFrame = err.message.slice(index + 1);
err.message = err.message.slice(0, index);
return err;
}
}
module.exports = StylusAsset;

View file

@ -0,0 +1,24 @@
'use strict';
const Asset = require('../Asset');
const toml = require('toml');
const serializeObject = require('../utils/serializeObject');
class TOMLAsset extends Asset {
constructor(name, pkg, options) {
super(name, pkg, options);
this.type = 'js';
}
parse(code) {
return toml.parse(code);
}
generate() {
return {
js: serializeObject(this.ast, this.options.minify)
};
}
}
module.exports = TOMLAsset;

View file

@ -0,0 +1,64 @@
'use strict';
function _asyncToGenerator(fn) { return function () { var gen = fn.apply(this, arguments); return new Promise(function (resolve, reject) { function step(key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { return Promise.resolve(value).then(function (value) { step("next", value); }, function (err) { step("throw", err); }); } } return step("next"); }); }; }
const Asset = require('../Asset');
const localRequire = require('../utils/localRequire');
class TypeScriptAsset extends Asset {
constructor(name, pkg, options) {
super(name, pkg, options);
this.type = 'js';
}
generate() {
var _this = this;
return _asyncToGenerator(function* () {
// require typescript, installed locally in the app
let typescript = yield localRequire('typescript', _this.name);
let transpilerOptions = {
compilerOptions: {
module: typescript.ModuleKind.CommonJS,
jsx: typescript.JsxEmit.Preserve,
// it brings the generated output from TypeScript closer to that generated by Babel
// see https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-7.html
esModuleInterop: true
},
fileName: _this.relativeName
};
let tsconfig = yield _this.getConfig(['tsconfig.json']);
// Overwrite default if config is found
if (tsconfig) {
transpilerOptions.compilerOptions = Object.assign(transpilerOptions.compilerOptions, tsconfig.compilerOptions);
}
transpilerOptions.compilerOptions.noEmit = false;
transpilerOptions.compilerOptions.sourceMap = _this.options.sourceMaps;
// Transpile Module using TypeScript and parse result as ast format through babylon
let transpiled = typescript.transpileModule(_this.contents, transpilerOptions);
let sourceMap = transpiled.sourceMapText;
if (sourceMap) {
sourceMap = JSON.parse(sourceMap);
sourceMap.sources = [_this.relativeName];
sourceMap.sourcesContent = [_this.contents];
// Remove the source map URL
let content = transpiled.outputText;
transpiled.outputText = content.substring(0, content.lastIndexOf('//# sourceMappingURL'));
}
return [{
type: 'js',
value: transpiled.outputText,
sourceMap
}];
})();
}
}
module.exports = TypeScriptAsset;

View file

@ -0,0 +1,309 @@
'use strict';
function _asyncToGenerator(fn) { return function () { var gen = fn.apply(this, arguments); return new Promise(function (resolve, reject) { function step(key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { return Promise.resolve(value).then(function (value) { step("next", value); }, function (err) { step("throw", err); }); } } return step("next"); }); }; }
const Asset = require('../Asset');
const localRequire = require('../utils/localRequire');
const md5 = require('../utils/md5');
var _require = require('uglify-es');
const minify = _require.minify;
class VueAsset extends Asset {
constructor(name, pkg, options) {
super(name, pkg, options);
this.type = 'js';
}
parse(code) {
var _this = this;
return _asyncToGenerator(function* () {
// Is being used in component-compiler-utils, errors if not installed...
_this.vueTemplateCompiler = yield localRequire('vue-template-compiler', _this.name);
_this.vue = yield localRequire('@vue/component-compiler-utils', _this.name);
return _this.vue.parse({
source: code,
needMap: _this.options.sourceMaps,
filename: _this.relativeName, // Used for sourcemaps
sourceRoot: '' // Used for sourcemaps. Override so it doesn't use cwd
});
})();
}
generate() {
var _this2 = this;
return _asyncToGenerator(function* () {
let descriptor = _this2.ast;
let parts = [];
if (descriptor.script) {
parts.push({
type: descriptor.script.lang || 'js',
value: descriptor.script.content,
sourceMap: descriptor.script.map
});
}
if (descriptor.template) {
parts.push({
type: descriptor.template.lang || 'html',
value: descriptor.template.content.trim()
});
}
if (descriptor.styles) {
var _iteratorNormalCompletion = true;
var _didIteratorError = false;
var _iteratorError = undefined;
try {
for (var _iterator = descriptor.styles[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
let style = _step.value;
parts.push({
type: style.lang || 'css',
value: style.content.trim(),
modules: !!style.module
});
}
} catch (err) {
_didIteratorError = true;
_iteratorError = err;
} finally {
try {
if (!_iteratorNormalCompletion && _iterator.return) {
_iterator.return();
}
} finally {
if (_didIteratorError) {
throw _iteratorError;
}
}
}
}
return parts;
})();
}
postProcess(generated) {
var _this3 = this;
return _asyncToGenerator(function* () {
let result = [];
let hasScoped = _this3.ast.styles.some(function (s) {
return s.scoped;
});
let id = md5(_this3.name).slice(-6);
let scopeId = hasScoped ? `data-v-${id}` : null;
let optsVar = '$' + id;
// Generate JS output.
let js = _this3.ast.script ? generated[0].value : '';
let supplemental = `
var ${optsVar} = exports.default || module.exports;
if (typeof ${optsVar} === 'function') {
${optsVar} = ${optsVar}.options;
}
`;
supplemental += _this3.compileTemplate(generated, scopeId, optsVar);
supplemental += _this3.compileCSSModules(generated, optsVar);
supplemental += _this3.compileHMR(generated, optsVar);
if (_this3.options.minify && supplemental) {
var _minify = minify(supplemental, { toplevel: true });
let code = _minify.code,
error = _minify.error;
if (error) {
throw error;
}
supplemental = code;
}
js += supplemental;
if (js) {
result.push({
type: 'js',
value: js
});
}
let map = generated.find(function (r) {
return r.type === 'map';
});
if (map) {
result.push(map);
}
let css = _this3.compileStyle(generated, scopeId);
if (css) {
result.push({
type: 'css',
value: css
});
}
return result;
})();
}
compileTemplate(generated, scopeId, optsVar) {
let html = generated.find(r => r.type === 'html');
if (html) {
let isFunctional = this.ast.template.attrs.functional;
let template = this.vue.compileTemplate({
source: html.value,
filename: this.relativeName,
compiler: this.vueTemplateCompiler,
isProduction: this.options.production,
isFunctional,
compilerOptions: {
scopeId
}
});
if (Array.isArray(template.errors) && template.errors.length >= 1) {
throw new Error(template.errors[0]);
}
return `
/* template */
Object.assign(${optsVar}, (function () {
${template.code}
return {
render: render,
staticRenderFns: staticRenderFns,
_compiled: true,
_scopeId: ${JSON.stringify(scopeId)},
functional: ${JSON.stringify(isFunctional)}
};
})());
`;
}
return '';
}
compileCSSModules(generated, optsVar) {
let cssRenditions = generated.filter(r => r.type === 'css');
let cssModulesCode = '';
this.ast.styles.forEach((style, index) => {
if (style.module) {
let cssModules = JSON.stringify(cssRenditions[index].cssModules);
let name = style.module === true ? '$style' : style.module;
cssModulesCode += `\nthis[${JSON.stringify(name)}] = ${cssModules};`;
}
});
if (cssModulesCode) {
cssModulesCode = `function hook(){${cssModulesCode}\n}`;
let isFunctional = this.ast.template && this.ast.template.attrs.functional;
if (isFunctional) {
return `
/* css modules */
(function () {
${cssModulesCode}
${optsVar}._injectStyles = hook;
var originalRender = ${optsVar}.render;
${optsVar}.render = function (h, context) {
hook.call(context);
return originalRender(h, context);
};
})();
`;
} else {
return `
/* css modules */
(function () {
${cssModulesCode}
${optsVar}.beforeCreate = ${optsVar}.beforeCreate ? ${optsVar}.beforeCreate.concat(hook) : [hook];
})();
`;
}
}
return '';
}
compileStyle(generated, scopeId) {
return generated.filter(r => r.type === 'css').reduce((p, r, i) => {
let css = r.value;
let scoped = this.ast.styles[i].scoped;
// Process scoped styles if needed.
if (scoped) {
var _vue$compileStyle = this.vue.compileStyle({
source: css,
filename: this.relativeName,
id: scopeId,
scoped
});
let code = _vue$compileStyle.code,
errors = _vue$compileStyle.errors;
if (errors.length) {
throw errors[0];
}
css = code;
}
return p + css;
}, '');
}
compileHMR(generated, optsVar) {
if (!this.options.hmr) {
return '';
}
this.addDependency('vue-hot-reload-api');
this.addDependency('vue');
let cssHMR = '';
if (this.ast.styles.length) {
cssHMR = `
var reloadCSS = require('_css_loader');
module.hot.dispose(reloadCSS);
module.hot.accept(reloadCSS);
`;
}
let isFunctional = this.ast.template && this.ast.template.attrs.functional;
return `
/* hot reload */
(function () {
if (module.hot) {
var api = require('vue-hot-reload-api');
api.install(require('vue'));
if (api.compatible) {
module.hot.accept();
if (!module.hot.data) {
api.createRecord('${optsVar}', ${optsVar});
} else {
api.${isFunctional ? 'rerender' : 'reload'}('${optsVar}', ${optsVar});
}
}
${cssHMR}
}
})();`;
}
}
module.exports = VueAsset;

View file

@ -0,0 +1,80 @@
'use strict';
const Asset = require('../Asset');
class WebManifestAsset extends Asset {
constructor(name, pkg, options) {
super(name, pkg, options);
this.type = 'webmanifest';
}
parse(content) {
return JSON.parse(content);
}
collectDependencies() {
if (Array.isArray(this.ast.icons)) {
var _iteratorNormalCompletion = true;
var _didIteratorError = false;
var _iteratorError = undefined;
try {
for (var _iterator = this.ast.icons[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
let icon = _step.value;
icon.src = this.addURLDependency(icon.src);
}
} catch (err) {
_didIteratorError = true;
_iteratorError = err;
} finally {
try {
if (!_iteratorNormalCompletion && _iterator.return) {
_iterator.return();
}
} finally {
if (_didIteratorError) {
throw _iteratorError;
}
}
}
}
if (Array.isArray(this.ast.screenshots)) {
var _iteratorNormalCompletion2 = true;
var _didIteratorError2 = false;
var _iteratorError2 = undefined;
try {
for (var _iterator2 = this.ast.screenshots[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {
let shot = _step2.value;
shot.src = this.addURLDependency(shot.src);
}
} catch (err) {
_didIteratorError2 = true;
_iteratorError2 = err;
} finally {
try {
if (!_iteratorNormalCompletion2 && _iterator2.return) {
_iterator2.return();
}
} finally {
if (_didIteratorError2) {
throw _iteratorError2;
}
}
}
}
if (this.ast.serviceworker && this.ast.serviceworker.src) {
this.ast.serviceworker.src = this.addURLDependency(this.ast.serviceworker.src);
}
}
generate() {
return JSON.stringify(this.ast);
}
}
module.exports = WebManifestAsset;

View file

@ -0,0 +1,24 @@
'use strict';
const Asset = require('../Asset');
const yaml = require('js-yaml');
const serializeObject = require('../utils/serializeObject');
class YAMLAsset extends Asset {
constructor(name, pkg, options) {
super(name, pkg, options);
this.type = 'js';
}
parse(code) {
return yaml.safeLoad(code);
}
generate() {
return {
js: serializeObject(this.ast, this.options.minify)
};
}
}
module.exports = YAMLAsset;