apitally 0.24.0 → 0.25.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.
- package/dist/adonisjs/index.cjs +3 -0
- package/dist/adonisjs/index.cjs.map +1 -1
- package/dist/adonisjs/index.d.cts +2 -0
- package/dist/adonisjs/index.d.ts +2 -0
- package/dist/adonisjs/index.js +2 -0
- package/dist/adonisjs/index.js.map +1 -1
- package/dist/adonisjs/middleware.cjs +6 -2
- package/dist/adonisjs/middleware.cjs.map +1 -1
- package/dist/adonisjs/middleware.d.cts +2 -0
- package/dist/adonisjs/middleware.d.ts +2 -0
- package/dist/adonisjs/middleware.js +6 -2
- package/dist/adonisjs/middleware.js.map +1 -1
- package/dist/adonisjs/provider.d.cts +2 -0
- package/dist/adonisjs/provider.d.ts +2 -0
- package/dist/adonisjs/stubs/config/apitally.stub +1 -0
- package/dist/common/client.cjs +4 -0
- package/dist/common/client.cjs.map +1 -1
- package/dist/common/client.d.cts +3 -0
- package/dist/common/client.d.ts +3 -0
- package/dist/common/client.js +4 -0
- package/dist/common/client.js.map +1 -1
- package/dist/common/consumerRegistry.d.cts +2 -0
- package/dist/common/consumerRegistry.d.ts +2 -0
- package/dist/common/requestCounter.d.cts +2 -0
- package/dist/common/requestCounter.d.ts +2 -0
- package/dist/common/requestLogger.cjs +11 -2
- package/dist/common/requestLogger.cjs.map +1 -1
- package/dist/common/requestLogger.d.cts +6 -1
- package/dist/common/requestLogger.d.ts +6 -1
- package/dist/common/requestLogger.js +11 -2
- package/dist/common/requestLogger.js.map +1 -1
- package/dist/common/serverErrorCounter.d.cts +2 -0
- package/dist/common/serverErrorCounter.d.ts +2 -0
- package/dist/common/spanCollector.cjs +217 -0
- package/dist/common/spanCollector.cjs.map +1 -0
- package/dist/common/spanCollector.d.cts +50 -0
- package/dist/common/spanCollector.d.ts +50 -0
- package/dist/common/spanCollector.js +194 -0
- package/dist/common/spanCollector.js.map +1 -0
- package/dist/common/types.d.cts +2 -0
- package/dist/common/types.d.ts +2 -0
- package/dist/common/validationErrorCounter.d.cts +2 -0
- package/dist/common/validationErrorCounter.d.ts +2 -0
- package/dist/elysia/index.cjs +3 -0
- package/dist/elysia/index.cjs.map +1 -1
- package/dist/elysia/index.d.cts +2 -0
- package/dist/elysia/index.d.ts +2 -0
- package/dist/elysia/index.js +2 -0
- package/dist/elysia/index.js.map +1 -1
- package/dist/elysia/plugin.cjs +9 -1
- package/dist/elysia/plugin.cjs.map +1 -1
- package/dist/elysia/plugin.d.cts +4 -0
- package/dist/elysia/plugin.d.ts +4 -0
- package/dist/elysia/plugin.js +9 -1
- package/dist/elysia/plugin.js.map +1 -1
- package/dist/elysia/utils.d.cts +2 -0
- package/dist/elysia/utils.d.ts +2 -0
- package/dist/express/index.cjs +3 -0
- package/dist/express/index.cjs.map +1 -1
- package/dist/express/index.d.cts +2 -0
- package/dist/express/index.d.ts +2 -0
- package/dist/express/index.js +2 -0
- package/dist/express/index.js.map +1 -1
- package/dist/express/middleware.cjs +85 -77
- package/dist/express/middleware.cjs.map +1 -1
- package/dist/express/middleware.d.cts +2 -0
- package/dist/express/middleware.d.ts +2 -0
- package/dist/express/middleware.js +85 -77
- package/dist/express/middleware.js.map +1 -1
- package/dist/fastify/index.cjs +3 -0
- package/dist/fastify/index.cjs.map +1 -1
- package/dist/fastify/index.d.cts +2 -0
- package/dist/fastify/index.d.ts +2 -0
- package/dist/fastify/index.js +2 -0
- package/dist/fastify/index.js.map +1 -1
- package/dist/fastify/plugin.cjs +14 -5
- package/dist/fastify/plugin.cjs.map +1 -1
- package/dist/fastify/plugin.d.cts +4 -0
- package/dist/fastify/plugin.d.ts +4 -0
- package/dist/fastify/plugin.js +14 -5
- package/dist/fastify/plugin.js.map +1 -1
- package/dist/h3/index.cjs +3 -0
- package/dist/h3/index.cjs.map +1 -1
- package/dist/h3/index.d.cts +2 -0
- package/dist/h3/index.d.ts +2 -0
- package/dist/h3/index.js +2 -0
- package/dist/h3/index.js.map +1 -1
- package/dist/h3/plugin.cjs +13 -5
- package/dist/h3/plugin.cjs.map +1 -1
- package/dist/h3/plugin.d.cts +4 -0
- package/dist/h3/plugin.d.ts +4 -0
- package/dist/h3/plugin.js +13 -5
- package/dist/h3/plugin.js.map +1 -1
- package/dist/hapi/index.cjs +3 -0
- package/dist/hapi/index.cjs.map +1 -1
- package/dist/hapi/index.d.cts +2 -0
- package/dist/hapi/index.d.ts +2 -0
- package/dist/hapi/index.js +2 -0
- package/dist/hapi/index.js.map +1 -1
- package/dist/hapi/plugin.cjs +10 -3
- package/dist/hapi/plugin.cjs.map +1 -1
- package/dist/hapi/plugin.d.cts +4 -0
- package/dist/hapi/plugin.d.ts +4 -0
- package/dist/hapi/plugin.js +10 -3
- package/dist/hapi/plugin.js.map +1 -1
- package/dist/hapi/utils.d.cts +2 -0
- package/dist/hapi/utils.d.ts +2 -0
- package/dist/hono/index.cjs +3 -0
- package/dist/hono/index.cjs.map +1 -1
- package/dist/hono/index.d.cts +2 -0
- package/dist/hono/index.d.ts +2 -0
- package/dist/hono/index.js +2 -0
- package/dist/hono/index.js.map +1 -1
- package/dist/hono/middleware.cjs +6 -2
- package/dist/hono/middleware.cjs.map +1 -1
- package/dist/hono/middleware.d.cts +2 -0
- package/dist/hono/middleware.d.ts +2 -0
- package/dist/hono/middleware.js +6 -2
- package/dist/hono/middleware.js.map +1 -1
- package/dist/hono/utils.d.cts +2 -0
- package/dist/hono/utils.d.ts +2 -0
- package/dist/koa/index.cjs +3 -0
- package/dist/koa/index.cjs.map +1 -1
- package/dist/koa/index.d.cts +2 -0
- package/dist/koa/index.d.ts +2 -0
- package/dist/koa/index.js +2 -0
- package/dist/koa/index.js.map +1 -1
- package/dist/koa/middleware.cjs +8 -4
- package/dist/koa/middleware.cjs.map +1 -1
- package/dist/koa/middleware.d.cts +2 -0
- package/dist/koa/middleware.d.ts +2 -0
- package/dist/koa/middleware.js +8 -4
- package/dist/koa/middleware.js.map +1 -1
- package/dist/loggers/console.d.cts +4 -0
- package/dist/loggers/console.d.ts +4 -0
- package/dist/loggers/hapi.d.cts +4 -0
- package/dist/loggers/hapi.d.ts +4 -0
- package/dist/loggers/index.d.cts +4 -0
- package/dist/loggers/index.d.ts +4 -0
- package/dist/loggers/nestjs.d.cts +4 -0
- package/dist/loggers/nestjs.d.ts +4 -0
- package/dist/loggers/pino.d.cts +4 -0
- package/dist/loggers/pino.d.ts +4 -0
- package/dist/loggers/winston.d.cts +4 -0
- package/dist/loggers/winston.d.ts +4 -0
- package/dist/nestjs/index.cjs +3 -0
- package/dist/nestjs/index.cjs.map +1 -1
- package/dist/nestjs/index.d.cts +2 -0
- package/dist/nestjs/index.d.ts +2 -0
- package/dist/nestjs/index.js +2 -0
- package/dist/nestjs/index.js.map +1 -1
- package/package.json +5 -2
|
@@ -1,5 +1,7 @@
|
|
|
1
|
+
import '../common/spanCollector.cjs';
|
|
1
2
|
import { ApitallyConsumer, ApitallyConfig } from '../common/types.cjs';
|
|
2
3
|
import { Context, Hono } from 'hono';
|
|
4
|
+
import '@opentelemetry/sdk-trace-base';
|
|
3
5
|
import '../common/logging.cjs';
|
|
4
6
|
import 'winston';
|
|
5
7
|
import '../common/requestLogger.cjs';
|
|
@@ -1,5 +1,7 @@
|
|
|
1
|
+
import '../common/spanCollector.js';
|
|
1
2
|
import { ApitallyConsumer, ApitallyConfig } from '../common/types.js';
|
|
2
3
|
import { Context, Hono } from 'hono';
|
|
4
|
+
import '@opentelemetry/sdk-trace-base';
|
|
3
5
|
import '../common/logging.js';
|
|
4
6
|
import 'winston';
|
|
5
7
|
import '../common/requestLogger.js';
|
package/dist/hono/middleware.js
CHANGED
|
@@ -39,7 +39,8 @@ function getMiddleware(client) {
|
|
|
39
39
|
await logsContext.run([], async () => {
|
|
40
40
|
const timestamp = Date.now() / 1e3;
|
|
41
41
|
const startTime = performance.now();
|
|
42
|
-
|
|
42
|
+
const spanHandle = client.spanCollector.startSpan();
|
|
43
|
+
await spanHandle.runInContext(next);
|
|
43
44
|
const [newResponse, responsePromise] = captureResponse(c.res, {
|
|
44
45
|
captureBody: client.requestLogger.enabled && client.requestLogger.config.logResponseBody && client.requestLogger.isSupportedContentType(c.res.headers.get("content-type")) || c.res.status === 400 && c.res.headers.get("content-type") === "application/json",
|
|
45
46
|
maxBodySize: client.requestLogger.maxBodySize
|
|
@@ -49,6 +50,9 @@ function getMiddleware(client) {
|
|
|
49
50
|
const responseHeaders = c.res.headers;
|
|
50
51
|
responsePromise.then(async (capturedResponse) => {
|
|
51
52
|
const responseTime = performance.now() - startTime;
|
|
53
|
+
spanHandle.setName(`${c.req.method} ${c.req.routePath}`);
|
|
54
|
+
const spans = spanHandle.end();
|
|
55
|
+
const traceId = spanHandle.traceId;
|
|
52
56
|
const requestSize = parseContentLength(c.req.header("content-length"));
|
|
53
57
|
const responseSize = capturedResponse.completed ? capturedResponse.size : void 0;
|
|
54
58
|
const consumer = getConsumer(c);
|
|
@@ -107,7 +111,7 @@ function getMiddleware(client) {
|
|
|
107
111
|
headers: convertHeaders(responseHeaders),
|
|
108
112
|
size: responseSize,
|
|
109
113
|
body: responseBody
|
|
110
|
-
}, c.error, logs);
|
|
114
|
+
}, c.error, logs, spans, traceId);
|
|
111
115
|
}
|
|
112
116
|
});
|
|
113
117
|
});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/hono/middleware.ts"],"sourcesContent":["import { Context, Hono } from \"hono\";\nimport { MiddlewareHandler } from \"hono/types\";\nimport { AsyncLocalStorage } from \"node:async_hooks\";\nimport { performance } from \"node:perf_hooks\";\n\nimport { ApitallyClient } from \"../common/client.js\";\nimport { consumerFromStringOrObject } from \"../common/consumerRegistry.js\";\nimport { parseContentLength } from \"../common/headers.js\";\nimport type { LogRecord } from \"../common/requestLogger.js\";\nimport { convertHeaders } from \"../common/requestLogger.js\";\nimport { captureResponse, getResponseJson } from \"../common/response.js\";\nimport { ApitallyConfig, ApitallyConsumer } from \"../common/types.js\";\nimport { patchConsole, patchWinston } from \"../loggers/index.js\";\nimport { extractZodErrors, getAppInfo } from \"./utils.js\";\n\ndeclare module \"hono\" {\n interface ContextVariableMap {\n apitallyConsumer?: ApitallyConsumer | string;\n }\n}\n\nexport function useApitally(app: Hono, config: ApitallyConfig) {\n const client = new ApitallyClient(config);\n const middleware = getMiddleware(client);\n app.use(middleware);\n\n const setStartupData = (attempt: number = 1) => {\n const appInfo = getAppInfo(app, config.appVersion);\n if (appInfo.paths.length > 0 || attempt >= 10) {\n client.setStartupData(appInfo);\n client.startSync();\n } else {\n setTimeout(() => setStartupData(attempt + 1), 500);\n }\n };\n setTimeout(() => setStartupData(), 500);\n}\n\nfunction getMiddleware(client: ApitallyClient): MiddlewareHandler {\n const logsContext = new AsyncLocalStorage<LogRecord[]>();\n\n if (client.requestLogger.config.captureLogs) {\n patchConsole(logsContext);\n patchWinston(logsContext);\n }\n\n return async (c, next) => {\n if (!client.isEnabled() || c.req.method.toUpperCase() === \"OPTIONS\") {\n await next();\n return;\n }\n\n await logsContext.run([], async () => {\n const timestamp = Date.now() / 1000;\n const startTime = performance.now();\n\n await next();\n\n const [newResponse, responsePromise] = captureResponse(c.res, {\n captureBody:\n (client.requestLogger.enabled &&\n client.requestLogger.config.logResponseBody &&\n client.requestLogger.isSupportedContentType(\n c.res.headers.get(\"content-type\"),\n )) ||\n (c.res.status === 400 &&\n c.res.headers.get(\"content-type\") === \"application/json\"),\n maxBodySize: client.requestLogger.maxBodySize,\n });\n c.res = newResponse;\n\n const statusCode = c.res.status;\n const responseHeaders = c.res.headers;\n\n responsePromise.then(async (capturedResponse) => {\n const responseTime = performance.now() - startTime;\n const requestSize = parseContentLength(c.req.header(\"content-length\"));\n const responseSize = capturedResponse.completed\n ? capturedResponse.size\n : undefined;\n\n const consumer = getConsumer(c);\n client.consumerRegistry.addOrUpdateConsumer(consumer);\n\n client.requestCounter.addRequest({\n consumer: consumer?.identifier,\n method: c.req.method,\n path: c.req.routePath,\n statusCode,\n responseTime,\n requestSize,\n responseSize,\n });\n\n if (statusCode === 400 && capturedResponse.body) {\n const responseJson = getResponseJson(capturedResponse.body);\n const validationErrors = extractZodErrors(responseJson);\n validationErrors.forEach((error) => {\n client.validationErrorCounter.addValidationError({\n consumer: consumer?.identifier,\n method: c.req.method,\n path: c.req.routePath,\n ...error,\n });\n });\n }\n\n if (c.error) {\n client.serverErrorCounter.addServerError({\n consumer: consumer?.identifier,\n method: c.req.method,\n path: c.req.routePath,\n type: c.error.name,\n msg: c.error.message,\n traceback: c.error.stack || \"\",\n });\n }\n\n if (client.requestLogger.enabled) {\n let requestBody;\n const responseBody = capturedResponse.body;\n const requestContentType = c.req.header(\"content-type\");\n if (\n client.requestLogger.config.logRequestBody &&\n client.requestLogger.isSupportedContentType(requestContentType)\n ) {\n requestBody = Buffer.from(await c.req.arrayBuffer());\n }\n const logs = logsContext.getStore();\n client.requestLogger.logRequest(\n {\n timestamp,\n method: c.req.method,\n path: c.req.routePath,\n url: c.req.url,\n headers: convertHeaders(c.req.header()),\n size: requestSize,\n consumer: consumer?.identifier,\n body: requestBody,\n },\n {\n statusCode: statusCode,\n responseTime: responseTime / 1000,\n headers: convertHeaders(responseHeaders),\n size: responseSize,\n body: responseBody,\n },\n c.error,\n logs,\n );\n }\n });\n });\n };\n}\n\nexport function setConsumer(\n c: Context,\n consumer: ApitallyConsumer | string | null | undefined,\n) {\n c.set(\"apitallyConsumer\", consumer || undefined);\n}\n\nfunction getConsumer(c: Context) {\n const consumer = c.get(\"apitallyConsumer\");\n if (consumer) {\n return consumerFromStringOrObject(consumer);\n }\n return null;\n}\n"],"mappings":";;AAEA,SAASA,yBAAyB;AAClC,SAASC,mBAAmB;AAE5B,SAASC,sBAAsB;AAC/B,SAASC,kCAAkC;AAC3C,SAASC,0BAA0B;AAEnC,SAASC,sBAAsB;AAC/B,SAASC,iBAAiBC,uBAAuB;AAEjD,SAASC,cAAcC,oBAAoB;AAC3C,SAASC,kBAAkBC,kBAAkB;AAQtC,SAASC,YAAYC,KAAWC,QA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,IAAIyB,OAAO,cAAA;AACxC,cACE3C,OAAOa,cAAcd,OAAO4E,kBAC5B3E,OAAOa,cAAcmB,uBAAuB0C,kBAAAA,GAC5C;AACAF,0BAAcI,OAAOC,KAAK,MAAM9D,EAAEG,IAAI4D,YAAW,CAAA;UACnD;AACA,gBAAMC,OAAOnE,YAAYoE,SAAQ;AACjChF,iBAAOa,cAAcoE,WACnB;YACE3D;YACAH,QAAQJ,EAAEG,IAAIC;YACdoC,MAAMxC,EAAEG,IAAIsC;YACZ0B,KAAKnE,EAAEG,IAAIgE;YACXjD,SAAS3C,eAAeyB,EAAEG,IAAIyB,OAAM,CAAA;YACpCG,MAAMJ;YACNM,UAAUA,qCAAUM;YACpBG,MAAMe;UACR,GACA;YACEnC;YACAI,cAAcA,eAAe;YAC7BR,SAAS3C,eAAegD,eAAAA;YACxBQ,MAAMF;YACNa,MAAMgB;UACR,GACA1D,EAAE8C,OACFkB,IAAAA;QAEJ;MACF,CAAA;IACF,CAAA;EACF;AACF;AApHS7E;AAsHF,SAASiF,YACdpE,GACAiC,UAAsD;AAEtDjC,IAAEqE,IAAI,oBAAoBpC,YAAYD,MAAAA;AACxC;AALgBoC;AAOhB,SAASlC,YAAYlC,GAAU;AAC7B,QAAMiC,WAAWjC,EAAEmB,IAAI,kBAAA;AACvB,MAAIc,UAAU;AACZ,WAAO5D,2BAA2B4D,QAAAA;EACpC;AACA,SAAO;AACT;AANSC;","names":["AsyncLocalStorage","performance","ApitallyClient","consumerFromStringOrObject","parseContentLength","convertHeaders","captureResponse","getResponseJson","patchConsole","patchWinston","extractZodErrors","getAppInfo","useApitally","app","config","client","middleware","getMiddleware","use","setStartupData","attempt","appInfo","appVersion","paths","length","startSync","setTimeout","logsContext","requestLogger","captureLogs","c","next","isEnabled","req","method","toUpperCase","run","timestamp","Date","now","startTime","newResponse","responsePromise","res","captureBody","enabled","logResponseBody","isSupportedContentType","headers","get","status","maxBodySize","statusCode","responseHeaders","then","capturedResponse","responseTime","requestSize","header","responseSize","completed","size","undefined","consumer","getConsumer","consumerRegistry","addOrUpdateConsumer","requestCounter","addRequest","identifier","path","routePath","body","responseJson","validationErrors","forEach","error","validationErrorCounter","addValidationError","serverErrorCounter","addServerError","type","name","msg","message","traceback","stack","requestBody","responseBody","requestContentType","logRequestBody","Buffer","from","arrayBuffer","logs","getStore","logRequest","url","setConsumer","set"]}
|
|
1
|
+
{"version":3,"sources":["../../src/hono/middleware.ts"],"sourcesContent":["import { Context, Hono } from \"hono\";\nimport { MiddlewareHandler } from \"hono/types\";\nimport { AsyncLocalStorage } from \"node:async_hooks\";\nimport { performance } from \"node:perf_hooks\";\n\nimport { ApitallyClient } from \"../common/client.js\";\nimport { consumerFromStringOrObject } from \"../common/consumerRegistry.js\";\nimport { parseContentLength } from \"../common/headers.js\";\nimport type { LogRecord } from \"../common/requestLogger.js\";\nimport { convertHeaders } from \"../common/requestLogger.js\";\nimport { captureResponse, getResponseJson } from \"../common/response.js\";\nimport { ApitallyConfig, ApitallyConsumer } from \"../common/types.js\";\nimport { patchConsole, patchWinston } from \"../loggers/index.js\";\nimport { extractZodErrors, getAppInfo } from \"./utils.js\";\n\ndeclare module \"hono\" {\n interface ContextVariableMap {\n apitallyConsumer?: ApitallyConsumer | string;\n }\n}\n\nexport function useApitally(app: Hono, config: ApitallyConfig) {\n const client = new ApitallyClient(config);\n const middleware = getMiddleware(client);\n app.use(middleware);\n\n const setStartupData = (attempt: number = 1) => {\n const appInfo = getAppInfo(app, config.appVersion);\n if (appInfo.paths.length > 0 || attempt >= 10) {\n client.setStartupData(appInfo);\n client.startSync();\n } else {\n setTimeout(() => setStartupData(attempt + 1), 500);\n }\n };\n setTimeout(() => setStartupData(), 500);\n}\n\nfunction getMiddleware(client: ApitallyClient): MiddlewareHandler {\n const logsContext = new AsyncLocalStorage<LogRecord[]>();\n\n if (client.requestLogger.config.captureLogs) {\n patchConsole(logsContext);\n patchWinston(logsContext);\n }\n\n return async (c, next) => {\n if (!client.isEnabled() || c.req.method.toUpperCase() === \"OPTIONS\") {\n await next();\n return;\n }\n\n await logsContext.run([], async () => {\n const timestamp = Date.now() / 1000;\n const startTime = performance.now();\n\n const spanHandle = client.spanCollector.startSpan();\n await spanHandle.runInContext(next);\n\n const [newResponse, responsePromise] = captureResponse(c.res, {\n captureBody:\n (client.requestLogger.enabled &&\n client.requestLogger.config.logResponseBody &&\n client.requestLogger.isSupportedContentType(\n c.res.headers.get(\"content-type\"),\n )) ||\n (c.res.status === 400 &&\n c.res.headers.get(\"content-type\") === \"application/json\"),\n maxBodySize: client.requestLogger.maxBodySize,\n });\n c.res = newResponse;\n\n const statusCode = c.res.status;\n const responseHeaders = c.res.headers;\n\n responsePromise.then(async (capturedResponse) => {\n const responseTime = performance.now() - startTime;\n\n spanHandle.setName(`${c.req.method} ${c.req.routePath}`);\n const spans = spanHandle.end();\n const traceId = spanHandle.traceId;\n\n const requestSize = parseContentLength(c.req.header(\"content-length\"));\n const responseSize = capturedResponse.completed\n ? capturedResponse.size\n : undefined;\n\n const consumer = getConsumer(c);\n client.consumerRegistry.addOrUpdateConsumer(consumer);\n\n client.requestCounter.addRequest({\n consumer: consumer?.identifier,\n method: c.req.method,\n path: c.req.routePath,\n statusCode,\n responseTime,\n requestSize,\n responseSize,\n });\n\n if (statusCode === 400 && capturedResponse.body) {\n const responseJson = getResponseJson(capturedResponse.body);\n const validationErrors = extractZodErrors(responseJson);\n validationErrors.forEach((error) => {\n client.validationErrorCounter.addValidationError({\n consumer: consumer?.identifier,\n method: c.req.method,\n path: c.req.routePath,\n ...error,\n });\n });\n }\n\n if (c.error) {\n client.serverErrorCounter.addServerError({\n consumer: consumer?.identifier,\n method: c.req.method,\n path: c.req.routePath,\n type: c.error.name,\n msg: c.error.message,\n traceback: c.error.stack || \"\",\n });\n }\n\n if (client.requestLogger.enabled) {\n let requestBody;\n const responseBody = capturedResponse.body;\n const requestContentType = c.req.header(\"content-type\");\n if (\n client.requestLogger.config.logRequestBody &&\n client.requestLogger.isSupportedContentType(requestContentType)\n ) {\n requestBody = Buffer.from(await c.req.arrayBuffer());\n }\n const logs = logsContext.getStore();\n client.requestLogger.logRequest(\n {\n timestamp,\n method: c.req.method,\n path: c.req.routePath,\n url: c.req.url,\n headers: convertHeaders(c.req.header()),\n size: requestSize,\n consumer: consumer?.identifier,\n body: requestBody,\n },\n {\n statusCode: statusCode,\n responseTime: responseTime / 1000,\n headers: convertHeaders(responseHeaders),\n size: responseSize,\n body: responseBody,\n },\n c.error,\n logs,\n spans,\n traceId,\n );\n }\n });\n });\n };\n}\n\nexport function setConsumer(\n c: Context,\n consumer: ApitallyConsumer | string | null | undefined,\n) {\n c.set(\"apitallyConsumer\", consumer || undefined);\n}\n\nfunction getConsumer(c: Context) {\n const consumer = c.get(\"apitallyConsumer\");\n if (consumer) {\n return consumerFromStringOrObject(consumer);\n }\n return null;\n}\n"],"mappings":";;AAEA,SAASA,yBAAyB;AAClC,SAASC,mBAAmB;AAE5B,SAASC,sBAAsB;AAC/B,SAASC,kCAAkC;AAC3C,SAASC,0BAA0B;AAEnC,SAASC,sBAAsB;AAC/B,SAASC,iBAAiBC,uBAAuB;AAEjD,SAASC,cAAcC,oBAAoB;AAC3C,SAASC,kBAAkBC,kBAAkB;AAQtC,SAASC,YAAYC,KAAWC,QAAsB;AAC3D,QAAMC,SAAS,IAAIb,eAAeY,MAAAA;AAClC,QAAME,aAAaC,cAAcF,MAAAA;AACjCF,MAAIK,IAAIF,UAAAA;AAER,QAAMG,iBAAiB,wBAACC,UAAkB,MAAC;AACzC,UAAMC,UAAUV,WAAWE,KAAKC,OAAOQ,UAAU;AACjD,QAAID,QAAQE,MAAMC,SAAS,KAAKJ,WAAW,IAAI;AAC7CL,aAAOI,eAAeE,OAAAA;AACtBN,aAAOU,UAAS;IAClB,OAAO;AACLC,iBAAW,MAAMP,eAAeC,UAAU,CAAA,GAAI,GAAA;IAChD;EACF,GARuB;AASvBM,aAAW,MAAMP,eAAAA,GAAkB,GAAA;AACrC;AAfgBP;AA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SAAQ;AACjCxF,iBAAOa,cAAc4E,WACnB;YACEnE;YACAH,QAAQJ,EAAEG,IAAIC;YACd6C,MAAMjD,EAAEG,IAAI6B;YACZ2C,KAAK3E,EAAEG,IAAIwE;YACXrD,SAAS/C,eAAeyB,EAAEG,IAAIkC,OAAM,CAAA;YACpCG,MAAMJ;YACNM,UAAUA,qCAAUM;YACpBE,MAAMe;UACR,GACA;YACEvC;YACAI,cAAcA,eAAe;YAC7BR,SAAS/C,eAAeoD,eAAAA;YACxBa,MAAMF;YACNY,MAAMgB;UACR,GACAlE,EAAEsD,OACFkB,MACAvC,OACAE,OAAAA;QAEJ;MACF,CAAA;IACF,CAAA;EACF;AACF;AA5HShD;AA8HF,SAASyF,YACd5E,GACA0C,UAAsD;AAEtD1C,IAAE6E,IAAI,oBAAoBnC,YAAYD,MAAAA;AACxC;AALgBmC;AAOhB,SAASjC,YAAY3C,GAAU;AAC7B,QAAM0C,WAAW1C,EAAEuB,IAAI,kBAAA;AACvB,MAAImB,UAAU;AACZ,WAAOrE,2BAA2BqE,QAAAA;EACpC;AACA,SAAO;AACT;AANSC;","names":["AsyncLocalStorage","performance","ApitallyClient","consumerFromStringOrObject","parseContentLength","convertHeaders","captureResponse","getResponseJson","patchConsole","patchWinston","extractZodErrors","getAppInfo","useApitally","app","config","client","middleware","getMiddleware","use","setStartupData","attempt","appInfo","appVersion","paths","length","startSync","setTimeout","logsContext","requestLogger","captureLogs","c","next","isEnabled","req","method","toUpperCase","run","timestamp","Date","now","startTime","spanHandle","spanCollector","startSpan","runInContext","newResponse","responsePromise","res","captureBody","enabled","logResponseBody","isSupportedContentType","headers","get","status","maxBodySize","statusCode","responseHeaders","then","capturedResponse","responseTime","setName","routePath","spans","end","traceId","requestSize","header","responseSize","completed","size","undefined","consumer","getConsumer","consumerRegistry","addOrUpdateConsumer","requestCounter","addRequest","identifier","path","body","responseJson","validationErrors","forEach","error","validationErrorCounter","addValidationError","serverErrorCounter","addServerError","type","name","msg","message","traceback","stack","requestBody","responseBody","requestContentType","logRequestBody","Buffer","from","arrayBuffer","logs","getStore","logRequest","url","setConsumer","set"]}
|
package/dist/hono/utils.d.cts
CHANGED
|
@@ -5,6 +5,8 @@ import 'winston';
|
|
|
5
5
|
import '../common/requestLogger.cjs';
|
|
6
6
|
import 'node:buffer';
|
|
7
7
|
import 'node:http';
|
|
8
|
+
import '../common/spanCollector.cjs';
|
|
9
|
+
import '@opentelemetry/sdk-trace-base';
|
|
8
10
|
import '../common/tempGzipFile.cjs';
|
|
9
11
|
|
|
10
12
|
declare function getAppInfo(app: Hono, appVersion?: string): StartupData;
|
package/dist/hono/utils.d.ts
CHANGED
|
@@ -5,6 +5,8 @@ import 'winston';
|
|
|
5
5
|
import '../common/requestLogger.js';
|
|
6
6
|
import 'node:buffer';
|
|
7
7
|
import 'node:http';
|
|
8
|
+
import '../common/spanCollector.js';
|
|
9
|
+
import '@opentelemetry/sdk-trace-base';
|
|
8
10
|
import '../common/tempGzipFile.js';
|
|
9
11
|
|
|
10
12
|
declare function getAppInfo(app: Hono, appVersion?: string): StartupData;
|
package/dist/koa/index.cjs
CHANGED
|
@@ -18,13 +18,16 @@ var __copyProps = (to, from, except, desc) => {
|
|
|
18
18
|
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
19
19
|
var koa_exports = {};
|
|
20
20
|
__export(koa_exports, {
|
|
21
|
+
ApitallySpanProcessor: () => import_spanCollector.ApitallySpanProcessor,
|
|
21
22
|
setConsumer: () => import_middleware.setConsumer,
|
|
22
23
|
useApitally: () => import_middleware.useApitally
|
|
23
24
|
});
|
|
24
25
|
module.exports = __toCommonJS(koa_exports);
|
|
26
|
+
var import_spanCollector = require("../common/spanCollector.js");
|
|
25
27
|
var import_middleware = require("./middleware.js");
|
|
26
28
|
// Annotate the CommonJS export names for ESM import in node:
|
|
27
29
|
0 && (module.exports = {
|
|
30
|
+
ApitallySpanProcessor,
|
|
28
31
|
setConsumer,
|
|
29
32
|
useApitally
|
|
30
33
|
});
|
package/dist/koa/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/koa/index.ts"],"sourcesContent":["export type { ApitallyConfig, ApitallyConsumer } from \"../common/types.js\";\nexport { setConsumer, useApitally } from \"./middleware.js\";\n"],"mappings":";;;;;;;;;;;;;;;;;;
|
|
1
|
+
{"version":3,"sources":["../../src/koa/index.ts"],"sourcesContent":["export { ApitallySpanProcessor } from \"../common/spanCollector.js\";\nexport type { ApitallyConfig, ApitallyConsumer } from \"../common/types.js\";\nexport { setConsumer, useApitally } from \"./middleware.js\";\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;;;;;;;2BAAsC;AAEtC,wBAAyC;","names":[]}
|
package/dist/koa/index.d.cts
CHANGED
|
@@ -1,5 +1,7 @@
|
|
|
1
|
+
export { ApitallySpanProcessor } from '../common/spanCollector.cjs';
|
|
1
2
|
export { ApitallyConfig, ApitallyConsumer } from '../common/types.cjs';
|
|
2
3
|
export { setConsumer, useApitally } from './middleware.cjs';
|
|
4
|
+
import '@opentelemetry/sdk-trace-base';
|
|
3
5
|
import '../common/logging.cjs';
|
|
4
6
|
import 'winston';
|
|
5
7
|
import '../common/requestLogger.cjs';
|
package/dist/koa/index.d.ts
CHANGED
|
@@ -1,5 +1,7 @@
|
|
|
1
|
+
export { ApitallySpanProcessor } from '../common/spanCollector.js';
|
|
1
2
|
export { ApitallyConfig, ApitallyConsumer } from '../common/types.js';
|
|
2
3
|
export { setConsumer, useApitally } from './middleware.js';
|
|
4
|
+
import '@opentelemetry/sdk-trace-base';
|
|
3
5
|
import '../common/logging.js';
|
|
4
6
|
import 'winston';
|
|
5
7
|
import '../common/requestLogger.js';
|
package/dist/koa/index.js
CHANGED
package/dist/koa/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/koa/index.ts"],"sourcesContent":["export type { ApitallyConfig, ApitallyConsumer } from \"../common/types.js\";\nexport { setConsumer, useApitally } from \"./middleware.js\";\n"],"mappings":"
|
|
1
|
+
{"version":3,"sources":["../../src/koa/index.ts"],"sourcesContent":["export { ApitallySpanProcessor } from \"../common/spanCollector.js\";\nexport type { ApitallyConfig, ApitallyConsumer } from \"../common/types.js\";\nexport { setConsumer, useApitally } from \"./middleware.js\";\n"],"mappings":"AAAA,SAASA,6BAA6B;AAEtC,SAASC,aAAaC,mBAAmB;","names":["ApitallySpanProcessor","setConsumer","useApitally"]}
|
package/dist/koa/middleware.cjs
CHANGED
|
@@ -62,8 +62,9 @@ function getMiddleware(client) {
|
|
|
62
62
|
let statusCode;
|
|
63
63
|
let serverError;
|
|
64
64
|
const startTime = performance.now();
|
|
65
|
+
const spanHandle = client.spanCollector.startSpan();
|
|
65
66
|
try {
|
|
66
|
-
await next
|
|
67
|
+
await spanHandle.runInContext(next);
|
|
67
68
|
} catch (error) {
|
|
68
69
|
path = getPath(ctx);
|
|
69
70
|
statusCode = error.statusCode || error.status || 500;
|
|
@@ -81,11 +82,14 @@ function getMiddleware(client) {
|
|
|
81
82
|
throw error;
|
|
82
83
|
} finally {
|
|
83
84
|
const responseTime = performance.now() - startTime;
|
|
84
|
-
const consumer = getConsumer(ctx);
|
|
85
|
-
client.consumerRegistry.addOrUpdateConsumer(consumer);
|
|
86
85
|
if (!path) {
|
|
87
86
|
path = getPath(ctx);
|
|
88
87
|
}
|
|
88
|
+
spanHandle.setName(`${ctx.request.method} ${path}`);
|
|
89
|
+
const spans = spanHandle.end();
|
|
90
|
+
const traceId = spanHandle.traceId;
|
|
91
|
+
const consumer = getConsumer(ctx);
|
|
92
|
+
client.consumerRegistry.addOrUpdateConsumer(consumer);
|
|
89
93
|
if (path) {
|
|
90
94
|
try {
|
|
91
95
|
client.requestCounter.addRequest({
|
|
@@ -121,7 +125,7 @@ function getMiddleware(client) {
|
|
|
121
125
|
headers: (0, import_requestLogger.convertHeaders)(ctx.response.headers),
|
|
122
126
|
size: ctx.response.length,
|
|
123
127
|
body: (0, import_requestLogger.convertBody)(ctx.response.body, ctx.response.get("content-type"))
|
|
124
|
-
}, serverError, logs);
|
|
128
|
+
}, serverError, logs, spans, traceId);
|
|
125
129
|
}
|
|
126
130
|
}
|
|
127
131
|
});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/koa/middleware.ts"],"sourcesContent":["import Koa from \"koa\";\nimport { AsyncLocalStorage } from \"node:async_hooks\";\n\nimport { ApitallyClient } from \"../common/client.js\";\nimport { consumerFromStringOrObject } from \"../common/consumerRegistry.js\";\nimport { getPackageVersion } from \"../common/packageVersions.js\";\nimport type { LogRecord } from \"../common/requestLogger.js\";\nimport { convertBody, convertHeaders } from \"../common/requestLogger.js\";\nimport {\n ApitallyConfig,\n ApitallyConsumer,\n PathInfo,\n StartupData,\n} from \"../common/types.js\";\nimport { patchConsole, patchWinston } from \"../loggers/index.js\";\n\nexport function useApitally(app: Koa, config: ApitallyConfig) {\n const client = new ApitallyClient(config);\n const middleware = getMiddleware(client);\n app.use(middleware);\n\n const setStartupData = (attempt: number = 1) => {\n const appInfo = getAppInfo(app, config.appVersion);\n if (appInfo.paths.length > 0 || attempt >= 10) {\n client.setStartupData(appInfo);\n client.startSync();\n } else {\n setTimeout(() => setStartupData(attempt + 1), 500);\n }\n };\n setTimeout(() => setStartupData(), 500);\n}\n\nfunction getMiddleware(client: ApitallyClient) {\n const logsContext = new AsyncLocalStorage<LogRecord[]>();\n\n if (client.requestLogger.config.captureLogs) {\n patchConsole(logsContext);\n patchWinston(logsContext);\n }\n\n return async (ctx: Koa.Context, next: Koa.Next) => {\n if (!client.isEnabled() || ctx.request.method.toUpperCase() === \"OPTIONS\") {\n await next();\n return;\n }\n\n await logsContext.run([], async () => {\n let path: string | undefined;\n let statusCode: number | undefined;\n let serverError: Error | undefined;\n const startTime = performance.now();\n try {\n await next();\n } catch (error: any) {\n path = getPath(ctx);\n statusCode = error.statusCode || error.status || 500;\n if (path && statusCode === 500 && error instanceof Error) {\n serverError = error;\n client.serverErrorCounter.addServerError({\n consumer: getConsumer(ctx)?.identifier,\n method: ctx.request.method,\n path,\n type: error.name,\n msg: error.message,\n traceback: error.stack || \"\",\n });\n }\n throw error;\n } finally {\n const responseTime = performance.now() - startTime;\n const consumer = getConsumer(ctx);\n client.consumerRegistry.addOrUpdateConsumer(consumer);\n if (!path) {\n path = getPath(ctx);\n }\n if (path) {\n try {\n client.requestCounter.addRequest({\n consumer: consumer?.identifier,\n method: ctx.request.method,\n path,\n statusCode: statusCode || ctx.response.status,\n responseTime,\n requestSize: ctx.request.length,\n responseSize: ctx.response.length,\n });\n } catch (error) {\n client.logger.error(\n \"Error while logging request in Apitally middleware.\",\n { context: ctx, error },\n );\n }\n }\n if (client.requestLogger.enabled) {\n const logs = logsContext.getStore();\n client.requestLogger.logRequest(\n {\n timestamp: Date.now() / 1000,\n method: ctx.request.method,\n path,\n url: ctx.request.href,\n headers: convertHeaders(ctx.request.headers),\n size: ctx.request.length,\n consumer: consumer?.identifier,\n body: convertBody(\n ctx.request.body,\n ctx.request.get(\"content-type\"),\n ),\n },\n {\n statusCode: statusCode || ctx.response.status,\n responseTime: responseTime / 1000,\n headers: convertHeaders(ctx.response.headers),\n size: ctx.response.length,\n body: convertBody(\n ctx.response.body,\n ctx.response.get(\"content-type\"),\n ),\n },\n serverError,\n logs,\n );\n }\n }\n });\n };\n}\n\nfunction getPath(ctx: Koa.Context) {\n return ctx._matchedRoute || ctx.routePath; // _matchedRoute is set by koa-router, routePath is set by koa-route\n}\n\nexport function setConsumer(\n ctx: Koa.Context,\n consumer: ApitallyConsumer | string | null | undefined,\n) {\n ctx.state.apitallyConsumer = consumer || undefined;\n}\n\nfunction getConsumer(ctx: Koa.Context) {\n if (ctx.state.apitallyConsumer) {\n return consumerFromStringOrObject(ctx.state.apitallyConsumer);\n } else if (ctx.state.consumerIdentifier) {\n // For backwards compatibility\n process.emitWarning(\n \"The consumerIdentifier property on the ctx.state object is deprecated. Use apitallyConsumer instead.\",\n \"DeprecationWarning\",\n );\n return consumerFromStringOrObject(ctx.state.consumerIdentifier);\n }\n return null;\n}\n\nfunction getAppInfo(app: Koa, appVersion?: string): StartupData {\n const versions: Array<[string, string]> = [\n [\"nodejs\", process.version.replace(/^v/, \"\")],\n ];\n const koaVersion = getPackageVersion(\"koa\");\n const apitallyVersion = getPackageVersion(\"../..\");\n if (koaVersion) {\n versions.push([\"koa\", koaVersion]);\n }\n if (apitallyVersion) {\n versions.push([\"apitally\", apitallyVersion]);\n }\n if (appVersion) {\n versions.push([\"app\", appVersion]);\n }\n return {\n paths: listEndpoints(app),\n versions: Object.fromEntries(versions),\n client: \"js:koa\",\n };\n}\n\nfunction isKoaRouterMiddleware(middleware: any) {\n return (\n typeof middleware === \"function\" &&\n middleware.router &&\n Array.isArray(middleware.router.stack)\n );\n}\n\nfunction listEndpoints(app: Koa) {\n const endpoints: Array<PathInfo> = [];\n app.middleware.forEach((middleware: any) => {\n if (isKoaRouterMiddleware(middleware)) {\n middleware.router.stack.forEach((layer: any) => {\n if (layer.methods && layer.methods.length > 0) {\n layer.methods.forEach((method: string) => {\n if (![\"HEAD\", \"OPTIONS\"].includes(method.toUpperCase())) {\n endpoints.push({\n method: method.toUpperCase(),\n path: layer.path,\n });\n }\n });\n }\n });\n }\n });\n return endpoints;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AACA;;;;;;AAAA,8BAAkC;AAElC,oBAA+B;AAC/B,8BAA2C;AAC3C,6BAAkC;AAElC,2BAA4C;AAO5C,qBAA2C;AAEpC,SAASA,YAAYC,KAAUC,QAAsB;AAC1D,QAAMC,SAAS,IAAIC,6BAAeF,MAAAA;AAClC,QAAMG,aAAaC,cAAcH,MAAAA;AACjCF,MAAIM,IAAIF,UAAAA;AAER,QAAMG,iBAAiB,wBAACC,UAAkB,MAAC;AACzC,UAAMC,UAAUC,WAAWV,KAAKC,OAAOU,UAAU;AACjD,QAAIF,QAAQG,MAAMC,SAAS,KAAKL,WAAW,IAAI;AAC7CN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K;AACvDuE,wBAAUR,KAAK;gBACbhE,QAAQA,OAAOC,YAAW;gBAC1BE,MAAMuE,MAAMvE;cACd,CAAA;YACF;UACF,CAAA;QACF;MACF,CAAA;IACF;EACF,CAAA;AACA,SAAOqE;AACT;AAnBSP;","names":["useApitally","app","config","client","ApitallyClient","middleware","getMiddleware","use","setStartupData","attempt","appInfo","getAppInfo","appVersion","paths","length","startSync","setTimeout","logsContext","AsyncLocalStorage","requestLogger","captureLogs","patchConsole","patchWinston","ctx","next","isEnabled","request","method","toUpperCase","run","path","statusCode","serverError","startTime","performance","now","error","getPath","status","Error","serverErrorCounter","addServerError","consumer","getConsumer","identifier","type","name","msg","message","traceback","stack","responseTime","consumerRegistry","addOrUpdateConsumer","requestCounter","addRequest","response","requestSize","responseSize","logger","context","enabled","logs","getStore","logRequest","timestamp","Date","url","href","headers","convertHeaders","size","body","convertBody","get","_matchedRoute","routePath","setConsumer","state","apitallyConsumer","undefined","consumerFromStringOrObject","consumerIdentifier","process","emitWarning","versions","version","replace","koaVersion","getPackageVersion","apitallyVersion","push","listEndpoints","Object","fromEntries","isKoaRouterMiddleware","router","Array","isArray","endpoints","forEach","layer","methods","includes"]}
|
|
1
|
+
{"version":3,"sources":["../../src/koa/middleware.ts"],"sourcesContent":["import Koa from \"koa\";\nimport { AsyncLocalStorage } from \"node:async_hooks\";\n\nimport { ApitallyClient } from \"../common/client.js\";\nimport { consumerFromStringOrObject } from \"../common/consumerRegistry.js\";\nimport { getPackageVersion } from \"../common/packageVersions.js\";\nimport type { LogRecord } from \"../common/requestLogger.js\";\nimport { convertBody, convertHeaders } from \"../common/requestLogger.js\";\nimport {\n ApitallyConfig,\n ApitallyConsumer,\n PathInfo,\n StartupData,\n} from \"../common/types.js\";\nimport { patchConsole, patchWinston } from \"../loggers/index.js\";\n\nexport function useApitally(app: Koa, config: ApitallyConfig) {\n const client = new ApitallyClient(config);\n const middleware = getMiddleware(client);\n app.use(middleware);\n\n const setStartupData = (attempt: number = 1) => {\n const appInfo = getAppInfo(app, config.appVersion);\n if (appInfo.paths.length > 0 || attempt >= 10) {\n client.setStartupData(appInfo);\n client.startSync();\n } else {\n setTimeout(() => setStartupData(attempt + 1), 500);\n }\n };\n setTimeout(() => setStartupData(), 500);\n}\n\nfunction getMiddleware(client: ApitallyClient) {\n const logsContext = new AsyncLocalStorage<LogRecord[]>();\n\n if (client.requestLogger.config.captureLogs) {\n patchConsole(logsContext);\n patchWinston(logsContext);\n }\n\n return async (ctx: Koa.Context, next: Koa.Next) => {\n if (!client.isEnabled() || ctx.request.method.toUpperCase() === \"OPTIONS\") {\n await next();\n return;\n }\n\n await logsContext.run([], async () => {\n let path: string | undefined;\n let statusCode: number | undefined;\n let serverError: Error | undefined;\n const startTime = performance.now();\n const spanHandle = client.spanCollector.startSpan();\n try {\n await spanHandle.runInContext(next);\n } catch (error: any) {\n path = getPath(ctx);\n statusCode = error.statusCode || error.status || 500;\n if (path && statusCode === 500 && error instanceof Error) {\n serverError = error;\n client.serverErrorCounter.addServerError({\n consumer: getConsumer(ctx)?.identifier,\n method: ctx.request.method,\n path,\n type: error.name,\n msg: error.message,\n traceback: error.stack || \"\",\n });\n }\n throw error;\n } finally {\n const responseTime = performance.now() - startTime;\n\n if (!path) {\n path = getPath(ctx);\n }\n\n spanHandle.setName(`${ctx.request.method} ${path}`);\n const spans = spanHandle.end();\n const traceId = spanHandle.traceId;\n\n const consumer = getConsumer(ctx);\n client.consumerRegistry.addOrUpdateConsumer(consumer);\n\n if (path) {\n try {\n client.requestCounter.addRequest({\n consumer: consumer?.identifier,\n method: ctx.request.method,\n path,\n statusCode: statusCode || ctx.response.status,\n responseTime,\n requestSize: ctx.request.length,\n responseSize: ctx.response.length,\n });\n } catch (error) {\n client.logger.error(\n \"Error while logging request in Apitally middleware.\",\n { context: ctx, error },\n );\n }\n }\n\n if (client.requestLogger.enabled) {\n const logs = logsContext.getStore();\n client.requestLogger.logRequest(\n {\n timestamp: Date.now() / 1000,\n method: ctx.request.method,\n path,\n url: ctx.request.href,\n headers: convertHeaders(ctx.request.headers),\n size: ctx.request.length,\n consumer: consumer?.identifier,\n body: convertBody(\n ctx.request.body,\n ctx.request.get(\"content-type\"),\n ),\n },\n {\n statusCode: statusCode || ctx.response.status,\n responseTime: responseTime / 1000,\n headers: convertHeaders(ctx.response.headers),\n size: ctx.response.length,\n body: convertBody(\n ctx.response.body,\n ctx.response.get(\"content-type\"),\n ),\n },\n serverError,\n logs,\n spans,\n traceId,\n );\n }\n }\n });\n };\n}\n\nfunction getPath(ctx: Koa.Context) {\n return ctx._matchedRoute || ctx.routePath; // _matchedRoute is set by koa-router, routePath is set by koa-route\n}\n\nexport function setConsumer(\n ctx: Koa.Context,\n consumer: ApitallyConsumer | string | null | undefined,\n) {\n ctx.state.apitallyConsumer = consumer || undefined;\n}\n\nfunction getConsumer(ctx: Koa.Context) {\n if (ctx.state.apitallyConsumer) {\n return consumerFromStringOrObject(ctx.state.apitallyConsumer);\n } else if (ctx.state.consumerIdentifier) {\n // For backwards compatibility\n process.emitWarning(\n \"The consumerIdentifier property on the ctx.state object is deprecated. Use apitallyConsumer instead.\",\n \"DeprecationWarning\",\n );\n return consumerFromStringOrObject(ctx.state.consumerIdentifier);\n }\n return null;\n}\n\nfunction getAppInfo(app: Koa, appVersion?: string): StartupData {\n const versions: Array<[string, string]> = [\n [\"nodejs\", process.version.replace(/^v/, \"\")],\n ];\n const koaVersion = getPackageVersion(\"koa\");\n const apitallyVersion = getPackageVersion(\"../..\");\n if (koaVersion) {\n versions.push([\"koa\", koaVersion]);\n }\n if (apitallyVersion) {\n versions.push([\"apitally\", apitallyVersion]);\n }\n if (appVersion) {\n versions.push([\"app\", appVersion]);\n }\n return {\n paths: listEndpoints(app),\n versions: Object.fromEntries(versions),\n client: \"js:koa\",\n };\n}\n\nfunction isKoaRouterMiddleware(middleware: any) {\n return (\n typeof middleware === \"function\" &&\n middleware.router &&\n Array.isArray(middleware.router.stack)\n );\n}\n\nfunction listEndpoints(app: Koa) {\n const endpoints: Array<PathInfo> = [];\n app.middleware.forEach((middleware: any) => {\n if (isKoaRouterMiddleware(middleware)) {\n middleware.router.stack.forEach((layer: any) => {\n if (layer.methods && layer.methods.length > 0) {\n layer.methods.forEach((method: string) => {\n if (![\"HEAD\", \"OPTIONS\"].includes(method.toUpperCase())) {\n endpoints.push({\n method: method.toUpperCase(),\n path: layer.path,\n });\n }\n });\n }\n });\n }\n });\n return endpoints;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AACA;;;;;;AAAA,8BAAkC;AAElC,oBAA+B;AAC/B,8BAA2C;AAC3C,6BAAkC;AAElC,2BAA4C;AAO5C,qBAA2C;AAEpC,SAASA,YAAYC,KAAUC,QAAsB;AAC1D,QAAMC,SAAS,IAAIC,6BAAeF,MAAAA;AAClC,QAAMG,aAAaC,cAAcH,MAAAA;AACjCF,MAAIM,IAAIF,UAAAA;AAER,QAAMG,iBAAiB,wBAACC,UAAkB,MAAC;AACzC,UAAMC,UAAUC,WAAWV,KAAKC,OAAOU,UAAU;AACjD,QAAIF,QAAQG,MAAMC,SAAS,KAAKL,WAAW,IAAI;AAC7CN,aAAOK,eAAeE,OAAAA;AACtBP,aAAOY,UAAS;IAClB,OAAO;AACLC,iBAAW,MAAMR,eAAeC,UAAU,CAAA,GAAI,GAAA;IAChD;EACF,GARuB;AASvBO,aAAW,MAAMR,eAAAA,GAAkB,GAAA;AACrC;AAfgBR;AAiBhB,SAASM,cAAcH,QAAsB;AAC3C,QAAMc,cAAc,IAAIC,0CAAAA;AAExB,MAAIf,OAAOgB,cAAcjB,OAAOkB,aAAa;AAC3CC,qCAAaJ,WAAAA;AACbK,qCAAaL,WAAAA;EACf;AAEA,SAAO,OAAOM,KAAkBC,SAAAA;AAC9B,QAAI,CAACrB,OAAOsB,UAAS,KAAMF,IAAIG,QAAQC,OAAOC,YAAW,MAAO,WAAW;AACzE,YAAMJ,KAAAA;AACN;IACF;AAEA,UAAMP,YAAYY,IAAI,CAAA,GAAI,YAAA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F,QAAQG,QAAQC,QAAQ,MAAM,EAAA;;;AAE3C,QAAMC,iBAAaC,0CAAkB,KAAA;AACrC,QAAMC,sBAAkBD,0CAAkB,OAAA;AAC1C,MAAID,YAAY;AACdH,aAASM,KAAK;MAAC;MAAOH;KAAW;EACnC;AACA,MAAIE,iBAAiB;AACnBL,aAASM,KAAK;MAAC;MAAYD;KAAgB;EAC7C;AACA,MAAItF,YAAY;AACdiF,aAASM,KAAK;MAAC;MAAOvF;KAAW;EACnC;AACA,SAAO;IACLC,OAAOuF,cAAcnG,GAAAA;IACrB4F,UAAUQ,OAAOC,YAAYT,QAAAA;IAC7B1F,QAAQ;EACV;AACF;AApBSQ;AAsBT,SAAS4F,sBAAsBlG,YAAe;AAC5C,SACE,OAAOA,eAAe,cACtBA,WAAWmG,UACXC,MAAMC,QAAQrG,WAAWmG,OAAOlD,KAAK;AAEzC;AANSiD;AAQT,SAASH,cAAcnG,KAAQ;AAC7B,QAAM0G,YAA6B,CAAA;AACnC1G,MAAII,WAAWuG,QAAQ,CAACvG,eAAAA;AACtB,QAAIkG,sBAAsBlG,UAAAA,GAAa;AACrCA,iBAAWmG,OAAOlD,MAAMsD,QAAQ,CAACC,UAAAA;AAC/B,YAAIA,MAAMC,WAAWD,MAAMC,QAAQhG,SAAS,GAAG;AAC7C+F,gBAAMC,QAAQF,QAAQ,CAACjF,WAAAA;AACrB,gBAAI,CAAC;cAAC;cAAQ;cAAWoF,SAASpF,OAAOC,YAAW,CAAA,GAAK;AACvD+E,wBAAUR,KAAK;gBACbxE,QAAQA,OAAOC,YAAW;gBAC1BE,MAAM+E,MAAM/E;cACd,CAAA;YACF;UACF,CAAA;QACF;MACF,CAAA;IACF;EACF,CAAA;AACA,SAAO6E;AACT;AAnBSP;","names":["useApitally","app","config","client","ApitallyClient","middleware","getMiddleware","use","setStartupData","attempt","appInfo","getAppInfo","appVersion","paths","length","startSync","setTimeout","logsContext","AsyncLocalStorage","requestLogger","captureLogs","patchConsole","patchWinston","ctx","next","isEnabled","request","method","toUpperCase","run","path","statusCode","serverError","startTime","performance","now","spanHandle","spanCollector","startSpan","runInContext","error","getPath","status","Error","serverErrorCounter","addServerError","consumer","getConsumer","identifier","type","name","msg","message","traceback","stack","responseTime","setName","spans","end","traceId","consumerRegistry","addOrUpdateConsumer","requestCounter","addRequest","response","requestSize","responseSize","logger","context","enabled","logs","getStore","logRequest","timestamp","Date","url","href","headers","convertHeaders","size","body","convertBody","get","_matchedRoute","routePath","setConsumer","state","apitallyConsumer","undefined","consumerFromStringOrObject","consumerIdentifier","process","emitWarning","versions","version","replace","koaVersion","getPackageVersion","apitallyVersion","push","listEndpoints","Object","fromEntries","isKoaRouterMiddleware","router","Array","isArray","endpoints","forEach","layer","methods","includes"]}
|
|
@@ -1,5 +1,7 @@
|
|
|
1
|
+
import '../common/spanCollector.cjs';
|
|
1
2
|
import { ApitallyConsumer, ApitallyConfig } from '../common/types.cjs';
|
|
2
3
|
import Koa from 'koa';
|
|
4
|
+
import '@opentelemetry/sdk-trace-base';
|
|
3
5
|
import '../common/logging.cjs';
|
|
4
6
|
import 'winston';
|
|
5
7
|
import '../common/requestLogger.cjs';
|
package/dist/koa/middleware.d.ts
CHANGED
|
@@ -1,5 +1,7 @@
|
|
|
1
|
+
import '../common/spanCollector.js';
|
|
1
2
|
import { ApitallyConsumer, ApitallyConfig } from '../common/types.js';
|
|
2
3
|
import Koa from 'koa';
|
|
4
|
+
import '@opentelemetry/sdk-trace-base';
|
|
3
5
|
import '../common/logging.js';
|
|
4
6
|
import 'winston';
|
|
5
7
|
import '../common/requestLogger.js';
|
package/dist/koa/middleware.js
CHANGED
|
@@ -39,8 +39,9 @@ function getMiddleware(client) {
|
|
|
39
39
|
let statusCode;
|
|
40
40
|
let serverError;
|
|
41
41
|
const startTime = performance.now();
|
|
42
|
+
const spanHandle = client.spanCollector.startSpan();
|
|
42
43
|
try {
|
|
43
|
-
await next
|
|
44
|
+
await spanHandle.runInContext(next);
|
|
44
45
|
} catch (error) {
|
|
45
46
|
path = getPath(ctx);
|
|
46
47
|
statusCode = error.statusCode || error.status || 500;
|
|
@@ -58,11 +59,14 @@ function getMiddleware(client) {
|
|
|
58
59
|
throw error;
|
|
59
60
|
} finally {
|
|
60
61
|
const responseTime = performance.now() - startTime;
|
|
61
|
-
const consumer = getConsumer(ctx);
|
|
62
|
-
client.consumerRegistry.addOrUpdateConsumer(consumer);
|
|
63
62
|
if (!path) {
|
|
64
63
|
path = getPath(ctx);
|
|
65
64
|
}
|
|
65
|
+
spanHandle.setName(`${ctx.request.method} ${path}`);
|
|
66
|
+
const spans = spanHandle.end();
|
|
67
|
+
const traceId = spanHandle.traceId;
|
|
68
|
+
const consumer = getConsumer(ctx);
|
|
69
|
+
client.consumerRegistry.addOrUpdateConsumer(consumer);
|
|
66
70
|
if (path) {
|
|
67
71
|
try {
|
|
68
72
|
client.requestCounter.addRequest({
|
|
@@ -98,7 +102,7 @@ function getMiddleware(client) {
|
|
|
98
102
|
headers: convertHeaders(ctx.response.headers),
|
|
99
103
|
size: ctx.response.length,
|
|
100
104
|
body: convertBody(ctx.response.body, ctx.response.get("content-type"))
|
|
101
|
-
}, serverError, logs);
|
|
105
|
+
}, serverError, logs, spans, traceId);
|
|
102
106
|
}
|
|
103
107
|
}
|
|
104
108
|
});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/koa/middleware.ts"],"sourcesContent":["import Koa from \"koa\";\nimport { AsyncLocalStorage } from \"node:async_hooks\";\n\nimport { ApitallyClient } from \"../common/client.js\";\nimport { consumerFromStringOrObject } from \"../common/consumerRegistry.js\";\nimport { getPackageVersion } from \"../common/packageVersions.js\";\nimport type { LogRecord } from \"../common/requestLogger.js\";\nimport { convertBody, convertHeaders } from \"../common/requestLogger.js\";\nimport {\n ApitallyConfig,\n ApitallyConsumer,\n PathInfo,\n StartupData,\n} from \"../common/types.js\";\nimport { patchConsole, patchWinston } from \"../loggers/index.js\";\n\nexport function useApitally(app: Koa, config: ApitallyConfig) {\n const client = new ApitallyClient(config);\n const middleware = getMiddleware(client);\n app.use(middleware);\n\n const setStartupData = (attempt: number = 1) => {\n const appInfo = getAppInfo(app, config.appVersion);\n if (appInfo.paths.length > 0 || attempt >= 10) {\n client.setStartupData(appInfo);\n client.startSync();\n } else {\n setTimeout(() => setStartupData(attempt + 1), 500);\n }\n };\n setTimeout(() => setStartupData(), 500);\n}\n\nfunction getMiddleware(client: ApitallyClient) {\n const logsContext = new AsyncLocalStorage<LogRecord[]>();\n\n if (client.requestLogger.config.captureLogs) {\n patchConsole(logsContext);\n patchWinston(logsContext);\n }\n\n return async (ctx: Koa.Context, next: Koa.Next) => {\n if (!client.isEnabled() || ctx.request.method.toUpperCase() === \"OPTIONS\") {\n await next();\n return;\n }\n\n await logsContext.run([], async () => {\n let path: string | undefined;\n let statusCode: number | undefined;\n let serverError: Error | undefined;\n const startTime = performance.now();\n try {\n await next();\n } catch (error: any) {\n path = getPath(ctx);\n statusCode = error.statusCode || error.status || 500;\n if (path && statusCode === 500 && error instanceof Error) {\n serverError = error;\n client.serverErrorCounter.addServerError({\n consumer: getConsumer(ctx)?.identifier,\n method: ctx.request.method,\n path,\n type: error.name,\n msg: error.message,\n traceback: error.stack || \"\",\n });\n }\n throw error;\n } finally {\n const responseTime = performance.now() - startTime;\n const consumer = getConsumer(ctx);\n client.consumerRegistry.addOrUpdateConsumer(consumer);\n if (!path) {\n path = getPath(ctx);\n }\n if (path) {\n try {\n client.requestCounter.addRequest({\n consumer: consumer?.identifier,\n method: ctx.request.method,\n path,\n statusCode: statusCode || ctx.response.status,\n responseTime,\n requestSize: ctx.request.length,\n responseSize: ctx.response.length,\n });\n } catch (error) {\n client.logger.error(\n \"Error while logging request in Apitally middleware.\",\n { context: ctx, error },\n );\n }\n }\n if (client.requestLogger.enabled) {\n const logs = logsContext.getStore();\n client.requestLogger.logRequest(\n {\n timestamp: Date.now() / 1000,\n method: ctx.request.method,\n path,\n url: ctx.request.href,\n headers: convertHeaders(ctx.request.headers),\n size: ctx.request.length,\n consumer: consumer?.identifier,\n body: convertBody(\n ctx.request.body,\n ctx.request.get(\"content-type\"),\n ),\n },\n {\n statusCode: statusCode || ctx.response.status,\n responseTime: responseTime / 1000,\n headers: convertHeaders(ctx.response.headers),\n size: ctx.response.length,\n body: convertBody(\n ctx.response.body,\n ctx.response.get(\"content-type\"),\n ),\n },\n serverError,\n logs,\n );\n }\n }\n });\n };\n}\n\nfunction getPath(ctx: Koa.Context) {\n return ctx._matchedRoute || ctx.routePath; // _matchedRoute is set by koa-router, routePath is set by koa-route\n}\n\nexport function setConsumer(\n ctx: Koa.Context,\n consumer: ApitallyConsumer | string | null | undefined,\n) {\n ctx.state.apitallyConsumer = consumer || undefined;\n}\n\nfunction getConsumer(ctx: Koa.Context) {\n if (ctx.state.apitallyConsumer) {\n return consumerFromStringOrObject(ctx.state.apitallyConsumer);\n } else if (ctx.state.consumerIdentifier) {\n // For backwards compatibility\n process.emitWarning(\n \"The consumerIdentifier property on the ctx.state object is deprecated. Use apitallyConsumer instead.\",\n \"DeprecationWarning\",\n );\n return consumerFromStringOrObject(ctx.state.consumerIdentifier);\n }\n return null;\n}\n\nfunction getAppInfo(app: Koa, appVersion?: string): StartupData {\n const versions: Array<[string, string]> = [\n [\"nodejs\", process.version.replace(/^v/, \"\")],\n ];\n const koaVersion = getPackageVersion(\"koa\");\n const apitallyVersion = getPackageVersion(\"../..\");\n if (koaVersion) {\n versions.push([\"koa\", koaVersion]);\n }\n if (apitallyVersion) {\n versions.push([\"apitally\", apitallyVersion]);\n }\n if (appVersion) {\n versions.push([\"app\", appVersion]);\n }\n return {\n paths: listEndpoints(app),\n versions: Object.fromEntries(versions),\n client: \"js:koa\",\n };\n}\n\nfunction isKoaRouterMiddleware(middleware: any) {\n return (\n typeof middleware === \"function\" &&\n middleware.router &&\n Array.isArray(middleware.router.stack)\n );\n}\n\nfunction listEndpoints(app: Koa) {\n const endpoints: Array<PathInfo> = [];\n app.middleware.forEach((middleware: any) => {\n if (isKoaRouterMiddleware(middleware)) {\n middleware.router.stack.forEach((layer: any) => {\n if (layer.methods && layer.methods.length > 0) {\n layer.methods.forEach((method: string) => {\n if (![\"HEAD\", \"OPTIONS\"].includes(method.toUpperCase())) {\n endpoints.push({\n method: method.toUpperCase(),\n path: layer.path,\n });\n }\n });\n }\n });\n }\n });\n return endpoints;\n}\n"],"mappings":";;AACA,SAASA,yBAAyB;AAElC,SAASC,sBAAsB;AAC/B,SAASC,kCAAkC;AAC3C,SAASC,yBAAyB;AAElC,SAASC,aAAaC,sBAAsB;AAO5C,SAASC,cAAcC,oBAAoB;AAEpC,SAASC,YAAYC,KAAUC,QAAsB;AAC1D,QAAMC,SAAS,IAAIV,eAAeS,MAAAA;AAClC,QAAME,aAAaC,cAAcF,MAAAA;AACjCF,MAAIK,IAAIF,UAAAA;AAER,QAAMG,iBAAiB,wBAACC,UAAkB,MAAC;AACzC,UAAMC,UAAUC,WAAWT,KAAKC,OAAOS,UAAU;AACjD,QAAIF,QAAQG,MAAMC,SAAS,KAAKL,WAAW,IAAI;AAC7CL,aAAOI,eAAeE,OAAAA;AACtBN,aAAOW,UAAS;IAClB,OAAO;AACLC,iBAAW,MAAMR,eAAeC,UAAU,CAAA,GAAI,GAAA;IAChD;EACF,GARuB;AASvBO,aAAW,MAAMR,eAAAA,GAAkB,GAAA;AACrC;AAfgBP;AAiBhB,SAASK,cAAcF,QAAsB;AAC3C,QAAMa,cAAc,IAAIxB,kBAAAA;AAExB,MAAIW,OAAOc,cAAcf,OAAOgB,aAAa;AAC3CpB,iBAAakB,WAAAA;AACbjB,iBAAaiB,WAAAA;EACf;AAEA,SAAO,OAAOG,KAAkBC,SAAAA;AAC9B,QAAI,CAACjB,OAAOkB,UAAS,KAAMF,IAAIG,QAAQC,OAAOC,YAAW,MAAO,WAAW;AACzE,YAAMJ,KAAAA;AACN;IACF;AAEA,UAAMJ,YAAYS,IAAI,CAAA,GAAI,YAAA;AA9C9B;AA+CM,UAAIC;AACJ,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AY;AACdmE,aAASK,KAAK;MAAC;MAAOxE;KAAW;EACnC;AACA,SAAO;IACLC,OAAOwE,cAAcnF,GAAAA;IACrB6E,UAAUO,OAAOC,YAAYR,QAAAA;IAC7B3E,QAAQ;EACV;AACF;AApBSO;AAsBT,SAAS6E,sBAAsBnF,YAAe;AAC5C,SACE,OAAOA,eAAe,cACtBA,WAAWoF,UACXC,MAAMC,QAAQtF,WAAWoF,OAAO1C,KAAK;AAEzC;AANSyC;AAQT,SAASH,cAAcnF,KAAQ;AAC7B,QAAM0F,YAA6B,CAAA;AACnC1F,MAAIG,WAAWwF,QAAQ,CAACxF,eAAAA;AACtB,QAAImF,sBAAsBnF,UAAAA,GAAa;AACrCA,iBAAWoF,OAAO1C,MAAM8C,QAAQ,CAACC,UAAAA;AAC/B,YAAIA,MAAMC,WAAWD,MAAMC,QAAQjF,SAAS,GAAG;AAC7CgF,gBAAMC,QAAQF,QAAQ,CAACrE,WAAAA;AACrB,gBAAI,CAAC;cAAC;cAAQ;cAAWwE,SAASxE,OAAOC,YAAW,CAAA,GAAK;AACvDmE,wBAAUR,KAAK;gBACb5D,QAAQA,OAAOC,YAAW;gBAC1BE,MAAMmE,MAAMnE;cACd,CAAA;YACF;UACF,CAAA;QACF;MACF,CAAA;IACF;EACF,CAAA;AACA,SAAOiE;AACT;AAnBSP;","names":["AsyncLocalStorage","ApitallyClient","consumerFromStringOrObject","getPackageVersion","convertBody","convertHeaders","patchConsole","patchWinston","useApitally","app","config","client","middleware","getMiddleware","use","setStartupData","attempt","appInfo","getAppInfo","appVersion","paths","length","startSync","setTimeout","logsContext","requestLogger","captureLogs","ctx","next","isEnabled","request","method","toUpperCase","run","path","statusCode","serverError","startTime","performance","now","error","getPath","status","Error","serverErrorCounter","addServerError","consumer","getConsumer","identifier","type","name","msg","message","traceback","stack","responseTime","consumerRegistry","addOrUpdateConsumer","requestCounter","addRequest","response","requestSize","responseSize","logger","context","enabled","logs","getStore","logRequest","timestamp","Date","url","href","headers","size","body","get","_matchedRoute","routePath","setConsumer","state","apitallyConsumer","undefined","consumerIdentifier","process","emitWarning","versions","version","replace","koaVersion","apitallyVersion","push","listEndpoints","Object","fromEntries","isKoaRouterMiddleware","router","Array","isArray","endpoints","forEach","layer","methods","includes"]}
|
|
1
|
+
{"version":3,"sources":["../../src/koa/middleware.ts"],"sourcesContent":["import Koa from \"koa\";\nimport { AsyncLocalStorage } from \"node:async_hooks\";\n\nimport { ApitallyClient } from \"../common/client.js\";\nimport { consumerFromStringOrObject } from \"../common/consumerRegistry.js\";\nimport { getPackageVersion } from \"../common/packageVersions.js\";\nimport type { LogRecord } from \"../common/requestLogger.js\";\nimport { convertBody, convertHeaders } from \"../common/requestLogger.js\";\nimport {\n ApitallyConfig,\n ApitallyConsumer,\n PathInfo,\n StartupData,\n} from \"../common/types.js\";\nimport { patchConsole, patchWinston } from \"../loggers/index.js\";\n\nexport function useApitally(app: Koa, config: ApitallyConfig) {\n const client = new ApitallyClient(config);\n const middleware = getMiddleware(client);\n app.use(middleware);\n\n const setStartupData = (attempt: number = 1) => {\n const appInfo = getAppInfo(app, config.appVersion);\n if (appInfo.paths.length > 0 || attempt >= 10) {\n client.setStartupData(appInfo);\n client.startSync();\n } else {\n setTimeout(() => setStartupData(attempt + 1), 500);\n }\n };\n setTimeout(() => setStartupData(), 500);\n}\n\nfunction getMiddleware(client: ApitallyClient) {\n const logsContext = new AsyncLocalStorage<LogRecord[]>();\n\n if (client.requestLogger.config.captureLogs) {\n patchConsole(logsContext);\n patchWinston(logsContext);\n }\n\n return async (ctx: Koa.Context, next: Koa.Next) => {\n if (!client.isEnabled() || ctx.request.method.toUpperCase() === \"OPTIONS\") {\n await next();\n return;\n }\n\n await logsContext.run([], async () => {\n let path: string | undefined;\n let statusCode: number | undefined;\n let serverError: Error | undefined;\n const startTime = performance.now();\n const spanHandle = client.spanCollector.startSpan();\n try {\n await spanHandle.runInContext(next);\n } catch (error: any) {\n path = getPath(ctx);\n statusCode = error.statusCode || error.status || 500;\n if (path && statusCode === 500 && error instanceof Error) {\n serverError = error;\n client.serverErrorCounter.addServerError({\n consumer: getConsumer(ctx)?.identifier,\n method: ctx.request.method,\n path,\n type: error.name,\n msg: error.message,\n traceback: error.stack || \"\",\n });\n }\n throw error;\n } finally {\n const responseTime = performance.now() - startTime;\n\n if (!path) {\n path = getPath(ctx);\n }\n\n spanHandle.setName(`${ctx.request.method} ${path}`);\n const spans = spanHandle.end();\n const traceId = spanHandle.traceId;\n\n const consumer = getConsumer(ctx);\n client.consumerRegistry.addOrUpdateConsumer(consumer);\n\n if (path) {\n try {\n client.requestCounter.addRequest({\n consumer: consumer?.identifier,\n method: ctx.request.method,\n path,\n statusCode: statusCode || ctx.response.status,\n responseTime,\n requestSize: ctx.request.length,\n responseSize: ctx.response.length,\n });\n } catch (error) {\n client.logger.error(\n \"Error while logging request in Apitally middleware.\",\n { context: ctx, error },\n );\n }\n }\n\n if (client.requestLogger.enabled) {\n const logs = logsContext.getStore();\n client.requestLogger.logRequest(\n {\n timestamp: Date.now() / 1000,\n method: ctx.request.method,\n path,\n url: ctx.request.href,\n headers: convertHeaders(ctx.request.headers),\n size: ctx.request.length,\n consumer: consumer?.identifier,\n body: convertBody(\n ctx.request.body,\n ctx.request.get(\"content-type\"),\n ),\n },\n {\n statusCode: statusCode || ctx.response.status,\n responseTime: responseTime / 1000,\n headers: convertHeaders(ctx.response.headers),\n size: ctx.response.length,\n body: convertBody(\n ctx.response.body,\n ctx.response.get(\"content-type\"),\n ),\n },\n serverError,\n logs,\n spans,\n traceId,\n );\n }\n }\n });\n };\n}\n\nfunction getPath(ctx: Koa.Context) {\n return ctx._matchedRoute || ctx.routePath; // _matchedRoute is set by koa-router, routePath is set by koa-route\n}\n\nexport function setConsumer(\n ctx: Koa.Context,\n consumer: ApitallyConsumer | string | null | undefined,\n) {\n ctx.state.apitallyConsumer = consumer || undefined;\n}\n\nfunction getConsumer(ctx: Koa.Context) {\n if (ctx.state.apitallyConsumer) {\n return consumerFromStringOrObject(ctx.state.apitallyConsumer);\n } else if (ctx.state.consumerIdentifier) {\n // For backwards compatibility\n process.emitWarning(\n \"The consumerIdentifier property on the ctx.state object is deprecated. Use apitallyConsumer instead.\",\n \"DeprecationWarning\",\n );\n return consumerFromStringOrObject(ctx.state.consumerIdentifier);\n }\n return null;\n}\n\nfunction getAppInfo(app: Koa, appVersion?: string): StartupData {\n const versions: Array<[string, string]> = [\n [\"nodejs\", process.version.replace(/^v/, \"\")],\n ];\n const koaVersion = getPackageVersion(\"koa\");\n const apitallyVersion = getPackageVersion(\"../..\");\n if (koaVersion) {\n versions.push([\"koa\", koaVersion]);\n }\n if (apitallyVersion) {\n versions.push([\"apitally\", apitallyVersion]);\n }\n if (appVersion) {\n versions.push([\"app\", appVersion]);\n }\n return {\n paths: listEndpoints(app),\n versions: Object.fromEntries(versions),\n client: \"js:koa\",\n };\n}\n\nfunction isKoaRouterMiddleware(middleware: any) {\n return (\n typeof middleware === \"function\" &&\n middleware.router &&\n Array.isArray(middleware.router.stack)\n );\n}\n\nfunction listEndpoints(app: Koa) {\n const endpoints: Array<PathInfo> = [];\n app.middleware.forEach((middleware: any) => {\n if (isKoaRouterMiddleware(middleware)) {\n middleware.router.stack.forEach((layer: any) => {\n if (layer.methods && layer.methods.length > 0) {\n layer.methods.forEach((method: string) => {\n if (![\"HEAD\", \"OPTIONS\"].includes(method.toUpperCase())) {\n endpoints.push({\n method: method.toUpperCase(),\n path: layer.path,\n });\n }\n });\n }\n });\n }\n });\n return endpoints;\n}\n"],"mappings":";;AACA,SAASA,yBAAyB;AAElC,SAASC,sBAAsB;AAC/B,SAASC,kCAAkC;AAC3C,SAASC,yBAAyB;AAElC,SAASC,aAAaC,sBAAsB;AAO5C,SAASC,cAAcC,oBAAoB;AAEpC,SAASC,YAAYC,KAAUC,QAAsB;AAC1D,QAAMC,SAAS,IAAIV,eAAeS,MAAAA;AAClC,QAAME,aAAaC,cAAcF,MAAAA;AACjCF,MAAIK,IAAIF,UAAAA;AAER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S6C;AAQT,SAASH,cAAc3F,KAAQ;AAC7B,QAAMkG,YAA6B,CAAA;AACnClG,MAAIG,WAAWgG,QAAQ,CAAChG,eAAAA;AACtB,QAAI2F,sBAAsB3F,UAAAA,GAAa;AACrCA,iBAAW4F,OAAO9C,MAAMkD,QAAQ,CAACC,UAAAA;AAC/B,YAAIA,MAAMC,WAAWD,MAAMC,QAAQzF,SAAS,GAAG;AAC7CwF,gBAAMC,QAAQF,QAAQ,CAAC7E,WAAAA;AACrB,gBAAI,CAAC;cAAC;cAAQ;cAAWgF,SAAShF,OAAOC,YAAW,CAAA,GAAK;AACvD2E,wBAAUR,KAAK;gBACbpE,QAAQA,OAAOC,YAAW;gBAC1BE,MAAM2E,MAAM3E;cACd,CAAA;YACF;UACF,CAAA;QACF;MACF,CAAA;IACF;EACF,CAAA;AACA,SAAOyE;AACT;AAnBSP;","names":["AsyncLocalStorage","ApitallyClient","consumerFromStringOrObject","getPackageVersion","convertBody","convertHeaders","patchConsole","patchWinston","useApitally","app","config","client","middleware","getMiddleware","use","setStartupData","attempt","appInfo","getAppInfo","appVersion","paths","length","startSync","setTimeout","logsContext","requestLogger","captureLogs","ctx","next","isEnabled","request","method","toUpperCase","run","path","statusCode","serverError","startTime","performance","now","spanHandle","spanCollector","startSpan","runInContext","error","getPath","status","Error","serverErrorCounter","addServerError","consumer","getConsumer","identifier","type","name","msg","message","traceback","stack","responseTime","setName","spans","end","traceId","consumerRegistry","addOrUpdateConsumer","requestCounter","addRequest","response","requestSize","responseSize","logger","context","enabled","logs","getStore","logRequest","timestamp","Date","url","href","headers","size","body","get","_matchedRoute","routePath","setConsumer","state","apitallyConsumer","undefined","consumerIdentifier","process","emitWarning","versions","version","replace","koaVersion","apitallyVersion","push","listEndpoints","Object","fromEntries","isKoaRouterMiddleware","router","Array","isArray","endpoints","forEach","layer","methods","includes"]}
|
|
@@ -2,6 +2,10 @@ import { AsyncLocalStorage } from 'node:async_hooks';
|
|
|
2
2
|
import { LogRecord } from '../common/requestLogger.cjs';
|
|
3
3
|
import 'node:buffer';
|
|
4
4
|
import 'node:http';
|
|
5
|
+
import '../common/spanCollector.cjs';
|
|
6
|
+
import '@opentelemetry/sdk-trace-base';
|
|
7
|
+
import '../common/logging.cjs';
|
|
8
|
+
import 'winston';
|
|
5
9
|
import '../common/tempGzipFile.cjs';
|
|
6
10
|
|
|
7
11
|
declare function patchConsole(logsContext: AsyncLocalStorage<LogRecord[]>): void;
|
|
@@ -2,6 +2,10 @@ import { AsyncLocalStorage } from 'node:async_hooks';
|
|
|
2
2
|
import { LogRecord } from '../common/requestLogger.js';
|
|
3
3
|
import 'node:buffer';
|
|
4
4
|
import 'node:http';
|
|
5
|
+
import '../common/spanCollector.js';
|
|
6
|
+
import '@opentelemetry/sdk-trace-base';
|
|
7
|
+
import '../common/logging.js';
|
|
8
|
+
import 'winston';
|
|
5
9
|
import '../common/tempGzipFile.js';
|
|
6
10
|
|
|
7
11
|
declare function patchConsole(logsContext: AsyncLocalStorage<LogRecord[]>): void;
|
package/dist/loggers/hapi.d.cts
CHANGED
|
@@ -3,6 +3,10 @@ import { AsyncLocalStorage } from 'node:async_hooks';
|
|
|
3
3
|
import { LogRecord } from '../common/requestLogger.cjs';
|
|
4
4
|
import 'node:buffer';
|
|
5
5
|
import 'node:http';
|
|
6
|
+
import '../common/spanCollector.cjs';
|
|
7
|
+
import '@opentelemetry/sdk-trace-base';
|
|
8
|
+
import '../common/logging.cjs';
|
|
9
|
+
import 'winston';
|
|
6
10
|
import '../common/tempGzipFile.cjs';
|
|
7
11
|
|
|
8
12
|
declare function handleHapiRequestEvent(event: RequestEvent, logsContext: AsyncLocalStorage<LogRecord[]>): void;
|
package/dist/loggers/hapi.d.ts
CHANGED
|
@@ -3,6 +3,10 @@ import { AsyncLocalStorage } from 'node:async_hooks';
|
|
|
3
3
|
import { LogRecord } from '../common/requestLogger.js';
|
|
4
4
|
import 'node:buffer';
|
|
5
5
|
import 'node:http';
|
|
6
|
+
import '../common/spanCollector.js';
|
|
7
|
+
import '@opentelemetry/sdk-trace-base';
|
|
8
|
+
import '../common/logging.js';
|
|
9
|
+
import 'winston';
|
|
6
10
|
import '../common/tempGzipFile.js';
|
|
7
11
|
|
|
8
12
|
declare function handleHapiRequestEvent(event: RequestEvent, logsContext: AsyncLocalStorage<LogRecord[]>): void;
|
package/dist/loggers/index.d.cts
CHANGED
|
@@ -7,5 +7,9 @@ import 'node:async_hooks';
|
|
|
7
7
|
import '../common/requestLogger.cjs';
|
|
8
8
|
import 'node:buffer';
|
|
9
9
|
import 'node:http';
|
|
10
|
+
import '../common/spanCollector.cjs';
|
|
11
|
+
import '@opentelemetry/sdk-trace-base';
|
|
12
|
+
import '../common/logging.cjs';
|
|
13
|
+
import 'winston';
|
|
10
14
|
import '../common/tempGzipFile.cjs';
|
|
11
15
|
import '@hapi/hapi';
|
package/dist/loggers/index.d.ts
CHANGED
|
@@ -7,5 +7,9 @@ import 'node:async_hooks';
|
|
|
7
7
|
import '../common/requestLogger.js';
|
|
8
8
|
import 'node:buffer';
|
|
9
9
|
import 'node:http';
|
|
10
|
+
import '../common/spanCollector.js';
|
|
11
|
+
import '@opentelemetry/sdk-trace-base';
|
|
12
|
+
import '../common/logging.js';
|
|
13
|
+
import 'winston';
|
|
10
14
|
import '../common/tempGzipFile.js';
|
|
11
15
|
import '@hapi/hapi';
|
|
@@ -2,6 +2,10 @@ import { AsyncLocalStorage } from 'node:async_hooks';
|
|
|
2
2
|
import { LogRecord } from '../common/requestLogger.cjs';
|
|
3
3
|
import 'node:buffer';
|
|
4
4
|
import 'node:http';
|
|
5
|
+
import '../common/spanCollector.cjs';
|
|
6
|
+
import '@opentelemetry/sdk-trace-base';
|
|
7
|
+
import '../common/logging.cjs';
|
|
8
|
+
import 'winston';
|
|
5
9
|
import '../common/tempGzipFile.cjs';
|
|
6
10
|
|
|
7
11
|
declare function patchNestLogger(logsContext: AsyncLocalStorage<LogRecord[]>): Promise<void>;
|
package/dist/loggers/nestjs.d.ts
CHANGED
|
@@ -2,6 +2,10 @@ import { AsyncLocalStorage } from 'node:async_hooks';
|
|
|
2
2
|
import { LogRecord } from '../common/requestLogger.js';
|
|
3
3
|
import 'node:buffer';
|
|
4
4
|
import 'node:http';
|
|
5
|
+
import '../common/spanCollector.js';
|
|
6
|
+
import '@opentelemetry/sdk-trace-base';
|
|
7
|
+
import '../common/logging.js';
|
|
8
|
+
import 'winston';
|
|
5
9
|
import '../common/tempGzipFile.js';
|
|
6
10
|
|
|
7
11
|
declare function patchNestLogger(logsContext: AsyncLocalStorage<LogRecord[]>): Promise<void>;
|
package/dist/loggers/pino.d.cts
CHANGED
|
@@ -2,6 +2,10 @@ import { AsyncLocalStorage } from 'node:async_hooks';
|
|
|
2
2
|
import { LogRecord } from '../common/requestLogger.cjs';
|
|
3
3
|
import 'node:buffer';
|
|
4
4
|
import 'node:http';
|
|
5
|
+
import '../common/spanCollector.cjs';
|
|
6
|
+
import '@opentelemetry/sdk-trace-base';
|
|
7
|
+
import '../common/logging.cjs';
|
|
8
|
+
import 'winston';
|
|
5
9
|
import '../common/tempGzipFile.cjs';
|
|
6
10
|
|
|
7
11
|
declare function patchPinoLogger(logger: any, logsContext: AsyncLocalStorage<LogRecord[]>): Promise<boolean>;
|
package/dist/loggers/pino.d.ts
CHANGED
|
@@ -2,6 +2,10 @@ import { AsyncLocalStorage } from 'node:async_hooks';
|
|
|
2
2
|
import { LogRecord } from '../common/requestLogger.js';
|
|
3
3
|
import 'node:buffer';
|
|
4
4
|
import 'node:http';
|
|
5
|
+
import '../common/spanCollector.js';
|
|
6
|
+
import '@opentelemetry/sdk-trace-base';
|
|
7
|
+
import '../common/logging.js';
|
|
8
|
+
import 'winston';
|
|
5
9
|
import '../common/tempGzipFile.js';
|
|
6
10
|
|
|
7
11
|
declare function patchPinoLogger(logger: any, logsContext: AsyncLocalStorage<LogRecord[]>): Promise<boolean>;
|
|
@@ -2,6 +2,10 @@ import { AsyncLocalStorage } from 'node:async_hooks';
|
|
|
2
2
|
import { LogRecord } from '../common/requestLogger.cjs';
|
|
3
3
|
import 'node:buffer';
|
|
4
4
|
import 'node:http';
|
|
5
|
+
import '../common/spanCollector.cjs';
|
|
6
|
+
import '@opentelemetry/sdk-trace-base';
|
|
7
|
+
import '../common/logging.cjs';
|
|
8
|
+
import 'winston';
|
|
5
9
|
import '../common/tempGzipFile.cjs';
|
|
6
10
|
|
|
7
11
|
declare function patchWinston(logsContext: AsyncLocalStorage<LogRecord[]>): Promise<void>;
|
|
@@ -2,6 +2,10 @@ import { AsyncLocalStorage } from 'node:async_hooks';
|
|
|
2
2
|
import { LogRecord } from '../common/requestLogger.js';
|
|
3
3
|
import 'node:buffer';
|
|
4
4
|
import 'node:http';
|
|
5
|
+
import '../common/spanCollector.js';
|
|
6
|
+
import '@opentelemetry/sdk-trace-base';
|
|
7
|
+
import '../common/logging.js';
|
|
8
|
+
import 'winston';
|
|
5
9
|
import '../common/tempGzipFile.js';
|
|
6
10
|
|
|
7
11
|
declare function patchWinston(logsContext: AsyncLocalStorage<LogRecord[]>): Promise<void>;
|
package/dist/nestjs/index.cjs
CHANGED
|
@@ -29,12 +29,14 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
|
|
|
29
29
|
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
30
30
|
var nestjs_exports = {};
|
|
31
31
|
__export(nestjs_exports, {
|
|
32
|
+
ApitallySpanProcessor: () => import_spanCollector.ApitallySpanProcessor,
|
|
32
33
|
setConsumer: () => setConsumer,
|
|
33
34
|
useApitally: () => useApitally
|
|
34
35
|
});
|
|
35
36
|
module.exports = __toCommonJS(nestjs_exports);
|
|
36
37
|
var import_common = require("@nestjs/common");
|
|
37
38
|
var import_rxjs = require("rxjs");
|
|
39
|
+
var import_spanCollector = require("../common/spanCollector.js");
|
|
38
40
|
var _a;
|
|
39
41
|
function _ts_decorate(decorators, target, key, desc) {
|
|
40
42
|
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
|
|
@@ -99,6 +101,7 @@ ApitallyInterceptor = _ts_decorate([
|
|
|
99
101
|
], ApitallyInterceptor);
|
|
100
102
|
// Annotate the CommonJS export names for ESM import in node:
|
|
101
103
|
0 && (module.exports = {
|
|
104
|
+
ApitallySpanProcessor,
|
|
102
105
|
setConsumer,
|
|
103
106
|
useApitally
|
|
104
107
|
});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/nestjs/index.ts"],"sourcesContent":["import {\n CallHandler,\n ExecutionContext,\n INestApplication,\n Injectable,\n NestInterceptor,\n} from \"@nestjs/common\";\nimport { catchError, throwError } from \"rxjs\";\n\nimport type { ApitallyConfig, ApitallyConsumer } from \"../common/types.js\";\nexport type { ApitallyConfig, ApitallyConsumer } from \"../common/types.js\";\n\nlet setConsumerFn:\n | ((\n request: any,\n consumer: ApitallyConsumer | string | null | undefined,\n ) => void)\n | null = null;\n\nexport async function useApitally(\n app: INestApplication,\n config: ApitallyConfig,\n) {\n const httpAdapter = app.getHttpAdapter();\n const instance = httpAdapter.getInstance();\n const platform = httpAdapter.constructor.name\n .toLowerCase()\n .includes(\"fastify\")\n ? \"fastify\"\n : \"express\";\n\n if (platform === \"express\") {\n const { useApitally, setConsumer } = await import(\"../express/index.js\");\n setConsumerFn = setConsumer;\n useApitally(instance, config);\n } else if (platform === \"fastify\") {\n const { apitallyPlugin, setConsumer } = await import(\"../fastify/index.js\");\n setConsumerFn = setConsumer;\n await instance.register(apitallyPlugin, config);\n }\n\n app.useGlobalInterceptors(new ApitallyInterceptor(platform));\n}\n\nexport function setConsumer(\n request: any,\n consumer: ApitallyConsumer | string | null | undefined,\n) {\n if (setConsumerFn) {\n setConsumerFn(request, consumer);\n }\n}\n\n@Injectable()\nclass ApitallyInterceptor implements NestInterceptor {\n constructor(private readonly platform: \"express\" | \"fastify\") {}\n\n intercept(context: ExecutionContext, next: CallHandler) {\n return next.handle().pipe(\n catchError((exception) => {\n if (context.getType() === \"http\") {\n const ctx = context.switchToHttp();\n const res = ctx.getResponse();\n\n if (this.platform === \"express\" && res.locals) {\n res.locals.serverError = exception;\n } else if (\n this.platform === \"fastify\" &&\n (!exception.statusCode || exception.statusCode === 500)\n ) {\n res.serverError = exception;\n }\n }\n return throwError(() => exception);\n }),\n );\n }\n}\n"],"mappings":"
|
|
1
|
+
{"version":3,"sources":["../../src/nestjs/index.ts"],"sourcesContent":["import {\n CallHandler,\n ExecutionContext,\n INestApplication,\n Injectable,\n NestInterceptor,\n} from \"@nestjs/common\";\nimport { catchError, throwError } from \"rxjs\";\n\nimport type { ApitallyConfig, ApitallyConsumer } from \"../common/types.js\";\nexport { ApitallySpanProcessor } from \"../common/spanCollector.js\";\nexport type { ApitallyConfig, ApitallyConsumer } from \"../common/types.js\";\n\nlet setConsumerFn:\n | ((\n request: any,\n consumer: ApitallyConsumer | string | null | undefined,\n ) => void)\n | null = null;\n\nexport async function useApitally(\n app: INestApplication,\n config: ApitallyConfig,\n) {\n const httpAdapter = app.getHttpAdapter();\n const instance = httpAdapter.getInstance();\n const platform = httpAdapter.constructor.name\n .toLowerCase()\n .includes(\"fastify\")\n ? \"fastify\"\n : \"express\";\n\n if (platform === \"express\") {\n const { useApitally, setConsumer } = await import(\"../express/index.js\");\n setConsumerFn = setConsumer;\n useApitally(instance, config);\n } else if (platform === \"fastify\") {\n const { apitallyPlugin, setConsumer } = await import(\"../fastify/index.js\");\n setConsumerFn = setConsumer;\n await instance.register(apitallyPlugin, config);\n }\n\n app.useGlobalInterceptors(new ApitallyInterceptor(platform));\n}\n\nexport function setConsumer(\n request: any,\n consumer: ApitallyConsumer | string | null | undefined,\n) {\n if (setConsumerFn) {\n setConsumerFn(request, consumer);\n }\n}\n\n@Injectable()\nclass ApitallyInterceptor implements NestInterceptor {\n constructor(private readonly platform: \"express\" | \"fastify\") {}\n\n intercept(context: ExecutionContext, next: CallHandler) {\n return next.handle().pipe(\n catchError((exception) => {\n if (context.getType() === \"http\") {\n const ctx = context.switchToHttp();\n const res = ctx.getResponse();\n\n if (this.platform === \"express\" && res.locals) {\n res.locals.serverError = exception;\n } else if (\n this.platform === \"fastify\" &&\n (!exception.statusCode || exception.statusCode === 500)\n ) {\n res.serverError = exception;\n }\n }\n return throwError(() => exception);\n }),\n );\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,oBAMO;AACP,kBAAuC;AAGvC,2BAAsC;;;;;;;;;;;;;AAGtC,IAAIA,gBAKO;AAEX,eAAsBC,YACpBC,KACAC,QAAsB;AAEtB,QAAMC,cAAcF,IAAIG,eAAc;AACtC,QAAMC,WAAWF,YAAYG,YAAW;AACxC,QAAMC,WAAWJ,YAAY,YAAYK,KACtCC,YAAW,EACXC,SAAS,SAAA,IACR,YACA;AAEJ,MAAIH,aAAa,WAAW;AAC1B,UAAM,EAAEP,aAAAA,cAAaW,aAAAA,aAAW,IAAK,MAAM,OAAO,qBAAA;AAClDZ,oBAAgBY;AAChBX,IAAAA,aAAYK,UAAUH,MAAAA;EACxB,WAAWK,aAAa,WAAW;AACjC,UAAM,EAAEK,gBAAgBD,aAAAA,aAAW,IAAK,MAAM,OAAO,qBAAA;AACrDZ,oBAAgBY;AAChB,UAAMN,SAASQ,SAASD,gBAAgBV,MAAAA;EAC1C;AAEAD,MAAIa,sBAAsB,IAAIC,oBAAoBR,QAAAA,CAAAA;AACpD;AAvBsBP;AAyBf,SAASW,YACdK,SACAC,UAAsD;AAEtD,MAAIlB,eAAe;AACjBA,kBAAciB,SAASC,QAAAA;EACzB;AACF;AAPgBN;AAShB,IACMI,uBADN,WACMA;;EACJ,YAA6BR,UAAiC;SAAjCA,WAAAA;EAAkC;EAE/DW,UAAUC,SAA2BC,MAAmB;AACtD,WAAOA,KAAKC,OAAM,EAAGC,SACnBC,wBAAW,CAACC,cAAAA;AACV,UAAIL,QAAQM,QAAO,MAAO,QAAQ;AAChC,cAAMC,MAAMP,QAAQQ,aAAY;AAChC,cAAMC,MAAMF,IAAIG,YAAW;AAE3B,YAAI,KAAKtB,aAAa,aAAaqB,IAAIE,QAAQ;AAC7CF,cAAIE,OAAOC,cAAcP;QAC3B,WACE,KAAKjB,aAAa,cACjB,CAACiB,UAAUQ,cAAcR,UAAUQ,eAAe,MACnD;AACAJ,cAAIG,cAAcP;QACpB;MACF;AACA,iBAAOS,wBAAW,MAAMT,SAAAA;IAC1B,CAAA,CAAA;EAEJ;AACF,GAvBMT,mCADN;;;;;;;;","names":["setConsumerFn","useApitally","app","config","httpAdapter","getHttpAdapter","instance","getInstance","platform","name","toLowerCase","includes","setConsumer","apitallyPlugin","register","useGlobalInterceptors","ApitallyInterceptor","request","consumer","intercept","context","next","handle","pipe","catchError","exception","getType","ctx","switchToHttp","res","getResponse","locals","serverError","statusCode","throwError"]}
|
package/dist/nestjs/index.d.cts
CHANGED
|
@@ -1,11 +1,13 @@
|
|
|
1
1
|
import { INestApplication } from '@nestjs/common';
|
|
2
2
|
import { ApitallyConfig, ApitallyConsumer } from '../common/types.cjs';
|
|
3
|
+
export { ApitallySpanProcessor } from '../common/spanCollector.cjs';
|
|
3
4
|
import '../common/logging.cjs';
|
|
4
5
|
import 'winston';
|
|
5
6
|
import '../common/requestLogger.cjs';
|
|
6
7
|
import 'node:buffer';
|
|
7
8
|
import 'node:http';
|
|
8
9
|
import '../common/tempGzipFile.cjs';
|
|
10
|
+
import '@opentelemetry/sdk-trace-base';
|
|
9
11
|
|
|
10
12
|
declare function useApitally(app: INestApplication, config: ApitallyConfig): Promise<void>;
|
|
11
13
|
declare function setConsumer(request: any, consumer: ApitallyConsumer | string | null | undefined): void;
|