dd-trace 6.25.0 → 6.26.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 (141) hide show
  1. package/README.md +3 -0
  2. package/ci/cypress/support.js +2 -1
  3. package/ci/vitest-no-worker-init-node-setup.mjs +2 -1
  4. package/ci/vitest-no-worker-init-runner-setup.mjs +2 -1
  5. package/ci/vitest-no-worker-init-setup.mjs +729 -724
  6. package/ci/vitest-no-worker-init-v5-setup.mjs +2 -1
  7. package/package.json +33 -30
  8. package/packages/datadog-esbuild/index.js +8 -15
  9. package/packages/datadog-esbuild/src/log.js +2 -29
  10. package/packages/datadog-instrumentations/src/ai.js +6 -1
  11. package/packages/datadog-instrumentations/src/cypress-config.js +20 -9
  12. package/packages/datadog-instrumentations/src/helpers/bundler-esm-exports.js +23 -1
  13. package/packages/datadog-instrumentations/src/helpers/bundler-log.js +38 -0
  14. package/packages/datadog-instrumentations/src/helpers/bundler-transform.js +9 -6
  15. package/packages/datadog-instrumentations/src/helpers/fetch.js +51 -6
  16. package/packages/datadog-instrumentations/src/helpers/rewriter/index.js +6 -0
  17. package/packages/datadog-instrumentations/src/helpers/rewriter/instrumentation-registry.js +8 -0
  18. package/packages/datadog-instrumentations/src/helpers/rewriter/instrumentations/modelcontextprotocol-client.js +30 -0
  19. package/packages/datadog-instrumentations/src/helpers/rewriter/instrumentations/modelcontextprotocol-server.js +23 -0
  20. package/packages/datadog-instrumentations/src/helpers/rewriter/instrumentations/next.js +21 -0
  21. package/packages/datadog-instrumentations/src/helpers/rewriter/instrumentations/postgres.js +33 -4
  22. package/packages/datadog-instrumentations/src/helpers/rewriter/target-patterns.json +30 -0
  23. package/packages/datadog-instrumentations/src/helpers/rewriter/targets.json +6 -0
  24. package/packages/datadog-instrumentations/src/helpers/rewriter/transforms/postgres.js +122 -0
  25. package/packages/datadog-instrumentations/src/microgateway-core.js +1 -2
  26. package/packages/datadog-instrumentations/src/modelcontextprotocol-client.js +21 -0
  27. package/packages/datadog-instrumentations/src/modelcontextprotocol-sdk.js +7 -1
  28. package/packages/datadog-instrumentations/src/modelcontextprotocol-server.js +41 -0
  29. package/packages/datadog-instrumentations/src/next.js +184 -20
  30. package/packages/datadog-instrumentations/src/router.js +35 -12
  31. package/packages/datadog-instrumentations/src/vitest-main.js +10 -2
  32. package/packages/datadog-plugin-aws-lambda/src/arn.js +41 -0
  33. package/packages/datadog-plugin-aws-lambda/src/event-type-guards.js +170 -0
  34. package/packages/datadog-plugin-aws-lambda/src/trigger.js +339 -0
  35. package/packages/datadog-plugin-aws-sdk/src/services/dynamodb.js +7 -0
  36. package/packages/datadog-plugin-aws-sdk/src/services/kinesis.js +32 -10
  37. package/packages/datadog-plugin-aws-sdk/src/services/lambda.js +10 -1
  38. package/packages/datadog-plugin-aws-sdk/src/services/sqs.js +4 -0
  39. package/packages/datadog-plugin-aws-sdk/src/services/stepfunctions.js +3 -0
  40. package/packages/datadog-plugin-cypress/src/cypress-plugin.js +30 -4
  41. package/packages/datadog-plugin-cypress/src/support.mjs +1353 -0
  42. package/packages/datadog-plugin-express/src/code_origin.js +2 -2
  43. package/packages/datadog-plugin-fastify/src/code_origin.js +2 -2
  44. package/packages/datadog-plugin-google-cloud-pubsub/src/consumer.js +10 -0
  45. package/packages/datadog-plugin-google-cloud-pubsub/src/producer.js +2 -0
  46. package/packages/datadog-plugin-google-cloud-pubsub/src/pubsub-push-subscription.js +7 -0
  47. package/packages/datadog-plugin-google-cloud-pubsub/src/resource-names.js +24 -0
  48. package/packages/datadog-plugin-graphql/src/tools/transforms.js +1 -0
  49. package/packages/datadog-plugin-http/src/client.js +2 -1
  50. package/packages/datadog-plugin-http2/src/client.js +2 -1
  51. package/packages/datadog-plugin-modelcontextprotocol-sdk/src/tracing.js +28 -2
  52. package/packages/datadog-plugin-modelcontextprotocol-sdk/src/utils.js +1 -0
  53. package/packages/datadog-plugin-mongodb-core/src/query.js +17 -1
  54. package/packages/datadog-plugin-postgres/src/index.js +118 -41
  55. package/packages/datadog-plugin-supabase/src/supabase-auth-js-gotrueclient-getuser.js +18 -8
  56. package/packages/datadog-plugin-supabase/src/supabase-functions-js-functionsclient-invoke.js +49 -13
  57. package/packages/datadog-plugin-supabase/src/supabase-storage-js-handle-request.js +34 -9
  58. package/packages/datadog-plugin-vitest/src/index.js +3 -2
  59. package/packages/datadog-plugin-ws/src/close.js +3 -5
  60. package/packages/datadog-plugin-ws/src/producer.js +1 -4
  61. package/packages/datadog-plugin-ws/src/receiver.js +3 -5
  62. package/packages/datadog-plugin-ws/src/server.js +44 -13
  63. package/packages/datadog-vite/index.js +537 -0
  64. package/packages/datadog-vite/src/log.js +5 -0
  65. package/packages/datadog-webpack/src/log.js +2 -29
  66. package/packages/dd-trace/src/aiguard/index.js +1 -1
  67. package/packages/dd-trace/src/aiguard/integrations/index.js +6 -5
  68. package/packages/dd-trace/src/appsec/blocking/index.js +17 -1
  69. package/packages/dd-trace/src/appsec/channels.js +7 -0
  70. package/packages/dd-trace/src/appsec/downstream_requests.js +105 -0
  71. package/packages/dd-trace/src/appsec/graphql.js +10 -13
  72. package/packages/dd-trace/src/appsec/handlers/auth.js +1 -3
  73. package/packages/dd-trace/src/appsec/handlers/http-request.js +60 -65
  74. package/packages/dd-trace/src/appsec/handlers/http-response.js +61 -7
  75. package/packages/dd-trace/src/appsec/handlers/payments.js +23 -27
  76. package/packages/dd-trace/src/appsec/index.js +6 -0
  77. package/packages/dd-trace/src/appsec/lambda.js +17 -17
  78. package/packages/dd-trace/src/appsec/rasp/command_injection.js +4 -4
  79. package/packages/dd-trace/src/appsec/rasp/index.js +8 -1
  80. package/packages/dd-trace/src/appsec/rasp/lfi.js +2 -2
  81. package/packages/dd-trace/src/appsec/rasp/sql_injection.js +7 -17
  82. package/packages/dd-trace/src/appsec/rasp/ssrf.js +80 -16
  83. package/packages/dd-trace/src/appsec/rasp/utils.js +33 -3
  84. package/packages/dd-trace/src/appsec/recommended.json +70 -3
  85. package/packages/dd-trace/src/appsec/reporter.js +9 -0
  86. package/packages/dd-trace/src/appsec/sdk/set_user.js +3 -3
  87. package/packages/dd-trace/src/appsec/sdk/track_event.js +4 -4
  88. package/packages/dd-trace/src/appsec/sdk/user_blocking.js +1 -1
  89. package/packages/dd-trace/src/appsec/user_tracking.js +6 -8
  90. package/packages/dd-trace/src/appsec/waf/index.js +65 -6
  91. package/packages/dd-trace/src/appsec/waf/waf_context_wrapper.js +33 -38
  92. package/packages/dd-trace/src/appsec/waf/waf_manager.js +18 -2
  93. package/packages/dd-trace/src/config/generated-config-types.d.ts +4 -2
  94. package/packages/dd-trace/src/config/index.js +46 -26
  95. package/packages/dd-trace/src/config/parsers.js +35 -0
  96. package/packages/dd-trace/src/config/remote-config-layers.js +38 -0
  97. package/packages/dd-trace/src/config/remote_config.js +2 -1
  98. package/packages/dd-trace/src/config/supported-configurations.json +14 -6
  99. package/packages/dd-trace/src/datastreams/fnv.js +27 -0
  100. package/packages/dd-trace/src/datastreams/pathway.js +113 -28
  101. package/packages/dd-trace/src/datastreams/processor.js +5 -4
  102. package/packages/dd-trace/src/debugger/config.js +1 -1
  103. package/packages/dd-trace/src/debugger/devtools_client/request-options.js +7 -9
  104. package/packages/dd-trace/src/debugger/devtools_client/send.js +1 -1
  105. package/packages/dd-trace/src/debugger/devtools_client/state.js +3 -1
  106. package/packages/dd-trace/src/debugger/devtools_client/tags.js +1 -1
  107. package/packages/dd-trace/src/debugger/index.js +2 -2
  108. package/packages/dd-trace/src/debugger/inspect-segment.js +3 -2
  109. package/packages/dd-trace/src/debugger/pause-duration-histogram.js +4 -1
  110. package/packages/dd-trace/src/debugger/probe_sampler.js +39 -17
  111. package/packages/dd-trace/src/debugger/unsupported-runtime.js +2 -0
  112. package/packages/dd-trace/src/git_metadata.js +2 -1
  113. package/packages/dd-trace/src/index.js +6 -3
  114. package/packages/dd-trace/src/lambda/facade.js +6 -5
  115. package/packages/dd-trace/src/llmobs/plugins/modelcontextprotocol-sdk/index.js +54 -3
  116. package/packages/dd-trace/src/llmobs/plugins/modelcontextprotocol-sdk/utils.js +81 -1
  117. package/packages/dd-trace/src/openfeature/agentless_configuration_source.js +3 -0
  118. package/packages/dd-trace/src/openfeature/configuration_source.js +20 -0
  119. package/packages/dd-trace/src/plugins/ci_plugin.js +104 -9
  120. package/packages/dd-trace/src/plugins/index.js +2 -0
  121. package/packages/dd-trace/src/plugins/util/ci.js +34 -0
  122. package/packages/dd-trace/src/plugins/util/http-otel-semantics.js +9 -14
  123. package/packages/dd-trace/src/plugins/util/test.js +28 -1
  124. package/packages/dd-trace/src/plugins/util/url.js +8 -5
  125. package/packages/dd-trace/src/plugins/util/user-provided-git.js +4 -4
  126. package/packages/dd-trace/src/process-tags/index.js +1 -1
  127. package/packages/dd-trace/src/profiler.js +74 -12
  128. package/packages/dd-trace/src/profiling/profiler.js +30 -2
  129. package/packages/dd-trace/src/profiling/profilers/space.js +3 -1
  130. package/packages/dd-trace/src/profiling/profilers/wall.js +4 -4
  131. package/packages/dd-trace/src/profiling/remote-config.js +354 -0
  132. package/packages/dd-trace/src/profiling/runtime-capabilities.js +11 -0
  133. package/packages/dd-trace/src/propagation-hash/index.js +7 -0
  134. package/packages/dd-trace/src/proxy.js +13 -1
  135. package/vendor/dist/@opentelemetry/core/LICENSE +11 -0
  136. package/vendor/dist/@opentelemetry/core/index.js +1 -1
  137. package/vite.d.ts +7 -0
  138. package/vite.js +3 -0
  139. package/lambda.d.ts +0 -39
  140. package/lambda.js +0 -3
  141. package/packages/datadog-plugin-cypress/src/support.js +0 -1348
