apitally 0.11.4 → 0.12.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (81) hide show
  1. package/README.md +27 -14
  2. package/dist/common/client.cjs +130 -110
  3. package/dist/common/client.cjs.map +1 -1
  4. package/dist/common/client.d.cts +2 -0
  5. package/dist/common/client.d.ts +2 -0
  6. package/dist/common/client.js +125 -105
  7. package/dist/common/client.js.map +1 -1
  8. package/dist/common/consumerRegistry.cjs.map +1 -1
  9. package/dist/common/consumerRegistry.js.map +1 -1
  10. package/dist/common/logging.cjs.map +1 -1
  11. package/dist/common/logging.js.map +1 -1
  12. package/dist/common/packageVersions.cjs.map +1 -1
  13. package/dist/common/packageVersions.js.map +1 -1
  14. package/dist/common/paramValidation.cjs.map +1 -1
  15. package/dist/common/paramValidation.js.map +1 -1
  16. package/dist/common/requestCounter.cjs.map +1 -1
  17. package/dist/common/requestCounter.js.map +1 -1
  18. package/dist/common/requestLogger.cjs +63 -7
  19. package/dist/common/requestLogger.cjs.map +1 -1
  20. package/dist/common/requestLogger.d.cts +3 -1
  21. package/dist/common/requestLogger.d.ts +3 -1
  22. package/dist/common/requestLogger.js +63 -7
  23. package/dist/common/requestLogger.js.map +1 -1
  24. package/dist/common/sentry.cjs +55 -0
  25. package/dist/common/sentry.cjs.map +1 -0
  26. package/dist/common/sentry.d.cts +6 -0
  27. package/dist/common/sentry.d.ts +6 -0
  28. package/dist/common/sentry.js +22 -0
  29. package/dist/common/sentry.js.map +1 -0
  30. package/dist/common/serverErrorCounter.cjs +58 -45
  31. package/dist/common/serverErrorCounter.cjs.map +1 -1
  32. package/dist/common/serverErrorCounter.d.cts +3 -6
  33. package/dist/common/serverErrorCounter.d.ts +3 -6
  34. package/dist/common/serverErrorCounter.js +53 -45
  35. package/dist/common/serverErrorCounter.js.map +1 -1
  36. package/dist/common/tempGzipFile.cjs +2 -2
  37. package/dist/common/tempGzipFile.cjs.map +1 -1
  38. package/dist/common/tempGzipFile.js +2 -2
  39. package/dist/common/tempGzipFile.js.map +1 -1
  40. package/dist/common/types.cjs.map +1 -1
  41. package/dist/common/validationErrorCounter.cjs.map +1 -1
  42. package/dist/common/validationErrorCounter.js.map +1 -1
  43. package/dist/express/index.cjs +139 -112
  44. package/dist/express/index.cjs.map +1 -1
  45. package/dist/express/index.js +134 -107
  46. package/dist/express/index.js.map +1 -1
  47. package/dist/express/middleware.cjs +139 -112
  48. package/dist/express/middleware.cjs.map +1 -1
  49. package/dist/express/middleware.js +134 -107
  50. package/dist/express/middleware.js.map +1 -1
  51. package/dist/express/utils.cjs.map +1 -1
  52. package/dist/express/utils.js.map +1 -1
  53. package/dist/fastify/index.cjs +136 -113
  54. package/dist/fastify/index.cjs.map +1 -1
  55. package/dist/fastify/index.js +131 -108
  56. package/dist/fastify/index.js.map +1 -1
  57. package/dist/fastify/plugin.cjs +136 -113
  58. package/dist/fastify/plugin.cjs.map +1 -1
  59. package/dist/fastify/plugin.js +131 -108
  60. package/dist/fastify/plugin.js.map +1 -1
  61. package/dist/hono/index.cjs +137 -112
  62. package/dist/hono/index.cjs.map +1 -1
  63. package/dist/hono/index.js +132 -107
  64. package/dist/hono/index.js.map +1 -1
  65. package/dist/hono/middleware.cjs +137 -112
  66. package/dist/hono/middleware.cjs.map +1 -1
  67. package/dist/hono/middleware.js +132 -107
  68. package/dist/hono/middleware.js.map +1 -1
  69. package/dist/koa/index.cjs +137 -111
  70. package/dist/koa/index.cjs.map +1 -1
  71. package/dist/koa/index.js +132 -106
  72. package/dist/koa/index.js.map +1 -1
  73. package/dist/koa/middleware.cjs +137 -111
  74. package/dist/koa/middleware.cjs.map +1 -1
  75. package/dist/koa/middleware.js +132 -106
  76. package/dist/koa/middleware.js.map +1 -1
  77. package/dist/nestjs/index.cjs +139 -112
  78. package/dist/nestjs/index.cjs.map +1 -1
  79. package/dist/nestjs/index.js +134 -107
  80. package/dist/nestjs/index.js.map +1 -1
  81. package/package.json +1 -1
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/express/utils.js"],"sourcesContent":["// Adapted from https://github.com/AlbertoFdzM/express-list-endpoints/blob/305535d43008b46f34e18b01947762e039af6d2d/src/index.js\n// and also incorporated changes from https://github.com/AlbertoFdzM/express-list-endpoints/pull/96\n\n/**\n * @typedef {Object} Route\n * @property {Object} methods\n * @property {string | string[]} path\n * @property {any[]} stack\n *\n * @typedef {Object} Endpoint\n * @property {string} path Path name\n * @property {string[]} methods Methods handled\n * @property {string[]} middlewares Mounted middlewares\n */\n\nconst regExpToParseExpressPathRegExp =\n /^\\/\\^\\\\?\\/?(?:(:?[\\w\\\\.-]*(?:\\\\\\/:?[\\w\\\\.-]*)*)|(\\(\\?:\\\\?\\/?\\([^)]+\\)\\)))\\\\\\/.*/;\nconst regExpToReplaceExpressPathRegExpParams = /\\(\\?:\\\\?\\/?\\([^)]+\\)\\)/;\nconst regexpExpressParamRegexp = /\\(\\?:\\\\?\\\\?\\/?\\([^)]+\\)\\)/g;\nconst regexpExpressPathParamRegexp = /(:[^)]+)\\([^)]+\\)/g;\n\nconst EXPRESS_ROOT_PATH_REGEXP_VALUE = \"/^\\\\/?(?=\\\\/|$)/i\";\nconst STACK_ITEM_VALID_NAMES = [\"router\", \"bound dispatch\", \"mounted_app\"];\n\n/**\n * Returns all the verbs detected for the passed route\n * @param {Route} route\n */\nconst getRouteMethods = function (route) {\n let methods = Object.keys(route.methods);\n\n methods = methods.filter((method) => method !== \"_all\");\n methods = methods.map((method) => method.toUpperCase());\n\n return methods;\n};\n\n/**\n * Returns the names (or anonymous) of all the middlewares attached to the\n * passed route\n * @param {Route} route\n * @returns {string[]}\n */\nconst getRouteMiddlewares = function (route) {\n return route.stack.map((item) => {\n return item.handle.name || \"anonymous\";\n });\n};\n\n/**\n * Returns true if found regexp related with express params\n * @param {string} expressPathRegExp\n * @returns {boolean}\n */\nconst hasParams = function (expressPathRegExp) {\n return regexpExpressParamRegexp.test(expressPathRegExp);\n};\n\n/**\n * @param {Route} route Express route object to be parsed\n * @param {string} basePath The basePath the route is on\n * @return {Endpoint[]} Endpoints info\n */\nconst parseExpressRoute = function (route, basePath) {\n const paths = [];\n\n if (Array.isArray(route.path)) {\n paths.push(...route.path);\n } else {\n paths.push(route.path);\n }\n\n /** @type {Endpoint[]} */\n const endpoints = paths.map((path) => {\n const completePath =\n basePath && path === \"/\" ? basePath : `${basePath}${path}`;\n\n /** @type {Endpoint} */\n const endpoint = {\n path: completePath.replace(regexpExpressPathParamRegexp, \"$1\"),\n methods: getRouteMethods(route),\n middlewares: getRouteMiddlewares(route),\n };\n\n return endpoint;\n });\n\n return endpoints;\n};\n\n/**\n * @param {RegExp} expressPathRegExp\n * @param {any[]} params\n * @returns {string}\n */\nexport const parseExpressPath = function (expressPathRegExp, params) {\n let parsedRegExp = expressPathRegExp.toString();\n let expressPathRegExpExec = regExpToParseExpressPathRegExp.exec(parsedRegExp);\n let paramIndex = 0;\n\n while (hasParams(parsedRegExp)) {\n const paramName = params[paramIndex].name;\n const paramId = `:${paramName}`;\n\n parsedRegExp = parsedRegExp.replace(\n regExpToReplaceExpressPathRegExpParams,\n (str) => {\n // Express >= 4.20.0 uses a different RegExp for parameters: it\n // captures the slash as part of the parameter. We need to check\n // for this case and add the slash to the value that will replace\n // the parameter in the path.\n if (str.startsWith(\"(?:\\\\/\")) {\n return `\\\\/${paramId}`;\n }\n\n return paramId;\n },\n );\n\n paramIndex++;\n }\n\n if (parsedRegExp !== expressPathRegExp.toString()) {\n expressPathRegExpExec = regExpToParseExpressPathRegExp.exec(parsedRegExp);\n }\n\n const parsedPath = expressPathRegExpExec[1].replace(/\\\\\\//g, \"/\");\n\n return parsedPath;\n};\n\n/**\n * @param {import('express').Express | import('express').Router | any} app\n * @param {string} [basePath]\n * @param {Endpoint[]} [endpoints]\n * @returns {Endpoint[]}\n */\nconst parseEndpoints = function (app, basePath, endpoints) {\n const stack = app.stack || (app._router && app._router.stack);\n\n endpoints = endpoints || [];\n basePath = basePath || \"\";\n\n if (!stack) {\n if (endpoints.length) {\n endpoints = addEndpoints(endpoints, [\n {\n path: basePath,\n methods: [],\n middlewares: [],\n },\n ]);\n }\n } else {\n endpoints = parseStack(stack, basePath, endpoints);\n }\n\n return endpoints;\n};\n\n/**\n * Ensures the path of the new endpoints isn't yet in the array.\n * If the path is already in the array merges the endpoints with the existing\n * one, if not, it adds them to the array.\n *\n * @param {Endpoint[]} currentEndpoints Array of current endpoints\n * @param {Endpoint[]} endpointsToAdd New endpoints to be added to the array\n * @returns {Endpoint[]} Updated endpoints array\n */\nconst addEndpoints = function (currentEndpoints, endpointsToAdd) {\n endpointsToAdd.forEach((newEndpoint) => {\n const existingEndpoint = currentEndpoints.find(\n (endpoint) => endpoint.path === newEndpoint.path,\n );\n\n if (existingEndpoint !== undefined) {\n const newMethods = newEndpoint.methods.filter(\n (method) => !existingEndpoint.methods.includes(method),\n );\n\n existingEndpoint.methods = existingEndpoint.methods.concat(newMethods);\n } else {\n currentEndpoints.push(newEndpoint);\n }\n });\n\n return currentEndpoints;\n};\n\n/**\n * @param {any[]} stack\n * @param {string} basePath\n * @param {Endpoint[]} endpoints\n * @returns {Endpoint[]}\n */\nconst parseStack = function (stack, basePath, endpoints) {\n stack.forEach((stackItem) => {\n if (stackItem.route) {\n const newEndpoints = parseExpressRoute(stackItem.route, basePath);\n\n endpoints = addEndpoints(endpoints, newEndpoints);\n } else if (STACK_ITEM_VALID_NAMES.includes(stackItem.name)) {\n const isExpressPathRegexp = regExpToParseExpressPathRegExp.test(\n stackItem.regexp,\n );\n\n let newBasePath = basePath;\n\n if (isExpressPathRegexp) {\n const parsedPath = parseExpressPath(stackItem.regexp, stackItem.keys);\n\n newBasePath += `/${parsedPath}`;\n } else if (\n !stackItem.path &&\n stackItem.regexp &&\n stackItem.regexp.toString() !== EXPRESS_ROOT_PATH_REGEXP_VALUE\n ) {\n const regExpPath = ` RegExp(${stackItem.regexp}) `;\n\n newBasePath += `/${regExpPath}`;\n }\n\n endpoints = parseEndpoints(stackItem.handle, newBasePath, endpoints);\n }\n });\n\n return endpoints;\n};\n\nexport const getEndpoints = function (app, basePath) {\n const endpoints = parseEndpoints(app);\n return endpoints.flatMap((route) =>\n route.methods\n .filter((method) => ![\"HEAD\", \"OPTIONS\"].includes(method.toUpperCase()))\n .map((method) => ({\n method,\n path: (basePath + route.path).replace(/\\/\\//g, \"/\"),\n })),\n );\n};\n"],"mappings":";;;;AAeA,IAAMA,iCACJ;AACF,IAAMC,yCAAyC;AAC/C,IAAMC,2BAA2B;AACjC,IAAMC,+BAA+B;AAErC,IAAMC,iCAAiC;AACvC,IAAMC,yBAAyB;EAAC;EAAU;EAAkB;;AAM5D,IAAMC,kBAAkB,gCAAUC,OAAK;AACrC,MAAIC,UAAUC,OAAOC,KAAKH,MAAMC,OAAO;AAEvCA,YAAUA,QAAQG,OAAO,CAACC,WAAWA,WAAW,MAAA;AAChDJ,YAAUA,QAAQK,IAAI,CAACD,WAAWA,OAAOE,YAAW,CAAA;AAEpD,SAAON;AACT,GAPwB;AAexB,IAAMO,sBAAsB,gCAAUR,OAAK;AACzC,SAAOA,MAAMS,MAAMH,IAAI,CAACI,SAAAA;AACtB,WAAOA,KAAKC,OAAOC,QAAQ;EAC7B,CAAA;AACF,GAJ4B;AAW5B,IAAMC,YAAY,gCAAUC,mBAAiB;AAC3C,SAAOnB,yBAAyBoB,KAAKD,iBAAAA;AACvC,GAFkB;AASlB,IAAME,oBAAoB,gCAAUhB,OAAOiB,UAAQ;AACjD,QAAMC,QAAQ,CAAA;AAEd,MAAIC,MAAMC,QAAQpB,MAAMqB,IAAI,GAAG;AAC7BH,UAAMI,KAAI,GAAItB,MAAMqB,IAAI;EAC1B,OAAO;AACLH,UAAMI,KAAKtB,MAAMqB,IAAI;EACvB;AAGA,QAAME,YAAYL,MAAMZ,IAAI,CAACe,SAAAA;AAC3B,UAAMG,eACJP,YAAYI,SAAS,MAAMJ,WAAW,GAAGA,QAAAA,GAAWI,IAAAA;AAGtD,UAAMI,WAA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B,eAAeC,GAAAA;AACjC,SAAOlB,UAAUwC,QAAQ,CAAC/D,UACxBA,MAAMC,QACHG,OAAO,CAACC,WAAW,CAAC;IAAC;IAAQ;IAAWiD,SAASjD,OAAOE,YAAW,CAAA,CAAA,EACnED,IAAI,CAACD,YAAY;IAChBA;IACAgB,OAAOJ,WAAWjB,MAAMqB,MAAMK,QAAQ,SAAS,GAAA;EACjD,EAAA,CAAA;AAEN,GAV4B;","names":["regExpToParseExpressPathRegExp","regExpToReplaceExpressPathRegExpParams","regexpExpressParamRegexp","regexpExpressPathParamRegexp","EXPRESS_ROOT_PATH_REGEXP_VALUE","STACK_ITEM_VALID_NAMES","getRouteMethods","route","methods","Object","keys","filter","method","map","toUpperCase","getRouteMiddlewares","stack","item","handle","name","hasParams","expressPathRegExp","test","parseExpressRoute","basePath","paths","Array","isArray","path","push","endpoints","completePath","endpoint","replace","middlewares","parseExpressPath","params","parsedRegExp","toString","expressPathRegExpExec","exec","paramIndex","paramName","paramId","str","startsWith","parsedPath","parseEndpoints","app","_router","length","addEndpoints","parseStack","currentEndpoints","endpointsToAdd","forEach","newEndpoint","existingEndpoint","find","undefined","newMethods","includes","concat","stackItem","newEndpoints","isExpressPathRegexp","regexp","newBasePath","regExpPath","getEndpoints","flatMap"]}
1
+ {"version":3,"sources":["utils.js"],"sourcesContent":["// Adapted from https://github.com/AlbertoFdzM/express-list-endpoints/blob/305535d43008b46f34e18b01947762e039af6d2d/src/index.js\n// and also incorporated changes from https://github.com/AlbertoFdzM/express-list-endpoints/pull/96\n\n/**\n * @typedef {Object} Route\n * @property {Object} methods\n * @property {string | string[]} path\n * @property {any[]} stack\n *\n * @typedef {Object} Endpoint\n * @property {string} path Path name\n * @property {string[]} methods Methods handled\n * @property {string[]} middlewares Mounted middlewares\n */\n\nconst regExpToParseExpressPathRegExp =\n /^\\/\\^\\\\?\\/?(?:(:?[\\w\\\\.-]*(?:\\\\\\/:?[\\w\\\\.-]*)*)|(\\(\\?:\\\\?\\/?\\([^)]+\\)\\)))\\\\\\/.*/;\nconst regExpToReplaceExpressPathRegExpParams = /\\(\\?:\\\\?\\/?\\([^)]+\\)\\)/;\nconst regexpExpressParamRegexp = /\\(\\?:\\\\?\\\\?\\/?\\([^)]+\\)\\)/g;\nconst regexpExpressPathParamRegexp = /(:[^)]+)\\([^)]+\\)/g;\n\nconst EXPRESS_ROOT_PATH_REGEXP_VALUE = \"/^\\\\/?(?=\\\\/|$)/i\";\nconst STACK_ITEM_VALID_NAMES = [\"router\", \"bound dispatch\", \"mounted_app\"];\n\n/**\n * Returns all the verbs detected for the passed route\n * @param {Route} route\n */\nconst getRouteMethods = function (route) {\n let methods = Object.keys(route.methods);\n\n methods = methods.filter((method) => method !== \"_all\");\n methods = methods.map((method) => method.toUpperCase());\n\n return methods;\n};\n\n/**\n * Returns the names (or anonymous) of all the middlewares attached to the\n * passed route\n * @param {Route} route\n * @returns {string[]}\n */\nconst getRouteMiddlewares = function (route) {\n return route.stack.map((item) => {\n return item.handle.name || \"anonymous\";\n });\n};\n\n/**\n * Returns true if found regexp related with express params\n * @param {string} expressPathRegExp\n * @returns {boolean}\n */\nconst hasParams = function (expressPathRegExp) {\n return regexpExpressParamRegexp.test(expressPathRegExp);\n};\n\n/**\n * @param {Route} route Express route object to be parsed\n * @param {string} basePath The basePath the route is on\n * @return {Endpoint[]} Endpoints info\n */\nconst parseExpressRoute = function (route, basePath) {\n const paths = [];\n\n if (Array.isArray(route.path)) {\n paths.push(...route.path);\n } else {\n paths.push(route.path);\n }\n\n /** @type {Endpoint[]} */\n const endpoints = paths.map((path) => {\n const completePath =\n basePath && path === \"/\" ? basePath : `${basePath}${path}`;\n\n /** @type {Endpoint} */\n const endpoint = {\n path: completePath.replace(regexpExpressPathParamRegexp, \"$1\"),\n methods: getRouteMethods(route),\n middlewares: getRouteMiddlewares(route),\n };\n\n return endpoint;\n });\n\n return endpoints;\n};\n\n/**\n * @param {RegExp} expressPathRegExp\n * @param {any[]} params\n * @returns {string}\n */\nexport const parseExpressPath = function (expressPathRegExp, params) {\n let parsedRegExp = expressPathRegExp.toString();\n let expressPathRegExpExec = regExpToParseExpressPathRegExp.exec(parsedRegExp);\n let paramIndex = 0;\n\n while (hasParams(parsedRegExp)) {\n const paramName = params[paramIndex].name;\n const paramId = `:${paramName}`;\n\n parsedRegExp = parsedRegExp.replace(\n regExpToReplaceExpressPathRegExpParams,\n (str) => {\n // Express >= 4.20.0 uses a different RegExp for parameters: it\n // captures the slash as part of the parameter. We need to check\n // for this case and add the slash to the value that will replace\n // the parameter in the path.\n if (str.startsWith(\"(?:\\\\/\")) {\n return `\\\\/${paramId}`;\n }\n\n return paramId;\n },\n );\n\n paramIndex++;\n }\n\n if (parsedRegExp !== expressPathRegExp.toString()) {\n expressPathRegExpExec = regExpToParseExpressPathRegExp.exec(parsedRegExp);\n }\n\n const parsedPath = expressPathRegExpExec[1].replace(/\\\\\\//g, \"/\");\n\n return parsedPath;\n};\n\n/**\n * @param {import('express').Express | import('express').Router | any} app\n * @param {string} [basePath]\n * @param {Endpoint[]} [endpoints]\n * @returns {Endpoint[]}\n */\nconst parseEndpoints = function (app, basePath, endpoints) {\n const stack = app.stack || (app._router && app._router.stack);\n\n endpoints = endpoints || [];\n basePath = basePath || \"\";\n\n if (!stack) {\n if (endpoints.length) {\n endpoints = addEndpoints(endpoints, [\n {\n path: basePath,\n methods: [],\n middlewares: [],\n },\n ]);\n }\n } else {\n endpoints = parseStack(stack, basePath, endpoints);\n }\n\n return endpoints;\n};\n\n/**\n * Ensures the path of the new endpoints isn't yet in the array.\n * If the path is already in the array merges the endpoints with the existing\n * one, if not, it adds them to the array.\n *\n * @param {Endpoint[]} currentEndpoints Array of current endpoints\n * @param {Endpoint[]} endpointsToAdd New endpoints to be added to the array\n * @returns {Endpoint[]} Updated endpoints array\n */\nconst addEndpoints = function (currentEndpoints, endpointsToAdd) {\n endpointsToAdd.forEach((newEndpoint) => {\n const existingEndpoint = currentEndpoints.find(\n (endpoint) => endpoint.path === newEndpoint.path,\n );\n\n if (existingEndpoint !== undefined) {\n const newMethods = newEndpoint.methods.filter(\n (method) => !existingEndpoint.methods.includes(method),\n );\n\n existingEndpoint.methods = existingEndpoint.methods.concat(newMethods);\n } else {\n currentEndpoints.push(newEndpoint);\n }\n });\n\n return currentEndpoints;\n};\n\n/**\n * @param {any[]} stack\n * @param {string} basePath\n * @param {Endpoint[]} endpoints\n * @returns {Endpoint[]}\n */\nconst parseStack = function (stack, basePath, endpoints) {\n stack.forEach((stackItem) => {\n if (stackItem.route) {\n const newEndpoints = parseExpressRoute(stackItem.route, basePath);\n\n endpoints = addEndpoints(endpoints, newEndpoints);\n } else if (STACK_ITEM_VALID_NAMES.includes(stackItem.name)) {\n const isExpressPathRegexp = regExpToParseExpressPathRegExp.test(\n stackItem.regexp,\n );\n\n let newBasePath = basePath;\n\n if (isExpressPathRegexp) {\n const parsedPath = parseExpressPath(stackItem.regexp, stackItem.keys);\n\n newBasePath += `/${parsedPath}`;\n } else if (\n !stackItem.path &&\n stackItem.regexp &&\n stackItem.regexp.toString() !== EXPRESS_ROOT_PATH_REGEXP_VALUE\n ) {\n const regExpPath = ` RegExp(${stackItem.regexp}) `;\n\n newBasePath += `/${regExpPath}`;\n }\n\n endpoints = parseEndpoints(stackItem.handle, newBasePath, endpoints);\n }\n });\n\n return endpoints;\n};\n\nexport const getEndpoints = function (app, basePath) {\n const endpoints = parseEndpoints(app);\n return endpoints.flatMap((route) =>\n route.methods\n .filter((method) => ![\"HEAD\", \"OPTIONS\"].includes(method.toUpperCase()))\n .map((method) => ({\n method,\n path: (basePath + route.path).replace(/\\/\\//g, \"/\"),\n })),\n );\n};\n"],"mappings":";;;;AAeA,IAAMA,iCACJ;AACF,IAAMC,yCAAyC;AAC/C,IAAMC,2BAA2B;AACjC,IAAMC,+BAA+B;AAErC,IAAMC,iCAAiC;AACvC,IAAMC,yBAAyB;EAAC;EAAU;EAAkB;;AAM5D,IAAMC,kBAAkB,gCAAUC,OAAK;AACrC,MAA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,aAAa,gCAAUpC,OAAOQ,UAAUM,WAAS;AACrDd,QAAMuC,QAAQ,CAACQ,cAAAA;AACb,QAAIA,UAAUxD,OAAO;AACnB,YAAMyD,eAAezC,kBAAkBwC,UAAUxD,OAAOiB,QAAAA;AAExDM,kBAAYqB,aAAarB,WAAWkC,YAAAA;IACtC,WAAW3D,uBAAuBwD,SAASE,UAAU5C,IAAI,GAAG;AAC1D,YAAM8C,sBAAsBjE,+BAA+BsB,KACzDyC,UAAUG,MAAM;AAGlB,UAAIC,cAAc3C;AAElB,UAAIyC,qBAAqB;AACvB,cAAMnB,aAAaX,iBAAiB4B,UAAUG,QAAQH,UAAUrD,IAAI;AAEpEyD,uBAAe,IAAIrB,UAAAA;MACrB,WACE,CAACiB,UAAUnC,QACXmC,UAAUG,UACVH,UAAUG,OAAO5B,SAAQ,MAAOlC,gCAChC;AACA,cAAMgE,aAAa,WAAWL,UAAUG,MAAM;AAE9CC,uBAAe,IAAIC,UAAAA;MACrB;AAEAtC,kBAAYiB,eAAegB,UAAU7C,QAAQiD,aAAarC,SAAAA;IAC5D;EACF,CAAA;AAEA,SAAOA;AACT,GAhCmB;AAkCZ,IAAMuC,eAAe,gCAAUrB,KAAKxB,UAAQ;AACjD,QAAMM,YAAYiB,eAAeC,GAAAA;AACjC,SAAOlB,UAAUwC,QAAQ,CAAC/D,UACxBA,MAAMC,QACHG,OAAO,CAACC,WAAW,CAAC;IAAC;IAAQ;IAAWiD,SAASjD,OAAOE,YAAW,CAAA,CAAA,EACnED,IAAI,CAACD,YAAY;IAChBA;IACAgB,OAAOJ,WAAWjB,MAAMqB,MAAMK,QAAQ,SAAS,GAAA;EACjD,EAAA,CAAA;AAEN,GAV4B;","names":["regExpToParseExpressPathRegExp","regExpToReplaceExpressPathRegExpParams","regexpExpressParamRegexp","regexpExpressPathParamRegexp","EXPRESS_ROOT_PATH_REGEXP_VALUE","STACK_ITEM_VALID_NAMES","getRouteMethods","route","methods","Object","keys","filter","method","map","toUpperCase","getRouteMiddlewares","stack","item","handle","name","hasParams","expressPathRegExp","test","parseExpressRoute","basePath","paths","Array","isArray","path","push","endpoints","completePath","endpoint","replace","middlewares","parseExpressPath","params","parsedRegExp","toString","expressPathRegExpExec","exec","paramIndex","paramName","paramId","str","startsWith","parsedPath","parseEndpoints","app","_router","length","addEndpoints","parseStack","currentEndpoints","endpointsToAdd","forEach","newEndpoint","existingEndpoint","find","undefined","newMethods","includes","concat","stackItem","newEndpoints","isExpressPathRegexp","regexp","newBasePath","regExpPath","getEndpoints","flatMap"]}
@@ -213,14 +213,116 @@ var RequestCounter = _RequestCounter;
213
213
  // src/common/requestLogger.ts
