UNPKG

fuse-box

Version:

Fuse-Box a bundler that does it right

1,471 lines 411 kB
if (typeof global === "object") { global.require = require; } var _1eb9 = {}; _1eb9.f = {} // cached modules _1eb9.m = {}; _1eb9.s = function(id) { var result = _1eb9.r(id); if (result === undefined) { return require(id); } } _1eb9.r = function(id) { var cached = _1eb9.m[id]; // resolve if in cache if (cached) { return cached.m.exports; } var file = _1eb9.f[id]; if (!file) return; cached = _1eb9.m[id] = {}; cached.exports = {}; cached.m = { exports: cached.exports }; file(cached.m, cached.exports); return cached.m.exports; }; // default/index.js _1eb9.f[0] = function(module,exports){ Object.defineProperty(exports, '__esModule', { value: true }); const CacheBreaker_1 = _1eb9.r(1); const Utils_1 = _1eb9.r(3); CacheBreaker_1.breakCache(); Utils_1.printCurrentVersion(); var WorkflowContext_1 = _1eb9.r(5); exports.Plugin = WorkflowContext_1.Plugin; exports.WorkFlowContext = WorkflowContext_1.WorkFlowContext; var Bundle_1 = _1eb9.r(28); exports.Bundle = Bundle_1.Bundle; var BundleProducer_1 = _1eb9.r(40); exports.BundleProducer = BundleProducer_1.BundleProducer; var FuseBox_1 = _1eb9.r(29); exports.FuseBoxOptions = FuseBox_1.FuseBoxOptions; var QuantumOptions_1 = _1eb9.r(63); exports.IQuantumExtensionParams = QuantumOptions_1.IQuantumExtensionParams; var ComputerStatementRule_1 = _1eb9.r(64); exports.ComputedStatementRule = ComputerStatementRule_1.ComputedStatementRule; var QuantumPlugin_1 = _1eb9.r(65); exports.QuantumPlugin = QuantumPlugin_1.QuantumPlugin; var ReplacePlugin_1 = _1eb9.r(80); exports.ReplacePlugin = ReplacePlugin_1.ReplacePlugin; var VuePlugin_1 = _1eb9.r(81); exports.VuePlugin = VuePlugin_1.VuePlugin; var VuePlugin_2 = _1eb9.r(82); exports.VueComponentPlugin = VuePlugin_2.VueComponentPlugin; var ImageBase64Plugin_1 = _1eb9.r(96); exports.ImageBase64Plugin = ImageBase64Plugin_1.ImageBase64Plugin; var CSSResourcePlugin_1 = _1eb9.r(98); exports.CSSResourcePlugin = CSSResourcePlugin_1.CSSResourcePlugin; var HotReloadPlugin_1 = _1eb9.r(61); exports.HotReloadPlugin = HotReloadPlugin_1.HotReloadPlugin; var EnvPlugin_1 = _1eb9.r(100); exports.EnvPlugin = EnvPlugin_1.EnvPlugin; var ConcatPlugin_1 = _1eb9.r(101); exports.ConcatPlugin = ConcatPlugin_1.ConcatPlugin; var StylusPlugin_1 = _1eb9.r(88); exports.StylusPlugin = StylusPlugin_1.StylusPlugin; var PostCSSPlugin_1 = _1eb9.r(102); exports.PostCSS = PostCSSPlugin_1.PostCSS; var PostCSSPlugin_2 = _1eb9.r(102); exports.PostCSSPlugin = PostCSSPlugin_2.PostCSS; var SVGPlugin_1 = _1eb9.r(103); exports.SVGPlugin = SVGPlugin_1.SVGPlugin; var BabelPlugin_1 = _1eb9.r(90); exports.BabelPlugin = BabelPlugin_1.BabelPlugin; var BublePlugin_1 = _1eb9.r(104); exports.BublePlugin = BublePlugin_1.BublePlugin; var CoffeePlugin_1 = _1eb9.r(91); exports.CoffeePlugin = CoffeePlugin_1.CoffeePlugin; var LESSPlugin_1 = _1eb9.r(86); exports.LESSPlugin = LESSPlugin_1.LESSPlugin; var CSSplugin_1 = _1eb9.r(83); exports.CSSPlugin = CSSplugin_1.CSSPlugin; var HTMLplugin_1 = _1eb9.r(89); exports.HTMLPlugin = HTMLplugin_1.HTMLPlugin; var Markdownplugin_1 = _1eb9.r(105); exports.MarkdownPlugin = Markdownplugin_1.MarkdownPlugin; var JSONplugin_1 = _1eb9.r(34); exports.JSONPlugin = JSONplugin_1.JSONPlugin; var BannerPlugin_1 = _1eb9.r(106); exports.BannerPlugin = BannerPlugin_1.BannerPlugin; var SassPlugin_1 = _1eb9.r(87); exports.SassPlugin = SassPlugin_1.SassPlugin; var UglifyESPlugin_1 = _1eb9.r(107); exports.UglifyESPlugin = UglifyESPlugin_1.UglifyESPlugin; var UglifyJSPlugin_1 = _1eb9.r(108); exports.UglifyJSPlugin = UglifyJSPlugin_1.UglifyJSPlugin; var SourceMapPlainJsPlugin_1 = _1eb9.r(109); exports.SourceMapPlainJsPlugin = SourceMapPlainJsPlugin_1.SourceMapPlainJsPlugin; var RawPlugin_1 = _1eb9.r(110); exports.RawPlugin = RawPlugin_1.RawPlugin; var OptimizeJSPlugin_1 = _1eb9.r(111); exports.OptimizeJSPlugin = OptimizeJSPlugin_1.OptimizeJSPlugin; var Fluent_1 = _1eb9.r(38); exports.Fluent = Fluent_1.Fluent; var FuseBox_2 = _1eb9.r(29); exports.FuseBox = FuseBox_2.FuseBox; var Sparky_1 = _1eb9.r(112); exports.Sparky = Sparky_1.Sparky; var SparkyContext_1 = _1eb9.r(117); exports.SparkyContext = SparkyContext_1.SparkyContext; var Cli_1 = _1eb9.r(118); exports.CLI = Cli_1.CLI; var CSSModules_1 = _1eb9.r(119); exports.CSSModules = CSSModules_1.CSSModules; var CopyPlugin_1 = _1eb9.r(120); exports.CopyPlugin = CopyPlugin_1.CopyPlugin; var WebIndexPlugin_1 = _1eb9.r(121); exports.WebIndexPlugin = WebIndexPlugin_1.WebIndexPlugin; var PlainJSPlugin_1 = _1eb9.r(122); exports.PlainJSPlugin = PlainJSPlugin_1.PlainJSPlugin; var ConsolidatePlugin_1 = _1eb9.r(92); exports.ConsolidatePlugin = ConsolidatePlugin_1.ConsolidatePlugin; var File_1 = _1eb9.r(7); exports.File = File_1.File; const _SparkyCollection = _1eb9.r(123); exports.SparkyCollection = _SparkyCollection; } // default/CacheBreaker.js _1eb9.f[1] = function(module,exports){ Object.defineProperty(exports, '__esModule', { value: true }); const Config_1 = _1eb9.r(2); const path = _1eb9.s('path'); const Utils_1 = _1eb9.r(3); const fs = _1eb9.s('fs'); const Log_1 = _1eb9.r(4); function breakCache() { const mainFile = require.main.filename; const fileKey = Utils_1.fastHash(mainFile); const currentStat = fs.statSync(mainFile); const fileModificationTime = currentStat.mtime.getTime(); const bustingCacheFolder = path.join(Config_1.Config.NODE_MODULES_DIR, 'fuse-box/.cache-busting'); try { Utils_1.ensureDir(bustingCacheFolder); } catch (error) { return; } const infoFile = path.join(bustingCacheFolder, fileKey); if (fs.existsSync(infoFile)) { const lastModifiedStored = fs.readFileSync(infoFile).toString(); if (fileModificationTime.toString() !== lastModifiedStored) { Log_1.Log.defer(log => log.echoGray(`--- cache cleared ---`)); Utils_1.removeFolder(Config_1.Config.TEMP_FOLDER); fs.writeFileSync(infoFile, fileModificationTime.toString()); } } else { fs.writeFileSync(infoFile, fileModificationTime.toString()); } } exports.breakCache = breakCache; } // default/Config.js _1eb9.f[2] = function(module,exports){ var __dirname = "."; Object.defineProperty(exports, '__esModule', { value: true }); const appRoot = _1eb9.s('app-root-path'); const path = _1eb9.s('path'); const PROJECT_ROOT = process.env.FUSEBOX_DIST_ROOT || path.resolve(__dirname); const MAIN_FILE = require.main.filename; if (MAIN_FILE.indexOf('gulp.js') > -1 && !process.env.PROJECT_ROOT) { console.warn('FuseBox wasn\'t able to detect your project root! You are running gulp!'); console.warn('Please set process.env.PROJECT_ROOT'); } class Configuration { constructor() { this.NODE_MODULES_DIR = process.env.PROJECT_NODE_MODULES || path.join(appRoot.path, 'node_modules'); this.FUSEBOX_ROOT = PROJECT_ROOT; this.FUSEBOX_MODULES = process.env.FUSEBOX_MODULES || path.join(PROJECT_ROOT, 'modules'); this.TEMP_FOLDER = process.env.FUSEBOX_TEMP_FOLDER || path.join(appRoot.path, '.fusebox'); this.PROJECT_FOLDER = appRoot.path; this.PROJECT_ROOT = process.env.PROJECT_ROOT || path.dirname(MAIN_FILE); this.FUSEBOX_VERSION = process.env.FUSEBOX_VERSION || _1eb9.s(path.join(PROJECT_ROOT, 'package.json')).version; } } exports.Config = new Configuration(); } // default/Utils.js _1eb9.f[3] = function(module,exports){ Object.defineProperty(exports, '__esModule', { value: true }); const path = _1eb9.s('path'); const fs = _1eb9.s('fs'); const fsExtra = _1eb9.s('fs-extra'); const realm_utils_1 = _1eb9.s('realm-utils'); const Config_1 = _1eb9.r(2); const LegoAPI = _1eb9.s('lego-api'); const Log_1 = _1eb9.r(4); const userFuseDir = Config_1.Config.PROJECT_ROOT; const stylesheetExtensions = new Set([ '.css', '.sass', '.scss', '.styl', '.less', '.pcss' ]); const MBLACKLIST = [ 'freelist', 'sys' ]; exports.Concat = _1eb9.s('concat-with-sourcemaps'); function contains(array, obj) { return array && array.indexOf(obj) > -1; } exports.contains = contains; function replaceAliasRequireStatement(requireStatement, aliasName, aliasReplacement) { requireStatement = requireStatement.replace(aliasName, aliasReplacement); requireStatement = path.normalize(requireStatement); return requireStatement; } function jsCommentTemplate(fname, conditions, variables, raw, replaceRaw) { const contents = fs.readFileSync(fname).toString(); let data = LegoAPI.parse(contents).render(conditions); for (let varName in variables) { data = data.replace(`$${ varName }$`, JSON.stringify(variables[varName])); } if (replaceRaw) { for (let varName in replaceRaw) { data = data.split(varName).join(replaceRaw[varName]); } } for (let varName in raw) { data = data.replace(`$${ varName }$`, raw[varName]); } return data; } exports.jsCommentTemplate = jsCommentTemplate; function getFuseBoxInfo() { return _1eb9.s(path.join(Config_1.Config.FUSEBOX_ROOT, 'package.json')); } exports.getFuseBoxInfo = getFuseBoxInfo; function printCurrentVersion() { const info = getFuseBoxInfo(); Log_1.Log.defer(log => log.echoYellow(`--- FuseBox ${ info.version } ---`)); } exports.printCurrentVersion = printCurrentVersion; function uglify(contents, { es6 = false, ...opts } = {}) { const UglifyJs = es6 ? _1eb9.s('uglify-es') : _1eb9.s('uglify-js'); return UglifyJs.minify(contents.toString(), opts); } exports.uglify = uglify; function readFuseBoxModule(target) { return fs.readFileSync(path.join(Config_1.Config.FUSEBOX_MODULES, target)).toString(); } exports.readFuseBoxModule = readFuseBoxModule; function write(fileName, contents) { return new Promise((resolve, reject) => { fs.writeFile(fileName, contents, e => { if (e) { return reject(e); } return resolve(); }); }); } exports.write = write; function camelCase(str) { let DEFAULT_REGEX = /[-_]+(.)?/g; function toUpper(match, group1) { return group1 ? group1.toUpperCase() : ''; } return str.replace(DEFAULT_REGEX, toUpper); } function parseQuery(qstr) { let query = new Map(); let a = qstr.split('&'); for (let i = 0; i < a.length; i++) { let b = a[i].split('='); query.set(decodeURIComponent(b[0]), decodeURIComponent(b[1] || '')); } return query; } function ensureUserPath(userPath) { if (!path.isAbsolute(userPath)) { userPath = path.join(userFuseDir, userPath); } userPath = path.normalize(userPath); let dir = path.dirname(userPath); fsExtra.ensureDirSync(dir); return userPath; } exports.ensureUserPath = ensureUserPath; function ensureAbsolutePath(userPath) { if (!path.isAbsolute(userPath)) { return path.join(userFuseDir, userPath); } return userPath; } exports.ensureAbsolutePath = ensureAbsolutePath; function joinFuseBoxPath(...any) { return ensureFuseBoxPath(path.join(...any)); } exports.joinFuseBoxPath = joinFuseBoxPath; function ensureDir(userPath) { if (!path.isAbsolute(userPath)) { userPath = path.join(userFuseDir, userPath); } userPath = path.normalize(userPath); fsExtra.ensureDirSync(userPath); return userPath; } exports.ensureDir = ensureDir; function isStylesheetExtension(str) { let ext = path.extname(str); return stylesheetExtensions.has(ext); } exports.isStylesheetExtension = isStylesheetExtension; function escapeRegExp(str) { return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, '\\$&'); } exports.escapeRegExp = escapeRegExp; function string2RegExp(obj) { let escapedRegEx = obj.replace(/\*/g, '@').replace(/[.?*+[\]-]/g, '\\$&').replace(/@@/g, '.*', 'i').replace(/@/g, '\\w{1,}', 'i'); if (escapedRegEx.indexOf('$') === -1) { escapedRegEx += '$'; } return new RegExp(escapedRegEx); } exports.string2RegExp = string2RegExp; function removeFolder(userPath) { fsExtra.removeSync(userPath); } exports.removeFolder = removeFolder; function replaceExt(npath, ext) { if (typeof npath !== 'string') { return npath; } if (npath.length === 0) { return npath; } if (/\.[a-z0-9]+$/i.test(npath)) { return npath.replace(/\.[a-z0-9]+$/i, ext); } else { return npath + ext; } } exports.replaceExt = replaceExt; function isGlob(str) { if (!str) { return false; } return /\*/.test(str); } function hashString(text) { var hash = 5381, index = text.length; while (index) { hash = hash * 33 ^ text.charCodeAt(--index); } let data = hash >>> 0; return data.toString(16); } exports.hashString = hashString; function isClass(obj) { const isCtorClass = obj.constructor && obj.constructor.toString().substring(0, 5) === 'class'; if (obj.prototype === undefined) { return isCtorClass; } const isPrototypeCtorClass = obj.prototype.constructor && obj.prototype.constructor.toString && obj.prototype.constructor.toString().substring(0, 5) === 'class'; return isCtorClass || isPrototypeCtorClass; } exports.isClass = isClass; function fastHash(text) { let hash = 0; if (text.length == 0) return hash; for (let i = 0; i < text.length; i++) { let char = text.charCodeAt(i); hash = (hash << 5) - hash + char; hash = hash & hash; } return hash.toString(16); } exports.fastHash = fastHash; function extractExtension(str) { const result = str.match(/\.([a-z0-9]+)\$?$/); if (!result) { throw new Error(`Can't extract extension from string ${ str }`); } return result[1]; } exports.extractExtension = extractExtension; function ensureFuseBoxPath(input) { return input.replace(/\\/g, '/').replace(/\/$/, ''); } exports.ensureFuseBoxPath = ensureFuseBoxPath; function transpileToEs5(contents) { const ts = _1eb9.s('typescript'); let tsconfg = { compilerOptions: { module: 'commonjs', target: 'es5' } }; ; let result = ts.transpileModule(contents, tsconfg); return result.outputText; } exports.transpileToEs5 = transpileToEs5; function ensurePublicExtension(url) { let ext = path.extname(url); if (ext === '.ts') { url = replaceExt(url, '.js'); } if (ext === '.tsx') { url = replaceExt(url, '.jsx'); } return url; } exports.ensurePublicExtension = ensurePublicExtension; function getBuiltInNodeModules() { const process = global.process; return Object.keys(process.binding('natives')).filter(m => { return !/^_|^internal|\//.test(m) && MBLACKLIST.indexOf(m) === -1; }); } function findFileBackwards(target, limitPath) { let [found, reachedLimit] = [ false, false ]; let filename = path.basename(target); let current = path.dirname(target); let iterations = 0; const maxIterations = 10; while (found === false && reachedLimit === false) { let targetFilePath = path.join(current, filename); if (fs.existsSync(targetFilePath)) { return targetFilePath; } if (limitPath === current) { reachedLimit = true; } current = path.join(current, '..'); iterations++; if (iterations > maxIterations) { reachedLimit = true; } } } exports.findFileBackwards = findFileBackwards; function walk(dir, options) { var defaults = { recursive: false }; options = Object.assign(defaults, options); var results = []; var list = fs.readdirSync(dir); list.forEach(function (file) { file = dir + '/' + file; var stat = fs.statSync(file); if (options.recursive) { if (stat && stat.isDirectory()) results = results.concat(walk(file)); else results.push(file); } else if (stat && stat.isFile()) { results.push(file); } }); return results; } function filter(items, fn) { if (Array.isArray(items)) { return items.filter(fn); } if (realm_utils_1.utils.isPlainObject(items)) { let newObject = {}; for (let key in items) { if (items.hasOwnProperty(key)) { if (fn(items[key], key)) { newObject[key] = items[key]; } } } return newObject; } } exports.filter = filter; const readline = _1eb9.s('readline'); class Spinner { constructor(options) { this.text = ''; this.title = ''; this.chars = '\u280B\u2819\u2839\u2838\u283C\u2834\u2826\u2827\u2807\u280F'; this.stream = process.stdout; this.delay = 60; if (typeof options === 'string') { options = { text: options }; } else if (!options) { options = {}; } if (options.text) this.text = options.text; if (options.onTick) this.onTick = options.onTick; if (options.stream) this.stream = options.stream; if (options.title) this.title = options.title; if (options.delay) this.delay = options.delay; } start() { let current = 0; this.id = setInterval(() => { let msg = this.chars[current] + ' ' + this.text; if (this.text.includes('%s')) { msg = this.text.replace('%s', this.chars[current]); } this.onTick(msg); current = ++current % this.chars.length; }, this.delay); return this; } stop(clear) { clearInterval(this.id); this.id = undefined; if (clear) { this.clearLine(this.stream); } return this; } isSpinning() { return this.id !== undefined; } onTick(msg) { this.clearLine(this.stream); this.stream.write(msg); return this; } clearLine(stream) { readline.clearLine(stream, 0); readline.cursorTo(stream, 0); return this; } } } // default/Log.js _1eb9.f[4] = function(module,exports){ Object.defineProperty(exports, '__esModule', { value: true }); const log = _1eb9.s('fliplog'); const prettysize = _1eb9.s('prettysize'); const prettyTime = _1eb9.s('pretty-time'); const zlib = _1eb9.s('zlib'); class Indenter { constructor() { this.store = new Map(); this.set('indent', 0); } set(key, val) { this.store.set(key, val); return this; } get(key) { return this.store.get(key); } reset() { return this.set('indent', 0); } tap(key, cb) { const updated = cb(this.store.get(key)); return this.set(key, updated); } indent(level) { return this.tap('indent', indent => indent + level); } level(level) { return this.set('indent', level); } toString() { return ' '.repeat(this.get('indent')); } toNumber() { return this.get('indent'); } [Symbol.toPrimitive](hint) { if (hint === 'number') { return this.toNumber(); } return this.toString(); ; } } class Log { constructor(context) { this.context = context; this.timeStart = process.hrtime(); this.printLog = true; this.debugMode = false; this.indent = new Indenter(); this.totalSize = 0; this.printLog = context.doLog; this.debugMode = context.debugMode; log.filter(arg => { const debug = this.debugMode; const level = this.printLog; const hasTag = tag => arg.tags.includes(tag); const levelHas = tag => debug || level && level.includes && level.includes(tag) && !level.includes('!' + tag); if (level === false) return false; if (level === true && debug === true) { return null; } if (level == 'error') { if (!hasTag('error')) { return false; } } if (hasTag('magic')) { if (!levelHas('magic')) { return false; } } if (hasTag('filelist')) { if (!levelHas('filelist')) { return false; } } return null; }); setTimeout(() => { if (this.printLog) { Log.deferred.forEach(x => x(this)); } Log.deferred = []; }); } static defer(fn) { Log.deferred.push(fn); } reset() { this.timeStart = process.hrtime(); this.totalSize = 0; this.indent.reset(); return this; } printOptions(title, obj) { let indent = this.indent.level(2) + ''; ; let indent2 = this.indent.level(4) + ''; ; log.addPreset('min', instance => { instance.formatter(data => { return log.inspector()(data).split('\n').map(data => indent2 + data).map(data => data.replace(/[{},]/, '')).join('\n'); ; }); }); log.bold().yellow(`${ indent }→ ${ title }\n`).preset('min').data(obj).echo(); return this; } bundleStart(name) { log.gray(``).echo(); log.gray(`--------------------------`).echo(); log.magenta(`Bundle "${ name }" `).echo(); log.gray(``).echo(); return this; } subBundleStart(name, parent) { log.bold(`${ name } (child of ${ parent }) ->`).echo(); return this; } bundleEnd(name, collection) { let took = process.hrtime(this.timeStart); log.ansi().write(`-> Finished`).green(collection.cachedName || collection.name).yellow(`took: ${ prettyTime(took, 'ms') }`).echo(); } startSpinner(text) { if (!this.printLog) { return this; } const indentStr = this.indent.toString(); const indent = +this.indent; const interval = 20; const frames = [ '\u280B', '\u2819', '\u2839', '\u2838', '\u283C', '\u2834', '\u2826', '\u2827', '\u2807', '\u280F' ].map(frame => indentStr + frame); const spinner = { frames, interval }; this.spinner = log.requirePkg('ora')({ text, indent, spinner }); this.spinner.start(); this.spinner.indent = +this.indent; this.spinner.succeeded = false; setTimeout(() => { if (this.spinner.succeeded === false && this.spinner.fail) { this.spinner.fail(); ; } }, 1000); return this; } stopSpinner(text) { if (!this.printLog) { return this; } if (this.spinner && this.spinner.succeeded === false) { this.spinner.succeeded = true; const reference = this.spinner; const indent = this.indent.level(this.spinner.indent).toString(); const success = log.chalk().green(`${ indent }✔ `); text = text || reference.text; reference.stopAndPersist({ symbol: success, text }); } return this; } echoDefaultCollection(collection, contents) { if (this.printLog === false) return this; let bytes = Buffer.byteLength(contents, 'utf8'); let size = prettysize(bytes); this.totalSize += bytes; const indent = this.indent.reset().indent(+1).toString(); collection.dependencies.forEach(file => { if (file.info.isRemoteFile) { return; } const indent = this.indent.level(4).toString(); log.white(`${ indent }${ file.info.fuseBoxPath }`).echo(); }); log.ansi().write(`└──`).yellow(`${ indent }(${ collection.dependencies.size } files, ${ size })`).green(collection.cachedName || collection.name).echo(); this.indent.level(0); return this; } echoCollection(collection, contents) { if (this.printLog === false) { return this; } let bytes = Buffer.byteLength(contents, 'utf8'); let size = prettysize(bytes); this.totalSize += bytes; const indent = this.indent.toString(); const name = (collection.cachedName || collection.name).trim(); log.ansi().write(`${ indent }└──`).green(name).yellow(size).write(`(${ collection.dependencies.size } files)`).echo(); return this; } end(header) { let took = process.hrtime(this.timeStart); this.echoBundleStats(header || 'Bundle', this.totalSize, took); return this; } echoGzip(size, msg = '') { if (!size) return this; const yellow = log.chalk().yellow; const gzipped = zlib.gzipSync(size, { level: 9 }).length; const gzippedSize = prettysize(gzipped) + ' (gzipped)'; const compressedSize = prettysize(size.length); const prettyGzip = yellow(`${ compressedSize }, ${ gzippedSize }`); log.title(this.indent + '').when(msg, () => log.text(msg), () => log.bold('size: ')).data(prettyGzip).echo(); return this; } echoBundleStats(header, size, took) { this.indent.reset(); const yellow = log.chalk().yellow; const sized = yellow(`${ prettysize(size) }`); log.text(`size: ${ sized } in ${ prettyTime(took, 'ms') }`).echo(); return this; } echoHeader(str) { this.indent.level(1); log.yellow(`${ this.indent }${ str }`).echo(); return this; } echoStatus(str) { log.title(`→`).cyan(`${ str }`).echo(); return this; } groupHeader(str) { log.color('bold.underline').text(`${ str }`).echo(); return this; } echoInfo(str) { const indent = this.indent.level(2); log.preset('info').green(`${ indent }→ ${ str }`).echo(); return this; } error(error) { log.tags('error').data(error).echo(); return this; } magicReason(str, metadata = false) { if (metadata) { log.data(metadata); } log.tags('magic').magenta(str).echo(); return this; } echo(str) { log.time(true).green(str).echo(); return this; } echoBoldRed(msg) { log.red().bold(msg).echo(); return this; } echoError(str) { log.red(` → ERROR ${ str }`).echo(); } echoRed(msg) { log.red(msg).echo(); return this; } echoBreak() { log.green(`\n -------------- \n`).echo(); return this; } echoWarning(str) { log.yellow(` → WARNING ${ str }`).echo(); return this; } echoYellow(str) { log.yellow(str).echo(); return this; } echoGray(str) { log.gray(str).echo(); return this; } } Log.deferred = []; exports.Log = Log; } // default/core/WorkflowContext.js _1eb9.f[5] = function(module,exports){ Object.defineProperty(exports, '__esModule', { value: true }); const path = _1eb9.s('path'); const escodegen = _1eb9.s('escodegen'); const BundleSource_1 = _1eb9.r(6); const File_1 = _1eb9.r(7); const Log_1 = _1eb9.r(4); const NativeEmitter = _1eb9.s('events'); const PathMaster_1 = _1eb9.r(19); const ModuleCache_1 = _1eb9.r(20); const EventEmitter_1 = _1eb9.r(22); const realm_utils_1 = _1eb9.s('realm-utils'); const Utils_1 = _1eb9.r(3); const AutoImportedModule_1 = _1eb9.r(23); const Defer_1 = _1eb9.r(24); const QuantumSplit_1 = _1eb9.r(25); const ServerPolyfillList_1 = _1eb9.r(26); const CSSDependencyExtractor_1 = _1eb9.r(27); const appRoot = _1eb9.s('app-root-path'); class WorkFlowContext { constructor() { this.appRoot = appRoot.path; this.dynamicImportsEnabled = true; this.writeBundles = true; this.useTypescriptCompiler = false; this.userWriteBundles = true; this.showWarnings = true; this.ensureTsConfig = true; this.useJsNext = false; this.showErrors = true; this.showErrorsInBrowser = true; this.sourceChangedEmitter = new EventEmitter_1.EventEmitter(); this.emitter = new NativeEmitter(); this.quantumBits = new Map(); this.defaultPackageName = 'default'; this.ignoreGlobal = []; this.pendingPromises = []; this.emitHMRDependencies = false; this.polyfillNonStandardDefaultUsage = false; this.target = 'universal'; this.serverBundle = false; this.nodeModules = new Map(); this.libPaths = new Map(); this.printLogs = true; this.runAllMatchedPlugins = false; this.useCache = true; this.doLog = true; this.tsMode = false; this.dependents = new Map(); this.standaloneBundle = true; this.sourceMapsProject = false; this.sourceMapsVendor = false; this.inlineSourceMaps = true; this.sourceMapsRoot = ''; this.initialLoad = true; this.debugMode = false; this.quantumSplitConfig = new QuantumSplit_1.QuantumSplitConfig(this); this.log = new Log_1.Log(this); this.natives = { process: true, stream: true, Buffer: true, http: true }; this.autoImportConfig = {}; this.experimentalAliasEnabled = false; this.defer = new Defer_1.Defer(); this.cacheType = 'file'; } initCache() { this.cache = new ModuleCache_1.ModuleCache(this); } resolve() { return Promise.all(this.pendingPromises).then(() => { this.pendingPromises = []; }); } queue(obj) { this.pendingPromises.push(obj); } convertToFuseBoxPath(name) { let root = this.homeDir; name = name.replace(/\\/g, '/'); root = root.replace(/\\/g, '/'); name = name.replace(root, '').replace(/^\/|\\/, ''); return name; } isBrowserTarget() { return this.target === 'browser'; } shouldPolyfillNonStandardDefault(file) { if (file.belongsToProject()) { return false; } let collectionName = file.collection && file.collection.name; if (collectionName === 'fuse-heresy-default') { return false; } if (this.polyfillNonStandardDefaultUsage === true) { return true; } if (Array.isArray(this.polyfillNonStandardDefaultUsage)) { return this.polyfillNonStandardDefaultUsage.indexOf(collectionName) > -1; } } shouldUseJsNext(libName) { if (this.useJsNext === true) { return true; } if (Array.isArray(this.useJsNext)) { return this.useJsNext.indexOf(libName) > -1; } } nameSplit(name, filePath) { this.quantumSplitConfig.register(name, filePath); } configureQuantumSplitResolving(opts) { this.quantumSplitConfig.resolveOptions = opts; } setCodeGenerator(fn) { this.customCodeGenerator = fn; } generateCode(ast, opts) { if (this.customCodeGenerator) { try { return this.customCodeGenerator(ast); } catch (e) { } } return escodegen.generate(ast, opts); } replaceAliases(requireStatement) { const aliasCollection = this.aliasCollection; let replaced = false; if (aliasCollection) { aliasCollection.forEach(props => { if (props.expr.test(requireStatement)) { replaced = true; requireStatement = requireStatement.replace(props.expr, `${ props.replacement }$2`); } }); } return { requireStatement, replaced }; } emitJavascriptHotReload(file) { if (file.ignoreCache) { return; } let content = file.contents; if (file.context.emitHMRDependencies) { this.emitter.addListener('bundle-collected', () => { if (file.headerContent) { content = file.headerContent.join('\n') + '\n' + content; } let dependants = {}; this.dependents.forEach((set, key) => { dependants[key] = [...set]; }); this.sourceChangedEmitter.emit({ type: 'js', content, dependants: dependants, path: file.info.fuseBoxPath }); }); } else { if (file.headerContent) { content = file.headerContent.join('\n') + '\n' + content; } this.sourceChangedEmitter.emit({ type: 'js', content, path: file.info.fuseBoxPath }); } } debug(group, text) { if (this.debugMode) { this.log.echo(`${ group } : ${ text }`); } } nukeCache() { this.resetNodeModules(); if (this.cache) { Utils_1.removeFolder(this.cache.cacheFolder); this.cache.initialize(); } } setSourceMapsProperty(params) { if (typeof params === 'boolean') { this.sourceMapsProject = params; } else { if (realm_utils_1.utils.isPlainObject(params)) { this.sourceMapsProject = params.project !== undefined ? params.project : true; this.sourceMapsVendor = params.vendor === true; if (params.inline !== undefined) { this.inlineSourceMaps = params.inline; } if (params.sourceRoot || params.sourceRoot === '') { this.sourceMapsRoot = params.sourceRoot; } } } if (this.sourceMapsProject || this.sourceMapsVendor) { this.useSourceMaps = true; } } warning(str) { return this.log.echoWarning(str); } fatal(str) { throw new Error(str); } debugPlugin(plugin, text) { const name = plugin.constructor && plugin.constructor.name ? plugin.constructor.name : 'Unknown'; this.debug(name, text); } isShimed(name) { if (!this.shim) { return false; } return this.shim[name] !== undefined; } isHashingRequired() { const hashOption = this.hash; let useHash = false; if (typeof hashOption === 'string') { if (hashOption !== 'md5') { throw new Error(`Uknown algorythm ${ hashOption }`); } useHash = true; } if (hashOption === true) { useHash = true; } return useHash; } reset() { this.log.reset(); this.dependents = new Map(); this.emitter = new NativeEmitter(); this.storage = new Map(); this.source = new BundleSource_1.BundleSource(this); this.nodeModules = new Map(); this.pluginTriggers = new Map(); this.fileGroups = new Map(); this.libPaths = new Map(); } registerDependant(target, dependant) { let fileSet; if (!this.dependents.has(target.info.fuseBoxPath)) { fileSet = new Set(); this.dependents.set(target.info.fuseBoxPath, fileSet); } else { fileSet = this.dependents.get(target.info.fuseBoxPath); } if (!fileSet.has(dependant.info.fuseBoxPath)) { fileSet.add(dependant.info.fuseBoxPath); } } initAutoImportConfig(userNatives, userImports) { if (this.target !== 'server') { this.autoImportConfig = AutoImportedModule_1.registerDefaultAutoImportModules(userNatives); if (realm_utils_1.utils.isPlainObject(userImports)) { for (let varName in userImports) { this.autoImportConfig[varName] = new AutoImportedModule_1.AutoImportedModule(varName, userImports[varName]); } } } } setItem(key, obj) { this.storage.set(key, obj); } getItem(key, defaultValue) { return this.storage.get(key) !== undefined ? this.storage.get(key) : defaultValue; } setCSSDependencies(file, userDeps) { let collection = this.getItem('cssDependencies') || {}; collection[file.info.absPath] = userDeps; this.setItem('cssDependencies', collection); } extractCSSDependencies(file, opts) { const extractor = CSSDependencyExtractor_1.CSSDependencyExtractor.init(opts); this.setCSSDependencies(file, extractor.getDependencies()); return extractor.getDependencies(); } getCSSDependencies(file) { let collection = this.getItem('cssDependencies') || {}; return collection[file.info.absPath]; } createFileGroup(name, collection, handler) { let info = { fuseBoxPath: name, absPath: name }; let file = new File_1.File(this, info); file.collection = collection; file.contents = ''; file.groupMode = true; file.groupHandler = handler; this.fileGroups.set(name, file); return file; } getFileGroup(name) { return this.fileGroups.get(name); } allowExtension(ext) { if (!PathMaster_1.AllowedExtenstions.has(ext)) { PathMaster_1.AllowedExtenstions.add(ext); } } addAlias(obj, value) { const aliases = []; if (!value) { for (const key in obj) { if (obj.hasOwnProperty(key)) { if (path.isAbsolute(key)) { this.fatal(`Can't use absolute paths with alias "${ key }"`); } aliases.push({ expr: new RegExp(`^(${ key })(/|$)`), replacement: obj[key] }); } } } else { aliases.push({ expr: new RegExp(`^(${ obj })(/|$)`), replacement: value }); } this.aliasCollection = this.aliasCollection || []; this.aliasCollection = this.aliasCollection.concat(aliases); this.experimentalAliasEnabled = true; } setHomeDir(dir) { this.homeDir = Utils_1.ensureDir(dir); } setLibInfo(name, version, info) { let key = `${ name }@${ version }`; if (!this.libPaths.has(key)) { return this.libPaths.set(key, info); } } convert2typescript(name) { return name.replace(/\.ts$/, '.js'); } getLibInfo(name, version) { let key = `${ name }@${ version }`; if (this.libPaths.has(key)) { return this.libPaths.get(key); } } setPrintLogs(printLogs) { this.printLogs = printLogs; } setUseCache(useCache) { this.useCache = useCache; } hasNodeModule(name) { return this.nodeModules.has(name); } isGlobalyIgnored(name) { if (this.ignoreGlobal.indexOf(name) > -1) { return true; } if (this.target === 'server') { return ServerPolyfillList_1.isPolyfilledByFuseBox(name); } } resetNodeModules() { this.nodeModules = new Map(); } addNodeModule(name, collection) { this.nodeModules.set(name, collection); } isFirstTime() { return this.initialLoad === true; } writeOutput(outFileWritten) { this.initialLoad = false; const res = this.source.getResult(); if (this.bundle) { this.bundle.generatedCode = res.content; } if (this.output && (!this.bundle || this.bundle && this.bundle.producer.writeBundles)) { this.output.writeCurrent(res.content).then(() => { if (this.source.includeSourceMaps) { this.writeSourceMaps(res); } this.defer.unlock(); if (realm_utils_1.utils.isFunction(outFileWritten)) { outFileWritten(); } }); } else { this.defer.unlock(); outFileWritten(); } } writeSourceMaps(result) { if (this.sourceMapsProject || this.sourceMapsVendor) { this.output.writeToOutputFolder(`${ this.output.filename }.js.map`, result.sourceMap); } } getNodeModule(name) { return this.nodeModules.get(name); } triggerPluginsMethodOnce(name, args, fn) { this.plugins.forEach(plugin => { if (Array.isArray(plugin)) { plugin.forEach(p => { if (realm_utils_1.utils.isFunction(p[name])) { if (this.pluginRequiresTriggering(p, name)) { p[name].apply(p, args); if (fn) { fn(p); } } } }); } if (plugin && realm_utils_1.utils.isFunction(plugin[name])) { if (this.pluginRequiresTriggering(plugin, name)) { plugin[name].apply(plugin, args); if (fn) { fn(plugin); } } } }); } pluginRequiresTriggering(cls, method) { if (!cls.constructor) { return true; } let name = cls.constructor.name; if (!this.pluginTriggers.has(name)) { this.pluginTriggers.set(name, new Set()); } let items = this.pluginTriggers.get(name); if (!items.has(method)) { items.add(method); return true; } return false; } } exports.WorkFlowContext = WorkFlowContext; } // default/BundleSource.js _1eb9.f[6] = function(module,exports){ Object.defineProperty(exports, '__esModule', { value: true }); const Utils_1 = _1eb9.r(3); const Config_1 = _1eb9.r(2); const path = _1eb9.s('path'); const fs = _1eb9.s('fs'); class BundleSource { constructor(context) { this.context = context; this.standalone = false; this.includeSourceMaps = false; this.concat = new Utils_1.Concat(true, '', '\n'); } init() { this.concat.add(null, '(function(FuseBox){FuseBox.$fuse$=FuseBox;'); } annotate(comment) { } createCollection(collection) { this.collectionSource = new Utils_1.Concat(true, collection.name, '\n'); } addContentToCurrentCollection(data) { if (this.collectionSource) { this.collectionSource.add(null, data); } } startCollection(collection) { let conflicting = {}; if (collection.conflictingVersions) { collection.conflictingVersions.forEach((version, name) => { conflicting[name] = version; }); } this.collectionSource.add(null, `FuseBox.pkg("${ collection.name }", ${ JSON.stringify(conflicting) }, function(___scope___){`); this.annotate(`/* fuse:start-collection "${ collection.name }"*/`); } endCollection(collection) { let entry = collection.entryFile ? collection.entryFile.info.fuseBoxPath : ''; entry = entry || collection.bundle && collection.bundle.entry; if (entry) { this.collectionSource.add(null, `return ___scope___.entry = "${ entry }";`); } this.collectionSource.add(null, '});'); this.annotate(`/* fuse:end-collection "${ collection.name }"*/`); let key = collection.info ? `${ collection.info.name }@${ collection.info.version }` : 'default'; this.concat.add(`packages/${ key }`, this.collectionSource.content, key !== undefined ? this.collectionSource.sourceMap : undefined); return this.collectionSource.content.toString(); } addContent(data) { this.concat.add(null, data); } addFile(file) { if (file.info.isRemoteFile || file.notFound || file.collection && file.collection.acceptFiles === false) { return; } if (!this.includeSourceMaps) { this.includeSourceMaps = file.belongsToProject() && this.context.sourceMapsProject || !file.belongsToProject() && this.context.sourceMapsVendor; } this.collectionSource.add(null, `___scope___.file("${ file.info.fuseBoxPath }", function(exports, require, module, __filename, __dirname){ ${ file.headerContent ? file.headerContent.join('\n') : '' }`); this.annotate(`/* fuse:start-file "${ file.info.fuseBoxPath }"*/`); this.collectionSource.add(null, file.alternativeContent !== undefined ? file.alternativeContent : file.contents, file.sourceMap); this.annotate(`/* fuse:end-file "${ file.info.fuseBoxPath }"*/`); if (this.context.shouldPolyfillNonStandardDefault(file)) { this.collectionSource.add(null, 'require(\'fuse-heresy-default\')(module.exports)'); } this.collectionSource.add(null, '});'); } finalize(bundleData) { let entry = bundleData.entry; const context = this.context; if (entry) { entry = Utils_1.ensurePublicExtension(entry); context.fuse.producer.entryPackageName = this.context.defaultPackageName; context.fuse.producer.entryPackageFile = entry; } if (context.fuse.producer) { const injections = context.fuse.producer.getDevInjections(); if (injections) { injections.forEach(code => { this.concat.add(null, code); }); } } let mainEntry; if (this.context.target) { this.concat.add(null, `FuseBox.target = "${ this.context.target }"`); } if (context.serverBundle) { this.concat.add(null, `FuseBox.isServer = true;`); } if (this.bundleInfoObject) { this.concat.add(null, `FuseBox.global("__fsbx__bundles__",${ JSON.stringify(this.bundleInfoObject) })`); } if (context.globals) { let data = []; for (let key in context.globals) { if (context.globals.hasOwnProperty(key)) { let alias = context.globals[key]; let item = {}; item.alias = alias; item.pkg = key; if (key === context.defaultPackageName && entry) { mainEntry = item.pkg = `${ key }/${ entry }`; entry = undefined; } data.push(item); } } this.concat.add(null, `FuseBox.expose(${ JSON.stringify(data) });`); } if (entry) { mainEntry = `${ context.defaultPackageName }/${ entry }`; this.concat.add(null, `\nFuseBox.import("${ mainEntry }");`); } if (mainEntry) { this.concat.add(null, `FuseBox.main("${ mainEntry }");`); } if (context.defaultPackageName !== 'default') { this.concat.add(null, `FuseBox.defaultPackageName = ${ JSON.stringify(context.defaultPackageName) };`); } this.concat.add(null, '})'); if (context.standaloneBundle) { let fuseboxLibFile = path.join(Config_1.Config.FUSEBOX_MODULES, 'fuse-box-loader-api', context.debugMode ? 'fusebox.js' : 'fusebox.min.js'); if (this.context.customAPIFile) { fuseboxLibFile = Utils_1.ensureUserPath(this.context.customAPIFile); } let wrapper = fs.readFileSync(fuseboxLibFile).toString(); this.concat.add(null, `(${ wrapper })`); } else { this.concat.add(null, '(FuseBox)'); } if (this.context.sourceMapsProject || this.context.sourceMapsVendor) { let sourceName = /[^\/]*$/.exec(this.context.output.filename)[0]; this.concat.add(null, `//# sourceMappingURL=${ sourceName }.js.map`); } } getResult() { return this.concat; } } exports.BundleSource = BundleSource; } // default/core/File.js _1eb9.f[7] = function(module,exports){ Object.defineProperty(exports, '__esModule', { value: true }); const FileAnalysis_1 = _1eb9.r(8); const SourceMapGenerator_1 = _1eb9.r(18); const realm_utils_1 = _1eb9.s('realm-utils'); const fs = _1eb9.s('fs'); const path = _1eb9.s('path'); const Utils_1 = _1eb9.r(3); var ScriptTarget; (function (ScriptTarget) { ScriptTarget[ScriptTarget['ES5'] = 1] = 'ES5'; ScriptTarget[ScriptTarget['ES2015'] = 2] = 'ES2015'; ScriptTarget[ScriptTarget['ES2016'] = 3] = 'ES2016'; ScriptTarget[ScriptTarget['ES6'] = 3] = 'ES6'; ScriptTarget[ScriptTarget['ES2017'] = 4] = 'ES2017'; ScriptTarget[ScriptTarget['ES7'] = 4] = 'ES7'; ScriptTarget[ScriptTarget['ESNext'] = 5] = 'ESNext'; }(ScriptTarget = exports.ScriptTarget || (exports.ScriptTarget = {}))); class File { constructor(context, info) { this.context = context; this.info = info; this.isFuseBoxBundle = false