dd-trace 5.133.0 → 5.135.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 (194) hide show
  1. package/LICENSE-3rdparty.csv +0 -1
  2. package/ci/cypress/support.js +15 -1
  3. package/ci/diagnose.js +4 -4
  4. package/ci/test-annotations.d.ts +5 -0
  5. package/ci/test-annotations.js +5 -0
  6. package/ci/test-optimization-validation/approval-artifacts.js +2 -2
  7. package/ci/test-optimization-validation/approval.js +2 -2
  8. package/ci/test-optimization-validation/artifact-id.js +2 -3
  9. package/ci/test-optimization-validation/ci-package-scripts.js +1 -1
  10. package/ci/test-optimization-validation/cli.js +1 -1
  11. package/ci/test-optimization-validation/command-runner.js +2 -3
  12. package/ci/test-optimization-validation/executable.js +1 -1
  13. package/ci/test-optimization-validation/framework-adapters/cucumber.js +1 -1
  14. package/ci/test-optimization-validation/literal-environment.js +2 -2
  15. package/ci/test-optimization-validation/manifest-scaffold.js +1 -1
  16. package/ci/test-optimization-validation/offline-fixtures.js +1 -1
  17. package/ci/test-optimization-validation/redaction.js +3 -3
  18. package/ci/test-optimization-validation/runner-contract.js +10 -10
  19. package/ci/test-optimization-validation/scenarios/ci-wiring.js +1 -1
  20. package/ci/vitest-no-worker-init-annotations.mjs +4 -0
  21. package/ci/vitest-no-worker-init-node-setup.mjs +22 -0
  22. package/ci/vitest-no-worker-init-runner-setup.mjs +7 -5
  23. package/ci/vitest-no-worker-init-setup.mjs +34 -12
  24. package/ci/vitest-no-worker-init-v5-setup.mjs +6 -0
  25. package/ext/exporters.js +1 -0
  26. package/index.d.ts +35 -5
  27. package/loader-hook.mjs +53 -0
  28. package/openfeature/exposure-hook.d.ts +66 -0
  29. package/openfeature/exposure-hook.js +5 -0
  30. package/package.json +23 -20
  31. package/packages/datadog-core/src/storage.js +1 -1
  32. package/packages/datadog-esbuild/index.js +70 -7
  33. package/packages/datadog-instrumentations/index.js +2 -1
  34. package/packages/datadog-instrumentations/src/cucumber.js +64 -21
  35. package/packages/datadog-instrumentations/src/cypress-config.js +163 -15
  36. package/packages/datadog-instrumentations/src/graphql.js +9 -3
  37. package/packages/datadog-instrumentations/src/grpc/server.js +23 -6
  38. package/packages/datadog-instrumentations/src/helpers/bundler-register.js +27 -8
  39. package/packages/datadog-instrumentations/src/helpers/fetch.js +5 -1
  40. package/packages/datadog-instrumentations/src/helpers/graphql-jit-runtime.js +30 -8
  41. package/packages/datadog-instrumentations/src/helpers/hooks.js +2 -1
  42. package/packages/datadog-instrumentations/src/helpers/register.js +9 -0
  43. package/packages/datadog-instrumentations/src/helpers/rewriter/index.js +16 -6
  44. package/packages/datadog-instrumentations/src/helpers/rewriter/instrumentation-registry.js +10 -0
  45. package/packages/datadog-instrumentations/src/helpers/rewriter/instrumentations/graphql-jit.js +3 -1
  46. package/packages/datadog-instrumentations/src/helpers/rewriter/instrumentations/jest.js +12 -0
  47. package/packages/datadog-instrumentations/src/helpers/rewriter/instrumentations/react-router.js +49 -0
  48. package/packages/datadog-instrumentations/src/helpers/rewriter/instrumentations/typesafe.js +23 -0
  49. package/packages/datadog-instrumentations/src/helpers/rewriter/instrumentations/vitest.js +8 -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 +8 -0
  52. package/packages/datadog-instrumentations/src/helpers/rewriter/targets.js +19 -2
  53. package/packages/datadog-instrumentations/src/helpers/rewriter/targets.json +13 -0
  54. package/packages/datadog-instrumentations/src/helpers/rewriter/transforms.js +1 -1
  55. package/packages/datadog-instrumentations/src/jest.js +332 -137
  56. package/packages/datadog-instrumentations/src/mariadb-bundle.js +69 -11
  57. package/packages/datadog-instrumentations/src/mariadb.js +13 -6
  58. package/packages/datadog-instrumentations/src/mocha/common.js +89 -8
  59. package/packages/datadog-instrumentations/src/mocha/main.js +11 -2
  60. package/packages/datadog-instrumentations/src/mocha/utils.js +92 -13
  61. package/packages/datadog-instrumentations/src/mocha/worker.js +1 -1
  62. package/packages/datadog-instrumentations/src/nova-sonic/session.js +25 -16
  63. package/packages/datadog-instrumentations/src/oracledb.js +33 -0
  64. package/packages/datadog-instrumentations/src/pg.js +2 -1
  65. package/packages/datadog-instrumentations/src/playwright.js +81 -26
  66. package/packages/datadog-instrumentations/src/react-router.js +106 -0
  67. package/packages/datadog-instrumentations/src/stripe.js +23 -12
  68. package/packages/datadog-instrumentations/src/typesafe.js +89 -0
  69. package/packages/datadog-instrumentations/src/vitest-main-no-worker-init.js +84 -47
  70. package/packages/datadog-instrumentations/src/vitest-main.js +33 -3
  71. package/packages/datadog-instrumentations/src/vitest-test-annotations.js +20 -0
  72. package/packages/datadog-instrumentations/src/vitest-util.js +5 -2
  73. package/packages/datadog-instrumentations/src/vitest-worker.js +39 -17
  74. package/packages/datadog-instrumentations/src/vitest.js +16 -6
  75. package/packages/datadog-plugin-cucumber/src/index.js +5 -0
  76. package/packages/datadog-plugin-cypress/src/cypress-plugin.js +277 -44
  77. package/packages/datadog-plugin-cypress/src/index.js +1 -1
  78. package/packages/datadog-plugin-cypress/src/lifecycle-owner.js +20 -0
  79. package/packages/datadog-plugin-cypress/src/plugin.js +10 -0
  80. package/packages/datadog-plugin-cypress/src/retry-config-observer.js +281 -0
  81. package/packages/datadog-plugin-cypress/src/setup-handoff.js +125 -0
  82. package/packages/datadog-plugin-cypress/src/support.js +1217 -437
  83. package/packages/datadog-plugin-graphql/src/execute.js +2 -2
  84. package/packages/datadog-plugin-graphql/src/utils.js +5 -5
  85. package/packages/datadog-plugin-jest/src/index.js +25 -3
  86. package/packages/datadog-plugin-mocha/src/index.js +47 -6
  87. package/packages/datadog-plugin-oracledb/src/connection-parser.js +21 -11
  88. package/packages/datadog-plugin-playwright/src/index.js +4 -0
  89. package/packages/datadog-plugin-react-router/src/index.js +118 -0
  90. package/packages/datadog-plugin-typesafe/src/index.js +17 -0
  91. package/packages/datadog-plugin-typesafe/src/tracing.js +31 -0
  92. package/packages/datadog-plugin-vitest/src/index.js +8 -0
  93. package/packages/dd-trace/src/agent/info.js +2 -1
  94. package/packages/dd-trace/src/aiguard/evaluation.js +143 -1
  95. package/packages/dd-trace/src/aiguard/sdk.js +0 -11
  96. package/packages/dd-trace/src/appsec/iast/path-line.js +2 -1
  97. package/packages/dd-trace/src/appsec/stack_trace.js +3 -2
  98. package/packages/dd-trace/src/ci-visibility/dynamic-instrumentation/worker/index.js +3 -2
  99. package/packages/dd-trace/src/ci-visibility/early-flake-detection/get-known-tests.js +9 -16
  100. package/packages/dd-trace/src/ci-visibility/exporters/ci-visibility-exporter.js +4 -2
  101. package/packages/dd-trace/src/ci-visibility/intelligent-test-runner/get-skippable-suites.js +9 -16
  102. package/packages/dd-trace/src/ci-visibility/requests/get-library-configuration.js +9 -14
  103. package/packages/dd-trace/src/ci-visibility/requests/route.js +44 -0
  104. package/packages/dd-trace/src/ci-visibility/telemetry-logs.js +5 -0
  105. package/packages/dd-trace/src/ci-visibility/test-annotations.js +72 -0
  106. package/packages/dd-trace/src/ci-visibility/test-declaration-annotations.js +170 -0
  107. package/packages/dd-trace/src/ci-visibility/test-management/get-test-management-tests.js +9 -16
  108. package/packages/dd-trace/src/config/defaults.js +4 -3
  109. package/packages/dd-trace/src/config/generated-config-types.d.ts +6 -0
  110. package/packages/dd-trace/src/config/index.js +140 -39
  111. package/packages/dd-trace/src/config/parsers.js +9 -1
  112. package/packages/dd-trace/src/config/supported-configurations.json +25 -0
  113. package/packages/dd-trace/src/debugger/devtools_client/breakpoints.js +6 -5
  114. package/packages/dd-trace/src/debugger/devtools_client/condition.js +5 -5
  115. package/packages/dd-trace/src/debugger/devtools_client/snapshot/collector.js +4 -6
  116. package/packages/dd-trace/src/debugger/probe_sampler.js +6 -6
  117. package/packages/dd-trace/src/debugger/unsupported-runtime.js +16 -0
  118. package/packages/dd-trace/src/encode/0.4.js +2 -2
  119. package/packages/dd-trace/src/esm-module-load.js +58 -0
  120. package/packages/dd-trace/src/exporter.js +25 -6
  121. package/packages/dd-trace/src/exporters/agent/index.js +3 -1
  122. package/packages/dd-trace/src/exporters/agentless/index.js +3 -1
  123. package/packages/dd-trace/src/exporters/common/request.js +4 -4
  124. package/packages/dd-trace/src/exporters/llmobs/index.js +135 -0
  125. package/packages/dd-trace/src/exporters/log/index.js +4 -3
  126. package/packages/dd-trace/src/llmobs/agent-manifest.js +19 -2
  127. package/packages/dd-trace/src/llmobs/constants/tags.js +4 -0
  128. package/packages/dd-trace/src/llmobs/experiments/index.js +2 -3
  129. package/packages/dd-trace/src/llmobs/experiments/noop.js +5 -2
  130. package/packages/dd-trace/src/llmobs/index.js +13 -2
  131. package/packages/dd-trace/src/llmobs/plugins/claude-agent-sdk/index.js +1 -1
  132. package/packages/dd-trace/src/llmobs/plugins/genai/index.js +1 -1
  133. package/packages/dd-trace/src/llmobs/plugins/genai/util.js +8 -4
  134. package/packages/dd-trace/src/llmobs/plugins/openai/constants.js +5 -0
  135. package/packages/dd-trace/src/llmobs/plugins/openai/index.js +9 -1
  136. package/packages/dd-trace/src/llmobs/plugins/typesafe/index.js +102 -0
  137. package/packages/dd-trace/src/llmobs/prompts/cache.js +3 -1
  138. package/packages/dd-trace/src/llmobs/sdk.js +17 -5
  139. package/packages/dd-trace/src/llmobs/span_processor.js +222 -12
  140. package/packages/dd-trace/src/llmobs/tagger.js +21 -8
  141. package/packages/dd-trace/src/llmobs/util.js +10 -4
  142. package/packages/dd-trace/src/llmobs/writers/util.js +3 -3
  143. package/packages/dd-trace/src/log/writer.js +7 -1
  144. package/packages/dd-trace/src/openfeature/agentless_configuration_source.js +64 -6
  145. package/packages/dd-trace/src/openfeature/configuration_source.js +18 -2
  146. package/packages/dd-trace/src/openfeature/debug-logging-hook.js +66 -3
  147. package/packages/dd-trace/src/openfeature/exposure-hook.js +185 -0
  148. package/packages/dd-trace/src/openfeature/flagging_provider.js +39 -13
  149. package/packages/dd-trace/src/openfeature/index.js +6 -0
  150. package/packages/dd-trace/src/openfeature/remote_config.js +16 -3
  151. package/packages/dd-trace/src/openfeature/writers/base.js +62 -27
  152. package/packages/dd-trace/src/openfeature/writers/exposures.js +161 -1
  153. package/packages/dd-trace/src/openfeature/writers/flag-eval-evp-hook.js +5 -0
  154. package/packages/dd-trace/src/openfeature/writers/flag-evaluation-aggregation.js +9 -4
  155. package/packages/dd-trace/src/openfeature/writers/flag-evaluation-payload.js +2 -0
  156. package/packages/dd-trace/src/openfeature/writers/flag-evaluation-pii.js +2 -0
  157. package/packages/dd-trace/src/openfeature/writers/split-features.js +25 -0
  158. package/packages/dd-trace/src/openfeature/writers/util.js +4 -4
  159. package/packages/dd-trace/src/opentelemetry/metrics/periodic_metric_reader.js +2 -2
  160. package/packages/dd-trace/src/opentelemetry/trace/otlp_transformer.js +18 -1
  161. package/packages/dd-trace/src/opentelemetry/tracer_provider.js +5 -1
  162. package/packages/dd-trace/src/opentracing/tracer.js +9 -13
  163. package/packages/dd-trace/src/otel-thread-ctx.js +47 -21
  164. package/packages/dd-trace/src/plugin_manager.js +1 -2
  165. package/packages/dd-trace/src/plugins/ci_plugin.js +4 -4
  166. package/packages/dd-trace/src/plugins/index.js +3 -0
  167. package/packages/dd-trace/src/plugins/tracing.js +1 -2
  168. package/packages/dd-trace/src/plugins/util/git.js +102 -40
  169. package/packages/dd-trace/src/plugins/util/http-otel-semantics.js +2 -4
  170. package/packages/dd-trace/src/plugins/util/stacktrace.js +2 -1
  171. package/packages/dd-trace/src/plugins/util/test.js +28 -6
  172. package/packages/dd-trace/src/plugins/util/web.js +106 -20
  173. package/packages/dd-trace/src/process-tags/index.js +1 -1
  174. package/packages/dd-trace/src/profiling/config.js +6 -3
  175. package/packages/dd-trace/src/proxy.js +15 -4
  176. package/packages/dd-trace/src/serverless.js +3 -2
  177. package/packages/dd-trace/src/span_processor.js +21 -9
  178. package/packages/dd-trace/src/span_stats.js +32 -3
  179. package/packages/dd-trace/src/startup-log.js +2 -1
  180. package/packages/dd-trace/src/tagger.js +7 -5
  181. package/packages/dd-trace/src/telemetry/dependencies.js +4 -0
  182. package/packages/dd-trace/src/telemetry/index.js +3 -0
  183. package/packages/dd-trace/src/telemetry/logs/index.js +21 -2
  184. package/packages/dd-trace/src/telemetry/logs/log-collector.js +2 -1
  185. package/packages/dd-trace/src/telemetry/telemetry.js +10 -3
  186. package/packages/dd-trace/src/util.js +9 -5
  187. package/register.js +2 -1
  188. package/vendor/dist/@apm-js-collab/code-transformer/index.js +8 -8
  189. package/vendor/dist/@datadog/openfeature-node-server/index.js +1 -1
  190. package/vendor/dist/@datadog/openfeature-node-server/rules-based/index.d.ts +78 -0
  191. package/vendor/dist/@datadog/openfeature-node-server/rules-based/index.js +1 -1
  192. package/vendor/dist/@opentelemetry/core/index.js +1 -1
  193. package/vendor/dist/@opentelemetry/resources/LICENSE +0 -201
  194. package/vendor/dist/@opentelemetry/resources/index.js +0 -1
