Repository URL to install this package:
|
Version:
0.7.0 ▾
|
// (c) Copyright 2023 Supertenant Ltd. - all rights reserved.
// See LICENSE file in project root for license terms.
"use strict";const shimmer=require("shimmer"),requireHook=require("../../../util/requireHook"),httpServer=require("../protocols/httpServer"),cls=require("../../cls");let active=!1;function instrumentRouter(Router){shimmer.wrap(Router.prototype,"routes",shimRoutes)}function shimRoutes(originalFunction){return function(){return instrumentedRoutes(this,originalFunction,arguments)}}function instrumentedRoutes(thisContext,originalRoutes,originalArgs){const dispatch=originalRoutes.apply(thisContext,originalArgs);function instrumentedDispatch(ctx,next){return active&&cls.isTracing()?dispatch.apply(this,arguments).then(resolvedValue=>{var matchedRouteLayers;return ctx.matched&&ctx.matched.length&&0<ctx.matched.length&&((matchedRouteLayers=ctx.matched.slice()).sort(byLeastSpecificLayer),annotateHttpEntrySpanWithPathTemplate(normalizeLayerPath(matchedRouteLayers[matchedRouteLayers.length-1].path))),resolvedValue}):dispatch.apply(this,arguments)}return instrumentedDispatch.router=dispatch.router,instrumentedDispatch}function byLeastSpecificLayer(a,b){var regexpA=a.path&&"object"==typeof a.path,regexpB=b.path&&"object"==typeof b.path;let pathA=normalizeLayerPath(a.path),pathB=normalizeLayerPath(b.path);a=pathA.endsWith("(.*)"),b=pathB.endsWith("(.*)");if(a&&b)return pathA.length-pathB.length;if(pathA=a?pathA.slice(0,-4):pathA,pathB=b?pathB.slice(0,-4):pathB,pathA!==pathB){if(pathA.startsWith(pathB))return 1;if(pathB.startsWith(pathA))return-1}return a?-1:b?1:regexpA&&!regexpB?-1:!regexpA&®expB?1:0}function normalizeLayerPath(p){return null==p?"":"object"==typeof p?p.toString():p}function annotateHttpEntrySpanWithPathTemplate(pathTemplate){var span=cls.getCurrentEntrySpan();span&&span.n===httpServer.spanName&&!span.pathTplFrozen&&(span.data.http.path_tpl=pathTemplate)}exports.activate=function(){active=!0},exports.deactivate=function(){active=!1},exports.init=function(){requireHook.onModuleLoad("koa-router",instrumentRouter)};