TODO naive implementation mutating app._router.stack - make more robust, also brittle
346272
function removeAPI(name, ignoreNotFound) {
  return function (done) {
    API.removeByName(name, function (err, api) {
      if (api) {
        done(null, api);
      } else {
        if (err && err.message == NOT_FOUND) {
          if (ignoreNotFound) {
            done(null, false);
          } else {
            done(err);
          }
        } else {
          console.log(err);
          done(err);
        }
      }
    });
  }
}
677043
function parseAhead( router, req, done ) {
	var idx = 0;
	var stack = router.stack;
	var params = {};
	var method = req.method ? req.method.toLowerCase() : undefined;
	next();

	function next() {
		var layer = stack[ idx++ ];
		if ( !layer ) {
			// strip dangling query params
			params = _.transform( params, function( acc, v, k ) {
				acc[ k ] = v.split( '?' )[ 0 ]; return acc;
			}, {} );
			return done( params );
		}

		if ( layer.method && layer.method !== method ) {
			return next();
		}
		layer.match( req.originalUrl );
		params = _.merge( params, layer.params );
		next();
	}
}
373666
function _recurseMatchAndExecute(
        match, actionRunner, paths,
        method, routerInstance, jsongCache) {
    var unhandledPaths = [];
    var invalidated = [];
    var reportedPaths = [];
    var currentMethod = method;
    return Observable.from(paths).pipe(

        // Each pathSet (some form of collapsed path) need to be sent
        // independently.  for each collapsed pathSet will, if producing
        // refs, be the highest likelihood of collapsibility.
        expand(function(nextPaths) {
            if (!nextPaths.length) {
                return Observable.empty();
            }

            var result = match(currentMethod, nextPaths);
            if (result.error) {
                return Observable.throw(result.error);
            }
            var matchedResults = result.value;

            // When there is explicitly not a match then we need to handle
            // the unhandled paths.
            if (!matchedResults.length) {
                unhandledPaths.push(nextPaths);
                return Observable.empty();
            }
            return runByPrecedence(
                nextPaths, matchedResults, actionRunner
            ).pipe(
                // Generate from the combined results the next requestable paths
                // and insert errors / values into the cache.
                mergeMap(function(results) {
                    var value = results.value;
                    var suffix = results.match.suffix;

                    // TODO: MaterializedPaths, use result.path to build up a
                    // "foundPaths" array.  This could be used to materialize
                    // if that is the case.  I don't think this is a
                    // requirement, but it could be.
                    if (!isArray(value)) {
                        value = [value];
                    }

                    var invsRefsAndValues =
                        mCGRI(jsongCache, value, routerInstance);
                    var invalidations = invsRefsAndValues.invalidations;
                    var unhandled = invsRefsAndValues.unhandledPaths;
                    var messages = invsRefsAndValues.messages;
                    var pathsToExpand = [];

                    if (suffix.length > 0) {
                        pathsToExpand = invsRefsAndValues.references;
                    }

                    // Merge the invalidations and unhandledPaths.
                    invalidations.forEach(function(invalidation) {
                        invalidated[invalidated.length] = invalidation.path;
                    });

                    unhandled.forEach(function(unhandledPath) {
                        unhandledPaths[unhandledPaths.length] = unhandledPath;
                    });

                    // Merges the remaining suffix with remaining nextPaths
                    pathsToExpand = pathsToExpand.map(function(next) {
                        return next.value.concat(suffix);
                    });

                    // Alters the behavior of the expand
                    messages.forEach(function(message) {
                        // mutates the method type for the matcher
                        if (message.method) {
                            currentMethod = message.method;
                        }

                        // Mutates the nextPaths and adds any additionalPaths
                        else if (message.additionalPath) {
                            var path = message.additionalPath;
                            pathsToExpand[pathsToExpand.length] = path;
                            reportedPaths[reportedPaths.length] = path;
                        }

                        // Any invalidations that come down from a call
                        else if (message.invalidations) {
                            message.
                                invalidations.
                                forEach(function(invalidation) {
                                    invalidated.push(invalidation);
                                });
                        }

                        // We need to add the unhandledPaths to the jsonGraph
                        // response.
                        else if (message.unhandledPaths) {
                            unhandledPaths = unhandledPaths.
                                concat(message.unhandledPaths);
                        }
                    });

                    // Explodes and collapse the tree to remove
                    // redundants and get optimized next set of
                    // paths to evaluate.
                    var optimizeResult = optimizePathSets(
                        jsongCache, pathsToExpand, routerInstance.maxRefFollow);
                    if (optimizeResult.error) {
                        return Observable.throw(optimizeResult.error);
                    }
                    pathsToExpand = optimizeResult.paths;

                    if (pathsToExpand.length) {
                        pathsToExpand = collapse(pathsToExpand);
                    }

                    return Observable.
                        from(pathsToExpand);
                }),
                defaultIfEmpty([])
            );

        }/* TODO: , Number.POSITIVE_INFINITY, Rx.Scheduler.queue*/),
        reduce(function(acc, x) {
            return acc;
        }, null),
        map(function() {
            return {
                unhandledPaths: unhandledPaths,
                invalidated: invalidated,
                jsonGraph: jsongCache,
                reportedPaths: reportedPaths
            };
        })
    );
}
1202785
function mount(router) {
  var r = arguments[1] || routes;
  var pre = arguments[2] || '';
  
  for (var k in r) {
    var file = '/' + pre + '' + k + '.js';
    debug('mount route ' + file + " ");
    var path = '';
    
    debug(k)
    debug(r[k])
    
    if (k === 'apie.js' || k === 'app.js'|| k === 'package.json') {
      return
    }

    if (typeof r[k] == 'object' && !(r[k]['body'] || r[k]['res']) ){
      // console.log('this is a obj');
      mount(router, r[k], pre + k + '/');
    } else if(k === 'index') {
      path = '/'+ pre;
      _use(router, file, path, r[k]);
    } else {
      path = '/' + pre + '' + k;
      _use(router, file, path, r[k]);
    }
  }
}
1029008
function toHaveMiddleware(middleware) {
    
    expect(this.actual).toExist('Route is undefined');
    toBeAnExpressRoute(this.actual.route);
    expect(this.actual.route.stack.length).toBeGreaterThan(1, 'No middleware found');
    if(expressGuards.isMiddleware(middleware)) {
        expect(this.actual.route.stack.find(l => l.handle.toString() === middleware.toString())).toExist(`middleware is not defined`);
    } else {
        const name = middleware || '<anonymous>';
        expect(this.actual.route.stack.find(l => l.name === name)).toExist(`${name} is not defined`);
    }
}
496041
function EvalRoute (ctx, next) {
	let router = this;
	let matched = router.match(router.opts.routerPath || ctx.routerPath || ctx.path, ctx.method);
	/* istanbul ignore else */
	if (ctx.matched) {
		ctx.matched.push.apply(ctx.matched, matched.path);
	} else {
		ctx.matched = matched.path;
	}
	if (matched.route) {
		return this.middleware()(ctx, next);
	} else {
		return Promise.resolve('koaton-no-route');
	}
}
894563
function () {
                        //noinspection JSReferencingMutableVariableFromClosure
                        res.push({
                            combine: 1,
                            path: prefix + currentComboUrls.join(comboSep) + suffix,
                            mods: currentComboMods
                        });
                    }
