/*
对viewerjs的react封装
https://github.com/fengyuanchen/viewerjs
198725
function deepMap(children, callback) {//参考https://github.com/reactjs/react-tabs/blob/master/src/helpers/childrenDeepMap.js
  return Children.map(children, child => {
    if (child === null) return null;
    if (isRViewerTrigger(child)) {
      return callback(child);
    }
    if (child.props && child.props.children && typeof child.props.children === 'object') {
      return cloneElement(child, {
        ...child.props,
        children: deepMap(child.props.children, callback),
      });
    }
    return child;
  });
}
38691
async function analyze(resource) {
	const libInfo = {
		noLibraryCSS: false,
		types: [],
		controls: [],
		elements: [],
		interfaces: []
	};

	function visit(node) {
		if ( node.type == Syntax.CallExpression
				&& node.callee.type === Syntax.MemberExpression
				&& isMethodCall(node.callee.object, CALL__SAP_UI_GETCORE)
				&& isIdentifier(node.callee.property, "initLibrary")
				&& node.arguments.length === 1
				&& node.arguments[0].type === Syntax.ObjectExpression ) {
			node.arguments[0].properties.forEach( (prop) => {
				const key = getPropertyKey(prop);
				const value = prop.value;
				if ( key === "noLibraryCSS"
						&& (value.type === Syntax.Literal && typeof value.value === "boolean") ) {
					libInfo.noLibraryCSS = value.value;
				} else if ( key === "types" && value.type == Syntax.ArrayExpression ) {
					libInfo.types = getStringArray(value, true);
				} else if ( key === "interfaces" && value.type == Syntax.ArrayExpression ) {
					libInfo.interfaces = getStringArray(value, true);
				} else if ( key === "controls" && value.type == Syntax.ArrayExpression ) {
					libInfo.controls = getStringArray(value, true);
				} else if ( key === "elements" && value.type == Syntax.ArrayExpression ) {
					libInfo.elements = getStringArray(value, true);
				}
			});

			return true; // abort, we're done
		}

		for ( const key of VisitorKeys[node.type] ) {
			const child = node[key];
			if ( Array.isArray(child) ) {
				if ( child.some(visit) ) {
					return true;
				}
			} else if ( child ) {
				if ( visit(child) ) {
					return true;
				}
			}
		}

		return false;
	}

	const code = await resource.getBuffer();
	visit( esprima.parseScript(code.toString()) );

	return libInfo;
}
305388
function (winjsComponent, propName, oldValue, newValue) {
                    // TODO: dispose
                    ReactDOM.render(React.DOM.div(null, newValue), winjsComponent.winControl.element);
                }
840377
function(module, exports, __webpack_require__) {

	/*
		MIT License http://www.opensource.org/licenses/mit-license.php
		Author Tobias Koppers @sokra
	*/
	var stylesInDom = {},
		memoize = function(fn) {
			var memo;
			return function () {
				if (typeof memo === "undefined") memo = fn.apply(this, arguments);
				return memo;
			};
		},
		isOldIE = memoize(function() {
			return /msie [6-9]\b/.test(window.navigator.userAgent.toLowerCase());
		}),
		getHeadElement = memoize(function () {
			return document.head || document.getElementsByTagName("head")[0];
		}),
		singletonElement = null,
		singletonCounter = 0,
		styleElementsInsertedAtTop = [];
	
	module.exports = function(list, options) {
		if(false) {
			if(typeof document !== "object") throw new Error("The style-loader cannot be used in a non-browser environment");
		}
	
		options = options || {};
		// Force single-tag solution on IE6-9, which has a hard limit on the # of <style>
		// tags it will allow on a page
		if (typeof options.singleton === "undefined") options.singleton = isOldIE();
	
		// By default, add <style> tags to the bottom of <head>.
		if (typeof options.insertAt === "undefined") options.insertAt = "bottom";
	
		var styles = listToStyles(list);
		addStylesToDom(styles, options);
	
		return function update(newList) {
			var mayRemove = [];
			for(var i = 0; i < styles.length; i++) {
				var item = styles[i];
				var domStyle = stylesInDom[item.id];
				domStyle.refs--;
				mayRemove.push(domStyle);
			}
			if(newList) {
				var newStyles = listToStyles(newList);
				addStylesToDom(newStyles, options);
			}
			for(var i = 0; i < mayRemove.length; i++) {
				var domStyle = mayRemove[i];
				if(domStyle.refs === 0) {
					for(var j = 0; j < domStyle.parts.length; j++)
						domStyle.parts[j]();
					delete stylesInDom[domStyle.id];
				}
			}
		};
	}
	
	function addStylesToDom(styles, options) {
		for(var i = 0; i < styles.length; i++) {
			var item = styles[i];
			var domStyle = stylesInDom[item.id];
			if(domStyle) {
				domStyle.refs++;
				for(var j = 0; j < domStyle.parts.length; j++) {
					domStyle.parts[j](item.parts[j]);
				}
				for(; j < item.parts.length; j++) {
					domStyle.parts.push(addStyle(item.parts[j], options));
				}
			} else {
				var parts = [];
				for(var j = 0; j < item.parts.length; j++) {
					parts.push(addStyle(item.parts[j], options));
				}
				stylesInDom[item.id] = {id: item.id, refs: 1, parts: parts};
			}
		}
	}
	
	function listToStyles(list) {
		var styles = [];
		var newStyles = {};
		for(var i = 0; i < list.length; i++) {
			var item = list[i];
			var id = item[0];
			var css = item[1];
			var media = item[2];
			var sourceMap = item[3];
			var part = {css: css, media: media, sourceMap: sourceMap};
			if(!newStyles[id])
				styles.push(newStyles[id] = {id: id, parts: [part]});
			else
				newStyles[id].parts.push(part);
		}
		return styles;
	}
	
	function insertStyleElement(options, styleElement) {
		var head = getHeadElement();
		var lastStyleElementInsertedAtTop = styleElementsInsertedAtTop[styleElementsInsertedAtTop.length - 1];
		if (options.insertAt === "top") {
			if(!lastStyleElementInsertedAtTop) {
				head.insertBefore(styleElement, head.firstChild);
			} else if(lastStyleElementInsertedAtTop.nextSibling) {
				head.insertBefore(styleElement, lastStyleElementInsertedAtTop.nextSibling);
			} else {
				head.appendChild(styleElement);
			}
			styleElementsInsertedAtTop.push(styleElement);
		} else if (options.insertAt === "bottom") {
			head.appendChild(styleElement);
		} else {
			throw new Error("Invalid value for parameter 'insertAt'. Must be 'top' or 'bottom'.");
		}
	}
	
	function removeStyleElement(styleElement) {
		styleElement.parentNode.removeChild(styleElement);
		var idx = styleElementsInsertedAtTop.indexOf(styleElement);
		if(idx >= 0) {
			styleElementsInsertedAtTop.splice(idx, 1);
		}
	}
	
	function createStyleElement(options) {
		var styleElement = document.createElement("style");
		styleElement.type = "text/css";
		insertStyleElement(options, styleElement);
		return styleElement;
	}
	
	function addStyle(obj, options) {
		var styleElement, update, remove;
	
		if (options.singleton) {
			var styleIndex = singletonCounter++;
			styleElement = singletonElement || (singletonElement = createStyleElement(options));
			update = applyToSingletonTag.bind(null, styleElement, styleIndex, false);
			remove = applyToSingletonTag.bind(null, styleElement, styleIndex, true);
		} else {
			styleElement = createStyleElement(options);
			update = applyToTag.bind(null, styleElement);
			remove = function() {
				removeStyleElement(styleElement);
			};
		}
	
		update(obj);
	
		return function updateStyle(newObj) {
			if(newObj) {
				if(newObj.css === obj.css && newObj.media === obj.media && newObj.sourceMap === obj.sourceMap)
					return;
				update(obj = newObj);
			} else {
				remove();
			}
		};
	}
	
	var replaceText = (function () {
		var textStore = [];
	
		return function (index, replacement) {
			textStore[index] = replacement;
			return textStore.filter(Boolean).join('\n');
		};
	})();
	
	function applyToSingletonTag(styleElement, index, remove, obj) {
		var css = remove ? "" : obj.css;
	
		if (styleElement.styleSheet) {
			styleElement.styleSheet.cssText = replaceText(index, css);
		} else {
			var cssNode = document.createTextNode(css);
			var childNodes = styleElement.childNodes;
			if (childNodes[index]) styleElement.removeChild(childNodes[index]);
			if (childNodes.length) {
				styleElement.insertBefore(cssNode, childNodes[index]);
			} else {
				styleElement.appendChild(cssNode);
			}
		}
	}
	
	function applyToTag(styleElement, obj) {
		var css = obj.css;
		var media = obj.media;
		var sourceMap = obj.sourceMap;
	
		if (media) {
			styleElement.setAttribute("media", media);
		}
	
		if (sourceMap) {
			// https://developer.chrome.com/devtools/docs/javascript-debugging
			// this makes source maps inside style tags work properly in Chrome
			css += '\n/*# sourceURL=' + sourceMap.sources[0] + ' */';
			// http://stackoverflow.com/a/26603875
			css += "\n/*# sourceMappingURL=data:application/json;base64," + btoa(unescape(encodeURIComponent(JSON.stringify(sourceMap)))) + " */";
		}
	
		if (styleElement.styleSheet) {
			styleElement.styleSheet.cssText = css;
		} else {
			while(styleElement.firstChild) {
				styleElement.removeChild(styleElement.firstChild);
			}
			styleElement.appendChild(document.createTextNode(css));
		}
	}


