/*! * router * Copyright(c) 2013 Roman Shtylman * Copyright(c) 2014-2022 Douglas Christopher Wilson * MIT Licensed */ 'use strict' /** * Module dependencies. * @private */ const isPromise = require('is-promise') const pathRegexp = require('path-to-regexp') const debug = require('debug')('router:layer') const deprecate = require('depd')('router') const { matchedRoute } = require('./symbols') const { publishEnd, recordThrown, requestChannel, shouldTrace, traceAsyncEnd, wrapNext } = require('./tracing') /** * Module variables. * @private */ const TRAILING_SLASH_REGEXP = /\/+$/ const MATCHING_GROUP_REGEXP = /\((?:\?<(.*?)>)?(?!\?)/g /** * Expose `Layer`. */ module.exports = Layer function Layer (path, options, fn) { if (!(this instanceof Layer)) { return new Layer(path, options, fn) } debug('new %o', path) const opts = options || {} this.handle = fn this.name = fn.name || '' // flat unnests nested path arrays and snapshots the caller's array this.rawPath = Array.isArray(path) ? path.flat(Infinity) : path this.slash = path === '/' && opts.end === false function matcher (_path) { if (_path instanceof RegExp) { const keys = [] let name = 0 let m // eslint-disable-next-line no-cond-assign while (m = MATCHING_GROUP_REGEXP.exec(_path.source)) { keys.push({ name: m[1] || name++, offset: m.index }) } return function regexpMatcher (p) { const match = _path.exec(p) if (!match) { return false } const params = {} for (let i = 1; i < match.length; i++) { const key = keys[i - 1] const prop = key.name const val = decodeParam(match[i]) if (val !== undefined) { params[prop] = val } } return { params, path: match[0] } } } return pathRegexp.match((opts.strict ? _path : loosen(_path)), { sensitive: opts.sensitive, end: opts.end, trailing: !opts.strict, decode: decodeParam }) } this.matchers = Array.isArray(this.rawPath) ? this.rawPath.map(matcher) : [matcher(path)] } /** * Handle the error for the layer. * * @param {Error} error * @param {Request} req * @param {Response} res * @param {function} next * @api private */ Layer.prototype.handleError = function handleError (error, req, res, next) { const fn = this.handle if (fn.length !== 4) { // not a standard error handler return next(error) } if (!shouldTrace(requestChannel)) { try { // invoke function const ret = handlePromise(fn(error, req, res, next)) // wait for returned promise if (ret) { ret.then(noop, function (error) { next(error || new Error('Rejected promise')) }) } } catch (err) { next(err) } return } invokeWithTrace(function (wrappedNext) { return fn(error, req, res, wrappedNext) }, { req, res, incomingError: error, layer: this, handler: fn, route: req[matchedRoute], errorHandler: true }, next) } /** * Handle the request for the layer. * * @param {Request} req * @param {Response} res * @param {function} next * @api private */ Layer.prototype.handleRequest = function handleRequest (req, res, next) { const fn = this.handle if (fn.length > 3) { // not a standard request handler return next() } // Skip tracing for route dispatch wrappers (this.route is only set on the // internal layer that calls route.dispatch); the user handlers inside the // route are traced individually. Also skip when there are no subscribers, // to avoid allocating a context object on every request. if (this.route || !shouldTrace(requestChannel)) { try { // invoke function const ret = handlePromise(fn(req, res, next)) // wait for returned promise if (ret) { ret.then(noop, function (error) { next(error || new Error('Rejected promise')) }) } } catch (err) { next(err) } return } invokeWithTrace(function (wrappedNext) { return fn(req, res, wrappedNext) }, { req, res, layer: this, handler: fn, route: req[matchedRoute] }, next) } /** * Invoke a handler wrapped in the request TracingChannel. Only called when the * channel has subscribers, so ctx is always present. * @private */ function invokeWithTrace (exec, ctx, next) { const wrappedNext = wrapNext(ctx, next) let settled = false // runStores fires `start` and sets the async context. Synchronous layers // emit only start/end. All outcomes flow through wrappedNext to keep signal // filtering and dedup in one place. requestChannel.start.runStores(ctx, function () { let out try { const ret = exec(wrappedNext) out = handlePromise(ret) // Same as tracePromise, a promise only gets its result once it resolves if (!out) ctx.result = ret } catch (err) { // A sync throw is forwarded verbatim, so a falsy value keeps routing // exactly as the untraced path does. wrappedNext(err) recordThrown(ctx, err, true) publishEnd(ctx, false) return } publishEnd(ctx, Boolean(out)) if (!out) return try { out.then( function (value) { // Same as tracePromise, only the first outcome settles the trace if (settled) return settled = true ctx.result = value traceAsyncEnd(ctx) }, function (err) { // A rejected promise is an error even when the reason is falsy; // normalize it to the error the router forwards to next(). rejected(err || new Error('Rejected promise')) } ) } catch (err) { // Same as tracePromise, a `then` that throws is a rejection, forwarded // verbatim as the untraced path does rejected(err) } }) function rejected (err) { // Routing still gets every outcome, as the untraced path does wrappedNext(err) if (settled) return settled = true recordThrown(ctx, err, false) traceAsyncEnd(ctx) } } /** * Passed to then() instead of null, since some thenables call their callbacks * without checking, and the traced path always passes a function. * * @private */ function noop () {} /** * If the return value is a promise, validate it and return it. * @private */ function handlePromise (ret) { if (isPromise(ret)) { if (!(ret instanceof Promise)) { deprecate('handlers that are Promise-like are deprecated, use a native Promise instead') } return ret } } /** * Return the matched values without storing request state on the layer. * * @param {String} path * @return {Object|false} * @api private */ Layer.prototype.match = function match (path) { let match let i = 0 if (path != null) { // fast path non-ending match for / (any path matches) if (this.slash) { return { params: {}, path: '', keys: [], pattern: this.rawPath } } while (!match && i < this.matchers.length) { // match the path match = this.matchers[i](path) i++ } } if (!match) { return false } return { params: match.params, path: match.path, keys: Object.keys(match.params), pattern: Array.isArray(this.rawPath) ? this.rawPath[i - 1] : this.rawPath } } /** * Decode param value. * * @param {string} val * @return {string} * @private */ function decodeParam (val) { if (typeof val !== 'string' || val.length === 0 || val.indexOf('%') === -1) { return val } try { return decodeURIComponent(val) } catch (err) { if (err instanceof URIError) { err.message = 'Failed to decode param \'' + val + '\'' err.status = err.statusCode = 400 } throw err } } /** * Loosens the given path for path-to-regexp matching. */ function loosen (path) { if (path instanceof RegExp || path === '/') { return path } return Array.isArray(path) ? path.map(function (p) { return loosen(p) }) : String(path).replace(TRAILING_SLASH_REGEXP, '') }