96306
function defaults(route, name, handle) {
  if (typeof route === 'function') {
    handle = route;
    name = handle.name;
    route = '/';
  }
  else if (typeof name === 'function') {
    handle = name;
    name = handle.name;
  }

  // A name needs to be provided
  if (!name) throw new NameError();

  // wrap sub-apps
  if ('function' == typeof handle.handle) {
    var server = handle;
    handle.route = route;
    handle = function(req, res, next){
      server.handle(req, res, next);
    };
  }

  // wrap vanilla http.Servers
  if (handle instanceof http.Server) {
    handle = handle.listeners('request')[0];
  }

  // strip trailing slash
  if ('/' == route[route.length - 1]) {
    route = route.slice(0, -1);
  }

  return {route: route, name: name, handle: handle};
}
291550
function createRouter() {
  var rtr = express.Router.apply(express, arguments);
  router.patch(rtr);
  return rtr;
}
363927
function init (router) {
  router.use((err, req, res, next) => {
    console.error(err.stack || err.message)

    res.statusCode = err.statusCode || 500
    res.end()
  })
}
357114
def bind(cls, app, *paths, methods=None, name=None, router=None, view=None):
        """"""
        cls.app = app
        if cls.app is not None:
            for _, m in inspect.getmembers(cls, predicate=inspect.isfunction):
                if not hasattr(m, ROUTE_PARAMS_ATTR):
                    continue
                paths_, methods_, name_ = getattr(m, ROUTE_PARAMS_ATTR)
                name_ = name_ or ("%s.%s" % (cls.name, m.__name__))
                delattr(m, ROUTE_PARAMS_ATTR)
                cls.app.register(*paths_, methods=methods_, name=name_, handler=cls)(m)

        @coroutine
        @functools.wraps(cls)
        def handler(request):
            return cls().dispatch(request, view=view)

        if not paths:
            paths = ["/%s" % cls.__name__]

        return routes_register(
            app, handler, *paths, methods=methods, router=router, name=name or cls.name)
