dd-trace 5.134.0 → 5.136.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 (353) hide show
  1. package/LICENSE-3rdparty.csv +0 -1
  2. package/ci/cypress/support.js +15 -1
  3. package/ci/init.js +2 -22
  4. package/ci/test-annotations.d.ts +5 -0
  5. package/ci/test-annotations.js +5 -0
  6. package/ci/vitest-no-worker-init-annotations.mjs +4 -0
  7. package/ci/vitest-no-worker-init-node-setup.mjs +22 -0
  8. package/ci/vitest-no-worker-init-runner-setup.mjs +7 -32
  9. package/ci/vitest-no-worker-init-setup.mjs +34 -12
  10. package/ci/vitest-no-worker-init-v5-setup.mjs +6 -0
  11. package/ext/exporters.js +1 -1
  12. package/index.d.ts +124 -5
  13. package/initialize.mjs +5 -2
  14. package/lambda.d.ts +39 -0
  15. package/lambda.js +3 -0
  16. package/loader-hook.mjs +53 -0
  17. package/openfeature/exposure-hook.d.ts +66 -0
  18. package/openfeature/exposure-hook.js +5 -0
  19. package/package.json +19 -15
  20. package/packages/datadog-core/src/storage.js +1 -1
  21. package/packages/datadog-esbuild/index.js +78 -62
  22. package/packages/datadog-instrumentations/src/aws-lambda.js +88 -0
  23. package/packages/datadog-instrumentations/src/cucumber.js +56 -19
  24. package/packages/datadog-instrumentations/src/cypress-config.js +163 -15
  25. package/packages/datadog-instrumentations/src/elevenlabs/activity.js +114 -0
  26. package/packages/datadog-instrumentations/src/elevenlabs/audio.js +104 -0
  27. package/packages/datadog-instrumentations/src/elevenlabs/index.js +288 -0
  28. package/packages/datadog-instrumentations/src/elevenlabs/session.js +444 -0
  29. package/packages/datadog-instrumentations/src/graphql.js +29 -20
  30. package/packages/datadog-instrumentations/src/grpc/server.js +23 -6
  31. package/packages/{datadog-esbuild/src/utils.js → datadog-instrumentations/src/helpers/bundler-esm-exports.js} +282 -40
  32. package/packages/datadog-instrumentations/src/helpers/bundler-transform.js +573 -0
  33. package/packages/datadog-instrumentations/src/helpers/bundler-utils.js +104 -0
  34. package/packages/datadog-instrumentations/src/helpers/fetch.js +5 -1
  35. package/packages/datadog-instrumentations/src/helpers/graphql-jit-runtime.js +30 -8
  36. package/packages/datadog-instrumentations/src/helpers/hook.js +29 -1
  37. package/packages/datadog-instrumentations/src/helpers/hooks.js +4 -8
  38. package/packages/datadog-instrumentations/src/helpers/lambda-handler.js +189 -0
  39. package/packages/datadog-instrumentations/src/helpers/rewriter/index.js +18 -6
  40. package/packages/datadog-instrumentations/src/helpers/rewriter/instrumentation-registry.js +26 -1
  41. package/packages/datadog-instrumentations/src/helpers/rewriter/instrumentations/async-mutex.js +41 -0
  42. package/packages/datadog-instrumentations/src/helpers/rewriter/instrumentations/elevenlabs.js +25 -0
  43. package/packages/datadog-instrumentations/src/helpers/rewriter/instrumentations/graphql-jit.js +3 -1
  44. package/packages/datadog-instrumentations/src/helpers/rewriter/instrumentations/graphql.js +0 -36
  45. package/packages/datadog-instrumentations/src/helpers/rewriter/instrumentations/next.js +40 -0
  46. package/packages/datadog-instrumentations/src/helpers/rewriter/instrumentations/openai-agents-realtime.js +23 -0
  47. package/packages/datadog-instrumentations/src/helpers/rewriter/instrumentations/react-router.js +49 -0
  48. package/packages/datadog-instrumentations/src/helpers/rewriter/instrumentations/trpc.js +148 -0
  49. package/packages/datadog-instrumentations/src/helpers/rewriter/instrumentations/typesafe.js +23 -0
  50. package/packages/datadog-instrumentations/src/helpers/rewriter/instrumentations/webdriverio.js +12 -0
  51. package/packages/datadog-instrumentations/src/helpers/rewriter/target-patterns.json +58 -0
  52. package/packages/datadog-instrumentations/src/helpers/rewriter/targets.js +19 -2
  53. package/packages/datadog-instrumentations/src/helpers/rewriter/targets.json +25 -3
  54. package/packages/datadog-instrumentations/src/helpers/rewriter/transforms.js +59 -2
  55. package/packages/datadog-instrumentations/src/ioredis.js +101 -3
  56. package/packages/datadog-instrumentations/src/jest.js +265 -82
  57. package/packages/datadog-instrumentations/src/mariadb-bundle.js +69 -11
  58. package/packages/datadog-instrumentations/src/mariadb.js +13 -6
  59. package/packages/datadog-instrumentations/src/mocha/common.js +89 -8
  60. package/packages/datadog-instrumentations/src/mocha/main.js +11 -2
  61. package/packages/datadog-instrumentations/src/mocha/utils.js +58 -12
  62. package/packages/datadog-instrumentations/src/mocha/worker.js +1 -1
  63. package/packages/datadog-instrumentations/src/next.js +19 -6
  64. package/packages/datadog-instrumentations/src/openai-agents-realtime.js +149 -0
  65. package/packages/datadog-instrumentations/src/openai-realtime/audio-accumulator.js +27 -0
  66. package/packages/datadog-instrumentations/src/openai-realtime/index.js +17 -6
  67. package/packages/datadog-instrumentations/src/openai-realtime/server-playback.js +887 -0
  68. package/packages/datadog-instrumentations/src/openai-realtime/session.js +150 -25
  69. package/packages/datadog-instrumentations/src/openai-realtime/turns.js +29 -2
  70. package/packages/datadog-instrumentations/src/oracledb.js +33 -0
  71. package/packages/datadog-instrumentations/src/otel-sdk-trace.js +11 -9
  72. package/packages/datadog-instrumentations/src/pg.js +2 -1
  73. package/packages/datadog-instrumentations/src/playwright.js +81 -28
  74. package/packages/datadog-instrumentations/src/react-router.js +106 -0
  75. package/packages/datadog-instrumentations/src/typesafe.js +89 -0
  76. package/packages/datadog-instrumentations/src/vitest-main-no-worker-init.js +84 -48
  77. package/packages/datadog-instrumentations/src/vitest-main.js +26 -0
  78. package/packages/datadog-instrumentations/src/vitest-test-annotations.js +20 -0
  79. package/packages/datadog-instrumentations/src/vitest-worker.js +39 -17
  80. package/packages/datadog-instrumentations/src/vitest.js +10 -8
  81. package/packages/datadog-instrumentations/src/webdriverio.js +12 -12
  82. package/packages/datadog-plugin-async-mutex/src/index.js +50 -0
  83. package/packages/datadog-plugin-aws-lambda/src/index.js +106 -0
  84. package/packages/datadog-plugin-cucumber/src/index.js +5 -0
  85. package/packages/datadog-plugin-cypress/src/cypress-plugin.js +296 -55
  86. package/packages/datadog-plugin-cypress/src/index.js +1 -1
  87. package/packages/datadog-plugin-cypress/src/lifecycle-owner.js +20 -0
  88. package/packages/datadog-plugin-cypress/src/plugin.js +10 -0
  89. package/packages/datadog-plugin-cypress/src/retry-config-observer.js +281 -0
  90. package/packages/datadog-plugin-cypress/src/setup-handoff.js +125 -0
  91. package/packages/datadog-plugin-cypress/src/support.js +1217 -439
  92. package/packages/datadog-plugin-elevenlabs/src/index.js +69 -0
  93. package/packages/datadog-plugin-google-cloud-pubsub/src/consumer.js +10 -7
  94. package/packages/datadog-plugin-google-cloud-pubsub/src/producer.js +19 -52
  95. package/packages/datadog-plugin-google-cloud-pubsub/src/pubsub-push-subscription.js +4 -2
  96. package/packages/datadog-plugin-google-cloud-pubsub/src/pubsub-request-context.js +25 -4
  97. package/packages/datadog-plugin-graphql/src/execute.js +2 -2
  98. package/packages/datadog-plugin-graphql/src/utils.js +5 -5
  99. package/packages/datadog-plugin-http/src/client.js +32 -9
  100. package/packages/datadog-plugin-http2/src/client.js +38 -13
  101. package/packages/datadog-plugin-jest/src/index.js +25 -3
  102. package/packages/datadog-plugin-mocha/src/index.js +47 -6
  103. package/packages/datadog-plugin-next/src/index.js +112 -14
  104. package/packages/datadog-plugin-oracledb/src/connection-parser.js +21 -11
  105. package/packages/datadog-plugin-playwright/src/index.js +4 -0
  106. package/packages/datadog-plugin-prisma/src/datadog-tracing-helper.js +5 -3
  107. package/packages/datadog-plugin-react-router/src/index.js +118 -0
  108. package/packages/datadog-plugin-trpc/src/index.js +15 -0
  109. package/packages/datadog-plugin-trpc/src/procedure.js +48 -0
  110. package/packages/datadog-plugin-trpc/src/request.js +81 -0
  111. package/packages/datadog-plugin-typesafe/src/index.js +17 -0
  112. package/packages/datadog-plugin-typesafe/src/tracing.js +31 -0
  113. package/packages/datadog-plugin-undici/src/index.js +22 -7
  114. package/packages/datadog-plugin-vitest/src/index.js +8 -0
  115. package/packages/datadog-turbopack/index.js +4 -28
  116. package/packages/datadog-turbopack/src/loader.js +14 -452
  117. package/packages/datadog-webpack/index.js +3 -55
  118. package/packages/dd-trace/src/agent/info.js +2 -1
  119. package/packages/dd-trace/src/aiguard/evaluation.js +62 -1
  120. package/packages/dd-trace/src/aiguard/sdk.js +8 -13
  121. package/packages/dd-trace/src/aiguard/tags.js +2 -0
  122. package/packages/dd-trace/src/appsec/blocking/index.js +4 -0
  123. package/packages/dd-trace/src/appsec/graphql.js +91 -6
  124. package/packages/dd-trace/src/appsec/recommended.json +1287 -90
  125. package/packages/dd-trace/src/before-exit.js +32 -0
  126. package/packages/dd-trace/src/bootstrap.js +5 -3
  127. package/packages/dd-trace/src/ci-visibility/early-flake-detection/get-known-tests.js +24 -18
  128. package/packages/dd-trace/src/ci-visibility/exporters/ci-visibility-exporter.js +16 -36
  129. package/packages/dd-trace/src/ci-visibility/exporters/git/git_metadata.js +41 -13
  130. package/packages/dd-trace/src/ci-visibility/exporters/request.js +2 -3
  131. package/packages/dd-trace/src/ci-visibility/intelligent-test-runner/get-skippable-suites.js +10 -18
  132. package/packages/dd-trace/src/ci-visibility/requests/get-library-configuration.js +10 -15
  133. package/packages/dd-trace/src/ci-visibility/requests/route.js +44 -0
  134. package/packages/dd-trace/src/ci-visibility/telemetry-logs.js +5 -0
  135. package/packages/dd-trace/src/ci-visibility/telemetry.js +6 -0
  136. package/packages/dd-trace/src/ci-visibility/test-annotations.js +72 -0
  137. package/packages/dd-trace/src/ci-visibility/test-declaration-annotations.js +170 -0
  138. package/packages/dd-trace/src/ci-visibility/test-management/get-test-management-tests.js +10 -17
  139. package/packages/dd-trace/src/ci-visibility/test-optimization-http-cache-schema.js +9 -134
  140. package/packages/dd-trace/src/ci-visibility/test-optimization-http-cache.js +11 -156
  141. package/packages/dd-trace/src/config/config-types.d.ts +3 -0
  142. package/packages/dd-trace/src/config/defaults.js +9 -3
  143. package/packages/dd-trace/src/config/generated-config-types.d.ts +46 -2
  144. package/packages/dd-trace/src/config/index.js +111 -43
  145. package/packages/dd-trace/src/config/parsers.js +18 -1
  146. package/packages/dd-trace/src/config/supported-configurations.json +174 -4
  147. package/packages/dd-trace/src/constants.js +1 -0
  148. package/packages/dd-trace/src/debugger/pause-duration-histogram.js +2 -1
  149. package/packages/dd-trace/src/debugger/probe_sampler.js +6 -6
  150. package/packages/dd-trace/src/encode/0.4.js +2 -2
  151. package/packages/dd-trace/src/esm-module-load.js +58 -0
  152. package/packages/dd-trace/src/exporter.js +23 -15
  153. package/packages/dd-trace/src/exporters/agent/index.js +3 -1
  154. package/packages/dd-trace/src/exporters/agentless/index.js +3 -1
  155. package/packages/dd-trace/src/exporters/common/request.js +83 -50
  156. package/packages/dd-trace/src/exporters/common/retry.js +12 -7
  157. package/packages/dd-trace/src/exporters/common/url.js +1 -1
  158. package/packages/dd-trace/src/exporters/llmobs/index.js +135 -0
  159. package/packages/dd-trace/src/exporters/log/index.js +4 -3
  160. package/packages/dd-trace/src/id.js +1 -1
  161. package/packages/dd-trace/src/lambda/facade.js +74 -0
  162. package/packages/dd-trace/src/lambda/handler.js +3 -41
  163. package/packages/dd-trace/src/lambda/index.js +38 -15
  164. package/packages/dd-trace/src/lambda/runtime/patch.js +19 -3
  165. package/packages/dd-trace/src/lambda/wrap.js +44 -0
  166. package/packages/dd-trace/src/llmobs/constants/tags.js +3 -0
  167. package/packages/dd-trace/src/llmobs/experiments/experiment.js +10 -5
  168. package/packages/dd-trace/src/llmobs/experiments/index.js +2 -3
  169. package/packages/dd-trace/src/llmobs/experiments/noop.js +5 -2
  170. package/packages/dd-trace/src/llmobs/index.js +13 -2
  171. package/packages/dd-trace/src/llmobs/plugins/claude-agent-sdk/index.js +1 -1
  172. package/packages/dd-trace/src/llmobs/plugins/elevenlabs.js +96 -0
  173. package/packages/dd-trace/src/llmobs/plugins/genai/index.js +1 -1
  174. package/packages/dd-trace/src/llmobs/plugins/genai/util.js +27 -10
  175. package/packages/dd-trace/src/llmobs/plugins/openai/realtime.js +38 -11
  176. package/packages/dd-trace/src/llmobs/plugins/typesafe/index.js +102 -0
  177. package/packages/dd-trace/src/llmobs/plugins/vertexai.js +10 -2
  178. package/packages/dd-trace/src/llmobs/prompts/cache.js +3 -1
  179. package/packages/dd-trace/src/llmobs/sdk.js +21 -1
  180. package/packages/dd-trace/src/llmobs/span_processor.js +219 -12
  181. package/packages/dd-trace/src/llmobs/tagger.js +25 -0
  182. package/packages/dd-trace/src/llmobs/writers/util.js +3 -3
  183. package/packages/dd-trace/src/log/channels.js +4 -0
  184. package/packages/dd-trace/src/log/writer.js +13 -2
  185. package/packages/dd-trace/src/openfeature/agentless_configuration_source.js +68 -6
  186. package/packages/dd-trace/src/openfeature/configuration_source.js +41 -17
  187. package/packages/dd-trace/src/openfeature/debug-logging-hook.js +66 -3
  188. package/packages/dd-trace/src/openfeature/exposure-hook.js +185 -0
  189. package/packages/dd-trace/src/openfeature/flag-selection.js +152 -0
  190. package/packages/dd-trace/src/openfeature/flagging_provider.js +58 -14
  191. package/packages/dd-trace/src/openfeature/remote_config.js +16 -3
  192. package/packages/dd-trace/src/openfeature/writers/base.js +63 -30
  193. package/packages/dd-trace/src/openfeature/writers/exposures.js +161 -1
  194. package/packages/dd-trace/src/openfeature/writers/flag-eval-evp-hook.js +5 -0
  195. package/packages/dd-trace/src/openfeature/writers/flag-evaluation-aggregation.js +9 -4
  196. package/packages/dd-trace/src/openfeature/writers/flag-evaluation-payload.js +2 -0
  197. package/packages/dd-trace/src/openfeature/writers/flag-evaluation-pii.js +2 -0
  198. package/packages/dd-trace/src/openfeature/writers/split-features.js +25 -0
  199. package/packages/dd-trace/src/opentelemetry/logs/index.js +11 -0
  200. package/packages/dd-trace/src/opentelemetry/logs/otlp_http_log_exporter.js +1 -1
  201. package/packages/dd-trace/src/opentelemetry/metrics/index.js +7 -1
  202. package/packages/dd-trace/src/opentelemetry/metrics/otlp_http_metric_exporter.js +1 -1
  203. package/packages/dd-trace/src/opentelemetry/metrics/otlp_span_stats_exporter.js +4 -1
  204. package/packages/dd-trace/src/opentelemetry/metrics/periodic_metric_reader.js +2 -2
  205. package/packages/dd-trace/src/opentelemetry/otlp/otlp_http_exporter_base.js +19 -1
  206. package/packages/dd-trace/src/opentelemetry/span-ending-hook.js +5 -1
  207. package/packages/dd-trace/src/opentelemetry/span-helpers.js +6 -1
  208. package/packages/dd-trace/src/opentelemetry/span.js +2 -2
  209. package/packages/dd-trace/src/opentelemetry/startup-config.js +174 -0
  210. package/packages/dd-trace/src/opentelemetry/trace/otlp_http_trace_exporter.js +1 -1
  211. package/packages/dd-trace/src/opentelemetry/trace/otlp_transformer.js +7 -1
  212. package/packages/dd-trace/src/opentelemetry/tracer_provider.js +5 -1
  213. package/packages/dd-trace/src/opentracing/propagation/tracestate.js +77 -23
  214. package/packages/dd-trace/src/opentracing/tracer.js +33 -13
  215. package/packages/dd-trace/src/otel-thread-ctx.js +72 -49
  216. package/packages/dd-trace/src/plugin_manager.js +34 -7
  217. package/packages/dd-trace/src/plugins/ci_plugin.js +45 -14
  218. package/packages/dd-trace/src/plugins/index.js +9 -0
  219. package/packages/dd-trace/src/plugins/plugin.js +4 -2
  220. package/packages/dd-trace/src/plugins/tracing.js +1 -1
  221. package/packages/dd-trace/src/plugins/util/ci.js +18 -1
  222. package/packages/dd-trace/src/plugins/util/git-cache.js +4 -4
  223. package/packages/dd-trace/src/plugins/util/git.js +273 -86
  224. package/packages/dd-trace/src/plugins/util/http-otel-semantics.js +77 -50
  225. package/packages/dd-trace/src/plugins/util/inferred_proxy.js +12 -4
  226. package/packages/dd-trace/src/plugins/util/status-validator.js +23 -10
  227. package/packages/dd-trace/src/plugins/util/tags.js +6 -0
  228. package/packages/dd-trace/src/plugins/util/test.js +90 -45
  229. package/packages/dd-trace/src/plugins/util/url.js +10 -2
  230. package/packages/dd-trace/src/plugins/util/user-provided-git.js +2 -2
  231. package/packages/dd-trace/src/plugins/util/web.js +81 -10
  232. package/packages/dd-trace/src/process-tags/index.js +1 -1
  233. package/packages/dd-trace/src/profiling/config.js +6 -3
  234. package/packages/dd-trace/src/profiling/webspan-utils.js +6 -5
  235. package/packages/dd-trace/src/proxy.js +48 -57
  236. package/packages/dd-trace/src/serverless.js +3 -2
  237. package/packages/dd-trace/src/span_processor.js +41 -9
  238. package/packages/dd-trace/src/span_stats.js +28 -2
  239. package/packages/dd-trace/src/startup-log.js +8 -5
  240. package/packages/dd-trace/src/tagger.js +7 -5
  241. package/packages/dd-trace/src/telemetry/dependencies.js +4 -0
  242. package/packages/dd-trace/src/telemetry/index.js +3 -0
  243. package/packages/dd-trace/src/telemetry/logs/index.js +21 -2
  244. package/packages/dd-trace/src/telemetry/logs/log-collector.js +1 -0
  245. package/packages/dd-trace/src/telemetry/metrics.js +2 -1
  246. package/packages/dd-trace/src/telemetry/telemetry.js +10 -3
  247. package/packages/dd-trace/src/tracer.js +0 -2
  248. package/packages/dd-trace/src/util.js +1 -1
  249. package/packages/dd-trace/src/web-tags-cache.js +8 -9
  250. package/register.js +4 -2
  251. package/vendor/dist/@apm-js-collab/code-transformer/LICENSE +489 -0
  252. package/vendor/dist/{@opentelemetry/resources → @datadog/flagging-core}/LICENSE +22 -2
  253. package/vendor/dist/@datadog/flagging-core/index.js +1 -0
  254. package/vendor/dist/@datadog/openfeature-node-server/LICENSE +21 -1
  255. package/vendor/dist/@datadog/openfeature-node-server/index.js +1 -1
  256. package/vendor/dist/@datadog/openfeature-node-server/rules-based/LICENSE +3 -1
  257. package/vendor/dist/@datadog/openfeature-node-server/rules-based/index.d.ts +78 -0
  258. package/vendor/dist/@datadog/openfeature-node-server/rules-based/index.js +1 -1
  259. package/vendor/dist/@datadog/sketches-js/LICENSE +263 -0
  260. package/vendor/dist/@datadog/source-map/LICENSE +1 -0
  261. package/vendor/dist/@isaacs/ttlcache/LICENSE +13 -0
  262. package/vendor/dist/@opentelemetry/core/LICENSE +209 -1
  263. package/vendor/dist/@opentelemetry/core/index.js +1 -1
  264. package/vendor/dist/crypto-randomuuid/LICENSE +3 -0
  265. package/vendor/dist/escape-string-regexp/LICENSE +13 -0
  266. package/vendor/dist/esquery/LICENSE +2 -0
  267. package/vendor/dist/https-proxy-agent/LICENSE +80 -1
  268. package/vendor/dist/istanbul-lib-coverage/LICENSE +2 -0
  269. package/vendor/dist/jest-docblock/LICENSE +16 -0
  270. package/vendor/dist/jsonpath-plus/LICENSE +13 -0
  271. package/vendor/dist/limiter/LICENSE +2 -0
  272. package/vendor/dist/lodash.sortby/LICENSE +2 -0
  273. package/vendor/dist/lru-cache/LICENSE +13 -0
  274. package/vendor/dist/meriyah/LICENSE +13 -0
  275. package/vendor/dist/module-details-from-path/LICENSE +2 -0
  276. package/vendor/dist/mutexify/promise/LICENSE +28 -0
  277. package/vendor/dist/pprof-format/LICENSE +13 -0
  278. package/vendor/dist/pprof-format/index.js +1 -1
  279. package/vendor/dist/protobufjs/LICENSE +219 -0
  280. package/vendor/dist/protobufjs/minimal/LICENSE +219 -0
  281. package/vendor/dist/proxy-from-env/LICENSE +13 -0
  282. package/vendor/dist/retry/LICENSE +2 -0
  283. package/vendor/dist/rfdc/LICENSE +2 -0
  284. package/vendor/dist/semifies/LICENSE +3 -1
  285. package/vendor/dist/shell-quote/LICENSE +3 -1
  286. package/vendor/dist/source-map/LICENSE +1 -0
  287. package/vendor/dist/source-map/lib/util/LICENSE +1 -0
  288. package/vendor/dist/tlhunter-sorted-set/LICENSE +2 -0
  289. package/vendor/dist/ttl-set/LICENSE +28 -0
  290. package/ci/diagnose.js +0 -2215
  291. package/ci/runbook.md +0 -299
  292. package/ci/test-optimization-validation/approval-artifacts.js +0 -175
  293. package/ci/test-optimization-validation/approval.js +0 -386
  294. package/ci/test-optimization-validation/artifact-id.js +0 -19
  295. package/ci/test-optimization-validation/blocker-category.js +0 -24
  296. package/ci/test-optimization-validation/bounded-json.js +0 -120
  297. package/ci/test-optimization-validation/ci-command-candidate.js +0 -77
  298. package/ci/test-optimization-validation/ci-discovery.js +0 -192
  299. package/ci/test-optimization-validation/ci-package-scripts.js +0 -169
  300. package/ci/test-optimization-validation/ci-remediation.js +0 -283
  301. package/ci/test-optimization-validation/cli.js +0 -954
  302. package/ci/test-optimization-validation/command-blocker.js +0 -377
  303. package/ci/test-optimization-validation/command-output-policy.js +0 -188
  304. package/ci/test-optimization-validation/command-runner.js +0 -650
  305. package/ci/test-optimization-validation/environment.js +0 -88
  306. package/ci/test-optimization-validation/executable-approval.js +0 -47
  307. package/ci/test-optimization-validation/executable.js +0 -244
  308. package/ci/test-optimization-validation/execution-lock.js +0 -70
  309. package/ci/test-optimization-validation/framework-adapters/cucumber-validation.json +0 -3
  310. package/ci/test-optimization-validation/framework-adapters/cucumber.js +0 -767
  311. package/ci/test-optimization-validation/framework-adapters/cypress.js +0 -99
  312. package/ci/test-optimization-validation/framework-adapters/playwright.js +0 -175
  313. package/ci/test-optimization-validation/framework-adapters/vitest.js +0 -513
  314. package/ci/test-optimization-validation/generated-file-policy.js +0 -63
  315. package/ci/test-optimization-validation/generated-files.js +0 -425
  316. package/ci/test-optimization-validation/generated-test-contract.js +0 -284
  317. package/ci/test-optimization-validation/generated-verifier.js +0 -235
  318. package/ci/test-optimization-validation/literal-environment.js +0 -56
  319. package/ci/test-optimization-validation/literal-glob.js +0 -52
  320. package/ci/test-optimization-validation/manifest-loader.js +0 -116
  321. package/ci/test-optimization-validation/manifest-scaffold.js +0 -1276
  322. package/ci/test-optimization-validation/manifest-schema.js +0 -695
  323. package/ci/test-optimization-validation/offline-fixtures.js +0 -335
  324. package/ci/test-optimization-validation/offline-output.js +0 -406
  325. package/ci/test-optimization-validation/package-check.js +0 -97
  326. package/ci/test-optimization-validation/payload-normalizer.js +0 -72
  327. package/ci/test-optimization-validation/plan-writer.js +0 -541
  328. package/ci/test-optimization-validation/preflight-runner.js +0 -186
  329. package/ci/test-optimization-validation/project-build-artifact.js +0 -31
  330. package/ci/test-optimization-validation/redaction.js +0 -319
  331. package/ci/test-optimization-validation/report-writer.js +0 -666
  332. package/ci/test-optimization-validation/result-semantics.js +0 -103
  333. package/ci/test-optimization-validation/runner-command.js +0 -264
  334. package/ci/test-optimization-validation/runner-contract.js +0 -695
  335. package/ci/test-optimization-validation/safe-files.js +0 -202
  336. package/ci/test-optimization-validation/scenarios/auto-test-retries.js +0 -171
  337. package/ci/test-optimization-validation/scenarios/basic-reporting.js +0 -407
  338. package/ci/test-optimization-validation/scenarios/ci-wiring.js +0 -666
  339. package/ci/test-optimization-validation/scenarios/early-flake-detection.js +0 -142
  340. package/ci/test-optimization-validation/scenarios/helpers.js +0 -621
  341. package/ci/test-optimization-validation/scenarios/test-management.js +0 -219
  342. package/ci/test-optimization-validation/source-text.js +0 -84
  343. package/ci/test-optimization-validation/static-diagnosis.js +0 -166
  344. package/ci/test-optimization-validation/test-output.js +0 -120
  345. package/ci/test-optimization-validation/validation-blocker.js +0 -21
  346. package/ci/validate-test-optimization.js +0 -3
  347. package/packages/datadog-esbuild/src/resolver.js +0 -284
  348. package/packages/dd-trace/src/ci-visibility/exporters/ci-validation/index.js +0 -156
  349. package/packages/dd-trace/src/ci-visibility/exporters/ci-validation/msgpack-to-json.js +0 -287
  350. package/packages/dd-trace/src/ci-visibility/exporters/ci-validation/payload-projection.js +0 -84
  351. package/packages/dd-trace/src/ci-visibility/exporters/ci-validation/sink.js +0 -368
  352. package/packages/dd-trace/src/ci-visibility/exporters/ci-validation/writer.js +0 -59
  353. package/vendor/dist/@opentelemetry/resources/index.js +0 -1
