dd-trace 6.16.0 → 6.17.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 (334) hide show
  1. package/ci/diagnose.js +0 -23
  2. package/ci/test-optimization-validation/approval-artifacts.js +0 -3
  3. package/ci/test-optimization-validation/approval.js +0 -6
  4. package/ci/test-optimization-validation/artifact-id.js +0 -1
  5. package/ci/test-optimization-validation/bounded-json.js +0 -1
  6. package/ci/test-optimization-validation/cli.js +0 -12
  7. package/ci/test-optimization-validation/command-output-policy.js +0 -1
  8. package/ci/test-optimization-validation/command-runner.js +0 -3
  9. package/ci/test-optimization-validation/environment.js +0 -4
  10. package/ci/test-optimization-validation/executable-approval.js +0 -1
  11. package/ci/test-optimization-validation/executable.js +0 -5
  12. package/ci/test-optimization-validation/framework-adapters/cucumber.js +0 -6
  13. package/ci/test-optimization-validation/framework-adapters/cypress.js +0 -3
  14. package/ci/test-optimization-validation/framework-adapters/playwright.js +0 -6
  15. package/ci/test-optimization-validation/framework-adapters/vitest.js +0 -4
  16. package/ci/test-optimization-validation/generated-test-contract.js +0 -5
  17. package/ci/test-optimization-validation/generated-verifier.js +0 -1
  18. package/ci/test-optimization-validation/literal-environment.js +0 -1
  19. package/ci/test-optimization-validation/manifest-scaffold.js +0 -17
  20. package/ci/test-optimization-validation/manifest-schema.js +0 -21
  21. package/ci/test-optimization-validation/offline-fixtures.js +0 -4
  22. package/ci/test-optimization-validation/plan-writer.js +0 -11
  23. package/ci/test-optimization-validation/preflight-runner.js +0 -1
  24. package/ci/test-optimization-validation/redaction.js +0 -4
  25. package/ci/test-optimization-validation/report-writer.js +0 -16
  26. package/ci/test-optimization-validation/runner-command.js +0 -3
  27. package/ci/test-optimization-validation/runner-contract.js +0 -4
  28. package/ci/test-optimization-validation/safe-files.js +0 -1
  29. package/ci/test-optimization-validation/scenarios/basic-reporting.js +0 -1
  30. package/ci/test-optimization-validation/scenarios/ci-wiring.js +0 -1
  31. package/ci/test-optimization-validation/source-text.js +0 -3
  32. package/ci/vitest-no-worker-init-setup.mjs +41 -16
  33. package/index.d.ts +165 -0
  34. package/package.json +17 -16
  35. package/packages/datadog-esbuild/src/utils.js +0 -2
  36. package/packages/datadog-instrumentations/src/aerospike.js +28 -6
  37. package/packages/datadog-instrumentations/src/aws-durable-execution-sdk-js.js +0 -2
  38. package/packages/datadog-instrumentations/src/aws-sdk.js +0 -2
  39. package/packages/datadog-instrumentations/src/claude-agent-sdk.js +0 -2
  40. package/packages/datadog-instrumentations/src/console.js +97 -0
  41. package/packages/datadog-instrumentations/src/cucumber.js +72 -12
  42. package/packages/datadog-instrumentations/src/cypress-config.js +0 -23
  43. package/packages/datadog-instrumentations/src/helpers/channel.js +0 -2
  44. package/packages/datadog-instrumentations/src/helpers/graphql-jit-runtime.js +0 -5
  45. package/packages/datadog-instrumentations/src/helpers/hooks.js +8 -0
  46. package/packages/datadog-instrumentations/src/helpers/instrumentation-utils.js +0 -3
  47. package/packages/datadog-instrumentations/src/helpers/pool-acquire.js +0 -6
  48. package/packages/datadog-instrumentations/src/helpers/register.js +4 -0
  49. package/packages/datadog-instrumentations/src/helpers/rewriter/index.js +72 -24
  50. package/packages/datadog-instrumentations/src/helpers/rewriter/instrumentation-registry.js +39 -0
  51. package/packages/datadog-instrumentations/src/helpers/rewriter/instrumentations/index.js +3 -17
  52. package/packages/datadog-instrumentations/src/helpers/rewriter/instrumentations/playwright.js +12 -0
  53. package/packages/datadog-instrumentations/src/helpers/rewriter/instrumentations/postgres.js +36 -0
  54. package/packages/datadog-instrumentations/src/helpers/rewriter/instrumentations/supabase.js +128 -0
  55. package/packages/datadog-instrumentations/src/helpers/rewriter/targets.json +16 -0
  56. package/packages/datadog-instrumentations/src/helpers/rewriter/transforms/postgres.js +388 -0
  57. package/packages/datadog-instrumentations/src/helpers/rewriter/transforms.js +0 -5
  58. package/packages/datadog-instrumentations/src/helpers/router-helper.js +0 -1
  59. package/packages/datadog-instrumentations/src/jest.js +141 -51
  60. package/packages/datadog-instrumentations/src/knex.js +0 -1
  61. package/packages/datadog-instrumentations/src/mariadb-bundle.js +0 -24
  62. package/packages/datadog-instrumentations/src/mariadb.js +0 -2
  63. package/packages/datadog-instrumentations/src/mocha/common.js +0 -1
  64. package/packages/datadog-instrumentations/src/mocha/main.js +22 -25
  65. package/packages/datadog-instrumentations/src/mocha/utils.js +119 -49
  66. package/packages/datadog-instrumentations/src/mocha/webdriverio-protocol.js +0 -6
  67. package/packages/datadog-instrumentations/src/mocha/worker.js +14 -17
  68. package/packages/datadog-instrumentations/src/mysql2.js +0 -2
  69. package/packages/datadog-instrumentations/src/openai-realtime/audio-accumulator.js +241 -0
  70. package/packages/datadog-instrumentations/src/openai-realtime/events.js +76 -0
  71. package/packages/datadog-instrumentations/src/openai-realtime/index.js +301 -0
  72. package/packages/datadog-instrumentations/src/openai-realtime/session.js +998 -0
  73. package/packages/datadog-instrumentations/src/openai-realtime/turns.js +211 -0
  74. package/packages/datadog-instrumentations/src/openai.js +51 -12
  75. package/packages/datadog-instrumentations/src/oracledb.js +9 -3
  76. package/packages/datadog-instrumentations/src/playwright-reporter.js +3 -16
  77. package/packages/datadog-instrumentations/src/playwright.js +238 -55
  78. package/packages/datadog-instrumentations/src/postgres.js +7 -0
  79. package/packages/datadog-instrumentations/src/router.js +0 -2
  80. package/packages/datadog-instrumentations/src/rum-browser-scripts.js +0 -2
  81. package/packages/datadog-instrumentations/src/sequelize.js +0 -1
  82. package/packages/datadog-instrumentations/src/supabase.js +15 -0
  83. package/packages/datadog-instrumentations/src/vitest-main-no-worker-init.js +18 -18
  84. package/packages/datadog-instrumentations/src/vitest-main.js +37 -17
  85. package/packages/datadog-instrumentations/src/vitest-util.js +7 -1
  86. package/packages/datadog-instrumentations/src/vitest-worker.js +49 -13
  87. package/packages/datadog-instrumentations/src/webdriverio.js +23 -42
  88. package/packages/datadog-instrumentations/src/ws.js +0 -1
  89. package/packages/datadog-plugin-ai/src/utils.js +0 -2
  90. package/packages/datadog-plugin-aws-durable-execution-sdk-js/src/trace-checkpoint.js +0 -1
  91. package/packages/datadog-plugin-aws-durable-execution-sdk-js/src/util.js +0 -2
  92. package/packages/datadog-plugin-aws-sdk/src/base.js +0 -1
  93. package/packages/datadog-plugin-aws-sdk/src/services/bedrockruntime/utils.js +0 -1
  94. package/packages/datadog-plugin-aws-sdk/src/services/eventbridge.js +0 -1
  95. package/packages/datadog-plugin-aws-sdk/src/util.js +0 -1
  96. package/packages/datadog-plugin-azure-durable-functions/src/index.js +0 -1
  97. package/packages/datadog-plugin-cucumber/src/index.js +10 -0
  98. package/packages/datadog-plugin-cypress/src/cypress-plugin.js +171 -75
  99. package/packages/datadog-plugin-cypress/src/finalization.js +0 -3
  100. package/packages/datadog-plugin-cypress/src/source-map-utils.js +0 -4
  101. package/packages/datadog-plugin-cypress/src/support.js +52 -7
  102. package/packages/datadog-plugin-graphql/src/resolve-error.js +1 -2
  103. package/packages/datadog-plugin-graphql/src/utils.js +0 -5
  104. package/packages/datadog-plugin-jest/src/index.js +13 -0
  105. package/packages/datadog-plugin-kafkajs/src/producer.js +0 -1
  106. package/packages/datadog-plugin-mocha/src/index.js +39 -11
  107. package/packages/datadog-plugin-mongodb-core/src/query.js +0 -1
  108. package/packages/datadog-plugin-openai/src/index.js +16 -1
  109. package/packages/datadog-plugin-openai/src/realtime.js +144 -0
  110. package/packages/datadog-plugin-openai-agents/src/integration.js +0 -4
  111. package/packages/datadog-plugin-openai-agents/src/util.js +0 -1
  112. package/packages/datadog-plugin-playwright/src/index.js +76 -9
  113. package/packages/datadog-plugin-postgres/src/index.js +167 -0
  114. package/packages/datadog-plugin-prisma/src/datadog-tracing-helper.js +0 -1
  115. package/packages/datadog-plugin-redis/src/index.js +15 -1
  116. package/packages/datadog-plugin-supabase/src/error.js +18 -0
  117. package/packages/datadog-plugin-supabase/src/index.js +21 -0
  118. package/packages/datadog-plugin-supabase/src/supabase-auth-js-gotrueclient-getuser.js +69 -0
  119. package/packages/datadog-plugin-supabase/src/supabase-functions-js-functionsclient-invoke.js +70 -0
  120. package/packages/datadog-plugin-supabase/src/supabase-postgrest-js-postgrestbuilder-then.js +122 -0
  121. package/packages/datadog-plugin-supabase/src/supabase-realtime-js-realtimechannel-send.js +66 -0
  122. package/packages/datadog-plugin-supabase/src/supabase-storage-js-handle-request.js +93 -0
  123. package/packages/datadog-plugin-supabase/src/url.js +17 -0
  124. package/packages/datadog-plugin-vitest/src/index.js +10 -0
  125. package/packages/datadog-plugin-ws/src/util.js +0 -4
  126. package/packages/datadog-turbopack/index.js +0 -6
  127. package/packages/datadog-turbopack/src/loader.js +0 -16
  128. package/packages/datadog-webpack/src/loader.js +0 -1
  129. package/packages/dd-trace/src/aiguard/client.js +2 -3
  130. package/packages/dd-trace/src/aiguard/evaluation.js +6 -12
  131. package/packages/dd-trace/src/aiguard/index.js +2 -2
  132. package/packages/dd-trace/src/aiguard/integrations/index.js +1 -1
  133. package/packages/dd-trace/src/aiguard/integrations/openai.js +81 -7
  134. package/packages/dd-trace/src/aiguard/messages/anthropic.js +0 -2
  135. package/packages/dd-trace/src/aiguard/messages/openai.js +64 -1
  136. package/packages/dd-trace/src/aiguard/messages/utils.js +0 -1
  137. package/packages/dd-trace/src/aiguard/redaction.js +0 -1
  138. package/packages/dd-trace/src/aiguard/sdk.js +1 -1
  139. package/packages/dd-trace/src/appsec/activation.js +1 -1
  140. package/packages/dd-trace/src/appsec/api_security/normalized-route.js +0 -5
  141. package/packages/dd-trace/src/appsec/api_security/sampler.js +0 -4
  142. package/packages/dd-trace/src/appsec/blocking/index.js +3 -3
  143. package/packages/dd-trace/src/appsec/downstream_requests.js +1 -4
  144. package/packages/dd-trace/src/appsec/iast/index.js +1 -1
  145. package/packages/dd-trace/src/appsec/iast/overhead-controller.js +5 -5
  146. package/packages/dd-trace/src/appsec/iast/taint-tracking/index.js +1 -1
  147. package/packages/dd-trace/src/appsec/iast/taint-tracking/plugin.js +1 -1
  148. package/packages/dd-trace/src/appsec/iast/taint-tracking/rewriter.js +3 -3
  149. package/packages/dd-trace/src/appsec/iast/vulnerabilities-formatter/evidence-redaction/sensitive-analyzers/sql-sensitive-analyzer.js +8 -10
  150. package/packages/dd-trace/src/appsec/iast/vulnerabilities-formatter/evidence-redaction/sensitive-handler.js +2 -2
  151. package/packages/dd-trace/src/appsec/iast/vulnerabilities-formatter/utils.js +4 -1
  152. package/packages/dd-trace/src/appsec/iast/vulnerability-reporter.js +7 -7
  153. package/packages/dd-trace/src/appsec/index.js +2 -2
  154. package/packages/dd-trace/src/appsec/lambda.js +71 -2
  155. package/packages/dd-trace/src/appsec/rasp/utils.js +5 -1
  156. package/packages/dd-trace/src/appsec/remote_config.js +8 -6
  157. package/packages/dd-trace/src/appsec/reporter.js +10 -6
  158. package/packages/dd-trace/src/appsec/rule_manager.js +3 -3
  159. package/packages/dd-trace/src/appsec/sdk/track_event.js +0 -2
  160. package/packages/dd-trace/src/appsec/waf/index.js +2 -2
  161. package/packages/dd-trace/src/appsec/waf/waf_manager.js +8 -5
  162. package/packages/dd-trace/src/carrier.js +0 -5
  163. package/packages/dd-trace/src/ci-visibility/dynamic-atr-retries.js +104 -0
  164. package/packages/dd-trace/src/ci-visibility/dynamic-instrumentation/worker/index.js +0 -2
  165. package/packages/dd-trace/src/ci-visibility/efd-retry-policy.js +34 -3
  166. package/packages/dd-trace/src/ci-visibility/exporters/agentless/coverage-writer.js +0 -1
  167. package/packages/dd-trace/src/ci-visibility/exporters/agentless/di-logs-writer.js +0 -1
  168. package/packages/dd-trace/src/ci-visibility/exporters/agentless/writer.js +0 -1
  169. package/packages/dd-trace/src/ci-visibility/exporters/ci-validation/index.js +0 -4
  170. package/packages/dd-trace/src/ci-visibility/exporters/ci-validation/msgpack-to-json.js +0 -1
  171. package/packages/dd-trace/src/ci-visibility/exporters/ci-validation/sink.js +0 -2
  172. package/packages/dd-trace/src/ci-visibility/exporters/ci-visibility-exporter.js +37 -15
  173. package/packages/dd-trace/src/ci-visibility/exporters/git/git_metadata.js +0 -3
  174. package/packages/dd-trace/src/ci-visibility/exporters/request.js +0 -11
  175. package/packages/dd-trace/src/ci-visibility/exporters/settings-cache-key.js +0 -1
  176. package/packages/dd-trace/src/ci-visibility/intelligent-test-runner/get-skippable-suites.js +0 -1
  177. package/packages/dd-trace/src/ci-visibility/requests/fs-cache.js +0 -6
  178. package/packages/dd-trace/src/ci-visibility/requests/get-library-configuration.js +2 -2
  179. package/packages/dd-trace/src/ci-visibility/requests/rate-limit.js +0 -1
  180. package/packages/dd-trace/src/ci-visibility/requests/upload-test-screenshot.js +0 -5
  181. package/packages/dd-trace/src/ci-visibility/requests/video-request.js +0 -1
  182. package/packages/dd-trace/src/ci-visibility/telemetry.js +13 -0
  183. package/packages/dd-trace/src/ci-visibility/test-optimization-cache.js +0 -1
  184. package/packages/dd-trace/src/ci-visibility/test-screenshot.js +0 -2
  185. package/packages/dd-trace/src/ci-visibility/test-video.js +0 -1
  186. package/packages/dd-trace/src/config/defaults.js +3 -2
  187. package/packages/dd-trace/src/config/generated-config-types.d.ts +73 -67
  188. package/packages/dd-trace/src/config/helper.js +0 -1
  189. package/packages/dd-trace/src/config/index.js +24 -24
  190. package/packages/dd-trace/src/config/parsers.js +34 -6
  191. package/packages/dd-trace/src/config/remote_config.js +25 -109
  192. package/packages/dd-trace/src/config/supported-configurations.json +139 -10
  193. package/packages/dd-trace/src/datastreams/encoding.js +0 -1
  194. package/packages/dd-trace/src/datastreams/pathway.js +0 -1
  195. package/packages/dd-trace/src/debugger/constants.js +10 -0
  196. package/packages/dd-trace/src/debugger/devtools_client/breakpoints.js +62 -10
  197. package/packages/dd-trace/src/debugger/devtools_client/config.js +2 -0
  198. package/packages/dd-trace/src/debugger/devtools_client/guardrail-metrics.js +15 -0
  199. package/packages/dd-trace/src/debugger/devtools_client/index.js +103 -27
  200. package/packages/dd-trace/src/debugger/devtools_client/json-buffer.js +50 -7
  201. package/packages/dd-trace/src/debugger/devtools_client/log.js +3 -1
  202. package/packages/dd-trace/src/debugger/devtools_client/probe_sampler.js +21 -8
  203. package/packages/dd-trace/src/debugger/devtools_client/send.js +40 -14
  204. package/packages/dd-trace/src/debugger/devtools_client/snapshot/index.js +53 -13
  205. package/packages/dd-trace/src/debugger/devtools_client/snapshot/processor.js +118 -71
  206. package/packages/dd-trace/src/debugger/devtools_client/snapshot-pruner.js +0 -3
  207. package/packages/dd-trace/src/debugger/devtools_client/status.js +20 -6
  208. package/packages/dd-trace/src/debugger/guardrail-metrics.js +167 -0
  209. package/packages/dd-trace/src/debugger/index.js +50 -2
  210. package/packages/dd-trace/src/debugger/inspect-segment.js +0 -3
  211. package/packages/dd-trace/src/debugger/probe_sampler.js +133 -9
  212. package/packages/dd-trace/src/debugger/probe_sampler_constants.js +31 -1
  213. package/packages/dd-trace/src/dogstatsd.js +0 -23
  214. package/packages/dd-trace/src/encode/0.4-cross-payload.js +0 -3
  215. package/packages/dd-trace/src/encode/0.4.js +0 -7
  216. package/packages/dd-trace/src/encode/0.5.js +0 -2
  217. package/packages/dd-trace/src/encode/tags-processors.js +0 -1
  218. package/packages/dd-trace/src/evp_proxy/discovery.js +0 -1
  219. package/packages/dd-trace/src/evp_proxy/path.js +0 -2
  220. package/packages/dd-trace/src/exporters/agent/writer.js +0 -1
  221. package/packages/dd-trace/src/exporters/agentless/index.js +0 -1
  222. package/packages/dd-trace/src/exporters/agentless/intake.js +0 -1
  223. package/packages/dd-trace/src/exporters/agentless/writer.js +0 -3
  224. package/packages/dd-trace/src/exporters/common/final-flush-request-tracker.js +0 -6
  225. package/packages/dd-trace/src/exporters/common/request.js +1 -0
  226. package/packages/dd-trace/src/exporters/common/url.js +0 -2
  227. package/packages/dd-trace/src/exporters/common/writer.js +0 -2
  228. package/packages/dd-trace/src/id.js +0 -11
  229. package/packages/dd-trace/src/llmobs/audio-codec.js +192 -0
  230. package/packages/dd-trace/src/llmobs/audio-utils.js +121 -0
  231. package/packages/dd-trace/src/llmobs/constants/audio.js +35 -0
  232. package/packages/dd-trace/src/llmobs/constants/prompts.js +14 -0
  233. package/packages/dd-trace/src/llmobs/constants/tags.js +17 -0
  234. package/packages/dd-trace/src/llmobs/eval-metric.js +0 -6
  235. package/packages/dd-trace/src/llmobs/experiments/dataset.js +0 -4
  236. package/packages/dd-trace/src/llmobs/experiments/experiment.js +0 -3
  237. package/packages/dd-trace/src/llmobs/experiments/index.js +7 -6
  238. package/packages/dd-trace/src/llmobs/experiments/util.js +1 -11
  239. package/packages/dd-trace/src/llmobs/index.js +1 -3
  240. package/packages/dd-trace/src/llmobs/noop.js +10 -0
  241. package/packages/dd-trace/src/llmobs/plugins/ai/util.js +0 -4
  242. package/packages/dd-trace/src/llmobs/plugins/anthropic/util.js +0 -1
  243. package/packages/dd-trace/src/llmobs/plugins/genai/util.js +0 -4
  244. package/packages/dd-trace/src/llmobs/plugins/modelcontextprotocol-sdk/utils.js +0 -2
  245. package/packages/dd-trace/src/llmobs/plugins/openai/constants.js +0 -2
  246. package/packages/dd-trace/src/llmobs/plugins/openai/index.js +4 -6
  247. package/packages/dd-trace/src/llmobs/plugins/openai/realtime.js +285 -0
  248. package/packages/dd-trace/src/llmobs/plugins/openai/utils.js +16 -3
  249. package/packages/dd-trace/src/llmobs/prompts/cache.js +272 -0
  250. package/packages/dd-trace/src/llmobs/prompts/manager.js +639 -0
  251. package/packages/dd-trace/src/llmobs/prompts/noop.js +29 -0
  252. package/packages/dd-trace/src/llmobs/prompts/prompt.js +92 -0
  253. package/packages/dd-trace/src/llmobs/sdk.js +21 -6
  254. package/packages/dd-trace/src/llmobs/span_processor.js +81 -2
  255. package/packages/dd-trace/src/llmobs/tagger.js +30 -7
  256. package/packages/dd-trace/src/llmobs/telemetry.js +36 -4
  257. package/packages/dd-trace/src/llmobs/util.js +0 -34
  258. package/packages/dd-trace/src/llmobs/writers/base.js +0 -1
  259. package/packages/dd-trace/src/llmobs/writers/util.js +1 -2
  260. package/packages/dd-trace/src/log/channels.js +3 -0
  261. package/packages/dd-trace/src/log/index.js +23 -5
  262. package/packages/dd-trace/src/log-submission/log-submission-plugin.js +74 -6
  263. package/packages/dd-trace/src/msgpack/chunk.js +0 -1
  264. package/packages/dd-trace/src/openfeature/agentless_configuration_source.js +0 -12
  265. package/packages/dd-trace/src/openfeature/encoding.js +0 -2
  266. package/packages/dd-trace/src/openfeature/eval-metrics-hook.js +0 -1
  267. package/packages/dd-trace/src/openfeature/index.js +0 -4
  268. package/packages/dd-trace/src/openfeature/span-enrichment-hook.js +0 -1
  269. package/packages/dd-trace/src/openfeature/span-enrichment.js +0 -4
  270. package/packages/dd-trace/src/openfeature/writers/base.js +0 -6
  271. package/packages/dd-trace/src/openfeature/writers/exposures.js +0 -5
  272. package/packages/dd-trace/src/openfeature/writers/util.js +0 -4
  273. package/packages/dd-trace/src/opentelemetry/logs/logger.js +0 -1
  274. package/packages/dd-trace/src/opentelemetry/logs/logger_provider.js +0 -1
  275. package/packages/dd-trace/src/opentelemetry/logs/otlp_http_log_exporter.js +0 -1
  276. package/packages/dd-trace/src/opentelemetry/logs/otlp_transformer.js +0 -2
  277. package/packages/dd-trace/src/opentelemetry/metrics/meter_provider.js +0 -1
  278. package/packages/dd-trace/src/opentelemetry/metrics/otlp_span_stats_transformer.js +0 -1
  279. package/packages/dd-trace/src/opentelemetry/metrics/otlp_transformer.js +0 -1
  280. package/packages/dd-trace/src/opentelemetry/metrics/periodic_metric_reader.js +1 -14
  281. package/packages/dd-trace/src/opentelemetry/metrics/time.js +0 -1
  282. package/packages/dd-trace/src/opentelemetry/otlp/otlp_http_exporter_base.js +30 -13
  283. package/packages/dd-trace/src/opentelemetry/otlp/otlp_transformer_base.js +0 -1
  284. package/packages/dd-trace/src/opentelemetry/span-helpers.js +0 -1
  285. package/packages/dd-trace/src/opentelemetry/trace/otlp_http_trace_exporter.js +0 -1
  286. package/packages/dd-trace/src/opentelemetry/trace/otlp_transformer.js +0 -3
  287. package/packages/dd-trace/src/opentracing/propagation/text_map.js +0 -6
  288. package/packages/dd-trace/src/opentracing/span_context.js +0 -1
  289. package/packages/dd-trace/src/otel-thread-ctx.js +38 -11
  290. package/packages/dd-trace/src/payload-tagging/tagging.js +15 -3
  291. package/packages/dd-trace/src/plugins/ci_plugin.js +0 -1
  292. package/packages/dd-trace/src/plugins/database.js +2 -6
  293. package/packages/dd-trace/src/plugins/index.js +7 -0
  294. package/packages/dd-trace/src/plugins/plugin.js +0 -4
  295. package/packages/dd-trace/src/plugins/tracing.js +1 -1
  296. package/packages/dd-trace/src/plugins/util/git.js +1 -3
  297. package/packages/dd-trace/src/plugins/util/http-otel-semantics.js +0 -1
  298. package/packages/dd-trace/src/plugins/util/llm.js +0 -2
  299. package/packages/dd-trace/src/plugins/util/status-validator.js +0 -1
  300. package/packages/dd-trace/src/plugins/util/test.js +21 -20
  301. package/packages/dd-trace/src/plugins/util/url.js +0 -5
  302. package/packages/dd-trace/src/priority_sampler.js +0 -6
  303. package/packages/dd-trace/src/process-tags/index.js +0 -1
  304. package/packages/dd-trace/src/profiler.js +132 -35
  305. package/packages/dd-trace/src/profiling/exporters/event_serializer.js +0 -1
  306. package/packages/dd-trace/src/profiling/profiler.js +101 -41
  307. package/packages/dd-trace/src/profiling/ssi-heuristics.js +29 -15
  308. package/packages/dd-trace/src/propagation-hash/index.js +0 -1
  309. package/packages/dd-trace/src/proxy.js +21 -45
  310. package/packages/dd-trace/src/random_sampler.js +0 -4
  311. package/packages/dd-trace/src/rate_limiter.js +0 -4
  312. package/packages/dd-trace/src/remote_config/capabilities.js +1 -9
  313. package/packages/dd-trace/src/remote_config/index.js +0 -1
  314. package/packages/dd-trace/src/runtime_metrics/otlp_runtime_metrics.js +0 -3
  315. package/packages/dd-trace/src/sampler.js +0 -4
  316. package/packages/dd-trace/src/sampling_rule.js +0 -7
  317. package/packages/dd-trace/src/serverless/vercel.js +0 -1
  318. package/packages/dd-trace/src/serverless.js +0 -1
  319. package/packages/dd-trace/src/service-naming/index.js +0 -1
  320. package/packages/dd-trace/src/service-naming/schemas/util.js +0 -1
  321. package/packages/dd-trace/src/service-naming/schemas/v0/storage.js +7 -0
  322. package/packages/dd-trace/src/service-naming/schemas/v1/storage.js +5 -0
  323. package/packages/dd-trace/src/span_processor.js +2 -2
  324. package/packages/dd-trace/src/span_sampler.js +0 -1
  325. package/packages/dd-trace/src/standalone/product.js +2 -2
  326. package/packages/dd-trace/src/standalone/tracesource.js +0 -1
  327. package/packages/dd-trace/src/startup-log.js +1 -1
  328. package/packages/dd-trace/src/telemetry/endpoints.js +0 -8
  329. package/packages/dd-trace/src/telemetry/logs/index.js +16 -5
  330. package/packages/dd-trace/src/telemetry/logs/log-collector.js +16 -6
  331. package/packages/dd-trace/src/telemetry/metrics.js +0 -2
  332. package/packages/dd-trace/src/telemetry/telemetry.js +4 -1
  333. package/packages/dd-trace/src/util.js +13 -1
  334. package/vendor/dist/@datadog/openfeature-node-server/index.js +1 -1