/***/ }
499066
function defineComponent(proto, SuperComponent) {
    // 如果传入一个不是 san component 的 constructor，直接返回不是组件构造函数
    // 这种场景导致的错误 san 不予考虑
    if (typeof proto === 'function') {
        return proto;
    }

    // #[begin] error
    if (typeof proto !== 'object') {
        throw new Error('[SAN FATAL] defineComponent need a plain object.');
    }
    // #[end]

    function ComponentClass(option) { // eslint-disable-line
        Component.call(this, option);
    }

    ComponentClass.prototype = proto;
    inherits(ComponentClass, SuperComponent || Component);

    return ComponentClass;
}
287478
function compileMPScript(script, mpOptioins, moduleId) {
    const babelrc = getBabelrc(mpOptioins.globalBabelrc);
    let result, metadata;
    let scriptContent = script.content;
    const babelOptions = { extends: babelrc, plugins: [parseComponentsDeps] };
    if (script.src) {
        // 处理src
        const scriptpath = path.join(path.dirname(this.resourcePath), script.src);
        scriptContent = fs.readFileSync(scriptpath).toString();
    }
    if (script.lang === 'ts') {
        // 处理ts
        metadata = parseComponentsDepsTs(scriptContent);
    } else {
        result = babel.transform(scriptContent, babelOptions);
        metadata = result.metadata;
    }

    // metadata: importsMap, components
    const { importsMap, components: originComponents } = metadata;

    // 处理子组件的信息
    const components = {};
    const fileInfo = resolveTarget(this.resourcePath, this.options.entry);
    if (originComponents) {
        resolveSrc(originComponents, components, this.resolve, this.context)
            .then(() => {
                resolveComponent(this.resourcePath, fileInfo, importsMap, components, moduleId);
            })
            .catch(err => {
                console.error(err);
                resolveComponent(this.resourcePath, fileInfo, importsMap, components, moduleId);
            });
    } else {
        resolveComponent(this.resourcePath, fileInfo, importsMap, components, moduleId);
    }

    return script;
}
690609
function generateHTML(fileName) {
  return new Promise( resolve => {
    const location = fileName === 'index.html' ? '/' : `/${fileName}`;
    match({routes, location}, (error, redirectLocation, renderProps) => {
      let html = ReactDOMServer.renderToString(
        <RouterContext {...renderProps} />
      );
      html = '<!doctype html>' + html;
      let write = fsp.writeFile(path.join(docsBuilt, fileName), html);
      resolve(write);
    });
  });
}
403090
function render(code, data) {
  var js = '```js' + code + '```'
  return `<div class="vomit-snippet"><div class="column">${marked(js)}</div><div class="column"><script>
(function() {${code}document.currentScript.parentElement.appendChild(component(${JSON.stringify(data.data)}))
})()</script></div></div>`
}
17649
function build(previousFileSizes) {
    let packText = userDevConfig ? '启动测试环境打包编译...' : '启动生产环境打包压缩...';
    let startTime = Date.now();
    let timer;
    let logProgress = function(stop) {
        var text = packText + '已耗时：' + ((Date.now() - startTime) / 1000).toFixed(3) + 's';

        if (stop) {
            clearTimeout(timer);
            spinner.succeed(chalk.green(text));
        } else {
            spinner.text = chalk.cyan(text);

            timer = setTimeout(logProgress, 100);
        }
    };

    clearConsole();
    logProgress();

    let compiler = webpack(config);

    return new Promise((resolve, reject) => {
        compiler.run((err, stats) => {
            let messages;

            logProgress(true); // 停止
            console.log();

            if (err) {
                if (!err.message) {
                    return reject(err);
                }

                messages = formatWebpackMessages({
                    errors: [err.message],
                    warnings: []
                });
            } else {
                messages = formatWebpackMessages(stats.toJson({ all: false, warnings: true, errors: true }));
            }

            if (messages.errors.length) {
                if (messages.errors.length > 1) {
                    messages.errors.length = 1;
                }

                return reject(new Error(messages.errors.join('\n\n')));
            }

            const resolveArgs = {
                stats,
                previousFileSizes,
                warnings: messages.warnings
            };

            return resolve(resolveArgs);
        });
    });
}
900585
function buildBrowser(file, watch) {
  const props = {
    entries: [paths.src + file + '.js'],
    debug : true,
    cache: {},
    packageCache: {},
    standalone: 'swapi'
  };

  const bundler = watch ? watchify(browserify(props)) : browserify(props);

  function rebundle() {
    let stream = bundler.transform('babelify')
      .bundle();
    return stream
      .pipe($.plumber())
      .on('error', (err) => { $.notify().write(err); })
      .pipe(source(file + '.browser.js'))
      .pipe(buffer())
      .pipe($.uglify())
      .pipe(gulp.dest(paths.dist));
  }

  bundler.on('update', function() {
    rebundle();
    $.util.log('Rebundle...');
  });

  return rebundle();
}
681247
function compileJSSource(ComponentClass) {
    var sourceBuffer = new CompileSourceBuffer();
    var contextId = genSSRId();

    sourceBuffer.addRendererStart();
    var renderId = compileComponentSource(sourceBuffer, ComponentClass, contextId);
    sourceBuffer.addRaw('return componentRenderers.' + renderId + '(data, noDataOutput)');
    sourceBuffer.addRendererEnd();

    return sourceBuffer.toCode();
}
45002
function () {
            var len = this.source.length,
                char,
                matched,
                result = '';
            if (this.position >= len) {
                return undefined;
            }
            for (; this.position < len; this.position++) {
                char = this.readNextChars(1);
                //读到 '@' 就停止，因为 '@' 后面的必定是脚本代码。Stop if '@', for the code behind '@' must be the server scripts.
                if (char === configure.symbol) {
                    break;
                }

                if (char === '<' && /^<(\w+)/.test(this.readNextChars(50))) {
                    matched = this.readNextChars(50).match(/^<(\w+)/);
                    this.tags.push({
                        type: matched[1],
                        position: this.position
                    });
                }

                //遇到 > 并且之前已经遇到过开始标签了。Meet '>' and there exists start tag.
                if (char === '>' && this.tags.length > 0) {
                    //...</div> , <img >
                    if (new RegExp('<(\\\\)?\/' + this.tags[this.tags.length - 1].type + '\\s*>$').test(this.readPrevChars() + char) || this.selfClosedTags.indexOf(this.tags[this.tags.length - 1].type) > -1) {
                        this.tags.pop();
                        result += char;
                        if ((this.tags[this.tags.length - 1] || {position: -1}).position >= (this.braces[this.braces.length - 1] || {position: -1}).position) {
                            continue;
                        } else {
                            this.position += 1;
                            //如果接下来的字符是空格。If next char is whitespace.
                            if (this.readNextChars(1).match(/\s/)) {
                                result += this.readNextChars(1);
                                this.position += 1;
                            }
                            break;
                        }
                    }
                }

                result += char;
            }

            //准备进入后端读取模式。Ready to switch to backend read mode.
            this.state = stateEnum.server;
            return result;
        }
