@sentry/server-utils 11.16.0 → 11.18.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/build/cjs/chunks/config.js +62 -2
- package/build/cjs/chunks/config.js.map +1 -1
- package/build/cjs/chunks/exports.js +231 -66
- package/build/cjs/chunks/exports.js.map +1 -1
- package/build/cjs/chunks/moduleInjectedTransform.js +8 -0
- package/build/cjs/chunks/moduleInjectedTransform.js.map +1 -1
- package/build/cjs/index.js +447 -199
- package/build/cjs/index.js.map +1 -1
- package/build/cjs/index.no-diagnostic-channels.js +1 -0
- package/build/cjs/index.request-handler.js +48 -3
- package/build/cjs/index.request-handler.js.map +1 -1
- package/build/esm/ai/langchain/embeddings.js +23 -8
- package/build/esm/ai/langchain/embeddings.js.map +1 -1
- package/build/esm/ai/langchain/index.js +41 -30
- package/build/esm/ai/langchain/index.js.map +1 -1
- package/build/esm/ai/langchain/utils.js +1 -5
- package/build/esm/ai/langchain/utils.js.map +1 -1
- package/build/esm/ai/langgraph/agent-span.js +6 -2
- package/build/esm/ai/langgraph/agent-span.js.map +1 -1
- package/build/esm/ai/langgraph/index.js +5 -1
- package/build/esm/ai/langgraph/index.js.map +1 -1
- package/build/esm/ai/langgraph/stream.js +4 -1
- package/build/esm/ai/langgraph/stream.js.map +1 -1
- package/build/esm/ai/mistral/streaming.js.map +1 -1
- package/build/esm/ai/pi-durable/index.js +10 -13
- package/build/esm/ai/pi-durable/index.js.map +1 -1
- package/build/esm/ai/pi-durable/runs.js +6 -5
- package/build/esm/ai/pi-durable/runs.js.map +1 -1
- package/build/esm/ai/pi-durable/tools.js +21 -17
- package/build/esm/ai/pi-durable/tools.js.map +1 -1
- package/build/esm/exports.js +2 -1
- package/build/esm/index.js +5 -2
- package/build/esm/index.js.map +1 -1
- package/build/esm/index.no-diagnostic-channels.js +2 -1
- package/build/esm/index.request-handler.js +3 -1
- package/build/esm/integrations/amqplib.js.map +1 -1
- package/build/esm/integrations/anthropic.js.map +1 -1
- package/build/esm/integrations/bullmq/tracer.js.map +1 -1
- package/build/esm/integrations/clickhouse-sql.js +31 -0
- package/build/esm/integrations/clickhouse-sql.js.map +1 -0
- package/build/esm/integrations/clickhouse.js +88 -0
- package/build/esm/integrations/clickhouse.js.map +1 -0
- package/build/esm/integrations/express/instrumentation.js +1 -0
- package/build/esm/integrations/express/instrumentation.js.map +1 -1
- package/build/esm/integrations/fastify/instrumentation.js +3 -1
- package/build/esm/integrations/fastify/instrumentation.js.map +1 -1
- package/build/esm/integrations/graphql/utils.js.map +1 -1
- package/build/esm/integrations/hapi/hapi-utils.js +6 -9
- package/build/esm/integrations/hapi/hapi-utils.js.map +1 -1
- package/build/esm/integrations/hapi/index.js +15 -1
- package/build/esm/integrations/hapi/index.js.map +1 -1
- package/build/esm/integrations/hono/isMiddleware.js.map +1 -1
- package/build/esm/integrations/hono/middlewareHandlers.js +3 -1
- package/build/esm/integrations/hono/middlewareHandlers.js.map +1 -1
- package/build/esm/integrations/hono/patchRoute.js +2 -1
- package/build/esm/integrations/hono/patchRoute.js.map +1 -1
- package/build/esm/integrations/hono/unwrapThrownValue.js +20 -0
- package/build/esm/integrations/hono/unwrapThrownValue.js.map +1 -0
- package/build/esm/integrations/index.js +2 -0
- package/build/esm/integrations/index.js.map +1 -1
- package/build/esm/integrations/langchain.js +10 -3
- package/build/esm/integrations/langchain.js.map +1 -1
- package/build/esm/integrations/mongodb/mongodb-span.js +7 -9
- package/build/esm/integrations/mongodb/mongodb-span.js.map +1 -1
- package/build/esm/integrations/pino.js +2 -2
- package/build/esm/integrations/pino.js.map +1 -1
- package/build/esm/integrations/prisma/tracing-helper.js.map +1 -1
- package/build/esm/integrations/serveTunnel.js +2 -2
- package/build/esm/integrations/serveTunnel.js.map +1 -1
- package/build/esm/integrations/vercel-ai/extract.js +88 -0
- package/build/esm/integrations/vercel-ai/extract.js.map +1 -0
- package/build/esm/integrations/vercel-ai/util.js +5 -1
- package/build/esm/integrations/vercel-ai/util.js.map +1 -1
- package/build/esm/integrations/vercel-ai/vercel-ai-dc-subscriber.js +19 -9
- package/build/esm/integrations/vercel-ai/vercel-ai-dc-subscriber.js.map +1 -1
- package/build/esm/integrations/winston.js +2 -2
- package/build/esm/integrations/winston.js.map +1 -1
- package/build/esm/orchestrion/channels.js +2 -0
- package/build/esm/orchestrion/channels.js.map +1 -1
- package/build/esm/orchestrion/config/channel-integration-definitions.js +8 -0
- package/build/esm/orchestrion/config/channel-integration-definitions.js.map +1 -1
- package/build/esm/orchestrion/config/clickhouse.js +51 -0
- package/build/esm/orchestrion/config/clickhouse.js.map +1 -0
- package/build/esm/orchestrion/config/hono.js +2 -2
- package/build/esm/orchestrion/config/hono.js.map +1 -1
- package/build/esm/orchestrion/config/index.js +2 -0
- package/build/esm/orchestrion/config/index.js.map +1 -1
- package/build/esm/package.json +1 -1
- package/build/esm/utils/installedModules.js +87 -0
- package/build/esm/utils/installedModules.js.map +1 -0
- package/build/esm/utils/module.js +29 -0
- package/build/esm/utils/module.js.map +1 -0
- package/build/esm/utils/serverTimingTraceHeader.js +49 -0
- package/build/esm/utils/serverTimingTraceHeader.js.map +1 -0
- package/build/esm/utils/sql.js +41 -19
- package/build/esm/utils/sql.js.map +1 -1
- package/build/esm/utils/tunnelServer.js +3 -3
- package/build/esm/utils/tunnelServer.js.map +1 -1
- package/build/esm/utils/wrapServerRequestHandler.js +5 -4
- package/build/esm/utils/wrapServerRequestHandler.js.map +1 -1
- package/build/types/ai/langchain/embeddings.d.ts +2 -2
- package/build/types/ai/langchain/embeddings.d.ts.map +1 -1
- package/build/types/ai/langchain/index.d.ts.map +1 -1
- package/build/types/ai/langchain/types.d.ts +8 -4
- package/build/types/ai/langchain/types.d.ts.map +1 -1
- package/build/types/ai/langchain/utils.d.ts.map +1 -1
- package/build/types/ai/langgraph/agent-span.d.ts +5 -2
- package/build/types/ai/langgraph/agent-span.d.ts.map +1 -1
- package/build/types/ai/langgraph/index.d.ts.map +1 -1
- package/build/types/ai/langgraph/stream.d.ts.map +1 -1
- package/build/types/ai/langgraph/types.d.ts +10 -2
- package/build/types/ai/langgraph/types.d.ts.map +1 -1
- package/build/types/ai/mistral/streaming.d.ts.map +1 -1
- package/build/types/ai/pi-durable/index.d.ts.map +1 -1
- package/build/types/ai/pi-durable/runs.d.ts +4 -2
- package/build/types/ai/pi-durable/runs.d.ts.map +1 -1
- package/build/types/ai/pi-durable/tools.d.ts +4 -6
- package/build/types/ai/pi-durable/tools.d.ts.map +1 -1
- package/build/types/ai/pi-durable/types.d.ts +10 -1
- package/build/types/ai/pi-durable/types.d.ts.map +1 -1
- package/build/types/exports.d.ts +1 -0
- package/build/types/exports.d.ts.map +1 -1
- package/build/types/index.d.ts +5 -3
- package/build/types/index.d.ts.map +1 -1
- package/build/types/index.request-handler.d.ts +1 -0
- package/build/types/index.request-handler.d.ts.map +1 -1
- package/build/types/integrations/amqplib.d.ts.map +1 -1
- package/build/types/integrations/anthropic.d.ts.map +1 -1
- package/build/types/integrations/bullmq/tracer.d.ts.map +1 -1
- package/build/types/integrations/clickhouse-sql.d.ts +8 -0
- package/build/types/integrations/clickhouse-sql.d.ts.map +1 -0
- package/build/types/integrations/clickhouse.d.ts +11 -0
- package/build/types/integrations/clickhouse.d.ts.map +1 -0
- package/build/types/integrations/express/types.d.ts +1 -0
- package/build/types/integrations/express/types.d.ts.map +1 -1
- package/build/types/integrations/fastify/instrumentation.d.ts.map +1 -1
- package/build/types/integrations/hapi/hapi-utils.d.ts.map +1 -1
- package/build/types/integrations/hapi/index.d.ts +12 -0
- package/build/types/integrations/hapi/index.d.ts.map +1 -1
- package/build/types/integrations/hono/isMiddleware.d.ts.map +1 -1
- package/build/types/integrations/hono/middlewareHandlers.d.ts.map +1 -1
- package/build/types/integrations/hono/patchRoute.d.ts.map +1 -1
- package/build/types/integrations/hono/unwrapThrownValue.d.ts +10 -0
- package/build/types/integrations/hono/unwrapThrownValue.d.ts.map +1 -0
- package/build/types/integrations/index.d.ts.map +1 -1
- package/build/types/integrations/langchain.d.ts.map +1 -1
- package/build/types/integrations/mongodb/mongodb-span.d.ts.map +1 -1
- package/build/types/integrations/prisma/tracing-helper.d.ts.map +1 -1
- package/build/types/integrations/vercel-ai/extract.d.ts +27 -0
- package/build/types/integrations/vercel-ai/extract.d.ts.map +1 -0
- package/build/types/integrations/vercel-ai/util.d.ts +2 -0
- package/build/types/integrations/vercel-ai/util.d.ts.map +1 -1
- package/build/types/integrations/vercel-ai/vercel-ai-dc-subscriber.d.ts +1 -1
- package/build/types/integrations/vercel-ai/vercel-ai-dc-subscriber.d.ts.map +1 -1
- package/build/types/orchestrion/channels.d.ts +12 -0
- package/build/types/orchestrion/channels.d.ts.map +1 -1
- package/build/types/orchestrion/config/channel-integration-definitions.d.ts +3 -0
- package/build/types/orchestrion/config/channel-integration-definitions.d.ts.map +1 -1
- package/build/types/orchestrion/config/clickhouse.d.ts +18 -0
- package/build/types/orchestrion/config/clickhouse.d.ts.map +1 -0
- package/build/types/orchestrion/config/index.d.ts.map +1 -1
- package/build/types/utils/installedModules.d.ts +17 -0
- package/build/types/utils/installedModules.d.ts.map +1 -0
- package/build/types/utils/module.d.ts +3 -0
- package/build/types/utils/module.d.ts.map +1 -0
- package/build/types/utils/serverTimingTraceHeader.d.ts +18 -0
- package/build/types/utils/serverTimingTraceHeader.d.ts.map +1 -0
- package/build/types/utils/sql.d.ts +28 -3
- package/build/types/utils/sql.d.ts.map +1 -1
- package/build/types/utils/tunnelServer.d.ts.map +1 -1
- package/build/types/utils/wrapServerRequestHandler.d.ts.map +1 -1
- package/package.json +4 -4
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":[],"sources":["../../../../src/orchestrion/config/index.ts"],"sourcesContent":["import type { InstrumentationConfig } from '../apmTypes';\n\nimport { uniq } from '@sentry/core';\n\nimport { awsSdkConfig } from './aws-sdk';\nimport { amqplibConfig } from './amqplib';\nimport { anthropicAiConfig } from './anthropic-ai';\nimport { cronConfig } from './cron';\nimport { dataloaderConfig } from './dataloader';\nimport { expressConfig } from './express';\nimport { firebaseConfig } from './firebase';\nimport { genericPoolConfig } from './generic-pool';\nimport { googleGenAiConfig } from './google-genai';\nimport { graphqlConfig } from './graphql';\nimport { groqConfig } from './groq';\nimport { hapiConfig } from './hapi';\nimport { honoConfig } from './hono';\nimport { ioredisConfig } from './ioredis';\nimport { kafkajsConfig } from './kafkajs';\nimport { knexConfig } from './knex';\nimport { koaConfig } from './koa';\nimport { langchainConfig } from './langchain';\nimport { langgraphConfig } from './langgraph';\nimport { lruMemoizerConfig } from './lru-memoizer';\nimport { flueConfig } from './flue';\nimport { mastraConfig } from './mastra';\nimport { piAiConfig } from './pi-ai';\nimport { piDurableConfig } from './pi-durable';\nimport { mcpServerConfig } from './mcp-server';\nimport { mistralConfig } from './mistral';\nimport { mongodbConfig } from './mongodb';\nimport { mongooseConfig } from './mongoose';\nimport { mysql2Config } from './mysql2';\nimport { mysqlConfig } from './mysql';\nimport { neonConfig } from './neon';\nimport { nestjsConfig } from './nestjs';\nimport { nitroConfig } from './nitro';\nimport { nodeCronConfig } from './node-cron';\nimport { nodeScheduleConfig } from './node-schedule';\nimport { openaiConfig } from './openai';\nimport { pgConfig } from './pg';\nimport { postgresJsConfig } from './postgres';\nimport { prismaConfig } from './prisma';\nimport { redisConfig } from './redis';\nimport { remixConfig } from './remix';\nimport { remixV3Config } from './remix-v3';\nimport { tediousConfig } from './tedious';\nimport { togetherAiConfig } from './together-ai';\nimport { typesafeConfig } from './typesafe';\nimport { vercelAiConfig } from './vercel-ai';\n// Kept sorted alphabetically by module so concurrent additions insert at different\n// points rather than all appending to the end (fewer merge conflicts).\n\n/**\n * The orchestrion code-transform configs. Every instrumentable library is here\n * so the transform is all-or-nothing: whenever orchestrion is enabled, all of\n * these are injected. The channel LISTENERS may live elsewhere (e.g. the NestJS\n * one lives in `@sentry/nestjs`), but the config that decides what gets\n * transformed is centralized here.\n *\n * This module MUST stay pure, stateless data. It is loaded in more than one realm\n * at once — the build-time bundler plugin inlines it into the server chunk, while\n * `@sentry/server-runtime-injection`'s external `register` loads its own copy from\n * `node_modules` at runtime. Two identical, side-effect-free arrays are harmless;\n * any module-level mutable state here would silently diverge between those copies.\n */\nexport const SENTRY_INSTRUMENTATIONS: InstrumentationConfig[] = [\n ...amqplibConfig,\n ...anthropicAiConfig,\n ...awsSdkConfig,\n ...cronConfig,\n ...dataloaderConfig,\n ...expressConfig,\n ...firebaseConfig,\n ...genericPoolConfig,\n ...googleGenAiConfig,\n ...graphqlConfig,\n ...groqConfig,\n ...hapiConfig,\n ...honoConfig,\n ...ioredisConfig,\n ...kafkajsConfig,\n ...knexConfig,\n ...koaConfig,\n ...langchainConfig,\n ...langgraphConfig,\n ...lruMemoizerConfig,\n ...flueConfig,\n ...mastraConfig,\n ...mcpServerConfig,\n ...mistralConfig,\n ...mongodbConfig,\n ...mongooseConfig,\n ...mysql2Config,\n ...mysqlConfig,\n ...neonConfig,\n ...nestjsConfig,\n ...nitroConfig,\n ...nodeCronConfig,\n ...nodeScheduleConfig,\n ...openaiConfig,\n ...pgConfig,\n ...piAiConfig,\n ...piDurableConfig,\n ...postgresJsConfig,\n ...prismaConfig,\n ...redisConfig,\n ...remixConfig,\n ...remixV3Config,\n ...tediousConfig,\n ...togetherAiConfig,\n ...typesafeConfig,\n ...vercelAiConfig,\n];\n\n/**\n * The subset of {@link SENTRY_INSTRUMENTATIONS} the RUNTIME loader\n * (`@sentry/server-runtime-injection`'s `register`, reached via `--import` or\n * `Sentry.init()`) can actually apply.\n *\n * Registration-only configs (native-channel libraries such as `ai` v7,\n * `ioredis`, `@redis/client`, `mysql2`, `mongoose`) carry the custom\n * `MODULE_REGISTRATION_TRANSFORM` operator. That operator is wired into the\n * BUNDLER plugins only (see `orchestrion/bundler/moduleInjectedTransform.ts`,\n * applied via `bundler/options.ts`'s `customTransforms`); the runtime loader's\n * `initialize()` receives no custom transforms. Attempting one of these at\n * runtime therefore throws `TypeError: transform is not a function`, which the\n * loader misreports as the always-on \"`@sentry/server-runtime-injection` was\n * bundled ... loads uninstrumented\" warning even though nothing is wrong.\n *\n * Excluding them at runtime is correct, not just a way to silence the warning:\n * these libraries publish their own tracing channels, and their integrations\n * subscribe through `setupOnce()` / `waitForTracingChannelBinding`,\n * independently of the module-injected snippet. That snippet only fires\n * `orchestrion.module-injected`, which drives the `setup()` /\n * `invokeOrchestrionInstrumentation` path; for a native-channel version that\n * path subscribes to the injected `orchestrion:*` channels the library never\n * publishes — a no-op. So running these at runtime would add no spans. The\n * snippet earns its keep only on the BUNDLER path — notably bundler-only SDKs\n * (e.g. `@sentry/cloudflare`) that discover a loaded module via that event to\n * instantiate its integration factory. `@sentry/node` registers its\n * integrations statically, so it does not need it.\n */\nexport const SENTRY_RUNTIME_INSTRUMENTATIONS: InstrumentationConfig[] = SENTRY_INSTRUMENTATIONS.filter(\n config => !config.transform,\n);\n\n/**\n * The unique set of package names instrumented by `SENTRY_INSTRUMENTATIONS`\n * merged with any caller-provided `instrumentations` (e.g. `['mysql']`).\n *\n * Bundler plugins MUST ensure these are actually bundled rather than\n * externalized: an externalized dependency is resolved from `node_modules` at\n * runtime and never passes through the code transform's `onLoad`, so its\n * diagnostics_channel calls are silently never injected. This includes a\n * plugin's custom `instrumentations`, otherwise those extra packages can stay\n * externalized and their transform never runs.\n */\nexport function instrumentedModuleNames(instrumentations: InstrumentationConfig[] = []): string[] {\n return [\n ...uniq([...SENTRY_INSTRUMENTATIONS, ...instrumentations].map(i => i.module.name)),\n // Additional things that need to be bundled but are not covered by the above\n // Remix needs to bundle this so @remix-run/server-runtime is _also_ bundled\n '@remix-run/node',\n ];\n}\n\n/** The instrumented module names from the default Sentry config, with no custom additions. */\nexport const INSTRUMENTED_MODULE_NAMES: string[] = instrumentedModuleNames();\n\n/**\n * The package names the SDK instruments through the orchestrion module transform (its\n * diagnostics-channel injection). Pass these to a server bundler's \"keep external\" option so the\n * packages load through Node's module loader — the only path the transform can hook — instead of\n * being inlined into the server bundle. A framework that has no Sentry bundler plugin (e.g. eve, via\n * `build.externalDependencies`) is the main caller; a listed package the app doesn't use is simply\n * ignored by the bundler.\n *\n * Unlike {@link INSTRUMENTED_MODULE_NAMES}, this is the plain instrumented set with no bundler-only\n * additions — those force a helper package to be *bundled*, the opposite of keeping it external.\n */\nexport function getInstrumentedModuleNames(): string[] {\n return uniq(SENTRY_INSTRUMENTATIONS.map(instrumentation => instrumentation.module.name));\n}\n\n/**\n * Returns `external` with any instrumented packages removed, so a bundler that\n * uses an \"external\" denylist (esbuild, Bun, Rollup) still bundles — and thus\n * transforms — them. Matches an exact package name (`'mysql'`) or a subpath\n * (`'mysql/lib/...'`); wildcard/other patterns are left untouched. `undefined`\n * is returned unchanged.\n *\n * Pass `moduleNames` from `instrumentedModuleNames(options.instrumentations)` so\n * custom instrumentations are stripped too; it defaults to the Sentry config\n * list. (Vite uses an `ssr.noExternal` allowlist instead, so it consumes\n * `instrumentedModuleNames` directly rather than this helper.)\n */\nexport function withoutInstrumentedExternals(\n external: readonly string[] | undefined,\n moduleNames: string[] = INSTRUMENTED_MODULE_NAMES,\n): string[] | undefined {\n if (!external) {\n return undefined;\n }\n return external.filter(entry => !moduleNames.some(name => entry === name || entry.startsWith(`${name}/`)));\n}\n\n// This is exported so that the nestjs package can use it to subscribe to the channels.\nexport { nestjsChannels } from './nestjs';\n// This is exported so that the remix package can use it to subscribe to the channels.\nexport { remixChannels } from './remix';\n// Exported so the remix package can subscribe to the Remix 3 channels, and hand only these configs to\n// the browser transform.\nexport { remixV3Channels, remixV3Config } from './remix-v3';\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkEA,MAAa,0BAAmD;CAC9D,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;AACL;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8BA,MAAa,kCAA2D,wBAAwB,QAC9F,WAAU,CAAC,OAAO,SACpB;;;;;;;;;;;;AAaA,SAAgB,wBAAwB,mBAA4C,CAAC,GAAa;CAChG,OAAO,CACL,GAAG,KAAK,CAAC,GAAG,yBAAyB,GAAG,gBAAgB,CAAC,CAAC,KAAI,MAAK,EAAE,OAAO,IAAI,CAAC,GAGjF,iBACF;AACF;;AAGA,MAAa,4BAAsC,wBAAwB;;;;;;;;;;;;AAa3E,SAAgB,6BAAuC;CACrD,OAAO,KAAK,wBAAwB,KAAI,oBAAmB,gBAAgB,OAAO,IAAI,CAAC;AACzF;;;;;;;;;;;;;AAcA,SAAgB,6BACd,UACA,cAAwB,2BACF;CACtB,IAAI,CAAC,UACH;CAEF,OAAO,SAAS,QAAO,UAAS,CAAC,YAAY,MAAK,SAAQ,UAAU,QAAQ,MAAM,WAAW,GAAG,KAAK,EAAE,CAAC,CAAC;AAC3G"}
|
|
1
|
+
{"version":3,"file":"index.js","names":[],"sources":["../../../../src/orchestrion/config/index.ts"],"sourcesContent":["import type { InstrumentationConfig } from '../apmTypes';\n\nimport { uniq } from '@sentry/core';\n\nimport { awsSdkConfig } from './aws-sdk';\nimport { amqplibConfig } from './amqplib';\nimport { anthropicAiConfig } from './anthropic-ai';\nimport { clickhouseConfig } from './clickhouse';\nimport { cronConfig } from './cron';\nimport { dataloaderConfig } from './dataloader';\nimport { expressConfig } from './express';\nimport { firebaseConfig } from './firebase';\nimport { genericPoolConfig } from './generic-pool';\nimport { googleGenAiConfig } from './google-genai';\nimport { graphqlConfig } from './graphql';\nimport { groqConfig } from './groq';\nimport { hapiConfig } from './hapi';\nimport { honoConfig } from './hono';\nimport { ioredisConfig } from './ioredis';\nimport { kafkajsConfig } from './kafkajs';\nimport { knexConfig } from './knex';\nimport { koaConfig } from './koa';\nimport { langchainConfig } from './langchain';\nimport { langgraphConfig } from './langgraph';\nimport { lruMemoizerConfig } from './lru-memoizer';\nimport { flueConfig } from './flue';\nimport { mastraConfig } from './mastra';\nimport { piAiConfig } from './pi-ai';\nimport { piDurableConfig } from './pi-durable';\nimport { mcpServerConfig } from './mcp-server';\nimport { mistralConfig } from './mistral';\nimport { mongodbConfig } from './mongodb';\nimport { mongooseConfig } from './mongoose';\nimport { mysql2Config } from './mysql2';\nimport { mysqlConfig } from './mysql';\nimport { neonConfig } from './neon';\nimport { nestjsConfig } from './nestjs';\nimport { nitroConfig } from './nitro';\nimport { nodeCronConfig } from './node-cron';\nimport { nodeScheduleConfig } from './node-schedule';\nimport { openaiConfig } from './openai';\nimport { pgConfig } from './pg';\nimport { postgresJsConfig } from './postgres';\nimport { prismaConfig } from './prisma';\nimport { redisConfig } from './redis';\nimport { remixConfig } from './remix';\nimport { remixV3Config } from './remix-v3';\nimport { tediousConfig } from './tedious';\nimport { togetherAiConfig } from './together-ai';\nimport { typesafeConfig } from './typesafe';\nimport { vercelAiConfig } from './vercel-ai';\n// Kept sorted alphabetically by module so concurrent additions insert at different\n// points rather than all appending to the end (fewer merge conflicts).\n\n/**\n * The orchestrion code-transform configs. Every instrumentable library is here\n * so the transform is all-or-nothing: whenever orchestrion is enabled, all of\n * these are injected. The channel LISTENERS may live elsewhere (e.g. the NestJS\n * one lives in `@sentry/nestjs`), but the config that decides what gets\n * transformed is centralized here.\n *\n * This module MUST stay pure, stateless data. It is loaded in more than one realm\n * at once — the build-time bundler plugin inlines it into the server chunk, while\n * `@sentry/server-runtime-injection`'s external `register` loads its own copy from\n * `node_modules` at runtime. Two identical, side-effect-free arrays are harmless;\n * any module-level mutable state here would silently diverge between those copies.\n */\nexport const SENTRY_INSTRUMENTATIONS: InstrumentationConfig[] = [\n ...amqplibConfig,\n ...anthropicAiConfig,\n ...awsSdkConfig,\n ...clickhouseConfig,\n ...cronConfig,\n ...dataloaderConfig,\n ...expressConfig,\n ...firebaseConfig,\n ...genericPoolConfig,\n ...googleGenAiConfig,\n ...graphqlConfig,\n ...groqConfig,\n ...hapiConfig,\n ...honoConfig,\n ...ioredisConfig,\n ...kafkajsConfig,\n ...knexConfig,\n ...koaConfig,\n ...langchainConfig,\n ...langgraphConfig,\n ...lruMemoizerConfig,\n ...flueConfig,\n ...mastraConfig,\n ...mcpServerConfig,\n ...mistralConfig,\n ...mongodbConfig,\n ...mongooseConfig,\n ...mysql2Config,\n ...mysqlConfig,\n ...neonConfig,\n ...nestjsConfig,\n ...nitroConfig,\n ...nodeCronConfig,\n ...nodeScheduleConfig,\n ...openaiConfig,\n ...pgConfig,\n ...piAiConfig,\n ...piDurableConfig,\n ...postgresJsConfig,\n ...prismaConfig,\n ...redisConfig,\n ...remixConfig,\n ...remixV3Config,\n ...tediousConfig,\n ...togetherAiConfig,\n ...typesafeConfig,\n ...vercelAiConfig,\n];\n\n/**\n * The subset of {@link SENTRY_INSTRUMENTATIONS} the RUNTIME loader\n * (`@sentry/server-runtime-injection`'s `register`, reached via `--import` or\n * `Sentry.init()`) can actually apply.\n *\n * Registration-only configs (native-channel libraries such as `ai` v7,\n * `ioredis`, `@redis/client`, `mysql2`, `mongoose`) carry the custom\n * `MODULE_REGISTRATION_TRANSFORM` operator. That operator is wired into the\n * BUNDLER plugins only (see `orchestrion/bundler/moduleInjectedTransform.ts`,\n * applied via `bundler/options.ts`'s `customTransforms`); the runtime loader's\n * `initialize()` receives no custom transforms. Attempting one of these at\n * runtime therefore throws `TypeError: transform is not a function`, which the\n * loader misreports as the always-on \"`@sentry/server-runtime-injection` was\n * bundled ... loads uninstrumented\" warning even though nothing is wrong.\n *\n * Excluding them at runtime is correct, not just a way to silence the warning:\n * these libraries publish their own tracing channels, and their integrations\n * subscribe through `setupOnce()` / `waitForTracingChannelBinding`,\n * independently of the module-injected snippet. That snippet only fires\n * `orchestrion.module-injected`, which drives the `setup()` /\n * `invokeOrchestrionInstrumentation` path; for a native-channel version that\n * path subscribes to the injected `orchestrion:*` channels the library never\n * publishes — a no-op. So running these at runtime would add no spans. The\n * snippet earns its keep only on the BUNDLER path — notably bundler-only SDKs\n * (e.g. `@sentry/cloudflare`) that discover a loaded module via that event to\n * instantiate its integration factory. `@sentry/node` registers its\n * integrations statically, so it does not need it.\n */\nexport const SENTRY_RUNTIME_INSTRUMENTATIONS: InstrumentationConfig[] = SENTRY_INSTRUMENTATIONS.filter(\n config => !config.transform,\n);\n\n/**\n * The unique set of package names instrumented by `SENTRY_INSTRUMENTATIONS`\n * merged with any caller-provided `instrumentations` (e.g. `['mysql']`).\n *\n * Bundler plugins MUST ensure these are actually bundled rather than\n * externalized: an externalized dependency is resolved from `node_modules` at\n * runtime and never passes through the code transform's `onLoad`, so its\n * diagnostics_channel calls are silently never injected. This includes a\n * plugin's custom `instrumentations`, otherwise those extra packages can stay\n * externalized and their transform never runs.\n */\nexport function instrumentedModuleNames(instrumentations: InstrumentationConfig[] = []): string[] {\n return [\n ...uniq([...SENTRY_INSTRUMENTATIONS, ...instrumentations].map(i => i.module.name)),\n // Additional things that need to be bundled but are not covered by the above\n // Remix needs to bundle this so @remix-run/server-runtime is _also_ bundled\n '@remix-run/node',\n ];\n}\n\n/** The instrumented module names from the default Sentry config, with no custom additions. */\nexport const INSTRUMENTED_MODULE_NAMES: string[] = instrumentedModuleNames();\n\n/**\n * The package names the SDK instruments through the orchestrion module transform (its\n * diagnostics-channel injection). Pass these to a server bundler's \"keep external\" option so the\n * packages load through Node's module loader — the only path the transform can hook — instead of\n * being inlined into the server bundle. A framework that has no Sentry bundler plugin (e.g. eve, via\n * `build.externalDependencies`) is the main caller; a listed package the app doesn't use is simply\n * ignored by the bundler.\n *\n * Unlike {@link INSTRUMENTED_MODULE_NAMES}, this is the plain instrumented set with no bundler-only\n * additions — those force a helper package to be *bundled*, the opposite of keeping it external.\n */\nexport function getInstrumentedModuleNames(): string[] {\n return uniq(SENTRY_INSTRUMENTATIONS.map(instrumentation => instrumentation.module.name));\n}\n\n/**\n * Returns `external` with any instrumented packages removed, so a bundler that\n * uses an \"external\" denylist (esbuild, Bun, Rollup) still bundles — and thus\n * transforms — them. Matches an exact package name (`'mysql'`) or a subpath\n * (`'mysql/lib/...'`); wildcard/other patterns are left untouched. `undefined`\n * is returned unchanged.\n *\n * Pass `moduleNames` from `instrumentedModuleNames(options.instrumentations)` so\n * custom instrumentations are stripped too; it defaults to the Sentry config\n * list. (Vite uses an `ssr.noExternal` allowlist instead, so it consumes\n * `instrumentedModuleNames` directly rather than this helper.)\n */\nexport function withoutInstrumentedExternals(\n external: readonly string[] | undefined,\n moduleNames: string[] = INSTRUMENTED_MODULE_NAMES,\n): string[] | undefined {\n if (!external) {\n return undefined;\n }\n return external.filter(entry => !moduleNames.some(name => entry === name || entry.startsWith(`${name}/`)));\n}\n\n// This is exported so that the nestjs package can use it to subscribe to the channels.\nexport { nestjsChannels } from './nestjs';\n// This is exported so that the remix package can use it to subscribe to the channels.\nexport { remixChannels } from './remix';\n// Exported so the remix package can subscribe to the Remix 3 channels, and hand only these configs to\n// the browser transform.\nexport { remixV3Channels, remixV3Config } from './remix-v3';\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAmEA,MAAa,0BAAmD;CAC9D,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;AACL;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8BA,MAAa,kCAA2D,wBAAwB,QAC9F,WAAU,CAAC,OAAO,SACpB;;;;;;;;;;;;AAaA,SAAgB,wBAAwB,mBAA4C,CAAC,GAAa;CAChG,OAAO,CACL,GAAG,KAAK,CAAC,GAAG,yBAAyB,GAAG,gBAAgB,CAAC,CAAC,KAAI,MAAK,EAAE,OAAO,IAAI,CAAC,GAGjF,iBACF;AACF;;AAGA,MAAa,4BAAsC,wBAAwB;;;;;;;;;;;;AAa3E,SAAgB,6BAAuC;CACrD,OAAO,KAAK,wBAAwB,KAAI,oBAAmB,gBAAgB,OAAO,IAAI,CAAC;AACzF;;;;;;;;;;;;;AAcA,SAAgB,6BACd,UACA,cAAwB,2BACF;CACtB,IAAI,CAAC,UACH;CAEF,OAAO,SAAS,QAAO,UAAS,CAAC,YAAY,MAAK,SAAQ,UAAU,QAAQ,MAAM,WAAW,GAAG,KAAK,EAAE,CAAC,CAAC;AAC3G"}
|
package/build/esm/package.json
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"type":"module","version":"11.
|
|
1
|
+
{"type":"module","version":"11.18.0","sideEffects":false}
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
// src/utils/installedModules.ts
|
|
2
|
+
const NODE_MODULES = "/node_modules/";
|
|
3
|
+
/**
|
|
4
|
+
* Returns the app's packages: the dependencies declared in its `package.json`, plus loaded packages. Each gets the exact
|
|
5
|
+
* version that a bare import from the app resolves through `node_modules`, or its declared range otherwise.
|
|
6
|
+
*/
|
|
7
|
+
function collectInstalledModules({ readFile, entryPath, cwd, loadedFiles = [] }) {
|
|
8
|
+
const read = (dir) => {
|
|
9
|
+
try {
|
|
10
|
+
return JSON.parse(readFile(join(dir, "package.json")) || "null") || void 0;
|
|
11
|
+
} catch {
|
|
12
|
+
return;
|
|
13
|
+
}
|
|
14
|
+
};
|
|
15
|
+
const entryDir = entryPath && dirname(toPosix(entryPath));
|
|
16
|
+
const cwdDir = cwd && toPosix(cwd);
|
|
17
|
+
const appRoot = findAppRoot(read, entryDir && cwdDir && !isIn(entryDir, cwdDir) ? [cwdDir, entryDir] : [entryDir, cwdDir]);
|
|
18
|
+
const resolveFrom = entryDir && appRoot && isIn(entryDir, appRoot) && !inNodeModules(entryDir) ? entryDir : appRoot || entryDir || cwdDir;
|
|
19
|
+
const nodeModulesDirs = resolveFrom ? ancestors(resolveFrom).map((dir) => join(dir, "node_modules")) : [];
|
|
20
|
+
const resolve = (name) => {
|
|
21
|
+
for (const dir of nodeModulesDirs) {
|
|
22
|
+
const version = read(join(dir, name))?.version;
|
|
23
|
+
if (version) return version;
|
|
24
|
+
}
|
|
25
|
+
};
|
|
26
|
+
const pkg = appRoot ? read(appRoot) : void 0;
|
|
27
|
+
const declared = {
|
|
28
|
+
...pkg?.dependencies,
|
|
29
|
+
...pkg?.devDependencies
|
|
30
|
+
};
|
|
31
|
+
const installed = {};
|
|
32
|
+
const seen = /* @__PURE__ */ new Set();
|
|
33
|
+
for (const file of loadedFiles) {
|
|
34
|
+
const path = toPosix(file);
|
|
35
|
+
const start = path.lastIndexOf(NODE_MODULES) + 14;
|
|
36
|
+
const [first = "", second] = path.slice(start).split("/");
|
|
37
|
+
const name = first.startsWith("@") ? `${first}/${second}` : first;
|
|
38
|
+
const dir = path.slice(0, start) + name;
|
|
39
|
+
if (start < 14 || seen.has(dir) || !nodeModulesDirs.some((d) => isIn(path, d))) continue;
|
|
40
|
+
seen.add(dir);
|
|
41
|
+
const version = read(dir)?.version;
|
|
42
|
+
if (version && installed[name] !== version) installed[name] = name in installed && resolve(name) || installed[name] || version;
|
|
43
|
+
}
|
|
44
|
+
for (const name of Object.keys(declared)) {
|
|
45
|
+
const version = resolve(name);
|
|
46
|
+
if (version) installed[name] = version;
|
|
47
|
+
}
|
|
48
|
+
return {
|
|
49
|
+
...declared,
|
|
50
|
+
...installed
|
|
51
|
+
};
|
|
52
|
+
}
|
|
53
|
+
/** Skips start dirs inside `node_modules` and `package.json` files that only set fields like `"type"`. */
|
|
54
|
+
function findAppRoot(read, startDirs) {
|
|
55
|
+
for (const startDir of startDirs) {
|
|
56
|
+
const root = startDir && !inNodeModules(startDir) ? ancestors(startDir).find((dir) => {
|
|
57
|
+
const pkg = read(dir);
|
|
58
|
+
return pkg && (pkg.name || pkg.dependencies || pkg.devDependencies);
|
|
59
|
+
}) : void 0;
|
|
60
|
+
if (root) return root;
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
function inNodeModules(dir) {
|
|
64
|
+
return `${dir}/`.includes(NODE_MODULES);
|
|
65
|
+
}
|
|
66
|
+
/** `dir` and its parents, up to the root. */
|
|
67
|
+
function ancestors(dir) {
|
|
68
|
+
const dirs = [dir];
|
|
69
|
+
for (let parent = dirname(dir); parent !== dirs[dirs.length - 1]; parent = dirname(parent)) dirs.push(parent);
|
|
70
|
+
return dirs;
|
|
71
|
+
}
|
|
72
|
+
function dirname(path) {
|
|
73
|
+
const index = path.lastIndexOf("/");
|
|
74
|
+
return index > 0 ? path.slice(0, index) : index === 0 ? "/" : path;
|
|
75
|
+
}
|
|
76
|
+
function join(dir, name) {
|
|
77
|
+
return dir.endsWith("/") ? dir + name : `${dir}/${name}`;
|
|
78
|
+
}
|
|
79
|
+
function isIn(path, dir) {
|
|
80
|
+
return path === dir || path.startsWith(dir.endsWith("/") ? dir : `${dir}/`);
|
|
81
|
+
}
|
|
82
|
+
function toPosix(path) {
|
|
83
|
+
return path.replace(/\\/g, "/");
|
|
84
|
+
}
|
|
85
|
+
export { collectInstalledModules };
|
|
86
|
+
|
|
87
|
+
//# sourceMappingURL=installedModules.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"installedModules.js","names":[],"sources":["../../../src/utils/installedModules.ts"],"sourcesContent":["type ModuleInfo = Record<string, string>;\ninterface PackageJson {\n name?: string;\n version?: string;\n dependencies?: ModuleInfo;\n devDependencies?: ModuleInfo;\n}\n\nconst NODE_MODULES = '/node_modules/';\n\n/**\n * Returns the app's packages: the dependencies declared in its `package.json`, plus loaded packages. Each gets the exact\n * version that a bare import from the app resolves through `node_modules`, or its declared range otherwise.\n */\nexport function collectInstalledModules({\n readFile,\n entryPath,\n cwd,\n loadedFiles = [],\n}: {\n readFile: (path: string) => string | undefined;\n entryPath?: string;\n cwd?: string;\n /**\n * Paths of files the process has already loaded, such as the keys of the CommonJS module cache. Packages these files\n * belong to are added too, which covers transitive dependencies that are not in `package.json`.\n */\n loadedFiles?: string[];\n}): ModuleInfo {\n const read = (dir: string): PackageJson | undefined => {\n try {\n return JSON.parse(readFile(join(dir, 'package.json')) || 'null') || undefined;\n } catch {\n return undefined;\n }\n };\n\n const entryDir = entryPath && dirname(toPosix(entryPath));\n const cwdDir = cwd && toPosix(cwd);\n // An entry file outside cwd usually belongs to a launcher, such as the AWS Lambda runtime.\n const appRoot = findAppRoot(\n read,\n entryDir && cwdDir && !isIn(entryDir, cwdDir) ? [cwdDir, entryDir] : [entryDir, cwdDir],\n );\n\n const resolveFrom =\n entryDir && appRoot && isIn(entryDir, appRoot) && !inNodeModules(entryDir)\n ? entryDir\n : appRoot || entryDir || cwdDir;\n const nodeModulesDirs = resolveFrom ? ancestors(resolveFrom).map(dir => join(dir, 'node_modules')) : [];\n const resolve = (name: string): string | undefined => {\n for (const dir of nodeModulesDirs) {\n const version = read(join(dir, name))?.version;\n if (version) {\n return version;\n }\n }\n return undefined;\n };\n\n const pkg = appRoot ? read(appRoot) : undefined;\n const declared: ModuleInfo = { ...pkg?.dependencies, ...pkg?.devDependencies };\n const installed: ModuleInfo = {};\n const seen = new Set<string>();\n\n for (const file of loadedFiles) {\n const path = toPosix(file);\n const start = path.lastIndexOf(NODE_MODULES) + NODE_MODULES.length;\n const [first = '', second] = path.slice(start).split('/');\n const name = first.startsWith('@') ? `${first}/${second}` : first;\n const dir = path.slice(0, start) + name;\n if (start < NODE_MODULES.length || seen.has(dir) || !nodeModulesDirs.some(d => isIn(path, d))) {\n continue;\n }\n seen.add(dir);\n const version = read(dir)?.version;\n if (version && installed[name] !== version) {\n // pnpm and Bun stores can hold several versions of a package; prefer the one the app resolves.\n installed[name] = (name in installed && resolve(name)) || installed[name] || version;\n }\n }\n\n for (const name of Object.keys(declared)) {\n const version = resolve(name);\n if (version) {\n installed[name] = version;\n }\n }\n\n return { ...declared, ...installed };\n}\n\n/** Skips start dirs inside `node_modules` and `package.json` files that only set fields like `\"type\"`. */\nfunction findAppRoot(\n read: (dir: string) => PackageJson | undefined,\n startDirs: Array<string | undefined>,\n): string | undefined {\n for (const startDir of startDirs) {\n const root =\n startDir && !inNodeModules(startDir)\n ? ancestors(startDir).find(dir => {\n const pkg = read(dir);\n return pkg && (pkg.name || pkg.dependencies || pkg.devDependencies);\n })\n : undefined;\n if (root) {\n return root;\n }\n }\n return undefined;\n}\n\nfunction inNodeModules(dir: string): boolean {\n return `${dir}/`.includes(NODE_MODULES);\n}\n\n/** `dir` and its parents, up to the root. */\nfunction ancestors(dir: string): string[] {\n const dirs = [dir];\n for (let parent = dirname(dir); parent !== dirs[dirs.length - 1]; parent = dirname(parent)) {\n dirs.push(parent);\n }\n return dirs;\n}\n\n// Minimal POSIX helpers: all paths are converted with `toPosix` first.\nfunction dirname(path: string): string {\n const index = path.lastIndexOf('/');\n return index > 0 ? path.slice(0, index) : index === 0 ? '/' : path;\n}\n\nfunction join(dir: string, name: string): string {\n return dir.endsWith('/') ? dir + name : `${dir}/${name}`;\n}\n\nfunction isIn(path: string, dir: string): boolean {\n return path === dir || path.startsWith(dir.endsWith('/') ? dir : `${dir}/`);\n}\n\nfunction toPosix(path: string): string {\n return path.replace(/\\\\/g, '/');\n}\n"],"mappings":";AAQA,MAAM,eAAe;;;;;AAMrB,SAAgB,wBAAwB,EACtC,UACA,WACA,KACA,cAAc,CAAC,KAUF;CACb,MAAM,QAAQ,QAAyC;EACrD,IAAI;GACF,OAAO,KAAK,MAAM,SAAS,KAAK,KAAK,cAAc,CAAC,KAAK,MAAM,KAAK,KAAA;EACtE,QAAQ;GACN;EACF;CACF;CAEA,MAAM,WAAW,aAAa,QAAQ,QAAQ,SAAS,CAAC;CACxD,MAAM,SAAS,OAAO,QAAQ,GAAG;CAEjC,MAAM,UAAU,YACd,MACA,YAAY,UAAU,CAAC,KAAK,UAAU,MAAM,IAAI,CAAC,QAAQ,QAAQ,IAAI,CAAC,UAAU,MAAM,CACxF;CAEA,MAAM,cACJ,YAAY,WAAW,KAAK,UAAU,OAAO,KAAK,CAAC,cAAc,QAAQ,IACrE,WACA,WAAW,YAAY;CAC7B,MAAM,kBAAkB,cAAc,UAAU,WAAW,CAAC,CAAC,KAAI,QAAO,KAAK,KAAK,cAAc,CAAC,IAAI,CAAC;CACtG,MAAM,WAAW,SAAqC;EACpD,KAAK,MAAM,OAAO,iBAAiB;GACjC,MAAM,UAAU,KAAK,KAAK,KAAK,IAAI,CAAC,CAAC,EAAE;GACvC,IAAI,SACF,OAAO;EAEX;CAEF;CAEA,MAAM,MAAM,UAAU,KAAK,OAAO,IAAI,KAAA;CACtC,MAAM,WAAuB;EAAE,GAAG,KAAK;EAAc,GAAG,KAAK;CAAgB;CAC7E,MAAM,YAAwB,CAAC;CAC/B,MAAM,uBAAO,IAAI,IAAY;CAE7B,KAAK,MAAM,QAAQ,aAAa;EAC9B,MAAM,OAAO,QAAQ,IAAI;EACzB,MAAM,QAAQ,KAAK,YAAY,YAAY,IAAI;EAC/C,MA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AK,YAAY,GAAG;CAClC,OAAO,QAAQ,IAAI,KAAK,MAAM,GAAG,KAAK,IAAI,UAAU,IAAI,MAAM;AAChE;AAEA,SAAS,KAAK,KAAa,MAAsB;CAC/C,OAAO,IAAI,SAAS,GAAG,IAAI,MAAM,OAAO,GAAG,IAAI,GAAG;AACpD;AAEA,SAAS,KAAK,MAAc,KAAsB;CAChD,OAAO,SAAS,OAAO,KAAK,WAAW,IAAI,SAAS,GAAG,IAAI,MAAM,GAAG,IAAI,EAAE;AAC5E;AAEA,SAAS,QAAQ,MAAsB;CACrC,OAAO,KAAK,QAAQ,OAAO,GAAG;AAChC"}
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import { dirname } from "@sentry/core";
|
|
2
|
+
import { posix, sep } from "node:path";
|
|
3
|
+
// src/utils/module.ts
|
|
4
|
+
/** normalizes Windows paths */
|
|
5
|
+
function normalizeWindowsPath(path) {
|
|
6
|
+
return path.replace(/^[A-Z]:/, "").replace(/\\/g, "/");
|
|
7
|
+
}
|
|
8
|
+
/** Creates a function that gets the module name from a filename */
|
|
9
|
+
function createGetModuleFromFilename(basePath = process.argv[1] ? dirname(process.argv[1]) : process.cwd(), isWindows = sep === "\\") {
|
|
10
|
+
const normalizedBase = isWindows ? normalizeWindowsPath(basePath) : basePath;
|
|
11
|
+
return (filename) => {
|
|
12
|
+
if (!filename) return;
|
|
13
|
+
const normalizedFilename = isWindows ? normalizeWindowsPath(filename) : filename;
|
|
14
|
+
let { dir, base: file, ext } = posix.parse(normalizedFilename);
|
|
15
|
+
if (ext === ".js" || ext === ".mjs" || ext === ".cjs") file = file.slice(0, ext.length * -1);
|
|
16
|
+
const decodedFile = decodeURIComponent(file);
|
|
17
|
+
if (!dir) dir = ".";
|
|
18
|
+
const n = dir.lastIndexOf("/node_modules");
|
|
19
|
+
if (n > -1) return `${dir.slice(n + 14).replace(/\//g, ".")}:${decodedFile}`;
|
|
20
|
+
if (dir.startsWith(normalizedBase)) {
|
|
21
|
+
const moduleName = dir.slice(normalizedBase.length + 1).replace(/\//g, ".");
|
|
22
|
+
return moduleName ? `${moduleName}:${decodedFile}` : decodedFile;
|
|
23
|
+
}
|
|
24
|
+
return decodedFile;
|
|
25
|
+
};
|
|
26
|
+
}
|
|
27
|
+
export { createGetModuleFromFilename };
|
|
28
|
+
|
|
29
|
+
//# sourceMappingURL=module.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"module.js","names":[],"sources":["../../../src/utils/module.ts"],"sourcesContent":["import { posix, sep } from 'node:path';\nimport { dirname } from '@sentry/core';\n\n/** normalizes Windows paths */\nfunction normalizeWindowsPath(path: string): string {\n return path\n .replace(/^[A-Z]:/, '') // remove Windows-style prefix\n .replace(/\\\\/g, '/'); // replace all `\\` instances with `/`\n}\n\n/** Creates a function that gets the module name from a filename */\nexport function createGetModuleFromFilename(\n basePath: string = process.argv[1] ? dirname(process.argv[1]) : process.cwd(),\n isWindows: boolean = sep === '\\\\',\n): (filename: string | undefined) => string | undefined {\n const normalizedBase = isWindows ? normalizeWindowsPath(basePath) : basePath;\n\n return (filename: string | undefined) => {\n if (!filename) {\n return;\n }\n\n const normalizedFilename = isWindows ? normalizeWindowsPath(filename) : filename;\n\n // eslint-disable-next-line prefer-const\n let { dir, base: file, ext } = posix.parse(normalizedFilename);\n\n if (ext === '.js' || ext === '.mjs' || ext === '.cjs') {\n file = file.slice(0, ext.length * -1);\n }\n\n // The file name might be URI-encoded which we want to decode to\n // the original file name.\n const decodedFile = decodeURIComponent(file);\n\n if (!dir) {\n // No dirname whatsoever\n dir = '.';\n }\n\n const n = dir.lastIndexOf('/node_modules');\n if (n > -1) {\n return `${dir.slice(n + 14).replace(/\\//g, '.')}:${decodedFile}`;\n }\n\n // Let's see if it's a part of the main module\n // To be a part of main module, it has to share the same base\n if (dir.startsWith(normalizedBase)) {\n const moduleName = dir.slice(normalizedBase.length + 1).replace(/\\//g, '.');\n return moduleName ? `${moduleName}:${decodedFile}` : decodedFile;\n }\n\n return decodedFile;\n };\n}\n"],"mappings":";;;;AAIA,SAAS,qBAAqB,MAAsB;CAClD,OAAO,KACJ,QAAQ,WAAW,EAAE,CAAC,CACtB,QAAQ,OAAO,GAAG;AACvB;;AAGA,SAAgB,4BACd,WAAmB,QAAQ,KAAK,KAAK,QAAQ,QAAQ,KAAK,EAAE,IAAI,QAAQ,IAAI,GAC5E,YAAqB,QAAQ,MACyB;CACtD,MAAM,iBAAiB,YAAY,qBAAqB,QAAQ,IAAI;CAEpE,QAAQ,aAAiC;EACvC,IAAI,CAAC,UACH;EAGF,MAAM,qBAAqB,YAAY,qBAAqB,QAAQ,IAAI;EAGxE,IAAI,EAAE,KAAK,MAAM,MAAM,QAAQ,MAAM,MAAM,kBAAkB;EAE7D,IAAI,QAAQ,SAAS,QAAQ,UAAU,QAAQ,QAC7C,OAAO,KAAK,MAAM,GAAG,IAAI,SAAS,EAAE;EAKtC,MAAM,cAAc,mBAAmB,IAAI;EAE3C,IAAI,CAAC,KAEH,MAAM;EAGR,MAAM,IAAI,IAAI,YAAY,eAAe;EACzC,IAAI,IAAI,IACN,OAAO,GAAG,IAAI,MAAM,IAAI,EAAE,CAAC,CAAC,QAAQ,OAAO,GAAG,EAAE,GAAG;EAKrD,IAAI,IAAI,WAAW,cAAc,GAAG;GAClC,MAAM,aAAa,IAAI,MAAM,eAAe,SAAS,CAAC,CAAC,CAAC,QAAQ,OAAO,GAAG;GAC1E,OAAO,aAAa,GAAG,WAAW,GAAG,gBAAgB;EACvD;EAEA,OAAO;CACT;AACF"}
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
import { DEBUG_BUILD } from "../debug-build.js";
|
|
2
|
+
import { debug, getTraceServerTimingHeader, isSharedCacheable } from "@sentry/core";
|
|
3
|
+
// src/utils/serverTimingTraceHeader.ts
|
|
4
|
+
const SERVER_TIMING_HEADER = "server-timing";
|
|
5
|
+
const enabledClients = /* @__PURE__ */ new WeakSet();
|
|
6
|
+
/**
|
|
7
|
+
* Sends the trace of the request in a `Server-Timing` header of the document responses that
|
|
8
|
+
* `wrapServerRequestHandler` returns, so the browser SDK continues it in the pageload span. The
|
|
9
|
+
* counterpart of `addServerTimingTraceHeader` of `@sentry/node` for runtimes with web `Request`
|
|
10
|
+
* handlers. Framework SDKs turn it on; it is off by default.
|
|
11
|
+
*/
|
|
12
|
+
function addServerTimingTraceHeader(client) {
|
|
13
|
+
enabledClients.add(client);
|
|
14
|
+
}
|
|
15
|
+
/**
|
|
16
|
+
* Adds the trace of the current context to the `Server-Timing` header of a document response that
|
|
17
|
+
* no shared cache may store, as `@sentry/node` does. A cache would replay the trace, and the sampling
|
|
18
|
+
* decision, of one visitor to everyone who gets the cached copy. An existing `sentry-trace` entry of
|
|
19
|
+
* the app is left alone.
|
|
20
|
+
*
|
|
21
|
+
* A `fetch` response has immutable headers, so it is copied then.
|
|
22
|
+
*/
|
|
23
|
+
function withServerTimingTraceHeader(client, response) {
|
|
24
|
+
if (!response || !enabledClients.has(client)) return response;
|
|
25
|
+
try {
|
|
26
|
+
const headers = response.headers;
|
|
27
|
+
const getHeader = (name) => headers.get(name) ?? void 0;
|
|
28
|
+
if (!getHeader("content-type")?.toLowerCase().startsWith("text/html") || isSharedCacheable(getHeader)) return response;
|
|
29
|
+
const existingValue = getHeader(SERVER_TIMING_HEADER);
|
|
30
|
+
if (existingValue?.includes("sentry-trace")) return response;
|
|
31
|
+
const traceHeader = getTraceServerTimingHeader();
|
|
32
|
+
if (!traceHeader) return response;
|
|
33
|
+
const value = existingValue ? `${existingValue}, ${traceHeader}` : traceHeader;
|
|
34
|
+
try {
|
|
35
|
+
headers.set(SERVER_TIMING_HEADER, value);
|
|
36
|
+
return response;
|
|
37
|
+
} catch {
|
|
38
|
+
const copy = new Response(response.body, response);
|
|
39
|
+
copy.headers.set(SERVER_TIMING_HEADER, value);
|
|
40
|
+
return copy;
|
|
41
|
+
}
|
|
42
|
+
} catch (e) {
|
|
43
|
+
DEBUG_BUILD && debug.warn("Failed to add the trace to the Server-Timing header", e);
|
|
44
|
+
return response;
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
export { addServerTimingTraceHeader, withServerTimingTraceHeader };
|
|
48
|
+
|
|
49
|
+
//# sourceMappingURL=serverTimingTraceHeader.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"serverTimingTraceHeader.js","names":[],"sources":["../../../src/utils/serverTimingTraceHeader.ts"],"sourcesContent":["import type { Client } from '@sentry/core';\nimport { debug, getTraceServerTimingHeader, isSharedCacheable } from '@sentry/core';\nimport { DEBUG_BUILD } from '../debug-build';\n\nconst SERVER_TIMING_HEADER = 'server-timing';\n\nconst enabledClients = new WeakSet<Client>();\n\n/**\n * Sends the trace of the request in a `Server-Timing` header of the document responses that\n * `wrapServerRequestHandler` returns, so the browser SDK continues it in the pageload span. The\n * counterpart of `addServerTimingTraceHeader` of `@sentry/node` for runtimes with web `Request`\n * handlers. Framework SDKs turn it on; it is off by default.\n */\nexport function addServerTimingTraceHeader(client: Client): void {\n enabledClients.add(client);\n}\n\n/**\n * Adds the trace of the current context to the `Server-Timing` header of a document response that\n * no shared cache may store, as `@sentry/node` does. A cache would replay the trace, and the sampling\n * decision, of one visitor to everyone who gets the cached copy. An existing `sentry-trace` entry of\n * the app is left alone.\n *\n * A `fetch` response has immutable headers, so it is copied then.\n */\nexport function withServerTimingTraceHeader<R extends Response | undefined>(client: Client, response: R): R {\n if (!response || !enabledClients.has(client)) {\n return response;\n }\n\n try {\n const headers = response.headers;\n const getHeader = (name: string): string | undefined => headers.get(name) ?? undefined;\n if (!getHeader('content-type')?.toLowerCase().startsWith('text/html') || isSharedCacheable(getHeader)) {\n return response;\n }\n\n const existingValue = getHeader(SERVER_TIMING_HEADER);\n if (existingValue?.includes('sentry-trace')) {\n return response;\n }\n\n const traceHeader = getTraceServerTimingHeader();\n if (!traceHeader) {\n return response;\n }\n\n const value = existingValue ? `${existingValue}, ${traceHeader}` : traceHeader;\n try {\n headers.set(SERVER_TIMING_HEADER, value);\n return response;\n } catch {\n // Passing the original response as the init keeps its status, status text and headers.\n const copy = new Response(response.body, response);\n copy.headers.set(SERVER_TIMING_HEADER, value);\n return copy as R;\n }\n } catch (e) {\n DEBUG_BUILD && debug.warn('Failed to add the trace to the Server-Timing header', e);\n return response;\n }\n}\n"],"mappings":";;;AAIA,MAAM,uBAAuB;AAE7B,MAAM,iCAAiB,IAAI,QAAgB;;;;;;;AAQ3C,SAAgB,2BAA2B,QAAsB;CAC/D,eAAe,IAAI,MAAM;AAC3B;;;;;;;;;AAUA,SAAgB,4BAA4D,QAAgB,UAAgB;CAC1G,IAAI,CAAC,YAAY,CAAC,eAAe,IAAI,MAAM,GACzC,OAAO;CAGT,IAAI;EACF,MAAM,UAAU,SAAS;EACzB,MAAM,aAAa,SAAqC,QAAQ,IAAI,IAAI,KAAK,KAAA;EAC7E,IAAI,CAAC,UAAU,cAAc,CAAC,EAAE,YAAY,CAAC,CAAC,WAAW,WAAW,KAAK,kBAAkB,SAAS,GAClG,OAAO;EAGT,MAAM,gBAAgB,UAAU,oBAAoB;EACpD,IAAI,eAAe,SAAS,cAAc,GACxC,OAAO;EAGT,MAAM,cAAc,2BAA2B;EAC/C,IAAI,CAAC,aACH,OAAO;EAGT,MAAM,QAAQ,gBAAgB,GAAG,cAAc,IAAI,gBAAgB;EACnE,IAAI;GACF,QAAQ,IAAI,sBAAsB,KAAK;GACvC,OAAO;EACT,QAAQ;GAEN,MAAM,OAAO,IAAI,SAAS,SAAS,MAAM,QAAQ;GACjD,KAAK,QAAQ,IAAI,sBAAsB,KAAK;GAC5C,OAAO;EACT;CACF,SAAS,GAAG;EACV,eAAe,MAAM,KAAK,uDAAuD,CAAC;EAClF,OAAO;CACT;AACF"}
|
package/build/esm/utils/sql.js
CHANGED
|
@@ -5,7 +5,7 @@ const MAX_SUMMARY_LENGTH = 255;
|
|
|
5
5
|
const IDENTIFIER = "(?:\"[^\"]*\"|'[^']*'|`[^`]*`|[^\\s(,;).'\"`]+)";
|
|
6
6
|
const TABLE_NAME = `${IDENTIFIER}(?:\\.${IDENTIFIER})*`;
|
|
7
7
|
const DDL_RE = new RegExp(`^\\s*(?<operation>(?:CREATE|DROP)\\s+(?:TABLE|INDEX)|ALTER\\s+TABLE)(?:\\s+IF\\s+(?:NOT\\s+)?EXISTS)?\\s+(?<table>${TABLE_NAME})`, "i");
|
|
8
|
-
const INSERT_RE = new RegExp(`^\\s*(?<operation>INSERT|REPLACE)(?:\\s+OR\\s+(?:ROLLBACK|ABORT|FAIL|IGNORE|REPLACE))?\\s+INTO
|
|
8
|
+
const INSERT_RE = new RegExp(`^\\s*(?<operation>INSERT|REPLACE)(?:\\s+OR\\s+(?:ROLLBACK|ABORT|FAIL|IGNORE|REPLACE))?\\s+INTO(?:\\s+TABLE)?\\s+(?<table>${TABLE_NAME})`, "i");
|
|
9
9
|
const UPDATE_RE = new RegExp(`^\\s*(?<operation>UPDATE)(?:\\s+OR\\s+(?:ROLLBACK|ABORT|FAIL|IGNORE|REPLACE))?\\s+(?<table>${TABLE_NAME})`, "i");
|
|
10
10
|
const DELETE_RE = new RegExp(`^\\s*(?<operation>DELETE)\\s+FROM\\s+(?<table>${TABLE_NAME})`, "i");
|
|
11
11
|
const SELECT_RE = /^\s*(?:\(\s*)?(?<operation>SELECT)\b/i;
|
|
@@ -91,8 +91,9 @@ function extractTableNames(sql) {
|
|
|
91
91
|
TOKEN_RE.lastIndex = 0;
|
|
92
92
|
let match;
|
|
93
93
|
while ((match = TOKEN_RE.exec(sql)) !== null) {
|
|
94
|
-
|
|
95
|
-
|
|
94
|
+
const table = match[1] || match[2];
|
|
95
|
+
if (table) {
|
|
96
|
+
tables.push(table);
|
|
96
97
|
continue;
|
|
97
98
|
}
|
|
98
99
|
const rest = sql.slice(match.index + match[0].length);
|
|
@@ -148,6 +149,7 @@ function toSqlDialect(system) {
|
|
|
148
149
|
if (system === "mssql" || system === "sqlserver" || system === "microsoft.sql_server") return "mssql";
|
|
149
150
|
return "standard";
|
|
150
151
|
}
|
|
152
|
+
const NO_RULES = {};
|
|
151
153
|
const DOLLAR_QUOTE_RE = /\$(?:[A-Za-z_]\w*)?\$/y;
|
|
152
154
|
/**
|
|
153
155
|
* Returns the index just past the run's closing `delimiter`, or -1 if the run never closes. The
|
|
@@ -168,6 +170,18 @@ function findQuotedRunEnd(sql, start, delimiter, backslashEscapes) {
|
|
|
168
170
|
}
|
|
169
171
|
return -1;
|
|
170
172
|
}
|
|
173
|
+
function findBlockCommentEnd(sql, start, nested) {
|
|
174
|
+
let depth = 1;
|
|
175
|
+
let i = start + 2;
|
|
176
|
+
while (i < sql.length && depth > 0) if (sql[i] === "*" && sql[i + 1] === "/") {
|
|
177
|
+
depth--;
|
|
178
|
+
i += 2;
|
|
179
|
+
} else if (nested && sql[i] === "/" && sql[i + 1] === "*") {
|
|
180
|
+
depth++;
|
|
181
|
+
i += 2;
|
|
182
|
+
} else i++;
|
|
183
|
+
return i;
|
|
184
|
+
}
|
|
171
185
|
/**
|
|
172
186
|
* Replaces every string literal with `?` and drops every comment, in one pass.
|
|
173
187
|
*
|
|
@@ -180,24 +194,25 @@ function findQuotedRunEnd(sql, start, delimiter, backslashEscapes) {
|
|
|
180
194
|
* built from.
|
|
181
195
|
*/
|
|
182
196
|
function stripLiteralsAndComments(sql, dialect) {
|
|
183
|
-
const
|
|
197
|
+
const [base, rules] = typeof dialect === "string" ? [dialect, NO_RULES] : ["standard", dialect];
|
|
198
|
+
const isMysql = base === "mysql";
|
|
199
|
+
const backslashEscapes = !!rules.backslashEscapes;
|
|
184
200
|
const out = [];
|
|
185
201
|
let i = 0;
|
|
186
202
|
while (i < sql.length) {
|
|
187
|
-
const char = sql
|
|
203
|
+
const char = sql.charAt(i);
|
|
188
204
|
const next = sql[i + 1];
|
|
189
|
-
if (char === "-" && next === "-" || isMysql && char === "#") {
|
|
205
|
+
if (char === "-" && next === "-" || (isMysql || rules.hashComments) && char === "#") {
|
|
190
206
|
const lineEnd = sql.indexOf("\n", i);
|
|
191
207
|
i = lineEnd === -1 ? sql.length : lineEnd;
|
|
192
208
|
continue;
|
|
193
209
|
}
|
|
194
210
|
if (char === "/" && next === "*") {
|
|
195
|
-
|
|
196
|
-
i = commentEnd === -1 ? sql.length : commentEnd + 2;
|
|
211
|
+
i = findBlockCommentEnd(sql, i, !!rules.nestedComments);
|
|
197
212
|
continue;
|
|
198
213
|
}
|
|
199
|
-
if (
|
|
200
|
-
const tag = matchDollarQuoteTag(sql, i);
|
|
214
|
+
if (base === "standard" && char === "$" && !isIdentifierChar(sql[i - 1])) {
|
|
215
|
+
const tag = matchDollarQuoteTag(sql, i, rules.dollarQuote);
|
|
201
216
|
if (tag) {
|
|
202
217
|
const bodyEnd = sql.indexOf(tag, i + tag.length);
|
|
203
218
|
i = bodyEnd === -1 ? sql.length : bodyEnd + tag.length;
|
|
@@ -205,21 +220,28 @@ function stripLiteralsAndComments(sql, dialect) {
|
|
|
205
220
|
continue;
|
|
206
221
|
}
|
|
207
222
|
}
|
|
208
|
-
const identifierCloser = getIdentifierCloser(char,
|
|
223
|
+
const identifierCloser = getIdentifierCloser(char, base);
|
|
209
224
|
if (identifierCloser) {
|
|
210
|
-
const runEnd = findQuotedRunEnd(sql, i, identifierCloser,
|
|
225
|
+
const runEnd = findQuotedRunEnd(sql, i, identifierCloser, backslashEscapes);
|
|
211
226
|
out.push(runEnd === -1 ? "?" : sql.slice(i, runEnd));
|
|
212
227
|
i = runEnd === -1 ? sql.length : runEnd;
|
|
213
228
|
continue;
|
|
214
229
|
}
|
|
215
230
|
if (char === "'" || char === "\"" && isMysql) {
|
|
216
|
-
const prefix = char === "'" ? getLiteralPrefix(out,
|
|
231
|
+
const prefix = char === "'" ? getLiteralPrefix(out, base) : void 0;
|
|
217
232
|
if (prefix) out.pop();
|
|
218
|
-
const runEnd = findQuotedRunEnd(sql, i, char, isMysql || prefix === "E");
|
|
233
|
+
const runEnd = findQuotedRunEnd(sql, i, char, isMysql || backslashEscapes || prefix === "E");
|
|
219
234
|
i = runEnd === -1 ? sql.length : runEnd;
|
|
220
235
|
out.push("?");
|
|
221
236
|
continue;
|
|
222
237
|
}
|
|
238
|
+
const literalLength = rules.matchLiteral?.(sql, i);
|
|
239
|
+
if (literalLength) {
|
|
240
|
+
out.push("?");
|
|
241
|
+
i += literalLength;
|
|
242
|
+
continue;
|
|
243
|
+
}
|
|
244
|
+
if (rules.isInlineData?.(sql, i, out)) break;
|
|
223
245
|
out.push(char);
|
|
224
246
|
i++;
|
|
225
247
|
}
|
|
@@ -240,9 +262,9 @@ function isIdentifierChar(char) {
|
|
|
240
262
|
return char !== void 0 && /[\w$]/.test(char);
|
|
241
263
|
}
|
|
242
264
|
/** Returns the opening dollar-quote tag at `start` (`$$` or `$tag$`), or undefined if there is none. */
|
|
243
|
-
function matchDollarQuoteTag(sql, start) {
|
|
244
|
-
|
|
245
|
-
return
|
|
265
|
+
function matchDollarQuoteTag(sql, start, pattern = DOLLAR_QUOTE_RE) {
|
|
266
|
+
pattern.lastIndex = start;
|
|
267
|
+
return pattern.exec(sql)?.[0];
|
|
246
268
|
}
|
|
247
269
|
/**
|
|
248
270
|
* Returns the literal-prefix character immediately before a `'`, if there is one: `X`/`B` for
|
|
@@ -265,7 +287,7 @@ function getLiteralPrefix(out, dialect) {
|
|
|
265
287
|
* booleans) are sanitized.
|
|
266
288
|
*
|
|
267
289
|
* Pass `dialect` when the statement comes from a driver whose literals are not standard-quoted;
|
|
268
|
-
* see {@link SqlDialect}.
|
|
290
|
+
* see {@link SqlDialect} and {@link SqlLexerRules}.
|
|
269
291
|
*/
|
|
270
292
|
function sanitizeSqlQuery(sqlQuery, dialect = "standard") {
|
|
271
293
|
if (!sqlQuery) return "Unknown SQL Query";
|
|
@@ -307,6 +329,6 @@ function getSqlSpanName(attributes, fallback) {
|
|
|
307
329
|
function toSpanName(value, fallback) {
|
|
308
330
|
return typeof value === "string" && value ? value : fallback;
|
|
309
331
|
}
|
|
310
|
-
export { getLowCardinalitySqlSpanName, getSqlOperationName, getSqlQueryAttributes, getSqlQuerySummary, getSqlSpanName, sanitizeSqlQuery, toSqlDialect };
|
|
332
|
+
export { getLowCardinalitySqlSpanName, getSqlOperationName, getSqlQueryAttributes, getSqlQuerySummary, getSqlSpanName, isIdentifierChar, sanitizeSqlQuery, toSqlDialect };
|
|
311
333
|
|
|
312
334
|
//# sourceMappingURL=sql.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"sql.js","names":[],"sources":["../../../src/utils/sql.ts"],"sourcesContent":["import {\n DB_NAMESPACE,\n DB_OPERATION_NAME,\n DB_QUERY_SUMMARY,\n DB_QUERY_TEXT,\n DB_SYSTEM_NAME,\n} from '@sentry/conventions/attributes';\nimport type { SpanAttributes } from '@sentry/core';\nimport { getClient, hasSpanStreamingEnabled } from '@sentry/core';\n\nconst MAX_SUMMARY_LENGTH = 255;\n\n// A single identifier: quoted (`\"...\"`, `'...'`, or MySQL backticks) or bare. The quoted forms have\n// to be matched as a unit, otherwise an identifier containing a space or a dot is cut in half.\nconst IDENTIFIER = '(?:\"[^\"]*\"|\\'[^\\']*\\'|`[^`]*`|[^\\\\s(,;).\\'\"`]+)';\n\n// A table reference can be schema-qualified (`\"public\".\"User\"`, `db.schema.table`), with each part\n// quoted independently. The whole qualified name is the summary target, since the schema is what\n// distinguishes two same-named tables.\nconst TABLE_NAME = `${IDENTIFIER}(?:\\\\.${IDENTIFIER})*`;\n\nconst DDL_RE = new RegExp(\n `^\\\\s*(?<operation>(?:CREATE|DROP)\\\\s+(?:TABLE|INDEX)|ALTER\\\\s+TABLE)(?:\\\\s+IF\\\\s+(?:NOT\\\\s+)?EXISTS)?\\\\s+(?<table>${TABLE_NAME})`,\n 'i',\n);\n\n// SQLite upserts insert an optional conflict clause between operation and INTO\n// (`INSERT OR REPLACE INTO`, https://sqlite.org/lang_insert.html), with `REPLACE INTO` as the\n// standalone shorthand. The clause is filler like INTO — stripping it keeps upserts on the same\n// low-cardinality summary as plain inserts.\nconst INSERT_RE = new RegExp(\n `^\\\\s*(?<operation>INSERT|REPLACE)(?:\\\\s+OR\\\\s+(?:ROLLBACK|ABORT|FAIL|IGNORE|REPLACE))?\\\\s+INTO\\\\s+(?<table>${TABLE_NAME})`,\n 'i',\n);\nconst UPDATE_RE = new RegExp(\n `^\\\\s*(?<operation>UPDATE)(?:\\\\s+OR\\\\s+(?:ROLLBACK|ABORT|FAIL|IGNORE|REPLACE))?\\\\s+(?<table>${TABLE_NAME})`,\n 'i',\n);\nconst DELETE_RE = new RegExp(`^\\\\s*(?<operation>DELETE)\\\\s+FROM\\\\s+(?<table>${TABLE_NAME})`, 'i');\n\nconst SELECT_RE = /^\\s*(?:\\(\\s*)?(?<operation>SELECT)\\b/i;\n\nconst PRAGMA_RE = /^\\s*(?<operation>PRAGMA)\\s+(?<command>\\S+)/i;\n\nconst TOKEN_RE = /\\b(?:FROM|JOIN)\\s+|\\(\\s*(SELECT)\\b|\\b(?:UNION|INTERSECT|EXCEPT|MINUS)\\s+(?:ALL\\s+)?(SELECT)\\b/gi;\nconst TABLE_REF_RE = new RegExp(`^${TABLE_NAME}`);\nconst COMMA_TABLE_RE = new RegExp(`^\\\\s*,\\\\s*(${TABLE_NAME})`);\nconst SUBQUERY_SELECT_RE = /^\\(\\s*(SELECT)\\b/i;\n\n/**\n * Derives a low-cardinality summary from a SQL query for use as `db.query.summary`.\n *\n * Conforms to the OTEL semantic convention for generating query summaries:\n * - Preserves original case of operations and identifiers (no normalization)\n * - Uses format: `{operation} {target1} {target2} ...`\n * - Strips filler words (INTO, FROM) from the operation\n * - Captures multiple table targets (JOINs)\n * - Handles INSERT...SELECT with both targets\n * - Truncates to 255 characters without splitting mid-value\n *\n * @see https://opentelemetry.io/docs/specs/semconv/database/database-spans/#generating-a-summary-of-the-query\n */\nexport function getSqlQuerySummary(query: string | undefined): string | undefined {\n if (!query) {\n return undefined;\n }\n\n const pragmaMatch = PRAGMA_RE.exec(query);\n if (pragmaMatch?.groups?.['operation'] && pragmaMatch.groups['command']) {\n const operation = pragmaMatch.groups['operation'];\n const command = pragmaMatch.groups['command'];\n const parenIdx = command.indexOf('(');\n return truncate(`${operation} ${parenIdx >= 0 ? command.substring(0, parenIdx) : command}`);\n }\n\n const ddlMatch = DDL_RE.exec(query);\n if (ddlMatch?.groups?.['operation'] && ddlMatch.groups['table']) {\n return truncate(`${ddlMatch.groups['operation']} ${ddlMatch.groups['table']}`);\n }\n\n const insertMatch = INSERT_RE.exec(query);\n if (insertMatch?.groups?.['operation'] && insertMatch.groups['table']) {\n const parts = [insertMatch.groups['operation'], insertMatch.groups['table']];\n const rest = query.slice(insertMatch[0].length);\n const subSelect = /\\b(SELECT)\\b/i.exec(rest);\n if (subSelect?.[1]) {\n parts.push(subSelect[1]);\n const selectTables = extractTableNames(rest.slice(subSelect.index));\n parts.push(...selectTables);\n }\n return truncate(parts.join(' '));\n }\n\n const updateMatch = UPDATE_RE.exec(query);\n if (updateMatch?.groups?.['operation'] && updateMatch.groups['table']) {\n return truncate(`${updateMatch.groups['operation']} ${updateMatch.groups['table']}`);\n }\n\n const deleteMatch = DELETE_RE.exec(query);\n if (deleteMatch?.groups?.['operation'] && deleteMatch.groups['table']) {\n return truncate(`${deleteMatch.groups['operation']} ${deleteMatch.groups['table']}`);\n }\n\n const selectMatch = SELECT_RE.exec(query);\n if (selectMatch?.groups?.['operation']) {\n const tables = extractTableNames(query.slice(selectMatch[0].length));\n if (tables.length > 0) {\n return truncate(`${selectMatch.groups['operation']} ${tables.join(' ')}`);\n }\n return selectMatch.groups['operation'];\n }\n\n return truncate(query.trim().split(/\\s+/)[0] ?? query);\n}\n\nconst LEADING_KEYWORD_RE = /^\\s*(?:\\(\\s*)*([A-Za-z]+)\\b/;\nconst CTE_MAIN_STATEMENT_RE = /\\(|\\)|\\b(SELECT|INSERT|UPDATE|DELETE|MERGE|VALUES|TABLE)\\b/gi;\n\n/**\n * Derives `db.operation.name` from a SQL query: the first operation keyword, in its original case.\n *\n * @see https://opentelemetry.io/docs/specs/semconv/registry/attributes/db/#db-operation-name\n */\nexport function getSqlOperationName(query: string | undefined): string | undefined {\n const match = query ? LEADING_KEYWORD_RE.exec(query) : null;\n const keyword = match?.[1];\n if (!query || !match || !keyword) {\n return undefined;\n }\n // Scanned from after `WITH`, so parentheses wrapping the whole query don't shift the depth.\n return keyword.toUpperCase() === 'WITH' ? getCteMainOperationName(query.slice(match[0].length)) : keyword;\n}\n\n/**\n * The operation of a `WITH` query is its main statement: the first operation keyword outside the\n * CTE bodies, which are all parenthesized. Counting parentheses is safe on a sanitized query, which\n * has no literals or comments left.\n */\nfunction getCteMainOperationName(query: string): string | undefined {\n let depth = 0;\n for (const match of query.matchAll(CTE_MAIN_STATEMENT_RE)) {\n if (match[0] === '(') {\n depth++;\n } else if (match[0] === ')') {\n depth--;\n } else if (depth === 0) {\n return match[1];\n }\n }\n return undefined;\n}\n\nfunction extractTableNames(sql: string): string[] {\n const tables: string[] = [];\n TOKEN_RE.lastIndex = 0;\n let match: RegExpExecArray | null;\n\n while ((match = TOKEN_RE.exec(sql)) !== null) {\n if (match[1] || match[2]) {\n tables.push((match[1] || match[2])!);\n continue;\n }\n\n const rest = sql.slice(match.index + match[0].length);\n\n const subqueryMatch = SUBQUERY_SELECT_RE.exec(rest);\n if (subqueryMatch?.[1]) {\n tables.push(subqueryMatch[1]);\n TOKEN_RE.lastIndex = match.index + match[0].length + subqueryMatch[0].length;\n continue;\n }\n\n const tableMatch = TABLE_REF_RE.exec(rest);\n if (!tableMatch) continue;\n tables.push(tableMatch[0]);\n\n let afterTable = rest.slice(tableMatch[0].length);\n let commaMatch: RegExpExecArray | null;\n while ((commaMatch = COMMA_TABLE_RE.exec(afterTable)) !== null) {\n if (!commaMatch[1]) break;\n tables.push(commaMatch[1]);\n afterTable = afterTable.slice(commaMatch[0].length);\n }\n }\n\n return tables;\n}\n\nfunction truncate(summary: string): string {\n if (summary.length <= MAX_SUMMARY_LENGTH) {\n return summary;\n }\n const truncated = summary.substring(0, MAX_SUMMARY_LENGTH);\n const lastSpace = truncated.lastIndexOf(' ');\n return lastSpace > 0 ? truncated.substring(0, lastSpace) : truncated;\n}\n\nlet integerLiteralRE: RegExp | undefined;\nlet mssqlIntegerLiteralRE: RegExp | undefined;\n\n/**\n * The lookbehind keeps `$n` and `?n` parameter placeholders out of the match. T-SQL has neither,\n * and `$1000` there is a money literal, so `$` only guards a placeholder outside `mssql`.\n *\n * Lazy init: constructing a lookbehind at module scope evaluates it on import and crashes\n * Safari <16.4 browser bundles that reach this file via the core barrel.\n */\nfunction getIntegerLiteralRE(dialect: SqlDialect): RegExp {\n if (dialect === 'mssql') {\n if (!mssqlIntegerLiteralRE) {\n mssqlIntegerLiteralRE = new RegExp('(?<!\\\\?)-?\\\\b\\\\d+\\\\b', 'g');\n }\n return mssqlIntegerLiteralRE;\n }\n if (!integerLiteralRE) {\n integerLiteralRE = new RegExp('(?<![$?])-?\\\\b\\\\d+\\\\b', 'g');\n }\n return integerLiteralRE;\n}\n\n/**\n * SQL dialect variants that matter for finding the end of a string literal:\n * - `standard` (PostgreSQL, SQLite): `\"` quotes identifiers, `''` is the only in-string escape,\n * and PostgreSQL's `$$…$$` dollar quoting opens a literal.\n * - `mysql`: `\"` quotes a string literal unless `ANSI_QUOTES` is set, and `\\` escapes the next\n * character unless `NO_BACKSLASH_ESCAPES` is set. Both default to off, and mysql/mysql2 escape\n * inlined values with backslashes, so this is the mode their statements arrive in.\n * - `mssql`: `[...]` quotes an identifier, so a `'` inside one is part of the name. `\"` quotes\n * one too, unless the connection sets `QUOTED_IDENTIFIER OFF`, which tedious leaves on.\n */\nexport type SqlDialect = 'standard' | 'mysql' | 'mssql';\n\n/**\n * Maps a driver or `db.system.name` value to the dialect its statements are written in. Callers\n * report different spellings for one engine: knex uses the driver name, Prisma the provider name,\n * and OTel the semantic-convention name. An engine we do not know about is lexed as `standard`.\n */\nexport function toSqlDialect(system: unknown): SqlDialect {\n if (system === 'mysql' || system === 'mysql2' || system === 'mariadb') {\n return 'mysql';\n }\n if (system === 'mssql' || system === 'sqlserver' || system === 'microsoft.sql_server') {\n return 'mssql';\n }\n return 'standard';\n}\n\n// Sticky, so the scanner can test one position without slicing the query on every `$`.\nconst DOLLAR_QUOTE_RE = /\\$(?:[A-Za-z_]\\w*)?\\$/y;\n\n/**\n * Returns the index just past the run's closing `delimiter`, or -1 if the run never closes. The\n * caller cannot derive that from the index alone: a query ending in `[a]]` consumed a doubled\n * delimiter, not a closing one.\n *\n * A doubled delimiter (`''`) escapes itself in every dialect; backslash escapes are dialect- and\n * context-dependent, so the caller decides.\n */\nfunction findQuotedRunEnd(sql: string, start: number, delimiter: string, backslashEscapes: boolean): number {\n for (let i = start + 1; i < sql.length; i++) {\n const char = sql[i];\n if (backslashEscapes && char === '\\\\') {\n i++;\n } else if (char === delimiter) {\n if (sql[i + 1] !== delimiter) {\n return i + 1;\n }\n i++;\n }\n }\n return -1;\n}\n\n/**\n * Replaces every string literal with `?` and drops every comment, in one pass.\n *\n * Doing this by scanning rather than by regex is what keeps quote state and comment state from\n * being decided independently: a regex for `'...'` cannot see that the quote it stopped at was\n * backslash-escaped, and a regex for `--...` cannot see that the `--` sits inside a literal. Both\n * mistakes end with user data surviving into `db.query.text` and `db.query.summary`.\n *\n * Quoted identifiers are preserved — they are the table and column names the query summary is\n * built from.\n */\nfunction stripLiteralsAndComments(sql: string, dialect: SqlDialect): string {\n const isMysql = dialect === 'mysql';\n const out: string[] = [];\n let i = 0;\n\n while (i < sql.length) {\n const char = sql[i]!;\n const next = sql[i + 1];\n\n if ((char === '-' && next === '-') || (isMysql && char === '#')) {\n const lineEnd = sql.indexOf('\\n', i);\n i = lineEnd === -1 ? sql.length : lineEnd;\n continue;\n }\n\n if (char === '/' && next === '*') {\n const commentEnd = sql.indexOf('*/', i + 2);\n i = commentEnd === -1 ? sql.length : commentEnd + 2;\n continue;\n }\n\n // In a dollar-quoted body (`$$body$$`, `$tag$body$tag$`) nothing has syntax meaning. Read the\n // previous character from the query, not from `out`, where a dropped comment would leave `$$`\n // looking like part of an identifier. Of the `standard` engines only PostgreSQL has dollar\n // quoting. SQLite `$name` parameters do not match the tag pattern, apart from the rare `$a$b`.\n if (dialect === 'standard' && char === '$' && !isIdentifierChar(sql[i - 1])) {\n const tag = matchDollarQuoteTag(sql, i);\n if (tag) {\n const bodyEnd = sql.indexOf(tag, i + tag.length);\n i = bodyEnd === -1 ? sql.length : bodyEnd + tag.length;\n out.push('?');\n continue;\n }\n }\n\n const identifierCloser = getIdentifierCloser(char, dialect);\n if (identifierCloser) {\n const runEnd = findQuotedRunEnd(sql, i, identifierCloser, false);\n // A run that never closes is not an identifier, so it collapses instead of being copied out.\n // Copying would carry every literal in the rest of the statement through unlexed.\n out.push(runEnd === -1 ? '?' : sql.slice(i, runEnd));\n i = runEnd === -1 ? sql.length : runEnd;\n continue;\n }\n\n if (char === \"'\" || (char === '\"' && isMysql)) {\n // A prefix like `X'1A'`, `B'01'`, `N'…'` or PostgreSQL's `E'a\\nb'` is part of the literal, so it has\n // to collapse into the same `?` instead of being left behind as a bare identifier.\n const prefix = char === \"'\" ? getLiteralPrefix(out, dialect) : undefined;\n if (prefix) {\n out.pop();\n }\n const runEnd = findQuotedRunEnd(sql, i, char, isMysql || prefix === 'E');\n i = runEnd === -1 ? sql.length : runEnd;\n out.push('?');\n continue;\n }\n\n out.push(char);\n i++;\n }\n\n return out.join('');\n}\n\n/**\n * Returns the character that closes an identifier opened by `char`, or undefined if `char` opens\n * none. SQL Server brackets close on `]`, and `]]` escapes a `]` inside the name, which is the same\n * doubling rule `findQuotedRunEnd` applies to quotes.\n */\nfunction getIdentifierCloser(char: string, dialect: SqlDialect): string | undefined {\n if (char === '`') {\n return '`';\n }\n if (char === '\"' && dialect !== 'mysql') {\n return '\"';\n }\n return char === '[' && dialect === 'mssql' ? ']' : undefined;\n}\n\n/** Whether `char` can appear inside an identifier. `undefined` (start of query) counts as a break. */\nfunction isIdentifierChar(char: string | undefined): boolean {\n return char !== undefined && /[\\w$]/.test(char);\n}\n\n/** Returns the opening dollar-quote tag at `start` (`$$` or `$tag$`), or undefined if there is none. */\nfunction matchDollarQuoteTag(sql: string, start: number): string | undefined {\n DOLLAR_QUOTE_RE.lastIndex = start;\n return DOLLAR_QUOTE_RE.exec(sql)?.[0];\n}\n\n/**\n * Returns the literal-prefix character immediately before a `'`, if there is one: `X`/`B` for\n * hex/binary literals, `N` for a national-character literal (SQL Server, MySQL), or `E` for a\n * PostgreSQL escape string (which honors backslash escapes).\n */\nfunction getLiteralPrefix(out: string[], dialect: SqlDialect): 'X' | 'B' | 'N' | 'E' | undefined {\n const last = out[out.length - 1];\n // A prefix only counts when it stands alone — the `X` in `MAX'...'` belongs to the identifier\n if (last?.length !== 1 || isIdentifierChar(out[out.length - 2]?.slice(-1))) {\n return undefined;\n }\n\n const prefix = last.toUpperCase();\n if (prefix === 'X' || prefix === 'B' || prefix === 'N') {\n return prefix;\n }\n return prefix === 'E' && dialect === 'standard' ? 'E' : undefined;\n}\n\n/**\n * Sanitize SQL query as per the OTEL semantic conventions\n * https://opentelemetry.io/docs/specs/semconv/database/database-spans/#sanitization-of-dbquerytext\n *\n * Parameter placeholders survive: PostgreSQL `$n`, SQLite `?n`, and named forms like `:name` and\n * `@name`. Per the OTEL spec they mark a parameterized query, so only values (strings, numbers,\n * booleans) are sanitized.\n *\n * Pass `dialect` when the statement comes from a driver whose literals are not standard-quoted;\n * see {@link SqlDialect}.\n */\nexport function sanitizeSqlQuery(sqlQuery: string | undefined, dialect: SqlDialect = 'standard'): string {\n if (!sqlQuery) {\n return 'Unknown SQL Query';\n }\n\n return (\n // Strip comments and string literals first: everything below is a regex that cannot tell\n // whether it is looking at SQL syntax or at a user-supplied value.\n stripLiteralsAndComments(sqlQuery, dialect)\n .replace(/;\\s*$/, '') // Remove trailing semicolons\n .replace(/^[\\s;]+/, '') // Remove leading semicolons (T-SQL's `;WITH`)\n // Collapse whitespace to a single space (after removing comments)\n .replace(/\\s+/g, ' ')\n .trim() // Remove extra spaces and trim\n // Sanitize hex numbers\n .replace(/\\b0x[0-9A-Fa-f]+/gi, '?')\n // Sanitize boolean literals\n .replace(/\\b(?:TRUE|FALSE)\\b/gi, '?')\n // Sanitize numeric literals (preserve $n placeholders via negative lookbehind)\n .replace(/-?\\b\\d+\\.?\\d*[eE][+-]?\\d+\\b/g, '?') // Scientific notation\n .replace(/-?\\b\\d+\\.\\d+\\b/g, '?') // Decimals\n .replace(/-?\\.\\d+\\b/g, '?') // Decimals starting with dot\n .replace(getIntegerLiteralRE(dialect), '?') // Integers (NOT parameter placeholders)\n // Collapse IN clauses for cardinality (both ? and $n variants)\n .replace(/\\bIN\\b\\s*\\(\\s*\\?(?:\\s*,\\s*\\?)*\\s*\\)/gi, 'IN (?)')\n .replace(/\\bIN\\b\\s*\\(\\s*\\$\\d+(?:\\s*,\\s*\\$\\d+)*\\s*\\)/gi, 'IN ($?)')\n );\n}\n\nexport interface SqlQueryAttributes {\n [DB_QUERY_TEXT]: string | undefined;\n [DB_QUERY_SUMMARY]: string | undefined;\n [DB_OPERATION_NAME]: string | undefined;\n}\n\n/**\n * Sanitizes a collected SQL statement into the query attributes the SQL integrations attach to\n * their spans: `db.query.text`, `db.query.summary` and `db.operation.name`. All are `undefined`\n * when there is no statement, so an empty query omits the attributes instead of reporting the\n * sanitizer's fallback text.\n */\nexport function getSqlQueryAttributes(sqlQuery: string | undefined, dialect?: SqlDialect): SqlQueryAttributes {\n const queryText = (sqlQuery && sanitizeSqlQuery(sqlQuery, dialect)) || undefined;\n return {\n [DB_QUERY_TEXT]: queryText,\n [DB_QUERY_SUMMARY]: getSqlQuerySummary(queryText),\n [DB_OPERATION_NAME]: getSqlOperationName(queryText),\n };\n}\n\n/**\n * Names a SQL span with a low-cardinality name: `db.query.summary`, falling back to `db.namespace`\n * and then `db.system.name`. `fallback` is the integration's name for a span with none of those.\n *\n * New SQL integrations should name their spans with this regardless of span streaming.\n */\nexport function getLowCardinalitySqlSpanName(attributes: SpanAttributes, fallback: string): string {\n return toSpanName(attributes[DB_QUERY_SUMMARY] || attributes[DB_NAMESPACE] || attributes[DB_SYSTEM_NAME], fallback);\n}\n\n/**\n * Names a SQL span from its attributes. Streamed span names have to be low cardinality (see\n * {@link getLowCardinalitySqlSpanName}); otherwise the sanitized `db.query.text` is used, which\n * existing integrations keep for spans that aren't streamed.\n */\nexport function getSqlSpanName(attributes: SpanAttributes, fallback: string): string {\n const client = getClient();\n if (client && hasSpanStreamingEnabled(client)) {\n return getLowCardinalitySqlSpanName(attributes, fallback);\n }\n return toSpanName(attributes[DB_QUERY_TEXT], fallback);\n}\n\nfunction toSpanName(value: unknown, fallback: string): string {\n return typeof value === 'string' && value ? value : fallback;\n}\n"],"mappings":";;;AAUA,MAAM,qBAAqB;AAI3B,MAAM,aAAa;AAKnB,MAAM,aAAa,GAAG,WAAW,QAAQ,WAAW;AAEpD,MAAM,SAAS,IAAI,OACjB,qHAAqH,WAAW,IAChI,GACF;AAMA,MAAM,YAAY,IAAI,OACpB,8GAA8G,WAAW,IACzH,GACF;AACA,MAAM,YAAY,IAAI,OACpB,8FAA8F,WAAW,IACzG,GACF;AACA,MAAM,YAAY,IAAI,OAAO,iDAAiD,WAAW,IAAI,GAAG;AAEhG,MAAM,YAAY;AAElB,MAAM,YAAY;AAElB,MAAM,WAAW;AACjB,MAAM,eAAe,IAAI,OAAO,IAAI,YAAY;AAChD,MAAM,iBAAiB,IAAI,OAAO,cAAc,WAAW,EAAE;AAC7D,MAAM,qBAAqB;;;;;;;;;;;;;;AAe3B,SAAgB,mBAAmB,OAA+C;CAChF,IAAI,CAAC,OACH;CAGF,MAAM,cAAc,UAAU,KAAK,KAAK;CACxC,IAAI,aAAa,SAAS,gBAAgB,YAAY,OAAO,YAAY;EACvE,MAAM,YAAY,YAAY,OAAO;EACrC,MAAM,UAAU,YAAY,OAAO;EACnC,MAAM,WAAW,QAAQ,QAAQ,GAAG;EACpC,OAAO,SAAS,GAAG,UAAU,GAAG,YAAY,IAAI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AAgB;GAChB,mBAAmB,mBAAmB,SAAS;GAC/C,oBAAoB,oBAAoB,SAAS;CACpD;AACF;;;;;;;AAQA,SAAgB,6BAA6B,YAA4B,UAA0B;CACjG,OAAO,WAAW,WAAW,qBAAqB,WAAW,iBAAiB,WAAW,iBAAiB,QAAQ;AACpH;;;;;;AAOA,SAAgB,eAAe,YAA4B,UAA0B;CACnF,MAAM,SAAS,UAAU;CACzB,IAAI,UAAU,wBAAwB,MAAM,GAC1C,OAAO,6BAA6B,YAAY,QAAQ;CAE1D,OAAO,WAAW,WAAW,gBAAgB,QAAQ;AACvD;AAEA,SAAS,WAAW,OAAgB,UAA0B;CAC5D,OAAO,OAAO,UAAU,YAAY,QAAQ,QAAQ;AACtD"}
|
|
1
|
+
{"version":3,"file":"sql.js","names":[],"sources":["../../../src/utils/sql.ts"],"sourcesContent":["/* eslint-disable max-lines */\nimport {\n DB_NAMESPACE,\n DB_OPERATION_NAME,\n DB_QUERY_SUMMARY,\n DB_QUERY_TEXT,\n DB_SYSTEM_NAME,\n} from '@sentry/conventions/attributes';\nimport type { SpanAttributes } from '@sentry/core';\nimport { getClient, hasSpanStreamingEnabled } from '@sentry/core';\n\nconst MAX_SUMMARY_LENGTH = 255;\n\n// A single identifier: quoted (`\"...\"`, `'...'`, or MySQL backticks) or bare. The quoted forms have\n// to be matched as a unit, otherwise an identifier containing a space or a dot is cut in half.\nconst IDENTIFIER = '(?:\"[^\"]*\"|\\'[^\\']*\\'|`[^`]*`|[^\\\\s(,;).\\'\"`]+)';\n\n// A table reference can be schema-qualified (`\"public\".\"User\"`, `db.schema.table`), with each part\n// quoted independently. The whole qualified name is the summary target, since the schema is what\n// distinguishes two same-named tables.\nconst TABLE_NAME = `${IDENTIFIER}(?:\\\\.${IDENTIFIER})*`;\n\nconst DDL_RE = new RegExp(\n `^\\\\s*(?<operation>(?:CREATE|DROP)\\\\s+(?:TABLE|INDEX)|ALTER\\\\s+TABLE)(?:\\\\s+IF\\\\s+(?:NOT\\\\s+)?EXISTS)?\\\\s+(?<table>${TABLE_NAME})`,\n 'i',\n);\n\n// SQLite upserts insert an optional conflict clause between operation and INTO\n// (`INSERT OR REPLACE INTO`, https://sqlite.org/lang_insert.html), with `REPLACE INTO` as the\n// standalone shorthand. The clause is filler like INTO — stripping it keeps upserts on the same\n// low-cardinality summary as plain inserts.\nconst INSERT_RE = new RegExp(\n `^\\\\s*(?<operation>INSERT|REPLACE)(?:\\\\s+OR\\\\s+(?:ROLLBACK|ABORT|FAIL|IGNORE|REPLACE))?\\\\s+INTO(?:\\\\s+TABLE)?\\\\s+(?<table>${TABLE_NAME})`,\n 'i',\n);\nconst UPDATE_RE = new RegExp(\n `^\\\\s*(?<operation>UPDATE)(?:\\\\s+OR\\\\s+(?:ROLLBACK|ABORT|FAIL|IGNORE|REPLACE))?\\\\s+(?<table>${TABLE_NAME})`,\n 'i',\n);\nconst DELETE_RE = new RegExp(`^\\\\s*(?<operation>DELETE)\\\\s+FROM\\\\s+(?<table>${TABLE_NAME})`, 'i');\n\nconst SELECT_RE = /^\\s*(?:\\(\\s*)?(?<operation>SELECT)\\b/i;\n\nconst PRAGMA_RE = /^\\s*(?<operation>PRAGMA)\\s+(?<command>\\S+)/i;\n\nconst TOKEN_RE = /\\b(?:FROM|JOIN)\\s+|\\(\\s*(SELECT)\\b|\\b(?:UNION|INTERSECT|EXCEPT|MINUS)\\s+(?:ALL\\s+)?(SELECT)\\b/gi;\nconst TABLE_REF_RE = new RegExp(`^${TABLE_NAME}`);\nconst COMMA_TABLE_RE = new RegExp(`^\\\\s*,\\\\s*(${TABLE_NAME})`);\nconst SUBQUERY_SELECT_RE = /^\\(\\s*(SELECT)\\b/i;\n\n/**\n * Derives a low-cardinality summary from a SQL query for use as `db.query.summary`.\n *\n * Conforms to the OTEL semantic convention for generating query summaries:\n * - Preserves original case of operations and identifiers (no normalization)\n * - Uses format: `{operation} {target1} {target2} ...`\n * - Strips filler words (INTO, FROM) from the operation\n * - Captures multiple table targets (JOINs)\n * - Handles INSERT...SELECT with both targets\n * - Truncates to 255 characters without splitting mid-value\n *\n * @see https://opentelemetry.io/docs/specs/semconv/database/database-spans/#generating-a-summary-of-the-query\n */\nexport function getSqlQuerySummary(query: string | undefined): string | undefined {\n if (!query) {\n return undefined;\n }\n\n const pragmaMatch = PRAGMA_RE.exec(query);\n if (pragmaMatch?.groups?.['operation'] && pragmaMatch.groups['command']) {\n const operation = pragmaMatch.groups['operation'];\n const command = pragmaMatch.groups['command'];\n const parenIdx = command.indexOf('(');\n return truncate(`${operation} ${parenIdx >= 0 ? command.substring(0, parenIdx) : command}`);\n }\n\n const ddlMatch = DDL_RE.exec(query);\n if (ddlMatch?.groups?.['operation'] && ddlMatch.groups['table']) {\n return truncate(`${ddlMatch.groups['operation']} ${ddlMatch.groups['table']}`);\n }\n\n const insertMatch = INSERT_RE.exec(query);\n if (insertMatch?.groups?.['operation'] && insertMatch.groups['table']) {\n const parts = [insertMatch.groups['operation'], insertMatch.groups['table']];\n const rest = query.slice(insertMatch[0].length);\n const subSelect = /\\b(SELECT)\\b/i.exec(rest);\n if (subSelect?.[1]) {\n parts.push(subSelect[1]);\n const selectTables = extractTableNames(rest.slice(subSelect.index));\n parts.push(...selectTables);\n }\n return truncate(parts.join(' '));\n }\n\n const updateMatch = UPDATE_RE.exec(query);\n if (updateMatch?.groups?.['operation'] && updateMatch.groups['table']) {\n return truncate(`${updateMatch.groups['operation']} ${updateMatch.groups['table']}`);\n }\n\n const deleteMatch = DELETE_RE.exec(query);\n if (deleteMatch?.groups?.['operation'] && deleteMatch.groups['table']) {\n return truncate(`${deleteMatch.groups['operation']} ${deleteMatch.groups['table']}`);\n }\n\n const selectMatch = SELECT_RE.exec(query);\n if (selectMatch?.groups?.['operation']) {\n const tables = extractTableNames(query.slice(selectMatch[0].length));\n if (tables.length > 0) {\n return truncate(`${selectMatch.groups['operation']} ${tables.join(' ')}`);\n }\n return selectMatch.groups['operation'];\n }\n\n return truncate(query.trim().split(/\\s+/)[0] ?? query);\n}\n\nconst LEADING_KEYWORD_RE = /^\\s*(?:\\(\\s*)*([A-Za-z]+)\\b/;\nconst CTE_MAIN_STATEMENT_RE = /\\(|\\)|\\b(SELECT|INSERT|UPDATE|DELETE|MERGE|VALUES|TABLE)\\b/gi;\n\n/**\n * Derives `db.operation.name` from a SQL query: the first operation keyword, in its original case.\n *\n * @see https://opentelemetry.io/docs/specs/semconv/registry/attributes/db/#db-operation-name\n */\nexport function getSqlOperationName(query: string | undefined): string | undefined {\n const match = query ? LEADING_KEYWORD_RE.exec(query) : null;\n const keyword = match?.[1];\n if (!query || !match || !keyword) {\n return undefined;\n }\n // Scanned from after `WITH`, so parentheses wrapping the whole query don't shift the depth.\n return keyword.toUpperCase() === 'WITH' ? getCteMainOperationName(query.slice(match[0].length)) : keyword;\n}\n\n/**\n * The operation of a `WITH` query is its main statement: the first operation keyword outside the\n * CTE bodies, which are all parenthesized. Counting parentheses is safe on a sanitized query, which\n * has no literals or comments left.\n */\nfunction getCteMainOperationName(query: string): string | undefined {\n let depth = 0;\n for (const match of query.matchAll(CTE_MAIN_STATEMENT_RE)) {\n if (match[0] === '(') {\n depth++;\n } else if (match[0] === ')') {\n depth--;\n } else if (depth === 0) {\n return match[1];\n }\n }\n return undefined;\n}\n\nfunction extractTableNames(sql: string): string[] {\n const tables: string[] = [];\n TOKEN_RE.lastIndex = 0;\n let match: RegExpExecArray | null;\n\n while ((match = TOKEN_RE.exec(sql)) !== null) {\n const table = match[1] || match[2];\n if (table) {\n tables.push(table);\n continue;\n }\n\n const rest = sql.slice(match.index + match[0].length);\n\n const subqueryMatch = SUBQUERY_SELECT_RE.exec(rest);\n if (subqueryMatch?.[1]) {\n tables.push(subqueryMatch[1]);\n TOKEN_RE.lastIndex = match.index + match[0].length + subqueryMatch[0].length;\n continue;\n }\n\n const tableMatch = TABLE_REF_RE.exec(rest);\n if (!tableMatch) continue;\n tables.push(tableMatch[0]);\n\n let afterTable = rest.slice(tableMatch[0].length);\n let commaMatch: RegExpExecArray | null;\n while ((commaMatch = COMMA_TABLE_RE.exec(afterTable)) !== null) {\n if (!commaMatch[1]) break;\n tables.push(commaMatch[1]);\n afterTable = afterTable.slice(commaMatch[0].length);\n }\n }\n\n return tables;\n}\n\nfunction truncate(summary: string): string {\n if (summary.length <= MAX_SUMMARY_LENGTH) {\n return summary;\n }\n const truncated = summary.substring(0, MAX_SUMMARY_LENGTH);\n const lastSpace = truncated.lastIndexOf(' ');\n return lastSpace > 0 ? truncated.substring(0, lastSpace) : truncated;\n}\n\nlet integerLiteralRE: RegExp | undefined;\nlet mssqlIntegerLiteralRE: RegExp | undefined;\n\n/**\n * The lookbehind keeps `$n` and `?n` parameter placeholders out of the match. T-SQL has neither,\n * and `$1000` there is a money literal, so `$` only guards a placeholder outside `mssql`.\n *\n * Lazy init: constructing a lookbehind at module scope evaluates it on import and crashes\n * Safari <16.4 browser bundles that reach this file via the core barrel.\n */\nfunction getIntegerLiteralRE(dialect: SqlDialect | SqlLexerRules): RegExp {\n if (dialect === 'mssql') {\n if (!mssqlIntegerLiteralRE) {\n mssqlIntegerLiteralRE = new RegExp('(?<!\\\\?)-?\\\\b\\\\d+\\\\b', 'g');\n }\n return mssqlIntegerLiteralRE;\n }\n if (!integerLiteralRE) {\n integerLiteralRE = new RegExp('(?<![$?])-?\\\\b\\\\d+\\\\b', 'g');\n }\n return integerLiteralRE;\n}\n\n/**\n * SQL dialect variants that matter for finding the end of a string literal:\n * - `standard` (PostgreSQL, SQLite): `\"` quotes identifiers, `''` is the only in-string escape,\n * and PostgreSQL's `$$…$$` dollar quoting opens a literal.\n * - `mysql`: `\"` quotes a string literal unless `ANSI_QUOTES` is set, and `\\` escapes the next\n * character unless `NO_BACKSLASH_ESCAPES` is set. Both default to off, and mysql/mysql2 escape\n * inlined values with backslashes, so this is the mode their statements arrive in.\n * - `mssql`: `[...]` quotes an identifier, so a `'` inside one is part of the name. `\"` quotes\n * one too, unless the connection sets `QUOTED_IDENTIFIER OFF`, which tedious leaves on.\n *\n * An engine with other rules passes {@link SqlLexerRules} instead.\n */\nexport type SqlDialect = 'standard' | 'mysql' | 'mssql';\n\n/**\n * Lexer rules for an engine that no {@link SqlDialect} covers. They apply on top of `standard`. The\n * integration of that engine defines them, so a bundle without that integration does not contain them.\n */\nexport interface SqlLexerRules {\n /** Whether `#` starts a line comment. */\n hashComments?: boolean;\n /** Whether a block comment can contain other block comments. */\n nestedComments?: boolean;\n /** Whether `\\` escapes the next character in a string literal or a quoted identifier. */\n backslashEscapes?: boolean;\n /** Sticky pattern for the opening tag of a dollar-quoted literal. Defaults to the PostgreSQL tag. */\n dollarQuote?: RegExp;\n /** Returns the length of the engine-specific literal at `start`, which the lexer replaces with `?`. */\n matchLiteral?: (sql: string, start: number) => number;\n /**\n * Returns true when inline data starts at `start`. The lexer drops the query text from `start` to the\n * end, because data cannot be sanitized as SQL. `out` holds the sanitized text before `start`.\n */\n isInlineData?: (sql: string, start: number, out: string[]) => boolean;\n}\n\n/**\n * Maps a driver or `db.system.name` value to the dialect its statements are written in. Callers\n * report different spellings for one engine: knex uses the driver name, Prisma the provider name,\n * and OTel the semantic-convention name. An engine we do not know about is lexed as `standard`.\n */\nexport function toSqlDialect(system: unknown): SqlDialect {\n if (system === 'mysql' || system === 'mysql2' || system === 'mariadb') {\n return 'mysql';\n }\n if (system === 'mssql' || system === 'sqlserver' || system === 'microsoft.sql_server') {\n return 'mssql';\n }\n return 'standard';\n}\n\nconst NO_RULES: SqlLexerRules = {};\n\n// Sticky, so the scanner can test one position without slicing the query on every `$`.\nconst DOLLAR_QUOTE_RE = /\\$(?:[A-Za-z_]\\w*)?\\$/y;\n\n/**\n * Returns the index just past the run's closing `delimiter`, or -1 if the run never closes. The\n * caller cannot derive that from the index alone: a query ending in `[a]]` consumed a doubled\n * delimiter, not a closing one.\n *\n * A doubled delimiter (`''`) escapes itself in every dialect; backslash escapes are dialect- and\n * context-dependent, so the caller decides.\n */\nfunction findQuotedRunEnd(sql: string, start: number, delimiter: string, backslashEscapes: boolean): number {\n for (let i = start + 1; i < sql.length; i++) {\n const char = sql[i];\n if (backslashEscapes && char === '\\\\') {\n i++;\n } else if (char === delimiter) {\n if (sql[i + 1] !== delimiter) {\n return i + 1;\n }\n i++;\n }\n }\n return -1;\n}\n\n// An unterminated comment consumes the rest of the query.\nfunction findBlockCommentEnd(sql: string, start: number, nested: boolean): number {\n let depth = 1;\n let i = start + 2;\n while (i < sql.length && depth > 0) {\n if (sql[i] === '*' && sql[i + 1] === '/') {\n depth--;\n i += 2;\n } else if (nested && sql[i] === '/' && sql[i + 1] === '*') {\n depth++;\n i += 2;\n } else {\n i++;\n }\n }\n return i;\n}\n\n/**\n * Replaces every string literal with `?` and drops every comment, in one pass.\n *\n * Doing this by scanning rather than by regex is what keeps quote state and comment state from\n * being decided independently: a regex for `'...'` cannot see that the quote it stopped at was\n * backslash-escaped, and a regex for `--...` cannot see that the `--` sits inside a literal. Both\n * mistakes end with user data surviving into `db.query.text` and `db.query.summary`.\n *\n * Quoted identifiers are preserved — they are the table and column names the query summary is\n * built from.\n */\nfunction stripLiteralsAndComments(sql: string, dialect: SqlDialect | SqlLexerRules): string {\n const [base, rules]: [SqlDialect, SqlLexerRules] =\n typeof dialect === 'string' ? [dialect, NO_RULES] : ['standard', dialect];\n const isMysql = base === 'mysql';\n const backslashEscapes = !!rules.backslashEscapes;\n const out: string[] = [];\n let i = 0;\n\n while (i < sql.length) {\n const char = sql.charAt(i);\n const next = sql[i + 1];\n\n if ((char === '-' && next === '-') || ((isMysql || rules.hashComments) && char === '#')) {\n const lineEnd = sql.indexOf('\\n', i);\n i = lineEnd === -1 ? sql.length : lineEnd;\n continue;\n }\n\n if (char === '/' && next === '*') {\n i = findBlockCommentEnd(sql, i, !!rules.nestedComments);\n continue;\n }\n\n // In a dollar-quoted body (`$$body$$`, `$tag$body$tag$`) nothing has syntax meaning. Read the\n // previous character from the query, not from `out`, where a dropped comment would leave `$$`\n // looking like part of an identifier. Of the `standard` engines only PostgreSQL has dollar\n // quoting. SQLite `$name` parameters do not match the tag pattern, apart from the rare `$a$b`.\n if (base === 'standard' && char === '$' && !isIdentifierChar(sql[i - 1])) {\n const tag = matchDollarQuoteTag(sql, i, rules.dollarQuote);\n if (tag) {\n const bodyEnd = sql.indexOf(tag, i + tag.length);\n i = bodyEnd === -1 ? sql.length : bodyEnd + tag.length;\n out.push('?');\n continue;\n }\n }\n\n const identifierCloser = getIdentifierCloser(char, base);\n if (identifierCloser) {\n const runEnd = findQuotedRunEnd(sql, i, identifierCloser, backslashEscapes);\n // A run that never closes is not an identifier, so it collapses instead of being copied out.\n // Copying would carry every literal in the rest of the statement through unlexed.\n out.push(runEnd === -1 ? '?' : sql.slice(i, runEnd));\n i = runEnd === -1 ? sql.length : runEnd;\n continue;\n }\n\n if (char === \"'\" || (char === '\"' && isMysql)) {\n // A prefix like `X'1A'`, `B'01'`, `N'…'` or PostgreSQL's `E'a\\nb'` is part of the literal, so it has\n // to collapse into the same `?` instead of being left behind as a bare identifier.\n const prefix = char === \"'\" ? getLiteralPrefix(out, base) : undefined;\n if (prefix) {\n out.pop();\n }\n const runEnd = findQuotedRunEnd(sql, i, char, isMysql || backslashEscapes || prefix === 'E');\n i = runEnd === -1 ? sql.length : runEnd;\n out.push('?');\n continue;\n }\n\n const literalLength = rules.matchLiteral?.(sql, i);\n if (literalLength) {\n out.push('?');\n i += literalLength;\n continue;\n }\n if (rules.isInlineData?.(sql, i, out)) {\n break;\n }\n out.push(char);\n i++;\n }\n\n return out.join('');\n}\n\n/**\n * Returns the character that closes an identifier opened by `char`, or undefined if `char` opens\n * none. SQL Server brackets close on `]`, and `]]` escapes a `]` inside the name, which is the same\n * doubling rule `findQuotedRunEnd` applies to quotes.\n */\nfunction getIdentifierCloser(char: string, dialect: SqlDialect): string | undefined {\n if (char === '`') {\n return '`';\n }\n if (char === '\"' && dialect !== 'mysql') {\n return '\"';\n }\n return char === '[' && dialect === 'mssql' ? ']' : undefined;\n}\n\n/** Whether `char` can appear inside an identifier. `undefined` (start of query) counts as a break. */\nexport function isIdentifierChar(char: string | undefined): boolean {\n return char !== undefined && /[\\w$]/.test(char);\n}\n\n/** Returns the opening dollar-quote tag at `start` (`$$` or `$tag$`), or undefined if there is none. */\nfunction matchDollarQuoteTag(sql: string, start: number, pattern = DOLLAR_QUOTE_RE): string | undefined {\n pattern.lastIndex = start;\n return pattern.exec(sql)?.[0];\n}\n\n/**\n * Returns the literal-prefix character immediately before a `'`, if there is one: `X`/`B` for\n * hex/binary literals, `N` for a national-character literal (SQL Server, MySQL), or `E` for a\n * PostgreSQL escape string (which honors backslash escapes).\n */\nfunction getLiteralPrefix(out: string[], dialect: SqlDialect): 'X' | 'B' | 'N' | 'E' | undefined {\n const last = out[out.length - 1];\n // A prefix only counts when it stands alone — the `X` in `MAX'...'` belongs to the identifier\n if (last?.length !== 1 || isIdentifierChar(out[out.length - 2]?.slice(-1))) {\n return undefined;\n }\n\n const prefix = last.toUpperCase();\n if (prefix === 'X' || prefix === 'B' || prefix === 'N') {\n return prefix;\n }\n return prefix === 'E' && dialect === 'standard' ? 'E' : undefined;\n}\n\n/**\n * Sanitize SQL query as per the OTEL semantic conventions\n * https://opentelemetry.io/docs/specs/semconv/database/database-spans/#sanitization-of-dbquerytext\n *\n * Parameter placeholders survive: PostgreSQL `$n`, SQLite `?n`, and named forms like `:name` and\n * `@name`. Per the OTEL spec they mark a parameterized query, so only values (strings, numbers,\n * booleans) are sanitized.\n *\n * Pass `dialect` when the statement comes from a driver whose literals are not standard-quoted;\n * see {@link SqlDialect} and {@link SqlLexerRules}.\n */\nexport function sanitizeSqlQuery(\n sqlQuery: string | undefined,\n dialect: SqlDialect | SqlLexerRules = 'standard',\n): string {\n if (!sqlQuery) {\n return 'Unknown SQL Query';\n }\n\n return (\n // Strip comments and string literals first: everything below is a regex that cannot tell\n // whether it is looking at SQL syntax or at a user-supplied value.\n stripLiteralsAndComments(sqlQuery, dialect)\n .replace(/;\\s*$/, '') // Remove trailing semicolons\n .replace(/^[\\s;]+/, '') // Remove leading semicolons (T-SQL's `;WITH`)\n // Collapse whitespace to a single space (after removing comments)\n .replace(/\\s+/g, ' ')\n .trim() // Remove extra spaces and trim\n // Sanitize hex numbers\n .replace(/\\b0x[0-9A-Fa-f]+/gi, '?')\n // Sanitize boolean literals\n .replace(/\\b(?:TRUE|FALSE)\\b/gi, '?')\n // Sanitize numeric literals (preserve $n placeholders via negative lookbehind)\n .replace(/-?\\b\\d+\\.?\\d*[eE][+-]?\\d+\\b/g, '?') // Scientific notation\n .replace(/-?\\b\\d+\\.\\d+\\b/g, '?') // Decimals\n .replace(/-?\\.\\d+\\b/g, '?') // Decimals starting with dot\n .replace(getIntegerLiteralRE(dialect), '?') // Integers (NOT parameter placeholders)\n // Collapse IN clauses for cardinality (both ? and $n variants)\n .replace(/\\bIN\\b\\s*\\(\\s*\\?(?:\\s*,\\s*\\?)*\\s*\\)/gi, 'IN (?)')\n .replace(/\\bIN\\b\\s*\\(\\s*\\$\\d+(?:\\s*,\\s*\\$\\d+)*\\s*\\)/gi, 'IN ($?)')\n );\n}\n\nexport interface SqlQueryAttributes {\n [DB_QUERY_TEXT]: string | undefined;\n [DB_QUERY_SUMMARY]: string | undefined;\n [DB_OPERATION_NAME]: string | undefined;\n}\n\n/**\n * Sanitizes a collected SQL statement into the query attributes the SQL integrations attach to\n * their spans: `db.query.text`, `db.query.summary` and `db.operation.name`. All are `undefined`\n * when there is no statement, so an empty query omits the attributes instead of reporting the\n * sanitizer's fallback text.\n */\nexport function getSqlQueryAttributes(\n sqlQuery: string | undefined,\n dialect?: SqlDialect | SqlLexerRules,\n): SqlQueryAttributes {\n const queryText = (sqlQuery && sanitizeSqlQuery(sqlQuery, dialect)) || undefined;\n return {\n [DB_QUERY_TEXT]: queryText,\n [DB_QUERY_SUMMARY]: getSqlQuerySummary(queryText),\n [DB_OPERATION_NAME]: getSqlOperationName(queryText),\n };\n}\n\n/**\n * Names a SQL span with a low-cardinality name: `db.query.summary`, falling back to `db.namespace`\n * and then `db.system.name`. `fallback` is the integration's name for a span with none of those.\n *\n * New SQL integrations should name their spans with this regardless of span streaming.\n */\nexport function getLowCardinalitySqlSpanName(attributes: SpanAttributes, fallback: string): string {\n return toSpanName(attributes[DB_QUERY_SUMMARY] || attributes[DB_NAMESPACE] || attributes[DB_SYSTEM_NAME], fallback);\n}\n\n/**\n * Names a SQL span from its attributes. Streamed span names have to be low cardinality (see\n * {@link getLowCardinalitySqlSpanName}); otherwise the sanitized `db.query.text` is used, which\n * existing integrations keep for spans that aren't streamed.\n */\nexport function getSqlSpanName(attributes: SpanAttributes, fallback: string): string {\n const client = getClient();\n if (client && hasSpanStreamingEnabled(client)) {\n return getLowCardinalitySqlSpanName(attributes, fallback);\n }\n return toSpanName(attributes[DB_QUERY_TEXT], fallback);\n}\n\nfunction toSpanName(value: unknown, fallback: string): string {\n return typeof value === 'string' && value ? value : fallback;\n}\n"],"mappings":";;;AAWA,MAAM,qBAAqB;AAI3B,MAAM,aAAa;AAKnB,MAAM,aAAa,GAAG,WAAW,QAAQ,WAAW;AAEpD,MAAM,SAAS,IAAI,OACjB,qHAAqH,WAAW,IAChI,GACF;AAMA,MAAM,YAAY,IAAI,OACpB,4HAA4H,WAAW,IACvI,GACF;AACA,MAAM,YAAY,IAAI,OACpB,8FAA8F,WAAW,IACzG,GACF;AACA,MAAM,YAAY,IAAI,OAAO,iDAAiD,WAAW,IAAI,GAAG;AAEhG,MAAM,YAAY;AAElB,MAAM,YAAY;AAElB,MAAM,WAAW;AACjB,MAAM,eAAe,IAAI,OAAO,IAAI,YAAY;AAChD,MAAM,iBAAiB,IAAI,OAAO,cAAc,WAAW,EAAE;AAC7D,MAAM,qBAAqB;;;;;;;;;;;;;;AAe3B,SAAgB,mBAAmB,OAA+C;CAChF,IAAI,CAAC,OACH;CAGF,MAAM,cAAc,UAAU,KAAK,KAAK;CACxC,IAAI,aAAa,SAAS,gBAAgB,YAAY,OAAO,YAAY;EACvE,MAAM,YAAY,YAAY,OAAO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|
import { DEBUG_BUILD } from "../debug-build.js";
|
|
2
2
|
import { debug } from "@sentry/core";
|
|
3
|
-
import {
|
|
3
|
+
import { handleServedNodeTunnelRequest, httpServerHandlesTunnel } from "@sentry/core/server";
|
|
4
4
|
// src/utils/tunnelServer.ts
|
|
5
5
|
const tunnelServers = /* @__PURE__ */ new WeakSet();
|
|
6
6
|
/**
|
|
@@ -14,12 +14,12 @@ const tunnelServers = /* @__PURE__ */ new WeakSet();
|
|
|
14
14
|
function instrumentTunnelServer(message) {
|
|
15
15
|
try {
|
|
16
16
|
const server = message?.server;
|
|
17
|
-
if (!server || tunnelServers.has(server) ||
|
|
17
|
+
if (!server || tunnelServers.has(server) || httpServerHandlesTunnel()) return;
|
|
18
18
|
tunnelServers.add(server);
|
|
19
19
|
const originalEmit = server.emit;
|
|
20
20
|
server.emit = function(event, ...data) {
|
|
21
21
|
const [request, response] = data;
|
|
22
|
-
if (event === "request" &&
|
|
22
|
+
if (event === "request" && handleServedNodeTunnelRequest(request, response)) return true;
|
|
23
23
|
return originalEmit.call(this, event, ...data);
|
|
24
24
|
};
|
|
25
25
|
} catch (error) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"tunnelServer.js","names":[
|
|
1
|
+
{"version":3,"file":"tunnelServer.js","names":[],"sources":["../../../src/utils/tunnelServer.ts"],"sourcesContent":["import { debug } from '@sentry/core';\nimport { handleServedNodeTunnelRequest, httpServerHandlesTunnel } from '@sentry/core/server';\nimport { DEBUG_BUILD } from '../debug-build';\n\ntype TunnelServer = { emit(event: string, ...data: unknown[]): boolean };\n\nconst tunnelServers = new WeakSet<TunnelServer>();\n\n/**\n * Wraps a Node server's `emit` once, so requests to the tunnel `serveTunnelIntegration` serves are answered before\n * any of the app's `request` listeners run. A listener for the `http.server.request.start` diagnostics channel, which\n * Node publishes right before it emits each request, so even the first request is answered. Only without core's HTTP\n * server instrumentation, whose own `emit` wrapper answers them otherwise.\n *\n * It never throws, since Node rethrows a channel listener's error as an uncaught exception.\n */\nexport function instrumentTunnelServer(message: unknown): void {\n try {\n const server = (message as { server?: TunnelServer } | undefined)?.server;\n if (!server || tunnelServers.has(server) || httpServerHandlesTunnel()) {\n return;\n }\n\n tunnelServers.add(server);\n // oxlint-disable-next-line typescript/unbound-method -- called with the server as `this` below\n const originalEmit = server.emit;\n server.emit = function (this: TunnelServer, event: string, ...data: unknown[]) {\n const [request, response] = data as Parameters<typeof handleServedNodeTunnelRequest>;\n if (event === 'request' && handleServedNodeTunnelRequest(request, response)) {\n return true;\n }\n\n return originalEmit.call(this, event, ...data);\n };\n } catch (error) {\n DEBUG_BUILD && debug.error('Sentry tunnel: failed to instrument a server', error);\n }\n}\n"],"mappings":";;;;AAMA,MAAM,gCAAgB,IAAI,QAAsB;;;;;;;;;AAUhD,SAAgB,uBAAuB,SAAwB;CAC7D,IAAI;EACF,MAAM,SAAU,SAAmD;EACnE,IAAI,CAAC,UAAU,cAAc,IAAI,MAAM,KAAK,wBAAwB,GAClE;EAGF,cAAc,IAAI,MAAM;EAExB,MAAM,eAAe,OAAO;EAC5B,OAAO,OAAO,SAA8B,OAAe,GAAG,MAAiB;GAC7E,MAAM,CAAC,SAAS,YAAY;GAC5B,IAAI,UAAU,aAAa,8BAA8B,SAAS,QAAQ,GACxE,OAAO;GAGT,OAAO,aAAa,KAAK,MAAM,OAAO,GAAG,IAAI;EAC/C;CACF,SAAS,OAAO;EACd,eAAe,MAAM,MAAM,gDAAgD,KAAK;CAClF;AACF"}
|