@burdenoff/be-sdk 2026.1110.3 → 2026.1111.1
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/activity/index.d.ts +165 -0
- package/dist/activity/index.js +389 -0
- package/dist/activity/index.js.map +1 -0
- package/dist/ai-credits/index.js +1 -1
- package/dist/{ai-credits-Ca-NNcVx.js → ai-credits-xxfwGpHS.js} +2 -2
- package/dist/{ai-credits-Ca-NNcVx.js.map → ai-credits-xxfwGpHS.js.map} +1 -1
- package/dist/auth/index.d.ts +1 -1
- package/dist/auth/index.js +1 -1
- package/dist/{auth-CEuBEBQN.js → auth-C5ctwSLp.js} +2 -2
- package/dist/{auth-CEuBEBQN.js.map → auth-C5ctwSLp.js.map} +1 -1
- package/dist/bootstrap/index.d.ts +74 -0
- package/dist/bootstrap/index.js +282 -0
- package/dist/bootstrap/index.js.map +1 -0
- package/dist/{client-DcZ3iGES.js → client-sAJTrb4i.js} +2 -2
- package/dist/{client-DcZ3iGES.js.map → client-sAJTrb4i.js.map} +1 -1
- package/dist/context/index.d.ts +35 -0
- package/dist/{context-CZnXf2yb.js → context/index.js} +38 -2
- package/dist/context/index.js.map +1 -0
- package/dist/database/index.js +1 -1
- package/dist/event-queue/index.d.ts +1 -1
- package/dist/explicit-activity-scope-DikJ7NAE.js +57 -0
- package/dist/explicit-activity-scope-DikJ7NAE.js.map +1 -0
- package/dist/export/index.js +1 -1
- package/dist/{export-B6fphx8a.js → export-DJXE3Osa.js} +3 -3
- package/dist/{export-B6fphx8a.js.map → export-DJXE3Osa.js.map} +1 -1
- package/dist/feature-flags/index.js +1 -1
- package/dist/{feature-flags-71oDkrUe.js → feature-flags-CP1KRgwD.js} +2 -2
- package/dist/{feature-flags-71oDkrUe.js.map → feature-flags-CP1KRgwD.js.map} +1 -1
- package/dist/files/index.js +1 -1
- package/dist/{files-DjH0099H.js → files-h5U-D2AF.js} +2 -2
- package/dist/{files-DjH0099H.js.map → files-h5U-D2AF.js.map} +1 -1
- package/dist/gateway/index.js +2 -2
- package/dist/{gateway-DBFmxWks.js → gateway-ByVo-n37.js} +2 -2
- package/dist/{gateway-DBFmxWks.js.map → gateway-ByVo-n37.js.map} +1 -1
- package/dist/graph/index.d.ts +1 -1
- package/dist/graph/index.js +1 -1
- package/dist/{graph-DDYgIryR.js → graph-CR7u4lpl.js} +2 -2
- package/dist/{graph-DDYgIryR.js.map → graph-CR7u4lpl.js.map} +1 -1
- package/dist/{graphql-DNkMkGBZ.d.ts → graphql-CUDyhibV.d.ts} +1 -1
- package/dist/{index-bZKZUvBu.d.ts → index-ADmsX0BI.d.ts} +3 -3
- package/dist/{index-BqYfCQSP.d.ts → index-B2LCaK0R.d.ts} +1 -1
- package/dist/{index-D6UeLAye.d.ts → index-CHwMhK6v.d.ts} +2 -2
- package/dist/{index-BQDsNAMR.d.ts → index-CTTwo9av.d.ts} +22 -1
- package/dist/{index-DZC-2o9R.d.ts → index-CVCyKzhB.d.ts} +2 -2
- package/dist/{index-CkT2aUr3.d.ts → index-C_GXXF32.d.ts} +2 -2
- package/dist/{index-BKwHQtHQ.d.ts → index-Cot73bdh.d.ts} +1 -1
- package/dist/{index-CnzbJZP7.d.ts → index-FRRaa6h2.d.ts} +2 -2
- package/dist/{index-N-huORcj.d.ts → index-U_tu3zUl.d.ts} +2 -2
- package/dist/index-cmR9k9ga.d.ts +26 -0
- package/dist/{index-CZTnQIRU.d.ts → index-zd_NPGJo.d.ts} +6 -141
- package/dist/index.d.ts +19 -479
- package/dist/index.js +22 -1492
- package/dist/index.js.map +1 -1
- package/dist/init/index.js +1 -1
- package/dist/{init-Dy3KhT6Y.js → init-CQPFmOOe.js} +3 -3
- package/dist/{init-Dy3KhT6Y.js.map → init-CQPFmOOe.js.map} +1 -1
- package/dist/instrumentation/index.d.ts +2 -2
- package/dist/logger/index.d.ts +1 -1
- package/dist/notifications/index.d.ts +1 -1
- package/dist/notifications/index.js +1 -1
- package/dist/{notifications-CdETrtFK.js → notifications-DY_i37WN.js} +2 -2
- package/dist/{notifications-CdETrtFK.js.map → notifications-DY_i37WN.js.map} +1 -1
- package/dist/payments/index.d.ts +144 -0
- package/dist/payments/index.js +404 -0
- package/dist/payments/index.js.map +1 -0
- package/dist/rate-limit-CBrK_U5H.js +142 -0
- package/dist/rate-limit-CBrK_U5H.js.map +1 -0
- package/dist/rbac/index.d.ts +1 -1
- package/dist/rbac/index.js +1 -1
- package/dist/{rbac-BB9l9Xph.js → rbac-Dvz0YzEt.js} +2 -2
- package/dist/{rbac-BB9l9Xph.js.map → rbac-Dvz0YzEt.js.map} +1 -1
- package/dist/resource-caps/index.d.ts +1 -1
- package/dist/{sdk-Dju9o-sq.js → sdk-B62itAH1.js} +11 -10
- package/dist/sdk-B62itAH1.js.map +1 -0
- package/dist/search/index.d.ts +112 -0
- package/dist/search/index.js +266 -0
- package/dist/search/index.js.map +1 -0
- package/dist/security/index.d.ts +2 -0
- package/dist/security/index.js +4 -0
- package/dist/security/index.js.map +1 -0
- package/dist/security/rate-limit/index.d.ts +2 -0
- package/dist/security/rate-limit/index.js +4 -0
- package/dist/security/rate-limit/index.js.map +1 -0
- package/dist/server/index.js +3 -2
- package/dist/server/index.js.map +1 -1
- package/dist/{stub-BqwKn4eh.js → stub-BUnfMiAS.js} +3 -56
- package/dist/stub-BUnfMiAS.js.map +1 -0
- package/dist/tags/index.js +1 -1
- package/dist/{tags-B5xpbgsk.js → tags-CbijgoqR.js} +2 -2
- package/dist/{tags-B5xpbgsk.js.map → tags-CbijgoqR.js.map} +1 -1
- package/dist/telemetry/index.d.ts +6 -3
- package/dist/telemetry/index.js +3 -2
- package/dist/telemetry/index.js.map +1 -1
- package/dist/tracker/index.d.ts +2 -2
- package/dist/tracker/index.js +5 -3
- package/dist/{tracker-BQVoEFUo.js → tracker-PQztSlhJ.js} +9 -390
- package/dist/tracker-PQztSlhJ.js.map +1 -0
- package/dist/translation/index.d.ts +120 -0
- package/dist/translation/index.js +573 -0
- package/dist/translation/index.js.map +1 -0
- package/dist/types/index.d.ts +3 -0
- package/dist/{types-Cj2RWXbz.js → types/index.js} +3 -3
- package/dist/types/index.js.map +1 -0
- package/dist/usage/index.d.ts +1 -1
- package/dist/usage/index.js +1 -1
- package/dist/{usage-BKFZiWQn.js → usage-BRqVP3CJ.js} +4 -4
- package/dist/{usage-BKFZiWQn.js.map → usage-BRqVP3CJ.js.map} +1 -1
- package/package.json +1 -1
- package/dist/context-CZnXf2yb.js.map +0 -1
- package/dist/sdk-Dju9o-sq.js.map +0 -1
- package/dist/stub-BqwKn4eh.js.map +0 -1
- package/dist/tracker-BQVoEFUo.js.map +0 -1
- package/dist/types-Cj2RWXbz.js.map +0 -1
package/dist/telemetry/index.js
CHANGED
|
@@ -348,7 +348,7 @@ async function bootstrapTelemetry(cfg) {
|
|
|
348
348
|
if (resolveOtelSdkEnabled()) {
|
|
349
349
|
console.log("[telemetry] OTel SDK bootstrap starting...");
|
|
350
350
|
try {
|
|
351
|
-
const { createOtelSdk } = await import("../sdk-
|
|
351
|
+
const { createOtelSdk } = await import("../sdk-B62itAH1.js");
|
|
352
352
|
otelSdk = await createOtelSdk({
|
|
353
353
|
serviceName: cfg.serviceName,
|
|
354
354
|
serviceVersion,
|
|
@@ -357,7 +357,8 @@ async function bootstrapTelemetry(cfg) {
|
|
|
357
357
|
env,
|
|
358
358
|
otlpEndpoint,
|
|
359
359
|
sampleRatio,
|
|
360
|
-
...cfg.idGenerator ? { idGenerator: cfg.idGenerator } : {}
|
|
360
|
+
...cfg.idGenerator ? { idGenerator: cfg.idGenerator } : {},
|
|
361
|
+
...cfg.otelModules ? { modules: cfg.otelModules } : {}
|
|
361
362
|
});
|
|
362
363
|
logger$1.info("[telemetry] OpenTelemetry exporter pipeline started", {
|
|
363
364
|
serviceName: cfg.serviceName,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["BaseLogger","anyApi","logger"],"sources":["../../src/telemetry/id-generator.ts","../../src/telemetry/health.ts","../../src/telemetry/metrics-endpoint.ts","../../src/telemetry/prisma-logging.ts","../../src/telemetry/pino-redaction.ts","../../src/telemetry/pino-logger.ts","../../src/telemetry/index.ts"],"sourcesContent":["/**\n * Custom trace/span id generation for `bootstrapTelemetry`.\n *\n * `@opentelemetry/sdk-node` accepts an `idGenerator` that the tracer provider\n * uses for every new trace id and span id. Services pass one when they need\n * span ids that are derived rather than random — for example, a workflow run\n * that executes across many jobs and pods but must surface as one trace with a\n * single, deterministic `workflow.run` parent span.\n *\n * The interface below is a structural twin of `IdGenerator` from\n * `@opentelemetry/sdk-trace-base`, declared here so the SDK's public types do\n * not require that optional peer dependency to be installed. Any\n * `IdGenerator` implementation (including `RandomIdGenerator`) satisfies it.\n */\n\nexport interface TelemetryIdGenerator {\n /** Returns a trace id: 32 lowercase hex characters (16 bytes), not all zero. */\n generateTraceId(): string;\n /** Returns a span id: 16 lowercase hex characters (8 bytes), not all zero. */\n generateSpanId(): string;\n}\n\n/**\n * Validate a caller-supplied id generator before it reaches the OTel SDK.\n *\n * A generator without both methods would make the tracer provider throw on\n * the first span, long after startup. Failing at bootstrap instead surfaces\n * the misconfiguration where it was made. `undefined` is accepted and means\n * \"use the SDK's default random generator\".\n */\nexport function assertTelemetryIdGenerator(candidate: unknown): asserts candidate is TelemetryIdGenerator | undefined {\n if (candidate === undefined) return;\n if (typeof candidate !== 'object' || candidate === null) {\n throw new TypeError('bootstrapTelemetry: idGenerator must be an object with generateTraceId and generateSpanId');\n }\n const { generateTraceId, generateSpanId } = candidate as {\n generateTraceId?: unknown;\n generateSpanId?: unknown;\n };\n if (typeof generateTraceId !== 'function' || typeof generateSpanId !== 'function') {\n throw new TypeError('bootstrapTelemetry: idGenerator must implement both generateTraceId() and generateSpanId()');\n }\n}\n","/**\n * `/health`, `/health/live`, `/health/ready` Elysia routes with a 1s\n * result cache so readiness checks can't stampede Postgres.\n *\n * Dependencies (prisma, eventQueue, valkey) are optional — omit any client and\n * the readiness check simply skips it.\n */\n\ninterface PrismaLike {\n $queryRaw: (strings: TemplateStringsArray) => Promise<unknown>;\n}\ninterface EventQueueLike {\n isConnected?: () => boolean | Promise<boolean>;\n healthCheck?: () => Promise<{ ok: boolean }>;\n}\ninterface ValkeyLike {\n ping: () => Promise<unknown>;\n}\n\nexport interface HealthDeps {\n prisma?: PrismaLike;\n eventQueue?: EventQueueLike;\n valkey?: ValkeyLike;\n /** Service version reported on /health. */\n version?: string;\n /** Service name reported on /health. */\n serviceName?: string;\n}\n\ninterface CachedStatus {\n ready: boolean;\n checked: Record<string, { ok: boolean; error?: string }>;\n at: number;\n}\n\nconst CACHE_TTL_MS = 1000;\n\nasync function probeReady(deps: HealthDeps): Promise<CachedStatus> {\n const checked: Record<string, { ok: boolean; error?: string }> = {};\n\n if (deps.prisma) {\n try {\n await deps.prisma.$queryRaw`SELECT 1`;\n checked['postgres'] = { ok: true };\n } catch (err) {\n checked['postgres'] = {\n ok: false,\n error: err instanceof Error ? err.message : String(err),\n };\n }\n }\n\n if (deps.eventQueue) {\n try {\n const connected =\n typeof deps.eventQueue.isConnected === 'function'\n ? await Promise.resolve(deps.eventQueue.isConnected())\n : ((await deps.eventQueue.healthCheck?.())?.ok ?? true);\n checked['eventQueue'] = { ok: Boolean(connected) };\n } catch (err) {\n checked['eventQueue'] = {\n ok: false,\n error: err instanceof Error ? err.message : String(err),\n };\n }\n }\n\n if (deps.valkey) {\n try {\n await deps.valkey.ping();\n checked['valkey'] = { ok: true };\n } catch (err) {\n checked['valkey'] = {\n ok: false,\n error: err instanceof Error ? err.message : String(err),\n };\n }\n }\n\n const ready = Object.values(checked).every((c) => c.ok);\n return { ready, checked, at: Date.now() };\n}\n\nexport function createHealthRoutes(_deps: HealthDeps = {}): unknown {\n // Return an Elysia app lazily so be-sdk doesn't hard-require elysia.\n return new Proxy(\n {},\n {\n get(_target, prop): unknown {\n // Tell TypeScript consumers the returned object is an Elysia plugin;\n // the actual mount happens via `createHealthRoutesImpl`. Services\n // that prefer direct use can call `createHealthRoutesImpl(elysia, deps)`.\n if (prop === 'use' || prop === 'then') return undefined;\n return undefined;\n },\n }\n );\n}\n\n/**\n * Mount health routes on an existing Elysia app. Callers hold a reference\n * to Elysia themselves; be-sdk stays decoupled.\n */\nexport function createHealthRoutesImpl<\n App extends {\n get: (path: string, handler: (ctx: unknown) => unknown) => App;\n },\n>(app: App, deps: HealthDeps = {}): App {\n let cache: CachedStatus | null = null;\n\n const getStatus = async (): Promise<CachedStatus> => {\n if (cache && Date.now() - cache.at < CACHE_TTL_MS) return cache;\n cache = await probeReady(deps);\n return cache;\n };\n\n app.get('/health/live', () => ({\n status: 'ok',\n serviceName: deps.serviceName,\n version: deps.version,\n }));\n\n app.get('/health/ready', async (ctx: unknown): Promise<unknown> => {\n const status = await getStatus();\n const ctxWithSet = ctx as { set?: { status?: number } };\n if (!status.ready && ctxWithSet.set) ctxWithSet.set.status = 503;\n return {\n status: status.ready ? 'ok' : 'degraded',\n serviceName: deps.serviceName,\n version: deps.version,\n checks: status.checked,\n };\n });\n\n app.get('/health', async (ctx: unknown): Promise<unknown> => {\n const status = await getStatus();\n const ctxWithSet = ctx as { set?: { status?: number } };\n if (!status.ready && ctxWithSet.set) ctxWithSet.set.status = 503;\n return {\n status: status.ready ? 'ok' : 'degraded',\n serviceName: deps.serviceName,\n version: deps.version,\n checks: status.checked,\n uptime_s: Math.round(process.uptime()),\n };\n });\n\n return app;\n}\n","/**\n * Prometheus `/metrics` route mounter. Uses the shared `prom-client`\n * default registry so all instrumentation (GraphQL Envelop, Prisma,\n * runtime) shows up on a single endpoint.\n */\n\ninterface PromRegistryLike {\n metrics: () => Promise<string> | string;\n contentType?: string;\n}\n\nexport interface MetricsMountOptions {\n registry?: PromRegistryLike;\n path?: string;\n}\n\nexport async function loadDefaultRegistry(): Promise<PromRegistryLike | null> {\n try {\n const mod = (await import('prom-client')) as unknown as {\n register: PromRegistryLike;\n collectDefaultMetrics: (opts?: Record<string, unknown>) => void;\n };\n // Kick runtime metrics into the default registry if not already.\n try {\n mod.collectDefaultMetrics({ register: mod.register });\n } catch {\n // Already registered — ignore duplicate-metric errors.\n }\n return mod.register;\n } catch {\n return null;\n }\n}\n\nexport function createMetricsRoutesImpl<\n App extends {\n get: (path: string, handler: (ctx: unknown) => unknown) => App;\n },\n>(app: App, opts: MetricsMountOptions = {}): App {\n const path = opts.path ?? '/metrics';\n\n app.get(path, async (ctx: unknown): Promise<unknown> => {\n const registry = opts.registry ?? (await loadDefaultRegistry());\n const ctxWithSet = ctx as { set?: { status?: number; headers?: Record<string, string> } };\n if (!registry) {\n if (ctxWithSet.set) ctxWithSet.set.status = 503;\n return '# prom-client not installed\\n';\n }\n if (ctxWithSet.set) {\n ctxWithSet.set.status = 200;\n ctxWithSet.set.headers = {\n 'content-type': registry.contentType ?? 'text/plain; version=0.0.4; charset=utf-8',\n };\n }\n return registry.metrics();\n });\n\n return app;\n}\n\n/**\n * Legacy export name used by the service template. Composes the Elysia\n * plugin-style function that `new Elysia().use(...)` accepts.\n */\nexport function createMetricsRoutes(opts: MetricsMountOptions = {}): unknown {\n return (app: Parameters<typeof createMetricsRoutesImpl>[0]): unknown => createMetricsRoutesImpl(app, opts);\n}\n","/**\n * Prisma client extension that pipes query events through the SDK logger\n * with trace/span correlation fields auto-injected. The\n * `@prisma/instrumentation` peer provides the spans\n * themselves; this extension only adds structured log events on top.\n */\nimport type { Logger } from '../logger/index.js';\nimport { redactSensitiveFields } from '../logger/index.js';\n\ntype PrismaQueryArgs = {\n model?: string;\n operation: string;\n args: unknown;\n query: (args: unknown) => Promise<unknown>;\n};\n\n/**\n * Returns a Prisma Client extension object compatible with the\n * `$extends()` API (Prisma v5+).\n *\n * ```ts\n * export const prisma = new PrismaClient().$extends(\n * createPrismaLoggingExtension(logger)\n * );\n * ```\n */\nexport function createPrismaLoggingExtension(logger: Logger): {\n name: string;\n query: {\n $allOperations: (args: PrismaQueryArgs) => Promise<unknown>;\n };\n} {\n return {\n name: 'burdenoff-pino-logging',\n query: {\n async $allOperations({ model, operation, args, query }: PrismaQueryArgs): Promise<unknown> {\n const start = Date.now();\n try {\n const result = await query(args);\n logger.debug('prisma.query', {\n model,\n operation,\n duration_ms: Date.now() - start,\n args: redactSensitiveFields(args),\n });\n return result;\n } catch (err) {\n logger.error('prisma.error', {\n model,\n operation,\n duration_ms: Date.now() - start,\n error: err instanceof Error ? err.message : String(err),\n });\n throw err;\n }\n },\n },\n };\n}\n","/**\n * Default Pino redact paths — covers the Burdenoff authorization +\n * gateway header + NATS/GraphQL payload surface area.\n *\n * Services can extend this list via their own Pino options.\n */\nexport const DEFAULT_REDACT_PATHS: readonly string[] = Object.freeze([\n 'password',\n '*.password',\n '*.*.password',\n 'token',\n 'authToken',\n 'workspaceToken',\n 'accessToken',\n 'refreshToken',\n 'clientSecret',\n 'apiKey',\n '*.apiKey',\n 'authorization',\n 'req.headers.authorization',\n 'req.headers[\"x-workspace-authorization\"]',\n 'req.headers.cookie',\n 'res.headers[\"set-cookie\"]',\n 'params.*.password',\n 'params.*.token',\n 'params.*.secret',\n]);\n","/**\n * Pino logger wrapper that emits structured JSON with trace/span correlation\n * fields. Falls back to the SDK's built-in Logger when `pino` isn't installed\n * so services without the peer dep still compile and run.\n *\n * # ACA stdout compatibility\n *\n * In Azure Container Apps the ContainerAppConsoleLogs agent captures\n * `console.log` / `process.stdout.write` output but does *not* reliably\n * capture Pino's default async sonic-boom destination (which writes to fd 1\n * through Node.js `fs.writeSync` / `fs.write`). This means every log line\n * produced through Pino's default destination is invisible in Log Analytics.\n *\n * The fix mirrors what the gateway's own `logger.ts` does in production:\n * pass `pino.destination({ sync: true })` as the second argument to the\n * Pino factory so writes are synchronous and go through a path that ACA\n * captures correctly.\n */\nimport { Logger as BaseLogger } from '../logger/index.js';\nimport { DEFAULT_REDACT_PATHS } from './pino-redaction.js';\n\nexport interface PinoLoggerConfig {\n serviceName: string;\n env: 'alpha' | 'prod' | 'dev';\n version: string;\n /** Override Pino log level. Default: warn (prod), info (alpha/dev). */\n level?: 'fatal' | 'error' | 'warn' | 'info' | 'debug' | 'trace';\n /** Extra redact paths appended to DEFAULT_REDACT_PATHS. */\n redactPaths?: string[];\n}\n\ninterface PinoLike {\n level: string;\n fatal: (...args: unknown[]) => void;\n error: (...args: unknown[]) => void;\n warn: (...args: unknown[]) => void;\n info: (...args: unknown[]) => void;\n debug: (...args: unknown[]) => void;\n trace: (...args: unknown[]) => void;\n child: (bindings: Record<string, unknown>) => PinoLike;\n}\n\n/**\n * Loaded Pino module: factory function + a synchronous destination factory.\n * In ACA, Pino's default async sonic-boom destination is invisible in Log\n * Analytics, so we always use a sync destination.\n */\ninterface PinoLoader {\n factory: (opts: unknown, dest?: unknown) => PinoLike;\n makeDest: () => unknown;\n}\n\nasync function tryLoadPino(): Promise<PinoLoader | null> {\n try {\n const mod = (await import('pino')) as unknown as { default?: unknown };\n const candidate = (mod.default ?? mod) as unknown;\n if (typeof candidate === 'function') {\n const factory = candidate as (opts: unknown, dest?: unknown) => PinoLike;\n const destination = (factory as unknown as Record<string, unknown>)?.['destination'] as\n ((opts?: { sync?: boolean }) => unknown) | undefined;\n const makeDest = typeof destination === 'function' ? () => destination({ sync: true }) : () => undefined;\n return { factory, makeDest };\n }\n return null;\n } catch {\n return null;\n }\n}\n\nclass PinoAdapter extends BaseLogger {\n constructor(private readonly pino: PinoLike) {\n super({\n level: (pino.level as BaseLogger['getLevel'] extends () => infer L ? L : never) ?? 'info',\n console: false,\n });\n }\n\n public override debug(message: string, ...args: unknown[]): void {\n this.pino.debug(this.mergeArgs(args), message);\n }\n public override info(message: string, ...args: unknown[]): void {\n this.pino.info(this.mergeArgs(args), message);\n }\n public override warn(message: string, ...args: unknown[]): void {\n this.pino.warn(this.mergeArgs(args), message);\n }\n public override error(message: string, ...args: unknown[]): void {\n this.pino.error(this.mergeArgs(args), message);\n }\n public override log(message: string, ...args: unknown[]): void {\n this.pino.info(this.mergeArgs(args), message);\n }\n public override trace(message: string, ...args: unknown[]): void {\n this.pino.trace(this.mergeArgs(args), message);\n }\n\n private mergeArgs(args: unknown[]): Record<string, unknown> {\n const out: Record<string, unknown> = {};\n for (const arg of args) {\n if (arg instanceof Error) {\n out['err'] = { message: arg.message, stack: arg.stack, name: arg.name };\n } else if (arg && typeof arg === 'object') {\n Object.assign(out, arg as Record<string, unknown>);\n } else if (arg !== undefined && arg !== null) {\n out['data'] = arg;\n }\n }\n return out;\n }\n}\n\n/**\n * Build a logger instance. Returns a Pino-backed adapter when `pino` is\n * installed; otherwise falls back to the SDK's built-in JSON Logger.\n *\n * Services call this through `bootstrapTelemetry`, not directly.\n */\nexport async function createPinoLogger(cfg: PinoLoggerConfig): Promise<BaseLogger> {\n const loader = await tryLoadPino();\n if (!loader) {\n // No pino — fall back to the built-in Logger with console output.\n const fallback = new BaseLogger({ level: cfg.env === 'prod' ? 'warn' : 'info', console: true });\n fallback.setContext({\n service: cfg.serviceName,\n env: cfg.env,\n version: cfg.version,\n });\n return fallback;\n }\n\n const redactPaths = [...DEFAULT_REDACT_PATHS, ...(cfg.redactPaths ?? [])];\n const dest = loader.makeDest();\n const pino = loader.factory(\n {\n name: cfg.serviceName,\n level: cfg.level ?? (cfg.env === 'prod' ? 'warn' : 'info'),\n base: {\n service: { name: cfg.serviceName, version: cfg.version },\n env: cfg.env,\n },\n redact: {\n paths: redactPaths,\n censor: '[REDACTED]',\n remove: false,\n },\n timestamp: () => `,\"time\":\"${new Date().toISOString()}\"`,\n mixin: () => pickTraceFields(),\n },\n // Explicit sync destination so output is visible in ACA Log Analytics.\n // Without this, Pino uses its default async sonic-boom which writes to fd 1\n // but the ContainerAppConsoleLogs agent doesn't capture it on Bun.\n dest\n );\n return new PinoAdapter(pino);\n}\n\nfunction pickTraceFields(): Record<string, string> {\n try {\n // Pull active span context via @opentelemetry/api if installed.\n // Use require-style dynamic access to keep this file dep-free.\n const api = (globalThis as unknown as { __otelApi?: unknown }).__otelApi;\n if (!api) return {};\n const anyApi = api as {\n trace: {\n getActiveSpan: () => { spanContext: () => { traceId: string; spanId: string; traceFlags: number } } | undefined;\n };\n };\n const span = anyApi.trace.getActiveSpan();\n if (!span) return {};\n const ctx = span.spanContext();\n return {\n trace_id: ctx.traceId,\n span_id: ctx.spanId,\n trace_flags: ctx.traceFlags.toString(16).padStart(2, '0'),\n };\n } catch {\n return {};\n }\n}\n","/**\n * Unified telemetry bootstrap for Burdenoff services.\n *\n * Composes the existing `instrumentation/` + `observability/` + `logger/`\n * modules and adds:\n * - `bootstrapTelemetry({ serviceName, boundary, module, env })` — single\n * call that initializes OTel, wires Pino logger with trace fields,\n * exposes GraphQL Yoga plugins, registers process exit hooks.\n * - `createHealthRoutes({ prisma, nats, valkey, version })` — `/health`,\n * `/health/live`, `/health/ready` Elysia routes.\n * - `createMetricsRoutes(registry?)` — `/metrics` Prometheus exposition.\n * - `createPrismaLoggingExtension(logger)` — Prisma extension that pipes\n * query events through Pino with trace/span correlation ids.\n *\n * The module does not pull in `@opentelemetry/sdk-node` or `pino` as direct\n * deps — services install those as optional peers, and imports are lazy so\n * services that don't install them still load.\n */\n\nimport type { Logger as BaseLogger } from '../logger/index.js';\nimport { logger as defaultLogger } from '../logger/index.js';\nimport {\n initializeInstrumentation,\n setupInstrumentation,\n type SetupInstrumentationOptions,\n type InstrumentationSetupResult,\n} from '../instrumentation/index.js';\nimport { defaultCollectorEndpoint } from './collector-endpoint.js';\nimport { assertTelemetryIdGenerator, type TelemetryIdGenerator } from './id-generator.js';\nimport { setActiveTelemetryLogger } from './logger-state.js';\nimport type { OtelSdkHandle } from './sdk.js';\n\nexport { createHealthRoutes } from './health.js';\nexport { createMetricsRoutes } from './metrics-endpoint.js';\nexport { createPrismaLoggingExtension } from './prisma-logging.js';\nexport { DEFAULT_REDACT_PATHS } from './pino-redaction.js';\nexport { createPinoLogger } from './pino-logger.js';\nexport { assertTelemetryIdGenerator, type TelemetryIdGenerator } from './id-generator.js';\nexport {\n COLLECTOR_SERVICE,\n OTLP_HTTP_PORT,\n defaultCollectorEndpoint,\n defaultCollectorTracesEndpoint,\n resolveCollectorLayer,\n type CollectorLayer,\n} from './collector-endpoint.js';\n\nexport type Boundary = 'wspace' | 'global' | 'gateway';\nexport type Env = 'alpha' | 'prod' | 'dev';\n\nexport interface TelemetryConfig {\n /** Full service name, e.g. \"wspace-auth-svc\". */\n serviceName: string;\n /** Semver of the service deployment; defaults to `process.env.npm_package_version`. */\n serviceVersion?: string;\n /** Monorepo boundary: `wspace`, `global`, or `gateway`. */\n boundary: Boundary;\n /** Module slug, e.g. `auth` (omit for gateways). */\n module?: string;\n /** Deployment environment; defaults to alpha for non-production NODE_ENV. */\n env?: Env;\n /**\n * OTLP endpoint for spans/metrics/logs. Defaults to\n * `$OTEL_EXPORTER_OTLP_ENDPOINT`, then to this service's own in-cluster\n * collector — `otel-collector` in the global layer,\n * `otel-collector-wspace` in the wspace layer.\n */\n otlpEndpoint?: string;\n /** Head-based sampling ratio. Default: alpha=1.0, prod=0.1. */\n sampleRatio?: number;\n /** Extra options forwarded to `setupInstrumentation`. */\n instrumentation?: SetupInstrumentationOptions;\n /**\n * Optional trace/span id generator for the OTel tracer provider. Omit it to\n * keep the SDK's default random ids. Pass one when span ids must be derived\n * (for example a deterministic run span shared by many jobs and pods). It\n * must implement both `generateTraceId()` and `generateSpanId()`;\n * `bootstrapTelemetry` throws a `TypeError` at startup otherwise. Any\n * `IdGenerator` from `@opentelemetry/sdk-trace-base` fits.\n */\n idGenerator?: TelemetryIdGenerator;\n}\n\nexport interface TelemetryHandle {\n /** The configured service name (for use in health routes, etc.). */\n serviceName: string;\n /** The resolved service version. */\n serviceVersion: string;\n /** Environment. */\n env: Env;\n /** The Pino-backed logger. */\n logger: BaseLogger;\n /** Initialized instrumentation (tracer + metrics + plugins). */\n instrumentation: InstrumentationSetupResult;\n /** Cleanup hook; services call on SIGTERM. */\n shutdown: () => Promise<void>;\n}\n\nfunction resolveEnv(explicit?: Env): Env {\n if (explicit) return explicit;\n const fromEnv = process.env['DEPLOY_ENV'] ?? process.env['NODE_ENV'] ?? '';\n if (fromEnv === 'production' || fromEnv === 'prod') return 'prod';\n if (fromEnv === 'development' || fromEnv === 'dev') return 'dev';\n return 'alpha';\n}\n\nfunction resolveVersion(explicit?: string): string {\n if (explicit) return explicit;\n return process.env['npm_package_version'] ?? process.env['SERVICE_VERSION'] ?? '0.0.0';\n}\n\nfunction resolveEndpoint(serviceName: string, boundary: Boundary, explicit?: string): string {\n if (explicit) return explicit;\n const fromEnv = process.env['OTEL_EXPORTER_OTLP_ENDPOINT'];\n if (fromEnv) return fromEnv;\n // Default to the collector in this service's OWN cluster. The previous\n // default was `alloy.sre.svc.cluster.local:4318`, which never worked on the\n // AWS estate: Alloy lives in the `monitoring` namespace (not `sre`), and its\n // OTLP receiver forwards logs to Loki only — it does not accept traces. Since\n // only the gateways and a handful of workers set OTEL_EXPORTER_OTLP_ENDPOINT\n // explicitly, that dead default is why tracing was broken fleet-wide.\n return defaultCollectorEndpoint(serviceName, boundary);\n}\n\nfunction resolveSampling(explicit: number | undefined, env: Env): number {\n if (typeof explicit === 'number' && Number.isFinite(explicit)) return Math.min(1, Math.max(0, explicit));\n const fromEnv = process.env['OTEL_TRACES_SAMPLER_ARG'];\n if (fromEnv) {\n const parsed = Number(fromEnv);\n if (Number.isFinite(parsed)) return Math.min(1, Math.max(0, parsed));\n }\n if (env === 'prod') return 0.1;\n return 1.0;\n}\n\nfunction resolveOtelSdkEnabled(): boolean {\n const sdkDisabled = process.env['OTEL_SDK_DISABLED'];\n if (sdkDisabled === 'true' || sdkDisabled === '1') return false;\n const otelEnabled = process.env['OTEL_ENABLED'];\n if (otelEnabled === 'false' || otelEnabled === '0') return false;\n return true;\n}\n\n/**\n * Bootstrap the full telemetry stack for a service.\n *\n * Services call this ONCE at startup **before** importing Prisma / GraphQL\n * Yoga / NATS so OTel can auto-instrument their dependencies.\n *\n * ```ts\n * // src/telemetry.ts\n * import { bootstrapTelemetry } from '@burdenoff/be-sdk/telemetry';\n * export const telemetry = await bootstrapTelemetry({\n * serviceName: 'wspace-auth-svc',\n * boundary: 'wspace',\n * module: 'auth',\n * });\n *\n * // src/index.ts — must be the FIRST import line.\n * import './telemetry.js';\n * ```\n */\nexport async function bootstrapTelemetry(cfg: TelemetryConfig): Promise<TelemetryHandle> {\n // Validate before any side effect so a broken generator fails loudly at\n // startup instead of inside the tracer provider on the first span.\n assertTelemetryIdGenerator(cfg.idGenerator);\n const env = resolveEnv(cfg.env);\n const serviceVersion = resolveVersion(cfg.serviceVersion);\n const otlpEndpoint = resolveEndpoint(cfg.serviceName, cfg.boundary, cfg.otlpEndpoint);\n const sampleRatio = resolveSampling(cfg.sampleRatio, env);\n\n // Pino logger with trace/span correlation + redaction.\n // createPinoLogger is async (loads pino via dynamic import); awaiting it\n // is required — without await, `logger` is a Promise and calls like\n // logger.warn(...) crash with \"logger.warn is not a function\" during the\n // sdk-node fallback path.\n const { createPinoLogger } = await import('./pino-logger.js');\n const logger = await createPinoLogger({\n serviceName: cfg.serviceName,\n env,\n version: serviceVersion,\n });\n setActiveTelemetryLogger(logger);\n\n // Initialize core instrumentation (tracer, metrics registry, envelop plugins).\n // `setupInstrumentation` internally calls `initializeInstrumentation`.\n const instrumentation = setupInstrumentation(cfg.serviceName, {\n ...cfg.instrumentation,\n tracing: {\n serviceName: cfg.serviceName,\n ...(cfg.instrumentation?.tracing ?? {}),\n samplingRate: sampleRatio,\n },\n metrics: {\n serviceName: cfg.serviceName,\n ...(cfg.instrumentation?.metrics ?? {}),\n },\n });\n\n // Start the NodeSDK exporter pipeline if sdk-node is present (optional).\n let otelSdk: OtelSdkHandle | undefined;\n if (resolveOtelSdkEnabled()) {\n // Use console.log as a Pino-independent fallback for the critical OTel\n // bootstrap path. In ACA, Pino's default async sonic-boom destination is\n // not captured by ContainerAppConsoleLogs (see pino-logger.ts), so if the\n // sync-destination fix hasn't been deployed yet the *only* way operators\n // can see OTel startup/failure messages is through console.log.\n console.log('[telemetry] OTel SDK bootstrap starting...');\n try {\n const { createOtelSdk } = await import('./sdk.js');\n otelSdk = await createOtelSdk({\n serviceName: cfg.serviceName,\n serviceVersion,\n boundary: cfg.boundary,\n module: cfg.module,\n env,\n otlpEndpoint,\n sampleRatio,\n ...(cfg.idGenerator ? { idGenerator: cfg.idGenerator } : {}),\n });\n // Explicit success log includes metrics path status so an operator can\n // distinguish traces-only startup from full traces+metrics startup.\n logger.info('[telemetry] OpenTelemetry exporter pipeline started', {\n serviceName: cfg.serviceName,\n otlpEndpoint: otlpEndpoint ? '<configured>' : '<not set>',\n sampleRatio,\n metricsEnabled: otelSdk.metricsEnabled,\n customIdGenerator: cfg.idGenerator !== undefined,\n });\n console.log('[telemetry] OTel SDK exporter pipeline started');\n\n if (!otelSdk.metricsEnabled && otelSdk.metricsDropReason) {\n logger.warn('[telemetry] OpenTelemetry metrics reader disabled; continuing with traces only', {\n serviceName: cfg.serviceName,\n reason: otelSdk.metricsDropReason,\n });\n console.warn('[telemetry] OTel SDK metrics reader disabled:', otelSdk.metricsDropReason);\n }\n } catch (err) {\n logger.warn('[telemetry] OpenTelemetry exporter pipeline failed to start; continuing with logs only', {\n error: err instanceof Error ? err.message : String(err),\n });\n // console.error is always captured by ACA, ensuring the failure reason\n // is visible to operators even when Pino output is not.\n console.error('[telemetry] OTel SDK failed:', err);\n }\n } else {\n logger.info('[telemetry] OTel SDK exporter disabled by env');\n console.log('[telemetry] OTel SDK exporter disabled by env');\n }\n\n const shutdown = async (): Promise<void> => {\n try {\n if (otelSdk?.shutdown) await otelSdk.shutdown();\n } catch (err) {\n logger.warn('[telemetry] shutdown error (ignored)', {\n error: err instanceof Error ? err.message : String(err),\n });\n }\n };\n\n // Mirror defaultLogger so services that still use the singleton get trace-enriched output.\n defaultLogger.setLevel(logger.getLevel?.() ?? 'info');\n\n return {\n serviceName: cfg.serviceName,\n serviceVersion,\n env,\n logger: logger,\n instrumentation,\n shutdown,\n };\n}\n\n// Re-export what services typically import.\nexport { initializeInstrumentation, setupInstrumentation };\n"],"mappings":";;;;;;;;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U,IAAI;IACd,QAAQ,IAAI;IACZ;IACA;IACA;IACA,GAAI,IAAI,cAAc,EAAE,aAAa,IAAI,YAAY,IAAI,CAAC;GAC5D,CAAC;GAGD,SAAO,KAAK,uDAAuD;IACjE,aAAa,IAAI;IACjB,cAAc,eAAe,iBAAiB;IAC9C;IACA,gBAAgB,QAAQ;IACxB,mBAAmB,IAAI,gBAAgB;GACzC,CAAC;GACD,QAAQ,IAAI,gDAAgD;GAE5D,IAAI,CAAC,QAAQ,kBAAkB,QAAQ,mBAAmB;IACxD,SAAO,KAAK,kFAAkF;KAC5F,aAAa,IAAI;KACjB,QAAQ,QAAQ;IAClB,CAAC;IACD,QAAQ,KAAK,iDAAiD,QAAQ,iBAAiB;GACzF;EACF,SAAS,KAAK;GACZ,SAAO,KAAK,0FAA0F,EACpG,OAAO,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG,EACxD,CAAC;GAGD,QAAQ,MAAM,gCAAgC,GAAG;EACnD;CACF,OAAO;EACL,SAAO,KAAK,+CAA+C;EAC3D,QAAQ,IAAI,+CAA+C;CAC7D;CAEA,MAAM,WAAW,YAA2B;EAC1C,IAAI;GACF,IAAI,SAAS,UAAU,MAAM,QAAQ,SAAS;EAChD,SAAS,KAAK;GACZ,SAAO,KAAK,wCAAwC,EAClD,OAAO,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG,EACxD,CAAC;EACH;CACF;CAGA,OAAc,SAASA,SAAO,WAAW,KAAK,MAAM;CAEpD,OAAO;EACL,aAAa,IAAI;EACjB;EACA;EACA,QAAQA;EACR;EACA;CACF;AACF"}
|
|
1
|
+
{"version":3,"file":"index.js","names":["BaseLogger","anyApi","logger"],"sources":["../../src/telemetry/id-generator.ts","../../src/telemetry/health.ts","../../src/telemetry/metrics-endpoint.ts","../../src/telemetry/prisma-logging.ts","../../src/telemetry/pino-redaction.ts","../../src/telemetry/pino-logger.ts","../../src/telemetry/index.ts"],"sourcesContent":["/**\n * Custom trace/span id generation for `bootstrapTelemetry`.\n *\n * `@opentelemetry/sdk-node` accepts an `idGenerator` that the tracer provider\n * uses for every new trace id and span id. Services pass one when they need\n * span ids that are derived rather than random — for example, a workflow run\n * that executes across many jobs and pods but must surface as one trace with a\n * single, deterministic `workflow.run` parent span.\n *\n * The interface below is a structural twin of `IdGenerator` from\n * `@opentelemetry/sdk-trace-base`, declared here so the SDK's public types do\n * not require that optional peer dependency to be installed. Any\n * `IdGenerator` implementation (including `RandomIdGenerator`) satisfies it.\n */\n\nexport interface TelemetryIdGenerator {\n /** Returns a trace id: 32 lowercase hex characters (16 bytes), not all zero. */\n generateTraceId(): string;\n /** Returns a span id: 16 lowercase hex characters (8 bytes), not all zero. */\n generateSpanId(): string;\n}\n\n/**\n * Validate a caller-supplied id generator before it reaches the OTel SDK.\n *\n * A generator without both methods would make the tracer provider throw on\n * the first span, long after startup. Failing at bootstrap instead surfaces\n * the misconfiguration where it was made. `undefined` is accepted and means\n * \"use the SDK's default random generator\".\n */\nexport function assertTelemetryIdGenerator(candidate: unknown): asserts candidate is TelemetryIdGenerator | undefined {\n if (candidate === undefined) return;\n if (typeof candidate !== 'object' || candidate === null) {\n throw new TypeError('bootstrapTelemetry: idGenerator must be an object with generateTraceId and generateSpanId');\n }\n const { generateTraceId, generateSpanId } = candidate as {\n generateTraceId?: unknown;\n generateSpanId?: unknown;\n };\n if (typeof generateTraceId !== 'function' || typeof generateSpanId !== 'function') {\n throw new TypeError('bootstrapTelemetry: idGenerator must implement both generateTraceId() and generateSpanId()');\n }\n}\n","/**\n * `/health`, `/health/live`, `/health/ready` Elysia routes with a 1s\n * result cache so readiness checks can't stampede Postgres.\n *\n * Dependencies (prisma, eventQueue, valkey) are optional — omit any client and\n * the readiness check simply skips it.\n */\n\ninterface PrismaLike {\n $queryRaw: (strings: TemplateStringsArray) => Promise<unknown>;\n}\ninterface EventQueueLike {\n isConnected?: () => boolean | Promise<boolean>;\n healthCheck?: () => Promise<{ ok: boolean }>;\n}\ninterface ValkeyLike {\n ping: () => Promise<unknown>;\n}\n\nexport interface HealthDeps {\n prisma?: PrismaLike;\n eventQueue?: EventQueueLike;\n valkey?: ValkeyLike;\n /** Service version reported on /health. */\n version?: string;\n /** Service name reported on /health. */\n serviceName?: string;\n}\n\ninterface CachedStatus {\n ready: boolean;\n checked: Record<string, { ok: boolean; error?: string }>;\n at: number;\n}\n\nconst CACHE_TTL_MS = 1000;\n\nasync function probeReady(deps: HealthDeps): Promise<CachedStatus> {\n const checked: Record<string, { ok: boolean; error?: string }> = {};\n\n if (deps.prisma) {\n try {\n await deps.prisma.$queryRaw`SELECT 1`;\n checked['postgres'] = { ok: true };\n } catch (err) {\n checked['postgres'] = {\n ok: false,\n error: err instanceof Error ? err.message : String(err),\n };\n }\n }\n\n if (deps.eventQueue) {\n try {\n const connected =\n typeof deps.eventQueue.isConnected === 'function'\n ? await Promise.resolve(deps.eventQueue.isConnected())\n : ((await deps.eventQueue.healthCheck?.())?.ok ?? true);\n checked['eventQueue'] = { ok: Boolean(connected) };\n } catch (err) {\n checked['eventQueue'] = {\n ok: false,\n error: err instanceof Error ? err.message : String(err),\n };\n }\n }\n\n if (deps.valkey) {\n try {\n await deps.valkey.ping();\n checked['valkey'] = { ok: true };\n } catch (err) {\n checked['valkey'] = {\n ok: false,\n error: err instanceof Error ? err.message : String(err),\n };\n }\n }\n\n const ready = Object.values(checked).every((c) => c.ok);\n return { ready, checked, at: Date.now() };\n}\n\nexport function createHealthRoutes(_deps: HealthDeps = {}): unknown {\n // Return an Elysia app lazily so be-sdk doesn't hard-require elysia.\n return new Proxy(\n {},\n {\n get(_target, prop): unknown {\n // Tell TypeScript consumers the returned object is an Elysia plugin;\n // the actual mount happens via `createHealthRoutesImpl`. Services\n // that prefer direct use can call `createHealthRoutesImpl(elysia, deps)`.\n if (prop === 'use' || prop === 'then') return undefined;\n return undefined;\n },\n }\n );\n}\n\n/**\n * Mount health routes on an existing Elysia app. Callers hold a reference\n * to Elysia themselves; be-sdk stays decoupled.\n */\nexport function createHealthRoutesImpl<\n App extends {\n get: (path: string, handler: (ctx: unknown) => unknown) => App;\n },\n>(app: App, deps: HealthDeps = {}): App {\n let cache: CachedStatus | null = null;\n\n const getStatus = async (): Promise<CachedStatus> => {\n if (cache && Date.now() - cache.at < CACHE_TTL_MS) return cache;\n cache = await probeReady(deps);\n return cache;\n };\n\n app.get('/health/live', () => ({\n status: 'ok',\n serviceName: deps.serviceName,\n version: deps.version,\n }));\n\n app.get('/health/ready', async (ctx: unknown): Promise<unknown> => {\n const status = await getStatus();\n const ctxWithSet = ctx as { set?: { status?: number } };\n if (!status.ready && ctxWithSet.set) ctxWithSet.set.status = 503;\n return {\n status: status.ready ? 'ok' : 'degraded',\n serviceName: deps.serviceName,\n version: deps.version,\n checks: status.checked,\n };\n });\n\n app.get('/health', async (ctx: unknown): Promise<unknown> => {\n const status = await getStatus();\n const ctxWithSet = ctx as { set?: { status?: number } };\n if (!status.ready && ctxWithSet.set) ctxWithSet.set.status = 503;\n return {\n status: status.ready ? 'ok' : 'degraded',\n serviceName: deps.serviceName,\n version: deps.version,\n checks: status.checked,\n uptime_s: Math.round(process.uptime()),\n };\n });\n\n return app;\n}\n","/**\n * Prometheus `/metrics` route mounter. Uses the shared `prom-client`\n * default registry so all instrumentation (GraphQL Envelop, Prisma,\n * runtime) shows up on a single endpoint.\n */\n\ninterface PromRegistryLike {\n metrics: () => Promise<string> | string;\n contentType?: string;\n}\n\nexport interface MetricsMountOptions {\n registry?: PromRegistryLike;\n path?: string;\n}\n\nexport async function loadDefaultRegistry(): Promise<PromRegistryLike | null> {\n try {\n const mod = (await import('prom-client')) as unknown as {\n register: PromRegistryLike;\n collectDefaultMetrics: (opts?: Record<string, unknown>) => void;\n };\n // Kick runtime metrics into the default registry if not already.\n try {\n mod.collectDefaultMetrics({ register: mod.register });\n } catch {\n // Already registered — ignore duplicate-metric errors.\n }\n return mod.register;\n } catch {\n return null;\n }\n}\n\nexport function createMetricsRoutesImpl<\n App extends {\n get: (path: string, handler: (ctx: unknown) => unknown) => App;\n },\n>(app: App, opts: MetricsMountOptions = {}): App {\n const path = opts.path ?? '/metrics';\n\n app.get(path, async (ctx: unknown): Promise<unknown> => {\n const registry = opts.registry ?? (await loadDefaultRegistry());\n const ctxWithSet = ctx as { set?: { status?: number; headers?: Record<string, string> } };\n if (!registry) {\n if (ctxWithSet.set) ctxWithSet.set.status = 503;\n return '# prom-client not installed\\n';\n }\n if (ctxWithSet.set) {\n ctxWithSet.set.status = 200;\n ctxWithSet.set.headers = {\n 'content-type': registry.contentType ?? 'text/plain; version=0.0.4; charset=utf-8',\n };\n }\n return registry.metrics();\n });\n\n return app;\n}\n\n/**\n * Legacy export name used by the service template. Composes the Elysia\n * plugin-style function that `new Elysia().use(...)` accepts.\n */\nexport function createMetricsRoutes(opts: MetricsMountOptions = {}): unknown {\n return (app: Parameters<typeof createMetricsRoutesImpl>[0]): unknown => createMetricsRoutesImpl(app, opts);\n}\n","/**\n * Prisma client extension that pipes query events through the SDK logger\n * with trace/span correlation fields auto-injected. The\n * `@prisma/instrumentation` peer provides the spans\n * themselves; this extension only adds structured log events on top.\n */\nimport type { Logger } from '../logger/index.js';\nimport { redactSensitiveFields } from '../logger/index.js';\n\ntype PrismaQueryArgs = {\n model?: string;\n operation: string;\n args: unknown;\n query: (args: unknown) => Promise<unknown>;\n};\n\n/**\n * Returns a Prisma Client extension object compatible with the\n * `$extends()` API (Prisma v5+).\n *\n * ```ts\n * export const prisma = new PrismaClient().$extends(\n * createPrismaLoggingExtension(logger)\n * );\n * ```\n */\nexport function createPrismaLoggingExtension(logger: Logger): {\n name: string;\n query: {\n $allOperations: (args: PrismaQueryArgs) => Promise<unknown>;\n };\n} {\n return {\n name: 'burdenoff-pino-logging',\n query: {\n async $allOperations({ model, operation, args, query }: PrismaQueryArgs): Promise<unknown> {\n const start = Date.now();\n try {\n const result = await query(args);\n logger.debug('prisma.query', {\n model,\n operation,\n duration_ms: Date.now() - start,\n args: redactSensitiveFields(args),\n });\n return result;\n } catch (err) {\n logger.error('prisma.error', {\n model,\n operation,\n duration_ms: Date.now() - start,\n error: err instanceof Error ? err.message : String(err),\n });\n throw err;\n }\n },\n },\n };\n}\n","/**\n * Default Pino redact paths — covers the Burdenoff authorization +\n * gateway header + NATS/GraphQL payload surface area.\n *\n * Services can extend this list via their own Pino options.\n */\nexport const DEFAULT_REDACT_PATHS: readonly string[] = Object.freeze([\n 'password',\n '*.password',\n '*.*.password',\n 'token',\n 'authToken',\n 'workspaceToken',\n 'accessToken',\n 'refreshToken',\n 'clientSecret',\n 'apiKey',\n '*.apiKey',\n 'authorization',\n 'req.headers.authorization',\n 'req.headers[\"x-workspace-authorization\"]',\n 'req.headers.cookie',\n 'res.headers[\"set-cookie\"]',\n 'params.*.password',\n 'params.*.token',\n 'params.*.secret',\n]);\n","/**\n * Pino logger wrapper that emits structured JSON with trace/span correlation\n * fields. Falls back to the SDK's built-in Logger when `pino` isn't installed\n * so services without the peer dep still compile and run.\n *\n * # ACA stdout compatibility\n *\n * In Azure Container Apps the ContainerAppConsoleLogs agent captures\n * `console.log` / `process.stdout.write` output but does *not* reliably\n * capture Pino's default async sonic-boom destination (which writes to fd 1\n * through Node.js `fs.writeSync` / `fs.write`). This means every log line\n * produced through Pino's default destination is invisible in Log Analytics.\n *\n * The fix mirrors what the gateway's own `logger.ts` does in production:\n * pass `pino.destination({ sync: true })` as the second argument to the\n * Pino factory so writes are synchronous and go through a path that ACA\n * captures correctly.\n */\nimport { Logger as BaseLogger } from '../logger/index.js';\nimport { DEFAULT_REDACT_PATHS } from './pino-redaction.js';\n\nexport interface PinoLoggerConfig {\n serviceName: string;\n env: 'alpha' | 'prod' | 'dev';\n version: string;\n /** Override Pino log level. Default: warn (prod), info (alpha/dev). */\n level?: 'fatal' | 'error' | 'warn' | 'info' | 'debug' | 'trace';\n /** Extra redact paths appended to DEFAULT_REDACT_PATHS. */\n redactPaths?: string[];\n}\n\ninterface PinoLike {\n level: string;\n fatal: (...args: unknown[]) => void;\n error: (...args: unknown[]) => void;\n warn: (...args: unknown[]) => void;\n info: (...args: unknown[]) => void;\n debug: (...args: unknown[]) => void;\n trace: (...args: unknown[]) => void;\n child: (bindings: Record<string, unknown>) => PinoLike;\n}\n\n/**\n * Loaded Pino module: factory function + a synchronous destination factory.\n * In ACA, Pino's default async sonic-boom destination is invisible in Log\n * Analytics, so we always use a sync destination.\n */\ninterface PinoLoader {\n factory: (opts: unknown, dest?: unknown) => PinoLike;\n makeDest: () => unknown;\n}\n\nasync function tryLoadPino(): Promise<PinoLoader | null> {\n try {\n const mod = (await import('pino')) as unknown as { default?: unknown };\n const candidate = (mod.default ?? mod) as unknown;\n if (typeof candidate === 'function') {\n const factory = candidate as (opts: unknown, dest?: unknown) => PinoLike;\n const destination = (factory as unknown as Record<string, unknown>)?.['destination'] as\n ((opts?: { sync?: boolean }) => unknown) | undefined;\n const makeDest = typeof destination === 'function' ? () => destination({ sync: true }) : () => undefined;\n return { factory, makeDest };\n }\n return null;\n } catch {\n return null;\n }\n}\n\nclass PinoAdapter extends BaseLogger {\n constructor(private readonly pino: PinoLike) {\n super({\n level: (pino.level as BaseLogger['getLevel'] extends () => infer L ? L : never) ?? 'info',\n console: false,\n });\n }\n\n public override debug(message: string, ...args: unknown[]): void {\n this.pino.debug(this.mergeArgs(args), message);\n }\n public override info(message: string, ...args: unknown[]): void {\n this.pino.info(this.mergeArgs(args), message);\n }\n public override warn(message: string, ...args: unknown[]): void {\n this.pino.warn(this.mergeArgs(args), message);\n }\n public override error(message: string, ...args: unknown[]): void {\n this.pino.error(this.mergeArgs(args), message);\n }\n public override log(message: string, ...args: unknown[]): void {\n this.pino.info(this.mergeArgs(args), message);\n }\n public override trace(message: string, ...args: unknown[]): void {\n this.pino.trace(this.mergeArgs(args), message);\n }\n\n private mergeArgs(args: unknown[]): Record<string, unknown> {\n const out: Record<string, unknown> = {};\n for (const arg of args) {\n if (arg instanceof Error) {\n out['err'] = { message: arg.message, stack: arg.stack, name: arg.name };\n } else if (arg && typeof arg === 'object') {\n Object.assign(out, arg as Record<string, unknown>);\n } else if (arg !== undefined && arg !== null) {\n out['data'] = arg;\n }\n }\n return out;\n }\n}\n\n/**\n * Build a logger instance. Returns a Pino-backed adapter when `pino` is\n * installed; otherwise falls back to the SDK's built-in JSON Logger.\n *\n * Services call this through `bootstrapTelemetry`, not directly.\n */\nexport async function createPinoLogger(cfg: PinoLoggerConfig): Promise<BaseLogger> {\n const loader = await tryLoadPino();\n if (!loader) {\n // No pino — fall back to the built-in Logger with console output.\n const fallback = new BaseLogger({ level: cfg.env === 'prod' ? 'warn' : 'info', console: true });\n fallback.setContext({\n service: cfg.serviceName,\n env: cfg.env,\n version: cfg.version,\n });\n return fallback;\n }\n\n const redactPaths = [...DEFAULT_REDACT_PATHS, ...(cfg.redactPaths ?? [])];\n const dest = loader.makeDest();\n const pino = loader.factory(\n {\n name: cfg.serviceName,\n level: cfg.level ?? (cfg.env === 'prod' ? 'warn' : 'info'),\n base: {\n service: { name: cfg.serviceName, version: cfg.version },\n env: cfg.env,\n },\n redact: {\n paths: redactPaths,\n censor: '[REDACTED]',\n remove: false,\n },\n timestamp: () => `,\"time\":\"${new Date().toISOString()}\"`,\n mixin: () => pickTraceFields(),\n },\n // Explicit sync destination so output is visible in ACA Log Analytics.\n // Without this, Pino uses its default async sonic-boom which writes to fd 1\n // but the ContainerAppConsoleLogs agent doesn't capture it on Bun.\n dest\n );\n return new PinoAdapter(pino);\n}\n\nfunction pickTraceFields(): Record<string, string> {\n try {\n // Pull active span context via @opentelemetry/api if installed.\n // Use require-style dynamic access to keep this file dep-free.\n const api = (globalThis as unknown as { __otelApi?: unknown }).__otelApi;\n if (!api) return {};\n const anyApi = api as {\n trace: {\n getActiveSpan: () => { spanContext: () => { traceId: string; spanId: string; traceFlags: number } } | undefined;\n };\n };\n const span = anyApi.trace.getActiveSpan();\n if (!span) return {};\n const ctx = span.spanContext();\n return {\n trace_id: ctx.traceId,\n span_id: ctx.spanId,\n trace_flags: ctx.traceFlags.toString(16).padStart(2, '0'),\n };\n } catch {\n return {};\n }\n}\n","/**\n * Unified telemetry bootstrap for Burdenoff services.\n *\n * Composes the existing `instrumentation/` + `observability/` + `logger/`\n * modules and adds:\n * - `bootstrapTelemetry({ serviceName, boundary, module, env })` — single\n * call that initializes OTel, wires Pino logger with trace fields,\n * exposes GraphQL Yoga plugins, registers process exit hooks.\n * - `createHealthRoutes({ prisma, nats, valkey, version })` — `/health`,\n * `/health/live`, `/health/ready` Elysia routes.\n * - `createMetricsRoutes(registry?)` — `/metrics` Prometheus exposition.\n * - `createPrismaLoggingExtension(logger)` — Prisma extension that pipes\n * query events through Pino with trace/span correlation ids.\n *\n * The module does not pull in `@opentelemetry/sdk-node` or `pino` as direct\n * deps — services install those as optional peers, and imports are lazy so\n * services that don't install them still load.\n */\n\nimport type { Logger as BaseLogger } from '../logger/index.js';\nimport { logger as defaultLogger } from '../logger/index.js';\nimport {\n initializeInstrumentation,\n setupInstrumentation,\n type SetupInstrumentationOptions,\n type InstrumentationSetupResult,\n} from '../instrumentation/index.js';\nimport { defaultCollectorEndpoint } from './collector-endpoint.js';\nimport { assertTelemetryIdGenerator, type TelemetryIdGenerator } from './id-generator.js';\nimport { setActiveTelemetryLogger } from './logger-state.js';\nimport type { OtelModules, OtelSdkHandle } from './sdk.js';\n\nexport type { OtelModules, OtelPeerPackage } from './sdk.js';\n\nexport { createHealthRoutes } from './health.js';\nexport { createMetricsRoutes } from './metrics-endpoint.js';\nexport { createPrismaLoggingExtension } from './prisma-logging.js';\nexport { DEFAULT_REDACT_PATHS } from './pino-redaction.js';\nexport { createPinoLogger } from './pino-logger.js';\nexport { assertTelemetryIdGenerator, type TelemetryIdGenerator } from './id-generator.js';\nexport {\n COLLECTOR_SERVICE,\n OTLP_HTTP_PORT,\n defaultCollectorEndpoint,\n defaultCollectorTracesEndpoint,\n resolveCollectorLayer,\n type CollectorLayer,\n} from './collector-endpoint.js';\n\nexport type Boundary = 'wspace' | 'global' | 'gateway';\nexport type Env = 'alpha' | 'prod' | 'dev';\n\nexport interface TelemetryConfig {\n /** Full service name, e.g. \"wspace-auth-svc\". */\n serviceName: string;\n /** Semver of the service deployment; defaults to `process.env.npm_package_version`. */\n serviceVersion?: string;\n /** Monorepo boundary: `wspace`, `global`, or `gateway`. */\n boundary: Boundary;\n /** Module slug, e.g. `auth` (omit for gateways). */\n module?: string;\n /** Deployment environment; defaults to alpha for non-production NODE_ENV. */\n env?: Env;\n /**\n * OTLP endpoint for spans/metrics/logs. Defaults to\n * `$OTEL_EXPORTER_OTLP_ENDPOINT`, then to this service's own in-cluster\n * collector — `otel-collector` in the global layer,\n * `otel-collector-wspace` in the wspace layer.\n */\n otlpEndpoint?: string;\n /** Head-based sampling ratio. Default: alpha=1.0, prod=0.1. */\n sampleRatio?: number;\n /** Extra options forwarded to `setupInstrumentation`. */\n instrumentation?: SetupInstrumentationOptions;\n /**\n * Optional trace/span id generator for the OTel tracer provider. Omit it to\n * keep the SDK's default random ids. Pass one when span ids must be derived\n * (for example a deterministic run span shared by many jobs and pods). It\n * must implement both `generateTraceId()` and `generateSpanId()`;\n * `bootstrapTelemetry` throws a `TypeError` at startup otherwise. Any\n * `IdGenerator` from `@opentelemetry/sdk-trace-base` fits.\n */\n idGenerator?: TelemetryIdGenerator;\n /**\n * Pre-loaded OpenTelemetry packages, keyed by package name (see\n * `OtelModules`). Needed by services built with `bun build --compile`,\n * which have no `node_modules` to load the optional peers from at runtime.\n */\n otelModules?: OtelModules;\n}\n\nexport interface TelemetryHandle {\n /** The configured service name (for use in health routes, etc.). */\n serviceName: string;\n /** The resolved service version. */\n serviceVersion: string;\n /** Environment. */\n env: Env;\n /** The Pino-backed logger. */\n logger: BaseLogger;\n /** Initialized instrumentation (tracer + metrics + plugins). */\n instrumentation: InstrumentationSetupResult;\n /** Cleanup hook; services call on SIGTERM. */\n shutdown: () => Promise<void>;\n}\n\nfunction resolveEnv(explicit?: Env): Env {\n if (explicit) return explicit;\n const fromEnv = process.env['DEPLOY_ENV'] ?? process.env['NODE_ENV'] ?? '';\n if (fromEnv === 'production' || fromEnv === 'prod') return 'prod';\n if (fromEnv === 'development' || fromEnv === 'dev') return 'dev';\n return 'alpha';\n}\n\nfunction resolveVersion(explicit?: string): string {\n if (explicit) return explicit;\n return process.env['npm_package_version'] ?? process.env['SERVICE_VERSION'] ?? '0.0.0';\n}\n\nfunction resolveEndpoint(serviceName: string, boundary: Boundary, explicit?: string): string {\n if (explicit) return explicit;\n const fromEnv = process.env['OTEL_EXPORTER_OTLP_ENDPOINT'];\n if (fromEnv) return fromEnv;\n // Default to the collector in this service's OWN cluster. The previous\n // default was `alloy.sre.svc.cluster.local:4318`, which never worked on the\n // AWS estate: Alloy lives in the `monitoring` namespace (not `sre`), and its\n // OTLP receiver forwards logs to Loki only — it does not accept traces. Since\n // only the gateways and a handful of workers set OTEL_EXPORTER_OTLP_ENDPOINT\n // explicitly, that dead default is why tracing was broken fleet-wide.\n return defaultCollectorEndpoint(serviceName, boundary);\n}\n\nfunction resolveSampling(explicit: number | undefined, env: Env): number {\n if (typeof explicit === 'number' && Number.isFinite(explicit)) return Math.min(1, Math.max(0, explicit));\n const fromEnv = process.env['OTEL_TRACES_SAMPLER_ARG'];\n if (fromEnv) {\n const parsed = Number(fromEnv);\n if (Number.isFinite(parsed)) return Math.min(1, Math.max(0, parsed));\n }\n if (env === 'prod') return 0.1;\n return 1.0;\n}\n\nfunction resolveOtelSdkEnabled(): boolean {\n const sdkDisabled = process.env['OTEL_SDK_DISABLED'];\n if (sdkDisabled === 'true' || sdkDisabled === '1') return false;\n const otelEnabled = process.env['OTEL_ENABLED'];\n if (otelEnabled === 'false' || otelEnabled === '0') return false;\n return true;\n}\n\n/**\n * Bootstrap the full telemetry stack for a service.\n *\n * Services call this ONCE at startup **before** importing Prisma / GraphQL\n * Yoga / NATS so OTel can auto-instrument their dependencies.\n *\n * ```ts\n * // src/telemetry.ts\n * import { bootstrapTelemetry } from '@burdenoff/be-sdk/telemetry';\n * export const telemetry = await bootstrapTelemetry({\n * serviceName: 'wspace-auth-svc',\n * boundary: 'wspace',\n * module: 'auth',\n * });\n *\n * // src/index.ts — must be the FIRST import line.\n * import './telemetry.js';\n * ```\n */\nexport async function bootstrapTelemetry(cfg: TelemetryConfig): Promise<TelemetryHandle> {\n // Validate before any side effect so a broken generator fails loudly at\n // startup instead of inside the tracer provider on the first span.\n assertTelemetryIdGenerator(cfg.idGenerator);\n const env = resolveEnv(cfg.env);\n const serviceVersion = resolveVersion(cfg.serviceVersion);\n const otlpEndpoint = resolveEndpoint(cfg.serviceName, cfg.boundary, cfg.otlpEndpoint);\n const sampleRatio = resolveSampling(cfg.sampleRatio, env);\n\n // Pino logger with trace/span correlation + redaction.\n // createPinoLogger is async (loads pino via dynamic import); awaiting it\n // is required — without await, `logger` is a Promise and calls like\n // logger.warn(...) crash with \"logger.warn is not a function\" during the\n // sdk-node fallback path.\n const { createPinoLogger } = await import('./pino-logger.js');\n const logger = await createPinoLogger({\n serviceName: cfg.serviceName,\n env,\n version: serviceVersion,\n });\n setActiveTelemetryLogger(logger);\n\n // Initialize core instrumentation (tracer, metrics registry, envelop plugins).\n // `setupInstrumentation` internally calls `initializeInstrumentation`.\n const instrumentation = setupInstrumentation(cfg.serviceName, {\n ...cfg.instrumentation,\n tracing: {\n serviceName: cfg.serviceName,\n ...(cfg.instrumentation?.tracing ?? {}),\n samplingRate: sampleRatio,\n },\n metrics: {\n serviceName: cfg.serviceName,\n ...(cfg.instrumentation?.metrics ?? {}),\n },\n });\n\n // Start the NodeSDK exporter pipeline if sdk-node is present (optional).\n let otelSdk: OtelSdkHandle | undefined;\n if (resolveOtelSdkEnabled()) {\n // Use console.log as a Pino-independent fallback for the critical OTel\n // bootstrap path. In ACA, Pino's default async sonic-boom destination is\n // not captured by ContainerAppConsoleLogs (see pino-logger.ts), so if the\n // sync-destination fix hasn't been deployed yet the *only* way operators\n // can see OTel startup/failure messages is through console.log.\n console.log('[telemetry] OTel SDK bootstrap starting...');\n try {\n const { createOtelSdk } = await import('./sdk.js');\n otelSdk = await createOtelSdk({\n serviceName: cfg.serviceName,\n serviceVersion,\n boundary: cfg.boundary,\n module: cfg.module,\n env,\n otlpEndpoint,\n sampleRatio,\n ...(cfg.idGenerator ? { idGenerator: cfg.idGenerator } : {}),\n ...(cfg.otelModules ? { modules: cfg.otelModules } : {}),\n });\n // Explicit success log includes metrics path status so an operator can\n // distinguish traces-only startup from full traces+metrics startup.\n logger.info('[telemetry] OpenTelemetry exporter pipeline started', {\n serviceName: cfg.serviceName,\n otlpEndpoint: otlpEndpoint ? '<configured>' : '<not set>',\n sampleRatio,\n metricsEnabled: otelSdk.metricsEnabled,\n customIdGenerator: cfg.idGenerator !== undefined,\n });\n console.log('[telemetry] OTel SDK exporter pipeline started');\n\n if (!otelSdk.metricsEnabled && otelSdk.metricsDropReason) {\n logger.warn('[telemetry] OpenTelemetry metrics reader disabled; continuing with traces only', {\n serviceName: cfg.serviceName,\n reason: otelSdk.metricsDropReason,\n });\n console.warn('[telemetry] OTel SDK metrics reader disabled:', otelSdk.metricsDropReason);\n }\n } catch (err) {\n logger.warn('[telemetry] OpenTelemetry exporter pipeline failed to start; continuing with logs only', {\n error: err instanceof Error ? err.message : String(err),\n });\n // console.error is always captured by ACA, ensuring the failure reason\n // is visible to operators even when Pino output is not.\n console.error('[telemetry] OTel SDK failed:', err);\n }\n } else {\n logger.info('[telemetry] OTel SDK exporter disabled by env');\n console.log('[telemetry] OTel SDK exporter disabled by env');\n }\n\n const shutdown = async (): Promise<void> => {\n try {\n if (otelSdk?.shutdown) await otelSdk.shutdown();\n } catch (err) {\n logger.warn('[telemetry] shutdown error (ignored)', {\n error: err instanceof Error ? err.message : String(err),\n });\n }\n };\n\n // Mirror defaultLogger so services that still use the singleton get trace-enriched output.\n defaultLogger.setLevel(logger.getLevel?.() ?? 'info');\n\n return {\n serviceName: cfg.serviceName,\n serviceVersion,\n env,\n logger: logger,\n instrumentation,\n shutdown,\n };\n}\n\n// Re-export what services typ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assistant-session-DA5ZKJOr.js";
|
|
2
2
|
import { t as suppressMutationAudit } from "../explicit-activity-scope-D8VeGGpt.js";
|
|
3
|
-
import {
|
|
4
|
-
import { p as
|
|
3
|
+
import { p as UsageMetricType } from "../index-CVCyKzhB.js";
|
|
4
|
+
import { S as trackerStub, _ as UsageTrackingOptions, a as AGENT_ACTIVITY_RESOURCE_TYPE, b as resolveAssistantSession, c as trackAgentActivity, d as RbacCheckOptions, f as TrackedActorType, g as UnifiedTrackingOptions, h as UnifiedTrackerStub, i as AGENT_ACTIVITY_ACTIONS, l as ActivityTrackingOptions, m as UNIFIED_TRACKER_CONSTANTS, n as TrackResult, o as AgentActivityAction, p as TrackingEvent, r as TrackerModule, s as AgentActivityOptions, t as TrackOptions, u as ProductTracker, v as createProductTracker, x as trackOperation, y as isTrackedActorType } from "../index-zd_NPGJo.js";
|
|
5
5
|
export { AGENT_ACTIVITY_ACTIONS, AGENT_ACTIVITY_RESOURCE_TYPE, AI_ASSISTANT_ACTOR_ORIGIN, type ActivityTrackingOptions, type ActorOrigin, type AgentActivityAction, type AgentActivityOptions, type AssistantSessionAttribution, type ProductTracker, type RbacCheckOptions, TrackOptions, TrackResult, type TrackedActorType, TrackerModule, type TrackingEvent, UNIFIED_TRACKER_CONSTANTS, UnifiedTrackerStub, type UnifiedTrackingOptions, UsageMetricType, type UsageTrackingOptions, createProductTracker, isTrackedActorType, resolveAssistantSession, suppressMutationAudit, trackAgentActivity, trackOperation, trackerStub };
|
package/dist/tracker/index.js
CHANGED
|
@@ -1,6 +1,8 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import
|
|
3
|
-
import { i as UsageMetricType } from "../usage-
|
|
1
|
+
import { i as suppressMutationAudit } from "../explicit-activity-scope-DikJ7NAE.js";
|
|
2
|
+
import "../activity/index.js";
|
|
3
|
+
import { i as UsageMetricType } from "../usage-BRqVP3CJ.js";
|
|
4
|
+
import { a as resolveAssistantSession, i as isTrackedActorType, l as AI_ASSISTANT_ACTOR_ORIGIN, n as UnifiedTrackerStub, o as trackOperation, r as createProductTracker, s as trackerStub, t as UNIFIED_TRACKER_CONSTANTS } from "../stub-BUnfMiAS.js";
|
|
5
|
+
import { i as trackAgentActivity, n as AGENT_ACTIVITY_ACTIONS, r as AGENT_ACTIVITY_RESOURCE_TYPE, t as TrackerModule } from "../tracker-PQztSlhJ.js";
|
|
4
6
|
|
|
5
7
|
export { AGENT_ACTIVITY_ACTIONS, AGENT_ACTIVITY_RESOURCE_TYPE, AI_ASSISTANT_ACTOR_ORIGIN, TrackerModule, UNIFIED_TRACKER_CONSTANTS, UnifiedTrackerStub, UsageMetricType, createProductTracker, isTrackedActorType, resolveAssistantSession, suppressMutationAudit, trackAgentActivity, trackOperation, trackerStub };
|
|
6
8
|
//# sourceMappingURL=index.js.map
|
|
@@ -1,392 +1,11 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { PermissionDeniedError, QuotaExceededError, ValidationError } from "./types/index.js";
|
|
2
2
|
import { a as logger } from "./logger-B6rCpb7D.js";
|
|
3
|
-
import { t as RBACModule } from "./rbac-
|
|
4
|
-
import {
|
|
5
|
-
import { a as UsageModule } from "./usage-
|
|
6
|
-
import { n as NotificationType, r as NotificationsModule } from "./notifications-
|
|
7
|
-
import {
|
|
8
|
-
|
|
9
|
-
// src/activity/index.ts
|
|
10
|
-
/**
|
|
11
|
-
* Activity Tracking Module
|
|
12
|
-
*
|
|
13
|
-
* Audit trail writes and reads against the workspace activity owner
|
|
14
|
-
* (`wspace-activity-svc`), reached through the configured workspace internal gateway.
|
|
15
|
-
*
|
|
16
|
-
* The SDK keeps its own descriptive vocabulary (`activityType`, `status`, `severity`,
|
|
17
|
-
* `duration`, ...) for callers, but the owning subgraph's `ActivityLog` type does not have
|
|
18
|
-
* those columns. This module therefore maps between the two contracts explicitly:
|
|
19
|
-
*
|
|
20
|
-
* - writes send only fields `RecordActivityInput` defines and carry the SDK-only fields in
|
|
21
|
-
* `metadata`, which the owner persists verbatim in the row's `details` column;
|
|
22
|
-
* - reads select only fields `ActivityLog` defines and rebuild the SDK shape from the row
|
|
23
|
-
* plus those persisted `details`.
|
|
24
|
-
*
|
|
25
|
-
* Selecting a field the owner does not define fails GraphQL validation for the whole
|
|
26
|
-
* operation, so the selections below are pinned by unit tests against the published schema.
|
|
27
|
-
*/
|
|
28
|
-
let ActivityType = /* @__PURE__ */ function(ActivityType) {
|
|
29
|
-
ActivityType["CREATE"] = "create";
|
|
30
|
-
ActivityType["READ"] = "read";
|
|
31
|
-
ActivityType["UPDATE"] = "update";
|
|
32
|
-
ActivityType["DELETE"] = "delete";
|
|
33
|
-
ActivityType["LOGIN"] = "login";
|
|
34
|
-
ActivityType["LOGOUT"] = "logout";
|
|
35
|
-
ActivityType["EXPORT"] = "export";
|
|
36
|
-
ActivityType["IMPORT"] = "import";
|
|
37
|
-
ActivityType["SHARE"] = "share";
|
|
38
|
-
ActivityType["DOWNLOAD"] = "download";
|
|
39
|
-
ActivityType["UPLOAD"] = "upload";
|
|
40
|
-
ActivityType["EXECUTE"] = "execute";
|
|
41
|
-
ActivityType["APPROVE"] = "approve";
|
|
42
|
-
ActivityType["REJECT"] = "reject";
|
|
43
|
-
ActivityType["CUSTOM"] = "custom";
|
|
44
|
-
return ActivityType;
|
|
45
|
-
}({});
|
|
46
|
-
let ActivityStatus = /* @__PURE__ */ function(ActivityStatus) {
|
|
47
|
-
ActivityStatus["SUCCESS"] = "success";
|
|
48
|
-
ActivityStatus["FAILURE"] = "failure";
|
|
49
|
-
ActivityStatus["PENDING"] = "pending";
|
|
50
|
-
ActivityStatus["WARNING"] = "warning";
|
|
51
|
-
return ActivityStatus;
|
|
52
|
-
}({});
|
|
53
|
-
let ActivitySeverity = /* @__PURE__ */ function(ActivitySeverity) {
|
|
54
|
-
ActivitySeverity["LOW"] = "low";
|
|
55
|
-
ActivitySeverity["MEDIUM"] = "medium";
|
|
56
|
-
ActivitySeverity["HIGH"] = "high";
|
|
57
|
-
ActivitySeverity["CRITICAL"] = "critical";
|
|
58
|
-
return ActivitySeverity;
|
|
59
|
-
}({});
|
|
60
|
-
/** Thrown by SDK operations the current activity owner does not expose. */
|
|
61
|
-
var ActivityOperationUnsupportedError = class ActivityOperationUnsupportedError extends SDKError {
|
|
62
|
-
constructor(operation, guidance) {
|
|
63
|
-
super(`ActivityModule.${operation} is not supported by the workspace activity owner: ${guidance}`, "ACTIVITY_OPERATION_UNSUPPORTED", { operation });
|
|
64
|
-
this.name = "ActivityOperationUnsupportedError";
|
|
65
|
-
Object.setPrototypeOf(this, ActivityOperationUnsupportedError.prototype);
|
|
66
|
-
}
|
|
67
|
-
};
|
|
68
|
-
/**
|
|
69
|
-
* `ActivityLog` fields selected from wspace-activity-svc. Every name here must exist on the
|
|
70
|
-
* owner's published `ActivityLog` type (see tests/activity-module.test.ts).
|
|
71
|
-
*/
|
|
72
|
-
const ACTIVITY_LOG_SELECTION = `
|
|
73
|
-
id
|
|
74
|
-
userId
|
|
75
|
-
action
|
|
76
|
-
description
|
|
77
|
-
details
|
|
78
|
-
timestamp
|
|
79
|
-
productId
|
|
80
|
-
workspaceId
|
|
81
|
-
resourceType
|
|
82
|
-
resourceId
|
|
83
|
-
targetUserId
|
|
84
|
-
ipAddress
|
|
85
|
-
userAgent
|
|
86
|
-
actorType
|
|
87
|
-
onBehalfOf
|
|
88
|
-
context {
|
|
89
|
-
projectId
|
|
90
|
-
custom
|
|
91
|
-
}
|
|
92
|
-
`;
|
|
93
|
-
const RECORD_ACTIVITY_MUTATION = `
|
|
94
|
-
mutation RecordActivity($input: RecordActivityInput!) {
|
|
95
|
-
recordActivity(input: $input) {
|
|
96
|
-
${ACTIVITY_LOG_SELECTION}
|
|
97
|
-
}
|
|
98
|
-
}
|
|
99
|
-
`;
|
|
100
|
-
const WORKSPACE_ACTIVITY_SLICE_QUERY = `
|
|
101
|
-
query GetWorkspaceActivitySlice($filter: ActivityLogFilter!) {
|
|
102
|
-
getWorkspaceActivitySlice(filter: $filter) {
|
|
103
|
-
${ACTIVITY_LOG_SELECTION}
|
|
104
|
-
}
|
|
105
|
-
activityCount(filter: $filter)
|
|
106
|
-
}
|
|
107
|
-
`;
|
|
108
|
-
/**
|
|
109
|
-
* Keys the SDK stores inside `metadata`/`details` for its own fields. The owner overwrites
|
|
110
|
-
* `metadata.ipAddress`/`metadata.userAgent` with the relaying request's values, so the end
|
|
111
|
-
* user's request details travel under their own keys.
|
|
112
|
-
*/
|
|
113
|
-
const SDK_DETAIL_KEYS = [
|
|
114
|
-
"activityType",
|
|
115
|
-
"status",
|
|
116
|
-
"severity",
|
|
117
|
-
"duration",
|
|
118
|
-
"organizationId",
|
|
119
|
-
"projectId",
|
|
120
|
-
"requestIpAddress",
|
|
121
|
-
"requestUserAgent",
|
|
122
|
-
"errorMessage",
|
|
123
|
-
"ipAddress",
|
|
124
|
-
"userAgent"
|
|
125
|
-
];
|
|
126
|
-
function readRecord(value) {
|
|
127
|
-
return typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
|
|
128
|
-
}
|
|
129
|
-
function readString(value) {
|
|
130
|
-
return typeof value === "string" && value.length > 0 ? value : void 0;
|
|
131
|
-
}
|
|
132
|
-
function readEnum(values, value, fallback) {
|
|
133
|
-
const allowed = Object.values(values);
|
|
134
|
-
return typeof value === "string" && allowed.includes(value) ? value : fallback;
|
|
135
|
-
}
|
|
136
|
-
/** Remove undefined entries so the payload only names fields the caller actually set. */
|
|
137
|
-
function compact(input) {
|
|
138
|
-
return Object.fromEntries(Object.entries(input).filter(([, value]) => value !== void 0));
|
|
139
|
-
}
|
|
140
|
-
/**
|
|
141
|
-
* Build the wspace-activity-svc `RecordActivityInput` for an SDK activity.
|
|
142
|
-
* Exported for unit tests.
|
|
143
|
-
*/
|
|
144
|
-
function buildRecordActivityInput(options, context = {}) {
|
|
145
|
-
const severity = options.severity ?? "low";
|
|
146
|
-
const metadata = compact({
|
|
147
|
-
...options.metadata,
|
|
148
|
-
activityType: options.activityType,
|
|
149
|
-
status: options.status,
|
|
150
|
-
severity,
|
|
151
|
-
duration: options.duration,
|
|
152
|
-
errorMessage: options.errorMessage,
|
|
153
|
-
organizationId: options.organizationId,
|
|
154
|
-
projectId: options.projectId,
|
|
155
|
-
requestIpAddress: options.ipAddress,
|
|
156
|
-
requestUserAgent: options.userAgent
|
|
157
|
-
});
|
|
158
|
-
const activityContext = compact({
|
|
159
|
-
workspaceId: options.workspaceId,
|
|
160
|
-
userId: options.userId,
|
|
161
|
-
projectId: options.projectId,
|
|
162
|
-
custom: options.organizationId ? { organizationId: options.organizationId } : void 0
|
|
163
|
-
});
|
|
164
|
-
return compact({
|
|
165
|
-
action: options.action,
|
|
166
|
-
description: options.description,
|
|
167
|
-
resourceType: options.resourceType,
|
|
168
|
-
resourceId: options.resourceId,
|
|
169
|
-
workspaceId: options.workspaceId,
|
|
170
|
-
productId: options.productId ?? context.productId,
|
|
171
|
-
targetUserId: options.targetUserId,
|
|
172
|
-
teamId: options.teamId,
|
|
173
|
-
success: options.status !== "failure",
|
|
174
|
-
errorMessage: options.errorMessage,
|
|
175
|
-
actorType: options.actorType,
|
|
176
|
-
onBehalfOf: options.onBehalfOf,
|
|
177
|
-
context: activityContext,
|
|
178
|
-
metadata,
|
|
179
|
-
dedupeKey: options.dedupeKey ?? `sdk-activity:${randomUUID()}`
|
|
180
|
-
});
|
|
181
|
-
}
|
|
182
|
-
/**
|
|
183
|
-
* Rebuild the SDK `Activity` shape from an owner row. Fields the owner has no column for are
|
|
184
|
-
* read back from the persisted `details`. Exported for unit tests.
|
|
185
|
-
*/
|
|
186
|
-
function toActivity(record) {
|
|
187
|
-
const details = readRecord(record.details) ?? {};
|
|
188
|
-
const custom = readRecord(record.context?.custom);
|
|
189
|
-
const metadata = {};
|
|
190
|
-
for (const [key, value] of Object.entries(details)) if (!SDK_DETAIL_KEYS.includes(key)) metadata[key] = value;
|
|
191
|
-
const duration = details["duration"];
|
|
192
|
-
return {
|
|
193
|
-
id: record.id,
|
|
194
|
-
userId: record.userId,
|
|
195
|
-
activityType: readEnum(ActivityType, details["activityType"], "custom"),
|
|
196
|
-
resourceType: record.resourceType ?? "",
|
|
197
|
-
resourceId: record.resourceId ?? void 0,
|
|
198
|
-
action: record.action,
|
|
199
|
-
status: readEnum(ActivityStatus, details["status"], "success"),
|
|
200
|
-
workspaceId: record.workspaceId ?? void 0,
|
|
201
|
-
organizationId: readString(details["organizationId"]) ?? readString(custom?.["organizationId"]),
|
|
202
|
-
projectId: record.context?.projectId ?? readString(details["projectId"]),
|
|
203
|
-
productId: record.productId ?? void 0,
|
|
204
|
-
description: record.description ?? void 0,
|
|
205
|
-
targetUserId: record.targetUserId ?? void 0,
|
|
206
|
-
actorType: record.actorType ?? void 0,
|
|
207
|
-
onBehalfOf: record.onBehalfOf ?? void 0,
|
|
208
|
-
ipAddress: readString(details["requestIpAddress"]) ?? record.ipAddress ?? void 0,
|
|
209
|
-
userAgent: readString(details["requestUserAgent"]) ?? record.userAgent ?? void 0,
|
|
210
|
-
metadata,
|
|
211
|
-
severity: readEnum(ActivitySeverity, details["severity"], "low"),
|
|
212
|
-
errorMessage: readString(details["errorMessage"]),
|
|
213
|
-
duration: typeof duration === "number" && Number.isFinite(duration) ? duration : void 0,
|
|
214
|
-
createdAt: record.timestamp
|
|
215
|
-
};
|
|
216
|
-
}
|
|
217
|
-
/**
|
|
218
|
-
* Build the owner's `ActivityLogFilter` for an SDK read. Filters the owner cannot apply are
|
|
219
|
-
* rejected rather than dropped, because dropping them would return rows the caller excluded.
|
|
220
|
-
* Exported for unit tests.
|
|
221
|
-
*/
|
|
222
|
-
function buildActivityLogFilter(options) {
|
|
223
|
-
if (!options.workspaceId) throw new ValidationError("workspaceId is required to read activities");
|
|
224
|
-
const unsupported = [
|
|
225
|
-
"organizationId",
|
|
226
|
-
"projectId",
|
|
227
|
-
"activityType",
|
|
228
|
-
"status",
|
|
229
|
-
"severity",
|
|
230
|
-
"search"
|
|
231
|
-
].filter((key) => options[key] !== void 0);
|
|
232
|
-
if (options.sortBy !== void 0 && options.sortBy !== "createdAt") unsupported.push("sortBy");
|
|
233
|
-
if (options.sortOrder !== void 0 && options.sortOrder !== "desc") unsupported.push("sortOrder");
|
|
234
|
-
if (unsupported.length > 0) throw new ValidationError(`Activity filters not supported by the workspace activity owner: ${unsupported.join(", ")}`, { unsupported });
|
|
235
|
-
return compact({
|
|
236
|
-
workspaceId: options.workspaceId,
|
|
237
|
-
userId: options.userId,
|
|
238
|
-
action: options.action,
|
|
239
|
-
resourceType: options.resourceType,
|
|
240
|
-
resourceId: options.resourceId,
|
|
241
|
-
targetUserId: options.targetUserId,
|
|
242
|
-
startDate: options.startDate,
|
|
243
|
-
endDate: options.endDate,
|
|
244
|
-
limit: options.limit ?? 50,
|
|
245
|
-
offset: options.offset ?? 0
|
|
246
|
-
});
|
|
247
|
-
}
|
|
248
|
-
/**
|
|
249
|
-
* Activity Tracking Module
|
|
250
|
-
*/
|
|
251
|
-
var ActivityModule = class {
|
|
252
|
-
client;
|
|
253
|
-
context;
|
|
254
|
-
constructor(client, context) {
|
|
255
|
-
this.client = client;
|
|
256
|
-
this.context = context;
|
|
257
|
-
}
|
|
258
|
-
/**
|
|
259
|
-
* Log activity
|
|
260
|
-
*
|
|
261
|
-
* The write is relayed as a platform service acting for `userId`, the same identity
|
|
262
|
-
* transport `trackOperation` uses, so the owner records the end user as the actor and
|
|
263
|
-
* honours `actorType`/`onBehalfOf` from the input.
|
|
264
|
-
*/
|
|
265
|
-
async log(options) {
|
|
266
|
-
if (!options.userId) throw new ValidationError("User ID is required");
|
|
267
|
-
if (!options.activityType) throw new ValidationError("Activity type is required");
|
|
268
|
-
if (!options.resourceType) throw new ValidationError("Resource type is required");
|
|
269
|
-
if (!options.action) throw new ValidationError("Action is required");
|
|
270
|
-
if (!options.status) throw new ValidationError("Status is required");
|
|
271
|
-
markExplicitActivity();
|
|
272
|
-
logger.debug("[Activity] Logging activity", {
|
|
273
|
-
userId: options.userId,
|
|
274
|
-
action: options.action,
|
|
275
|
-
resourceType: options.resourceType
|
|
276
|
-
});
|
|
277
|
-
const input = buildRecordActivityInput(options, this.context);
|
|
278
|
-
const requestContext = {
|
|
279
|
-
...this.context,
|
|
280
|
-
actorId: options.userId,
|
|
281
|
-
actorType: "service",
|
|
282
|
-
workspaceId: options.workspaceId ?? this.context.workspaceId
|
|
283
|
-
};
|
|
284
|
-
const activity = toActivity((await this.client.query(RECORD_ACTIVITY_MUTATION, { input }, requestContext)).recordActivity);
|
|
285
|
-
logger.info("[Activity] Activity logged", { activityId: activity.id });
|
|
286
|
-
return activity;
|
|
287
|
-
}
|
|
288
|
-
/**
|
|
289
|
-
* Log activity with automatic status detection
|
|
290
|
-
*/
|
|
291
|
-
async logSuccess(userId, action, resourceType, resourceId, metadata) {
|
|
292
|
-
return this.log({
|
|
293
|
-
userId,
|
|
294
|
-
action,
|
|
295
|
-
resourceType,
|
|
296
|
-
resourceId,
|
|
297
|
-
activityType: this.inferActivityType(action),
|
|
298
|
-
status: "success",
|
|
299
|
-
severity: "low",
|
|
300
|
-
metadata,
|
|
301
|
-
workspaceId: this.context.workspaceId
|
|
302
|
-
});
|
|
303
|
-
}
|
|
304
|
-
/**
|
|
305
|
-
* Log failed activity
|
|
306
|
-
*/
|
|
307
|
-
async logFailure(userId, action, resourceType, errorMessage, resourceId, metadata) {
|
|
308
|
-
return this.log({
|
|
309
|
-
userId,
|
|
310
|
-
action,
|
|
311
|
-
resourceType,
|
|
312
|
-
resourceId,
|
|
313
|
-
activityType: this.inferActivityType(action),
|
|
314
|
-
status: "failure",
|
|
315
|
-
severity: "high",
|
|
316
|
-
errorMessage,
|
|
317
|
-
metadata,
|
|
318
|
-
workspaceId: this.context.workspaceId
|
|
319
|
-
});
|
|
320
|
-
}
|
|
321
|
-
/**
|
|
322
|
-
* Get one workspace's activities, newest first.
|
|
323
|
-
*
|
|
324
|
-
* Reads the owner's workspace-scoped slice (`getWorkspaceActivitySlice`) together with the
|
|
325
|
-
* matching `activityCount`, so `total` counts every row the filter matches, not just the page.
|
|
326
|
-
*/
|
|
327
|
-
async getActivities(options) {
|
|
328
|
-
logger.debug("[Activity] Getting activities", options);
|
|
329
|
-
const filter = buildActivityLogFilter(options);
|
|
330
|
-
const requestContext = {
|
|
331
|
-
...this.context,
|
|
332
|
-
workspaceId: options.workspaceId
|
|
333
|
-
};
|
|
334
|
-
const response = await this.client.query(WORKSPACE_ACTIVITY_SLICE_QUERY, { filter }, requestContext);
|
|
335
|
-
return {
|
|
336
|
-
activities: response.getWorkspaceActivitySlice.map(toActivity),
|
|
337
|
-
total: response.activityCount
|
|
338
|
-
};
|
|
339
|
-
}
|
|
340
|
-
/**
|
|
341
|
-
* @deprecated The workspace activity owner has no read-by-id operation. Use
|
|
342
|
-
* {@link getActivities} with `resourceId`/`action` filters instead.
|
|
343
|
-
*/
|
|
344
|
-
async getActivity(_activityId) {
|
|
345
|
-
throw new ActivityOperationUnsupportedError("getActivity", "use getActivities with a workspace filter");
|
|
346
|
-
}
|
|
347
|
-
/**
|
|
348
|
-
* @deprecated The workspace activity owner has no statistics operation. Use
|
|
349
|
-
* {@link getActivities} (its `total` is the owner's `activityCount`) per filter instead.
|
|
350
|
-
*/
|
|
351
|
-
async getStats(_options) {
|
|
352
|
-
throw new ActivityOperationUnsupportedError("getStats", "use getActivities and its total per filter");
|
|
353
|
-
}
|
|
354
|
-
/**
|
|
355
|
-
* @deprecated Retention is enforced by the activity owner's retention policy and legal holds;
|
|
356
|
-
* there is no client-driven cleanup operation.
|
|
357
|
-
*/
|
|
358
|
-
async cleanup(_olderThanDays, _workspaceId) {
|
|
359
|
-
throw new ActivityOperationUnsupportedError("cleanup", "retention is enforced by the activity owner");
|
|
360
|
-
}
|
|
361
|
-
/**
|
|
362
|
-
* @deprecated The workspace activity owner exports through `exportActivityLogsSiem`
|
|
363
|
-
* (CEF/LEEF/JSON lines); there is no CSV export operation.
|
|
364
|
-
*/
|
|
365
|
-
async exportToCSV(_options) {
|
|
366
|
-
throw new ActivityOperationUnsupportedError("exportToCSV", "use the owner exportActivityLogsSiem query");
|
|
367
|
-
}
|
|
368
|
-
/**
|
|
369
|
-
* Infer activity type from action string
|
|
370
|
-
*/
|
|
371
|
-
inferActivityType(action) {
|
|
372
|
-
const actionLower = action.toLowerCase();
|
|
373
|
-
if (actionLower.includes("create") || actionLower.includes("add")) return "create";
|
|
374
|
-
if (actionLower.includes("update") || actionLower.includes("edit") || actionLower.includes("modify")) return "update";
|
|
375
|
-
if (actionLower.includes("delete") || actionLower.includes("remove")) return "delete";
|
|
376
|
-
if (actionLower.includes("read") || actionLower.includes("view") || actionLower.includes("get")) return "read";
|
|
377
|
-
if (actionLower.includes("login") || actionLower.includes("signin")) return "login";
|
|
378
|
-
if (actionLower.includes("logout") || actionLower.includes("signout")) return "logout";
|
|
379
|
-
if (actionLower.includes("export")) return "export";
|
|
380
|
-
if (actionLower.includes("import")) return "import";
|
|
381
|
-
if (actionLower.includes("share")) return "share";
|
|
382
|
-
if (actionLower.includes("download")) return "download";
|
|
383
|
-
if (actionLower.includes("upload")) return "upload";
|
|
384
|
-
if (actionLower.includes("execute") || actionLower.includes("run")) return "execute";
|
|
385
|
-
if (actionLower.includes("approve")) return "approve";
|
|
386
|
-
if (actionLower.includes("reject")) return "reject";
|
|
387
|
-
return "custom";
|
|
388
|
-
}
|
|
389
|
-
};
|
|
3
|
+
import { t as RBACModule } from "./rbac-Dvz0YzEt.js";
|
|
4
|
+
import { ActivityModule, ActivitySeverity, ActivityStatus, ActivityType } from "./activity/index.js";
|
|
5
|
+
import { a as UsageModule } from "./usage-BRqVP3CJ.js";
|
|
6
|
+
import { n as NotificationType, r as NotificationsModule } from "./notifications-DY_i37WN.js";
|
|
7
|
+
import { o as trackOperation } from "./stub-BUnfMiAS.js";
|
|
8
|
+
import { r as runInExplicitActivityScope, t as createExplicitActivityScope } from "./explicit-activity-scope-DikJ7NAE.js";
|
|
390
9
|
|
|
391
10
|
// src/tracker/agent-activity.ts
|
|
392
11
|
/**
|
|
@@ -835,5 +454,5 @@ var TrackerModule = class {
|
|
|
835
454
|
}
|
|
836
455
|
};
|
|
837
456
|
|
|
838
|
-
export {
|
|
839
|
-
//# sourceMappingURL=tracker-
|
|
457
|
+
export { trackAgentActivity as i, AGENT_ACTIVITY_ACTIONS as n, AGENT_ACTIVITY_RESOURCE_TYPE as r, TrackerModule as t };
|
|
458
|
+
//# sourceMappingURL=tracker-PQztSlhJ.js.map
|