214
214
  var import_async_lock = __toESM(require("async-lock"), 1);
215
215
  var import_buffer2 = require("buffer");
216
- var import_crypto2 = require("crypto");
216
+ var import_crypto3 = require("crypto");
217
217
  var import_fs2 = require("fs");
218
218
  var import_os2 = require("os");
219
219
  var import_path2 = require("path");
220
220
 
221
+ // src/common/sentry.ts
222
+ var sentry;
223
+ (async () => {
224
+ try {
225
+ sentry = await import("@sentry/node");
226
+ } catch (e) {
227
+ }
228
+ })();
229
+ function getSentryEventId() {
230
+ if (sentry && sentry.lastEventId) {
231
+ return sentry.lastEventId();
232
+ }
233
+ return void 0;
234
+ }
235
+ __name(getSentryEventId, "getSentryEventId");
236
+
237
+ // src/common/serverErrorCounter.ts
238
+ var import_crypto = require("crypto");
239
+ var MAX_MSG_LENGTH = 2048;
240
+ var MAX_STACKTRACE_LENGTH = 65536;
241
+ var _ServerErrorCounter = class _ServerErrorCounter {
242
+ errorCounts;
243
+ errorDetails;
244
+ sentryEventIds;
245
+ constructor() {
246
+ this.errorCounts = /* @__PURE__ */ new Map();
247
+ this.errorDetails = /* @__PURE__ */ new Map();
248
+ this.sentryEventIds = /* @__PURE__ */ new Map();
249
+ }
250
+ addServerError(serverError) {
251
+ const key = this.getKey(serverError);
252
+ if (!this.errorDetails.has(key)) {
253
+ this.errorDetails.set(key, serverError);
254
+ }
255
+ this.errorCounts.set(key, (this.errorCounts.get(key) || 0) + 1);
256
+ const sentryEventId = getSentryEventId();
257
+ if (sentryEventId) {
258
+ this.sentryEventIds.set(key, sentryEventId);
259
+ }
260
+ }
261
+ getAndResetServerErrors() {
262
+ const data = [];
263
+ this.errorCounts.forEach((count, key) => {
264
+ const serverError = this.errorDetails.get(key);
265
+ if (serverError) {
266
+ data.push({
267
+ consumer: serverError.consumer || null,
268
+ method: serverError.method,
269
+ path: serverError.path,
270
+ type: serverError.type,
271
+ msg: truncateExceptionMessage(serverError.msg),
272
+ traceback: truncateExceptionStackTrace(serverError.traceback),
273
+ sentry_event_id: this.sentryEventIds.get(key) || null,
274
+ error_count: count
275
+ });
276
+ }
277
+ });
278
+ this.errorCounts.clear();
279
+ this.errorDetails.clear();
280
+ return data;
281
+ }
282
+ getKey(serverError) {
283
+ const hashInput = [
284
+ serverError.consumer || "",
285
+ serverError.method.toUpperCase(),
286
+ serverError.path,
287
+ serverError.type,
288
+ serverError.msg.trim(),
289
+ serverError.traceback.trim()
290
+ ].join("|");
291
+ return (0, import_crypto.createHash)("md5").update(hashInput).digest("hex");
292
+ }
293
+ };
294
+ __name(_ServerErrorCounter, "ServerErrorCounter");
295
+ var ServerErrorCounter = _ServerErrorCounter;
296
+ function truncateExceptionMessage(msg) {
297
+ if (msg.length <= MAX_MSG_LENGTH) {
298
+ return msg;
299
+ }
300
+ const suffix = "... (truncated)";
301
+ const cutoff = MAX_MSG_LENGTH - suffix.length;
302
+ return msg.substring(0, cutoff) + suffix;
303
+ }
304
+ __name(truncateExceptionMessage, "truncateExceptionMessage");
305
+ function truncateExceptionStackTrace(stack) {
306
+ const suffix = "... (truncated) ...";
307
+ const cutoff = MAX_STACKTRACE_LENGTH - suffix.length;
308
+ const lines = stack.trim().split("\n");
309
+ const truncatedLines = [];
310
+ let length = 0;
311
+ for (const line of lines) {
312
+ if (length + line.length + 1 > cutoff) {
313
+ truncatedLines.push(suffix);
314
+ break;
315
+ }
316
+ truncatedLines.push(line);
317
+ length += line.length + 1;
318
+ }
319
+ return truncatedLines.join("\n");
320
+ }
321
+ __name(truncateExceptionStackTrace, "truncateExceptionStackTrace");
322
+
221
323
  // src/common/tempGzipFile.ts