@@ -2,6 +2,7 @@
2
2
 
3
3
  const { getEnvironmentVariable, getValueFromEnvSources } = require('./config/helper')
4
4
 
5
+ const IS_AWS_LAMBDA = getEnvironmentVariable('AWS_LAMBDA_FUNCTION_NAME') !== undefined
5
6
  const IS_AWS_LAMBDA_MICROVM = getEnvironmentVariable('AWS_LAMBDA_MICROVM_IMAGE_ARN') !== undefined
6
7
  // Standard Lambda, whose sandbox freezes between invocations. Excludes Lambda Lite (native-http),
7
8
  // Managed Instances (lambda-managed-instances) and MicroVMs.
@@ -46,11 +47,10 @@ function getIsFlexConsumptionAzureFunction () {
46
47
  }
47
48
 
48
49
  function isInServerlessEnvironment () {
49
- const inAWSLambda = getEnvironmentVariable('AWS_LAMBDA_FUNCTION_NAME') !== undefined
50
50
  const isGCPFunction = getIsGCPFunction()
51
51
  const isAzureFunction = getIsAzureFunction()
52
52
 
53
- return IS_AWS_LAMBDA_MICROVM || inAWSLambda || isGCPFunction || isAzureFunction
53
+ return IS_AWS_LAMBDA_MICROVM || IS_AWS_LAMBDA || isGCPFunction || isAzureFunction
54
54
  }