884006
function Router(req, res, next) {
        const server = this;
        const state = {
            method: req.method.toUpperCase(),
            params: {},
            routes: routes.concat(),
            routeUnhandled: true,
            server: server,
        };
        run(state, req, res, err => {
            req.params = {};
            if (state.routeUnhandled) req.log('unhandled', 'Router had no matching paths');
            next(err);
        });
    }
663176
function executeArrayMutation(state, payload, action) {
      var newValue, pathWithIds;

      if (!PROP_SUBPROP.includes('*')) {
        newValue = payload;
        pathWithIds = PROP_SUBPROP;
      } else {
        if (!isArray(payload) && action !== 'splice') payload = [payload];
        if (action !== 'pop' && action !== 'shift') newValue = payload.pop();
        var ids = getIdsFromPayload(payload, conf, PROP_SUBPROP);
        if (!checkIdWildcardRatio(ids, PROP_SUBPROP, conf)) return;
        pathWithIds = fillinPathWildcards(ids, PROP_SUBPROP, state, conf);
      }

      if (action === 'push') {
        return pushDeepValue(state, pathWithIds, newValue);
      }

      if (action === 'pop') {
        return popDeepValue(state, pathWithIds);
      }

      if (action === 'shift') {
        return shiftDeepValue(state, pathWithIds);
      }

      if (action === 'splice') {
        return spliceDeepValue.apply(void 0, [state, pathWithIds].concat(_toConsumableArray(newValue)));
      }
    }
947311
function Router(options) {
  if ( !(this instanceof Router) ) {
    return new Router(options);
  }
  options = options || {};
  var self = this;
  this.routes = [];
  this.caseSensitive = options.caseSensitive;
  this.strict = options.strict;
  this.connect = connect();
  this.middleware = function (req, res, next){
    dispatch(self, req, res, next);
  };
  this.eventHandlers = {
    404 : function(req, res){
      res.writeHead(404);
      res.end('Not found');
    },
    405 : function(req, res, resource){
      res.setHeader('Allow', allowHeader(self, resource));
      res.writeHead(405);
      res.end('Not allowed');
    },
    'HEAD' : function(req, res, resource){
      if (!resource.GET){
        return self.eventHandlers[405](req, res, resource);
      }
      // node server suppresses the response output
      // on a HEAD response so we don't need to mute it like this:
      /*

      var origResWrite = res.write;
      var origResEnd = res.end;

      res.write = function(){
        origResWrite.apply(res, ['']);
      };
      res.end = function(){
        console.log("in muted end()");
        origResEnd.apply(res, ['']);
      };
      */
      // re-distpach as a GET
      req.method = "GET";
      return dispatch(self, req, res, function(){});
    },
    'OPTIONS' : function(req, res, resource){
      var header = allowHeader(self, resource);
      res.setHeader('Allow', header);
      res.writeHead(200);
      res.end('Allow: ' + header);
    }
  };
  // we never tackle 501, because the node server just drops requests
  // with invalid methods
}
820678
def modify_stack(target_status, failure_message, &block)
      if wait?
        status = modify_stack_synchronously(&block)
        raise StackUpdateError, failure_message unless target_status === status
        status
      else
        modify_stack_asynchronously(&block)
      end
    end