222
324
  var import_buffer = require("buffer");
223
- var import_crypto = require("crypto");
325
+ var import_crypto2 = require("crypto");
224
326
  var import_fs = require("fs");
225
327
  var import_os = require("os");
226
328
  var import_path = require("path");
@@ -233,16 +335,16 @@ var _TempGzipFile = class _TempGzipFile {
233
335
  readyPromise;
234
336
  closedPromise;
235
337
  constructor() {
236
- this.uuid = (0, import_crypto.randomUUID)();
338
+ this.uuid = (0, import_crypto2.randomUUID)();
237
339
  this.filePath = (0, import_path.join)((0, import_os.tmpdir)(), `apitally-${this.uuid}.gz`);
238
340
  this.writeStream = (0, import_fs.createWriteStream)(this.filePath);
239
341
  this.readyPromise = new Promise((resolve, reject) => {
240
342
  this.writeStream.once("ready", resolve);
241
343
  this.writeStream.once("error", reject);
242
344
  });
243
- this.closedPromise = new Promise((resolve) => {
345
+ this.closedPromise = new Promise((resolve, reject) => {
244
346
  this.writeStream.once("close", resolve);
245
- this.writeStream.once("error", resolve);
347
+ this.writeStream.once("error", reject);
246
348
  });
247
349
  this.gzip = (0, import_zlib.createGzip)();
248
350
  this.gzip.pipe(this.writeStream);
@@ -340,6 +442,7 @@ var DEFAULT_CONFIG = {
340
442
  logRequestBody: false,
341
443
  logResponseHeaders: true,
342
444
  logResponseBody: false,
445
+ logException: true,
343
446
  maskQueryParams: [],
344
447
  maskHeaders: [],
345
448
  excludePaths: []
@@ -392,7 +495,10 @@ var _RequestLogger = class _RequestLogger {
392
495
  hasSupportedContentType(headers) {
393
496
  var _a2;
394
497
  const contentType = (_a2 = headers.find(([k]) => k.toLowerCase() === "content-type")) == null ? void 0 : _a2[1];
395
- return contentType !== void 0 && ALLOWED_CONTENT_TYPES.some((t) => contentType.startsWith(t));
498
+ return this.isSupportedContentType(contentType);
499
+ }
500
+ isSupportedContentType(contentType) {
501
+ return typeof contentType === "string" && ALLOWED_CONTENT_TYPES.some((t) => contentType.startsWith(t));
396
502
  }
397
503
  maskQueryParams(search) {
398
504
  const params = new URLSearchParams(search);
@@ -409,7 +515,7 @@ var _RequestLogger = class _RequestLogger {
409
515
  this.shouldMaskHeader(k) ? MASKED : v
410
516
  ]);
411
517
  }
412
- logRequest(request, response) {
518
+ logRequest(request, response, error) {
413
519
  var _a2, _b, _c;
414
520
  if (!this.enabled || this.suspendUntil !== null) return;
415
521
  const url = new URL(request.url);
@@ -420,8 +526,6 @@ var _RequestLogger = class _RequestLogger {
420
526
  }
421
527
  url.search = this.config.logQueryParams ? this.maskQueryParams(url.search) : "";
422
528
  request.url = url.toString();
423
- request.headers = this.config.logRequestHeaders ? this.maskHeaders(request.headers) : [];
424
- response.headers = this.config.logResponseHeaders ? this.maskHeaders(response.headers) : [];
425
529
  if (!this.config.logRequestBody || !this.hasSupportedContentType(request.headers)) {
426
530
  request.body = void 0;
427
531
  } else if (request.body) {
@@ -454,10 +558,18 @@ var _RequestLogger = class _RequestLogger {
454
558
  }
455
559
  }
456
560
  }
561
+ request.headers = this.config.logRequestHeaders ? this.maskHeaders(request.headers) : [];
562
+ response.headers = this.config.logResponseHeaders ? this.maskHeaders(response.headers) : [];
457
563
  const item = {
458
- uuid: (0, import_crypto2.randomUUID)(),
564
+ uuid: (0, import_crypto3.randomUUID)(),
459
565
  request: skipEmptyValues(request),
460
- response: skipEmptyValues(response)
566
+ response: skipEmptyValues(response),
567
+ exception: error && this.config.logException ? {
568
+ type: error.name,
569
+ message: truncateExceptionMessage(error.message),
570
+ stacktrace: truncateExceptionStackTrace(error.stack || ""),
571
+ sentryEventId: getSentryEventId()
572
+ } : null
461
573
  };
462
574
  [
463
575
  item.request.body,
@@ -609,7 +721,7 @@ function skipEmptyValues(data) {
609
721
  __name(skipEmptyValues, "skipEmptyValues");
610
722
  function checkWritableFs() {
611
723
  try {
612
- const testPath = (0, import_path2.join)((0, import_os2.tmpdir)(), `apitally-${(0, import_crypto2.randomUUID)()}`);
724
+ const testPath = (0, import_path2.join)((0, import_os2.tmpdir)(), `apitally-${(0, import_crypto3.randomUUID)()}`);
613
725
  (0, import_fs2.writeFileSync)(testPath, "test");
614
726
  (0, import_fs2.unlinkSync)(testPath);
615
727
  return true;
@@ -619,104 +731,6 @@ function checkWritableFs() {
619
731
  }
620
732
  __name(checkWritableFs, "checkWritableFs");
621
733
 
622
- // src/common/serverErrorCounter.ts
623
- var import_crypto3 = require("crypto");
624
- var MAX_MSG_LENGTH = 2048;
625
- var MAX_STACKTRACE_LENGTH = 65536;
626
- var _ServerErrorCounter = class _ServerErrorCounter {
627
- errorCounts;
628
- errorDetails;
629
- sentryEventIds;
630
- sentry;
631
- constructor() {
632
- this.errorCounts = /* @__PURE__ */ new Map();
633
- this.errorDetails = /* @__PURE__ */ new Map();
634
- this.sentryEventIds = /* @__PURE__ */ new Map();
635
- this.tryImportSentry();
636
- }
637
- addServerError(serverError) {
638
- const key = this.getKey(serverError);
639
- if (!this.errorDetails.has(key)) {
640
- this.errorDetails.set(key, serverError);
641
- }
642
- this.errorCounts.set(key, (this.errorCounts.get(key) || 0) + 1);
643
- this.captureSentryEventId(key);
644
- }
645
- getAndResetServerErrors() {
646
- const data = [];
647
- this.errorCounts.forEach((count, key) => {
648
- const serverError = this.errorDetails.get(key);
649
- if (serverError) {
650
- data.push({
651
- consumer: serverError.consumer || null,
652
- method: serverError.method,
653
- path: serverError.path,
654
- type: serverError.type,
655
- msg: this.getTruncatedMessage(serverError.msg),
656
- traceback: this.getTruncatedStack(serverError.traceback),
657
- sentry_event_id: this.sentryEventIds.get(key) || null,
658
- error_count: count
659
- });
660
- }
661
- });
662
- this.errorCounts.clear();
663
- this.errorDetails.clear();
664
- return data;
665
- }
666
- getKey(serverError) {
667
- const hashInput = [
668
- serverError.consumer || "",
669
- serverError.method.toUpperCase(),
670
- serverError.path,
671
- serverError.type,
672
- serverError.msg.trim(),
673
- serverError.traceback.trim()
674
- ].join("|");
675
- return (0, import_crypto3.createHash)("md5").update(hashInput).digest("hex");
676
- }
677
- getTruncatedMessage(msg) {
678
- msg = msg.trim();
679
- if (msg.length <= MAX_MSG_LENGTH) {
680
- return msg;
681
- }
682
- const suffix = "... (truncated)";
683
- const cutoff = MAX_MSG_LENGTH - suffix.length;
684
- return msg.substring(0, cutoff) + suffix;
685
- }
686
- getTruncatedStack(stack) {
687
- const suffix = "... (truncated) ...";
688
- const cutoff = MAX_STACKTRACE_LENGTH - suffix.length;
689
- const lines = stack.trim().split("\n");
690
- const truncatedLines = [];
691
- let length = 0;
692
- for (const line of lines) {
693
- if (length + line.length + 1 > cutoff) {
694
- truncatedLines.push(suffix);
695
- break;
696
- }
697
- truncatedLines.push(line);
698
- length += line.length + 1;
699
- }
700
- return truncatedLines.join("\n");
701
- }
702
- captureSentryEventId(serverErrorKey) {
703
- if (this.sentry && this.sentry.lastEventId) {
704
- const eventId = this.sentry.lastEventId();
705
- if (eventId) {
706
- this.sentryEventIds.set(serverErrorKey, eventId);
707
- }
708
- }
709
- }
710
- async tryImportSentry() {
711
- try {
712
- this.sentry = await import("@sentry/node");
713
- } catch (e) {
714
- }
715
- }
716
- };
717
- __name(_ServerErrorCounter, "ServerErrorCounter");
718
- var ServerErrorCounter = _ServerErrorCounter;
719
-
720
734
  // src/common/validationErrorCounter.ts
721
735
  var import_crypto4 = require("crypto");
722
736
  var _ValidationErrorCounter = class _ValidationErrorCounter {
@@ -790,6 +804,7 @@ var _ApitallyClient = class _ApitallyClient {
790
804
  syncIntervalId;
791
805
  startupData;
792
806
  startupDataSent = false;
807
+ enabled = true;
793
808
  requestCounter;
794
809
  requestLogger;
795
810
  validationErrorCounter;
@@ -826,12 +841,16 @@ var _ApitallyClient = class _ApitallyClient {
826
841
  }
827
842
  return _ApitallyClient.instance;
828
843
  }
844
+ isEnabled() {
845
+ return this.enabled;
846
+ }
829
847
  static async shutdown() {
830
848
  if (_ApitallyClient.instance) {
831
849
  await _ApitallyClient.instance.handleShutdown();
832
850
  }
833
851
  }
834
852
  async handleShutdown() {
853
+ this.enabled = false;
835
854
  this.stopSync();
836
855
  await this.sendSyncData();
837
856
  await this.sendLogData();
@@ -1015,6 +1034,7 @@ var _ApitallyClient = class _ApitallyClient {
1015
1034
  if (error instanceof HTTPError) {
1016
1035
  if (error.response.status === 404) {
1017
1036
  this.logger.error(`Invalid Apitally client ID: '${this.clientId}'`);
1037
+ this.enabled = false;
1018
1038
  this.stopSync();
1019
1039
  return true;
1020
1040
  }
@@ -1082,7 +1102,10 @@ var apitallyPlugin = /* @__PURE__ */ __name(async (fastify, config) => {
1082
1102
  await client.handleShutdown();
1083
1103
  });
1084
1104
  fastify.addHook("onSend", (request, reply, payload, done) => {
1085
- reply.payload = payload;
1105
+ const contentType = reply.getHeader("content-type");
1106
+ if (client.requestLogger.isSupportedContentType(contentType)) {
1107
+ reply.payload = payload;
1108
+ }
1086
1109
  done();
1087
1110
  });
1088
1111
  fastify.addHook("onError", (request, reply, error, done) => {
@@ -1093,7 +1116,7 @@ var apitallyPlugin = /* @__PURE__ */ __name(async (fastify, config) => {
1093
1116
  });
1094
1117
  fastify.addHook("onResponse", (request, reply, done) => {
1095
1118
  var _a2;
1096
- if (request.method.toUpperCase() !== "OPTIONS") {
1119
+ if (client.isEnabled() && request.method.toUpperCase() !== "OPTIONS") {
1097
1120
  const consumer = getConsumer(request);
1098
1121
  const path = "routeOptions" in request ? request.routeOptions.url : request.routerPath;
1099
1122
  const requestSize = request.headers["content-length"];
@@ -1155,7 +1178,7 @@ var apitallyPlugin = /* @__PURE__ */ __name(async (fastify, config) => {
1155
1178
  headers: convertHeaders(reply.getHeaders()),
1156
1179
  size: Number(responseSize),
1157
1180
  body: convertBody(reply.payload, (_a2 = reply.getHeader("content-type")) == null ? void 0 : _a2.toString())
1158
- });
1181
+ }, reply.serverError);
1159
1182
  }
1160
1183
  }
1161
1184
  done();