@depup/dd-trace 5.97.0-depup.0 → 6.4.0-depup.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (633) hide show
  1. package/LICENSE-3rdparty.csv +89 -104
  2. package/README.md +9 -3
  3. package/changes.json +8 -3
  4. package/ci/init.js +25 -5
  5. package/ci/vitest-no-worker-init-setup.mjs +430 -0
  6. package/ext/exporters.js +1 -0
  7. package/ext/tags.js +3 -0
  8. package/index.d.ts +315 -244
  9. package/index.electron.js +3 -0
  10. package/initialize.mjs +9 -8
  11. package/loader-hook.mjs +154 -47
  12. package/package.json +118 -78
  13. package/packages/datadog-core/src/storage.js +47 -48
  14. package/packages/datadog-esbuild/index.js +32 -1
  15. package/packages/datadog-esbuild/src/utils.js +46 -3
  16. package/packages/datadog-instrumentations/src/aerospike.js +3 -3
  17. package/packages/datadog-instrumentations/src/ai.js +131 -76
  18. package/packages/datadog-instrumentations/src/amqplib.js +6 -7
  19. package/packages/datadog-instrumentations/src/anthropic.js +10 -10
  20. package/packages/datadog-instrumentations/src/apollo-server-core.js +3 -3
  21. package/packages/datadog-instrumentations/src/apollo-server.js +10 -18
  22. package/packages/datadog-instrumentations/src/avsc.js +6 -6
  23. package/packages/datadog-instrumentations/src/aws-durable-execution-sdk-js-context-methods.js +18 -0
  24. package/packages/datadog-instrumentations/src/aws-durable-execution-sdk-js.js +111 -0
  25. package/packages/datadog-instrumentations/src/aws-sdk.js +172 -72
  26. package/packages/datadog-instrumentations/src/azure-cosmos.js +7 -0
  27. package/packages/datadog-instrumentations/src/azure-durable-functions.js +8 -8
  28. package/packages/datadog-instrumentations/src/azure-functions.js +3 -0
  29. package/packages/datadog-instrumentations/src/bluebird.js +2 -2
  30. package/packages/datadog-instrumentations/src/body-parser.js +5 -2
  31. package/packages/datadog-instrumentations/src/cassandra-driver.js +12 -9
  32. package/packages/datadog-instrumentations/src/child_process.js +15 -15
  33. package/packages/datadog-instrumentations/src/claude-agent-sdk.js +587 -0
  34. package/packages/datadog-instrumentations/src/confluentinc-kafka-javascript.js +41 -24
  35. package/packages/datadog-instrumentations/src/connect.js +14 -12
  36. package/packages/datadog-instrumentations/src/cookie-parser.js +5 -4
  37. package/packages/datadog-instrumentations/src/cookie.js +9 -3
  38. package/packages/datadog-instrumentations/src/couchbase.js +73 -238
  39. package/packages/datadog-instrumentations/src/crypto.js +49 -4
  40. package/packages/datadog-instrumentations/src/cucumber-worker-threads.js +19 -0
  41. package/packages/datadog-instrumentations/src/cucumber.js +747 -187
  42. package/packages/datadog-instrumentations/src/cypress-config.js +164 -56
  43. package/packages/datadog-instrumentations/src/cypress.js +5 -3
  44. package/packages/datadog-instrumentations/src/dns.js +60 -59
  45. package/packages/datadog-instrumentations/src/elasticsearch.js +9 -12
  46. package/packages/datadog-instrumentations/src/electron/preload.js +42 -0
  47. package/packages/datadog-instrumentations/src/electron.js +240 -0
  48. package/packages/datadog-instrumentations/src/express-mongo-sanitize.js +11 -9
  49. package/packages/datadog-instrumentations/src/express-session.js +14 -13
  50. package/packages/datadog-instrumentations/src/express.js +52 -30
  51. package/packages/datadog-instrumentations/src/fastify.js +169 -86
  52. package/packages/datadog-instrumentations/src/fetch.js +5 -5
  53. package/packages/datadog-instrumentations/src/fs.js +22 -20
  54. package/packages/datadog-instrumentations/src/google-cloud-pubsub.js +5 -7
  55. package/packages/datadog-instrumentations/src/google-genai.js +4 -4
  56. package/packages/datadog-instrumentations/src/graphql.js +26 -362
  57. package/packages/datadog-instrumentations/src/grpc/client.js +48 -32
  58. package/packages/datadog-instrumentations/src/grpc/server.js +20 -2
  59. package/packages/datadog-instrumentations/src/hapi.js +2 -2
  60. package/packages/datadog-instrumentations/src/helpers/callback-instrumentor.js +74 -0
  61. package/packages/datadog-instrumentations/src/helpers/check-require-cache.js +85 -9
  62. package/packages/datadog-instrumentations/src/helpers/hook.js +4 -1
  63. package/packages/datadog-instrumentations/src/helpers/hooks.js +12 -0
  64. package/packages/datadog-instrumentations/src/helpers/instrument.js +36 -3
  65. package/packages/datadog-instrumentations/src/helpers/kafka.js +58 -0
  66. package/packages/datadog-instrumentations/src/helpers/optional-peer-bundler.js +65 -0
  67. package/packages/datadog-instrumentations/src/helpers/promise-instrumentor.js +42 -0
  68. package/packages/datadog-instrumentations/src/helpers/promise.js +2 -2
  69. package/packages/datadog-instrumentations/src/helpers/register.js +7 -5
  70. package/packages/datadog-instrumentations/src/helpers/require-optional-peer.js +17 -0
  71. package/packages/datadog-instrumentations/src/helpers/rewriter/compiler.js +13 -5
  72. package/packages/datadog-instrumentations/src/helpers/rewriter/index.js +24 -7
  73. package/packages/datadog-instrumentations/src/helpers/rewriter/instrumentations/ai.js +6 -6
  74. package/packages/datadog-instrumentations/src/helpers/rewriter/instrumentations/aws-durable-execution-sdk-js.js +31 -0
  75. package/packages/datadog-instrumentations/src/helpers/rewriter/instrumentations/azure-cosmos.js +50 -0
  76. package/packages/datadog-instrumentations/src/helpers/rewriter/instrumentations/claude-agent-sdk.js +17 -0
  77. package/packages/datadog-instrumentations/src/helpers/rewriter/instrumentations/graphql.js +201 -0
  78. package/packages/datadog-instrumentations/src/helpers/rewriter/instrumentations/index.js +7 -0
  79. package/packages/datadog-instrumentations/src/helpers/rewriter/instrumentations/langgraph.js +4 -2
  80. package/packages/datadog-instrumentations/src/helpers/rewriter/instrumentations/mercurius.js +31 -0
  81. package/packages/datadog-instrumentations/src/helpers/rewriter/instrumentations/modelcontextprotocol-sdk.js +35 -0
  82. package/packages/datadog-instrumentations/src/helpers/rewriter/instrumentations/playwright.js +85 -0
  83. package/packages/datadog-instrumentations/src/helpers/rewriter/loader.mjs +18 -2
  84. package/packages/datadog-instrumentations/src/helpers/rewriter/transforms.js +49 -224
  85. package/packages/datadog-instrumentations/src/helpers/router-helper.js +8 -8
  86. package/packages/datadog-instrumentations/src/hono.js +71 -9
  87. package/packages/datadog-instrumentations/src/http/client.js +48 -24
  88. package/packages/datadog-instrumentations/src/http/server.js +75 -29
  89. package/packages/datadog-instrumentations/src/http2/client.js +15 -12
  90. package/packages/datadog-instrumentations/src/http2/server.js +156 -23
  91. package/packages/datadog-instrumentations/src/ioredis.js +17 -14
  92. package/packages/datadog-instrumentations/src/iovalkey.js +1 -2
  93. package/packages/datadog-instrumentations/src/jest/bail-reporter.js +42 -0
  94. package/packages/datadog-instrumentations/src/jest/coverage-backfill.js +163 -0
  95. package/packages/datadog-instrumentations/src/jest.js +1783 -401
  96. package/packages/datadog-instrumentations/src/kafkajs.js +284 -170
  97. package/packages/datadog-instrumentations/src/knex.js +17 -17
  98. package/packages/datadog-instrumentations/src/koa.js +15 -14
  99. package/packages/datadog-instrumentations/src/ldapjs.js +5 -5
  100. package/packages/datadog-instrumentations/src/light-my-request.js +2 -2
  101. package/packages/datadog-instrumentations/src/limitd-client.js +4 -4
  102. package/packages/datadog-instrumentations/src/lodash.js +4 -4
  103. package/packages/datadog-instrumentations/src/mariadb.js +18 -16
  104. package/packages/datadog-instrumentations/src/memcached.js +4 -3
  105. package/packages/datadog-instrumentations/src/mercurius.js +11 -0
  106. package/packages/datadog-instrumentations/src/microgateway-core.js +2 -2
  107. package/packages/datadog-instrumentations/src/mocha/common.js +7 -4
  108. package/packages/datadog-instrumentations/src/mocha/main.js +557 -118
  109. package/packages/datadog-instrumentations/src/mocha/utils.js +531 -131
  110. package/packages/datadog-instrumentations/src/mocha/worker.js +27 -9
  111. package/packages/datadog-instrumentations/src/modelcontextprotocol-sdk.js +254 -0
  112. package/packages/datadog-instrumentations/src/mongodb-core.js +43 -31
  113. package/packages/datadog-instrumentations/src/mongodb.js +79 -5
  114. package/packages/datadog-instrumentations/src/mongoose.js +43 -34
  115. package/packages/datadog-instrumentations/src/mquery.js +5 -5
  116. package/packages/datadog-instrumentations/src/multer.js +5 -4
  117. package/packages/datadog-instrumentations/src/mysql.js +17 -17
  118. package/packages/datadog-instrumentations/src/mysql2.js +39 -5
  119. package/packages/datadog-instrumentations/src/nats.js +182 -0
  120. package/packages/datadog-instrumentations/src/net.js +19 -11
  121. package/packages/datadog-instrumentations/src/next.js +44 -10
  122. package/packages/datadog-instrumentations/src/nyc.js +43 -6
  123. package/packages/datadog-instrumentations/src/openai.js +124 -38
  124. package/packages/datadog-instrumentations/src/oracledb.js +12 -7
  125. package/packages/datadog-instrumentations/src/otel-sdk-trace.js +27 -6
  126. package/packages/datadog-instrumentations/src/passport-utils.js +5 -5
  127. package/packages/datadog-instrumentations/src/path-to-regexp.js +44 -0
  128. package/packages/datadog-instrumentations/src/pg.js +58 -25
  129. package/packages/datadog-instrumentations/src/pino.js +25 -41
  130. package/packages/datadog-instrumentations/src/playwright-browser-scripts.js +27 -0
  131. package/packages/datadog-instrumentations/src/playwright.js +1086 -350
  132. package/packages/datadog-instrumentations/src/protobufjs.js +16 -16
  133. package/packages/datadog-instrumentations/src/redis.js +28 -15
  134. package/packages/datadog-instrumentations/src/restify.js +6 -5
  135. package/packages/datadog-instrumentations/src/router.js +243 -87
  136. package/packages/datadog-instrumentations/src/selenium.js +1 -2
  137. package/packages/datadog-instrumentations/src/stripe.js +47 -33
  138. package/packages/datadog-instrumentations/src/tedious.js +28 -0
  139. package/packages/datadog-instrumentations/src/vitest-main-no-worker-init.js +1297 -0
  140. package/packages/datadog-instrumentations/src/vitest-main.js +1592 -0
  141. package/packages/datadog-instrumentations/src/vitest-util.js +251 -0
  142. package/packages/datadog-instrumentations/src/vitest-worker.js +822 -0
  143. package/packages/datadog-instrumentations/src/vitest.js +11 -1262
  144. package/packages/datadog-instrumentations/src/winston.js +4 -4
  145. package/packages/datadog-instrumentations/src/ws.js +7 -7
  146. package/packages/datadog-instrumentations/src/zlib.js +29 -0
  147. package/packages/datadog-plugin-ai/src/index.js +1 -1
  148. package/packages/datadog-plugin-ai/src/tracing.js +66 -3
  149. package/packages/datadog-plugin-ai/src/utils.js +17 -4
  150. package/packages/datadog-plugin-apollo/src/gateway/request.js +1 -21
  151. package/packages/datadog-plugin-avsc/src/schema_iterator.js +3 -3
  152. package/packages/datadog-plugin-aws-durable-execution-sdk-js/src/checkpoint.js +31 -0
  153. package/packages/datadog-plugin-aws-durable-execution-sdk-js/src/client.js +55 -0
  154. package/packages/datadog-plugin-aws-durable-execution-sdk-js/src/context.js +123 -0
  155. package/packages/datadog-plugin-aws-durable-execution-sdk-js/src/handler.js +129 -0
  156. package/packages/datadog-plugin-aws-durable-execution-sdk-js/src/index.js +19 -0
  157. package/packages/datadog-plugin-aws-durable-execution-sdk-js/src/trace-checkpoint.js +224 -0
  158. package/packages/datadog-plugin-aws-durable-execution-sdk-js/src/util.js +79 -0
  159. package/packages/datadog-plugin-aws-sdk/src/base.js +86 -50
  160. package/packages/datadog-plugin-aws-sdk/src/services/bedrockruntime/tracing.js +1 -1
  161. package/packages/datadog-plugin-aws-sdk/src/services/bedrockruntime/utils.js +218 -4
  162. package/packages/datadog-plugin-aws-sdk/src/services/cloudwatchlogs.js +1 -1
  163. package/packages/datadog-plugin-aws-sdk/src/services/dynamodb.js +2 -1
  164. package/packages/datadog-plugin-aws-sdk/src/services/eventbridge.js +59 -14
  165. package/packages/datadog-plugin-aws-sdk/src/services/kinesis.js +174 -75
  166. package/packages/datadog-plugin-aws-sdk/src/services/lambda.js +34 -23
  167. package/packages/datadog-plugin-aws-sdk/src/services/redshift.js +2 -1
  168. package/packages/datadog-plugin-aws-sdk/src/services/s3.js +1 -1
  169. package/packages/datadog-plugin-aws-sdk/src/services/sns.js +26 -26
  170. package/packages/datadog-plugin-aws-sdk/src/services/sqs.js +187 -101
  171. package/packages/datadog-plugin-aws-sdk/src/services/stepfunctions.js +20 -18
  172. package/packages/datadog-plugin-azure-cosmos/src/index.js +144 -0
  173. package/packages/datadog-plugin-azure-event-hubs/src/producer.js +8 -15
  174. package/packages/datadog-plugin-azure-functions/src/index.js +7 -3
  175. package/packages/datadog-plugin-azure-service-bus/src/producer.js +5 -10
  176. package/packages/datadog-plugin-bullmq/src/consumer.js +5 -4
  177. package/packages/datadog-plugin-bullmq/src/filter.js +35 -0
  178. package/packages/datadog-plugin-bullmq/src/producer.js +121 -33
  179. package/packages/datadog-plugin-bunyan/src/index.js +28 -0
  180. package/packages/datadog-plugin-child_process/src/index.js +13 -2
  181. package/packages/datadog-plugin-child_process/src/scrub-cmd-params.js +6 -6
  182. package/packages/datadog-plugin-claude-agent-sdk/src/index.js +31 -0
  183. package/packages/datadog-plugin-claude-agent-sdk/src/tracing.js +107 -0
  184. package/packages/datadog-plugin-claude-agent-sdk/src/util.js +15 -0
  185. package/packages/datadog-plugin-couchbase/src/index.js +58 -52
  186. package/packages/datadog-plugin-cucumber/src/index.js +46 -28
  187. package/packages/datadog-plugin-cypress/src/cypress-plugin.js +961 -92
  188. package/packages/datadog-plugin-cypress/src/index.js +104 -2
  189. package/packages/datadog-plugin-cypress/src/plugin.js +6 -14
  190. package/packages/datadog-plugin-cypress/src/source-map-utils.js +48 -1
  191. package/packages/datadog-plugin-cypress/src/support.js +180 -25
  192. package/packages/datadog-plugin-dd-trace-api/src/index.js +1 -1
  193. package/packages/datadog-plugin-dns/src/lookup.js +8 -6
  194. package/packages/datadog-plugin-elasticsearch/src/index.js +28 -8
  195. package/packages/datadog-plugin-electron/src/index.js +17 -0
  196. package/packages/datadog-plugin-electron/src/ipc.js +143 -0
  197. package/packages/datadog-plugin-electron/src/net.js +82 -0
  198. package/packages/datadog-plugin-express/src/code_origin.js +1 -1
  199. package/packages/datadog-plugin-fastify/src/code_origin.js +1 -1
  200. package/packages/datadog-plugin-fs/src/index.js +2 -1
  201. package/packages/datadog-plugin-google-cloud-pubsub/src/consumer.js +2 -5
  202. package/packages/datadog-plugin-google-cloud-pubsub/src/producer.js +27 -18
  203. package/packages/datadog-plugin-google-cloud-pubsub/src/pubsub-push-subscription.js +5 -8
  204. package/packages/datadog-plugin-graphql/src/execute.js +706 -34
  205. package/packages/datadog-plugin-graphql/src/index.js +43 -9
  206. package/packages/datadog-plugin-graphql/src/parse.js +45 -4
  207. package/packages/datadog-plugin-graphql/src/request.js +135 -0
  208. package/packages/datadog-plugin-graphql/src/tools/signature.js +32 -7
  209. package/packages/datadog-plugin-graphql/src/tools/transforms.js +118 -100
  210. package/packages/datadog-plugin-graphql/src/utils.js +261 -3
  211. package/packages/datadog-plugin-graphql/src/validate.js +53 -7
  212. package/packages/datadog-plugin-grpc/src/client.js +7 -8
  213. package/packages/datadog-plugin-grpc/src/server.js +1 -1
  214. package/packages/datadog-plugin-grpc/src/util.js +57 -22
  215. package/packages/datadog-plugin-http/src/client.js +12 -14
  216. package/packages/datadog-plugin-http/src/index.js +6 -8
  217. package/packages/datadog-plugin-http/src/server.js +63 -20
  218. package/packages/datadog-plugin-http2/src/client.js +6 -3
  219. package/packages/datadog-plugin-http2/src/server.js +48 -8
  220. package/packages/datadog-plugin-jest/src/index.js +133 -67
  221. package/packages/datadog-plugin-jest/src/util.js +37 -16
  222. package/packages/datadog-plugin-kafkajs/src/batch-consumer.js +1 -1
  223. package/packages/datadog-plugin-kafkajs/src/consumer.js +2 -9
  224. package/packages/datadog-plugin-kafkajs/src/producer.js +37 -8
  225. package/packages/datadog-plugin-langgraph/src/stream.js +1 -1
  226. package/packages/datadog-plugin-memcached/src/index.js +1 -1
  227. package/packages/datadog-plugin-mocha/src/index.js +66 -20
  228. package/packages/datadog-plugin-modelcontextprotocol-sdk/src/index.js +24 -0
  229. package/packages/datadog-plugin-modelcontextprotocol-sdk/src/tracing.js +173 -0
  230. package/packages/datadog-plugin-modelcontextprotocol-sdk/src/utils.js +30 -0
  231. package/packages/datadog-plugin-mongodb-core/src/bulk-write.js +43 -0
  232. package/packages/datadog-plugin-mongodb-core/src/index.js +8 -206
  233. package/packages/datadog-plugin-mongodb-core/src/query.js +452 -0
  234. package/packages/datadog-plugin-mysql/src/index.js +9 -4
  235. package/packages/datadog-plugin-nats/src/consumer.js +43 -0
  236. package/packages/datadog-plugin-nats/src/index.js +20 -0
  237. package/packages/datadog-plugin-nats/src/producer.js +62 -0
  238. package/packages/datadog-plugin-nats/src/util.js +33 -0
  239. package/packages/datadog-plugin-next/src/index.js +12 -4
  240. package/packages/datadog-plugin-openai/src/services.js +4 -3
  241. package/packages/datadog-plugin-openai/src/tracing.js +27 -25
  242. package/packages/datadog-plugin-oracledb/src/index.js +13 -2
  243. package/packages/datadog-plugin-pg/src/index.js +13 -3
  244. package/packages/datadog-plugin-pino/src/index.js +42 -0
  245. package/packages/datadog-plugin-playwright/src/index.js +21 -11
  246. package/packages/datadog-plugin-protobufjs/src/schema_iterator.js +3 -3
  247. package/packages/datadog-plugin-redis/src/index.js +54 -25
  248. package/packages/datadog-plugin-rhea/src/producer.js +1 -1
  249. package/packages/datadog-plugin-router/src/index.js +46 -44
  250. package/packages/datadog-plugin-selenium/src/index.js +1 -1
  251. package/packages/datadog-plugin-tedious/src/index.js +1 -1
  252. package/packages/datadog-plugin-undici/src/index.js +24 -2
  253. package/packages/datadog-plugin-vitest/src/index.js +160 -90
  254. package/packages/datadog-plugin-winston/src/index.js +30 -0
  255. package/packages/datadog-plugin-ws/src/close.js +3 -1
  256. package/packages/datadog-plugin-ws/src/producer.js +2 -0
  257. package/packages/datadog-plugin-ws/src/receiver.js +2 -1
  258. package/packages/datadog-shimmer/src/shimmer.js +101 -39
  259. package/packages/datadog-webpack/index.js +17 -1
  260. package/packages/datadog-webpack/src/optional-peer-loader.js +17 -0
  261. package/packages/dd-trace/index.electron.js +3 -0
  262. package/packages/dd-trace/index.js +2 -36
  263. package/packages/dd-trace/src/aiguard/channels.js +7 -0
  264. package/packages/dd-trace/src/aiguard/index.js +16 -34
  265. package/packages/dd-trace/src/aiguard/integrations/evaluate.js +46 -0
  266. package/packages/dd-trace/src/aiguard/integrations/index.js +34 -0
  267. package/packages/dd-trace/src/aiguard/integrations/openai.js +80 -0
  268. package/packages/dd-trace/src/aiguard/integrations/vercel-ai.js +92 -0
  269. package/packages/dd-trace/src/aiguard/messages/openai.js +382 -0
  270. package/packages/{datadog-instrumentations/src/helpers/ai-messages.js → dd-trace/src/aiguard/messages/vercel-ai.js} +30 -27
  271. package/packages/dd-trace/src/aiguard/sdk.js +147 -54
  272. package/packages/dd-trace/src/aiguard/tags.js +26 -10
  273. package/packages/dd-trace/src/appsec/api_security/index.js +55 -0
  274. package/packages/dd-trace/src/appsec/api_security/sampler.js +147 -0
  275. package/packages/dd-trace/src/appsec/blocked_templates.js +4 -3
  276. package/packages/dd-trace/src/appsec/blocking.js +82 -42
  277. package/packages/dd-trace/src/appsec/channels.js +5 -1
  278. package/packages/dd-trace/src/appsec/downstream_requests.js +116 -62
  279. package/packages/dd-trace/src/appsec/graphql.js +20 -17
  280. package/packages/dd-trace/src/appsec/iast/analyzers/hardcoded-password-rules.js +1 -1
  281. package/packages/dd-trace/src/appsec/iast/analyzers/hardcoded-secret-rules.js +81 -81
  282. package/packages/dd-trace/src/appsec/iast/analyzers/nosql-injection-mongodb-analyzer.js +23 -23
  283. package/packages/dd-trace/src/appsec/iast/index.js +3 -2
  284. package/packages/dd-trace/src/appsec/iast/security-controls/index.js +4 -4
  285. package/packages/dd-trace/src/appsec/iast/taint-tracking/plugins/kafka.js +2 -2
  286. package/packages/dd-trace/src/appsec/iast/taint-tracking/rewriter.js +4 -4
  287. package/packages/dd-trace/src/appsec/iast/taint-tracking/taint-tracking-impl.js +2 -2
  288. package/packages/dd-trace/src/appsec/iast/telemetry/index.js +2 -1
  289. package/packages/dd-trace/src/appsec/iast/vulnerabilities-formatter/evidence-redaction/sensitive-analyzers/ldap-sensitive-analyzer.js +54 -12
  290. package/packages/dd-trace/src/appsec/iast/vulnerabilities-formatter/evidence-redaction/sensitive-analyzers/url-sensitive-analyzer.js +5 -1
  291. package/packages/dd-trace/src/appsec/iast/vulnerabilities-formatter/evidence-redaction/sensitive-handler.js +31 -4
  292. package/packages/dd-trace/src/appsec/iast/vulnerabilities-formatter/index.js +1 -3
  293. package/packages/dd-trace/src/appsec/iast/vulnerabilities-formatter/utils.js +83 -48
  294. package/packages/dd-trace/src/appsec/iast/vulnerability-reporter.js +1 -1
  295. package/packages/dd-trace/src/appsec/index.js +65 -47
  296. package/packages/dd-trace/src/appsec/lambda.js +135 -0
  297. package/packages/dd-trace/src/appsec/rasp/command_injection.js +4 -5
  298. package/packages/dd-trace/src/appsec/rasp/lfi.js +8 -4
  299. package/packages/dd-trace/src/appsec/rasp/sql_injection.js +5 -10
  300. package/packages/dd-trace/src/appsec/rasp/ssrf.js +26 -18
  301. package/packages/dd-trace/src/appsec/recommended.json +2438 -13
  302. package/packages/dd-trace/src/appsec/reporter.js +87 -28
  303. package/packages/dd-trace/src/appsec/rule_manager.js +4 -2
  304. package/packages/dd-trace/src/appsec/sdk/set_user.js +1 -1
  305. package/packages/dd-trace/src/appsec/sdk/track_event.js +5 -5
  306. package/packages/dd-trace/src/appsec/sdk/user_blocking.js +7 -11
  307. package/packages/dd-trace/src/appsec/sdk/utils.js +5 -3
  308. package/packages/dd-trace/src/appsec/store.js +50 -0
  309. package/packages/dd-trace/src/appsec/telemetry/api_security.js +34 -0
  310. package/packages/dd-trace/src/appsec/telemetry/index.js +27 -1
  311. package/packages/dd-trace/src/appsec/user_tracking.js +5 -4
  312. package/packages/dd-trace/src/appsec/waf/index.js +19 -9
  313. package/packages/dd-trace/src/appsec/waf/waf_context_wrapper.js +35 -20
  314. package/packages/dd-trace/src/appsec/waf/waf_manager.js +1 -1
  315. package/packages/dd-trace/src/azure_metadata.js +17 -6
  316. package/packages/dd-trace/src/baggage.js +32 -13
  317. package/packages/dd-trace/src/bootstrap.js +39 -0
  318. package/packages/dd-trace/src/ci-visibility/dynamic-instrumentation/index.js +30 -5
  319. package/packages/dd-trace/src/ci-visibility/dynamic-instrumentation/worker/index.js +122 -24
  320. package/packages/dd-trace/src/ci-visibility/early-flake-detection/get-known-tests.js +22 -7
  321. package/packages/dd-trace/src/ci-visibility/exporters/agent-proxy/index.js +5 -2
  322. package/packages/dd-trace/src/ci-visibility/exporters/agentless/coverage-writer.js +2 -2
  323. package/packages/dd-trace/src/ci-visibility/exporters/agentless/di-logs-writer.js +2 -2
  324. package/packages/dd-trace/src/ci-visibility/exporters/agentless/index.js +6 -2
  325. package/packages/dd-trace/src/ci-visibility/exporters/agentless/writer.js +2 -2
  326. package/packages/dd-trace/src/ci-visibility/exporters/ci-visibility-exporter.js +148 -25
  327. package/packages/dd-trace/src/ci-visibility/exporters/git/git_metadata.js +3 -4
  328. package/packages/dd-trace/src/ci-visibility/exporters/test-worker/index.js +28 -10
  329. package/packages/dd-trace/src/ci-visibility/exporters/test-worker/writer.js +22 -0
  330. package/packages/dd-trace/src/ci-visibility/intelligent-test-runner/get-skippable-suites.js +105 -22
  331. package/packages/dd-trace/src/ci-visibility/lage.js +2 -1
  332. package/packages/dd-trace/src/ci-visibility/log-submission/log-submission-plugin.js +4 -5
  333. package/packages/dd-trace/src/ci-visibility/requests/fs-cache.js +4 -5
  334. package/packages/dd-trace/src/ci-visibility/requests/get-library-configuration.js +73 -55
  335. package/packages/dd-trace/src/ci-visibility/requests/request.js +14 -50
  336. package/packages/dd-trace/src/ci-visibility/requests/upload-coverage-report.js +4 -4
  337. package/packages/dd-trace/src/ci-visibility/requests/upload-test-screenshot.js +156 -0
  338. package/packages/dd-trace/src/ci-visibility/test-api-manual/test-api-manual-plugin.js +5 -3
  339. package/packages/dd-trace/src/ci-visibility/test-management/get-test-management-tests.js +24 -6
  340. package/packages/dd-trace/src/ci-visibility/test-optimization-cache.js +70 -6
  341. package/packages/dd-trace/src/ci-visibility/test-optimization-http-cache-schema.js +128 -0
  342. package/packages/dd-trace/src/ci-visibility/test-optimization-http-cache.js +291 -0
  343. package/packages/dd-trace/src/config/config-types.d.ts +8 -6
  344. package/packages/dd-trace/src/config/defaults.js +71 -44
  345. package/packages/dd-trace/src/config/generated-config-types.d.ts +676 -131
  346. package/packages/dd-trace/src/config/git_properties.js +2 -2
  347. package/packages/dd-trace/src/config/helper.js +139 -33
  348. package/packages/dd-trace/src/config/index.js +117 -131
  349. package/packages/dd-trace/src/config/major-overrides.js +100 -0
  350. package/packages/dd-trace/src/config/normalize-service.js +31 -0
  351. package/packages/dd-trace/src/config/parsers.js +138 -10
  352. package/packages/dd-trace/src/config/remote_config.js +1 -1
  353. package/packages/dd-trace/src/config/supported-configurations.json +394 -203
  354. package/packages/dd-trace/src/constants.js +15 -0
  355. package/packages/dd-trace/src/crashtracking/crashtracker.js +18 -6
  356. package/packages/dd-trace/src/datastreams/checkpointer.js +6 -12
  357. package/packages/dd-trace/src/datastreams/context.js +4 -2
  358. package/packages/dd-trace/src/datastreams/encoding.js +39 -28
  359. package/packages/dd-trace/src/datastreams/index.js +2 -1
  360. package/packages/dd-trace/src/datastreams/manager.js +1 -1
  361. package/packages/dd-trace/src/datastreams/pathway.js +35 -30
  362. package/packages/dd-trace/src/datastreams/processor.js +31 -22
  363. package/packages/dd-trace/src/datastreams/size.js +6 -2
  364. package/packages/dd-trace/src/datastreams/writer.js +15 -6
  365. package/packages/dd-trace/src/debugger/config.js +9 -4
  366. package/packages/dd-trace/src/debugger/devtools_client/breakpoints.js +49 -35
  367. package/packages/dd-trace/src/debugger/devtools_client/condition.js +5 -8
  368. package/packages/dd-trace/src/debugger/devtools_client/config.js +3 -2
  369. package/packages/dd-trace/src/debugger/devtools_client/index.js +33 -71
  370. package/packages/dd-trace/src/debugger/devtools_client/probe_sampler.js +83 -0
  371. package/packages/dd-trace/src/debugger/devtools_client/send.js +27 -6
  372. package/packages/dd-trace/src/debugger/devtools_client/snapshot/collector.js +2 -2
  373. package/packages/dd-trace/src/debugger/devtools_client/snapshot/processor.js +5 -2
  374. package/packages/dd-trace/src/debugger/devtools_client/snapshot-pruner.js +1 -0
  375. package/packages/dd-trace/src/debugger/devtools_client/source-maps.js +1 -1
  376. package/packages/dd-trace/src/debugger/devtools_client/state.js +3 -1
  377. package/packages/dd-trace/src/debugger/index.js +13 -9
  378. package/packages/dd-trace/src/debugger/probe_sampler.js +112 -0
  379. package/packages/dd-trace/src/debugger/probe_sampler_constants.js +19 -0
  380. package/packages/dd-trace/src/dogstatsd.js +34 -28
  381. package/packages/dd-trace/src/encode/0.4.js +829 -268
  382. package/packages/dd-trace/src/encode/0.5.js +158 -22
  383. package/packages/dd-trace/src/encode/agentless-ci-visibility.js +141 -65
  384. package/packages/dd-trace/src/encode/agentless-json.js +12 -6
  385. package/packages/dd-trace/src/encode/coverage-ci-visibility.js +52 -15
  386. package/packages/dd-trace/src/encode/span-stats.js +19 -16
  387. package/packages/dd-trace/src/encode/tags-processors.js +30 -25
  388. package/packages/dd-trace/src/exporter.js +3 -1
  389. package/packages/dd-trace/src/exporters/agent/index.js +4 -5
  390. package/packages/dd-trace/src/exporters/agent/writer.js +1 -2
  391. package/packages/dd-trace/src/exporters/agentless/index.js +12 -13
  392. package/packages/dd-trace/src/exporters/agentless/intake.js +43 -0
  393. package/packages/dd-trace/src/exporters/agentless/writer.js +12 -11
  394. package/packages/dd-trace/src/exporters/common/agents.js +3 -1
  395. package/packages/dd-trace/src/exporters/common/buffering-exporter.js +3 -3
  396. package/packages/dd-trace/src/exporters/common/request.js +48 -28
  397. package/packages/dd-trace/src/exporters/common/retry.js +104 -0
  398. package/packages/dd-trace/src/exporters/common/url.js +34 -0
  399. package/packages/dd-trace/src/exporters/common/util.js +2 -2
  400. package/packages/dd-trace/src/exporters/common/writer.js +17 -1
  401. package/packages/dd-trace/src/exporters/electron/index.js +49 -0
  402. package/packages/dd-trace/src/exporters/span-stats/index.js +1 -2
  403. package/packages/dd-trace/src/exporters/span-stats/writer.js +1 -3
  404. package/packages/dd-trace/src/external-logger/src/index.js +2 -1
  405. package/packages/dd-trace/src/feature-registry.js +22 -0
  406. package/packages/dd-trace/src/git_metadata.js +68 -0
  407. package/packages/dd-trace/src/git_metadata_tagger.js +13 -5
  408. package/packages/dd-trace/src/guardrails/index.js +11 -6
  409. package/packages/dd-trace/src/guardrails/telemetry.js +40 -3
  410. package/packages/dd-trace/src/heap_snapshots.js +4 -4
  411. package/packages/dd-trace/src/id.js +46 -27
  412. package/packages/dd-trace/src/index.js +7 -8
  413. package/packages/dd-trace/src/lambda/handler-paths.js +52 -0
  414. package/packages/dd-trace/src/lambda/handler.js +2 -6
  415. package/packages/dd-trace/src/lambda/index.js +62 -14
  416. package/packages/dd-trace/src/lambda/runtime/patch.js +21 -46
  417. package/packages/dd-trace/src/llmobs/constants/tags.js +13 -0
  418. package/packages/dd-trace/src/llmobs/index.js +37 -7
  419. package/packages/dd-trace/src/llmobs/plugins/ai/ddTelemetry.js +403 -0
  420. package/packages/dd-trace/src/llmobs/plugins/ai/index.js +8 -395
  421. package/packages/dd-trace/src/llmobs/plugins/ai/util.js +119 -7
  422. package/packages/dd-trace/src/llmobs/plugins/ai/vercelTelemetry.js +363 -0
  423. package/packages/dd-trace/src/llmobs/plugins/{anthropic.js → anthropic/index.js} +32 -79
  424. package/packages/dd-trace/src/llmobs/plugins/anthropic/util.js +109 -0
  425. package/packages/dd-trace/src/llmobs/plugins/base.js +4 -4
  426. package/packages/dd-trace/src/llmobs/plugins/bedrockruntime.js +89 -37
  427. package/packages/dd-trace/src/llmobs/plugins/claude-agent-sdk/index.js +270 -0
  428. package/packages/dd-trace/src/llmobs/plugins/claude-agent-sdk/utils.js +10 -0
  429. package/packages/dd-trace/src/llmobs/plugins/genai/index.js +5 -1
  430. package/packages/dd-trace/src/llmobs/plugins/genai/util.js +81 -16
  431. package/packages/dd-trace/src/llmobs/plugins/langchain/handlers/chain.js +3 -2
  432. package/packages/dd-trace/src/llmobs/plugins/langchain/handlers/chat_model.js +3 -2
  433. package/packages/dd-trace/src/llmobs/plugins/langchain/handlers/embedding.js +2 -1
  434. package/packages/dd-trace/src/llmobs/plugins/langchain/handlers/index.js +1 -50
  435. package/packages/dd-trace/src/llmobs/plugins/langchain/handlers/vectorstore.js +2 -1
  436. package/packages/dd-trace/src/llmobs/plugins/langchain/index.js +14 -8
  437. package/packages/dd-trace/src/llmobs/plugins/langchain/messages.js +76 -0
  438. package/packages/dd-trace/src/llmobs/plugins/langgraph/index.js +3 -28
  439. package/packages/dd-trace/src/llmobs/plugins/modelcontextprotocol-sdk/index.js +68 -0
  440. package/packages/dd-trace/src/llmobs/plugins/modelcontextprotocol-sdk/utils.js +57 -0
  441. package/packages/dd-trace/src/llmobs/plugins/openai/index.js +21 -51
  442. package/packages/dd-trace/src/llmobs/sdk.js +56 -35
  443. package/packages/dd-trace/src/llmobs/span_processor.js +90 -11
  444. package/packages/dd-trace/src/llmobs/tagger.js +129 -4
  445. package/packages/dd-trace/src/llmobs/telemetry.js +31 -1
  446. package/packages/dd-trace/src/llmobs/util.js +202 -9
  447. package/packages/dd-trace/src/llmobs/writers/base.js +11 -5
  448. package/packages/dd-trace/src/llmobs/writers/spans.js +1 -1
  449. package/packages/dd-trace/src/llmobs/writers/util.js +1 -2
  450. package/packages/dd-trace/src/log/index.js +19 -31
  451. package/packages/dd-trace/src/log/writer.js +3 -1
  452. package/packages/dd-trace/src/msgpack/chunk.js +430 -11
  453. package/packages/dd-trace/src/msgpack/index.js +101 -2
  454. package/packages/dd-trace/src/noop/proxy.js +5 -4
  455. package/packages/dd-trace/src/noop/span.js +3 -1
  456. package/packages/dd-trace/src/openfeature/encoding.js +70 -0
  457. package/packages/dd-trace/src/openfeature/eval-metrics-hook.js +103 -0
  458. package/packages/dd-trace/src/openfeature/flagging_provider.js +26 -1
  459. package/packages/dd-trace/src/openfeature/noop.js +40 -36
  460. package/packages/dd-trace/src/openfeature/register.js +46 -0
  461. package/packages/dd-trace/src/openfeature/remote_config.js +6 -1
  462. package/packages/dd-trace/src/openfeature/span-enrichment-hook.js +143 -0
  463. package/packages/dd-trace/src/openfeature/span-enrichment.js +149 -0
  464. package/packages/dd-trace/src/openfeature/writers/base.js +3 -11
  465. package/packages/dd-trace/src/openfeature/writers/exposures.js +82 -70
  466. package/packages/dd-trace/src/openfeature/writers/util.js +1 -2
  467. package/packages/dd-trace/src/opentelemetry/active-span-proxy.js +42 -0
  468. package/packages/dd-trace/src/opentelemetry/bridge-span-base.js +107 -0
  469. package/packages/dd-trace/src/opentelemetry/context_manager.js +27 -13
  470. package/packages/dd-trace/src/opentelemetry/logs/index.js +6 -6
  471. package/packages/dd-trace/src/opentelemetry/logs/otlp_http_log_exporter.js +3 -2
  472. package/packages/dd-trace/src/opentelemetry/metrics/index.js +61 -12
  473. package/packages/dd-trace/src/opentelemetry/metrics/instruments.js +28 -14
  474. package/packages/dd-trace/src/opentelemetry/metrics/meter.js +7 -10
  475. package/packages/dd-trace/src/opentelemetry/metrics/otlp_http_metric_exporter.js +3 -2
  476. package/packages/dd-trace/src/opentelemetry/metrics/otlp_span_stats_exporter.js +40 -0
  477. package/packages/dd-trace/src/opentelemetry/metrics/otlp_span_stats_transformer.js +169 -0
  478. package/packages/dd-trace/src/opentelemetry/metrics/periodic_metric_reader.js +99 -5
  479. package/packages/dd-trace/src/opentelemetry/metrics/time.js +19 -0
  480. package/packages/dd-trace/src/opentelemetry/otlp/common.proto +2 -2
  481. package/packages/dd-trace/src/opentelemetry/otlp/logs.proto +1 -1
  482. package/packages/dd-trace/src/opentelemetry/otlp/logs_service.proto +1 -1
  483. package/packages/dd-trace/src/opentelemetry/otlp/metrics.proto +1 -1
  484. package/packages/dd-trace/src/opentelemetry/otlp/metrics_service.proto +1 -1
  485. package/packages/dd-trace/src/opentelemetry/otlp/otlp_http_exporter_base.js +56 -82
  486. package/packages/dd-trace/src/opentelemetry/otlp/otlp_transformer_base.js +1 -2
  487. package/packages/dd-trace/src/opentelemetry/otlp/protobuf_loader.js +14 -2
  488. package/packages/dd-trace/src/opentelemetry/otlp/trace.proto +358 -0
  489. package/packages/dd-trace/src/opentelemetry/otlp/trace_service.proto +78 -0
  490. package/packages/dd-trace/src/opentelemetry/span-helpers.js +325 -0
  491. package/packages/dd-trace/src/opentelemetry/span.js +59 -109
  492. package/packages/dd-trace/src/opentelemetry/span_context.js +1 -0
  493. package/packages/dd-trace/src/opentelemetry/span_processor.js +7 -5
  494. package/packages/dd-trace/src/opentelemetry/trace/index.js +75 -0
  495. package/packages/dd-trace/src/opentelemetry/trace/otlp_http_trace_exporter.js +75 -0
  496. package/packages/dd-trace/src/opentelemetry/trace/otlp_transformer.js +375 -0
  497. package/packages/dd-trace/src/opentelemetry/tracer.js +20 -69
  498. package/packages/dd-trace/src/opentelemetry/tracer_provider.js +33 -17
  499. package/packages/dd-trace/src/opentracing/propagation/log.js +28 -8
  500. package/packages/dd-trace/src/opentracing/propagation/text_map.js +278 -148
  501. package/packages/dd-trace/src/opentracing/propagation/text_map_dsm.js +11 -11
  502. package/packages/dd-trace/src/opentracing/propagation/tracestate.js +98 -32
  503. package/packages/dd-trace/src/opentracing/span.js +127 -73
  504. package/packages/dd-trace/src/opentracing/span_context.js +68 -3
  505. package/packages/dd-trace/src/opentracing/tracer.js +46 -19
  506. package/packages/dd-trace/src/payload-tagging/config/index.js +2 -2
  507. package/packages/dd-trace/src/plugin_manager.js +36 -14
  508. package/packages/dd-trace/src/plugins/apollo.js +3 -1
  509. package/packages/dd-trace/src/plugins/ci_plugin.js +387 -85
  510. package/packages/dd-trace/src/plugins/database.js +61 -18
  511. package/packages/dd-trace/src/plugins/index.js +14 -0
  512. package/packages/dd-trace/src/plugins/log_injection.js +56 -0
  513. package/packages/dd-trace/src/plugins/log_plugin.js +4 -44
  514. package/packages/dd-trace/src/plugins/outbound.js +1 -1
  515. package/packages/dd-trace/src/plugins/plugin.js +19 -28
  516. package/packages/dd-trace/src/plugins/storage.js +2 -2
  517. package/packages/dd-trace/src/plugins/tracing.js +70 -13
  518. package/packages/dd-trace/src/plugins/util/ci.js +127 -40
  519. package/packages/dd-trace/src/plugins/util/git-cache.js +23 -23
  520. package/packages/dd-trace/src/plugins/util/git.js +3 -1
  521. package/packages/dd-trace/src/plugins/util/http-otel-semantics.js +276 -0
  522. package/packages/dd-trace/src/plugins/util/llm.js +6 -1
  523. package/packages/dd-trace/src/plugins/util/stacktrace.js +2 -2
  524. package/packages/dd-trace/src/plugins/util/test.js +894 -65
  525. package/packages/dd-trace/src/plugins/util/url.js +71 -5
  526. package/packages/dd-trace/src/plugins/util/user-provided-git.js +18 -16
  527. package/packages/dd-trace/src/plugins/util/web.js +116 -180
  528. package/packages/dd-trace/src/priority_sampler.js +12 -21
  529. package/packages/dd-trace/src/profiling/config.js +132 -212
  530. package/packages/dd-trace/src/profiling/constants.js +4 -7
  531. package/packages/dd-trace/src/profiling/exporter_cli.js +10 -10
  532. package/packages/dd-trace/src/profiling/exporters/agent.js +61 -28
  533. package/packages/dd-trace/src/profiling/exporters/event_serializer.js +45 -14
  534. package/packages/dd-trace/src/profiling/exporters/file.js +16 -5
  535. package/packages/dd-trace/src/profiling/oom.js +71 -0
  536. package/packages/dd-trace/src/profiling/profiler.js +84 -105
  537. package/packages/dd-trace/src/profiling/profilers/event_plugins/crypto.js +32 -0
  538. package/packages/dd-trace/src/profiling/profilers/event_plugins/zlib.js +19 -0
  539. package/packages/dd-trace/src/profiling/profilers/events.js +57 -13
  540. package/packages/dd-trace/src/profiling/profilers/space.js +27 -16
  541. package/packages/dd-trace/src/profiling/profilers/wall.js +49 -35
  542. package/packages/dd-trace/src/profiling/ssi-heuristics.js +3 -3
  543. package/packages/dd-trace/src/propagation-hash/index.js +1 -1
  544. package/packages/dd-trace/src/proxy.js +50 -36
  545. package/packages/dd-trace/src/rate_limiter.js +1 -1
  546. package/packages/dd-trace/src/remote_config/index.js +6 -5
  547. package/packages/dd-trace/src/remote_config/scheduler.js +1 -1
  548. package/packages/dd-trace/src/ritm.js +6 -3
  549. package/packages/dd-trace/src/runtime_metrics/client.js +30 -0
  550. package/packages/dd-trace/src/runtime_metrics/index.js +14 -4
  551. package/packages/dd-trace/src/runtime_metrics/otlp_runtime_metrics.js +284 -0
  552. package/packages/dd-trace/src/runtime_metrics/runtime_metrics.js +42 -41
  553. package/packages/dd-trace/src/sampling_rule.js +7 -7
  554. package/packages/dd-trace/src/scope.js +10 -15
  555. package/packages/dd-trace/src/serverless.js +6 -7
  556. package/packages/dd-trace/src/service-naming/extra-services.js +14 -0
  557. package/packages/dd-trace/src/service-naming/index.js +1 -1
  558. package/packages/dd-trace/src/service-naming/schemas/definition.js +4 -1
  559. package/packages/dd-trace/src/service-naming/schemas/util.js +48 -3
  560. package/packages/dd-trace/src/service-naming/schemas/v0/graphql.js +6 -0
  561. package/packages/dd-trace/src/service-naming/schemas/v0/messaging.js +61 -2
  562. package/packages/dd-trace/src/service-naming/schemas/v0/serverless.js +12 -0
  563. package/packages/dd-trace/src/service-naming/schemas/v0/storage.js +60 -0
  564. package/packages/dd-trace/src/service-naming/schemas/v0/web.js +25 -1
  565. package/packages/dd-trace/src/service-naming/schemas/v0/websocket.js +5 -0
  566. package/packages/dd-trace/src/service-naming/schemas/v1/graphql.js +8 -0
  567. package/packages/dd-trace/src/service-naming/schemas/v1/messaging.js +32 -0
  568. package/packages/dd-trace/src/service-naming/schemas/v1/serverless.js +12 -0
  569. package/packages/dd-trace/src/service-naming/schemas/v1/storage.js +17 -0
  570. package/packages/dd-trace/src/service-naming/schemas/v1/web.js +23 -3
  571. package/packages/dd-trace/src/service-naming/schemas/v1/websocket.js +6 -0
  572. package/packages/dd-trace/src/service-naming/source-resolver.js +50 -0
  573. package/packages/dd-trace/src/span_format.js +269 -81
  574. package/packages/dd-trace/src/span_processor.js +13 -13
  575. package/packages/dd-trace/src/span_stats.js +101 -79
  576. package/packages/dd-trace/src/spanleak.js +1 -2
  577. package/packages/dd-trace/src/standalone/index.js +3 -25
  578. package/packages/dd-trace/src/startup-log.js +3 -3
  579. package/packages/dd-trace/src/tagger.js +2 -4
  580. package/packages/dd-trace/src/telemetry/dependencies.js +2 -2
  581. package/packages/dd-trace/src/telemetry/endpoints.js +7 -5
  582. package/packages/dd-trace/src/telemetry/index.js +2 -2
  583. package/packages/dd-trace/src/telemetry/logs/index.js +1 -1
  584. package/packages/dd-trace/src/telemetry/send-data.js +20 -20
  585. package/packages/dd-trace/src/telemetry/session-propagation.js +1 -1
  586. package/packages/dd-trace/src/telemetry/telemetry.js +16 -14
  587. package/packages/dd-trace/src/tracer.js +23 -9
  588. package/packages/dd-trace/src/tracer_metadata.js +1 -1
  589. package/packages/dd-trace/src/util.js +31 -0
  590. package/register.js +58 -1
  591. package/vendor/dist/@apm-js-collab/code-transformer/index.js +94 -42
  592. package/vendor/dist/@datadog/sketches-js/LICENSE +10 -36
  593. package/vendor/dist/@datadog/sketches-js/index.js +1 -1
  594. package/vendor/dist/pprof-format/index.js +1 -1
  595. package/vendor/dist/protobufjs/index.js +1 -1
  596. package/vendor/dist/protobufjs/minimal/index.js +1 -1
  597. package/vendor/dist/shell-quote/index.js +1 -1
  598. package/packages/datadog-plugin-graphql/src/resolve.js +0 -178
  599. package/packages/dd-trace/src/agent/url.js +0 -28
  600. package/packages/dd-trace/src/appsec/api_security_sampler.js +0 -117
  601. package/packages/dd-trace/src/lambda/runtime/ritm.js +0 -133
  602. package/packages/dd-trace/src/log/utils.js +0 -16
  603. package/packages/dd-trace/src/msgpack/encoder.js +0 -308
  604. package/packages/dd-trace/src/plugins/structured_log_plugin.js +0 -9
  605. package/scripts/preinstall.js +0 -34
  606. package/vendor/dist/ignore/LICENSE +0 -21
  607. package/vendor/dist/ignore/index.js +0 -1
  608. package/vendor/dist/opentracing/LICENSE +0 -201
  609. package/vendor/dist/opentracing/binary_carrier.d.ts +0 -11
  610. package/vendor/dist/opentracing/constants.d.ts +0 -61
  611. package/vendor/dist/opentracing/examples/demo/demo.d.ts +0 -2
  612. package/vendor/dist/opentracing/ext/tags.d.ts +0 -90
  613. package/vendor/dist/opentracing/functions.d.ts +0 -20
  614. package/vendor/dist/opentracing/global_tracer.d.ts +0 -14
  615. package/vendor/dist/opentracing/index.d.ts +0 -12
  616. package/vendor/dist/opentracing/index.js +0 -1
  617. package/vendor/dist/opentracing/mock_tracer/index.d.ts +0 -5
  618. package/vendor/dist/opentracing/mock_tracer/mock_context.d.ts +0 -13
  619. package/vendor/dist/opentracing/mock_tracer/mock_report.d.ts +0 -16
  620. package/vendor/dist/opentracing/mock_tracer/mock_span.d.ts +0 -50
  621. package/vendor/dist/opentracing/mock_tracer/mock_tracer.d.ts +0 -26
  622. package/vendor/dist/opentracing/noop.d.ts +0 -8
  623. package/vendor/dist/opentracing/reference.d.ts +0 -33
  624. package/vendor/dist/opentracing/span.d.ts +0 -147
  625. package/vendor/dist/opentracing/span_context.d.ts +0 -26
  626. package/vendor/dist/opentracing/test/api_compatibility.d.ts +0 -16
  627. package/vendor/dist/opentracing/test/mocktracer_implemenation.d.ts +0 -3
  628. package/vendor/dist/opentracing/test/noop_implementation.d.ts +0 -4
  629. package/vendor/dist/opentracing/test/opentracing_api.d.ts +0 -3
  630. package/vendor/dist/opentracing/test/unittest.d.ts +0 -2
  631. package/vendor/dist/opentracing/tracer.d.ts +0 -127
  632. package/vendor/dist/path-to-regexp/LICENSE +0 -21
  633. package/vendor/dist/path-to-regexp/index.js +0 -1