@@ -11,6 +11,7 @@ const {
11
11
  setInstrumentationHttpResource,
12
12
  } = require('../../dd-trace/src/plugins/util/http-otel-semantics')
13
13
  const { RESOURCE_NAME } = require('../../../ext/tags')
14
+ const satisfies = require('../../../vendor/dist/semifies')
14
15
  const { channel, addHook } = require('./helpers/instrument')
15
16
 
16
17
  const startChannel = channel('apm:next:request:start')
@@ -18,6 +19,7 @@ const finishChannel = channel('apm:next:request:finish')
18
19
  const errorChannel = channel('apm:next:request:error')
19
20
  const pageLoadChannel = channel('apm:next:page:load')
20
21
  const bodyParsedChannel = channel('apm:next:body-parsed')
22
+ const responseJsonChannel = channel('apm:next:response:json')
21
23
  const queryParsedChannel = channel('apm:next:query-parsed')
22
24
  const backgroundRevalidationChannel = channel('apm:next:request:background-revalidation')
23
25
 
@@ -42,6 +44,7 @@ const backgroundRevalidationChannel = channel('apm:next:request:background-reval
42
44
  * @property {boolean} [responseFinished]
43
45
  * @property {unknown} [error]
44
46
  * @property {NextRequest} [nextRequest]
47
+ * @property {(error: object) => void} ignoreError
45
48
  *
46
49
  * @typedef {object} ResponseGeneratorContext
47
50
  * @property {boolean} [hasResolved]
@@ -55,6 +58,7 @@ const backgroundRevalidationChannel = channel('apm:next:request:background-reval
55
58
  */
56
59
 
57
60
  const requests = new WeakSet()
61
+ const responseConstructors = new WeakSet()
58
62
  const nodeNextRequestsToNextRequests = new WeakMap()
59
63
  const noFallbackErrorPrototypes = new WeakSet()
60
64
  // Next.js <= 14.2.6
@@ -65,6 +69,19 @@ const NEXT_REQUEST_META = Symbol.for('NextInternalRequestMeta')
65
69
  const META_IS_MIDDLEWARE = 'middlewareInvoke'
66
70
  const encounteredMiddleware = new WeakSet()
67
71
 
72
+ const abortReasons = new WeakSet()
73
+ const incomingRequests = new WeakSet()
74
+ const blockableApiModules = new WeakMap()
75
+
76
+ /**
77
+ * Keeps an error a subscriber raised to stop the request, such as a blocked request, out of the request errors.
78
+ *
79
+ * @param {object} error
80
+ */
81
+ function ignoreError (error) {
82
+ abortReasons.add(error)
83
+ }
84
+
68
85
  // `next.span_type` value Next.js sets on its own OTel root request span; the whole detection surface.
69
86
  const NEXT_BASE_SERVER_HANDLE_REQUEST = 'BaseServer.handleRequest'
70
87
 
@@ -204,7 +221,7 @@ function getRequestMeta (req, key) {
204
221
  * @param {(ctx: NextRequestContext) => Promise<T>} handler
205
222
  * @param {unknown} [error]
206
223
  * @param {boolean} [finishOnResponse]
207
- * @returns {Promise<T>}
224
+ * @returns {Promise<T | undefined>}
208
225
  */
209
226
  function instrument (req, res, handler, error, finishOnResponse = false) {
210
227
  req = req.originalRequest || req
@@ -214,7 +231,7 @@ function instrument (req, res, handler, error, finishOnResponse = false) {
214
231
  const isMiddleware = req.headers[MIDDLEWARE_HEADER] || getRequestMeta(req, META_IS_MIDDLEWARE)
215
232
  if ((isMiddleware && !encounteredMiddleware.has(req)) || requests.has(req)) {
216
233
  encounteredMiddleware.add(req)
217
- if (error) {
234
+ if (error && !isIgnoredError(error)) {
218
235
  errorChannel.publish({ error })
219
236
  }
220
237
  return handler()
@@ -222,7 +239,7 @@ function instrument (req, res, handler, error, finishOnResponse = false) {
222
239
 
223
240
  requests.add(req)
224
241
 
225
- const ctx = finishOnResponse ? { req, res, finishOnResponse } : { req, res }
242
+ const ctx = finishOnResponse ? { req, res, finishOnResponse, ignoreError } : { req, res, ignoreError }
226
243
  if (finishOnResponse) {
227
244
  const onResponseFinish = () => {
228
245
  res.removeListener('finish', onResponseFinish)
@@ -237,14 +254,20 @@ function instrument (req, res, handler, error, finishOnResponse = false) {
237
254
  const queryIndex = req.url.indexOf('?')
238
255
  if (queryIndex !== -1) {
239
256
  const searchParams = new URLSearchParams(req.url.slice(queryIndex + 1))
240
- const query = {}
241
- for (const key of searchParams.keys()) {
242
- if (!query[key]) {
243
- query[key] = searchParams.getAll(key)
257
+ /** @type {Record<string, string[]>} */
258
+ const query = Object.create(null)
259
+ for (const [key, value] of searchParams) {
260
+ const values = query[key]
261
+ if (values === undefined) {
262
+ query[key] = [value]
263
+ } else {
264
+ values.push(value)
244
265
  }
245
266
  }
246
267
 
247
- queryParsedChannel.publish({ query })
268
+ const abortController = new AbortController()
269
+ queryParsedChannel.publish({ req, res, query, abortController })
270
+ if (abortController.signal.aborted) return /** @type {Promise<undefined>} */ (Promise.resolve())
248
271
  }
249
272
  }
250
273
 
@@ -294,7 +317,7 @@ function publishFinish (ctx, error) {
294
317
  function finish (ctx, result, error) {
295
318
  if (ctx.finishOnResponse) {
296
319
  ctx.handlerFinished = true
297
- if (error && !isNoFallbackError(error)) ctx.error = error
320
+ if (error && !isIgnoredError(error)) ctx.error = error
298
321
  if (!ctx.responseFinished) return
299
322
  }
300
323
 
@@ -306,13 +329,27 @@ function isNoFallbackError (error) {
306
329
  return isNativeError(error) && noFallbackErrorPrototypes.has(Object.getPrototypeOf(error))
307
330
  }
308
331
 
332
+ /**
333
+ * An error that keeps an abort reason as its own `cause`, whether it is a native error or not, comes from the same
334
+ * stop. Reading the own data property runs no getter of the application.
335
+ *
336
+ * @param {unknown} error
337
+ */
338
+ function isIgnoredError (error) {
339
+ if (typeof error !== 'object' || error === null) return false
340
+
341
+ return abortReasons.has(error) ||
342
+ abortReasons.has(Object.getOwnPropertyDescriptor(error, 'cause')?.value) ||
343
+ isNoFallbackError(error)
344
+ }
345
+
309
346
  /**
310
347
  * @param {NextNodeRequest} req
311
348
  * @param {NextRequestContext | undefined} ctx
312
349
  * @param {unknown} error
313
350
  */
314
351
  function publishError (req, ctx, error) {
315
- if (!error || isNoFallbackError(error)) return
352
+ if (!error || isIgnoredError(error)) return
316
353
 
317
354
  if (ctx) {
318
355
  ctx.error = error
@@ -335,6 +372,7 @@ addHook({
335
372
  return function (nodeNextRequest) {
336
373
  const nextRequest = fromNodeNextRequest.apply(this, arguments)
337
374
  nodeNextRequestsToNextRequests.set(nodeNextRequest.originalRequest, nextRequest)
375
+ if (bodyParsedChannel.hasSubscribers) incomingRequests.add(nextRequest)
338
376
  return nextRequest
339
377
  }
340
378
  })
@@ -402,6 +440,7 @@ function wrapAppRouteHandle (handle) {
402
440
  nodeNextRequestsToNextRequests.set(nodeRequest, req)
403
441
  }
404
442
  }
443
+ if (bodyParsedChannel.hasSubscribers) incomingRequests.add(req)
405
444
 
406
445
  return handle.apply(this, arguments)
407
446
  }
@@ -546,9 +585,13 @@ function wrapPagesApiRender (render) {
546
585
  }
547
586
  }
548
587
 
549
- function instrumentPagesApiRuntime (runtime) {
588
+ // Pages API routes run through the compiled runtime from Next.js 13.5, which inlines the body parser and apiResolver.
589
+ function instrumentPagesApiRuntime (runtime, version) {
550
590
  const PagesAPIRouteModule = runtime.PagesAPIRouteModule || runtime.default
551
- instrumentRouteModule(PagesAPIRouteModule, [['render', wrapPagesApiRender]], false)
591
+ const wrappers = [['render', wrapPagesApiRenderBody]]
592
+ // Keep wrapPagesApiRender on its previous >=15.4.1 range; the hook is widened only for the body wrapper.
593
+ if (satisfies(version, '>=15.4.1')) wrappers.push(['render', wrapPagesApiRender])
594
+ instrumentRouteModule(PagesAPIRouteModule, wrappers, false)
552
595
  return runtime
553
596
  }
554
597
 
@@ -561,18 +604,96 @@ function instrumentAppPageRuntime (runtime) {
561
604
  return runtime
562
605
  }
563
606
 
564
- for (const [runtime, instrumentRuntime] of [
565
- ['app-route', instrumentAppRouteRuntime],
566
- ['pages-api', instrumentPagesApiRuntime],
567
- ['app-page', instrumentAppPageRuntime],
568
- ]) {
607
+ for (const [runtime, instrumentRuntime, versions] of /** @type {const} */ ([
608
+ ['app-route', instrumentAppRouteRuntime, '>=15.4.1'],
609
+ ['pages-api', instrumentPagesApiRuntime, '>=13.5'],
610
+ ['app-page', instrumentAppPageRuntime, '>=15.4.1'],
611
+ ])) {
569
612
  addHook({
570
613
  name: 'next',
571
- versions: ['>=15.4.1'],
614
+ versions: [versions],
572
615
  filePattern: String.raw`${COMPILED_RUNTIME_PATH}${runtime}[\w-]*\.runtime\.(?:dev|prod)\.js$`,
573
616
  }, instrumentRuntime)
574
617
  }
575
618
 
619
+ /**
620
+ * @param {Function} handler
621
+ */
622
+ function wrapApiHandler (handler) {
623
+ return function (req, res) {
624
+ const { body } = req
625
+ if (bodyParsedChannel.hasSubscribers && body !== undefined && body !== '') {
626
+ const abortController = new AbortController()
627
+ bodyParsedChannel.publish({ req, res, body, abortController })
628
+ if (abortController.signal.aborted) return
629
+ }
630
+
631
+ return handler.apply(this, arguments)
632
+ }
633
+ }
634
+
635
+ /**
636
+ * Pages API modules expose the handler through a webpack export getter that can't be wrapped in place, so the
637
+ * module is replaced by one that inherits from it with a wrapped handler.
638
+ *
639
+ * @param {{ default?: unknown } | Function} apiModule
640
+ * @returns {{ default?: unknown } | Function}
641
+ */
642
+ function getBlockableApiModule (apiModule) {
643
+ let blockableModule = blockableApiModules.get(apiModule)
644
+ if (blockableModule) return blockableModule
645
+
646
+ const handler = apiModule?.default || apiModule
647
+ if (typeof handler !== 'function') return apiModule
648
+
649
+ blockableModule = Object.create(apiModule, { default: { value: wrapApiHandler(handler) } })
650
+ blockableApiModules.set(apiModule, blockableModule)
651
+ // wrapPagesApiRenderBody stores the replacement as `userland`, so later renders pass it back here: resolve it to
652
+ // itself instead of nesting another handler wrapper.
653
+ blockableApiModules.set(blockableModule, blockableModule)
654
+ return blockableModule
655
+ }
656
+
657
+ /**
658
+ * @param {Function} render
659
+ */
660
+ function wrapPagesApiRenderBody (render) {
661
+ /** @this {{ userland: { default?: unknown } }} */
662
+ return function () {
663
+ if (bodyParsedChannel.hasSubscribers) {
664
+ const blockableModule = getBlockableApiModule(this.userland)
665
+ if (blockableModule !== this.userland) {
666
+ // Next.js 16 exposes `userland` through a prototype getter, so shadow it instead of assigning it.
667
+ Object.defineProperty(this, 'userland', { value: blockableModule, configurable: true, writable: true })
668
+ }
669
+ }
670
+
671
+ return render.apply(this, arguments)
672
+ }
673
+ }
674
+
675
+ /**
676
+ * @param {Function} apiResolver
677
+ */
678
+ function wrapApiResolver (apiResolver) {
679
+ return function (...args) {
680
+ if (bodyParsedChannel.hasSubscribers) {
681
+ args[3] = getBlockableApiModule(args[3])
682
+ }
683
+
684
+ return Reflect.apply(apiResolver, this, args)
685
+ }
686
+ }
687
+
688
+ for (const file of ['dist/server/api-utils.js', 'dist/server/api-utils/node.js']) {
689
+ addHook({ name: 'next', versions: ['>=11.1 <13.5'], file }, apiUtils => {
690
+ const apiUtilsExports = /** @type {{ apiResolver?: Function }} */ (apiUtils)
691
+ if (typeof apiUtilsExports.apiResolver !== 'function') return apiUtils
692
+
693
+ return shimmer.wrap(apiUtilsExports, 'apiResolver', wrapApiResolver, { replaceGetter: true })
694
+ })
695
+ }
696
+
576
697
  addHook({
577
698
  name: 'next',
578
699
  versions: ['>=11.1'],
@@ -638,6 +759,23 @@ addHook({
638
759
  return nextServer
639
760
  })
640
761
 
762
+ /**
763
+ * @param {Request} request
764
+ * @param {unknown} body
765
+ */
766
+ function publishBodyParsed (request, body) {
767
+ if (!bodyParsedChannel.hasSubscribers) return
768
+
769
+ const abortController = incomingRequests.has(request) ? new AbortController() : undefined
770
+ bodyParsedChannel.publish({ body, abortController })
771
+
772
+ if (abortController?.signal.aborted) {
773
+ const { reason } = abortController.signal
774
+ abortReasons.add(reason)
775
+ throw reason
776
+ }
777
+ }
778
+
641
779
  addHook({
642
780
  name: 'next',
643
781
  versions: ['>=13'],
@@ -645,11 +783,25 @@ addHook({
645
783
  }, request => {
646
784
  const requestProto = Object.getPrototypeOf(request.NextRequest.prototype)
647
785
 
786
+ // Next bundles copies of NextResponse, but each delegates JSON serialization to the runtime's native/polyfill
787
+ // Response constructor. That constructor is selected at runtime and has no Next.js source function to rewrite.
788
+ const Response = globalThis.Response
789
+ if (typeof Response?.json === 'function' && !responseConstructors.has(Response)) {
790
+ responseConstructors.add(Response)
791
+ shimmer.wrap(Response, 'json', json => function (body) {
792
+ const response = json.apply(this, arguments)
793
+ if (responseJsonChannel.hasSubscribers) {
794
+ responseJsonChannel.publish({ body, stream: response.body })
795
+ }
796
+ return response
797
+ })
798
+ }
799
+
648
800
  shimmer.massWrap(requestProto, ['text', 'json'], function (originalMethod) {
649
801
  return async function wrappedJson () {
650
802
  const body = await originalMethod.apply(this, arguments)
651
803
 
652
- bodyParsedChannel.publish({ body })
804
+ publishBodyParsed(this, body)
653
805
 
654
806
  return body
655
807
  }
@@ -663,11 +815,23 @@ addHook({
663
815
  if (typeof body.entries === 'function') {
664
816
  normalizedBody = Object.fromEntries(body.entries())
665
817
  }
666
- bodyParsedChannel.publish({ body: normalizedBody })
818
+ publishBodyParsed(this, normalizedBody)
667
819
 
668
820
  return body
669
821
  }
670
822
  })
671
823
 
824
+ shimmer.wrap(requestProto, 'clone', function (originalClone) {
825
+ return function wrappedClone () {
826
+ const clone = originalClone.apply(this, arguments)
827
+
828
+ if (bodyParsedChannel.hasSubscribers && incomingRequests.has(this)) {
829
+ incomingRequests.add(clone)
830
+ }
831
+
832
+ return clone
833
+ }
834
+ })
835
+
672
836
  return request
673
837
  })
@@ -55,20 +55,24 @@ function annotateLayer (layer, matchers) {
55
55
  }
56
56
 
57
57
  /**
58
- * Resolve the route for a dispatched layer. Single-pattern layers carry a
59
- * constant route; only multi-pattern stacks need the per-request `layer.path`
60
- * match the host already computed.
58
+ * Single-pattern layers carry a constant route. Multi-pattern layers use the
59
+ * host's request-local pattern when available, or match its legacy `layer.path`.
61
60
  *
62
61
  * @param {{ captureRoute?: string, needMultiMatch: boolean,
63
62
  * matchers: Array<{ path?: string, regex?: RegExp }> }} meta
64
63
  * @param {{ path?: string }} layer
64
+ * @param {import('node:http').IncomingMessage} [req]
65
+ * @param {symbol} [matchedRoute]
65
66
  * @returns {string | undefined}
66
67
  */
67
- function resolveLayerRoute (meta, layer) {
68
+ function resolveLayerRoute (meta, layer, req, matchedRoute) {
68
69
  if (!meta.needMultiMatch) return meta.captureRoute
69
70
 
71
+ const pattern = matchedRoute && req[matchedRoute]
72
+ if (typeof pattern === 'string') return pattern
73
+
70
74
  for (const matcher of meta.matchers) {
71
- if (matcher.regex?.test(layer.path)) return matcher.path
75
+ if (matchedRoute ? matcher.regex === pattern : matcher.regex?.test(layer.path)) return matcher.path
72
76
  }
73
77
  }
74
78
 
@@ -80,11 +84,13 @@ function resolveLayerRoute (meta, layer) {
80
84
  * matchers: Array<{ path?: string, regex?: RegExp }> }} meta
81
85
  * @param {{ path?: string }} layer
82
86
  * @param {Function} next
87
+ * @param {import('node:http').IncomingMessage} req
88
+ * @param {symbol | undefined} matchedRoute
83
89
  * @returns {string | undefined | typeof ROUTE_RESOLUTION_FAILED}
84
90
  */
85
- function resolveLayerRouteOrForwardError (meta, layer, next) {
91
+ function resolveLayerRouteOrForwardError (meta, layer, next, req, matchedRoute) {
86
92
  try {
87
- return resolveLayerRoute(meta, layer)
93
+ return resolveLayerRoute(meta, layer, req, matchedRoute)
88
94
  } catch (error) {
89
95
  next(error)
90
96
  return ROUTE_RESOLUTION_FAILED
@@ -121,13 +127,14 @@ function adoptRequestNext (req, hostNext, wrappedNext) {
121
127
  * span is published only for the layer the host actually runs.
122
128
  *
123
129
  * @param {string} name Channel namespace (`apm:<name>:middleware:*`).
130
+ * @param {symbol} [matchedRoute] Native request-local route key, when provided by the host.
124
131
  * @returns {{
125
132
  * wrapLayerRequest: (originalRequest: Function) => Function,
126
133
  * wrapLayerError: (originalError: Function) => Function,
127
134
  * wrapLegacyHandle: (layer: object, original: Function, guardRepeatedNext?: boolean) => Function
128
135
  * }}
129
136
  */
130
- function createLayerDispatchWrappers (name) {
137
+ function createLayerDispatchWrappers (name, matchedRoute) {
131
138
  const enterChannel = channel(`apm:${name}:middleware:enter`)
132
139
  const exitChannel = channel(`apm:${name}:middleware:exit`)
133
140
  const finishChannel = channel(`apm:${name}:middleware:finish`)
@@ -188,7 +195,7 @@ function createLayerDispatchWrappers (name) {
188
195
 
189
196
  let route = meta.captureRoute
190
197
  if (meta.needMultiMatch) {
191
- route = resolveLayerRouteOrForwardError(meta, this, next)
198
+ route = resolveLayerRouteOrForwardError(meta, this, next, req, matchedRoute)
192
199
  if (route === ROUTE_RESOLUTION_FAILED) return
193
200
  }
194
201
 
@@ -217,7 +224,7 @@ function createLayerDispatchWrappers (name) {
217
224
 
218
225
  let route = meta.captureRoute
219
226
  if (meta.needMultiMatch) {
220
- route = resolveLayerRouteOrForwardError(meta, this, next)
227
+ route = resolveLayerRouteOrForwardError(meta, this, next, req, matchedRoute)
221
228
  if (route === ROUTE_RESOLUTION_FAILED) return
222
229
  }
223
230
 
@@ -644,10 +651,26 @@ function wrapHandleRequest (original) {
644
651
  }
645
652
  }
646
653
 
654
+ /** @type {Map<string | undefined, symbol>} */
655
+ const matchedRouteSymbols = new Map()
656
+
657
+ addHook({ name: 'router', file: 'lib/symbols.js', versions: ['>=2'] },
658
+ /**
659
+ * @param {{ matchedRoute: symbol }} symbols
660
+ * @param {string} version
661
+ * @param {boolean} isIitm
662
+ * @param {{ moduleBaseDir?: string }} hookMeta
663
+ */
664
+ function captureMatchedRoute (symbols, version, isIitm, { moduleBaseDir }) {
665
+ matchedRouteSymbols.set(moduleBaseDir, symbols.matchedRoute)
666
+ return symbols
667
+ })
668
+
647
669
  addHook({
648
670
  name: 'router', file: 'lib/layer.js', versions: ['>=2'],
649
- }, Layer => {
650
- const { wrapLayerRequest, wrapLayerError } = createLayerDispatchWrappers('router')
671
+ }, (Layer, version, isIitm, { moduleBaseDir }) => {
672
+ const matchedRoute = matchedRouteSymbols.get(moduleBaseDir)
673
+ const { wrapLayerRequest, wrapLayerError } = createLayerDispatchWrappers('router', matchedRoute)
651
674
 
652
675
  // `handleRequest` carries two concerns: the middleware dispatch span and the
653
676
  // param-start publish (`wrapHandleRequest`). Wrap the dispatch first so it
@@ -1197,6 +1197,11 @@ function safeWorkspaceProject (ctx) {
1197
1197
  return project
1198
1198
  }
1199
1199
 
1200
+ function hasCachedSpecifications (ctx) {
1201
+ const cachedSpecs = ctx?.specifications?._cachedSpecs
1202
+ return typeof cachedSpecs?.size === 'number' && cachedSpecs.size > 0
1203
+ }
1204
+
1200
1205
  function getSortWrapper (sort, frameworkVersion) {
1201
1206
  return async function () {
1202
1207
  if (this.ctx.config.shard && this.ctx.state.pathsSet.size > 0 && arguments[0].length === 0) {
@@ -1229,13 +1234,16 @@ function getFinishWrapper (exitOrClose) {
1229
1234
 
1230
1235
  // pathsSet contains candidates before sharding, including files that never run.
1231
1236
  const hasNoTestFiles = this.state.pathsSet.size === 0
1232
- const isEmptyShard = emptyShardContexts.has(this)
1237
+ const files = this.state.getFiles()
1238
+ const tests = getTypeTasks(files)
1239
+ const isEmptyShard = emptyShardContexts.has(this) ||
1240
+ (this.config.shard && this.config.passWithNoTests && !areAllSuitesSkipped &&
1241
+ files.length === 0 && hasCachedSpecifications(this))
1233
1242
  const hasUnexpectedEmptySession = hasNoTestFiles && !isEmptyShard &&
1234
1243
  !areAllSuitesSkipped && !this.config.passWithNoTests
1235
1244
  if (!error && hasUnexpectedEmptySession) {
1236
1245
  error = new Error('No test files were found.')
1237
1246
  }
1238
- const tests = getTypeTasks(this.state.getFiles())
1239
1247
  const hasExecutedTests = tests.some(test =>
1240
1248
  test.mode !== 'skip' && test.mode !== 'todo' &&
1241
1249
  (test.result?.state === 'pass' || test.result?.state === 'fail')
@@ -0,0 +1,41 @@
1
+ 'use strict'
2
+
3
+ // Ported from datadog-lambda-js at da9fc3c0c9dca00893f70c9a1bd5ac1254af3b01.
4
+
5
+ /**
6
+ * @param {string} arn
7
+ * @param {string} [version]
8
+ */
9
+ function parseLambdaARN (arn, version) {
10
+ let [, , , region, accountId, , functionname, alias] = arn.split(':')
11
+ const tags = { region, account_id: accountId, functionname }
12
+ // If we have an alias...
13
+ if (alias === undefined) {
14
+ tags.resource = functionname
15
+ } else {
16
+ // Check if $Latest and remove $ for datadog tag convention.
17
+ if (alias.startsWith('$')) {
18
+ alias = alias.slice(1)
19
+ // Check if this is an alias and not a version.
20
+ } else if (!Number(alias)) {
21
+ tags.executedversion = version
22
+ }
23
+ tags.resource = functionname + ':' + alias
24
+ }
25
+ return tags
26
+ }
27
+
28
+ /** @param {Record<string, string | undefined>} tags */
29
+ function makeTagStringsFromObject (tags) {
30
+ return Object.entries(tags).map(([tagKey, tagValue]) => `${tagKey}:${tagValue}`)
31
+ }
32
+
33
+ /**
34
+ * @param {string} arn
35
+ * @param {string} [version]
36
+ */
37
+ function parseTagsFromARN (arn, version) {
38
+ return makeTagStringsFromObject(parseLambdaARN(arn, version))
39
+ }
40
+
41
+ module.exports = { parseLambdaARN, parseTagsFromARN }