@@ -207,7 +207,6 @@ class DogStatsDClient {
207
207
  /**
208
208
  * @param {boolean|(() => void)} [forceTelemetry] - Whether to ignore the telemetry interval, or completion callback
209
209
  * @param {() => void} [done] - Called after serverless deliveries complete
210
- * @returns {void}
211
210
  */
212
211
  flush (forceTelemetry = false, done) {
213
212
  if (typeof forceTelemetry === 'function') {
@@ -238,7 +237,6 @@ class DogStatsDClient {
238
237
  /**
239
238
  * @param {boolean} force - Whether to ignore the telemetry interval
240
239
  * @param {((send: (done?: () => void) => void) => void)} [track] - Tracks a non-serverless delivery
241
- * @returns {void}
242
240
  */
243
241
  #flushTelemetry (force, track) {
244
242
  const telemetry = this.telemetry
@@ -291,7 +289,6 @@ class DogStatsDClient {
291
289
  * @param {DogStatsDBufferState} state - Payload state to flush
292
290
  * @param {boolean} recordTelemetry - Whether to record the transport outcome
293
291
  * @param {((send: (done?: () => void) => void) => void)} [track] - Tracks a non-serverless delivery
294
- * @returns {void}
295
292
  */
296
293
  #flush (state, recordTelemetry, track) {
297
294
  const queue = this._enqueue(state)
@@ -314,7 +311,6 @@ class DogStatsDClient {
314
311
 
315
312
  /**
316
313
  * @param {number} bytes - Number of bytes sent
317
- * @returns {void}
318
314
  */
319
315
  #recordSent (bytes) {
320
316
  const telemetry = this.telemetry
@@ -326,7 +322,6 @@ class DogStatsDClient {
326
322
  /**
327
323
  * @param {number} bytes - Number of bytes dropped
328
324
  * @param {number} [packets] - Number of packets dropped
329
- * @returns {void}
330
325
  */
331
326
  #recordDropped (bytes, packets = 1) {
332
327
  const telemetry = this.telemetry
@@ -341,7 +336,6 @@ class DogStatsDClient {
341
336
  * @param {Buffer[]} queue - The metrics to send
342
337
  * @param {boolean} recordTelemetry - Whether to record the transport outcome
343
338
  * @param {() => void} [done] - Called after delivery completes
344
- * @returns {void}
345
339
  * @memberof DogStatsDClient
346
340
  */
347
341
  _sendHttp (queue, recordTelemetry, done) {
@@ -375,7 +369,6 @@ class DogStatsDClient {
375
369
  * @param {Buffer[]} queue - The metrics to send
376
370
  * @param {boolean} recordTelemetry - Whether to record the transport outcome
377
371
  * @param {() => void} [done] - Called after delivery completes
378
- * @returns {void}
379
372
  * @memberof DogStatsDClient
380
373
  */
381
374
  _sendUdp (queue, recordTelemetry, done) {
@@ -411,7 +404,6 @@ class DogStatsDClient {
411
404
  * @param {number} family - The family of the address
412
405
  * @param {boolean} recordTelemetry - Whether to record the transport outcome
413
406
  * @param {() => void} [done] - Called after every packet completes
414
- * @returns {void}
415
407
  * @memberof DogStatsDClient
416
408
  */
417
409
  _sendUdpFromQueue (queue, address, family, recordTelemetry, done) {
@@ -457,7 +449,6 @@ class DogStatsDClient {
457
449
  * @param {string[]} tags - The metric tags
458
450
  * @param {string} [tagsPrefix] - Serialized global tags
459
451
  * @param {DogStatsDBufferState} [state] - Payload state receiving the metric
460
- * @returns {void}
461
452
  * @memberof DogStatsDClient
462
453
  */
463
454
  _add (stat, value, type, tags, tagsPrefix = this.#tagsPrefix, state = this.#metrics) {
@@ -482,7 +473,6 @@ class DogStatsDClient {
482
473
  * @param {string} stat - Telemetry metric name
483
474
  * @param {number} value - Telemetry metric value
484
475
  * @param {string} [typeLabel] - Submitted or aggregated metric type
485
- * @returns {void}
486
476
  */
487
477
  #addTelemetry (stat, value, typeLabel) {
488
478
  const tags = typeLabel === undefined ? undefined : [`metrics_type:${typeLabel}`]
@@ -496,7 +486,6 @@ class DogStatsDClient {
496
486
  *
497
487
  * @param {string} message - The message to write
498
488
  * @param {DogStatsDBufferState} [state] - Payload state receiving the message
499
- * @returns {void}
500
489
  * @memberof DogStatsDClient
501
490
  */
502
491
  _write (message, state = this.#metrics) {
@@ -605,7 +594,6 @@ class MetricsAggregationClient {
605
594
  /**
606
595
  * @param {boolean|(() => void)} [forceTelemetry] - Whether to ignore the telemetry interval, or completion callback
607
596
  * @param {() => void} [done] - Called after serverless deliveries complete
608
- * @returns {void}
609
597
  */
610
598
  flush (forceTelemetry = false, done) {
611
599
  if (typeof forceTelemetry === 'function') {
@@ -680,9 +668,6 @@ class MetricsAggregationClient {
680
668
  this.count(name, -count, tags)
681
669
  }
682
670
 
683
- /**
684
- * @returns {number} Number of gauge contexts flushed
685
- */
686
671
  _captureGauges () {
687
672
  let metrics = 0
688
673
  const contexts = this._captureTree(this._gauges, (node, name, tags) => {
@@ -696,9 +681,6 @@ class MetricsAggregationClient {
696
681
  return contexts
697
682
  }
698
683
 
699
- /**
700
- * @returns {number} Number of counter contexts flushed
701
- */
702
684
  _captureCounters () {
703
685
  let metrics = 0
704
686
  const contexts = this._captureTree(this._counters, (node, name, tags) => {
@@ -712,9 +694,6 @@ class MetricsAggregationClient {
712
694
  return contexts
713
695
  }
714
696
 
715
- /**
716
- * @returns {number} Number of histogram contexts flushed
717
- */
718
697
  _captureHistograms () {
719
698
  let metrics = 0
720
699
  const contexts = this._captureTree(this._histograms, (node, name, tags) => {
@@ -740,7 +719,6 @@ class MetricsAggregationClient {
740
719
  /**
741
720
  * @param {Map<string, MetricNode>} tree - Metric context tree
742
721
  * @param {CaptureMetric} fn - Called for every context with submissions
743
- * @returns {number} Number of contexts with submissions
744
722
  */
745
723
  _captureTree (tree, fn) {
746
724
  let contexts = 0
@@ -757,7 +735,6 @@ class MetricsAggregationClient {
757
735
  * @param {string} name - Metric name
758
736
  * @param {string[]} tags - Current metric tags
759
737
  * @param {CaptureMetric} fn - Called for every context with submissions
760
- * @returns {number} Number of contexts with submissions
761
738
  */
762
739
  _captureNode (node, name, tags, fn) {
763
740
  let contexts = 0
@@ -74,13 +74,11 @@ class CrossPayloadAgentEncoder extends AgentEncoder {
74
74
  return super.makePayload()
75
75
  }
76
76
 
77
- /** @returns {void} */
78
77
  reset () {
79
78
  this.#prepareReset()
80
79
  super.reset()
81
80
  }
82
81
 
83
- /** @returns {void} */
84
82
  #prepareReset () {
85
83
  const crossPayloadState = this.#crossPayloadState
86
84
  if (crossPayloadState !== undefined && !prepareCrossPayloadReset(crossPayloadState)) {
@@ -129,7 +127,6 @@ function markPayloadString (crossPayloadState, value) {
129
127
 
130
128
  /**
131
129
  * @param {ReturnType<typeof createCrossPayloadState>} crossPayloadState
132
- * @returns {boolean}
133
130
  */
134
131
  function prepareCrossPayloadReset (crossPayloadState) {
135
132
  const learning = crossPayloadState.learningPayloadCount < CROSS_PAYLOAD_LEARNING_PAYLOAD_LIMIT
@@ -136,7 +136,6 @@ function formatSpanWithLegacyEvents (span) {
136
136
  * replacer hooks).
137
137
  *
138
138
  * @param {Array<{ name: unknown, startTime: number, attributes?: object }>} spanEvents
139
- * @returns {string}
140
139
  */
141
140
  function stringifySpanEvents (spanEvents) {
142
141
  let result = '['
@@ -200,7 +199,6 @@ function stringifyAttributeValue (value) {
200
199
  * conversion (which is what `JSON.stringify` calls internally).
201
200
  *
202
201
  * @param {number} value
203
- * @returns {string}
204
202
  */
205
203
  function jsonNumber (value) {
206
204
  if (Number.isFinite(value)) return String(value)
@@ -215,7 +213,6 @@ function jsonNumber (value) {
215
213
  * lone surrogates, etc.).
216
214
  *
217
215
  * @param {string} value
218
- * @returns {string}
219
216
  */
220
217
  function escapeJsonString (value) {
221
218
  for (let index = 0; index < value.length; index++) {
@@ -649,7 +646,6 @@ class AgentEncoder {
649
646
  * @param {number} offset
650
647
  * @param {Buffer} keyPrefix Precomputed `[key, 0xCF]`.
651
648
  * @param {{ toBuffer: () => Uint8Array | number[] }} identifier
652
- * @returns {number}
653
649
  */
654
650
  #writeIdAt (target, offset, keyPrefix, identifier) {
655
651
  target.set(keyPrefix, offset)
@@ -871,7 +867,6 @@ class AgentEncoder {
871
867
  * @param {MsgpackChunk} bytes
872
868
  * @param {string} key
873
869
  * @param {unknown} value
874
- * @returns {boolean}
875
870
  */
876
871
  #emitAttribute (bytes, key, value) {
877
872
  if (typeof value === 'string') {
@@ -911,7 +906,6 @@ class AgentEncoder {
911
906
  * @param {MsgpackChunk} bytes
912
907
  * @param {string} key
913
908
  * @param {Array<unknown>} array
914
- * @returns {boolean}
915
909
  */
916
910
  #emitArrayAttribute (bytes, key, array) {
917
911
  const sectionStart = bytes.length
@@ -946,7 +940,6 @@ class AgentEncoder {
946
940
  * @param {MsgpackChunk} bytes
947
941
  * @param {string} key
948
942
  * @param {unknown} value
949
- * @returns {boolean}
950
943
  */
951
944
  #emitArrayItem (bytes, key, value) {
952
945
  if (typeof value === 'string') {
@@ -173,7 +173,6 @@ class AgentEncoder extends BaseEncoder {
173
173
  * @param {Uint8Array} target
174
174
  * @param {number} offset
175
175
  * @param {number} index
176
- * @returns {number}
177
176
  */
178
177
  #writeIndexAt (target, offset, index) {
179
178
  target[offset] = 0xCE
@@ -192,7 +191,6 @@ class AgentEncoder extends BaseEncoder {
192
191
  * @param {Uint8Array} target
193
192
  * @param {number} offset
194
193
  * @param {{ toBuffer: () => Uint8Array | number[] }} identifier
195
- * @returns {number}
196
194
  */
197
195
  #writeIdAt (target, offset, identifier) {
198
196
  target[offset] = 0xCF
@@ -53,7 +53,6 @@ function truncateSpanTestOpt (span) {
53
53
  * the formatter no longer reshapes events, it hands the raw array through.
54
54
  *
55
55
  * @param {{ startTime: number }} event
56
- * @returns {number}
57
56
  */
58
57
  function eventTimeNano (event) {
59
58
  return Math.round(event.startTime * 1e6)
@@ -106,7 +106,6 @@ function selectEVPProxyPath (agentInfo, { supportedPaths, requiredHeaders = [] }
106
106
  * @param {string[]} [options.requiredHeaders] - Headers that the proxy must forward unchanged to intake. Each
107
107
  * header must appear in `evp_proxy_allowed_headers`. Do not include routing headers that the Agent consumes.
108
108
  * @param {(error: Error|null, route?: {url: URL, basePath: string}) => void} callback - Result callback
109
- * @returns {void}
110
109
  */
111
110
  function discoverEVPProxy (url, options, callback) {
112
111
  fetchAgentInfo(url, (error, agentInfo) => {
@@ -4,7 +4,6 @@ const LEADING_SLASHES = /^\/+/
4
4
 
5
5
  /**
6
6
  * @param {string} value
7
- * @returns {string}
8
7
  */
9
8
  function stripTrailingSlashes (value) {
10
9
  let end = value.length
@@ -19,7 +18,6 @@ function stripTrailingSlashes (value) {
19
18
  *
20
19
  * @param {string} basePath - EVP proxy base path
21
20
  * @param {string} endpoint - Product intake endpoint
22
- * @returns {string} Joined request path
23
21
  */
24
22
  function joinEVPProxyPath (basePath, endpoint) {
25
23
  const normalizedBasePath = stripTrailingSlashes(basePath)
@@ -44,7 +44,6 @@ class AgentWriter extends BaseWriter {
44
44
  * Test Optimization owns its own request lifecycle tracking.
45
45
  * @param {(error?: Error) => void} [done]
46
46
  * @param {{ deadline?: number }} [options]
47
- * @returns {void}
48
47
  */
49
48
  flushDirect (done, options) {
50
49
  if (this.#requestTracker) {
@@ -63,7 +63,6 @@ class AgentlessExporter {
63
63
  /**
64
64
  * Sets the intake URL.
65
65
  * @param {string} urlString - The new intake URL
66
- * @returns {boolean} True if URL was set successfully
67
66
  */
68
67
  setUrl (urlString) {
69
68
  try {
@@ -25,7 +25,6 @@ const INTAKE_PATH = '/api/v2/spans'
25
25
  * reattach the TLD, e.g. 'us2.ddog-gov.com' -> 'https://browser-intake-us2-ddog-gov.com'.
26
26
  *
27
27
  * @param {string} [site] - The Datadog site, e.g. 'us3.datadoghq.com'. Defaults to 'datadoghq.com'.
28
- * @returns {string} The intake origin, without a path.
29
28
  */
30
29
  function computeIntakeUrl (site = 'datadoghq.com') {
31
30
  const normalized = site.toLowerCase()
@@ -117,9 +117,6 @@ class AgentlessWriter extends BaseWriter {
117
117
  }
118
118
  }
119
119
 
120
- /**
121
- * @returns {string} The full agentless intake endpoint.
122
- */
123
120
  #endpoint () {
124
121
  const endpoint = new URL(this._url)
125
122
  endpoint.pathname = INTAKE_PATH
@@ -45,7 +45,6 @@ class FinalFlushRequestTracker {
45
45
  *
46
46
  * @param {(error?: Error) => void} [done]
47
47
  * @param {{ deadline?: number }} [options]
48
- * @returns {void}
49
48
  */
50
49
  flush (done, options) {
51
50
  if (options?.deadline === undefined) {
@@ -112,7 +111,6 @@ class FinalFlushRequestTracker {
112
111
  * @param {RequestOptions} options
113
112
  * @param {(error: Error|null, result?: string|null, statusCode?: number,
114
113
  * headers?: import('node:http').IncomingHttpHeaders) => void} callback
115
- * @returns {void}
116
114
  */
117
115
  send (request, data, options, callback) {
118
116
  const controller = new AbortController()
@@ -141,7 +139,6 @@ class FinalFlushRequestTracker {
141
139
 
142
140
  /**
143
141
  * @param {PendingRequest} pendingRequest
144
- * @returns {void}
145
142
  */
146
143
  #dropRequest (pendingRequest) {
147
144
  this.#pendingRequests.delete(pendingRequest)
@@ -155,7 +152,6 @@ class FinalFlushRequestTracker {
155
152
  /**
156
153
  * @param {FinalFlush} finalFlush
157
154
  * @param {PendingRequest} pendingRequest
158
- * @returns {void}
159
155
  */
160
156
  #attachRequest (finalFlush, pendingRequest) {
161
157
  finalFlush.requests.add(pendingRequest)
@@ -165,7 +161,6 @@ class FinalFlushRequestTracker {
165
161
 
166
162
  /**
167
163
  * @param {PendingRequest} pendingRequest
168
- * @returns {void}
169
164
  */
170
165
  #updateRequestDeadline (pendingRequest) {
171
166
  let deadline = 0
@@ -177,7 +172,6 @@ class FinalFlushRequestTracker {
177
172
 
178
173
  /**
179
174
  * @param {FinalFlush} finalFlush
180
- * @returns {void}
181
175
  */
182
176
  #finishFinalFlush (finalFlush) {
183
177
  if (!this.#finalFlushes.has(finalFlush) || !finalFlush.writerDone || finalFlush.requests.size !== 0) return
@@ -170,6 +170,7 @@ function request (data, options, callback) {
170
170
  }
171
171
  const error = new log.NoTransmitError(errorMessage)
172
172
  error.status = res.statusCode
173
+ if (options.includeErrorResponseBody) error.responseBody = responseData
173
174
 
174
175
  complete(error, null, res.statusCode, res.headers)
175
176
  }
@@ -7,7 +7,6 @@ const { urlToHttpOptions } = require('./url-to-http-options-polyfill')
7
7
 
8
8
  /**
9
9
  * @param {string} hostname
10
- * @returns {boolean}
11
10
  */
12
11
  function isLoopbackHost (hostname) {
13
12
  // Gate the 127/8 prefix on an IPv4 literal so names such as 127.example.com cannot pass.
@@ -20,7 +19,6 @@ function isLoopbackHost (hostname) {
20
19
  /**
21
20
  * @param {string|undefined} protocol
22
21
  * @param {string|undefined} hostname
23
- * @returns {boolean}
24
22
  */
25
23
  function canSendApiKey (protocol, hostname) {
26
24
  return protocol === 'https:' || protocol === 'unix:' ||
@@ -27,7 +27,6 @@ class Writer {
27
27
  * Flushes queued telemetry, retaining delivery on supported serverless platforms.
28
28
  * @param {(error?: Error) => void} [done]
29
29
  * @param {{ deadline?: number }} [options]
30
- * @returns {void}
31
30
  */
32
31
  flush (done, options) {
33
32
  if (this.#deliveryTracker) {
@@ -40,7 +39,6 @@ class Writer {
40
39
  * Flushes queued telemetry without registering serverless delivery retention.
41
40
  * @param {(error?: Error) => void} [done]
42
41
  * @param {{ deadline?: number }} [options]
43
- * @returns {void}
44
42
  */
45
43
  flushDirect (done = noop, options) {
46
44
  const count = this._encoder.count()
@@ -36,7 +36,6 @@ class Identifier {
36
36
 
37
37
  /**
38
38
  * @param {number} [radix]
39
- * @returns {string}
40
39
  */
41
40
  toString (radix = 16) {
42
41
  if (radix === 16) {
@@ -50,9 +49,6 @@ class Identifier {
50
49
  return toNumberString(this.#buffer, radix)
51
50
  }
52
51
 
53
- /**
54
- * @returns {bigint}
55
- */
56
52
  toBigInt () {
57
53
  this.#bigInt ??= Buffer.from(this.#buffer).readBigUInt64BE(0)
58
54
  return this.#bigInt
@@ -75,9 +71,6 @@ class Identifier {
75
71
  return this.#buffer.slice(-8)
76
72
  }
77
73
 
78
- /**
79
- * @returns {string}
80
- */
81
74
  toJSON () {
82
75
  return this.toString()
83
76
  }
@@ -88,7 +81,6 @@ class Identifier {
88
81
  * only this identifier's hex representation.
89
82
  *
90
83
  * @param {string | undefined} traceIdHigh - 16-char hex of the upper 64 bits, or undefined
91
- * @returns {string}
92
84
  */
93
85
  toTraceIdHex (traceIdHigh) {
94
86
  if (traceIdHigh && this.#buffer.length <= 8) {
@@ -99,7 +91,6 @@ class Identifier {
99
91
 
100
92
  /**
101
93
  * @param {Identifier} other
102
- * @returns {boolean}
103
94
  */
104
95
  equals (other) {
105
96
  // Big-endian suffix compare: when buffers differ in length, only the
@@ -182,7 +173,6 @@ function fromString (str, raddix) {
182
173
  /**
183
174
  * @param {number[] | Uint8Array} buffer
184
175
  * @param {number} [radix]
185
- * @returns {string}
186
176
  */
187
177
  function toNumberString (buffer, radix) {
188
178
  let high = readInt32(buffer, buffer.length - 8)
@@ -233,7 +223,6 @@ function pseudoRandom () {
233
223
  /**
234
224
  * @param {number[] | Uint8Array} buffer
235
225
  * @param {number} offset
236
- * @returns {number}
237
226
  */
238
227
  function readInt32 (buffer, offset) {
239
228
  return (buffer[offset + 0] * 16_777_216) +
@@ -0,0 +1,192 @@
1
+ 'use strict'
2
+
3
+ // Raw-audio primitives shared by the LLM Observability integrations: mapping provider audio formats
4
+ // to MIME types, decoding telephony audio to PCM16, wrapping PCM16 in a WAV container, and deriving
5
+ // a segment's playback duration from its byte count. Deliberately free of LLM Observability concepts
6
+ // so the realtime instrumentation can use the timing half without pulling in span plumbing.
7
+
8
+ const { G711_SAMPLE_RATE, PCM16_BYTES_PER_SAMPLE, WAV_HEADER_BYTES } = require('./constants/audio')
9
+
10
+ // OpenAI Realtime audio `format` values (legacy string form) that don't map to `audio/<format>`.
11
+ // A Map rather than an object literal so a hostile format string ("constructor", "__proto__") can't
12
+ // resolve to something off Object.prototype.
13
+ const REALTIME_FORMAT_MIME_TYPES = new Map([
14
+ ['pcm16', 'audio/pcm'],
15
+ ['pcm', 'audio/pcm'],
16
+ ['g711_ulaw', 'audio/pcmu'],
17
+ ['g711_alaw', 'audio/pcma'],
18
+ ])
19
+
20
+ // Raw little-endian PCM16. Not renderable on its own, but losslessly wrappable in a WAV container.
21
+ const PCM16_MIME_TYPES = new Set(['audio/pcm', 'audio/pcm16', 'audio/l16'])
22
+
23
+ // G.711 telephony audio (8 kHz, 8-bit companded), used by Realtime for phone-call integrations.
24
+ const G711_MIME_TO_VARIANT = new Map([
25
+ ['audio/pcmu', 'ulaw'],
26
+ ['audio/g711_ulaw', 'ulaw'],
27
+ ['audio/pcma', 'alaw'],
28
+ ['audio/g711_alaw', 'alaw'],
29
+ ])
30
+
31
+ /**
32
+ * Decode one G.711 mu-law byte to a signed 16-bit linear PCM sample (CCITT G.711).
33
+ *
34
+ * @param {number} byte
35
+ */
36
+ function decodeUlawSample (byte) {
37
+ byte = ~byte & 0xFF
38
+ let sample = ((byte & 0x0F) << 3) + 0x84
39
+ sample <<= (byte & 0x70) >> 4
40
+ return (byte & 0x80) ? (0x84 - sample) : (sample - 0x84)
41
+ }
42
+
43
+ /**
44
+ * Decode one G.711 A-law byte to a signed 16-bit linear PCM sample (CCITT G.711).
45
+ *
46
+ * @param {number} byte
47
+ */
48
+ function decodeAlawSample (byte) {
49
+ byte ^= 0x55
50
+ let sample = (byte & 0x0F) << 4
51
+ const segment = (byte & 0x70) >> 4
52
+ if (segment === 0) {
53
+ sample += 8
54
+ } else if (segment === 1) {
55
+ sample += 0x1_08
56
+ } else {
57
+ sample = (sample + 0x1_08) << (segment - 1)
58
+ }
59
+ return (byte & 0x80) ? sample : -sample
60
+ }
61
+
62
+ // The input domain is a single byte, so both decodes collapse to a 256-entry lookup built once.
63
+ const ULAW_TABLE = new Int16Array(256)
64
+ const ALAW_TABLE = new Int16Array(256)
65
+ for (let byte = 0; byte < 256; byte++) {
66
+ ULAW_TABLE[byte] = decodeUlawSample(byte)
67
+ ALAW_TABLE[byte] = decodeAlawSample(byte)
68
+ }
69
+
70
+ /**
71
+ * Map an OpenAI Realtime audio format to a MIME type.
72
+ *
73
+ * Handles both the legacy string form (e.g. "pcm16", "g711_ulaw") and the newer discriminated-union
74
+ * object whose `type` is already a MIME type (e.g. "audio/pcm"). Yields an empty string when the
75
+ * format is absent or unusable, which callers treat as "unknown" rather than guessing a rate.
76
+ *
77
+ * @param {string | { type?: string } | undefined} format
78
+ */
79
+ function realtimeAudioFormatToMime (format) {
80
+ const type = typeof format === 'object' && format !== null ? format.type : format
81
+ if (typeof type !== 'string') return ''
82
+
83
+ const normalized = type.trim().toLowerCase()
84
+ if (!normalized) return ''
85
+ if (normalized.startsWith('audio/')) return normalized
86
+
87
+ return REALTIME_FORMAT_MIME_TYPES.get(normalized) ?? `audio/${normalized}`
88
+ }
89
+
90
+ /**
91
+ * @param {string} mimeType
92
+ */
93
+ function isPcm16AudioMime (mimeType) {
94
+ return typeof mimeType === 'string' && PCM16_MIME_TYPES.has(mimeType.trim().toLowerCase())
95
+ }
96
+
97
+ /**
98
+ * @param {string} mimeType
99
+ * @returns {'ulaw' | 'alaw' | undefined} The G.711 variant, or `undefined` for any other format.
100
+ */
101
+ function g711Variant (mimeType) {
102
+ if (typeof mimeType !== 'string') return
103
+ return G711_MIME_TO_VARIANT.get(mimeType.trim().toLowerCase())
104
+ }
105
+
106
+ /**
107
+ * Decode G.711 audio to raw little-endian PCM16.
108
+ *
109
+ * @param {Buffer} data
110
+ * @param {'ulaw' | 'alaw'} variant
111
+ * @returns {Buffer}
112
+ */
113
+ function g711ToPcm16 (data, variant) {
114
+ const table = variant === 'alaw' ? ALAW_TABLE : ULAW_TABLE
115
+ const pcm = Buffer.allocUnsafe(data.length * PCM16_BYTES_PER_SAMPLE)
116
+ for (let i = 0; i < data.length; i++) {
117
+ pcm.writeInt16LE(table[data[i]], i * PCM16_BYTES_PER_SAMPLE)
118
+ }
119
+ return pcm
120
+ }
121
+
122
+ /**
123
+ * Wrap raw little-endian PCM16 audio in a WAV container.
124
+ *
125
+ * Lossless and cheap — it only prepends a 44-byte header — and turns raw PCM, which the UI can't
126
+ * render, into a playable `audio/wav` payload.
127
+ *
128
+ * @param {Buffer} pcm
129
+ * @param {number} [sampleRate]
130
+ * @param {number} [channels]
131
+ * @returns {Buffer}
132
+ */
133
+ function pcm16ToWav (pcm, sampleRate = 24_000, channels = 1) {
134
+ const blockAlign = channels * PCM16_BYTES_PER_SAMPLE
135
+ const header = Buffer.allocUnsafe(WAV_HEADER_BYTES)
136
+
137
+ header.write('RIFF', 0, 'latin1')
138
+ header.writeUInt32LE(WAV_HEADER_BYTES - 8 + pcm.length, 4) // RIFF chunk size: everything after this field
139
+ header.write('WAVE', 8, 'latin1')
140
+ header.write('fmt ', 12, 'latin1')
141
+ header.writeUInt32LE(16, 16) // fmt chunk size, 16 for PCM
142
+ header.writeUInt16LE(1, 20) // audio format, 1 for uncompressed PCM
143
+ header.writeUInt16LE(channels, 22)
144
+ header.writeUInt32LE(sampleRate, 24)
145
+ header.writeUInt32LE(sampleRate * blockAlign, 28) // byte rate
146
+ header.writeUInt16LE(blockAlign, 32)
147
+ header.writeUInt16LE(PCM16_BYTES_PER_SAMPLE * 8, 34) // bits per sample
148
+ header.write('data', 36, 'latin1')
149
+ header.writeUInt32LE(pcm.length, 40)
150
+
151
+ return Buffer.concat([header, pcm], WAV_HEADER_BYTES + pcm.length)
152
+ }
153
+
154
+ /**
155
+ * Byte rate of a raw audio format: PCM16 is 2 bytes per sample at the session's rate, G.711 is 1
156
+ * byte per sample at the fixed 8 kHz rate. Any other or unknown format returns `undefined` — we do
157
+ * not guess a rate, so durations and offsets derived from it are simply unavailable.
158
+ *
159
+ * @param {string} mimeType
160
+ * @param {number} sampleRate
161
+ * @returns {number | undefined}
162
+ */
163
+ function bytesPerSecond (mimeType, sampleRate) {
164
+ if (sampleRate > 0 && isPcm16AudioMime(mimeType)) return sampleRate * PCM16_BYTES_PER_SAMPLE
165
+ if (g711Variant(mimeType) !== undefined) return G711_SAMPLE_RATE
166
+ }
167
+
168
+ /**
169
+ * Playback duration (in milliseconds) of an audio segment, from its decoded byte count. Sizes the
170
+ * user-speech and agent-speech spans and the turn root's end, so it may be fractional.
171
+ *
172
+ * @param {number} decodedBytes
173
+ * @param {string} mimeType
174
+ * @param {number} sampleRate
175
+ * @returns {number | undefined}
176
+ */
177
+ function segmentDurationMs (decodedBytes, mimeType, sampleRate) {
178
+ if (!(decodedBytes > 0)) return
179
+ const rate = bytesPerSecond(mimeType, sampleRate)
180
+ if (!rate) return
181
+ return decodedBytes / rate * 1000
182
+ }
183
+
184
+ module.exports = {
185
+ bytesPerSecond,
186
+ g711ToPcm16,
187
+ g711Variant,
188
+ isPcm16AudioMime,
189
+ pcm16ToWav,
190
+ realtimeAudioFormatToMime,
191
+ segmentDurationMs,
192
+ }