@@ -1,38 +1,258 @@
1
1
  'use strict'
2
2
 
3
- const { MsgpackChunk, MsgpackEncoder } = require('../msgpack')
3
+ const getConfig = require('../config')
4
+ const { MsgpackChunk, MAX_SIZE: MAX_CHUNK_SIZE } = require('../msgpack')
4
5
  const log = require('../log')
5
- const { isTrue } = require('../util')
6
- const { memoize } = require('../log/utils')
7
- const { getValueFromEnvSources } = require('../config/helper')
8
- const { truncateSpan, normalizeSpan } = require('./tags-processors')
6
+ const { normalizeSpan, eventTimeNano } = require('./tags-processors')
9
7
 
10
8
  const SOFT_LIMIT = 8 * 1024 * 1024 // 8MB
9
+ // Values longer than this byte threshold skip the `_stringMap` lookup and
10
+ // emit through `bytes.write` directly. Hashing a multi-KiB string for
11
+ // `Map.get` costs more than the cache hit saves on the inputs that produce
12
+ // strings this long (events JSON, stack traces, large query bodies) — they
13
+ // are unique per span, so the cache hit rate stays near zero anyway.
14
+ const STRING_CACHE_BYPASS_LIMIT = 1024
15
+
16
+ // Pre-encoded static keys + value-prefix bytes; the hot encode loop emits
17
+ // each via one Uint8Array.set instead of routing through the string cache.
18
+
19
+ /**
20
+ * @param {string} key fixstr key, must be < 32 UTF-8 bytes.
21
+ * @returns {Buffer}
22
+ */
23
+ function buildKey (key) {
24
+ const length = Buffer.byteLength(key)
25
+ const buffer = Buffer.allocUnsafe(length + 1)
26
+ buffer[0] = length | 0xA0
27
+ buffer.utf8Write(key, 1, length)
28
+ return buffer
29
+ }
30
+
31
+ /**
32
+ * @param {string} key fixstr key, must be < 32 UTF-8 bytes.
33
+ * @param {number} prefix msgpack prefix byte for the value that follows the key.
34
+ * @returns {Buffer}
35
+ */
36
+ function buildKeyWithPrefix (key, prefix) {
37
+ const length = Buffer.byteLength(key)
38
+ const buffer = Buffer.allocUnsafe(length + 2)
39
+ buffer[0] = length | 0xA0
40
+ buffer.utf8Write(key, 1, length)
41
+ buffer[length + 1] = prefix
42
+ return buffer
43
+ }
44
+
45
+ const KEY_TYPE = buildKey('type')
46
+ const KEY_NAME = buildKey('name')
47
+ const KEY_RESOURCE = buildKey('resource')
48
+ const KEY_SERVICE = buildKey('service')
49
+ const KEY_ERROR = buildKey('error')
50
+ const KEY_START = buildKey('start')
51
+ const KEY_DURATION = buildKey('duration')
52
+
53
+ // Fused `[KEY_ERROR, fixint]` payloads. `error` is `0` or `1` on nearly every
54
+ // span (the boolean-shaped tracer field collapsed onto a single byte). One
55
+ // `bytes.set` writes the key and the value together instead of routing the
56
+ // value through `writeIntOrFloat`'s reserve + branch table.
57
+ const KEY_ERROR_0 = Buffer.concat([KEY_ERROR, Buffer.from([0x00])])
58
+ const KEY_ERROR_1 = Buffer.concat([KEY_ERROR, Buffer.from([0x01])])
59
+ // `[KEY_START, 0xCF]` — `start` is always a nanosecond timestamp ≥ 2³², so
60
+ // the msgpack u64 type byte is statically known and fuses with the key. The
61
+ // 8-byte value is written inline right after.
62
+ const KEY_START_PREFIX = buildKeyWithPrefix('start', 0xCF)
63
+ const KEY_SPAN_EVENTS = buildKey('span_events')
64
+ const KEY_META_STRUCT = buildKey('meta_struct')
65
+ const KEY_TRACE_ID_PREFIX = buildKeyWithPrefix('trace_id', 0xCF)
66
+ const KEY_SPAN_ID_PREFIX = buildKeyWithPrefix('span_id', 0xCF)
67
+ const KEY_PARENT_ID_PREFIX = buildKeyWithPrefix('parent_id', 0xCF)
68
+ const KEY_META_PREFIX = buildKeyWithPrefix('meta', 0xDF)
69
+ const KEY_METRICS_PREFIX = buildKeyWithPrefix('metrics', 0xDF)
70
+
71
+ // Span-event field keys — `name` is shared with the span-level KEY_NAME.
72
+ const KEY_EVENT_TIME = buildKey('time_unix_nano')
73
+ const KEY_EVENT_ATTRIBUTES = buildKey('attributes')
74
+
75
+ // Pre-encoded prefix for a span-event-attribute typed wrapper:
76
+ // `[0x82 fixmap(2), 'type' fixstr, type fixint, '<value>_value' fixstr]`.
77
+ // The hot path emits one of these constants + the raw value, so the encoder
78
+ // never has to allocate `{ type: N, *_value: ... }` wrappers.
79
+ function buildAttrPrefix (typeByte, valueKey) {
80
+ const valueKeyBuf = buildKey(valueKey)
81
+ const buf = Buffer.allocUnsafe(7 + valueKeyBuf.length)
82
+ buf[0] = 0x82
83
+ buf[1] = 0xA4
84
+ buf[2] = 0x74 // t
85
+ buf[3] = 0x79 // y
86
+ buf[4] = 0x70 // p
87
+ buf[5] = 0x65 // e
88
+ buf[6] = typeByte
89
+ valueKeyBuf.copy(buf, 7)
90
+ return buf
91
+ }
11
92
 