1129067
function selfapi (/* parent, …overrides, child */) {
  // Parent API instance or root server app.
  var parent = null;

  // Child API overrides.
  var path = null;
  var title = null;
  var description = null;

  // Child API instance.
  var child = null;

  if ((this instanceof API) || isServerApp(this)) {
    // Called from parent, e.g. `var api = parent.api(…)`.
    parent = this;
  } else if ((arguments[0] instanceof API) || isServerApp(arguments[0])) {
    // First argument is parent, e.g. `var api = selfapi(parent…)`.
    parent = [].shift.call(arguments);
  }

  if (typeof arguments[0] === 'string' /* || instanceof RegExp */) {
    // Next argument is path, e.g. `api(…path…)`.
    path = [].shift.call(arguments);
    if (typeof arguments[0] === 'string') {
      // Next argument is title, e.g. `api(…path, title…)`.
      title = [].shift.call(arguments);
      if (typeof arguments[0] === 'string') {
        // Next argument is description, e.g. `api(…path, title, description…)`.
        description = [].shift.call(arguments);
      }
    }
  }

  if (arguments[arguments.length - 1] instanceof API) {
    // Last argument is child API instance, e.g. `selfapi(…api)`.
    child = [].pop.call(arguments);
  } else if (typeof arguments[arguments.length - 1] === 'object') {
    // Last argument is parameters object, e.g. `selfapi(…parameters)`.
    var parameters = [].pop.call(arguments);
    child = new API(parameters);
  } else {
    // No further useful argument.
    child = new API({});
  }

  // Apply any overrides.
  if (path) {
    child.path = path;
  }
  if (title) {
    child.title = title;
  }
  if (description) {
    child.description = description;
  }

  // Associate child and parent, triggering the `set parent` function if needed.
  if (parent) {
    child.parent = parent;
  }

  return child;
}
144982
function patchRoute(lookup) {
  // Save off the original method in scope of the prototype modifications.
  let originalRouteMethod = Ember.RouterDSL.prototype.route;

  // We need to do a few things before and after the original route function.
  Ember.RouterDSL.prototype.route = function(name, options, callback) {
    Ember.assert('You may not include a "." in your route name.', !~name.indexOf('.'));

    // Method signature identification from the original method.
    if (arguments.length === 2 && typeof options === 'function') {
      callback = options;
      options = {};
    }

    if (arguments.length === 1) {
      options = {};
    }

    // Save off a reference to the original arguments in a reachable scope.
    // This is so later calls to `alias` have something to find.
    if (!this.handlers) { this.handlers = {}; }
    this.handlers[name] = [ options, callback ];

    // For storing the root of the aliased route.
    if (!this.intercepting) { this.intercepting = []; }

    // So, we're "recursing" through a structure, but we can sneak in by wrapping the invoked function.
    if (this.intercepting.length) {

      // Make the callback modify the DSL generated for nested routes.
      // Necessary so they can register themselves.
      // Propogate the original interception information forward.
      var currentIntercepting = this.intercepting[this.intercepting.length - 1];
      let interceptingCallback = function() {
        this.intercepting = [currentIntercepting];
        callback.call(this);
      };

      // Figure out how many routes we created.
      let originalLength = [].concat.apply([], this.matches).length;
      originalRouteMethod.call(this, name, options, callback ? interceptingCallback : undefined);
      let newMatches = [].concat.apply([], this.matches);
      let newLength = newMatches.length;

      // Add each of them to the lookup.
      for (let i = originalLength; i < newLength; i += 3) {
        let intermediate = newMatches[i + 1].split('.');
        let qualifiedAliasRoute = intermediate.join('/');
        let qualifiedTargetRoute = qualifiedAliasRoute.replace(currentIntercepting.aliasRoute, currentIntercepting.aliasTarget);

        if (qualifiedAliasRoute !== qualifiedTargetRoute) {
          lookup[qualifiedAliasRoute] = qualifiedTargetRoute;
        } else {
          // For index routes we need to try again with the base intercepting object.
          let isIndex = intermediate.pop().indexOf('index') === 0;
          qualifiedTargetRoute = qualifiedAliasRoute.replace(this.intercepting[0].aliasRoute, this.intercepting[0].aliasTarget);
          if (isIndex && qualifiedAliasRoute !== qualifiedTargetRoute) {
            lookup[qualifiedAliasRoute] = qualifiedTargetRoute;
          }
        }
      }

    } else {
      originalRouteMethod.call(this, name, options, callback);
    }
  };
}