1096358
function inlineFileRegHandle(regFiles, buildInfo, options, reqModuleJS, file) {        
        var content = '';
        if(regFiles && regFiles.length) {
            var destMP = {'.js':options.jsDestPath,'.css':options.cssDestPath};
            for(var j=0;j<regFiles.length;j++) {
                var jp = regFiles[j].trim().replace(/(^['"]*)|(['"]*$)/g, '');               
                if(!jp) continue;
                //去除?之后面路径
                if(jp.indexOf('?') > -1) jp = jp.substr(0, jp.indexOf('?'));

                if(jp[0] == '/') {
                    //相对于当前根路径
                    var filepath = path.join(options.destPath, jp);
                }
                //相对于js构建目标目录
                else if(jp[0] != '.') { 
                    var ext = path.extname(jp).toLowerCase();
                    var dest = destMP[ext] || options.destPath;
                    var filepath = path.join(dest, jp);
                    
                    //如果不存在，则相对于当前html发布路径
                    if(!fs.existsSync(filepath)) {                        
                        filepath = path.join(options.dest, jp); 
                    }//如果不存在，则相对于当前根发布路径
                    if(!fs.existsSync(filepath) && options.destPath) {                        
                        filepath = path.join(options.destPath, jp); 
                    }                              
                    //如果文件还是不存在，则相对于项目发布路径
                    if(!fs.existsSync(filepath)) {
                        console.log(filepath + ' not exists, check dest path!');
                        //相对于当前html文件                  
                        filepath = path.join(path.dirname(file.path), jp); 
                    }
                }
                else {
                    //相对于当前html路径
                    var filepath = path.join(options.dest, jp);
                }
                //读取内联的文件内容
                content += readInlineContent(filepath, buildInfo, reqModuleJS, options) + '\n';
            }
        }
        return content;
    }
1331463
function (md) {
            var html = marked(md, this.options.markdown);
            //Only reprocess if helpers were asked for
            if (this.options.helpers || (html.indexOf('{{#crossLink') > -1)) {
                //console.log('MD: ', html);
                try {
                    // marked auto-escapes quotation marks (and unfortunately
                    // does not expose the escaping function)
                    html = html.replace(/&quot;/g, "\"");
                    html = (Y.Handlebars.compile(html))({});
                } catch (hError) {
                    //Remove all the extra escapes
                    html = html.replace(/\\{/g, '{').replace(/\\}/g, '}');
                    Y.log('Failed to parse Handlebars, probably an unknown helper, skipping..', 'warn', 'builder');
                }
                //console.log('HB: ', html);
            }
            return html;
        }
1371846
function compileTemplates() {
  const mainHtml = fs.readFileSync(path.resolve(docsDir, 'src/template.html'), {
    encoding: 'utf8',
  });
  const mainTemplate = Handlebars.compile(mainHtml);

  function createPage(fileName, tab, content) {
    const html = mainTemplate({
      tabs: [{
        title: 'Get started',
        url: 'get-started.html',
        selected: tab === 'get-started',
      }, {
        title: 'Components',
        url: 'components.html',
        selected: tab === 'components',
      }],
      content,
      luiVersion: LUI_VERSION,
    });
    fileUtil.writeFile(path.resolve(docsDir, 'dist', fileName), html);
  }

  function createIndexPage() {
    const content = fs.readFileSync(path.resolve(docsDir, 'src/pages/index.html'), {
      encoding: 'utf8',
    });
    const template = Handlebars.compile(content);
    const html = template();
    return createPage('index.html', 'index', html);
  }

  function createGetStartedPage() {
    const content = fs.readFileSync(path.resolve(docsDir, 'src/pages/get-started.html'), {
      encoding: 'utf8',
    });
    const template = Handlebars.compile(content);
    const html = template({
      luiVersion: LUI_VERSION,
    });
    return createPage('get-started.html', 'get-started', html);
  }

  function createComponentPage(templateName, template, tab, content) {
    return createPage(templateName, tab, template({
      content,
      sections: sections.map(section => ({
        name: section.name,
        pages: section.pages.map(page => ({
          name: page.name,
          template: page.template,
          selected: page.template === templateName,
        })),
      })),
    }));
  }

  function createComponentPages() {
    const componentHtml = fs.readFileSync(path.resolve(docsDir, 'src/component-template.html'), {
      encoding: 'utf8',
    });
    const componentTemplate = Handlebars.compile(componentHtml);

    sections.forEach((section) => {
      section.pages.forEach((page) => {
        const file = `src/pages/${page.template}`;
        const fileContent = fs.readFileSync(path.resolve(docsDir, file), {
          encoding: 'utf8',
        });

        const template = Handlebars.compile(fileContent);
        const html = template();

        createComponentPage(page.template, componentTemplate, 'components', html);
      });
    });

    const file = 'src/pages/components.html';
    const fileContent = fs.readFileSync(path.resolve(docsDir, file), {
      encoding: 'utf8',
    });
    createComponentPage('components.html', componentTemplate, 'components', fileContent);
  }

  createIndexPage();
  createGetStartedPage();
  createComponentPages();
}
875121
function watchCompiler(compiler, options={}){
  let watching = false
  log('Watch Building')
  const startWatchTime = Date.now()
  const watchConfig = { // watch options:
    //aggregateTimeout: 300, // wait so long for more changes
    //poll: true // use polling instead of native watchers
    // pass a number to set the polling interval
  }

  options.onRebuild = options.onRebuild || function(){}

  return new Promise(function(res,rej){  
    //webpack watch functionality
    compiler.watch(watchConfig, function(err,stats){
      if(err)return rej(err)

      if(watching){
        log('Rebuilt '+getServerTime())
        options.onRebuild(stats)
      }else{
        watching = true
        log('Watching '+(Date.now()-startWatchTime)/1000+' seconds')
        res( this )
      }
    });
  })
}
389714
function loadJS(url, callback, fail, charset) {
        var node = DOC.createElement('script');
        var args = _arrSlice.call(arguments, 0);
        if($.isString(fail) && args.length === 3) {
            //如果fail为字符串，认为是charset
            charset = fail;
        } else if(args.length === 4 && $.isString(charset)) {

        } else {
            charset = config.charset;
        }
        $.isFunction(callback) && jsCallback(node, callback, fail);

        node.charset = charset;
        node.async = true;
        node.src = url;
        HEAD.insertBefore(node, BASEELEMENT);
        return $;
    }