12
- function formatSpan (span, config) {
13
- span = normalizeSpan(truncateSpan(span, false))
93
+ const ATTR_PREFIX_STRING = buildAttrPrefix(0x00, 'string_value')
94
+ const ATTR_PREFIX_BOOL = buildAttrPrefix(0x01, 'bool_value')
95
+ const ATTR_PREFIX_INT = buildAttrPrefix(0x02, 'int_value')
96
+ const ATTR_PREFIX_DOUBLE = buildAttrPrefix(0x03, 'double_value')
97
+
98
+ // Outer array attribute is the only nested case: `[0x82, 'type', 4,
99
+ // 'array_value', 0x81 fixmap(1), 'values', 0xDD array32-prefix]`. The 4-byte
100
+ // length slot follows.
101
+ const ATTR_PREFIX_ARRAY = Buffer.concat([
102
+ buildAttrPrefix(0x04, 'array_value'),
103
+ Buffer.from([0x81]),
104
+ buildKey('values'),
105
+ Buffer.from([0xDD]),
106
+ ])
107
+
108
+ // Pre-encoded boolean payloads: `[ATTR_PREFIX_BOOL, 0xC3 / 0xC2]`. Used by
109
+ // `#emitAttribute` and `#emitArrayItem` to emit the whole bool wrapper in a
110
+ // single `bytes.set`.
111
+ const ATTR_PAYLOAD_BOOL_TRUE = Buffer.concat([ATTR_PREFIX_BOOL, Buffer.from([0xC3])])
112
+ const ATTR_PAYLOAD_BOOL_FALSE = Buffer.concat([ATTR_PREFIX_BOOL, Buffer.from([0xC2])])
113
+
114
+ function formatSpanWithLegacyEvents (span) {
115
+ span = normalizeSpan(span)
14
116
  if (span.span_events) {
15
- // ensure span events are encoded as tags if agent doesn't support native top level span events
16
- if (config?.trace?.nativeSpanEvents) {
17
- formatSpanEvents(span)
117
+ // Reads the raw `_events` array directly (no formatter pre-reshape) and
118
+ // serializes to the legacy meta.events JSON string. The serialization is
119
+ // still the main cost on the legacy path; the native span_events slot
120
+ // (`#encodeSpanEvents`) avoids it entirely.
121
+ span.meta.events = stringifySpanEvents(span.span_events)
122
+ // `= undefined` over `delete` to keep the span's hidden class — `delete`
123
+ // would push every event-bearing span into V8 dictionary mode.
124
+ span.span_events = undefined
125
+ }
126
+ return span
127
+ }
128
+
129
+ /**
130
+ * Hand-written stringifier for `span.span_events`. Events arrive in their raw
131
+ * `{ name, startTime, attributes? }` shape; `time_unix_nano` is derived per
132
+ * event via `eventTimeNano` and empty attribute objects are dropped, matching
133
+ * what the formatter used to precompute. Attribute values are pre-sanitized to
134
+ * primitives or arrays of primitives, so we skip everything `JSON.stringify`
135
+ * does for the generic case (toJSON probing, prototype-chain key iteration,
136
+ * replacer hooks).
137
+ *
138
+ * @param {Array<{ name: unknown, startTime: number, attributes?: object }>} spanEvents
139
+ * @returns {string}
140
+ */
141
+ function stringifySpanEvents (spanEvents) {
142
+ let result = '['
143
+ for (let index = 0; index < spanEvents.length; index++) {
144
+ if (index > 0) result += ','
145
+ const event = spanEvents[index]
146
+ // `_sanitizeEventAttributes` leaves `attributes` undefined when empty, so a
147
+ // present value always has entries — no emptiness probe here.
148
+ const attributes = event.attributes
149
+ // `addEvent` does not type-check `name`; defer the unusual cases to
150
+ // `JSON.stringify` so non-string names match the prior behaviour instead
151
+ // of throwing in `escapeJsonString`. Build the wire-shaped object so the
152
+ // emitted key stays `time_unix_nano`, not the raw `startTime`.
153
+ if (typeof event.name !== 'string') {
154
+ result += JSON.stringify({ name: event.name, time_unix_nano: eventTimeNano(event), attributes })
155
+ continue
156
+ }
157
+ result += '{"name":' + escapeJsonString(event.name) +
158
+ ',"time_unix_nano":' + jsonNumber(eventTimeNano(event))
159
+ if (attributes) {
160
+ result += ',"attributes":' + stringifyAttributes(attributes)
161
+ }
162
+ result += '}'
163
+ }
164
+ return result + ']'
165
+ }
166
+
167
+ function stringifyAttributes (attributes) {
168
+ let result = '{'
169
+ let first = true
170
+ for (const key of Object.keys(attributes)) {
171
+ if (first) {
172
+ first = false
18
173
  } else {
19
- span.meta.events = JSON.stringify(span.span_events)
20
- delete span.span_events
174
+ result += ','
21
175
  }
176
+ result += escapeJsonString(key) + ':' + stringifyAttributeValue(attributes[key])
22
177
  }
23
- return span
178
+ return result + '}'
179
+ }
180
+
181
+ function stringifyAttributeValue (value) {
182
+ if (typeof value === 'string') return escapeJsonString(value)
183
+ if (typeof value === 'number') return jsonNumber(value)
184
+ if (typeof value === 'boolean') return value ? 'true' : 'false'
185
+ if (Array.isArray(value)) {
186
+ let result = '['
187
+ for (let index = 0; index < value.length; index++) {
188
+ if (index > 0) result += ','
189
+ result += stringifyAttributeValue(value[index])
190
+ }
191
+ return result + ']'
192
+ }
193
+ // Sanitization rejects everything else, but keep the safety net.
194
+ return 'null'
195
+ }
196
+
197
+ /**
198
+ * Match `JSON.stringify` for numbers: `NaN` and `±Infinity` collapse to the
199
+ * literal `null`, everything else uses ECMAScript's default `Number → String`
200
+ * conversion (which is what `JSON.stringify` calls internally).
201
+ *
202
+ * @param {number} value
203
+ * @returns {string}
204
+ */
205
+ function jsonNumber (value) {
206
+ if (Number.isFinite(value)) return String(value)
207
+ return 'null'
208
+ }
209
+
210
+ /**
211
+ * Fast path: scan once, and if no character in the string requires JSON
212
+ * escaping, emit `"<str>"` as-is. The scanned chars are `"`, `\`, and any
213
+ * control char in the U+0000–U+001F range. Anything else delegates to
214
+ * `JSON.stringify` for full spec-compliant escaping (surrogate pairs,
215
+ * lone surrogates, etc.).
216
+ *
217
+ * @param {string} value
218
+ * @returns {string}
219
+ */
220
+ function escapeJsonString (value) {
221
+ for (let index = 0; index < value.length; index++) {
222
+ const code = value.charCodeAt(index)
223
+ if (code < 0x20 || code === 0x22 || code === 0x5C) {
224
+ return JSON.stringify(value)
225
+ }
226
+ }
227
+ return '"' + value + '"'
228
+ }
229
+
230
+ function lazyEncodedTraceBufferLogger (bytes, start, end) {
231
+ const hex = bytes.buffer.subarray(start, end).toString('hex').match(/../g).join(' ')
232
+ return `Adding encoded trace to buffer: ${hex}`
24
233
  }
25
234
 
26
235
  class AgentEncoder {
236
+ #limit
237
+ #writer
238
+ #config
239
+ #debugEncoding
240
+ #formatSpan
241
+
27
242
  constructor (writer, limit = SOFT_LIMIT) {
28
- this._msgpack = new MsgpackEncoder()
29
- this._limit = limit
243
+ this.#limit = limit
30
244
  this._traceBytes = new MsgpackChunk()
31
245
  this._stringBytes = new MsgpackChunk()
32
- this._writer = writer
246
+ this.#writer = writer
33
247
  this._reset()
34
- this._debugEncoding = isTrue(getValueFromEnvSources('DD_TRACE_ENCODING_DEBUG'))
35
- this._config = this._writer?._config
248
+ this.#config = getConfig()
249
+ this.#debugEncoding = this.#config.DD_TRACE_ENCODING_DEBUG
250
+ // Pick the per-span formatter once so the hot loop pays no per-span
251
+ // config check. The native path keeps the raw `span_events` slot for
252
+ // `#encodeSpanEvents`; the legacy path serializes it into meta.events.
253
+ this.#formatSpan = this.#config.DD_TRACE_NATIVE_SPAN_EVENTS
254
+ ? normalizeSpan
255
+ : formatSpanWithLegacyEvents
36
256
  }
37
257
 
38
258
  count () {
@@ -45,23 +265,38 @@ class AgentEncoder {
45
265
 
46
266
  this._traceCount++
47
267
 
48
- this._encode(bytes, trace)
49
-
50
- const end = bytes.length
51
-
52
- if (this._debugEncoding) {
53
- // eslint-disable-next-line eslint-rules/eslint-log-printf-style
54
- log.debug(() => {
55
- const hex = bytes.buffer.subarray(start, end).toString('hex').match(/../g).join(' ')
268
+ try {
269
+ this._encode(bytes, trace)
270
+ } catch (error) {
271
+ if (error.code !== 'ERR_MSGPACK_CHUNK_OVERFLOW') throw error
272
+ // The trace, or the queued payload it joined, hit the chunk cap.
273
+ // Rolling back just the in-flight trace is unsafe: the string cache
274
+ // may already hold subarrays / indices pointing at bytes we'd
275
+ // discard, and the next encode would emit stale bytes against a
276
+ // smaller string table. Drop the whole queued payload so the next
277
+ // encode starts from a clean state. Emitting a partial buffer would
278
+ // corrupt the msgpack wire. The virtual `reset()` is called (not
279
+ // `_reset()`) so subclasses can clear their own per-payload state
280
+ // (e.g. `AgentlessCiVisibilityEncoder._eventCount`).
281
+ const dropped = this._traceCount
282
+ this.reset()
283
+ log.error(
284
+ 'Trace encoder reset after exceeding the %d byte chunk cap; dropped %d trace(s)',
285
+ MAX_CHUNK_SIZE,
286
+ dropped
287
+ )
288
+ return
289
+ }
56
290
 
57
- return `Adding encoded trace to buffer: ${hex}`
58
- })
291
+ if (this.#debugEncoding) {
292
+ const end = bytes.length
293
+ log.debug(lazyEncodedTraceBufferLogger, bytes, start, end)
59
294
  }
60
295
 
61
- // we can go over the soft limit since the agent has a 50MB hard limit
62
- if (this._traceBytes.length > this._limit || this._stringBytes.length > this._limit) {
296
+ // Soft limit overshoot is fine — the agent caps at 50 MB.
297
+ if (this._traceBytes.length > this.#limit || this._stringBytes.length > this.#limit) {
63
298
  log.debug('Buffer went over soft limit, flushing')
64
- this._writer.flush()
299
+ this.#writer.flush()
65
300
  }
66
301
  }
67
302
 
@@ -81,188 +316,412 @@ class AgentEncoder {
81
316
  }
82
317
 
83
318
  _encode (bytes, trace) {
84
- this._encodeArrayPrefix(bytes, trace)
319
+ bytes.writeArrayPrefix(trace)
320
+
321
+ const formatSpan = this.#formatSpan
322
+ const stringMap = this._stringMap
323
+ // Snapshot the string buffer so we can detect a mid-encode resize and
324
+ // release the old backing store afterwards (see `#refreshStringCache`).
325
+ const stringBufferAtStart = this._stringBytes.buffer
85
326
 
86
327
  for (let span of trace) {
87
- span = formatSpan(span, this._config)
88
- bytes.reserve(1)
328
+ span = formatSpan(span)
89
329
 
90
- // this is the original size of the fixed map for span attributes that always exist
91
330
  let mapSize = 11
331
+ if (span.type) mapSize++
332
+ if (span.meta_struct) mapSize++
333
+ if (span.span_events) mapSize++
334
+
335
+ // Pre-fetch the cached string entries up front and fuse the map prefix,
336
+ // optional `type`, three IDs, `name` / `resource` / `service`, and —
337
+ // in the common fixint-error case — the error/start/duration_key
338
+ // emissions into a single `bytes.reserve` + sequential native writes.
339
+ // Replaces up to ten separate `bytes.reserve` calls per span with one.
340
+ let typeEntry
341
+ if (span.type) {
342
+ typeEntry = stringMap[span.type] ?? this._cacheString(span.type)
343
+ }
344
+ const nameEntry = stringMap[span.name] ?? this._cacheString(span.name)
345
+ const resourceEntry = stringMap[span.resource] ?? this._cacheString(span.resource)
346
+ const serviceEntry = stringMap[span.service] ?? this._cacheString(span.service)
347
+ const nameLen = nameEntry.length
348
+ const resourceLen = resourceEntry.length
349
+ const serviceLen = serviceEntry.length
350
+
351
+ // `error` is `0` or `1` on nearly every span, and `start` is a
352
+ // nanosecond timestamp ≥ 2³² (always a msgpack u64). Decide the fused
353
+ // error key+value up front (`KEY_ERROR_0` / `KEY_ERROR_1`, or `undefined`
354
+ // for the rare non-binary flag) so the tail fuses without re-deciding the
355
+ // error shape twice. The fused tail also needs `start` as a u64; when
356
+ // either misses (synthetic small `start`, non-binary error) the tail
357
+ // routes each integer through `writeIntOrFloat` for the shortest
358
+ // encoding.
359
+ const errorEntry = span.error === 0
360
+ ? KEY_ERROR_0
361
+ : span.error === 1 ? KEY_ERROR_1 : undefined
362
+ const fuseTail = errorEntry !== undefined && span.start >= 0x1_00_00_00_00
363
+
364
+ let blockSize = 1 +
365
+ KEY_TRACE_ID_PREFIX.length + 8 +
366
+ KEY_SPAN_ID_PREFIX.length + 8 +
367
+ KEY_PARENT_ID_PREFIX.length + 8 +
368
+ KEY_NAME.length + nameLen +
369
+ KEY_RESOURCE.length + resourceLen +
370
+ KEY_SERVICE.length + serviceLen
371
+ if (typeEntry) blockSize += KEY_TYPE.length + typeEntry.length
372
+ if (fuseTail) {
373
+ blockSize += errorEntry.length + KEY_START_PREFIX.length + 8 + KEY_DURATION.length
374
+ }
92
375
 
93
- // increment the payload map size depending on if some optional fields exist
94
- if (span.type) mapSize += 1
95
- if (span.meta_struct) mapSize += 1
96
- if (span.span_events) mapSize += 1
376
+ const blockOffset = bytes.length
377
+ bytes.reserve(blockSize)
378
+ const target = bytes.buffer
379
+ let cursor = blockOffset
97
380
 
98
- bytes.buffer[bytes.length - 1] = 0x80 + mapSize
381
+ target[cursor++] = 0x80 + mapSize
99
382
 
100
- if (span.type) {
101
- this._encodeString(bytes, 'type')
102
- this._encodeString(bytes, span.type)
383
+ if (typeEntry) {
384
+ target.set(KEY_TYPE, cursor)
385
+ cursor += KEY_TYPE.length
386
+ target.set(typeEntry, cursor)
387
+ cursor += typeEntry.length
103
388
  }
104
389
 
105
- this._encodeString(bytes, 'trace_id')
106
- this._encodeId(bytes, span.trace_id)
107
- this._encodeString(bytes, 'span_id')
108
- this._encodeId(bytes, span.span_id)
109
- this._encodeString(bytes, 'parent_id')
110
- this._encodeId(bytes, span.parent_id)
111
- this._encodeString(bytes, 'name')
112
- this._encodeString(bytes, span.name)
113
- this._encodeString(bytes, 'resource')
114
- this._encodeString(bytes, span.resource)
115
- this._encodeString(bytes, 'service')
116
- this._encodeString(bytes, span.service)
117
- this._encodeString(bytes, 'error')
118
- this._encodeInteger(bytes, span.error)
119
- this._encodeString(bytes, 'start')
120
- this._encodeLong(bytes, span.start)
121
- this._encodeString(bytes, 'duration')
122
- this._encodeLong(bytes, span.duration)
123
- this._encodeString(bytes, 'meta')
124
- this._encodeMap(bytes, span.meta)
125
- this._encodeString(bytes, 'metrics')
126
- this._encodeMap(bytes, span.metrics)
390
+ cursor = this.#writeIdAt(target, cursor, KEY_TRACE_ID_PREFIX, span.trace_id)
391
+ cursor = this.#writeIdAt(target, cursor, KEY_SPAN_ID_PREFIX, span.span_id)
392
+ cursor = this.#writeIdAt(target, cursor, KEY_PARENT_ID_PREFIX, span.parent_id)
393
+
394
+ target.set(KEY_NAME, cursor)
395
+ cursor += KEY_NAME.length
396
+ target.set(nameEntry, cursor)
397
+ cursor += nameLen
398
+
399
+ target.set(KEY_RESOURCE, cursor)
400
+ cursor += KEY_RESOURCE.length
401
+ target.set(resourceEntry, cursor)
402
+ cursor += resourceLen
403
+
404
+ target.set(KEY_SERVICE, cursor)
405
+ cursor += KEY_SERVICE.length
406
+ target.set(serviceEntry, cursor)
407
+ cursor += serviceLen
408
+
409
+ if (fuseTail) {
410
+ target.set(errorEntry, cursor)
411
+ cursor += errorEntry.length
412
+
413
+ target.set(KEY_START_PREFIX, cursor)
414
+ cursor += KEY_START_PREFIX.length
415
+ // Inline u64 write so the 0xCF type byte and the 8 timestamp bytes
416
+ // share the same reserve as the keys.
417
+ target.writeUInt32BE((span.start / 0x1_00_00_00_00) >>> 0, cursor)
418
+ target.writeUInt32BE(span.start >>> 0, cursor + 4)
419
+ cursor += 8
420
+
421
+ target.set(KEY_DURATION, cursor)
422
+ } else if (errorEntry) {
423
+ bytes.set(errorEntry)
424
+ bytes.set(KEY_START)
425
+ bytes.writeIntOrFloat(span.start)
426
+ bytes.set(KEY_DURATION)
427
+ } else {
428
+ bytes.set(KEY_ERROR)
429
+ bytes.writeIntOrFloat(span.error)
430
+ bytes.set(KEY_START)
431
+ bytes.writeIntOrFloat(span.start)
432
+ bytes.set(KEY_DURATION)
433
+ }
434
+ bytes.writeIntOrFloat(span.duration)
435
+
436
+ this.#encodeMetaEntries(bytes, KEY_META_PREFIX, span.meta)
437
+ this.#encodeMetaEntries(bytes, KEY_METRICS_PREFIX, span.metrics)
438
+
127
439
  if (span.span_events) {
128
- this._encodeString(bytes, 'span_events')
129
- this._encodeObjectAsArray(bytes, span.span_events, new Set())
440
+ bytes.set(KEY_SPAN_EVENTS)
441
+ this.#encodeSpanEvents(bytes, span.span_events)
130
442
  }
131
443
  if (span.meta_struct) {
132
- this._encodeString(bytes, 'meta_struct')
133
- this._encodeMetaStruct(bytes, span.meta_struct)
444
+ bytes.set(KEY_META_STRUCT)
445
+ this.#encodeMetaStruct(bytes, span.meta_struct)
134
446
  }
135
447
  }
448
+
449
+ if (this._stringBytes.buffer !== stringBufferAtStart) {
450
+ this.#refreshStringCache()
451
+ }
452
+ }
453
+
454
+ /**
455
+ * Rebuild the cached string subarrays in `_stringMap` against the current
456
+ * `_stringBytes.buffer`. After `MsgpackChunk.reserve()` resizes, the prior
457
+ * subarrays still reference the old `Buffer`'s `ArrayBuffer` and pin it
458
+ * until `_reset()` clears the map; for a payload that grows 2 → 4 → 8 MB
459
+ * that is up to 6 MB of avoidable peak memory. `Buffer.allocUnsafe(>= 2
460
+ * MB)` bypasses the small-allocation pool and starts at offset 0 in its
461
+ * `ArrayBuffer`, so the old subarray's `byteOffset` is the entry's start
462
+ * position in the new buffer.
463
+ */
464
+ #refreshStringCache () {
465
+ const newBuffer = this._stringBytes.buffer
466
+ const stringMap = this._stringMap
467
+ for (const key of Object.keys(stringMap)) {
468
+ const old = stringMap[key]
469
+ stringMap[key] = newBuffer.subarray(old.byteOffset, old.byteOffset + old.length)
470
+ }
136
471
  }
137
472
 
138
473
  _reset () {
139
474
  this._traceCount = 0
140
- this._traceBytes.length = 0
475
+ this._traceBytes.reset()
141
476
  this._stringCount = 0
142
- this._stringBytes.length = 0
477
+ this._stringBytes.reset()
143
478
  this._stringMap = Object.create(null)
144
479
 
145
480
  this._cacheString('')
146
481
  }
147
482
 
148
- _encodeBuffer (bytes, buffer) {
149
- this._msgpack.encodeBin(bytes, buffer)
150
- }
151
-
152
- _encodeBool (bytes, value) {
153
- this._msgpack.encodeBoolean(bytes, value)
154
- }
155
-
156
- _encodeArrayPrefix (bytes, value) {
157
- this._msgpack.encodeArrayPrefix(bytes, value)
158
- }
159
-
160
- _encodeMapPrefix (bytes, keysLength) {
161
- this._msgpack.encodeMapPrefix(bytes, keysLength)
162
- }
163
-
164
- _encodeByte (bytes, value) {
165
- this._msgpack.encodeByte(bytes, value)
166
- }
167
-
168
483
  // TODO: Use BigInt instead.
169
- _encodeId (bytes, id) {
484
+ _encodeId (bytes, identifier) {
485
+ const idBuffer = identifier.toBuffer()
486
+ const start = idBuffer.length - 8
170
487
  const offset = bytes.length
171
488
 
172
489
  bytes.reserve(9)
173
490
 
174
- id = id.toArray()
491
+ const target = bytes.buffer
492
+ target[offset] = 0xCF
493
+ target[offset + 1] = idBuffer[start]
494
+ target[offset + 2] = idBuffer[start + 1]
495
+ target[offset + 3] = idBuffer[start + 2]
496
+ target[offset + 4] = idBuffer[start + 3]
497
+ target[offset + 5] = idBuffer[start + 4]
498
+ target[offset + 6] = idBuffer[start + 5]
499
+ target[offset + 7] = idBuffer[start + 6]
500
+ target[offset + 8] = idBuffer[start + 7]
501
+ }
502
+
503
+ // Single pass: reserve the count slot, encode entries while counting, patch the count.
504
+ // Subclasses (0.5, CI visibility encoders) inherit this; the wire stays on float64
505
+ // for numeric values to keep their established trace / events intake unchanged.
506
+ _encodeMap (bytes, value) {
507
+ const offset = bytes.length
508
+ bytes.reserve(5)
509
+ bytes.buffer[offset] = 0xDF
510
+
511
+ let count = 0
512
+ for (const key of Object.keys(value)) {
513
+ const entryValue = value[key]
514
+ if (typeof entryValue === 'string') {
515
+ this._encodeString(bytes, key)
516
+ this._encodeString(bytes, entryValue)
517
+ count++
518
+ } else if (typeof entryValue === 'number') {
519
+ this._encodeString(bytes, key)
520
+ bytes.writeFloat(entryValue)
521
+ count++
522
+ }
523
+ }
175
524
 
176
- bytes.buffer[offset] = 0xCF
177
- bytes.buffer[offset + 1] = id[0]
178
- bytes.buffer[offset + 2] = id[1]
179
- bytes.buffer[offset + 3] = id[2]
180
- bytes.buffer[offset + 4] = id[3]
181
- bytes.buffer[offset + 5] = id[4]
182
- bytes.buffer[offset + 6] = id[5]
183
- bytes.buffer[offset + 7] = id[6]
184
- bytes.buffer[offset + 8] = id[7]
525
+ const target = bytes.buffer
526
+ target[offset + 1] = count >>> 24
527
+ target[offset + 2] = count >>> 16
528
+ target[offset + 3] = count >>> 8
529
+ target[offset + 4] = count
185
530
  }
186
531
 
187
- _encodeNumber (bytes, value) {
188
- this._msgpack.encodeNumber(bytes, value)
532
+ _encodeString (bytes, value = '') {
533
+ if (value.length > STRING_CACHE_BYPASS_LIMIT) {
534
+ bytes.write(value)
535
+ return
536
+ }
537
+ const entry = this._stringMap[value] ?? this._cacheString(value)
538
+ const length = entry.length
539
+ const offset = bytes.length
540
+ bytes.reserve(length)
541
+ bytes.buffer.set(entry, offset)
189
542
  }
190
543
 
191
- _encodeInteger (bytes, value) {
192
- this._msgpack.encodeInteger(bytes, value)
544
+ _cacheString (value) {
545
+ let entry = this._stringMap[value]
546
+ if (entry === undefined) {
547
+ this._stringCount++
548
+ const start = this._stringBytes.length
549
+ const written = this._stringBytes.write(value)
550
+ entry = this._stringBytes.buffer.subarray(start, start + written)
551
+ this._stringMap[value] = entry
552
+ }
553
+ return entry
193
554
  }
194
555
 
195
- _encodeLong (bytes, value) {
196
- this._msgpack.encodeLong(bytes, value)
556
+ _writeArrayPrefix (buffer, offset, count) {
557
+ buffer[offset++] = 0xDD
558
+ buffer.writeUInt32BE(count, offset)
559
+
560
+ return offset + 4
197
561
  }
198
562
 
199
- _encodeMap (bytes, value) {
200
- const keys = Object.keys(value)
201
- const validKeys = keys.filter(key => typeof value[key] === 'string' || typeof value[key] === 'number')
563
+ _writeTraces (buffer, offset = 0) {
564
+ offset = this._writeArrayPrefix(buffer, offset, this._traceCount)
565
+ offset += this._traceBytes.buffer.copy(buffer, offset, 0, this._traceBytes.length)
202
566
 
203
- this._encodeMapPrefix(bytes, validKeys.length)
567
+ return offset
568
+ }
204
569
 
205
- for (const key of validKeys) {
206
- this._encodeString(bytes, key)
207
- this._encodeValue(bytes, value[key])
570
+ /**
571
+ * Fast path for `span.meta` / `span.metrics`. Inlines the string cache so
572
+ * each entry is one reserve (not two) and skips the polymorphic dispatch.
573
+ *
574
+ * @param {MsgpackChunk} bytes
575
+ * @param {Buffer} keyPrefix Precomputed `[key, 0xDF]`.
576
+ * @param {Record<string, unknown>} value
577
+ */
578
+ #encodeMetaEntries (bytes, keyPrefix, value) {
579
+ const keyPrefixLen = keyPrefix.length
580
+ const headerOffset = bytes.length
581
+ bytes.reserve(keyPrefixLen + 4)
582
+ bytes.buffer.set(keyPrefix, headerOffset)
583
+ const countOffset = headerOffset + keyPrefixLen
584
+
585
+ const stringMap = this._stringMap
586
+ let count = 0
587
+
588
+ for (const key of Object.keys(value)) {
589
+ const entryValue = value[key]
590
+ if (typeof entryValue !== 'string' && typeof entryValue !== 'number') continue
591
+
592
+ const keyEntry = stringMap[key] ?? this._cacheString(key)
593
+ const keyEntryLen = keyEntry.length
594
+ const writeOffset = bytes.length
595
+
596
+ if (typeof entryValue === 'string') {
597
+ if (entryValue.length > STRING_CACHE_BYPASS_LIMIT) {
598
+ // Long values (events JSON, stack traces, large query bodies) are
599
+ // unique per span; hashing them for the cache lookup costs more
600
+ // than the lookup ever recovers. Emit the key from the cache and
601
+ // stream the value directly.
602
+ bytes.reserve(keyEntryLen)
603
+ bytes.buffer.set(keyEntry, writeOffset)
604
+ bytes.write(entryValue)
605
+ count++
606
+ continue
607
+ }
608
+ const valueEntry = stringMap[entryValue] ?? this._cacheString(entryValue)
609
+ const valueEntryLen = valueEntry.length
610
+ bytes.reserve(keyEntryLen + valueEntryLen)
611
+ const target = bytes.buffer
612
+ target.set(keyEntry, writeOffset)
613
+ target.set(valueEntry, writeOffset + keyEntryLen)
614
+ } else {
615
+ // Speculate that `entryValue` is a positive fixint (0..127): one
616
+ // reserve covers both the key and the value. The metrics map (sample
617
+ // rate, priority, `_dd.measured`, attribute counts) is mostly small
618
+ // unsigned integers, so the speculation wins on every entry that
619
+ // doesn't go through the slow `writeIntOrFloat` dispatch chain.
620
+ bytes.reserve(keyEntryLen + 1)
621
+ const target = bytes.buffer
622
+ target.set(keyEntry, writeOffset)
623
+ if (entryValue === (entryValue & 0x7F)) {
624
+ target[writeOffset + keyEntryLen] = entryValue
625
+ } else {
626
+ // Speculation missed; rewind the speculative byte and route the
627
+ // value through the full encoder so it picks the right type.
628
+ bytes.length = writeOffset + keyEntryLen
629
+ bytes.writeIntOrFloat(entryValue)
630
+ }
631
+ }
632
+ count++
208
633
  }
209
- }
210
634
 
211
- _encodeValue (bytes, value) {
635
+ const target = bytes.buffer
636
+ target[countOffset] = count >>> 24
637
+ target[countOffset + 1] = count >>> 16
638
+ target[countOffset + 2] = count >>> 8
639
+ target[countOffset + 3] = count
640
+ }
641
+
642
+ /**
643
+ * Write `[keyPrefix, 8-byte uint64 id]` into `target` at `offset` and
644
+ * return the new cursor. Caller is responsible for having reserved enough
645
+ * room — this is the no-reserve variant used inside `_encode`'s combined
646
+ * fixed-fields block.
647
+ *
648
+ * @param {Uint8Array} target
649
+ * @param {number} offset
650
+ * @param {Buffer} keyPrefix Precomputed `[key, 0xCF]`.
651
+ * @param {{ toBuffer: () => Uint8Array | number[] }} identifier
652
+ * @returns {number}
653
+ */
654
+ #writeIdAt (target, offset, keyPrefix, identifier) {
655
+ target.set(keyPrefix, offset)
656
+ offset += keyPrefix.length
657
+ const idBuffer = identifier.toBuffer()
658
+ const start = idBuffer.length - 8
659
+ target[offset] = idBuffer[start]
660
+ target[offset + 1] = idBuffer[start + 1]
661
+ target[offset + 2] = idBuffer[start + 2]
662
+ target[offset + 3] = idBuffer[start + 3]
663
+ target[offset + 4] = idBuffer[start + 4]
664
+ target[offset + 5] = idBuffer[start + 5]
665
+ target[offset + 6] = idBuffer[start + 6]
666
+ target[offset + 7] = idBuffer[start + 7]
667
+ return offset + 8
668
+ }
669
+
670
+ /**
671
+ * @param {MsgpackChunk} bytes
672
+ * @param {string | number | boolean} value
673
+ */
674
+ #encodeValue (bytes, value) {
212
675
  switch (typeof value) {
213
676
  case 'string':
214
677
  this._encodeString(bytes, value)
215
678
  break
216
679
  case 'number':
217
- this._encodeFloat(bytes, value)
680
+ bytes.writeFloat(value)
218
681
  break
219
682
  case 'boolean':
220
- this._encodeBool(bytes, value)
683
+ bytes.writeBoolean(value)
221
684
  break
222
- default:
223
- // should not happen
224
685
  }
225
686
  }
226
687
 
227
- _encodeString (bytes, value = '') {
228
- this._cacheString(value)
229
-
230
- const { start, end } = this._stringMap[value]
231
-
232
- this._stringBytes.copy(bytes, start, end)
233
- }
234
-
235
- _encodeFloat (bytes, value) {
236
- this._msgpack.encodeFloat(bytes, value)
237
- }
238
-
239
- _encodeMetaStruct (bytes, value) {
240
- const keys = Array.isArray(value) ? [] : Object.keys(value)
241
- const validKeys = keys.filter(key => {
242
- const v = value[key]
243
- return typeof v === 'string' ||
244
- typeof v === 'number' ||
245
- (v !== null && typeof v === 'object')
246
- })
247
-
248
- this._encodeMapPrefix(bytes, validKeys.length)
688
+ #encodeMetaStruct (bytes, value) {
689
+ if (Array.isArray(value)) {
690
+ bytes.writeMapPrefix(0)
691
+ return
692
+ }
249
693
 
250
- for (const key of validKeys) {
251
- const v = value[key]
252
- this._encodeString(bytes, key)
253
- this._encodeObjectAsByteArray(bytes, v)
694
+ const offset = bytes.length
695
+ bytes.reserve(5)
696
+ bytes.buffer[offset] = 0xDF
697
+
698
+ let count = 0
699
+ for (const key of Object.keys(value)) {
700
+ const entryValue = value[key]
701
+ if (typeof entryValue === 'string' || typeof entryValue === 'number' ||
702
+ (entryValue !== null && typeof entryValue === 'object')) {
703
+ this._encodeString(bytes, key)
704
+ this.#encodeObjectAsByteArray(bytes, entryValue)
705
+ count++
706
+ }
254
707
  }
708
+
709
+ const target = bytes.buffer
710
+ target[offset + 1] = count >>> 24
711
+ target[offset + 2] = count >>> 16
712
+ target[offset + 3] = count >>> 8
713
+ target[offset + 4] = count
255
714
  }
256
715
 
257
- _encodeObjectAsByteArray (bytes, value) {
716
+ #encodeObjectAsByteArray (bytes, value) {
258
717
  const prefixLength = 5
259
718
  const offset = bytes.length
260
719
 
261
720
  bytes.reserve(prefixLength)
262
721
 
263
- this._encodeObject(bytes, value)
722
+ this.#encodeObject(bytes, value)
264
723
 
265
- // we should do it after encoding the object to know the real length
724
+ // The byte length isn't known until the inner object has been encoded.
266
725
  const length = bytes.length - offset - prefixLength
267
726
  bytes.buffer[offset] = 0xC6
268
727
  bytes.buffer[offset + 1] = length >> 24
@@ -271,155 +730,257 @@ class AgentEncoder {
271
730
  bytes.buffer[offset + 4] = length
272
731
  }
273
732
 
274
- _encodeObject (bytes, value, circularReferencesDetector = new Set()) {
733
+ #encodeObject (bytes, value, circularReferencesDetector = new Set()) {
275
734
  circularReferencesDetector.add(value)
276
735
  if (Array.isArray(value)) {
277
- this._encodeObjectAsArray(bytes, value, circularReferencesDetector)
736
+ this.#encodeObjectAsArray(bytes, value, circularReferencesDetector)
278
737
  } else if (value !== null && typeof value === 'object') {
279
- this._encodeObjectAsMap(bytes, value, circularReferencesDetector)
738
+ this.#encodeObjectAsMap(bytes, value, circularReferencesDetector)
280
739
  } else if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') {
281
- this._encodeValue(bytes, value)
740
+ this.#encodeValue(bytes, value)
282
741
  }
283
742
  }
284
743
 
285
- _encodeObjectAsMap (bytes, value, circularReferencesDetector) {
286
- const keys = Object.keys(value)
287
- const validKeys = keys.filter(key => {
288
- const v = value[key]
289
- return typeof v === 'string' ||
290
- typeof v === 'number' || typeof v === 'boolean' ||
291
- (v !== null && typeof v === 'object' && !circularReferencesDetector.has(v))
292
- })
293
-
294
- this._encodeMapPrefix(bytes, validKeys.length)
295
-
296
- for (const key of validKeys) {
297
- const v = value[key]
298
- this._encodeString(bytes, key)
299
- this._encodeObject(bytes, v, circularReferencesDetector)
744
+ #encodeObjectAsMap (bytes, value, circularReferencesDetector) {
745
+ const offset = bytes.length
746
+ bytes.reserve(5)
747
+ bytes.buffer[offset] = 0xDF
748
+
749
+ let count = 0
750
+ for (const key of Object.keys(value)) {
751
+ const entryValue = value[key]
752
+ if (typeof entryValue === 'string' || typeof entryValue === 'number' || typeof entryValue === 'boolean' ||
753
+ (entryValue !== null && typeof entryValue === 'object' &&
754
+ !circularReferencesDetector.has(entryValue))) {
755
+ this._encodeString(bytes, key)
756
+ this.#encodeObject(bytes, entryValue, circularReferencesDetector)
757
+ count++
758
+ }
300
759
  }
301
- }
302
-
303
- _encodeObjectAsArray (bytes, value, circularReferencesDetector) {
304
- const validValue = value.filter(item =>
305
- typeof item === 'string' ||
306
- typeof item === 'number' ||
307
- (item !== null && typeof item === 'object' && !circularReferencesDetector.has(item)))
308
-
309
- this._encodeArrayPrefix(bytes, validValue)
310
760
 
311
- for (const item of validValue) {
312
- this._encodeObject(bytes, item, circularReferencesDetector)
313
- }
761
+ const target = bytes.buffer
762
+ target[offset + 1] = count >>> 24
763
+ target[offset + 2] = count >>> 16
764
+ target[offset + 3] = count >>> 8
765
+ target[offset + 4] = count
314
766
  }
315
767
 
316
- _cacheString (value) {
317
- if (!(value in this._stringMap)) {
318
- this._stringCount++
319
- this._stringMap[value] = {
320
- start: this._stringBytes.length,
321
- end: this._stringBytes.length + this._stringBytes.write(value),
768
+ #encodeObjectAsArray (bytes, value, circularReferencesDetector) {
769
+ const offset = bytes.length
770
+ bytes.reserve(5)
771
+ bytes.buffer[offset] = 0xDD
772
+
773
+ let count = 0
774
+ for (const item of value) {
775
+ if (typeof item === 'string' || typeof item === 'number' ||
776
+ (item !== null && typeof item === 'object' && !circularReferencesDetector.has(item))) {
777
+ this.#encodeObject(bytes, item, circularReferencesDetector)
778
+ count++
322
779
  }
323
780
  }
324
- }
325
781
 
326
- _writeArrayPrefix (buffer, offset, count) {
327
- buffer[offset++] = 0xDD
328
- buffer.writeUInt32BE(count, offset)
782
+ const target = bytes.buffer
783
+ target[offset + 1] = count >>> 24
784
+ target[offset + 2] = count >>> 16
785
+ target[offset + 3] = count >>> 8
786
+ target[offset + 4] = count
787
+ }
788
+
789
+ /**
790
+ * Specialized encoder for `span.span_events`. Walks the events directly,
791
+ * emitting OTel attribute typed wrappers inline from the raw attribute
792
+ * values — no `formatSpanEvents` pre-pass and no recursive generic walk.
793
+ *
794
+ * @param {MsgpackChunk} bytes
795
+ * @param {Array<{ name: unknown, startTime: number, attributes?: object }>} spanEvents
796
+ */
797
+ #encodeSpanEvents (bytes, spanEvents) {
798
+ const offset = bytes.length
799
+ bytes.reserve(5)
800
+ bytes.buffer[offset] = 0xDD
329
801
 
330
- return offset + 4
331
- }
802
+ let arrayCount = 0
803
+ for (const event of spanEvents) {
804
+ // `addEvent` and the OTel bridge do not type-check `name`, and a
805
+ // non-string would throw downstream in `Buffer.byteLength`. Drop the
806
+ // bad event silently so the rest of the trace still encodes.
807
+ if (event === null || typeof event !== 'object' || typeof event.name !== 'string') continue
332
808
 
333
- _writeTraces (buffer, offset = 0) {
334
- offset = this._writeArrayPrefix(buffer, offset, this._traceCount)
335
- offset += this._traceBytes.buffer.copy(buffer, offset, 0, this._traceBytes.length)
809
+ const eventHeaderOffset = bytes.length
810
+ bytes.reserve(1)
811
+ bytes.buffer[eventHeaderOffset] = 0x82
336
812
 
337
- return offset
338
- }
339
- }
813
+ bytes.set(KEY_NAME)
814
+ this._encodeString(bytes, event.name)
815
+ bytes.set(KEY_EVENT_TIME)
816
+ bytes.writeFloat(eventTimeNano(event))
340
817
 
341
- const memoizedLogDebug = memoize((key, message) => {
342
- log.debug(message)
343
- // return something to store in memoize cache
344
- return true
345
- })
346
-
347
- function formatSpanEvents (span) {
348
- for (const spanEvent of span.span_events) {
349
- if (spanEvent.attributes) {
350
- let hasAttributes = false
351
- for (const [key, value] of Object.entries(spanEvent.attributes)) {
352
- const newValue = convertSpanEventAttributeValues(key, value)
353
- if (newValue === undefined) {
354
- delete spanEvent.attributes[key] // delete from attributes if undefined
355
- } else {
356
- hasAttributes = true
357
- spanEvent.attributes[key] = newValue
358
- }
359
- }
360
- if (!hasAttributes) {
361
- delete spanEvent.attributes
818
+ const attributes = event.attributes
819
+ if (attributes !== null && typeof attributes === 'object') {
820
+ this.#encodeAttributesIfAny(bytes, attributes, eventHeaderOffset)
362
821
  }
822
+ arrayCount++
363
823
  }
364
- }
365
- }
366
824
 
367
- function convertSpanEventAttributeValues (key, value, depth = 0) {
368
- if (typeof value === 'string') {
369
- return {
370
- type: 0,
371
- string_value: value,
825
+ const target = bytes.buffer
826
+ target[offset + 1] = arrayCount >>> 24
827
+ target[offset + 2] = arrayCount >>> 16
828
+ target[offset + 3] = arrayCount >>> 8
829
+ target[offset + 4] = arrayCount
830
+ }
831
+
832
+ /**
833
+ * Optimistically emits the `'attributes'` slot for an event. If every entry
834
+ * filters out, the partial output is rewound and the event's map header
835
+ * stays at 2 entries.
836
+ *
837
+ * @param {MsgpackChunk} bytes
838
+ * @param {Record<string, unknown>} attributes
839
+ * @param {number} eventHeaderOffset
840
+ */
841
+ #encodeAttributesIfAny (bytes, attributes, eventHeaderOffset) {
842
+ const sectionStart = bytes.length
843
+
844
+ bytes.set(KEY_EVENT_ATTRIBUTES)
845
+ const countOffset = bytes.length
846
+ bytes.reserve(5)
847
+ bytes.buffer[countOffset] = 0xDF
848
+
849
+ let count = 0
850
+ for (const key of Object.keys(attributes)) {
851
+ if (this.#emitAttribute(bytes, key, attributes[key])) count++
372
852
  }
373
- }
374
853
 
375
- if (typeof value === 'boolean') {
376
- return {
377
- type: 1,
378
- bool_value: value,
854
+ if (count === 0) {
855
+ bytes.length = sectionStart
856
+ return
379
857
  }
380
- }
381
858
 
382
- if (typeof value === 'number') {
383
- if (Number.isInteger(value)) {
384
- return {
385
- type: 2,
386
- int_value: value,
387
- }
859
+ const target = bytes.buffer
860
+ target[countOffset + 1] = count >>> 24
861
+ target[countOffset + 2] = count >>> 16
862
+ target[countOffset + 3] = count >>> 8
863
+ target[countOffset + 4] = count
864
+ bytes.buffer[eventHeaderOffset] = 0x83
865
+ }
866
+
867
+ /**
868
+ * Emit `<key, typed_wrapper>` for a single attribute. Returns true on a
869
+ * supported type, false (with a memoized debug log) otherwise.
870
+ *
871
+ * @param {MsgpackChunk} bytes
872
+ * @param {string} key
873
+ * @param {unknown} value
874
+ * @returns {boolean}
875
+ */
876
+ #emitAttribute (bytes, key, value) {
877
+ if (typeof value === 'string') {
878
+ this._encodeString(bytes, key)
879
+ bytes.set(ATTR_PREFIX_STRING)
880
+ this._encodeString(bytes, value)
881
+ return true
388
882
  }
389
- return {
390
- type: 3,
391
- double_value: value,
883
+ if (typeof value === 'number') {
884
+ this._encodeString(bytes, key)
885
+ bytes.set(Number.isInteger(value) ? ATTR_PREFIX_INT : ATTR_PREFIX_DOUBLE)
886
+ bytes.writeIntOrFloat(value)
887
+ return true
888
+ }
889
+ if (typeof value === 'boolean') {
890
+ this._encodeString(bytes, key)
891
+ bytes.set(value ? ATTR_PAYLOAD_BOOL_TRUE : ATTR_PAYLOAD_BOOL_FALSE)
892
+ return true
893
+ }
894
+ if (Array.isArray(value)) {
895
+ return this.#emitArrayAttribute(bytes, key, value)
896
+ }
897
+ memoizedLogDebug(
898
+ key,
899
+ 'Encountered unsupported data type for span event v0.4 encoding, key: ' +
900
+ '%s: with value: %s. Skipping encoding of pair.',
901
+ value
902
+ )
903
+ return false
904
+ }
905
+
906
+ /**
907
+ * Emit `<key, { type: 4, array_value: { values: [...] } }>` from a raw
908
+ * array of primitives. Filters nested arrays / unsupported items; if no
909
+ * items remain the whole entry is rewound.
910
+ *
911
+ * @param {MsgpackChunk} bytes
912
+ * @param {string} key
913
+ * @param {Array<unknown>} array
914
+ * @returns {boolean}
915
+ */
916
+ #emitArrayAttribute (bytes, key, array) {
917
+ const sectionStart = bytes.length
918
+
919
+ this._encodeString(bytes, key)
920
+ bytes.set(ATTR_PREFIX_ARRAY)
921
+ const arrayCountOffset = bytes.length
922
+ bytes.reserve(4)
923
+
924
+ let count = 0
925
+ for (const item of array) {
926
+ if (this.#emitArrayItem(bytes, key, item)) count++
392
927
  }
393
- }
394
928
 
395
- if (Array.isArray(value)) {
396
- if (depth === 0) {
397
- const convertedArray = []
398
- for (const val of value) {
399
- const convertedVal = convertSpanEventAttributeValues(key, val, 1)
400
- if (convertedVal !== undefined) {
401
- convertedArray.push(convertedVal)
402
- }
403
- }
929
+ if (count === 0) {
930
+ bytes.length = sectionStart
931
+ return false
932
+ }
404
933
 
405
- // Only include array_value if there are valid elements
406
- if (convertedArray.length > 0) {
407
- return {
408
- type: 4,
409
- array_value: { values: convertedArray },
410
- }
411
- }
412
- // If all elements were unsupported, return undefined
413
- } else {
414
- memoizedLogDebug(key, 'Encountered nested array data type for span event v0.4 encoding. ' +
415
- `Skipping encoding key: ${key}: with value: ${typeof value}.`
934
+ const target = bytes.buffer
935
+ target[arrayCountOffset] = count >>> 24
936
+ target[arrayCountOffset + 1] = count >>> 16
937
+ target[arrayCountOffset + 2] = count >>> 8
938
+ target[arrayCountOffset + 3] = count
939
+ return true
940
+ }
941
+
942
+ /**
943
+ * Emit a single typed wrapper inside an `array_value.values` array. No
944
+ * recursion: nested arrays are dropped with a memoized debug log.
945
+ *
946
+ * @param {MsgpackChunk} bytes
947
+ * @param {string} key
948
+ * @param {unknown} value
949
+ * @returns {boolean}
950
+ */
951
+ #emitArrayItem (bytes, key, value) {
952
+ if (typeof value === 'string') {
953
+ bytes.set(ATTR_PREFIX_STRING)
954
+ this._encodeString(bytes, value)
955
+ return true
956
+ }
957
+ if (typeof value === 'number') {
958
+ bytes.set(Number.isInteger(value) ? ATTR_PREFIX_INT : ATTR_PREFIX_DOUBLE)
959
+ bytes.writeIntOrFloat(value)
960
+ return true
961
+ }
962
+ if (typeof value === 'boolean') {
963
+ bytes.set(value ? ATTR_PAYLOAD_BOOL_TRUE : ATTR_PAYLOAD_BOOL_FALSE)
964
+ return true
965
+ }
966
+ if (Array.isArray(value)) {
967
+ memoizedLogDebug(
968
+ key,
969
+ 'Encountered nested array data type for span event v0.4 encoding. ' +
970
+ 'Skipping encoding key: %s: with value: %s.',
971
+ value
416
972
  )
417
973
  }
418
- } else {
419
- memoizedLogDebug(key, 'Encountered unsupported data type for span event v0.4 encoding, key: ' +
420
- `${key}: with value: ${typeof value}. Skipping encoding of pair.`
421
- )
974
+ return false
975
+ }
976
+ }
977
+
978
+ const seenKeys = new Set()
979
+ function memoizedLogDebug (key, message, value) {
980
+ if (!seenKeys.has(key)) {
981
+ seenKeys.add(key)
982
+ log.debug(message, key, typeof value)
422
983
  }
423
984
  }
424
985
 
425
- module.exports = { AgentEncoder }
986
+ module.exports = { AgentEncoder, stringifySpanEvents }