55
55
 
56
56
  /**
@@ -112,6 +112,7 @@ module.exports = {
112
112
  enableGCPPubSubPushSubscription,
113
113
  getIsFlexConsumptionAzureFunction,
114
114
  initializeServerlessTelemetry,
115
+ IS_AWS_LAMBDA,
115
116
  IS_AWS_LAMBDA_MICROVM,
116
117
  IS_STANDARD_AWS_LAMBDA,
117
118
  // true only for a Node that bundles its own OpenSSL, whose CSPRNG keeps the snapshot's DRBG
@@ -1,7 +1,10 @@
1
1
  'use strict'
2
2
 
3
+ const { channel } = require('dc-polyfill')
4
+
3
5
  const { AUTO_KEEP, AUTO_REJECT } = require('../../../ext/priority')
4
6
  const log = require('./log')
7
+ const { usesOtlpTraceExporter } = require('./exporter')
5
8
  const spanFormat = require('./span_format')
6
9
  const SpanSampler = require('./span_sampler')
7
10
  const GitMetadataTagger = require('./git_metadata_tagger')
@@ -10,6 +13,8 @@ const { applyHttpOtelSemantics } = require('./plugins/util/http-otel-semantics')
10
13
  const TraceState = require('./opentracing/propagation/tracestate')
11
14
  const { APM_TRACING_ENABLED_KEY, SDK_OTLP_EXPORT_KEY } = require('./constants')
12
15
 
16
+ const traceSampledCh = channel('dd-trace:trace:sampled')
17
+
13
18
  const startedSpans = new WeakSet()
14
19
  const finishedSpans = new WeakSet()
15
20
 
@@ -26,12 +31,12 @@ function serializeOtlpTraceState (context) {
26
31
  class SpanProcessor {
27
32
  #exportOtlpTraces
28
33
 
29
- constructor (exporter, prioritySampler, config, otlpStatsExporter, exportOtlpTraces) {
34
+ constructor (exporter, prioritySampler, config, otlpStatsExporter) {
30
35
  this._exporter = exporter
31
36
  this._prioritySampler = prioritySampler
32
37
  this._config = config
33
38
  this._killAll = false
34
- this.#exportOtlpTraces = exportOtlpTraces
39
+ this.#exportOtlpTraces = usesOtlpTraceExporter(config)
35
40
 
36
41
  if (config.stats?.DD_TRACE_STATS_COMPUTATION_ENABLED &&
37
42
  !config.appsec?.DD_EXPERIMENTAL_APPSEC_STANDALONE_ENABLED) {
@@ -45,7 +50,6 @@ class SpanProcessor {
45
50
  this._processTags = config.DD_EXPERIMENTAL_PROPAGATE_PROCESS_TAGS_ENABLED
46
51
  ? processTags.serialized
47
52
  : false
48
- this._nativeExport = config.OTEL_TRACES_EXPORTER !== 'otlp'
49
53
  }
50
54
 
51
55
  sample (span) {
@@ -83,9 +87,18 @@ class SpanProcessor {
83
87
  this.sample(span)
84
88
  this._gitMetadataTagger.tagGitMetadata(spanContext)
85
89
 
90
+ const discard = this.#isDiscarded(spanContext)
91
+ const willExport = !discard && trace.isRecording !== false
92
+
93
+ if (traceSampledCh.hasSubscribers) {
94
+ traceSampledCh.publish({
95
+ spans: finished,
96
+ willExport,
97
+ })
98
+ }
99
+
86
100
  let isFirstSpanInChunk = true
87
101
  const stampApmDisabled = this._config.apmTracingEnabled === false
88
- const discard = this.#isDiscarded(spanContext)
89
102
  const exportOtlpTraces = this.#exportOtlpTraces && !(spanContext._sampling.priority < AUTO_KEEP)
90
103
  let traceState
91
104
 
@@ -102,21 +115,20 @@ class SpanProcessor {
102
115
  formattedSpan.metrics[APM_TRACING_ENABLED_KEY] = 0
103
116
  }
104
117
  // Stamped after formatting so a span tag with the same key can't override it.
105
- if (isFirstSpanInChunk && this._nativeExport) {
118
+ if (isFirstSpanInChunk && !this.#exportOtlpTraces) {
106
119
  formattedSpan.meta[SDK_OTLP_EXPORT_KEY] = 'false'
107
120
  }
108
121
  isFirstSpanInChunk = false
109
- // Span stats read Datadog HTTP tag names from the formatted span, so
110
- // record them before the OTel rename — an export-only transform.
111
- this._stats?.onSpanFinished(formattedSpan)
112
122
  if (this._config.DD_TRACE_OTEL_SEMANTICS_ENABLED) {
113
123
  applyHttpOtelSemantics(formattedSpan)
114
124
  }
125
+ // Trace metrics must aggregate the same names and attributes the OTLP exporter emits.
126
+ this._stats?.onSpanFinished(formattedSpan)
115
127
  formatted.push(formattedSpan)
116
128
  }
117
129
  }
118
130
 
119
- if (!discard && formatted.length !== 0 && trace.isRecording !== false) {
131
+ if (willExport && formatted.length !== 0) {
120
132
  this._exporter.export(formatted)
121
133
  }
122
134
 
@@ -100,16 +100,42 @@ class SpanAggStats {
100
100
  }
101
101
  }
102
102
 
103
+ /**
104
+ * Accept canonical decimal strings or numbers in the non-negative int32 range.
105
+ *
106
+ * @param {unknown} value
107
+ */
108
+ function toStatusCode (value) {
109
+ if (typeof value === 'number') return value === (value | 0) && value >= 0 ? value : undefined
110
+ if (typeof value !== 'string') return
111
+
112
+ const integer = Number(value) | 0
113
+ return integer >= 0 && String(integer) === value ? integer : undefined
114
+ }
115
+
116
+ /**
117
+ * @param {import('./span_format').FormattedSpan} span
118
+ */
119
+ function httpStatusCode (span) {
120
+ const datadogStatus = span.meta[HTTP_STATUS_CODE]
121
+ if (datadogStatus) return datadogStatus
122
+
123
+ const otelMetaStatus = toStatusCode(span.meta['http.response.status_code'])
124
+ if (otelMetaStatus !== undefined) return otelMetaStatus
125
+
126
+ return toStatusCode(span.metrics?.['http.response.status_code']) ?? 0
127
+ }
128
+
103
129
  class SpanAggKey {
104
130
  constructor (span) {
105
131
  this.name = span.name || DEFAULT_SPAN_NAME
106
132
  this.service = span.service || DEFAULT_SERVICE_NAME
107
133
  this.resource = span.resource || ''
108
134
  this.type = span.type || ''
109
- this.statusCode = span.meta[HTTP_STATUS_CODE] || 0
135
+ this.statusCode = httpStatusCode(span)
110
136
  this.synthetics = span.meta[ORIGIN_KEY] === 'synthetics'
111
137
  this.endpoint = span.meta[HTTP_ROUTE] || span.meta[HTTP_ENDPOINT] || ''
112
- this.method = span.meta[HTTP_METHOD] || ''
138
+ this.method = span.meta[HTTP_METHOD] || span.meta['http.request.method'] || ''
113
139
  this.srvSrc = span.meta[SVC_SRC_KEY] || ''
114
140
  this.spanKind = span.meta[SPAN_KIND] || ''
115
141
  // dd gRPC plugin sets a numeric code via setTag; OTel/manual sets a string name via meta.
@@ -208,6 +234,7 @@ class SpanStatsProcessor {
208
234
  env,
209
235
  tags,
210
236
  version: appVersion,
237
+ reportHostname,
211
238
  _DD_TRACE_METRICS_OTEL_FLUSH_INTERVAL: flushIntervalMs,
212
239
  } = config
213
240
  if (!otlpExporter) {
@@ -217,7 +244,9 @@ class SpanStatsProcessor {
217
244
  this.interval = intervalMs / 1e3
218
245
  this.bucketSizeNs = intervalMs * 1e6
219
246
  this.buckets = new TimeBuckets(Boolean(otlpExporter))
220
- this.hostname = os.hostname()
247
+ // A non-empty client hostname takes precedence over the agent's own hostname for the resulting
248
+ // metrics, so only send it when explicitly requested.
249
+ this.hostname = reportHostname ? os.hostname() : ''
221
250
  this.enabled = enabled
222
251
  this.otlpExporter = otlpExporter || null
223
252
  this.env = env
@@ -3,6 +3,7 @@
3
3
  const os = require('os')
4
4
  const { inspect } = require('util')
5
5
  const tracerVersion = require('../../../package.json').version
6
+ const { usesOtlpTraceExporter } = require('./exporter')
6
7
  const { warn } = require('./log/writer')
7
8
 
8
9
  const errors = {}
@@ -107,7 +108,7 @@ function configInfo () {
107
108
  profiling_enabled: profilingEnabled === 'true' || profilingEnabled === 'auto',
108
109
  appsec_enabled: config.appsec.DD_APPSEC_ENABLED,
109
110
  data_streams_enabled: !!config.dsmEnabled,
110
- otlp_traces_export_enabled: config.OTEL_TRACES_EXPORTER === 'otlp' && !config.isCiVisibility,
111
+ otlp_traces_export_enabled: usesOtlpTraceExporter(config),
111
112
  otlp_metrics_export_enabled: !!config.DD_METRICS_OTEL_ENABLED,
112
113
  otlp_logs_export_enabled: !!config.DD_LOGS_OTEL_ENABLED,
113
114
  }
@@ -2,13 +2,13 @@
2
2
 
3
3
  // TODO: Rename and move file. This is a general purpose helper for adding tags to a carrier.
4
4
 
5
- function addNonEmpty (carrier, key, value) {
5
+ function addNonEmpty (carrier, key, value, decode) {
6
6
  if (key !== '') {
7
- carrier[key] = value
7
+ carrier[decode ? decodeURIComponent(key) : key] = decode ? decodeURIComponent(value) : value
8
8
  }
9
9
  }
10
10
 
11
- function add (carrier, keyValuePairs, valueSeparator = ':') {
11
+ function add (carrier, keyValuePairs, valueSeparator = ':', decode = false) {
12
12
  if (typeof keyValuePairs === 'string') {
13
13
  let valueStart = 0
14
14
  let keyStart = 0
@@ -25,7 +25,8 @@ function add (carrier, keyValuePairs, valueSeparator = ':') {
25
25
  addNonEmpty(
26
26
  carrier,
27
27
  keyValuePairs.slice(keyStart, valueStart).trim(),
28
- keyValuePairs.slice(valueStart + 1, i).trim()
28
+ keyValuePairs.slice(valueStart + 1, i).trim(),
29
+ decode
29
30
  )
30
31
  keyStart = i + 1
31
32
  valueStart = 0
@@ -37,7 +38,8 @@ function add (carrier, keyValuePairs, valueSeparator = ':') {
37
38
  addNonEmpty(
38
39
  carrier,
39
40
  keyValuePairs.slice(keyStart, valueStart).trim(),
40
- keyValuePairs.slice(valueStart + 1).trim()
41
+ keyValuePairs.slice(valueStart + 1).trim(),
42
+ decode
41
43
  )
42
44
  }
43
45
  } else if (Array.isArray(keyValuePairs)) {
@@ -4,6 +4,7 @@ const path = require('path')
4
4
  const { fileURLToPath } = require('url')
5
5
  const dc = require('dc-polyfill')
6
6
  const parse = require('../../../../vendor/dist/module-details-from-path')
7
+ const { getPublishedModuleLoads } = require('../esm-module-load')
7
8
  const requirePackageJson = require('../require-package-json')
8
9
  const { isTrue } = require('../../src/util')
9
10
  const { sendData } = require('./send-data')
@@ -85,6 +86,9 @@ function loadAllTheLoadedModules () {
85
86
  onModuleLoad({ filename })
86
87
  }
87
88
  }
89
+ for (const filename of getPublishedModuleLoads()) {
90
+ onModuleLoad({ filename })
91
+ }
88
92
  }
89
93
 
90
94
  function onModuleLoad (data) {
@@ -22,4 +22,7 @@ module.exports = {
22
22
  appClosing () {
23
23
  telemetry?.appClosing()
24
24
  },
25
+ flush () {
26
+ telemetry?.flush()
27
+ },
25
28
  }
@@ -7,6 +7,12 @@ const logCollector = require('./log-collector')
7
7
  const telemetryLog = dc.channel('datadog:telemetry:log')
8
8
  const errorLog = dc.channel('datadog:log:error:record')
9
9
 
10
+ /**
11
+ * @typedef {object} TelemetryLogOptions
12
+ * @property {string} [tags] Default tags appended to every outgoing log.
13
+ */
14
+
15
+ let logOptions
10
16
  let enabled = false
11
17
 
12
18
  /**
@@ -68,10 +74,15 @@ function getErrorType (cause) {
68
74
  }
69
75
  }
70
76
 
71
- function start (config) {
77
+ /**
78
+ * @param {import('../../config/config-base')} config
79
+ * @param {TelemetryLogOptions} [options]
80
+ */
81
+ function start (config, options) {
72
82
  if (!config.telemetry.DD_TELEMETRY_LOG_COLLECTION_ENABLED || enabled) return
73
83
 
74
84
  enabled = true
85
+ logOptions = options
75
86
 
76
87
  telemetryLog.subscribe(onLog)
77
88
 
@@ -80,6 +91,7 @@ function start (config) {
80
91
 
81
92
  function stop () {
82
93
  enabled = false
94
+ logOptions = undefined
83
95
 
84
96
  if (telemetryLog.hasSubscribers) {
85
97
  telemetryLog.unsubscribe(onLog)
@@ -91,8 +103,15 @@ function stop () {
91
103
  function send (config, application, host) {
92
104
  if (!enabled) return
93
105
 
94
- const logs = logCollector.drain()
106
+ let logs = logCollector.drain()
95
107
  if (logs) {
108
+ const tags = logOptions?.tags
109
+ if (tags) {
110
+ logs = logs.map(entry => ({
111
+ ...entry,
112
+ tags: entry.tags ? `${entry.tags},${tags}` : tags,
113
+ }))
114
+ }
96
115
  sendData(config, application, host, 'logs', { logs })
97
116
  }
98
117
  }
@@ -23,6 +23,7 @@ function createHash (logEntry) {
23
23
  let result = logEntry.level ? hashCode(logEntry.level) : 0
24
24
  result = (((prime * result) | 0) + (logEntry.message ? hashCode(logEntry.message) : 0)) | 0
25
25
  result = (((prime * result) | 0) + (logEntry.stack_trace ? hashCode(logEntry.stack_trace) : 0)) | 0
26
+ result = (((prime * result) | 0) + (logEntry.tags ? hashCode(logEntry.tags) : 0)) | 0
26
27
  return result
27
28
  }
28
29
 
@@ -48,7 +49,7 @@ function sanitize (logEntry) {
48
49
 
49
50
  for (let i = Math.max(firstIndex, 0); i < lines.length; i++) {
50
51
  const line = lines[i]
51
- if (line.includes(ddBasePath)) {
52
+ if (ddBasePath !== undefined && line.includes(ddBasePath)) {
52
53
  stackLines.push(line.replace(ddBasePath, ''))
53
54
  } else {
54
55
  const match = NODE_FRAME_LINE_REGEX.exec(line)
@@ -203,7 +203,12 @@ function appClosing () {
203
203
  telemetryAppClosingChannel.publish()
204
204
  const { reqType, payload } = createPayload('app-closing')
205
205
  sendData(config, application, host, reqType, payload)
206
- // We flush before shutting down.
206
+ flush()
207
+ }
208
+
209
+ function flush () {
210
+ if (!config?.telemetry.DD_INSTRUMENTATION_TELEMETRY_ENABLED) return
211
+
207
212
  metricsManager.send(config, application, host)
208
213
  telemetryLogger.send(config, application, host)
209
214
  }
@@ -316,8 +321,9 @@ function extendedHeartbeat (config) {
316
321
  /**
317
322
  * @param {import('../config/config-base')} aConfig
318
323
  * @param {PluginManager} thePluginManager
324
+ * @param {import('./logs').TelemetryLogOptions} [logOptions]
319
325
  */
320
- function start (aConfig, thePluginManager) {
326
+ function start (aConfig, thePluginManager, logOptions) {
321
327
  if (!aConfig.telemetry.DD_INSTRUMENTATION_TELEMETRY_ENABLED) {
322
328
  if (aConfig.appsec.DD_APPSEC_SCA_ENABLED) {
323
329
  logger.warn('DD_APPSEC_SCA_ENABLED requires enabling telemetry to work.')
@@ -331,7 +337,7 @@ function start (aConfig, thePluginManager) {
331
337
  integrations = getIntegrations()
332
338
 
333
339
  dependencies.start(config, application, host, getRetryData, updateRetryData)
334
- telemetryLogger.start(config)
340
+ telemetryLogger.start(config, logOptions)
335
341
  endpoints.start(config, application, host, getRetryData, updateRetryData)
336
342
  sessionPropagation.start(config)
337
343
 
@@ -397,4 +403,5 @@ module.exports = {
397
403
  updateIntegrations,
398
404
  updateConfig,
399
405
  appClosing,
406
+ flush,
400
407
  }
@@ -145,9 +145,12 @@ function stripQueryAndFragment (target) {
145
145
  }
146
146
 
147
147
  function calculateDDBasePath (dirname) {
148
- const dirSteps = dirname.split(path.sep)
149
- const packagesIndex = dirSteps.lastIndexOf('packages')
150
- return dirSteps.slice(0, packagesIndex).join(path.sep) + path.sep
148
+ // Bundled into ESM output, `__dirname` is not defined. Bundled into CJS output, it is the bundle's directory,
149
+ // which may contain an unrelated `packages` segment (e.g. a monorepo). Only this file's own directory identifies
150
+ // where dd-trace lives.
151
+ const suffix = path.sep + path.join('packages', 'dd-trace', 'src')
152
+ if (dirname === undefined || !dirname.endsWith(suffix)) return
153
+ return dirname.slice(0, -suffix.length) + path.sep
151
154
  }
152
155
 
153
156
  function normalizePluginEnvName (envPluginName, makeLowercase = false) {
@@ -164,7 +167,7 @@ function normalizePluginEnvName (envPluginName, makeLowercase = false) {
164
167
  * @param {number} rate
165
168
  */
166
169
  function formatKnuthRate (rate) {
167
- const string = Number(rate).toFixed(6)
170
+ const string = rate.toFixed(6)
168
171
  for (let i = string.length - 1; i > 0; i--) {
169
172
  if (string[i] === '0') continue
170
173
  return string.slice(0, i + (string[i] === '.' ? 0 : 1))
@@ -191,7 +194,8 @@ module.exports = {
191
194
  globMatch,
192
195
  getSegment,
193
196
  stripQueryAndFragment,
194
- ddBasePath: globalThis.__DD_ESBUILD_BASEPATH || calculateDDBasePath(__dirname),
197
+ ddBasePath: globalThis.__DD_ESBUILD_BASEPATH ||
198
+ calculateDDBasePath(typeof __dirname === 'string' ? __dirname : undefined),
195
199
  normalizePluginEnvName,
196
200
  formatKnuthRate,
197
201
  truncateString,
package/register.js CHANGED
@@ -27,7 +27,8 @@ if (shouldRegisterSyncLoaderHooks()) {
27
27
  }
28
28
 
29
29
  if (!isSyncLoaderRegistered) {
30
- register('./loader-hook.mjs', parentURL)
30
+ const { getLoaderRegisterOptions } = require('./packages/dd-trace/src/esm-module-load')
31
+ register('./loader-hook.mjs', parentURL, getLoaderRegisterOptions())
31
32
  }
32
33
 
33
34
  function shouldRegisterSyncLoaderHooks () {
@@ -1,4 +1,4 @@
1
- (()=>{var i={"./@apm-js-collab/code-transformer/index.js"(i,s,k){"use strict";i.exports=k("./@apm-js-collab/code-transformer/lib/index.js")},"./@apm-js-collab/code-transformer/lib/index.js"(i,s,k){"use strict";let{InstrumentationMatcher:S}=k("./@apm-js-collab/code-transformer/lib/matcher.js");i.exports={create:function(i,s){return new S(i,s)}}},"./@apm-js-collab/code-transformer/lib/matcher.js"(i,s,k){"use strict";let S=k("./semifies/index.js"),{Transformer:E}=k("./@apm-js-collab/code-transformer/lib/transformer.js");let InstrumentationMatcher=class InstrumentationMatcher{#e=[];#t=null;#r={};#n={};constructor(i,s){this.#e=i,this.#t=s||"diagnostics_channel"}free(){this.#r={}}addTransform(i,s){this.#n[i]=s}getTransformer(i,s,k){k=k.replace(/\\/g,"/");let w=`${i}/${k}@${s}`;if(this.#r[w])return this.#r[w];let C=this.#e.filter(({module:E})=>E.name===i&&("string"==typeof E.filePath?E.filePath===k:E.filePath.test(k))&&S(s,E.versionRange));if(0!==C.length)return this.#r[w]=new E(i,s,k,C,this.#t,this.#n),this.#r[w]}};i.exports={InstrumentationMatcher}},"./@apm-js-collab/code-transformer/lib/transformer.js"(i,s,k){"use strict";let S,E,w=k("./esquery/dist/esquery.min.js"),{parse:C}=k("./meriyah/dist/meriyah.cjs"),{generate:T}=k("./astring/dist/astring.js"),_=k("./@apm-js-collab/code-transformer/lib/transforms.js");let Transformer=class Transformer{#a=null;#o=null;#i=null;#e=[];#t=null;#n={};constructor(i,s,k,S,E,w={}){this.#a=i,this.#o=s,this.#i=k,this.#e=S,this.#t=E,this.#n=w}free(){}get moduleName(){return this.#a}get filePath(){return this.#i}transform(i,s,O){let N;if(Buffer.isBuffer(i)&&(i=i.toString()),!i)return{code:i};let D={},q=0,j={..._,...this.#n,defaults:{..._}};for(let k of this.#e){let{astQuery:S,functionQuery:E={}}=k;if(!N){let k={loc:!0,ranges:!0,raw:!0,module:"esm"===s};try{N=C(i,k)}catch{N=C(i,{...k,module:!k.module})}"esm"===s&&(D=this.#s(N))}let T=this.#l(E,D),_=S||this.#c(T),O={...k,dcModule:this.#t,moduleType:s,moduleVersion:this.#o,functionQuery:T,transforms:j};O.operator=this.#u(O),w.traverse(N,w.parse(_),(...i)=>{q++,this.#p(O,...i)})}if(0===q&&this.#e.length>0){let i=this.#e.map(({astQuery:i,functionQuery:s={}})=>{if(i)return i;let k=this.#l(s,D),S=s.methodName||s.privateMethodName||s.functionName||s.expressionName||"constructor",E=s.className||s.functionName||s.expressionName,w=k.className||k.functionName||k.expressionName;return E&&E!==w?`${E} (local name: ${w})`:S});throw Error(`Failed to find injection points for: ${JSON.stringify(i)}`)}if(N){let i;S??=k("./@apm-js-collab/code-transformer/node_modules/source-map/source-map.js").SourceMapConsumer,E??=k("./@apm-js-collab/code-transformer/node_modules/source-map/source-map.js").SourceMapGenerator;let s=`${this.#a}/${this.#i}`;if(O){let k=new S(O);k.file=s,i=E.fromSourceMap(k)}else i=new E({file:s});return{code:T(N,{sourceMap:i}),map:i.toString()}}return{code:i}}#p(i,...s){let k=i.transforms[i.operator],{index:S=0}=i.functionQuery,[E]=s,w=E.init?.type||E.type;if("ClassDeclaration"===w||"ClassExpression"===w||"VariableDeclarator"!==E.type&&(i.functionIndex=++i.functionIndex||0,null===S||S===i.functionIndex))k(i,...s)}#u({transform:i,functionQuery:{kind:s}}){if(i)return i;switch(s){case"Async":return"tracePromise";case"Auto":return"traceAuto";case"Callback":return"traceCallback";default:return"traceSync"}}#s(i){let s={};for(let k of i.body)if("ExportNamedDeclaration"===k.type&&!k.source){for(let i of k.specifiers)if(i.exported&&i.local){let k=i.exported.name??i.exported.value,S=i.local.name??i.local.value;k&&S&&(s[k]=S)}}return s}#l(i,s){if(!i.isExportAlias)return i;let{functionName:k,expressionName:S,className:E}=i;return k&&s[k]?{...i,functionName:s[k]}:S&&s[S]?{...i,expressionName:s[S]}:E&&s[E]?{...i,className:s[E]}:i}#c(i){let{functionName:s,expressionName:k,className:S,objectName:E,propertyName:w}=i,C=i.privateMethodName?"PrivateIdentifier":"Identifier",T=[],_=i.methodName||i.privateMethodName;if(S?(_??="constructor",T.push(`[id.name="${S}"]`,`[id.name="${S}"] > ClassExpression`,`[id.name="${S}"] > ClassBody > [key.name="${_}"][key.type=${C}] > [async]`,`[id.name="${S}"] > ClassExpression > ClassBody > [key.name="${_}"][key.type=${C}] > [async]`)):_&&T.push(`ClassBody > [key.name="${_}"][key.type=${C}] > [async]`,`Property[key.name="${_}"][key.type=${C}] > [async]`),s?T.push(`FunctionDeclaration[id.name="${s}"][async]`):k&&T.push(`FunctionExpression[id.name="${k}"][async]`,`ArrowFunctionExpression[id.name="${k}"][async]`,`VariableDeclarator[id.name="${k}"] > FunctionExpression[async]`,`VariableDeclarator[id.name="${k}"] > ArrowFunctionExpression[async]`,`AssignmentExpression[left.property.name="${k}"] > FunctionExpression[async]`,`AssignmentExpression[left.property.name="${k}"] > ArrowFunctionExpression[async]`,`AssignmentExpression[left.name="${k}"] > FunctionExpression[async]`,`AssignmentExpression[left.name="${k}"] > ArrowFunctionExpression[async]`),E||w){if(!E||!w)throw Error(`functionQuery: 'objectName' and 'propertyName' must be used together (got objectName=${E}, propertyName=${w})`);let i="this"===E?"left.object.type=ThisExpression":`left.object.name="${E}"`;T.push(`AssignmentExpression[${i}][left.property.name="${w}"] > [async]`)}return T.join(", ")}};i.exports={Transformer}},"./@apm-js-collab/code-transformer/lib/transforms.js"(i,s,k){"use strict";let S=k("./esquery/dist/esquery.min.js"),{parse:E}=k("./meriyah/dist/meriyah.cjs"),tracingChannelPredicate=i=>i.declarations?.[0]?.id?.properties?.[0]?.value?.name==="tr_ch_apm_tracingChannel",w=/[^\w]/g,formatChannelVariable=i=>`tr_ch_apm$${i.replace(w,"_")}`;function wrapParams(i){return[...(i||[]).filter(i=>"RestElement"!==i.type&&"AssignmentPattern"!==i.type).map((i,s)=>({type:"Identifier",name:`__apm$arg${s}`})),{type:"RestElement",argument:{type:"Identifier",name:"__apm$args"}}]}function traceAny(i,s,k,S){let E=S[S.length-1];"ClassDeclaration"===s.type||"ClassExpression"===s.type?traceInstanceMethod(i,s,E):traceFunction(i,s,E)}function isChannelRunStoresReturn(i,s){if("ReturnStatement"!==i.type)return!1;let k=i.argument?.type==="CallExpression"?i.argument.callee:null;return k?.type==="MemberExpression"&&k.property?.name==="runStores"&&k.object?.type==="MemberExpression"&&k.object.property?.name==="start"&&k.object.object?.type==="Identifier"&&k.object.object.name===s}function nextWrappedFunction(i){let declInit=(i,s)=>{let k=i?.find(i=>"VariableDeclaration"===i.type&&i.declarations.some(i=>i.id?.name===s));return k?.declarations.find(i=>i.id?.name===s)?.init??null},s=declInit(i,"__apm$traced"),k=declInit(s?.body?.body,"__apm$wrapped"),S=k?.type;return"FunctionExpression"===S||"ArrowFunctionExpression"===S||"FunctionDeclaration"===S?k:null}function isWrappedForChannel(i,s){let k=new Set,S=i;for(;S&&!k.has(S);){k.add(S);let i=S.body?.body;if(!Array.isArray(i))break;if(i.some(i=>isChannelRunStoresReturn(i,s)))return!0;S=nextWrappedFunction(i)}return!1}function constructorPatchesMethod(i,s){let k=i?.value?.body?.body;return!!Array.isArray(k)&&k.some(i=>"VariableDeclaration"===i.type&&i.declarations.some(i=>i.id?.name===s))}function traceFunction(i,s,k){if(isWrappedForChannel(s,formatChannelVariable(i.channelName)))return;i.transforms.tracingChannelDeclaration(i,k);let{functionQuery:{methodName:S,privateMethodName:E,functionName:w,expressionName:C,propertyName:T}}=i,_="constructor"!==S&&(S||E||w||C||T)?s.type:"ArrowFunctionExpression",O=s.params;s.body=wrap(i,{type:_,params:O,body:s.body,async:s.async,expression:!1,generator:s.generator},k),s.params=wrapParams(O),s.generator=!1,s.async=!1,wrapSuper(i,s)}function traceInstanceMethod(i,s,k){let{functionQuery:S,operator:w,channelName:C}=i,{methodName:T}=S;if(!T)return;let _=s.body;if(_.body.some(({key:i})=>i?.name===T))return;let O=_.body.find(({kind:i})=>"constructor"===i),N=`${formatChannelVariable(C)}$${T}`;if(O&&constructorPatchesMethod(O,N))return;i.transforms.tracingChannelDeclaration(i,k),O||(O=E(s.superClass?"class A extends Object { constructor (...args) { super(...args) } }":"class A { constructor () {} }").body[0].body.body[0],_.body.unshift(O));let D=E(`
1
+ (()=>{var i={"./@apm-js-collab/code-transformer/index.js"(i,s,k){"use strict";i.exports=k("./@apm-js-collab/code-transformer/lib/index.js")},"./@apm-js-collab/code-transformer/lib/index.js"(i,s,k){"use strict";let{InstrumentationMatcher:S}=k("./@apm-js-collab/code-transformer/lib/matcher.js");i.exports={create:function(i,s){return new S(i,s)}}},"./@apm-js-collab/code-transformer/lib/matcher.js"(i,s,k){"use strict";let S=k("./semifies/index.js"),{Transformer:E}=k("./@apm-js-collab/code-transformer/lib/transformer.js");let InstrumentationMatcher=class InstrumentationMatcher{#e=[];#t=null;#r={};#n={};constructor(i,s){this.#e=i,this.#t=s||"diagnostics_channel"}free(){this.#r={}}addTransform(i,s){this.#n[i]=s}getTransformer(i,s,k){k=k.replace(/\\/g,"/");let w=`${i}/${k}@${s}`;if(this.#r[w])return this.#r[w];let C=this.#e.filter(({module:E})=>E.name===i&&("string"==typeof E.filePath?E.filePath===k:E.filePath.test(k))&&S(s,E.versionRange));if(0!==C.length)return this.#r[w]=new E(i,s,k,C,this.#t,this.#n),this.#r[w]}};i.exports={InstrumentationMatcher}},"./@apm-js-collab/code-transformer/lib/transformer.js"(i,s,k){"use strict";let S,E,w=k("./esquery/dist/esquery.min.js"),{parse:C}=k("./meriyah/dist/meriyah.cjs"),{generate:T}=k("./astring/dist/astring.js"),_=k("./@apm-js-collab/code-transformer/lib/transforms.js");let Transformer=class Transformer{#a=null;#o=null;#i=null;#e=[];#t=null;#n={};constructor(i,s,k,S,E,w={}){this.#a=i,this.#o=s,this.#i=k,this.#e=S,this.#t=E,this.#n=w}free(){}get moduleName(){return this.#a}get filePath(){return this.#i}transform(i,s,O,N){let D,q=N?.sourceFile||`${this.#a}/${this.#i}`;if(Buffer.isBuffer(i)&&(i=i.toString()),!i)return{code:i};let j={},R=0,$={..._,...this.#n,defaults:{..._}};for(let k of this.#e){let{astQuery:S,functionQuery:E={}}=k;if(!D){let k={loc:!0,ranges:!0,raw:!0,module:"esm"===s};try{D=C(i,k)}catch{D=C(i,{...k,module:!k.module})}"esm"===s&&(j=this.#s(D))}let T=this.#l(E,j),_=S||this.#c(T),O={...k,dcModule:this.#t,moduleType:s,moduleVersion:this.#o,functionQuery:T,transforms:$};O.operator=this.#u(O),w.traverse(D,w.parse(_),(...i)=>{R++,this.#p(O,...i)})}if(0===R&&this.#e.length>0){let i=this.#e.map(({astQuery:i,functionQuery:s={}})=>{if(i)return i;let k=this.#l(s,j),S=s.methodName||s.privateMethodName||s.functionName||s.expressionName||"constructor",E=s.className||s.functionName||s.expressionName,w=k.className||k.functionName||k.expressionName;return E&&E!==w?`${E} (local name: ${w})`:S});throw Error(`Failed to find injection points for: ${JSON.stringify(i)}`)}if(D){S??=k("./@apm-js-collab/code-transformer/node_modules/source-map/source-map.js").SourceMapConsumer;let s=new(E??=k("./@apm-js-collab/code-transformer/node_modules/source-map/source-map.js").SourceMapGenerator)({file:q});s.setSourceContent(q,i);let w=T(D,{sourceMap:s});return O&&s.applySourceMap(new S(O),q),{code:w,map:s.toString()}}return{code:i}}#p(i,...s){let k="function"==typeof i.transform?i.transform:i.transforms[i.operator],{index:S=0}=i.functionQuery,[E]=s,w=E.init?.type||E.type;if("ClassDeclaration"===w||"ClassExpression"===w||"VariableDeclarator"!==E.type&&(i.functionIndex=++i.functionIndex||0,null===S||S===i.functionIndex))k(i,...s)}#u({transform:i,functionQuery:{kind:s}}){if("string"==typeof i)return i;switch(s){case"Async":return"tracePromise";case"Auto":return"traceAuto";case"Callback":return"traceCallback";default:return"traceSync"}}#s(i){let s={};for(let k of i.body)if("ExportNamedDeclaration"===k.type&&!k.source){for(let i of k.specifiers)if(i.exported&&i.local){let k=i.exported.name??i.exported.value,S=i.local.name??i.local.value;k&&S&&(s[k]=S)}}return s}#l(i,s){if(!i.isExportAlias)return i;let{functionName:k,expressionName:S,className:E}=i;return k&&s[k]?{...i,functionName:s[k]}:S&&s[S]?{...i,expressionName:s[S]}:E&&s[E]?{...i,className:s[E]}:i}#c(i){let{functionName:s,expressionName:k,className:S,objectName:E,propertyName:w}=i,C=i.privateMethodName?"PrivateIdentifier":"Identifier",T=[],_=i.methodName||i.privateMethodName;if(S?(_??="constructor",T.push(`[id.name="${S}"]`,`[id.name="${S}"] > ClassExpression`,`[id.name="${S}"] > ClassBody > [key.name="${_}"][key.type=${C}] > [async]`,`[id.name="${S}"] > ClassExpression > ClassBody > [key.name="${_}"][key.type=${C}] > [async]`)):_&&T.push(`ClassBody > [key.name="${_}"][key.type=${C}] > [async]`,`Property[key.name="${_}"][key.type=${C}] > [async]`),s?T.push(`FunctionDeclaration[id.name="${s}"][async]`):k&&T.push(`FunctionExpression[id.name="${k}"][async]`,`ArrowFunctionExpression[id.name="${k}"][async]`,`VariableDeclarator[id.name="${k}"] > FunctionExpression[async]`,`VariableDeclarator[id.name="${k}"] > ArrowFunctionExpression[async]`,`AssignmentExpression[left.property.name="${k}"] > FunctionExpression[async]`,`AssignmentExpression[left.property.name="${k}"] > ArrowFunctionExpression[async]`,`AssignmentExpression[left.name="${k}"] > FunctionExpression[async]`,`AssignmentExpression[left.name="${k}"] > ArrowFunctionExpression[async]`),E||w){if(!E||!w)throw Error(`functionQuery: 'objectName' and 'propertyName' must be used together (got objectName=${E}, propertyName=${w})`);let i="this"===E?"left.object.type=ThisExpression":`left.object.name="${E}"`;T.push(`AssignmentExpression[${i}][left.property.name="${w}"] > [async]`)}return T.join(", ")}};i.exports={Transformer}},"./@apm-js-collab/code-transformer/lib/transforms.js"(i,s,k){"use strict";let S=k("./esquery/dist/esquery.min.js"),{parse:E}=k("./meriyah/dist/meriyah.cjs"),tracingChannelPredicate=i=>i.declarations?.[0]?.id?.properties?.[0]?.value?.name==="tr_ch_apm_tracingChannel",w=/[^\w]/g,formatChannelVariable=i=>`tr_ch_apm$${i.replace(w,"_")}`;function wrapParams(i){return[...(i||[]).filter(i=>"RestElement"!==i.type&&"AssignmentPattern"!==i.type).map((i,s)=>({type:"Identifier",name:`__apm$arg${s}`})),{type:"RestElement",argument:{type:"Identifier",name:"__apm$args"}}]}function traceAny(i,s,k,S){let E=S[S.length-1];"ClassDeclaration"===s.type||"ClassExpression"===s.type?traceInstanceMethod(i,s,E):traceFunction(i,s,E)}function isChannelRunStoresReturn(i,s){if("ReturnStatement"!==i.type)return!1;let k=i.argument?.type==="CallExpression"?i.argument.callee:null;return k?.type==="MemberExpression"&&k.property?.name==="runStores"&&k.object?.type==="MemberExpression"&&k.object.property?.name==="start"&&k.object.object?.type==="Identifier"&&k.object.object.name===s}function nextWrappedFunction(i){let declInit=(i,s)=>{let k=i?.find(i=>"VariableDeclaration"===i.type&&i.declarations.some(i=>i.id?.name===s));return k?.declarations.find(i=>i.id?.name===s)?.init??null},s=declInit(i,"__apm$traced"),k=declInit(s?.body?.body,"__apm$wrapped"),S=k?.type;return"FunctionExpression"===S||"ArrowFunctionExpression"===S||"FunctionDeclaration"===S?k:null}function isWrappedForChannel(i,s){let k=new Set,S=i;for(;S&&!k.has(S);){k.add(S);let i=S.body?.body;if(!Array.isArray(i))break;if(i.some(i=>isChannelRunStoresReturn(i,s)))return!0;S=nextWrappedFunction(i)}return!1}function constructorPatchesMethod(i,s){let k=i?.value?.body?.body;return!!Array.isArray(k)&&k.some(i=>"VariableDeclaration"===i.type&&i.declarations.some(i=>i.id?.name===s))}function traceFunction(i,s,k){if(isWrappedForChannel(s,formatChannelVariable(i.channelName)))return;i.transforms.tracingChannelDeclaration(i,k);let{functionQuery:{methodName:S,privateMethodName:E,functionName:w,expressionName:C,propertyName:T}}=i,_="constructor"===S||!S&&!E&&!w&&!C&&!T,O=_?"ArrowFunctionExpression":s.type,N=s.params,D=`${formatChannelVariable(i.channelName)}$self`;i.selfBinding=_&&captureSelfAtSuper(s,D)?D:null,s.body=wrap(i,{type:O,params:N,body:s.body,async:s.async,expression:!1,generator:s.generator},k),s.params=wrapParams(N),s.generator=!1,s.async=!1,"ArrowFunctionExpression"!==O&&wrapSuper(i,s)}function traceInstanceMethod(i,s,k){let{functionQuery:S,operator:w,channelName:C}=i,{methodName:T}=S;if(!T)return;let _=s.body;if(_.body.some(({key:i})=>i?.name===T))return;let O=_.body.find(({kind:i})=>"constructor"===i),N=`${formatChannelVariable(C)}$${T}`;if(O&&constructorPatchesMethod(O,N))return;i.transforms.tracingChannelDeclaration(i,k),O||(O=E(s.superClass?"class A extends Object { constructor (...args) { super(...args) } }":"class A { constructor () {} }").body[0].body.body[0],_.body.unshift(O));let D=E(`
2
2
  const ${N} = this["${T}"]
3
3
  this["${T}"] = function () {}
4
4
  if (typeof ${N} === 'function') {
@@ -7,8 +7,8 @@
7
7
  configurable: true
8
8
  })
9
9
  }
10
- `).body,q=D[1].expression.right;q.params=[{type:"RestElement",argument:{type:"Identifier",name:"__apm$args"}}],q.async="tracePromise"===w,q.body=wrap(i,{type:"Identifier",name:N},k),wrapSuper(i,q),O.value.body.body.push(...D)}function wrap(i,s,k){let w,{operator:C,moduleVersion:T}=i,{returnKind:_}=i.functionQuery,O=_?generateIterPatch(i,_,k):"";"traceCallback"===C&&(w=wrapCallback(i,s,O)),"tracePromise"===C&&(w=wrapPromise(i,s,O)),"traceSync"===C&&(w=wrapSync(i,s,O)),"traceAuto"===C&&(w=wrapAuto(i,s,O));let N=(s.params||[]).filter(i=>"RestElement"!==i.type&&"AssignmentPattern"!==i.type).map((i,s)=>`__apm$arg${s}`).concat("...__apm$args").join(", "),D=w.body[0].body,q=E("ArrowFunctionExpression"===s.type?`
11
- const __apm$arguments = [${N}];
10
+ `).body,q=D[1].expression.right;q.params=[{type:"RestElement",argument:{type:"Identifier",name:"__apm$args"}}],q.async="tracePromise"===w,i.selfBinding=null,q.body=wrap(i,{type:"Identifier",name:N},k),wrapSuper(i,q),O.value.body.body.push(...D)}function wrap(i,s,k){let w,{operator:C,moduleVersion:T,selfBinding:_}=i,{returnKind:O}=i.functionQuery,N=O?generateIterPatch(i,O,k):"";"traceCallback"===C&&(w=wrapCallback(i,s,N)),"tracePromise"===C&&(w=wrapPromise(i,s,N)),"traceSync"===C&&(w=wrapSync(i,s,N)),"traceAuto"===C&&(w=wrapAuto(i,s,N));let D=(s.params||[]).filter(i=>"RestElement"!==i.type&&"AssignmentPattern"!==i.type).map((i,s)=>`__apm$arg${s}`).concat("...__apm$args").join(", "),q=w.body[0].body,j=E((_?`let ${_};`:"")+("ArrowFunctionExpression"===s.type?`
11
+ const __apm$arguments = [${D}];
12
12
  const __apm$ctx = {
13
13
  arguments: __apm$arguments,
14
14
  moduleVersion: ${JSON.stringify(T)}
@@ -18,7 +18,7 @@
18
18
  return __apm$wrapped(...__apm$arguments);
19
19
  };
20
20
  `:`
21
- const __apm$arguments = [${N}].slice(0, arguments.length);
21
+ const __apm$arguments = [${D}].slice(0, arguments.length);
22
22
  const __apm$ctx = {
23
23
  arguments: __apm$arguments,
24
24
  self: this,
@@ -28,7 +28,7 @@
28
28
  const __apm$wrapped = () => {};
29
29
  return __apm$wrapped.apply(this, __apm$arguments);
30
30
  };
31
- `).body;return D.body.unshift(...q),S.query(D,"[id.name=__apm$wrapped]")[0].init=s,D}function wrapSuper(i,s){let k=new Set;for(let i of(S.traverse(s.body,S.parse("[object.type=Super]"),(i,s)=>{let S,{name:w}=i.property;if(s.callee){let{expression:i}=E(`__apm$super['${w}'].call(this)`).body[0];s.callee=S=i.callee,s.arguments.unshift(...i.arguments)}else s.expression=S=E(`__apm$super['${w}']`).body[0];S.computed=s.callee.computed,S.optional=s.callee.optional,k.add(w)}),k)){let k=E(`
31
+ `)).body;return q.body.unshift(...j),S.query(q,"[id.name=__apm$wrapped]")[0].init=s,q}function captureSelfAtSuper(i,s){let k=!1,visit=(i,S)=>{let w=i[S];if(null!==w&&"object"==typeof w){if(Array.isArray(w)){for(let i=0;i<w.length;i++)visit(w,i);return}if("string"==typeof w.type&&"ClassBody"!==w.type&&"FunctionExpression"!==w.type&&"FunctionDeclaration"!==w.type){if("CallExpression"===w.type&&"Super"===w.callee.type){let C=E(`(0, ${s} = this)`).body[0].expression;C.expressions[0]=w,i[S]=C,k=!0;return}for(let i of Object.keys(w))visit(w,i)}}};return visit(i,"body"),k}function wrapSuper(i,s){let k=new Set;for(let i of(S.traverse(s.body,S.parse("[object.type=Super]"),(i,s)=>{let S,{name:w}=i.property;if(s.callee){let{expression:i}=E(`__apm$super['${w}'].call(this)`).body[0];s.callee=S=i.callee,s.arguments.unshift(...i.arguments)}else s.expression=S=E(`__apm$super['${w}']`).body[0];S.computed=s.callee.computed,S.optional=s.callee.optional,k.add(w)}),k)){let k=E(`
32
32
  class Wrapper {
33
33
  wrapper () {
34
34
  __apm$super['${i}'] = super['${i}']
@@ -73,7 +73,7 @@
73
73
  ${C}.error.publish(__apm$ctx);
74
74
  throw err;
75
75
  } finally {
76
- __apm$ctx.self ??= this;
76
+ __apm$ctx.self ??= ${(({selfBinding:i})=>i||"this")(i)};
77
77
  ${C}.end.publish(__apm$ctx);
78
78
  }
79
79
  });
@@ -134,7 +134,7 @@
134
134
  ${w}.error.publish(__apm$ctx);
135
135
  throw err;
136
136
  } finally {
137
- __apm$ctx.self ??= this;
137
+ __apm$ctx.self ??= ${(({selfBinding:i})=>i||"this")(i)};
138
138
  ${w}.end.publish(__apm$ctx);
139
139
  }
140
140
  });
@@ -152,7 +152,7 @@
152
152
  ${w}.error.publish(__apm$ctx);
153
153
  throw err;
154
154
  } finally {
155
- __apm$ctx.self ??= this;
155
+ __apm$ctx.self ??= ${(({selfBinding:i})=>i||"this")(i)};
156
156
  ${w}.end.publish(__apm$ctx);
157
157
  }
158
158
  return __apm$ctx.result;