@@ -0,0 +1,573 @@
1
+ 'use strict'
2
+
3
+ const fs = require('node:fs')
4
+ const Module = require('node:module')
5
+ const path = require('node:path')
6
+
7
+ const { isESMFile } = require('./bundler-utils')
8
+ const extractPackageAndModulePath = require('./extract-package-and-module-path')
9
+ const hooks = require('./hooks')
10
+ const instrumentations = require('./instrumentations')
11
+ const { filename, matchesInstrumentation } = require('./instrumentation-utils')
12
+ const { createBundlerRewriter } = require('./rewriter')
13
+ const {
14
+ getRewriteTarget,
15
+ getRewriteTargetNames,
16
+ } = require('./rewriter/targets')
17
+
18
+ const CHANNEL = 'dd-trace:bundler:load'
19
+ const ARGUMENTS_BINDING = 1
20
+ const MODULE_BINDING = 2
21
+ const REQUIRE_BINDING = 4
22
+ const COMMONJS_BINDINGS = MODULE_BINDING | REQUIRE_BINDING
23
+ const targetPackages = new Set(Object.keys(hooks))
24
+ for (const name of getRewriteTargetNames()) targetPackages.add(name)
25
+ const packagePathPattern = createPackagePathPattern()
26
+ // Process-global on purpose: shared by every bundler integration in the process so each dc
27
+ // module gets one rewriter and each package hook loads once. Keys are absolute paths or names.
28
+ const entrypoints = new Map()
29
+ const loadedHooks = new Set()
30
+ const packageCache = new Map()
31
+ const rewriters = new Map()
32
+
33
+ /**
34
+ * @typedef {'orchestrion-rewrite'|'cjs-publication'|'esm-intercept'|'none'} Classification
35
+ */
36
+
37
+ /**
38
+ * @typedef {object} PackageInfo
39
+ * @property {string} [entrypoint]
40
+ * @property {boolean} esm
41
+ * @property {string} moduleName
42
+ * @property {string} name
43
+ * @property {string} packageJsonPath
44
+ * @property {string} version
45
+ */
46
+
47
+ /**
48
+ * @typedef {object} Target
49
+ * @property {Classification} kind
50
+ * @property {string} nativeResourcePath
51
+ * @property {string} resourcePath
52
+ * @property {PackageInfo} packageInfo
53
+ * @property {Array<{ package: string, path: string, version: string }>} publications
54
+ * @property {import('./rewriter/targets').RewriteTarget} [rewriteTarget]
55
+ */
56
+
57
+ /**
58
+ * Classifies a resolved package file. For ESM package-root hooks, request is the original
59
+ * package specifier: resolving a dual package with require conditions can select a different file.
60
+ * A rewrite classification may still append matching CommonJS publications.
61
+ *
62
+ * Not a pure lookup: it realpaths the file, reads package.json, loads the package's dd-trace hook
63
+ * and, for CommonJS entrypoint candidates, resolves the package entrypoint with Module.createRequire.
64
+ * Results are cached per package, but bundler callers should still gate calls with
65
+ * `packagePathPattern` rather than classifying every module speculatively.
66
+ *
67
+ * @param {{ resourcePath: string, request?: string, warn?: (warning: Error) => void }} options
68
+ * @returns {Classification}
69
+ */
70
+ function classify ({ resourcePath, request, warn }) {
71
+ try {
72
+ return getTarget(resourcePath, true, request)?.kind ?? 'none'
73
+ } catch (error) {
74
+ reportWarning(warn, error)
75
+ return 'none'
76
+ }
77
+ }
78
+
79
+ /**
80
+ * Instruments a resolved foreign Node.js module, or leaves it untouched on error.
81
+ *
82
+ * @param {{ source: string, resourcePath: string, inputSourceMap?: string|object,
83
+ * warn?: (warning: Error) => void }} options
84
+ * @returns {{ code: string, map?: string|object }|undefined}
85
+ */
86
+ /* eslint-disable unicorn/no-useless-undefined -- Explicit optional returns satisfy noImplicitReturns. */
87
+ function instrument ({ source, resourcePath, inputSourceMap, warn }) {
88
+ try {
89
+ const target = getTarget(resourcePath, false)
90
+ if (!target || target.kind === 'none') return undefined
91
+
92
+ const { nativeResourcePath, packageInfo, publications, rewriteTarget } = target
93
+ resourcePath = target.resourcePath
94
+ const esm = packageInfo.esm
95
+ if (publications.length > 0 && hasUnsafeCommonJsBindings(source)) {
96
+ reportWarning(warn, new Error(`Skipped CommonJS publication for unsafe wrapper bindings in ${resourcePath}`))
97
+ return undefined
98
+ }
99
+
100
+ const dcModule = getDcModule(nativeResourcePath)
101
+ let code = source
102
+ let sourceMap = inputSourceMap
103
+ let rewritten = false
104
+ if (rewriteTarget) {
105
+ const rewrite = getRewriter(dcModule)
106
+ const result = rewrite(
107
+ source,
108
+ resourcePath,
109
+ esm ? 'module' : 'commonjs',
110
+ rewriteTarget,
111
+ inputSourceMap
112
+ )
113
+ code = /** @type {string} */ (result.code)
114
+ sourceMap = result.map
115
+ rewritten = code !== source
116
+ }
117
+
118
+ if (publications.length > 0) code = appendCommonJsPublications(code, publications, dcModule)
119
+ if (rewritten && rewriteTarget && publications.length === 0 &&
120
+ (rewriteTarget.activate || hooks[rewriteTarget.moduleName])) {
121
+ if (!esm && hasUnsafeCommonJsBindings(code)) {
122
+ reportWarning(warn, new Error(`Skipped CommonJS activation for unsafe wrapper bindings in ${resourcePath}`))
123
+ return undefined
124
+ }
125
+ code = appendActivation(code, {
126
+ package: rewriteTarget.moduleName,
127
+ path: filename(rewriteTarget.moduleName, rewriteTarget.filePath),
128
+ version: packageInfo.version,
129
+ }, dcModule, esm)
130
+ }
131
+ return { code, map: sourceMap }
132
+ } catch (error) {
133
+ reportWarning(warn, error)
134
+ return undefined
135
+ }
136
+ }
137
+ /* eslint-enable unicorn/no-useless-undefined */
138
+
139
+ /**
140
+ * @param {string} inputPath
141
+ * @param {boolean} includeEsmHooks
142
+ * @param {string} [request]
143
+ * @returns {Target|undefined}
144
+ */
145
+ function getTarget (inputPath, includeEsmHooks, request) {
146
+ const nativeResourcePath = fs.realpathSync(inputPath)
147
+ const resourcePath = nativeResourcePath.replaceAll('\\', '/')
148
+ const extracted = extractPackageAndModulePath(resourcePath)
149
+ if (!extracted.pkg || !targetPackages.has(extracted.pkg)) return
150
+
151
+ const rewriteTarget = getRewriteTarget(resourcePath)
152
+ const packageInfo = getPackageInfo(
153
+ nativeResourcePath,
154
+ extracted.pkg,
155
+ /** @type {string} */ (extracted.path),
156
+ path.normalize(/** @type {string} */ (extracted.pkgJson))
157
+ )
158
+ let publications = []
159
+ if (!packageInfo.esm) {
160
+ publications = getPublications(resourcePath, packageInfo)
161
+ } else if (includeEsmHooks && !rewriteTarget) {
162
+ // instrument() cannot intercept ESM exports, so only classification loads ESM hooks; the
163
+ // bundler that requested it is responsible for intercepting 'esm-intercept' modules.
164
+ publications = getPublications(resourcePath, packageInfo, request)
165
+ }
166
+
167
+ /** @type {Classification} */
168
+ let kind = 'none'
169
+ if (rewriteTarget) {
170
+ kind = 'orchestrion-rewrite'
171
+ } else if (publications.length > 0) {
172
+ kind = packageInfo.esm ? 'esm-intercept' : 'cjs-publication'
173
+ }
174
+ return { kind, nativeResourcePath, resourcePath, packageInfo, publications, rewriteTarget }
175
+ }
176
+
177
+ /**
178
+ * @param {((warning: Error) => void)|undefined} warn
179
+ * @param {unknown} error
180
+ */
181
+ function reportWarning (warn, error) {
182
+ try {
183
+ warn?.(error instanceof Error ? error : new Error(String(error)))
184
+ } catch {
185
+ // A bundler's warning callback must not turn a failed transform into a build failure.
186
+ }
187
+ }
188
+
189
+ /**
190
+ * @param {string} nativeResourcePath
191
+ * @param {string} name
192
+ * @param {string} modulePath
193
+ * @param {string} packageJsonPath
194
+ * @returns {PackageInfo}
195
+ */
196
+ function getPackageInfo (nativeResourcePath, name, modulePath, packageJsonPath) {
197
+ let cached = packageCache.get(packageJsonPath)
198
+ if (!cached) {
199
+ const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, 'utf8'))
200
+ cached = { packageJson, version: packageJson.version }
201
+ packageCache.set(packageJsonPath, cached)
202
+ }
203
+
204
+ return {
205
+ esm: isESMFile(nativeResourcePath, packageJsonPath, cached.packageJson),
206
+ moduleName: filename(name, modulePath),
207
+ name,
208
+ packageJsonPath,
209
+ version: cached.version,
210
+ }
211
+ }
212
+
213
+ /**
214
+ * @param {string} resourcePath
215
+ * @param {PackageInfo} packageInfo
216
+ * @param {string} [request]
217
+ * @returns {Array<{ package: string, path: string, version: string }>}
218
+ */
219
+ function getPublications (resourcePath, packageInfo, request) {
220
+ loadPackageHook(packageInfo.name)
221
+ const entries = instrumentations[packageInfo.name]
222
+ if (!entries) return []
223
+
224
+ const publications = []
225
+ const paths = new Set()
226
+ for (const entry of entries) {
227
+ if (!packageInfo.esm && !entry.file && !entry.filePattern) {
228
+ packageInfo.entrypoint ??= getCommonJsEntrypoint(packageInfo.name, packageInfo.packageJsonPath)
229
+ }
230
+ const isEntrypoint = packageInfo.esm ? request === packageInfo.name : resourcePath === packageInfo.entrypoint
231
+ let moduleName
232
+ if (entry.file || entry.filePattern) {
233
+ moduleName = packageInfo.moduleName
234
+ } else if (isEntrypoint) {
235
+ moduleName = packageInfo.name
236
+ }
237
+ if (!moduleName || paths.has(moduleName) ||
238
+ !matchesInstrumentation(packageInfo.name, packageInfo.version, moduleName, entry)) continue
239
+
240
+ paths.add(moduleName)
241
+ publications.push({ package: packageInfo.name, path: moduleName, version: packageInfo.version })
242
+ }
243
+ return publications
244
+ }
245
+
246
+ /**
247
+ * @param {string} name
248
+ * @param {string} packageJsonPath
249
+ */
250
+ function getCommonJsEntrypoint (name, packageJsonPath) {
251
+ const cached = entrypoints.get(packageJsonPath)
252
+ if (cached) return cached
253
+
254
+ const packageRequire = Module.createRequire(packageJsonPath)
255
+ let entrypoint
256
+ try {
257
+ entrypoint = packageRequire.resolve(name)
258
+ } catch {
259
+ entrypoint = packageRequire.resolve(path.dirname(packageJsonPath))
260
+ }
261
+ const resolved = fs.realpathSync(entrypoint).replaceAll('\\', '/')
262
+ entrypoints.set(packageJsonPath, resolved)
263
+ return resolved
264
+ }
265
+
266
+ /**
267
+ * @param {string} name
268
+ */
269
+ function loadPackageHook (name) {
270
+ if (loadedHooks.has(name)) return
271
+ const hook = hooks[name]
272
+ const load = hook?.fn ?? hook
273
+ if (typeof load === 'function') load()
274
+ loadedHooks.add(name)
275
+ }
276
+
277
+ /**
278
+ * @param {string} dcModule
279
+ * @returns {ReturnType<typeof createBundlerRewriter>}
280
+ */
281
+ function getRewriter (dcModule) {
282
+ const cached = rewriters.get(dcModule)
283
+ if (cached) return cached
284
+ const rewrite = createBundlerRewriter(dcModule)
285
+ rewriters.set(dcModule, rewrite)
286
+ return rewrite
287
+ }
288
+
289
+ /**
290
+ * @param {string} source
291
+ */
292
+ function hasUnsafeCommonJsBindings (source) {
293
+ try {
294
+ const { parse } = require('./rewriter/compiler')
295
+ if (source.startsWith('#!')) source = `//${source.slice(2)}`
296
+ const program = parse(Module.wrap(source))
297
+ const wrapper = program.body[0]?.expression
298
+ return wrapper?.type !== 'FunctionExpression' || hasUnsafeNode(wrapper.body, 0, 0)
299
+ } catch {
300
+ return true
301
+ }
302
+ }
303
+
304
+ /**
305
+ * @param {object} node
306
+ * @param {number} functionDepth
307
+ * @param {number} shadowedBindings
308
+ * @param {object} [parent]
309
+ * @param {string} [parentKey]
310
+ */
311
+ function hasUnsafeNode (node, functionDepth, shadowedBindings, parent, parentKey) {
312
+ if (functionDepth === 0 && hasCommonJsDeclaration(node, parent)) return true
313
+ if (node.type === 'AssignmentExpression' && mutatesCommonJsBinding(node.left, shadowedBindings)) return true
314
+ if (node.type === 'UpdateExpression' && mutatesCommonJsBinding(node.argument, shadowedBindings)) return true
315
+ if ((node.type === 'ForInStatement' || node.type === 'ForOfStatement') &&
316
+ mutatesCommonJsBinding(node.left, shadowedBindings)) return true
317
+ if (node.type === 'CallExpression' && node.callee?.type === 'Identifier' && node.callee.name === 'eval') return true
318
+ if (!(shadowedBindings & ARGUMENTS_BINDING) && node.type === 'Identifier' && node.name === 'arguments' &&
319
+ isReferencedIdentifier(parent, /** @type {string} */ (parentKey))) return true
320
+
321
+ const nestedFunction = node.type === 'ArrowFunctionExpression' || node.type === 'FunctionDeclaration' ||
322
+ node.type === 'FunctionExpression'
323
+ if (nestedFunction) {
324
+ functionDepth++
325
+ shadowedBindings |= getFunctionBindings(node)
326
+ }
327
+ shadowedBindings |= getLexicalBindings(node)
328
+
329
+ for (const key of Object.keys(node)) {
330
+ if ((node.type === 'VariableDeclarator' && key === 'id') ||
331
+ (node.type === 'CatchClause' && key === 'param')) continue
332
+ const value = node[key]
333
+ if (Array.isArray(value)) {
334
+ for (const child of value) {
335
+ if (child?.type && hasUnsafeNode(child, functionDepth, shadowedBindings, node, key)) return true
336
+ }
337
+ } else if (value?.type && hasUnsafeNode(value, functionDepth, shadowedBindings, node, key)) {
338
+ return true
339
+ }
340
+ }
341
+ return false
342
+ }
343
+
344
+ /**
345
+ * @param {object} node
346
+ * @param {object} [parent]
347
+ */
348
+ function hasCommonJsDeclaration (node, parent) {
349
+ if (node.type === 'VariableDeclarator') {
350
+ return parent?.kind === 'var' && Boolean(getBindingMask(node.id) & COMMONJS_BINDINGS)
351
+ }
352
+ if (node.type === 'FunctionDeclaration') {
353
+ return Boolean(getBindingMask(node.id) & COMMONJS_BINDINGS)
354
+ }
355
+ return false
356
+ }
357
+
358
+ /**
359
+ * @param {object} node
360
+ * @param {number} shadowedBindings
361
+ */
362
+ function mutatesCommonJsBinding (node, shadowedBindings) {
363
+ return Boolean(getBindingMask(node) & COMMONJS_BINDINGS & ~shadowedBindings)
364
+ }
365
+
366
+ /**
367
+ * @param {object} node
368
+ */
369
+ function getBindingMask (node) {
370
+ if (!node) return 0
371
+ if (node.type === 'Identifier') {
372
+ if (node.name === 'arguments') return ARGUMENTS_BINDING
373
+ if (node.name === 'module') return MODULE_BINDING
374
+ return node.name === 'require' ? REQUIRE_BINDING : 0
375
+ }
376
+ if (node.type === 'AssignmentPattern') return getBindingMask(node.left)
377
+ if (node.type === 'RestElement') return getBindingMask(node.argument)
378
+ if (node.type === 'ArrayPattern') {
379
+ let bindings = 0
380
+ for (const element of node.elements) bindings |= getBindingMask(element)
381
+ return bindings
382
+ }
383
+ if (node.type === 'ObjectPattern') {
384
+ let bindings = 0
385
+ for (const property of node.properties) {
386
+ bindings |= getBindingMask(property.type === 'RestElement' ? property.argument : property.value)
387
+ }
388
+ return bindings
389
+ }
390
+ return 0
391
+ }
392
+
393
+ /**
394
+ * @param {object} node
395
+ */
396
+ function getFunctionBindings (node) {
397
+ let bindings = node.type === 'ArrowFunctionExpression' ? 0 : ARGUMENTS_BINDING
398
+ bindings |= getBindingMask(node.id)
399
+ for (const param of node.params) bindings |= getBindingMask(param)
400
+ return bindings | getVarBindings(node.body)
401
+ }
402
+
403
+ /**
404
+ * @param {object} node
405
+ */
406
+ function getVarBindings (node) {
407
+ if (node.type === 'ArrowFunctionExpression' || node.type === 'FunctionDeclaration' ||
408
+ node.type === 'FunctionExpression' || node.type === 'ClassDeclaration' || node.type === 'ClassExpression') return 0
409
+
410
+ let bindings = 0
411
+ if (node.type === 'VariableDeclaration' && node.kind === 'var') {
412
+ for (const declaration of node.declarations) bindings |= getBindingMask(declaration.id)
413
+ }
414
+ for (const key of Object.keys(node)) {
415
+ const value = node[key]
416
+ if (Array.isArray(value)) {
417
+ for (const child of value) {
418
+ if (child?.type) bindings |= getVarBindings(child)
419
+ }
420
+ } else if (value?.type) {
421
+ bindings |= getVarBindings(value)
422
+ }
423
+ }
424
+ return bindings
425
+ }
426
+
427
+ /**
428
+ * @param {object} node
429
+ */
430
+ function getLexicalBindings (node) {
431
+ let bindings = 0
432
+ if (node.type === 'BlockStatement') {
433
+ for (const statement of node.body) bindings |= getStatementBindings(statement)
434
+ } else if (node.type === 'SwitchStatement') {
435
+ for (const switchCase of node.cases) {
436
+ for (const statement of switchCase.consequent) bindings |= getStatementBindings(statement)
437
+ }
438
+ } else if (node.type === 'CatchClause') {
439
+ bindings = getBindingMask(node.param)
440
+ } else if (node.type === 'ForStatement') {
441
+ bindings = getLexicalDeclarationBindings(node.init)
442
+ } else if (node.type === 'ForInStatement' || node.type === 'ForOfStatement') {
443
+ bindings = getLexicalDeclarationBindings(node.left)
444
+ } else if (node.type === 'ClassExpression') {
445
+ bindings = getBindingMask(node.id)
446
+ }
447
+ return bindings
448
+ }
449
+
450
+ /**
451
+ * @param {object} node
452
+ */
453
+ function getStatementBindings (node) {
454
+ if (node.type === 'VariableDeclaration') return getLexicalDeclarationBindings(node)
455
+ if (node.type === 'FunctionDeclaration' || node.type === 'ClassDeclaration') return getBindingMask(node.id)
456
+ return 0
457
+ }
458
+
459
+ /**
460
+ * @param {object} [node]
461
+ */
462
+ function getLexicalDeclarationBindings (node) {
463
+ if (node?.type !== 'VariableDeclaration' || node.kind === 'var') return 0
464
+ let bindings = 0
465
+ for (const declaration of node.declarations) bindings |= getBindingMask(declaration.id)
466
+ return bindings
467
+ }
468
+
469
+ /**
470
+ * @param {object} parent
471
+ * @param {string} parentKey
472
+ */
473
+ function isReferencedIdentifier (parent, parentKey) {
474
+ if (parent.type === 'MemberExpression' && parentKey === 'property' && !parent.computed) return false
475
+ if ((parent.type === 'Property' || parent.type === 'MethodDefinition' || parent.type === 'PropertyDefinition') &&
476
+ parentKey === 'key' && !parent.computed) {
477
+ return parent.type === 'Property' && parent.shorthand
478
+ }
479
+ return parentKey !== 'label'
480
+ }
481
+
482
+ /**
483
+ * @param {string} source
484
+ * @param {Array<{ package: string, path: string, version: string }>} payloads
485
+ * @param {string} dcModule
486
+ */
487
+ function appendCommonJsPublications (source, payloads, dcModule) {
488
+ let publications = ''
489
+ let index = 0
490
+ for (const payload of payloads) {
491
+ publications += ` const payload${index} = {
492
+ module: module.exports,
493
+ package: ${JSON.stringify(payload.package)},
494
+ path: ${JSON.stringify(payload.path)},
495
+ version: ${JSON.stringify(payload.version)},
496
+ }
497
+ channel.publish(payload${index})
498
+ module.exports = payload${index++}.module
499
+ `
500
+ }
501
+
502
+ return `${source}
503
+ {
504
+ const dc = require(${JSON.stringify(dcModule)})
505
+ const channel = dc.channel('${CHANNEL}')
506
+ if (channel.hasSubscribers) {
507
+ ${publications} }
508
+ }
509
+ `
510
+ }
511
+
512
+ /**
513
+ * @param {string} source
514
+ * @param {{ package: string, path: string, version: string }} payload
515
+ * @param {string} dcModule
516
+ * @param {boolean} esm
517
+ */
518
+ function appendActivation (source, payload, dcModule, esm) {
519
+ if (esm) {
520
+ return `${source}
521
+ import ddTraceBundlerDc from ${JSON.stringify(dcModule)}
522
+ {
523
+ const channel = ddTraceBundlerDc.channel('${CHANNEL}')
524
+ if (channel.hasSubscribers) channel.publish(${JSON.stringify({ activate: true, ...payload })})
525
+ }
526
+ `
527
+ }
528
+
529
+ return `${source}
530
+ {
531
+ const dc = require(${JSON.stringify(dcModule)})
532
+ const channel = dc.channel('${CHANNEL}')
533
+ if (channel.hasSubscribers) channel.publish(${JSON.stringify({ activate: true, ...payload })})
534
+ }
535
+ `
536
+ }
537
+
538
+ /**
539
+ * Matches paths containing a directory named after a target package. Bundlers use it as a cheap
540
+ * prefilter; the instrumentation still resolves the real package before changing a file.
541
+ *
542
+ * @returns {RegExp}
543
+ */
544
+ function createPackagePathPattern () {
545
+ const builtins = new Set(Module.builtinModules)
546
+ const names = []
547
+ for (const name of targetPackages) {
548
+ if (!name.startsWith('.') && !builtins.has(name)) names.push(escapeRegExp(name))
549
+ }
550
+ names.sort()
551
+ return new RegExp(`(?:^|/)(?:${names.join('|')})(?:/|$)`)
552
+ }
553
+
554
+ /**
555
+ * @param {string} value
556
+ */
557
+ function escapeRegExp (value) {
558
+ return value.replaceAll(/[.*+?^${}()|[\]\\]/g, String.raw`\$&`)
559
+ }
560
+
561
+ /**
562
+ * @param {string} nativeResourcePath
563
+ */
564
+ function getDcModule (nativeResourcePath) {
565
+ let value = path.relative(path.dirname(nativeResourcePath), require.resolve('dc-polyfill')).replaceAll('\\', '/')
566
+ if (path.isAbsolute(value) || path.win32.isAbsolute(value)) {
567
+ throw new Error(`Cannot create a relative diagnostic-channel import from ${nativeResourcePath}`)
568
+ }
569
+ if (!value.startsWith('./') && !value.startsWith('../')) value = `./${value}`
570
+ return value
571
+ }
572
+
573
+ module.exports = { classify, instrument, packagePathPattern }
@@ -0,0 +1,104 @@
1
+ 'use strict'
2
+
3
+ const { execSync } = require('node:child_process')
4
+ const fs = require('node:fs')
5
+ const path = require('node:path')
6
+
7
+ /**
8
+ * @typedef {{ debug: (...args: unknown[]) => void, warn: (...args: unknown[]) => void }} BundlerLog
9
+ */
10
+
11
+ /**
12
+ * Determines if a file is a ESM module or CommonJS
13
+ *
14
+ * @param {string} fullPathToModule File to analyze
15
+ * @param {string} [modulePackageJsonPath] Path of the package.json
16
+ * @param {object} [packageJson] The content of the module package.json
17
+ */
18
+ function isESMFile (fullPathToModule, modulePackageJsonPath, packageJson = {}) {
19
+ if (fullPathToModule.endsWith('.mjs') || fullPathToModule.endsWith('.mts')) return true
20
+ if (fullPathToModule.endsWith('.cjs') || fullPathToModule.endsWith('.cts')) return false
21
+
22
+ const pathParts = fullPathToModule.split(path.sep)
23
+ do {
24
+ pathParts.pop()
25
+
26
+ const packageJsonPath = [...pathParts, 'package.json'].join(path.sep)
27
+ if (packageJsonPath === modulePackageJsonPath) {
28
+ return packageJson.type === 'module'
29
+ }
30
+
31
+ try {
32
+ const packageJsonContent = fs.readFileSync(packageJsonPath).toString()
33
+ const packageJson = JSON.parse(packageJsonContent)
34
+ return packageJson.type === 'module'
35
+ } catch {
36
+ // file does not exit, continue
37
+ }
38
+ } while (pathParts.length > 0)
39
+
40
+ return packageJson.type === 'module'
41
+ }
42
+
43
+ /**
44
+ * Reads the repository URL and commit SHA of the current working directory.
45
+ *
46
+ * @param {BundlerLog} log
47
+ * @returns {{ repositoryURL: string | null, commitSHA: string | null }}
48
+ */
49
+ function getGitMetadata (log) {
50
+ /** @type {{ repositoryURL: string | null, commitSHA: string | null }} */
51
+ const gitMetadata = {
52
+ repositoryURL: null,
53
+ commitSHA: null,
54
+ }
55
+
56
+ try {
57
+ gitMetadata.repositoryURL = execSync('git config --get remote.origin.url', {
58
+ encoding: 'utf8',
59
+ stdio: ['pipe', 'pipe', 'ignore'],
60
+ cwd: process.cwd(),
61
+ }).trim()
62
+ } catch (e) {
63
+ log.warn('failed to get git repository URL:', e.message)
64
+ }
65
+
66
+ try {
67
+ gitMetadata.commitSHA = execSync('git rev-parse HEAD', {
68
+ encoding: 'utf8',
69
+ stdio: ['pipe', 'pipe', 'ignore'],
70
+ cwd: process.cwd(),
71
+ }).trim()
72
+ } catch (e) {
73
+ log.warn('failed to get git commit SHA:', e.message)
74
+ }
75
+
76
+ return gitMetadata
77
+ }
78
+
79
+ /**
80
+ * Returns a script setting `DD_GIT_REPOSITORY_URL` and `DD_GIT_COMMIT_SHA` from the git metadata of the current working
81
+ * directory, to prepend to the entry chunks of a bundle. Returns an empty string when no metadata is available.
82
+ *
83
+ * @param {BundlerLog} log
84
+ */
85
+ function getGitMetadataBanner (log) {
86
+ const { repositoryURL, commitSHA } = getGitMetadata(log)
87
+ if (!repositoryURL && !commitSHA) {
88
+ log.warn('No git metadata available - skipping injection')
89
+ return ''
90
+ }
91
+
92
+ log.debug(
93
+ 'Automatically injected git metadata (DD_GIT_REPOSITORY_URL: %s, DD_GIT_COMMIT_SHA: %s)',
94
+ repositoryURL || 'not available',
95
+ commitSHA || 'not available'
96
+ )
97
+ return 'if (typeof process === \'object\' && process !== null &&\n' +
98
+ ' process.env !== null && typeof process.env === \'object\') {\n' +
99
+ (repositoryURL ? ` process.env.DD_GIT_REPOSITORY_URL = ${JSON.stringify(repositoryURL)};\n` : '') +
100
+ (commitSHA ? ` process.env.DD_GIT_COMMIT_SHA = ${JSON.stringify(commitSHA)};\n` : '') +
101
+ '}\n'
102
+ }
103
+
104
+ module.exports = { getGitMetadataBanner, isESMFile }
@@ -19,8 +19,12 @@ exports.createWrapFetch = function createWrapFetch (Request, ch, onLoad) {
19
19
  }
20
20
  const req = new Request(input, init)
21
21
  const ctx = { req }
22
+ const signal = init?.signal
22
23
 
23
- return ch.tracePromise(() => fetch.call(this, req), ctx)
24
+ // The signal of `req` only weakly follows `init.signal` and is collected once `req` is unreachable, which
25
+ // stops aborts from reaching the in-flight request. Passing it again lets `fetch` follow it directly.
26
+ const options = signal ? { signal, referrer: req.referrer, referrerPolicy: req.referrerPolicy } : undefined
27
+ return ch.tracePromise(() => fetch.call(this, req, options), ctx)
24
28
  }
25
29
  }
26
30
  }