Borrowed from https://github.com/mikedeboer/node-github/blob/master/util.js
776371
function toCamelCase (str, upper) {
  str = str.toLowerCase().replace(/(?:(^.)|(\s+.)|(-.))/g, function (match) {
    return match.charAt(match.length - 1).toUpperCase()
  })
  if (upper) {
    return str
  }
  return str.charAt(0).toLowerCase() + str.substr(1)
}
128955
function prepareDebug() {
  // Import Closure Library and deps.js.
  require('../src/wtf/bootstrap/node').importClosureLibrary([
    'wtf_js-deps.js'
  ]);

  // Disable asserts unless debugging - asserts cause all code to deopt.
  if (debugMode) {
    goog.require('goog.asserts');
    goog.asserts.assert = function(condition, opt_message) {
      console.assert(condition, opt_message);
      return condition;
    };
  } else {
    goog.DEBUG = false;
    goog.require('goog.asserts');
    goog.asserts.assert = function(condition) {
      return condition;
    };
  }

  // Load WTF and configure options.
  goog.require('wtf');
  wtf.NODE = true;
  goog.require('wtf.db.exports');
  goog.require('wtf.db.node');
}
174277
function appendRecursively(formData, collection, parentkey, parentIsArray) {
    //console.log(...arguments)

    for (let k in collection) {
        const val = collection[k];

        if (val === undefined) continue;

        if (val instanceof File) {
            let mkey = (parentkey ? parentkey + '.' : '') + k;

            // if(parentIsArray)
            // 	mkey = parentkey
            // else
            // 	mkey = k


            val.foo = 'bar'

            formData.append(mkey, val)
        }
        else if (Array.isArray(val)) {

            let mkey = '';
            if (parentIsArray) {
                mkey = parentkey; //parentKey can/should never be empty if parentISarray
            } else {
                mkey = (parentkey ? parentkey + '.' + k : k);
            }

            appendRecursively(formData, val, mkey, true);
        }
        else if (typeof val === 'object') {
            let mkey = (parentkey ? parentkey + '.' : '') + k;
            appendRecursively(formData, val, mkey, false);
        }
        else {
            let mkey = (parentkey ? parentkey + '.' : '') + k;
            formData.append(mkey, val)
        }

    }
}
256163
function getNodeProps(node, key, opts, renderer) {
    var props = { key: key }, undef;

    // `sourcePos` is true if the user wants source information (line/column info from markdown source)
    if (opts.sourcePos && node.sourcepos) {
        props['data-sourcepos'] = flattenPosition(node.sourcepos);
    }

    var type = normalizeTypeName(node.type);

    switch (type) {
        case 'html_inline':
        case 'html_block':
            props.isBlock = type === 'html_block';
            props.escapeHtml = opts.escapeHtml;
            props.skipHtml = opts.skipHtml;
            break;
        case 'code_block':
            var codeInfo = node.info ? node.info.split(/ +/) : [];
            if (codeInfo.length > 0 && codeInfo[0].length > 0) {
                props.language = codeInfo[0];
                props.codeinfo = codeInfo;
            }
            break;
        case 'code':
            props.children = node.literal;
            props.inline = true;
            break;
        case 'heading':
            props.level = node.level;
            break;
        case 'softbreak':
            props.softBreak = opts.softBreak;
            break;
        case 'link':
            props.href = opts.transformLinkUri ? opts.transformLinkUri(node.destination) : node.destination;
            props.title = node.title || undef;
            if (opts.linkTarget) {
                props.target = opts.linkTarget;
            }
            break;
        case 'image':
            props.src = opts.transformImageUri ? opts.transformImageUri(node.destination) : node.destination;
            props.title = node.title || undef;

            // Commonmark treats image description as children. We just want the text
            props.alt = node.react.children.join('');
            node.react.children = undef;
            break;
        case 'list':
            props.start = node.listStart;
            props.type = node.listType;
            props.tight = node.listTight;
            break;
        default:
    }

    if (typeof renderer !== 'string') {
        props.literal = node.literal;
    }

    var children = props.children || (node.react && node.react.children);
    if (Array.isArray(children)) {
        props.children = children.reduce(reduceChildren, []) || null;
    }

    return props;
}
1072877
function (yamlJson, cb) {
		
		let all_apis = {};
		let all_errors = {};
		
		let paths = reformatPaths(yamlJson.paths);
		let definitions = yamlJson.definitions;
		let parameters = yamlJson.parameters;
		
		let convertedDefinitions = {};
		let convertedParameters = {};
		
		// convert definitions first
		if (definitions) {
			let definitionsKeys = Object.keys(definitions);
			definitionsKeys.forEach(function (eachDef) {
				convertedDefinitions[eachDef] = convertItem(null, definitions[eachDef], 1); // 1 ??? definitions should never have schema -=-=-=-=-=
			});
		}
		
		// convert parameters then
		if (parameters) {
			let parametersKeys = Object.keys(parameters);
			parametersKeys.forEach(function (eachParam) {
				convertedParameters[eachParam] = convertItem(convertedDefinitions, parameters[eachParam], 1);
			});
			all_apis.commonFields = convertedParameters;
		}
		
		let pathsKeys = Object.keys(paths);
		pathsKeys.forEach(function (eachPath) {
			let methods = paths[eachPath];
			let methodsKeys = Object.keys(methods);
			
			methodsKeys.forEach(function (eachMethod) {
				let apiData = methods[eachMethod];
				
				if (!all_apis[eachMethod]) {
					all_apis[eachMethod] = {};
				}
				
				var mwFile = eachPath.replace(/\\/g, "_").replace(/:/g, "_").replace(/\//g, "_").replace(/[_]{2,}/g, "_").replace(/{/g, "").replace(/}/g, "");
				mwFile = mwFile.toLowerCase();
				if (mwFile[0] === "_") {
					mwFile = mwFile.substring(1);
				}
				mwFile += "_" + eachMethod.toLowerCase() + ".js";
				
				all_apis[eachMethod][eachPath] = {
					_apiInfo: {},
					"mw": '%dirname% + "/lib/mw/' + mwFile + '"'
				};
				let newSoajsApi = all_apis[eachMethod][eachPath];
				
				let params = apiData.parameters;
				
				let group = apiData.tags ? apiData.tags[0] : "";
				newSoajsApi._apiInfo.group = group && group !== '' ? group : "general";
				newSoajsApi._apiInfo.l = apiData.summary;
				newSoajsApi.imfv = convertParams(convertedDefinitions, convertedParameters, params);
			});
		});
		
		// todo: convert errors
		
		return cb({"schema": all_apis, "errors": all_errors});
	}
1181576
function() {
    var captures;
    if (captures = /^(-)?(\d+\.\d+|\d+|\.\d+)(%|[a-zA-Z]+)?[ \t]*/.exec(this.str)) {
      this.skip(captures);
      var n = parseFloat(captures[2]);
      if ('-' == captures[1]) n = -n;
      var node = new nodes.Unit(n, captures[3]);
      node.raw = captures[0];
      return new Token('unit', node);
    }
  }
1148355
function transformFunction(node) {
  var nameNode = node.nodes[0];
  var paramsNodes = node.nodes[1] ? node.nodes[1].nodes : [];
  node.name = nameNode.value;
  if (node.name) {
    node.item('functions')[node.name] = node;
  }
  node.params = [];
  node.paramIndex = {};

  var paramTags = node.paramTags;
  // for functions assigned to variables, paramTags are in parent --
  // i.e. '/* @param a */ var parent = function (a) {}'
  if (node.paramTags === undefined && node.parent &&
      node.parent.type === 'assign' && node.parent.paramTags) {
    paramTags = node.parent.paramTags;
  }
  node.item('paramTags', paramTags);

  if (node.copyTags) {
    var tagSource = node.item('functions')[node.copyTags];
    if (tagSource) {
      if (!node.description && tagSource.description) {
        node.description = tagSource.description;
      }
      if (!paramTags && tagSource.item('paramTags')) {
        paramTags = tagSource.item('paramTags');
      }
    }
  }

  paramsNodes.forEach(function (paramNode, i) {
    var param = {
      name: paramNode.value
    };
    node.paramIndex[param.name] = i;
    if (paramTags) {
      if (paramTags[param.name]) {
        var tagValue = paramTags[param.name];
    // if (node.item('path') === 'cli') {
    //   console.log(tagValue)
    // }
        Object.keys(tagValue).forEach(function (key, i) {
          if (key !== 'name') {
            param[key] = tagValue[key];
          }
        });
      }
    }
    node.params.push(param);
  });
    // if (node.item('path') === 'cli') {
    //   console.log(node.params)
    // }
}
1122703
function gulpLodashAutobuild(options) {
  const search = /_\.(\w*)/g;
  let props = [];

  options = options ? options : { target: './lodash.custom.js', settings: {} };

  if (options.include) {
    props = options.include;
  }

  function log(message) {
    gutil.log(magenta(PLUGIN_NAME), message);
  }

  function warn(message) {
    log(red('WARNING') + ' ' + message);
  }

  function raiseError(message) {
    return new PluginError(PLUGIN_NAME, message);
  }

  function findProps(body) {
    let content = body;

    // TODO: Need to be able to handle chaining, below is just the beginning
    // Remove line breaks
    content = content.replace(/(\r\n|\n|\r)/gm, '');
    // Remove comments
    content = content.replace(/(\/\*[\w\'\s\r\n\*]*\*\/)|(\/\/[\w\s\']*)|(\<![\-\-\s\w\>\/]*\>)/gm, '');
    // Remove bank spaces
    content = content.replace(/\s/g, '');

    // Match regex
    const tmp = content.match(search);
    if (tmp) {
      props = props.concat(tmp);
    }
  }

  function transform(file, enc, callback) {
    const _this = this;
    if (file.isBuffer()) {
      warn('Buffers not supported...');
      return callback();
    } else if (file.isStream()) {
      let body = '';
      file.contents.on('data', function(chunk) {
        body += chunk;
      }).on('end', function() {
        findProps(body);
        _this.push(file);
        callback();
      });
    } else {
      _this.push(file);
      callback();
    }
  }

  function flush(callback) {
    props = _.uniq(props).map(function(item) {
      return item.split('.')[1];
    }).sort();

    // Remove invalid property names
    const propsInvalid = _.difference(props, _.keys(_));
    const propsValid = _.intersection(props, _.keys(_));

    log('Build includes: ' + propsValid.join(', '));

    if (propsInvalid.length) {
      warn('Invalid properties ignored: ' + propsInvalid.join(', '));
    }

    childProcess.execFile(autobuild,
      [
        '-d',
        '-c',
        'include=' + propsValid.join(',' + ''),
        'settings=' + JSON.stringify(options.settings)
      ],
      {
        maxBuffer: 1024 * 600
      },
      function(error, stdout) {
        if (error !== null) {
          throw raiseError(error);
        }
        mkdirp(path.dirname(options.target), function() {
          fs.writeFile(options.target, stdout, function(error) {
            if (error !== null) {
              throw raiseError(error);
            }
            callback();
          });
        });
      });
  }

  return through.obj(transform, flush);
}
1093217
function getTextBetween(node1, node2) {
            const allTokens = [node1].concat(sourceCode.getTokensBetween(node1, node2)).concat(node2);
            const sourceText = sourceCode.getText();

            return allTokens.slice(0, -1).reduce((accumulator, token, index) => accumulator + sourceText.slice(token.range[1], allTokens[index + 1].range[0]), "");
        }
1295185
function concatJS(data) {
  const hexo = this;
  const options = hexo.config.js_concator;
  // Reture if disabled.
  if (options.enable === false) return;

  const log = hexo.log || console;
  const route = hexo.route;
  const routeList = route.list();

  // let include = options.include;
  // if (include && !Array.isArray(include)) include = [include];

  // 1. get all local scripts
  const htmls = {};
  const bundlePath = options.bundle_path;
  const front = options.front;
  return Promise.all(routeList.filter(path => path.endsWith('.html')).map(path => {
    // 1. get the htmls that has local scripts
    return new Promise((resolve, reject) => {
      const html = route.get(path);
      let htmlTxt = '';
      html.on('data', (chunk) => (htmlTxt += chunk));
      html.on('end', () => {
        const $ = cheerio.load(htmlTxt, { decodeEntities: false });
        const $scripts = {};
        const srcs = [];
        $('script[src]').each((idx, ele) => {
          const $script = $(ele);
          let src = $script.attr('src');
          if (src && src.length) {
            // local script
            if (!src.startsWith('//') && !src.startsWith('http')) {
              src = route.format(src);
              // ignore and remove duplicated
              if (srcs.indexOf(src) === -1) {
                srcs.push(src);
                $scripts[src] = $script;
              } else {
                $script.remove();
              }
            }
          }
        });
        if (srcs.length) {
          htmls[path] = { path, $, srcs, $scripts };
        }
        resolve();
      });
    });
  }))
    // 2. extract common scripts
    .then(() => {
      const htmlPaths = Object.keys(htmls);
      const scripts = [];
      // collect the scripts
      for (const path of htmlPaths) {
        const html = htmls[path];
        const srcs = html.srcs;
        for (let i = srcs.length - 1; i >= 0; --i) { // reverse for deletion
          const src = srcs[i];
          if (scripts.indexOf(src) === -1) {
            // if a script exists in more than one htmls,
            // TODO, or match the pattern in exclude array
            const count = htmlPaths.reduce((sum, path) => (htmls[path].srcs.indexOf(src) !== -1 ? ++sum : sum), 0);
            if (count > 1) {
              // remove
              log[options.silent ? 'debug' : 'info']('update Concate JS: remove %s from %s', src, path);
              html.$scripts[src].remove();
              delete html.$scripts[src];
              srcs.splice(srcs.indexOf(src), 1);
              scripts.push(src);
            }
            // if (htmlPaths.every(path => htmls[path].srcs.indexOf(src) !== -1) ||
            //   include.some(pattern => minimatch(src, pattern, { matchBase: true }))) {
            // }
          } else {
            // remove
            log[options.silent ? 'debug' : 'info']('update Concate JS: remove %s from %s', src, path);
            html.$scripts[src].remove();
            delete html.$scripts[src];
            srcs.splice(srcs.indexOf(src), 1);
          }
        }
        html.srcs = srcs;
      }

      if (scripts.length > 1) {
        // add the bundle script to all html
        for (const path of htmlPaths) {
          const html = htmls[path];
          if (front) {
            html.$(`<script type="text/javascript" src="${route.format(bundlePath)}"></script>`).insertBefore(html.$('body>script').first());
          } else {
            html.$('body').append(`<script type="text/javascript" src="/${route.format(bundlePath)}"></script>`);
          }
          route.set(path, html.$.html());
          log[options.silent ? 'debug' : 'info']('update Concate JS: add /%s to %s', route.format(bundlePath), path);
        }
      }
      return scripts.reverse();
    })
    // 3. concat the script
    .then((scripts) => {
      if (scripts.length < 1) return;
      log[options.silent ? 'debug' : 'info']('update Concate JS: try to concat %s scripts', scripts.length);
      return Promise.all(scripts.map(path => {
        return new Promise((resolve, reject) => {
          const script = route.get(path);
          let scriptTxt = '';
          script.on('data', chunk => (scriptTxt += chunk));
          script.on('end', () => {
            route.remove(path);
            log[options.silent ? 'debug' : 'info']('update Concate JS: concat script %s', path);
            resolve(scriptTxt);
          });
        });
      })).then(results => {
        const bundleScript = results.reduce((txt, script) => (txt += script), '');
        route.set(route.format(bundlePath), bundleScript);
        log[options.silent ? 'debug' : 'info']('update Concate JS: finish concat js script');
      });
    });
}
1088309
async function srcToDocs (dir) {
  const location = path.join(srcPath, dir)
  const srcFiles = await getFiles(location, (item) => item.path.endsWith('.js') && !item.path.endsWith('index.js'))
  const filesContents = await readFiles(srcFiles)
  const filesComments = srcFiles.map((location, index) => {
    const fnName = path.basename(location).replace(/\.js$/, '')
    const matter = getMatter(fnName, dir)
    const doc = matter.concat(extractComments(filesContents[index])).concat(getRuleImport(fnName))
    return { comments: doc.join('\n'), location }
  })
  await writeDocs(docsDir, filesComments)
}
281404
function jsdocCommand( jsdoc ) {
	var cmd = [];
	cmd.unshift( jsdoc.options );
	if ( jsdoc.tutorials.length > 0 ) {
		cmd.push( "-u " + path.resolve( jsdoc.tutorials ) );
	}
	cmd.push( "-d " + path.resolve( jsdoc.dest ) );
	cmd.push( "-t " + path.resolve( jsdoc.template ) );
	cmd.push( "-c " + path.resolve( jsdoc.config ) );
	sys.each( jsdoc.src, function ( src ) {
		cmd.push( path.resolve( src ) );
	} );
	cmd.unshift( path.resolve( "./node_modules/jsdoc/jsdoc" ) );
	cmd.unshift( "node" );

	return cmd.join( " " );
}
96271
function notfoundUnit (server) {
  var regexes = [];
  var callbacks = [];

  function notfound (paths, literalCall) {
    regexes.push(RegExp(paths));
    callbacks.push(literalCall);
  }

  server.notfound = notfound;

  return function notfoundLayer (req, res) {
    res.statusCode = 404;
    var matched = null;
    var cbindex = -1;
    for (var i = 0; i < regexes.length; i++) {
      matched = req.path.match (regexes[i]);
      if (matched !== null) { cbindex = i; break; }
    }
    if (cbindex >= 0) {
      catchpath(req, res, matched, callbacks[cbindex], server.templateReader);
    } else {
      res.end('Not Found\n');
    }
  };
}
1250926
function(str) {
            var root, error = null;

            i = j = current = 0;
            chunks = [];
            input = str.replace(/\r\n/g, '\n');
            if (env.filename) {
                that.env.inputs[env.filename] = input;
            }

            // Split the input into chunks.
            chunks = (function (chunks) {
                var j = 0,
                    skip = /(?:@\{[\w-]+\}|[^"'`\{\}\/\(\)\\])+/g,
                    comment = /\/\*(?:[^*]|\*+[^\/*])*\*+\/|\/\/.*/g,
                    string = /"((?:[^"\\\r\n]|\\.)*)"|'((?:[^'\\\r\n]|\\.)*)'|`((?:[^`]|\\.)*)`/g,
                    level = 0,
                    match,
                    chunk = chunks[0],
                    inParam;

                for (var i = 0, c, cc; i < input.length;) {
                    skip.lastIndex = i;
                    match = skip.exec(input);
                    if (match) {
                        if (match.index === i) {
                            i += match[0].length;
                            chunk.push(match[0]);
                        }
                    }
                    c = input.charAt(i);
                    comment.lastIndex = string.lastIndex = i;

                    match = string.exec(input)
                    if (match) {
                        if (match.index === i) {
                            i += match[0].length;
                            chunk.push(match[0]);
                            continue;
                        }
                    }

                    if (!inParam && c === '/') {
                        cc = input.charAt(i + 1);
                        if (cc === '/' || cc === '*') {
                            match = comment.exec(input);
                            if (match) {
                                if (match.index === i) {
                                    i += match[0].length;
                                    chunk.push(match[0]);
                                    continue;
                                }
                            }
                        }
                    }

                    switch (c) {
                        case '{':
                            if (!inParam) {
                                level ++;
                            }
                            else {
                                inParam = false;
                            }
                            chunk.push(c);
                            break;
                        case '}':
                            if (!inParam) {
                                level --;
                                chunk.push(c);
                                chunks[++j] = chunk = [];
                            }
                            else {
                                inParam = false;
                                chunk.push(c);
                            }
                            break;
                        case '(':
                            if (!inParam) {
                                inParam = true;
                            }
                            else {
                                inParam = false;
                            }
                            chunk.push(c);
                            break;
                        case ')':
                            if (inParam) {
                                inParam = false;
                            }
                            chunk.push(c);
                            break;
                        default:
                            chunk.push(c);
                    }

                    i++;
                }
                if (level !== 0) {
                    error = {
                        index: i - 1,
                        message: (level > 0) ? "missing closing `}`" : "missing opening `{`",
                        filename: env.filename
                    };
                }

                return chunks.map(function (c) { return c.join(''); });
            })([[]]);

            if (error) {
                util.error(env, error);
                throw new Error('N/A');
            }

            // Start with the primary rule.
            // The whole syntax tree is held under a Ruleset node,
            // with the `root` property set to true, so no `{}` are
            // output.
            root = new tree.Ruleset([], $(this.parsers.primary));
            root.root = true;

            // Get an array of Ruleset objects, flattened
            // and sorted according to specificitySort
            root.toList = (function() {
                return function(env) {
                    env.frames = env.frames || [];


                    // call populates Invalid-caused errors
                    var definitions = this.flatten([], [], env);
                    definitions.sort(specificitySort);
                    return definitions;
                };
            })();

            // Sort rules by specificity: this function expects selectors to be
            // split already.
            //
            // Written to be used as a .sort(Function);
            // argument.
            //
            // [1, 0, 0, 467] > [0, 0, 1, 520]
            var specificitySort = function(a, b) {
                var as = a.specificity;
                var bs = b.specificity;

                if (as[0] != bs[0]) return bs[0] - as[0];
                if (as[1] != bs[1]) return bs[1] - as[1];
                if (as[2] != bs[2]) return bs[2] - as[2];
                return bs[3] - as[3];
            };

            return root;
        }
576866
function (opt, handler) {

			var recquire_t = require('aureooms-node-recursive-require');
			var extend = require('node.extend');

			var dflt = {
				name: undefined,
				src: undefined,
				exports: undefined,
				base: 0,
				index: 'index.js',
				intro: 'intro.js',
				outro: 'outro.js',
				rec: false,
				flat: true,
				debug: false
			};

			opt = extend({}, dflt, opt);

			if (opt.name) opt.name = opt.name.replace(/-/g, '');

			var recquire = recquire_t(opt);

			recquire(opt.src, opt.exports, -opt.base, handler);
		}
49908
function getCode(code, opts, attrs, url) {
  var type = getType(attrs),
    parserOpts = getParserOptions(attrs)

  //#if NODE
  // istanbul ignore else
  if (url) {
    var src = getAttr(attrs, 'src')
    if (src) {
      var
        charset = getAttr(attrs, 'charset'),
        file = path.resolve(path.dirname(url), src)
      code = require('fs').readFileSync(file, charset || 'utf8')
    }
  }
  //#endif
  return _compileJS(code, opts, type, parserOpts, url)
}
195178
function ErrorStackParser$$parseOpera11(error) {
	            var filtered = _filter(error.stack.split('\n'), function (line) {
	                return !!line.match(FIREFOX_SAFARI_STACK_REGEXP) &&
	                    !line.match(/^Error created at/);
	            }, this);
	
	            return _map(filtered, function (line) {
	                var tokens = line.split('@');
	                var locationParts = this.extractLocation(tokens.pop());
	                var functionCall = (tokens.shift() || '');
	                var functionName = functionCall
	                        .replace(/<anonymous function(: (\w+))?>/, '$2')
	                        .replace(/\([^\)]*\)/g, '') || undefined;
	                var argsRaw;
	                if (functionCall.match(/\(([^\)]*)\)/)) {
	                    argsRaw = functionCall.replace(/^[^\(]+\(([^\)]*)\)$/, '$1');
	                }
	                var args = (argsRaw === undefined || argsRaw === '[arguments not available]') ? undefined : argsRaw.split(',');
	                return new StackFrame(functionName, args, locationParts[0], locationParts[1], locationParts[2], line);
	            }, this);
	        }