From 64781434428c31625de2a76d1632abf2ebaba4ed Mon Sep 17 00:00:00 2001 From: Nicolas Hrubec Date: Fri, 2 Jan 2026 16:19:55 +0100 Subject: [PATCH 01/22] Add first working version --- .../tanstackstart-react/src/middleware.ts | 35 ++++++ .../src/routes/test-middleware.tsx | 47 ++++++++ .../tanstackstart-react/src/start.ts | 9 ++ .../tests/middleware.test.ts | 91 ++++++++++++++++ .../tests/transaction.test.ts | 13 +-- .../tanstackstart-react/src/client/index.ts | 33 ++++++ .../tanstackstart-react/src/index.types.ts | 3 + .../tanstackstart-react/src/server/index.ts | 1 + .../src/server/middleware.ts | 102 ++++++++++++++++++ 9 files changed, 328 insertions(+), 6 deletions(-) create mode 100644 dev-packages/e2e-tests/test-applications/tanstackstart-react/src/middleware.ts create mode 100644 dev-packages/e2e-tests/test-applications/tanstackstart-react/src/routes/test-middleware.tsx create mode 100644 dev-packages/e2e-tests/test-applications/tanstackstart-react/src/start.ts create mode 100644 dev-packages/e2e-tests/test-applications/tanstackstart-react/tests/middleware.test.ts create mode 100644 packages/tanstackstart-react/src/server/middleware.ts diff --git a/dev-packages/e2e-tests/test-applications/tanstackstart-react/src/middleware.ts b/dev-packages/e2e-tests/test-applications/tanstackstart-react/src/middleware.ts new file mode 100644 index 000000000000..fcd62f600a14 --- /dev/null +++ b/dev-packages/e2e-tests/test-applications/tanstackstart-react/src/middleware.ts @@ -0,0 +1,35 @@ +import { createMiddleware } from '@tanstack/react-start'; +import { wrapMiddlewareWithSentry, wrapMiddlewareListWithSentry } from '@sentry/tanstackstart-react'; + +// Global request middleware - runs on every request +const globalRequestMiddleware = createMiddleware().server(async ({ next }) => { + console.log('Global request middleware executed'); + return next(); +}); + +// Global function middleware - runs on every server function +const globalFunctionMiddleware = createMiddleware({ type: 'function' }).server(async ({ next }) => { + console.log('Global function middleware executed'); + return next(); +}); + +// Server function specific middleware +const serverFnMiddleware = createMiddleware({ type: 'function' }).server(async ({ next }) => { + console.log('Server function middleware executed'); + return next(); +}); + +// Wrap global request middleware +export const wrappedGlobalRequestMiddleware = wrapMiddlewareWithSentry(globalRequestMiddleware, { + name: 'globalRequestMiddleware', +}); + +// Wrap global function middleware +export const wrappedGlobalFunctionMiddleware = wrapMiddlewareWithSentry(globalFunctionMiddleware, { + name: 'globalFunctionMiddleware', +}); + +// Wrap server function middleware using list wrapper +export const [wrappedServerFnMiddleware] = wrapMiddlewareListWithSentry({ + serverFnMiddleware, +}); diff --git a/dev-packages/e2e-tests/test-applications/tanstackstart-react/src/routes/test-middleware.tsx b/dev-packages/e2e-tests/test-applications/tanstackstart-react/src/routes/test-middleware.tsx new file mode 100644 index 000000000000..bc061b5bb0c1 --- /dev/null +++ b/dev-packages/e2e-tests/test-applications/tanstackstart-react/src/routes/test-middleware.tsx @@ -0,0 +1,47 @@ +import { createFileRoute } from '@tanstack/react-router'; +import { createServerFn } from '@tanstack/react-start'; +import { wrappedServerFnMiddleware } from '../middleware'; + +// Server function with specific middleware (also gets global function middleware) +const serverFnWithMiddleware = createServerFn() + .middleware([wrappedServerFnMiddleware]) + .handler(async () => { + console.log('Server function with specific middleware executed'); + return { message: 'Server function middleware test' }; + }); + +// Server function without specific middleware (only gets global function middleware) +const serverFnWithoutMiddleware = createServerFn().handler(async () => { + console.log('Server function without specific middleware executed'); + return { message: 'Global middleware only test' }; +}); + +export const Route = createFileRoute('/test-middleware')({ + component: TestMiddleware, +}); + +function TestMiddleware() { + return ( +
+

Test Middleware Page

+ + +
+ ); +} diff --git a/dev-packages/e2e-tests/test-applications/tanstackstart-react/src/start.ts b/dev-packages/e2e-tests/test-applications/tanstackstart-react/src/start.ts new file mode 100644 index 000000000000..eecd2816e492 --- /dev/null +++ b/dev-packages/e2e-tests/test-applications/tanstackstart-react/src/start.ts @@ -0,0 +1,9 @@ +import { createStart } from '@tanstack/react-start'; +import { wrappedGlobalRequestMiddleware, wrappedGlobalFunctionMiddleware } from './middleware'; + +export const startInstance = createStart(() => { + return { + requestMiddleware: [wrappedGlobalRequestMiddleware], + functionMiddleware: [wrappedGlobalFunctionMiddleware], + }; +}); diff --git a/dev-packages/e2e-tests/test-applications/tanstackstart-react/tests/middleware.test.ts b/dev-packages/e2e-tests/test-applications/tanstackstart-react/tests/middleware.test.ts new file mode 100644 index 000000000000..d494f27f54d0 --- /dev/null +++ b/dev-packages/e2e-tests/test-applications/tanstackstart-react/tests/middleware.test.ts @@ -0,0 +1,91 @@ +import { expect, test } from '@playwright/test'; +import { waitForTransaction } from '@sentry-internal/test-utils'; + +test('Sends spans for server function specific middleware', async ({ page }) => { + const transactionEventPromise = waitForTransaction('tanstackstart-react', transactionEvent => { + return ( + transactionEvent?.contexts?.trace?.op === 'http.server' && + !!transactionEvent?.transaction?.startsWith('GET /_serverFn') + ); + }); + + await page.goto('/test-middleware'); + await expect(page.locator('#server-fn-middleware-btn')).toBeVisible(); + await page.locator('#server-fn-middleware-btn').click(); + + const transactionEvent = await transactionEventPromise; + + expect(Array.isArray(transactionEvent?.spans)).toBe(true); + + // Check for the server function specific middleware span + expect(transactionEvent?.spans).toEqual( + expect.arrayContaining([ + expect.objectContaining({ + description: 'serverFnMiddleware', + op: 'middleware.tanstackstart', + origin: 'manual.middleware.tanstackstart', + data: expect.objectContaining({ + 'sentry.op': 'middleware.tanstackstart', + 'sentry.origin': 'manual.middleware.tanstackstart', + }), + status: 'ok', + }), + ]), + ); +}); + +test('Sends spans for global function middleware', async ({ page }) => { + const transactionEventPromise = waitForTransaction('tanstackstart-react', transactionEvent => { + return ( + transactionEvent?.contexts?.trace?.op === 'http.server' && + !!transactionEvent?.transaction?.startsWith('GET /_serverFn') + ); + }); + + await page.goto('/test-middleware'); + await expect(page.locator('#server-fn-global-only-btn')).toBeVisible(); + await page.locator('#server-fn-global-only-btn').click(); + + const transactionEvent = await transactionEventPromise; + + expect(Array.isArray(transactionEvent?.spans)).toBe(true); + + // Check for the global function middleware span + expect(transactionEvent?.spans).toEqual( + expect.arrayContaining([ + expect.objectContaining({ + description: 'globalFunctionMiddleware', + op: 'middleware.tanstackstart', + origin: 'manual.middleware.tanstackstart', + status: 'ok', + }), + ]), + ); +}); + +test('Sends spans for global request middleware on page load', async ({ page }) => { + const transactionEventPromise = waitForTransaction('tanstackstart-react', transactionEvent => { + return ( + transactionEvent?.contexts?.trace?.op === 'http.server' && + transactionEvent?.transaction === 'GET /test-middleware' + ); + }); + + await page.goto('/test-middleware'); + + const transactionEvent = await transactionEventPromise; + + expect(Array.isArray(transactionEvent?.spans)).toBe(true); + + // Check for the global request middleware span + expect(transactionEvent?.spans).toEqual( + expect.arrayContaining([ + expect.objectContaining({ + description: 'globalRequestMiddleware', + op: 'middleware.tanstackstart', + origin: 'manual.middleware.tanstackstart', + status: 'ok', + }), + ]), + ); +}); diff --git a/dev-packages/e2e-tests/test-applications/tanstackstart-react/tests/transaction.test.ts b/dev-packages/e2e-tests/test-applications/tanstackstart-react/tests/transaction.test.ts index d2ebbffb0ec0..82a79b0ef9f7 100644 --- a/dev-packages/e2e-tests/test-applications/tanstackstart-react/tests/transaction.test.ts +++ b/dev-packages/e2e-tests/test-applications/tanstackstart-react/tests/transaction.test.ts @@ -84,17 +84,18 @@ test('Sends a server function transaction for a nested server function only if i ]), ); - // Verify that the auto span is the parent of the nested span - const autoSpan = transactionEvent?.spans?.find( - (span: { op?: string; origin?: string }) => - span.op === 'function.tanstackstart' && span.origin === 'auto.function.tanstackstart.server', + // Verify that the globalFunctionMiddleware span is the parent of the nested span + // (middleware spans are inserted between the auto function span and user code) + const functionMiddlewareSpan = transactionEvent?.spans?.find( + (span: { description?: string; origin?: string }) => + span.description === 'globalFunctionMiddleware' && span.origin === 'manual.middleware.tanstackstart', ); const nestedSpan = transactionEvent?.spans?.find( (span: { description?: string; origin?: string }) => span.description === 'testNestedLog' && span.origin === 'manual', ); - expect(autoSpan).toBeDefined(); + expect(functionMiddlewareSpan).toBeDefined(); expect(nestedSpan).toBeDefined(); - expect(nestedSpan?.parent_span_id).toBe(autoSpan?.span_id); + expect(nestedSpan?.parent_span_id).toBe(functionMiddlewareSpan?.span_id); }); diff --git a/packages/tanstackstart-react/src/client/index.ts b/packages/tanstackstart-react/src/client/index.ts index 2299b46b7d64..264541b03eba 100644 --- a/packages/tanstackstart-react/src/client/index.ts +++ b/packages/tanstackstart-react/src/client/index.ts @@ -4,3 +4,36 @@ export * from '@sentry/react'; export { init } from './sdk'; + +type TanStackMiddleware = { + options: { type: string; server: (...args: unknown[]) => unknown }; + middleware: (...args: unknown[]) => unknown; + inputValidator: (...args: unknown[]) => unknown; + client: (...args: unknown[]) => unknown; + server: (...args: unknown[]) => unknown; +}; + +type MiddlewareWrapperOptions = { + name: string; +}; + +/** + * No-op stub for client-side builds. + * The actual implementation is server-only, but this stub allows isomorphic code + * that imports these functions to build successfully on the client. + */ +export function wrapMiddlewareWithSentry( + middleware: T, + _options: MiddlewareWrapperOptions, +): T { + return middleware; +} + +/** + * No-op stub for client-side builds. + * The actual implementation is server-only, but this stub allows isomorphic code + * that imports these functions to build successfully on the client. + */ +export function wrapMiddlewareListWithSentry(middlewares: Record): T[] { + return Object.values(middlewares); +} diff --git a/packages/tanstackstart-react/src/index.types.ts b/packages/tanstackstart-react/src/index.types.ts index cf624f5a1a0b..27c46d3ce733 100644 --- a/packages/tanstackstart-react/src/index.types.ts +++ b/packages/tanstackstart-react/src/index.types.ts @@ -34,3 +34,6 @@ export declare const openFeatureIntegration: typeof clientSdk.openFeatureIntegra export declare const OpenFeatureIntegrationHook: typeof clientSdk.OpenFeatureIntegrationHook; export declare const statsigIntegration: typeof clientSdk.statsigIntegration; export declare const unleashIntegration: typeof clientSdk.unleashIntegration; + +export declare const wrapMiddlewareWithSentry: typeof serverSdk.wrapMiddlewareWithSentry; +export declare const wrapMiddlewareListWithSentry: typeof serverSdk.wrapMiddlewareListWithSentry; diff --git a/packages/tanstackstart-react/src/server/index.ts b/packages/tanstackstart-react/src/server/index.ts index 299f1cd85ea9..08b60c043141 100644 --- a/packages/tanstackstart-react/src/server/index.ts +++ b/packages/tanstackstart-react/src/server/index.ts @@ -5,6 +5,7 @@ export * from '@sentry/node'; export { init } from './sdk'; export { wrapFetchWithSentry } from './wrapFetchWithSentry'; +export { wrapMiddlewareWithSentry, wrapMiddlewareListWithSentry } from './middleware'; /** * A passthrough error boundary for the server that doesn't depend on any react. Error boundaries don't catch SSR errors diff --git a/packages/tanstackstart-react/src/server/middleware.ts b/packages/tanstackstart-react/src/server/middleware.ts new file mode 100644 index 000000000000..1aea00d4ed92 --- /dev/null +++ b/packages/tanstackstart-react/src/server/middleware.ts @@ -0,0 +1,102 @@ +import { SEMANTIC_ATTRIBUTE_SENTRY_OP, SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN, startSpan } from '@sentry/node'; + +const SENTRY_WRAPPED = Symbol.for('sentry.middleware.wrapped'); + +type TanStackMiddleware = { + options: { type: string; server: (...args: unknown[]) => unknown }; + middleware: (...args: unknown[]) => unknown; + inputValidator: (...args: unknown[]) => unknown; + client: (...args: unknown[]) => unknown; + server: (...args: unknown[]) => unknown; +}; + +type MiddlewareWrapperOptions = { + name: string; +}; + +/** + * Wraps a TanStack Start middleware with Sentry instrumentation to create spans. + * + * @example + * ```ts + * import { wrapMiddlewareWithSentry } from '@sentry/tanstackstart-react'; + * import { createMiddleware } from '@tanstack/react-start'; + * + * const authMiddleware = wrapMiddlewareWithSentry( + * createMiddleware().server(async ({ next }) => { + * // auth logic + * return next(); + * }), + * { name: 'authMiddleware' } + * ); + * ``` + * + * @param middleware - The TanStack Start middleware to wrap + * @param options - Options for the wrapper, including the span name + * @returns The wrapped middleware with Sentry instrumentation + */ +export function wrapMiddlewareWithSentry( + middleware: T, + options: MiddlewareWrapperOptions, +): T { + // Check for double-wrapping + if ((middleware as unknown as Record)[SENTRY_WRAPPED]) { + return middleware; + } + + const originalServerFn = middleware.options.server; + + // Wrap the options.server function (this is what TanStack Start actually calls) + const wrappedServerFn = function (this: unknown, ...args: unknown[]): unknown { + return startSpan( + { + op: 'middleware.tanstackstart', + name: options.name, + attributes: { + [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'manual.middleware.tanstackstart', + [SEMANTIC_ATTRIBUTE_SENTRY_OP]: 'middleware.tanstackstart', + }, + }, + () => originalServerFn.apply(this, args), + ); + }; + + // Create a new middleware object with the wrapped server function + const wrappedMiddleware = { + ...middleware, + options: { + ...middleware.options, + server: wrappedServerFn, + }, + }; + + // Mark the whole object as wrapped + Object.defineProperty(wrappedMiddleware, SENTRY_WRAPPED, { value: true }); + + return wrappedMiddleware as T; +} + +/** + * Wraps multiple TanStack Start middlewares with Sentry instrumentation. + * Object keys are used as span names to avoid users having to specify this manually. + * + * @example + * ```ts + * import { wrapMiddlewareListWithSentry } from '@sentry/tanstackstart-react'; + * + * const wrappedMiddlewares = wrapMiddlewareListWithSentry({ + * authMiddleware, + * loggingMiddleware, + * }); + * + * createServerFn().middleware(wrappedMiddlewares) + * ``` + * + * @param middlewares - An object containing middlewares + * @returns An array of wrapped middlewares + */ +export function wrapMiddlewareListWithSentry(middlewares: Record): T[] { + return Object.entries(middlewares).map(([name, middleware]) => { + return wrapMiddlewareWithSentry(middleware, { name }); + }); +} From 538066abb3d92e2922eaf72e410848dc728ff22b Mon Sep 17 00:00:00 2001 From: Nicolas Hrubec Date: Fri, 2 Jan 2026 16:44:18 +0100 Subject: [PATCH 02/22] Use proxy --- .../src/server/middleware.ts | 51 +++++++------------ 1 file changed, 17 insertions(+), 34 deletions(-) diff --git a/packages/tanstackstart-react/src/server/middleware.ts b/packages/tanstackstart-react/src/server/middleware.ts index 1aea00d4ed92..c9d5e2e0e9b1 100644 --- a/packages/tanstackstart-react/src/server/middleware.ts +++ b/packages/tanstackstart-react/src/server/middleware.ts @@ -3,11 +3,7 @@ import { SEMANTIC_ATTRIBUTE_SENTRY_OP, SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN, startSp const SENTRY_WRAPPED = Symbol.for('sentry.middleware.wrapped'); type TanStackMiddleware = { - options: { type: string; server: (...args: unknown[]) => unknown }; - middleware: (...args: unknown[]) => unknown; - inputValidator: (...args: unknown[]) => unknown; - client: (...args: unknown[]) => unknown; - server: (...args: unknown[]) => unknown; + options: { server: (...args: unknown[]) => unknown }; }; type MiddlewareWrapperOptions = { @@ -39,41 +35,28 @@ export function wrapMiddlewareWithSentry( middleware: T, options: MiddlewareWrapperOptions, ): T { - // Check for double-wrapping - if ((middleware as unknown as Record)[SENTRY_WRAPPED]) { + if ((middleware as Record)[SENTRY_WRAPPED]) { return middleware; } - const originalServerFn = middleware.options.server; - - // Wrap the options.server function (this is what TanStack Start actually calls) - const wrappedServerFn = function (this: unknown, ...args: unknown[]): unknown { - return startSpan( - { - op: 'middleware.tanstackstart', - name: options.name, - attributes: { - [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'manual.middleware.tanstackstart', - [SEMANTIC_ATTRIBUTE_SENTRY_OP]: 'middleware.tanstackstart', + middleware.options.server = new Proxy(middleware.options.server, { + apply: (target, thisArg, args) => { + return startSpan( + { + op: 'middleware.tanstackstart', + name: options.name, + attributes: { + [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'manual.middleware.tanstackstart', + [SEMANTIC_ATTRIBUTE_SENTRY_OP]: 'middleware.tanstackstart', + }, }, - }, - () => originalServerFn.apply(this, args), - ); - }; - - // Create a new middleware object with the wrapped server function - const wrappedMiddleware = { - ...middleware, - options: { - ...middleware.options, - server: wrappedServerFn, + () => target.apply(thisArg, args), + ); }, - }; - - // Mark the whole object as wrapped - Object.defineProperty(wrappedMiddleware, SENTRY_WRAPPED, { value: true }); + }); - return wrappedMiddleware as T; + Object.defineProperty(middleware, SENTRY_WRAPPED, { value: true }); + return middleware; } /** From e67f0844d97c9dd7d561d7b0efa55a0b379cebce Mon Sep 17 00:00:00 2001 From: Nicolas Hrubec Date: Fri, 2 Jan 2026 16:52:57 +0100 Subject: [PATCH 03/22] remove T typing --- packages/tanstackstart-react/src/server/middleware.ts | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/packages/tanstackstart-react/src/server/middleware.ts b/packages/tanstackstart-react/src/server/middleware.ts index c9d5e2e0e9b1..eec5a3d1aeb1 100644 --- a/packages/tanstackstart-react/src/server/middleware.ts +++ b/packages/tanstackstart-react/src/server/middleware.ts @@ -31,10 +31,10 @@ type MiddlewareWrapperOptions = { * @param options - Options for the wrapper, including the span name * @returns The wrapped middleware with Sentry instrumentation */ -export function wrapMiddlewareWithSentry( - middleware: T, +export function wrapMiddlewareWithSentry( + middleware: TanStackMiddleware, options: MiddlewareWrapperOptions, -): T { +): TanStackMiddleware { if ((middleware as Record)[SENTRY_WRAPPED]) { return middleware; } @@ -78,7 +78,7 @@ export function wrapMiddlewareWithSentry( * @param middlewares - An object containing middlewares * @returns An array of wrapped middlewares */ -export function wrapMiddlewareListWithSentry(middlewares: Record): T[] { +export function wrapMiddlewareListWithSentry(middlewares: Record): TanStackMiddleware[] { return Object.entries(middlewares).map(([name, middleware]) => { return wrapMiddlewareWithSentry(middleware, { name }); }); From 1cb5cedd711f272f6aa8cee9d2db57cd38547971 Mon Sep 17 00:00:00 2001 From: Nicolas Hrubec Date: Fri, 2 Jan 2026 17:08:39 +0100 Subject: [PATCH 04/22] Be more defensive --- .../src/server/middleware.ts | 40 ++++++++++--------- 1 file changed, 21 insertions(+), 19 deletions(-) diff --git a/packages/tanstackstart-react/src/server/middleware.ts b/packages/tanstackstart-react/src/server/middleware.ts index eec5a3d1aeb1..115d817b421f 100644 --- a/packages/tanstackstart-react/src/server/middleware.ts +++ b/packages/tanstackstart-react/src/server/middleware.ts @@ -1,9 +1,9 @@ +import { addNonEnumerableProperty } from '@sentry/core'; import { SEMANTIC_ATTRIBUTE_SENTRY_OP, SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN, startSpan } from '@sentry/node'; -const SENTRY_WRAPPED = Symbol.for('sentry.middleware.wrapped'); - type TanStackMiddleware = { - options: { server: (...args: unknown[]) => unknown }; + options?: { server?: (...args: unknown[]) => unknown }; + SENTRY_WRAPPED?: boolean; }; type MiddlewareWrapperOptions = { @@ -35,27 +35,29 @@ export function wrapMiddlewareWithSentry( middleware: TanStackMiddleware, options: MiddlewareWrapperOptions, ): TanStackMiddleware { - if ((middleware as Record)[SENTRY_WRAPPED]) { + if (middleware.SENTRY_WRAPPED) { return middleware; } - middleware.options.server = new Proxy(middleware.options.server, { - apply: (target, thisArg, args) => { - return startSpan( - { - op: 'middleware.tanstackstart', - name: options.name, - attributes: { - [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'manual.middleware.tanstackstart', - [SEMANTIC_ATTRIBUTE_SENTRY_OP]: 'middleware.tanstackstart', + if (middleware.options?.server) { + middleware.options.server = new Proxy(middleware.options.server, { + apply: (target, thisArg, args) => { + return startSpan( + { + op: 'middleware.tanstackstart', + name: options.name, + attributes: { + [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'manual.middleware.tanstackstart', + [SEMANTIC_ATTRIBUTE_SENTRY_OP]: 'middleware.tanstackstart', + }, }, - }, - () => target.apply(thisArg, args), - ); - }, - }); + () => target.apply(thisArg, args), + ); + }, + }); + } - Object.defineProperty(middleware, SENTRY_WRAPPED, { value: true }); + addNonEnumerableProperty(middleware, 'SENTRY_WRAPPED', true); return middleware; } From b18ebb52cec5c58afc5d9851d4bf887c2e400efc Mon Sep 17 00:00:00 2001 From: Nicolas Hrubec Date: Fri, 2 Jan 2026 17:24:34 +0100 Subject: [PATCH 05/22] Add test for request route middleware --- .../tanstackstart-react/src/middleware.ts | 9 ++++++- .../src/routes/api.test-middleware.ts | 13 +++++++++ .../tests/middleware.test.ts | 27 +++++++++++++++++++ 3 files changed, 48 insertions(+), 1 deletion(-) create mode 100644 dev-packages/e2e-tests/test-applications/tanstackstart-react/src/routes/api.test-middleware.ts diff --git a/dev-packages/e2e-tests/test-applications/tanstackstart-react/src/middleware.ts b/dev-packages/e2e-tests/test-applications/tanstackstart-react/src/middleware.ts index fcd62f600a14..07452b5eafaa 100644 --- a/dev-packages/e2e-tests/test-applications/tanstackstart-react/src/middleware.ts +++ b/dev-packages/e2e-tests/test-applications/tanstackstart-react/src/middleware.ts @@ -19,6 +19,12 @@ const serverFnMiddleware = createMiddleware({ type: 'function' }).server(async ( return next(); }); +// Server route specific request middleware +const serverRouteRequestMiddleware = createMiddleware().server(async ({ next }) => { + console.log('Server route request middleware executed'); + return next(); +}); + // Wrap global request middleware export const wrappedGlobalRequestMiddleware = wrapMiddlewareWithSentry(globalRequestMiddleware, { name: 'globalRequestMiddleware', @@ -30,6 +36,7 @@ export const wrappedGlobalFunctionMiddleware = wrapMiddlewareWithSentry(globalFu }); // Wrap server function middleware using list wrapper -export const [wrappedServerFnMiddleware] = wrapMiddlewareListWithSentry({ +export const [wrappedServerFnMiddleware, wrappedServerRouteRequestMiddleware] = wrapMiddlewareListWithSentry({ serverFnMiddleware, + serverRouteRequestMiddleware, }); diff --git a/dev-packages/e2e-tests/test-applications/tanstackstart-react/src/routes/api.test-middleware.ts b/dev-packages/e2e-tests/test-applications/tanstackstart-react/src/routes/api.test-middleware.ts new file mode 100644 index 000000000000..1bf3fdb1c5da --- /dev/null +++ b/dev-packages/e2e-tests/test-applications/tanstackstart-react/src/routes/api.test-middleware.ts @@ -0,0 +1,13 @@ +import { createFileRoute } from '@tanstack/react-router'; +import { wrappedServerRouteRequestMiddleware } from '../middleware'; + +export const Route = createFileRoute('/api/test-middleware')({ + server: { + middleware: [wrappedServerRouteRequestMiddleware], + handlers: { + GET: async () => { + return { message: 'Server route middleware test' }; + }, + }, + }, +}); diff --git a/dev-packages/e2e-tests/test-applications/tanstackstart-react/tests/middleware.test.ts b/dev-packages/e2e-tests/test-applications/tanstackstart-react/tests/middleware.test.ts index d494f27f54d0..03c7742fb431 100644 --- a/dev-packages/e2e-tests/test-applications/tanstackstart-react/tests/middleware.test.ts +++ b/dev-packages/e2e-tests/test-applications/tanstackstart-react/tests/middleware.test.ts @@ -89,3 +89,30 @@ test('Sends spans for global request middleware on page load', async ({ page }) ]), ); }); + +test('Sends spans for server route specific request middleware', async ({ page }) => { + const transactionEventPromise = waitForTransaction('tanstackstart-react', transactionEvent => { + return ( + transactionEvent?.contexts?.trace?.op === 'http.server' && + transactionEvent?.transaction === 'GET /api/test-middleware' + ); + }); + + await page.goto('/api/test-middleware'); + + const transactionEvent = await transactionEventPromise; + + expect(Array.isArray(transactionEvent?.spans)).toBe(true); + + // Check for the server route specific request middleware span + expect(transactionEvent?.spans).toEqual( + expect.arrayContaining([ + expect.objectContaining({ + description: 'serverRouteRequestMiddleware', + op: 'middleware.tanstackstart', + origin: 'manual.middleware.tanstackstart', + status: 'ok', + }), + ]), + ); +}); From 05edb2ff75fd3a1f2e6928b6373b18c96c694c6f Mon Sep 17 00:00:00 2001 From: Nicolas Hrubec Date: Mon, 5 Jan 2026 14:25:42 +0100 Subject: [PATCH 06/22] cleaning up types --- .../tanstackstart-react/src/client/index.ts | 18 +++--------------- .../tanstackstart-react/src/common/index.ts | 2 +- .../tanstackstart-react/src/common/types.ts | 8 ++++++++ .../src/server/middleware.ts | 18 +++++++----------- 4 files changed, 19 insertions(+), 27 deletions(-) create mode 100644 packages/tanstackstart-react/src/common/types.ts diff --git a/packages/tanstackstart-react/src/client/index.ts b/packages/tanstackstart-react/src/client/index.ts index 264541b03eba..2d5e611588c3 100644 --- a/packages/tanstackstart-react/src/client/index.ts +++ b/packages/tanstackstart-react/src/client/index.ts @@ -5,22 +5,11 @@ export * from '@sentry/react'; export { init } from './sdk'; -type TanStackMiddleware = { - options: { type: string; server: (...args: unknown[]) => unknown }; - middleware: (...args: unknown[]) => unknown; - inputValidator: (...args: unknown[]) => unknown; - client: (...args: unknown[]) => unknown; - server: (...args: unknown[]) => unknown; -}; - -type MiddlewareWrapperOptions = { - name: string; -}; +import type { MiddlewareWrapperOptions, TanStackMiddleware } from '../common/types'; /** * No-op stub for client-side builds. - * The actual implementation is server-only, but this stub allows isomorphic code - * that imports these functions to build successfully on the client. + * The actual implementation is server-only, but this stub is needed to prevent build errors. */ export function wrapMiddlewareWithSentry( middleware: T, @@ -31,8 +20,7 @@ export function wrapMiddlewareWithSentry( /** * No-op stub for client-side builds. - * The actual implementation is server-only, but this stub allows isomorphic code - * that imports these functions to build successfully on the client. + * The actual implementation is server-only, but this stub is needed to prevent build errors. */ export function wrapMiddlewareListWithSentry(middlewares: Record): T[] { return Object.values(middlewares); diff --git a/packages/tanstackstart-react/src/common/index.ts b/packages/tanstackstart-react/src/common/index.ts index cb0ff5c3b541..1fa8830b947a 100644 --- a/packages/tanstackstart-react/src/common/index.ts +++ b/packages/tanstackstart-react/src/common/index.ts @@ -1 +1 @@ -export {}; +export type { TanStackMiddleware, MiddlewareWrapperOptions } from './types'; diff --git a/packages/tanstackstart-react/src/common/types.ts b/packages/tanstackstart-react/src/common/types.ts new file mode 100644 index 000000000000..c876268a631a --- /dev/null +++ b/packages/tanstackstart-react/src/common/types.ts @@ -0,0 +1,8 @@ +export type TanStackMiddleware = { + options?: { server?: (...args: unknown[]) => unknown }; + __SENTRY_WRAPPED__?: boolean; +}; + +export type MiddlewareWrapperOptions = { + name: string; +}; diff --git a/packages/tanstackstart-react/src/server/middleware.ts b/packages/tanstackstart-react/src/server/middleware.ts index 115d817b421f..a0f4f41e76bc 100644 --- a/packages/tanstackstart-react/src/server/middleware.ts +++ b/packages/tanstackstart-react/src/server/middleware.ts @@ -1,14 +1,6 @@ import { addNonEnumerableProperty } from '@sentry/core'; import { SEMANTIC_ATTRIBUTE_SENTRY_OP, SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN, startSpan } from '@sentry/node'; - -type TanStackMiddleware = { - options?: { server?: (...args: unknown[]) => unknown }; - SENTRY_WRAPPED?: boolean; -}; - -type MiddlewareWrapperOptions = { - name: string; -}; +import type { MiddlewareWrapperOptions, TanStackMiddleware } from '../common/types'; /** * Wraps a TanStack Start middleware with Sentry instrumentation to create spans. @@ -35,10 +27,12 @@ export function wrapMiddlewareWithSentry( middleware: TanStackMiddleware, options: MiddlewareWrapperOptions, ): TanStackMiddleware { - if (middleware.SENTRY_WRAPPED) { + if (middleware.__SENTRY_WRAPPED__) { + // already instrumented return middleware; } + // instrument server middleware if (middleware.options?.server) { middleware.options.server = new Proxy(middleware.options.server, { apply: (target, thisArg, args) => { @@ -57,7 +51,9 @@ export function wrapMiddlewareWithSentry( }); } - addNonEnumerableProperty(middleware, 'SENTRY_WRAPPED', true); + // mark as instrumented + addNonEnumerableProperty(middleware, '__SENTRY_WRAPPED__', true); + return middleware; } From 05bb46d45abfd95687fdc7df6e9650d9964a38cd Mon Sep 17 00:00:00 2001 From: Nicolas Hrubec Date: Mon, 5 Jan 2026 15:14:40 +0100 Subject: [PATCH 07/22] make middleware type generic --- .../tanstackstart-react/src/client/index.ts | 6 ++--- .../tanstackstart-react/src/common/index.ts | 2 +- .../tanstackstart-react/src/common/types.ts | 3 +-- .../src/server/middleware.ts | 22 +++++++++++-------- 4 files changed, 18 insertions(+), 15 deletions(-) diff --git a/packages/tanstackstart-react/src/client/index.ts b/packages/tanstackstart-react/src/client/index.ts index 2d5e611588c3..d86b3c804a0b 100644 --- a/packages/tanstackstart-react/src/client/index.ts +++ b/packages/tanstackstart-react/src/client/index.ts @@ -5,13 +5,13 @@ export * from '@sentry/react'; export { init } from './sdk'; -import type { MiddlewareWrapperOptions, TanStackMiddleware } from '../common/types'; +import type { MiddlewareWrapperOptions, TanStackMiddlewareBase } from '../common/types'; /** * No-op stub for client-side builds. * The actual implementation is server-only, but this stub is needed to prevent build errors. */ -export function wrapMiddlewareWithSentry( +export function wrapMiddlewareWithSentry( middleware: T, _options: MiddlewareWrapperOptions, ): T { @@ -22,6 +22,6 @@ export function wrapMiddlewareWithSentry( * No-op stub for client-side builds. * The actual implementation is server-only, but this stub is needed to prevent build errors. */ -export function wrapMiddlewareListWithSentry(middlewares: Record): T[] { +export function wrapMiddlewareListWithSentry(middlewares: Record): T[] { return Object.values(middlewares); } diff --git a/packages/tanstackstart-react/src/common/index.ts b/packages/tanstackstart-react/src/common/index.ts index 1fa8830b947a..0fbc5e41ca34 100644 --- a/packages/tanstackstart-react/src/common/index.ts +++ b/packages/tanstackstart-react/src/common/index.ts @@ -1 +1 @@ -export type { TanStackMiddleware, MiddlewareWrapperOptions } from './types'; +export type { TanStackMiddlewareBase, MiddlewareWrapperOptions } from './types'; diff --git a/packages/tanstackstart-react/src/common/types.ts b/packages/tanstackstart-react/src/common/types.ts index c876268a631a..82e20754cb72 100644 --- a/packages/tanstackstart-react/src/common/types.ts +++ b/packages/tanstackstart-react/src/common/types.ts @@ -1,6 +1,5 @@ -export type TanStackMiddleware = { +export type TanStackMiddlewareBase = { options?: { server?: (...args: unknown[]) => unknown }; - __SENTRY_WRAPPED__?: boolean; }; export type MiddlewareWrapperOptions = { diff --git a/packages/tanstackstart-react/src/server/middleware.ts b/packages/tanstackstart-react/src/server/middleware.ts index a0f4f41e76bc..bf007631b04e 100644 --- a/packages/tanstackstart-react/src/server/middleware.ts +++ b/packages/tanstackstart-react/src/server/middleware.ts @@ -1,6 +1,8 @@ import { addNonEnumerableProperty } from '@sentry/core'; import { SEMANTIC_ATTRIBUTE_SENTRY_OP, SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN, startSpan } from '@sentry/node'; -import type { MiddlewareWrapperOptions, TanStackMiddleware } from '../common/types'; +import type { MiddlewareWrapperOptions, TanStackMiddlewareBase } from '../common/types'; + +const SENTRY_WRAPPED = '__SENTRY_WRAPPED__'; /** * Wraps a TanStack Start middleware with Sentry instrumentation to create spans. @@ -23,11 +25,11 @@ import type { MiddlewareWrapperOptions, TanStackMiddleware } from '../common/typ * @param options - Options for the wrapper, including the span name * @returns The wrapped middleware with Sentry instrumentation */ -export function wrapMiddlewareWithSentry( - middleware: TanStackMiddleware, +export function wrapMiddlewareWithSentry( + middleware: T, options: MiddlewareWrapperOptions, -): TanStackMiddleware { - if (middleware.__SENTRY_WRAPPED__) { +): T { + if ((middleware as TanStackMiddlewareBase & { [SENTRY_WRAPPED]?: boolean })[SENTRY_WRAPPED]) { // already instrumented return middleware; } @@ -49,10 +51,10 @@ export function wrapMiddlewareWithSentry( ); }, }); - } - // mark as instrumented - addNonEnumerableProperty(middleware, '__SENTRY_WRAPPED__', true); + // mark as instrumented + addNonEnumerableProperty(middleware as unknown as Record, SENTRY_WRAPPED, true); + } return middleware; } @@ -76,7 +78,9 @@ export function wrapMiddlewareWithSentry( * @param middlewares - An object containing middlewares * @returns An array of wrapped middlewares */ -export function wrapMiddlewareListWithSentry(middlewares: Record): TanStackMiddleware[] { +export function wrapMiddlewareListWithSentry( + middlewares: Record, +): T[] { return Object.entries(middlewares).map(([name, middleware]) => { return wrapMiddlewareWithSentry(middleware, { name }); }); From c119ee3ba7744d6c980b1c7fe96689bc24571490 Mon Sep 17 00:00:00 2001 From: Nicolas Hrubec Date: Mon, 5 Jan 2026 16:34:02 +0100 Subject: [PATCH 08/22] proxy next --- .../_tanstack-start-manifest_v-CS8AEhoz.js | 4 + .../ssr/assets/createSsrRpc-mJR5gjC5.js | 16 + .../services/ssr/assets/index-Byn0LoyG.js | 15 + .../services/ssr/assets/index-D3FWW_HK.js | 26 + .../ssr/assets/middleware-BDyeOn_H.js | 107 + .../services/ssr/assets/router-DIOBJIBx.js | 32549 +++++++++++++ .../services/ssr/assets/start-CoL2Pr07.js | 46 + .../ssr/assets/test-middleware-B3Fw5htt.js | 26 + .../ssr/assets/test-middleware-D8HJv8ES.js | 27 + .../ssr/assets/test-serverFn-BuIGT-94.js | 25 + .../ssr/assets/test-serverFn-DsUG4NI8.js | 31 + .../.nitro/vite/services/ssr/server.js | 40638 ++++++++++++++++ .../tanstackstart-react/src/routeTree.gen.ts | 157 + .../tests/transaction.test.ts | 7 +- .../src/server/middleware.ts | 53 +- .../tanstackstart-react/src/server/utils.ts | 16 + 16 files changed, 73727 insertions(+), 16 deletions(-) create mode 100644 dev-packages/e2e-tests/test-applications/tanstackstart-react/.nitro/vite/services/ssr/assets/_tanstack-start-manifest_v-CS8AEhoz.js create mode 100644 dev-packages/e2e-tests/test-applications/tanstackstart-react/.nitro/vite/services/ssr/assets/createSsrRpc-mJR5gjC5.js create mode 100644 dev-packages/e2e-tests/test-applications/tanstackstart-react/.nitro/vite/services/ssr/assets/index-Byn0LoyG.js create mode 100644 dev-packages/e2e-tests/test-applications/tanstackstart-react/.nitro/vite/services/ssr/assets/index-D3FWW_HK.js create mode 100644 dev-packages/e2e-tests/test-applications/tanstackstart-react/.nitro/vite/services/ssr/assets/middleware-BDyeOn_H.js create mode 100644 dev-packages/e2e-tests/test-applications/tanstackstart-react/.nitro/vite/services/ssr/assets/router-DIOBJIBx.js create mode 100644 dev-packages/e2e-tests/test-applications/tanstackstart-react/.nitro/vite/services/ssr/assets/start-CoL2Pr07.js create mode 100644 dev-packages/e2e-tests/test-applications/tanstackstart-react/.nitro/vite/services/ssr/assets/test-middleware-B3Fw5htt.js create mode 100644 dev-packages/e2e-tests/test-applications/tanstackstart-react/.nitro/vite/services/ssr/assets/test-middleware-D8HJv8ES.js create mode 100644 dev-packages/e2e-tests/test-applications/tanstackstart-react/.nitro/vite/services/ssr/assets/test-serverFn-BuIGT-94.js create mode 100644 dev-packages/e2e-tests/test-applications/tanstackstart-react/.nitro/vite/services/ssr/assets/test-serverFn-DsUG4NI8.js create mode 100644 dev-packages/e2e-tests/test-applications/tanstackstart-react/.nitro/vite/services/ssr/server.js create mode 100644 dev-packages/e2e-tests/test-applications/tanstackstart-react/src/routeTree.gen.ts diff --git a/dev-packages/e2e-tests/test-applications/tanstackstart-react/.nitro/vite/services/ssr/assets/_tanstack-start-manifest_v-CS8AEhoz.js b/dev-packages/e2e-tests/test-applications/tanstackstart-react/.nitro/vite/services/ssr/assets/_tanstack-start-manifest_v-CS8AEhoz.js new file mode 100644 index 000000000000..c1f76cca0302 --- /dev/null +++ b/dev-packages/e2e-tests/test-applications/tanstackstart-react/.nitro/vite/services/ssr/assets/_tanstack-start-manifest_v-CS8AEhoz.js @@ -0,0 +1,4 @@ +const tsrStartManifest = () => ({ "routes": { "__root__": { "filePath": "/Users/nicolashrubec/dev/sentry-javascript/dev-packages/e2e-tests/test-applications/tanstackstart-react/src/routes/__root.tsx", "children": ["/", "/test-middleware", "/test-serverFn", "/api/error", "/api/test-middleware"], "preloads": ["/assets/main-DQu1yQem.js"], "assets": [] }, "/": { "filePath": "/Users/nicolashrubec/dev/sentry-javascript/dev-packages/e2e-tests/test-applications/tanstackstart-react/src/routes/index.tsx", "assets": [], "preloads": ["/assets/index-Bpuxls5B.js", "/assets/createServerFn-CV961CDn.js"] }, "/test-middleware": { "filePath": "/Users/nicolashrubec/dev/sentry-javascript/dev-packages/e2e-tests/test-applications/tanstackstart-react/src/routes/test-middleware.tsx", "assets": [], "preloads": ["/assets/test-middleware-D_sRyXaw.js", "/assets/createServerFn-CV961CDn.js"] }, "/test-serverFn": { "filePath": "/Users/nicolashrubec/dev/sentry-javascript/dev-packages/e2e-tests/test-applications/tanstackstart-react/src/routes/test-serverFn.tsx", "assets": [], "preloads": ["/assets/test-serverFn-CFEBvR7b.js", "/assets/createServerFn-CV961CDn.js"] }, "/api/error": { "filePath": "/Users/nicolashrubec/dev/sentry-javascript/dev-packages/e2e-tests/test-applications/tanstackstart-react/src/routes/api.error.ts" }, "/api/test-middleware": { "filePath": "/Users/nicolashrubec/dev/sentry-javascript/dev-packages/e2e-tests/test-applications/tanstackstart-react/src/routes/api.test-middleware.ts" } }, "clientEntry": "/assets/main-DQu1yQem.js" }); +export { + tsrStartManifest +}; diff --git a/dev-packages/e2e-tests/test-applications/tanstackstart-react/.nitro/vite/services/ssr/assets/createSsrRpc-mJR5gjC5.js b/dev-packages/e2e-tests/test-applications/tanstackstart-react/.nitro/vite/services/ssr/assets/createSsrRpc-mJR5gjC5.js new file mode 100644 index 000000000000..75d8a8c75c90 --- /dev/null +++ b/dev-packages/e2e-tests/test-applications/tanstackstart-react/.nitro/vite/services/ssr/assets/createSsrRpc-mJR5gjC5.js @@ -0,0 +1,16 @@ +import { br as TSS_SERVER_FUNCTION, bs as getServerFnById } from "../server.js"; +const createSsrRpc = (functionId, importer) => { + const url = "/_serverFn/" + functionId; + const fn = async (...args) => { + const serverFn = await getServerFnById(functionId); + return serverFn(...args); + }; + return Object.assign(fn, { + url, + functionId, + [TSS_SERVER_FUNCTION]: true + }); +}; +export { + createSsrRpc as c +}; diff --git a/dev-packages/e2e-tests/test-applications/tanstackstart-react/.nitro/vite/services/ssr/assets/index-Byn0LoyG.js b/dev-packages/e2e-tests/test-applications/tanstackstart-react/.nitro/vite/services/ssr/assets/index-Byn0LoyG.js new file mode 100644 index 000000000000..0bad03dd42b6 --- /dev/null +++ b/dev-packages/e2e-tests/test-applications/tanstackstart-react/.nitro/vite/services/ssr/assets/index-Byn0LoyG.js @@ -0,0 +1,15 @@ +import { bo as createServerRpc, bp as createServerFn } from "../server.js"; +import "node:async_hooks"; +import "node:stream"; +import "util"; +import "crypto"; +import "async_hooks"; +import "stream"; +import "node:stream/web"; +const throwServerError_createServerFn_handler = createServerRpc("41399900a9fa876e415539e79e0239344988f6b8a15be321b96c32b46279e8df", (opts, signal) => throwServerError.__executeServer(opts, signal)); +const throwServerError = createServerFn().handler(throwServerError_createServerFn_handler, async () => { + throw new Error("Sentry Server Function Test Error"); +}); +export { + throwServerError_createServerFn_handler +}; diff --git a/dev-packages/e2e-tests/test-applications/tanstackstart-react/.nitro/vite/services/ssr/assets/index-D3FWW_HK.js b/dev-packages/e2e-tests/test-applications/tanstackstart-react/.nitro/vite/services/ssr/assets/index-D3FWW_HK.js new file mode 100644 index 000000000000..511ab599b2c0 --- /dev/null +++ b/dev-packages/e2e-tests/test-applications/tanstackstart-react/.nitro/vite/services/ssr/assets/index-D3FWW_HK.js @@ -0,0 +1,26 @@ +import { bj as jsxRuntimeExports, bp as createServerFn } from "../server.js"; +import { c as createSsrRpc } from "./createSsrRpc-mJR5gjC5.js"; +import "node:async_hooks"; +import "node:stream"; +import "util"; +import "crypto"; +import "async_hooks"; +import "stream"; +import "node:stream/web"; +const throwServerError = createServerFn().handler(createSsrRpc("41399900a9fa876e415539e79e0239344988f6b8a15be321b96c32b46279e8df")); +function Home() { + return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [ + /* @__PURE__ */ jsxRuntimeExports.jsx("button", { type: "button", onClick: () => { + throw new Error("Sentry Client Test Error"); + }, children: "Break the client" }), + /* @__PURE__ */ jsxRuntimeExports.jsx("button", { type: "button", onClick: async () => { + await throwServerError(); + }, children: "Break server function" }), + /* @__PURE__ */ jsxRuntimeExports.jsx("button", { type: "button", onClick: async () => { + await fetch("/api/error"); + }, children: "Break API route" }) + ] }); +} +export { + Home as component +}; diff --git a/dev-packages/e2e-tests/test-applications/tanstackstart-react/.nitro/vite/services/ssr/assets/middleware-BDyeOn_H.js b/dev-packages/e2e-tests/test-applications/tanstackstart-react/.nitro/vite/services/ssr/assets/middleware-BDyeOn_H.js new file mode 100644 index 000000000000..0d132b319e9a --- /dev/null +++ b/dev-packages/e2e-tests/test-applications/tanstackstart-react/.nitro/vite/services/ssr/assets/middleware-BDyeOn_H.js @@ -0,0 +1,107 @@ +import { b as getActiveSpan, an as startSpanManual, ar as addNonEnumerableProperty, bq as getMiddlewareSpanOptions, aV as withActiveSpan } from "../server.js"; +const SENTRY_WRAPPED = "__SENTRY_WRAPPED__"; +function getNextProxy(next, span, prevSpan) { + return new Proxy(next, { + apply: (originalNext, thisArgNext, argsNext) => { + span.end(); + if (prevSpan) { + return withActiveSpan(prevSpan, () => { + return Reflect.apply(originalNext, thisArgNext, argsNext); + }); + } + return Reflect.apply(originalNext, thisArgNext, argsNext); + } + }); +} +function wrapMiddlewareWithSentry(middleware, options) { + if (middleware[SENTRY_WRAPPED]) { + return middleware; + } + if (middleware.options?.server) { + middleware.options.server = new Proxy(middleware.options.server, { + apply: (originalServer, thisArgServer, argsServer) => { + const prevSpan = getActiveSpan(); + return startSpanManual(getMiddlewareSpanOptions(options.name), (span) => { + const middlewareArgs = argsServer[0]; + if (middlewareArgs && typeof middlewareArgs === "object" && typeof middlewareArgs.next === "function") { + middlewareArgs.next = getNextProxy(middlewareArgs.next, span, prevSpan); + } + return originalServer.apply(thisArgServer, argsServer); + }); + } + }); + addNonEnumerableProperty(middleware, SENTRY_WRAPPED, true); + } + return middleware; +} +function wrapMiddlewareListWithSentry(middlewares) { + return Object.entries(middlewares).map(([name, middleware]) => { + return wrapMiddlewareWithSentry(middleware, { name }); + }); +} +const createMiddleware = (options, __opts) => { + const resolvedOptions = { + type: "request", + ...__opts || options + }; + return { + options: resolvedOptions, + middleware: (middleware) => { + return createMiddleware( + {}, + Object.assign(resolvedOptions, { middleware }) + ); + }, + inputValidator: (inputValidator) => { + return createMiddleware( + {}, + Object.assign(resolvedOptions, { inputValidator }) + ); + }, + client: (client) => { + return createMiddleware( + {}, + Object.assign(resolvedOptions, { client }) + ); + }, + server: (server) => { + return createMiddleware( + {}, + Object.assign(resolvedOptions, { server }) + ); + } + }; +}; +const globalRequestMiddleware = createMiddleware().server(async ({ next }) => { + console.log("Global request middleware executed"); + return next(); +}); +const globalFunctionMiddleware = createMiddleware({ type: "function" }).server(async ({ next }) => { + console.log("Global function middleware executed"); + return next(); +}); +const serverFnMiddleware = createMiddleware({ type: "function" }).server(async ({ next }) => { + console.log("Server function middleware executed"); + return next(); +}); +const serverRouteRequestMiddleware = createMiddleware().server(async ({ next }) => { + console.log("Server route request middleware executed"); + return next(); +}); +const wrappedGlobalRequestMiddleware = wrapMiddlewareWithSentry(globalRequestMiddleware, { + name: "globalRequestMiddleware" +}); +const wrappedGlobalFunctionMiddleware = wrapMiddlewareWithSentry(globalFunctionMiddleware, { + name: "globalFunctionMiddleware" +}); +const [wrappedServerFnMiddleware, wrappedServerRouteRequestMiddleware] = wrapMiddlewareListWithSentry({ + serverFnMiddleware, + serverRouteRequestMiddleware +}); +export { + wrappedGlobalFunctionMiddleware as a, + wrappedGlobalRequestMiddleware as b, + createMiddleware as c, + wrappedServerFnMiddleware as d, + wrappedServerRouteRequestMiddleware as w +}; diff --git a/dev-packages/e2e-tests/test-applications/tanstackstart-react/.nitro/vite/services/ssr/assets/router-DIOBJIBx.js b/dev-packages/e2e-tests/test-applications/tanstackstart-react/.nitro/vite/services/ssr/assets/router-DIOBJIBx.js new file mode 100644 index 000000000000..9615c8a1e9be --- /dev/null +++ b/dev-packages/e2e-tests/test-applications/tanstackstart-react/.nitro/vite/services/ssr/assets/router-DIOBJIBx.js @@ -0,0 +1,32549 @@ +import { c as commonjsGlobal, g as getAugmentedNamespace, D as DEBUG_BUILD$3, d as debug$2, a as getFunctionName, G as GLOBAL_OBJ, b as getActiveSpan$1, e as getRootSpan, S as SPAN_STATUS_ERROR, i as isThenable, f as getGlobalScope, m as merge$1, s as spanToTraceContext, h as getDynamicSamplingContextFromSpan, j as spanToJSON, k as dateTimestampInSeconds, u as uuid4, l as addExceptionMechanism, n as DEFAULT_ENVIRONMENT, t as truncate, o as Scope, p as normalize$1, q as getCurrentScope, r as getIsolationScope, v as makeSession, w as updateSession, x as closeSession, y as getClient, z as withScope, A as getTraceContextFromScope, B as getDynamicSamplingContextFromScope, C as dsnToString, E as createEnvelope, F as getGlobalSingleton, H as forEachEnvelopeItem, I as serializeEnvelope, J as envelopeItemTypeToDataCategory, K as SEMANTIC_ATTRIBUTE_EXCLUSIVE_TIME, L as SEMANTIC_ATTRIBUTE_PROFILE_ID, M as makeDsn, N as checkOrSetAlreadyCaught, O as createEventEnvelope, P as addItemToEnvelope, Q as createAttachmentEnvelopeItem, R as createSessionEnvelope, T as isParameterizedString, U as isPrimitive$1, V as parseSampleRate, W as shouldIgnoreSpan$1, X as showSpanDropWarning, Y as reparentChildSpans, Z as isPlainObject$1, _ as addExceptionTypeValue, $ as isError, a0 as normalizeToSize, a1 as extractExceptionKeysForMessage, a2 as isErrorEvent$2, a3 as SDK_VERSION, a4 as getMainCarrier, a5 as getAsyncContextStrategy, a6 as spanToTraceHeader, a7 as dynamicSamplingContextToSentryBaggageHeader, a8 as TRACEPARENT_REGEXP, a9 as spanToTraceparentHeader, aa as generateSentryTraceHeader, ab as generateTraceparentHeader, ac as consoleSandbox, ad as getOriginalFunction, ae as getEventDescription, af as stringMatchesSomePattern, ag as isInstanceOf, ah as CONSOLE_LEVELS, ai as fill, aj as originalConsoleMethods, ak as safeJoin, al as SEMANTIC_ATTRIBUTE_SENTRY_OP, am as SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN, an as startSpanManual$1, ao as startSpan$2, ap as handleCallbackErrors, aq as UNKNOWN_FUNCTION, ar as addNonEnumerableProperty, as as withIsolationScope, at as generateSpanId, au as getSpanStatusFromHttpCode, av as setAsyncContextStrategy, aw as SEMANTIC_ATTRIBUTE_SENTRY_SOURCE, ax as hasSpansEnabled, ay as baggageHeaderToDynamicSamplingContext, az as sampleSpan, aA as SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE, aB as parseBaggageHeader, aC as SENTRY_BAGGAGE_KEY_PREFIX, aD as timedEventsToMeasurements, aE as addChildSpanToSpan, aF as getDefaultIsolationScope, aG as getDefaultCurrentScope, aH as setCapturedScopesOnSpan, aI as logSpanStart, aJ as logSpanEnd, aK as propagationContextFromHeaders, aL as shouldContinueTrace, aM as getCapturedScopesOnSpan, aN as convertSpanLinksForEnvelope, aO as getStatusMessage, aP as spanTimeInputToSeconds, aQ as SEMANTIC_ATTRIBUTE_SENTRY_CUSTOM_SPAN_NAME, aR as SPAN_STATUS_OK, aS as objectToBaggageHeader, aT as parseSemver, aU as snipLine, aV as withActiveSpan$1, aW as isMatchingPattern, aX as suppressTracing$2, aY as createStackParser, aZ as stackParserFromStackParserOptions, a_ as getDefaultExportFromCjs, a$ as SEMANTIC_ATTRIBUTE_CACHE_ITEM_SIZE, b0 as SEMANTIC_ATTRIBUTE_CACHE_HIT, b1 as SEMANTIC_ATTRIBUTE_CACHE_KEY, b2 as rootRouteId, b3 as invariant, b4 as trimPathLeft, b5 as joinPaths, b6 as reactExports, b7 as dummyMatchContext, b8 as matchContext, b9 as useRouterState, ba as useRouter, bb as requireReactDom, bc as useForwardedRef, bd as useIntersectionObserver, be as functionalUpdate, bf as exactPathTest, bg as removeTrailingSlash, bh as deepEqual, bi as React__default, bj as jsxRuntimeExports, bk as warning, bl as isModuleNotFoundError, bm as RouterCore, bn as Outlet } from "../server.js"; +import { w as wrappedServerRouteRequestMiddleware } from "./middleware-BDyeOn_H.js"; +import { performance } from "perf_hooks"; +import require$$0, { inspect, types as types$5 } from "util"; +import require$$2$1 from "url"; +import * as path$1 from "path"; +import path__default, { normalize } from "path"; +import * as moduleModule from "module"; +import moduleModule__default from "module"; +import require$$3, { threadId, isMainThread } from "worker_threads"; +import { readFileSync } from "fs"; +import require$$5 from "events"; +import * as diagnosticsChannel from "node:diagnostics_channel"; +import diagnosticsChannel__default, { subscribe, unsubscribe } from "node:diagnostics_channel"; +import { errorMonitor } from "node:events"; +import * as diagch from "diagnostics_channel"; +import diagch__default from "diagnostics_channel"; +import * as net from "node:net"; +import require$$1$1 from "async_hooks"; +import { execFile } from "node:child_process"; +import { readdir, readFile, createReadStream, existsSync, readFileSync as readFileSync$1 } from "node:fs"; +import * as os from "node:os"; +import { join, dirname as dirname$1, posix, sep as sep$1 } from "node:path"; +import * as util from "node:util"; +import { promisify } from "node:util"; +import { createInterface } from "node:readline"; +import { Worker } from "node:worker_threads"; +import * as http$1 from "node:http"; +import * as https from "node:https"; +import { Readable } from "node:stream"; +import { createGzip } from "node:zlib"; +import * as tls from "node:tls"; +import "node:async_hooks"; +import "crypto"; +import "stream"; +import "node:stream/web"; +var src$n = {}; +var utils$h = {}; +var diag = {}; +var ComponentLogger = {}; +var globalUtils = {}; +var platform = {}; +var node$1 = {}; +var globalThis$1 = {}; +var hasRequiredGlobalThis; +function requireGlobalThis() { + if (hasRequiredGlobalThis) return globalThis$1; + hasRequiredGlobalThis = 1; + Object.defineProperty(globalThis$1, "__esModule", { value: true }); + globalThis$1._globalThis = void 0; + globalThis$1._globalThis = typeof globalThis === "object" ? globalThis : commonjsGlobal; + return globalThis$1; +} +var hasRequiredNode; +function requireNode() { + if (hasRequiredNode) return node$1; + hasRequiredNode = 1; + (function(exports$1) { + var __createBinding = node$1 && node$1.__createBinding || (Object.create ? (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + Object.defineProperty(o, k2, { enumerable: true, get: function() { + return m[k]; + } }); + }) : (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + o[k2] = m[k]; + })); + var __exportStar = node$1 && node$1.__exportStar || function(m, exports$12) { + for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports$12, p)) __createBinding(exports$12, m, p); + }; + Object.defineProperty(exports$1, "__esModule", { value: true }); + __exportStar(/* @__PURE__ */ requireGlobalThis(), exports$1); + })(node$1); + return node$1; +} +var hasRequiredPlatform; +function requirePlatform() { + if (hasRequiredPlatform) return platform; + hasRequiredPlatform = 1; + (function(exports$1) { + var __createBinding = platform && platform.__createBinding || (Object.create ? (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + Object.defineProperty(o, k2, { enumerable: true, get: function() { + return m[k]; + } }); + }) : (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + o[k2] = m[k]; + })); + var __exportStar = platform && platform.__exportStar || function(m, exports$12) { + for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports$12, p)) __createBinding(exports$12, m, p); + }; + Object.defineProperty(exports$1, "__esModule", { value: true }); + __exportStar(/* @__PURE__ */ requireNode(), exports$1); + })(platform); + return platform; +} +var version$j = {}; +var hasRequiredVersion$j; +function requireVersion$j() { + if (hasRequiredVersion$j) return version$j; + hasRequiredVersion$j = 1; + Object.defineProperty(version$j, "__esModule", { value: true }); + version$j.VERSION = void 0; + version$j.VERSION = "1.9.0"; + return version$j; +} +var semver = {}; +var hasRequiredSemver; +function requireSemver() { + if (hasRequiredSemver) return semver; + hasRequiredSemver = 1; + Object.defineProperty(semver, "__esModule", { value: true }); + semver.isCompatible = semver._makeCompatibilityCheck = void 0; + const version_1 = /* @__PURE__ */ requireVersion$j(); + const re = /^(\d+)\.(\d+)\.(\d+)(-(.+))?$/; + function _makeCompatibilityCheck(ownVersion) { + const acceptedVersions = /* @__PURE__ */ new Set([ownVersion]); + const rejectedVersions = /* @__PURE__ */ new Set(); + const myVersionMatch = ownVersion.match(re); + if (!myVersionMatch) { + return () => false; + } + const ownVersionParsed = { + major: +myVersionMatch[1], + minor: +myVersionMatch[2], + patch: +myVersionMatch[3], + prerelease: myVersionMatch[4] + }; + if (ownVersionParsed.prerelease != null) { + return function isExactmatch(globalVersion) { + return globalVersion === ownVersion; + }; + } + function _reject(v) { + rejectedVersions.add(v); + return false; + } + function _accept(v) { + acceptedVersions.add(v); + return true; + } + return function isCompatible(globalVersion) { + if (acceptedVersions.has(globalVersion)) { + return true; + } + if (rejectedVersions.has(globalVersion)) { + return false; + } + const globalVersionMatch = globalVersion.match(re); + if (!globalVersionMatch) { + return _reject(globalVersion); + } + const globalVersionParsed = { + major: +globalVersionMatch[1], + minor: +globalVersionMatch[2], + patch: +globalVersionMatch[3], + prerelease: globalVersionMatch[4] + }; + if (globalVersionParsed.prerelease != null) { + return _reject(globalVersion); + } + if (ownVersionParsed.major !== globalVersionParsed.major) { + return _reject(globalVersion); + } + if (ownVersionParsed.major === 0) { + if (ownVersionParsed.minor === globalVersionParsed.minor && ownVersionParsed.patch <= globalVersionParsed.patch) { + return _accept(globalVersion); + } + return _reject(globalVersion); + } + if (ownVersionParsed.minor <= globalVersionParsed.minor) { + return _accept(globalVersion); + } + return _reject(globalVersion); + }; + } + semver._makeCompatibilityCheck = _makeCompatibilityCheck; + semver.isCompatible = _makeCompatibilityCheck(version_1.VERSION); + return semver; +} +var hasRequiredGlobalUtils; +function requireGlobalUtils() { + if (hasRequiredGlobalUtils) return globalUtils; + hasRequiredGlobalUtils = 1; + Object.defineProperty(globalUtils, "__esModule", { value: true }); + globalUtils.unregisterGlobal = globalUtils.getGlobal = globalUtils.registerGlobal = void 0; + const platform_1 = /* @__PURE__ */ requirePlatform(); + const version_1 = /* @__PURE__ */ requireVersion$j(); + const semver_1 = /* @__PURE__ */ requireSemver(); + const major = version_1.VERSION.split(".")[0]; + const GLOBAL_OPENTELEMETRY_API_KEY = Symbol.for(`opentelemetry.js.api.${major}`); + const _global2 = platform_1._globalThis; + function registerGlobal(type, instance, diag2, allowOverride = false) { + var _a; + const api = _global2[GLOBAL_OPENTELEMETRY_API_KEY] = (_a = _global2[GLOBAL_OPENTELEMETRY_API_KEY]) !== null && _a !== void 0 ? _a : { + version: version_1.VERSION + }; + if (!allowOverride && api[type]) { + const err = new Error(`@opentelemetry/api: Attempted duplicate registration of API: ${type}`); + diag2.error(err.stack || err.message); + return false; + } + if (api.version !== version_1.VERSION) { + const err = new Error(`@opentelemetry/api: Registration of version v${api.version} for ${type} does not match previously registered API v${version_1.VERSION}`); + diag2.error(err.stack || err.message); + return false; + } + api[type] = instance; + diag2.debug(`@opentelemetry/api: Registered a global for ${type} v${version_1.VERSION}.`); + return true; + } + globalUtils.registerGlobal = registerGlobal; + function getGlobal(type) { + var _a, _b; + const globalVersion = (_a = _global2[GLOBAL_OPENTELEMETRY_API_KEY]) === null || _a === void 0 ? void 0 : _a.version; + if (!globalVersion || !(0, semver_1.isCompatible)(globalVersion)) { + return; + } + return (_b = _global2[GLOBAL_OPENTELEMETRY_API_KEY]) === null || _b === void 0 ? void 0 : _b[type]; + } + globalUtils.getGlobal = getGlobal; + function unregisterGlobal(type, diag2) { + diag2.debug(`@opentelemetry/api: Unregistering a global for ${type} v${version_1.VERSION}.`); + const api = _global2[GLOBAL_OPENTELEMETRY_API_KEY]; + if (api) { + delete api[type]; + } + } + globalUtils.unregisterGlobal = unregisterGlobal; + return globalUtils; +} +var hasRequiredComponentLogger; +function requireComponentLogger() { + if (hasRequiredComponentLogger) return ComponentLogger; + hasRequiredComponentLogger = 1; + Object.defineProperty(ComponentLogger, "__esModule", { value: true }); + ComponentLogger.DiagComponentLogger = void 0; + const global_utils_1 = /* @__PURE__ */ requireGlobalUtils(); + class DiagComponentLogger { + constructor(props) { + this._namespace = props.namespace || "DiagComponentLogger"; + } + debug(...args) { + return logProxy("debug", this._namespace, args); + } + error(...args) { + return logProxy("error", this._namespace, args); + } + info(...args) { + return logProxy("info", this._namespace, args); + } + warn(...args) { + return logProxy("warn", this._namespace, args); + } + verbose(...args) { + return logProxy("verbose", this._namespace, args); + } + } + ComponentLogger.DiagComponentLogger = DiagComponentLogger; + function logProxy(funcName, namespace, args) { + const logger2 = (0, global_utils_1.getGlobal)("diag"); + if (!logger2) { + return; + } + args.unshift(namespace); + return logger2[funcName](...args); + } + return ComponentLogger; +} +var logLevelLogger = {}; +var types$4 = {}; +var hasRequiredTypes$3; +function requireTypes$3() { + if (hasRequiredTypes$3) return types$4; + hasRequiredTypes$3 = 1; + (function(exports$1) { + Object.defineProperty(exports$1, "__esModule", { value: true }); + exports$1.DiagLogLevel = void 0; + (function(DiagLogLevel) { + DiagLogLevel[DiagLogLevel["NONE"] = 0] = "NONE"; + DiagLogLevel[DiagLogLevel["ERROR"] = 30] = "ERROR"; + DiagLogLevel[DiagLogLevel["WARN"] = 50] = "WARN"; + DiagLogLevel[DiagLogLevel["INFO"] = 60] = "INFO"; + DiagLogLevel[DiagLogLevel["DEBUG"] = 70] = "DEBUG"; + DiagLogLevel[DiagLogLevel["VERBOSE"] = 80] = "VERBOSE"; + DiagLogLevel[DiagLogLevel["ALL"] = 9999] = "ALL"; + })(exports$1.DiagLogLevel || (exports$1.DiagLogLevel = {})); + })(types$4); + return types$4; +} +var hasRequiredLogLevelLogger; +function requireLogLevelLogger() { + if (hasRequiredLogLevelLogger) return logLevelLogger; + hasRequiredLogLevelLogger = 1; + Object.defineProperty(logLevelLogger, "__esModule", { value: true }); + logLevelLogger.createLogLevelDiagLogger = void 0; + const types_1 = /* @__PURE__ */ requireTypes$3(); + function createLogLevelDiagLogger(maxLevel, logger2) { + if (maxLevel < types_1.DiagLogLevel.NONE) { + maxLevel = types_1.DiagLogLevel.NONE; + } else if (maxLevel > types_1.DiagLogLevel.ALL) { + maxLevel = types_1.DiagLogLevel.ALL; + } + logger2 = logger2 || {}; + function _filterFunc(funcName, theLevel) { + const theFunc = logger2[funcName]; + if (typeof theFunc === "function" && maxLevel >= theLevel) { + return theFunc.bind(logger2); + } + return function() { + }; + } + return { + error: _filterFunc("error", types_1.DiagLogLevel.ERROR), + warn: _filterFunc("warn", types_1.DiagLogLevel.WARN), + info: _filterFunc("info", types_1.DiagLogLevel.INFO), + debug: _filterFunc("debug", types_1.DiagLogLevel.DEBUG), + verbose: _filterFunc("verbose", types_1.DiagLogLevel.VERBOSE) + }; + } + logLevelLogger.createLogLevelDiagLogger = createLogLevelDiagLogger; + return logLevelLogger; +} +var hasRequiredDiag; +function requireDiag() { + if (hasRequiredDiag) return diag; + hasRequiredDiag = 1; + Object.defineProperty(diag, "__esModule", { value: true }); + diag.DiagAPI = void 0; + const ComponentLogger_1 = /* @__PURE__ */ requireComponentLogger(); + const logLevelLogger_1 = /* @__PURE__ */ requireLogLevelLogger(); + const types_1 = /* @__PURE__ */ requireTypes$3(); + const global_utils_1 = /* @__PURE__ */ requireGlobalUtils(); + const API_NAME = "diag"; + class DiagAPI { + /** + * Private internal constructor + * @private + */ + constructor() { + function _logProxy(funcName) { + return function(...args) { + const logger2 = (0, global_utils_1.getGlobal)("diag"); + if (!logger2) + return; + return logger2[funcName](...args); + }; + } + const self = this; + const setLogger = (logger2, optionsOrLogLevel = { logLevel: types_1.DiagLogLevel.INFO }) => { + var _a, _b, _c; + if (logger2 === self) { + const err = new Error("Cannot use diag as the logger for itself. Please use a DiagLogger implementation like ConsoleDiagLogger or a custom implementation"); + self.error((_a = err.stack) !== null && _a !== void 0 ? _a : err.message); + return false; + } + if (typeof optionsOrLogLevel === "number") { + optionsOrLogLevel = { + logLevel: optionsOrLogLevel + }; + } + const oldLogger = (0, global_utils_1.getGlobal)("diag"); + const newLogger = (0, logLevelLogger_1.createLogLevelDiagLogger)((_b = optionsOrLogLevel.logLevel) !== null && _b !== void 0 ? _b : types_1.DiagLogLevel.INFO, logger2); + if (oldLogger && !optionsOrLogLevel.suppressOverrideMessage) { + const stack = (_c = new Error().stack) !== null && _c !== void 0 ? _c : ""; + oldLogger.warn(`Current logger will be overwritten from ${stack}`); + newLogger.warn(`Current logger will overwrite one already registered from ${stack}`); + } + return (0, global_utils_1.registerGlobal)("diag", newLogger, self, true); + }; + self.setLogger = setLogger; + self.disable = () => { + (0, global_utils_1.unregisterGlobal)(API_NAME, self); + }; + self.createComponentLogger = (options) => { + return new ComponentLogger_1.DiagComponentLogger(options); + }; + self.verbose = _logProxy("verbose"); + self.debug = _logProxy("debug"); + self.info = _logProxy("info"); + self.warn = _logProxy("warn"); + self.error = _logProxy("error"); + } + /** Get the singleton instance of the DiagAPI API */ + static instance() { + if (!this._instance) { + this._instance = new DiagAPI(); + } + return this._instance; + } + } + diag.DiagAPI = DiagAPI; + return diag; +} +var baggageImpl = {}; +var hasRequiredBaggageImpl; +function requireBaggageImpl() { + if (hasRequiredBaggageImpl) return baggageImpl; + hasRequiredBaggageImpl = 1; + Object.defineProperty(baggageImpl, "__esModule", { value: true }); + baggageImpl.BaggageImpl = void 0; + class BaggageImpl { + constructor(entries) { + this._entries = entries ? new Map(entries) : /* @__PURE__ */ new Map(); + } + getEntry(key) { + const entry = this._entries.get(key); + if (!entry) { + return void 0; + } + return Object.assign({}, entry); + } + getAllEntries() { + return Array.from(this._entries.entries()).map(([k, v]) => [k, v]); + } + setEntry(key, entry) { + const newBaggage = new BaggageImpl(this._entries); + newBaggage._entries.set(key, entry); + return newBaggage; + } + removeEntry(key) { + const newBaggage = new BaggageImpl(this._entries); + newBaggage._entries.delete(key); + return newBaggage; + } + removeEntries(...keys) { + const newBaggage = new BaggageImpl(this._entries); + for (const key of keys) { + newBaggage._entries.delete(key); + } + return newBaggage; + } + clear() { + return new BaggageImpl(); + } + } + baggageImpl.BaggageImpl = BaggageImpl; + return baggageImpl; +} +var symbol = {}; +var hasRequiredSymbol; +function requireSymbol() { + if (hasRequiredSymbol) return symbol; + hasRequiredSymbol = 1; + Object.defineProperty(symbol, "__esModule", { value: true }); + symbol.baggageEntryMetadataSymbol = void 0; + symbol.baggageEntryMetadataSymbol = Symbol("BaggageEntryMetadata"); + return symbol; +} +var hasRequiredUtils$h; +function requireUtils$h() { + if (hasRequiredUtils$h) return utils$h; + hasRequiredUtils$h = 1; + Object.defineProperty(utils$h, "__esModule", { value: true }); + utils$h.baggageEntryMetadataFromString = utils$h.createBaggage = void 0; + const diag_1 = /* @__PURE__ */ requireDiag(); + const baggage_impl_1 = /* @__PURE__ */ requireBaggageImpl(); + const symbol_1 = /* @__PURE__ */ requireSymbol(); + const diag2 = diag_1.DiagAPI.instance(); + function createBaggage(entries = {}) { + return new baggage_impl_1.BaggageImpl(new Map(Object.entries(entries))); + } + utils$h.createBaggage = createBaggage; + function baggageEntryMetadataFromString(str) { + if (typeof str !== "string") { + diag2.error(`Cannot create baggage metadata from unknown type: ${typeof str}`); + str = ""; + } + return { + __TYPE__: symbol_1.baggageEntryMetadataSymbol, + toString() { + return str; + } + }; + } + utils$h.baggageEntryMetadataFromString = baggageEntryMetadataFromString; + return utils$h; +} +var context$1 = {}; +var hasRequiredContext$1; +function requireContext$1() { + if (hasRequiredContext$1) return context$1; + hasRequiredContext$1 = 1; + Object.defineProperty(context$1, "__esModule", { value: true }); + context$1.ROOT_CONTEXT = context$1.createContextKey = void 0; + function createContextKey(description) { + return Symbol.for(description); + } + context$1.createContextKey = createContextKey; + class BaseContext { + /** + * Construct a new context which inherits values from an optional parent context. + * + * @param parentContext a context from which to inherit values + */ + constructor(parentContext) { + const self = this; + self._currentContext = parentContext ? new Map(parentContext) : /* @__PURE__ */ new Map(); + self.getValue = (key) => self._currentContext.get(key); + self.setValue = (key, value) => { + const context2 = new BaseContext(self._currentContext); + context2._currentContext.set(key, value); + return context2; + }; + self.deleteValue = (key) => { + const context2 = new BaseContext(self._currentContext); + context2._currentContext.delete(key); + return context2; + }; + } + } + context$1.ROOT_CONTEXT = new BaseContext(); + return context$1; +} +var consoleLogger = {}; +var hasRequiredConsoleLogger; +function requireConsoleLogger() { + if (hasRequiredConsoleLogger) return consoleLogger; + hasRequiredConsoleLogger = 1; + Object.defineProperty(consoleLogger, "__esModule", { value: true }); + consoleLogger.DiagConsoleLogger = void 0; + const consoleMap = [ + { n: "error", c: "error" }, + { n: "warn", c: "warn" }, + { n: "info", c: "info" }, + { n: "debug", c: "debug" }, + { n: "verbose", c: "trace" } + ]; + class DiagConsoleLogger { + constructor() { + function _consoleFunc(funcName) { + return function(...args) { + if (console) { + let theFunc = console[funcName]; + if (typeof theFunc !== "function") { + theFunc = console.log; + } + if (typeof theFunc === "function") { + return theFunc.apply(console, args); + } + } + }; + } + for (let i = 0; i < consoleMap.length; i++) { + this[consoleMap[i].n] = _consoleFunc(consoleMap[i].c); + } + } + } + consoleLogger.DiagConsoleLogger = DiagConsoleLogger; + return consoleLogger; +} +var NoopMeter = {}; +var hasRequiredNoopMeter; +function requireNoopMeter() { + if (hasRequiredNoopMeter) return NoopMeter; + hasRequiredNoopMeter = 1; + (function(exports$1) { + Object.defineProperty(exports$1, "__esModule", { value: true }); + exports$1.createNoopMeter = exports$1.NOOP_OBSERVABLE_UP_DOWN_COUNTER_METRIC = exports$1.NOOP_OBSERVABLE_GAUGE_METRIC = exports$1.NOOP_OBSERVABLE_COUNTER_METRIC = exports$1.NOOP_UP_DOWN_COUNTER_METRIC = exports$1.NOOP_HISTOGRAM_METRIC = exports$1.NOOP_GAUGE_METRIC = exports$1.NOOP_COUNTER_METRIC = exports$1.NOOP_METER = exports$1.NoopObservableUpDownCounterMetric = exports$1.NoopObservableGaugeMetric = exports$1.NoopObservableCounterMetric = exports$1.NoopObservableMetric = exports$1.NoopHistogramMetric = exports$1.NoopGaugeMetric = exports$1.NoopUpDownCounterMetric = exports$1.NoopCounterMetric = exports$1.NoopMetric = exports$1.NoopMeter = void 0; + class NoopMeter2 { + constructor() { + } + /** + * @see {@link Meter.createGauge} + */ + createGauge(_name, _options) { + return exports$1.NOOP_GAUGE_METRIC; + } + /** + * @see {@link Meter.createHistogram} + */ + createHistogram(_name, _options) { + return exports$1.NOOP_HISTOGRAM_METRIC; + } + /** + * @see {@link Meter.createCounter} + */ + createCounter(_name, _options) { + return exports$1.NOOP_COUNTER_METRIC; + } + /** + * @see {@link Meter.createUpDownCounter} + */ + createUpDownCounter(_name, _options) { + return exports$1.NOOP_UP_DOWN_COUNTER_METRIC; + } + /** + * @see {@link Meter.createObservableGauge} + */ + createObservableGauge(_name, _options) { + return exports$1.NOOP_OBSERVABLE_GAUGE_METRIC; + } + /** + * @see {@link Meter.createObservableCounter} + */ + createObservableCounter(_name, _options) { + return exports$1.NOOP_OBSERVABLE_COUNTER_METRIC; + } + /** + * @see {@link Meter.createObservableUpDownCounter} + */ + createObservableUpDownCounter(_name, _options) { + return exports$1.NOOP_OBSERVABLE_UP_DOWN_COUNTER_METRIC; + } + /** + * @see {@link Meter.addBatchObservableCallback} + */ + addBatchObservableCallback(_callback, _observables) { + } + /** + * @see {@link Meter.removeBatchObservableCallback} + */ + removeBatchObservableCallback(_callback) { + } + } + exports$1.NoopMeter = NoopMeter2; + class NoopMetric { + } + exports$1.NoopMetric = NoopMetric; + class NoopCounterMetric extends NoopMetric { + add(_value, _attributes) { + } + } + exports$1.NoopCounterMetric = NoopCounterMetric; + class NoopUpDownCounterMetric extends NoopMetric { + add(_value, _attributes) { + } + } + exports$1.NoopUpDownCounterMetric = NoopUpDownCounterMetric; + class NoopGaugeMetric extends NoopMetric { + record(_value, _attributes) { + } + } + exports$1.NoopGaugeMetric = NoopGaugeMetric; + class NoopHistogramMetric extends NoopMetric { + record(_value, _attributes) { + } + } + exports$1.NoopHistogramMetric = NoopHistogramMetric; + class NoopObservableMetric { + addCallback(_callback) { + } + removeCallback(_callback) { + } + } + exports$1.NoopObservableMetric = NoopObservableMetric; + class NoopObservableCounterMetric extends NoopObservableMetric { + } + exports$1.NoopObservableCounterMetric = NoopObservableCounterMetric; + class NoopObservableGaugeMetric extends NoopObservableMetric { + } + exports$1.NoopObservableGaugeMetric = NoopObservableGaugeMetric; + class NoopObservableUpDownCounterMetric extends NoopObservableMetric { + } + exports$1.NoopObservableUpDownCounterMetric = NoopObservableUpDownCounterMetric; + exports$1.NOOP_METER = new NoopMeter2(); + exports$1.NOOP_COUNTER_METRIC = new NoopCounterMetric(); + exports$1.NOOP_GAUGE_METRIC = new NoopGaugeMetric(); + exports$1.NOOP_HISTOGRAM_METRIC = new NoopHistogramMetric(); + exports$1.NOOP_UP_DOWN_COUNTER_METRIC = new NoopUpDownCounterMetric(); + exports$1.NOOP_OBSERVABLE_COUNTER_METRIC = new NoopObservableCounterMetric(); + exports$1.NOOP_OBSERVABLE_GAUGE_METRIC = new NoopObservableGaugeMetric(); + exports$1.NOOP_OBSERVABLE_UP_DOWN_COUNTER_METRIC = new NoopObservableUpDownCounterMetric(); + function createNoopMeter() { + return exports$1.NOOP_METER; + } + exports$1.createNoopMeter = createNoopMeter; + })(NoopMeter); + return NoopMeter; +} +var Metric = {}; +var hasRequiredMetric; +function requireMetric() { + if (hasRequiredMetric) return Metric; + hasRequiredMetric = 1; + (function(exports$1) { + Object.defineProperty(exports$1, "__esModule", { value: true }); + exports$1.ValueType = void 0; + (function(ValueType) { + ValueType[ValueType["INT"] = 0] = "INT"; + ValueType[ValueType["DOUBLE"] = 1] = "DOUBLE"; + })(exports$1.ValueType || (exports$1.ValueType = {})); + })(Metric); + return Metric; +} +var TextMapPropagator = {}; +var hasRequiredTextMapPropagator; +function requireTextMapPropagator() { + if (hasRequiredTextMapPropagator) return TextMapPropagator; + hasRequiredTextMapPropagator = 1; + Object.defineProperty(TextMapPropagator, "__esModule", { value: true }); + TextMapPropagator.defaultTextMapSetter = TextMapPropagator.defaultTextMapGetter = void 0; + TextMapPropagator.defaultTextMapGetter = { + get(carrier, key) { + if (carrier == null) { + return void 0; + } + return carrier[key]; + }, + keys(carrier) { + if (carrier == null) { + return []; + } + return Object.keys(carrier); + } + }; + TextMapPropagator.defaultTextMapSetter = { + set(carrier, key, value) { + if (carrier == null) { + return; + } + carrier[key] = value; + } + }; + return TextMapPropagator; +} +var ProxyTracer = {}; +var NoopTracer = {}; +var context = {}; +var NoopContextManager = {}; +var hasRequiredNoopContextManager; +function requireNoopContextManager() { + if (hasRequiredNoopContextManager) return NoopContextManager; + hasRequiredNoopContextManager = 1; + Object.defineProperty(NoopContextManager, "__esModule", { value: true }); + NoopContextManager.NoopContextManager = void 0; + const context_1 = /* @__PURE__ */ requireContext$1(); + let NoopContextManager$1 = class NoopContextManager { + active() { + return context_1.ROOT_CONTEXT; + } + with(_context, fn, thisArg, ...args) { + return fn.call(thisArg, ...args); + } + bind(_context, target) { + return target; + } + enable() { + return this; + } + disable() { + return this; + } + }; + NoopContextManager.NoopContextManager = NoopContextManager$1; + return NoopContextManager; +} +var hasRequiredContext; +function requireContext() { + if (hasRequiredContext) return context; + hasRequiredContext = 1; + Object.defineProperty(context, "__esModule", { value: true }); + context.ContextAPI = void 0; + const NoopContextManager_1 = /* @__PURE__ */ requireNoopContextManager(); + const global_utils_1 = /* @__PURE__ */ requireGlobalUtils(); + const diag_1 = /* @__PURE__ */ requireDiag(); + const API_NAME = "context"; + const NOOP_CONTEXT_MANAGER = new NoopContextManager_1.NoopContextManager(); + class ContextAPI { + /** Empty private constructor prevents end users from constructing a new instance of the API */ + constructor() { + } + /** Get the singleton instance of the Context API */ + static getInstance() { + if (!this._instance) { + this._instance = new ContextAPI(); + } + return this._instance; + } + /** + * Set the current context manager. + * + * @returns true if the context manager was successfully registered, else false + */ + setGlobalContextManager(contextManager) { + return (0, global_utils_1.registerGlobal)(API_NAME, contextManager, diag_1.DiagAPI.instance()); + } + /** + * Get the currently active context + */ + active() { + return this._getContextManager().active(); + } + /** + * Execute a function with an active context + * + * @param context context to be active during function execution + * @param fn function to execute in a context + * @param thisArg optional receiver to be used for calling fn + * @param args optional arguments forwarded to fn + */ + with(context2, fn, thisArg, ...args) { + return this._getContextManager().with(context2, fn, thisArg, ...args); + } + /** + * Bind a context to a target function or event emitter + * + * @param context context to bind to the event emitter or function. Defaults to the currently active context + * @param target function or event emitter to bind + */ + bind(context2, target) { + return this._getContextManager().bind(context2, target); + } + _getContextManager() { + return (0, global_utils_1.getGlobal)(API_NAME) || NOOP_CONTEXT_MANAGER; + } + /** Disable and remove the global context manager */ + disable() { + this._getContextManager().disable(); + (0, global_utils_1.unregisterGlobal)(API_NAME, diag_1.DiagAPI.instance()); + } + } + context.ContextAPI = ContextAPI; + return context; +} +var contextUtils = {}; +var NonRecordingSpan = {}; +var invalidSpanConstants = {}; +var trace_flags = {}; +var hasRequiredTrace_flags; +function requireTrace_flags() { + if (hasRequiredTrace_flags) return trace_flags; + hasRequiredTrace_flags = 1; + (function(exports$1) { + Object.defineProperty(exports$1, "__esModule", { value: true }); + exports$1.TraceFlags = void 0; + (function(TraceFlags) { + TraceFlags[TraceFlags["NONE"] = 0] = "NONE"; + TraceFlags[TraceFlags["SAMPLED"] = 1] = "SAMPLED"; + })(exports$1.TraceFlags || (exports$1.TraceFlags = {})); + })(trace_flags); + return trace_flags; +} +var hasRequiredInvalidSpanConstants; +function requireInvalidSpanConstants() { + if (hasRequiredInvalidSpanConstants) return invalidSpanConstants; + hasRequiredInvalidSpanConstants = 1; + (function(exports$1) { + Object.defineProperty(exports$1, "__esModule", { value: true }); + exports$1.INVALID_SPAN_CONTEXT = exports$1.INVALID_TRACEID = exports$1.INVALID_SPANID = void 0; + const trace_flags_1 = /* @__PURE__ */ requireTrace_flags(); + exports$1.INVALID_SPANID = "0000000000000000"; + exports$1.INVALID_TRACEID = "00000000000000000000000000000000"; + exports$1.INVALID_SPAN_CONTEXT = { + traceId: exports$1.INVALID_TRACEID, + spanId: exports$1.INVALID_SPANID, + traceFlags: trace_flags_1.TraceFlags.NONE + }; + })(invalidSpanConstants); + return invalidSpanConstants; +} +var hasRequiredNonRecordingSpan; +function requireNonRecordingSpan() { + if (hasRequiredNonRecordingSpan) return NonRecordingSpan; + hasRequiredNonRecordingSpan = 1; + Object.defineProperty(NonRecordingSpan, "__esModule", { value: true }); + NonRecordingSpan.NonRecordingSpan = void 0; + const invalid_span_constants_1 = /* @__PURE__ */ requireInvalidSpanConstants(); + let NonRecordingSpan$1 = class NonRecordingSpan { + constructor(_spanContext = invalid_span_constants_1.INVALID_SPAN_CONTEXT) { + this._spanContext = _spanContext; + } + // Returns a SpanContext. + spanContext() { + return this._spanContext; + } + // By default does nothing + setAttribute(_key, _value) { + return this; + } + // By default does nothing + setAttributes(_attributes) { + return this; + } + // By default does nothing + addEvent(_name, _attributes) { + return this; + } + addLink(_link) { + return this; + } + addLinks(_links) { + return this; + } + // By default does nothing + setStatus(_status) { + return this; + } + // By default does nothing + updateName(_name) { + return this; + } + // By default does nothing + end(_endTime) { + } + // isRecording always returns false for NonRecordingSpan. + isRecording() { + return false; + } + // By default does nothing + recordException(_exception, _time) { + } + }; + NonRecordingSpan.NonRecordingSpan = NonRecordingSpan$1; + return NonRecordingSpan; +} +var hasRequiredContextUtils; +function requireContextUtils() { + if (hasRequiredContextUtils) return contextUtils; + hasRequiredContextUtils = 1; + Object.defineProperty(contextUtils, "__esModule", { value: true }); + contextUtils.getSpanContext = contextUtils.setSpanContext = contextUtils.deleteSpan = contextUtils.setSpan = contextUtils.getActiveSpan = contextUtils.getSpan = void 0; + const context_1 = /* @__PURE__ */ requireContext$1(); + const NonRecordingSpan_1 = /* @__PURE__ */ requireNonRecordingSpan(); + const context_2 = /* @__PURE__ */ requireContext(); + const SPAN_KEY = (0, context_1.createContextKey)("OpenTelemetry Context Key SPAN"); + function getSpan(context2) { + return context2.getValue(SPAN_KEY) || void 0; + } + contextUtils.getSpan = getSpan; + function getActiveSpan2() { + return getSpan(context_2.ContextAPI.getInstance().active()); + } + contextUtils.getActiveSpan = getActiveSpan2; + function setSpan(context2, span) { + return context2.setValue(SPAN_KEY, span); + } + contextUtils.setSpan = setSpan; + function deleteSpan(context2) { + return context2.deleteValue(SPAN_KEY); + } + contextUtils.deleteSpan = deleteSpan; + function setSpanContext(context2, spanContext) { + return setSpan(context2, new NonRecordingSpan_1.NonRecordingSpan(spanContext)); + } + contextUtils.setSpanContext = setSpanContext; + function getSpanContext(context2) { + var _a; + return (_a = getSpan(context2)) === null || _a === void 0 ? void 0 : _a.spanContext(); + } + contextUtils.getSpanContext = getSpanContext; + return contextUtils; +} +var spancontextUtils = {}; +var hasRequiredSpancontextUtils; +function requireSpancontextUtils() { + if (hasRequiredSpancontextUtils) return spancontextUtils; + hasRequiredSpancontextUtils = 1; + Object.defineProperty(spancontextUtils, "__esModule", { value: true }); + spancontextUtils.wrapSpanContext = spancontextUtils.isSpanContextValid = spancontextUtils.isValidSpanId = spancontextUtils.isValidTraceId = void 0; + const invalid_span_constants_1 = /* @__PURE__ */ requireInvalidSpanConstants(); + const NonRecordingSpan_1 = /* @__PURE__ */ requireNonRecordingSpan(); + const VALID_TRACEID_REGEX = /^([0-9a-f]{32})$/i; + const VALID_SPANID_REGEX = /^[0-9a-f]{16}$/i; + function isValidTraceId(traceId) { + return VALID_TRACEID_REGEX.test(traceId) && traceId !== invalid_span_constants_1.INVALID_TRACEID; + } + spancontextUtils.isValidTraceId = isValidTraceId; + function isValidSpanId(spanId) { + return VALID_SPANID_REGEX.test(spanId) && spanId !== invalid_span_constants_1.INVALID_SPANID; + } + spancontextUtils.isValidSpanId = isValidSpanId; + function isSpanContextValid(spanContext) { + return isValidTraceId(spanContext.traceId) && isValidSpanId(spanContext.spanId); + } + spancontextUtils.isSpanContextValid = isSpanContextValid; + function wrapSpanContext(spanContext) { + return new NonRecordingSpan_1.NonRecordingSpan(spanContext); + } + spancontextUtils.wrapSpanContext = wrapSpanContext; + return spancontextUtils; +} +var hasRequiredNoopTracer; +function requireNoopTracer() { + if (hasRequiredNoopTracer) return NoopTracer; + hasRequiredNoopTracer = 1; + Object.defineProperty(NoopTracer, "__esModule", { value: true }); + NoopTracer.NoopTracer = void 0; + const context_1 = /* @__PURE__ */ requireContext(); + const context_utils_1 = /* @__PURE__ */ requireContextUtils(); + const NonRecordingSpan_1 = /* @__PURE__ */ requireNonRecordingSpan(); + const spancontext_utils_1 = /* @__PURE__ */ requireSpancontextUtils(); + const contextApi2 = context_1.ContextAPI.getInstance(); + let NoopTracer$1 = class NoopTracer { + // startSpan starts a noop span. + startSpan(name, options, context2 = contextApi2.active()) { + const root = Boolean(options === null || options === void 0 ? void 0 : options.root); + if (root) { + return new NonRecordingSpan_1.NonRecordingSpan(); + } + const parentFromContext = context2 && (0, context_utils_1.getSpanContext)(context2); + if (isSpanContext(parentFromContext) && (0, spancontext_utils_1.isSpanContextValid)(parentFromContext)) { + return new NonRecordingSpan_1.NonRecordingSpan(parentFromContext); + } else { + return new NonRecordingSpan_1.NonRecordingSpan(); + } + } + startActiveSpan(name, arg2, arg3, arg4) { + let opts; + let ctx; + let fn; + if (arguments.length < 2) { + return; + } else if (arguments.length === 2) { + fn = arg2; + } else if (arguments.length === 3) { + opts = arg2; + fn = arg3; + } else { + opts = arg2; + ctx = arg3; + fn = arg4; + } + const parentContext = ctx !== null && ctx !== void 0 ? ctx : contextApi2.active(); + const span = this.startSpan(name, opts, parentContext); + const contextWithSpanSet = (0, context_utils_1.setSpan)(parentContext, span); + return contextApi2.with(contextWithSpanSet, fn, void 0, span); + } + }; + NoopTracer.NoopTracer = NoopTracer$1; + function isSpanContext(spanContext) { + return typeof spanContext === "object" && typeof spanContext["spanId"] === "string" && typeof spanContext["traceId"] === "string" && typeof spanContext["traceFlags"] === "number"; + } + return NoopTracer; +} +var hasRequiredProxyTracer; +function requireProxyTracer() { + if (hasRequiredProxyTracer) return ProxyTracer; + hasRequiredProxyTracer = 1; + Object.defineProperty(ProxyTracer, "__esModule", { value: true }); + ProxyTracer.ProxyTracer = void 0; + const NoopTracer_1 = /* @__PURE__ */ requireNoopTracer(); + const NOOP_TRACER = new NoopTracer_1.NoopTracer(); + let ProxyTracer$1 = class ProxyTracer { + constructor(_provider, name, version2, options) { + this._provider = _provider; + this.name = name; + this.version = version2; + this.options = options; + } + startSpan(name, options, context2) { + return this._getTracer().startSpan(name, options, context2); + } + startActiveSpan(_name, _options, _context, _fn) { + const tracer = this._getTracer(); + return Reflect.apply(tracer.startActiveSpan, tracer, arguments); + } + /** + * Try to get a tracer from the proxy tracer provider. + * If the proxy tracer provider has no delegate, return a noop tracer. + */ + _getTracer() { + if (this._delegate) { + return this._delegate; + } + const tracer = this._provider.getDelegateTracer(this.name, this.version, this.options); + if (!tracer) { + return NOOP_TRACER; + } + this._delegate = tracer; + return this._delegate; + } + }; + ProxyTracer.ProxyTracer = ProxyTracer$1; + return ProxyTracer; +} +var ProxyTracerProvider = {}; +var NoopTracerProvider = {}; +var hasRequiredNoopTracerProvider; +function requireNoopTracerProvider() { + if (hasRequiredNoopTracerProvider) return NoopTracerProvider; + hasRequiredNoopTracerProvider = 1; + Object.defineProperty(NoopTracerProvider, "__esModule", { value: true }); + NoopTracerProvider.NoopTracerProvider = void 0; + const NoopTracer_1 = /* @__PURE__ */ requireNoopTracer(); + let NoopTracerProvider$1 = class NoopTracerProvider { + getTracer(_name, _version, _options) { + return new NoopTracer_1.NoopTracer(); + } + }; + NoopTracerProvider.NoopTracerProvider = NoopTracerProvider$1; + return NoopTracerProvider; +} +var hasRequiredProxyTracerProvider; +function requireProxyTracerProvider() { + if (hasRequiredProxyTracerProvider) return ProxyTracerProvider; + hasRequiredProxyTracerProvider = 1; + Object.defineProperty(ProxyTracerProvider, "__esModule", { value: true }); + ProxyTracerProvider.ProxyTracerProvider = void 0; + const ProxyTracer_1 = /* @__PURE__ */ requireProxyTracer(); + const NoopTracerProvider_1 = /* @__PURE__ */ requireNoopTracerProvider(); + const NOOP_TRACER_PROVIDER = new NoopTracerProvider_1.NoopTracerProvider(); + let ProxyTracerProvider$1 = class ProxyTracerProvider { + /** + * Get a {@link ProxyTracer} + */ + getTracer(name, version2, options) { + var _a; + return (_a = this.getDelegateTracer(name, version2, options)) !== null && _a !== void 0 ? _a : new ProxyTracer_1.ProxyTracer(this, name, version2, options); + } + getDelegate() { + var _a; + return (_a = this._delegate) !== null && _a !== void 0 ? _a : NOOP_TRACER_PROVIDER; + } + /** + * Set the delegate tracer provider + */ + setDelegate(delegate) { + this._delegate = delegate; + } + getDelegateTracer(name, version2, options) { + var _a; + return (_a = this._delegate) === null || _a === void 0 ? void 0 : _a.getTracer(name, version2, options); + } + }; + ProxyTracerProvider.ProxyTracerProvider = ProxyTracerProvider$1; + return ProxyTracerProvider; +} +var SamplingResult = {}; +var hasRequiredSamplingResult; +function requireSamplingResult() { + if (hasRequiredSamplingResult) return SamplingResult; + hasRequiredSamplingResult = 1; + (function(exports$1) { + Object.defineProperty(exports$1, "__esModule", { value: true }); + exports$1.SamplingDecision = void 0; + (function(SamplingDecision2) { + SamplingDecision2[SamplingDecision2["NOT_RECORD"] = 0] = "NOT_RECORD"; + SamplingDecision2[SamplingDecision2["RECORD"] = 1] = "RECORD"; + SamplingDecision2[SamplingDecision2["RECORD_AND_SAMPLED"] = 2] = "RECORD_AND_SAMPLED"; + })(exports$1.SamplingDecision || (exports$1.SamplingDecision = {})); + })(SamplingResult); + return SamplingResult; +} +var span_kind = {}; +var hasRequiredSpan_kind; +function requireSpan_kind() { + if (hasRequiredSpan_kind) return span_kind; + hasRequiredSpan_kind = 1; + (function(exports$1) { + Object.defineProperty(exports$1, "__esModule", { value: true }); + exports$1.SpanKind = void 0; + (function(SpanKind) { + SpanKind[SpanKind["INTERNAL"] = 0] = "INTERNAL"; + SpanKind[SpanKind["SERVER"] = 1] = "SERVER"; + SpanKind[SpanKind["CLIENT"] = 2] = "CLIENT"; + SpanKind[SpanKind["PRODUCER"] = 3] = "PRODUCER"; + SpanKind[SpanKind["CONSUMER"] = 4] = "CONSUMER"; + })(exports$1.SpanKind || (exports$1.SpanKind = {})); + })(span_kind); + return span_kind; +} +var status = {}; +var hasRequiredStatus; +function requireStatus() { + if (hasRequiredStatus) return status; + hasRequiredStatus = 1; + (function(exports$1) { + Object.defineProperty(exports$1, "__esModule", { value: true }); + exports$1.SpanStatusCode = void 0; + (function(SpanStatusCode) { + SpanStatusCode[SpanStatusCode["UNSET"] = 0] = "UNSET"; + SpanStatusCode[SpanStatusCode["OK"] = 1] = "OK"; + SpanStatusCode[SpanStatusCode["ERROR"] = 2] = "ERROR"; + })(exports$1.SpanStatusCode || (exports$1.SpanStatusCode = {})); + })(status); + return status; +} +var utils$g = {}; +var tracestateImpl = {}; +var tracestateValidators = {}; +var hasRequiredTracestateValidators; +function requireTracestateValidators() { + if (hasRequiredTracestateValidators) return tracestateValidators; + hasRequiredTracestateValidators = 1; + Object.defineProperty(tracestateValidators, "__esModule", { value: true }); + tracestateValidators.validateValue = tracestateValidators.validateKey = void 0; + const VALID_KEY_CHAR_RANGE2 = "[_0-9a-z-*/]"; + const VALID_KEY2 = `[a-z]${VALID_KEY_CHAR_RANGE2}{0,255}`; + const VALID_VENDOR_KEY2 = `[a-z0-9]${VALID_KEY_CHAR_RANGE2}{0,240}@[a-z]${VALID_KEY_CHAR_RANGE2}{0,13}`; + const VALID_KEY_REGEX2 = new RegExp(`^(?:${VALID_KEY2}|${VALID_VENDOR_KEY2})$`); + const VALID_VALUE_BASE_REGEX2 = /^[ -~]{0,255}[!-~]$/; + const INVALID_VALUE_COMMA_EQUAL_REGEX2 = /,|=/; + function validateKey2(key) { + return VALID_KEY_REGEX2.test(key); + } + tracestateValidators.validateKey = validateKey2; + function validateValue2(value) { + return VALID_VALUE_BASE_REGEX2.test(value) && !INVALID_VALUE_COMMA_EQUAL_REGEX2.test(value); + } + tracestateValidators.validateValue = validateValue2; + return tracestateValidators; +} +var hasRequiredTracestateImpl; +function requireTracestateImpl() { + if (hasRequiredTracestateImpl) return tracestateImpl; + hasRequiredTracestateImpl = 1; + Object.defineProperty(tracestateImpl, "__esModule", { value: true }); + tracestateImpl.TraceStateImpl = void 0; + const tracestate_validators_1 = /* @__PURE__ */ requireTracestateValidators(); + const MAX_TRACE_STATE_ITEMS2 = 32; + const MAX_TRACE_STATE_LEN2 = 512; + const LIST_MEMBERS_SEPARATOR2 = ","; + const LIST_MEMBER_KEY_VALUE_SPLITTER2 = "="; + class TraceStateImpl { + constructor(rawTraceState) { + this._internalState = /* @__PURE__ */ new Map(); + if (rawTraceState) + this._parse(rawTraceState); + } + set(key, value) { + const traceState = this._clone(); + if (traceState._internalState.has(key)) { + traceState._internalState.delete(key); + } + traceState._internalState.set(key, value); + return traceState; + } + unset(key) { + const traceState = this._clone(); + traceState._internalState.delete(key); + return traceState; + } + get(key) { + return this._internalState.get(key); + } + serialize() { + return this._keys().reduce((agg, key) => { + agg.push(key + LIST_MEMBER_KEY_VALUE_SPLITTER2 + this.get(key)); + return agg; + }, []).join(LIST_MEMBERS_SEPARATOR2); + } + _parse(rawTraceState) { + if (rawTraceState.length > MAX_TRACE_STATE_LEN2) + return; + this._internalState = rawTraceState.split(LIST_MEMBERS_SEPARATOR2).reverse().reduce((agg, part) => { + const listMember = part.trim(); + const i = listMember.indexOf(LIST_MEMBER_KEY_VALUE_SPLITTER2); + if (i !== -1) { + const key = listMember.slice(0, i); + const value = listMember.slice(i + 1, part.length); + if ((0, tracestate_validators_1.validateKey)(key) && (0, tracestate_validators_1.validateValue)(value)) { + agg.set(key, value); + } + } + return agg; + }, /* @__PURE__ */ new Map()); + if (this._internalState.size > MAX_TRACE_STATE_ITEMS2) { + this._internalState = new Map(Array.from(this._internalState.entries()).reverse().slice(0, MAX_TRACE_STATE_ITEMS2)); + } + } + _keys() { + return Array.from(this._internalState.keys()).reverse(); + } + _clone() { + const traceState = new TraceStateImpl(); + traceState._internalState = new Map(this._internalState); + return traceState; + } + } + tracestateImpl.TraceStateImpl = TraceStateImpl; + return tracestateImpl; +} +var hasRequiredUtils$g; +function requireUtils$g() { + if (hasRequiredUtils$g) return utils$g; + hasRequiredUtils$g = 1; + Object.defineProperty(utils$g, "__esModule", { value: true }); + utils$g.createTraceState = void 0; + const tracestate_impl_1 = /* @__PURE__ */ requireTracestateImpl(); + function createTraceState(rawTraceState) { + return new tracestate_impl_1.TraceStateImpl(rawTraceState); + } + utils$g.createTraceState = createTraceState; + return utils$g; +} +var contextApi = {}; +var hasRequiredContextApi; +function requireContextApi() { + if (hasRequiredContextApi) return contextApi; + hasRequiredContextApi = 1; + Object.defineProperty(contextApi, "__esModule", { value: true }); + contextApi.context = void 0; + const context_1 = /* @__PURE__ */ requireContext(); + contextApi.context = context_1.ContextAPI.getInstance(); + return contextApi; +} +var diagApi = {}; +var hasRequiredDiagApi; +function requireDiagApi() { + if (hasRequiredDiagApi) return diagApi; + hasRequiredDiagApi = 1; + Object.defineProperty(diagApi, "__esModule", { value: true }); + diagApi.diag = void 0; + const diag_1 = /* @__PURE__ */ requireDiag(); + diagApi.diag = diag_1.DiagAPI.instance(); + return diagApi; +} +var metricsApi = {}; +var metrics = {}; +var NoopMeterProvider = {}; +var hasRequiredNoopMeterProvider; +function requireNoopMeterProvider() { + if (hasRequiredNoopMeterProvider) return NoopMeterProvider; + hasRequiredNoopMeterProvider = 1; + Object.defineProperty(NoopMeterProvider, "__esModule", { value: true }); + NoopMeterProvider.NOOP_METER_PROVIDER = NoopMeterProvider.NoopMeterProvider = void 0; + const NoopMeter_1 = /* @__PURE__ */ requireNoopMeter(); + let NoopMeterProvider$1 = class NoopMeterProvider { + getMeter(_name, _version, _options) { + return NoopMeter_1.NOOP_METER; + } + }; + NoopMeterProvider.NoopMeterProvider = NoopMeterProvider$1; + NoopMeterProvider.NOOP_METER_PROVIDER = new NoopMeterProvider$1(); + return NoopMeterProvider; +} +var hasRequiredMetrics; +function requireMetrics() { + if (hasRequiredMetrics) return metrics; + hasRequiredMetrics = 1; + Object.defineProperty(metrics, "__esModule", { value: true }); + metrics.MetricsAPI = void 0; + const NoopMeterProvider_1 = /* @__PURE__ */ requireNoopMeterProvider(); + const global_utils_1 = /* @__PURE__ */ requireGlobalUtils(); + const diag_1 = /* @__PURE__ */ requireDiag(); + const API_NAME = "metrics"; + class MetricsAPI { + /** Empty private constructor prevents end users from constructing a new instance of the API */ + constructor() { + } + /** Get the singleton instance of the Metrics API */ + static getInstance() { + if (!this._instance) { + this._instance = new MetricsAPI(); + } + return this._instance; + } + /** + * Set the current global meter provider. + * Returns true if the meter provider was successfully registered, else false. + */ + setGlobalMeterProvider(provider) { + return (0, global_utils_1.registerGlobal)(API_NAME, provider, diag_1.DiagAPI.instance()); + } + /** + * Returns the global meter provider. + */ + getMeterProvider() { + return (0, global_utils_1.getGlobal)(API_NAME) || NoopMeterProvider_1.NOOP_METER_PROVIDER; + } + /** + * Returns a meter from the global meter provider. + */ + getMeter(name, version2, options) { + return this.getMeterProvider().getMeter(name, version2, options); + } + /** Remove the global meter provider */ + disable() { + (0, global_utils_1.unregisterGlobal)(API_NAME, diag_1.DiagAPI.instance()); + } + } + metrics.MetricsAPI = MetricsAPI; + return metrics; +} +var hasRequiredMetricsApi; +function requireMetricsApi() { + if (hasRequiredMetricsApi) return metricsApi; + hasRequiredMetricsApi = 1; + Object.defineProperty(metricsApi, "__esModule", { value: true }); + metricsApi.metrics = void 0; + const metrics_1 = /* @__PURE__ */ requireMetrics(); + metricsApi.metrics = metrics_1.MetricsAPI.getInstance(); + return metricsApi; +} +var propagationApi = {}; +var propagation = {}; +var NoopTextMapPropagator = {}; +var hasRequiredNoopTextMapPropagator; +function requireNoopTextMapPropagator() { + if (hasRequiredNoopTextMapPropagator) return NoopTextMapPropagator; + hasRequiredNoopTextMapPropagator = 1; + Object.defineProperty(NoopTextMapPropagator, "__esModule", { value: true }); + NoopTextMapPropagator.NoopTextMapPropagator = void 0; + let NoopTextMapPropagator$1 = class NoopTextMapPropagator { + /** Noop inject function does nothing */ + inject(_context, _carrier) { + } + /** Noop extract function does nothing and returns the input context */ + extract(context2, _carrier) { + return context2; + } + fields() { + return []; + } + }; + NoopTextMapPropagator.NoopTextMapPropagator = NoopTextMapPropagator$1; + return NoopTextMapPropagator; +} +var contextHelpers = {}; +var hasRequiredContextHelpers; +function requireContextHelpers() { + if (hasRequiredContextHelpers) return contextHelpers; + hasRequiredContextHelpers = 1; + Object.defineProperty(contextHelpers, "__esModule", { value: true }); + contextHelpers.deleteBaggage = contextHelpers.setBaggage = contextHelpers.getActiveBaggage = contextHelpers.getBaggage = void 0; + const context_1 = /* @__PURE__ */ requireContext(); + const context_2 = /* @__PURE__ */ requireContext$1(); + const BAGGAGE_KEY = (0, context_2.createContextKey)("OpenTelemetry Baggage Key"); + function getBaggage(context2) { + return context2.getValue(BAGGAGE_KEY) || void 0; + } + contextHelpers.getBaggage = getBaggage; + function getActiveBaggage() { + return getBaggage(context_1.ContextAPI.getInstance().active()); + } + contextHelpers.getActiveBaggage = getActiveBaggage; + function setBaggage(context2, baggage) { + return context2.setValue(BAGGAGE_KEY, baggage); + } + contextHelpers.setBaggage = setBaggage; + function deleteBaggage(context2) { + return context2.deleteValue(BAGGAGE_KEY); + } + contextHelpers.deleteBaggage = deleteBaggage; + return contextHelpers; +} +var hasRequiredPropagation; +function requirePropagation() { + if (hasRequiredPropagation) return propagation; + hasRequiredPropagation = 1; + Object.defineProperty(propagation, "__esModule", { value: true }); + propagation.PropagationAPI = void 0; + const global_utils_1 = /* @__PURE__ */ requireGlobalUtils(); + const NoopTextMapPropagator_1 = /* @__PURE__ */ requireNoopTextMapPropagator(); + const TextMapPropagator_1 = /* @__PURE__ */ requireTextMapPropagator(); + const context_helpers_1 = /* @__PURE__ */ requireContextHelpers(); + const utils_1 = /* @__PURE__ */ requireUtils$h(); + const diag_1 = /* @__PURE__ */ requireDiag(); + const API_NAME = "propagation"; + const NOOP_TEXT_MAP_PROPAGATOR = new NoopTextMapPropagator_1.NoopTextMapPropagator(); + class PropagationAPI { + /** Empty private constructor prevents end users from constructing a new instance of the API */ + constructor() { + this.createBaggage = utils_1.createBaggage; + this.getBaggage = context_helpers_1.getBaggage; + this.getActiveBaggage = context_helpers_1.getActiveBaggage; + this.setBaggage = context_helpers_1.setBaggage; + this.deleteBaggage = context_helpers_1.deleteBaggage; + } + /** Get the singleton instance of the Propagator API */ + static getInstance() { + if (!this._instance) { + this._instance = new PropagationAPI(); + } + return this._instance; + } + /** + * Set the current propagator. + * + * @returns true if the propagator was successfully registered, else false + */ + setGlobalPropagator(propagator2) { + return (0, global_utils_1.registerGlobal)(API_NAME, propagator2, diag_1.DiagAPI.instance()); + } + /** + * Inject context into a carrier to be propagated inter-process + * + * @param context Context carrying tracing data to inject + * @param carrier carrier to inject context into + * @param setter Function used to set values on the carrier + */ + inject(context2, carrier, setter = TextMapPropagator_1.defaultTextMapSetter) { + return this._getGlobalPropagator().inject(context2, carrier, setter); + } + /** + * Extract context from a carrier + * + * @param context Context which the newly created context will inherit from + * @param carrier Carrier to extract context from + * @param getter Function used to extract keys from a carrier + */ + extract(context2, carrier, getter = TextMapPropagator_1.defaultTextMapGetter) { + return this._getGlobalPropagator().extract(context2, carrier, getter); + } + /** + * Return a list of all fields which may be used by the propagator. + */ + fields() { + return this._getGlobalPropagator().fields(); + } + /** Remove the global propagator */ + disable() { + (0, global_utils_1.unregisterGlobal)(API_NAME, diag_1.DiagAPI.instance()); + } + _getGlobalPropagator() { + return (0, global_utils_1.getGlobal)(API_NAME) || NOOP_TEXT_MAP_PROPAGATOR; + } + } + propagation.PropagationAPI = PropagationAPI; + return propagation; +} +var hasRequiredPropagationApi; +function requirePropagationApi() { + if (hasRequiredPropagationApi) return propagationApi; + hasRequiredPropagationApi = 1; + Object.defineProperty(propagationApi, "__esModule", { value: true }); + propagationApi.propagation = void 0; + const propagation_1 = /* @__PURE__ */ requirePropagation(); + propagationApi.propagation = propagation_1.PropagationAPI.getInstance(); + return propagationApi; +} +var traceApi = {}; +var trace$1 = {}; +var hasRequiredTrace$1; +function requireTrace$1() { + if (hasRequiredTrace$1) return trace$1; + hasRequiredTrace$1 = 1; + Object.defineProperty(trace$1, "__esModule", { value: true }); + trace$1.TraceAPI = void 0; + const global_utils_1 = /* @__PURE__ */ requireGlobalUtils(); + const ProxyTracerProvider_1 = /* @__PURE__ */ requireProxyTracerProvider(); + const spancontext_utils_1 = /* @__PURE__ */ requireSpancontextUtils(); + const context_utils_1 = /* @__PURE__ */ requireContextUtils(); + const diag_1 = /* @__PURE__ */ requireDiag(); + const API_NAME = "trace"; + class TraceAPI { + /** Empty private constructor prevents end users from constructing a new instance of the API */ + constructor() { + this._proxyTracerProvider = new ProxyTracerProvider_1.ProxyTracerProvider(); + this.wrapSpanContext = spancontext_utils_1.wrapSpanContext; + this.isSpanContextValid = spancontext_utils_1.isSpanContextValid; + this.deleteSpan = context_utils_1.deleteSpan; + this.getSpan = context_utils_1.getSpan; + this.getActiveSpan = context_utils_1.getActiveSpan; + this.getSpanContext = context_utils_1.getSpanContext; + this.setSpan = context_utils_1.setSpan; + this.setSpanContext = context_utils_1.setSpanContext; + } + /** Get the singleton instance of the Trace API */ + static getInstance() { + if (!this._instance) { + this._instance = new TraceAPI(); + } + return this._instance; + } + /** + * Set the current global tracer. + * + * @returns true if the tracer provider was successfully registered, else false + */ + setGlobalTracerProvider(provider) { + const success = (0, global_utils_1.registerGlobal)(API_NAME, this._proxyTracerProvider, diag_1.DiagAPI.instance()); + if (success) { + this._proxyTracerProvider.setDelegate(provider); + } + return success; + } + /** + * Returns the global tracer provider. + */ + getTracerProvider() { + return (0, global_utils_1.getGlobal)(API_NAME) || this._proxyTracerProvider; + } + /** + * Returns a tracer from the global tracer provider. + */ + getTracer(name, version2) { + return this.getTracerProvider().getTracer(name, version2); + } + /** Remove the global tracer provider */ + disable() { + (0, global_utils_1.unregisterGlobal)(API_NAME, diag_1.DiagAPI.instance()); + this._proxyTracerProvider = new ProxyTracerProvider_1.ProxyTracerProvider(); + } + } + trace$1.TraceAPI = TraceAPI; + return trace$1; +} +var hasRequiredTraceApi; +function requireTraceApi() { + if (hasRequiredTraceApi) return traceApi; + hasRequiredTraceApi = 1; + Object.defineProperty(traceApi, "__esModule", { value: true }); + traceApi.trace = void 0; + const trace_1 = /* @__PURE__ */ requireTrace$1(); + traceApi.trace = trace_1.TraceAPI.getInstance(); + return traceApi; +} +var hasRequiredSrc$n; +function requireSrc$n() { + if (hasRequiredSrc$n) return src$n; + hasRequiredSrc$n = 1; + (function(exports$1) { + Object.defineProperty(exports$1, "__esModule", { value: true }); + exports$1.trace = exports$1.propagation = exports$1.metrics = exports$1.diag = exports$1.context = exports$1.INVALID_SPAN_CONTEXT = exports$1.INVALID_TRACEID = exports$1.INVALID_SPANID = exports$1.isValidSpanId = exports$1.isValidTraceId = exports$1.isSpanContextValid = exports$1.createTraceState = exports$1.TraceFlags = exports$1.SpanStatusCode = exports$1.SpanKind = exports$1.SamplingDecision = exports$1.ProxyTracerProvider = exports$1.ProxyTracer = exports$1.defaultTextMapSetter = exports$1.defaultTextMapGetter = exports$1.ValueType = exports$1.createNoopMeter = exports$1.DiagLogLevel = exports$1.DiagConsoleLogger = exports$1.ROOT_CONTEXT = exports$1.createContextKey = exports$1.baggageEntryMetadataFromString = void 0; + var utils_1 = /* @__PURE__ */ requireUtils$h(); + Object.defineProperty(exports$1, "baggageEntryMetadataFromString", { enumerable: true, get: function() { + return utils_1.baggageEntryMetadataFromString; + } }); + var context_1 = /* @__PURE__ */ requireContext$1(); + Object.defineProperty(exports$1, "createContextKey", { enumerable: true, get: function() { + return context_1.createContextKey; + } }); + Object.defineProperty(exports$1, "ROOT_CONTEXT", { enumerable: true, get: function() { + return context_1.ROOT_CONTEXT; + } }); + var consoleLogger_1 = /* @__PURE__ */ requireConsoleLogger(); + Object.defineProperty(exports$1, "DiagConsoleLogger", { enumerable: true, get: function() { + return consoleLogger_1.DiagConsoleLogger; + } }); + var types_1 = /* @__PURE__ */ requireTypes$3(); + Object.defineProperty(exports$1, "DiagLogLevel", { enumerable: true, get: function() { + return types_1.DiagLogLevel; + } }); + var NoopMeter_1 = /* @__PURE__ */ requireNoopMeter(); + Object.defineProperty(exports$1, "createNoopMeter", { enumerable: true, get: function() { + return NoopMeter_1.createNoopMeter; + } }); + var Metric_1 = /* @__PURE__ */ requireMetric(); + Object.defineProperty(exports$1, "ValueType", { enumerable: true, get: function() { + return Metric_1.ValueType; + } }); + var TextMapPropagator_1 = /* @__PURE__ */ requireTextMapPropagator(); + Object.defineProperty(exports$1, "defaultTextMapGetter", { enumerable: true, get: function() { + return TextMapPropagator_1.defaultTextMapGetter; + } }); + Object.defineProperty(exports$1, "defaultTextMapSetter", { enumerable: true, get: function() { + return TextMapPropagator_1.defaultTextMapSetter; + } }); + var ProxyTracer_1 = /* @__PURE__ */ requireProxyTracer(); + Object.defineProperty(exports$1, "ProxyTracer", { enumerable: true, get: function() { + return ProxyTracer_1.ProxyTracer; + } }); + var ProxyTracerProvider_1 = /* @__PURE__ */ requireProxyTracerProvider(); + Object.defineProperty(exports$1, "ProxyTracerProvider", { enumerable: true, get: function() { + return ProxyTracerProvider_1.ProxyTracerProvider; + } }); + var SamplingResult_1 = /* @__PURE__ */ requireSamplingResult(); + Object.defineProperty(exports$1, "SamplingDecision", { enumerable: true, get: function() { + return SamplingResult_1.SamplingDecision; + } }); + var span_kind_1 = /* @__PURE__ */ requireSpan_kind(); + Object.defineProperty(exports$1, "SpanKind", { enumerable: true, get: function() { + return span_kind_1.SpanKind; + } }); + var status_1 = /* @__PURE__ */ requireStatus(); + Object.defineProperty(exports$1, "SpanStatusCode", { enumerable: true, get: function() { + return status_1.SpanStatusCode; + } }); + var trace_flags_1 = /* @__PURE__ */ requireTrace_flags(); + Object.defineProperty(exports$1, "TraceFlags", { enumerable: true, get: function() { + return trace_flags_1.TraceFlags; + } }); + var utils_2 = /* @__PURE__ */ requireUtils$g(); + Object.defineProperty(exports$1, "createTraceState", { enumerable: true, get: function() { + return utils_2.createTraceState; + } }); + var spancontext_utils_1 = /* @__PURE__ */ requireSpancontextUtils(); + Object.defineProperty(exports$1, "isSpanContextValid", { enumerable: true, get: function() { + return spancontext_utils_1.isSpanContextValid; + } }); + Object.defineProperty(exports$1, "isValidTraceId", { enumerable: true, get: function() { + return spancontext_utils_1.isValidTraceId; + } }); + Object.defineProperty(exports$1, "isValidSpanId", { enumerable: true, get: function() { + return spancontext_utils_1.isValidSpanId; + } }); + var invalid_span_constants_1 = /* @__PURE__ */ requireInvalidSpanConstants(); + Object.defineProperty(exports$1, "INVALID_SPANID", { enumerable: true, get: function() { + return invalid_span_constants_1.INVALID_SPANID; + } }); + Object.defineProperty(exports$1, "INVALID_TRACEID", { enumerable: true, get: function() { + return invalid_span_constants_1.INVALID_TRACEID; + } }); + Object.defineProperty(exports$1, "INVALID_SPAN_CONTEXT", { enumerable: true, get: function() { + return invalid_span_constants_1.INVALID_SPAN_CONTEXT; + } }); + const context_api_1 = /* @__PURE__ */ requireContextApi(); + Object.defineProperty(exports$1, "context", { enumerable: true, get: function() { + return context_api_1.context; + } }); + const diag_api_1 = /* @__PURE__ */ requireDiagApi(); + Object.defineProperty(exports$1, "diag", { enumerable: true, get: function() { + return diag_api_1.diag; + } }); + const metrics_api_1 = /* @__PURE__ */ requireMetricsApi(); + Object.defineProperty(exports$1, "metrics", { enumerable: true, get: function() { + return metrics_api_1.metrics; + } }); + const propagation_api_1 = /* @__PURE__ */ requirePropagationApi(); + Object.defineProperty(exports$1, "propagation", { enumerable: true, get: function() { + return propagation_api_1.propagation; + } }); + const trace_api_1 = /* @__PURE__ */ requireTraceApi(); + Object.defineProperty(exports$1, "trace", { enumerable: true, get: function() { + return trace_api_1.trace; + } }); + exports$1.default = { + context: context_api_1.context, + diag: diag_api_1.diag, + metrics: metrics_api_1.metrics, + propagation: propagation_api_1.propagation, + trace: trace_api_1.trace + }; + })(src$n); + return src$n; +} +var srcExports$l = /* @__PURE__ */ requireSrc$n(); +var src$m = {}; +var http = {}; +const SUPPRESS_TRACING_KEY = srcExports$l.createContextKey("OpenTelemetry SDK Context Key SUPPRESS_TRACING"); +function suppressTracing$1(context2) { + return context2.setValue(SUPPRESS_TRACING_KEY, true); +} +function unsuppressTracing(context2) { + return context2.deleteValue(SUPPRESS_TRACING_KEY); +} +function isTracingSuppressed(context2) { + return context2.getValue(SUPPRESS_TRACING_KEY) === true; +} +const BAGGAGE_KEY_PAIR_SEPARATOR = "="; +const BAGGAGE_PROPERTIES_SEPARATOR = ";"; +const BAGGAGE_ITEMS_SEPARATOR = ","; +const BAGGAGE_HEADER = "baggage"; +const BAGGAGE_MAX_NAME_VALUE_PAIRS = 180; +const BAGGAGE_MAX_PER_NAME_VALUE_PAIRS = 4096; +const BAGGAGE_MAX_TOTAL_LENGTH = 8192; +function serializeKeyPairs(keyPairs) { + return keyPairs.reduce((hValue, current) => { + const value = `${hValue}${hValue !== "" ? BAGGAGE_ITEMS_SEPARATOR : ""}${current}`; + return value.length > BAGGAGE_MAX_TOTAL_LENGTH ? hValue : value; + }, ""); +} +function getKeyPairs(baggage) { + return baggage.getAllEntries().map(([key, value]) => { + let entry = `${encodeURIComponent(key)}=${encodeURIComponent(value.value)}`; + if (value.metadata !== void 0) { + entry += BAGGAGE_PROPERTIES_SEPARATOR + value.metadata.toString(); + } + return entry; + }); +} +function parsePairKeyValue(entry) { + const valueProps = entry.split(BAGGAGE_PROPERTIES_SEPARATOR); + if (valueProps.length <= 0) + return; + const keyPairPart = valueProps.shift(); + if (!keyPairPart) + return; + const separatorIndex = keyPairPart.indexOf(BAGGAGE_KEY_PAIR_SEPARATOR); + if (separatorIndex <= 0) + return; + const key = decodeURIComponent(keyPairPart.substring(0, separatorIndex).trim()); + const value = decodeURIComponent(keyPairPart.substring(separatorIndex + 1).trim()); + let metadata; + if (valueProps.length > 0) { + metadata = srcExports$l.baggageEntryMetadataFromString(valueProps.join(BAGGAGE_PROPERTIES_SEPARATOR)); + } + return { key, value, metadata }; +} +function parseKeyPairsIntoRecord(value) { + const result = {}; + if (typeof value === "string" && value.length > 0) { + value.split(BAGGAGE_ITEMS_SEPARATOR).forEach((entry) => { + const keyPair = parsePairKeyValue(entry); + if (keyPair !== void 0 && keyPair.value.length > 0) { + result[keyPair.key] = keyPair.value; + } + }); + } + return result; +} +class W3CBaggagePropagator { + inject(context2, carrier, setter) { + const baggage = srcExports$l.propagation.getBaggage(context2); + if (!baggage || isTracingSuppressed(context2)) + return; + const keyPairs = getKeyPairs(baggage).filter((pair) => { + return pair.length <= BAGGAGE_MAX_PER_NAME_VALUE_PAIRS; + }).slice(0, BAGGAGE_MAX_NAME_VALUE_PAIRS); + const headerValue = serializeKeyPairs(keyPairs); + if (headerValue.length > 0) { + setter.set(carrier, BAGGAGE_HEADER, headerValue); + } + } + extract(context2, carrier, getter) { + const headerValue = getter.get(carrier, BAGGAGE_HEADER); + const baggageString = Array.isArray(headerValue) ? headerValue.join(BAGGAGE_ITEMS_SEPARATOR) : headerValue; + if (!baggageString) + return context2; + const baggage = {}; + if (baggageString.length === 0) { + return context2; + } + const pairs = baggageString.split(BAGGAGE_ITEMS_SEPARATOR); + pairs.forEach((entry) => { + const keyPair = parsePairKeyValue(entry); + if (keyPair) { + const baggageEntry = { value: keyPair.value }; + if (keyPair.metadata) { + baggageEntry.metadata = keyPair.metadata; + } + baggage[keyPair.key] = baggageEntry; + } + }); + if (Object.entries(baggage).length === 0) { + return context2; + } + return srcExports$l.propagation.setBaggage(context2, srcExports$l.propagation.createBaggage(baggage)); + } + fields() { + return [BAGGAGE_HEADER]; + } +} +class AnchoredClock { + _monotonicClock; + _epochMillis; + _performanceMillis; + /** + * Create a new AnchoredClock anchored to the current time returned by systemClock. + * + * @param systemClock should be a clock that returns the number of milliseconds since January 1 1970 such as Date + * @param monotonicClock should be a clock that counts milliseconds monotonically such as window.performance or perf_hooks.performance + */ + constructor(systemClock, monotonicClock) { + this._monotonicClock = monotonicClock; + this._epochMillis = systemClock.now(); + this._performanceMillis = monotonicClock.now(); + } + /** + * Returns the current time by adding the number of milliseconds since the + * AnchoredClock was created to the creation epoch time + */ + now() { + const delta = this._monotonicClock.now() - this._performanceMillis; + return this._epochMillis + delta; + } +} +function sanitizeAttributes(attributes) { + const out = {}; + if (typeof attributes !== "object" || attributes == null) { + return out; + } + for (const key in attributes) { + if (!Object.prototype.hasOwnProperty.call(attributes, key)) { + continue; + } + if (!isAttributeKey(key)) { + srcExports$l.diag.warn(`Invalid attribute key: ${key}`); + continue; + } + const val = attributes[key]; + if (!isAttributeValue(val)) { + srcExports$l.diag.warn(`Invalid attribute value set for key: ${key}`); + continue; + } + if (Array.isArray(val)) { + out[key] = val.slice(); + } else { + out[key] = val; + } + } + return out; +} +function isAttributeKey(key) { + return typeof key === "string" && key !== ""; +} +function isAttributeValue(val) { + if (val == null) { + return true; + } + if (Array.isArray(val)) { + return isHomogeneousAttributeValueArray(val); + } + return isValidPrimitiveAttributeValueType(typeof val); +} +function isHomogeneousAttributeValueArray(arr) { + let type; + for (const element of arr) { + if (element == null) + continue; + const elementType = typeof element; + if (elementType === type) { + continue; + } + if (!type) { + if (isValidPrimitiveAttributeValueType(elementType)) { + type = elementType; + continue; + } + return false; + } + return false; + } + return true; +} +function isValidPrimitiveAttributeValueType(valType) { + switch (valType) { + case "number": + case "boolean": + case "string": + return true; + } + return false; +} +function loggingErrorHandler() { + return (ex) => { + srcExports$l.diag.error(stringifyException(ex)); + }; +} +function stringifyException(ex) { + if (typeof ex === "string") { + return ex; + } else { + return JSON.stringify(flattenException(ex)); + } +} +function flattenException(ex) { + const result = {}; + let current = ex; + while (current !== null) { + Object.getOwnPropertyNames(current).forEach((propertyName) => { + if (result[propertyName]) + return; + const value = current[propertyName]; + if (value) { + result[propertyName] = String(value); + } + }); + current = Object.getPrototypeOf(current); + } + return result; +} +let delegateHandler = loggingErrorHandler(); +function setGlobalErrorHandler(handler) { + delegateHandler = handler; +} +function globalErrorHandler(ex) { + try { + delegateHandler(ex); + } catch { + } +} +function getNumberFromEnv(key) { + const raw = process.env[key]; + if (raw == null || raw.trim() === "") { + return void 0; + } + const value = Number(raw); + if (isNaN(value)) { + srcExports$l.diag.warn(`Unknown value ${inspect(raw)} for ${key}, expected a number, using defaults`); + return void 0; + } + return value; +} +function getStringFromEnv(key) { + const raw = process.env[key]; + if (raw == null || raw.trim() === "") { + return void 0; + } + return raw; +} +function getBooleanFromEnv(key) { + const raw = process.env[key]?.trim().toLowerCase(); + if (raw == null || raw === "") { + return false; + } + if (raw === "true") { + return true; + } else if (raw === "false") { + return false; + } else { + srcExports$l.diag.warn(`Unknown value ${inspect(raw)} for ${key}, expected 'true' or 'false', falling back to 'false' (default)`); + return false; + } +} +function getStringListFromEnv(key) { + return getStringFromEnv(key)?.split(",").map((v) => v.trim()).filter((s) => s !== ""); +} +const _globalThis$1 = typeof globalThis === "object" ? globalThis : global; +const otperformance = performance; +const VERSION$2 = "2.2.0"; +var src$l = {}; +var trace = {}; +var SemanticAttributes = {}; +var utils$f = {}; +var hasRequiredUtils$f; +function requireUtils$f() { + if (hasRequiredUtils$f) return utils$f; + hasRequiredUtils$f = 1; + Object.defineProperty(utils$f, "__esModule", { value: true }); + utils$f.createConstMap = void 0; + // @__NO_SIDE_EFFECTS__ + function createConstMap(values) { + let res = {}; + const len = values.length; + for (let lp = 0; lp < len; lp++) { + const val = values[lp]; + if (val) { + res[String(val).toUpperCase().replace(/[-.]/g, "_")] = val; + } + } + return res; + } + utils$f.createConstMap = createConstMap; + return utils$f; +} +var hasRequiredSemanticAttributes; +function requireSemanticAttributes() { + if (hasRequiredSemanticAttributes) return SemanticAttributes; + hasRequiredSemanticAttributes = 1; + Object.defineProperty(SemanticAttributes, "__esModule", { value: true }); + SemanticAttributes.SEMATTRS_NET_HOST_CARRIER_ICC = SemanticAttributes.SEMATTRS_NET_HOST_CARRIER_MNC = SemanticAttributes.SEMATTRS_NET_HOST_CARRIER_MCC = SemanticAttributes.SEMATTRS_NET_HOST_CARRIER_NAME = SemanticAttributes.SEMATTRS_NET_HOST_CONNECTION_SUBTYPE = SemanticAttributes.SEMATTRS_NET_HOST_CONNECTION_TYPE = SemanticAttributes.SEMATTRS_NET_HOST_NAME = SemanticAttributes.SEMATTRS_NET_HOST_PORT = SemanticAttributes.SEMATTRS_NET_HOST_IP = SemanticAttributes.SEMATTRS_NET_PEER_NAME = SemanticAttributes.SEMATTRS_NET_PEER_PORT = SemanticAttributes.SEMATTRS_NET_PEER_IP = SemanticAttributes.SEMATTRS_NET_TRANSPORT = SemanticAttributes.SEMATTRS_FAAS_INVOKED_REGION = SemanticAttributes.SEMATTRS_FAAS_INVOKED_PROVIDER = SemanticAttributes.SEMATTRS_FAAS_INVOKED_NAME = SemanticAttributes.SEMATTRS_FAAS_COLDSTART = SemanticAttributes.SEMATTRS_FAAS_CRON = SemanticAttributes.SEMATTRS_FAAS_TIME = SemanticAttributes.SEMATTRS_FAAS_DOCUMENT_NAME = SemanticAttributes.SEMATTRS_FAAS_DOCUMENT_TIME = SemanticAttributes.SEMATTRS_FAAS_DOCUMENT_OPERATION = SemanticAttributes.SEMATTRS_FAAS_DOCUMENT_COLLECTION = SemanticAttributes.SEMATTRS_FAAS_EXECUTION = SemanticAttributes.SEMATTRS_FAAS_TRIGGER = SemanticAttributes.SEMATTRS_EXCEPTION_ESCAPED = SemanticAttributes.SEMATTRS_EXCEPTION_STACKTRACE = SemanticAttributes.SEMATTRS_EXCEPTION_MESSAGE = SemanticAttributes.SEMATTRS_EXCEPTION_TYPE = SemanticAttributes.SEMATTRS_DB_SQL_TABLE = SemanticAttributes.SEMATTRS_DB_MONGODB_COLLECTION = SemanticAttributes.SEMATTRS_DB_REDIS_DATABASE_INDEX = SemanticAttributes.SEMATTRS_DB_HBASE_NAMESPACE = SemanticAttributes.SEMATTRS_DB_CASSANDRA_COORDINATOR_DC = SemanticAttributes.SEMATTRS_DB_CASSANDRA_COORDINATOR_ID = SemanticAttributes.SEMATTRS_DB_CASSANDRA_SPECULATIVE_EXECUTION_COUNT = SemanticAttributes.SEMATTRS_DB_CASSANDRA_IDEMPOTENCE = SemanticAttributes.SEMATTRS_DB_CASSANDRA_TABLE = SemanticAttributes.SEMATTRS_DB_CASSANDRA_CONSISTENCY_LEVEL = SemanticAttributes.SEMATTRS_DB_CASSANDRA_PAGE_SIZE = SemanticAttributes.SEMATTRS_DB_CASSANDRA_KEYSPACE = SemanticAttributes.SEMATTRS_DB_MSSQL_INSTANCE_NAME = SemanticAttributes.SEMATTRS_DB_OPERATION = SemanticAttributes.SEMATTRS_DB_STATEMENT = SemanticAttributes.SEMATTRS_DB_NAME = SemanticAttributes.SEMATTRS_DB_JDBC_DRIVER_CLASSNAME = SemanticAttributes.SEMATTRS_DB_USER = SemanticAttributes.SEMATTRS_DB_CONNECTION_STRING = SemanticAttributes.SEMATTRS_DB_SYSTEM = SemanticAttributes.SEMATTRS_AWS_LAMBDA_INVOKED_ARN = void 0; + SemanticAttributes.SEMATTRS_MESSAGING_DESTINATION_KIND = SemanticAttributes.SEMATTRS_MESSAGING_DESTINATION = SemanticAttributes.SEMATTRS_MESSAGING_SYSTEM = SemanticAttributes.SEMATTRS_AWS_DYNAMODB_GLOBAL_SECONDARY_INDEX_UPDATES = SemanticAttributes.SEMATTRS_AWS_DYNAMODB_ATTRIBUTE_DEFINITIONS = SemanticAttributes.SEMATTRS_AWS_DYNAMODB_SCANNED_COUNT = SemanticAttributes.SEMATTRS_AWS_DYNAMODB_COUNT = SemanticAttributes.SEMATTRS_AWS_DYNAMODB_TOTAL_SEGMENTS = SemanticAttributes.SEMATTRS_AWS_DYNAMODB_SEGMENT = SemanticAttributes.SEMATTRS_AWS_DYNAMODB_SCAN_FORWARD = SemanticAttributes.SEMATTRS_AWS_DYNAMODB_TABLE_COUNT = SemanticAttributes.SEMATTRS_AWS_DYNAMODB_EXCLUSIVE_START_TABLE = SemanticAttributes.SEMATTRS_AWS_DYNAMODB_LOCAL_SECONDARY_INDEXES = SemanticAttributes.SEMATTRS_AWS_DYNAMODB_GLOBAL_SECONDARY_INDEXES = SemanticAttributes.SEMATTRS_AWS_DYNAMODB_SELECT = SemanticAttributes.SEMATTRS_AWS_DYNAMODB_INDEX_NAME = SemanticAttributes.SEMATTRS_AWS_DYNAMODB_ATTRIBUTES_TO_GET = SemanticAttributes.SEMATTRS_AWS_DYNAMODB_LIMIT = SemanticAttributes.SEMATTRS_AWS_DYNAMODB_PROJECTION = SemanticAttributes.SEMATTRS_AWS_DYNAMODB_CONSISTENT_READ = SemanticAttributes.SEMATTRS_AWS_DYNAMODB_PROVISIONED_WRITE_CAPACITY = SemanticAttributes.SEMATTRS_AWS_DYNAMODB_PROVISIONED_READ_CAPACITY = SemanticAttributes.SEMATTRS_AWS_DYNAMODB_ITEM_COLLECTION_METRICS = SemanticAttributes.SEMATTRS_AWS_DYNAMODB_CONSUMED_CAPACITY = SemanticAttributes.SEMATTRS_AWS_DYNAMODB_TABLE_NAMES = SemanticAttributes.SEMATTRS_HTTP_CLIENT_IP = SemanticAttributes.SEMATTRS_HTTP_ROUTE = SemanticAttributes.SEMATTRS_HTTP_SERVER_NAME = SemanticAttributes.SEMATTRS_HTTP_RESPONSE_CONTENT_LENGTH_UNCOMPRESSED = SemanticAttributes.SEMATTRS_HTTP_RESPONSE_CONTENT_LENGTH = SemanticAttributes.SEMATTRS_HTTP_REQUEST_CONTENT_LENGTH_UNCOMPRESSED = SemanticAttributes.SEMATTRS_HTTP_REQUEST_CONTENT_LENGTH = SemanticAttributes.SEMATTRS_HTTP_USER_AGENT = SemanticAttributes.SEMATTRS_HTTP_FLAVOR = SemanticAttributes.SEMATTRS_HTTP_STATUS_CODE = SemanticAttributes.SEMATTRS_HTTP_SCHEME = SemanticAttributes.SEMATTRS_HTTP_HOST = SemanticAttributes.SEMATTRS_HTTP_TARGET = SemanticAttributes.SEMATTRS_HTTP_URL = SemanticAttributes.SEMATTRS_HTTP_METHOD = SemanticAttributes.SEMATTRS_CODE_LINENO = SemanticAttributes.SEMATTRS_CODE_FILEPATH = SemanticAttributes.SEMATTRS_CODE_NAMESPACE = SemanticAttributes.SEMATTRS_CODE_FUNCTION = SemanticAttributes.SEMATTRS_THREAD_NAME = SemanticAttributes.SEMATTRS_THREAD_ID = SemanticAttributes.SEMATTRS_ENDUSER_SCOPE = SemanticAttributes.SEMATTRS_ENDUSER_ROLE = SemanticAttributes.SEMATTRS_ENDUSER_ID = SemanticAttributes.SEMATTRS_PEER_SERVICE = void 0; + SemanticAttributes.DBSYSTEMVALUES_FILEMAKER = SemanticAttributes.DBSYSTEMVALUES_DERBY = SemanticAttributes.DBSYSTEMVALUES_FIREBIRD = SemanticAttributes.DBSYSTEMVALUES_ADABAS = SemanticAttributes.DBSYSTEMVALUES_CACHE = SemanticAttributes.DBSYSTEMVALUES_EDB = SemanticAttributes.DBSYSTEMVALUES_FIRSTSQL = SemanticAttributes.DBSYSTEMVALUES_INGRES = SemanticAttributes.DBSYSTEMVALUES_HANADB = SemanticAttributes.DBSYSTEMVALUES_MAXDB = SemanticAttributes.DBSYSTEMVALUES_PROGRESS = SemanticAttributes.DBSYSTEMVALUES_HSQLDB = SemanticAttributes.DBSYSTEMVALUES_CLOUDSCAPE = SemanticAttributes.DBSYSTEMVALUES_HIVE = SemanticAttributes.DBSYSTEMVALUES_REDSHIFT = SemanticAttributes.DBSYSTEMVALUES_POSTGRESQL = SemanticAttributes.DBSYSTEMVALUES_DB2 = SemanticAttributes.DBSYSTEMVALUES_ORACLE = SemanticAttributes.DBSYSTEMVALUES_MYSQL = SemanticAttributes.DBSYSTEMVALUES_MSSQL = SemanticAttributes.DBSYSTEMVALUES_OTHER_SQL = SemanticAttributes.SemanticAttributes = SemanticAttributes.SEMATTRS_MESSAGE_UNCOMPRESSED_SIZE = SemanticAttributes.SEMATTRS_MESSAGE_COMPRESSED_SIZE = SemanticAttributes.SEMATTRS_MESSAGE_ID = SemanticAttributes.SEMATTRS_MESSAGE_TYPE = SemanticAttributes.SEMATTRS_RPC_JSONRPC_ERROR_MESSAGE = SemanticAttributes.SEMATTRS_RPC_JSONRPC_ERROR_CODE = SemanticAttributes.SEMATTRS_RPC_JSONRPC_REQUEST_ID = SemanticAttributes.SEMATTRS_RPC_JSONRPC_VERSION = SemanticAttributes.SEMATTRS_RPC_GRPC_STATUS_CODE = SemanticAttributes.SEMATTRS_RPC_METHOD = SemanticAttributes.SEMATTRS_RPC_SERVICE = SemanticAttributes.SEMATTRS_RPC_SYSTEM = SemanticAttributes.SEMATTRS_MESSAGING_KAFKA_TOMBSTONE = SemanticAttributes.SEMATTRS_MESSAGING_KAFKA_PARTITION = SemanticAttributes.SEMATTRS_MESSAGING_KAFKA_CLIENT_ID = SemanticAttributes.SEMATTRS_MESSAGING_KAFKA_CONSUMER_GROUP = SemanticAttributes.SEMATTRS_MESSAGING_KAFKA_MESSAGE_KEY = SemanticAttributes.SEMATTRS_MESSAGING_RABBITMQ_ROUTING_KEY = SemanticAttributes.SEMATTRS_MESSAGING_CONSUMER_ID = SemanticAttributes.SEMATTRS_MESSAGING_OPERATION = SemanticAttributes.SEMATTRS_MESSAGING_MESSAGE_PAYLOAD_COMPRESSED_SIZE_BYTES = SemanticAttributes.SEMATTRS_MESSAGING_MESSAGE_PAYLOAD_SIZE_BYTES = SemanticAttributes.SEMATTRS_MESSAGING_CONVERSATION_ID = SemanticAttributes.SEMATTRS_MESSAGING_MESSAGE_ID = SemanticAttributes.SEMATTRS_MESSAGING_URL = SemanticAttributes.SEMATTRS_MESSAGING_PROTOCOL_VERSION = SemanticAttributes.SEMATTRS_MESSAGING_PROTOCOL = SemanticAttributes.SEMATTRS_MESSAGING_TEMP_DESTINATION = void 0; + SemanticAttributes.FAASINVOKEDPROVIDERVALUES_ALIBABA_CLOUD = SemanticAttributes.FaasDocumentOperationValues = SemanticAttributes.FAASDOCUMENTOPERATIONVALUES_DELETE = SemanticAttributes.FAASDOCUMENTOPERATIONVALUES_EDIT = SemanticAttributes.FAASDOCUMENTOPERATIONVALUES_INSERT = SemanticAttributes.FaasTriggerValues = SemanticAttributes.FAASTRIGGERVALUES_OTHER = SemanticAttributes.FAASTRIGGERVALUES_TIMER = SemanticAttributes.FAASTRIGGERVALUES_PUBSUB = SemanticAttributes.FAASTRIGGERVALUES_HTTP = SemanticAttributes.FAASTRIGGERVALUES_DATASOURCE = SemanticAttributes.DbCassandraConsistencyLevelValues = SemanticAttributes.DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_SERIAL = SemanticAttributes.DBCASSANDRACONSISTENCYLEVELVALUES_SERIAL = SemanticAttributes.DBCASSANDRACONSISTENCYLEVELVALUES_ANY = SemanticAttributes.DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_ONE = SemanticAttributes.DBCASSANDRACONSISTENCYLEVELVALUES_THREE = SemanticAttributes.DBCASSANDRACONSISTENCYLEVELVALUES_TWO = SemanticAttributes.DBCASSANDRACONSISTENCYLEVELVALUES_ONE = SemanticAttributes.DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_QUORUM = SemanticAttributes.DBCASSANDRACONSISTENCYLEVELVALUES_QUORUM = SemanticAttributes.DBCASSANDRACONSISTENCYLEVELVALUES_EACH_QUORUM = SemanticAttributes.DBCASSANDRACONSISTENCYLEVELVALUES_ALL = SemanticAttributes.DbSystemValues = SemanticAttributes.DBSYSTEMVALUES_COCKROACHDB = SemanticAttributes.DBSYSTEMVALUES_MEMCACHED = SemanticAttributes.DBSYSTEMVALUES_ELASTICSEARCH = SemanticAttributes.DBSYSTEMVALUES_GEODE = SemanticAttributes.DBSYSTEMVALUES_NEO4J = SemanticAttributes.DBSYSTEMVALUES_DYNAMODB = SemanticAttributes.DBSYSTEMVALUES_COSMOSDB = SemanticAttributes.DBSYSTEMVALUES_COUCHDB = SemanticAttributes.DBSYSTEMVALUES_COUCHBASE = SemanticAttributes.DBSYSTEMVALUES_REDIS = SemanticAttributes.DBSYSTEMVALUES_MONGODB = SemanticAttributes.DBSYSTEMVALUES_HBASE = SemanticAttributes.DBSYSTEMVALUES_CASSANDRA = SemanticAttributes.DBSYSTEMVALUES_COLDFUSION = SemanticAttributes.DBSYSTEMVALUES_H2 = SemanticAttributes.DBSYSTEMVALUES_VERTICA = SemanticAttributes.DBSYSTEMVALUES_TERADATA = SemanticAttributes.DBSYSTEMVALUES_SYBASE = SemanticAttributes.DBSYSTEMVALUES_SQLITE = SemanticAttributes.DBSYSTEMVALUES_POINTBASE = SemanticAttributes.DBSYSTEMVALUES_PERVASIVE = SemanticAttributes.DBSYSTEMVALUES_NETEZZA = SemanticAttributes.DBSYSTEMVALUES_MARIADB = SemanticAttributes.DBSYSTEMVALUES_INTERBASE = SemanticAttributes.DBSYSTEMVALUES_INSTANTDB = SemanticAttributes.DBSYSTEMVALUES_INFORMIX = void 0; + SemanticAttributes.MESSAGINGOPERATIONVALUES_RECEIVE = SemanticAttributes.MessagingDestinationKindValues = SemanticAttributes.MESSAGINGDESTINATIONKINDVALUES_TOPIC = SemanticAttributes.MESSAGINGDESTINATIONKINDVALUES_QUEUE = SemanticAttributes.HttpFlavorValues = SemanticAttributes.HTTPFLAVORVALUES_QUIC = SemanticAttributes.HTTPFLAVORVALUES_SPDY = SemanticAttributes.HTTPFLAVORVALUES_HTTP_2_0 = SemanticAttributes.HTTPFLAVORVALUES_HTTP_1_1 = SemanticAttributes.HTTPFLAVORVALUES_HTTP_1_0 = SemanticAttributes.NetHostConnectionSubtypeValues = SemanticAttributes.NETHOSTCONNECTIONSUBTYPEVALUES_LTE_CA = SemanticAttributes.NETHOSTCONNECTIONSUBTYPEVALUES_NRNSA = SemanticAttributes.NETHOSTCONNECTIONSUBTYPEVALUES_NR = SemanticAttributes.NETHOSTCONNECTIONSUBTYPEVALUES_IWLAN = SemanticAttributes.NETHOSTCONNECTIONSUBTYPEVALUES_TD_SCDMA = SemanticAttributes.NETHOSTCONNECTIONSUBTYPEVALUES_GSM = SemanticAttributes.NETHOSTCONNECTIONSUBTYPEVALUES_HSPAP = SemanticAttributes.NETHOSTCONNECTIONSUBTYPEVALUES_EHRPD = SemanticAttributes.NETHOSTCONNECTIONSUBTYPEVALUES_LTE = SemanticAttributes.NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_B = SemanticAttributes.NETHOSTCONNECTIONSUBTYPEVALUES_IDEN = SemanticAttributes.NETHOSTCONNECTIONSUBTYPEVALUES_HSPA = SemanticAttributes.NETHOSTCONNECTIONSUBTYPEVALUES_HSUPA = SemanticAttributes.NETHOSTCONNECTIONSUBTYPEVALUES_HSDPA = SemanticAttributes.NETHOSTCONNECTIONSUBTYPEVALUES_CDMA2000_1XRTT = SemanticAttributes.NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_A = SemanticAttributes.NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_0 = SemanticAttributes.NETHOSTCONNECTIONSUBTYPEVALUES_CDMA = SemanticAttributes.NETHOSTCONNECTIONSUBTYPEVALUES_UMTS = SemanticAttributes.NETHOSTCONNECTIONSUBTYPEVALUES_EDGE = SemanticAttributes.NETHOSTCONNECTIONSUBTYPEVALUES_GPRS = SemanticAttributes.NetHostConnectionTypeValues = SemanticAttributes.NETHOSTCONNECTIONTYPEVALUES_UNKNOWN = SemanticAttributes.NETHOSTCONNECTIONTYPEVALUES_UNAVAILABLE = SemanticAttributes.NETHOSTCONNECTIONTYPEVALUES_CELL = SemanticAttributes.NETHOSTCONNECTIONTYPEVALUES_WIRED = SemanticAttributes.NETHOSTCONNECTIONTYPEVALUES_WIFI = SemanticAttributes.NetTransportValues = SemanticAttributes.NETTRANSPORTVALUES_OTHER = SemanticAttributes.NETTRANSPORTVALUES_INPROC = SemanticAttributes.NETTRANSPORTVALUES_PIPE = SemanticAttributes.NETTRANSPORTVALUES_UNIX = SemanticAttributes.NETTRANSPORTVALUES_IP = SemanticAttributes.NETTRANSPORTVALUES_IP_UDP = SemanticAttributes.NETTRANSPORTVALUES_IP_TCP = SemanticAttributes.FaasInvokedProviderValues = SemanticAttributes.FAASINVOKEDPROVIDERVALUES_GCP = SemanticAttributes.FAASINVOKEDPROVIDERVALUES_AZURE = SemanticAttributes.FAASINVOKEDPROVIDERVALUES_AWS = void 0; + SemanticAttributes.MessageTypeValues = SemanticAttributes.MESSAGETYPEVALUES_RECEIVED = SemanticAttributes.MESSAGETYPEVALUES_SENT = SemanticAttributes.RpcGrpcStatusCodeValues = SemanticAttributes.RPCGRPCSTATUSCODEVALUES_UNAUTHENTICATED = SemanticAttributes.RPCGRPCSTATUSCODEVALUES_DATA_LOSS = SemanticAttributes.RPCGRPCSTATUSCODEVALUES_UNAVAILABLE = SemanticAttributes.RPCGRPCSTATUSCODEVALUES_INTERNAL = SemanticAttributes.RPCGRPCSTATUSCODEVALUES_UNIMPLEMENTED = SemanticAttributes.RPCGRPCSTATUSCODEVALUES_OUT_OF_RANGE = SemanticAttributes.RPCGRPCSTATUSCODEVALUES_ABORTED = SemanticAttributes.RPCGRPCSTATUSCODEVALUES_FAILED_PRECONDITION = SemanticAttributes.RPCGRPCSTATUSCODEVALUES_RESOURCE_EXHAUSTED = SemanticAttributes.RPCGRPCSTATUSCODEVALUES_PERMISSION_DENIED = SemanticAttributes.RPCGRPCSTATUSCODEVALUES_ALREADY_EXISTS = SemanticAttributes.RPCGRPCSTATUSCODEVALUES_NOT_FOUND = SemanticAttributes.RPCGRPCSTATUSCODEVALUES_DEADLINE_EXCEEDED = SemanticAttributes.RPCGRPCSTATUSCODEVALUES_INVALID_ARGUMENT = SemanticAttributes.RPCGRPCSTATUSCODEVALUES_UNKNOWN = SemanticAttributes.RPCGRPCSTATUSCODEVALUES_CANCELLED = SemanticAttributes.RPCGRPCSTATUSCODEVALUES_OK = SemanticAttributes.MessagingOperationValues = SemanticAttributes.MESSAGINGOPERATIONVALUES_PROCESS = void 0; + const utils_1 = /* @__PURE__ */ requireUtils$f(); + const TMP_AWS_LAMBDA_INVOKED_ARN = "aws.lambda.invoked_arn"; + const TMP_DB_SYSTEM = "db.system"; + const TMP_DB_CONNECTION_STRING = "db.connection_string"; + const TMP_DB_USER = "db.user"; + const TMP_DB_JDBC_DRIVER_CLASSNAME = "db.jdbc.driver_classname"; + const TMP_DB_NAME = "db.name"; + const TMP_DB_STATEMENT = "db.statement"; + const TMP_DB_OPERATION = "db.operation"; + const TMP_DB_MSSQL_INSTANCE_NAME = "db.mssql.instance_name"; + const TMP_DB_CASSANDRA_KEYSPACE = "db.cassandra.keyspace"; + const TMP_DB_CASSANDRA_PAGE_SIZE = "db.cassandra.page_size"; + const TMP_DB_CASSANDRA_CONSISTENCY_LEVEL = "db.cassandra.consistency_level"; + const TMP_DB_CASSANDRA_TABLE = "db.cassandra.table"; + const TMP_DB_CASSANDRA_IDEMPOTENCE = "db.cassandra.idempotence"; + const TMP_DB_CASSANDRA_SPECULATIVE_EXECUTION_COUNT = "db.cassandra.speculative_execution_count"; + const TMP_DB_CASSANDRA_COORDINATOR_ID = "db.cassandra.coordinator.id"; + const TMP_DB_CASSANDRA_COORDINATOR_DC = "db.cassandra.coordinator.dc"; + const TMP_DB_HBASE_NAMESPACE = "db.hbase.namespace"; + const TMP_DB_REDIS_DATABASE_INDEX = "db.redis.database_index"; + const TMP_DB_MONGODB_COLLECTION = "db.mongodb.collection"; + const TMP_DB_SQL_TABLE = "db.sql.table"; + const TMP_EXCEPTION_TYPE = "exception.type"; + const TMP_EXCEPTION_MESSAGE = "exception.message"; + const TMP_EXCEPTION_STACKTRACE = "exception.stacktrace"; + const TMP_EXCEPTION_ESCAPED = "exception.escaped"; + const TMP_FAAS_TRIGGER = "faas.trigger"; + const TMP_FAAS_EXECUTION = "faas.execution"; + const TMP_FAAS_DOCUMENT_COLLECTION = "faas.document.collection"; + const TMP_FAAS_DOCUMENT_OPERATION = "faas.document.operation"; + const TMP_FAAS_DOCUMENT_TIME = "faas.document.time"; + const TMP_FAAS_DOCUMENT_NAME = "faas.document.name"; + const TMP_FAAS_TIME = "faas.time"; + const TMP_FAAS_CRON = "faas.cron"; + const TMP_FAAS_COLDSTART = "faas.coldstart"; + const TMP_FAAS_INVOKED_NAME = "faas.invoked_name"; + const TMP_FAAS_INVOKED_PROVIDER = "faas.invoked_provider"; + const TMP_FAAS_INVOKED_REGION = "faas.invoked_region"; + const TMP_NET_TRANSPORT = "net.transport"; + const TMP_NET_PEER_IP = "net.peer.ip"; + const TMP_NET_PEER_PORT = "net.peer.port"; + const TMP_NET_PEER_NAME = "net.peer.name"; + const TMP_NET_HOST_IP = "net.host.ip"; + const TMP_NET_HOST_PORT = "net.host.port"; + const TMP_NET_HOST_NAME = "net.host.name"; + const TMP_NET_HOST_CONNECTION_TYPE = "net.host.connection.type"; + const TMP_NET_HOST_CONNECTION_SUBTYPE = "net.host.connection.subtype"; + const TMP_NET_HOST_CARRIER_NAME = "net.host.carrier.name"; + const TMP_NET_HOST_CARRIER_MCC = "net.host.carrier.mcc"; + const TMP_NET_HOST_CARRIER_MNC = "net.host.carrier.mnc"; + const TMP_NET_HOST_CARRIER_ICC = "net.host.carrier.icc"; + const TMP_PEER_SERVICE = "peer.service"; + const TMP_ENDUSER_ID = "enduser.id"; + const TMP_ENDUSER_ROLE = "enduser.role"; + const TMP_ENDUSER_SCOPE = "enduser.scope"; + const TMP_THREAD_ID = "thread.id"; + const TMP_THREAD_NAME = "thread.name"; + const TMP_CODE_FUNCTION = "code.function"; + const TMP_CODE_NAMESPACE = "code.namespace"; + const TMP_CODE_FILEPATH = "code.filepath"; + const TMP_CODE_LINENO = "code.lineno"; + const TMP_HTTP_METHOD = "http.method"; + const TMP_HTTP_URL = "http.url"; + const TMP_HTTP_TARGET = "http.target"; + const TMP_HTTP_HOST = "http.host"; + const TMP_HTTP_SCHEME = "http.scheme"; + const TMP_HTTP_STATUS_CODE = "http.status_code"; + const TMP_HTTP_FLAVOR = "http.flavor"; + const TMP_HTTP_USER_AGENT = "http.user_agent"; + const TMP_HTTP_REQUEST_CONTENT_LENGTH = "http.request_content_length"; + const TMP_HTTP_REQUEST_CONTENT_LENGTH_UNCOMPRESSED = "http.request_content_length_uncompressed"; + const TMP_HTTP_RESPONSE_CONTENT_LENGTH = "http.response_content_length"; + const TMP_HTTP_RESPONSE_CONTENT_LENGTH_UNCOMPRESSED = "http.response_content_length_uncompressed"; + const TMP_HTTP_SERVER_NAME = "http.server_name"; + const TMP_HTTP_ROUTE = "http.route"; + const TMP_HTTP_CLIENT_IP = "http.client_ip"; + const TMP_AWS_DYNAMODB_TABLE_NAMES = "aws.dynamodb.table_names"; + const TMP_AWS_DYNAMODB_CONSUMED_CAPACITY = "aws.dynamodb.consumed_capacity"; + const TMP_AWS_DYNAMODB_ITEM_COLLECTION_METRICS = "aws.dynamodb.item_collection_metrics"; + const TMP_AWS_DYNAMODB_PROVISIONED_READ_CAPACITY = "aws.dynamodb.provisioned_read_capacity"; + const TMP_AWS_DYNAMODB_PROVISIONED_WRITE_CAPACITY = "aws.dynamodb.provisioned_write_capacity"; + const TMP_AWS_DYNAMODB_CONSISTENT_READ = "aws.dynamodb.consistent_read"; + const TMP_AWS_DYNAMODB_PROJECTION = "aws.dynamodb.projection"; + const TMP_AWS_DYNAMODB_LIMIT = "aws.dynamodb.limit"; + const TMP_AWS_DYNAMODB_ATTRIBUTES_TO_GET = "aws.dynamodb.attributes_to_get"; + const TMP_AWS_DYNAMODB_INDEX_NAME = "aws.dynamodb.index_name"; + const TMP_AWS_DYNAMODB_SELECT = "aws.dynamodb.select"; + const TMP_AWS_DYNAMODB_GLOBAL_SECONDARY_INDEXES = "aws.dynamodb.global_secondary_indexes"; + const TMP_AWS_DYNAMODB_LOCAL_SECONDARY_INDEXES = "aws.dynamodb.local_secondary_indexes"; + const TMP_AWS_DYNAMODB_EXCLUSIVE_START_TABLE = "aws.dynamodb.exclusive_start_table"; + const TMP_AWS_DYNAMODB_TABLE_COUNT = "aws.dynamodb.table_count"; + const TMP_AWS_DYNAMODB_SCAN_FORWARD = "aws.dynamodb.scan_forward"; + const TMP_AWS_DYNAMODB_SEGMENT = "aws.dynamodb.segment"; + const TMP_AWS_DYNAMODB_TOTAL_SEGMENTS = "aws.dynamodb.total_segments"; + const TMP_AWS_DYNAMODB_COUNT = "aws.dynamodb.count"; + const TMP_AWS_DYNAMODB_SCANNED_COUNT = "aws.dynamodb.scanned_count"; + const TMP_AWS_DYNAMODB_ATTRIBUTE_DEFINITIONS = "aws.dynamodb.attribute_definitions"; + const TMP_AWS_DYNAMODB_GLOBAL_SECONDARY_INDEX_UPDATES = "aws.dynamodb.global_secondary_index_updates"; + const TMP_MESSAGING_SYSTEM = "messaging.system"; + const TMP_MESSAGING_DESTINATION = "messaging.destination"; + const TMP_MESSAGING_DESTINATION_KIND = "messaging.destination_kind"; + const TMP_MESSAGING_TEMP_DESTINATION = "messaging.temp_destination"; + const TMP_MESSAGING_PROTOCOL = "messaging.protocol"; + const TMP_MESSAGING_PROTOCOL_VERSION = "messaging.protocol_version"; + const TMP_MESSAGING_URL = "messaging.url"; + const TMP_MESSAGING_MESSAGE_ID = "messaging.message_id"; + const TMP_MESSAGING_CONVERSATION_ID = "messaging.conversation_id"; + const TMP_MESSAGING_MESSAGE_PAYLOAD_SIZE_BYTES = "messaging.message_payload_size_bytes"; + const TMP_MESSAGING_MESSAGE_PAYLOAD_COMPRESSED_SIZE_BYTES = "messaging.message_payload_compressed_size_bytes"; + const TMP_MESSAGING_OPERATION = "messaging.operation"; + const TMP_MESSAGING_CONSUMER_ID = "messaging.consumer_id"; + const TMP_MESSAGING_RABBITMQ_ROUTING_KEY = "messaging.rabbitmq.routing_key"; + const TMP_MESSAGING_KAFKA_MESSAGE_KEY = "messaging.kafka.message_key"; + const TMP_MESSAGING_KAFKA_CONSUMER_GROUP = "messaging.kafka.consumer_group"; + const TMP_MESSAGING_KAFKA_CLIENT_ID = "messaging.kafka.client_id"; + const TMP_MESSAGING_KAFKA_PARTITION = "messaging.kafka.partition"; + const TMP_MESSAGING_KAFKA_TOMBSTONE = "messaging.kafka.tombstone"; + const TMP_RPC_SYSTEM = "rpc.system"; + const TMP_RPC_SERVICE = "rpc.service"; + const TMP_RPC_METHOD = "rpc.method"; + const TMP_RPC_GRPC_STATUS_CODE = "rpc.grpc.status_code"; + const TMP_RPC_JSONRPC_VERSION = "rpc.jsonrpc.version"; + const TMP_RPC_JSONRPC_REQUEST_ID = "rpc.jsonrpc.request_id"; + const TMP_RPC_JSONRPC_ERROR_CODE = "rpc.jsonrpc.error_code"; + const TMP_RPC_JSONRPC_ERROR_MESSAGE = "rpc.jsonrpc.error_message"; + const TMP_MESSAGE_TYPE = "message.type"; + const TMP_MESSAGE_ID = "message.id"; + const TMP_MESSAGE_COMPRESSED_SIZE = "message.compressed_size"; + const TMP_MESSAGE_UNCOMPRESSED_SIZE = "message.uncompressed_size"; + SemanticAttributes.SEMATTRS_AWS_LAMBDA_INVOKED_ARN = TMP_AWS_LAMBDA_INVOKED_ARN; + SemanticAttributes.SEMATTRS_DB_SYSTEM = TMP_DB_SYSTEM; + SemanticAttributes.SEMATTRS_DB_CONNECTION_STRING = TMP_DB_CONNECTION_STRING; + SemanticAttributes.SEMATTRS_DB_USER = TMP_DB_USER; + SemanticAttributes.SEMATTRS_DB_JDBC_DRIVER_CLASSNAME = TMP_DB_JDBC_DRIVER_CLASSNAME; + SemanticAttributes.SEMATTRS_DB_NAME = TMP_DB_NAME; + SemanticAttributes.SEMATTRS_DB_STATEMENT = TMP_DB_STATEMENT; + SemanticAttributes.SEMATTRS_DB_OPERATION = TMP_DB_OPERATION; + SemanticAttributes.SEMATTRS_DB_MSSQL_INSTANCE_NAME = TMP_DB_MSSQL_INSTANCE_NAME; + SemanticAttributes.SEMATTRS_DB_CASSANDRA_KEYSPACE = TMP_DB_CASSANDRA_KEYSPACE; + SemanticAttributes.SEMATTRS_DB_CASSANDRA_PAGE_SIZE = TMP_DB_CASSANDRA_PAGE_SIZE; + SemanticAttributes.SEMATTRS_DB_CASSANDRA_CONSISTENCY_LEVEL = TMP_DB_CASSANDRA_CONSISTENCY_LEVEL; + SemanticAttributes.SEMATTRS_DB_CASSANDRA_TABLE = TMP_DB_CASSANDRA_TABLE; + SemanticAttributes.SEMATTRS_DB_CASSANDRA_IDEMPOTENCE = TMP_DB_CASSANDRA_IDEMPOTENCE; + SemanticAttributes.SEMATTRS_DB_CASSANDRA_SPECULATIVE_EXECUTION_COUNT = TMP_DB_CASSANDRA_SPECULATIVE_EXECUTION_COUNT; + SemanticAttributes.SEMATTRS_DB_CASSANDRA_COORDINATOR_ID = TMP_DB_CASSANDRA_COORDINATOR_ID; + SemanticAttributes.SEMATTRS_DB_CASSANDRA_COORDINATOR_DC = TMP_DB_CASSANDRA_COORDINATOR_DC; + SemanticAttributes.SEMATTRS_DB_HBASE_NAMESPACE = TMP_DB_HBASE_NAMESPACE; + SemanticAttributes.SEMATTRS_DB_REDIS_DATABASE_INDEX = TMP_DB_REDIS_DATABASE_INDEX; + SemanticAttributes.SEMATTRS_DB_MONGODB_COLLECTION = TMP_DB_MONGODB_COLLECTION; + SemanticAttributes.SEMATTRS_DB_SQL_TABLE = TMP_DB_SQL_TABLE; + SemanticAttributes.SEMATTRS_EXCEPTION_TYPE = TMP_EXCEPTION_TYPE; + SemanticAttributes.SEMATTRS_EXCEPTION_MESSAGE = TMP_EXCEPTION_MESSAGE; + SemanticAttributes.SEMATTRS_EXCEPTION_STACKTRACE = TMP_EXCEPTION_STACKTRACE; + SemanticAttributes.SEMATTRS_EXCEPTION_ESCAPED = TMP_EXCEPTION_ESCAPED; + SemanticAttributes.SEMATTRS_FAAS_TRIGGER = TMP_FAAS_TRIGGER; + SemanticAttributes.SEMATTRS_FAAS_EXECUTION = TMP_FAAS_EXECUTION; + SemanticAttributes.SEMATTRS_FAAS_DOCUMENT_COLLECTION = TMP_FAAS_DOCUMENT_COLLECTION; + SemanticAttributes.SEMATTRS_FAAS_DOCUMENT_OPERATION = TMP_FAAS_DOCUMENT_OPERATION; + SemanticAttributes.SEMATTRS_FAAS_DOCUMENT_TIME = TMP_FAAS_DOCUMENT_TIME; + SemanticAttributes.SEMATTRS_FAAS_DOCUMENT_NAME = TMP_FAAS_DOCUMENT_NAME; + SemanticAttributes.SEMATTRS_FAAS_TIME = TMP_FAAS_TIME; + SemanticAttributes.SEMATTRS_FAAS_CRON = TMP_FAAS_CRON; + SemanticAttributes.SEMATTRS_FAAS_COLDSTART = TMP_FAAS_COLDSTART; + SemanticAttributes.SEMATTRS_FAAS_INVOKED_NAME = TMP_FAAS_INVOKED_NAME; + SemanticAttributes.SEMATTRS_FAAS_INVOKED_PROVIDER = TMP_FAAS_INVOKED_PROVIDER; + SemanticAttributes.SEMATTRS_FAAS_INVOKED_REGION = TMP_FAAS_INVOKED_REGION; + SemanticAttributes.SEMATTRS_NET_TRANSPORT = TMP_NET_TRANSPORT; + SemanticAttributes.SEMATTRS_NET_PEER_IP = TMP_NET_PEER_IP; + SemanticAttributes.SEMATTRS_NET_PEER_PORT = TMP_NET_PEER_PORT; + SemanticAttributes.SEMATTRS_NET_PEER_NAME = TMP_NET_PEER_NAME; + SemanticAttributes.SEMATTRS_NET_HOST_IP = TMP_NET_HOST_IP; + SemanticAttributes.SEMATTRS_NET_HOST_PORT = TMP_NET_HOST_PORT; + SemanticAttributes.SEMATTRS_NET_HOST_NAME = TMP_NET_HOST_NAME; + SemanticAttributes.SEMATTRS_NET_HOST_CONNECTION_TYPE = TMP_NET_HOST_CONNECTION_TYPE; + SemanticAttributes.SEMATTRS_NET_HOST_CONNECTION_SUBTYPE = TMP_NET_HOST_CONNECTION_SUBTYPE; + SemanticAttributes.SEMATTRS_NET_HOST_CARRIER_NAME = TMP_NET_HOST_CARRIER_NAME; + SemanticAttributes.SEMATTRS_NET_HOST_CARRIER_MCC = TMP_NET_HOST_CARRIER_MCC; + SemanticAttributes.SEMATTRS_NET_HOST_CARRIER_MNC = TMP_NET_HOST_CARRIER_MNC; + SemanticAttributes.SEMATTRS_NET_HOST_CARRIER_ICC = TMP_NET_HOST_CARRIER_ICC; + SemanticAttributes.SEMATTRS_PEER_SERVICE = TMP_PEER_SERVICE; + SemanticAttributes.SEMATTRS_ENDUSER_ID = TMP_ENDUSER_ID; + SemanticAttributes.SEMATTRS_ENDUSER_ROLE = TMP_ENDUSER_ROLE; + SemanticAttributes.SEMATTRS_ENDUSER_SCOPE = TMP_ENDUSER_SCOPE; + SemanticAttributes.SEMATTRS_THREAD_ID = TMP_THREAD_ID; + SemanticAttributes.SEMATTRS_THREAD_NAME = TMP_THREAD_NAME; + SemanticAttributes.SEMATTRS_CODE_FUNCTION = TMP_CODE_FUNCTION; + SemanticAttributes.SEMATTRS_CODE_NAMESPACE = TMP_CODE_NAMESPACE; + SemanticAttributes.SEMATTRS_CODE_FILEPATH = TMP_CODE_FILEPATH; + SemanticAttributes.SEMATTRS_CODE_LINENO = TMP_CODE_LINENO; + SemanticAttributes.SEMATTRS_HTTP_METHOD = TMP_HTTP_METHOD; + SemanticAttributes.SEMATTRS_HTTP_URL = TMP_HTTP_URL; + SemanticAttributes.SEMATTRS_HTTP_TARGET = TMP_HTTP_TARGET; + SemanticAttributes.SEMATTRS_HTTP_HOST = TMP_HTTP_HOST; + SemanticAttributes.SEMATTRS_HTTP_SCHEME = TMP_HTTP_SCHEME; + SemanticAttributes.SEMATTRS_HTTP_STATUS_CODE = TMP_HTTP_STATUS_CODE; + SemanticAttributes.SEMATTRS_HTTP_FLAVOR = TMP_HTTP_FLAVOR; + SemanticAttributes.SEMATTRS_HTTP_USER_AGENT = TMP_HTTP_USER_AGENT; + SemanticAttributes.SEMATTRS_HTTP_REQUEST_CONTENT_LENGTH = TMP_HTTP_REQUEST_CONTENT_LENGTH; + SemanticAttributes.SEMATTRS_HTTP_REQUEST_CONTENT_LENGTH_UNCOMPRESSED = TMP_HTTP_REQUEST_CONTENT_LENGTH_UNCOMPRESSED; + SemanticAttributes.SEMATTRS_HTTP_RESPONSE_CONTENT_LENGTH = TMP_HTTP_RESPONSE_CONTENT_LENGTH; + SemanticAttributes.SEMATTRS_HTTP_RESPONSE_CONTENT_LENGTH_UNCOMPRESSED = TMP_HTTP_RESPONSE_CONTENT_LENGTH_UNCOMPRESSED; + SemanticAttributes.SEMATTRS_HTTP_SERVER_NAME = TMP_HTTP_SERVER_NAME; + SemanticAttributes.SEMATTRS_HTTP_ROUTE = TMP_HTTP_ROUTE; + SemanticAttributes.SEMATTRS_HTTP_CLIENT_IP = TMP_HTTP_CLIENT_IP; + SemanticAttributes.SEMATTRS_AWS_DYNAMODB_TABLE_NAMES = TMP_AWS_DYNAMODB_TABLE_NAMES; + SemanticAttributes.SEMATTRS_AWS_DYNAMODB_CONSUMED_CAPACITY = TMP_AWS_DYNAMODB_CONSUMED_CAPACITY; + SemanticAttributes.SEMATTRS_AWS_DYNAMODB_ITEM_COLLECTION_METRICS = TMP_AWS_DYNAMODB_ITEM_COLLECTION_METRICS; + SemanticAttributes.SEMATTRS_AWS_DYNAMODB_PROVISIONED_READ_CAPACITY = TMP_AWS_DYNAMODB_PROVISIONED_READ_CAPACITY; + SemanticAttributes.SEMATTRS_AWS_DYNAMODB_PROVISIONED_WRITE_CAPACITY = TMP_AWS_DYNAMODB_PROVISIONED_WRITE_CAPACITY; + SemanticAttributes.SEMATTRS_AWS_DYNAMODB_CONSISTENT_READ = TMP_AWS_DYNAMODB_CONSISTENT_READ; + SemanticAttributes.SEMATTRS_AWS_DYNAMODB_PROJECTION = TMP_AWS_DYNAMODB_PROJECTION; + SemanticAttributes.SEMATTRS_AWS_DYNAMODB_LIMIT = TMP_AWS_DYNAMODB_LIMIT; + SemanticAttributes.SEMATTRS_AWS_DYNAMODB_ATTRIBUTES_TO_GET = TMP_AWS_DYNAMODB_ATTRIBUTES_TO_GET; + SemanticAttributes.SEMATTRS_AWS_DYNAMODB_INDEX_NAME = TMP_AWS_DYNAMODB_INDEX_NAME; + SemanticAttributes.SEMATTRS_AWS_DYNAMODB_SELECT = TMP_AWS_DYNAMODB_SELECT; + SemanticAttributes.SEMATTRS_AWS_DYNAMODB_GLOBAL_SECONDARY_INDEXES = TMP_AWS_DYNAMODB_GLOBAL_SECONDARY_INDEXES; + SemanticAttributes.SEMATTRS_AWS_DYNAMODB_LOCAL_SECONDARY_INDEXES = TMP_AWS_DYNAMODB_LOCAL_SECONDARY_INDEXES; + SemanticAttributes.SEMATTRS_AWS_DYNAMODB_EXCLUSIVE_START_TABLE = TMP_AWS_DYNAMODB_EXCLUSIVE_START_TABLE; + SemanticAttributes.SEMATTRS_AWS_DYNAMODB_TABLE_COUNT = TMP_AWS_DYNAMODB_TABLE_COUNT; + SemanticAttributes.SEMATTRS_AWS_DYNAMODB_SCAN_FORWARD = TMP_AWS_DYNAMODB_SCAN_FORWARD; + SemanticAttributes.SEMATTRS_AWS_DYNAMODB_SEGMENT = TMP_AWS_DYNAMODB_SEGMENT; + SemanticAttributes.SEMATTRS_AWS_DYNAMODB_TOTAL_SEGMENTS = TMP_AWS_DYNAMODB_TOTAL_SEGMENTS; + SemanticAttributes.SEMATTRS_AWS_DYNAMODB_COUNT = TMP_AWS_DYNAMODB_COUNT; + SemanticAttributes.SEMATTRS_AWS_DYNAMODB_SCANNED_COUNT = TMP_AWS_DYNAMODB_SCANNED_COUNT; + SemanticAttributes.SEMATTRS_AWS_DYNAMODB_ATTRIBUTE_DEFINITIONS = TMP_AWS_DYNAMODB_ATTRIBUTE_DEFINITIONS; + SemanticAttributes.SEMATTRS_AWS_DYNAMODB_GLOBAL_SECONDARY_INDEX_UPDATES = TMP_AWS_DYNAMODB_GLOBAL_SECONDARY_INDEX_UPDATES; + SemanticAttributes.SEMATTRS_MESSAGING_SYSTEM = TMP_MESSAGING_SYSTEM; + SemanticAttributes.SEMATTRS_MESSAGING_DESTINATION = TMP_MESSAGING_DESTINATION; + SemanticAttributes.SEMATTRS_MESSAGING_DESTINATION_KIND = TMP_MESSAGING_DESTINATION_KIND; + SemanticAttributes.SEMATTRS_MESSAGING_TEMP_DESTINATION = TMP_MESSAGING_TEMP_DESTINATION; + SemanticAttributes.SEMATTRS_MESSAGING_PROTOCOL = TMP_MESSAGING_PROTOCOL; + SemanticAttributes.SEMATTRS_MESSAGING_PROTOCOL_VERSION = TMP_MESSAGING_PROTOCOL_VERSION; + SemanticAttributes.SEMATTRS_MESSAGING_URL = TMP_MESSAGING_URL; + SemanticAttributes.SEMATTRS_MESSAGING_MESSAGE_ID = TMP_MESSAGING_MESSAGE_ID; + SemanticAttributes.SEMATTRS_MESSAGING_CONVERSATION_ID = TMP_MESSAGING_CONVERSATION_ID; + SemanticAttributes.SEMATTRS_MESSAGING_MESSAGE_PAYLOAD_SIZE_BYTES = TMP_MESSAGING_MESSAGE_PAYLOAD_SIZE_BYTES; + SemanticAttributes.SEMATTRS_MESSAGING_MESSAGE_PAYLOAD_COMPRESSED_SIZE_BYTES = TMP_MESSAGING_MESSAGE_PAYLOAD_COMPRESSED_SIZE_BYTES; + SemanticAttributes.SEMATTRS_MESSAGING_OPERATION = TMP_MESSAGING_OPERATION; + SemanticAttributes.SEMATTRS_MESSAGING_CONSUMER_ID = TMP_MESSAGING_CONSUMER_ID; + SemanticAttributes.SEMATTRS_MESSAGING_RABBITMQ_ROUTING_KEY = TMP_MESSAGING_RABBITMQ_ROUTING_KEY; + SemanticAttributes.SEMATTRS_MESSAGING_KAFKA_MESSAGE_KEY = TMP_MESSAGING_KAFKA_MESSAGE_KEY; + SemanticAttributes.SEMATTRS_MESSAGING_KAFKA_CONSUMER_GROUP = TMP_MESSAGING_KAFKA_CONSUMER_GROUP; + SemanticAttributes.SEMATTRS_MESSAGING_KAFKA_CLIENT_ID = TMP_MESSAGING_KAFKA_CLIENT_ID; + SemanticAttributes.SEMATTRS_MESSAGING_KAFKA_PARTITION = TMP_MESSAGING_KAFKA_PARTITION; + SemanticAttributes.SEMATTRS_MESSAGING_KAFKA_TOMBSTONE = TMP_MESSAGING_KAFKA_TOMBSTONE; + SemanticAttributes.SEMATTRS_RPC_SYSTEM = TMP_RPC_SYSTEM; + SemanticAttributes.SEMATTRS_RPC_SERVICE = TMP_RPC_SERVICE; + SemanticAttributes.SEMATTRS_RPC_METHOD = TMP_RPC_METHOD; + SemanticAttributes.SEMATTRS_RPC_GRPC_STATUS_CODE = TMP_RPC_GRPC_STATUS_CODE; + SemanticAttributes.SEMATTRS_RPC_JSONRPC_VERSION = TMP_RPC_JSONRPC_VERSION; + SemanticAttributes.SEMATTRS_RPC_JSONRPC_REQUEST_ID = TMP_RPC_JSONRPC_REQUEST_ID; + SemanticAttributes.SEMATTRS_RPC_JSONRPC_ERROR_CODE = TMP_RPC_JSONRPC_ERROR_CODE; + SemanticAttributes.SEMATTRS_RPC_JSONRPC_ERROR_MESSAGE = TMP_RPC_JSONRPC_ERROR_MESSAGE; + SemanticAttributes.SEMATTRS_MESSAGE_TYPE = TMP_MESSAGE_TYPE; + SemanticAttributes.SEMATTRS_MESSAGE_ID = TMP_MESSAGE_ID; + SemanticAttributes.SEMATTRS_MESSAGE_COMPRESSED_SIZE = TMP_MESSAGE_COMPRESSED_SIZE; + SemanticAttributes.SEMATTRS_MESSAGE_UNCOMPRESSED_SIZE = TMP_MESSAGE_UNCOMPRESSED_SIZE; + SemanticAttributes.SemanticAttributes = /* @__PURE__ */ (0, utils_1.createConstMap)([ + TMP_AWS_LAMBDA_INVOKED_ARN, + TMP_DB_SYSTEM, + TMP_DB_CONNECTION_STRING, + TMP_DB_USER, + TMP_DB_JDBC_DRIVER_CLASSNAME, + TMP_DB_NAME, + TMP_DB_STATEMENT, + TMP_DB_OPERATION, + TMP_DB_MSSQL_INSTANCE_NAME, + TMP_DB_CASSANDRA_KEYSPACE, + TMP_DB_CASSANDRA_PAGE_SIZE, + TMP_DB_CASSANDRA_CONSISTENCY_LEVEL, + TMP_DB_CASSANDRA_TABLE, + TMP_DB_CASSANDRA_IDEMPOTENCE, + TMP_DB_CASSANDRA_SPECULATIVE_EXECUTION_COUNT, + TMP_DB_CASSANDRA_COORDINATOR_ID, + TMP_DB_CASSANDRA_COORDINATOR_DC, + TMP_DB_HBASE_NAMESPACE, + TMP_DB_REDIS_DATABASE_INDEX, + TMP_DB_MONGODB_COLLECTION, + TMP_DB_SQL_TABLE, + TMP_EXCEPTION_TYPE, + TMP_EXCEPTION_MESSAGE, + TMP_EXCEPTION_STACKTRACE, + TMP_EXCEPTION_ESCAPED, + TMP_FAAS_TRIGGER, + TMP_FAAS_EXECUTION, + TMP_FAAS_DOCUMENT_COLLECTION, + TMP_FAAS_DOCUMENT_OPERATION, + TMP_FAAS_DOCUMENT_TIME, + TMP_FAAS_DOCUMENT_NAME, + TMP_FAAS_TIME, + TMP_FAAS_CRON, + TMP_FAAS_COLDSTART, + TMP_FAAS_INVOKED_NAME, + TMP_FAAS_INVOKED_PROVIDER, + TMP_FAAS_INVOKED_REGION, + TMP_NET_TRANSPORT, + TMP_NET_PEER_IP, + TMP_NET_PEER_PORT, + TMP_NET_PEER_NAME, + TMP_NET_HOST_IP, + TMP_NET_HOST_PORT, + TMP_NET_HOST_NAME, + TMP_NET_HOST_CONNECTION_TYPE, + TMP_NET_HOST_CONNECTION_SUBTYPE, + TMP_NET_HOST_CARRIER_NAME, + TMP_NET_HOST_CARRIER_MCC, + TMP_NET_HOST_CARRIER_MNC, + TMP_NET_HOST_CARRIER_ICC, + TMP_PEER_SERVICE, + TMP_ENDUSER_ID, + TMP_ENDUSER_ROLE, + TMP_ENDUSER_SCOPE, + TMP_THREAD_ID, + TMP_THREAD_NAME, + TMP_CODE_FUNCTION, + TMP_CODE_NAMESPACE, + TMP_CODE_FILEPATH, + TMP_CODE_LINENO, + TMP_HTTP_METHOD, + TMP_HTTP_URL, + TMP_HTTP_TARGET, + TMP_HTTP_HOST, + TMP_HTTP_SCHEME, + TMP_HTTP_STATUS_CODE, + TMP_HTTP_FLAVOR, + TMP_HTTP_USER_AGENT, + TMP_HTTP_REQUEST_CONTENT_LENGTH, + TMP_HTTP_REQUEST_CONTENT_LENGTH_UNCOMPRESSED, + TMP_HTTP_RESPONSE_CONTENT_LENGTH, + TMP_HTTP_RESPONSE_CONTENT_LENGTH_UNCOMPRESSED, + TMP_HTTP_SERVER_NAME, + TMP_HTTP_ROUTE, + TMP_HTTP_CLIENT_IP, + TMP_AWS_DYNAMODB_TABLE_NAMES, + TMP_AWS_DYNAMODB_CONSUMED_CAPACITY, + TMP_AWS_DYNAMODB_ITEM_COLLECTION_METRICS, + TMP_AWS_DYNAMODB_PROVISIONED_READ_CAPACITY, + TMP_AWS_DYNAMODB_PROVISIONED_WRITE_CAPACITY, + TMP_AWS_DYNAMODB_CONSISTENT_READ, + TMP_AWS_DYNAMODB_PROJECTION, + TMP_AWS_DYNAMODB_LIMIT, + TMP_AWS_DYNAMODB_ATTRIBUTES_TO_GET, + TMP_AWS_DYNAMODB_INDEX_NAME, + TMP_AWS_DYNAMODB_SELECT, + TMP_AWS_DYNAMODB_GLOBAL_SECONDARY_INDEXES, + TMP_AWS_DYNAMODB_LOCAL_SECONDARY_INDEXES, + TMP_AWS_DYNAMODB_EXCLUSIVE_START_TABLE, + TMP_AWS_DYNAMODB_TABLE_COUNT, + TMP_AWS_DYNAMODB_SCAN_FORWARD, + TMP_AWS_DYNAMODB_SEGMENT, + TMP_AWS_DYNAMODB_TOTAL_SEGMENTS, + TMP_AWS_DYNAMODB_COUNT, + TMP_AWS_DYNAMODB_SCANNED_COUNT, + TMP_AWS_DYNAMODB_ATTRIBUTE_DEFINITIONS, + TMP_AWS_DYNAMODB_GLOBAL_SECONDARY_INDEX_UPDATES, + TMP_MESSAGING_SYSTEM, + TMP_MESSAGING_DESTINATION, + TMP_MESSAGING_DESTINATION_KIND, + TMP_MESSAGING_TEMP_DESTINATION, + TMP_MESSAGING_PROTOCOL, + TMP_MESSAGING_PROTOCOL_VERSION, + TMP_MESSAGING_URL, + TMP_MESSAGING_MESSAGE_ID, + TMP_MESSAGING_CONVERSATION_ID, + TMP_MESSAGING_MESSAGE_PAYLOAD_SIZE_BYTES, + TMP_MESSAGING_MESSAGE_PAYLOAD_COMPRESSED_SIZE_BYTES, + TMP_MESSAGING_OPERATION, + TMP_MESSAGING_CONSUMER_ID, + TMP_MESSAGING_RABBITMQ_ROUTING_KEY, + TMP_MESSAGING_KAFKA_MESSAGE_KEY, + TMP_MESSAGING_KAFKA_CONSUMER_GROUP, + TMP_MESSAGING_KAFKA_CLIENT_ID, + TMP_MESSAGING_KAFKA_PARTITION, + TMP_MESSAGING_KAFKA_TOMBSTONE, + TMP_RPC_SYSTEM, + TMP_RPC_SERVICE, + TMP_RPC_METHOD, + TMP_RPC_GRPC_STATUS_CODE, + TMP_RPC_JSONRPC_VERSION, + TMP_RPC_JSONRPC_REQUEST_ID, + TMP_RPC_JSONRPC_ERROR_CODE, + TMP_RPC_JSONRPC_ERROR_MESSAGE, + TMP_MESSAGE_TYPE, + TMP_MESSAGE_ID, + TMP_MESSAGE_COMPRESSED_SIZE, + TMP_MESSAGE_UNCOMPRESSED_SIZE + ]); + const TMP_DBSYSTEMVALUES_OTHER_SQL = "other_sql"; + const TMP_DBSYSTEMVALUES_MSSQL = "mssql"; + const TMP_DBSYSTEMVALUES_MYSQL = "mysql"; + const TMP_DBSYSTEMVALUES_ORACLE = "oracle"; + const TMP_DBSYSTEMVALUES_DB2 = "db2"; + const TMP_DBSYSTEMVALUES_POSTGRESQL = "postgresql"; + const TMP_DBSYSTEMVALUES_REDSHIFT = "redshift"; + const TMP_DBSYSTEMVALUES_HIVE = "hive"; + const TMP_DBSYSTEMVALUES_CLOUDSCAPE = "cloudscape"; + const TMP_DBSYSTEMVALUES_HSQLDB = "hsqldb"; + const TMP_DBSYSTEMVALUES_PROGRESS = "progress"; + const TMP_DBSYSTEMVALUES_MAXDB = "maxdb"; + const TMP_DBSYSTEMVALUES_HANADB = "hanadb"; + const TMP_DBSYSTEMVALUES_INGRES = "ingres"; + const TMP_DBSYSTEMVALUES_FIRSTSQL = "firstsql"; + const TMP_DBSYSTEMVALUES_EDB = "edb"; + const TMP_DBSYSTEMVALUES_CACHE = "cache"; + const TMP_DBSYSTEMVALUES_ADABAS = "adabas"; + const TMP_DBSYSTEMVALUES_FIREBIRD = "firebird"; + const TMP_DBSYSTEMVALUES_DERBY = "derby"; + const TMP_DBSYSTEMVALUES_FILEMAKER = "filemaker"; + const TMP_DBSYSTEMVALUES_INFORMIX = "informix"; + const TMP_DBSYSTEMVALUES_INSTANTDB = "instantdb"; + const TMP_DBSYSTEMVALUES_INTERBASE = "interbase"; + const TMP_DBSYSTEMVALUES_MARIADB = "mariadb"; + const TMP_DBSYSTEMVALUES_NETEZZA = "netezza"; + const TMP_DBSYSTEMVALUES_PERVASIVE = "pervasive"; + const TMP_DBSYSTEMVALUES_POINTBASE = "pointbase"; + const TMP_DBSYSTEMVALUES_SQLITE = "sqlite"; + const TMP_DBSYSTEMVALUES_SYBASE = "sybase"; + const TMP_DBSYSTEMVALUES_TERADATA = "teradata"; + const TMP_DBSYSTEMVALUES_VERTICA = "vertica"; + const TMP_DBSYSTEMVALUES_H2 = "h2"; + const TMP_DBSYSTEMVALUES_COLDFUSION = "coldfusion"; + const TMP_DBSYSTEMVALUES_CASSANDRA = "cassandra"; + const TMP_DBSYSTEMVALUES_HBASE = "hbase"; + const TMP_DBSYSTEMVALUES_MONGODB = "mongodb"; + const TMP_DBSYSTEMVALUES_REDIS = "redis"; + const TMP_DBSYSTEMVALUES_COUCHBASE = "couchbase"; + const TMP_DBSYSTEMVALUES_COUCHDB = "couchdb"; + const TMP_DBSYSTEMVALUES_COSMOSDB = "cosmosdb"; + const TMP_DBSYSTEMVALUES_DYNAMODB = "dynamodb"; + const TMP_DBSYSTEMVALUES_NEO4J = "neo4j"; + const TMP_DBSYSTEMVALUES_GEODE = "geode"; + const TMP_DBSYSTEMVALUES_ELASTICSEARCH = "elasticsearch"; + const TMP_DBSYSTEMVALUES_MEMCACHED = "memcached"; + const TMP_DBSYSTEMVALUES_COCKROACHDB = "cockroachdb"; + SemanticAttributes.DBSYSTEMVALUES_OTHER_SQL = TMP_DBSYSTEMVALUES_OTHER_SQL; + SemanticAttributes.DBSYSTEMVALUES_MSSQL = TMP_DBSYSTEMVALUES_MSSQL; + SemanticAttributes.DBSYSTEMVALUES_MYSQL = TMP_DBSYSTEMVALUES_MYSQL; + SemanticAttributes.DBSYSTEMVALUES_ORACLE = TMP_DBSYSTEMVALUES_ORACLE; + SemanticAttributes.DBSYSTEMVALUES_DB2 = TMP_DBSYSTEMVALUES_DB2; + SemanticAttributes.DBSYSTEMVALUES_POSTGRESQL = TMP_DBSYSTEMVALUES_POSTGRESQL; + SemanticAttributes.DBSYSTEMVALUES_REDSHIFT = TMP_DBSYSTEMVALUES_REDSHIFT; + SemanticAttributes.DBSYSTEMVALUES_HIVE = TMP_DBSYSTEMVALUES_HIVE; + SemanticAttributes.DBSYSTEMVALUES_CLOUDSCAPE = TMP_DBSYSTEMVALUES_CLOUDSCAPE; + SemanticAttributes.DBSYSTEMVALUES_HSQLDB = TMP_DBSYSTEMVALUES_HSQLDB; + SemanticAttributes.DBSYSTEMVALUES_PROGRESS = TMP_DBSYSTEMVALUES_PROGRESS; + SemanticAttributes.DBSYSTEMVALUES_MAXDB = TMP_DBSYSTEMVALUES_MAXDB; + SemanticAttributes.DBSYSTEMVALUES_HANADB = TMP_DBSYSTEMVALUES_HANADB; + SemanticAttributes.DBSYSTEMVALUES_INGRES = TMP_DBSYSTEMVALUES_INGRES; + SemanticAttributes.DBSYSTEMVALUES_FIRSTSQL = TMP_DBSYSTEMVALUES_FIRSTSQL; + SemanticAttributes.DBSYSTEMVALUES_EDB = TMP_DBSYSTEMVALUES_EDB; + SemanticAttributes.DBSYSTEMVALUES_CACHE = TMP_DBSYSTEMVALUES_CACHE; + SemanticAttributes.DBSYSTEMVALUES_ADABAS = TMP_DBSYSTEMVALUES_ADABAS; + SemanticAttributes.DBSYSTEMVALUES_FIREBIRD = TMP_DBSYSTEMVALUES_FIREBIRD; + SemanticAttributes.DBSYSTEMVALUES_DERBY = TMP_DBSYSTEMVALUES_DERBY; + SemanticAttributes.DBSYSTEMVALUES_FILEMAKER = TMP_DBSYSTEMVALUES_FILEMAKER; + SemanticAttributes.DBSYSTEMVALUES_INFORMIX = TMP_DBSYSTEMVALUES_INFORMIX; + SemanticAttributes.DBSYSTEMVALUES_INSTANTDB = TMP_DBSYSTEMVALUES_INSTANTDB; + SemanticAttributes.DBSYSTEMVALUES_INTERBASE = TMP_DBSYSTEMVALUES_INTERBASE; + SemanticAttributes.DBSYSTEMVALUES_MARIADB = TMP_DBSYSTEMVALUES_MARIADB; + SemanticAttributes.DBSYSTEMVALUES_NETEZZA = TMP_DBSYSTEMVALUES_NETEZZA; + SemanticAttributes.DBSYSTEMVALUES_PERVASIVE = TMP_DBSYSTEMVALUES_PERVASIVE; + SemanticAttributes.DBSYSTEMVALUES_POINTBASE = TMP_DBSYSTEMVALUES_POINTBASE; + SemanticAttributes.DBSYSTEMVALUES_SQLITE = TMP_DBSYSTEMVALUES_SQLITE; + SemanticAttributes.DBSYSTEMVALUES_SYBASE = TMP_DBSYSTEMVALUES_SYBASE; + SemanticAttributes.DBSYSTEMVALUES_TERADATA = TMP_DBSYSTEMVALUES_TERADATA; + SemanticAttributes.DBSYSTEMVALUES_VERTICA = TMP_DBSYSTEMVALUES_VERTICA; + SemanticAttributes.DBSYSTEMVALUES_H2 = TMP_DBSYSTEMVALUES_H2; + SemanticAttributes.DBSYSTEMVALUES_COLDFUSION = TMP_DBSYSTEMVALUES_COLDFUSION; + SemanticAttributes.DBSYSTEMVALUES_CASSANDRA = TMP_DBSYSTEMVALUES_CASSANDRA; + SemanticAttributes.DBSYSTEMVALUES_HBASE = TMP_DBSYSTEMVALUES_HBASE; + SemanticAttributes.DBSYSTEMVALUES_MONGODB = TMP_DBSYSTEMVALUES_MONGODB; + SemanticAttributes.DBSYSTEMVALUES_REDIS = TMP_DBSYSTEMVALUES_REDIS; + SemanticAttributes.DBSYSTEMVALUES_COUCHBASE = TMP_DBSYSTEMVALUES_COUCHBASE; + SemanticAttributes.DBSYSTEMVALUES_COUCHDB = TMP_DBSYSTEMVALUES_COUCHDB; + SemanticAttributes.DBSYSTEMVALUES_COSMOSDB = TMP_DBSYSTEMVALUES_COSMOSDB; + SemanticAttributes.DBSYSTEMVALUES_DYNAMODB = TMP_DBSYSTEMVALUES_DYNAMODB; + SemanticAttributes.DBSYSTEMVALUES_NEO4J = TMP_DBSYSTEMVALUES_NEO4J; + SemanticAttributes.DBSYSTEMVALUES_GEODE = TMP_DBSYSTEMVALUES_GEODE; + SemanticAttributes.DBSYSTEMVALUES_ELASTICSEARCH = TMP_DBSYSTEMVALUES_ELASTICSEARCH; + SemanticAttributes.DBSYSTEMVALUES_MEMCACHED = TMP_DBSYSTEMVALUES_MEMCACHED; + SemanticAttributes.DBSYSTEMVALUES_COCKROACHDB = TMP_DBSYSTEMVALUES_COCKROACHDB; + SemanticAttributes.DbSystemValues = /* @__PURE__ */ (0, utils_1.createConstMap)([ + TMP_DBSYSTEMVALUES_OTHER_SQL, + TMP_DBSYSTEMVALUES_MSSQL, + TMP_DBSYSTEMVALUES_MYSQL, + TMP_DBSYSTEMVALUES_ORACLE, + TMP_DBSYSTEMVALUES_DB2, + TMP_DBSYSTEMVALUES_POSTGRESQL, + TMP_DBSYSTEMVALUES_REDSHIFT, + TMP_DBSYSTEMVALUES_HIVE, + TMP_DBSYSTEMVALUES_CLOUDSCAPE, + TMP_DBSYSTEMVALUES_HSQLDB, + TMP_DBSYSTEMVALUES_PROGRESS, + TMP_DBSYSTEMVALUES_MAXDB, + TMP_DBSYSTEMVALUES_HANADB, + TMP_DBSYSTEMVALUES_INGRES, + TMP_DBSYSTEMVALUES_FIRSTSQL, + TMP_DBSYSTEMVALUES_EDB, + TMP_DBSYSTEMVALUES_CACHE, + TMP_DBSYSTEMVALUES_ADABAS, + TMP_DBSYSTEMVALUES_FIREBIRD, + TMP_DBSYSTEMVALUES_DERBY, + TMP_DBSYSTEMVALUES_FILEMAKER, + TMP_DBSYSTEMVALUES_INFORMIX, + TMP_DBSYSTEMVALUES_INSTANTDB, + TMP_DBSYSTEMVALUES_INTERBASE, + TMP_DBSYSTEMVALUES_MARIADB, + TMP_DBSYSTEMVALUES_NETEZZA, + TMP_DBSYSTEMVALUES_PERVASIVE, + TMP_DBSYSTEMVALUES_POINTBASE, + TMP_DBSYSTEMVALUES_SQLITE, + TMP_DBSYSTEMVALUES_SYBASE, + TMP_DBSYSTEMVALUES_TERADATA, + TMP_DBSYSTEMVALUES_VERTICA, + TMP_DBSYSTEMVALUES_H2, + TMP_DBSYSTEMVALUES_COLDFUSION, + TMP_DBSYSTEMVALUES_CASSANDRA, + TMP_DBSYSTEMVALUES_HBASE, + TMP_DBSYSTEMVALUES_MONGODB, + TMP_DBSYSTEMVALUES_REDIS, + TMP_DBSYSTEMVALUES_COUCHBASE, + TMP_DBSYSTEMVALUES_COUCHDB, + TMP_DBSYSTEMVALUES_COSMOSDB, + TMP_DBSYSTEMVALUES_DYNAMODB, + TMP_DBSYSTEMVALUES_NEO4J, + TMP_DBSYSTEMVALUES_GEODE, + TMP_DBSYSTEMVALUES_ELASTICSEARCH, + TMP_DBSYSTEMVALUES_MEMCACHED, + TMP_DBSYSTEMVALUES_COCKROACHDB + ]); + const TMP_DBCASSANDRACONSISTENCYLEVELVALUES_ALL = "all"; + const TMP_DBCASSANDRACONSISTENCYLEVELVALUES_EACH_QUORUM = "each_quorum"; + const TMP_DBCASSANDRACONSISTENCYLEVELVALUES_QUORUM = "quorum"; + const TMP_DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_QUORUM = "local_quorum"; + const TMP_DBCASSANDRACONSISTENCYLEVELVALUES_ONE = "one"; + const TMP_DBCASSANDRACONSISTENCYLEVELVALUES_TWO = "two"; + const TMP_DBCASSANDRACONSISTENCYLEVELVALUES_THREE = "three"; + const TMP_DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_ONE = "local_one"; + const TMP_DBCASSANDRACONSISTENCYLEVELVALUES_ANY = "any"; + const TMP_DBCASSANDRACONSISTENCYLEVELVALUES_SERIAL = "serial"; + const TMP_DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_SERIAL = "local_serial"; + SemanticAttributes.DBCASSANDRACONSISTENCYLEVELVALUES_ALL = TMP_DBCASSANDRACONSISTENCYLEVELVALUES_ALL; + SemanticAttributes.DBCASSANDRACONSISTENCYLEVELVALUES_EACH_QUORUM = TMP_DBCASSANDRACONSISTENCYLEVELVALUES_EACH_QUORUM; + SemanticAttributes.DBCASSANDRACONSISTENCYLEVELVALUES_QUORUM = TMP_DBCASSANDRACONSISTENCYLEVELVALUES_QUORUM; + SemanticAttributes.DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_QUORUM = TMP_DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_QUORUM; + SemanticAttributes.DBCASSANDRACONSISTENCYLEVELVALUES_ONE = TMP_DBCASSANDRACONSISTENCYLEVELVALUES_ONE; + SemanticAttributes.DBCASSANDRACONSISTENCYLEVELVALUES_TWO = TMP_DBCASSANDRACONSISTENCYLEVELVALUES_TWO; + SemanticAttributes.DBCASSANDRACONSISTENCYLEVELVALUES_THREE = TMP_DBCASSANDRACONSISTENCYLEVELVALUES_THREE; + SemanticAttributes.DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_ONE = TMP_DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_ONE; + SemanticAttributes.DBCASSANDRACONSISTENCYLEVELVALUES_ANY = TMP_DBCASSANDRACONSISTENCYLEVELVALUES_ANY; + SemanticAttributes.DBCASSANDRACONSISTENCYLEVELVALUES_SERIAL = TMP_DBCASSANDRACONSISTENCYLEVELVALUES_SERIAL; + SemanticAttributes.DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_SERIAL = TMP_DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_SERIAL; + SemanticAttributes.DbCassandraConsistencyLevelValues = /* @__PURE__ */ (0, utils_1.createConstMap)([ + TMP_DBCASSANDRACONSISTENCYLEVELVALUES_ALL, + TMP_DBCASSANDRACONSISTENCYLEVELVALUES_EACH_QUORUM, + TMP_DBCASSANDRACONSISTENCYLEVELVALUES_QUORUM, + TMP_DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_QUORUM, + TMP_DBCASSANDRACONSISTENCYLEVELVALUES_ONE, + TMP_DBCASSANDRACONSISTENCYLEVELVALUES_TWO, + TMP_DBCASSANDRACONSISTENCYLEVELVALUES_THREE, + TMP_DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_ONE, + TMP_DBCASSANDRACONSISTENCYLEVELVALUES_ANY, + TMP_DBCASSANDRACONSISTENCYLEVELVALUES_SERIAL, + TMP_DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_SERIAL + ]); + const TMP_FAASTRIGGERVALUES_DATASOURCE = "datasource"; + const TMP_FAASTRIGGERVALUES_HTTP = "http"; + const TMP_FAASTRIGGERVALUES_PUBSUB = "pubsub"; + const TMP_FAASTRIGGERVALUES_TIMER = "timer"; + const TMP_FAASTRIGGERVALUES_OTHER = "other"; + SemanticAttributes.FAASTRIGGERVALUES_DATASOURCE = TMP_FAASTRIGGERVALUES_DATASOURCE; + SemanticAttributes.FAASTRIGGERVALUES_HTTP = TMP_FAASTRIGGERVALUES_HTTP; + SemanticAttributes.FAASTRIGGERVALUES_PUBSUB = TMP_FAASTRIGGERVALUES_PUBSUB; + SemanticAttributes.FAASTRIGGERVALUES_TIMER = TMP_FAASTRIGGERVALUES_TIMER; + SemanticAttributes.FAASTRIGGERVALUES_OTHER = TMP_FAASTRIGGERVALUES_OTHER; + SemanticAttributes.FaasTriggerValues = /* @__PURE__ */ (0, utils_1.createConstMap)([ + TMP_FAASTRIGGERVALUES_DATASOURCE, + TMP_FAASTRIGGERVALUES_HTTP, + TMP_FAASTRIGGERVALUES_PUBSUB, + TMP_FAASTRIGGERVALUES_TIMER, + TMP_FAASTRIGGERVALUES_OTHER + ]); + const TMP_FAASDOCUMENTOPERATIONVALUES_INSERT = "insert"; + const TMP_FAASDOCUMENTOPERATIONVALUES_EDIT = "edit"; + const TMP_FAASDOCUMENTOPERATIONVALUES_DELETE = "delete"; + SemanticAttributes.FAASDOCUMENTOPERATIONVALUES_INSERT = TMP_FAASDOCUMENTOPERATIONVALUES_INSERT; + SemanticAttributes.FAASDOCUMENTOPERATIONVALUES_EDIT = TMP_FAASDOCUMENTOPERATIONVALUES_EDIT; + SemanticAttributes.FAASDOCUMENTOPERATIONVALUES_DELETE = TMP_FAASDOCUMENTOPERATIONVALUES_DELETE; + SemanticAttributes.FaasDocumentOperationValues = /* @__PURE__ */ (0, utils_1.createConstMap)([ + TMP_FAASDOCUMENTOPERATIONVALUES_INSERT, + TMP_FAASDOCUMENTOPERATIONVALUES_EDIT, + TMP_FAASDOCUMENTOPERATIONVALUES_DELETE + ]); + const TMP_FAASINVOKEDPROVIDERVALUES_ALIBABA_CLOUD = "alibaba_cloud"; + const TMP_FAASINVOKEDPROVIDERVALUES_AWS = "aws"; + const TMP_FAASINVOKEDPROVIDERVALUES_AZURE = "azure"; + const TMP_FAASINVOKEDPROVIDERVALUES_GCP = "gcp"; + SemanticAttributes.FAASINVOKEDPROVIDERVALUES_ALIBABA_CLOUD = TMP_FAASINVOKEDPROVIDERVALUES_ALIBABA_CLOUD; + SemanticAttributes.FAASINVOKEDPROVIDERVALUES_AWS = TMP_FAASINVOKEDPROVIDERVALUES_AWS; + SemanticAttributes.FAASINVOKEDPROVIDERVALUES_AZURE = TMP_FAASINVOKEDPROVIDERVALUES_AZURE; + SemanticAttributes.FAASINVOKEDPROVIDERVALUES_GCP = TMP_FAASINVOKEDPROVIDERVALUES_GCP; + SemanticAttributes.FaasInvokedProviderValues = /* @__PURE__ */ (0, utils_1.createConstMap)([ + TMP_FAASINVOKEDPROVIDERVALUES_ALIBABA_CLOUD, + TMP_FAASINVOKEDPROVIDERVALUES_AWS, + TMP_FAASINVOKEDPROVIDERVALUES_AZURE, + TMP_FAASINVOKEDPROVIDERVALUES_GCP + ]); + const TMP_NETTRANSPORTVALUES_IP_TCP = "ip_tcp"; + const TMP_NETTRANSPORTVALUES_IP_UDP = "ip_udp"; + const TMP_NETTRANSPORTVALUES_IP = "ip"; + const TMP_NETTRANSPORTVALUES_UNIX = "unix"; + const TMP_NETTRANSPORTVALUES_PIPE = "pipe"; + const TMP_NETTRANSPORTVALUES_INPROC = "inproc"; + const TMP_NETTRANSPORTVALUES_OTHER = "other"; + SemanticAttributes.NETTRANSPORTVALUES_IP_TCP = TMP_NETTRANSPORTVALUES_IP_TCP; + SemanticAttributes.NETTRANSPORTVALUES_IP_UDP = TMP_NETTRANSPORTVALUES_IP_UDP; + SemanticAttributes.NETTRANSPORTVALUES_IP = TMP_NETTRANSPORTVALUES_IP; + SemanticAttributes.NETTRANSPORTVALUES_UNIX = TMP_NETTRANSPORTVALUES_UNIX; + SemanticAttributes.NETTRANSPORTVALUES_PIPE = TMP_NETTRANSPORTVALUES_PIPE; + SemanticAttributes.NETTRANSPORTVALUES_INPROC = TMP_NETTRANSPORTVALUES_INPROC; + SemanticAttributes.NETTRANSPORTVALUES_OTHER = TMP_NETTRANSPORTVALUES_OTHER; + SemanticAttributes.NetTransportValues = /* @__PURE__ */ (0, utils_1.createConstMap)([ + TMP_NETTRANSPORTVALUES_IP_TCP, + TMP_NETTRANSPORTVALUES_IP_UDP, + TMP_NETTRANSPORTVALUES_IP, + TMP_NETTRANSPORTVALUES_UNIX, + TMP_NETTRANSPORTVALUES_PIPE, + TMP_NETTRANSPORTVALUES_INPROC, + TMP_NETTRANSPORTVALUES_OTHER + ]); + const TMP_NETHOSTCONNECTIONTYPEVALUES_WIFI = "wifi"; + const TMP_NETHOSTCONNECTIONTYPEVALUES_WIRED = "wired"; + const TMP_NETHOSTCONNECTIONTYPEVALUES_CELL = "cell"; + const TMP_NETHOSTCONNECTIONTYPEVALUES_UNAVAILABLE = "unavailable"; + const TMP_NETHOSTCONNECTIONTYPEVALUES_UNKNOWN = "unknown"; + SemanticAttributes.NETHOSTCONNECTIONTYPEVALUES_WIFI = TMP_NETHOSTCONNECTIONTYPEVALUES_WIFI; + SemanticAttributes.NETHOSTCONNECTIONTYPEVALUES_WIRED = TMP_NETHOSTCONNECTIONTYPEVALUES_WIRED; + SemanticAttributes.NETHOSTCONNECTIONTYPEVALUES_CELL = TMP_NETHOSTCONNECTIONTYPEVALUES_CELL; + SemanticAttributes.NETHOSTCONNECTIONTYPEVALUES_UNAVAILABLE = TMP_NETHOSTCONNECTIONTYPEVALUES_UNAVAILABLE; + SemanticAttributes.NETHOSTCONNECTIONTYPEVALUES_UNKNOWN = TMP_NETHOSTCONNECTIONTYPEVALUES_UNKNOWN; + SemanticAttributes.NetHostConnectionTypeValues = /* @__PURE__ */ (0, utils_1.createConstMap)([ + TMP_NETHOSTCONNECTIONTYPEVALUES_WIFI, + TMP_NETHOSTCONNECTIONTYPEVALUES_WIRED, + TMP_NETHOSTCONNECTIONTYPEVALUES_CELL, + TMP_NETHOSTCONNECTIONTYPEVALUES_UNAVAILABLE, + TMP_NETHOSTCONNECTIONTYPEVALUES_UNKNOWN + ]); + const TMP_NETHOSTCONNECTIONSUBTYPEVALUES_GPRS = "gprs"; + const TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EDGE = "edge"; + const TMP_NETHOSTCONNECTIONSUBTYPEVALUES_UMTS = "umts"; + const TMP_NETHOSTCONNECTIONSUBTYPEVALUES_CDMA = "cdma"; + const TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_0 = "evdo_0"; + const TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_A = "evdo_a"; + const TMP_NETHOSTCONNECTIONSUBTYPEVALUES_CDMA2000_1XRTT = "cdma2000_1xrtt"; + const TMP_NETHOSTCONNECTIONSUBTYPEVALUES_HSDPA = "hsdpa"; + const TMP_NETHOSTCONNECTIONSUBTYPEVALUES_HSUPA = "hsupa"; + const TMP_NETHOSTCONNECTIONSUBTYPEVALUES_HSPA = "hspa"; + const TMP_NETHOSTCONNECTIONSUBTYPEVALUES_IDEN = "iden"; + const TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_B = "evdo_b"; + const TMP_NETHOSTCONNECTIONSUBTYPEVALUES_LTE = "lte"; + const TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EHRPD = "ehrpd"; + const TMP_NETHOSTCONNECTIONSUBTYPEVALUES_HSPAP = "hspap"; + const TMP_NETHOSTCONNECTIONSUBTYPEVALUES_GSM = "gsm"; + const TMP_NETHOSTCONNECTIONSUBTYPEVALUES_TD_SCDMA = "td_scdma"; + const TMP_NETHOSTCONNECTIONSUBTYPEVALUES_IWLAN = "iwlan"; + const TMP_NETHOSTCONNECTIONSUBTYPEVALUES_NR = "nr"; + const TMP_NETHOSTCONNECTIONSUBTYPEVALUES_NRNSA = "nrnsa"; + const TMP_NETHOSTCONNECTIONSUBTYPEVALUES_LTE_CA = "lte_ca"; + SemanticAttributes.NETHOSTCONNECTIONSUBTYPEVALUES_GPRS = TMP_NETHOSTCONNECTIONSUBTYPEVALUES_GPRS; + SemanticAttributes.NETHOSTCONNECTIONSUBTYPEVALUES_EDGE = TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EDGE; + SemanticAttributes.NETHOSTCONNECTIONSUBTYPEVALUES_UMTS = TMP_NETHOSTCONNECTIONSUBTYPEVALUES_UMTS; + SemanticAttributes.NETHOSTCONNECTIONSUBTYPEVALUES_CDMA = TMP_NETHOSTCONNECTIONSUBTYPEVALUES_CDMA; + SemanticAttributes.NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_0 = TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_0; + SemanticAttributes.NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_A = TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_A; + SemanticAttributes.NETHOSTCONNECTIONSUBTYPEVALUES_CDMA2000_1XRTT = TMP_NETHOSTCONNECTIONSUBTYPEVALUES_CDMA2000_1XRTT; + SemanticAttributes.NETHOSTCONNECTIONSUBTYPEVALUES_HSDPA = TMP_NETHOSTCONNECTIONSUBTYPEVALUES_HSDPA; + SemanticAttributes.NETHOSTCONNECTIONSUBTYPEVALUES_HSUPA = TMP_NETHOSTCONNECTIONSUBTYPEVALUES_HSUPA; + SemanticAttributes.NETHOSTCONNECTIONSUBTYPEVALUES_HSPA = TMP_NETHOSTCONNECTIONSUBTYPEVALUES_HSPA; + SemanticAttributes.NETHOSTCONNECTIONSUBTYPEVALUES_IDEN = TMP_NETHOSTCONNECTIONSUBTYPEVALUES_IDEN; + SemanticAttributes.NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_B = TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_B; + SemanticAttributes.NETHOSTCONNECTIONSUBTYPEVALUES_LTE = TMP_NETHOSTCONNECTIONSUBTYPEVALUES_LTE; + SemanticAttributes.NETHOSTCONNECTIONSUBTYPEVALUES_EHRPD = TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EHRPD; + SemanticAttributes.NETHOSTCONNECTIONSUBTYPEVALUES_HSPAP = TMP_NETHOSTCONNECTIONSUBTYPEVALUES_HSPAP; + SemanticAttributes.NETHOSTCONNECTIONSUBTYPEVALUES_GSM = TMP_NETHOSTCONNECTIONSUBTYPEVALUES_GSM; + SemanticAttributes.NETHOSTCONNECTIONSUBTYPEVALUES_TD_SCDMA = TMP_NETHOSTCONNECTIONSUBTYPEVALUES_TD_SCDMA; + SemanticAttributes.NETHOSTCONNECTIONSUBTYPEVALUES_IWLAN = TMP_NETHOSTCONNECTIONSUBTYPEVALUES_IWLAN; + SemanticAttributes.NETHOSTCONNECTIONSUBTYPEVALUES_NR = TMP_NETHOSTCONNECTIONSUBTYPEVALUES_NR; + SemanticAttributes.NETHOSTCONNECTIONSUBTYPEVALUES_NRNSA = TMP_NETHOSTCONNECTIONSUBTYPEVALUES_NRNSA; + SemanticAttributes.NETHOSTCONNECTIONSUBTYPEVALUES_LTE_CA = TMP_NETHOSTCONNECTIONSUBTYPEVALUES_LTE_CA; + SemanticAttributes.NetHostConnectionSubtypeValues = /* @__PURE__ */ (0, utils_1.createConstMap)([ + TMP_NETHOSTCONNECTIONSUBTYPEVALUES_GPRS, + TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EDGE, + TMP_NETHOSTCONNECTIONSUBTYPEVALUES_UMTS, + TMP_NETHOSTCONNECTIONSUBTYPEVALUES_CDMA, + TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_0, + TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_A, + TMP_NETHOSTCONNECTIONSUBTYPEVALUES_CDMA2000_1XRTT, + TMP_NETHOSTCONNECTIONSUBTYPEVALUES_HSDPA, + TMP_NETHOSTCONNECTIONSUBTYPEVALUES_HSUPA, + TMP_NETHOSTCONNECTIONSUBTYPEVALUES_HSPA, + TMP_NETHOSTCONNECTIONSUBTYPEVALUES_IDEN, + TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_B, + TMP_NETHOSTCONNECTIONSUBTYPEVALUES_LTE, + TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EHRPD, + TMP_NETHOSTCONNECTIONSUBTYPEVALUES_HSPAP, + TMP_NETHOSTCONNECTIONSUBTYPEVALUES_GSM, + TMP_NETHOSTCONNECTIONSUBTYPEVALUES_TD_SCDMA, + TMP_NETHOSTCONNECTIONSUBTYPEVALUES_IWLAN, + TMP_NETHOSTCONNECTIONSUBTYPEVALUES_NR, + TMP_NETHOSTCONNECTIONSUBTYPEVALUES_NRNSA, + TMP_NETHOSTCONNECTIONSUBTYPEVALUES_LTE_CA + ]); + const TMP_HTTPFLAVORVALUES_HTTP_1_0 = "1.0"; + const TMP_HTTPFLAVORVALUES_HTTP_1_1 = "1.1"; + const TMP_HTTPFLAVORVALUES_HTTP_2_0 = "2.0"; + const TMP_HTTPFLAVORVALUES_SPDY = "SPDY"; + const TMP_HTTPFLAVORVALUES_QUIC = "QUIC"; + SemanticAttributes.HTTPFLAVORVALUES_HTTP_1_0 = TMP_HTTPFLAVORVALUES_HTTP_1_0; + SemanticAttributes.HTTPFLAVORVALUES_HTTP_1_1 = TMP_HTTPFLAVORVALUES_HTTP_1_1; + SemanticAttributes.HTTPFLAVORVALUES_HTTP_2_0 = TMP_HTTPFLAVORVALUES_HTTP_2_0; + SemanticAttributes.HTTPFLAVORVALUES_SPDY = TMP_HTTPFLAVORVALUES_SPDY; + SemanticAttributes.HTTPFLAVORVALUES_QUIC = TMP_HTTPFLAVORVALUES_QUIC; + SemanticAttributes.HttpFlavorValues = { + HTTP_1_0: TMP_HTTPFLAVORVALUES_HTTP_1_0, + HTTP_1_1: TMP_HTTPFLAVORVALUES_HTTP_1_1, + HTTP_2_0: TMP_HTTPFLAVORVALUES_HTTP_2_0, + SPDY: TMP_HTTPFLAVORVALUES_SPDY, + QUIC: TMP_HTTPFLAVORVALUES_QUIC + }; + const TMP_MESSAGINGDESTINATIONKINDVALUES_QUEUE = "queue"; + const TMP_MESSAGINGDESTINATIONKINDVALUES_TOPIC = "topic"; + SemanticAttributes.MESSAGINGDESTINATIONKINDVALUES_QUEUE = TMP_MESSAGINGDESTINATIONKINDVALUES_QUEUE; + SemanticAttributes.MESSAGINGDESTINATIONKINDVALUES_TOPIC = TMP_MESSAGINGDESTINATIONKINDVALUES_TOPIC; + SemanticAttributes.MessagingDestinationKindValues = /* @__PURE__ */ (0, utils_1.createConstMap)([ + TMP_MESSAGINGDESTINATIONKINDVALUES_QUEUE, + TMP_MESSAGINGDESTINATIONKINDVALUES_TOPIC + ]); + const TMP_MESSAGINGOPERATIONVALUES_RECEIVE = "receive"; + const TMP_MESSAGINGOPERATIONVALUES_PROCESS = "process"; + SemanticAttributes.MESSAGINGOPERATIONVALUES_RECEIVE = TMP_MESSAGINGOPERATIONVALUES_RECEIVE; + SemanticAttributes.MESSAGINGOPERATIONVALUES_PROCESS = TMP_MESSAGINGOPERATIONVALUES_PROCESS; + SemanticAttributes.MessagingOperationValues = /* @__PURE__ */ (0, utils_1.createConstMap)([ + TMP_MESSAGINGOPERATIONVALUES_RECEIVE, + TMP_MESSAGINGOPERATIONVALUES_PROCESS + ]); + const TMP_RPCGRPCSTATUSCODEVALUES_OK = 0; + const TMP_RPCGRPCSTATUSCODEVALUES_CANCELLED = 1; + const TMP_RPCGRPCSTATUSCODEVALUES_UNKNOWN = 2; + const TMP_RPCGRPCSTATUSCODEVALUES_INVALID_ARGUMENT = 3; + const TMP_RPCGRPCSTATUSCODEVALUES_DEADLINE_EXCEEDED = 4; + const TMP_RPCGRPCSTATUSCODEVALUES_NOT_FOUND = 5; + const TMP_RPCGRPCSTATUSCODEVALUES_ALREADY_EXISTS = 6; + const TMP_RPCGRPCSTATUSCODEVALUES_PERMISSION_DENIED = 7; + const TMP_RPCGRPCSTATUSCODEVALUES_RESOURCE_EXHAUSTED = 8; + const TMP_RPCGRPCSTATUSCODEVALUES_FAILED_PRECONDITION = 9; + const TMP_RPCGRPCSTATUSCODEVALUES_ABORTED = 10; + const TMP_RPCGRPCSTATUSCODEVALUES_OUT_OF_RANGE = 11; + const TMP_RPCGRPCSTATUSCODEVALUES_UNIMPLEMENTED = 12; + const TMP_RPCGRPCSTATUSCODEVALUES_INTERNAL = 13; + const TMP_RPCGRPCSTATUSCODEVALUES_UNAVAILABLE = 14; + const TMP_RPCGRPCSTATUSCODEVALUES_DATA_LOSS = 15; + const TMP_RPCGRPCSTATUSCODEVALUES_UNAUTHENTICATED = 16; + SemanticAttributes.RPCGRPCSTATUSCODEVALUES_OK = TMP_RPCGRPCSTATUSCODEVALUES_OK; + SemanticAttributes.RPCGRPCSTATUSCODEVALUES_CANCELLED = TMP_RPCGRPCSTATUSCODEVALUES_CANCELLED; + SemanticAttributes.RPCGRPCSTATUSCODEVALUES_UNKNOWN = TMP_RPCGRPCSTATUSCODEVALUES_UNKNOWN; + SemanticAttributes.RPCGRPCSTATUSCODEVALUES_INVALID_ARGUMENT = TMP_RPCGRPCSTATUSCODEVALUES_INVALID_ARGUMENT; + SemanticAttributes.RPCGRPCSTATUSCODEVALUES_DEADLINE_EXCEEDED = TMP_RPCGRPCSTATUSCODEVALUES_DEADLINE_EXCEEDED; + SemanticAttributes.RPCGRPCSTATUSCODEVALUES_NOT_FOUND = TMP_RPCGRPCSTATUSCODEVALUES_NOT_FOUND; + SemanticAttributes.RPCGRPCSTATUSCODEVALUES_ALREADY_EXISTS = TMP_RPCGRPCSTATUSCODEVALUES_ALREADY_EXISTS; + SemanticAttributes.RPCGRPCSTATUSCODEVALUES_PERMISSION_DENIED = TMP_RPCGRPCSTATUSCODEVALUES_PERMISSION_DENIED; + SemanticAttributes.RPCGRPCSTATUSCODEVALUES_RESOURCE_EXHAUSTED = TMP_RPCGRPCSTATUSCODEVALUES_RESOURCE_EXHAUSTED; + SemanticAttributes.RPCGRPCSTATUSCODEVALUES_FAILED_PRECONDITION = TMP_RPCGRPCSTATUSCODEVALUES_FAILED_PRECONDITION; + SemanticAttributes.RPCGRPCSTATUSCODEVALUES_ABORTED = TMP_RPCGRPCSTATUSCODEVALUES_ABORTED; + SemanticAttributes.RPCGRPCSTATUSCODEVALUES_OUT_OF_RANGE = TMP_RPCGRPCSTATUSCODEVALUES_OUT_OF_RANGE; + SemanticAttributes.RPCGRPCSTATUSCODEVALUES_UNIMPLEMENTED = TMP_RPCGRPCSTATUSCODEVALUES_UNIMPLEMENTED; + SemanticAttributes.RPCGRPCSTATUSCODEVALUES_INTERNAL = TMP_RPCGRPCSTATUSCODEVALUES_INTERNAL; + SemanticAttributes.RPCGRPCSTATUSCODEVALUES_UNAVAILABLE = TMP_RPCGRPCSTATUSCODEVALUES_UNAVAILABLE; + SemanticAttributes.RPCGRPCSTATUSCODEVALUES_DATA_LOSS = TMP_RPCGRPCSTATUSCODEVALUES_DATA_LOSS; + SemanticAttributes.RPCGRPCSTATUSCODEVALUES_UNAUTHENTICATED = TMP_RPCGRPCSTATUSCODEVALUES_UNAUTHENTICATED; + SemanticAttributes.RpcGrpcStatusCodeValues = { + OK: TMP_RPCGRPCSTATUSCODEVALUES_OK, + CANCELLED: TMP_RPCGRPCSTATUSCODEVALUES_CANCELLED, + UNKNOWN: TMP_RPCGRPCSTATUSCODEVALUES_UNKNOWN, + INVALID_ARGUMENT: TMP_RPCGRPCSTATUSCODEVALUES_INVALID_ARGUMENT, + DEADLINE_EXCEEDED: TMP_RPCGRPCSTATUSCODEVALUES_DEADLINE_EXCEEDED, + NOT_FOUND: TMP_RPCGRPCSTATUSCODEVALUES_NOT_FOUND, + ALREADY_EXISTS: TMP_RPCGRPCSTATUSCODEVALUES_ALREADY_EXISTS, + PERMISSION_DENIED: TMP_RPCGRPCSTATUSCODEVALUES_PERMISSION_DENIED, + RESOURCE_EXHAUSTED: TMP_RPCGRPCSTATUSCODEVALUES_RESOURCE_EXHAUSTED, + FAILED_PRECONDITION: TMP_RPCGRPCSTATUSCODEVALUES_FAILED_PRECONDITION, + ABORTED: TMP_RPCGRPCSTATUSCODEVALUES_ABORTED, + OUT_OF_RANGE: TMP_RPCGRPCSTATUSCODEVALUES_OUT_OF_RANGE, + UNIMPLEMENTED: TMP_RPCGRPCSTATUSCODEVALUES_UNIMPLEMENTED, + INTERNAL: TMP_RPCGRPCSTATUSCODEVALUES_INTERNAL, + UNAVAILABLE: TMP_RPCGRPCSTATUSCODEVALUES_UNAVAILABLE, + DATA_LOSS: TMP_RPCGRPCSTATUSCODEVALUES_DATA_LOSS, + UNAUTHENTICATED: TMP_RPCGRPCSTATUSCODEVALUES_UNAUTHENTICATED + }; + const TMP_MESSAGETYPEVALUES_SENT = "SENT"; + const TMP_MESSAGETYPEVALUES_RECEIVED = "RECEIVED"; + SemanticAttributes.MESSAGETYPEVALUES_SENT = TMP_MESSAGETYPEVALUES_SENT; + SemanticAttributes.MESSAGETYPEVALUES_RECEIVED = TMP_MESSAGETYPEVALUES_RECEIVED; + SemanticAttributes.MessageTypeValues = /* @__PURE__ */ (0, utils_1.createConstMap)([ + TMP_MESSAGETYPEVALUES_SENT, + TMP_MESSAGETYPEVALUES_RECEIVED + ]); + return SemanticAttributes; +} +var hasRequiredTrace; +function requireTrace() { + if (hasRequiredTrace) return trace; + hasRequiredTrace = 1; + (function(exports$1) { + var __createBinding = trace && trace.__createBinding || (Object.create ? (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m[k]; + } }; + } + Object.defineProperty(o, k2, desc); + }) : (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + o[k2] = m[k]; + })); + var __exportStar = trace && trace.__exportStar || function(m, exports$12) { + for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports$12, p)) __createBinding(exports$12, m, p); + }; + Object.defineProperty(exports$1, "__esModule", { value: true }); + __exportStar(/* @__PURE__ */ requireSemanticAttributes(), exports$1); + })(trace); + return trace; +} +var resource = {}; +var SemanticResourceAttributes = {}; +var hasRequiredSemanticResourceAttributes; +function requireSemanticResourceAttributes() { + if (hasRequiredSemanticResourceAttributes) return SemanticResourceAttributes; + hasRequiredSemanticResourceAttributes = 1; + Object.defineProperty(SemanticResourceAttributes, "__esModule", { value: true }); + SemanticResourceAttributes.SEMRESATTRS_K8S_STATEFULSET_NAME = SemanticResourceAttributes.SEMRESATTRS_K8S_STATEFULSET_UID = SemanticResourceAttributes.SEMRESATTRS_K8S_DEPLOYMENT_NAME = SemanticResourceAttributes.SEMRESATTRS_K8S_DEPLOYMENT_UID = SemanticResourceAttributes.SEMRESATTRS_K8S_REPLICASET_NAME = SemanticResourceAttributes.SEMRESATTRS_K8S_REPLICASET_UID = SemanticResourceAttributes.SEMRESATTRS_K8S_CONTAINER_NAME = SemanticResourceAttributes.SEMRESATTRS_K8S_POD_NAME = SemanticResourceAttributes.SEMRESATTRS_K8S_POD_UID = SemanticResourceAttributes.SEMRESATTRS_K8S_NAMESPACE_NAME = SemanticResourceAttributes.SEMRESATTRS_K8S_NODE_UID = SemanticResourceAttributes.SEMRESATTRS_K8S_NODE_NAME = SemanticResourceAttributes.SEMRESATTRS_K8S_CLUSTER_NAME = SemanticResourceAttributes.SEMRESATTRS_HOST_IMAGE_VERSION = SemanticResourceAttributes.SEMRESATTRS_HOST_IMAGE_ID = SemanticResourceAttributes.SEMRESATTRS_HOST_IMAGE_NAME = SemanticResourceAttributes.SEMRESATTRS_HOST_ARCH = SemanticResourceAttributes.SEMRESATTRS_HOST_TYPE = SemanticResourceAttributes.SEMRESATTRS_HOST_NAME = SemanticResourceAttributes.SEMRESATTRS_HOST_ID = SemanticResourceAttributes.SEMRESATTRS_FAAS_MAX_MEMORY = SemanticResourceAttributes.SEMRESATTRS_FAAS_INSTANCE = SemanticResourceAttributes.SEMRESATTRS_FAAS_VERSION = SemanticResourceAttributes.SEMRESATTRS_FAAS_ID = SemanticResourceAttributes.SEMRESATTRS_FAAS_NAME = SemanticResourceAttributes.SEMRESATTRS_DEVICE_MODEL_NAME = SemanticResourceAttributes.SEMRESATTRS_DEVICE_MODEL_IDENTIFIER = SemanticResourceAttributes.SEMRESATTRS_DEVICE_ID = SemanticResourceAttributes.SEMRESATTRS_DEPLOYMENT_ENVIRONMENT = SemanticResourceAttributes.SEMRESATTRS_CONTAINER_IMAGE_TAG = SemanticResourceAttributes.SEMRESATTRS_CONTAINER_IMAGE_NAME = SemanticResourceAttributes.SEMRESATTRS_CONTAINER_RUNTIME = SemanticResourceAttributes.SEMRESATTRS_CONTAINER_ID = SemanticResourceAttributes.SEMRESATTRS_CONTAINER_NAME = SemanticResourceAttributes.SEMRESATTRS_AWS_LOG_STREAM_ARNS = SemanticResourceAttributes.SEMRESATTRS_AWS_LOG_STREAM_NAMES = SemanticResourceAttributes.SEMRESATTRS_AWS_LOG_GROUP_ARNS = SemanticResourceAttributes.SEMRESATTRS_AWS_LOG_GROUP_NAMES = SemanticResourceAttributes.SEMRESATTRS_AWS_EKS_CLUSTER_ARN = SemanticResourceAttributes.SEMRESATTRS_AWS_ECS_TASK_REVISION = SemanticResourceAttributes.SEMRESATTRS_AWS_ECS_TASK_FAMILY = SemanticResourceAttributes.SEMRESATTRS_AWS_ECS_TASK_ARN = SemanticResourceAttributes.SEMRESATTRS_AWS_ECS_LAUNCHTYPE = SemanticResourceAttributes.SEMRESATTRS_AWS_ECS_CLUSTER_ARN = SemanticResourceAttributes.SEMRESATTRS_AWS_ECS_CONTAINER_ARN = SemanticResourceAttributes.SEMRESATTRS_CLOUD_PLATFORM = SemanticResourceAttributes.SEMRESATTRS_CLOUD_AVAILABILITY_ZONE = SemanticResourceAttributes.SEMRESATTRS_CLOUD_REGION = SemanticResourceAttributes.SEMRESATTRS_CLOUD_ACCOUNT_ID = SemanticResourceAttributes.SEMRESATTRS_CLOUD_PROVIDER = void 0; + SemanticResourceAttributes.CLOUDPLATFORMVALUES_GCP_COMPUTE_ENGINE = SemanticResourceAttributes.CLOUDPLATFORMVALUES_AZURE_APP_SERVICE = SemanticResourceAttributes.CLOUDPLATFORMVALUES_AZURE_FUNCTIONS = SemanticResourceAttributes.CLOUDPLATFORMVALUES_AZURE_AKS = SemanticResourceAttributes.CLOUDPLATFORMVALUES_AZURE_CONTAINER_INSTANCES = SemanticResourceAttributes.CLOUDPLATFORMVALUES_AZURE_VM = SemanticResourceAttributes.CLOUDPLATFORMVALUES_AWS_ELASTIC_BEANSTALK = SemanticResourceAttributes.CLOUDPLATFORMVALUES_AWS_LAMBDA = SemanticResourceAttributes.CLOUDPLATFORMVALUES_AWS_EKS = SemanticResourceAttributes.CLOUDPLATFORMVALUES_AWS_ECS = SemanticResourceAttributes.CLOUDPLATFORMVALUES_AWS_EC2 = SemanticResourceAttributes.CLOUDPLATFORMVALUES_ALIBABA_CLOUD_FC = SemanticResourceAttributes.CLOUDPLATFORMVALUES_ALIBABA_CLOUD_ECS = SemanticResourceAttributes.CloudProviderValues = SemanticResourceAttributes.CLOUDPROVIDERVALUES_GCP = SemanticResourceAttributes.CLOUDPROVIDERVALUES_AZURE = SemanticResourceAttributes.CLOUDPROVIDERVALUES_AWS = SemanticResourceAttributes.CLOUDPROVIDERVALUES_ALIBABA_CLOUD = SemanticResourceAttributes.SemanticResourceAttributes = SemanticResourceAttributes.SEMRESATTRS_WEBENGINE_DESCRIPTION = SemanticResourceAttributes.SEMRESATTRS_WEBENGINE_VERSION = SemanticResourceAttributes.SEMRESATTRS_WEBENGINE_NAME = SemanticResourceAttributes.SEMRESATTRS_TELEMETRY_AUTO_VERSION = SemanticResourceAttributes.SEMRESATTRS_TELEMETRY_SDK_VERSION = SemanticResourceAttributes.SEMRESATTRS_TELEMETRY_SDK_LANGUAGE = SemanticResourceAttributes.SEMRESATTRS_TELEMETRY_SDK_NAME = SemanticResourceAttributes.SEMRESATTRS_SERVICE_VERSION = SemanticResourceAttributes.SEMRESATTRS_SERVICE_INSTANCE_ID = SemanticResourceAttributes.SEMRESATTRS_SERVICE_NAMESPACE = SemanticResourceAttributes.SEMRESATTRS_SERVICE_NAME = SemanticResourceAttributes.SEMRESATTRS_PROCESS_RUNTIME_DESCRIPTION = SemanticResourceAttributes.SEMRESATTRS_PROCESS_RUNTIME_VERSION = SemanticResourceAttributes.SEMRESATTRS_PROCESS_RUNTIME_NAME = SemanticResourceAttributes.SEMRESATTRS_PROCESS_OWNER = SemanticResourceAttributes.SEMRESATTRS_PROCESS_COMMAND_ARGS = SemanticResourceAttributes.SEMRESATTRS_PROCESS_COMMAND_LINE = SemanticResourceAttributes.SEMRESATTRS_PROCESS_COMMAND = SemanticResourceAttributes.SEMRESATTRS_PROCESS_EXECUTABLE_PATH = SemanticResourceAttributes.SEMRESATTRS_PROCESS_EXECUTABLE_NAME = SemanticResourceAttributes.SEMRESATTRS_PROCESS_PID = SemanticResourceAttributes.SEMRESATTRS_OS_VERSION = SemanticResourceAttributes.SEMRESATTRS_OS_NAME = SemanticResourceAttributes.SEMRESATTRS_OS_DESCRIPTION = SemanticResourceAttributes.SEMRESATTRS_OS_TYPE = SemanticResourceAttributes.SEMRESATTRS_K8S_CRONJOB_NAME = SemanticResourceAttributes.SEMRESATTRS_K8S_CRONJOB_UID = SemanticResourceAttributes.SEMRESATTRS_K8S_JOB_NAME = SemanticResourceAttributes.SEMRESATTRS_K8S_JOB_UID = SemanticResourceAttributes.SEMRESATTRS_K8S_DAEMONSET_NAME = SemanticResourceAttributes.SEMRESATTRS_K8S_DAEMONSET_UID = void 0; + SemanticResourceAttributes.TelemetrySdkLanguageValues = SemanticResourceAttributes.TELEMETRYSDKLANGUAGEVALUES_WEBJS = SemanticResourceAttributes.TELEMETRYSDKLANGUAGEVALUES_RUBY = SemanticResourceAttributes.TELEMETRYSDKLANGUAGEVALUES_PYTHON = SemanticResourceAttributes.TELEMETRYSDKLANGUAGEVALUES_PHP = SemanticResourceAttributes.TELEMETRYSDKLANGUAGEVALUES_NODEJS = SemanticResourceAttributes.TELEMETRYSDKLANGUAGEVALUES_JAVA = SemanticResourceAttributes.TELEMETRYSDKLANGUAGEVALUES_GO = SemanticResourceAttributes.TELEMETRYSDKLANGUAGEVALUES_ERLANG = SemanticResourceAttributes.TELEMETRYSDKLANGUAGEVALUES_DOTNET = SemanticResourceAttributes.TELEMETRYSDKLANGUAGEVALUES_CPP = SemanticResourceAttributes.OsTypeValues = SemanticResourceAttributes.OSTYPEVALUES_Z_OS = SemanticResourceAttributes.OSTYPEVALUES_SOLARIS = SemanticResourceAttributes.OSTYPEVALUES_AIX = SemanticResourceAttributes.OSTYPEVALUES_HPUX = SemanticResourceAttributes.OSTYPEVALUES_DRAGONFLYBSD = SemanticResourceAttributes.OSTYPEVALUES_OPENBSD = SemanticResourceAttributes.OSTYPEVALUES_NETBSD = SemanticResourceAttributes.OSTYPEVALUES_FREEBSD = SemanticResourceAttributes.OSTYPEVALUES_DARWIN = SemanticResourceAttributes.OSTYPEVALUES_LINUX = SemanticResourceAttributes.OSTYPEVALUES_WINDOWS = SemanticResourceAttributes.HostArchValues = SemanticResourceAttributes.HOSTARCHVALUES_X86 = SemanticResourceAttributes.HOSTARCHVALUES_PPC64 = SemanticResourceAttributes.HOSTARCHVALUES_PPC32 = SemanticResourceAttributes.HOSTARCHVALUES_IA64 = SemanticResourceAttributes.HOSTARCHVALUES_ARM64 = SemanticResourceAttributes.HOSTARCHVALUES_ARM32 = SemanticResourceAttributes.HOSTARCHVALUES_AMD64 = SemanticResourceAttributes.AwsEcsLaunchtypeValues = SemanticResourceAttributes.AWSECSLAUNCHTYPEVALUES_FARGATE = SemanticResourceAttributes.AWSECSLAUNCHTYPEVALUES_EC2 = SemanticResourceAttributes.CloudPlatformValues = SemanticResourceAttributes.CLOUDPLATFORMVALUES_GCP_APP_ENGINE = SemanticResourceAttributes.CLOUDPLATFORMVALUES_GCP_CLOUD_FUNCTIONS = SemanticResourceAttributes.CLOUDPLATFORMVALUES_GCP_KUBERNETES_ENGINE = SemanticResourceAttributes.CLOUDPLATFORMVALUES_GCP_CLOUD_RUN = void 0; + const utils_1 = /* @__PURE__ */ requireUtils$f(); + const TMP_CLOUD_PROVIDER = "cloud.provider"; + const TMP_CLOUD_ACCOUNT_ID = "cloud.account.id"; + const TMP_CLOUD_REGION = "cloud.region"; + const TMP_CLOUD_AVAILABILITY_ZONE = "cloud.availability_zone"; + const TMP_CLOUD_PLATFORM = "cloud.platform"; + const TMP_AWS_ECS_CONTAINER_ARN = "aws.ecs.container.arn"; + const TMP_AWS_ECS_CLUSTER_ARN = "aws.ecs.cluster.arn"; + const TMP_AWS_ECS_LAUNCHTYPE = "aws.ecs.launchtype"; + const TMP_AWS_ECS_TASK_ARN = "aws.ecs.task.arn"; + const TMP_AWS_ECS_TASK_FAMILY = "aws.ecs.task.family"; + const TMP_AWS_ECS_TASK_REVISION = "aws.ecs.task.revision"; + const TMP_AWS_EKS_CLUSTER_ARN = "aws.eks.cluster.arn"; + const TMP_AWS_LOG_GROUP_NAMES = "aws.log.group.names"; + const TMP_AWS_LOG_GROUP_ARNS = "aws.log.group.arns"; + const TMP_AWS_LOG_STREAM_NAMES = "aws.log.stream.names"; + const TMP_AWS_LOG_STREAM_ARNS = "aws.log.stream.arns"; + const TMP_CONTAINER_NAME = "container.name"; + const TMP_CONTAINER_ID = "container.id"; + const TMP_CONTAINER_RUNTIME = "container.runtime"; + const TMP_CONTAINER_IMAGE_NAME = "container.image.name"; + const TMP_CONTAINER_IMAGE_TAG = "container.image.tag"; + const TMP_DEPLOYMENT_ENVIRONMENT = "deployment.environment"; + const TMP_DEVICE_ID = "device.id"; + const TMP_DEVICE_MODEL_IDENTIFIER = "device.model.identifier"; + const TMP_DEVICE_MODEL_NAME = "device.model.name"; + const TMP_FAAS_NAME = "faas.name"; + const TMP_FAAS_ID = "faas.id"; + const TMP_FAAS_VERSION = "faas.version"; + const TMP_FAAS_INSTANCE = "faas.instance"; + const TMP_FAAS_MAX_MEMORY = "faas.max_memory"; + const TMP_HOST_ID = "host.id"; + const TMP_HOST_NAME = "host.name"; + const TMP_HOST_TYPE = "host.type"; + const TMP_HOST_ARCH = "host.arch"; + const TMP_HOST_IMAGE_NAME = "host.image.name"; + const TMP_HOST_IMAGE_ID = "host.image.id"; + const TMP_HOST_IMAGE_VERSION = "host.image.version"; + const TMP_K8S_CLUSTER_NAME = "k8s.cluster.name"; + const TMP_K8S_NODE_NAME = "k8s.node.name"; + const TMP_K8S_NODE_UID = "k8s.node.uid"; + const TMP_K8S_NAMESPACE_NAME = "k8s.namespace.name"; + const TMP_K8S_POD_UID = "k8s.pod.uid"; + const TMP_K8S_POD_NAME = "k8s.pod.name"; + const TMP_K8S_CONTAINER_NAME = "k8s.container.name"; + const TMP_K8S_REPLICASET_UID = "k8s.replicaset.uid"; + const TMP_K8S_REPLICASET_NAME = "k8s.replicaset.name"; + const TMP_K8S_DEPLOYMENT_UID = "k8s.deployment.uid"; + const TMP_K8S_DEPLOYMENT_NAME = "k8s.deployment.name"; + const TMP_K8S_STATEFULSET_UID = "k8s.statefulset.uid"; + const TMP_K8S_STATEFULSET_NAME = "k8s.statefulset.name"; + const TMP_K8S_DAEMONSET_UID = "k8s.daemonset.uid"; + const TMP_K8S_DAEMONSET_NAME = "k8s.daemonset.name"; + const TMP_K8S_JOB_UID = "k8s.job.uid"; + const TMP_K8S_JOB_NAME = "k8s.job.name"; + const TMP_K8S_CRONJOB_UID = "k8s.cronjob.uid"; + const TMP_K8S_CRONJOB_NAME = "k8s.cronjob.name"; + const TMP_OS_TYPE = "os.type"; + const TMP_OS_DESCRIPTION = "os.description"; + const TMP_OS_NAME = "os.name"; + const TMP_OS_VERSION = "os.version"; + const TMP_PROCESS_PID = "process.pid"; + const TMP_PROCESS_EXECUTABLE_NAME = "process.executable.name"; + const TMP_PROCESS_EXECUTABLE_PATH = "process.executable.path"; + const TMP_PROCESS_COMMAND = "process.command"; + const TMP_PROCESS_COMMAND_LINE = "process.command_line"; + const TMP_PROCESS_COMMAND_ARGS = "process.command_args"; + const TMP_PROCESS_OWNER = "process.owner"; + const TMP_PROCESS_RUNTIME_NAME = "process.runtime.name"; + const TMP_PROCESS_RUNTIME_VERSION = "process.runtime.version"; + const TMP_PROCESS_RUNTIME_DESCRIPTION = "process.runtime.description"; + const TMP_SERVICE_NAME = "service.name"; + const TMP_SERVICE_NAMESPACE = "service.namespace"; + const TMP_SERVICE_INSTANCE_ID = "service.instance.id"; + const TMP_SERVICE_VERSION = "service.version"; + const TMP_TELEMETRY_SDK_NAME = "telemetry.sdk.name"; + const TMP_TELEMETRY_SDK_LANGUAGE = "telemetry.sdk.language"; + const TMP_TELEMETRY_SDK_VERSION = "telemetry.sdk.version"; + const TMP_TELEMETRY_AUTO_VERSION = "telemetry.auto.version"; + const TMP_WEBENGINE_NAME = "webengine.name"; + const TMP_WEBENGINE_VERSION = "webengine.version"; + const TMP_WEBENGINE_DESCRIPTION = "webengine.description"; + SemanticResourceAttributes.SEMRESATTRS_CLOUD_PROVIDER = TMP_CLOUD_PROVIDER; + SemanticResourceAttributes.SEMRESATTRS_CLOUD_ACCOUNT_ID = TMP_CLOUD_ACCOUNT_ID; + SemanticResourceAttributes.SEMRESATTRS_CLOUD_REGION = TMP_CLOUD_REGION; + SemanticResourceAttributes.SEMRESATTRS_CLOUD_AVAILABILITY_ZONE = TMP_CLOUD_AVAILABILITY_ZONE; + SemanticResourceAttributes.SEMRESATTRS_CLOUD_PLATFORM = TMP_CLOUD_PLATFORM; + SemanticResourceAttributes.SEMRESATTRS_AWS_ECS_CONTAINER_ARN = TMP_AWS_ECS_CONTAINER_ARN; + SemanticResourceAttributes.SEMRESATTRS_AWS_ECS_CLUSTER_ARN = TMP_AWS_ECS_CLUSTER_ARN; + SemanticResourceAttributes.SEMRESATTRS_AWS_ECS_LAUNCHTYPE = TMP_AWS_ECS_LAUNCHTYPE; + SemanticResourceAttributes.SEMRESATTRS_AWS_ECS_TASK_ARN = TMP_AWS_ECS_TASK_ARN; + SemanticResourceAttributes.SEMRESATTRS_AWS_ECS_TASK_FAMILY = TMP_AWS_ECS_TASK_FAMILY; + SemanticResourceAttributes.SEMRESATTRS_AWS_ECS_TASK_REVISION = TMP_AWS_ECS_TASK_REVISION; + SemanticResourceAttributes.SEMRESATTRS_AWS_EKS_CLUSTER_ARN = TMP_AWS_EKS_CLUSTER_ARN; + SemanticResourceAttributes.SEMRESATTRS_AWS_LOG_GROUP_NAMES = TMP_AWS_LOG_GROUP_NAMES; + SemanticResourceAttributes.SEMRESATTRS_AWS_LOG_GROUP_ARNS = TMP_AWS_LOG_GROUP_ARNS; + SemanticResourceAttributes.SEMRESATTRS_AWS_LOG_STREAM_NAMES = TMP_AWS_LOG_STREAM_NAMES; + SemanticResourceAttributes.SEMRESATTRS_AWS_LOG_STREAM_ARNS = TMP_AWS_LOG_STREAM_ARNS; + SemanticResourceAttributes.SEMRESATTRS_CONTAINER_NAME = TMP_CONTAINER_NAME; + SemanticResourceAttributes.SEMRESATTRS_CONTAINER_ID = TMP_CONTAINER_ID; + SemanticResourceAttributes.SEMRESATTRS_CONTAINER_RUNTIME = TMP_CONTAINER_RUNTIME; + SemanticResourceAttributes.SEMRESATTRS_CONTAINER_IMAGE_NAME = TMP_CONTAINER_IMAGE_NAME; + SemanticResourceAttributes.SEMRESATTRS_CONTAINER_IMAGE_TAG = TMP_CONTAINER_IMAGE_TAG; + SemanticResourceAttributes.SEMRESATTRS_DEPLOYMENT_ENVIRONMENT = TMP_DEPLOYMENT_ENVIRONMENT; + SemanticResourceAttributes.SEMRESATTRS_DEVICE_ID = TMP_DEVICE_ID; + SemanticResourceAttributes.SEMRESATTRS_DEVICE_MODEL_IDENTIFIER = TMP_DEVICE_MODEL_IDENTIFIER; + SemanticResourceAttributes.SEMRESATTRS_DEVICE_MODEL_NAME = TMP_DEVICE_MODEL_NAME; + SemanticResourceAttributes.SEMRESATTRS_FAAS_NAME = TMP_FAAS_NAME; + SemanticResourceAttributes.SEMRESATTRS_FAAS_ID = TMP_FAAS_ID; + SemanticResourceAttributes.SEMRESATTRS_FAAS_VERSION = TMP_FAAS_VERSION; + SemanticResourceAttributes.SEMRESATTRS_FAAS_INSTANCE = TMP_FAAS_INSTANCE; + SemanticResourceAttributes.SEMRESATTRS_FAAS_MAX_MEMORY = TMP_FAAS_MAX_MEMORY; + SemanticResourceAttributes.SEMRESATTRS_HOST_ID = TMP_HOST_ID; + SemanticResourceAttributes.SEMRESATTRS_HOST_NAME = TMP_HOST_NAME; + SemanticResourceAttributes.SEMRESATTRS_HOST_TYPE = TMP_HOST_TYPE; + SemanticResourceAttributes.SEMRESATTRS_HOST_ARCH = TMP_HOST_ARCH; + SemanticResourceAttributes.SEMRESATTRS_HOST_IMAGE_NAME = TMP_HOST_IMAGE_NAME; + SemanticResourceAttributes.SEMRESATTRS_HOST_IMAGE_ID = TMP_HOST_IMAGE_ID; + SemanticResourceAttributes.SEMRESATTRS_HOST_IMAGE_VERSION = TMP_HOST_IMAGE_VERSION; + SemanticResourceAttributes.SEMRESATTRS_K8S_CLUSTER_NAME = TMP_K8S_CLUSTER_NAME; + SemanticResourceAttributes.SEMRESATTRS_K8S_NODE_NAME = TMP_K8S_NODE_NAME; + SemanticResourceAttributes.SEMRESATTRS_K8S_NODE_UID = TMP_K8S_NODE_UID; + SemanticResourceAttributes.SEMRESATTRS_K8S_NAMESPACE_NAME = TMP_K8S_NAMESPACE_NAME; + SemanticResourceAttributes.SEMRESATTRS_K8S_POD_UID = TMP_K8S_POD_UID; + SemanticResourceAttributes.SEMRESATTRS_K8S_POD_NAME = TMP_K8S_POD_NAME; + SemanticResourceAttributes.SEMRESATTRS_K8S_CONTAINER_NAME = TMP_K8S_CONTAINER_NAME; + SemanticResourceAttributes.SEMRESATTRS_K8S_REPLICASET_UID = TMP_K8S_REPLICASET_UID; + SemanticResourceAttributes.SEMRESATTRS_K8S_REPLICASET_NAME = TMP_K8S_REPLICASET_NAME; + SemanticResourceAttributes.SEMRESATTRS_K8S_DEPLOYMENT_UID = TMP_K8S_DEPLOYMENT_UID; + SemanticResourceAttributes.SEMRESATTRS_K8S_DEPLOYMENT_NAME = TMP_K8S_DEPLOYMENT_NAME; + SemanticResourceAttributes.SEMRESATTRS_K8S_STATEFULSET_UID = TMP_K8S_STATEFULSET_UID; + SemanticResourceAttributes.SEMRESATTRS_K8S_STATEFULSET_NAME = TMP_K8S_STATEFULSET_NAME; + SemanticResourceAttributes.SEMRESATTRS_K8S_DAEMONSET_UID = TMP_K8S_DAEMONSET_UID; + SemanticResourceAttributes.SEMRESATTRS_K8S_DAEMONSET_NAME = TMP_K8S_DAEMONSET_NAME; + SemanticResourceAttributes.SEMRESATTRS_K8S_JOB_UID = TMP_K8S_JOB_UID; + SemanticResourceAttributes.SEMRESATTRS_K8S_JOB_NAME = TMP_K8S_JOB_NAME; + SemanticResourceAttributes.SEMRESATTRS_K8S_CRONJOB_UID = TMP_K8S_CRONJOB_UID; + SemanticResourceAttributes.SEMRESATTRS_K8S_CRONJOB_NAME = TMP_K8S_CRONJOB_NAME; + SemanticResourceAttributes.SEMRESATTRS_OS_TYPE = TMP_OS_TYPE; + SemanticResourceAttributes.SEMRESATTRS_OS_DESCRIPTION = TMP_OS_DESCRIPTION; + SemanticResourceAttributes.SEMRESATTRS_OS_NAME = TMP_OS_NAME; + SemanticResourceAttributes.SEMRESATTRS_OS_VERSION = TMP_OS_VERSION; + SemanticResourceAttributes.SEMRESATTRS_PROCESS_PID = TMP_PROCESS_PID; + SemanticResourceAttributes.SEMRESATTRS_PROCESS_EXECUTABLE_NAME = TMP_PROCESS_EXECUTABLE_NAME; + SemanticResourceAttributes.SEMRESATTRS_PROCESS_EXECUTABLE_PATH = TMP_PROCESS_EXECUTABLE_PATH; + SemanticResourceAttributes.SEMRESATTRS_PROCESS_COMMAND = TMP_PROCESS_COMMAND; + SemanticResourceAttributes.SEMRESATTRS_PROCESS_COMMAND_LINE = TMP_PROCESS_COMMAND_LINE; + SemanticResourceAttributes.SEMRESATTRS_PROCESS_COMMAND_ARGS = TMP_PROCESS_COMMAND_ARGS; + SemanticResourceAttributes.SEMRESATTRS_PROCESS_OWNER = TMP_PROCESS_OWNER; + SemanticResourceAttributes.SEMRESATTRS_PROCESS_RUNTIME_NAME = TMP_PROCESS_RUNTIME_NAME; + SemanticResourceAttributes.SEMRESATTRS_PROCESS_RUNTIME_VERSION = TMP_PROCESS_RUNTIME_VERSION; + SemanticResourceAttributes.SEMRESATTRS_PROCESS_RUNTIME_DESCRIPTION = TMP_PROCESS_RUNTIME_DESCRIPTION; + SemanticResourceAttributes.SEMRESATTRS_SERVICE_NAME = TMP_SERVICE_NAME; + SemanticResourceAttributes.SEMRESATTRS_SERVICE_NAMESPACE = TMP_SERVICE_NAMESPACE; + SemanticResourceAttributes.SEMRESATTRS_SERVICE_INSTANCE_ID = TMP_SERVICE_INSTANCE_ID; + SemanticResourceAttributes.SEMRESATTRS_SERVICE_VERSION = TMP_SERVICE_VERSION; + SemanticResourceAttributes.SEMRESATTRS_TELEMETRY_SDK_NAME = TMP_TELEMETRY_SDK_NAME; + SemanticResourceAttributes.SEMRESATTRS_TELEMETRY_SDK_LANGUAGE = TMP_TELEMETRY_SDK_LANGUAGE; + SemanticResourceAttributes.SEMRESATTRS_TELEMETRY_SDK_VERSION = TMP_TELEMETRY_SDK_VERSION; + SemanticResourceAttributes.SEMRESATTRS_TELEMETRY_AUTO_VERSION = TMP_TELEMETRY_AUTO_VERSION; + SemanticResourceAttributes.SEMRESATTRS_WEBENGINE_NAME = TMP_WEBENGINE_NAME; + SemanticResourceAttributes.SEMRESATTRS_WEBENGINE_VERSION = TMP_WEBENGINE_VERSION; + SemanticResourceAttributes.SEMRESATTRS_WEBENGINE_DESCRIPTION = TMP_WEBENGINE_DESCRIPTION; + SemanticResourceAttributes.SemanticResourceAttributes = /* @__PURE__ */ (0, utils_1.createConstMap)([ + TMP_CLOUD_PROVIDER, + TMP_CLOUD_ACCOUNT_ID, + TMP_CLOUD_REGION, + TMP_CLOUD_AVAILABILITY_ZONE, + TMP_CLOUD_PLATFORM, + TMP_AWS_ECS_CONTAINER_ARN, + TMP_AWS_ECS_CLUSTER_ARN, + TMP_AWS_ECS_LAUNCHTYPE, + TMP_AWS_ECS_TASK_ARN, + TMP_AWS_ECS_TASK_FAMILY, + TMP_AWS_ECS_TASK_REVISION, + TMP_AWS_EKS_CLUSTER_ARN, + TMP_AWS_LOG_GROUP_NAMES, + TMP_AWS_LOG_GROUP_ARNS, + TMP_AWS_LOG_STREAM_NAMES, + TMP_AWS_LOG_STREAM_ARNS, + TMP_CONTAINER_NAME, + TMP_CONTAINER_ID, + TMP_CONTAINER_RUNTIME, + TMP_CONTAINER_IMAGE_NAME, + TMP_CONTAINER_IMAGE_TAG, + TMP_DEPLOYMENT_ENVIRONMENT, + TMP_DEVICE_ID, + TMP_DEVICE_MODEL_IDENTIFIER, + TMP_DEVICE_MODEL_NAME, + TMP_FAAS_NAME, + TMP_FAAS_ID, + TMP_FAAS_VERSION, + TMP_FAAS_INSTANCE, + TMP_FAAS_MAX_MEMORY, + TMP_HOST_ID, + TMP_HOST_NAME, + TMP_HOST_TYPE, + TMP_HOST_ARCH, + TMP_HOST_IMAGE_NAME, + TMP_HOST_IMAGE_ID, + TMP_HOST_IMAGE_VERSION, + TMP_K8S_CLUSTER_NAME, + TMP_K8S_NODE_NAME, + TMP_K8S_NODE_UID, + TMP_K8S_NAMESPACE_NAME, + TMP_K8S_POD_UID, + TMP_K8S_POD_NAME, + TMP_K8S_CONTAINER_NAME, + TMP_K8S_REPLICASET_UID, + TMP_K8S_REPLICASET_NAME, + TMP_K8S_DEPLOYMENT_UID, + TMP_K8S_DEPLOYMENT_NAME, + TMP_K8S_STATEFULSET_UID, + TMP_K8S_STATEFULSET_NAME, + TMP_K8S_DAEMONSET_UID, + TMP_K8S_DAEMONSET_NAME, + TMP_K8S_JOB_UID, + TMP_K8S_JOB_NAME, + TMP_K8S_CRONJOB_UID, + TMP_K8S_CRONJOB_NAME, + TMP_OS_TYPE, + TMP_OS_DESCRIPTION, + TMP_OS_NAME, + TMP_OS_VERSION, + TMP_PROCESS_PID, + TMP_PROCESS_EXECUTABLE_NAME, + TMP_PROCESS_EXECUTABLE_PATH, + TMP_PROCESS_COMMAND, + TMP_PROCESS_COMMAND_LINE, + TMP_PROCESS_COMMAND_ARGS, + TMP_PROCESS_OWNER, + TMP_PROCESS_RUNTIME_NAME, + TMP_PROCESS_RUNTIME_VERSION, + TMP_PROCESS_RUNTIME_DESCRIPTION, + TMP_SERVICE_NAME, + TMP_SERVICE_NAMESPACE, + TMP_SERVICE_INSTANCE_ID, + TMP_SERVICE_VERSION, + TMP_TELEMETRY_SDK_NAME, + TMP_TELEMETRY_SDK_LANGUAGE, + TMP_TELEMETRY_SDK_VERSION, + TMP_TELEMETRY_AUTO_VERSION, + TMP_WEBENGINE_NAME, + TMP_WEBENGINE_VERSION, + TMP_WEBENGINE_DESCRIPTION + ]); + const TMP_CLOUDPROVIDERVALUES_ALIBABA_CLOUD = "alibaba_cloud"; + const TMP_CLOUDPROVIDERVALUES_AWS = "aws"; + const TMP_CLOUDPROVIDERVALUES_AZURE = "azure"; + const TMP_CLOUDPROVIDERVALUES_GCP = "gcp"; + SemanticResourceAttributes.CLOUDPROVIDERVALUES_ALIBABA_CLOUD = TMP_CLOUDPROVIDERVALUES_ALIBABA_CLOUD; + SemanticResourceAttributes.CLOUDPROVIDERVALUES_AWS = TMP_CLOUDPROVIDERVALUES_AWS; + SemanticResourceAttributes.CLOUDPROVIDERVALUES_AZURE = TMP_CLOUDPROVIDERVALUES_AZURE; + SemanticResourceAttributes.CLOUDPROVIDERVALUES_GCP = TMP_CLOUDPROVIDERVALUES_GCP; + SemanticResourceAttributes.CloudProviderValues = /* @__PURE__ */ (0, utils_1.createConstMap)([ + TMP_CLOUDPROVIDERVALUES_ALIBABA_CLOUD, + TMP_CLOUDPROVIDERVALUES_AWS, + TMP_CLOUDPROVIDERVALUES_AZURE, + TMP_CLOUDPROVIDERVALUES_GCP + ]); + const TMP_CLOUDPLATFORMVALUES_ALIBABA_CLOUD_ECS = "alibaba_cloud_ecs"; + const TMP_CLOUDPLATFORMVALUES_ALIBABA_CLOUD_FC = "alibaba_cloud_fc"; + const TMP_CLOUDPLATFORMVALUES_AWS_EC2 = "aws_ec2"; + const TMP_CLOUDPLATFORMVALUES_AWS_ECS = "aws_ecs"; + const TMP_CLOUDPLATFORMVALUES_AWS_EKS = "aws_eks"; + const TMP_CLOUDPLATFORMVALUES_AWS_LAMBDA = "aws_lambda"; + const TMP_CLOUDPLATFORMVALUES_AWS_ELASTIC_BEANSTALK = "aws_elastic_beanstalk"; + const TMP_CLOUDPLATFORMVALUES_AZURE_VM = "azure_vm"; + const TMP_CLOUDPLATFORMVALUES_AZURE_CONTAINER_INSTANCES = "azure_container_instances"; + const TMP_CLOUDPLATFORMVALUES_AZURE_AKS = "azure_aks"; + const TMP_CLOUDPLATFORMVALUES_AZURE_FUNCTIONS = "azure_functions"; + const TMP_CLOUDPLATFORMVALUES_AZURE_APP_SERVICE = "azure_app_service"; + const TMP_CLOUDPLATFORMVALUES_GCP_COMPUTE_ENGINE = "gcp_compute_engine"; + const TMP_CLOUDPLATFORMVALUES_GCP_CLOUD_RUN = "gcp_cloud_run"; + const TMP_CLOUDPLATFORMVALUES_GCP_KUBERNETES_ENGINE = "gcp_kubernetes_engine"; + const TMP_CLOUDPLATFORMVALUES_GCP_CLOUD_FUNCTIONS = "gcp_cloud_functions"; + const TMP_CLOUDPLATFORMVALUES_GCP_APP_ENGINE = "gcp_app_engine"; + SemanticResourceAttributes.CLOUDPLATFORMVALUES_ALIBABA_CLOUD_ECS = TMP_CLOUDPLATFORMVALUES_ALIBABA_CLOUD_ECS; + SemanticResourceAttributes.CLOUDPLATFORMVALUES_ALIBABA_CLOUD_FC = TMP_CLOUDPLATFORMVALUES_ALIBABA_CLOUD_FC; + SemanticResourceAttributes.CLOUDPLATFORMVALUES_AWS_EC2 = TMP_CLOUDPLATFORMVALUES_AWS_EC2; + SemanticResourceAttributes.CLOUDPLATFORMVALUES_AWS_ECS = TMP_CLOUDPLATFORMVALUES_AWS_ECS; + SemanticResourceAttributes.CLOUDPLATFORMVALUES_AWS_EKS = TMP_CLOUDPLATFORMVALUES_AWS_EKS; + SemanticResourceAttributes.CLOUDPLATFORMVALUES_AWS_LAMBDA = TMP_CLOUDPLATFORMVALUES_AWS_LAMBDA; + SemanticResourceAttributes.CLOUDPLATFORMVALUES_AWS_ELASTIC_BEANSTALK = TMP_CLOUDPLATFORMVALUES_AWS_ELASTIC_BEANSTALK; + SemanticResourceAttributes.CLOUDPLATFORMVALUES_AZURE_VM = TMP_CLOUDPLATFORMVALUES_AZURE_VM; + SemanticResourceAttributes.CLOUDPLATFORMVALUES_AZURE_CONTAINER_INSTANCES = TMP_CLOUDPLATFORMVALUES_AZURE_CONTAINER_INSTANCES; + SemanticResourceAttributes.CLOUDPLATFORMVALUES_AZURE_AKS = TMP_CLOUDPLATFORMVALUES_AZURE_AKS; + SemanticResourceAttributes.CLOUDPLATFORMVALUES_AZURE_FUNCTIONS = TMP_CLOUDPLATFORMVALUES_AZURE_FUNCTIONS; + SemanticResourceAttributes.CLOUDPLATFORMVALUES_AZURE_APP_SERVICE = TMP_CLOUDPLATFORMVALUES_AZURE_APP_SERVICE; + SemanticResourceAttributes.CLOUDPLATFORMVALUES_GCP_COMPUTE_ENGINE = TMP_CLOUDPLATFORMVALUES_GCP_COMPUTE_ENGINE; + SemanticResourceAttributes.CLOUDPLATFORMVALUES_GCP_CLOUD_RUN = TMP_CLOUDPLATFORMVALUES_GCP_CLOUD_RUN; + SemanticResourceAttributes.CLOUDPLATFORMVALUES_GCP_KUBERNETES_ENGINE = TMP_CLOUDPLATFORMVALUES_GCP_KUBERNETES_ENGINE; + SemanticResourceAttributes.CLOUDPLATFORMVALUES_GCP_CLOUD_FUNCTIONS = TMP_CLOUDPLATFORMVALUES_GCP_CLOUD_FUNCTIONS; + SemanticResourceAttributes.CLOUDPLATFORMVALUES_GCP_APP_ENGINE = TMP_CLOUDPLATFORMVALUES_GCP_APP_ENGINE; + SemanticResourceAttributes.CloudPlatformValues = /* @__PURE__ */ (0, utils_1.createConstMap)([ + TMP_CLOUDPLATFORMVALUES_ALIBABA_CLOUD_ECS, + TMP_CLOUDPLATFORMVALUES_ALIBABA_CLOUD_FC, + TMP_CLOUDPLATFORMVALUES_AWS_EC2, + TMP_CLOUDPLATFORMVALUES_AWS_ECS, + TMP_CLOUDPLATFORMVALUES_AWS_EKS, + TMP_CLOUDPLATFORMVALUES_AWS_LAMBDA, + TMP_CLOUDPLATFORMVALUES_AWS_ELASTIC_BEANSTALK, + TMP_CLOUDPLATFORMVALUES_AZURE_VM, + TMP_CLOUDPLATFORMVALUES_AZURE_CONTAINER_INSTANCES, + TMP_CLOUDPLATFORMVALUES_AZURE_AKS, + TMP_CLOUDPLATFORMVALUES_AZURE_FUNCTIONS, + TMP_CLOUDPLATFORMVALUES_AZURE_APP_SERVICE, + TMP_CLOUDPLATFORMVALUES_GCP_COMPUTE_ENGINE, + TMP_CLOUDPLATFORMVALUES_GCP_CLOUD_RUN, + TMP_CLOUDPLATFORMVALUES_GCP_KUBERNETES_ENGINE, + TMP_CLOUDPLATFORMVALUES_GCP_CLOUD_FUNCTIONS, + TMP_CLOUDPLATFORMVALUES_GCP_APP_ENGINE + ]); + const TMP_AWSECSLAUNCHTYPEVALUES_EC2 = "ec2"; + const TMP_AWSECSLAUNCHTYPEVALUES_FARGATE = "fargate"; + SemanticResourceAttributes.AWSECSLAUNCHTYPEVALUES_EC2 = TMP_AWSECSLAUNCHTYPEVALUES_EC2; + SemanticResourceAttributes.AWSECSLAUNCHTYPEVALUES_FARGATE = TMP_AWSECSLAUNCHTYPEVALUES_FARGATE; + SemanticResourceAttributes.AwsEcsLaunchtypeValues = /* @__PURE__ */ (0, utils_1.createConstMap)([ + TMP_AWSECSLAUNCHTYPEVALUES_EC2, + TMP_AWSECSLAUNCHTYPEVALUES_FARGATE + ]); + const TMP_HOSTARCHVALUES_AMD64 = "amd64"; + const TMP_HOSTARCHVALUES_ARM32 = "arm32"; + const TMP_HOSTARCHVALUES_ARM64 = "arm64"; + const TMP_HOSTARCHVALUES_IA64 = "ia64"; + const TMP_HOSTARCHVALUES_PPC32 = "ppc32"; + const TMP_HOSTARCHVALUES_PPC64 = "ppc64"; + const TMP_HOSTARCHVALUES_X86 = "x86"; + SemanticResourceAttributes.HOSTARCHVALUES_AMD64 = TMP_HOSTARCHVALUES_AMD64; + SemanticResourceAttributes.HOSTARCHVALUES_ARM32 = TMP_HOSTARCHVALUES_ARM32; + SemanticResourceAttributes.HOSTARCHVALUES_ARM64 = TMP_HOSTARCHVALUES_ARM64; + SemanticResourceAttributes.HOSTARCHVALUES_IA64 = TMP_HOSTARCHVALUES_IA64; + SemanticResourceAttributes.HOSTARCHVALUES_PPC32 = TMP_HOSTARCHVALUES_PPC32; + SemanticResourceAttributes.HOSTARCHVALUES_PPC64 = TMP_HOSTARCHVALUES_PPC64; + SemanticResourceAttributes.HOSTARCHVALUES_X86 = TMP_HOSTARCHVALUES_X86; + SemanticResourceAttributes.HostArchValues = /* @__PURE__ */ (0, utils_1.createConstMap)([ + TMP_HOSTARCHVALUES_AMD64, + TMP_HOSTARCHVALUES_ARM32, + TMP_HOSTARCHVALUES_ARM64, + TMP_HOSTARCHVALUES_IA64, + TMP_HOSTARCHVALUES_PPC32, + TMP_HOSTARCHVALUES_PPC64, + TMP_HOSTARCHVALUES_X86 + ]); + const TMP_OSTYPEVALUES_WINDOWS = "windows"; + const TMP_OSTYPEVALUES_LINUX = "linux"; + const TMP_OSTYPEVALUES_DARWIN = "darwin"; + const TMP_OSTYPEVALUES_FREEBSD = "freebsd"; + const TMP_OSTYPEVALUES_NETBSD = "netbsd"; + const TMP_OSTYPEVALUES_OPENBSD = "openbsd"; + const TMP_OSTYPEVALUES_DRAGONFLYBSD = "dragonflybsd"; + const TMP_OSTYPEVALUES_HPUX = "hpux"; + const TMP_OSTYPEVALUES_AIX = "aix"; + const TMP_OSTYPEVALUES_SOLARIS = "solaris"; + const TMP_OSTYPEVALUES_Z_OS = "z_os"; + SemanticResourceAttributes.OSTYPEVALUES_WINDOWS = TMP_OSTYPEVALUES_WINDOWS; + SemanticResourceAttributes.OSTYPEVALUES_LINUX = TMP_OSTYPEVALUES_LINUX; + SemanticResourceAttributes.OSTYPEVALUES_DARWIN = TMP_OSTYPEVALUES_DARWIN; + SemanticResourceAttributes.OSTYPEVALUES_FREEBSD = TMP_OSTYPEVALUES_FREEBSD; + SemanticResourceAttributes.OSTYPEVALUES_NETBSD = TMP_OSTYPEVALUES_NETBSD; + SemanticResourceAttributes.OSTYPEVALUES_OPENBSD = TMP_OSTYPEVALUES_OPENBSD; + SemanticResourceAttributes.OSTYPEVALUES_DRAGONFLYBSD = TMP_OSTYPEVALUES_DRAGONFLYBSD; + SemanticResourceAttributes.OSTYPEVALUES_HPUX = TMP_OSTYPEVALUES_HPUX; + SemanticResourceAttributes.OSTYPEVALUES_AIX = TMP_OSTYPEVALUES_AIX; + SemanticResourceAttributes.OSTYPEVALUES_SOLARIS = TMP_OSTYPEVALUES_SOLARIS; + SemanticResourceAttributes.OSTYPEVALUES_Z_OS = TMP_OSTYPEVALUES_Z_OS; + SemanticResourceAttributes.OsTypeValues = /* @__PURE__ */ (0, utils_1.createConstMap)([ + TMP_OSTYPEVALUES_WINDOWS, + TMP_OSTYPEVALUES_LINUX, + TMP_OSTYPEVALUES_DARWIN, + TMP_OSTYPEVALUES_FREEBSD, + TMP_OSTYPEVALUES_NETBSD, + TMP_OSTYPEVALUES_OPENBSD, + TMP_OSTYPEVALUES_DRAGONFLYBSD, + TMP_OSTYPEVALUES_HPUX, + TMP_OSTYPEVALUES_AIX, + TMP_OSTYPEVALUES_SOLARIS, + TMP_OSTYPEVALUES_Z_OS + ]); + const TMP_TELEMETRYSDKLANGUAGEVALUES_CPP = "cpp"; + const TMP_TELEMETRYSDKLANGUAGEVALUES_DOTNET = "dotnet"; + const TMP_TELEMETRYSDKLANGUAGEVALUES_ERLANG = "erlang"; + const TMP_TELEMETRYSDKLANGUAGEVALUES_GO = "go"; + const TMP_TELEMETRYSDKLANGUAGEVALUES_JAVA = "java"; + const TMP_TELEMETRYSDKLANGUAGEVALUES_NODEJS = "nodejs"; + const TMP_TELEMETRYSDKLANGUAGEVALUES_PHP = "php"; + const TMP_TELEMETRYSDKLANGUAGEVALUES_PYTHON = "python"; + const TMP_TELEMETRYSDKLANGUAGEVALUES_RUBY = "ruby"; + const TMP_TELEMETRYSDKLANGUAGEVALUES_WEBJS = "webjs"; + SemanticResourceAttributes.TELEMETRYSDKLANGUAGEVALUES_CPP = TMP_TELEMETRYSDKLANGUAGEVALUES_CPP; + SemanticResourceAttributes.TELEMETRYSDKLANGUAGEVALUES_DOTNET = TMP_TELEMETRYSDKLANGUAGEVALUES_DOTNET; + SemanticResourceAttributes.TELEMETRYSDKLANGUAGEVALUES_ERLANG = TMP_TELEMETRYSDKLANGUAGEVALUES_ERLANG; + SemanticResourceAttributes.TELEMETRYSDKLANGUAGEVALUES_GO = TMP_TELEMETRYSDKLANGUAGEVALUES_GO; + SemanticResourceAttributes.TELEMETRYSDKLANGUAGEVALUES_JAVA = TMP_TELEMETRYSDKLANGUAGEVALUES_JAVA; + SemanticResourceAttributes.TELEMETRYSDKLANGUAGEVALUES_NODEJS = TMP_TELEMETRYSDKLANGUAGEVALUES_NODEJS; + SemanticResourceAttributes.TELEMETRYSDKLANGUAGEVALUES_PHP = TMP_TELEMETRYSDKLANGUAGEVALUES_PHP; + SemanticResourceAttributes.TELEMETRYSDKLANGUAGEVALUES_PYTHON = TMP_TELEMETRYSDKLANGUAGEVALUES_PYTHON; + SemanticResourceAttributes.TELEMETRYSDKLANGUAGEVALUES_RUBY = TMP_TELEMETRYSDKLANGUAGEVALUES_RUBY; + SemanticResourceAttributes.TELEMETRYSDKLANGUAGEVALUES_WEBJS = TMP_TELEMETRYSDKLANGUAGEVALUES_WEBJS; + SemanticResourceAttributes.TelemetrySdkLanguageValues = /* @__PURE__ */ (0, utils_1.createConstMap)([ + TMP_TELEMETRYSDKLANGUAGEVALUES_CPP, + TMP_TELEMETRYSDKLANGUAGEVALUES_DOTNET, + TMP_TELEMETRYSDKLANGUAGEVALUES_ERLANG, + TMP_TELEMETRYSDKLANGUAGEVALUES_GO, + TMP_TELEMETRYSDKLANGUAGEVALUES_JAVA, + TMP_TELEMETRYSDKLANGUAGEVALUES_NODEJS, + TMP_TELEMETRYSDKLANGUAGEVALUES_PHP, + TMP_TELEMETRYSDKLANGUAGEVALUES_PYTHON, + TMP_TELEMETRYSDKLANGUAGEVALUES_RUBY, + TMP_TELEMETRYSDKLANGUAGEVALUES_WEBJS + ]); + return SemanticResourceAttributes; +} +var hasRequiredResource; +function requireResource() { + if (hasRequiredResource) return resource; + hasRequiredResource = 1; + (function(exports$1) { + var __createBinding = resource && resource.__createBinding || (Object.create ? (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m[k]; + } }; + } + Object.defineProperty(o, k2, desc); + }) : (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + o[k2] = m[k]; + })); + var __exportStar = resource && resource.__exportStar || function(m, exports$12) { + for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports$12, p)) __createBinding(exports$12, m, p); + }; + Object.defineProperty(exports$1, "__esModule", { value: true }); + __exportStar(/* @__PURE__ */ requireSemanticResourceAttributes(), exports$1); + })(resource); + return resource; +} +var stable_attributes = {}; +var hasRequiredStable_attributes; +function requireStable_attributes() { + if (hasRequiredStable_attributes) return stable_attributes; + hasRequiredStable_attributes = 1; + Object.defineProperty(stable_attributes, "__esModule", { value: true }); + stable_attributes.ATTR_EXCEPTION_TYPE = stable_attributes.ATTR_EXCEPTION_STACKTRACE = stable_attributes.ATTR_EXCEPTION_MESSAGE = stable_attributes.ATTR_EXCEPTION_ESCAPED = stable_attributes.ERROR_TYPE_VALUE_OTHER = stable_attributes.ATTR_ERROR_TYPE = stable_attributes.DOTNET_GC_HEAP_GENERATION_VALUE_POH = stable_attributes.DOTNET_GC_HEAP_GENERATION_VALUE_LOH = stable_attributes.DOTNET_GC_HEAP_GENERATION_VALUE_GEN2 = stable_attributes.DOTNET_GC_HEAP_GENERATION_VALUE_GEN1 = stable_attributes.DOTNET_GC_HEAP_GENERATION_VALUE_GEN0 = stable_attributes.ATTR_DOTNET_GC_HEAP_GENERATION = stable_attributes.DB_SYSTEM_NAME_VALUE_POSTGRESQL = stable_attributes.DB_SYSTEM_NAME_VALUE_MYSQL = stable_attributes.DB_SYSTEM_NAME_VALUE_MICROSOFT_SQL_SERVER = stable_attributes.DB_SYSTEM_NAME_VALUE_MARIADB = stable_attributes.ATTR_DB_SYSTEM_NAME = stable_attributes.ATTR_DB_STORED_PROCEDURE_NAME = stable_attributes.ATTR_DB_RESPONSE_STATUS_CODE = stable_attributes.ATTR_DB_QUERY_TEXT = stable_attributes.ATTR_DB_QUERY_SUMMARY = stable_attributes.ATTR_DB_OPERATION_NAME = stable_attributes.ATTR_DB_OPERATION_BATCH_SIZE = stable_attributes.ATTR_DB_NAMESPACE = stable_attributes.ATTR_DB_COLLECTION_NAME = stable_attributes.ATTR_CODE_STACKTRACE = stable_attributes.ATTR_CODE_LINE_NUMBER = stable_attributes.ATTR_CODE_FUNCTION_NAME = stable_attributes.ATTR_CODE_FILE_PATH = stable_attributes.ATTR_CODE_COLUMN_NUMBER = stable_attributes.ATTR_CLIENT_PORT = stable_attributes.ATTR_CLIENT_ADDRESS = stable_attributes.ATTR_ASPNETCORE_USER_IS_AUTHENTICATED = stable_attributes.ASPNETCORE_ROUTING_MATCH_STATUS_VALUE_SUCCESS = stable_attributes.ASPNETCORE_ROUTING_MATCH_STATUS_VALUE_FAILURE = stable_attributes.ATTR_ASPNETCORE_ROUTING_MATCH_STATUS = stable_attributes.ATTR_ASPNETCORE_ROUTING_IS_FALLBACK = stable_attributes.ATTR_ASPNETCORE_REQUEST_IS_UNHANDLED = stable_attributes.ASPNETCORE_RATE_LIMITING_RESULT_VALUE_REQUEST_CANCELED = stable_attributes.ASPNETCORE_RATE_LIMITING_RESULT_VALUE_GLOBAL_LIMITER = stable_attributes.ASPNETCORE_RATE_LIMITING_RESULT_VALUE_ENDPOINT_LIMITER = stable_attributes.ASPNETCORE_RATE_LIMITING_RESULT_VALUE_ACQUIRED = stable_attributes.ATTR_ASPNETCORE_RATE_LIMITING_RESULT = stable_attributes.ATTR_ASPNETCORE_RATE_LIMITING_POLICY = stable_attributes.ATTR_ASPNETCORE_DIAGNOSTICS_HANDLER_TYPE = stable_attributes.ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT_VALUE_UNHANDLED = stable_attributes.ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT_VALUE_SKIPPED = stable_attributes.ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT_VALUE_HANDLED = stable_attributes.ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT_VALUE_ABORTED = stable_attributes.ATTR_ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT = void 0; + stable_attributes.OTEL_STATUS_CODE_VALUE_ERROR = stable_attributes.ATTR_OTEL_STATUS_CODE = stable_attributes.ATTR_OTEL_SCOPE_VERSION = stable_attributes.ATTR_OTEL_SCOPE_NAME = stable_attributes.NETWORK_TYPE_VALUE_IPV6 = stable_attributes.NETWORK_TYPE_VALUE_IPV4 = stable_attributes.ATTR_NETWORK_TYPE = stable_attributes.NETWORK_TRANSPORT_VALUE_UNIX = stable_attributes.NETWORK_TRANSPORT_VALUE_UDP = stable_attributes.NETWORK_TRANSPORT_VALUE_TCP = stable_attributes.NETWORK_TRANSPORT_VALUE_QUIC = stable_attributes.NETWORK_TRANSPORT_VALUE_PIPE = stable_attributes.ATTR_NETWORK_TRANSPORT = stable_attributes.ATTR_NETWORK_PROTOCOL_VERSION = stable_attributes.ATTR_NETWORK_PROTOCOL_NAME = stable_attributes.ATTR_NETWORK_PEER_PORT = stable_attributes.ATTR_NETWORK_PEER_ADDRESS = stable_attributes.ATTR_NETWORK_LOCAL_PORT = stable_attributes.ATTR_NETWORK_LOCAL_ADDRESS = stable_attributes.JVM_THREAD_STATE_VALUE_WAITING = stable_attributes.JVM_THREAD_STATE_VALUE_TIMED_WAITING = stable_attributes.JVM_THREAD_STATE_VALUE_TERMINATED = stable_attributes.JVM_THREAD_STATE_VALUE_RUNNABLE = stable_attributes.JVM_THREAD_STATE_VALUE_NEW = stable_attributes.JVM_THREAD_STATE_VALUE_BLOCKED = stable_attributes.ATTR_JVM_THREAD_STATE = stable_attributes.ATTR_JVM_THREAD_DAEMON = stable_attributes.JVM_MEMORY_TYPE_VALUE_NON_HEAP = stable_attributes.JVM_MEMORY_TYPE_VALUE_HEAP = stable_attributes.ATTR_JVM_MEMORY_TYPE = stable_attributes.ATTR_JVM_MEMORY_POOL_NAME = stable_attributes.ATTR_JVM_GC_NAME = stable_attributes.ATTR_JVM_GC_ACTION = stable_attributes.ATTR_HTTP_ROUTE = stable_attributes.ATTR_HTTP_RESPONSE_STATUS_CODE = stable_attributes.ATTR_HTTP_RESPONSE_HEADER = stable_attributes.ATTR_HTTP_REQUEST_RESEND_COUNT = stable_attributes.ATTR_HTTP_REQUEST_METHOD_ORIGINAL = stable_attributes.HTTP_REQUEST_METHOD_VALUE_TRACE = stable_attributes.HTTP_REQUEST_METHOD_VALUE_PUT = stable_attributes.HTTP_REQUEST_METHOD_VALUE_POST = stable_attributes.HTTP_REQUEST_METHOD_VALUE_PATCH = stable_attributes.HTTP_REQUEST_METHOD_VALUE_OPTIONS = stable_attributes.HTTP_REQUEST_METHOD_VALUE_HEAD = stable_attributes.HTTP_REQUEST_METHOD_VALUE_GET = stable_attributes.HTTP_REQUEST_METHOD_VALUE_DELETE = stable_attributes.HTTP_REQUEST_METHOD_VALUE_CONNECT = stable_attributes.HTTP_REQUEST_METHOD_VALUE_OTHER = stable_attributes.ATTR_HTTP_REQUEST_METHOD = stable_attributes.ATTR_HTTP_REQUEST_HEADER = void 0; + stable_attributes.ATTR_USER_AGENT_ORIGINAL = stable_attributes.ATTR_URL_SCHEME = stable_attributes.ATTR_URL_QUERY = stable_attributes.ATTR_URL_PATH = stable_attributes.ATTR_URL_FULL = stable_attributes.ATTR_URL_FRAGMENT = stable_attributes.ATTR_TELEMETRY_SDK_VERSION = stable_attributes.ATTR_TELEMETRY_SDK_NAME = stable_attributes.TELEMETRY_SDK_LANGUAGE_VALUE_WEBJS = stable_attributes.TELEMETRY_SDK_LANGUAGE_VALUE_SWIFT = stable_attributes.TELEMETRY_SDK_LANGUAGE_VALUE_RUST = stable_attributes.TELEMETRY_SDK_LANGUAGE_VALUE_RUBY = stable_attributes.TELEMETRY_SDK_LANGUAGE_VALUE_PYTHON = stable_attributes.TELEMETRY_SDK_LANGUAGE_VALUE_PHP = stable_attributes.TELEMETRY_SDK_LANGUAGE_VALUE_NODEJS = stable_attributes.TELEMETRY_SDK_LANGUAGE_VALUE_JAVA = stable_attributes.TELEMETRY_SDK_LANGUAGE_VALUE_GO = stable_attributes.TELEMETRY_SDK_LANGUAGE_VALUE_ERLANG = stable_attributes.TELEMETRY_SDK_LANGUAGE_VALUE_DOTNET = stable_attributes.TELEMETRY_SDK_LANGUAGE_VALUE_CPP = stable_attributes.ATTR_TELEMETRY_SDK_LANGUAGE = stable_attributes.SIGNALR_TRANSPORT_VALUE_WEB_SOCKETS = stable_attributes.SIGNALR_TRANSPORT_VALUE_SERVER_SENT_EVENTS = stable_attributes.SIGNALR_TRANSPORT_VALUE_LONG_POLLING = stable_attributes.ATTR_SIGNALR_TRANSPORT = stable_attributes.SIGNALR_CONNECTION_STATUS_VALUE_TIMEOUT = stable_attributes.SIGNALR_CONNECTION_STATUS_VALUE_NORMAL_CLOSURE = stable_attributes.SIGNALR_CONNECTION_STATUS_VALUE_APP_SHUTDOWN = stable_attributes.ATTR_SIGNALR_CONNECTION_STATUS = stable_attributes.ATTR_SERVICE_VERSION = stable_attributes.ATTR_SERVICE_NAME = stable_attributes.ATTR_SERVER_PORT = stable_attributes.ATTR_SERVER_ADDRESS = stable_attributes.ATTR_OTEL_STATUS_DESCRIPTION = stable_attributes.OTEL_STATUS_CODE_VALUE_OK = void 0; + stable_attributes.ATTR_ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT = "aspnetcore.diagnostics.exception.result"; + stable_attributes.ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT_VALUE_ABORTED = "aborted"; + stable_attributes.ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT_VALUE_HANDLED = "handled"; + stable_attributes.ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT_VALUE_SKIPPED = "skipped"; + stable_attributes.ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT_VALUE_UNHANDLED = "unhandled"; + stable_attributes.ATTR_ASPNETCORE_DIAGNOSTICS_HANDLER_TYPE = "aspnetcore.diagnostics.handler.type"; + stable_attributes.ATTR_ASPNETCORE_RATE_LIMITING_POLICY = "aspnetcore.rate_limiting.policy"; + stable_attributes.ATTR_ASPNETCORE_RATE_LIMITING_RESULT = "aspnetcore.rate_limiting.result"; + stable_attributes.ASPNETCORE_RATE_LIMITING_RESULT_VALUE_ACQUIRED = "acquired"; + stable_attributes.ASPNETCORE_RATE_LIMITING_RESULT_VALUE_ENDPOINT_LIMITER = "endpoint_limiter"; + stable_attributes.ASPNETCORE_RATE_LIMITING_RESULT_VALUE_GLOBAL_LIMITER = "global_limiter"; + stable_attributes.ASPNETCORE_RATE_LIMITING_RESULT_VALUE_REQUEST_CANCELED = "request_canceled"; + stable_attributes.ATTR_ASPNETCORE_REQUEST_IS_UNHANDLED = "aspnetcore.request.is_unhandled"; + stable_attributes.ATTR_ASPNETCORE_ROUTING_IS_FALLBACK = "aspnetcore.routing.is_fallback"; + stable_attributes.ATTR_ASPNETCORE_ROUTING_MATCH_STATUS = "aspnetcore.routing.match_status"; + stable_attributes.ASPNETCORE_ROUTING_MATCH_STATUS_VALUE_FAILURE = "failure"; + stable_attributes.ASPNETCORE_ROUTING_MATCH_STATUS_VALUE_SUCCESS = "success"; + stable_attributes.ATTR_ASPNETCORE_USER_IS_AUTHENTICATED = "aspnetcore.user.is_authenticated"; + stable_attributes.ATTR_CLIENT_ADDRESS = "client.address"; + stable_attributes.ATTR_CLIENT_PORT = "client.port"; + stable_attributes.ATTR_CODE_COLUMN_NUMBER = "code.column.number"; + stable_attributes.ATTR_CODE_FILE_PATH = "code.file.path"; + stable_attributes.ATTR_CODE_FUNCTION_NAME = "code.function.name"; + stable_attributes.ATTR_CODE_LINE_NUMBER = "code.line.number"; + stable_attributes.ATTR_CODE_STACKTRACE = "code.stacktrace"; + stable_attributes.ATTR_DB_COLLECTION_NAME = "db.collection.name"; + stable_attributes.ATTR_DB_NAMESPACE = "db.namespace"; + stable_attributes.ATTR_DB_OPERATION_BATCH_SIZE = "db.operation.batch.size"; + stable_attributes.ATTR_DB_OPERATION_NAME = "db.operation.name"; + stable_attributes.ATTR_DB_QUERY_SUMMARY = "db.query.summary"; + stable_attributes.ATTR_DB_QUERY_TEXT = "db.query.text"; + stable_attributes.ATTR_DB_RESPONSE_STATUS_CODE = "db.response.status_code"; + stable_attributes.ATTR_DB_STORED_PROCEDURE_NAME = "db.stored_procedure.name"; + stable_attributes.ATTR_DB_SYSTEM_NAME = "db.system.name"; + stable_attributes.DB_SYSTEM_NAME_VALUE_MARIADB = "mariadb"; + stable_attributes.DB_SYSTEM_NAME_VALUE_MICROSOFT_SQL_SERVER = "microsoft.sql_server"; + stable_attributes.DB_SYSTEM_NAME_VALUE_MYSQL = "mysql"; + stable_attributes.DB_SYSTEM_NAME_VALUE_POSTGRESQL = "postgresql"; + stable_attributes.ATTR_DOTNET_GC_HEAP_GENERATION = "dotnet.gc.heap.generation"; + stable_attributes.DOTNET_GC_HEAP_GENERATION_VALUE_GEN0 = "gen0"; + stable_attributes.DOTNET_GC_HEAP_GENERATION_VALUE_GEN1 = "gen1"; + stable_attributes.DOTNET_GC_HEAP_GENERATION_VALUE_GEN2 = "gen2"; + stable_attributes.DOTNET_GC_HEAP_GENERATION_VALUE_LOH = "loh"; + stable_attributes.DOTNET_GC_HEAP_GENERATION_VALUE_POH = "poh"; + stable_attributes.ATTR_ERROR_TYPE = "error.type"; + stable_attributes.ERROR_TYPE_VALUE_OTHER = "_OTHER"; + stable_attributes.ATTR_EXCEPTION_ESCAPED = "exception.escaped"; + stable_attributes.ATTR_EXCEPTION_MESSAGE = "exception.message"; + stable_attributes.ATTR_EXCEPTION_STACKTRACE = "exception.stacktrace"; + stable_attributes.ATTR_EXCEPTION_TYPE = "exception.type"; + const ATTR_HTTP_REQUEST_HEADER = (key) => `http.request.header.${key}`; + stable_attributes.ATTR_HTTP_REQUEST_HEADER = ATTR_HTTP_REQUEST_HEADER; + stable_attributes.ATTR_HTTP_REQUEST_METHOD = "http.request.method"; + stable_attributes.HTTP_REQUEST_METHOD_VALUE_OTHER = "_OTHER"; + stable_attributes.HTTP_REQUEST_METHOD_VALUE_CONNECT = "CONNECT"; + stable_attributes.HTTP_REQUEST_METHOD_VALUE_DELETE = "DELETE"; + stable_attributes.HTTP_REQUEST_METHOD_VALUE_GET = "GET"; + stable_attributes.HTTP_REQUEST_METHOD_VALUE_HEAD = "HEAD"; + stable_attributes.HTTP_REQUEST_METHOD_VALUE_OPTIONS = "OPTIONS"; + stable_attributes.HTTP_REQUEST_METHOD_VALUE_PATCH = "PATCH"; + stable_attributes.HTTP_REQUEST_METHOD_VALUE_POST = "POST"; + stable_attributes.HTTP_REQUEST_METHOD_VALUE_PUT = "PUT"; + stable_attributes.HTTP_REQUEST_METHOD_VALUE_TRACE = "TRACE"; + stable_attributes.ATTR_HTTP_REQUEST_METHOD_ORIGINAL = "http.request.method_original"; + stable_attributes.ATTR_HTTP_REQUEST_RESEND_COUNT = "http.request.resend_count"; + const ATTR_HTTP_RESPONSE_HEADER = (key) => `http.response.header.${key}`; + stable_attributes.ATTR_HTTP_RESPONSE_HEADER = ATTR_HTTP_RESPONSE_HEADER; + stable_attributes.ATTR_HTTP_RESPONSE_STATUS_CODE = "http.response.status_code"; + stable_attributes.ATTR_HTTP_ROUTE = "http.route"; + stable_attributes.ATTR_JVM_GC_ACTION = "jvm.gc.action"; + stable_attributes.ATTR_JVM_GC_NAME = "jvm.gc.name"; + stable_attributes.ATTR_JVM_MEMORY_POOL_NAME = "jvm.memory.pool.name"; + stable_attributes.ATTR_JVM_MEMORY_TYPE = "jvm.memory.type"; + stable_attributes.JVM_MEMORY_TYPE_VALUE_HEAP = "heap"; + stable_attributes.JVM_MEMORY_TYPE_VALUE_NON_HEAP = "non_heap"; + stable_attributes.ATTR_JVM_THREAD_DAEMON = "jvm.thread.daemon"; + stable_attributes.ATTR_JVM_THREAD_STATE = "jvm.thread.state"; + stable_attributes.JVM_THREAD_STATE_VALUE_BLOCKED = "blocked"; + stable_attributes.JVM_THREAD_STATE_VALUE_NEW = "new"; + stable_attributes.JVM_THREAD_STATE_VALUE_RUNNABLE = "runnable"; + stable_attributes.JVM_THREAD_STATE_VALUE_TERMINATED = "terminated"; + stable_attributes.JVM_THREAD_STATE_VALUE_TIMED_WAITING = "timed_waiting"; + stable_attributes.JVM_THREAD_STATE_VALUE_WAITING = "waiting"; + stable_attributes.ATTR_NETWORK_LOCAL_ADDRESS = "network.local.address"; + stable_attributes.ATTR_NETWORK_LOCAL_PORT = "network.local.port"; + stable_attributes.ATTR_NETWORK_PEER_ADDRESS = "network.peer.address"; + stable_attributes.ATTR_NETWORK_PEER_PORT = "network.peer.port"; + stable_attributes.ATTR_NETWORK_PROTOCOL_NAME = "network.protocol.name"; + stable_attributes.ATTR_NETWORK_PROTOCOL_VERSION = "network.protocol.version"; + stable_attributes.ATTR_NETWORK_TRANSPORT = "network.transport"; + stable_attributes.NETWORK_TRANSPORT_VALUE_PIPE = "pipe"; + stable_attributes.NETWORK_TRANSPORT_VALUE_QUIC = "quic"; + stable_attributes.NETWORK_TRANSPORT_VALUE_TCP = "tcp"; + stable_attributes.NETWORK_TRANSPORT_VALUE_UDP = "udp"; + stable_attributes.NETWORK_TRANSPORT_VALUE_UNIX = "unix"; + stable_attributes.ATTR_NETWORK_TYPE = "network.type"; + stable_attributes.NETWORK_TYPE_VALUE_IPV4 = "ipv4"; + stable_attributes.NETWORK_TYPE_VALUE_IPV6 = "ipv6"; + stable_attributes.ATTR_OTEL_SCOPE_NAME = "otel.scope.name"; + stable_attributes.ATTR_OTEL_SCOPE_VERSION = "otel.scope.version"; + stable_attributes.ATTR_OTEL_STATUS_CODE = "otel.status_code"; + stable_attributes.OTEL_STATUS_CODE_VALUE_ERROR = "ERROR"; + stable_attributes.OTEL_STATUS_CODE_VALUE_OK = "OK"; + stable_attributes.ATTR_OTEL_STATUS_DESCRIPTION = "otel.status_description"; + stable_attributes.ATTR_SERVER_ADDRESS = "server.address"; + stable_attributes.ATTR_SERVER_PORT = "server.port"; + stable_attributes.ATTR_SERVICE_NAME = "service.name"; + stable_attributes.ATTR_SERVICE_VERSION = "service.version"; + stable_attributes.ATTR_SIGNALR_CONNECTION_STATUS = "signalr.connection.status"; + stable_attributes.SIGNALR_CONNECTION_STATUS_VALUE_APP_SHUTDOWN = "app_shutdown"; + stable_attributes.SIGNALR_CONNECTION_STATUS_VALUE_NORMAL_CLOSURE = "normal_closure"; + stable_attributes.SIGNALR_CONNECTION_STATUS_VALUE_TIMEOUT = "timeout"; + stable_attributes.ATTR_SIGNALR_TRANSPORT = "signalr.transport"; + stable_attributes.SIGNALR_TRANSPORT_VALUE_LONG_POLLING = "long_polling"; + stable_attributes.SIGNALR_TRANSPORT_VALUE_SERVER_SENT_EVENTS = "server_sent_events"; + stable_attributes.SIGNALR_TRANSPORT_VALUE_WEB_SOCKETS = "web_sockets"; + stable_attributes.ATTR_TELEMETRY_SDK_LANGUAGE = "telemetry.sdk.language"; + stable_attributes.TELEMETRY_SDK_LANGUAGE_VALUE_CPP = "cpp"; + stable_attributes.TELEMETRY_SDK_LANGUAGE_VALUE_DOTNET = "dotnet"; + stable_attributes.TELEMETRY_SDK_LANGUAGE_VALUE_ERLANG = "erlang"; + stable_attributes.TELEMETRY_SDK_LANGUAGE_VALUE_GO = "go"; + stable_attributes.TELEMETRY_SDK_LANGUAGE_VALUE_JAVA = "java"; + stable_attributes.TELEMETRY_SDK_LANGUAGE_VALUE_NODEJS = "nodejs"; + stable_attributes.TELEMETRY_SDK_LANGUAGE_VALUE_PHP = "php"; + stable_attributes.TELEMETRY_SDK_LANGUAGE_VALUE_PYTHON = "python"; + stable_attributes.TELEMETRY_SDK_LANGUAGE_VALUE_RUBY = "ruby"; + stable_attributes.TELEMETRY_SDK_LANGUAGE_VALUE_RUST = "rust"; + stable_attributes.TELEMETRY_SDK_LANGUAGE_VALUE_SWIFT = "swift"; + stable_attributes.TELEMETRY_SDK_LANGUAGE_VALUE_WEBJS = "webjs"; + stable_attributes.ATTR_TELEMETRY_SDK_NAME = "telemetry.sdk.name"; + stable_attributes.ATTR_TELEMETRY_SDK_VERSION = "telemetry.sdk.version"; + stable_attributes.ATTR_URL_FRAGMENT = "url.fragment"; + stable_attributes.ATTR_URL_FULL = "url.full"; + stable_attributes.ATTR_URL_PATH = "url.path"; + stable_attributes.ATTR_URL_QUERY = "url.query"; + stable_attributes.ATTR_URL_SCHEME = "url.scheme"; + stable_attributes.ATTR_USER_AGENT_ORIGINAL = "user_agent.original"; + return stable_attributes; +} +var stable_metrics = {}; +var hasRequiredStable_metrics; +function requireStable_metrics() { + if (hasRequiredStable_metrics) return stable_metrics; + hasRequiredStable_metrics = 1; + Object.defineProperty(stable_metrics, "__esModule", { value: true }); + stable_metrics.METRIC_SIGNALR_SERVER_ACTIVE_CONNECTIONS = stable_metrics.METRIC_KESTREL_UPGRADED_CONNECTIONS = stable_metrics.METRIC_KESTREL_TLS_HANDSHAKE_DURATION = stable_metrics.METRIC_KESTREL_REJECTED_CONNECTIONS = stable_metrics.METRIC_KESTREL_QUEUED_REQUESTS = stable_metrics.METRIC_KESTREL_QUEUED_CONNECTIONS = stable_metrics.METRIC_KESTREL_CONNECTION_DURATION = stable_metrics.METRIC_KESTREL_ACTIVE_TLS_HANDSHAKES = stable_metrics.METRIC_KESTREL_ACTIVE_CONNECTIONS = stable_metrics.METRIC_JVM_THREAD_COUNT = stable_metrics.METRIC_JVM_MEMORY_USED_AFTER_LAST_GC = stable_metrics.METRIC_JVM_MEMORY_USED = stable_metrics.METRIC_JVM_MEMORY_LIMIT = stable_metrics.METRIC_JVM_MEMORY_COMMITTED = stable_metrics.METRIC_JVM_GC_DURATION = stable_metrics.METRIC_JVM_CPU_TIME = stable_metrics.METRIC_JVM_CPU_RECENT_UTILIZATION = stable_metrics.METRIC_JVM_CPU_COUNT = stable_metrics.METRIC_JVM_CLASS_UNLOADED = stable_metrics.METRIC_JVM_CLASS_LOADED = stable_metrics.METRIC_JVM_CLASS_COUNT = stable_metrics.METRIC_HTTP_SERVER_REQUEST_DURATION = stable_metrics.METRIC_HTTP_CLIENT_REQUEST_DURATION = stable_metrics.METRIC_DOTNET_TIMER_COUNT = stable_metrics.METRIC_DOTNET_THREAD_POOL_WORK_ITEM_COUNT = stable_metrics.METRIC_DOTNET_THREAD_POOL_THREAD_COUNT = stable_metrics.METRIC_DOTNET_THREAD_POOL_QUEUE_LENGTH = stable_metrics.METRIC_DOTNET_PROCESS_MEMORY_WORKING_SET = stable_metrics.METRIC_DOTNET_PROCESS_CPU_TIME = stable_metrics.METRIC_DOTNET_PROCESS_CPU_COUNT = stable_metrics.METRIC_DOTNET_MONITOR_LOCK_CONTENTIONS = stable_metrics.METRIC_DOTNET_JIT_COMPILED_METHODS = stable_metrics.METRIC_DOTNET_JIT_COMPILED_IL_SIZE = stable_metrics.METRIC_DOTNET_JIT_COMPILATION_TIME = stable_metrics.METRIC_DOTNET_GC_PAUSE_TIME = stable_metrics.METRIC_DOTNET_GC_LAST_COLLECTION_MEMORY_COMMITTED_SIZE = stable_metrics.METRIC_DOTNET_GC_LAST_COLLECTION_HEAP_SIZE = stable_metrics.METRIC_DOTNET_GC_LAST_COLLECTION_HEAP_FRAGMENTATION_SIZE = stable_metrics.METRIC_DOTNET_GC_HEAP_TOTAL_ALLOCATED = stable_metrics.METRIC_DOTNET_GC_COLLECTIONS = stable_metrics.METRIC_DOTNET_EXCEPTIONS = stable_metrics.METRIC_DOTNET_ASSEMBLY_COUNT = stable_metrics.METRIC_DB_CLIENT_OPERATION_DURATION = stable_metrics.METRIC_ASPNETCORE_ROUTING_MATCH_ATTEMPTS = stable_metrics.METRIC_ASPNETCORE_RATE_LIMITING_REQUESTS = stable_metrics.METRIC_ASPNETCORE_RATE_LIMITING_REQUEST_LEASE_DURATION = stable_metrics.METRIC_ASPNETCORE_RATE_LIMITING_REQUEST_TIME_IN_QUEUE = stable_metrics.METRIC_ASPNETCORE_RATE_LIMITING_QUEUED_REQUESTS = stable_metrics.METRIC_ASPNETCORE_RATE_LIMITING_ACTIVE_REQUEST_LEASES = stable_metrics.METRIC_ASPNETCORE_DIAGNOSTICS_EXCEPTIONS = void 0; + stable_metrics.METRIC_SIGNALR_SERVER_CONNECTION_DURATION = void 0; + stable_metrics.METRIC_ASPNETCORE_DIAGNOSTICS_EXCEPTIONS = "aspnetcore.diagnostics.exceptions"; + stable_metrics.METRIC_ASPNETCORE_RATE_LIMITING_ACTIVE_REQUEST_LEASES = "aspnetcore.rate_limiting.active_request_leases"; + stable_metrics.METRIC_ASPNETCORE_RATE_LIMITING_QUEUED_REQUESTS = "aspnetcore.rate_limiting.queued_requests"; + stable_metrics.METRIC_ASPNETCORE_RATE_LIMITING_REQUEST_TIME_IN_QUEUE = "aspnetcore.rate_limiting.request.time_in_queue"; + stable_metrics.METRIC_ASPNETCORE_RATE_LIMITING_REQUEST_LEASE_DURATION = "aspnetcore.rate_limiting.request_lease.duration"; + stable_metrics.METRIC_ASPNETCORE_RATE_LIMITING_REQUESTS = "aspnetcore.rate_limiting.requests"; + stable_metrics.METRIC_ASPNETCORE_ROUTING_MATCH_ATTEMPTS = "aspnetcore.routing.match_attempts"; + stable_metrics.METRIC_DB_CLIENT_OPERATION_DURATION = "db.client.operation.duration"; + stable_metrics.METRIC_DOTNET_ASSEMBLY_COUNT = "dotnet.assembly.count"; + stable_metrics.METRIC_DOTNET_EXCEPTIONS = "dotnet.exceptions"; + stable_metrics.METRIC_DOTNET_GC_COLLECTIONS = "dotnet.gc.collections"; + stable_metrics.METRIC_DOTNET_GC_HEAP_TOTAL_ALLOCATED = "dotnet.gc.heap.total_allocated"; + stable_metrics.METRIC_DOTNET_GC_LAST_COLLECTION_HEAP_FRAGMENTATION_SIZE = "dotnet.gc.last_collection.heap.fragmentation.size"; + stable_metrics.METRIC_DOTNET_GC_LAST_COLLECTION_HEAP_SIZE = "dotnet.gc.last_collection.heap.size"; + stable_metrics.METRIC_DOTNET_GC_LAST_COLLECTION_MEMORY_COMMITTED_SIZE = "dotnet.gc.last_collection.memory.committed_size"; + stable_metrics.METRIC_DOTNET_GC_PAUSE_TIME = "dotnet.gc.pause.time"; + stable_metrics.METRIC_DOTNET_JIT_COMPILATION_TIME = "dotnet.jit.compilation.time"; + stable_metrics.METRIC_DOTNET_JIT_COMPILED_IL_SIZE = "dotnet.jit.compiled_il.size"; + stable_metrics.METRIC_DOTNET_JIT_COMPILED_METHODS = "dotnet.jit.compiled_methods"; + stable_metrics.METRIC_DOTNET_MONITOR_LOCK_CONTENTIONS = "dotnet.monitor.lock_contentions"; + stable_metrics.METRIC_DOTNET_PROCESS_CPU_COUNT = "dotnet.process.cpu.count"; + stable_metrics.METRIC_DOTNET_PROCESS_CPU_TIME = "dotnet.process.cpu.time"; + stable_metrics.METRIC_DOTNET_PROCESS_MEMORY_WORKING_SET = "dotnet.process.memory.working_set"; + stable_metrics.METRIC_DOTNET_THREAD_POOL_QUEUE_LENGTH = "dotnet.thread_pool.queue.length"; + stable_metrics.METRIC_DOTNET_THREAD_POOL_THREAD_COUNT = "dotnet.thread_pool.thread.count"; + stable_metrics.METRIC_DOTNET_THREAD_POOL_WORK_ITEM_COUNT = "dotnet.thread_pool.work_item.count"; + stable_metrics.METRIC_DOTNET_TIMER_COUNT = "dotnet.timer.count"; + stable_metrics.METRIC_HTTP_CLIENT_REQUEST_DURATION = "http.client.request.duration"; + stable_metrics.METRIC_HTTP_SERVER_REQUEST_DURATION = "http.server.request.duration"; + stable_metrics.METRIC_JVM_CLASS_COUNT = "jvm.class.count"; + stable_metrics.METRIC_JVM_CLASS_LOADED = "jvm.class.loaded"; + stable_metrics.METRIC_JVM_CLASS_UNLOADED = "jvm.class.unloaded"; + stable_metrics.METRIC_JVM_CPU_COUNT = "jvm.cpu.count"; + stable_metrics.METRIC_JVM_CPU_RECENT_UTILIZATION = "jvm.cpu.recent_utilization"; + stable_metrics.METRIC_JVM_CPU_TIME = "jvm.cpu.time"; + stable_metrics.METRIC_JVM_GC_DURATION = "jvm.gc.duration"; + stable_metrics.METRIC_JVM_MEMORY_COMMITTED = "jvm.memory.committed"; + stable_metrics.METRIC_JVM_MEMORY_LIMIT = "jvm.memory.limit"; + stable_metrics.METRIC_JVM_MEMORY_USED = "jvm.memory.used"; + stable_metrics.METRIC_JVM_MEMORY_USED_AFTER_LAST_GC = "jvm.memory.used_after_last_gc"; + stable_metrics.METRIC_JVM_THREAD_COUNT = "jvm.thread.count"; + stable_metrics.METRIC_KESTREL_ACTIVE_CONNECTIONS = "kestrel.active_connections"; + stable_metrics.METRIC_KESTREL_ACTIVE_TLS_HANDSHAKES = "kestrel.active_tls_handshakes"; + stable_metrics.METRIC_KESTREL_CONNECTION_DURATION = "kestrel.connection.duration"; + stable_metrics.METRIC_KESTREL_QUEUED_CONNECTIONS = "kestrel.queued_connections"; + stable_metrics.METRIC_KESTREL_QUEUED_REQUESTS = "kestrel.queued_requests"; + stable_metrics.METRIC_KESTREL_REJECTED_CONNECTIONS = "kestrel.rejected_connections"; + stable_metrics.METRIC_KESTREL_TLS_HANDSHAKE_DURATION = "kestrel.tls_handshake.duration"; + stable_metrics.METRIC_KESTREL_UPGRADED_CONNECTIONS = "kestrel.upgraded_connections"; + stable_metrics.METRIC_SIGNALR_SERVER_ACTIVE_CONNECTIONS = "signalr.server.active_connections"; + stable_metrics.METRIC_SIGNALR_SERVER_CONNECTION_DURATION = "signalr.server.connection.duration"; + return stable_metrics; +} +var stable_events = {}; +var hasRequiredStable_events; +function requireStable_events() { + if (hasRequiredStable_events) return stable_events; + hasRequiredStable_events = 1; + Object.defineProperty(stable_events, "__esModule", { value: true }); + stable_events.EVENT_EXCEPTION = void 0; + stable_events.EVENT_EXCEPTION = "exception"; + return stable_events; +} +var hasRequiredSrc$m; +function requireSrc$m() { + if (hasRequiredSrc$m) return src$l; + hasRequiredSrc$m = 1; + (function(exports$1) { + var __createBinding = src$l && src$l.__createBinding || (Object.create ? (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m[k]; + } }; + } + Object.defineProperty(o, k2, desc); + }) : (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + o[k2] = m[k]; + })); + var __exportStar = src$l && src$l.__exportStar || function(m, exports$12) { + for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports$12, p)) __createBinding(exports$12, m, p); + }; + Object.defineProperty(exports$1, "__esModule", { value: true }); + __exportStar(/* @__PURE__ */ requireTrace(), exports$1); + __exportStar(/* @__PURE__ */ requireResource(), exports$1); + __exportStar(/* @__PURE__ */ requireStable_attributes(), exports$1); + __exportStar(/* @__PURE__ */ requireStable_metrics(), exports$1); + __exportStar(/* @__PURE__ */ requireStable_events(), exports$1); + })(src$l); + return src$l; +} +var srcExports$k = /* @__PURE__ */ requireSrc$m(); +const ATTR_PROCESS_RUNTIME_NAME = "process.runtime.name"; +const SDK_INFO = { + [srcExports$k.ATTR_TELEMETRY_SDK_NAME]: "opentelemetry", + [ATTR_PROCESS_RUNTIME_NAME]: "node", + [srcExports$k.ATTR_TELEMETRY_SDK_LANGUAGE]: srcExports$k.TELEMETRY_SDK_LANGUAGE_VALUE_NODEJS, + [srcExports$k.ATTR_TELEMETRY_SDK_VERSION]: VERSION$2 +}; +const NANOSECOND_DIGITS = 9; +const NANOSECOND_DIGITS_IN_MILLIS = 6; +const MILLISECONDS_TO_NANOSECONDS = Math.pow(10, NANOSECOND_DIGITS_IN_MILLIS); +const SECOND_TO_NANOSECONDS = Math.pow(10, NANOSECOND_DIGITS); +function millisToHrTime(epochMillis) { + const epochSeconds = epochMillis / 1e3; + const seconds = Math.trunc(epochSeconds); + const nanos = Math.round(epochMillis % 1e3 * MILLISECONDS_TO_NANOSECONDS); + return [seconds, nanos]; +} +function getTimeOrigin() { + let timeOrigin = otperformance.timeOrigin; + if (typeof timeOrigin !== "number") { + const perf = otperformance; + timeOrigin = perf.timing && perf.timing.fetchStart; + } + return timeOrigin; +} +function hrTime(performanceNow) { + const timeOrigin = millisToHrTime(getTimeOrigin()); + const now = millisToHrTime(typeof performanceNow === "number" ? performanceNow : otperformance.now()); + return addHrTimes(timeOrigin, now); +} +function timeInputToHrTime(time) { + if (isTimeInputHrTime(time)) { + return time; + } else if (typeof time === "number") { + if (time < getTimeOrigin()) { + return hrTime(time); + } else { + return millisToHrTime(time); + } + } else if (time instanceof Date) { + return millisToHrTime(time.getTime()); + } else { + throw TypeError("Invalid input type"); + } +} +function hrTimeDuration(startTime, endTime) { + let seconds = endTime[0] - startTime[0]; + let nanos = endTime[1] - startTime[1]; + if (nanos < 0) { + seconds -= 1; + nanos += SECOND_TO_NANOSECONDS; + } + return [seconds, nanos]; +} +function hrTimeToTimeStamp(time) { + const precision = NANOSECOND_DIGITS; + const tmp = `${"0".repeat(precision)}${time[1]}Z`; + const nanoString = tmp.substring(tmp.length - precision - 1); + const date = new Date(time[0] * 1e3).toISOString(); + return date.replace("000Z", nanoString); +} +function hrTimeToNanoseconds(time) { + return time[0] * SECOND_TO_NANOSECONDS + time[1]; +} +function hrTimeToMilliseconds(time) { + return time[0] * 1e3 + time[1] / 1e6; +} +function hrTimeToMicroseconds(time) { + return time[0] * 1e6 + time[1] / 1e3; +} +function isTimeInputHrTime(value) { + return Array.isArray(value) && value.length === 2 && typeof value[0] === "number" && typeof value[1] === "number"; +} +function isTimeInput(value) { + return isTimeInputHrTime(value) || typeof value === "number" || value instanceof Date; +} +function addHrTimes(time1, time2) { + const out = [time1[0] + time2[0], time1[1] + time2[1]]; + if (out[1] >= SECOND_TO_NANOSECONDS) { + out[1] -= SECOND_TO_NANOSECONDS; + out[0] += 1; + } + return out; +} +function unrefTimer(timer) { + if (typeof timer !== "number") { + timer.unref(); + } +} +var ExportResultCode; +(function(ExportResultCode2) { + ExportResultCode2[ExportResultCode2["SUCCESS"] = 0] = "SUCCESS"; + ExportResultCode2[ExportResultCode2["FAILED"] = 1] = "FAILED"; +})(ExportResultCode || (ExportResultCode = {})); +class CompositePropagator { + _propagators; + _fields; + /** + * Construct a composite propagator from a list of propagators. + * + * @param [config] Configuration object for composite propagator + */ + constructor(config2 = {}) { + this._propagators = config2.propagators ?? []; + this._fields = Array.from(new Set(this._propagators.map((p) => typeof p.fields === "function" ? p.fields() : []).reduce((x, y) => x.concat(y), []))); + } + /** + * Run each of the configured propagators with the given context and carrier. + * Propagators are run in the order they are configured, so if multiple + * propagators write the same carrier key, the propagator later in the list + * will "win". + * + * @param context Context to inject + * @param carrier Carrier into which context will be injected + */ + inject(context2, carrier, setter) { + for (const propagator2 of this._propagators) { + try { + propagator2.inject(context2, carrier, setter); + } catch (err) { + srcExports$l.diag.warn(`Failed to inject with ${propagator2.constructor.name}. Err: ${err.message}`); + } + } + } + /** + * Run each of the configured propagators with the given context and carrier. + * Propagators are run in the order they are configured, so if multiple + * propagators write the same context key, the propagator later in the list + * will "win". + * + * @param context Context to add values to + * @param carrier Carrier from which to extract context + */ + extract(context2, carrier, getter) { + return this._propagators.reduce((ctx, propagator2) => { + try { + return propagator2.extract(ctx, carrier, getter); + } catch (err) { + srcExports$l.diag.warn(`Failed to extract with ${propagator2.constructor.name}. Err: ${err.message}`); + } + return ctx; + }, context2); + } + fields() { + return this._fields.slice(); + } +} +const VALID_KEY_CHAR_RANGE = "[_0-9a-z-*/]"; +const VALID_KEY = `[a-z]${VALID_KEY_CHAR_RANGE}{0,255}`; +const VALID_VENDOR_KEY = `[a-z0-9]${VALID_KEY_CHAR_RANGE}{0,240}@[a-z]${VALID_KEY_CHAR_RANGE}{0,13}`; +const VALID_KEY_REGEX = new RegExp(`^(?:${VALID_KEY}|${VALID_VENDOR_KEY})$`); +const VALID_VALUE_BASE_REGEX = /^[ -~]{0,255}[!-~]$/; +const INVALID_VALUE_COMMA_EQUAL_REGEX = /,|=/; +function validateKey(key) { + return VALID_KEY_REGEX.test(key); +} +function validateValue(value) { + return VALID_VALUE_BASE_REGEX.test(value) && !INVALID_VALUE_COMMA_EQUAL_REGEX.test(value); +} +const MAX_TRACE_STATE_ITEMS = 32; +const MAX_TRACE_STATE_LEN = 512; +const LIST_MEMBERS_SEPARATOR = ","; +const LIST_MEMBER_KEY_VALUE_SPLITTER = "="; +class TraceState { + _internalState = /* @__PURE__ */ new Map(); + constructor(rawTraceState) { + if (rawTraceState) + this._parse(rawTraceState); + } + set(key, value) { + const traceState = this._clone(); + if (traceState._internalState.has(key)) { + traceState._internalState.delete(key); + } + traceState._internalState.set(key, value); + return traceState; + } + unset(key) { + const traceState = this._clone(); + traceState._internalState.delete(key); + return traceState; + } + get(key) { + return this._internalState.get(key); + } + serialize() { + return this._keys().reduce((agg, key) => { + agg.push(key + LIST_MEMBER_KEY_VALUE_SPLITTER + this.get(key)); + return agg; + }, []).join(LIST_MEMBERS_SEPARATOR); + } + _parse(rawTraceState) { + if (rawTraceState.length > MAX_TRACE_STATE_LEN) + return; + this._internalState = rawTraceState.split(LIST_MEMBERS_SEPARATOR).reverse().reduce((agg, part) => { + const listMember = part.trim(); + const i = listMember.indexOf(LIST_MEMBER_KEY_VALUE_SPLITTER); + if (i !== -1) { + const key = listMember.slice(0, i); + const value = listMember.slice(i + 1, part.length); + if (validateKey(key) && validateValue(value)) { + agg.set(key, value); + } + } + return agg; + }, /* @__PURE__ */ new Map()); + if (this._internalState.size > MAX_TRACE_STATE_ITEMS) { + this._internalState = new Map(Array.from(this._internalState.entries()).reverse().slice(0, MAX_TRACE_STATE_ITEMS)); + } + } + _keys() { + return Array.from(this._internalState.keys()).reverse(); + } + _clone() { + const traceState = new TraceState(); + traceState._internalState = new Map(this._internalState); + return traceState; + } +} +const TRACE_PARENT_HEADER = "traceparent"; +const TRACE_STATE_HEADER = "tracestate"; +const VERSION$1 = "00"; +const VERSION_PART = "(?!ff)[\\da-f]{2}"; +const TRACE_ID_PART = "(?![0]{32})[\\da-f]{32}"; +const PARENT_ID_PART = "(?![0]{16})[\\da-f]{16}"; +const FLAGS_PART = "[\\da-f]{2}"; +const TRACE_PARENT_REGEX = new RegExp(`^\\s?(${VERSION_PART})-(${TRACE_ID_PART})-(${PARENT_ID_PART})-(${FLAGS_PART})(-.*)?\\s?$`); +function parseTraceParent(traceParent) { + const match2 = TRACE_PARENT_REGEX.exec(traceParent); + if (!match2) + return null; + if (match2[1] === "00" && match2[5]) + return null; + return { + traceId: match2[2], + spanId: match2[3], + traceFlags: parseInt(match2[4], 16) + }; +} +class W3CTraceContextPropagator { + inject(context2, carrier, setter) { + const spanContext = srcExports$l.trace.getSpanContext(context2); + if (!spanContext || isTracingSuppressed(context2) || !srcExports$l.isSpanContextValid(spanContext)) + return; + const traceParent = `${VERSION$1}-${spanContext.traceId}-${spanContext.spanId}-0${Number(spanContext.traceFlags || srcExports$l.TraceFlags.NONE).toString(16)}`; + setter.set(carrier, TRACE_PARENT_HEADER, traceParent); + if (spanContext.traceState) { + setter.set(carrier, TRACE_STATE_HEADER, spanContext.traceState.serialize()); + } + } + extract(context2, carrier, getter) { + const traceParentHeader = getter.get(carrier, TRACE_PARENT_HEADER); + if (!traceParentHeader) + return context2; + const traceParent = Array.isArray(traceParentHeader) ? traceParentHeader[0] : traceParentHeader; + if (typeof traceParent !== "string") + return context2; + const spanContext = parseTraceParent(traceParent); + if (!spanContext) + return context2; + spanContext.isRemote = true; + const traceStateHeader = getter.get(carrier, TRACE_STATE_HEADER); + if (traceStateHeader) { + const state = Array.isArray(traceStateHeader) ? traceStateHeader.join(",") : traceStateHeader; + spanContext.traceState = new TraceState(typeof state === "string" ? state : void 0); + } + return srcExports$l.trace.setSpanContext(context2, spanContext); + } + fields() { + return [TRACE_PARENT_HEADER, TRACE_STATE_HEADER]; + } +} +const RPC_METADATA_KEY = srcExports$l.createContextKey("OpenTelemetry SDK Context Key RPC_METADATA"); +var RPCType; +(function(RPCType2) { + RPCType2["HTTP"] = "http"; +})(RPCType || (RPCType = {})); +function setRPCMetadata(context2, meta) { + return context2.setValue(RPC_METADATA_KEY, meta); +} +function deleteRPCMetadata(context2) { + return context2.deleteValue(RPC_METADATA_KEY); +} +function getRPCMetadata(context2) { + return context2.getValue(RPC_METADATA_KEY); +} +const objectTag = "[object Object]"; +const nullTag = "[object Null]"; +const undefinedTag = "[object Undefined]"; +const funcProto = Function.prototype; +const funcToString = funcProto.toString; +const objectCtorString = funcToString.call(Object); +const getPrototypeOf = Object.getPrototypeOf; +const objectProto = Object.prototype; +const hasOwnProperty = objectProto.hasOwnProperty; +const symToStringTag = Symbol ? Symbol.toStringTag : void 0; +const nativeObjectToString = objectProto.toString; +function isPlainObject(value) { + if (!isObjectLike(value) || baseGetTag(value) !== objectTag) { + return false; + } + const proto = getPrototypeOf(value); + if (proto === null) { + return true; + } + const Ctor = hasOwnProperty.call(proto, "constructor") && proto.constructor; + return typeof Ctor == "function" && Ctor instanceof Ctor && funcToString.call(Ctor) === objectCtorString; +} +function isObjectLike(value) { + return value != null && typeof value == "object"; +} +function baseGetTag(value) { + if (value == null) { + return value === void 0 ? undefinedTag : nullTag; + } + return symToStringTag && symToStringTag in Object(value) ? getRawTag(value) : objectToString(value); +} +function getRawTag(value) { + const isOwn = hasOwnProperty.call(value, symToStringTag), tag = value[symToStringTag]; + let unmasked = false; + try { + value[symToStringTag] = void 0; + unmasked = true; + } catch { + } + const result = nativeObjectToString.call(value); + if (unmasked) { + if (isOwn) { + value[symToStringTag] = tag; + } else { + delete value[symToStringTag]; + } + } + return result; +} +function objectToString(value) { + return nativeObjectToString.call(value); +} +const MAX_LEVEL = 20; +function merge(...args) { + let result = args.shift(); + const objects = /* @__PURE__ */ new WeakMap(); + while (args.length > 0) { + result = mergeTwoObjects(result, args.shift(), 0, objects); + } + return result; +} +function takeValue(value) { + if (isArray(value)) { + return value.slice(); + } + return value; +} +function mergeTwoObjects(one, two, level = 0, objects) { + let result; + if (level > MAX_LEVEL) { + return void 0; + } + level++; + if (isPrimitive(one) || isPrimitive(two) || isFunction(two)) { + result = takeValue(two); + } else if (isArray(one)) { + result = one.slice(); + if (isArray(two)) { + for (let i = 0, j = two.length; i < j; i++) { + result.push(takeValue(two[i])); + } + } else if (isObject(two)) { + const keys = Object.keys(two); + for (let i = 0, j = keys.length; i < j; i++) { + const key = keys[i]; + result[key] = takeValue(two[key]); + } + } + } else if (isObject(one)) { + if (isObject(two)) { + if (!shouldMerge(one, two)) { + return two; + } + result = Object.assign({}, one); + const keys = Object.keys(two); + for (let i = 0, j = keys.length; i < j; i++) { + const key = keys[i]; + const twoValue = two[key]; + if (isPrimitive(twoValue)) { + if (typeof twoValue === "undefined") { + delete result[key]; + } else { + result[key] = twoValue; + } + } else { + const obj1 = result[key]; + const obj2 = twoValue; + if (wasObjectReferenced(one, key, objects) || wasObjectReferenced(two, key, objects)) { + delete result[key]; + } else { + if (isObject(obj1) && isObject(obj2)) { + const arr1 = objects.get(obj1) || []; + const arr2 = objects.get(obj2) || []; + arr1.push({ obj: one, key }); + arr2.push({ obj: two, key }); + objects.set(obj1, arr1); + objects.set(obj2, arr2); + } + result[key] = mergeTwoObjects(result[key], twoValue, level, objects); + } + } + } + } else { + result = two; + } + } + return result; +} +function wasObjectReferenced(obj, key, objects) { + const arr = objects.get(obj[key]) || []; + for (let i = 0, j = arr.length; i < j; i++) { + const info = arr[i]; + if (info.key === key && info.obj === obj) { + return true; + } + } + return false; +} +function isArray(value) { + return Array.isArray(value); +} +function isFunction(value) { + return typeof value === "function"; +} +function isObject(value) { + return !isPrimitive(value) && !isArray(value) && !isFunction(value) && typeof value === "object"; +} +function isPrimitive(value) { + return typeof value === "string" || typeof value === "number" || typeof value === "boolean" || typeof value === "undefined" || value instanceof Date || value instanceof RegExp || value === null; +} +function shouldMerge(one, two) { + if (!isPlainObject(one) || !isPlainObject(two)) { + return false; + } + return true; +} +class TimeoutError extends Error { + constructor(message) { + super(message); + Object.setPrototypeOf(this, TimeoutError.prototype); + } +} +function callWithTimeout(promise, timeout) { + let timeoutHandle; + const timeoutPromise = new Promise(function timeoutFunction(_resolve, reject) { + timeoutHandle = setTimeout(function timeoutHandler() { + reject(new TimeoutError("Operation timed out.")); + }, timeout); + }); + return Promise.race([promise, timeoutPromise]).then((result) => { + clearTimeout(timeoutHandle); + return result; + }, (reason) => { + clearTimeout(timeoutHandle); + throw reason; + }); +} +function urlMatches(url, urlToMatch) { + if (typeof urlToMatch === "string") { + return url === urlToMatch; + } else { + return !!url.match(urlToMatch); + } +} +function isUrlIgnored(url, ignoredUrls) { + if (!ignoredUrls) { + return false; + } + for (const ignoreUrl of ignoredUrls) { + if (urlMatches(url, ignoreUrl)) { + return true; + } + } + return false; +} +class Deferred { + _promise; + _resolve; + _reject; + constructor() { + this._promise = new Promise((resolve, reject) => { + this._resolve = resolve; + this._reject = reject; + }); + } + get promise() { + return this._promise; + } + resolve(val) { + this._resolve(val); + } + reject(err) { + this._reject(err); + } +} +class BindOnceFuture { + _callback; + _that; + _isCalled = false; + _deferred = new Deferred(); + constructor(_callback, _that) { + this._callback = _callback; + this._that = _that; + } + get isCalled() { + return this._isCalled; + } + get promise() { + return this._deferred.promise; + } + call(...args) { + if (!this._isCalled) { + this._isCalled = true; + try { + Promise.resolve(this._callback.call(this._that, ...args)).then((val) => this._deferred.resolve(val), (err) => this._deferred.reject(err)); + } catch (err) { + this._deferred.reject(err); + } + } + return this._deferred.promise; + } +} +const logLevelMap = { + ALL: srcExports$l.DiagLogLevel.ALL, + VERBOSE: srcExports$l.DiagLogLevel.VERBOSE, + DEBUG: srcExports$l.DiagLogLevel.DEBUG, + INFO: srcExports$l.DiagLogLevel.INFO, + WARN: srcExports$l.DiagLogLevel.WARN, + ERROR: srcExports$l.DiagLogLevel.ERROR, + NONE: srcExports$l.DiagLogLevel.NONE +}; +function diagLogLevelFromString(value) { + if (value == null) { + return void 0; + } + const resolvedLogLevel = logLevelMap[value.toUpperCase()]; + if (resolvedLogLevel == null) { + srcExports$l.diag.warn(`Unknown log level "${value}", expected one of ${Object.keys(logLevelMap)}, using default`); + return srcExports$l.DiagLogLevel.INFO; + } + return resolvedLogLevel; +} +function _export(exporter, arg) { + return new Promise((resolve) => { + srcExports$l.context.with(suppressTracing$1(srcExports$l.context.active()), () => { + exporter.export(arg, (result) => { + resolve(result); + }); + }); + }); +} +const internal = { + _export +}; +const esm$1 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ + __proto__: null, + AnchoredClock, + BindOnceFuture, + CompositePropagator, + get ExportResultCode() { + return ExportResultCode; + }, + get RPCType() { + return RPCType; + }, + SDK_INFO, + TRACE_PARENT_HEADER, + TRACE_STATE_HEADER, + TimeoutError, + TraceState, + W3CBaggagePropagator, + W3CTraceContextPropagator, + _globalThis: _globalThis$1, + addHrTimes, + callWithTimeout, + deleteRPCMetadata, + diagLogLevelFromString, + getBooleanFromEnv, + getNumberFromEnv, + getRPCMetadata, + getStringFromEnv, + getStringListFromEnv, + getTimeOrigin, + globalErrorHandler, + hrTime, + hrTimeDuration, + hrTimeToMicroseconds, + hrTimeToMilliseconds, + hrTimeToNanoseconds, + hrTimeToTimeStamp, + internal, + isAttributeValue, + isTimeInput, + isTimeInputHrTime, + isTracingSuppressed, + isUrlIgnored, + loggingErrorHandler, + merge, + millisToHrTime, + otperformance, + parseKeyPairsIntoRecord, + parseTraceParent, + sanitizeAttributes, + setGlobalErrorHandler, + setRPCMetadata, + suppressTracing: suppressTracing$1, + timeInputToHrTime, + unrefTimer, + unsuppressTracing, + urlMatches +}, Symbol.toStringTag, { value: "Module" })); +const require$$1 = /* @__PURE__ */ getAugmentedNamespace(esm$1); +var version$i = {}; +var hasRequiredVersion$i; +function requireVersion$i() { + if (hasRequiredVersion$i) return version$i; + hasRequiredVersion$i = 1; + Object.defineProperty(version$i, "__esModule", { value: true }); + version$i.VERSION = void 0; + version$i.VERSION = "0.208.0"; + return version$i; +} +class NoopLogger { + emit(_logRecord) { + } +} +const NOOP_LOGGER = new NoopLogger(); +class NoopLoggerProvider { + getLogger(_name, _version, _options) { + return new NoopLogger(); + } +} +const NOOP_LOGGER_PROVIDER = new NoopLoggerProvider(); +class ProxyLogger { + constructor(_provider, name, version2, options) { + this._provider = _provider; + this.name = name; + this.version = version2; + this.options = options; + } + /** + * Emit a log record. This method should only be used by log appenders. + * + * @param logRecord + */ + emit(logRecord) { + this._getLogger().emit(logRecord); + } + /** + * Try to get a logger from the proxy logger provider. + * If the proxy logger provider has no delegate, return a noop logger. + */ + _getLogger() { + if (this._delegate) { + return this._delegate; + } + const logger2 = this._provider._getDelegateLogger(this.name, this.version, this.options); + if (!logger2) { + return NOOP_LOGGER; + } + this._delegate = logger2; + return this._delegate; + } +} +class ProxyLoggerProvider { + getLogger(name, version2, options) { + var _a; + return (_a = this._getDelegateLogger(name, version2, options)) !== null && _a !== void 0 ? _a : new ProxyLogger(this, name, version2, options); + } + /** + * Get the delegate logger provider. + * Used by tests only. + * @internal + */ + _getDelegate() { + var _a; + return (_a = this._delegate) !== null && _a !== void 0 ? _a : NOOP_LOGGER_PROVIDER; + } + /** + * Set the delegate logger provider + * @internal + */ + _setDelegate(delegate) { + this._delegate = delegate; + } + /** + * @internal + */ + _getDelegateLogger(name, version2, options) { + var _a; + return (_a = this._delegate) === null || _a === void 0 ? void 0 : _a.getLogger(name, version2, options); + } +} +const _globalThis = typeof globalThis === "object" ? globalThis : global; +const GLOBAL_LOGS_API_KEY = Symbol.for("io.opentelemetry.js.api.logs"); +const _global = _globalThis; +function makeGetter(requiredVersion, instance, fallback) { + return (version2) => version2 === requiredVersion ? instance : fallback; +} +const API_BACKWARDS_COMPATIBILITY_VERSION = 1; +class LogsAPI { + constructor() { + this._proxyLoggerProvider = new ProxyLoggerProvider(); + } + static getInstance() { + if (!this._instance) { + this._instance = new LogsAPI(); + } + return this._instance; + } + setGlobalLoggerProvider(provider) { + if (_global[GLOBAL_LOGS_API_KEY]) { + return this.getLoggerProvider(); + } + _global[GLOBAL_LOGS_API_KEY] = makeGetter(API_BACKWARDS_COMPATIBILITY_VERSION, provider, NOOP_LOGGER_PROVIDER); + this._proxyLoggerProvider._setDelegate(provider); + return provider; + } + /** + * Returns the global logger provider. + * + * @returns LoggerProvider + */ + getLoggerProvider() { + var _a, _b; + return (_b = (_a = _global[GLOBAL_LOGS_API_KEY]) === null || _a === void 0 ? void 0 : _a.call(_global, API_BACKWARDS_COMPATIBILITY_VERSION)) !== null && _b !== void 0 ? _b : this._proxyLoggerProvider; + } + /** + * Returns a logger from the global logger provider. + * + * @returns Logger + */ + getLogger(name, version2, options) { + return this.getLoggerProvider().getLogger(name, version2, options); + } + /** Remove the global logger provider */ + disable() { + delete _global[GLOBAL_LOGS_API_KEY]; + this._proxyLoggerProvider = new ProxyLoggerProvider(); + } +} +const logs = LogsAPI.getInstance(); +function enableInstrumentations(instrumentations, tracerProvider, meterProvider, loggerProvider) { + for (let i = 0, j = instrumentations.length; i < j; i++) { + const instrumentation2 = instrumentations[i]; + if (tracerProvider) { + instrumentation2.setTracerProvider(tracerProvider); + } + if (meterProvider) { + instrumentation2.setMeterProvider(meterProvider); + } + if (loggerProvider && instrumentation2.setLoggerProvider) { + instrumentation2.setLoggerProvider(loggerProvider); + } + if (!instrumentation2.getConfig().enabled) { + instrumentation2.enable(); + } + } +} +function disableInstrumentations(instrumentations) { + instrumentations.forEach((instrumentation2) => instrumentation2.disable()); +} +function registerInstrumentations(options) { + const tracerProvider = options.tracerProvider || srcExports$l.trace.getTracerProvider(); + const meterProvider = options.meterProvider || srcExports$l.metrics.getMeterProvider(); + const loggerProvider = options.loggerProvider || logs.getLoggerProvider(); + const instrumentations = options.instrumentations?.flat() ?? []; + enableInstrumentations(instrumentations, tracerProvider, meterProvider, loggerProvider); + return () => { + disableInstrumentations(instrumentations); + }; +} +const VERSION_REGEXP = /^(?:v)?(?(?0|[1-9]\d*)\.(?0|[1-9]\d*)\.(?0|[1-9]\d*))(?:-(?(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\+(?[0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*))?$/; +const RANGE_REGEXP = /^(?<|>|=|==|<=|>=|~|\^|~>)?\s*(?:v)?(?(?x|X|\*|0|[1-9]\d*)(?:\.(?x|X|\*|0|[1-9]\d*))?(?:\.(?x|X|\*|0|[1-9]\d*))?)(?:-(?(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\+(?[0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*))?$/; +const operatorResMap = { + ">": [1], + ">=": [0, 1], + "=": [0], + "<=": [-1, 0], + "<": [-1], + "!=": [-1, 1] +}; +function satisfies(version2, range, options) { + if (!_validateVersion(version2)) { + srcExports$l.diag.error(`Invalid version: ${version2}`); + return false; + } + if (!range) { + return true; + } + range = range.replace(/([<>=~^]+)\s+/g, "$1"); + const parsedVersion = _parseVersion(version2); + if (!parsedVersion) { + return false; + } + const allParsedRanges = []; + const checkResult = _doSatisfies(parsedVersion, range, allParsedRanges, options); + if (checkResult && !options?.includePrerelease) { + return _doPreleaseCheck(parsedVersion, allParsedRanges); + } + return checkResult; +} +function _validateVersion(version2) { + return typeof version2 === "string" && VERSION_REGEXP.test(version2); +} +function _doSatisfies(parsedVersion, range, allParsedRanges, options) { + if (range.includes("||")) { + const ranges = range.trim().split("||"); + for (const r of ranges) { + if (_checkRange(parsedVersion, r, allParsedRanges, options)) { + return true; + } + } + return false; + } else if (range.includes(" - ")) { + range = replaceHyphen(range, options); + } else if (range.includes(" ")) { + const ranges = range.trim().replace(/\s{2,}/g, " ").split(" "); + for (const r of ranges) { + if (!_checkRange(parsedVersion, r, allParsedRanges, options)) { + return false; + } + } + return true; + } + return _checkRange(parsedVersion, range, allParsedRanges, options); +} +function _checkRange(parsedVersion, range, allParsedRanges, options) { + range = _normalizeRange(range, options); + if (range.includes(" ")) { + return _doSatisfies(parsedVersion, range, allParsedRanges, options); + } else { + const parsedRange = _parseRange(range); + allParsedRanges.push(parsedRange); + return _satisfies(parsedVersion, parsedRange); + } +} +function _satisfies(parsedVersion, parsedRange) { + if (parsedRange.invalid) { + return false; + } + if (!parsedRange.version || _isWildcard(parsedRange.version)) { + return true; + } + let comparisonResult = _compareVersionSegments(parsedVersion.versionSegments || [], parsedRange.versionSegments || []); + if (comparisonResult === 0) { + const versionPrereleaseSegments = parsedVersion.prereleaseSegments || []; + const rangePrereleaseSegments = parsedRange.prereleaseSegments || []; + if (!versionPrereleaseSegments.length && !rangePrereleaseSegments.length) { + comparisonResult = 0; + } else if (!versionPrereleaseSegments.length && rangePrereleaseSegments.length) { + comparisonResult = 1; + } else if (versionPrereleaseSegments.length && !rangePrereleaseSegments.length) { + comparisonResult = -1; + } else { + comparisonResult = _compareVersionSegments(versionPrereleaseSegments, rangePrereleaseSegments); + } + } + return operatorResMap[parsedRange.op]?.includes(comparisonResult); +} +function _doPreleaseCheck(parsedVersion, allParsedRanges) { + if (parsedVersion.prerelease) { + return allParsedRanges.some((r) => r.prerelease && r.version === parsedVersion.version); + } + return true; +} +function _normalizeRange(range, options) { + range = range.trim(); + range = replaceCaret(range, options); + range = replaceTilde(range); + range = replaceXRange(range, options); + range = range.trim(); + return range; +} +function isX(id) { + return !id || id.toLowerCase() === "x" || id === "*"; +} +function _parseVersion(versionString) { + const match2 = versionString.match(VERSION_REGEXP); + if (!match2) { + srcExports$l.diag.error(`Invalid version: ${versionString}`); + return void 0; + } + const version2 = match2.groups.version; + const prerelease = match2.groups.prerelease; + const build = match2.groups.build; + const versionSegments = version2.split("."); + const prereleaseSegments = prerelease?.split("."); + return { + op: void 0, + version: version2, + versionSegments, + versionSegmentCount: versionSegments.length, + prerelease, + prereleaseSegments, + prereleaseSegmentCount: prereleaseSegments ? prereleaseSegments.length : 0, + build + }; +} +function _parseRange(rangeString) { + if (!rangeString) { + return {}; + } + const match2 = rangeString.match(RANGE_REGEXP); + if (!match2) { + srcExports$l.diag.error(`Invalid range: ${rangeString}`); + return { + invalid: true + }; + } + let op = match2.groups.op; + const version2 = match2.groups.version; + const prerelease = match2.groups.prerelease; + const build = match2.groups.build; + const versionSegments = version2.split("."); + const prereleaseSegments = prerelease?.split("."); + if (op === "==") { + op = "="; + } + return { + op: op || "=", + version: version2, + versionSegments, + versionSegmentCount: versionSegments.length, + prerelease, + prereleaseSegments, + prereleaseSegmentCount: prereleaseSegments ? prereleaseSegments.length : 0, + build + }; +} +function _isWildcard(s) { + return s === "*" || s === "x" || s === "X"; +} +function _parseVersionString(v) { + const n = parseInt(v, 10); + return isNaN(n) ? v : n; +} +function _normalizeVersionType(a, b) { + if (typeof a === typeof b) { + if (typeof a === "number") { + return [a, b]; + } else if (typeof a === "string") { + return [a, b]; + } else { + throw new Error("Version segments can only be strings or numbers"); + } + } else { + return [String(a), String(b)]; + } +} +function _compareVersionStrings(v1, v2) { + if (_isWildcard(v1) || _isWildcard(v2)) { + return 0; + } + const [parsedV1, parsedV2] = _normalizeVersionType(_parseVersionString(v1), _parseVersionString(v2)); + if (parsedV1 > parsedV2) { + return 1; + } else if (parsedV1 < parsedV2) { + return -1; + } + return 0; +} +function _compareVersionSegments(v1, v2) { + for (let i = 0; i < Math.max(v1.length, v2.length); i++) { + const res = _compareVersionStrings(v1[i] || "0", v2[i] || "0"); + if (res !== 0) { + return res; + } + } + return 0; +} +const LETTERDASHNUMBER = "[a-zA-Z0-9-]"; +const NUMERICIDENTIFIER = "0|[1-9]\\d*"; +const NONNUMERICIDENTIFIER = `\\d*[a-zA-Z-]${LETTERDASHNUMBER}*`; +const GTLT = "((?:<|>)?=?)"; +const PRERELEASEIDENTIFIER = `(?:${NUMERICIDENTIFIER}|${NONNUMERICIDENTIFIER})`; +const PRERELEASE = `(?:-(${PRERELEASEIDENTIFIER}(?:\\.${PRERELEASEIDENTIFIER})*))`; +const BUILDIDENTIFIER = `${LETTERDASHNUMBER}+`; +const BUILD = `(?:\\+(${BUILDIDENTIFIER}(?:\\.${BUILDIDENTIFIER})*))`; +const XRANGEIDENTIFIER = `${NUMERICIDENTIFIER}|x|X|\\*`; +const XRANGEPLAIN = `[v=\\s]*(${XRANGEIDENTIFIER})(?:\\.(${XRANGEIDENTIFIER})(?:\\.(${XRANGEIDENTIFIER})(?:${PRERELEASE})?${BUILD}?)?)?`; +const XRANGE = `^${GTLT}\\s*${XRANGEPLAIN}$`; +const XRANGE_REGEXP = new RegExp(XRANGE); +const HYPHENRANGE = `^\\s*(${XRANGEPLAIN})\\s+-\\s+(${XRANGEPLAIN})\\s*$`; +const HYPHENRANGE_REGEXP = new RegExp(HYPHENRANGE); +const LONETILDE = "(?:~>?)"; +const TILDE = `^${LONETILDE}${XRANGEPLAIN}$`; +const TILDE_REGEXP = new RegExp(TILDE); +const LONECARET = "(?:\\^)"; +const CARET = `^${LONECARET}${XRANGEPLAIN}$`; +const CARET_REGEXP = new RegExp(CARET); +function replaceTilde(comp) { + const r = TILDE_REGEXP; + return comp.replace(r, (_, M, m, p, pr) => { + let ret; + if (isX(M)) { + ret = ""; + } else if (isX(m)) { + ret = `>=${M}.0.0 <${+M + 1}.0.0-0`; + } else if (isX(p)) { + ret = `>=${M}.${m}.0 <${M}.${+m + 1}.0-0`; + } else if (pr) { + ret = `>=${M}.${m}.${p}-${pr} <${M}.${+m + 1}.0-0`; + } else { + ret = `>=${M}.${m}.${p} <${M}.${+m + 1}.0-0`; + } + return ret; + }); +} +function replaceCaret(comp, options) { + const r = CARET_REGEXP; + const z = options?.includePrerelease ? "-0" : ""; + return comp.replace(r, (_, M, m, p, pr) => { + let ret; + if (isX(M)) { + ret = ""; + } else if (isX(m)) { + ret = `>=${M}.0.0${z} <${+M + 1}.0.0-0`; + } else if (isX(p)) { + if (M === "0") { + ret = `>=${M}.${m}.0${z} <${M}.${+m + 1}.0-0`; + } else { + ret = `>=${M}.${m}.0${z} <${+M + 1}.0.0-0`; + } + } else if (pr) { + if (M === "0") { + if (m === "0") { + ret = `>=${M}.${m}.${p}-${pr} <${M}.${m}.${+p + 1}-0`; + } else { + ret = `>=${M}.${m}.${p}-${pr} <${M}.${+m + 1}.0-0`; + } + } else { + ret = `>=${M}.${m}.${p}-${pr} <${+M + 1}.0.0-0`; + } + } else { + if (M === "0") { + if (m === "0") { + ret = `>=${M}.${m}.${p}${z} <${M}.${m}.${+p + 1}-0`; + } else { + ret = `>=${M}.${m}.${p}${z} <${M}.${+m + 1}.0-0`; + } + } else { + ret = `>=${M}.${m}.${p} <${+M + 1}.0.0-0`; + } + } + return ret; + }); +} +function replaceXRange(comp, options) { + const r = XRANGE_REGEXP; + return comp.replace(r, (ret, gtlt, M, m, p, pr) => { + const xM = isX(M); + const xm = xM || isX(m); + const xp = xm || isX(p); + const anyX = xp; + if (gtlt === "=" && anyX) { + gtlt = ""; + } + pr = options?.includePrerelease ? "-0" : ""; + if (xM) { + if (gtlt === ">" || gtlt === "<") { + ret = "<0.0.0-0"; + } else { + ret = "*"; + } + } else if (gtlt && anyX) { + if (xm) { + m = 0; + } + p = 0; + if (gtlt === ">") { + gtlt = ">="; + if (xm) { + M = +M + 1; + m = 0; + p = 0; + } else { + m = +m + 1; + p = 0; + } + } else if (gtlt === "<=") { + gtlt = "<"; + if (xm) { + M = +M + 1; + } else { + m = +m + 1; + } + } + if (gtlt === "<") { + pr = "-0"; + } + ret = `${gtlt + M}.${m}.${p}${pr}`; + } else if (xm) { + ret = `>=${M}.0.0${pr} <${+M + 1}.0.0-0`; + } else if (xp) { + ret = `>=${M}.${m}.0${pr} <${M}.${+m + 1}.0-0`; + } + return ret; + }); +} +function replaceHyphen(comp, options) { + const r = HYPHENRANGE_REGEXP; + return comp.replace(r, (_, from, fM, fm, fp, fpr, fb, to, tM, tm, tp, tpr) => { + if (isX(fM)) { + from = ""; + } else if (isX(fm)) { + from = `>=${fM}.0.0${options?.includePrerelease ? "-0" : ""}`; + } else if (isX(fp)) { + from = `>=${fM}.${fm}.0${options?.includePrerelease ? "-0" : ""}`; + } else if (fpr) { + from = `>=${from}`; + } else { + from = `>=${from}${options?.includePrerelease ? "-0" : ""}`; + } + if (isX(tM)) { + to = ""; + } else if (isX(tm)) { + to = `<${+tM + 1}.0.0-0`; + } else if (isX(tp)) { + to = `<${tM}.${+tm + 1}.0-0`; + } else if (tpr) { + to = `<=${tM}.${tm}.${tp}-${tpr}`; + } else if (options?.includePrerelease) { + to = `<${tM}.${tm}.${+tp + 1}-0`; + } else { + to = `<=${to}`; + } + return `${from} ${to}`.trim(); + }); +} +let logger = console.error.bind(console); +function defineProperty(obj, name, value) { + const enumerable = !!obj[name] && Object.prototype.propertyIsEnumerable.call(obj, name); + Object.defineProperty(obj, name, { + configurable: true, + enumerable, + writable: true, + value + }); +} +const wrap = (nodule, name, wrapper) => { + if (!nodule || !nodule[name]) { + logger("no original function " + String(name) + " to wrap"); + return; + } + if (!wrapper) { + logger("no wrapper function"); + logger(new Error().stack); + return; + } + const original = nodule[name]; + if (typeof original !== "function" || typeof wrapper !== "function") { + logger("original object and wrapper must be functions"); + return; + } + const wrapped = wrapper(original, name); + defineProperty(wrapped, "__original", original); + defineProperty(wrapped, "__unwrap", () => { + if (nodule[name] === wrapped) { + defineProperty(nodule, name, original); + } + }); + defineProperty(wrapped, "__wrapped", true); + defineProperty(nodule, name, wrapped); + return wrapped; +}; +const massWrap = (nodules, names2, wrapper) => { + if (!nodules) { + logger("must provide one or more modules to patch"); + logger(new Error().stack); + return; + } else if (!Array.isArray(nodules)) { + nodules = [nodules]; + } + if (!(names2 && Array.isArray(names2))) { + logger("must provide one or more functions to wrap on modules"); + return; + } + nodules.forEach((nodule) => { + names2.forEach((name) => { + wrap(nodule, name, wrapper); + }); + }); +}; +const unwrap = (nodule, name) => { + if (!nodule || !nodule[name]) { + logger("no function to unwrap."); + logger(new Error().stack); + return; + } + const wrapped = nodule[name]; + if (!wrapped.__unwrap) { + logger("no original to unwrap to -- has " + String(name) + " already been unwrapped?"); + } else { + wrapped.__unwrap(); + return; + } +}; +const massUnwrap = (nodules, names2) => { + if (!nodules) { + logger("must provide one or more modules to patch"); + logger(new Error().stack); + return; + } else if (!Array.isArray(nodules)) { + nodules = [nodules]; + } + if (!(names2 && Array.isArray(names2))) { + logger("must provide one or more functions to unwrap on modules"); + return; + } + nodules.forEach((nodule) => { + names2.forEach((name) => { + unwrap(nodule, name); + }); + }); +}; +class InstrumentationAbstract { + instrumentationName; + instrumentationVersion; + _config = {}; + _tracer; + _meter; + _logger; + _diag; + constructor(instrumentationName, instrumentationVersion, config2) { + this.instrumentationName = instrumentationName; + this.instrumentationVersion = instrumentationVersion; + this.setConfig(config2); + this._diag = srcExports$l.diag.createComponentLogger({ + namespace: instrumentationName + }); + this._tracer = srcExports$l.trace.getTracer(instrumentationName, instrumentationVersion); + this._meter = srcExports$l.metrics.getMeter(instrumentationName, instrumentationVersion); + this._logger = logs.getLogger(instrumentationName, instrumentationVersion); + this._updateMetricInstruments(); + } + /* Api to wrap instrumented method */ + _wrap = wrap; + /* Api to unwrap instrumented methods */ + _unwrap = unwrap; + /* Api to mass wrap instrumented method */ + _massWrap = massWrap; + /* Api to mass unwrap instrumented methods */ + _massUnwrap = massUnwrap; + /* Returns meter */ + get meter() { + return this._meter; + } + /** + * Sets MeterProvider to this plugin + * @param meterProvider + */ + setMeterProvider(meterProvider) { + this._meter = meterProvider.getMeter(this.instrumentationName, this.instrumentationVersion); + this._updateMetricInstruments(); + } + /* Returns logger */ + get logger() { + return this._logger; + } + /** + * Sets LoggerProvider to this plugin + * @param loggerProvider + */ + setLoggerProvider(loggerProvider) { + this._logger = loggerProvider.getLogger(this.instrumentationName, this.instrumentationVersion); + } + /** + * @experimental + * + * Get module definitions defined by {@link init}. + * This can be used for experimental compile-time instrumentation. + * + * @returns an array of {@link InstrumentationModuleDefinition} + */ + getModuleDefinitions() { + const initResult = this.init() ?? []; + if (!Array.isArray(initResult)) { + return [initResult]; + } + return initResult; + } + /** + * Sets the new metric instruments with the current Meter. + */ + _updateMetricInstruments() { + return; + } + /* Returns InstrumentationConfig */ + getConfig() { + return this._config; + } + /** + * Sets InstrumentationConfig to this plugin + * @param config + */ + setConfig(config2) { + this._config = { + enabled: true, + ...config2 + }; + } + /** + * Sets TraceProvider to this plugin + * @param tracerProvider + */ + setTracerProvider(tracerProvider) { + this._tracer = tracerProvider.getTracer(this.instrumentationName, this.instrumentationVersion); + } + /* Returns tracer */ + get tracer() { + return this._tracer; + } + /** + * Execute span customization hook, if configured, and log any errors. + * Any semantics of the trigger and info are defined by the specific instrumentation. + * @param hookHandler The optional hook handler which the user has configured via instrumentation config + * @param triggerName The name of the trigger for executing the hook for logging purposes + * @param span The span to which the hook should be applied + * @param info The info object to be passed to the hook, with useful data the hook may use + */ + _runSpanCustomizationHook(hookHandler, triggerName, span, info) { + if (!hookHandler) { + return; + } + try { + hookHandler(span, info); + } catch (e) { + this._diag.error(`Error running span customization hook due to exception in handler`, { triggerName }, e); + } + } +} +var requireInTheMiddle = { exports: {} }; +const noop = () => { +}; +const debug = () => console.debug; +const coerce = noop; +const disable = noop; +const enable = noop; +const enabled = noop; +const extend = debug; +const humanize = noop; +const destroy = noop; +const init$3 = noop; +const log$1 = console.debug; +const formatArgs = noop; +const save = noop; +const load = noop; +const useColors = noop; +const colors = []; +const inspectOpts = {}; +const names = []; +const skips = []; +const formatters = {}; +const selectColors = noop; +Object.assign(debug, { + default: debug, + coerce, + disable, + enable, + enabled, + extend, + humanize, + destroy, + init: init$3, + log: log$1, + formatArgs, + save, + load, + useColors, + colors, + inspectOpts, + names, + skips, + formatters, + selectColors +}); +const debug$1 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ + __proto__: null, + coerce, + colors, + default: debug, + destroy, + disable, + enable, + enabled, + extend, + formatArgs, + formatters, + humanize, + init: init$3, + inspectOpts, + load, + log: log$1, + names, + save, + selectColors, + skips, + useColors +}, Symbol.toStringTag, { value: "Module" })); +const require$$4 = /* @__PURE__ */ getAugmentedNamespace(debug$1); +var moduleDetailsFromPath; +var hasRequiredModuleDetailsFromPath; +function requireModuleDetailsFromPath() { + if (hasRequiredModuleDetailsFromPath) return moduleDetailsFromPath; + hasRequiredModuleDetailsFromPath = 1; + var sep2 = path__default.sep; + moduleDetailsFromPath = function(file) { + var segments = file.split(sep2); + var index = segments.lastIndexOf("node_modules"); + if (index === -1) return; + if (!segments[index + 1]) return; + var scoped = segments[index + 1][0] === "@"; + var name = scoped ? segments[index + 1] + "/" + segments[index + 2] : segments[index + 1]; + var offset = scoped ? 3 : 2; + var basedir = ""; + var lastBaseDirSegmentIndex = index + offset - 1; + for (var i = 0; i <= lastBaseDirSegmentIndex; i++) { + if (i === lastBaseDirSegmentIndex) { + basedir += segments[i]; + } else { + basedir += segments[i] + sep2; + } + } + var path2 = ""; + var lastSegmentIndex = segments.length - 1; + for (var i2 = index + offset; i2 <= lastSegmentIndex; i2++) { + if (i2 === lastSegmentIndex) { + path2 += segments[i2]; + } else { + path2 += segments[i2] + sep2; + } + } + return { + name, + basedir, + path: path2 + }; + }; + return moduleDetailsFromPath; +} +var hasRequiredRequireInTheMiddle; +function requireRequireInTheMiddle() { + if (hasRequiredRequireInTheMiddle) return requireInTheMiddle.exports; + hasRequiredRequireInTheMiddle = 1; + const path2 = path__default; + const Module = moduleModule__default; + const debug2 = require$$4("require-in-the-middle"); + const moduleDetailsFromPath2 = requireModuleDetailsFromPath(); + requireInTheMiddle.exports = Hook; + requireInTheMiddle.exports.Hook = Hook; + let builtinModules; + let isCore; + if (Module.isBuiltin) { + isCore = Module.isBuiltin; + } else if (Module.builtinModules) { + isCore = (moduleName) => { + if (moduleName.startsWith("node:")) { + return true; + } + if (builtinModules === void 0) { + builtinModules = new Set(Module.builtinModules); + } + return builtinModules.has(moduleName); + }; + } else { + throw new Error("'require-in-the-middle' requires Node.js >=v9.3.0 or >=v8.10.0"); + } + const normalize2 = /([/\\]index)?(\.js)?$/; + class ExportsCache { + constructor() { + this._localCache = /* @__PURE__ */ new Map(); + this._kRitmExports = Symbol("RitmExports"); + } + has(filename, isBuiltin) { + if (this._localCache.has(filename)) { + return true; + } else if (!isBuiltin) { + const mod = require.cache[filename]; + return !!(mod && this._kRitmExports in mod); + } else { + return false; + } + } + get(filename, isBuiltin) { + const cachedExports = this._localCache.get(filename); + if (cachedExports !== void 0) { + return cachedExports; + } else if (!isBuiltin) { + const mod = require.cache[filename]; + return mod && mod[this._kRitmExports]; + } + } + set(filename, exports$1, isBuiltin) { + if (isBuiltin) { + this._localCache.set(filename, exports$1); + } else if (filename in require.cache) { + require.cache[filename][this._kRitmExports] = exports$1; + } else { + debug2('non-core module is unexpectedly not in require.cache: "%s"', filename); + this._localCache.set(filename, exports$1); + } + } + } + function Hook(modules, options, onrequire) { + if (this instanceof Hook === false) return new Hook(modules, options, onrequire); + if (typeof modules === "function") { + onrequire = modules; + modules = null; + options = null; + } else if (typeof options === "function") { + onrequire = options; + options = null; + } + if (typeof Module._resolveFilename !== "function") { + console.error("Error: Expected Module._resolveFilename to be a function (was: %s) - aborting!", typeof Module._resolveFilename); + console.error("Please report this error as an issue related to Node.js %s at https://github.com/nodejs/require-in-the-middle/issues", process.version); + return; + } + this._cache = new ExportsCache(); + this._unhooked = false; + this._origRequire = Module.prototype.require; + const self = this; + const patching = /* @__PURE__ */ new Set(); + const internals = options ? options.internals === true : false; + const hasWhitelist = Array.isArray(modules); + debug2("registering require hook"); + this._require = Module.prototype.require = function(id) { + if (self._unhooked === true) { + debug2("ignoring require call - module is soft-unhooked"); + return self._origRequire.apply(this, arguments); + } + return patchedRequire.call(this, arguments, false); + }; + if (typeof process.getBuiltinModule === "function") { + this._origGetBuiltinModule = process.getBuiltinModule; + this._getBuiltinModule = process.getBuiltinModule = function(id) { + if (self._unhooked === true) { + debug2("ignoring process.getBuiltinModule call - module is soft-unhooked"); + return self._origGetBuiltinModule.apply(this, arguments); + } + return patchedRequire.call(this, arguments, true); + }; + } + function patchedRequire(args, coreOnly) { + const id = args[0]; + const core = isCore(id); + let filename; + if (core) { + filename = id; + if (id.startsWith("node:")) { + const idWithoutPrefix = id.slice(5); + if (isCore(idWithoutPrefix)) { + filename = idWithoutPrefix; + } + } + } else if (coreOnly) { + debug2("call to process.getBuiltinModule with unknown built-in id"); + return self._origGetBuiltinModule.apply(this, args); + } else { + try { + filename = Module._resolveFilename(id, this); + } catch (resolveErr) { + debug2('Module._resolveFilename("%s") threw %j, calling original Module.require', id, resolveErr.message); + return self._origRequire.apply(this, args); + } + } + let moduleName, basedir; + debug2("processing %s module require('%s'): %s", core === true ? "core" : "non-core", id, filename); + if (self._cache.has(filename, core) === true) { + debug2("returning already patched cached module: %s", filename); + return self._cache.get(filename, core); + } + const isPatching = patching.has(filename); + if (isPatching === false) { + patching.add(filename); + } + const exports$1 = coreOnly ? self._origGetBuiltinModule.apply(this, args) : self._origRequire.apply(this, args); + if (isPatching === true) { + debug2("module is in the process of being patched already - ignoring: %s", filename); + return exports$1; + } + patching.delete(filename); + if (core === true) { + if (hasWhitelist === true && modules.includes(filename) === false) { + debug2("ignoring core module not on whitelist: %s", filename); + return exports$1; + } + moduleName = filename; + } else if (hasWhitelist === true && modules.includes(filename)) { + const parsedPath = path2.parse(filename); + moduleName = parsedPath.name; + basedir = parsedPath.dir; + } else { + const stat = moduleDetailsFromPath2(filename); + if (stat === void 0) { + debug2("could not parse filename: %s", filename); + return exports$1; + } + moduleName = stat.name; + basedir = stat.basedir; + const fullModuleName = resolveModuleName(stat); + debug2("resolved filename to module: %s (id: %s, resolved: %s, basedir: %s)", moduleName, id, fullModuleName, basedir); + let matchFound = false; + if (hasWhitelist) { + if (!id.startsWith(".") && modules.includes(id)) { + moduleName = id; + matchFound = true; + } + if (!modules.includes(moduleName) && !modules.includes(fullModuleName)) { + return exports$1; + } + if (modules.includes(fullModuleName) && fullModuleName !== moduleName) { + moduleName = fullModuleName; + matchFound = true; + } + } + if (!matchFound) { + let res; + try { + res = require.resolve(moduleName, { paths: [basedir] }); + } catch (e) { + debug2("could not resolve module: %s", moduleName); + self._cache.set(filename, exports$1, core); + return exports$1; + } + if (res !== filename) { + if (internals === true) { + moduleName = moduleName + path2.sep + path2.relative(basedir, filename); + debug2("preparing to process require of internal file: %s", moduleName); + } else { + debug2("ignoring require of non-main module file: %s", res); + self._cache.set(filename, exports$1, core); + return exports$1; + } + } + } + } + self._cache.set(filename, exports$1, core); + debug2("calling require hook: %s", moduleName); + const patchedExports = onrequire(exports$1, moduleName, basedir); + self._cache.set(filename, patchedExports, core); + debug2("returning module: %s", moduleName); + return patchedExports; + } + } + Hook.prototype.unhook = function() { + this._unhooked = true; + if (this._require === Module.prototype.require) { + Module.prototype.require = this._origRequire; + debug2("require unhook successful"); + } else { + debug2("require unhook unsuccessful"); + } + if (process.getBuiltinModule !== void 0) { + if (this._getBuiltinModule === process.getBuiltinModule) { + process.getBuiltinModule = this._origGetBuiltinModule; + debug2("process.getBuiltinModule unhook successful"); + } else { + debug2("process.getBuiltinModule unhook unsuccessful"); + } + } + }; + function resolveModuleName(stat) { + const normalizedPath = path2.sep !== "/" ? stat.path.split(path2.sep).join("/") : stat.path; + return path2.posix.join(stat.name, normalizedPath).replace(normalize2, ""); + } + return requireInTheMiddle.exports; +} +var requireInTheMiddleExports = requireRequireInTheMiddle(); +const ModuleNameSeparator = "/"; +class ModuleNameTrieNode { + hooks = []; + children = /* @__PURE__ */ new Map(); +} +class ModuleNameTrie { + _trie = new ModuleNameTrieNode(); + _counter = 0; + /** + * Insert a module hook into the trie + * + * @param {Hooked} hook Hook + */ + insert(hook) { + let trieNode = this._trie; + for (const moduleNamePart of hook.moduleName.split(ModuleNameSeparator)) { + let nextNode = trieNode.children.get(moduleNamePart); + if (!nextNode) { + nextNode = new ModuleNameTrieNode(); + trieNode.children.set(moduleNamePart, nextNode); + } + trieNode = nextNode; + } + trieNode.hooks.push({ hook, insertedId: this._counter++ }); + } + /** + * Search for matching hooks in the trie + * + * @param {string} moduleName Module name + * @param {boolean} maintainInsertionOrder Whether to return the results in insertion order + * @param {boolean} fullOnly Whether to return only full matches + * @returns {Hooked[]} Matching hooks + */ + search(moduleName, { maintainInsertionOrder, fullOnly } = {}) { + let trieNode = this._trie; + const results = []; + let foundFull = true; + for (const moduleNamePart of moduleName.split(ModuleNameSeparator)) { + const nextNode = trieNode.children.get(moduleNamePart); + if (!nextNode) { + foundFull = false; + break; + } + if (!fullOnly) { + results.push(...nextNode.hooks); + } + trieNode = nextNode; + } + if (fullOnly && foundFull) { + results.push(...trieNode.hooks); + } + if (results.length === 0) { + return []; + } + if (results.length === 1) { + return [results[0].hook]; + } + if (maintainInsertionOrder) { + results.sort((a, b) => a.insertedId - b.insertedId); + } + return results.map(({ hook }) => hook); + } +} +const isMocha = [ + "afterEach", + "after", + "beforeEach", + "before", + "describe", + "it" +].every((fn) => { + return typeof global[fn] === "function"; +}); +class RequireInTheMiddleSingleton { + _moduleNameTrie = new ModuleNameTrie(); + static _instance; + constructor() { + this._initialize(); + } + _initialize() { + new requireInTheMiddleExports.Hook( + // Intercept all `require` calls; we will filter the matching ones below + null, + { internals: true }, + (exports$1, name, basedir) => { + const normalizedModuleName = normalizePathSeparators(name); + const matches = this._moduleNameTrie.search(normalizedModuleName, { + maintainInsertionOrder: true, + // For core modules (e.g. `fs`), do not match on sub-paths (e.g. `fs/promises'). + // This matches the behavior of `require-in-the-middle`. + // `basedir` is always `undefined` for core modules. + fullOnly: basedir === void 0 + }); + for (const { onRequire } of matches) { + exports$1 = onRequire(exports$1, name, basedir); + } + return exports$1; + } + ); + } + /** + * Register a hook with `require-in-the-middle` + * + * @param {string} moduleName Module name + * @param {OnRequireFn} onRequire Hook function + * @returns {Hooked} Registered hook + */ + register(moduleName, onRequire) { + const hooked = { moduleName, onRequire }; + this._moduleNameTrie.insert(hooked); + return hooked; + } + /** + * Get the `RequireInTheMiddleSingleton` singleton + * + * @returns {RequireInTheMiddleSingleton} Singleton of `RequireInTheMiddleSingleton` + */ + static getInstance() { + if (isMocha) + return new RequireInTheMiddleSingleton(); + return this._instance = this._instance ?? new RequireInTheMiddleSingleton(); + } +} +function normalizePathSeparators(moduleNameOrPath) { + return path$1.sep !== ModuleNameSeparator ? moduleNameOrPath.split(path$1.sep).join(ModuleNameSeparator) : moduleNameOrPath; +} +var importInTheMiddle = { exports: {} }; +var register = {}; +var hasRequiredRegister; +function requireRegister() { + if (hasRequiredRegister) return register; + hasRequiredRegister = 1; + const importHooks = []; + const setters = /* @__PURE__ */ new WeakMap(); + const getters = /* @__PURE__ */ new WeakMap(); + const specifiers = /* @__PURE__ */ new Map(); + const toHook = []; + const proxyHandler = { + set(target, name, value) { + return setters.get(target)[name](value); + }, + get(target, name) { + if (name === Symbol.toStringTag) { + return "Module"; + } + const getter = getters.get(target)[name]; + if (typeof getter === "function") { + return getter(); + } + }, + defineProperty(target, property, descriptor) { + if (!("value" in descriptor)) { + throw new Error("Getters/setters are not supported for exports property descriptors."); + } + return setters.get(target)[property](descriptor.value); + } + }; + function register$1(name, namespace, set, get, specifier) { + specifiers.set(name, specifier); + setters.set(namespace, set); + getters.set(namespace, get); + const proxy = new Proxy(namespace, proxyHandler); + importHooks.forEach((hook) => hook(name, proxy, specifier)); + toHook.push([name, proxy, specifier]); + } + let experimentalPatchInternals = false; + function getExperimentalPatchInternals() { + return experimentalPatchInternals; + } + function setExperimentalPatchInternals(value) { + experimentalPatchInternals = value; + } + register.register = register$1; + register.importHooks = importHooks; + register.specifiers = specifiers; + register.toHook = toHook; + register.getExperimentalPatchInternals = getExperimentalPatchInternals; + register.setExperimentalPatchInternals = setExperimentalPatchInternals; + return register; +} +var hasRequiredImportInTheMiddle; +function requireImportInTheMiddle() { + if (hasRequiredImportInTheMiddle) return importInTheMiddle.exports; + hasRequiredImportInTheMiddle = 1; + const path2 = path__default; + const parse = requireModuleDetailsFromPath(); + const { fileURLToPath } = require$$2$1; + const { MessageChannel } = require$$3; + const { + importHooks, + specifiers, + toHook, + getExperimentalPatchInternals + } = requireRegister(); + function addHook(hook) { + importHooks.push(hook); + toHook.forEach(([name, namespace, specifier]) => hook(name, namespace, specifier)); + } + function removeHook(hook) { + const index = importHooks.indexOf(hook); + if (index > -1) { + importHooks.splice(index, 1); + } + } + function callHookFn(hookFn, namespace, name, baseDir) { + const newDefault = hookFn(namespace, name, baseDir); + if (newDefault && newDefault !== namespace) { + namespace.default = newDefault; + } + } + let sendModulesToLoader; + function createAddHookMessageChannel() { + const { port1, port2 } = new MessageChannel(); + let pendingAckCount = 0; + let resolveFn; + sendModulesToLoader = (modules) => { + pendingAckCount++; + port1.postMessage(modules); + }; + port1.on("message", () => { + pendingAckCount--; + if (resolveFn && pendingAckCount <= 0) { + resolveFn(); + } + }).unref(); + function waitForAllMessagesAcknowledged() { + const timer = setInterval(() => { + }, 1e3); + const promise = new Promise((resolve) => { + resolveFn = resolve; + }).then(() => { + clearInterval(timer); + }); + if (pendingAckCount === 0) { + resolveFn(); + } + return promise; + } + const addHookMessagePort = port2; + const registerOptions = { data: { addHookMessagePort, include: [] }, transferList: [addHookMessagePort] }; + return { registerOptions, addHookMessagePort, waitForAllMessagesAcknowledged }; + } + function Hook(modules, options, hookFn) { + if (this instanceof Hook === false) return new Hook(modules, options, hookFn); + if (typeof modules === "function") { + hookFn = modules; + modules = null; + options = null; + } else if (typeof options === "function") { + hookFn = options; + options = null; + } + const internals = options ? options.internals === true : false; + if (sendModulesToLoader && Array.isArray(modules)) { + sendModulesToLoader(modules); + } + this._iitmHook = (name, namespace, specifier) => { + const filename = name; + const isBuiltin = name.startsWith("node:"); + let baseDir; + if (isBuiltin) { + name = name.replace(/^node:/, ""); + } else { + if (name.startsWith("file://")) { + try { + name = fileURLToPath(name); + } catch (e) { + } + } + const details = parse(name); + if (details) { + name = details.name; + baseDir = details.basedir; + } + } + if (modules) { + for (const moduleName of modules) { + if (moduleName === specifier) { + callHookFn(hookFn, namespace, name, baseDir); + } else if (moduleName === name) { + if (baseDir) { + if (internals) { + name = name + path2.sep + path2.relative(baseDir, fileURLToPath(filename)); + } else { + if (!getExperimentalPatchInternals() && !baseDir.endsWith(specifiers.get(filename))) continue; + } + } + callHookFn(hookFn, namespace, name, baseDir); + } + } + } else { + callHookFn(hookFn, namespace, name, baseDir); + } + }; + addHook(this._iitmHook); + } + Hook.prototype.unhook = function() { + removeHook(this._iitmHook); + }; + importInTheMiddle.exports = Hook; + importInTheMiddle.exports.Hook = Hook; + importInTheMiddle.exports.addHook = addHook; + importInTheMiddle.exports.removeHook = removeHook; + importInTheMiddle.exports.createAddHookMessageChannel = createAddHookMessageChannel; + return importInTheMiddle.exports; +} +var importInTheMiddleExports = requireImportInTheMiddle(); +function safeExecuteInTheMiddle(execute, onFinish, preventThrowingError) { + let error2; + let result; + try { + result = execute(); + } catch (e) { + error2 = e; + } finally { + onFinish(error2, result); + if (error2 && !preventThrowingError) { + throw error2; + } + return result; + } +} +async function safeExecuteInTheMiddleAsync(execute, onFinish, preventThrowingError) { + let error2; + let result; + try { + result = await execute(); + } catch (e) { + error2 = e; + } finally { + await onFinish(error2, result); + if (error2 && !preventThrowingError) { + throw error2; + } + return result; + } +} +function isWrapped(func) { + return typeof func === "function" && typeof func.__original === "function" && typeof func.__unwrap === "function" && func.__wrapped === true; +} +class InstrumentationBase extends InstrumentationAbstract { + _modules; + _hooks = []; + _requireInTheMiddleSingleton = RequireInTheMiddleSingleton.getInstance(); + _enabled = false; + constructor(instrumentationName, instrumentationVersion, config2) { + super(instrumentationName, instrumentationVersion, config2); + let modules = this.init(); + if (modules && !Array.isArray(modules)) { + modules = [modules]; + } + this._modules = modules || []; + if (this._config.enabled) { + this.enable(); + } + } + _wrap = (moduleExports, name, wrapper) => { + if (isWrapped(moduleExports[name])) { + this._unwrap(moduleExports, name); + } + if (!types$5.isProxy(moduleExports)) { + return wrap(moduleExports, name, wrapper); + } else { + const wrapped = wrap(Object.assign({}, moduleExports), name, wrapper); + Object.defineProperty(moduleExports, name, { + value: wrapped + }); + return wrapped; + } + }; + _unwrap = (moduleExports, name) => { + if (!types$5.isProxy(moduleExports)) { + return unwrap(moduleExports, name); + } else { + return Object.defineProperty(moduleExports, name, { + value: moduleExports[name] + }); + } + }; + _massWrap = (moduleExportsArray, names2, wrapper) => { + if (!moduleExportsArray) { + srcExports$l.diag.error("must provide one or more modules to patch"); + return; + } else if (!Array.isArray(moduleExportsArray)) { + moduleExportsArray = [moduleExportsArray]; + } + if (!(names2 && Array.isArray(names2))) { + srcExports$l.diag.error("must provide one or more functions to wrap on modules"); + return; + } + moduleExportsArray.forEach((moduleExports) => { + names2.forEach((name) => { + this._wrap(moduleExports, name, wrapper); + }); + }); + }; + _massUnwrap = (moduleExportsArray, names2) => { + if (!moduleExportsArray) { + srcExports$l.diag.error("must provide one or more modules to patch"); + return; + } else if (!Array.isArray(moduleExportsArray)) { + moduleExportsArray = [moduleExportsArray]; + } + if (!(names2 && Array.isArray(names2))) { + srcExports$l.diag.error("must provide one or more functions to wrap on modules"); + return; + } + moduleExportsArray.forEach((moduleExports) => { + names2.forEach((name) => { + this._unwrap(moduleExports, name); + }); + }); + }; + _warnOnPreloadedModules() { + this._modules.forEach((module2) => { + const { name } = module2; + try { + const resolvedModule = require.resolve(name); + if (require.cache[resolvedModule]) { + this._diag.warn(`Module ${name} has been loaded before ${this.instrumentationName} so it might not work, please initialize it before requiring ${name}`); + } + } catch { + } + }); + } + _extractPackageVersion(baseDir) { + try { + const json = readFileSync(path$1.join(baseDir, "package.json"), { + encoding: "utf8" + }); + const version2 = JSON.parse(json).version; + return typeof version2 === "string" ? version2 : void 0; + } catch { + srcExports$l.diag.warn("Failed extracting version", baseDir); + } + return void 0; + } + _onRequire(module2, exports$1, name, baseDir) { + if (!baseDir) { + if (typeof module2.patch === "function") { + module2.moduleExports = exports$1; + if (this._enabled) { + this._diag.debug("Applying instrumentation patch for nodejs core module on require hook", { + module: module2.name + }); + return module2.patch(exports$1); + } + } + return exports$1; + } + const version2 = this._extractPackageVersion(baseDir); + module2.moduleVersion = version2; + if (module2.name === name) { + if (isSupported(module2.supportedVersions, version2, module2.includePrerelease)) { + if (typeof module2.patch === "function") { + module2.moduleExports = exports$1; + if (this._enabled) { + this._diag.debug("Applying instrumentation patch for module on require hook", { + module: module2.name, + version: module2.moduleVersion, + baseDir + }); + return module2.patch(exports$1, module2.moduleVersion); + } + } + } + return exports$1; + } + const files = module2.files ?? []; + const normalizedName = path$1.normalize(name); + const supportedFileInstrumentations = files.filter((f) => f.name === normalizedName).filter((f) => isSupported(f.supportedVersions, version2, module2.includePrerelease)); + return supportedFileInstrumentations.reduce((patchedExports, file) => { + file.moduleExports = patchedExports; + if (this._enabled) { + this._diag.debug("Applying instrumentation patch for nodejs module file on require hook", { + module: module2.name, + version: module2.moduleVersion, + fileName: file.name, + baseDir + }); + return file.patch(patchedExports, module2.moduleVersion); + } + return patchedExports; + }, exports$1); + } + enable() { + if (this._enabled) { + return; + } + this._enabled = true; + if (this._hooks.length > 0) { + for (const module2 of this._modules) { + if (typeof module2.patch === "function" && module2.moduleExports) { + this._diag.debug("Applying instrumentation patch for nodejs module on instrumentation enabled", { + module: module2.name, + version: module2.moduleVersion + }); + module2.patch(module2.moduleExports, module2.moduleVersion); + } + for (const file of module2.files) { + if (file.moduleExports) { + this._diag.debug("Applying instrumentation patch for nodejs module file on instrumentation enabled", { + module: module2.name, + version: module2.moduleVersion, + fileName: file.name + }); + file.patch(file.moduleExports, module2.moduleVersion); + } + } + } + return; + } + this._warnOnPreloadedModules(); + for (const module2 of this._modules) { + const hookFn = (exports$1, name, baseDir) => { + if (!baseDir && path$1.isAbsolute(name)) { + const parsedPath = path$1.parse(name); + name = parsedPath.name; + baseDir = parsedPath.dir; + } + return this._onRequire(module2, exports$1, name, baseDir); + }; + const onRequire = (exports$1, name, baseDir) => { + return this._onRequire(module2, exports$1, name, baseDir); + }; + const hook = path$1.isAbsolute(module2.name) ? new requireInTheMiddleExports.Hook([module2.name], { internals: true }, onRequire) : this._requireInTheMiddleSingleton.register(module2.name, onRequire); + this._hooks.push(hook); + const esmHook = new importInTheMiddleExports.Hook([module2.name], { internals: false }, hookFn); + this._hooks.push(esmHook); + } + } + disable() { + if (!this._enabled) { + return; + } + this._enabled = false; + for (const module2 of this._modules) { + if (typeof module2.unpatch === "function" && module2.moduleExports) { + this._diag.debug("Removing instrumentation patch for nodejs module on instrumentation disabled", { + module: module2.name, + version: module2.moduleVersion + }); + module2.unpatch(module2.moduleExports, module2.moduleVersion); + } + for (const file of module2.files) { + if (file.moduleExports) { + this._diag.debug("Removing instrumentation patch for nodejs module file on instrumentation disabled", { + module: module2.name, + version: module2.moduleVersion, + fileName: file.name + }); + file.unpatch(file.moduleExports, module2.moduleVersion); + } + } + } + } + isEnabled() { + return this._enabled; + } +} +function isSupported(supportedVersions2, version2, includePrerelease) { + if (typeof version2 === "undefined") { + return supportedVersions2.includes("*"); + } + return supportedVersions2.some((supportedVersion) => { + return satisfies(version2, supportedVersion, { includePrerelease }); + }); +} +class InstrumentationNodeModuleDefinition { + name; + supportedVersions; + patch; + unpatch; + files; + constructor(name, supportedVersions2, patch, unpatch, files) { + this.name = name; + this.supportedVersions = supportedVersions2; + this.patch = patch; + this.unpatch = unpatch; + this.files = files || []; + } +} +class InstrumentationNodeModuleFile { + supportedVersions; + patch; + unpatch; + name; + constructor(name, supportedVersions2, patch, unpatch) { + this.supportedVersions = supportedVersions2; + this.patch = patch; + this.unpatch = unpatch; + this.name = normalize(name); + } +} +var SemconvStability; +(function(SemconvStability2) { + SemconvStability2[SemconvStability2["STABLE"] = 1] = "STABLE"; + SemconvStability2[SemconvStability2["OLD"] = 2] = "OLD"; + SemconvStability2[SemconvStability2["DUPLICATE"] = 3] = "DUPLICATE"; +})(SemconvStability || (SemconvStability = {})); +function semconvStabilityFromStr(namespace, str) { + let semconvStability = SemconvStability.OLD; + const entries = str?.split(",").map((v) => v.trim()).filter((s) => s !== ""); + for (const entry of entries ?? []) { + if (entry.toLowerCase() === namespace + "/dup") { + semconvStability = SemconvStability.DUPLICATE; + break; + } else if (entry.toLowerCase() === namespace) { + semconvStability = SemconvStability.STABLE; + } + } + return semconvStability; +} +const esm = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ + __proto__: null, + InstrumentationBase, + InstrumentationNodeModuleDefinition, + InstrumentationNodeModuleFile, + get SemconvStability() { + return SemconvStability; + }, + isWrapped, + registerInstrumentations, + safeExecuteInTheMiddle, + safeExecuteInTheMiddleAsync, + semconvStabilityFromStr +}, Symbol.toStringTag, { value: "Module" })); +const require$$2 = /* @__PURE__ */ getAugmentedNamespace(esm); +var utils$e = {}; +var semconv$b = {}; +var hasRequiredSemconv$b; +function requireSemconv$b() { + if (hasRequiredSemconv$b) return semconv$b; + hasRequiredSemconv$b = 1; + Object.defineProperty(semconv$b, "__esModule", { value: true }); + semconv$b.HTTP_FLAVOR_VALUE_HTTP_1_1 = semconv$b.NET_TRANSPORT_VALUE_IP_UDP = semconv$b.NET_TRANSPORT_VALUE_IP_TCP = semconv$b.ATTR_NET_TRANSPORT = semconv$b.ATTR_NET_PEER_PORT = semconv$b.ATTR_NET_PEER_NAME = semconv$b.ATTR_NET_PEER_IP = semconv$b.ATTR_NET_HOST_PORT = semconv$b.ATTR_NET_HOST_NAME = semconv$b.ATTR_NET_HOST_IP = semconv$b.ATTR_HTTP_USER_AGENT = semconv$b.ATTR_HTTP_URL = semconv$b.ATTR_HTTP_TARGET = semconv$b.ATTR_HTTP_STATUS_CODE = semconv$b.ATTR_HTTP_SERVER_NAME = semconv$b.ATTR_HTTP_SCHEME = semconv$b.ATTR_HTTP_RESPONSE_CONTENT_LENGTH_UNCOMPRESSED = semconv$b.ATTR_HTTP_RESPONSE_CONTENT_LENGTH = semconv$b.ATTR_HTTP_REQUEST_CONTENT_LENGTH_UNCOMPRESSED = semconv$b.ATTR_HTTP_REQUEST_CONTENT_LENGTH = semconv$b.ATTR_HTTP_METHOD = semconv$b.ATTR_HTTP_HOST = semconv$b.ATTR_HTTP_FLAVOR = semconv$b.ATTR_HTTP_CLIENT_IP = semconv$b.USER_AGENT_SYNTHETIC_TYPE_VALUE_TEST = semconv$b.USER_AGENT_SYNTHETIC_TYPE_VALUE_BOT = semconv$b.ATTR_USER_AGENT_SYNTHETIC_TYPE = void 0; + semconv$b.ATTR_USER_AGENT_SYNTHETIC_TYPE = "user_agent.synthetic.type"; + semconv$b.USER_AGENT_SYNTHETIC_TYPE_VALUE_BOT = "bot"; + semconv$b.USER_AGENT_SYNTHETIC_TYPE_VALUE_TEST = "test"; + semconv$b.ATTR_HTTP_CLIENT_IP = "http.client_ip"; + semconv$b.ATTR_HTTP_FLAVOR = "http.flavor"; + semconv$b.ATTR_HTTP_HOST = "http.host"; + semconv$b.ATTR_HTTP_METHOD = "http.method"; + semconv$b.ATTR_HTTP_REQUEST_CONTENT_LENGTH = "http.request_content_length"; + semconv$b.ATTR_HTTP_REQUEST_CONTENT_LENGTH_UNCOMPRESSED = "http.request_content_length_uncompressed"; + semconv$b.ATTR_HTTP_RESPONSE_CONTENT_LENGTH = "http.response_content_length"; + semconv$b.ATTR_HTTP_RESPONSE_CONTENT_LENGTH_UNCOMPRESSED = "http.response_content_length_uncompressed"; + semconv$b.ATTR_HTTP_SCHEME = "http.scheme"; + semconv$b.ATTR_HTTP_SERVER_NAME = "http.server_name"; + semconv$b.ATTR_HTTP_STATUS_CODE = "http.status_code"; + semconv$b.ATTR_HTTP_TARGET = "http.target"; + semconv$b.ATTR_HTTP_URL = "http.url"; + semconv$b.ATTR_HTTP_USER_AGENT = "http.user_agent"; + semconv$b.ATTR_NET_HOST_IP = "net.host.ip"; + semconv$b.ATTR_NET_HOST_NAME = "net.host.name"; + semconv$b.ATTR_NET_HOST_PORT = "net.host.port"; + semconv$b.ATTR_NET_PEER_IP = "net.peer.ip"; + semconv$b.ATTR_NET_PEER_NAME = "net.peer.name"; + semconv$b.ATTR_NET_PEER_PORT = "net.peer.port"; + semconv$b.ATTR_NET_TRANSPORT = "net.transport"; + semconv$b.NET_TRANSPORT_VALUE_IP_TCP = "ip_tcp"; + semconv$b.NET_TRANSPORT_VALUE_IP_UDP = "ip_udp"; + semconv$b.HTTP_FLAVOR_VALUE_HTTP_1_1 = "1.1"; + return semconv$b; +} +var AttributeNames$9 = {}; +var hasRequiredAttributeNames$7; +function requireAttributeNames$7() { + if (hasRequiredAttributeNames$7) return AttributeNames$9; + hasRequiredAttributeNames$7 = 1; + (function(exports$1) { + Object.defineProperty(exports$1, "__esModule", { value: true }); + exports$1.AttributeNames = void 0; + (function(AttributeNames2) { + AttributeNames2["HTTP_ERROR_NAME"] = "http.error_name"; + AttributeNames2["HTTP_ERROR_MESSAGE"] = "http.error_message"; + AttributeNames2["HTTP_STATUS_TEXT"] = "http.status_text"; + })(exports$1.AttributeNames || (exports$1.AttributeNames = {})); + })(AttributeNames$9); + return AttributeNames$9; +} +var internalTypes$8 = {}; +var hasRequiredInternalTypes$8; +function requireInternalTypes$8() { + if (hasRequiredInternalTypes$8) return internalTypes$8; + hasRequiredInternalTypes$8 = 1; + Object.defineProperty(internalTypes$8, "__esModule", { value: true }); + internalTypes$8.DEFAULT_QUERY_STRINGS_TO_REDACT = internalTypes$8.STR_REDACTED = internalTypes$8.SYNTHETIC_BOT_NAMES = internalTypes$8.SYNTHETIC_TEST_NAMES = void 0; + internalTypes$8.SYNTHETIC_TEST_NAMES = ["alwayson"]; + internalTypes$8.SYNTHETIC_BOT_NAMES = ["googlebot", "bingbot"]; + internalTypes$8.STR_REDACTED = "REDACTED"; + internalTypes$8.DEFAULT_QUERY_STRINGS_TO_REDACT = [ + "sig", + "Signature", + "AWSAccessKeyId", + "X-Goog-Signature" + ]; + return internalTypes$8; +} +var error; +var hasRequiredError; +function requireError() { + if (hasRequiredError) return error; + hasRequiredError = 1; + var util2 = require$$0; + function ParseError(message, input) { + Error.captureStackTrace(this, ParseError); + this.name = this.constructor.name; + this.message = message; + this.input = input; + } + util2.inherits(ParseError, Error); + error = ParseError; + return error; +} +var ascii; +var hasRequiredAscii; +function requireAscii() { + if (hasRequiredAscii) return ascii; + hasRequiredAscii = 1; + function isDelimiter(code) { + return code === 34 || code === 40 || code === 41 || code === 44 || code === 47 || code >= 58 && code <= 64 || code >= 91 && code <= 93 || code === 123 || code === 125; + } + function isTokenChar(code) { + return code === 33 || code >= 35 && code <= 39 || code === 42 || code === 43 || code === 45 || code === 46 || code >= 48 && code <= 57 || code >= 65 && code <= 90 || code >= 94 && code <= 122 || code === 124 || code === 126; + } + function isPrint(code) { + return code >= 32 && code <= 126; + } + function isExtended(code) { + return code >= 128 && code <= 255; + } + ascii = { + isDelimiter, + isTokenChar, + isExtended, + isPrint + }; + return ascii; +} +var forwardedParse; +var hasRequiredForwardedParse; +function requireForwardedParse() { + if (hasRequiredForwardedParse) return forwardedParse; + hasRequiredForwardedParse = 1; + var util2 = require$$0; + var ParseError = requireError(); + var ascii2 = requireAscii(); + var isDelimiter = ascii2.isDelimiter; + var isTokenChar = ascii2.isTokenChar; + var isExtended = ascii2.isExtended; + var isPrint = ascii2.isPrint; + function decode(str) { + return str.replace(/\\(.)/g, "$1"); + } + function unexpectedCharacterMessage(header, position) { + return util2.format( + "Unexpected character '%s' at index %d", + header.charAt(position), + position + ); + } + function parse(header) { + var mustUnescape = false; + var isEscaping = false; + var inQuotes = false; + var forwarded = {}; + var output = []; + var start = -1; + var end = -1; + var parameter; + var code; + for (var i = 0; i < header.length; i++) { + code = header.charCodeAt(i); + if (parameter === void 0) { + if (i !== 0 && start === -1 && (code === 32 || code === 9)) { + continue; + } + if (isTokenChar(code)) { + if (start === -1) start = i; + } else if (code === 61 && start !== -1) { + parameter = header.slice(start, i).toLowerCase(); + start = -1; + } else { + throw new ParseError(unexpectedCharacterMessage(header, i), header); + } + } else { + if (isEscaping && (code === 9 || isPrint(code) || isExtended(code))) { + isEscaping = false; + } else if (isTokenChar(code)) { + if (end !== -1) { + throw new ParseError(unexpectedCharacterMessage(header, i), header); + } + if (start === -1) start = i; + } else if (isDelimiter(code) || isExtended(code)) { + if (inQuotes) { + if (code === 34) { + inQuotes = false; + end = i; + } else if (code === 92) { + if (start === -1) start = i; + isEscaping = mustUnescape = true; + } else if (start === -1) { + start = i; + } + } else if (code === 34 && header.charCodeAt(i - 1) === 61) { + inQuotes = true; + } else if ((code === 44 || code === 59) && (start !== -1 || end !== -1)) { + if (start !== -1) { + if (end === -1) end = i; + forwarded[parameter] = mustUnescape ? decode(header.slice(start, end)) : header.slice(start, end); + } else { + forwarded[parameter] = ""; + } + if (code === 44) { + output.push(forwarded); + forwarded = {}; + } + parameter = void 0; + start = end = -1; + } else { + throw new ParseError(unexpectedCharacterMessage(header, i), header); + } + } else if (code === 32 || code === 9) { + if (end !== -1) continue; + if (inQuotes) { + if (start === -1) start = i; + } else if (start !== -1) { + end = i; + } else { + throw new ParseError(unexpectedCharacterMessage(header, i), header); + } + } else { + throw new ParseError(unexpectedCharacterMessage(header, i), header); + } + } + } + if (parameter === void 0 || inQuotes || start === -1 && end === -1 || code === 32 || code === 9) { + throw new ParseError("Unexpected end of input", header); + } + if (start !== -1) { + if (end === -1) end = i; + forwarded[parameter] = mustUnescape ? decode(header.slice(start, end)) : header.slice(start, end); + } else { + forwarded[parameter] = ""; + } + output.push(forwarded); + return output; + } + forwardedParse = parse; + return forwardedParse; +} +var hasRequiredUtils$e; +function requireUtils$e() { + if (hasRequiredUtils$e) return utils$e; + hasRequiredUtils$e = 1; + (function(exports$1) { + Object.defineProperty(exports$1, "__esModule", { value: true }); + exports$1.headerCapture = exports$1.getIncomingStableRequestMetricAttributesOnResponse = exports$1.getIncomingRequestMetricAttributesOnResponse = exports$1.getIncomingRequestAttributesOnResponse = exports$1.getIncomingRequestMetricAttributes = exports$1.getIncomingRequestAttributes = exports$1.getRemoteClientAddress = exports$1.getOutgoingStableRequestMetricAttributesOnResponse = exports$1.getOutgoingRequestMetricAttributesOnResponse = exports$1.getOutgoingRequestAttributesOnResponse = exports$1.setAttributesFromHttpKind = exports$1.getOutgoingRequestMetricAttributes = exports$1.getOutgoingRequestAttributes = exports$1.extractHostnameAndPort = exports$1.isValidOptionsType = exports$1.getRequestInfo = exports$1.isCompressed = exports$1.setResponseContentLengthAttribute = exports$1.setRequestContentLengthAttribute = exports$1.setSpanWithError = exports$1.satisfiesPattern = exports$1.parseResponseStatus = exports$1.getAbsoluteUrl = void 0; + const api_1 = /* @__PURE__ */ requireSrc$n(); + const semantic_conventions_1 = /* @__PURE__ */ requireSrc$m(); + const semconv_1 = /* @__PURE__ */ requireSemconv$b(); + const core_1 = require$$1; + const instrumentation_1 = require$$2; + const url = require$$2$1; + const AttributeNames_1 = /* @__PURE__ */ requireAttributeNames$7(); + const internal_types_1 = /* @__PURE__ */ requireInternalTypes$8(); + const internal_types_2 = /* @__PURE__ */ requireInternalTypes$8(); + const forwardedParse2 = requireForwardedParse(); + const getAbsoluteUrl2 = (requestUrl, headers, fallbackProtocol = "http:", redactedQueryParams = Array.from(internal_types_2.DEFAULT_QUERY_STRINGS_TO_REDACT)) => { + const reqUrlObject = requestUrl || {}; + const protocol = reqUrlObject.protocol || fallbackProtocol; + const port = (reqUrlObject.port || "").toString(); + let path2 = reqUrlObject.path || "/"; + let host = reqUrlObject.host || reqUrlObject.hostname || headers.host || "localhost"; + if (host.indexOf(":") === -1 && port && port !== "80" && port !== "443") { + host += `:${port}`; + } + if (path2.includes("?")) { + const parsedUrl = url.parse(path2); + const pathname = parsedUrl.pathname || ""; + const query = parsedUrl.query || ""; + const searchParams = new URLSearchParams(query); + const sensitiveParamsToRedact = redactedQueryParams || []; + for (const sensitiveParam of sensitiveParamsToRedact) { + if (searchParams.has(sensitiveParam) && searchParams.get(sensitiveParam) !== "") { + searchParams.set(sensitiveParam, internal_types_2.STR_REDACTED); + } + } + const redactedQuery = searchParams.toString(); + path2 = `${pathname}?${redactedQuery}`; + } + const authPart = reqUrlObject.auth ? `${internal_types_2.STR_REDACTED}:${internal_types_2.STR_REDACTED}@` : ""; + return `${protocol}//${authPart}${host}${path2}`; + }; + exports$1.getAbsoluteUrl = getAbsoluteUrl2; + const parseResponseStatus = (kind, statusCode) => { + const upperBound = kind === api_1.SpanKind.CLIENT ? 400 : 500; + if (statusCode && statusCode >= 100 && statusCode < upperBound) { + return api_1.SpanStatusCode.UNSET; + } + return api_1.SpanStatusCode.ERROR; + }; + exports$1.parseResponseStatus = parseResponseStatus; + const satisfiesPattern = (constant, pattern) => { + if (typeof pattern === "string") { + return pattern === constant; + } else if (pattern instanceof RegExp) { + return pattern.test(constant); + } else if (typeof pattern === "function") { + return pattern(constant); + } else { + throw new TypeError("Pattern is in unsupported datatype"); + } + }; + exports$1.satisfiesPattern = satisfiesPattern; + const setSpanWithError = (span, error2, semconvStability) => { + const message = error2.message; + if (semconvStability & instrumentation_1.SemconvStability.OLD) { + span.setAttribute(AttributeNames_1.AttributeNames.HTTP_ERROR_NAME, error2.name); + span.setAttribute(AttributeNames_1.AttributeNames.HTTP_ERROR_MESSAGE, message); + } + if (semconvStability & instrumentation_1.SemconvStability.STABLE) { + span.setAttribute(semantic_conventions_1.ATTR_ERROR_TYPE, error2.name); + } + span.setStatus({ code: api_1.SpanStatusCode.ERROR, message }); + span.recordException(error2); + }; + exports$1.setSpanWithError = setSpanWithError; + const setRequestContentLengthAttribute = (request, attributes) => { + const length = getContentLength2(request.headers); + if (length === null) + return; + if ((0, exports$1.isCompressed)(request.headers)) { + attributes[semconv_1.ATTR_HTTP_REQUEST_CONTENT_LENGTH] = length; + } else { + attributes[semconv_1.ATTR_HTTP_REQUEST_CONTENT_LENGTH_UNCOMPRESSED] = length; + } + }; + exports$1.setRequestContentLengthAttribute = setRequestContentLengthAttribute; + const setResponseContentLengthAttribute = (response, attributes) => { + const length = getContentLength2(response.headers); + if (length === null) + return; + if ((0, exports$1.isCompressed)(response.headers)) { + attributes[semconv_1.ATTR_HTTP_RESPONSE_CONTENT_LENGTH] = length; + } else { + attributes[semconv_1.ATTR_HTTP_RESPONSE_CONTENT_LENGTH_UNCOMPRESSED] = length; + } + }; + exports$1.setResponseContentLengthAttribute = setResponseContentLengthAttribute; + function getContentLength2(headers) { + const contentLengthHeader = headers["content-length"]; + if (contentLengthHeader === void 0) + return null; + const contentLength = parseInt(contentLengthHeader, 10); + if (isNaN(contentLength)) + return null; + return contentLength; + } + const isCompressed2 = (headers) => { + const encoding = headers["content-encoding"]; + return !!encoding && encoding !== "identity"; + }; + exports$1.isCompressed = isCompressed2; + function stringUrlToHttpOptions(stringUrl) { + const { hostname, pathname, port, username, password, search, protocol, hash, href, origin, host } = new URL(stringUrl); + const options = { + protocol, + hostname: hostname && hostname[0] === "[" ? hostname.slice(1, -1) : hostname, + hash, + search, + pathname, + path: `${pathname || ""}${search || ""}`, + href, + origin, + host + }; + if (port !== "") { + options.port = Number(port); + } + if (username || password) { + options.auth = `${decodeURIComponent(username)}:${decodeURIComponent(password)}`; + } + return options; + } + const getRequestInfo = (logger2, options, extraOptions) => { + let pathname; + let origin; + let optionsParsed; + let invalidUrl = false; + if (typeof options === "string") { + try { + const convertedOptions = stringUrlToHttpOptions(options); + optionsParsed = convertedOptions; + pathname = convertedOptions.pathname || "/"; + } catch (e) { + invalidUrl = true; + logger2.verbose("Unable to parse URL provided to HTTP request, using fallback to determine path. Original error:", e); + optionsParsed = { + path: options + }; + pathname = optionsParsed.path || "/"; + } + origin = `${optionsParsed.protocol || "http:"}//${optionsParsed.host}`; + if (extraOptions !== void 0) { + Object.assign(optionsParsed, extraOptions); + } + } else if (options instanceof url.URL) { + optionsParsed = { + protocol: options.protocol, + hostname: typeof options.hostname === "string" && options.hostname.startsWith("[") ? options.hostname.slice(1, -1) : options.hostname, + path: `${options.pathname || ""}${options.search || ""}` + }; + if (options.port !== "") { + optionsParsed.port = Number(options.port); + } + if (options.username || options.password) { + optionsParsed.auth = `${options.username}:${options.password}`; + } + pathname = options.pathname; + origin = options.origin; + if (extraOptions !== void 0) { + Object.assign(optionsParsed, extraOptions); + } + } else { + optionsParsed = Object.assign({ protocol: options.host ? "http:" : void 0 }, options); + const hostname = optionsParsed.host || (optionsParsed.port != null ? `${optionsParsed.hostname}${optionsParsed.port}` : optionsParsed.hostname); + origin = `${optionsParsed.protocol || "http:"}//${hostname}`; + pathname = options.pathname; + if (!pathname && optionsParsed.path) { + try { + const parsedUrl = new URL(optionsParsed.path, origin); + pathname = parsedUrl.pathname || "/"; + } catch { + pathname = "/"; + } + } + } + const method = optionsParsed.method ? optionsParsed.method.toUpperCase() : "GET"; + return { origin, pathname, method, optionsParsed, invalidUrl }; + }; + exports$1.getRequestInfo = getRequestInfo; + const isValidOptionsType = (options) => { + if (!options) { + return false; + } + const type = typeof options; + return type === "string" || type === "object" && !Array.isArray(options); + }; + exports$1.isValidOptionsType = isValidOptionsType; + const extractHostnameAndPort = (requestOptions) => { + if (requestOptions.hostname && requestOptions.port) { + return { hostname: requestOptions.hostname, port: requestOptions.port }; + } + const matches = requestOptions.host?.match(/^([^:/ ]+)(:\d{1,5})?/) || null; + const hostname = requestOptions.hostname || (matches === null ? "localhost" : matches[1]); + let port = requestOptions.port; + if (!port) { + if (matches && matches[2]) { + port = matches[2].substring(1); + } else { + port = requestOptions.protocol === "https:" ? "443" : "80"; + } + } + return { hostname, port }; + }; + exports$1.extractHostnameAndPort = extractHostnameAndPort; + const getOutgoingRequestAttributes = (requestOptions, options, semconvStability, enableSyntheticSourceDetection) => { + const hostname = options.hostname; + const port = options.port; + const method = requestOptions.method ?? "GET"; + const normalizedMethod = normalizeMethod(method); + const headers = requestOptions.headers || {}; + const userAgent = headers["user-agent"]; + const urlFull = (0, exports$1.getAbsoluteUrl)(requestOptions, headers, `${options.component}:`, options.redactedQueryParams); + const oldAttributes = { + [semconv_1.ATTR_HTTP_URL]: urlFull, + [semconv_1.ATTR_HTTP_METHOD]: method, + [semconv_1.ATTR_HTTP_TARGET]: requestOptions.path || "/", + [semconv_1.ATTR_NET_PEER_NAME]: hostname, + [semconv_1.ATTR_HTTP_HOST]: headers.host ?? `${hostname}:${port}` + }; + const newAttributes = { + // Required attributes + [semantic_conventions_1.ATTR_HTTP_REQUEST_METHOD]: normalizedMethod, + [semantic_conventions_1.ATTR_SERVER_ADDRESS]: hostname, + [semantic_conventions_1.ATTR_SERVER_PORT]: Number(port), + [semantic_conventions_1.ATTR_URL_FULL]: urlFull, + [semantic_conventions_1.ATTR_USER_AGENT_ORIGINAL]: userAgent + // leaving out protocol version, it is not yet negotiated + // leaving out protocol name, it is only required when protocol version is set + // retries and redirects not supported + // Opt-in attributes left off for now + }; + if (method !== normalizedMethod) { + newAttributes[semantic_conventions_1.ATTR_HTTP_REQUEST_METHOD_ORIGINAL] = method; + } + if (enableSyntheticSourceDetection && userAgent) { + newAttributes[semconv_1.ATTR_USER_AGENT_SYNTHETIC_TYPE] = getSyntheticType(userAgent); + } + if (userAgent !== void 0) { + oldAttributes[semconv_1.ATTR_HTTP_USER_AGENT] = userAgent; + } + switch (semconvStability) { + case instrumentation_1.SemconvStability.STABLE: + return Object.assign(newAttributes, options.hookAttributes); + case instrumentation_1.SemconvStability.OLD: + return Object.assign(oldAttributes, options.hookAttributes); + } + return Object.assign(oldAttributes, newAttributes, options.hookAttributes); + }; + exports$1.getOutgoingRequestAttributes = getOutgoingRequestAttributes; + const getOutgoingRequestMetricAttributes = (spanAttributes) => { + const metricAttributes = {}; + metricAttributes[semconv_1.ATTR_HTTP_METHOD] = spanAttributes[semconv_1.ATTR_HTTP_METHOD]; + metricAttributes[semconv_1.ATTR_NET_PEER_NAME] = spanAttributes[semconv_1.ATTR_NET_PEER_NAME]; + return metricAttributes; + }; + exports$1.getOutgoingRequestMetricAttributes = getOutgoingRequestMetricAttributes; + const setAttributesFromHttpKind = (kind, attributes) => { + if (kind) { + attributes[semconv_1.ATTR_HTTP_FLAVOR] = kind; + if (kind.toUpperCase() !== "QUIC") { + attributes[semconv_1.ATTR_NET_TRANSPORT] = semconv_1.NET_TRANSPORT_VALUE_IP_TCP; + } else { + attributes[semconv_1.ATTR_NET_TRANSPORT] = semconv_1.NET_TRANSPORT_VALUE_IP_UDP; + } + } + }; + exports$1.setAttributesFromHttpKind = setAttributesFromHttpKind; + const getSyntheticType = (userAgent) => { + const userAgentString = String(userAgent).toLowerCase(); + for (const name of internal_types_1.SYNTHETIC_TEST_NAMES) { + if (userAgentString.includes(name)) { + return semconv_1.USER_AGENT_SYNTHETIC_TYPE_VALUE_TEST; + } + } + for (const name of internal_types_1.SYNTHETIC_BOT_NAMES) { + if (userAgentString.includes(name)) { + return semconv_1.USER_AGENT_SYNTHETIC_TYPE_VALUE_BOT; + } + } + return; + }; + const getOutgoingRequestAttributesOnResponse = (response, semconvStability) => { + const { statusCode, statusMessage, httpVersion, socket } = response; + const oldAttributes = {}; + const stableAttributes = {}; + if (statusCode != null) { + stableAttributes[semantic_conventions_1.ATTR_HTTP_RESPONSE_STATUS_CODE] = statusCode; + } + if (socket) { + const { remoteAddress, remotePort } = socket; + oldAttributes[semconv_1.ATTR_NET_PEER_IP] = remoteAddress; + oldAttributes[semconv_1.ATTR_NET_PEER_PORT] = remotePort; + stableAttributes[semantic_conventions_1.ATTR_NETWORK_PEER_ADDRESS] = remoteAddress; + stableAttributes[semantic_conventions_1.ATTR_NETWORK_PEER_PORT] = remotePort; + stableAttributes[semantic_conventions_1.ATTR_NETWORK_PROTOCOL_VERSION] = response.httpVersion; + } + (0, exports$1.setResponseContentLengthAttribute)(response, oldAttributes); + if (statusCode) { + oldAttributes[semconv_1.ATTR_HTTP_STATUS_CODE] = statusCode; + oldAttributes[AttributeNames_1.AttributeNames.HTTP_STATUS_TEXT] = (statusMessage || "").toUpperCase(); + } + (0, exports$1.setAttributesFromHttpKind)(httpVersion, oldAttributes); + switch (semconvStability) { + case instrumentation_1.SemconvStability.STABLE: + return stableAttributes; + case instrumentation_1.SemconvStability.OLD: + return oldAttributes; + } + return Object.assign(oldAttributes, stableAttributes); + }; + exports$1.getOutgoingRequestAttributesOnResponse = getOutgoingRequestAttributesOnResponse; + const getOutgoingRequestMetricAttributesOnResponse = (spanAttributes) => { + const metricAttributes = {}; + metricAttributes[semconv_1.ATTR_NET_PEER_PORT] = spanAttributes[semconv_1.ATTR_NET_PEER_PORT]; + metricAttributes[semconv_1.ATTR_HTTP_STATUS_CODE] = spanAttributes[semconv_1.ATTR_HTTP_STATUS_CODE]; + metricAttributes[semconv_1.ATTR_HTTP_FLAVOR] = spanAttributes[semconv_1.ATTR_HTTP_FLAVOR]; + return metricAttributes; + }; + exports$1.getOutgoingRequestMetricAttributesOnResponse = getOutgoingRequestMetricAttributesOnResponse; + const getOutgoingStableRequestMetricAttributesOnResponse = (spanAttributes) => { + const metricAttributes = {}; + if (spanAttributes[semantic_conventions_1.ATTR_NETWORK_PROTOCOL_VERSION]) { + metricAttributes[semantic_conventions_1.ATTR_NETWORK_PROTOCOL_VERSION] = spanAttributes[semantic_conventions_1.ATTR_NETWORK_PROTOCOL_VERSION]; + } + if (spanAttributes[semantic_conventions_1.ATTR_HTTP_RESPONSE_STATUS_CODE]) { + metricAttributes[semantic_conventions_1.ATTR_HTTP_RESPONSE_STATUS_CODE] = spanAttributes[semantic_conventions_1.ATTR_HTTP_RESPONSE_STATUS_CODE]; + } + return metricAttributes; + }; + exports$1.getOutgoingStableRequestMetricAttributesOnResponse = getOutgoingStableRequestMetricAttributesOnResponse; + function parseHostHeader(hostHeader, proto) { + const parts = hostHeader.split(":"); + if (parts.length === 1) { + if (proto === "http") { + return { host: parts[0], port: "80" }; + } + if (proto === "https") { + return { host: parts[0], port: "443" }; + } + return { host: parts[0] }; + } + if (parts.length === 2) { + return { + host: parts[0], + port: parts[1] + }; + } + if (parts[0].startsWith("[")) { + if (parts[parts.length - 1].endsWith("]")) { + if (proto === "http") { + return { host: hostHeader, port: "80" }; + } + if (proto === "https") { + return { host: hostHeader, port: "443" }; + } + } else if (parts[parts.length - 2].endsWith("]")) { + return { + host: parts.slice(0, -1).join(":"), + port: parts[parts.length - 1] + }; + } + } + return { host: hostHeader }; + } + function getServerAddress(request, component) { + const forwardedHeader = request.headers["forwarded"]; + if (forwardedHeader) { + for (const entry of parseForwardedHeader2(forwardedHeader)) { + if (entry.host) { + return parseHostHeader(entry.host, entry.proto); + } + } + } + const xForwardedHost = request.headers["x-forwarded-host"]; + if (typeof xForwardedHost === "string") { + if (typeof request.headers["x-forwarded-proto"] === "string") { + return parseHostHeader(xForwardedHost, request.headers["x-forwarded-proto"]); + } + if (Array.isArray(request.headers["x-forwarded-proto"])) { + return parseHostHeader(xForwardedHost, request.headers["x-forwarded-proto"][0]); + } + return parseHostHeader(xForwardedHost); + } else if (Array.isArray(xForwardedHost) && typeof xForwardedHost[0] === "string" && xForwardedHost[0].length > 0) { + if (typeof request.headers["x-forwarded-proto"] === "string") { + return parseHostHeader(xForwardedHost[0], request.headers["x-forwarded-proto"]); + } + if (Array.isArray(request.headers["x-forwarded-proto"])) { + return parseHostHeader(xForwardedHost[0], request.headers["x-forwarded-proto"][0]); + } + return parseHostHeader(xForwardedHost[0]); + } + const host = request.headers["host"]; + if (typeof host === "string" && host.length > 0) { + return parseHostHeader(host, component); + } + return null; + } + function getRemoteClientAddress(request) { + const forwardedHeader = request.headers["forwarded"]; + if (forwardedHeader) { + for (const entry of parseForwardedHeader2(forwardedHeader)) { + if (entry.for) { + return removePortFromAddress(entry.for); + } + } + } + const xForwardedFor = request.headers["x-forwarded-for"]; + if (xForwardedFor) { + let xForwardedForVal; + if (typeof xForwardedFor === "string") { + xForwardedForVal = xForwardedFor; + } else if (Array.isArray(xForwardedFor)) { + xForwardedForVal = xForwardedFor[0]; + } + if (typeof xForwardedForVal === "string") { + xForwardedForVal = xForwardedForVal.split(",")[0].trim(); + return removePortFromAddress(xForwardedForVal); + } + } + const remote = request.socket.remoteAddress; + if (remote) { + return remote; + } + return null; + } + exports$1.getRemoteClientAddress = getRemoteClientAddress; + function removePortFromAddress(input) { + try { + const { hostname: address } = new URL(`http://${input}`); + if (address.startsWith("[") && address.endsWith("]")) { + return address.slice(1, -1); + } + return address; + } catch { + return input; + } + } + function getInfoFromIncomingMessage(component, request, logger2) { + try { + if (request.headers.host) { + return new URL(request.url ?? "/", `${component}://${request.headers.host}`); + } else { + const unsafeParsedUrl = new URL( + request.url ?? "/", + // using localhost as a workaround to still use the URL constructor for parsing + `${component}://localhost` + ); + return { + pathname: unsafeParsedUrl.pathname, + search: unsafeParsedUrl.search, + toString: function() { + return unsafeParsedUrl.pathname + unsafeParsedUrl.search; + } + }; + } + } catch (e) { + logger2.verbose("Unable to get URL from request", e); + return {}; + } + } + const getIncomingRequestAttributes = (request, options, logger2) => { + const headers = request.headers; + const userAgent = headers["user-agent"]; + const ips = headers["x-forwarded-for"]; + const httpVersion = request.httpVersion; + const host = headers.host; + const hostname = host?.replace(/^(.*)(:[0-9]{1,5})/, "$1") || "localhost"; + const method = request.method; + const normalizedMethod = normalizeMethod(method); + const serverAddress = getServerAddress(request, options.component); + const serverName = options.serverName; + const remoteClientAddress = getRemoteClientAddress(request); + const newAttributes = { + [semantic_conventions_1.ATTR_HTTP_REQUEST_METHOD]: normalizedMethod, + [semantic_conventions_1.ATTR_URL_SCHEME]: options.component, + [semantic_conventions_1.ATTR_SERVER_ADDRESS]: serverAddress?.host, + [semantic_conventions_1.ATTR_NETWORK_PEER_ADDRESS]: request.socket.remoteAddress, + [semantic_conventions_1.ATTR_NETWORK_PEER_PORT]: request.socket.remotePort, + [semantic_conventions_1.ATTR_NETWORK_PROTOCOL_VERSION]: request.httpVersion, + [semantic_conventions_1.ATTR_USER_AGENT_ORIGINAL]: userAgent + }; + const parsedUrl = getInfoFromIncomingMessage(options.component, request, logger2); + if (parsedUrl?.pathname != null) { + newAttributes[semantic_conventions_1.ATTR_URL_PATH] = parsedUrl.pathname; + } + if (parsedUrl.search) { + newAttributes[semantic_conventions_1.ATTR_URL_QUERY] = parsedUrl.search.slice(1); + } + if (remoteClientAddress != null) { + newAttributes[semantic_conventions_1.ATTR_CLIENT_ADDRESS] = remoteClientAddress; + } + if (serverAddress?.port != null) { + newAttributes[semantic_conventions_1.ATTR_SERVER_PORT] = Number(serverAddress.port); + } + if (method !== normalizedMethod) { + newAttributes[semantic_conventions_1.ATTR_HTTP_REQUEST_METHOD_ORIGINAL] = method; + } + if (options.enableSyntheticSourceDetection && userAgent) { + newAttributes[semconv_1.ATTR_USER_AGENT_SYNTHETIC_TYPE] = getSyntheticType(userAgent); + } + const oldAttributes = { + [semconv_1.ATTR_HTTP_URL]: parsedUrl.toString(), + [semconv_1.ATTR_HTTP_HOST]: host, + [semconv_1.ATTR_NET_HOST_NAME]: hostname, + [semconv_1.ATTR_HTTP_METHOD]: method, + [semconv_1.ATTR_HTTP_SCHEME]: options.component + }; + if (typeof ips === "string") { + oldAttributes[semconv_1.ATTR_HTTP_CLIENT_IP] = ips.split(",")[0]; + } + if (typeof serverName === "string") { + oldAttributes[semconv_1.ATTR_HTTP_SERVER_NAME] = serverName; + } + if (parsedUrl?.pathname) { + oldAttributes[semconv_1.ATTR_HTTP_TARGET] = parsedUrl?.pathname + parsedUrl?.search || "/"; + } + if (userAgent !== void 0) { + oldAttributes[semconv_1.ATTR_HTTP_USER_AGENT] = userAgent; + } + (0, exports$1.setRequestContentLengthAttribute)(request, oldAttributes); + (0, exports$1.setAttributesFromHttpKind)(httpVersion, oldAttributes); + switch (options.semconvStability) { + case instrumentation_1.SemconvStability.STABLE: + return Object.assign(newAttributes, options.hookAttributes); + case instrumentation_1.SemconvStability.OLD: + return Object.assign(oldAttributes, options.hookAttributes); + } + return Object.assign(oldAttributes, newAttributes, options.hookAttributes); + }; + exports$1.getIncomingRequestAttributes = getIncomingRequestAttributes; + const getIncomingRequestMetricAttributes = (spanAttributes) => { + const metricAttributes = {}; + metricAttributes[semconv_1.ATTR_HTTP_SCHEME] = spanAttributes[semconv_1.ATTR_HTTP_SCHEME]; + metricAttributes[semconv_1.ATTR_HTTP_METHOD] = spanAttributes[semconv_1.ATTR_HTTP_METHOD]; + metricAttributes[semconv_1.ATTR_NET_HOST_NAME] = spanAttributes[semconv_1.ATTR_NET_HOST_NAME]; + metricAttributes[semconv_1.ATTR_HTTP_FLAVOR] = spanAttributes[semconv_1.ATTR_HTTP_FLAVOR]; + return metricAttributes; + }; + exports$1.getIncomingRequestMetricAttributes = getIncomingRequestMetricAttributes; + const getIncomingRequestAttributesOnResponse2 = (request, response, semconvStability) => { + const { socket } = request; + const { statusCode, statusMessage } = response; + const newAttributes = { + [semantic_conventions_1.ATTR_HTTP_RESPONSE_STATUS_CODE]: statusCode + }; + const rpcMetadata = (0, core_1.getRPCMetadata)(api_1.context.active()); + const oldAttributes = {}; + if (socket) { + const { localAddress, localPort, remoteAddress, remotePort } = socket; + oldAttributes[semconv_1.ATTR_NET_HOST_IP] = localAddress; + oldAttributes[semconv_1.ATTR_NET_HOST_PORT] = localPort; + oldAttributes[semconv_1.ATTR_NET_PEER_IP] = remoteAddress; + oldAttributes[semconv_1.ATTR_NET_PEER_PORT] = remotePort; + } + oldAttributes[semconv_1.ATTR_HTTP_STATUS_CODE] = statusCode; + oldAttributes[AttributeNames_1.AttributeNames.HTTP_STATUS_TEXT] = (statusMessage || "").toUpperCase(); + if (rpcMetadata?.type === core_1.RPCType.HTTP && rpcMetadata.route !== void 0) { + oldAttributes[semantic_conventions_1.ATTR_HTTP_ROUTE] = rpcMetadata.route; + newAttributes[semantic_conventions_1.ATTR_HTTP_ROUTE] = rpcMetadata.route; + } + switch (semconvStability) { + case instrumentation_1.SemconvStability.STABLE: + return newAttributes; + case instrumentation_1.SemconvStability.OLD: + return oldAttributes; + } + return Object.assign(oldAttributes, newAttributes); + }; + exports$1.getIncomingRequestAttributesOnResponse = getIncomingRequestAttributesOnResponse2; + const getIncomingRequestMetricAttributesOnResponse = (spanAttributes) => { + const metricAttributes = {}; + metricAttributes[semconv_1.ATTR_HTTP_STATUS_CODE] = spanAttributes[semconv_1.ATTR_HTTP_STATUS_CODE]; + metricAttributes[semconv_1.ATTR_NET_HOST_PORT] = spanAttributes[semconv_1.ATTR_NET_HOST_PORT]; + if (spanAttributes[semantic_conventions_1.ATTR_HTTP_ROUTE] !== void 0) { + metricAttributes[semantic_conventions_1.ATTR_HTTP_ROUTE] = spanAttributes[semantic_conventions_1.ATTR_HTTP_ROUTE]; + } + return metricAttributes; + }; + exports$1.getIncomingRequestMetricAttributesOnResponse = getIncomingRequestMetricAttributesOnResponse; + const getIncomingStableRequestMetricAttributesOnResponse = (spanAttributes) => { + const metricAttributes = {}; + if (spanAttributes[semantic_conventions_1.ATTR_HTTP_ROUTE] !== void 0) { + metricAttributes[semantic_conventions_1.ATTR_HTTP_ROUTE] = spanAttributes[semantic_conventions_1.ATTR_HTTP_ROUTE]; + } + if (spanAttributes[semantic_conventions_1.ATTR_HTTP_RESPONSE_STATUS_CODE]) { + metricAttributes[semantic_conventions_1.ATTR_HTTP_RESPONSE_STATUS_CODE] = spanAttributes[semantic_conventions_1.ATTR_HTTP_RESPONSE_STATUS_CODE]; + } + return metricAttributes; + }; + exports$1.getIncomingStableRequestMetricAttributesOnResponse = getIncomingStableRequestMetricAttributesOnResponse; + function headerCapture(type, headers) { + const normalizedHeaders = /* @__PURE__ */ new Map(); + for (let i = 0, len = headers.length; i < len; i++) { + const capturedHeader = headers[i].toLowerCase(); + normalizedHeaders.set(capturedHeader, capturedHeader.replace(/-/g, "_")); + } + return (span, getHeader) => { + for (const capturedHeader of normalizedHeaders.keys()) { + const value = getHeader(capturedHeader); + if (value === void 0) { + continue; + } + const normalizedHeader = normalizedHeaders.get(capturedHeader); + const key = `http.${type}.header.${normalizedHeader}`; + if (typeof value === "string") { + span.setAttribute(key, [value]); + } else if (Array.isArray(value)) { + span.setAttribute(key, value); + } else { + span.setAttribute(key, [value]); + } + } + }; + } + exports$1.headerCapture = headerCapture; + const KNOWN_METHODS = /* @__PURE__ */ new Set([ + // methods from https://www.rfc-editor.org/rfc/rfc9110.html#name-methods + "GET", + "HEAD", + "POST", + "PUT", + "DELETE", + "CONNECT", + "OPTIONS", + "TRACE", + // PATCH from https://www.rfc-editor.org/rfc/rfc5789.html + "PATCH" + ]); + function normalizeMethod(method) { + if (method == null) { + return "GET"; + } + const upper = method.toUpperCase(); + if (KNOWN_METHODS.has(upper)) { + return upper; + } + return "_OTHER"; + } + function parseForwardedHeader2(header) { + try { + return forwardedParse2(header); + } catch { + return []; + } + } + })(utils$e); + return utils$e; +} +var hasRequiredHttp; +function requireHttp() { + if (hasRequiredHttp) return http; + hasRequiredHttp = 1; + Object.defineProperty(http, "__esModule", { value: true }); + http.HttpInstrumentation = void 0; + const api_1 = /* @__PURE__ */ requireSrc$n(); + const core_1 = require$$1; + const url = require$$2$1; + const version_1 = /* @__PURE__ */ requireVersion$i(); + const instrumentation_1 = require$$2; + const events_1 = require$$5; + const semantic_conventions_1 = /* @__PURE__ */ requireSrc$m(); + const utils_1 = /* @__PURE__ */ requireUtils$e(); + class HttpInstrumentation extends instrumentation_1.InstrumentationBase { + /** keep track on spans not ended */ + _spanNotEnded = /* @__PURE__ */ new WeakSet(); + _headerCapture; + _semconvStability = instrumentation_1.SemconvStability.OLD; + constructor(config2 = {}) { + super("@opentelemetry/instrumentation-http", version_1.VERSION, config2); + this._headerCapture = this._createHeaderCapture(); + this._semconvStability = (0, instrumentation_1.semconvStabilityFromStr)("http", process.env.OTEL_SEMCONV_STABILITY_OPT_IN); + } + _updateMetricInstruments() { + this._oldHttpServerDurationHistogram = this.meter.createHistogram("http.server.duration", { + description: "Measures the duration of inbound HTTP requests.", + unit: "ms", + valueType: api_1.ValueType.DOUBLE + }); + this._oldHttpClientDurationHistogram = this.meter.createHistogram("http.client.duration", { + description: "Measures the duration of outbound HTTP requests.", + unit: "ms", + valueType: api_1.ValueType.DOUBLE + }); + this._stableHttpServerDurationHistogram = this.meter.createHistogram(semantic_conventions_1.METRIC_HTTP_SERVER_REQUEST_DURATION, { + description: "Duration of HTTP server requests.", + unit: "s", + valueType: api_1.ValueType.DOUBLE, + advice: { + explicitBucketBoundaries: [ + 5e-3, + 0.01, + 0.025, + 0.05, + 0.075, + 0.1, + 0.25, + 0.5, + 0.75, + 1, + 2.5, + 5, + 7.5, + 10 + ] + } + }); + this._stableHttpClientDurationHistogram = this.meter.createHistogram(semantic_conventions_1.METRIC_HTTP_CLIENT_REQUEST_DURATION, { + description: "Duration of HTTP client requests.", + unit: "s", + valueType: api_1.ValueType.DOUBLE, + advice: { + explicitBucketBoundaries: [ + 5e-3, + 0.01, + 0.025, + 0.05, + 0.075, + 0.1, + 0.25, + 0.5, + 0.75, + 1, + 2.5, + 5, + 7.5, + 10 + ] + } + }); + } + _recordServerDuration(durationMs, oldAttributes, stableAttributes) { + if (this._semconvStability & instrumentation_1.SemconvStability.OLD) { + this._oldHttpServerDurationHistogram.record(durationMs, oldAttributes); + } + if (this._semconvStability & instrumentation_1.SemconvStability.STABLE) { + this._stableHttpServerDurationHistogram.record(durationMs / 1e3, stableAttributes); + } + } + _recordClientDuration(durationMs, oldAttributes, stableAttributes) { + if (this._semconvStability & instrumentation_1.SemconvStability.OLD) { + this._oldHttpClientDurationHistogram.record(durationMs, oldAttributes); + } + if (this._semconvStability & instrumentation_1.SemconvStability.STABLE) { + this._stableHttpClientDurationHistogram.record(durationMs / 1e3, stableAttributes); + } + } + setConfig(config2 = {}) { + super.setConfig(config2); + this._headerCapture = this._createHeaderCapture(); + } + init() { + return [this._getHttpsInstrumentation(), this._getHttpInstrumentation()]; + } + _getHttpInstrumentation() { + return new instrumentation_1.InstrumentationNodeModuleDefinition("http", ["*"], (moduleExports) => { + const isESM = moduleExports[Symbol.toStringTag] === "Module"; + if (!this.getConfig().disableOutgoingRequestInstrumentation) { + const patchedRequest = this._wrap(moduleExports, "request", this._getPatchOutgoingRequestFunction("http")); + const patchedGet = this._wrap(moduleExports, "get", this._getPatchOutgoingGetFunction(patchedRequest)); + if (isESM) { + moduleExports.default.request = patchedRequest; + moduleExports.default.get = patchedGet; + } + } + if (!this.getConfig().disableIncomingRequestInstrumentation) { + this._wrap(moduleExports.Server.prototype, "emit", this._getPatchIncomingRequestFunction("http")); + } + return moduleExports; + }, (moduleExports) => { + if (moduleExports === void 0) + return; + if (!this.getConfig().disableOutgoingRequestInstrumentation) { + this._unwrap(moduleExports, "request"); + this._unwrap(moduleExports, "get"); + } + if (!this.getConfig().disableIncomingRequestInstrumentation) { + this._unwrap(moduleExports.Server.prototype, "emit"); + } + }); + } + _getHttpsInstrumentation() { + return new instrumentation_1.InstrumentationNodeModuleDefinition("https", ["*"], (moduleExports) => { + const isESM = moduleExports[Symbol.toStringTag] === "Module"; + if (!this.getConfig().disableOutgoingRequestInstrumentation) { + const patchedRequest = this._wrap(moduleExports, "request", this._getPatchHttpsOutgoingRequestFunction("https")); + const patchedGet = this._wrap(moduleExports, "get", this._getPatchHttpsOutgoingGetFunction(patchedRequest)); + if (isESM) { + moduleExports.default.request = patchedRequest; + moduleExports.default.get = patchedGet; + } + } + if (!this.getConfig().disableIncomingRequestInstrumentation) { + this._wrap(moduleExports.Server.prototype, "emit", this._getPatchIncomingRequestFunction("https")); + } + return moduleExports; + }, (moduleExports) => { + if (moduleExports === void 0) + return; + if (!this.getConfig().disableOutgoingRequestInstrumentation) { + this._unwrap(moduleExports, "request"); + this._unwrap(moduleExports, "get"); + } + if (!this.getConfig().disableIncomingRequestInstrumentation) { + this._unwrap(moduleExports.Server.prototype, "emit"); + } + }); + } + /** + * Creates spans for incoming requests, restoring spans' context if applied. + */ + _getPatchIncomingRequestFunction(component) { + return (original) => { + return this._incomingRequestFunction(component, original); + }; + } + /** + * Creates spans for outgoing requests, sending spans' context for distributed + * tracing. + */ + _getPatchOutgoingRequestFunction(component) { + return (original) => { + return this._outgoingRequestFunction(component, original); + }; + } + _getPatchOutgoingGetFunction(clientRequest) { + return (_original) => { + return function outgoingGetRequest(options, ...args) { + const req = clientRequest(options, ...args); + req.end(); + return req; + }; + }; + } + /** Patches HTTPS outgoing requests */ + _getPatchHttpsOutgoingRequestFunction(component) { + return (original) => { + const instrumentation2 = this; + return function httpsOutgoingRequest(options, ...args) { + if (component === "https" && typeof options === "object" && options?.constructor?.name !== "URL") { + options = Object.assign({}, options); + instrumentation2._setDefaultOptions(options); + } + return instrumentation2._getPatchOutgoingRequestFunction(component)(original)(options, ...args); + }; + }; + } + _setDefaultOptions(options) { + options.protocol = options.protocol || "https:"; + options.port = options.port || 443; + } + /** Patches HTTPS outgoing get requests */ + _getPatchHttpsOutgoingGetFunction(clientRequest) { + return (original) => { + const instrumentation2 = this; + return function httpsOutgoingRequest(options, ...args) { + return instrumentation2._getPatchOutgoingGetFunction(clientRequest)(original)(options, ...args); + }; + }; + } + /** + * Attach event listeners to a client request to end span and add span attributes. + * + * @param request The original request object. + * @param span representing the current operation + * @param startTime representing the start time of the request to calculate duration in Metric + * @param oldMetricAttributes metric attributes for old semantic conventions + * @param stableMetricAttributes metric attributes for new semantic conventions + */ + _traceClientRequest(request, span, startTime, oldMetricAttributes, stableMetricAttributes) { + if (this.getConfig().requestHook) { + this._callRequestHook(span, request); + } + let responseFinished = false; + request.prependListener("response", (response) => { + this._diag.debug("outgoingRequest on response()"); + if (request.listenerCount("response") <= 1) { + response.resume(); + } + const responseAttributes = (0, utils_1.getOutgoingRequestAttributesOnResponse)(response, this._semconvStability); + span.setAttributes(responseAttributes); + oldMetricAttributes = Object.assign(oldMetricAttributes, (0, utils_1.getOutgoingRequestMetricAttributesOnResponse)(responseAttributes)); + stableMetricAttributes = Object.assign(stableMetricAttributes, (0, utils_1.getOutgoingStableRequestMetricAttributesOnResponse)(responseAttributes)); + if (this.getConfig().responseHook) { + this._callResponseHook(span, response); + } + this._headerCapture.client.captureRequestHeaders(span, (header) => request.getHeader(header)); + this._headerCapture.client.captureResponseHeaders(span, (header) => response.headers[header]); + api_1.context.bind(api_1.context.active(), response); + const endHandler = () => { + this._diag.debug("outgoingRequest on end()"); + if (responseFinished) { + return; + } + responseFinished = true; + let status2; + if (response.aborted && !response.complete) { + status2 = { code: api_1.SpanStatusCode.ERROR }; + } else { + status2 = { + code: (0, utils_1.parseResponseStatus)(api_1.SpanKind.CLIENT, response.statusCode) + }; + } + span.setStatus(status2); + if (this.getConfig().applyCustomAttributesOnSpan) { + (0, instrumentation_1.safeExecuteInTheMiddle)(() => this.getConfig().applyCustomAttributesOnSpan(span, request, response), () => { + }, true); + } + this._closeHttpSpan(span, api_1.SpanKind.CLIENT, startTime, oldMetricAttributes, stableMetricAttributes); + }; + response.on("end", endHandler); + response.on(events_1.errorMonitor, (error2) => { + this._diag.debug("outgoingRequest on error()", error2); + if (responseFinished) { + return; + } + responseFinished = true; + this._onOutgoingRequestError(span, oldMetricAttributes, stableMetricAttributes, startTime, error2); + }); + }); + request.on("close", () => { + this._diag.debug("outgoingRequest on request close()"); + if (request.aborted || responseFinished) { + return; + } + responseFinished = true; + this._closeHttpSpan(span, api_1.SpanKind.CLIENT, startTime, oldMetricAttributes, stableMetricAttributes); + }); + request.on(events_1.errorMonitor, (error2) => { + this._diag.debug("outgoingRequest on request error()", error2); + if (responseFinished) { + return; + } + responseFinished = true; + this._onOutgoingRequestError(span, oldMetricAttributes, stableMetricAttributes, startTime, error2); + }); + this._diag.debug("http.ClientRequest return request"); + return request; + } + _incomingRequestFunction(component, original) { + const instrumentation2 = this; + return function incomingRequest(event, ...args) { + if (event !== "request") { + return original.apply(this, [event, ...args]); + } + const request = args[0]; + const response = args[1]; + const method = request.method || "GET"; + instrumentation2._diag.debug(`${component} instrumentation incomingRequest`); + if ((0, instrumentation_1.safeExecuteInTheMiddle)(() => instrumentation2.getConfig().ignoreIncomingRequestHook?.(request), (e) => { + if (e != null) { + instrumentation2._diag.error("caught ignoreIncomingRequestHook error: ", e); + } + }, true)) { + return api_1.context.with((0, core_1.suppressTracing)(api_1.context.active()), () => { + api_1.context.bind(api_1.context.active(), request); + api_1.context.bind(api_1.context.active(), response); + return original.apply(this, [event, ...args]); + }); + } + const headers = request.headers; + const spanAttributes = (0, utils_1.getIncomingRequestAttributes)(request, { + component, + serverName: instrumentation2.getConfig().serverName, + hookAttributes: instrumentation2._callStartSpanHook(request, instrumentation2.getConfig().startIncomingSpanHook), + semconvStability: instrumentation2._semconvStability, + enableSyntheticSourceDetection: instrumentation2.getConfig().enableSyntheticSourceDetection || false + }, instrumentation2._diag); + const spanOptions = { + kind: api_1.SpanKind.SERVER, + attributes: spanAttributes + }; + const startTime = (0, core_1.hrTime)(); + const oldMetricAttributes = (0, utils_1.getIncomingRequestMetricAttributes)(spanAttributes); + const stableMetricAttributes = { + [semantic_conventions_1.ATTR_HTTP_REQUEST_METHOD]: spanAttributes[semantic_conventions_1.ATTR_HTTP_REQUEST_METHOD], + [semantic_conventions_1.ATTR_URL_SCHEME]: spanAttributes[semantic_conventions_1.ATTR_URL_SCHEME] + }; + if (spanAttributes[semantic_conventions_1.ATTR_NETWORK_PROTOCOL_VERSION]) { + stableMetricAttributes[semantic_conventions_1.ATTR_NETWORK_PROTOCOL_VERSION] = spanAttributes[semantic_conventions_1.ATTR_NETWORK_PROTOCOL_VERSION]; + } + const ctx = api_1.propagation.extract(api_1.ROOT_CONTEXT, headers); + const span = instrumentation2._startHttpSpan(method, spanOptions, ctx); + const rpcMetadata = { + type: core_1.RPCType.HTTP, + span + }; + return api_1.context.with((0, core_1.setRPCMetadata)(api_1.trace.setSpan(ctx, span), rpcMetadata), () => { + api_1.context.bind(api_1.context.active(), request); + api_1.context.bind(api_1.context.active(), response); + if (instrumentation2.getConfig().requestHook) { + instrumentation2._callRequestHook(span, request); + } + if (instrumentation2.getConfig().responseHook) { + instrumentation2._callResponseHook(span, response); + } + instrumentation2._headerCapture.server.captureRequestHeaders(span, (header) => request.headers[header]); + let hasError = false; + response.on("close", () => { + if (hasError) { + return; + } + instrumentation2._onServerResponseFinish(request, response, span, oldMetricAttributes, stableMetricAttributes, startTime); + }); + response.on(events_1.errorMonitor, (err) => { + hasError = true; + instrumentation2._onServerResponseError(span, oldMetricAttributes, stableMetricAttributes, startTime, err); + }); + return (0, instrumentation_1.safeExecuteInTheMiddle)(() => original.apply(this, [event, ...args]), (error2) => { + if (error2) { + instrumentation2._onServerResponseError(span, oldMetricAttributes, stableMetricAttributes, startTime, error2); + throw error2; + } + }); + }); + }; + } + _outgoingRequestFunction(component, original) { + const instrumentation2 = this; + return function outgoingRequest(options, ...args) { + if (!(0, utils_1.isValidOptionsType)(options)) { + return original.apply(this, [options, ...args]); + } + const extraOptions = typeof args[0] === "object" && (typeof options === "string" || options instanceof url.URL) ? args.shift() : void 0; + const { method, invalidUrl, optionsParsed } = (0, utils_1.getRequestInfo)(instrumentation2._diag, options, extraOptions); + if ((0, instrumentation_1.safeExecuteInTheMiddle)(() => instrumentation2.getConfig().ignoreOutgoingRequestHook?.(optionsParsed), (e) => { + if (e != null) { + instrumentation2._diag.error("caught ignoreOutgoingRequestHook error: ", e); + } + }, true)) { + return original.apply(this, [optionsParsed, ...args]); + } + const { hostname, port } = (0, utils_1.extractHostnameAndPort)(optionsParsed); + const attributes = (0, utils_1.getOutgoingRequestAttributes)(optionsParsed, { + component, + port, + hostname, + hookAttributes: instrumentation2._callStartSpanHook(optionsParsed, instrumentation2.getConfig().startOutgoingSpanHook), + redactedQueryParams: instrumentation2.getConfig().redactedQueryParams + // Added config for adding custom query strings + }, instrumentation2._semconvStability, instrumentation2.getConfig().enableSyntheticSourceDetection || false); + const startTime = (0, core_1.hrTime)(); + const oldMetricAttributes = (0, utils_1.getOutgoingRequestMetricAttributes)(attributes); + const stableMetricAttributes = { + [semantic_conventions_1.ATTR_HTTP_REQUEST_METHOD]: attributes[semantic_conventions_1.ATTR_HTTP_REQUEST_METHOD], + [semantic_conventions_1.ATTR_SERVER_ADDRESS]: attributes[semantic_conventions_1.ATTR_SERVER_ADDRESS], + [semantic_conventions_1.ATTR_SERVER_PORT]: attributes[semantic_conventions_1.ATTR_SERVER_PORT] + }; + if (attributes[semantic_conventions_1.ATTR_HTTP_RESPONSE_STATUS_CODE]) { + stableMetricAttributes[semantic_conventions_1.ATTR_HTTP_RESPONSE_STATUS_CODE] = attributes[semantic_conventions_1.ATTR_HTTP_RESPONSE_STATUS_CODE]; + } + if (attributes[semantic_conventions_1.ATTR_NETWORK_PROTOCOL_VERSION]) { + stableMetricAttributes[semantic_conventions_1.ATTR_NETWORK_PROTOCOL_VERSION] = attributes[semantic_conventions_1.ATTR_NETWORK_PROTOCOL_VERSION]; + } + const spanOptions = { + kind: api_1.SpanKind.CLIENT, + attributes + }; + const span = instrumentation2._startHttpSpan(method, spanOptions); + const parentContext = api_1.context.active(); + const requestContext = api_1.trace.setSpan(parentContext, span); + if (!optionsParsed.headers) { + optionsParsed.headers = {}; + } else { + optionsParsed.headers = Object.assign({}, optionsParsed.headers); + } + api_1.propagation.inject(requestContext, optionsParsed.headers); + return api_1.context.with(requestContext, () => { + const cb = args[args.length - 1]; + if (typeof cb === "function") { + args[args.length - 1] = api_1.context.bind(parentContext, cb); + } + const request = (0, instrumentation_1.safeExecuteInTheMiddle)(() => { + if (invalidUrl) { + return original.apply(this, [options, ...args]); + } else { + return original.apply(this, [optionsParsed, ...args]); + } + }, (error2) => { + if (error2) { + instrumentation2._onOutgoingRequestError(span, oldMetricAttributes, stableMetricAttributes, startTime, error2); + throw error2; + } + }); + instrumentation2._diag.debug(`${component} instrumentation outgoingRequest`); + api_1.context.bind(parentContext, request); + return instrumentation2._traceClientRequest(request, span, startTime, oldMetricAttributes, stableMetricAttributes); + }); + }; + } + _onServerResponseFinish(request, response, span, oldMetricAttributes, stableMetricAttributes, startTime) { + const attributes = (0, utils_1.getIncomingRequestAttributesOnResponse)(request, response, this._semconvStability); + oldMetricAttributes = Object.assign(oldMetricAttributes, (0, utils_1.getIncomingRequestMetricAttributesOnResponse)(attributes)); + stableMetricAttributes = Object.assign(stableMetricAttributes, (0, utils_1.getIncomingStableRequestMetricAttributesOnResponse)(attributes)); + this._headerCapture.server.captureResponseHeaders(span, (header) => response.getHeader(header)); + span.setAttributes(attributes).setStatus({ + code: (0, utils_1.parseResponseStatus)(api_1.SpanKind.SERVER, response.statusCode) + }); + const route = attributes[semantic_conventions_1.ATTR_HTTP_ROUTE]; + if (route) { + span.updateName(`${request.method || "GET"} ${route}`); + } + if (this.getConfig().applyCustomAttributesOnSpan) { + (0, instrumentation_1.safeExecuteInTheMiddle)(() => this.getConfig().applyCustomAttributesOnSpan(span, request, response), () => { + }, true); + } + this._closeHttpSpan(span, api_1.SpanKind.SERVER, startTime, oldMetricAttributes, stableMetricAttributes); + } + _onOutgoingRequestError(span, oldMetricAttributes, stableMetricAttributes, startTime, error2) { + (0, utils_1.setSpanWithError)(span, error2, this._semconvStability); + stableMetricAttributes[semantic_conventions_1.ATTR_ERROR_TYPE] = error2.name; + this._closeHttpSpan(span, api_1.SpanKind.CLIENT, startTime, oldMetricAttributes, stableMetricAttributes); + } + _onServerResponseError(span, oldMetricAttributes, stableMetricAttributes, startTime, error2) { + (0, utils_1.setSpanWithError)(span, error2, this._semconvStability); + stableMetricAttributes[semantic_conventions_1.ATTR_ERROR_TYPE] = error2.name; + this._closeHttpSpan(span, api_1.SpanKind.SERVER, startTime, oldMetricAttributes, stableMetricAttributes); + } + _startHttpSpan(name, options, ctx = api_1.context.active()) { + const requireParent = options.kind === api_1.SpanKind.CLIENT ? this.getConfig().requireParentforOutgoingSpans : this.getConfig().requireParentforIncomingSpans; + let span; + const currentSpan = api_1.trace.getSpan(ctx); + if (requireParent === true && (!currentSpan || !api_1.trace.isSpanContextValid(currentSpan.spanContext()))) { + span = api_1.trace.wrapSpanContext(api_1.INVALID_SPAN_CONTEXT); + } else if (requireParent === true && currentSpan?.spanContext().isRemote) { + span = currentSpan; + } else { + span = this.tracer.startSpan(name, options, ctx); + } + this._spanNotEnded.add(span); + return span; + } + _closeHttpSpan(span, spanKind, startTime, oldMetricAttributes, stableMetricAttributes) { + if (!this._spanNotEnded.has(span)) { + return; + } + span.end(); + this._spanNotEnded.delete(span); + const duration = (0, core_1.hrTimeToMilliseconds)((0, core_1.hrTimeDuration)(startTime, (0, core_1.hrTime)())); + if (spanKind === api_1.SpanKind.SERVER) { + this._recordServerDuration(duration, oldMetricAttributes, stableMetricAttributes); + } else if (spanKind === api_1.SpanKind.CLIENT) { + this._recordClientDuration(duration, oldMetricAttributes, stableMetricAttributes); + } + } + _callResponseHook(span, response) { + (0, instrumentation_1.safeExecuteInTheMiddle)(() => this.getConfig().responseHook(span, response), () => { + }, true); + } + _callRequestHook(span, request) { + (0, instrumentation_1.safeExecuteInTheMiddle)(() => this.getConfig().requestHook(span, request), () => { + }, true); + } + _callStartSpanHook(request, hookFunc) { + if (typeof hookFunc === "function") { + return (0, instrumentation_1.safeExecuteInTheMiddle)(() => hookFunc(request), () => { + }, true); + } + } + _createHeaderCapture() { + const config2 = this.getConfig(); + return { + client: { + captureRequestHeaders: (0, utils_1.headerCapture)("request", config2.headersToSpanAttributes?.client?.requestHeaders ?? []), + captureResponseHeaders: (0, utils_1.headerCapture)("response", config2.headersToSpanAttributes?.client?.responseHeaders ?? []) + }, + server: { + captureRequestHeaders: (0, utils_1.headerCapture)("request", config2.headersToSpanAttributes?.server?.requestHeaders ?? []), + captureResponseHeaders: (0, utils_1.headerCapture)("response", config2.headersToSpanAttributes?.server?.responseHeaders ?? []) + } + }; + } + } + http.HttpInstrumentation = HttpInstrumentation; + return http; +} +var hasRequiredSrc$l; +function requireSrc$l() { + if (hasRequiredSrc$l) return src$m; + hasRequiredSrc$l = 1; + (function(exports$1) { + Object.defineProperty(exports$1, "__esModule", { value: true }); + exports$1.HttpInstrumentation = void 0; + var http_1 = /* @__PURE__ */ requireHttp(); + Object.defineProperty(exports$1, "HttpInstrumentation", { enumerable: true, get: function() { + return http_1.HttpInstrumentation; + } }); + })(src$m); + return src$m; +} +var srcExports$j = /* @__PURE__ */ requireSrc$l(); +const handlers = {}; +const instrumented = {}; +function addHandler(type, handler) { + handlers[type] = handlers[type] || []; + handlers[type].push(handler); +} +function maybeInstrument(type, instrumentFn) { + if (!instrumented[type]) { + instrumented[type] = true; + try { + instrumentFn(); + } catch (e) { + DEBUG_BUILD$3 && debug$2.error(`Error while instrumenting ${type}`, e); + } + } +} +function triggerHandlers(type, data) { + const typeHandlers = type && handlers[type]; + if (!typeHandlers) { + return; + } + for (const handler of typeHandlers) { + try { + handler(data); + } catch (e) { + DEBUG_BUILD$3 && debug$2.error( + `Error while triggering instrumentation handler. +Type: ${type} +Name: ${getFunctionName(handler)} +Error:`, + e + ); + } + } +} +let _oldOnErrorHandler = null; +function addGlobalErrorInstrumentationHandler(handler) { + const type = "error"; + addHandler(type, handler); + maybeInstrument(type, instrumentError); +} +function instrumentError() { + _oldOnErrorHandler = GLOBAL_OBJ.onerror; + GLOBAL_OBJ.onerror = function(msg, url, line, column, error2) { + const handlerData = { + column, + error: error2, + line, + msg, + url + }; + triggerHandlers("error", handlerData); + if (_oldOnErrorHandler) { + return _oldOnErrorHandler.apply(this, arguments); + } + return false; + }; + GLOBAL_OBJ.onerror.__SENTRY_INSTRUMENTED__ = true; +} +let _oldOnUnhandledRejectionHandler = null; +function addGlobalUnhandledRejectionInstrumentationHandler(handler) { + const type = "unhandledrejection"; + addHandler(type, handler); + maybeInstrument(type, instrumentUnhandledRejection); +} +function instrumentUnhandledRejection() { + _oldOnUnhandledRejectionHandler = GLOBAL_OBJ.onunhandledrejection; + GLOBAL_OBJ.onunhandledrejection = function(e) { + const handlerData = e; + triggerHandlers("unhandledrejection", handlerData); + if (_oldOnUnhandledRejectionHandler) { + return _oldOnUnhandledRejectionHandler.apply(this, arguments); + } + return true; + }; + GLOBAL_OBJ.onunhandledrejection.__SENTRY_INSTRUMENTED__ = true; +} +let errorsInstrumented = false; +function registerSpanErrorInstrumentation() { + if (errorsInstrumented) { + return; + } + function errorCallback() { + const activeSpan = getActiveSpan$1(); + const rootSpan = activeSpan && getRootSpan(activeSpan); + if (rootSpan) { + const message = "internal_error"; + DEBUG_BUILD$3 && debug$2.log(`[Tracing] Root span: ${message} -> Global error occurred`); + rootSpan.setStatus({ code: SPAN_STATUS_ERROR, message }); + } + } + errorCallback.tag = "sentry_tracingErrorCallback"; + errorsInstrumented = true; + addGlobalErrorInstrumentationHandler(errorCallback); + addGlobalUnhandledRejectionInstrumentationHandler(errorCallback); +} +const STATE_PENDING = 0; +const STATE_RESOLVED = 1; +const STATE_REJECTED = 2; +function resolvedSyncPromise(value) { + return new SyncPromise((resolve) => { + resolve(value); + }); +} +function rejectedSyncPromise(reason) { + return new SyncPromise((_, reject) => { + reject(reason); + }); +} +class SyncPromise { + constructor(executor) { + this._state = STATE_PENDING; + this._handlers = []; + this._runExecutor(executor); + } + /** @inheritdoc */ + then(onfulfilled, onrejected) { + return new SyncPromise((resolve, reject) => { + this._handlers.push([ + false, + (result) => { + if (!onfulfilled) { + resolve(result); + } else { + try { + resolve(onfulfilled(result)); + } catch (e) { + reject(e); + } + } + }, + (reason) => { + if (!onrejected) { + reject(reason); + } else { + try { + resolve(onrejected(reason)); + } catch (e) { + reject(e); + } + } + } + ]); + this._executeHandlers(); + }); + } + /** @inheritdoc */ + catch(onrejected) { + return this.then((val) => val, onrejected); + } + /** @inheritdoc */ + finally(onfinally) { + return new SyncPromise((resolve, reject) => { + let val; + let isRejected; + return this.then( + (value) => { + isRejected = false; + val = value; + if (onfinally) { + onfinally(); + } + }, + (reason) => { + isRejected = true; + val = reason; + if (onfinally) { + onfinally(); + } + } + ).then(() => { + if (isRejected) { + reject(val); + return; + } + resolve(val); + }); + }); + } + /** Excute the resolve/reject handlers. */ + _executeHandlers() { + if (this._state === STATE_PENDING) { + return; + } + const cachedHandlers = this._handlers.slice(); + this._handlers = []; + cachedHandlers.forEach((handler) => { + if (handler[0]) { + return; + } + if (this._state === STATE_RESOLVED) { + handler[1](this._value); + } + if (this._state === STATE_REJECTED) { + handler[2](this._value); + } + handler[0] = true; + }); + } + /** Run the executor for the SyncPromise. */ + _runExecutor(executor) { + const setResult = (state, value) => { + if (this._state !== STATE_PENDING) { + return; + } + if (isThenable(value)) { + void value.then(resolve, reject); + return; + } + this._state = state; + this._value = value; + this._executeHandlers(); + }; + const resolve = (value) => { + setResult(STATE_RESOLVED, value); + }; + const reject = (reason) => { + setResult(STATE_REJECTED, reason); + }; + try { + executor(resolve, reject); + } catch (e) { + reject(e); + } + } +} +function notifyEventProcessors(processors, event, hint, index = 0) { + try { + const result = _notifyEventProcessors(event, hint, processors, index); + return isThenable(result) ? result : resolvedSyncPromise(result); + } catch (error2) { + return rejectedSyncPromise(error2); + } +} +function _notifyEventProcessors(event, hint, processors, index) { + const processor = processors[index]; + if (!event || !processor) { + return event; + } + const result = processor({ ...event }, hint); + DEBUG_BUILD$3 && result === null && debug$2.log(`Event processor "${processor.id || "?"}" dropped event`); + if (isThenable(result)) { + return result.then((final) => _notifyEventProcessors(final, hint, processors, index + 1)); + } + return _notifyEventProcessors(result, hint, processors, index + 1); +} +let parsedStackResults; +let lastSentryKeysCount; +let lastNativeKeysCount; +let cachedFilenameDebugIds; +function getFilenameToDebugIdMap(stackParser) { + const sentryDebugIdMap = GLOBAL_OBJ._sentryDebugIds; + const nativeDebugIdMap = GLOBAL_OBJ._debugIds; + if (!sentryDebugIdMap && !nativeDebugIdMap) { + return {}; + } + const sentryDebugIdKeys = sentryDebugIdMap ? Object.keys(sentryDebugIdMap) : []; + const nativeDebugIdKeys = nativeDebugIdMap ? Object.keys(nativeDebugIdMap) : []; + if (cachedFilenameDebugIds && sentryDebugIdKeys.length === lastSentryKeysCount && nativeDebugIdKeys.length === lastNativeKeysCount) { + return cachedFilenameDebugIds; + } + lastSentryKeysCount = sentryDebugIdKeys.length; + lastNativeKeysCount = nativeDebugIdKeys.length; + cachedFilenameDebugIds = {}; + if (!parsedStackResults) { + parsedStackResults = {}; + } + const processDebugIds = (debugIdKeys, debugIdMap) => { + for (const key of debugIdKeys) { + const debugId = debugIdMap[key]; + const result = parsedStackResults?.[key]; + if (result && cachedFilenameDebugIds && debugId) { + cachedFilenameDebugIds[result[0]] = debugId; + if (parsedStackResults) { + parsedStackResults[key] = [result[0], debugId]; + } + } else if (debugId) { + const parsedStack = stackParser(key); + for (let i = parsedStack.length - 1; i >= 0; i--) { + const stackFrame = parsedStack[i]; + const filename = stackFrame?.filename; + if (filename && cachedFilenameDebugIds && parsedStackResults) { + cachedFilenameDebugIds[filename] = debugId; + parsedStackResults[key] = [filename, debugId]; + break; + } + } + } + } + }; + if (sentryDebugIdMap) { + processDebugIds(sentryDebugIdKeys, sentryDebugIdMap); + } + if (nativeDebugIdMap) { + processDebugIds(nativeDebugIdKeys, nativeDebugIdMap); + } + return cachedFilenameDebugIds; +} +function applyScopeDataToEvent(event, data) { + const { fingerprint, span, breadcrumbs, sdkProcessingMetadata } = data; + applyDataToEvent(event, data); + if (span) { + applySpanToEvent(event, span); + } + applyFingerprintToEvent(event, fingerprint); + applyBreadcrumbsToEvent(event, breadcrumbs); + applySdkMetadataToEvent(event, sdkProcessingMetadata); +} +function mergeScopeData(data, mergeData) { + const { + extra, + tags, + attributes, + user, + contexts, + level, + sdkProcessingMetadata, + breadcrumbs, + fingerprint, + eventProcessors, + attachments, + propagationContext, + transactionName, + span + } = mergeData; + mergeAndOverwriteScopeData(data, "extra", extra); + mergeAndOverwriteScopeData(data, "tags", tags); + mergeAndOverwriteScopeData(data, "attributes", attributes); + mergeAndOverwriteScopeData(data, "user", user); + mergeAndOverwriteScopeData(data, "contexts", contexts); + data.sdkProcessingMetadata = merge$1(data.sdkProcessingMetadata, sdkProcessingMetadata, 2); + if (level) { + data.level = level; + } + if (transactionName) { + data.transactionName = transactionName; + } + if (span) { + data.span = span; + } + if (breadcrumbs.length) { + data.breadcrumbs = [...data.breadcrumbs, ...breadcrumbs]; + } + if (fingerprint.length) { + data.fingerprint = [...data.fingerprint, ...fingerprint]; + } + if (eventProcessors.length) { + data.eventProcessors = [...data.eventProcessors, ...eventProcessors]; + } + if (attachments.length) { + data.attachments = [...data.attachments, ...attachments]; + } + data.propagationContext = { ...data.propagationContext, ...propagationContext }; +} +function mergeAndOverwriteScopeData(data, prop, mergeVal) { + data[prop] = merge$1(data[prop], mergeVal, 1); +} +function getCombinedScopeData(isolationScope, currentScope) { + const scopeData = getGlobalScope().getScopeData(); + isolationScope && mergeScopeData(scopeData, isolationScope.getScopeData()); + currentScope && mergeScopeData(scopeData, currentScope.getScopeData()); + return scopeData; +} +function applyDataToEvent(event, data) { + const { extra, tags, user, contexts, level, transactionName } = data; + if (Object.keys(extra).length) { + event.extra = { ...extra, ...event.extra }; + } + if (Object.keys(tags).length) { + event.tags = { ...tags, ...event.tags }; + } + if (Object.keys(user).length) { + event.user = { ...user, ...event.user }; + } + if (Object.keys(contexts).length) { + event.contexts = { ...contexts, ...event.contexts }; + } + if (level) { + event.level = level; + } + if (transactionName && event.type !== "transaction") { + event.transaction = transactionName; + } +} +function applyBreadcrumbsToEvent(event, breadcrumbs) { + const mergedBreadcrumbs = [...event.breadcrumbs || [], ...breadcrumbs]; + event.breadcrumbs = mergedBreadcrumbs.length ? mergedBreadcrumbs : void 0; +} +function applySdkMetadataToEvent(event, sdkProcessingMetadata) { + event.sdkProcessingMetadata = { + ...event.sdkProcessingMetadata, + ...sdkProcessingMetadata + }; +} +function applySpanToEvent(event, span) { + event.contexts = { + trace: spanToTraceContext(span), + ...event.contexts + }; + event.sdkProcessingMetadata = { + dynamicSamplingContext: getDynamicSamplingContextFromSpan(span), + ...event.sdkProcessingMetadata + }; + const rootSpan = getRootSpan(span); + const transactionName = spanToJSON(rootSpan).description; + if (transactionName && !event.transaction && event.type === "transaction") { + event.transaction = transactionName; + } +} +function applyFingerprintToEvent(event, fingerprint) { + event.fingerprint = event.fingerprint ? Array.isArray(event.fingerprint) ? event.fingerprint : [event.fingerprint] : []; + if (fingerprint) { + event.fingerprint = event.fingerprint.concat(fingerprint); + } + if (!event.fingerprint.length) { + delete event.fingerprint; + } +} +function prepareEvent(options, event, hint, scope, client, isolationScope) { + const { normalizeDepth = 3, normalizeMaxBreadth = 1e3 } = options; + const prepared = { + ...event, + event_id: event.event_id || hint.event_id || uuid4(), + timestamp: event.timestamp || dateTimestampInSeconds() + }; + const integrations = hint.integrations || options.integrations.map((i) => i.name); + applyClientOptions(prepared, options); + applyIntegrationsMetadata(prepared, integrations); + if (client) { + client.emit("applyFrameMetadata", event); + } + if (event.type === void 0) { + applyDebugIds(prepared, options.stackParser); + } + const finalScope = getFinalScope(scope, hint.captureContext); + if (hint.mechanism) { + addExceptionMechanism(prepared, hint.mechanism); + } + const clientEventProcessors = client ? client.getEventProcessors() : []; + const data = getCombinedScopeData(isolationScope, finalScope); + const attachments = [...hint.attachments || [], ...data.attachments]; + if (attachments.length) { + hint.attachments = attachments; + } + applyScopeDataToEvent(prepared, data); + const eventProcessors = [ + ...clientEventProcessors, + // Run scope event processors _after_ all other processors + ...data.eventProcessors + ]; + const result = notifyEventProcessors(eventProcessors, prepared, hint); + return result.then((evt) => { + if (evt) { + applyDebugMeta(evt); + } + if (typeof normalizeDepth === "number" && normalizeDepth > 0) { + return normalizeEvent(evt, normalizeDepth, normalizeMaxBreadth); + } + return evt; + }); +} +function applyClientOptions(event, options) { + const { environment, release, dist, maxValueLength } = options; + event.environment = event.environment || environment || DEFAULT_ENVIRONMENT; + if (!event.release && release) { + event.release = release; + } + if (!event.dist && dist) { + event.dist = dist; + } + const request = event.request; + if (request?.url && maxValueLength) { + request.url = truncate(request.url, maxValueLength); + } + if (maxValueLength) { + event.exception?.values?.forEach((exception) => { + if (exception.value) { + exception.value = truncate(exception.value, maxValueLength); + } + }); + } +} +function applyDebugIds(event, stackParser) { + const filenameDebugIdMap = getFilenameToDebugIdMap(stackParser); + event.exception?.values?.forEach((exception) => { + exception.stacktrace?.frames?.forEach((frame) => { + if (frame.filename) { + frame.debug_id = filenameDebugIdMap[frame.filename]; + } + }); + }); +} +function applyDebugMeta(event) { + const filenameDebugIdMap = {}; + event.exception?.values?.forEach((exception) => { + exception.stacktrace?.frames?.forEach((frame) => { + if (frame.debug_id) { + if (frame.abs_path) { + filenameDebugIdMap[frame.abs_path] = frame.debug_id; + } else if (frame.filename) { + filenameDebugIdMap[frame.filename] = frame.debug_id; + } + delete frame.debug_id; + } + }); + }); + if (Object.keys(filenameDebugIdMap).length === 0) { + return; + } + event.debug_meta = event.debug_meta || {}; + event.debug_meta.images = event.debug_meta.images || []; + const images = event.debug_meta.images; + Object.entries(filenameDebugIdMap).forEach(([filename, debug_id]) => { + images.push({ + type: "sourcemap", + code_file: filename, + debug_id + }); + }); +} +function applyIntegrationsMetadata(event, integrationNames) { + if (integrationNames.length > 0) { + event.sdk = event.sdk || {}; + event.sdk.integrations = [...event.sdk.integrations || [], ...integrationNames]; + } +} +function normalizeEvent(event, depth, maxBreadth) { + if (!event) { + return null; + } + const normalized = { + ...event, + ...event.breadcrumbs && { + breadcrumbs: event.breadcrumbs.map((b) => ({ + ...b, + ...b.data && { + data: normalize$1(b.data, depth, maxBreadth) + } + })) + }, + ...event.user && { + user: normalize$1(event.user, depth, maxBreadth) + }, + ...event.contexts && { + contexts: normalize$1(event.contexts, depth, maxBreadth) + }, + ...event.extra && { + extra: normalize$1(event.extra, depth, maxBreadth) + } + }; + if (event.contexts?.trace && normalized.contexts) { + normalized.contexts.trace = event.contexts.trace; + if (event.contexts.trace.data) { + normalized.contexts.trace.data = normalize$1(event.contexts.trace.data, depth, maxBreadth); + } + } + if (event.spans) { + normalized.spans = event.spans.map((span) => { + return { + ...span, + ...span.data && { + data: normalize$1(span.data, depth, maxBreadth) + } + }; + }); + } + if (event.contexts?.flags && normalized.contexts) { + normalized.contexts.flags = normalize$1(event.contexts.flags, 3, maxBreadth); + } + return normalized; +} +function getFinalScope(scope, captureContext) { + if (!captureContext) { + return scope; + } + const finalScope = scope ? scope.clone() : new Scope(); + finalScope.update(captureContext); + return finalScope; +} +function parseEventHintOrCaptureContext(hint) { + if (!hint) { + return void 0; + } + if (hintIsScopeOrFunction(hint)) { + return { captureContext: hint }; + } + if (hintIsScopeContext(hint)) { + return { + captureContext: hint + }; + } + return hint; +} +function hintIsScopeOrFunction(hint) { + return hint instanceof Scope || typeof hint === "function"; +} +const captureContextKeys = [ + "user", + "level", + "extra", + "contexts", + "tags", + "fingerprint", + "propagationContext" +]; +function hintIsScopeContext(hint) { + return Object.keys(hint).some((key) => captureContextKeys.includes(key)); +} +function captureException(exception, hint) { + return getCurrentScope().captureException(exception, parseEventHintOrCaptureContext(hint)); +} +function captureEvent(event, hint) { + return getCurrentScope().captureEvent(event, hint); +} +async function flush(timeout) { + const client = getClient(); + if (client) { + return client.flush(timeout); + } + DEBUG_BUILD$3 && debug$2.warn("Cannot flush events. No client defined."); + return Promise.resolve(false); +} +function isEnabled() { + const client = getClient(); + return client?.getOptions().enabled !== false && !!client?.getTransport(); +} +function startSession(context2) { + const isolationScope = getIsolationScope(); + const currentScope = getCurrentScope(); + const { userAgent } = GLOBAL_OBJ.navigator || {}; + const session = makeSession({ + user: currentScope.getUser() || isolationScope.getUser(), + ...userAgent && { userAgent }, + ...context2 + }); + const currentSession = isolationScope.getSession(); + if (currentSession?.status === "ok") { + updateSession(currentSession, { status: "exited" }); + } + endSession(); + isolationScope.setSession(session); + return session; +} +function endSession() { + const isolationScope = getIsolationScope(); + const currentScope = getCurrentScope(); + const session = currentScope.getSession() || isolationScope.getSession(); + if (session) { + closeSession(session); + } + _sendSessionUpdate(); + isolationScope.setSession(); +} +function _sendSessionUpdate() { + const isolationScope = getIsolationScope(); + const client = getClient(); + const session = isolationScope.getSession(); + if (session && client) { + client.captureSession(session); + } +} +const SENTRY_API_VERSION = "7"; +function getBaseApiEndpoint(dsn) { + const protocol = dsn.protocol ? `${dsn.protocol}:` : ""; + const port = dsn.port ? `:${dsn.port}` : ""; + return `${protocol}//${dsn.host}${port}${dsn.path ? `/${dsn.path}` : ""}/api/`; +} +function _getIngestEndpoint(dsn) { + return `${getBaseApiEndpoint(dsn)}${dsn.projectId}/envelope/`; +} +function _encodedAuth(dsn, sdkInfo) { + const params = { + sentry_version: SENTRY_API_VERSION + }; + if (dsn.publicKey) { + params.sentry_key = dsn.publicKey; + } + if (sdkInfo) { + params.sentry_client = `${sdkInfo.name}/${sdkInfo.version}`; + } + return new URLSearchParams(params).toString(); +} +function getEnvelopeEndpointWithUrlEncodedAuth(dsn, tunnel, sdkInfo) { + return tunnel ? tunnel : `${_getIngestEndpoint(dsn)}?${_encodedAuth(dsn, sdkInfo)}`; +} +const installedIntegrations = []; +function filterDuplicates(integrations) { + const integrationsByName = {}; + integrations.forEach((currentInstance) => { + const { name } = currentInstance; + const existingInstance = integrationsByName[name]; + if (existingInstance && !existingInstance.isDefaultInstance && currentInstance.isDefaultInstance) { + return; + } + integrationsByName[name] = currentInstance; + }); + return Object.values(integrationsByName); +} +function getIntegrationsToSetup(options) { + const defaultIntegrations = options.defaultIntegrations || []; + const userIntegrations = options.integrations; + defaultIntegrations.forEach((integration) => { + integration.isDefaultInstance = true; + }); + let integrations; + if (Array.isArray(userIntegrations)) { + integrations = [...defaultIntegrations, ...userIntegrations]; + } else if (typeof userIntegrations === "function") { + const resolvedUserIntegrations = userIntegrations(defaultIntegrations); + integrations = Array.isArray(resolvedUserIntegrations) ? resolvedUserIntegrations : [resolvedUserIntegrations]; + } else { + integrations = defaultIntegrations; + } + return filterDuplicates(integrations); +} +function setupIntegrations(client, integrations) { + const integrationIndex = {}; + integrations.forEach((integration) => { + if (integration) { + setupIntegration(client, integration, integrationIndex); + } + }); + return integrationIndex; +} +function afterSetupIntegrations(client, integrations) { + for (const integration of integrations) { + if (integration?.afterAllSetup) { + integration.afterAllSetup(client); + } + } +} +function setupIntegration(client, integration, integrationIndex) { + if (integrationIndex[integration.name]) { + DEBUG_BUILD$3 && debug$2.log(`Integration skipped because it was already installed: ${integration.name}`); + return; + } + integrationIndex[integration.name] = integration; + if (!installedIntegrations.includes(integration.name) && typeof integration.setupOnce === "function") { + integration.setupOnce(); + installedIntegrations.push(integration.name); + } + if (integration.setup && typeof integration.setup === "function") { + integration.setup(client); + } + if (typeof integration.preprocessEvent === "function") { + const callback = integration.preprocessEvent.bind(integration); + client.on("preprocessEvent", (event, hint) => callback(event, hint, client)); + } + if (typeof integration.processEvent === "function") { + const callback = integration.processEvent.bind(integration); + const processor = Object.assign((event, hint) => callback(event, hint, client), { + id: integration.name + }); + client.addEventProcessor(processor); + } + DEBUG_BUILD$3 && debug$2.log(`Integration installed: ${integration.name}`); +} +function defineIntegration(fn) { + return fn; +} +function _getTraceInfoFromScope(client, scope) { + if (!scope) { + return [void 0, void 0]; + } + return withScope(scope, () => { + const span = getActiveSpan$1(); + const traceContext = span ? spanToTraceContext(span) : getTraceContextFromScope(scope); + const dynamicSamplingContext = span ? getDynamicSamplingContextFromSpan(span) : getDynamicSamplingContextFromScope(client, scope); + return [dynamicSamplingContext, traceContext]; + }); +} +function createLogContainerEnvelopeItem(items) { + return [ + { + type: "log", + item_count: items.length, + content_type: "application/vnd.sentry.items.log+json" + }, + { + items + } + ]; +} +function createLogEnvelope(logs2, metadata, tunnel, dsn) { + const headers = {}; + if (metadata?.sdk) { + headers.sdk = { + name: metadata.sdk.name, + version: metadata.sdk.version + }; + } + if (!!tunnel && !!dsn) { + headers.dsn = dsnToString(dsn); + } + return createEnvelope(headers, [createLogContainerEnvelopeItem(logs2)]); +} +function _INTERNAL_flushLogsBuffer(client, maybeLogBuffer) { + const logBuffer = maybeLogBuffer ?? _INTERNAL_getLogBuffer(client) ?? []; + if (logBuffer.length === 0) { + return; + } + const clientOptions = client.getOptions(); + const envelope = createLogEnvelope(logBuffer, clientOptions._metadata, clientOptions.tunnel, client.getDsn()); + _getBufferMap$1().set(client, []); + client.emit("flushLogs"); + client.sendEnvelope(envelope); +} +function _INTERNAL_getLogBuffer(client) { + return _getBufferMap$1().get(client); +} +function _getBufferMap$1() { + return getGlobalSingleton("clientToLogBufferMap", () => /* @__PURE__ */ new WeakMap()); +} +function createMetricContainerEnvelopeItem(items) { + return [ + { + type: "trace_metric", + item_count: items.length, + content_type: "application/vnd.sentry.items.trace-metric+json" + }, + { + items + } + ]; +} +function createMetricEnvelope(metrics2, metadata, tunnel, dsn) { + const headers = {}; + if (metadata?.sdk) { + headers.sdk = { + name: metadata.sdk.name, + version: metadata.sdk.version + }; + } + if (!!tunnel && !!dsn) { + headers.dsn = dsnToString(dsn); + } + return createEnvelope(headers, [createMetricContainerEnvelopeItem(metrics2)]); +} +function _INTERNAL_flushMetricsBuffer(client, maybeMetricBuffer) { + const metricBuffer = maybeMetricBuffer ?? _INTERNAL_getMetricBuffer(client) ?? []; + if (metricBuffer.length === 0) { + return; + } + const clientOptions = client.getOptions(); + const envelope = createMetricEnvelope(metricBuffer, clientOptions._metadata, clientOptions.tunnel, client.getDsn()); + _getBufferMap().set(client, []); + client.emit("flushMetrics"); + client.sendEnvelope(envelope); +} +function _INTERNAL_getMetricBuffer(client) { + return _getBufferMap().get(client); +} +function _getBufferMap() { + return getGlobalSingleton("clientToMetricBufferMap", () => /* @__PURE__ */ new WeakMap()); +} +const SENTRY_BUFFER_FULL_ERROR = Symbol.for("SentryBufferFullError"); +function makePromiseBuffer(limit = 100) { + const buffer = /* @__PURE__ */ new Set(); + function isReady() { + return buffer.size < limit; + } + function remove(task) { + buffer.delete(task); + } + function add(taskProducer) { + if (!isReady()) { + return rejectedSyncPromise(SENTRY_BUFFER_FULL_ERROR); + } + const task = taskProducer(); + buffer.add(task); + void task.then( + () => remove(task), + () => remove(task) + ); + return task; + } + function drain(timeout) { + if (!buffer.size) { + return resolvedSyncPromise(true); + } + const drainPromise = Promise.allSettled(Array.from(buffer)).then(() => true); + if (!timeout) { + return drainPromise; + } + const promises = [drainPromise, new Promise((resolve) => setTimeout(() => resolve(false), timeout))]; + return Promise.race(promises); + } + return { + get $() { + return Array.from(buffer); + }, + add, + drain + }; +} +const DEFAULT_RETRY_AFTER = 60 * 1e3; +function parseRetryAfterHeader(header, now = Date.now()) { + const headerDelay = parseInt(`${header}`, 10); + if (!isNaN(headerDelay)) { + return headerDelay * 1e3; + } + const headerDate = Date.parse(`${header}`); + if (!isNaN(headerDate)) { + return headerDate - now; + } + return DEFAULT_RETRY_AFTER; +} +function disabledUntil(limits, dataCategory) { + return limits[dataCategory] || limits.all || 0; +} +function isRateLimited(limits, dataCategory, now = Date.now()) { + return disabledUntil(limits, dataCategory) > now; +} +function updateRateLimits(limits, { statusCode, headers }, now = Date.now()) { + const updatedRateLimits = { + ...limits + }; + const rateLimitHeader = headers?.["x-sentry-rate-limits"]; + const retryAfterHeader = headers?.["retry-after"]; + if (rateLimitHeader) { + for (const limit of rateLimitHeader.trim().split(",")) { + const [retryAfter, categories, , , namespaces] = limit.split(":", 5); + const headerDelay = parseInt(retryAfter, 10); + const delay = (!isNaN(headerDelay) ? headerDelay : 60) * 1e3; + if (!categories) { + updatedRateLimits.all = now + delay; + } else { + for (const category of categories.split(";")) { + if (category === "metric_bucket") { + if (!namespaces || namespaces.split(";").includes("custom")) { + updatedRateLimits[category] = now + delay; + } + } else { + updatedRateLimits[category] = now + delay; + } + } + } + } + } else if (retryAfterHeader) { + updatedRateLimits.all = now + parseRetryAfterHeader(retryAfterHeader, now); + } else if (statusCode === 429) { + updatedRateLimits.all = now + 60 * 1e3; + } + return updatedRateLimits; +} +const DEFAULT_TRANSPORT_BUFFER_SIZE = 64; +function createTransport(options, makeRequest, buffer = makePromiseBuffer( + options.bufferSize || DEFAULT_TRANSPORT_BUFFER_SIZE +)) { + let rateLimits = {}; + const flush2 = (timeout) => buffer.drain(timeout); + function send(envelope) { + const filteredEnvelopeItems = []; + forEachEnvelopeItem(envelope, (item, type) => { + const dataCategory = envelopeItemTypeToDataCategory(type); + if (isRateLimited(rateLimits, dataCategory)) { + options.recordDroppedEvent("ratelimit_backoff", dataCategory); + } else { + filteredEnvelopeItems.push(item); + } + }); + if (filteredEnvelopeItems.length === 0) { + return Promise.resolve({}); + } + const filteredEnvelope = createEnvelope(envelope[0], filteredEnvelopeItems); + const recordEnvelopeLoss = (reason) => { + forEachEnvelopeItem(filteredEnvelope, (item, type) => { + options.recordDroppedEvent(reason, envelopeItemTypeToDataCategory(type)); + }); + }; + const requestTask = () => makeRequest({ body: serializeEnvelope(filteredEnvelope) }).then( + (response) => { + if (response.statusCode !== void 0 && (response.statusCode < 200 || response.statusCode >= 300)) { + DEBUG_BUILD$3 && debug$2.warn(`Sentry responded with status code ${response.statusCode} to sent event.`); + } + rateLimits = updateRateLimits(rateLimits, response); + return response; + }, + (error2) => { + recordEnvelopeLoss("network_error"); + DEBUG_BUILD$3 && debug$2.error("Encountered error running transport request:", error2); + throw error2; + } + ); + return buffer.add(requestTask).then( + (result) => result, + (error2) => { + if (error2 === SENTRY_BUFFER_FULL_ERROR) { + DEBUG_BUILD$3 && debug$2.error("Skipped sending event because buffer is full."); + recordEnvelopeLoss("queue_overflow"); + return Promise.resolve({}); + } else { + throw error2; + } + } + ); + } + return { + send, + flush: flush2 + }; +} +function createClientReportEnvelope(discarded_events, dsn, timestamp) { + const clientReportItem = [ + { type: "client_report" }, + { + timestamp: dateTimestampInSeconds(), + discarded_events + } + ]; + return createEnvelope(dsn ? { dsn } : {}, [clientReportItem]); +} +function getPossibleEventMessages(event) { + const possibleMessages = []; + if (event.message) { + possibleMessages.push(event.message); + } + try { + const lastException = event.exception.values[event.exception.values.length - 1]; + if (lastException?.value) { + possibleMessages.push(lastException.value); + if (lastException.type) { + possibleMessages.push(`${lastException.type}: ${lastException.value}`); + } + } + } catch { + } + return possibleMessages; +} +function convertTransactionEventToSpanJson(event) { + const { trace_id, parent_span_id, span_id, status: status2, origin, data, op } = event.contexts?.trace ?? {}; + return { + data: data ?? {}, + description: event.transaction, + op, + parent_span_id, + span_id: span_id ?? "", + start_timestamp: event.start_timestamp ?? 0, + status: status2, + timestamp: event.timestamp, + trace_id: trace_id ?? "", + origin, + profile_id: data?.[SEMANTIC_ATTRIBUTE_PROFILE_ID], + exclusive_time: data?.[SEMANTIC_ATTRIBUTE_EXCLUSIVE_TIME], + measurements: event.measurements, + is_segment: true + }; +} +function convertSpanJsonToTransactionEvent(span) { + return { + type: "transaction", + timestamp: span.timestamp, + start_timestamp: span.start_timestamp, + transaction: span.description, + contexts: { + trace: { + trace_id: span.trace_id, + span_id: span.span_id, + parent_span_id: span.parent_span_id, + op: span.op, + status: span.status, + origin: span.origin, + data: { + ...span.data, + ...span.profile_id && { [SEMANTIC_ATTRIBUTE_PROFILE_ID]: span.profile_id }, + ...span.exclusive_time && { [SEMANTIC_ATTRIBUTE_EXCLUSIVE_TIME]: span.exclusive_time } + } + } + }, + measurements: span.measurements + }; +} +const ALREADY_SEEN_ERROR = "Not capturing exception because it's already been captured."; +const MISSING_RELEASE_FOR_SESSION_ERROR = "Discarded session because of missing or non-string release"; +const INTERNAL_ERROR_SYMBOL = Symbol.for("SentryInternalError"); +const DO_NOT_SEND_EVENT_SYMBOL = Symbol.for("SentryDoNotSendEventError"); +const DEFAULT_FLUSH_INTERVAL = 5e3; +function _makeInternalError(message) { + return { + message, + [INTERNAL_ERROR_SYMBOL]: true + }; +} +function _makeDoNotSendEventError(message) { + return { + message, + [DO_NOT_SEND_EVENT_SYMBOL]: true + }; +} +function _isInternalError(error2) { + return !!error2 && typeof error2 === "object" && INTERNAL_ERROR_SYMBOL in error2; +} +function _isDoNotSendEventError(error2) { + return !!error2 && typeof error2 === "object" && DO_NOT_SEND_EVENT_SYMBOL in error2; +} +function setupWeightBasedFlushing(client, afterCaptureHook, flushHook, estimateSizeFn, flushFn) { + let weight = 0; + let flushTimeout; + let isTimerActive = false; + client.on(flushHook, () => { + weight = 0; + clearTimeout(flushTimeout); + isTimerActive = false; + }); + client.on(afterCaptureHook, (item) => { + weight += estimateSizeFn(item); + if (weight >= 8e5) { + flushFn(client); + } else if (!isTimerActive) { + isTimerActive = true; + flushTimeout = setTimeout(() => { + flushFn(client); + }, DEFAULT_FLUSH_INTERVAL); + } + }); + client.on("flush", () => { + flushFn(client); + }); +} +class Client { + /** Options passed to the SDK. */ + /** The client Dsn, if specified in options. Without this Dsn, the SDK will be disabled. */ + /** Array of set up integrations. */ + /** Number of calls being processed */ + /** Holds flushable */ + // eslint-disable-next-line @typescript-eslint/ban-types + /** + * Initializes this client instance. + * + * @param options Options for the client. + */ + constructor(options) { + this._options = options; + this._integrations = {}; + this._numProcessing = 0; + this._outcomes = {}; + this._hooks = {}; + this._eventProcessors = []; + this._promiseBuffer = makePromiseBuffer(options.transportOptions?.bufferSize ?? DEFAULT_TRANSPORT_BUFFER_SIZE); + if (options.dsn) { + this._dsn = makeDsn(options.dsn); + } else { + DEBUG_BUILD$3 && debug$2.warn("No DSN provided, client will not send events."); + } + if (this._dsn) { + const url = getEnvelopeEndpointWithUrlEncodedAuth( + this._dsn, + options.tunnel, + options._metadata ? options._metadata.sdk : void 0 + ); + this._transport = options.transport({ + tunnel: this._options.tunnel, + recordDroppedEvent: this.recordDroppedEvent.bind(this), + ...options.transportOptions, + url + }); + } + this._options.enableLogs = this._options.enableLogs ?? this._options._experiments?.enableLogs; + if (this._options.enableLogs) { + setupWeightBasedFlushing(this, "afterCaptureLog", "flushLogs", estimateLogSizeInBytes, _INTERNAL_flushLogsBuffer); + } + const enableMetrics = this._options.enableMetrics ?? this._options._experiments?.enableMetrics ?? true; + if (enableMetrics) { + setupWeightBasedFlushing( + this, + "afterCaptureMetric", + "flushMetrics", + estimateMetricSizeInBytes, + _INTERNAL_flushMetricsBuffer + ); + } + } + /** + * Captures an exception event and sends it to Sentry. + * + * Unlike `captureException` exported from every SDK, this method requires that you pass it the current scope. + */ + captureException(exception, hint, scope) { + const eventId = uuid4(); + if (checkOrSetAlreadyCaught(exception)) { + DEBUG_BUILD$3 && debug$2.log(ALREADY_SEEN_ERROR); + return eventId; + } + const hintWithEventId = { + event_id: eventId, + ...hint + }; + this._process( + () => this.eventFromException(exception, hintWithEventId).then((event) => this._captureEvent(event, hintWithEventId, scope)).then((res) => res), + "error" + ); + return hintWithEventId.event_id; + } + /** + * Captures a message event and sends it to Sentry. + * + * Unlike `captureMessage` exported from every SDK, this method requires that you pass it the current scope. + */ + captureMessage(message, level, hint, currentScope) { + const hintWithEventId = { + event_id: uuid4(), + ...hint + }; + const eventMessage = isParameterizedString(message) ? message : String(message); + const isMessage = isPrimitive$1(message); + const promisedEvent = isMessage ? this.eventFromMessage(eventMessage, level, hintWithEventId) : this.eventFromException(message, hintWithEventId); + this._process( + () => promisedEvent.then((event) => this._captureEvent(event, hintWithEventId, currentScope)), + isMessage ? "unknown" : "error" + ); + return hintWithEventId.event_id; + } + /** + * Captures a manually created event and sends it to Sentry. + * + * Unlike `captureEvent` exported from every SDK, this method requires that you pass it the current scope. + */ + captureEvent(event, hint, currentScope) { + const eventId = uuid4(); + if (hint?.originalException && checkOrSetAlreadyCaught(hint.originalException)) { + DEBUG_BUILD$3 && debug$2.log(ALREADY_SEEN_ERROR); + return eventId; + } + const hintWithEventId = { + event_id: eventId, + ...hint + }; + const sdkProcessingMetadata = event.sdkProcessingMetadata || {}; + const capturedSpanScope = sdkProcessingMetadata.capturedSpanScope; + const capturedSpanIsolationScope = sdkProcessingMetadata.capturedSpanIsolationScope; + const dataCategory = getDataCategoryByType(event.type); + this._process( + () => this._captureEvent(event, hintWithEventId, capturedSpanScope || currentScope, capturedSpanIsolationScope), + dataCategory + ); + return hintWithEventId.event_id; + } + /** + * Captures a session. + */ + captureSession(session) { + this.sendSession(session); + updateSession(session, { init: false }); + } + /** + * Create a cron monitor check in and send it to Sentry. This method is not available on all clients. + * + * @param checkIn An object that describes a check in. + * @param upsertMonitorConfig An optional object that describes a monitor config. Use this if you want + * to create a monitor automatically when sending a check in. + * @param scope An optional scope containing event metadata. + * @returns A string representing the id of the check in. + */ + /** + * Get the current Dsn. + */ + getDsn() { + return this._dsn; + } + /** + * Get the current options. + */ + getOptions() { + return this._options; + } + /** + * Get the SDK metadata. + * @see SdkMetadata + */ + getSdkMetadata() { + return this._options._metadata; + } + /** + * Returns the transport that is used by the client. + * Please note that the transport gets lazy initialized so it will only be there once the first event has been sent. + */ + getTransport() { + return this._transport; + } + /** + * Wait for all events to be sent or the timeout to expire, whichever comes first. + * + * @param timeout Maximum time in ms the client should wait for events to be flushed. Omitting this parameter will + * cause the client to wait until all events are sent before resolving the promise. + * @returns A promise that will resolve with `true` if all events are sent before the timeout, or `false` if there are + * still events in the queue when the timeout is reached. + */ + // @ts-expect-error - PromiseLike is a subset of Promise + async flush(timeout) { + const transport = this._transport; + if (!transport) { + return true; + } + this.emit("flush"); + const clientFinished = await this._isClientDoneProcessing(timeout); + const transportFlushed = await transport.flush(timeout); + return clientFinished && transportFlushed; + } + /** + * Flush the event queue and set the client to `enabled = false`. See {@link Client.flush}. + * + * @param {number} timeout Maximum time in ms the client should wait before shutting down. Omitting this parameter will cause + * the client to wait until all events are sent before disabling itself. + * @returns {Promise} A promise which resolves to `true` if the flush completes successfully before the timeout, or `false` if + * it doesn't. + */ + // @ts-expect-error - PromiseLike is a subset of Promise + async close(timeout) { + const result = await this.flush(timeout); + this.getOptions().enabled = false; + this.emit("close"); + return result; + } + /** + * Get all installed event processors. + */ + getEventProcessors() { + return this._eventProcessors; + } + /** + * Adds an event processor that applies to any event processed by this client. + */ + addEventProcessor(eventProcessor) { + this._eventProcessors.push(eventProcessor); + } + /** + * Initialize this client. + * Call this after the client was set on a scope. + */ + init() { + if (this._isEnabled() || // Force integrations to be setup even if no DSN was set when we have + // Spotlight enabled. This is particularly important for browser as we + // don't support the `spotlight` option there and rely on the users + // adding the `spotlightBrowserIntegration()` to their integrations which + // wouldn't get initialized with the check below when there's no DSN set. + this._options.integrations.some(({ name }) => name.startsWith("Spotlight"))) { + this._setupIntegrations(); + } + } + /** + * Gets an installed integration by its name. + * + * @returns {Integration|undefined} The installed integration or `undefined` if no integration with that `name` was installed. + */ + getIntegrationByName(integrationName) { + return this._integrations[integrationName]; + } + /** + * Add an integration to the client. + * This can be used to e.g. lazy load integrations. + * In most cases, this should not be necessary, + * and you're better off just passing the integrations via `integrations: []` at initialization time. + * However, if you find the need to conditionally load & add an integration, you can use `addIntegration` to do so. + */ + addIntegration(integration) { + const isAlreadyInstalled = this._integrations[integration.name]; + setupIntegration(this, integration, this._integrations); + if (!isAlreadyInstalled) { + afterSetupIntegrations(this, [integration]); + } + } + /** + * Send a fully prepared event to Sentry. + */ + sendEvent(event, hint = {}) { + this.emit("beforeSendEvent", event, hint); + let env = createEventEnvelope(event, this._dsn, this._options._metadata, this._options.tunnel); + for (const attachment of hint.attachments || []) { + env = addItemToEnvelope(env, createAttachmentEnvelopeItem(attachment)); + } + this.sendEnvelope(env).then((sendResponse) => this.emit("afterSendEvent", event, sendResponse)); + } + /** + * Send a session or session aggregrates to Sentry. + */ + sendSession(session) { + const { release: clientReleaseOption, environment: clientEnvironmentOption = DEFAULT_ENVIRONMENT } = this._options; + if ("aggregates" in session) { + const sessionAttrs = session.attrs || {}; + if (!sessionAttrs.release && !clientReleaseOption) { + DEBUG_BUILD$3 && debug$2.warn(MISSING_RELEASE_FOR_SESSION_ERROR); + return; + } + sessionAttrs.release = sessionAttrs.release || clientReleaseOption; + sessionAttrs.environment = sessionAttrs.environment || clientEnvironmentOption; + session.attrs = sessionAttrs; + } else { + if (!session.release && !clientReleaseOption) { + DEBUG_BUILD$3 && debug$2.warn(MISSING_RELEASE_FOR_SESSION_ERROR); + return; + } + session.release = session.release || clientReleaseOption; + session.environment = session.environment || clientEnvironmentOption; + } + this.emit("beforeSendSession", session); + const env = createSessionEnvelope(session, this._dsn, this._options._metadata, this._options.tunnel); + this.sendEnvelope(env); + } + /** + * Record on the client that an event got dropped (ie, an event that will not be sent to Sentry). + */ + recordDroppedEvent(reason, category, count = 1) { + if (this._options.sendClientReports) { + const key = `${reason}:${category}`; + DEBUG_BUILD$3 && debug$2.log(`Recording outcome: "${key}"${count > 1 ? ` (${count} times)` : ""}`); + this._outcomes[key] = (this._outcomes[key] || 0) + count; + } + } + /* eslint-disable @typescript-eslint/unified-signatures */ + /** + * Register a callback for whenever a span is started. + * Receives the span as argument. + * @returns {() => void} A function that, when executed, removes the registered callback. + */ + /** + * Register a hook on this client. + */ + on(hook, callback) { + const hookCallbacks = this._hooks[hook] = this._hooks[hook] || /* @__PURE__ */ new Set(); + const uniqueCallback = (...args) => callback(...args); + hookCallbacks.add(uniqueCallback); + return () => { + hookCallbacks.delete(uniqueCallback); + }; + } + /** Fire a hook whenever a span starts. */ + /** + * Emit a hook that was previously registered via `on()`. + */ + emit(hook, ...rest) { + const callbacks = this._hooks[hook]; + if (callbacks) { + callbacks.forEach((callback) => callback(...rest)); + } + } + /** + * Send an envelope to Sentry. + */ + // @ts-expect-error - PromiseLike is a subset of Promise + async sendEnvelope(envelope) { + this.emit("beforeEnvelope", envelope); + if (this._isEnabled() && this._transport) { + try { + return await this._transport.send(envelope); + } catch (reason) { + DEBUG_BUILD$3 && debug$2.error("Error while sending envelope:", reason); + return {}; + } + } + DEBUG_BUILD$3 && debug$2.error("Transport disabled"); + return {}; + } + /* eslint-enable @typescript-eslint/unified-signatures */ + /** Setup integrations for this client. */ + _setupIntegrations() { + const { integrations } = this._options; + this._integrations = setupIntegrations(this, integrations); + afterSetupIntegrations(this, integrations); + } + /** Updates existing session based on the provided event */ + _updateSessionFromEvent(session, event) { + let crashed = event.level === "fatal"; + let errored = false; + const exceptions = event.exception?.values; + if (exceptions) { + errored = true; + crashed = false; + for (const ex of exceptions) { + if (ex.mechanism?.handled === false) { + crashed = true; + break; + } + } + } + const sessionNonTerminal = session.status === "ok"; + const shouldUpdateAndSend = sessionNonTerminal && session.errors === 0 || sessionNonTerminal && crashed; + if (shouldUpdateAndSend) { + updateSession(session, { + ...crashed && { status: "crashed" }, + errors: session.errors || Number(errored || crashed) + }); + this.captureSession(session); + } + } + /** + * Determine if the client is finished processing. Returns a promise because it will wait `timeout` ms before saying + * "no" (resolving to `false`) in order to give the client a chance to potentially finish first. + * + * @param timeout The time, in ms, after which to resolve to `false` if the client is still busy. Passing `0` (or not + * passing anything) will make the promise wait as long as it takes for processing to finish before resolving to + * `true`. + * @returns A promise which will resolve to `true` if processing is already done or finishes before the timeout, and + * `false` otherwise + */ + async _isClientDoneProcessing(timeout) { + let ticked = 0; + while (!timeout || ticked < timeout) { + await new Promise((resolve) => setTimeout(resolve, 1)); + if (!this._numProcessing) { + return true; + } + ticked++; + } + return false; + } + /** Determines whether this SDK is enabled and a transport is present. */ + _isEnabled() { + return this.getOptions().enabled !== false && this._transport !== void 0; + } + /** + * Adds common information to events. + * + * The information includes release and environment from `options`, + * breadcrumbs and context (extra, tags and user) from the scope. + * + * Information that is already present in the event is never overwritten. For + * nested objects, such as the context, keys are merged. + * + * @param event The original event. + * @param hint May contain additional information about the original exception. + * @param currentScope A scope containing event metadata. + * @returns A new event with more information. + */ + _prepareEvent(event, hint, currentScope, isolationScope) { + const options = this.getOptions(); + const integrations = Object.keys(this._integrations); + if (!hint.integrations && integrations?.length) { + hint.integrations = integrations; + } + this.emit("preprocessEvent", event, hint); + if (!event.type) { + isolationScope.setLastEventId(event.event_id || hint.event_id); + } + return prepareEvent(options, event, hint, currentScope, this, isolationScope).then((evt) => { + if (evt === null) { + return evt; + } + this.emit("postprocessEvent", evt, hint); + evt.contexts = { + trace: getTraceContextFromScope(currentScope), + ...evt.contexts + }; + const dynamicSamplingContext = getDynamicSamplingContextFromScope(this, currentScope); + evt.sdkProcessingMetadata = { + dynamicSamplingContext, + ...evt.sdkProcessingMetadata + }; + return evt; + }); + } + /** + * Processes the event and logs an error in case of rejection + * @param event + * @param hint + * @param scope + */ + _captureEvent(event, hint = {}, currentScope = getCurrentScope(), isolationScope = getIsolationScope()) { + if (DEBUG_BUILD$3 && isErrorEvent$1(event)) { + debug$2.log(`Captured error event \`${getPossibleEventMessages(event)[0] || ""}\``); + } + return this._processEvent(event, hint, currentScope, isolationScope).then( + (finalEvent) => { + return finalEvent.event_id; + }, + (reason) => { + if (DEBUG_BUILD$3) { + if (_isDoNotSendEventError(reason)) { + debug$2.log(reason.message); + } else if (_isInternalError(reason)) { + debug$2.warn(reason.message); + } else { + debug$2.warn(reason); + } + } + return void 0; + } + ); + } + /** + * Processes an event (either error or message) and sends it to Sentry. + * + * This also adds breadcrumbs and context information to the event. However, + * platform specific meta data (such as the User's IP address) must be added + * by the SDK implementor. + * + * + * @param event The event to send to Sentry. + * @param hint May contain additional information about the original exception. + * @param currentScope A scope containing event metadata. + * @returns A SyncPromise that resolves with the event or rejects in case event was/will not be send. + */ + _processEvent(event, hint, currentScope, isolationScope) { + const options = this.getOptions(); + const { sampleRate } = options; + const isTransaction = isTransactionEvent(event); + const isError2 = isErrorEvent$1(event); + const eventType = event.type || "error"; + const beforeSendLabel = `before send for type \`${eventType}\``; + const parsedSampleRate = typeof sampleRate === "undefined" ? void 0 : parseSampleRate(sampleRate); + if (isError2 && typeof parsedSampleRate === "number" && Math.random() > parsedSampleRate) { + this.recordDroppedEvent("sample_rate", "error"); + return rejectedSyncPromise( + _makeDoNotSendEventError( + `Discarding event because it's not included in the random sample (sampling rate = ${sampleRate})` + ) + ); + } + const dataCategory = getDataCategoryByType(event.type); + return this._prepareEvent(event, hint, currentScope, isolationScope).then((prepared) => { + if (prepared === null) { + this.recordDroppedEvent("event_processor", dataCategory); + throw _makeDoNotSendEventError("An event processor returned `null`, will not send event."); + } + const isInternalException = hint.data && hint.data.__sentry__ === true; + if (isInternalException) { + return prepared; + } + const result = processBeforeSend(this, options, prepared, hint); + return _validateBeforeSendResult(result, beforeSendLabel); + }).then((processedEvent) => { + if (processedEvent === null) { + this.recordDroppedEvent("before_send", dataCategory); + if (isTransaction) { + const spans = event.spans || []; + const spanCount = 1 + spans.length; + this.recordDroppedEvent("before_send", "span", spanCount); + } + throw _makeDoNotSendEventError(`${beforeSendLabel} returned \`null\`, will not send event.`); + } + const session = currentScope.getSession() || isolationScope.getSession(); + if (isError2 && session) { + this._updateSessionFromEvent(session, processedEvent); + } + if (isTransaction) { + const spanCountBefore = processedEvent.sdkProcessingMetadata?.spanCountBeforeProcessing || 0; + const spanCountAfter = processedEvent.spans ? processedEvent.spans.length : 0; + const droppedSpanCount = spanCountBefore - spanCountAfter; + if (droppedSpanCount > 0) { + this.recordDroppedEvent("before_send", "span", droppedSpanCount); + } + } + const transactionInfo = processedEvent.transaction_info; + if (isTransaction && transactionInfo && processedEvent.transaction !== event.transaction) { + const source = "custom"; + processedEvent.transaction_info = { + ...transactionInfo, + source + }; + } + this.sendEvent(processedEvent, hint); + return processedEvent; + }).then(null, (reason) => { + if (_isDoNotSendEventError(reason) || _isInternalError(reason)) { + throw reason; + } + this.captureException(reason, { + mechanism: { + handled: false, + type: "internal" + }, + data: { + __sentry__: true + }, + originalException: reason + }); + throw _makeInternalError( + `Event processing pipeline threw an error, original event will not be sent. Details have been sent as a new event. +Reason: ${reason}` + ); + }); + } + /** + * Occupies the client with processing and event + */ + _process(taskProducer, dataCategory) { + this._numProcessing++; + void this._promiseBuffer.add(taskProducer).then( + (value) => { + this._numProcessing--; + return value; + }, + (reason) => { + this._numProcessing--; + if (reason === SENTRY_BUFFER_FULL_ERROR) { + this.recordDroppedEvent("queue_overflow", dataCategory); + } + return reason; + } + ); + } + /** + * Clears outcomes on this client and returns them. + */ + _clearOutcomes() { + const outcomes = this._outcomes; + this._outcomes = {}; + return Object.entries(outcomes).map(([key, quantity]) => { + const [reason, category] = key.split(":"); + return { + reason, + category, + quantity + }; + }); + } + /** + * Sends client reports as an envelope. + */ + _flushOutcomes() { + DEBUG_BUILD$3 && debug$2.log("Flushing outcomes..."); + const outcomes = this._clearOutcomes(); + if (outcomes.length === 0) { + DEBUG_BUILD$3 && debug$2.log("No outcomes to send"); + return; + } + if (!this._dsn) { + DEBUG_BUILD$3 && debug$2.log("No dsn provided, will not send outcomes"); + return; + } + DEBUG_BUILD$3 && debug$2.log("Sending outcomes:", outcomes); + const envelope = createClientReportEnvelope(outcomes, this._options.tunnel && dsnToString(this._dsn)); + this.sendEnvelope(envelope); + } + /** + * Creates an {@link Event} from all inputs to `captureException` and non-primitive inputs to `captureMessage`. + */ +} +function getDataCategoryByType(type) { + return type === "replay_event" ? "replay" : type || "error"; +} +function _validateBeforeSendResult(beforeSendResult, beforeSendLabel) { + const invalidValueError = `${beforeSendLabel} must return \`null\` or a valid event.`; + if (isThenable(beforeSendResult)) { + return beforeSendResult.then( + (event) => { + if (!isPlainObject$1(event) && event !== null) { + throw _makeInternalError(invalidValueError); + } + return event; + }, + (e) => { + throw _makeInternalError(`${beforeSendLabel} rejected with ${e}`); + } + ); + } else if (!isPlainObject$1(beforeSendResult) && beforeSendResult !== null) { + throw _makeInternalError(invalidValueError); + } + return beforeSendResult; +} +function processBeforeSend(client, options, event, hint) { + const { beforeSend, beforeSendTransaction, beforeSendSpan, ignoreSpans } = options; + let processedEvent = event; + if (isErrorEvent$1(processedEvent) && beforeSend) { + return beforeSend(processedEvent, hint); + } + if (isTransactionEvent(processedEvent)) { + if (beforeSendSpan || ignoreSpans) { + const rootSpanJson = convertTransactionEventToSpanJson(processedEvent); + if (ignoreSpans?.length && shouldIgnoreSpan$1(rootSpanJson, ignoreSpans)) { + return null; + } + if (beforeSendSpan) { + const processedRootSpanJson = beforeSendSpan(rootSpanJson); + if (!processedRootSpanJson) { + showSpanDropWarning(); + } else { + processedEvent = merge$1(event, convertSpanJsonToTransactionEvent(processedRootSpanJson)); + } + } + if (processedEvent.spans) { + const processedSpans = []; + const initialSpans = processedEvent.spans; + for (const span of initialSpans) { + if (ignoreSpans?.length && shouldIgnoreSpan$1(span, ignoreSpans)) { + reparentChildSpans(initialSpans, span); + continue; + } + if (beforeSendSpan) { + const processedSpan = beforeSendSpan(span); + if (!processedSpan) { + showSpanDropWarning(); + processedSpans.push(span); + } else { + processedSpans.push(processedSpan); + } + } else { + processedSpans.push(span); + } + } + const droppedSpans = processedEvent.spans.length - processedSpans.length; + if (droppedSpans) { + client.recordDroppedEvent("before_send", "span", droppedSpans); + } + processedEvent.spans = processedSpans; + } + } + if (beforeSendTransaction) { + if (processedEvent.spans) { + const spanCountBefore = processedEvent.spans.length; + processedEvent.sdkProcessingMetadata = { + ...event.sdkProcessingMetadata, + spanCountBeforeProcessing: spanCountBefore + }; + } + return beforeSendTransaction(processedEvent, hint); + } + } + return processedEvent; +} +function isErrorEvent$1(event) { + return event.type === void 0; +} +function isTransactionEvent(event) { + return event.type === "transaction"; +} +function estimateMetricSizeInBytes(metric) { + let weight = 0; + if (metric.name) { + weight += metric.name.length * 2; + } + weight += 8; + return weight + estimateAttributesSizeInBytes(metric.attributes); +} +function estimateLogSizeInBytes(log2) { + let weight = 0; + if (log2.message) { + weight += log2.message.length * 2; + } + return weight + estimateAttributesSizeInBytes(log2.attributes); +} +function estimateAttributesSizeInBytes(attributes) { + if (!attributes) { + return 0; + } + let weight = 0; + Object.values(attributes).forEach((value) => { + if (Array.isArray(value)) { + weight += value.length * estimatePrimitiveSizeInBytes(value[0]); + } else if (isPrimitive$1(value)) { + weight += estimatePrimitiveSizeInBytes(value); + } else { + weight += 100; + } + }); + return weight; +} +function estimatePrimitiveSizeInBytes(value) { + if (typeof value === "string") { + return value.length * 2; + } else if (typeof value === "number") { + return 8; + } else if (typeof value === "boolean") { + return 4; + } + return 0; +} +function createCheckInEnvelope(checkIn, dynamicSamplingContext, metadata, tunnel, dsn) { + const headers = { + sent_at: (/* @__PURE__ */ new Date()).toISOString() + }; + if (metadata?.sdk) { + headers.sdk = { + name: metadata.sdk.name, + version: metadata.sdk.version + }; + } + if (!!tunnel && !!dsn) { + headers.dsn = dsnToString(dsn); + } + if (dynamicSamplingContext) { + headers.trace = dynamicSamplingContext; + } + const item = createCheckInEnvelopeItem(checkIn); + return createEnvelope(headers, [item]); +} +function createCheckInEnvelopeItem(checkIn) { + const checkInHeaders = { + type: "check_in" + }; + return [checkInHeaders, checkIn]; +} +function addUserAgentToTransportHeaders(options) { + const sdkMetadata = options._metadata?.sdk; + const sdkUserAgent = sdkMetadata?.name && sdkMetadata?.version ? `${sdkMetadata?.name}/${sdkMetadata?.version}` : void 0; + options.transportOptions = { + ...options.transportOptions, + headers: { + ...sdkUserAgent && { "user-agent": sdkUserAgent }, + ...options.transportOptions?.headers + } + }; +} +function parseStackFrames(stackParser, error2) { + return stackParser(error2.stack || "", 1); +} +function exceptionFromError(stackParser, error2) { + const exception = { + type: error2.name || error2.constructor.name, + value: error2.message + }; + const frames = parseStackFrames(stackParser, error2); + if (frames.length) { + exception.stacktrace = { frames }; + } + return exception; +} +function getErrorPropertyFromObject(obj) { + for (const prop in obj) { + if (Object.prototype.hasOwnProperty.call(obj, prop)) { + const value = obj[prop]; + if (value instanceof Error) { + return value; + } + } + } + return void 0; +} +function getMessageForObject(exception) { + if ("name" in exception && typeof exception.name === "string") { + let message = `'${exception.name}' captured as exception`; + if ("message" in exception && typeof exception.message === "string") { + message += ` with message '${exception.message}'`; + } + return message; + } else if ("message" in exception && typeof exception.message === "string") { + return exception.message; + } + const keys = extractExceptionKeysForMessage(exception); + if (isErrorEvent$2(exception)) { + return `Event \`ErrorEvent\` captured as exception with message \`${exception.message}\``; + } + const className = getObjectClassName(exception); + return `${className && className !== "Object" ? `'${className}'` : "Object"} captured as exception with keys: ${keys}`; +} +function getObjectClassName(obj) { + try { + const prototype = Object.getPrototypeOf(obj); + return prototype ? prototype.constructor.name : void 0; + } catch { + } +} +function getException(client, mechanism, exception, hint) { + if (isError(exception)) { + return [exception, void 0]; + } + mechanism.synthetic = true; + if (isPlainObject$1(exception)) { + const normalizeDepth = client?.getOptions().normalizeDepth; + const extras = { ["__serialized__"]: normalizeToSize(exception, normalizeDepth) }; + const errorFromProp = getErrorPropertyFromObject(exception); + if (errorFromProp) { + return [errorFromProp, extras]; + } + const message = getMessageForObject(exception); + const ex2 = hint?.syntheticException || new Error(message); + ex2.message = message; + return [ex2, extras]; + } + const ex = hint?.syntheticException || new Error(exception); + ex.message = `${exception}`; + return [ex, void 0]; +} +function eventFromUnknownInput(client, stackParser, exception, hint) { + const providedMechanism = hint?.data && hint.data.mechanism; + const mechanism = providedMechanism || { + handled: true, + type: "generic" + }; + const [ex, extras] = getException(client, mechanism, exception, hint); + const event = { + exception: { + values: [exceptionFromError(stackParser, ex)] + } + }; + if (extras) { + event.extra = extras; + } + addExceptionTypeValue(event); + addExceptionMechanism(event, mechanism); + return { + ...event, + event_id: hint?.event_id + }; +} +function eventFromMessage(stackParser, message, level = "info", hint, attachStacktrace) { + const event = { + event_id: hint?.event_id, + level + }; + if (attachStacktrace && hint?.syntheticException) { + const frames = parseStackFrames(stackParser, hint.syntheticException); + if (frames.length) { + event.exception = { + values: [ + { + value: message, + stacktrace: { frames } + } + ] + }; + addExceptionMechanism(event, { synthetic: true }); + } + } + if (isParameterizedString(message)) { + const { __sentry_template_string__, __sentry_template_values__ } = message; + event.logentry = { + message: __sentry_template_string__, + params: __sentry_template_values__ + }; + return event; + } + event.message = message; + return event; +} +class ServerRuntimeClient extends Client { + /** + * Creates a new Edge SDK instance. + * @param options Configuration options for this SDK. + */ + constructor(options) { + registerSpanErrorInstrumentation(); + addUserAgentToTransportHeaders(options); + super(options); + this._setUpMetricsProcessing(); + } + /** + * @inheritDoc + */ + eventFromException(exception, hint) { + const event = eventFromUnknownInput(this, this._options.stackParser, exception, hint); + event.level = "error"; + return resolvedSyncPromise(event); + } + /** + * @inheritDoc + */ + eventFromMessage(message, level = "info", hint) { + return resolvedSyncPromise( + eventFromMessage(this._options.stackParser, message, level, hint, this._options.attachStacktrace) + ); + } + /** + * @inheritDoc + */ + captureException(exception, hint, scope) { + setCurrentRequestSessionErroredOrCrashed(hint); + return super.captureException(exception, hint, scope); + } + /** + * @inheritDoc + */ + captureEvent(event, hint, scope) { + const isException = !event.type && event.exception?.values && event.exception.values.length > 0; + if (isException) { + setCurrentRequestSessionErroredOrCrashed(hint); + } + return super.captureEvent(event, hint, scope); + } + /** + * Create a cron monitor check in and send it to Sentry. + * + * @param checkIn An object that describes a check in. + * @param upsertMonitorConfig An optional object that describes a monitor config. Use this if you want + * to create a monitor automatically when sending a check in. + */ + captureCheckIn(checkIn, monitorConfig, scope) { + const id = "checkInId" in checkIn && checkIn.checkInId ? checkIn.checkInId : uuid4(); + if (!this._isEnabled()) { + DEBUG_BUILD$3 && debug$2.warn("SDK not enabled, will not capture check-in."); + return id; + } + const options = this.getOptions(); + const { release, environment, tunnel } = options; + const serializedCheckIn = { + check_in_id: id, + monitor_slug: checkIn.monitorSlug, + status: checkIn.status, + release, + environment + }; + if ("duration" in checkIn) { + serializedCheckIn.duration = checkIn.duration; + } + if (monitorConfig) { + serializedCheckIn.monitor_config = { + schedule: monitorConfig.schedule, + checkin_margin: monitorConfig.checkinMargin, + max_runtime: monitorConfig.maxRuntime, + timezone: monitorConfig.timezone, + failure_issue_threshold: monitorConfig.failureIssueThreshold, + recovery_threshold: monitorConfig.recoveryThreshold + }; + } + const [dynamicSamplingContext, traceContext] = _getTraceInfoFromScope(this, scope); + if (traceContext) { + serializedCheckIn.contexts = { + trace: traceContext + }; + } + const envelope = createCheckInEnvelope( + serializedCheckIn, + dynamicSamplingContext, + this.getSdkMetadata(), + tunnel, + this.getDsn() + ); + DEBUG_BUILD$3 && debug$2.log("Sending checkin:", checkIn.monitorSlug, checkIn.status); + this.sendEnvelope(envelope); + return id; + } + /** + * @inheritDoc + */ + _prepareEvent(event, hint, currentScope, isolationScope) { + if (this._options.platform) { + event.platform = event.platform || this._options.platform; + } + if (this._options.runtime) { + event.contexts = { + ...event.contexts, + runtime: event.contexts?.runtime || this._options.runtime + }; + } + if (this._options.serverName) { + event.server_name = event.server_name || this._options.serverName; + } + return super._prepareEvent(event, hint, currentScope, isolationScope); + } + /** + * Process a server-side metric before it is captured. + */ + _setUpMetricsProcessing() { + this.on("processMetric", (metric) => { + if (this._options.serverName) { + metric.attributes = { + "server.address": this._options.serverName, + ...metric.attributes + }; + } + }); + } +} +function setCurrentRequestSessionErroredOrCrashed(eventHint) { + const requestSession = getIsolationScope().getScopeData().sdkProcessingMetadata.requestSession; + if (requestSession) { + const isHandledException = eventHint?.mechanism?.handled ?? true; + if (isHandledException && requestSession.status !== "crashed") { + requestSession.status = "errored"; + } else if (!isHandledException) { + requestSession.status = "crashed"; + } + } +} +const SKIPPED_AI_PROVIDERS = /* @__PURE__ */ new Set(); +function _INTERNAL_skipAiProviderWrapping(modules) { + modules.forEach((module2) => { + SKIPPED_AI_PROVIDERS.add(module2); + DEBUG_BUILD$3 && debug$2.log(`AI provider "${module2}" wrapping will be skipped`); + }); +} +function _INTERNAL_shouldSkipAiProviderWrapping(module2) { + return SKIPPED_AI_PROVIDERS.has(module2); +} +function _INTERNAL_clearAiProviderSkips() { + SKIPPED_AI_PROVIDERS.clear(); + DEBUG_BUILD$3 && debug$2.log("Cleared AI provider skip registrations"); +} +const DEFAULT_BASE_URL = "thismessage:/"; +function parseStringToURLObject(url, urlBase) { + const isRelative = url.indexOf("://") <= 0 && url.indexOf("//") !== 0; + const base = isRelative ? DEFAULT_BASE_URL : void 0; + try { + if ("canParse" in URL && !URL.canParse(url, base)) { + return void 0; + } + const fullUrlObject = new URL(url, base); + if (isRelative) { + return { + isRelative, + pathname: fullUrlObject.pathname, + search: fullUrlObject.search, + hash: fullUrlObject.hash + }; + } + return fullUrlObject; + } catch { + } + return void 0; +} +function parseUrl(url) { + if (!url) { + return {}; + } + const match2 = url.match(/^(([^:/?#]+):)?(\/\/([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?$/); + if (!match2) { + return {}; + } + const query = match2[6] || ""; + const fragment = match2[8] || ""; + return { + host: match2[4], + path: match2[5], + protocol: match2[2], + search: query, + hash: fragment, + relative: match2[5] + query + fragment + // everything minus origin + }; +} +function stripUrlQueryAndFragment(urlPath) { + return urlPath.split(/[?#]/, 1)[0]; +} +function getSanitizedUrlString(url) { + const { protocol, host, path: path2 } = url; + const filteredHost = host?.replace(/^.*@/, "[filtered]:[filtered]@").replace(/(:80)$/, "").replace(/(:443)$/, "") || ""; + return `${protocol ? `${protocol}://` : ""}${filteredHost}${path2}`; +} +function applySdkMetadata(options, name, names2 = [name], source = "npm") { + const metadata = options._metadata || {}; + if (!metadata.sdk) { + metadata.sdk = { + name: `sentry.javascript.${name}`, + packages: names2.map((name2) => ({ + name: `${source}:@sentry/${name2}`, + version: SDK_VERSION + })), + version: SDK_VERSION + }; + } + options._metadata = metadata; +} +function getTraceData$1(options = {}) { + const client = options.client || getClient(); + if (!isEnabled() || !client) { + return {}; + } + const carrier = getMainCarrier(); + const acs = getAsyncContextStrategy(carrier); + if (acs.getTraceData) { + return acs.getTraceData(options); + } + const scope = options.scope || getCurrentScope(); + const span = options.span || getActiveSpan$1(); + const sentryTrace = span ? spanToTraceHeader(span) : scopeToTraceHeader(scope); + const dsc = span ? getDynamicSamplingContextFromSpan(span) : getDynamicSamplingContextFromScope(client, scope); + const baggage = dynamicSamplingContextToSentryBaggageHeader(dsc); + const isValidSentryTraceHeader = TRACEPARENT_REGEXP.test(sentryTrace); + if (!isValidSentryTraceHeader) { + debug$2.warn("Invalid sentry-trace data. Cannot generate trace data"); + return {}; + } + const traceData = { + "sentry-trace": sentryTrace, + baggage + }; + if (options.propagateTraceparent) { + traceData.traceparent = span ? spanToTraceparentHeader(span) : scopeToTraceparentHeader(scope); + } + return traceData; +} +function scopeToTraceHeader(scope) { + const { traceId, sampled, propagationSpanId } = scope.getPropagationContext(); + return generateSentryTraceHeader(traceId, propagationSpanId, sampled); +} +function scopeToTraceparentHeader(scope) { + const { traceId, sampled, propagationSpanId } = scope.getPropagationContext(); + return generateTraceparentHeader(traceId, propagationSpanId, sampled); +} +function debounce(func, wait, options) { + let callbackReturnValue; + let timerId; + let maxTimerId; + const maxWait = Math.max(options.maxWait, wait); + const setTimeoutImpl = options?.setTimeoutImpl || setTimeout; + function invokeFunc() { + cancelTimers(); + callbackReturnValue = func(); + return callbackReturnValue; + } + function cancelTimers() { + timerId !== void 0 && clearTimeout(timerId); + maxTimerId !== void 0 && clearTimeout(maxTimerId); + timerId = maxTimerId = void 0; + } + function flush2() { + if (timerId !== void 0 || maxTimerId !== void 0) { + return invokeFunc(); + } + return callbackReturnValue; + } + function debounced() { + if (timerId) { + clearTimeout(timerId); + } + timerId = setTimeoutImpl(invokeFunc, wait); + if (maxWait && maxTimerId === void 0) { + maxTimerId = setTimeoutImpl(invokeFunc, maxWait); + } + return callbackReturnValue; + } + debounced.cancel = cancelTimers; + debounced.flush = flush2; + return debounced; +} +function headersToDict(reqHeaders) { + const headers = /* @__PURE__ */ Object.create(null); + try { + Object.entries(reqHeaders).forEach(([key, value]) => { + if (typeof value === "string") { + headers[key] = value; + } + }); + } catch { + } + return headers; +} +function httpRequestToRequestData(request) { + const headers = request.headers || {}; + const forwardedHost = typeof headers["x-forwarded-host"] === "string" ? headers["x-forwarded-host"] : void 0; + const host = forwardedHost || (typeof headers.host === "string" ? headers.host : void 0); + const forwardedProto = typeof headers["x-forwarded-proto"] === "string" ? headers["x-forwarded-proto"] : void 0; + const protocol = forwardedProto || request.protocol || (request.socket?.encrypted ? "https" : "http"); + const url = request.url || ""; + const absoluteUrl = getAbsoluteUrl$2({ + url, + host, + protocol + }); + const data = request.body || void 0; + const cookies = request.cookies; + return { + url: absoluteUrl, + method: request.method, + query_string: extractQueryParamsFromUrl(url), + headers: headersToDict(headers), + cookies, + data + }; +} +function getAbsoluteUrl$2({ + url, + protocol, + host +}) { + if (url?.startsWith("http")) { + return url; + } + if (url && host) { + return `${protocol}://${host}${url}`; + } + return void 0; +} +const SENSITIVE_HEADER_SNIPPETS = [ + "auth", + "token", + "secret", + "session", + // for the user_session cookie + "password", + "passwd", + "pwd", + "key", + "jwt", + "bearer", + "sso", + "saml", + "csrf", + "xsrf", + "credentials", + // Always treat cookie headers as sensitive in case individual key-value cookie pairs cannot properly be extracted + "set-cookie", + "cookie" +]; +const PII_HEADER_SNIPPETS = ["x-forwarded-", "-user"]; +function httpHeadersToSpanAttributes(headers, sendDefaultPii = false) { + const spanAttributes = {}; + try { + Object.entries(headers).forEach(([key, value]) => { + if (value == null) { + return; + } + const lowerCasedHeaderKey = key.toLowerCase(); + const isCookieHeader = lowerCasedHeaderKey === "cookie" || lowerCasedHeaderKey === "set-cookie"; + if (isCookieHeader && typeof value === "string" && value !== "") { + const isSetCookie = lowerCasedHeaderKey === "set-cookie"; + const semicolonIndex = value.indexOf(";"); + const cookieString = isSetCookie && semicolonIndex !== -1 ? value.substring(0, semicolonIndex) : value; + const cookies = isSetCookie ? [cookieString] : cookieString.split("; "); + for (const cookie of cookies) { + const equalSignIndex = cookie.indexOf("="); + const cookieKey = equalSignIndex !== -1 ? cookie.substring(0, equalSignIndex) : cookie; + const cookieValue = equalSignIndex !== -1 ? cookie.substring(equalSignIndex + 1) : ""; + const lowerCasedCookieKey = cookieKey.toLowerCase(); + addSpanAttribute(spanAttributes, lowerCasedHeaderKey, lowerCasedCookieKey, cookieValue, sendDefaultPii); + } + } else { + addSpanAttribute(spanAttributes, lowerCasedHeaderKey, "", value, sendDefaultPii); + } + }); + } catch { + } + return spanAttributes; +} +function normalizeAttributeKey(key) { + return key.replace(/-/g, "_"); +} +function addSpanAttribute(spanAttributes, headerKey, cookieKey, value, sendPii) { + const normalizedKey = cookieKey ? `http.request.header.${normalizeAttributeKey(headerKey)}.${normalizeAttributeKey(cookieKey)}` : `http.request.header.${normalizeAttributeKey(headerKey)}`; + const headerValue = handleHttpHeader(cookieKey || headerKey, value, sendPii); + if (headerValue !== void 0) { + spanAttributes[normalizedKey] = headerValue; + } +} +function handleHttpHeader(lowerCasedKey, value, sendPii) { + const isSensitive = sendPii ? SENSITIVE_HEADER_SNIPPETS.some((snippet) => lowerCasedKey.includes(snippet)) : [...PII_HEADER_SNIPPETS, ...SENSITIVE_HEADER_SNIPPETS].some((snippet) => lowerCasedKey.includes(snippet)); + if (isSensitive) { + return "[Filtered]"; + } else if (Array.isArray(value)) { + return value.map((v) => v != null ? String(v) : v).join(";"); + } else if (typeof value === "string") { + return value; + } + return void 0; +} +function extractQueryParamsFromUrl(url) { + if (!url) { + return; + } + try { + const queryParams = new URL(url, "http://s.io").search.slice(1); + return queryParams.length ? queryParams : void 0; + } catch { + return void 0; + } +} +const DEFAULT_BREADCRUMBS = 100; +function addBreadcrumb(breadcrumb, hint) { + const client = getClient(); + const isolationScope = getIsolationScope(); + if (!client) return; + const { beforeBreadcrumb = null, maxBreadcrumbs = DEFAULT_BREADCRUMBS } = client.getOptions(); + if (maxBreadcrumbs <= 0) return; + const timestamp = dateTimestampInSeconds(); + const mergedBreadcrumb = { timestamp, ...breadcrumb }; + const finalBreadcrumb = beforeBreadcrumb ? consoleSandbox(() => beforeBreadcrumb(mergedBreadcrumb, hint)) : mergedBreadcrumb; + if (finalBreadcrumb === null) return; + if (client.emit) { + client.emit("beforeAddBreadcrumb", finalBreadcrumb, hint); + } + isolationScope.addBreadcrumb(finalBreadcrumb, maxBreadcrumbs); +} +let originalFunctionToString; +const INTEGRATION_NAME$G = "FunctionToString"; +const SETUP_CLIENTS = /* @__PURE__ */ new WeakMap(); +const _functionToStringIntegration = (() => { + return { + name: INTEGRATION_NAME$G, + setupOnce() { + originalFunctionToString = Function.prototype.toString; + try { + Function.prototype.toString = function(...args) { + const originalFunction = getOriginalFunction(this); + const context2 = SETUP_CLIENTS.has(getClient()) && originalFunction !== void 0 ? originalFunction : this; + return originalFunctionToString.apply(context2, args); + }; + } catch { + } + }, + setup(client) { + SETUP_CLIENTS.set(client, true); + } + }; +}); +const functionToStringIntegration = defineIntegration(_functionToStringIntegration); +const DEFAULT_IGNORE_ERRORS = [ + /^Script error\.?$/, + /^Javascript error: Script error\.? on line 0$/, + /^ResizeObserver loop completed with undelivered notifications.$/, + // The browser logs this when a ResizeObserver handler takes a bit longer. Usually this is not an actual issue though. It indicates slowness. + /^Cannot redefine property: googletag$/, + // This is thrown when google tag manager is used in combination with an ad blocker + /^Can't find variable: gmo$/, + // Error from Google Search App https://issuetracker.google.com/issues/396043331 + /^undefined is not an object \(evaluating 'a\.[A-Z]'\)$/, + // Random error that happens but not actionable or noticeable to end-users. + `can't redefine non-configurable property "solana"`, + // Probably a browser extension or custom browser (Brave) throwing this error + "vv().getRestrictions is not a function. (In 'vv().getRestrictions(1,a)', 'vv().getRestrictions' is undefined)", + // Error thrown by GTM, seemingly not affecting end-users + "Can't find variable: _AutofillCallbackHandler", + // Unactionable error in instagram webview https://developers.facebook.com/community/threads/320013549791141/ + /^Non-Error promise rejection captured with value: Object Not Found Matching Id:\d+, MethodName:simulateEvent, ParamCount:\d+$/, + // unactionable error from CEFSharp, a .NET library that embeds chromium in .NET apps + /^Java exception was raised during method invocation$/ + // error from Facebook Mobile browser (https://github.com/getsentry/sentry-javascript/issues/15065) +]; +const INTEGRATION_NAME$F = "EventFilters"; +const eventFiltersIntegration = defineIntegration((options = {}) => { + let mergedOptions; + return { + name: INTEGRATION_NAME$F, + setup(client) { + const clientOptions = client.getOptions(); + mergedOptions = _mergeOptions(options, clientOptions); + }, + processEvent(event, _hint, client) { + if (!mergedOptions) { + const clientOptions = client.getOptions(); + mergedOptions = _mergeOptions(options, clientOptions); + } + return _shouldDropEvent(event, mergedOptions) ? null : event; + } + }; +}); +const inboundFiltersIntegration = defineIntegration(((options = {}) => { + return { + ...eventFiltersIntegration(options), + name: "InboundFilters" + }; +})); +function _mergeOptions(internalOptions = {}, clientOptions = {}) { + return { + allowUrls: [...internalOptions.allowUrls || [], ...clientOptions.allowUrls || []], + denyUrls: [...internalOptions.denyUrls || [], ...clientOptions.denyUrls || []], + ignoreErrors: [ + ...internalOptions.ignoreErrors || [], + ...clientOptions.ignoreErrors || [], + ...internalOptions.disableErrorDefaults ? [] : DEFAULT_IGNORE_ERRORS + ], + ignoreTransactions: [...internalOptions.ignoreTransactions || [], ...clientOptions.ignoreTransactions || []] + }; +} +function _shouldDropEvent(event, options) { + if (!event.type) { + if (_isIgnoredError(event, options.ignoreErrors)) { + DEBUG_BUILD$3 && debug$2.warn( + `Event dropped due to being matched by \`ignoreErrors\` option. +Event: ${getEventDescription(event)}` + ); + return true; + } + if (_isUselessError(event)) { + DEBUG_BUILD$3 && debug$2.warn( + `Event dropped due to not having an error message, error type or stacktrace. +Event: ${getEventDescription( + event + )}` + ); + return true; + } + if (_isDeniedUrl(event, options.denyUrls)) { + DEBUG_BUILD$3 && debug$2.warn( + `Event dropped due to being matched by \`denyUrls\` option. +Event: ${getEventDescription( + event + )}. +Url: ${_getEventFilterUrl(event)}` + ); + return true; + } + if (!_isAllowedUrl(event, options.allowUrls)) { + DEBUG_BUILD$3 && debug$2.warn( + `Event dropped due to not being matched by \`allowUrls\` option. +Event: ${getEventDescription( + event + )}. +Url: ${_getEventFilterUrl(event)}` + ); + return true; + } + } else if (event.type === "transaction") { + if (_isIgnoredTransaction(event, options.ignoreTransactions)) { + DEBUG_BUILD$3 && debug$2.warn( + `Event dropped due to being matched by \`ignoreTransactions\` option. +Event: ${getEventDescription(event)}` + ); + return true; + } + } + return false; +} +function _isIgnoredError(event, ignoreErrors) { + if (!ignoreErrors?.length) { + return false; + } + return getPossibleEventMessages(event).some((message) => stringMatchesSomePattern(message, ignoreErrors)); +} +function _isIgnoredTransaction(event, ignoreTransactions) { + if (!ignoreTransactions?.length) { + return false; + } + const name = event.transaction; + return name ? stringMatchesSomePattern(name, ignoreTransactions) : false; +} +function _isDeniedUrl(event, denyUrls) { + if (!denyUrls?.length) { + return false; + } + const url = _getEventFilterUrl(event); + return !url ? false : stringMatchesSomePattern(url, denyUrls); +} +function _isAllowedUrl(event, allowUrls) { + if (!allowUrls?.length) { + return true; + } + const url = _getEventFilterUrl(event); + return !url ? true : stringMatchesSomePattern(url, allowUrls); +} +function _getLastValidUrl(frames = []) { + for (let i = frames.length - 1; i >= 0; i--) { + const frame = frames[i]; + if (frame && frame.filename !== "" && frame.filename !== "[native code]") { + return frame.filename || null; + } + } + return null; +} +function _getEventFilterUrl(event) { + try { + const rootException = [...event.exception?.values ?? []].reverse().find((value) => value.mechanism?.parent_id === void 0 && value.stacktrace?.frames?.length); + const frames = rootException?.stacktrace?.frames; + return frames ? _getLastValidUrl(frames) : null; + } catch { + DEBUG_BUILD$3 && debug$2.error(`Cannot extract url for event ${getEventDescription(event)}`); + return null; + } +} +function _isUselessError(event) { + if (!event.exception?.values?.length) { + return false; + } + return ( + // No top-level message + !event.message && // There are no exception values that have a stacktrace, a non-generic-Error type or value + !event.exception.values.some((value) => value.stacktrace || value.type && value.type !== "Error" || value.value) + ); +} +function applyAggregateErrorsToEvent(exceptionFromErrorImplementation, parser, key, limit, event, hint) { + if (!event.exception?.values || !hint || !isInstanceOf(hint.originalException, Error)) { + return; + } + const originalException = event.exception.values.length > 0 ? event.exception.values[event.exception.values.length - 1] : void 0; + if (originalException) { + event.exception.values = aggregateExceptionsFromError( + exceptionFromErrorImplementation, + parser, + limit, + hint.originalException, + key, + event.exception.values, + originalException, + 0 + ); + } +} +function aggregateExceptionsFromError(exceptionFromErrorImplementation, parser, limit, error2, key, prevExceptions, exception, exceptionId) { + if (prevExceptions.length >= limit + 1) { + return prevExceptions; + } + let newExceptions = [...prevExceptions]; + if (isInstanceOf(error2[key], Error)) { + applyExceptionGroupFieldsForParentException(exception, exceptionId); + const newException = exceptionFromErrorImplementation(parser, error2[key]); + const newExceptionId = newExceptions.length; + applyExceptionGroupFieldsForChildException(newException, key, newExceptionId, exceptionId); + newExceptions = aggregateExceptionsFromError( + exceptionFromErrorImplementation, + parser, + limit, + error2[key], + key, + [newException, ...newExceptions], + newException, + newExceptionId + ); + } + if (Array.isArray(error2.errors)) { + error2.errors.forEach((childError, i) => { + if (isInstanceOf(childError, Error)) { + applyExceptionGroupFieldsForParentException(exception, exceptionId); + const newException = exceptionFromErrorImplementation(parser, childError); + const newExceptionId = newExceptions.length; + applyExceptionGroupFieldsForChildException(newException, `errors[${i}]`, newExceptionId, exceptionId); + newExceptions = aggregateExceptionsFromError( + exceptionFromErrorImplementation, + parser, + limit, + childError, + key, + [newException, ...newExceptions], + newException, + newExceptionId + ); + } + }); + } + return newExceptions; +} +function applyExceptionGroupFieldsForParentException(exception, exceptionId) { + exception.mechanism = { + handled: true, + type: "auto.core.linked_errors", + ...exception.mechanism, + ...exception.type === "AggregateError" && { is_exception_group: true }, + exception_id: exceptionId + }; +} +function applyExceptionGroupFieldsForChildException(exception, source, exceptionId, parentId) { + exception.mechanism = { + handled: true, + ...exception.mechanism, + type: "chained", + source, + exception_id: exceptionId, + parent_id: parentId + }; +} +const DEFAULT_KEY = "cause"; +const DEFAULT_LIMIT = 5; +const INTEGRATION_NAME$E = "LinkedErrors"; +const _linkedErrorsIntegration = ((options = {}) => { + const limit = options.limit || DEFAULT_LIMIT; + const key = options.key || DEFAULT_KEY; + return { + name: INTEGRATION_NAME$E, + preprocessEvent(event, hint, client) { + const options2 = client.getOptions(); + applyAggregateErrorsToEvent(exceptionFromError, options2.stackParser, key, limit, event, hint); + } + }; +}); +const linkedErrorsIntegration = defineIntegration(_linkedErrorsIntegration); +function parseCookie(str) { + const obj = {}; + let index = 0; + while (index < str.length) { + const eqIdx = str.indexOf("=", index); + if (eqIdx === -1) { + break; + } + let endIdx = str.indexOf(";", index); + if (endIdx === -1) { + endIdx = str.length; + } else if (endIdx < eqIdx) { + index = str.lastIndexOf(";", eqIdx - 1) + 1; + continue; + } + const key = str.slice(index, eqIdx).trim(); + if (void 0 === obj[key]) { + let val = str.slice(eqIdx + 1, endIdx).trim(); + if (val.charCodeAt(0) === 34) { + val = val.slice(1, -1); + } + try { + obj[key] = val.indexOf("%") !== -1 ? decodeURIComponent(val) : val; + } catch { + obj[key] = val; + } + } + index = endIdx + 1; + } + return obj; +} +const ipHeaderNames = [ + "X-Client-IP", + "X-Forwarded-For", + "Fly-Client-IP", + "CF-Connecting-IP", + "Fastly-Client-Ip", + "True-Client-Ip", + "X-Real-IP", + "X-Cluster-Client-IP", + "X-Forwarded", + "Forwarded-For", + "Forwarded", + "X-Vercel-Forwarded-For" +]; +function getClientIPAddress(headers) { + const headerValues = ipHeaderNames.map((headerName) => { + const rawValue = headers[headerName]; + const value = Array.isArray(rawValue) ? rawValue.join(";") : rawValue; + if (headerName === "Forwarded") { + return parseForwardedHeader(value); + } + return value?.split(",").map((v) => v.trim()); + }); + const flattenedHeaderValues = headerValues.reduce((acc, val) => { + if (!val) { + return acc; + } + return acc.concat(val); + }, []); + const ipAddress = flattenedHeaderValues.find((ip) => ip !== null && isIP(ip)); + return ipAddress || null; +} +function parseForwardedHeader(value) { + if (!value) { + return null; + } + for (const part of value.split(";")) { + if (part.startsWith("for=")) { + return part.slice(4); + } + } + return null; +} +function isIP(str) { + const regex = /(?:^(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)){3}$)|(?:^(?:(?:[a-fA-F\d]{1,4}:){7}(?:[a-fA-F\d]{1,4}|:)|(?:[a-fA-F\d]{1,4}:){6}(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)(?:\\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)){3}|:[a-fA-F\d]{1,4}|:)|(?:[a-fA-F\d]{1,4}:){5}(?::(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)(?:\\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)){3}|(?::[a-fA-F\d]{1,4}){1,2}|:)|(?:[a-fA-F\d]{1,4}:){4}(?:(?::[a-fA-F\d]{1,4}){0,1}:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)(?:\\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)){3}|(?::[a-fA-F\d]{1,4}){1,3}|:)|(?:[a-fA-F\d]{1,4}:){3}(?:(?::[a-fA-F\d]{1,4}){0,2}:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)(?:\\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)){3}|(?::[a-fA-F\d]{1,4}){1,4}|:)|(?:[a-fA-F\d]{1,4}:){2}(?:(?::[a-fA-F\d]{1,4}){0,3}:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)(?:\\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)){3}|(?::[a-fA-F\d]{1,4}){1,5}|:)|(?:[a-fA-F\d]{1,4}:){1}(?:(?::[a-fA-F\d]{1,4}){0,4}:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)(?:\\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)){3}|(?::[a-fA-F\d]{1,4}){1,6}|:)|(?::(?:(?::[a-fA-F\d]{1,4}){0,5}:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)(?:\\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)){3}|(?::[a-fA-F\d]{1,4}){1,7}|:)))(?:%[0-9a-zA-Z]{1,})?$)/; + return regex.test(str); +} +const DEFAULT_INCLUDE = { + cookies: true, + data: true, + headers: true, + query_string: true, + url: true +}; +const INTEGRATION_NAME$D = "RequestData"; +const _requestDataIntegration = ((options = {}) => { + const include = { + ...DEFAULT_INCLUDE, + ...options.include + }; + return { + name: INTEGRATION_NAME$D, + processEvent(event, _hint, client) { + const { sdkProcessingMetadata = {} } = event; + const { normalizedRequest, ipAddress } = sdkProcessingMetadata; + const includeWithDefaultPiiApplied = { + ...include, + ip: include.ip ?? client.getOptions().sendDefaultPii + }; + if (normalizedRequest) { + addNormalizedRequestDataToEvent(event, normalizedRequest, { ipAddress }, includeWithDefaultPiiApplied); + } + return event; + } + }; +}); +const requestDataIntegration = defineIntegration(_requestDataIntegration); +function addNormalizedRequestDataToEvent(event, req, additionalData, include) { + event.request = { + ...event.request, + ...extractNormalizedRequestData(req, include) + }; + if (include.ip) { + const ip = req.headers && getClientIPAddress(req.headers) || additionalData.ipAddress; + if (ip) { + event.user = { + ...event.user, + ip_address: ip + }; + } + } +} +function extractNormalizedRequestData(normalizedRequest, include) { + const requestData = {}; + const headers = { ...normalizedRequest.headers }; + if (include.headers) { + requestData.headers = headers; + if (!include.cookies) { + delete headers.cookie; + } + if (!include.ip) { + ipHeaderNames.forEach((ipHeaderName) => { + delete headers[ipHeaderName]; + }); + } + } + requestData.method = normalizedRequest.method; + if (include.url) { + requestData.url = normalizedRequest.url; + } + if (include.cookies) { + const cookies = normalizedRequest.cookies || (headers?.cookie ? parseCookie(headers.cookie) : void 0); + requestData.cookies = cookies || {}; + } + if (include.query_string) { + requestData.query_string = normalizedRequest.query_string; + } + if (include.data) { + requestData.data = normalizedRequest.data; + } + return requestData; +} +function addConsoleInstrumentationHandler(handler) { + const type = "console"; + addHandler(type, handler); + maybeInstrument(type, instrumentConsole); +} +function instrumentConsole() { + if (!("console" in GLOBAL_OBJ)) { + return; + } + CONSOLE_LEVELS.forEach(function(level) { + if (!(level in GLOBAL_OBJ.console)) { + return; + } + fill(GLOBAL_OBJ.console, level, function(originalConsoleMethod) { + originalConsoleMethods[level] = originalConsoleMethod; + return function(...args) { + const handlerData = { args, level }; + triggerHandlers("console", handlerData); + const log2 = originalConsoleMethods[level]; + log2?.apply(GLOBAL_OBJ.console, args); + }; + }); + }); +} +function severityLevelFromString(level) { + return level === "warn" ? "warning" : ["fatal", "error", "warning", "log", "info", "debug"].includes(level) ? level : "log"; +} +const splitPathRe = /^(\S+:\\|\/?)([\s\S]*?)((?:\.{1,2}|[^/\\]+?|)(\.[^./\\]*|))(?:[/\\]*)$/; +function splitPath(filename) { + const truncated = filename.length > 1024 ? `${filename.slice(-1024)}` : filename; + const parts = splitPathRe.exec(truncated); + return parts ? parts.slice(1) : []; +} +function dirname(path2) { + const result = splitPath(path2); + const root = result[0] || ""; + let dir = result[1]; + if (!root && !dir) { + return "."; + } + if (dir) { + dir = dir.slice(0, dir.length - 1); + } + return root + dir; +} +const INTEGRATION_NAME$C = "Console"; +const consoleIntegration = defineIntegration((options = {}) => { + const levels = new Set(options.levels || CONSOLE_LEVELS); + return { + name: INTEGRATION_NAME$C, + setup(client) { + addConsoleInstrumentationHandler(({ args, level }) => { + if (getClient() !== client || !levels.has(level)) { + return; + } + addConsoleBreadcrumb(level, args); + }); + } + }; +}); +function addConsoleBreadcrumb(level, args) { + const breadcrumb = { + category: "console", + data: { + arguments: args, + logger: "console" + }, + level: severityLevelFromString(level), + message: formatConsoleArgs(args) + }; + if (level === "assert") { + if (args[0] === false) { + const assertionArgs = args.slice(1); + breadcrumb.message = assertionArgs.length > 0 ? `Assertion failed: ${formatConsoleArgs(assertionArgs)}` : "Assertion failed"; + breadcrumb.data.arguments = assertionArgs; + } else { + return; + } + } + addBreadcrumb(breadcrumb, { + input: args, + level + }); +} +function formatConsoleArgs(values) { + return "util" in GLOBAL_OBJ && typeof GLOBAL_OBJ.util.format === "function" ? GLOBAL_OBJ.util.format(...values) : safeJoin(values, " "); +} +const GEN_AI_PROMPT_ATTRIBUTE = "gen_ai.prompt"; +const GEN_AI_SYSTEM_ATTRIBUTE = "gen_ai.system"; +const GEN_AI_REQUEST_MODEL_ATTRIBUTE = "gen_ai.request.model"; +const GEN_AI_REQUEST_STREAM_ATTRIBUTE = "gen_ai.request.stream"; +const GEN_AI_REQUEST_TEMPERATURE_ATTRIBUTE = "gen_ai.request.temperature"; +const GEN_AI_REQUEST_MAX_TOKENS_ATTRIBUTE = "gen_ai.request.max_tokens"; +const GEN_AI_REQUEST_FREQUENCY_PENALTY_ATTRIBUTE = "gen_ai.request.frequency_penalty"; +const GEN_AI_REQUEST_PRESENCE_PENALTY_ATTRIBUTE = "gen_ai.request.presence_penalty"; +const GEN_AI_REQUEST_TOP_P_ATTRIBUTE = "gen_ai.request.top_p"; +const GEN_AI_REQUEST_TOP_K_ATTRIBUTE = "gen_ai.request.top_k"; +const GEN_AI_REQUEST_ENCODING_FORMAT_ATTRIBUTE = "gen_ai.request.encoding_format"; +const GEN_AI_REQUEST_DIMENSIONS_ATTRIBUTE = "gen_ai.request.dimensions"; +const GEN_AI_RESPONSE_FINISH_REASONS_ATTRIBUTE = "gen_ai.response.finish_reasons"; +const GEN_AI_RESPONSE_MODEL_ATTRIBUTE = "gen_ai.response.model"; +const GEN_AI_RESPONSE_ID_ATTRIBUTE = "gen_ai.response.id"; +const GEN_AI_RESPONSE_STOP_REASON_ATTRIBUTE = "gen_ai.response.stop_reason"; +const GEN_AI_USAGE_INPUT_TOKENS_ATTRIBUTE = "gen_ai.usage.input_tokens"; +const GEN_AI_USAGE_OUTPUT_TOKENS_ATTRIBUTE = "gen_ai.usage.output_tokens"; +const GEN_AI_USAGE_TOTAL_TOKENS_ATTRIBUTE = "gen_ai.usage.total_tokens"; +const GEN_AI_OPERATION_NAME_ATTRIBUTE = "gen_ai.operation.name"; +const GEN_AI_REQUEST_MESSAGES_ATTRIBUTE = "gen_ai.request.messages"; +const GEN_AI_RESPONSE_TEXT_ATTRIBUTE = "gen_ai.response.text"; +const GEN_AI_REQUEST_AVAILABLE_TOOLS_ATTRIBUTE = "gen_ai.request.available_tools"; +const GEN_AI_RESPONSE_STREAMING_ATTRIBUTE = "gen_ai.response.streaming"; +const GEN_AI_RESPONSE_TOOL_CALLS_ATTRIBUTE = "gen_ai.response.tool_calls"; +const GEN_AI_AGENT_NAME_ATTRIBUTE = "gen_ai.agent.name"; +const GEN_AI_PIPELINE_NAME_ATTRIBUTE = "gen_ai.pipeline.name"; +const GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS_ATTRIBUTE = "gen_ai.usage.cache_creation_input_tokens"; +const GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS_ATTRIBUTE = "gen_ai.usage.cache_read_input_tokens"; +const GEN_AI_USAGE_INPUT_TOKENS_CACHE_WRITE_ATTRIBUTE = "gen_ai.usage.input_tokens.cache_write"; +const GEN_AI_USAGE_INPUT_TOKENS_CACHED_ATTRIBUTE = "gen_ai.usage.input_tokens.cached"; +const GEN_AI_INVOKE_AGENT_OPERATION_ATTRIBUTE = "gen_ai.invoke_agent"; +const GEN_AI_GENERATE_TEXT_DO_GENERATE_OPERATION_ATTRIBUTE = "gen_ai.generate_text"; +const GEN_AI_STREAM_TEXT_DO_STREAM_OPERATION_ATTRIBUTE = "gen_ai.stream_text"; +const GEN_AI_GENERATE_OBJECT_DO_GENERATE_OPERATION_ATTRIBUTE = "gen_ai.generate_object"; +const GEN_AI_STREAM_OBJECT_DO_STREAM_OPERATION_ATTRIBUTE = "gen_ai.stream_object"; +const GEN_AI_EMBED_DO_EMBED_OPERATION_ATTRIBUTE = "gen_ai.embed"; +const GEN_AI_EMBED_MANY_DO_EMBED_OPERATION_ATTRIBUTE = "gen_ai.embed_many"; +const GEN_AI_EXECUTE_TOOL_OPERATION_ATTRIBUTE = "gen_ai.execute_tool"; +const OPENAI_RESPONSE_ID_ATTRIBUTE = "openai.response.id"; +const OPENAI_RESPONSE_MODEL_ATTRIBUTE = "openai.response.model"; +const OPENAI_RESPONSE_TIMESTAMP_ATTRIBUTE = "openai.response.timestamp"; +const OPENAI_USAGE_COMPLETION_TOKENS_ATTRIBUTE = "openai.usage.completion_tokens"; +const OPENAI_USAGE_PROMPT_TOKENS_ATTRIBUTE = "openai.usage.prompt_tokens"; +const OPENAI_OPERATIONS = { + CHAT: "chat", + RESPONSES: "responses", + EMBEDDINGS: "embeddings" +}; +const ANTHROPIC_AI_RESPONSE_TIMESTAMP_ATTRIBUTE = "anthropic.response.timestamp"; +const toolCallSpanMap = /* @__PURE__ */ new Map(); +const DEFAULT_GEN_AI_MESSAGES_BYTE_LIMIT = 2e4; +const utf8Bytes = (text) => { + return new TextEncoder().encode(text).length; +}; +const jsonBytes = (value) => { + return utf8Bytes(JSON.stringify(value)); +}; +function truncateTextByBytes(text, maxBytes) { + if (utf8Bytes(text) <= maxBytes) { + return text; + } + let low = 0; + let high = text.length; + let bestFit = ""; + while (low <= high) { + const mid = Math.floor((low + high) / 2); + const candidate = text.slice(0, mid); + const byteSize = utf8Bytes(candidate); + if (byteSize <= maxBytes) { + bestFit = candidate; + low = mid + 1; + } else { + high = mid - 1; + } + } + return bestFit; +} +function getPartText(part) { + if (typeof part === "string") { + return part; + } + if ("text" in part) return part.text; + return ""; +} +function withPartText(part, text) { + if (typeof part === "string") { + return text; + } + return { ...part, text }; +} +function isContentMessage(message) { + return message !== null && typeof message === "object" && "content" in message && typeof message.content === "string"; +} +function isContentArrayMessage(message) { + return message !== null && typeof message === "object" && "content" in message && Array.isArray(message.content); +} +function isContentMedia(part) { + if (!part || typeof part !== "object") return false; + return isContentMediaSource(part) || hasInlineData(part) || "media_type" in part && typeof part.media_type === "string" && "data" in part || "image_url" in part && typeof part.image_url === "string" && part.image_url.startsWith("data:") || "type" in part && (part.type === "blob" || part.type === "base64") || "b64_json" in part || "type" in part && "result" in part && part.type === "image_generation" || "uri" in part && typeof part.uri === "string" && part.uri.startsWith("data:"); +} +function isContentMediaSource(part) { + return "type" in part && typeof part.type === "string" && "source" in part && isContentMedia(part.source); +} +function hasInlineData(part) { + return "inlineData" in part && !!part.inlineData && typeof part.inlineData === "object" && "data" in part.inlineData && typeof part.inlineData.data === "string"; +} +function isPartsMessage(message) { + return message !== null && typeof message === "object" && "parts" in message && Array.isArray(message.parts) && message.parts.length > 0; +} +function truncateContentMessage(message, maxBytes) { + const emptyMessage = { ...message, content: "" }; + const overhead = jsonBytes(emptyMessage); + const availableForContent = maxBytes - overhead; + if (availableForContent <= 0) { + return []; + } + const truncatedContent = truncateTextByBytes(message.content, availableForContent); + return [{ ...message, content: truncatedContent }]; +} +function truncatePartsMessage(message, maxBytes) { + const { parts } = message; + const emptyParts = parts.map((part) => withPartText(part, "")); + const overhead = jsonBytes({ ...message, parts: emptyParts }); + let remainingBytes = maxBytes - overhead; + if (remainingBytes <= 0) { + return []; + } + const includedParts = []; + for (const part of parts) { + const text = getPartText(part); + const textSize = utf8Bytes(text); + if (textSize <= remainingBytes) { + includedParts.push(part); + remainingBytes -= textSize; + } else if (includedParts.length === 0) { + const truncated = truncateTextByBytes(text, remainingBytes); + if (truncated) { + includedParts.push(withPartText(part, truncated)); + } + break; + } else { + break; + } + } + if (includedParts.length <= 0) { + return []; + } else { + return [{ ...message, parts: includedParts }]; + } +} +function truncateSingleMessage(message, maxBytes) { + if (!message || typeof message !== "object") { + return []; + } + if (isContentMessage(message)) { + return truncateContentMessage(message, maxBytes); + } + if (isPartsMessage(message)) { + return truncatePartsMessage(message, maxBytes); + } + return []; +} +const REMOVED_STRING = "[Filtered]"; +const MEDIA_FIELDS = ["image_url", "data", "content", "b64_json", "result", "uri"]; +function stripInlineMediaFromSingleMessage(part) { + const strip = { ...part }; + if (isContentMedia(strip.source)) { + strip.source = stripInlineMediaFromSingleMessage(strip.source); + } + if (hasInlineData(part)) { + strip.inlineData = { ...part.inlineData, data: REMOVED_STRING }; + } + for (const field of MEDIA_FIELDS) { + if (typeof strip[field] === "string") strip[field] = REMOVED_STRING; + } + return strip; +} +function stripInlineMediaFromMessages(messages) { + const stripped = messages.map((message) => { + let newMessage = void 0; + if (!!message && typeof message === "object") { + if (isContentArrayMessage(message)) { + newMessage = { + ...message, + content: stripInlineMediaFromMessages(message.content) + }; + } else if ("content" in message && isContentMedia(message.content)) { + newMessage = { + ...message, + content: stripInlineMediaFromSingleMessage(message.content) + }; + } + if (isPartsMessage(message)) { + newMessage = { + // might have to strip content AND parts + ...newMessage ?? message, + parts: stripInlineMediaFromMessages(message.parts) + }; + } + if (isContentMedia(newMessage)) { + newMessage = stripInlineMediaFromSingleMessage(newMessage); + } else if (isContentMedia(message)) { + newMessage = stripInlineMediaFromSingleMessage(message); + } + } + return newMessage ?? message; + }); + return stripped; +} +function truncateMessagesByBytes(messages, maxBytes) { + if (!Array.isArray(messages) || messages.length === 0) { + return messages; + } + const stripped = stripInlineMediaFromMessages(messages); + const totalBytes = jsonBytes(stripped); + if (totalBytes <= maxBytes) { + return stripped; + } + const messageSizes = stripped.map(jsonBytes); + let bytesUsed = 0; + let startIndex = stripped.length; + for (let i = stripped.length - 1; i >= 0; i--) { + const messageSize = messageSizes[i]; + if (messageSize && bytesUsed + messageSize > maxBytes) { + break; + } + if (messageSize) { + bytesUsed += messageSize; + } + startIndex = i; + } + if (startIndex === stripped.length) { + const newestMessage = stripped[stripped.length - 1]; + return truncateSingleMessage(newestMessage, maxBytes); + } + return stripped.slice(startIndex); +} +function truncateGenAiMessages(messages) { + return truncateMessagesByBytes(messages, DEFAULT_GEN_AI_MESSAGES_BYTE_LIMIT); +} +function truncateGenAiStringInput(input) { + return truncateTextByBytes(input, DEFAULT_GEN_AI_MESSAGES_BYTE_LIMIT); +} +function getFinalOperationName(methodPath) { + if (methodPath.includes("messages")) { + return "messages"; + } + if (methodPath.includes("completions")) { + return "completions"; + } + if (methodPath.includes("models")) { + return "models"; + } + if (methodPath.includes("chat")) { + return "chat"; + } + return methodPath.split(".").pop() || "unknown"; +} +function getSpanOperation$1(methodPath) { + return `gen_ai.${getFinalOperationName(methodPath)}`; +} +function buildMethodPath$1(currentPath, prop) { + return currentPath ? `${currentPath}.${prop}` : prop; +} +function setTokenUsageAttributes$1(span, promptTokens, completionTokens, cachedInputTokens, cachedOutputTokens) { + if (promptTokens !== void 0) { + span.setAttributes({ + [GEN_AI_USAGE_INPUT_TOKENS_ATTRIBUTE]: promptTokens + }); + } + if (completionTokens !== void 0) { + span.setAttributes({ + [GEN_AI_USAGE_OUTPUT_TOKENS_ATTRIBUTE]: completionTokens + }); + } + if (promptTokens !== void 0 || completionTokens !== void 0 || cachedInputTokens !== void 0 || cachedOutputTokens !== void 0) { + const totalTokens = (promptTokens ?? 0) + (completionTokens ?? 0) + (cachedInputTokens ?? 0) + (cachedOutputTokens ?? 0); + span.setAttributes({ + [GEN_AI_USAGE_TOTAL_TOKENS_ATTRIBUTE]: totalTokens + }); + } +} +function getTruncatedJsonString(value) { + if (typeof value === "string") { + return truncateGenAiStringInput(value); + } + if (Array.isArray(value)) { + const truncatedMessages = truncateGenAiMessages(value); + return JSON.stringify(truncatedMessages); + } + return JSON.stringify(value); +} +const OPERATION_NAME_ATTRIBUTE = "operation.name"; +const AI_PROMPT_ATTRIBUTE = "ai.prompt"; +const AI_SCHEMA_ATTRIBUTE = "ai.schema"; +const AI_RESPONSE_OBJECT_ATTRIBUTE = "ai.response.object"; +const AI_RESPONSE_TEXT_ATTRIBUTE = "ai.response.text"; +const AI_RESPONSE_TOOL_CALLS_ATTRIBUTE = "ai.response.toolCalls"; +const AI_PROMPT_MESSAGES_ATTRIBUTE = "ai.prompt.messages"; +const AI_PROMPT_TOOLS_ATTRIBUTE = "ai.prompt.tools"; +const AI_MODEL_ID_ATTRIBUTE = "ai.model.id"; +const AI_RESPONSE_PROVIDER_METADATA_ATTRIBUTE = "ai.response.providerMetadata"; +const AI_USAGE_CACHED_INPUT_TOKENS_ATTRIBUTE = "ai.usage.cachedInputTokens"; +const AI_TELEMETRY_FUNCTION_ID_ATTRIBUTE = "ai.telemetry.functionId"; +const AI_USAGE_COMPLETION_TOKENS_ATTRIBUTE = "ai.usage.completionTokens"; +const AI_USAGE_PROMPT_TOKENS_ATTRIBUTE = "ai.usage.promptTokens"; +const AI_TOOL_CALL_NAME_ATTRIBUTE = "ai.toolCall.name"; +const AI_TOOL_CALL_ID_ATTRIBUTE = "ai.toolCall.id"; +const AI_TOOL_CALL_ARGS_ATTRIBUTE = "ai.toolCall.args"; +const AI_TOOL_CALL_RESULT_ATTRIBUTE = "ai.toolCall.result"; +function accumulateTokensForParent(span, tokenAccumulator) { + const parentSpanId = span.parent_span_id; + if (!parentSpanId) { + return; + } + const inputTokens = span.data[GEN_AI_USAGE_INPUT_TOKENS_ATTRIBUTE]; + const outputTokens = span.data[GEN_AI_USAGE_OUTPUT_TOKENS_ATTRIBUTE]; + if (typeof inputTokens === "number" || typeof outputTokens === "number") { + const existing = tokenAccumulator.get(parentSpanId) || { inputTokens: 0, outputTokens: 0 }; + if (typeof inputTokens === "number") { + existing.inputTokens += inputTokens; + } + if (typeof outputTokens === "number") { + existing.outputTokens += outputTokens; + } + tokenAccumulator.set(parentSpanId, existing); + } +} +function applyAccumulatedTokens(spanOrTrace, tokenAccumulator) { + const accumulated = tokenAccumulator.get(spanOrTrace.span_id); + if (!accumulated || !spanOrTrace.data) { + return; + } + if (accumulated.inputTokens > 0) { + spanOrTrace.data[GEN_AI_USAGE_INPUT_TOKENS_ATTRIBUTE] = accumulated.inputTokens; + } + if (accumulated.outputTokens > 0) { + spanOrTrace.data[GEN_AI_USAGE_OUTPUT_TOKENS_ATTRIBUTE] = accumulated.outputTokens; + } + if (accumulated.inputTokens > 0 || accumulated.outputTokens > 0) { + spanOrTrace.data["gen_ai.usage.total_tokens"] = accumulated.inputTokens + accumulated.outputTokens; + } +} +function _INTERNAL_getSpanForToolCallId(toolCallId) { + return toolCallSpanMap.get(toolCallId); +} +function _INTERNAL_cleanupToolCallSpan(toolCallId) { + toolCallSpanMap.delete(toolCallId); +} +function convertAvailableToolsToJsonString(tools) { + const toolObjects = tools.map((tool) => { + if (typeof tool === "string") { + try { + return JSON.parse(tool); + } catch { + return tool; + } + } + return tool; + }); + return JSON.stringify(toolObjects); +} +function convertPromptToMessages(prompt) { + try { + const p = JSON.parse(prompt); + if (!!p && typeof p === "object") { + const { prompt: prompt2, system } = p; + if (typeof prompt2 === "string" || typeof system === "string") { + const messages = []; + if (typeof system === "string") { + messages.push({ role: "system", content: system }); + } + if (typeof prompt2 === "string") { + messages.push({ role: "user", content: prompt2 }); + } + return messages; + } + } + } catch { + } + return []; +} +function requestMessagesFromPrompt(span, attributes) { + if (attributes[AI_PROMPT_ATTRIBUTE]) { + const truncatedPrompt = getTruncatedJsonString(attributes[AI_PROMPT_ATTRIBUTE]); + span.setAttribute("gen_ai.prompt", truncatedPrompt); + } + const prompt = attributes[AI_PROMPT_ATTRIBUTE]; + if (typeof prompt === "string" && !attributes[GEN_AI_REQUEST_MESSAGES_ATTRIBUTE] && !attributes[AI_PROMPT_MESSAGES_ATTRIBUTE]) { + const messages = convertPromptToMessages(prompt); + if (messages.length) span.setAttribute(GEN_AI_REQUEST_MESSAGES_ATTRIBUTE, getTruncatedJsonString(messages)); + } +} +function getSpanOpFromName(name) { + switch (name) { + case "ai.generateText": + case "ai.streamText": + case "ai.generateObject": + case "ai.streamObject": + case "ai.embed": + case "ai.embedMany": + return GEN_AI_INVOKE_AGENT_OPERATION_ATTRIBUTE; + case "ai.generateText.doGenerate": + return GEN_AI_GENERATE_TEXT_DO_GENERATE_OPERATION_ATTRIBUTE; + case "ai.streamText.doStream": + return GEN_AI_STREAM_TEXT_DO_STREAM_OPERATION_ATTRIBUTE; + case "ai.generateObject.doGenerate": + return GEN_AI_GENERATE_OBJECT_DO_GENERATE_OPERATION_ATTRIBUTE; + case "ai.streamObject.doStream": + return GEN_AI_STREAM_OBJECT_DO_STREAM_OPERATION_ATTRIBUTE; + case "ai.embed.doEmbed": + return GEN_AI_EMBED_DO_EMBED_OPERATION_ATTRIBUTE; + case "ai.embedMany.doEmbed": + return GEN_AI_EMBED_MANY_DO_EMBED_OPERATION_ATTRIBUTE; + case "ai.toolCall": + return GEN_AI_EXECUTE_TOOL_OPERATION_ATTRIBUTE; + default: + if (name.startsWith("ai.stream")) { + return "ai.run"; + } + return void 0; + } +} +function addOriginToSpan$1(span, origin) { + span.setAttribute(SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN, origin); +} +function onVercelAiSpanStart(span) { + const { data: attributes, description: name } = spanToJSON(span); + if (!name) { + return; + } + if (attributes[AI_TOOL_CALL_NAME_ATTRIBUTE] && attributes[AI_TOOL_CALL_ID_ATTRIBUTE] && name === "ai.toolCall") { + processToolCallSpan(span, attributes); + return; + } + if (!name.startsWith("ai.")) { + return; + } + processGenerateSpan(span, name, attributes); +} +function vercelAiEventProcessor(event) { + if (event.type === "transaction" && event.spans) { + const tokenAccumulator = /* @__PURE__ */ new Map(); + for (const span of event.spans) { + processEndedVercelAiSpan(span); + accumulateTokensForParent(span, tokenAccumulator); + } + for (const span of event.spans) { + if (span.op !== "gen_ai.invoke_agent") { + continue; + } + applyAccumulatedTokens(span, tokenAccumulator); + } + const trace2 = event.contexts?.trace; + if (trace2 && trace2.op === "gen_ai.invoke_agent") { + applyAccumulatedTokens(trace2, tokenAccumulator); + } + } + return event; +} +function processEndedVercelAiSpan(span) { + const { data: attributes, origin } = span; + if (origin !== "auto.vercelai.otel") { + return; + } + renameAttributeKey(attributes, AI_USAGE_COMPLETION_TOKENS_ATTRIBUTE, GEN_AI_USAGE_OUTPUT_TOKENS_ATTRIBUTE); + renameAttributeKey(attributes, AI_USAGE_PROMPT_TOKENS_ATTRIBUTE, GEN_AI_USAGE_INPUT_TOKENS_ATTRIBUTE); + renameAttributeKey(attributes, AI_USAGE_CACHED_INPUT_TOKENS_ATTRIBUTE, GEN_AI_USAGE_INPUT_TOKENS_CACHED_ATTRIBUTE); + if (typeof attributes[GEN_AI_USAGE_INPUT_TOKENS_ATTRIBUTE] === "number" && typeof attributes[GEN_AI_USAGE_INPUT_TOKENS_CACHED_ATTRIBUTE] === "number") { + attributes[GEN_AI_USAGE_INPUT_TOKENS_ATTRIBUTE] = attributes[GEN_AI_USAGE_INPUT_TOKENS_ATTRIBUTE] + attributes[GEN_AI_USAGE_INPUT_TOKENS_CACHED_ATTRIBUTE]; + } + if (typeof attributes[GEN_AI_USAGE_OUTPUT_TOKENS_ATTRIBUTE] === "number" && typeof attributes[GEN_AI_USAGE_INPUT_TOKENS_ATTRIBUTE] === "number") { + attributes["gen_ai.usage.total_tokens"] = attributes[GEN_AI_USAGE_OUTPUT_TOKENS_ATTRIBUTE] + attributes[GEN_AI_USAGE_INPUT_TOKENS_ATTRIBUTE]; + } + if (attributes[AI_PROMPT_TOOLS_ATTRIBUTE] && Array.isArray(attributes[AI_PROMPT_TOOLS_ATTRIBUTE])) { + attributes[AI_PROMPT_TOOLS_ATTRIBUTE] = convertAvailableToolsToJsonString( + attributes[AI_PROMPT_TOOLS_ATTRIBUTE] + ); + } + renameAttributeKey(attributes, OPERATION_NAME_ATTRIBUTE, GEN_AI_OPERATION_NAME_ATTRIBUTE); + renameAttributeKey(attributes, AI_PROMPT_MESSAGES_ATTRIBUTE, GEN_AI_REQUEST_MESSAGES_ATTRIBUTE); + renameAttributeKey(attributes, AI_RESPONSE_TEXT_ATTRIBUTE, "gen_ai.response.text"); + renameAttributeKey(attributes, AI_RESPONSE_TOOL_CALLS_ATTRIBUTE, "gen_ai.response.tool_calls"); + renameAttributeKey(attributes, AI_RESPONSE_OBJECT_ATTRIBUTE, "gen_ai.response.object"); + renameAttributeKey(attributes, AI_PROMPT_TOOLS_ATTRIBUTE, "gen_ai.request.available_tools"); + renameAttributeKey(attributes, AI_TOOL_CALL_ARGS_ATTRIBUTE, "gen_ai.tool.input"); + renameAttributeKey(attributes, AI_TOOL_CALL_RESULT_ATTRIBUTE, "gen_ai.tool.output"); + renameAttributeKey(attributes, AI_SCHEMA_ATTRIBUTE, "gen_ai.request.schema"); + renameAttributeKey(attributes, AI_MODEL_ID_ATTRIBUTE, GEN_AI_REQUEST_MODEL_ATTRIBUTE); + addProviderMetadataToAttributes(attributes); + for (const key of Object.keys(attributes)) { + if (key.startsWith("ai.")) { + renameAttributeKey(attributes, key, `vercel.${key}`); + } + } +} +function renameAttributeKey(attributes, oldKey, newKey) { + if (attributes[oldKey] != null) { + attributes[newKey] = attributes[oldKey]; + delete attributes[oldKey]; + } +} +function processToolCallSpan(span, attributes) { + addOriginToSpan$1(span, "auto.vercelai.otel"); + span.setAttribute(SEMANTIC_ATTRIBUTE_SENTRY_OP, "gen_ai.execute_tool"); + renameAttributeKey(attributes, AI_TOOL_CALL_NAME_ATTRIBUTE, "gen_ai.tool.name"); + renameAttributeKey(attributes, AI_TOOL_CALL_ID_ATTRIBUTE, "gen_ai.tool.call.id"); + const toolCallId = attributes["gen_ai.tool.call.id"]; + if (typeof toolCallId === "string") { + toolCallSpanMap.set(toolCallId, span); + } + if (!attributes["gen_ai.tool.type"]) { + span.setAttribute("gen_ai.tool.type", "function"); + } + const toolName = attributes["gen_ai.tool.name"]; + if (toolName) { + span.updateName(`execute_tool ${toolName}`); + } +} +function processGenerateSpan(span, name, attributes) { + addOriginToSpan$1(span, "auto.vercelai.otel"); + const nameWthoutAi = name.replace("ai.", ""); + span.setAttribute("ai.pipeline.name", nameWthoutAi); + span.updateName(nameWthoutAi); + const functionId = attributes[AI_TELEMETRY_FUNCTION_ID_ATTRIBUTE]; + if (functionId && typeof functionId === "string") { + span.updateName(`${nameWthoutAi} ${functionId}`); + span.setAttribute("gen_ai.function_id", functionId); + } + requestMessagesFromPrompt(span, attributes); + if (attributes[AI_MODEL_ID_ATTRIBUTE] && !attributes[GEN_AI_RESPONSE_MODEL_ATTRIBUTE]) { + span.setAttribute(GEN_AI_RESPONSE_MODEL_ATTRIBUTE, attributes[AI_MODEL_ID_ATTRIBUTE]); + } + span.setAttribute("ai.streaming", name.includes("stream")); + const op = getSpanOpFromName(name); + if (op) { + span.setAttribute(SEMANTIC_ATTRIBUTE_SENTRY_OP, op); + } + const modelId = attributes[AI_MODEL_ID_ATTRIBUTE]; + if (modelId) { + switch (name) { + case "ai.generateText.doGenerate": + span.updateName(`generate_text ${modelId}`); + break; + case "ai.streamText.doStream": + span.updateName(`stream_text ${modelId}`); + break; + case "ai.generateObject.doGenerate": + span.updateName(`generate_object ${modelId}`); + break; + case "ai.streamObject.doStream": + span.updateName(`stream_object ${modelId}`); + break; + case "ai.embed.doEmbed": + span.updateName(`embed ${modelId}`); + break; + case "ai.embedMany.doEmbed": + span.updateName(`embed_many ${modelId}`); + break; + } + } +} +function addVercelAiProcessors(client) { + client.on("spanStart", onVercelAiSpanStart); + client.addEventProcessor(Object.assign(vercelAiEventProcessor, { id: "VercelAiEventProcessor" })); +} +function addProviderMetadataToAttributes(attributes) { + const providerMetadata = attributes[AI_RESPONSE_PROVIDER_METADATA_ATTRIBUTE]; + if (providerMetadata) { + try { + const providerMetadataObject = JSON.parse(providerMetadata); + if (providerMetadataObject.openai) { + setAttributeIfDefined( + attributes, + GEN_AI_USAGE_INPUT_TOKENS_CACHED_ATTRIBUTE, + providerMetadataObject.openai.cachedPromptTokens + ); + setAttributeIfDefined( + attributes, + "gen_ai.usage.output_tokens.reasoning", + providerMetadataObject.openai.reasoningTokens + ); + setAttributeIfDefined( + attributes, + "gen_ai.usage.output_tokens.prediction_accepted", + providerMetadataObject.openai.acceptedPredictionTokens + ); + setAttributeIfDefined( + attributes, + "gen_ai.usage.output_tokens.prediction_rejected", + providerMetadataObject.openai.rejectedPredictionTokens + ); + setAttributeIfDefined(attributes, "gen_ai.conversation.id", providerMetadataObject.openai.responseId); + } + if (providerMetadataObject.anthropic) { + const cachedInputTokens = providerMetadataObject.anthropic.usage?.cache_read_input_tokens ?? providerMetadataObject.anthropic.cacheReadInputTokens; + setAttributeIfDefined(attributes, GEN_AI_USAGE_INPUT_TOKENS_CACHED_ATTRIBUTE, cachedInputTokens); + const cacheWriteInputTokens = providerMetadataObject.anthropic.usage?.cache_creation_input_tokens ?? providerMetadataObject.anthropic.cacheCreationInputTokens; + setAttributeIfDefined(attributes, GEN_AI_USAGE_INPUT_TOKENS_CACHE_WRITE_ATTRIBUTE, cacheWriteInputTokens); + } + if (providerMetadataObject.bedrock?.usage) { + setAttributeIfDefined( + attributes, + GEN_AI_USAGE_INPUT_TOKENS_CACHED_ATTRIBUTE, + providerMetadataObject.bedrock.usage.cacheReadInputTokens + ); + setAttributeIfDefined( + attributes, + GEN_AI_USAGE_INPUT_TOKENS_CACHE_WRITE_ATTRIBUTE, + providerMetadataObject.bedrock.usage.cacheWriteInputTokens + ); + } + if (providerMetadataObject.deepseek) { + setAttributeIfDefined( + attributes, + GEN_AI_USAGE_INPUT_TOKENS_CACHED_ATTRIBUTE, + providerMetadataObject.deepseek.promptCacheHitTokens + ); + setAttributeIfDefined( + attributes, + "gen_ai.usage.input_tokens.cache_miss", + providerMetadataObject.deepseek.promptCacheMissTokens + ); + } + } catch { + } + } +} +function setAttributeIfDefined(attributes, key, value) { + if (value != null) { + attributes[key] = value; + } +} +const OPENAI_INTEGRATION_NAME = "OpenAI"; +const INSTRUMENTED_METHODS$1 = ["responses.create", "chat.completions.create", "embeddings.create"]; +const RESPONSES_TOOL_CALL_EVENT_TYPES = [ + "response.output_item.added", + "response.function_call_arguments.delta", + "response.function_call_arguments.done", + "response.output_item.done" +]; +const RESPONSE_EVENT_TYPES = [ + "response.created", + "response.in_progress", + "response.failed", + "response.completed", + "response.incomplete", + "response.queued", + "response.output_text.delta", + ...RESPONSES_TOOL_CALL_EVENT_TYPES +]; +function getOperationName(methodPath) { + if (methodPath.includes("chat.completions")) { + return OPENAI_OPERATIONS.CHAT; + } + if (methodPath.includes("responses")) { + return OPENAI_OPERATIONS.RESPONSES; + } + if (methodPath.includes("embeddings")) { + return OPENAI_OPERATIONS.EMBEDDINGS; + } + return methodPath.split(".").pop() || "unknown"; +} +function getSpanOperation(methodPath) { + return `gen_ai.${getOperationName(methodPath)}`; +} +function shouldInstrument$2(methodPath) { + return INSTRUMENTED_METHODS$1.includes(methodPath); +} +function buildMethodPath(currentPath, prop) { + return currentPath ? `${currentPath}.${prop}` : prop; +} +function isChatCompletionResponse(response) { + return response !== null && typeof response === "object" && "object" in response && response.object === "chat.completion"; +} +function isResponsesApiResponse(response) { + return response !== null && typeof response === "object" && "object" in response && response.object === "response"; +} +function isEmbeddingsResponse(response) { + if (response === null || typeof response !== "object" || !("object" in response)) { + return false; + } + const responseObject = response; + return responseObject.object === "list" && typeof responseObject.model === "string" && responseObject.model.toLowerCase().includes("embedding"); +} +function isResponsesApiStreamEvent(event) { + return event !== null && typeof event === "object" && "type" in event && typeof event.type === "string" && event.type.startsWith("response."); +} +function isChatCompletionChunk(event) { + return event !== null && typeof event === "object" && "object" in event && event.object === "chat.completion.chunk"; +} +function addChatCompletionAttributes(span, response, recordOutputs) { + setCommonResponseAttributes(span, response.id, response.model, response.created); + if (response.usage) { + setTokenUsageAttributes( + span, + response.usage.prompt_tokens, + response.usage.completion_tokens, + response.usage.total_tokens + ); + } + if (Array.isArray(response.choices)) { + const finishReasons = response.choices.map((choice) => choice.finish_reason).filter((reason) => reason !== null); + if (finishReasons.length > 0) { + span.setAttributes({ + [GEN_AI_RESPONSE_FINISH_REASONS_ATTRIBUTE]: JSON.stringify(finishReasons) + }); + } + if (recordOutputs) { + const toolCalls = response.choices.map((choice) => choice.message?.tool_calls).filter((calls) => Array.isArray(calls) && calls.length > 0).flat(); + if (toolCalls.length > 0) { + span.setAttributes({ + [GEN_AI_RESPONSE_TOOL_CALLS_ATTRIBUTE]: JSON.stringify(toolCalls) + }); + } + } + } +} +function addResponsesApiAttributes(span, response, recordOutputs) { + setCommonResponseAttributes(span, response.id, response.model, response.created_at); + if (response.status) { + span.setAttributes({ + [GEN_AI_RESPONSE_FINISH_REASONS_ATTRIBUTE]: JSON.stringify([response.status]) + }); + } + if (response.usage) { + setTokenUsageAttributes( + span, + response.usage.input_tokens, + response.usage.output_tokens, + response.usage.total_tokens + ); + } + if (recordOutputs) { + const responseWithOutput = response; + if (Array.isArray(responseWithOutput.output) && responseWithOutput.output.length > 0) { + const functionCalls = responseWithOutput.output.filter( + (item) => typeof item === "object" && item !== null && item.type === "function_call" + ); + if (functionCalls.length > 0) { + span.setAttributes({ + [GEN_AI_RESPONSE_TOOL_CALLS_ATTRIBUTE]: JSON.stringify(functionCalls) + }); + } + } + } +} +function addEmbeddingsAttributes(span, response) { + span.setAttributes({ + [OPENAI_RESPONSE_MODEL_ATTRIBUTE]: response.model, + [GEN_AI_RESPONSE_MODEL_ATTRIBUTE]: response.model + }); + if (response.usage) { + setTokenUsageAttributes(span, response.usage.prompt_tokens, void 0, response.usage.total_tokens); + } +} +function setTokenUsageAttributes(span, promptTokens, completionTokens, totalTokens) { + if (promptTokens !== void 0) { + span.setAttributes({ + [OPENAI_USAGE_PROMPT_TOKENS_ATTRIBUTE]: promptTokens, + [GEN_AI_USAGE_INPUT_TOKENS_ATTRIBUTE]: promptTokens + }); + } + if (completionTokens !== void 0) { + span.setAttributes({ + [OPENAI_USAGE_COMPLETION_TOKENS_ATTRIBUTE]: completionTokens, + [GEN_AI_USAGE_OUTPUT_TOKENS_ATTRIBUTE]: completionTokens + }); + } + if (totalTokens !== void 0) { + span.setAttributes({ + [GEN_AI_USAGE_TOTAL_TOKENS_ATTRIBUTE]: totalTokens + }); + } +} +function setCommonResponseAttributes(span, id, model, timestamp) { + span.setAttributes({ + [OPENAI_RESPONSE_ID_ATTRIBUTE]: id, + [GEN_AI_RESPONSE_ID_ATTRIBUTE]: id + }); + span.setAttributes({ + [OPENAI_RESPONSE_MODEL_ATTRIBUTE]: model, + [GEN_AI_RESPONSE_MODEL_ATTRIBUTE]: model + }); + span.setAttributes({ + [OPENAI_RESPONSE_TIMESTAMP_ATTRIBUTE]: new Date(timestamp * 1e3).toISOString() + }); +} +function processChatCompletionToolCalls(toolCalls, state) { + for (const toolCall of toolCalls) { + const index = toolCall.index; + if (index === void 0 || !toolCall.function) continue; + if (!(index in state.chatCompletionToolCalls)) { + state.chatCompletionToolCalls[index] = { + ...toolCall, + function: { + name: toolCall.function.name, + arguments: toolCall.function.arguments || "" + } + }; + } else { + const existingToolCall = state.chatCompletionToolCalls[index]; + if (toolCall.function.arguments && existingToolCall?.function) { + existingToolCall.function.arguments += toolCall.function.arguments; + } + } + } +} +function processChatCompletionChunk(chunk, state, recordOutputs) { + state.responseId = chunk.id ?? state.responseId; + state.responseModel = chunk.model ?? state.responseModel; + state.responseTimestamp = chunk.created ?? state.responseTimestamp; + if (chunk.usage) { + state.promptTokens = chunk.usage.prompt_tokens; + state.completionTokens = chunk.usage.completion_tokens; + state.totalTokens = chunk.usage.total_tokens; + } + for (const choice of chunk.choices ?? []) { + if (recordOutputs) { + if (choice.delta?.content) { + state.responseTexts.push(choice.delta.content); + } + if (choice.delta?.tool_calls) { + processChatCompletionToolCalls(choice.delta.tool_calls, state); + } + } + if (choice.finish_reason) { + state.finishReasons.push(choice.finish_reason); + } + } +} +function processResponsesApiEvent(streamEvent, state, recordOutputs, span) { + if (!(streamEvent && typeof streamEvent === "object")) { + state.eventTypes.push("unknown:non-object"); + return; + } + if (streamEvent instanceof Error) { + span.setStatus({ code: SPAN_STATUS_ERROR, message: "internal_error" }); + captureException(streamEvent, { + mechanism: { + handled: false, + type: "auto.ai.openai.stream-response" + } + }); + return; + } + if (!("type" in streamEvent)) return; + const event = streamEvent; + if (!RESPONSE_EVENT_TYPES.includes(event.type)) { + state.eventTypes.push(event.type); + return; + } + if (recordOutputs) { + if (event.type === "response.output_item.done" && "item" in event) { + state.responsesApiToolCalls.push(event.item); + } + if (event.type === "response.output_text.delta" && "delta" in event && event.delta) { + state.responseTexts.push(event.delta); + return; + } + } + if ("response" in event) { + const { response } = event; + state.responseId = response.id ?? state.responseId; + state.responseModel = response.model ?? state.responseModel; + state.responseTimestamp = response.created_at ?? state.responseTimestamp; + if (response.usage) { + state.promptTokens = response.usage.input_tokens; + state.completionTokens = response.usage.output_tokens; + state.totalTokens = response.usage.total_tokens; + } + if (response.status) { + state.finishReasons.push(response.status); + } + if (recordOutputs && response.output_text) { + state.responseTexts.push(response.output_text); + } + } +} +async function* instrumentStream$1(stream, span, recordOutputs) { + const state = { + eventTypes: [], + responseTexts: [], + finishReasons: [], + responseId: "", + responseModel: "", + responseTimestamp: 0, + promptTokens: void 0, + completionTokens: void 0, + totalTokens: void 0, + chatCompletionToolCalls: {}, + responsesApiToolCalls: [] + }; + try { + for await (const event of stream) { + if (isChatCompletionChunk(event)) { + processChatCompletionChunk(event, state, recordOutputs); + } else if (isResponsesApiStreamEvent(event)) { + processResponsesApiEvent(event, state, recordOutputs, span); + } + yield event; + } + } finally { + setCommonResponseAttributes(span, state.responseId, state.responseModel, state.responseTimestamp); + setTokenUsageAttributes(span, state.promptTokens, state.completionTokens, state.totalTokens); + span.setAttributes({ + [GEN_AI_RESPONSE_STREAMING_ATTRIBUTE]: true + }); + if (state.finishReasons.length) { + span.setAttributes({ + [GEN_AI_RESPONSE_FINISH_REASONS_ATTRIBUTE]: JSON.stringify(state.finishReasons) + }); + } + if (recordOutputs && state.responseTexts.length) { + span.setAttributes({ + [GEN_AI_RESPONSE_TEXT_ATTRIBUTE]: state.responseTexts.join("") + }); + } + const chatCompletionToolCallsArray = Object.values(state.chatCompletionToolCalls); + const allToolCalls = [...chatCompletionToolCallsArray, ...state.responsesApiToolCalls]; + if (allToolCalls.length > 0) { + span.setAttributes({ + [GEN_AI_RESPONSE_TOOL_CALLS_ATTRIBUTE]: JSON.stringify(allToolCalls) + }); + } + span.end(); + } +} +function extractRequestAttributes$2(args, methodPath) { + const attributes = { + [GEN_AI_SYSTEM_ATTRIBUTE]: "openai", + [GEN_AI_OPERATION_NAME_ATTRIBUTE]: getOperationName(methodPath), + [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: "auto.ai.openai" + }; + if (args.length > 0 && typeof args[0] === "object" && args[0] !== null) { + const params = args[0]; + const tools = Array.isArray(params.tools) ? params.tools : []; + const hasWebSearchOptions = params.web_search_options && typeof params.web_search_options === "object"; + const webSearchOptions = hasWebSearchOptions ? [{ type: "web_search_options", ...params.web_search_options }] : []; + const availableTools = [...tools, ...webSearchOptions]; + if (availableTools.length > 0) { + attributes[GEN_AI_REQUEST_AVAILABLE_TOOLS_ATTRIBUTE] = JSON.stringify(availableTools); + } + } + if (args.length > 0 && typeof args[0] === "object" && args[0] !== null) { + const params = args[0]; + attributes[GEN_AI_REQUEST_MODEL_ATTRIBUTE] = params.model ?? "unknown"; + if ("temperature" in params) attributes[GEN_AI_REQUEST_TEMPERATURE_ATTRIBUTE] = params.temperature; + if ("top_p" in params) attributes[GEN_AI_REQUEST_TOP_P_ATTRIBUTE] = params.top_p; + if ("frequency_penalty" in params) + attributes[GEN_AI_REQUEST_FREQUENCY_PENALTY_ATTRIBUTE] = params.frequency_penalty; + if ("presence_penalty" in params) attributes[GEN_AI_REQUEST_PRESENCE_PENALTY_ATTRIBUTE] = params.presence_penalty; + if ("stream" in params) attributes[GEN_AI_REQUEST_STREAM_ATTRIBUTE] = params.stream; + if ("encoding_format" in params) attributes[GEN_AI_REQUEST_ENCODING_FORMAT_ATTRIBUTE] = params.encoding_format; + if ("dimensions" in params) attributes[GEN_AI_REQUEST_DIMENSIONS_ATTRIBUTE] = params.dimensions; + } else { + attributes[GEN_AI_REQUEST_MODEL_ATTRIBUTE] = "unknown"; + } + return attributes; +} +function addResponseAttributes$2(span, result, recordOutputs) { + if (!result || typeof result !== "object") return; + const response = result; + if (isChatCompletionResponse(response)) { + addChatCompletionAttributes(span, response, recordOutputs); + if (recordOutputs && response.choices?.length) { + const responseTexts = response.choices.map((choice) => choice.message?.content || ""); + span.setAttributes({ [GEN_AI_RESPONSE_TEXT_ATTRIBUTE]: JSON.stringify(responseTexts) }); + } + } else if (isResponsesApiResponse(response)) { + addResponsesApiAttributes(span, response, recordOutputs); + if (recordOutputs && response.output_text) { + span.setAttributes({ [GEN_AI_RESPONSE_TEXT_ATTRIBUTE]: response.output_text }); + } + } else if (isEmbeddingsResponse(response)) { + addEmbeddingsAttributes(span, response); + } +} +function addRequestAttributes(span, params) { + if ("messages" in params) { + const truncatedMessages = getTruncatedJsonString(params.messages); + span.setAttributes({ [GEN_AI_REQUEST_MESSAGES_ATTRIBUTE]: truncatedMessages }); + } + if ("input" in params) { + const truncatedInput = getTruncatedJsonString(params.input); + span.setAttributes({ [GEN_AI_REQUEST_MESSAGES_ATTRIBUTE]: truncatedInput }); + } +} +function instrumentMethod$2(originalMethod, methodPath, context2, options) { + return async function instrumentedMethod(...args) { + const requestAttributes = extractRequestAttributes$2(args, methodPath); + const model = requestAttributes[GEN_AI_REQUEST_MODEL_ATTRIBUTE] || "unknown"; + const operationName = getOperationName(methodPath); + const params = args[0]; + const isStreamRequested = params && typeof params === "object" && params.stream === true; + if (isStreamRequested) { + return startSpanManual$1( + { + name: `${operationName} ${model} stream-response`, + op: getSpanOperation(methodPath), + attributes: requestAttributes + }, + async (span) => { + try { + if (options.recordInputs && params) { + addRequestAttributes(span, params); + } + const result = await originalMethod.apply(context2, args); + return instrumentStream$1( + result, + span, + options.recordOutputs ?? false + ); + } catch (error2) { + span.setStatus({ code: SPAN_STATUS_ERROR, message: "internal_error" }); + captureException(error2, { + mechanism: { + handled: false, + type: "auto.ai.openai.stream", + data: { + function: methodPath + } + } + }); + span.end(); + throw error2; + } + } + ); + } else { + return startSpan$2( + { + name: `${operationName} ${model}`, + op: getSpanOperation(methodPath), + attributes: requestAttributes + }, + async (span) => { + try { + if (options.recordInputs && params) { + addRequestAttributes(span, params); + } + const result = await originalMethod.apply(context2, args); + addResponseAttributes$2(span, result, options.recordOutputs); + return result; + } catch (error2) { + captureException(error2, { + mechanism: { + handled: false, + type: "auto.ai.openai", + data: { + function: methodPath + } + } + }); + throw error2; + } + } + ); + } + }; +} +function createDeepProxy$2(target, currentPath = "", options) { + return new Proxy(target, { + get(obj, prop) { + const value = obj[prop]; + const methodPath = buildMethodPath(currentPath, String(prop)); + if (typeof value === "function" && shouldInstrument$2(methodPath)) { + return instrumentMethod$2(value, methodPath, obj, options); + } + if (typeof value === "function") { + return value.bind(obj); + } + if (value && typeof value === "object") { + return createDeepProxy$2(value, methodPath, options); + } + return value; + } + }); +} +function instrumentOpenAiClient(client, options) { + const sendDefaultPii = Boolean(getClient()?.getOptions().sendDefaultPii); + const _options = { + recordInputs: sendDefaultPii, + recordOutputs: sendDefaultPii, + ...options + }; + return createDeepProxy$2(client, "", _options); +} +function isErrorEvent(event, span) { + if ("type" in event && typeof event.type === "string") { + if (event.type === "error") { + span.setStatus({ code: SPAN_STATUS_ERROR, message: event.error?.type ?? "internal_error" }); + captureException(event.error, { + mechanism: { + handled: false, + type: "auto.ai.anthropic.anthropic_error" + } + }); + return true; + } + } + return false; +} +function handleMessageMetadata(event, state) { + if (event.type === "message_delta" && event.usage) { + if ("output_tokens" in event.usage && typeof event.usage.output_tokens === "number") { + state.completionTokens = event.usage.output_tokens; + } + } + if (event.message) { + const message = event.message; + if (message.id) state.responseId = message.id; + if (message.model) state.responseModel = message.model; + if (message.stop_reason) state.finishReasons.push(message.stop_reason); + if (message.usage) { + if (typeof message.usage.input_tokens === "number") state.promptTokens = message.usage.input_tokens; + if (typeof message.usage.cache_creation_input_tokens === "number") + state.cacheCreationInputTokens = message.usage.cache_creation_input_tokens; + if (typeof message.usage.cache_read_input_tokens === "number") + state.cacheReadInputTokens = message.usage.cache_read_input_tokens; + } + } +} +function handleContentBlockStart(event, state) { + if (event.type !== "content_block_start" || typeof event.index !== "number" || !event.content_block) return; + if (event.content_block.type === "tool_use" || event.content_block.type === "server_tool_use") { + state.activeToolBlocks[event.index] = { + id: event.content_block.id, + name: event.content_block.name, + inputJsonParts: [] + }; + } +} +function handleContentBlockDelta(event, state, recordOutputs) { + if (event.type !== "content_block_delta" || !event.delta) return; + if (typeof event.index === "number" && "partial_json" in event.delta && typeof event.delta.partial_json === "string") { + const active = state.activeToolBlocks[event.index]; + if (active) { + active.inputJsonParts.push(event.delta.partial_json); + } + } + if (recordOutputs && typeof event.delta.text === "string") { + state.responseTexts.push(event.delta.text); + } +} +function handleContentBlockStop(event, state) { + if (event.type !== "content_block_stop" || typeof event.index !== "number") return; + const active = state.activeToolBlocks[event.index]; + if (!active) return; + const raw = active.inputJsonParts.join(""); + let parsedInput; + try { + parsedInput = raw ? JSON.parse(raw) : {}; + } catch { + parsedInput = { __unparsed: raw }; + } + state.toolCalls.push({ + type: "tool_use", + id: active.id, + name: active.name, + input: parsedInput + }); + delete state.activeToolBlocks[event.index]; +} +function processEvent(event, state, recordOutputs, span) { + if (!(event && typeof event === "object")) { + return; + } + const isError2 = isErrorEvent(event, span); + if (isError2) return; + handleMessageMetadata(event, state); + handleContentBlockStart(event, state); + handleContentBlockDelta(event, state, recordOutputs); + handleContentBlockStop(event, state); +} +function finalizeStreamSpan(state, span, recordOutputs) { + if (!span.isRecording()) { + return; + } + if (state.responseId) { + span.setAttributes({ + [GEN_AI_RESPONSE_ID_ATTRIBUTE]: state.responseId + }); + } + if (state.responseModel) { + span.setAttributes({ + [GEN_AI_RESPONSE_MODEL_ATTRIBUTE]: state.responseModel + }); + } + setTokenUsageAttributes$1( + span, + state.promptTokens, + state.completionTokens, + state.cacheCreationInputTokens, + state.cacheReadInputTokens + ); + span.setAttributes({ + [GEN_AI_RESPONSE_STREAMING_ATTRIBUTE]: true + }); + if (state.finishReasons.length > 0) { + span.setAttributes({ + [GEN_AI_RESPONSE_FINISH_REASONS_ATTRIBUTE]: JSON.stringify(state.finishReasons) + }); + } + if (recordOutputs && state.responseTexts.length > 0) { + span.setAttributes({ + [GEN_AI_RESPONSE_TEXT_ATTRIBUTE]: state.responseTexts.join("") + }); + } + if (recordOutputs && state.toolCalls.length > 0) { + span.setAttributes({ + [GEN_AI_RESPONSE_TOOL_CALLS_ATTRIBUTE]: JSON.stringify(state.toolCalls) + }); + } + span.end(); +} +async function* instrumentAsyncIterableStream(stream, span, recordOutputs) { + const state = { + responseTexts: [], + finishReasons: [], + responseId: "", + responseModel: "", + promptTokens: void 0, + completionTokens: void 0, + cacheCreationInputTokens: void 0, + cacheReadInputTokens: void 0, + toolCalls: [], + activeToolBlocks: {} + }; + try { + for await (const event of stream) { + processEvent(event, state, recordOutputs, span); + yield event; + } + } finally { + if (state.responseId) { + span.setAttributes({ + [GEN_AI_RESPONSE_ID_ATTRIBUTE]: state.responseId + }); + } + if (state.responseModel) { + span.setAttributes({ + [GEN_AI_RESPONSE_MODEL_ATTRIBUTE]: state.responseModel + }); + } + setTokenUsageAttributes$1( + span, + state.promptTokens, + state.completionTokens, + state.cacheCreationInputTokens, + state.cacheReadInputTokens + ); + span.setAttributes({ + [GEN_AI_RESPONSE_STREAMING_ATTRIBUTE]: true + }); + if (state.finishReasons.length > 0) { + span.setAttributes({ + [GEN_AI_RESPONSE_FINISH_REASONS_ATTRIBUTE]: JSON.stringify(state.finishReasons) + }); + } + if (recordOutputs && state.responseTexts.length > 0) { + span.setAttributes({ + [GEN_AI_RESPONSE_TEXT_ATTRIBUTE]: state.responseTexts.join("") + }); + } + if (recordOutputs && state.toolCalls.length > 0) { + span.setAttributes({ + [GEN_AI_RESPONSE_TOOL_CALLS_ATTRIBUTE]: JSON.stringify(state.toolCalls) + }); + } + span.end(); + } +} +function instrumentMessageStream(stream, span, recordOutputs) { + const state = { + responseTexts: [], + finishReasons: [], + responseId: "", + responseModel: "", + promptTokens: void 0, + completionTokens: void 0, + cacheCreationInputTokens: void 0, + cacheReadInputTokens: void 0, + toolCalls: [], + activeToolBlocks: {} + }; + stream.on("streamEvent", (event) => { + processEvent(event, state, recordOutputs, span); + }); + stream.on("message", () => { + finalizeStreamSpan(state, span, recordOutputs); + }); + stream.on("error", (error2) => { + captureException(error2, { + mechanism: { + handled: false, + type: "auto.ai.anthropic.stream_error" + } + }); + if (span.isRecording()) { + span.setStatus({ code: SPAN_STATUS_ERROR, message: "stream_error" }); + span.end(); + } + }); + return stream; +} +const ANTHROPIC_AI_INTEGRATION_NAME = "Anthropic_AI"; +const ANTHROPIC_AI_INSTRUMENTED_METHODS = [ + "messages.create", + "messages.stream", + "messages.countTokens", + "models.get", + "completions.create", + "models.retrieve", + "beta.messages.create" +]; +function shouldInstrument$1(methodPath) { + return ANTHROPIC_AI_INSTRUMENTED_METHODS.includes(methodPath); +} +function handleResponseError(span, response) { + if (response.error) { + span.setStatus({ code: SPAN_STATUS_ERROR, message: response.error.type || "internal_error" }); + captureException(response.error, { + mechanism: { + handled: false, + type: "auto.ai.anthropic.anthropic_error" + } + }); + } +} +function messagesFromParams(params) { + const { system, messages } = params; + const systemMessages = typeof system === "string" ? [{ role: "system", content: params.system }] : []; + const userMessages = Array.isArray(messages) ? messages : messages != null ? [messages] : []; + return [...systemMessages, ...userMessages]; +} +function extractRequestAttributes$1(args, methodPath) { + const attributes = { + [GEN_AI_SYSTEM_ATTRIBUTE]: "anthropic", + [GEN_AI_OPERATION_NAME_ATTRIBUTE]: getFinalOperationName(methodPath), + [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: "auto.ai.anthropic" + }; + if (args.length > 0 && typeof args[0] === "object" && args[0] !== null) { + const params = args[0]; + if (params.tools && Array.isArray(params.tools)) { + attributes[GEN_AI_REQUEST_AVAILABLE_TOOLS_ATTRIBUTE] = JSON.stringify(params.tools); + } + attributes[GEN_AI_REQUEST_MODEL_ATTRIBUTE] = params.model ?? "unknown"; + if ("temperature" in params) attributes[GEN_AI_REQUEST_TEMPERATURE_ATTRIBUTE] = params.temperature; + if ("top_p" in params) attributes[GEN_AI_REQUEST_TOP_P_ATTRIBUTE] = params.top_p; + if ("stream" in params) attributes[GEN_AI_REQUEST_STREAM_ATTRIBUTE] = params.stream; + if ("top_k" in params) attributes[GEN_AI_REQUEST_TOP_K_ATTRIBUTE] = params.top_k; + if ("frequency_penalty" in params) + attributes[GEN_AI_REQUEST_FREQUENCY_PENALTY_ATTRIBUTE] = params.frequency_penalty; + if ("max_tokens" in params) attributes[GEN_AI_REQUEST_MAX_TOKENS_ATTRIBUTE] = params.max_tokens; + } else { + if (methodPath === "models.retrieve" || methodPath === "models.get") { + attributes[GEN_AI_REQUEST_MODEL_ATTRIBUTE] = args[0]; + } else { + attributes[GEN_AI_REQUEST_MODEL_ATTRIBUTE] = "unknown"; + } + } + return attributes; +} +function addPrivateRequestAttributes$1(span, params) { + const messages = messagesFromParams(params); + if (messages.length) { + const truncatedMessages = getTruncatedJsonString(messages); + span.setAttributes({ [GEN_AI_REQUEST_MESSAGES_ATTRIBUTE]: truncatedMessages }); + } + if ("input" in params) { + const truncatedInput = getTruncatedJsonString(params.input); + span.setAttributes({ [GEN_AI_REQUEST_MESSAGES_ATTRIBUTE]: truncatedInput }); + } + if ("prompt" in params) { + span.setAttributes({ [GEN_AI_PROMPT_ATTRIBUTE]: JSON.stringify(params.prompt) }); + } +} +function addContentAttributes(span, response) { + if ("content" in response) { + if (Array.isArray(response.content)) { + span.setAttributes({ + [GEN_AI_RESPONSE_TEXT_ATTRIBUTE]: response.content.map((item) => item.text).filter((text) => !!text).join("") + }); + const toolCalls = []; + for (const item of response.content) { + if (item.type === "tool_use" || item.type === "server_tool_use") { + toolCalls.push(item); + } + } + if (toolCalls.length > 0) { + span.setAttributes({ [GEN_AI_RESPONSE_TOOL_CALLS_ATTRIBUTE]: JSON.stringify(toolCalls) }); + } + } + } + if ("completion" in response) { + span.setAttributes({ [GEN_AI_RESPONSE_TEXT_ATTRIBUTE]: response.completion }); + } + if ("input_tokens" in response) { + span.setAttributes({ [GEN_AI_RESPONSE_TEXT_ATTRIBUTE]: JSON.stringify(response.input_tokens) }); + } +} +function addMetadataAttributes(span, response) { + if ("id" in response && "model" in response) { + span.setAttributes({ + [GEN_AI_RESPONSE_ID_ATTRIBUTE]: response.id, + [GEN_AI_RESPONSE_MODEL_ATTRIBUTE]: response.model + }); + if ("created" in response && typeof response.created === "number") { + span.setAttributes({ + [ANTHROPIC_AI_RESPONSE_TIMESTAMP_ATTRIBUTE]: new Date(response.created * 1e3).toISOString() + }); + } + if ("created_at" in response && typeof response.created_at === "number") { + span.setAttributes({ + [ANTHROPIC_AI_RESPONSE_TIMESTAMP_ATTRIBUTE]: new Date(response.created_at * 1e3).toISOString() + }); + } + if ("usage" in response && response.usage) { + setTokenUsageAttributes$1( + span, + response.usage.input_tokens, + response.usage.output_tokens, + response.usage.cache_creation_input_tokens, + response.usage.cache_read_input_tokens + ); + } + } +} +function addResponseAttributes$1(span, response, recordOutputs) { + if (!response || typeof response !== "object") return; + if ("type" in response && response.type === "error") { + handleResponseError(span, response); + return; + } + if (recordOutputs) { + addContentAttributes(span, response); + } + addMetadataAttributes(span, response); +} +function handleStreamingError(error2, span, methodPath) { + captureException(error2, { + mechanism: { handled: false, type: "auto.ai.anthropic", data: { function: methodPath } } + }); + if (span.isRecording()) { + span.setStatus({ code: SPAN_STATUS_ERROR, message: "internal_error" }); + span.end(); + } + throw error2; +} +function handleStreamingRequest(originalMethod, target, context2, args, requestAttributes, operationName, methodPath, params, options, isStreamRequested, isStreamingMethod2) { + const model = requestAttributes[GEN_AI_REQUEST_MODEL_ATTRIBUTE] ?? "unknown"; + const spanConfig = { + name: `${operationName} ${model} stream-response`, + op: getSpanOperation$1(methodPath), + attributes: requestAttributes + }; + if (isStreamRequested && !isStreamingMethod2) { + return startSpanManual$1(spanConfig, async (span) => { + try { + if (options.recordInputs && params) { + addPrivateRequestAttributes$1(span, params); + } + const result = await originalMethod.apply(context2, args); + return instrumentAsyncIterableStream( + result, + span, + options.recordOutputs ?? false + ); + } catch (error2) { + return handleStreamingError(error2, span, methodPath); + } + }); + } else { + return startSpanManual$1(spanConfig, (span) => { + try { + if (options.recordInputs && params) { + addPrivateRequestAttributes$1(span, params); + } + const messageStream = target.apply(context2, args); + return instrumentMessageStream(messageStream, span, options.recordOutputs ?? false); + } catch (error2) { + return handleStreamingError(error2, span, methodPath); + } + }); + } +} +function instrumentMethod$1(originalMethod, methodPath, context2, options) { + return new Proxy(originalMethod, { + apply(target, thisArg, args) { + const requestAttributes = extractRequestAttributes$1(args, methodPath); + const model = requestAttributes[GEN_AI_REQUEST_MODEL_ATTRIBUTE] ?? "unknown"; + const operationName = getFinalOperationName(methodPath); + const params = typeof args[0] === "object" ? args[0] : void 0; + const isStreamRequested = Boolean(params?.stream); + const isStreamingMethod2 = methodPath === "messages.stream"; + if (isStreamRequested || isStreamingMethod2) { + return handleStreamingRequest( + originalMethod, + target, + context2, + args, + requestAttributes, + operationName, + methodPath, + params, + options, + isStreamRequested, + isStreamingMethod2 + ); + } + return startSpan$2( + { + name: `${operationName} ${model}`, + op: getSpanOperation$1(methodPath), + attributes: requestAttributes + }, + (span) => { + if (options.recordInputs && params) { + addPrivateRequestAttributes$1(span, params); + } + return handleCallbackErrors( + () => target.apply(context2, args), + (error2) => { + captureException(error2, { + mechanism: { + handled: false, + type: "auto.ai.anthropic", + data: { + function: methodPath + } + } + }); + }, + () => { + }, + (result) => addResponseAttributes$1(span, result, options.recordOutputs) + ); + } + ); + } + }); +} +function createDeepProxy$1(target, currentPath = "", options) { + return new Proxy(target, { + get(obj, prop) { + const value = obj[prop]; + const methodPath = buildMethodPath$1(currentPath, String(prop)); + if (typeof value === "function" && shouldInstrument$1(methodPath)) { + return instrumentMethod$1(value, methodPath, obj, options); + } + if (typeof value === "function") { + return value.bind(obj); + } + if (value && typeof value === "object") { + return createDeepProxy$1(value, methodPath, options); + } + return value; + } + }); +} +function instrumentAnthropicAiClient(anthropicAiClient, options) { + const sendDefaultPii = Boolean(getClient()?.getOptions().sendDefaultPii); + const _options = { + recordInputs: sendDefaultPii, + recordOutputs: sendDefaultPii, + ...options + }; + return createDeepProxy$1(anthropicAiClient, "", _options); +} +const GOOGLE_GENAI_INTEGRATION_NAME = "Google_GenAI"; +const GOOGLE_GENAI_INSTRUMENTED_METHODS = [ + "models.generateContent", + "models.generateContentStream", + "chats.create", + "sendMessage", + "sendMessageStream" +]; +const GOOGLE_GENAI_SYSTEM_NAME = "google_genai"; +const CHATS_CREATE_METHOD = "chats.create"; +const CHAT_PATH = "chat"; +function isErrorChunk(chunk, span) { + const feedback = chunk?.promptFeedback; + if (feedback?.blockReason) { + const message = feedback.blockReasonMessage ?? feedback.blockReason; + span.setStatus({ code: SPAN_STATUS_ERROR, message: `Content blocked: ${message}` }); + captureException(`Content blocked: ${message}`, { + mechanism: { handled: false, type: "auto.ai.google_genai" } + }); + return true; + } + return false; +} +function handleResponseMetadata(chunk, state) { + if (typeof chunk.responseId === "string") state.responseId = chunk.responseId; + if (typeof chunk.modelVersion === "string") state.responseModel = chunk.modelVersion; + const usage = chunk.usageMetadata; + if (usage) { + if (typeof usage.promptTokenCount === "number") state.promptTokens = usage.promptTokenCount; + if (typeof usage.candidatesTokenCount === "number") state.completionTokens = usage.candidatesTokenCount; + if (typeof usage.totalTokenCount === "number") state.totalTokens = usage.totalTokenCount; + } +} +function handleCandidateContent(chunk, state, recordOutputs) { + if (Array.isArray(chunk.functionCalls)) { + state.toolCalls.push(...chunk.functionCalls); + } + for (const candidate of chunk.candidates ?? []) { + if (candidate?.finishReason && !state.finishReasons.includes(candidate.finishReason)) { + state.finishReasons.push(candidate.finishReason); + } + for (const part of candidate?.content?.parts ?? []) { + if (recordOutputs && part.text) state.responseTexts.push(part.text); + if (part.functionCall) { + state.toolCalls.push({ + type: "function", + id: part.functionCall.id, + name: part.functionCall.name, + arguments: part.functionCall.args + }); + } + } + } +} +function processChunk(chunk, state, recordOutputs, span) { + if (!chunk || isErrorChunk(chunk, span)) return; + handleResponseMetadata(chunk, state); + handleCandidateContent(chunk, state, recordOutputs); +} +async function* instrumentStream(stream, span, recordOutputs) { + const state = { + responseTexts: [], + finishReasons: [], + toolCalls: [] + }; + try { + for await (const chunk of stream) { + processChunk(chunk, state, recordOutputs, span); + yield chunk; + } + } finally { + const attrs = { + [GEN_AI_RESPONSE_STREAMING_ATTRIBUTE]: true + }; + if (state.responseId) attrs[GEN_AI_RESPONSE_ID_ATTRIBUTE] = state.responseId; + if (state.responseModel) attrs[GEN_AI_RESPONSE_MODEL_ATTRIBUTE] = state.responseModel; + if (state.promptTokens !== void 0) attrs[GEN_AI_USAGE_INPUT_TOKENS_ATTRIBUTE] = state.promptTokens; + if (state.completionTokens !== void 0) attrs[GEN_AI_USAGE_OUTPUT_TOKENS_ATTRIBUTE] = state.completionTokens; + if (state.totalTokens !== void 0) attrs[GEN_AI_USAGE_TOTAL_TOKENS_ATTRIBUTE] = state.totalTokens; + if (state.finishReasons.length) { + attrs[GEN_AI_RESPONSE_FINISH_REASONS_ATTRIBUTE] = JSON.stringify(state.finishReasons); + } + if (recordOutputs && state.responseTexts.length) { + attrs[GEN_AI_RESPONSE_TEXT_ATTRIBUTE] = state.responseTexts.join(""); + } + if (recordOutputs && state.toolCalls.length) { + attrs[GEN_AI_RESPONSE_TOOL_CALLS_ATTRIBUTE] = JSON.stringify(state.toolCalls); + } + span.setAttributes(attrs); + span.end(); + } +} +function shouldInstrument(methodPath) { + if (GOOGLE_GENAI_INSTRUMENTED_METHODS.includes(methodPath)) { + return true; + } + const methodName = methodPath.split(".").pop(); + return GOOGLE_GENAI_INSTRUMENTED_METHODS.includes(methodName); +} +function isStreamingMethod(methodPath) { + return methodPath.includes("Stream"); +} +function contentUnionToMessages(content, role = "user") { + if (typeof content === "string") { + return [{ role, content }]; + } + if (Array.isArray(content)) { + return content.flatMap((content2) => contentUnionToMessages(content2, role)); + } + if (typeof content !== "object" || !content) return []; + if ("role" in content && typeof content.role === "string") { + return [content]; + } + if ("parts" in content) { + return [{ ...content, role }]; + } + return [{ role, content }]; +} +function extractModel(params, context2) { + if ("model" in params && typeof params.model === "string") { + return params.model; + } + if (context2 && typeof context2 === "object") { + const contextObj = context2; + if ("model" in contextObj && typeof contextObj.model === "string") { + return contextObj.model; + } + if ("modelVersion" in contextObj && typeof contextObj.modelVersion === "string") { + return contextObj.modelVersion; + } + } + return "unknown"; +} +function extractConfigAttributes(config2) { + const attributes = {}; + if ("temperature" in config2 && typeof config2.temperature === "number") { + attributes[GEN_AI_REQUEST_TEMPERATURE_ATTRIBUTE] = config2.temperature; + } + if ("topP" in config2 && typeof config2.topP === "number") { + attributes[GEN_AI_REQUEST_TOP_P_ATTRIBUTE] = config2.topP; + } + if ("topK" in config2 && typeof config2.topK === "number") { + attributes[GEN_AI_REQUEST_TOP_K_ATTRIBUTE] = config2.topK; + } + if ("maxOutputTokens" in config2 && typeof config2.maxOutputTokens === "number") { + attributes[GEN_AI_REQUEST_MAX_TOKENS_ATTRIBUTE] = config2.maxOutputTokens; + } + if ("frequencyPenalty" in config2 && typeof config2.frequencyPenalty === "number") { + attributes[GEN_AI_REQUEST_FREQUENCY_PENALTY_ATTRIBUTE] = config2.frequencyPenalty; + } + if ("presencePenalty" in config2 && typeof config2.presencePenalty === "number") { + attributes[GEN_AI_REQUEST_PRESENCE_PENALTY_ATTRIBUTE] = config2.presencePenalty; + } + return attributes; +} +function extractRequestAttributes(methodPath, params, context2) { + const attributes = { + [GEN_AI_SYSTEM_ATTRIBUTE]: GOOGLE_GENAI_SYSTEM_NAME, + [GEN_AI_OPERATION_NAME_ATTRIBUTE]: getFinalOperationName(methodPath), + [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: "auto.ai.google_genai" + }; + if (params) { + attributes[GEN_AI_REQUEST_MODEL_ATTRIBUTE] = extractModel(params, context2); + if ("config" in params && typeof params.config === "object" && params.config) { + const config2 = params.config; + Object.assign(attributes, extractConfigAttributes(config2)); + if ("tools" in config2 && Array.isArray(config2.tools)) { + const functionDeclarations = config2.tools.flatMap( + (tool) => tool.functionDeclarations + ); + attributes[GEN_AI_REQUEST_AVAILABLE_TOOLS_ATTRIBUTE] = JSON.stringify(functionDeclarations); + } + } + } else { + attributes[GEN_AI_REQUEST_MODEL_ATTRIBUTE] = extractModel({}, context2); + } + return attributes; +} +function addPrivateRequestAttributes(span, params) { + const messages = []; + if ("config" in params && params.config && typeof params.config === "object" && "systemInstruction" in params.config && params.config.systemInstruction) { + messages.push(...contentUnionToMessages(params.config.systemInstruction, "system")); + } + if ("history" in params) { + messages.push(...contentUnionToMessages(params.history, "user")); + } + if ("contents" in params) { + messages.push(...contentUnionToMessages(params.contents, "user")); + } + if ("message" in params) { + messages.push(...contentUnionToMessages(params.message, "user")); + } + if (messages.length) { + span.setAttributes({ + [GEN_AI_REQUEST_MESSAGES_ATTRIBUTE]: JSON.stringify(truncateGenAiMessages(messages)) + }); + } +} +function addResponseAttributes(span, response, recordOutputs) { + if (!response || typeof response !== "object") return; + if (response.modelVersion) { + span.setAttribute(GEN_AI_RESPONSE_MODEL_ATTRIBUTE, response.modelVersion); + } + if (response.usageMetadata && typeof response.usageMetadata === "object") { + const usage = response.usageMetadata; + if (typeof usage.promptTokenCount === "number") { + span.setAttributes({ + [GEN_AI_USAGE_INPUT_TOKENS_ATTRIBUTE]: usage.promptTokenCount + }); + } + if (typeof usage.candidatesTokenCount === "number") { + span.setAttributes({ + [GEN_AI_USAGE_OUTPUT_TOKENS_ATTRIBUTE]: usage.candidatesTokenCount + }); + } + if (typeof usage.totalTokenCount === "number") { + span.setAttributes({ + [GEN_AI_USAGE_TOTAL_TOKENS_ATTRIBUTE]: usage.totalTokenCount + }); + } + } + if (recordOutputs && Array.isArray(response.candidates) && response.candidates.length > 0) { + const responseTexts = response.candidates.map((candidate) => { + if (candidate.content?.parts && Array.isArray(candidate.content.parts)) { + return candidate.content.parts.map((part) => typeof part.text === "string" ? part.text : "").filter((text) => text.length > 0).join(""); + } + return ""; + }).filter((text) => text.length > 0); + if (responseTexts.length > 0) { + span.setAttributes({ + [GEN_AI_RESPONSE_TEXT_ATTRIBUTE]: responseTexts.join("") + }); + } + } + if (recordOutputs && response.functionCalls) { + const functionCalls = response.functionCalls; + if (Array.isArray(functionCalls) && functionCalls.length > 0) { + span.setAttributes({ + [GEN_AI_RESPONSE_TOOL_CALLS_ATTRIBUTE]: JSON.stringify(functionCalls) + }); + } + } +} +function instrumentMethod(originalMethod, methodPath, context2, options) { + const isSyncCreate = methodPath === CHATS_CREATE_METHOD; + return new Proxy(originalMethod, { + apply(target, _, args) { + const params = args[0]; + const requestAttributes = extractRequestAttributes(methodPath, params, context2); + const model = requestAttributes[GEN_AI_REQUEST_MODEL_ATTRIBUTE] ?? "unknown"; + const operationName = getFinalOperationName(methodPath); + if (isStreamingMethod(methodPath)) { + return startSpanManual$1( + { + name: `${operationName} ${model} stream-response`, + op: getSpanOperation$1(methodPath), + attributes: requestAttributes + }, + async (span) => { + try { + if (options.recordInputs && params) { + addPrivateRequestAttributes(span, params); + } + const stream = await target.apply(context2, args); + return instrumentStream(stream, span, Boolean(options.recordOutputs)); + } catch (error2) { + span.setStatus({ code: SPAN_STATUS_ERROR, message: "internal_error" }); + captureException(error2, { + mechanism: { + handled: false, + type: "auto.ai.google_genai", + data: { function: methodPath } + } + }); + span.end(); + throw error2; + } + } + ); + } + return startSpan$2( + { + name: isSyncCreate ? `${operationName} ${model} create` : `${operationName} ${model}`, + op: getSpanOperation$1(methodPath), + attributes: requestAttributes + }, + (span) => { + if (options.recordInputs && params) { + addPrivateRequestAttributes(span, params); + } + return handleCallbackErrors( + () => target.apply(context2, args), + (error2) => { + captureException(error2, { + mechanism: { handled: false, type: "auto.ai.google_genai", data: { function: methodPath } } + }); + }, + () => { + }, + (result) => { + if (!isSyncCreate) { + addResponseAttributes(span, result, options.recordOutputs); + } + } + ); + } + ); + } + }); +} +function createDeepProxy(target, currentPath = "", options) { + return new Proxy(target, { + get: (t, prop, receiver) => { + const value = Reflect.get(t, prop, receiver); + const methodPath = buildMethodPath$1(currentPath, String(prop)); + if (typeof value === "function" && shouldInstrument(methodPath)) { + if (methodPath === CHATS_CREATE_METHOD) { + const instrumentedMethod = instrumentMethod(value, methodPath, t, options); + return function instrumentedAndProxiedCreate(...args) { + const result = instrumentedMethod(...args); + if (result && typeof result === "object") { + return createDeepProxy(result, CHAT_PATH, options); + } + return result; + }; + } + return instrumentMethod(value, methodPath, t, options); + } + if (typeof value === "function") { + return value.bind(t); + } + if (value && typeof value === "object") { + return createDeepProxy(value, methodPath, options); + } + return value; + } + }); +} +function instrumentGoogleGenAIClient(client, options) { + const sendDefaultPii = Boolean(getClient()?.getOptions().sendDefaultPii); + const _options = { + recordInputs: sendDefaultPii, + recordOutputs: sendDefaultPii, + ...options + }; + return createDeepProxy(client, "", _options); +} +const LANGCHAIN_INTEGRATION_NAME = "LangChain"; +const LANGCHAIN_ORIGIN = "auto.ai.langchain"; +const ROLE_MAP = { + human: "user", + ai: "assistant", + assistant: "assistant", + system: "system", + function: "function", + tool: "tool" +}; +const setIfDefined = (target, key, value) => { + if (value != null) target[key] = value; +}; +const setNumberIfDefined = (target, key, value) => { + const n = Number(value); + if (!Number.isNaN(n)) target[key] = n; +}; +function asString(v) { + if (typeof v === "string") return v; + try { + return JSON.stringify(v); + } catch { + return String(v); + } +} +function normalizeMessageRole(role) { + const normalized = role.toLowerCase(); + return ROLE_MAP[normalized] ?? normalized; +} +function normalizeRoleNameFromCtor(name) { + if (name.includes("System")) return "system"; + if (name.includes("Human")) return "user"; + if (name.includes("AI") || name.includes("Assistant")) return "assistant"; + if (name.includes("Function")) return "function"; + if (name.includes("Tool")) return "tool"; + return "user"; +} +function getInvocationParams(tags) { + if (!tags || Array.isArray(tags)) return void 0; + return tags.invocation_params; +} +function normalizeLangChainMessages(messages) { + return messages.map((message) => { + const maybeGetType = message._getType; + if (typeof maybeGetType === "function") { + const messageType = maybeGetType.call(message); + return { + role: normalizeMessageRole(messageType), + content: asString(message.content) + }; + } + const ctor = message.constructor?.name; + if (ctor) { + return { + role: normalizeMessageRole(normalizeRoleNameFromCtor(ctor)), + content: asString(message.content) + }; + } + if (message.type) { + const role = String(message.type).toLowerCase(); + return { + role: normalizeMessageRole(role), + content: asString(message.content) + }; + } + if (message.role) { + return { + role: normalizeMessageRole(String(message.role)), + content: asString(message.content) + }; + } + if (message.lc === 1 && message.kwargs) { + const id = message.id; + const messageType = Array.isArray(id) && id.length > 0 ? id[id.length - 1] : ""; + const role = typeof messageType === "string" ? normalizeRoleNameFromCtor(messageType) : "user"; + return { + role: normalizeMessageRole(role), + content: asString(message.kwargs?.content) + }; + } + return { + role: "user", + content: asString(message.content) + }; + }); +} +function extractCommonRequestAttributes(serialized, invocationParams, langSmithMetadata) { + const attrs = {}; + const kwargs = "kwargs" in serialized ? serialized.kwargs : void 0; + const temperature = invocationParams?.temperature ?? langSmithMetadata?.ls_temperature ?? kwargs?.temperature; + setNumberIfDefined(attrs, GEN_AI_REQUEST_TEMPERATURE_ATTRIBUTE, temperature); + const maxTokens = invocationParams?.max_tokens ?? langSmithMetadata?.ls_max_tokens ?? kwargs?.max_tokens; + setNumberIfDefined(attrs, GEN_AI_REQUEST_MAX_TOKENS_ATTRIBUTE, maxTokens); + const topP = invocationParams?.top_p ?? kwargs?.top_p; + setNumberIfDefined(attrs, GEN_AI_REQUEST_TOP_P_ATTRIBUTE, topP); + const frequencyPenalty = invocationParams?.frequency_penalty; + setNumberIfDefined(attrs, GEN_AI_REQUEST_FREQUENCY_PENALTY_ATTRIBUTE, frequencyPenalty); + const presencePenalty = invocationParams?.presence_penalty; + setNumberIfDefined(attrs, GEN_AI_REQUEST_PRESENCE_PENALTY_ATTRIBUTE, presencePenalty); + if (invocationParams && "stream" in invocationParams) { + setIfDefined(attrs, GEN_AI_REQUEST_STREAM_ATTRIBUTE, Boolean(invocationParams.stream)); + } + return attrs; +} +function baseRequestAttributes(system, modelName, operation, serialized, invocationParams, langSmithMetadata) { + return { + [GEN_AI_SYSTEM_ATTRIBUTE]: asString(system ?? "langchain"), + [GEN_AI_OPERATION_NAME_ATTRIBUTE]: operation, + [GEN_AI_REQUEST_MODEL_ATTRIBUTE]: asString(modelName), + [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: LANGCHAIN_ORIGIN, + ...extractCommonRequestAttributes(serialized, invocationParams, langSmithMetadata) + }; +} +function extractLLMRequestAttributes(llm, prompts, recordInputs, invocationParams, langSmithMetadata) { + const system = langSmithMetadata?.ls_provider; + const modelName = invocationParams?.model ?? langSmithMetadata?.ls_model_name ?? "unknown"; + const attrs = baseRequestAttributes(system, modelName, "pipeline", llm, invocationParams, langSmithMetadata); + if (recordInputs && Array.isArray(prompts) && prompts.length > 0) { + const messages = prompts.map((p) => ({ role: "user", content: p })); + setIfDefined(attrs, GEN_AI_REQUEST_MESSAGES_ATTRIBUTE, asString(messages)); + } + return attrs; +} +function extractChatModelRequestAttributes(llm, langChainMessages, recordInputs, invocationParams, langSmithMetadata) { + const system = langSmithMetadata?.ls_provider ?? llm.id?.[2]; + const modelName = invocationParams?.model ?? langSmithMetadata?.ls_model_name ?? "unknown"; + const attrs = baseRequestAttributes(system, modelName, "chat", llm, invocationParams, langSmithMetadata); + if (recordInputs && Array.isArray(langChainMessages) && langChainMessages.length > 0) { + const normalized = normalizeLangChainMessages(langChainMessages.flat()); + const truncated = truncateGenAiMessages(normalized); + setIfDefined(attrs, GEN_AI_REQUEST_MESSAGES_ATTRIBUTE, asString(truncated)); + } + return attrs; +} +function addToolCallsAttributes(generations, attrs) { + const toolCalls = []; + const flatGenerations = generations.flat(); + for (const gen of flatGenerations) { + const content = gen.message?.content; + if (Array.isArray(content)) { + for (const item of content) { + const t = item; + if (t.type === "tool_use") toolCalls.push(t); + } + } + } + if (toolCalls.length > 0) { + setIfDefined(attrs, GEN_AI_RESPONSE_TOOL_CALLS_ATTRIBUTE, asString(toolCalls)); + } +} +function addTokenUsageAttributes(llmOutput, attrs) { + if (!llmOutput) return; + const tokenUsage = llmOutput.tokenUsage; + const anthropicUsage = llmOutput.usage; + if (tokenUsage) { + setNumberIfDefined(attrs, GEN_AI_USAGE_INPUT_TOKENS_ATTRIBUTE, tokenUsage.promptTokens); + setNumberIfDefined(attrs, GEN_AI_USAGE_OUTPUT_TOKENS_ATTRIBUTE, tokenUsage.completionTokens); + setNumberIfDefined(attrs, GEN_AI_USAGE_TOTAL_TOKENS_ATTRIBUTE, tokenUsage.totalTokens); + } else if (anthropicUsage) { + setNumberIfDefined(attrs, GEN_AI_USAGE_INPUT_TOKENS_ATTRIBUTE, anthropicUsage.input_tokens); + setNumberIfDefined(attrs, GEN_AI_USAGE_OUTPUT_TOKENS_ATTRIBUTE, anthropicUsage.output_tokens); + const input = Number(anthropicUsage.input_tokens); + const output = Number(anthropicUsage.output_tokens); + const total = (Number.isNaN(input) ? 0 : input) + (Number.isNaN(output) ? 0 : output); + if (total > 0) setNumberIfDefined(attrs, GEN_AI_USAGE_TOTAL_TOKENS_ATTRIBUTE, total); + if (anthropicUsage.cache_creation_input_tokens !== void 0) + setNumberIfDefined( + attrs, + GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS_ATTRIBUTE, + anthropicUsage.cache_creation_input_tokens + ); + if (anthropicUsage.cache_read_input_tokens !== void 0) + setNumberIfDefined(attrs, GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS_ATTRIBUTE, anthropicUsage.cache_read_input_tokens); + } +} +function extractLlmResponseAttributes(llmResult, recordOutputs) { + if (!llmResult) return; + const attrs = {}; + if (Array.isArray(llmResult.generations)) { + const finishReasons = llmResult.generations.flat().map((g) => { + if (g.generationInfo?.finish_reason) { + return g.generationInfo.finish_reason; + } + if (g.generation_info?.finish_reason) { + return g.generation_info.finish_reason; + } + return null; + }).filter((r) => typeof r === "string"); + if (finishReasons.length > 0) { + setIfDefined(attrs, GEN_AI_RESPONSE_FINISH_REASONS_ATTRIBUTE, asString(finishReasons)); + } + addToolCallsAttributes(llmResult.generations, attrs); + if (recordOutputs) { + const texts = llmResult.generations.flat().map((gen) => gen.text ?? gen.message?.content).filter((t) => typeof t === "string"); + if (texts.length > 0) { + setIfDefined(attrs, GEN_AI_RESPONSE_TEXT_ATTRIBUTE, asString(texts)); + } + } + } + addTokenUsageAttributes(llmResult.llmOutput, attrs); + const llmOutput = llmResult.llmOutput; + const firstGeneration = llmResult.generations?.[0]?.[0]; + const v1Message = firstGeneration?.message; + const modelName = llmOutput?.model_name ?? llmOutput?.model ?? v1Message?.response_metadata?.model_name; + if (modelName) setIfDefined(attrs, GEN_AI_RESPONSE_MODEL_ATTRIBUTE, modelName); + const responseId = llmOutput?.id ?? v1Message?.id; + if (responseId) { + setIfDefined(attrs, GEN_AI_RESPONSE_ID_ATTRIBUTE, responseId); + } + const stopReason = llmOutput?.stop_reason ?? v1Message?.response_metadata?.finish_reason; + if (stopReason) { + setIfDefined(attrs, GEN_AI_RESPONSE_STOP_REASON_ATTRIBUTE, asString(stopReason)); + } + return attrs; +} +function createLangChainCallbackHandler(options = {}) { + const recordInputs = options.recordInputs ?? false; + const recordOutputs = options.recordOutputs ?? false; + const spanMap = /* @__PURE__ */ new Map(); + const exitSpan = (runId) => { + const span = spanMap.get(runId); + if (span?.isRecording()) { + span.end(); + spanMap.delete(runId); + } + }; + const handler = { + // Required LangChain BaseCallbackHandler properties + lc_serializable: false, + lc_namespace: ["langchain_core", "callbacks", "sentry"], + lc_secrets: void 0, + lc_attributes: void 0, + lc_aliases: void 0, + lc_serializable_keys: void 0, + lc_id: ["langchain_core", "callbacks", "sentry"], + lc_kwargs: {}, + name: "SentryCallbackHandler", + // BaseCallbackHandlerInput boolean flags + ignoreLLM: false, + ignoreChain: false, + ignoreAgent: false, + ignoreRetriever: false, + ignoreCustomEvent: false, + raiseError: false, + awaitHandlers: true, + handleLLMStart(llm, prompts, runId, _parentRunId, _extraParams, tags, metadata, _runName) { + const invocationParams = getInvocationParams(tags); + const attributes = extractLLMRequestAttributes( + llm, + prompts, + recordInputs, + invocationParams, + metadata + ); + const modelName = attributes[GEN_AI_REQUEST_MODEL_ATTRIBUTE]; + const operationName = attributes[GEN_AI_OPERATION_NAME_ATTRIBUTE]; + startSpanManual$1( + { + name: `${operationName} ${modelName}`, + op: "gen_ai.pipeline", + attributes: { + ...attributes, + [SEMANTIC_ATTRIBUTE_SENTRY_OP]: "gen_ai.pipeline" + } + }, + (span) => { + spanMap.set(runId, span); + return span; + } + ); + }, + // Chat Model Start Handler + handleChatModelStart(llm, messages, runId, _parentRunId, _extraParams, tags, metadata, _runName) { + const invocationParams = getInvocationParams(tags); + const attributes = extractChatModelRequestAttributes( + llm, + messages, + recordInputs, + invocationParams, + metadata + ); + const modelName = attributes[GEN_AI_REQUEST_MODEL_ATTRIBUTE]; + const operationName = attributes[GEN_AI_OPERATION_NAME_ATTRIBUTE]; + startSpanManual$1( + { + name: `${operationName} ${modelName}`, + op: "gen_ai.chat", + attributes: { + ...attributes, + [SEMANTIC_ATTRIBUTE_SENTRY_OP]: "gen_ai.chat" + } + }, + (span) => { + spanMap.set(runId, span); + return span; + } + ); + }, + // LLM End Handler - note: handleLLMEnd with capital LLM (used by both LLMs and chat models!) + handleLLMEnd(output, runId, _parentRunId, _tags, _extraParams) { + const span = spanMap.get(runId); + if (span?.isRecording()) { + const attributes = extractLlmResponseAttributes(output, recordOutputs); + if (attributes) { + span.setAttributes(attributes); + } + exitSpan(runId); + } + }, + // LLM Error Handler - note: handleLLMError with capital LLM + handleLLMError(error2, runId) { + const span = spanMap.get(runId); + if (span?.isRecording()) { + span.setStatus({ code: SPAN_STATUS_ERROR, message: "llm_error" }); + exitSpan(runId); + } + captureException(error2, { + mechanism: { + handled: false, + type: `${LANGCHAIN_ORIGIN}.llm_error_handler` + } + }); + }, + // Chain Start Handler + handleChainStart(chain, inputs, runId, _parentRunId) { + const chainName = chain.name || "unknown_chain"; + const attributes = { + [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: "auto.ai.langchain", + "langchain.chain.name": chainName + }; + if (recordInputs) { + attributes["langchain.chain.inputs"] = JSON.stringify(inputs); + } + startSpanManual$1( + { + name: `chain ${chainName}`, + op: "gen_ai.invoke_agent", + attributes: { + ...attributes, + [SEMANTIC_ATTRIBUTE_SENTRY_OP]: "gen_ai.invoke_agent" + } + }, + (span) => { + spanMap.set(runId, span); + return span; + } + ); + }, + // Chain End Handler + handleChainEnd(outputs, runId) { + const span = spanMap.get(runId); + if (span?.isRecording()) { + if (recordOutputs) { + span.setAttributes({ + "langchain.chain.outputs": JSON.stringify(outputs) + }); + } + exitSpan(runId); + } + }, + // Chain Error Handler + handleChainError(error2, runId) { + const span = spanMap.get(runId); + if (span?.isRecording()) { + span.setStatus({ code: SPAN_STATUS_ERROR, message: "chain_error" }); + exitSpan(runId); + } + captureException(error2, { + mechanism: { + handled: false, + type: `${LANGCHAIN_ORIGIN}.chain_error_handler` + } + }); + }, + // Tool Start Handler + handleToolStart(tool, input, runId, _parentRunId) { + const toolName = tool.name || "unknown_tool"; + const attributes = { + [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: LANGCHAIN_ORIGIN, + "gen_ai.tool.name": toolName + }; + if (recordInputs) { + attributes["gen_ai.tool.input"] = input; + } + startSpanManual$1( + { + name: `execute_tool ${toolName}`, + op: "gen_ai.execute_tool", + attributes: { + ...attributes, + [SEMANTIC_ATTRIBUTE_SENTRY_OP]: "gen_ai.execute_tool" + } + }, + (span) => { + spanMap.set(runId, span); + return span; + } + ); + }, + // Tool End Handler + handleToolEnd(output, runId) { + const span = spanMap.get(runId); + if (span?.isRecording()) { + if (recordOutputs) { + span.setAttributes({ + "gen_ai.tool.output": JSON.stringify(output) + }); + } + exitSpan(runId); + } + }, + // Tool Error Handler + handleToolError(error2, runId) { + const span = spanMap.get(runId); + if (span?.isRecording()) { + span.setStatus({ code: SPAN_STATUS_ERROR, message: "tool_error" }); + exitSpan(runId); + } + captureException(error2, { + mechanism: { + handled: false, + type: `${LANGCHAIN_ORIGIN}.tool_error_handler` + } + }); + }, + // LangChain BaseCallbackHandler required methods + copy() { + return handler; + }, + toJSON() { + return { + lc: 1, + type: "not_implemented", + id: handler.lc_id + }; + }, + toJSONNotImplemented() { + return { + lc: 1, + type: "not_implemented", + id: handler.lc_id + }; + } + }; + return handler; +} +const LANGGRAPH_INTEGRATION_NAME = "LangGraph"; +const LANGGRAPH_ORIGIN = "auto.ai.langgraph"; +function extractToolCalls(messages) { + if (!messages || messages.length === 0) { + return null; + } + const toolCalls = []; + for (const message of messages) { + if (message && typeof message === "object") { + const msgToolCalls = message.tool_calls; + if (msgToolCalls && Array.isArray(msgToolCalls)) { + toolCalls.push(...msgToolCalls); + } + } + } + return toolCalls.length > 0 ? toolCalls : null; +} +function extractTokenUsageFromMessage(message) { + const msg = message; + let inputTokens = 0; + let outputTokens = 0; + let totalTokens = 0; + if (msg.usage_metadata && typeof msg.usage_metadata === "object") { + const usage = msg.usage_metadata; + if (typeof usage.input_tokens === "number") { + inputTokens = usage.input_tokens; + } + if (typeof usage.output_tokens === "number") { + outputTokens = usage.output_tokens; + } + if (typeof usage.total_tokens === "number") { + totalTokens = usage.total_tokens; + } + return { inputTokens, outputTokens, totalTokens }; + } + if (msg.response_metadata && typeof msg.response_metadata === "object") { + const metadata = msg.response_metadata; + if (metadata.tokenUsage && typeof metadata.tokenUsage === "object") { + const tokenUsage = metadata.tokenUsage; + if (typeof tokenUsage.promptTokens === "number") { + inputTokens = tokenUsage.promptTokens; + } + if (typeof tokenUsage.completionTokens === "number") { + outputTokens = tokenUsage.completionTokens; + } + if (typeof tokenUsage.totalTokens === "number") { + totalTokens = tokenUsage.totalTokens; + } + } + } + return { inputTokens, outputTokens, totalTokens }; +} +function extractModelMetadata(span, message) { + const msg = message; + if (msg.response_metadata && typeof msg.response_metadata === "object") { + const metadata = msg.response_metadata; + if (metadata.model_name && typeof metadata.model_name === "string") { + span.setAttribute(GEN_AI_RESPONSE_MODEL_ATTRIBUTE, metadata.model_name); + } + if (metadata.finish_reason && typeof metadata.finish_reason === "string") { + span.setAttribute(GEN_AI_RESPONSE_FINISH_REASONS_ATTRIBUTE, [metadata.finish_reason]); + } + } +} +function extractToolsFromCompiledGraph(compiledGraph) { + if (!compiledGraph.builder?.nodes?.tools?.runnable?.tools) { + return null; + } + const tools = compiledGraph.builder?.nodes?.tools?.runnable?.tools; + if (!tools || !Array.isArray(tools) || tools.length === 0) { + return null; + } + return tools.map((tool) => ({ + name: tool.lc_kwargs?.name, + description: tool.lc_kwargs?.description, + schema: tool.lc_kwargs?.schema + })); +} +function setResponseAttributes(span, inputMessages, result) { + const resultObj = result; + const outputMessages = resultObj?.messages; + if (!outputMessages || !Array.isArray(outputMessages)) { + return; + } + const inputCount = inputMessages?.length ?? 0; + const newMessages = outputMessages.length > inputCount ? outputMessages.slice(inputCount) : []; + if (newMessages.length === 0) { + return; + } + const toolCalls = extractToolCalls(newMessages); + if (toolCalls) { + span.setAttribute(GEN_AI_RESPONSE_TOOL_CALLS_ATTRIBUTE, JSON.stringify(toolCalls)); + } + const normalizedNewMessages = normalizeLangChainMessages(newMessages); + span.setAttribute(GEN_AI_RESPONSE_TEXT_ATTRIBUTE, JSON.stringify(normalizedNewMessages)); + let totalInputTokens = 0; + let totalOutputTokens = 0; + let totalTokens = 0; + for (const message of newMessages) { + const tokens = extractTokenUsageFromMessage(message); + totalInputTokens += tokens.inputTokens; + totalOutputTokens += tokens.outputTokens; + totalTokens += tokens.totalTokens; + extractModelMetadata(span, message); + } + if (totalInputTokens > 0) { + span.setAttribute(GEN_AI_USAGE_INPUT_TOKENS_ATTRIBUTE, totalInputTokens); + } + if (totalOutputTokens > 0) { + span.setAttribute(GEN_AI_USAGE_OUTPUT_TOKENS_ATTRIBUTE, totalOutputTokens); + } + if (totalTokens > 0) { + span.setAttribute(GEN_AI_USAGE_TOTAL_TOKENS_ATTRIBUTE, totalTokens); + } +} +function instrumentStateGraphCompile(originalCompile, options) { + return new Proxy(originalCompile, { + apply(target, thisArg, args) { + return startSpan$2( + { + op: "gen_ai.create_agent", + name: "create_agent", + attributes: { + [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: LANGGRAPH_ORIGIN, + [SEMANTIC_ATTRIBUTE_SENTRY_OP]: "gen_ai.create_agent", + [GEN_AI_OPERATION_NAME_ATTRIBUTE]: "create_agent" + } + }, + (span) => { + try { + const compiledGraph = Reflect.apply(target, thisArg, args); + const compileOptions = args.length > 0 ? args[0] : {}; + if (compileOptions?.name && typeof compileOptions.name === "string") { + span.setAttribute(GEN_AI_AGENT_NAME_ATTRIBUTE, compileOptions.name); + span.updateName(`create_agent ${compileOptions.name}`); + } + const originalInvoke = compiledGraph.invoke; + if (originalInvoke && typeof originalInvoke === "function") { + compiledGraph.invoke = instrumentCompiledGraphInvoke( + originalInvoke.bind(compiledGraph), + compiledGraph, + compileOptions, + options + ); + } + return compiledGraph; + } catch (error2) { + span.setStatus({ code: SPAN_STATUS_ERROR, message: "internal_error" }); + captureException(error2, { + mechanism: { + handled: false, + type: "auto.ai.langgraph.error" + } + }); + throw error2; + } + } + ); + } + }); +} +function instrumentCompiledGraphInvoke(originalInvoke, graphInstance, compileOptions, options) { + return new Proxy(originalInvoke, { + apply(target, thisArg, args) { + return startSpan$2( + { + op: "gen_ai.invoke_agent", + name: "invoke_agent", + attributes: { + [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: LANGGRAPH_ORIGIN, + [SEMANTIC_ATTRIBUTE_SENTRY_OP]: GEN_AI_INVOKE_AGENT_OPERATION_ATTRIBUTE, + [GEN_AI_OPERATION_NAME_ATTRIBUTE]: "invoke_agent" + } + }, + async (span) => { + try { + const graphName = compileOptions?.name; + if (graphName && typeof graphName === "string") { + span.setAttribute(GEN_AI_PIPELINE_NAME_ATTRIBUTE, graphName); + span.setAttribute(GEN_AI_AGENT_NAME_ATTRIBUTE, graphName); + span.updateName(`invoke_agent ${graphName}`); + } + const tools = extractToolsFromCompiledGraph(graphInstance); + if (tools) { + span.setAttribute(GEN_AI_REQUEST_AVAILABLE_TOOLS_ATTRIBUTE, JSON.stringify(tools)); + } + const recordInputs = options.recordInputs; + const recordOutputs = options.recordOutputs; + const inputMessages = args.length > 0 ? args[0].messages ?? [] : []; + if (inputMessages && recordInputs) { + const normalizedMessages = normalizeLangChainMessages(inputMessages); + const truncatedMessages = truncateGenAiMessages(normalizedMessages); + span.setAttribute(GEN_AI_REQUEST_MESSAGES_ATTRIBUTE, JSON.stringify(truncatedMessages)); + } + const result = await Reflect.apply(target, thisArg, args); + if (recordOutputs) { + setResponseAttributes(span, inputMessages ?? null, result); + } + return result; + } catch (error2) { + span.setStatus({ code: SPAN_STATUS_ERROR, message: "internal_error" }); + captureException(error2, { + mechanism: { + handled: false, + type: "auto.ai.langgraph.error" + } + }); + throw error2; + } + } + ); + } + }); +} +function getBreadcrumbLogLevelFromHttpStatusCode(statusCode) { + if (statusCode === void 0) { + return void 0; + } else if (statusCode >= 400 && statusCode < 500) { + return "warning"; + } else if (statusCode >= 500) { + return "error"; + } else { + return void 0; + } +} +function replaceExports(exports$1, exportName, wrappedConstructor) { + const original = exports$1[exportName]; + if (typeof original !== "function") { + return; + } + try { + exports$1[exportName] = wrappedConstructor; + } catch (error2) { + Object.defineProperty(exports$1, exportName, { + value: wrappedConstructor, + writable: true, + configurable: true, + enumerable: true + }); + } + if (exports$1.default === original) { + try { + exports$1.default = wrappedConstructor; + } catch (error2) { + Object.defineProperty(exports$1, "default", { + value: wrappedConstructor, + writable: true, + configurable: true, + enumerable: true + }); + } + } +} +function filenameIsInApp(filename, isNative = false) { + const isInternal = isNative || filename && // It's not internal if it's an absolute linux path + !filename.startsWith("/") && // It's not internal if it's an absolute windows path + !filename.match(/^[A-Z]:/) && // It's not internal if the path is starting with a dot + !filename.startsWith(".") && // It's not internal if the frame has a protocol. In node, this is usually the case if the file got pre-processed with a bundler like webpack + !filename.match(/^[a-zA-Z]([a-zA-Z0-9.\-+])*:\/\//); + return !isInternal && filename !== void 0 && !filename.includes("node_modules/"); +} +function node(getModule) { + const FILENAME_MATCH = /^\s*[-]{4,}$/; + const FULL_MATCH = /at (?:async )?(?:(.+?)\s+\()?(?:(.+):(\d+):(\d+)?|([^)]+))\)?/; + const DATA_URI_MATCH = /at (?:async )?(.+?) \(data:(.*?),/; + return (line) => { + const dataUriMatch = line.match(DATA_URI_MATCH); + if (dataUriMatch) { + return { + filename: ``, + function: dataUriMatch[1] + }; + } + const lineMatch = line.match(FULL_MATCH); + if (lineMatch) { + let object; + let method; + let functionName; + let typeName; + let methodName; + if (lineMatch[1]) { + functionName = lineMatch[1]; + let methodStart = functionName.lastIndexOf("."); + if (functionName[methodStart - 1] === ".") { + methodStart--; + } + if (methodStart > 0) { + object = functionName.slice(0, methodStart); + method = functionName.slice(methodStart + 1); + const objectEnd = object.indexOf(".Module"); + if (objectEnd > 0) { + functionName = functionName.slice(objectEnd + 1); + object = object.slice(0, objectEnd); + } + } + typeName = void 0; + } + if (method) { + typeName = object; + methodName = method; + } + if (method === "") { + methodName = void 0; + functionName = void 0; + } + if (functionName === void 0) { + methodName = methodName || UNKNOWN_FUNCTION; + functionName = typeName ? `${typeName}.${methodName}` : methodName; + } + let filename = lineMatch[2]?.startsWith("file://") ? lineMatch[2].slice(7) : lineMatch[2]; + const isNative = lineMatch[5] === "native"; + if (filename?.match(/\/[A-Z]:/)) { + filename = filename.slice(1); + } + if (!filename && lineMatch[5] && !isNative) { + filename = lineMatch[5]; + } + return { + filename: filename ? decodeURI(filename) : void 0, + module: getModule ? getModule(filename) : void 0, + function: functionName, + lineno: _parseIntOrUndefined(lineMatch[3]), + colno: _parseIntOrUndefined(lineMatch[4]), + in_app: filenameIsInApp(filename || "", isNative) + }; + } + if (line.match(FILENAME_MATCH)) { + return { + filename: line + }; + } + return void 0; + }; +} +function nodeStackLineParser(getModule) { + return [90, node(getModule)]; +} +function _parseIntOrUndefined(input) { + return parseInt(input || "", 10) || void 0; +} +class LRUMap { + constructor(_maxSize) { + this._maxSize = _maxSize; + this._cache = /* @__PURE__ */ new Map(); + } + /** Get the current size of the cache */ + get size() { + return this._cache.size; + } + /** Get an entry or undefined if it was not in the cache. Re-inserts to update the recently used order */ + get(key) { + const value = this._cache.get(key); + if (value === void 0) { + return void 0; + } + this._cache.delete(key); + this._cache.set(key, value); + return value; + } + /** Insert an entry and evict an older entry if we've reached maxSize */ + set(key, value) { + if (this._cache.size >= this._maxSize) { + const nextKey = this._cache.keys().next().value; + this._cache.delete(nextKey); + } + this._cache.set(key, value); + } + /** Remove an entry and return the entry if it was in the cache */ + remove(key) { + const value = this._cache.get(key); + if (value) { + this._cache.delete(key); + } + return value; + } + /** Clear all entries */ + clear() { + this._cache.clear(); + } + /** Get all the keys */ + keys() { + return Array.from(this._cache.keys()); + } + /** Get all the values */ + values() { + const values = []; + this._cache.forEach((value) => values.push(value)); + return values; + } +} +const INSTRUMENTED = {}; +function generateInstrumentOnce(name, creatorOrClass, optionsCallback) { + if (optionsCallback) { + return _generateInstrumentOnceWithOptions( + name, + creatorOrClass, + optionsCallback + ); + } + return _generateInstrumentOnce(name, creatorOrClass); +} +function _generateInstrumentOnce(name, creator) { + return Object.assign( + (options) => { + const instrumented2 = INSTRUMENTED[name]; + if (instrumented2) { + if (options) { + instrumented2.setConfig(options); + } + return instrumented2; + } + const instrumentation2 = creator(options); + INSTRUMENTED[name] = instrumentation2; + registerInstrumentations({ + instrumentations: [instrumentation2] + }); + return instrumentation2; + }, + { id: name } + ); +} +function _generateInstrumentOnceWithOptions(name, instrumentationClass, optionsCallback) { + return Object.assign( + (_options) => { + const options = optionsCallback(_options); + const instrumented2 = INSTRUMENTED[name]; + if (instrumented2) { + instrumented2.setConfig(options); + return instrumented2; + } + const instrumentation2 = new instrumentationClass(options); + INSTRUMENTED[name] = instrumentation2; + registerInstrumentations({ + instrumentations: [instrumentation2] + }); + return instrumentation2; + }, + { id: name } + ); +} +function instrumentWhenWrapped(instrumentation2) { + let isWrapped2 = false; + let callbacks = []; + if (!hasWrap(instrumentation2)) { + isWrapped2 = true; + } else { + const originalWrap = instrumentation2["_wrap"]; + instrumentation2["_wrap"] = (...args) => { + isWrapped2 = true; + callbacks.forEach((callback) => callback()); + callbacks = []; + return originalWrap(...args); + }; + } + const registerCallback = (callback) => { + if (isWrapped2) { + callback(); + } else { + callbacks.push(callback); + } + }; + return registerCallback; +} +function hasWrap(instrumentation2) { + return typeof instrumentation2["_wrap"] === "function"; +} +const DEBUG_BUILD$2 = typeof __SENTRY_DEBUG__ === "undefined" || __SENTRY_DEBUG__; +const INSTRUMENTATION_NAME$1 = "@sentry/instrumentation-http"; +const MAX_BODY_BYTE_LENGTH = 1024 * 1024; +const HTTP_SERVER_INSTRUMENTED_KEY = srcExports$l.createContextKey("sentry_http_server_instrumented"); +const INTEGRATION_NAME$B = "Http.Server"; +const clientToRequestSessionAggregatesMap = /* @__PURE__ */ new Map(); +const wrappedEmitFns = /* @__PURE__ */ new WeakSet(); +function addStartSpanCallback(request, callback) { + addNonEnumerableProperty(request, "_startSpanCallback", new WeakRef(callback)); +} +const _httpServerIntegration = ((options = {}) => { + const _options = { + sessions: options.sessions ?? true, + sessionFlushingDelayMS: options.sessionFlushingDelayMS ?? 6e4, + maxRequestBodySize: options.maxRequestBodySize ?? "medium", + ignoreRequestBody: options.ignoreRequestBody + }; + return { + name: INTEGRATION_NAME$B, + setupOnce() { + const onHttpServerRequestStart = ((_data) => { + const data = _data; + instrumentServer(data.server, _options); + }); + subscribe("http.server.request.start", onHttpServerRequestStart); + }, + afterAllSetup(client) { + if (DEBUG_BUILD$2 && client.getIntegrationByName("Http")) { + debug$2.warn( + "It seems that you have manually added `httpServerIntegration` while `httpIntegration` is also present. Make sure to remove `httpServerIntegration` when adding `httpIntegration`." + ); + } + } + }; +}); +const httpServerIntegration = _httpServerIntegration; +function instrumentServer(server, { + ignoreRequestBody, + maxRequestBodySize, + sessions, + sessionFlushingDelayMS +}) { + const originalEmit = server.emit; + if (wrappedEmitFns.has(originalEmit)) { + return; + } + const newEmit = new Proxy(originalEmit, { + apply(target, thisArg, args) { + if (args[0] !== "request") { + return target.apply(thisArg, args); + } + const client = getClient(); + if (srcExports$l.context.active().getValue(HTTP_SERVER_INSTRUMENTED_KEY) || !client) { + return target.apply(thisArg, args); + } + DEBUG_BUILD$2 && debug$2.log(INTEGRATION_NAME$B, "Handling incoming request"); + const isolationScope = getIsolationScope().clone(); + const request = args[1]; + const response = args[2]; + const normalizedRequest = httpRequestToRequestData(request); + const ipAddress = request.ip || request.socket?.remoteAddress; + const url = request.url || "/"; + if (maxRequestBodySize !== "none" && !ignoreRequestBody?.(url, request)) { + patchRequestToCaptureBody(request, isolationScope, maxRequestBodySize); + } + isolationScope.setSDKProcessingMetadata({ normalizedRequest, ipAddress }); + const httpMethod = (request.method || "GET").toUpperCase(); + const httpTargetWithoutQueryFragment = stripUrlQueryAndFragment(url); + const bestEffortTransactionName = `${httpMethod} ${httpTargetWithoutQueryFragment}`; + isolationScope.setTransactionName(bestEffortTransactionName); + if (sessions && client) { + recordRequestSession(client, { + requestIsolationScope: isolationScope, + response, + sessionFlushingDelayMS: sessionFlushingDelayMS ?? 6e4 + }); + } + return withIsolationScope(isolationScope, () => { + getCurrentScope().getPropagationContext().propagationSpanId = generateSpanId(); + const ctx = srcExports$l.propagation.extract(srcExports$l.context.active(), normalizedRequest.headers).setValue(HTTP_SERVER_INSTRUMENTED_KEY, true); + return srcExports$l.context.with(ctx, () => { + client.emit("httpServerRequest", request, response, normalizedRequest); + const callback = request._startSpanCallback?.deref(); + if (callback) { + return callback(() => target.apply(thisArg, args)); + } + return target.apply(thisArg, args); + }); + }); + } + }); + wrappedEmitFns.add(newEmit); + server.emit = newEmit; +} +function recordRequestSession(client, { + requestIsolationScope, + response, + sessionFlushingDelayMS +}) { + requestIsolationScope.setSDKProcessingMetadata({ + requestSession: { status: "ok" } + }); + response.once("close", () => { + const requestSession = requestIsolationScope.getScopeData().sdkProcessingMetadata.requestSession; + if (client && requestSession) { + DEBUG_BUILD$2 && debug$2.log(`Recorded request session with status: ${requestSession.status}`); + const roundedDate = /* @__PURE__ */ new Date(); + roundedDate.setSeconds(0, 0); + const dateBucketKey = roundedDate.toISOString(); + const existingClientAggregate = clientToRequestSessionAggregatesMap.get(client); + const bucket = existingClientAggregate?.[dateBucketKey] || { exited: 0, crashed: 0, errored: 0 }; + bucket[{ ok: "exited", crashed: "crashed", errored: "errored" }[requestSession.status]]++; + if (existingClientAggregate) { + existingClientAggregate[dateBucketKey] = bucket; + } else { + DEBUG_BUILD$2 && debug$2.log("Opened new request session aggregate."); + const newClientAggregate = { [dateBucketKey]: bucket }; + clientToRequestSessionAggregatesMap.set(client, newClientAggregate); + const flushPendingClientAggregates = () => { + clearTimeout(timeout); + unregisterClientFlushHook(); + clientToRequestSessionAggregatesMap.delete(client); + const aggregatePayload = Object.entries(newClientAggregate).map( + ([timestamp, value]) => ({ + started: timestamp, + exited: value.exited, + errored: value.errored, + crashed: value.crashed + }) + ); + client.sendSession({ aggregates: aggregatePayload }); + }; + const unregisterClientFlushHook = client.on("flush", () => { + DEBUG_BUILD$2 && debug$2.log("Sending request session aggregate due to client flush"); + flushPendingClientAggregates(); + }); + const timeout = setTimeout(() => { + DEBUG_BUILD$2 && debug$2.log("Sending request session aggregate due to flushing schedule"); + flushPendingClientAggregates(); + }, sessionFlushingDelayMS).unref(); + } + } + }); +} +function patchRequestToCaptureBody(req, isolationScope, maxIncomingRequestBodySize) { + let bodyByteLength = 0; + const chunks = []; + DEBUG_BUILD$2 && debug$2.log(INTEGRATION_NAME$B, "Patching request.on"); + const callbackMap = /* @__PURE__ */ new WeakMap(); + const maxBodySize = maxIncomingRequestBodySize === "small" ? 1e3 : maxIncomingRequestBodySize === "medium" ? 1e4 : MAX_BODY_BYTE_LENGTH; + try { + req.on = new Proxy(req.on, { + apply: (target, thisArg, args) => { + const [event, listener, ...restArgs] = args; + if (event === "data") { + DEBUG_BUILD$2 && debug$2.log(INTEGRATION_NAME$B, `Handling request.on("data") with maximum body size of ${maxBodySize}b`); + const callback = new Proxy(listener, { + apply: (target2, thisArg2, args2) => { + try { + const chunk = args2[0]; + const bufferifiedChunk = Buffer.from(chunk); + if (bodyByteLength < maxBodySize) { + chunks.push(bufferifiedChunk); + bodyByteLength += bufferifiedChunk.byteLength; + } else if (DEBUG_BUILD$2) { + debug$2.log( + INTEGRATION_NAME$B, + `Dropping request body chunk because maximum body length of ${maxBodySize}b is exceeded.` + ); + } + } catch (err) { + DEBUG_BUILD$2 && debug$2.error(INTEGRATION_NAME$B, "Encountered error while storing body chunk."); + } + return Reflect.apply(target2, thisArg2, args2); + } + }); + callbackMap.set(listener, callback); + return Reflect.apply(target, thisArg, [event, callback, ...restArgs]); + } + return Reflect.apply(target, thisArg, args); + } + }); + req.off = new Proxy(req.off, { + apply: (target, thisArg, args) => { + const [, listener] = args; + const callback = callbackMap.get(listener); + if (callback) { + callbackMap.delete(listener); + const modifiedArgs = args.slice(); + modifiedArgs[1] = callback; + return Reflect.apply(target, thisArg, modifiedArgs); + } + return Reflect.apply(target, thisArg, args); + } + }); + req.on("end", () => { + try { + const body = Buffer.concat(chunks).toString("utf-8"); + if (body) { + const bodyByteLength2 = Buffer.byteLength(body, "utf-8"); + const truncatedBody = bodyByteLength2 > maxBodySize ? `${Buffer.from(body).subarray(0, maxBodySize - 3).toString("utf-8")}...` : body; + isolationScope.setSDKProcessingMetadata({ normalizedRequest: { data: truncatedBody } }); + } + } catch (error2) { + if (DEBUG_BUILD$2) { + debug$2.error(INTEGRATION_NAME$B, "Error building captured request body", error2); + } + } + }); + } catch (error2) { + if (DEBUG_BUILD$2) { + debug$2.error(INTEGRATION_NAME$B, "Error patching request to capture body", error2); + } + } +} +const INTEGRATION_NAME$A = "Http.ServerSpans"; +const _httpServerSpansIntegration = ((options = {}) => { + const ignoreStaticAssets = options.ignoreStaticAssets ?? true; + const ignoreIncomingRequests = options.ignoreIncomingRequests; + const ignoreStatusCodes = options.ignoreStatusCodes ?? [ + [401, 404], + // 300 and 304 are possibly valid status codes we do not want to filter + [301, 303], + [305, 399] + ]; + const { onSpanCreated } = options; + const { requestHook: requestHook2, responseHook, applyCustomAttributesOnSpan } = options.instrumentation ?? {}; + return { + name: INTEGRATION_NAME$A, + setup(client) { + if (typeof __SENTRY_TRACING__ !== "undefined" && !__SENTRY_TRACING__) { + return; + } + client.on("httpServerRequest", (_request, _response, normalizedRequest) => { + const request = _request; + const response = _response; + const startSpan2 = (next) => { + if (shouldIgnoreSpansForIncomingRequest(request, { + ignoreStaticAssets, + ignoreIncomingRequests + })) { + DEBUG_BUILD$2 && debug$2.log(INTEGRATION_NAME$A, "Skipping span creation for incoming request", request.url); + return next(); + } + const fullUrl = normalizedRequest.url || request.url || "/"; + const urlObj = parseStringToURLObject(fullUrl); + const headers = request.headers; + const userAgent = headers["user-agent"]; + const ips = headers["x-forwarded-for"]; + const httpVersion = request.httpVersion; + const host = headers.host; + const hostname = host?.replace(/^(.*)(:[0-9]{1,5})/, "$1") || "localhost"; + const tracer = client.tracer; + const scheme = fullUrl.startsWith("https") ? "https" : "http"; + const method = normalizedRequest.method || request.method?.toUpperCase() || "GET"; + const httpTargetWithoutQueryFragment = urlObj ? urlObj.pathname : stripUrlQueryAndFragment(fullUrl); + const bestEffortTransactionName = `${method} ${httpTargetWithoutQueryFragment}`; + const span = tracer.startSpan(bestEffortTransactionName, { + kind: srcExports$l.SpanKind.SERVER, + attributes: { + // Sentry specific attributes + [SEMANTIC_ATTRIBUTE_SENTRY_OP]: "http.server", + [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: "auto.http.otel.http", + "sentry.http.prefetch": isKnownPrefetchRequest(request) || void 0, + // Old Semantic Conventions attributes - added for compatibility with what `@opentelemetry/instrumentation-http` output before + "http.url": fullUrl, + "http.method": normalizedRequest.method, + "http.target": urlObj ? `${urlObj.pathname}${urlObj.search}` : httpTargetWithoutQueryFragment, + "http.host": host, + "net.host.name": hostname, + "http.client_ip": typeof ips === "string" ? ips.split(",")[0] : void 0, + "http.user_agent": userAgent, + "http.scheme": scheme, + "http.flavor": httpVersion, + "net.transport": httpVersion?.toUpperCase() === "QUIC" ? "ip_udp" : "ip_tcp", + ...getRequestContentLengthAttribute(request), + ...httpHeadersToSpanAttributes( + normalizedRequest.headers || {}, + client.getOptions().sendDefaultPii ?? false + ) + } + }); + requestHook2?.(span, request); + responseHook?.(span, response); + applyCustomAttributesOnSpan?.(span, request, response); + onSpanCreated?.(span, request, response); + const rpcMetadata = { + type: RPCType.HTTP, + span + }; + return srcExports$l.context.with(setRPCMetadata(srcExports$l.trace.setSpan(srcExports$l.context.active(), span), rpcMetadata), () => { + srcExports$l.context.bind(srcExports$l.context.active(), request); + srcExports$l.context.bind(srcExports$l.context.active(), response); + let isEnded = false; + function endSpan2(status2) { + if (isEnded) { + return; + } + isEnded = true; + const newAttributes = getIncomingRequestAttributesOnResponse(request, response); + span.setAttributes(newAttributes); + span.setStatus(status2); + span.end(); + const route = newAttributes["http.route"]; + if (route) { + getIsolationScope().setTransactionName(`${request.method?.toUpperCase() || "GET"} ${route}`); + } + } + response.on("close", () => { + endSpan2(getSpanStatusFromHttpCode(response.statusCode)); + }); + response.on(errorMonitor, () => { + const httpStatus = getSpanStatusFromHttpCode(response.statusCode); + endSpan2(httpStatus.code === SPAN_STATUS_ERROR ? httpStatus : { code: SPAN_STATUS_ERROR }); + }); + return next(); + }); + }; + addStartSpanCallback(request, startSpan2); + }); + }, + processEvent(event) { + if (event.type === "transaction") { + const statusCode = event.contexts?.trace?.data?.["http.response.status_code"]; + if (typeof statusCode === "number") { + const shouldDrop = shouldFilterStatusCode(statusCode, ignoreStatusCodes); + if (shouldDrop) { + DEBUG_BUILD$2 && debug$2.log("Dropping transaction due to status code", statusCode); + return null; + } + } + } + return event; + }, + afterAllSetup(client) { + if (!DEBUG_BUILD$2) { + return; + } + if (client.getIntegrationByName("Http")) { + debug$2.warn( + "It seems that you have manually added `httpServerSpansIntergation` while `httpIntegration` is also present. Make sure to remove `httpIntegration` when adding `httpServerSpansIntegration`." + ); + } + if (!client.getIntegrationByName("Http.Server")) { + debug$2.error( + "It seems that you have manually added `httpServerSpansIntergation` without adding `httpServerIntegration`. This is a requiement for spans to be created - please add the `httpServerIntegration` integration." + ); + } + } + }; +}); +const httpServerSpansIntegration = _httpServerSpansIntegration; +function isKnownPrefetchRequest(req) { + return req.headers["next-router-prefetch"] === "1"; +} +function isStaticAssetRequest(urlPath) { + const path2 = stripUrlQueryAndFragment(urlPath); + if (path2.match(/\.(ico|png|jpg|jpeg|gif|svg|css|js|woff|woff2|ttf|eot|webp|avif)$/)) { + return true; + } + if (path2.match(/^\/(robots\.txt|sitemap\.xml|manifest\.json|browserconfig\.xml)$/)) { + return true; + } + return false; +} +function shouldIgnoreSpansForIncomingRequest(request, { + ignoreStaticAssets, + ignoreIncomingRequests +}) { + if (isTracingSuppressed(srcExports$l.context.active())) { + return true; + } + const urlPath = request.url; + const method = request.method?.toUpperCase(); + if (method === "OPTIONS" || method === "HEAD" || !urlPath) { + return true; + } + if (ignoreStaticAssets && method === "GET" && isStaticAssetRequest(urlPath)) { + return true; + } + if (ignoreIncomingRequests?.(urlPath, request)) { + return true; + } + return false; +} +function getRequestContentLengthAttribute(request) { + const length = getContentLength(request.headers); + if (length == null) { + return {}; + } + if (isCompressed(request.headers)) { + return { + ["http.request_content_length"]: length + }; + } else { + return { + ["http.request_content_length_uncompressed"]: length + }; + } +} +function getContentLength(headers) { + const contentLengthHeader = headers["content-length"]; + if (contentLengthHeader === void 0) return null; + const contentLength = parseInt(contentLengthHeader, 10); + if (isNaN(contentLength)) return null; + return contentLength; +} +function isCompressed(headers) { + const encoding = headers["content-encoding"]; + return !!encoding && encoding !== "identity"; +} +function getIncomingRequestAttributesOnResponse(request, response) { + const { socket } = request; + const { statusCode, statusMessage } = response; + const newAttributes = { + [srcExports$k.ATTR_HTTP_RESPONSE_STATUS_CODE]: statusCode, + // eslint-disable-next-line deprecation/deprecation + [srcExports$k.SEMATTRS_HTTP_STATUS_CODE]: statusCode, + "http.status_text": statusMessage?.toUpperCase() + }; + const rpcMetadata = getRPCMetadata(srcExports$l.context.active()); + if (socket) { + const { localAddress, localPort, remoteAddress, remotePort } = socket; + newAttributes[srcExports$k.SEMATTRS_NET_HOST_IP] = localAddress; + newAttributes[srcExports$k.SEMATTRS_NET_HOST_PORT] = localPort; + newAttributes[srcExports$k.SEMATTRS_NET_PEER_IP] = remoteAddress; + newAttributes["net.peer.port"] = remotePort; + } + newAttributes[srcExports$k.SEMATTRS_HTTP_STATUS_CODE] = statusCode; + newAttributes["http.status_text"] = (statusMessage || "").toUpperCase(); + if (rpcMetadata?.type === RPCType.HTTP && rpcMetadata.route !== void 0) { + const routeName = rpcMetadata.route; + newAttributes[srcExports$k.ATTR_HTTP_ROUTE] = routeName; + } + return newAttributes; +} +function shouldFilterStatusCode(statusCode, dropForStatusCodes) { + return dropForStatusCodes.some((code) => { + if (typeof code === "number") { + return code === statusCode; + } + const [min, max] = code; + return statusCode >= min && statusCode <= max; + }); +} +function getRequestUrl$1(requestOptions) { + const protocol = requestOptions.protocol || ""; + const hostname = requestOptions.hostname || requestOptions.host || ""; + const port = !requestOptions.port || requestOptions.port === 80 || requestOptions.port === 443 || /^(.*):(\d+)$/.test(hostname) ? "" : `:${requestOptions.port}`; + const path2 = requestOptions.path ? requestOptions.path : "/"; + return `${protocol}//${hostname}${port}${path2}`; +} +function defaultServiceName() { + return `unknown_service:${process.argv0}`; +} +const isPromiseLike$1 = (val) => { + return val !== null && typeof val === "object" && typeof val.then === "function"; +}; +class ResourceImpl { + _rawAttributes; + _asyncAttributesPending = false; + _schemaUrl; + _memoizedAttributes; + static FromAttributeList(attributes, options) { + const res = new ResourceImpl({}, options); + res._rawAttributes = guardedRawAttributes(attributes); + res._asyncAttributesPending = attributes.filter(([_, val]) => isPromiseLike$1(val)).length > 0; + return res; + } + constructor(resource2, options) { + const attributes = resource2.attributes ?? {}; + this._rawAttributes = Object.entries(attributes).map(([k, v]) => { + if (isPromiseLike$1(v)) { + this._asyncAttributesPending = true; + } + return [k, v]; + }); + this._rawAttributes = guardedRawAttributes(this._rawAttributes); + this._schemaUrl = validateSchemaUrl(options?.schemaUrl); + } + get asyncAttributesPending() { + return this._asyncAttributesPending; + } + async waitForAsyncAttributes() { + if (!this.asyncAttributesPending) { + return; + } + for (let i = 0; i < this._rawAttributes.length; i++) { + const [k, v] = this._rawAttributes[i]; + this._rawAttributes[i] = [k, isPromiseLike$1(v) ? await v : v]; + } + this._asyncAttributesPending = false; + } + get attributes() { + if (this.asyncAttributesPending) { + srcExports$l.diag.error("Accessing resource attributes before async attributes settled"); + } + if (this._memoizedAttributes) { + return this._memoizedAttributes; + } + const attrs = {}; + for (const [k, v] of this._rawAttributes) { + if (isPromiseLike$1(v)) { + srcExports$l.diag.debug(`Unsettled resource attribute ${k} skipped`); + continue; + } + if (v != null) { + attrs[k] ??= v; + } + } + if (!this._asyncAttributesPending) { + this._memoizedAttributes = attrs; + } + return attrs; + } + getRawAttributes() { + return this._rawAttributes; + } + get schemaUrl() { + return this._schemaUrl; + } + merge(resource2) { + if (resource2 == null) + return this; + const mergedSchemaUrl = mergeSchemaUrl(this, resource2); + const mergedOptions = mergedSchemaUrl ? { schemaUrl: mergedSchemaUrl } : void 0; + return ResourceImpl.FromAttributeList([...resource2.getRawAttributes(), ...this.getRawAttributes()], mergedOptions); + } +} +function resourceFromAttributes(attributes, options) { + return ResourceImpl.FromAttributeList(Object.entries(attributes), options); +} +function defaultResource() { + return resourceFromAttributes({ + [srcExports$k.ATTR_SERVICE_NAME]: defaultServiceName(), + [srcExports$k.ATTR_TELEMETRY_SDK_LANGUAGE]: SDK_INFO[srcExports$k.ATTR_TELEMETRY_SDK_LANGUAGE], + [srcExports$k.ATTR_TELEMETRY_SDK_NAME]: SDK_INFO[srcExports$k.ATTR_TELEMETRY_SDK_NAME], + [srcExports$k.ATTR_TELEMETRY_SDK_VERSION]: SDK_INFO[srcExports$k.ATTR_TELEMETRY_SDK_VERSION] + }); +} +function guardedRawAttributes(attributes) { + return attributes.map(([k, v]) => { + if (isPromiseLike$1(v)) { + return [ + k, + v.catch((err) => { + srcExports$l.diag.debug("promise rejection for resource attribute: %s - %s", k, err); + return void 0; + }) + ]; + } + return [k, v]; + }); +} +function validateSchemaUrl(schemaUrl) { + if (typeof schemaUrl === "string" || schemaUrl === void 0) { + return schemaUrl; + } + srcExports$l.diag.warn("Schema URL must be string or undefined, got %s. Schema URL will be ignored.", schemaUrl); + return void 0; +} +function mergeSchemaUrl(old, updating) { + const oldSchemaUrl = old?.schemaUrl; + const updatingSchemaUrl = updating?.schemaUrl; + const isOldEmpty = oldSchemaUrl === void 0 || oldSchemaUrl === ""; + const isUpdatingEmpty = updatingSchemaUrl === void 0 || updatingSchemaUrl === ""; + if (isOldEmpty) { + return updatingSchemaUrl; + } + if (isUpdatingEmpty) { + return oldSchemaUrl; + } + if (oldSchemaUrl === updatingSchemaUrl) { + return oldSchemaUrl; + } + srcExports$l.diag.warn('Schema URL merge conflict: old resource has "%s", updating resource has "%s". Resulting resource will have undefined Schema URL.', oldSchemaUrl, updatingSchemaUrl); + return void 0; +} +const ExceptionEventName = "exception"; +class SpanImpl { + // Below properties are included to implement ReadableSpan for export + // purposes but are not intended to be written-to directly. + _spanContext; + kind; + parentSpanContext; + attributes = {}; + links = []; + events = []; + startTime; + resource; + instrumentationScope; + _droppedAttributesCount = 0; + _droppedEventsCount = 0; + _droppedLinksCount = 0; + name; + status = { + code: srcExports$l.SpanStatusCode.UNSET + }; + endTime = [0, 0]; + _ended = false; + _duration = [-1, -1]; + _spanProcessor; + _spanLimits; + _attributeValueLengthLimit; + _performanceStartTime; + _performanceOffset; + _startTimeProvided; + /** + * Constructs a new SpanImpl instance. + */ + constructor(opts) { + const now = Date.now(); + this._spanContext = opts.spanContext; + this._performanceStartTime = otperformance.now(); + this._performanceOffset = now - (this._performanceStartTime + getTimeOrigin()); + this._startTimeProvided = opts.startTime != null; + this._spanLimits = opts.spanLimits; + this._attributeValueLengthLimit = this._spanLimits.attributeValueLengthLimit || 0; + this._spanProcessor = opts.spanProcessor; + this.name = opts.name; + this.parentSpanContext = opts.parentSpanContext; + this.kind = opts.kind; + this.links = opts.links || []; + this.startTime = this._getTime(opts.startTime ?? now); + this.resource = opts.resource; + this.instrumentationScope = opts.scope; + if (opts.attributes != null) { + this.setAttributes(opts.attributes); + } + this._spanProcessor.onStart(this, opts.context); + } + spanContext() { + return this._spanContext; + } + setAttribute(key, value) { + if (value == null || this._isSpanEnded()) + return this; + if (key.length === 0) { + srcExports$l.diag.warn(`Invalid attribute key: ${key}`); + return this; + } + if (!isAttributeValue(value)) { + srcExports$l.diag.warn(`Invalid attribute value set for key: ${key}`); + return this; + } + const { attributeCountLimit } = this._spanLimits; + if (attributeCountLimit !== void 0 && Object.keys(this.attributes).length >= attributeCountLimit && !Object.prototype.hasOwnProperty.call(this.attributes, key)) { + this._droppedAttributesCount++; + return this; + } + this.attributes[key] = this._truncateToSize(value); + return this; + } + setAttributes(attributes) { + for (const [k, v] of Object.entries(attributes)) { + this.setAttribute(k, v); + } + return this; + } + /** + * + * @param name Span Name + * @param [attributesOrStartTime] Span attributes or start time + * if type is {@type TimeInput} and 3rd param is undefined + * @param [timeStamp] Specified time stamp for the event + */ + addEvent(name, attributesOrStartTime, timeStamp) { + if (this._isSpanEnded()) + return this; + const { eventCountLimit } = this._spanLimits; + if (eventCountLimit === 0) { + srcExports$l.diag.warn("No events allowed."); + this._droppedEventsCount++; + return this; + } + if (eventCountLimit !== void 0 && this.events.length >= eventCountLimit) { + if (this._droppedEventsCount === 0) { + srcExports$l.diag.debug("Dropping extra events."); + } + this.events.shift(); + this._droppedEventsCount++; + } + if (isTimeInput(attributesOrStartTime)) { + if (!isTimeInput(timeStamp)) { + timeStamp = attributesOrStartTime; + } + attributesOrStartTime = void 0; + } + const attributes = sanitizeAttributes(attributesOrStartTime); + this.events.push({ + name, + attributes, + time: this._getTime(timeStamp), + droppedAttributesCount: 0 + }); + return this; + } + addLink(link) { + this.links.push(link); + return this; + } + addLinks(links) { + this.links.push(...links); + return this; + } + setStatus(status2) { + if (this._isSpanEnded()) + return this; + this.status = { ...status2 }; + if (this.status.message != null && typeof status2.message !== "string") { + srcExports$l.diag.warn(`Dropping invalid status.message of type '${typeof status2.message}', expected 'string'`); + delete this.status.message; + } + return this; + } + updateName(name) { + if (this._isSpanEnded()) + return this; + this.name = name; + return this; + } + end(endTime) { + if (this._isSpanEnded()) { + srcExports$l.diag.error(`${this.name} ${this._spanContext.traceId}-${this._spanContext.spanId} - You can only call end() on a span once.`); + return; + } + this._ended = true; + this.endTime = this._getTime(endTime); + this._duration = hrTimeDuration(this.startTime, this.endTime); + if (this._duration[0] < 0) { + srcExports$l.diag.warn("Inconsistent start and end time, startTime > endTime. Setting span duration to 0ms.", this.startTime, this.endTime); + this.endTime = this.startTime.slice(); + this._duration = [0, 0]; + } + if (this._droppedEventsCount > 0) { + srcExports$l.diag.warn(`Dropped ${this._droppedEventsCount} events because eventCountLimit reached`); + } + this._spanProcessor.onEnd(this); + } + _getTime(inp) { + if (typeof inp === "number" && inp <= otperformance.now()) { + return hrTime(inp + this._performanceOffset); + } + if (typeof inp === "number") { + return millisToHrTime(inp); + } + if (inp instanceof Date) { + return millisToHrTime(inp.getTime()); + } + if (isTimeInputHrTime(inp)) { + return inp; + } + if (this._startTimeProvided) { + return millisToHrTime(Date.now()); + } + const msDuration = otperformance.now() - this._performanceStartTime; + return addHrTimes(this.startTime, millisToHrTime(msDuration)); + } + isRecording() { + return this._ended === false; + } + recordException(exception, time) { + const attributes = {}; + if (typeof exception === "string") { + attributes[srcExports$k.ATTR_EXCEPTION_MESSAGE] = exception; + } else if (exception) { + if (exception.code) { + attributes[srcExports$k.ATTR_EXCEPTION_TYPE] = exception.code.toString(); + } else if (exception.name) { + attributes[srcExports$k.ATTR_EXCEPTION_TYPE] = exception.name; + } + if (exception.message) { + attributes[srcExports$k.ATTR_EXCEPTION_MESSAGE] = exception.message; + } + if (exception.stack) { + attributes[srcExports$k.ATTR_EXCEPTION_STACKTRACE] = exception.stack; + } + } + if (attributes[srcExports$k.ATTR_EXCEPTION_TYPE] || attributes[srcExports$k.ATTR_EXCEPTION_MESSAGE]) { + this.addEvent(ExceptionEventName, attributes, time); + } else { + srcExports$l.diag.warn(`Failed to record an exception ${exception}`); + } + } + get duration() { + return this._duration; + } + get ended() { + return this._ended; + } + get droppedAttributesCount() { + return this._droppedAttributesCount; + } + get droppedEventsCount() { + return this._droppedEventsCount; + } + get droppedLinksCount() { + return this._droppedLinksCount; + } + _isSpanEnded() { + if (this._ended) { + const error2 = new Error(`Operation attempted on ended Span {traceId: ${this._spanContext.traceId}, spanId: ${this._spanContext.spanId}}`); + srcExports$l.diag.warn(`Cannot execute the operation on ended Span {traceId: ${this._spanContext.traceId}, spanId: ${this._spanContext.spanId}}`, error2); + } + return this._ended; + } + // Utility function to truncate given value within size + // for value type of string, will truncate to given limit + // for type of non-string, will return same value + _truncateToLimitUtil(value, limit) { + if (value.length <= limit) { + return value; + } + return value.substring(0, limit); + } + /** + * If the given attribute value is of type string and has more characters than given {@code attributeValueLengthLimit} then + * return string with truncated to {@code attributeValueLengthLimit} characters + * + * If the given attribute value is array of strings then + * return new array of strings with each element truncated to {@code attributeValueLengthLimit} characters + * + * Otherwise return same Attribute {@code value} + * + * @param value Attribute value + * @returns truncated attribute value if required, otherwise same value + */ + _truncateToSize(value) { + const limit = this._attributeValueLengthLimit; + if (limit <= 0) { + srcExports$l.diag.warn(`Attribute value limit must be positive, got ${limit}`); + return value; + } + if (typeof value === "string") { + return this._truncateToLimitUtil(value, limit); + } + if (Array.isArray(value)) { + return value.map((val) => typeof val === "string" ? this._truncateToLimitUtil(val, limit) : val); + } + return value; + } +} +var SamplingDecision; +(function(SamplingDecision2) { + SamplingDecision2[SamplingDecision2["NOT_RECORD"] = 0] = "NOT_RECORD"; + SamplingDecision2[SamplingDecision2["RECORD"] = 1] = "RECORD"; + SamplingDecision2[SamplingDecision2["RECORD_AND_SAMPLED"] = 2] = "RECORD_AND_SAMPLED"; +})(SamplingDecision || (SamplingDecision = {})); +class AlwaysOffSampler { + shouldSample() { + return { + decision: SamplingDecision.NOT_RECORD + }; + } + toString() { + return "AlwaysOffSampler"; + } +} +class AlwaysOnSampler { + shouldSample() { + return { + decision: SamplingDecision.RECORD_AND_SAMPLED + }; + } + toString() { + return "AlwaysOnSampler"; + } +} +class ParentBasedSampler { + _root; + _remoteParentSampled; + _remoteParentNotSampled; + _localParentSampled; + _localParentNotSampled; + constructor(config2) { + this._root = config2.root; + if (!this._root) { + globalErrorHandler(new Error("ParentBasedSampler must have a root sampler configured")); + this._root = new AlwaysOnSampler(); + } + this._remoteParentSampled = config2.remoteParentSampled ?? new AlwaysOnSampler(); + this._remoteParentNotSampled = config2.remoteParentNotSampled ?? new AlwaysOffSampler(); + this._localParentSampled = config2.localParentSampled ?? new AlwaysOnSampler(); + this._localParentNotSampled = config2.localParentNotSampled ?? new AlwaysOffSampler(); + } + shouldSample(context2, traceId, spanName, spanKind, attributes, links) { + const parentContext = srcExports$l.trace.getSpanContext(context2); + if (!parentContext || !srcExports$l.isSpanContextValid(parentContext)) { + return this._root.shouldSample(context2, traceId, spanName, spanKind, attributes, links); + } + if (parentContext.isRemote) { + if (parentContext.traceFlags & srcExports$l.TraceFlags.SAMPLED) { + return this._remoteParentSampled.shouldSample(context2, traceId, spanName, spanKind, attributes, links); + } + return this._remoteParentNotSampled.shouldSample(context2, traceId, spanName, spanKind, attributes, links); + } + if (parentContext.traceFlags & srcExports$l.TraceFlags.SAMPLED) { + return this._localParentSampled.shouldSample(context2, traceId, spanName, spanKind, attributes, links); + } + return this._localParentNotSampled.shouldSample(context2, traceId, spanName, spanKind, attributes, links); + } + toString() { + return `ParentBased{root=${this._root.toString()}, remoteParentSampled=${this._remoteParentSampled.toString()}, remoteParentNotSampled=${this._remoteParentNotSampled.toString()}, localParentSampled=${this._localParentSampled.toString()}, localParentNotSampled=${this._localParentNotSampled.toString()}}`; + } +} +class TraceIdRatioBasedSampler { + _ratio; + _upperBound; + constructor(_ratio = 0) { + this._ratio = _ratio; + this._ratio = this._normalize(_ratio); + this._upperBound = Math.floor(this._ratio * 4294967295); + } + shouldSample(context2, traceId) { + return { + decision: srcExports$l.isValidTraceId(traceId) && this._accumulate(traceId) < this._upperBound ? SamplingDecision.RECORD_AND_SAMPLED : SamplingDecision.NOT_RECORD + }; + } + toString() { + return `TraceIdRatioBased{${this._ratio}}`; + } + _normalize(ratio) { + if (typeof ratio !== "number" || isNaN(ratio)) + return 0; + return ratio >= 1 ? 1 : ratio <= 0 ? 0 : ratio; + } + _accumulate(traceId) { + let accumulation = 0; + for (let i = 0; i < traceId.length / 8; i++) { + const pos = i * 8; + const part = parseInt(traceId.slice(pos, pos + 8), 16); + accumulation = (accumulation ^ part) >>> 0; + } + return accumulation; + } +} +var TracesSamplerValues; +(function(TracesSamplerValues2) { + TracesSamplerValues2["AlwaysOff"] = "always_off"; + TracesSamplerValues2["AlwaysOn"] = "always_on"; + TracesSamplerValues2["ParentBasedAlwaysOff"] = "parentbased_always_off"; + TracesSamplerValues2["ParentBasedAlwaysOn"] = "parentbased_always_on"; + TracesSamplerValues2["ParentBasedTraceIdRatio"] = "parentbased_traceidratio"; + TracesSamplerValues2["TraceIdRatio"] = "traceidratio"; +})(TracesSamplerValues || (TracesSamplerValues = {})); +const DEFAULT_RATIO = 1; +function loadDefaultConfig() { + return { + sampler: buildSamplerFromEnv(), + forceFlushTimeoutMillis: 3e4, + generalLimits: { + attributeValueLengthLimit: getNumberFromEnv("OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT") ?? Infinity, + attributeCountLimit: getNumberFromEnv("OTEL_ATTRIBUTE_COUNT_LIMIT") ?? 128 + }, + spanLimits: { + attributeValueLengthLimit: getNumberFromEnv("OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT") ?? Infinity, + attributeCountLimit: getNumberFromEnv("OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT") ?? 128, + linkCountLimit: getNumberFromEnv("OTEL_SPAN_LINK_COUNT_LIMIT") ?? 128, + eventCountLimit: getNumberFromEnv("OTEL_SPAN_EVENT_COUNT_LIMIT") ?? 128, + attributePerEventCountLimit: getNumberFromEnv("OTEL_SPAN_ATTRIBUTE_PER_EVENT_COUNT_LIMIT") ?? 128, + attributePerLinkCountLimit: getNumberFromEnv("OTEL_SPAN_ATTRIBUTE_PER_LINK_COUNT_LIMIT") ?? 128 + } + }; +} +function buildSamplerFromEnv() { + const sampler = getStringFromEnv("OTEL_TRACES_SAMPLER") ?? TracesSamplerValues.ParentBasedAlwaysOn; + switch (sampler) { + case TracesSamplerValues.AlwaysOn: + return new AlwaysOnSampler(); + case TracesSamplerValues.AlwaysOff: + return new AlwaysOffSampler(); + case TracesSamplerValues.ParentBasedAlwaysOn: + return new ParentBasedSampler({ + root: new AlwaysOnSampler() + }); + case TracesSamplerValues.ParentBasedAlwaysOff: + return new ParentBasedSampler({ + root: new AlwaysOffSampler() + }); + case TracesSamplerValues.TraceIdRatio: + return new TraceIdRatioBasedSampler(getSamplerProbabilityFromEnv()); + case TracesSamplerValues.ParentBasedTraceIdRatio: + return new ParentBasedSampler({ + root: new TraceIdRatioBasedSampler(getSamplerProbabilityFromEnv()) + }); + default: + srcExports$l.diag.error(`OTEL_TRACES_SAMPLER value "${sampler}" invalid, defaulting to "${TracesSamplerValues.ParentBasedAlwaysOn}".`); + return new ParentBasedSampler({ + root: new AlwaysOnSampler() + }); + } +} +function getSamplerProbabilityFromEnv() { + const probability = getNumberFromEnv("OTEL_TRACES_SAMPLER_ARG"); + if (probability == null) { + srcExports$l.diag.error(`OTEL_TRACES_SAMPLER_ARG is blank, defaulting to ${DEFAULT_RATIO}.`); + return DEFAULT_RATIO; + } + if (probability < 0 || probability > 1) { + srcExports$l.diag.error(`OTEL_TRACES_SAMPLER_ARG=${probability} was given, but it is out of range ([0..1]), defaulting to ${DEFAULT_RATIO}.`); + return DEFAULT_RATIO; + } + return probability; +} +const DEFAULT_ATTRIBUTE_COUNT_LIMIT = 128; +const DEFAULT_ATTRIBUTE_VALUE_LENGTH_LIMIT = Infinity; +function mergeConfig(userConfig) { + const perInstanceDefaults = { + sampler: buildSamplerFromEnv() + }; + const DEFAULT_CONFIG = loadDefaultConfig(); + const target = Object.assign({}, DEFAULT_CONFIG, perInstanceDefaults, userConfig); + target.generalLimits = Object.assign({}, DEFAULT_CONFIG.generalLimits, userConfig.generalLimits || {}); + target.spanLimits = Object.assign({}, DEFAULT_CONFIG.spanLimits, userConfig.spanLimits || {}); + return target; +} +function reconfigureLimits(userConfig) { + const spanLimits = Object.assign({}, userConfig.spanLimits); + spanLimits.attributeCountLimit = userConfig.spanLimits?.attributeCountLimit ?? userConfig.generalLimits?.attributeCountLimit ?? getNumberFromEnv("OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT") ?? getNumberFromEnv("OTEL_ATTRIBUTE_COUNT_LIMIT") ?? DEFAULT_ATTRIBUTE_COUNT_LIMIT; + spanLimits.attributeValueLengthLimit = userConfig.spanLimits?.attributeValueLengthLimit ?? userConfig.generalLimits?.attributeValueLengthLimit ?? getNumberFromEnv("OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT") ?? getNumberFromEnv("OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT") ?? DEFAULT_ATTRIBUTE_VALUE_LENGTH_LIMIT; + return Object.assign({}, userConfig, { spanLimits }); +} +const SPAN_ID_BYTES = 8; +const TRACE_ID_BYTES = 16; +class RandomIdGenerator { + /** + * Returns a random 16-byte trace ID formatted/encoded as a 32 lowercase hex + * characters corresponding to 128 bits. + */ + generateTraceId = getIdGenerator(TRACE_ID_BYTES); + /** + * Returns a random 8-byte span ID formatted/encoded as a 16 lowercase hex + * characters corresponding to 64 bits. + */ + generateSpanId = getIdGenerator(SPAN_ID_BYTES); +} +const SHARED_BUFFER = Buffer.allocUnsafe(TRACE_ID_BYTES); +function getIdGenerator(bytes) { + return function generateId() { + for (let i = 0; i < bytes / 4; i++) { + SHARED_BUFFER.writeUInt32BE(Math.random() * 2 ** 32 >>> 0, i * 4); + } + for (let i = 0; i < bytes; i++) { + if (SHARED_BUFFER[i] > 0) { + break; + } else if (i === bytes - 1) { + SHARED_BUFFER[bytes - 1] = 1; + } + } + return SHARED_BUFFER.toString("hex", 0, bytes); + }; +} +class Tracer { + _sampler; + _generalLimits; + _spanLimits; + _idGenerator; + instrumentationScope; + _resource; + _spanProcessor; + /** + * Constructs a new Tracer instance. + */ + constructor(instrumentationScope, config2, resource2, spanProcessor) { + const localConfig = mergeConfig(config2); + this._sampler = localConfig.sampler; + this._generalLimits = localConfig.generalLimits; + this._spanLimits = localConfig.spanLimits; + this._idGenerator = config2.idGenerator || new RandomIdGenerator(); + this._resource = resource2; + this._spanProcessor = spanProcessor; + this.instrumentationScope = instrumentationScope; + } + /** + * Starts a new Span or returns the default NoopSpan based on the sampling + * decision. + */ + startSpan(name, options = {}, context2 = srcExports$l.context.active()) { + if (options.root) { + context2 = srcExports$l.trace.deleteSpan(context2); + } + const parentSpan = srcExports$l.trace.getSpan(context2); + if (isTracingSuppressed(context2)) { + srcExports$l.diag.debug("Instrumentation suppressed, returning Noop Span"); + const nonRecordingSpan = srcExports$l.trace.wrapSpanContext(srcExports$l.INVALID_SPAN_CONTEXT); + return nonRecordingSpan; + } + const parentSpanContext = parentSpan?.spanContext(); + const spanId = this._idGenerator.generateSpanId(); + let validParentSpanContext; + let traceId; + let traceState; + if (!parentSpanContext || !srcExports$l.trace.isSpanContextValid(parentSpanContext)) { + traceId = this._idGenerator.generateTraceId(); + } else { + traceId = parentSpanContext.traceId; + traceState = parentSpanContext.traceState; + validParentSpanContext = parentSpanContext; + } + const spanKind = options.kind ?? srcExports$l.SpanKind.INTERNAL; + const links = (options.links ?? []).map((link) => { + return { + context: link.context, + attributes: sanitizeAttributes(link.attributes) + }; + }); + const attributes = sanitizeAttributes(options.attributes); + const samplingResult = this._sampler.shouldSample(context2, traceId, name, spanKind, attributes, links); + traceState = samplingResult.traceState ?? traceState; + const traceFlags = samplingResult.decision === srcExports$l.SamplingDecision.RECORD_AND_SAMPLED ? srcExports$l.TraceFlags.SAMPLED : srcExports$l.TraceFlags.NONE; + const spanContext = { traceId, spanId, traceFlags, traceState }; + if (samplingResult.decision === srcExports$l.SamplingDecision.NOT_RECORD) { + srcExports$l.diag.debug("Recording is off, propagating context in a non-recording span"); + const nonRecordingSpan = srcExports$l.trace.wrapSpanContext(spanContext); + return nonRecordingSpan; + } + const initAttributes = sanitizeAttributes(Object.assign(attributes, samplingResult.attributes)); + const span = new SpanImpl({ + resource: this._resource, + scope: this.instrumentationScope, + context: context2, + spanContext, + name, + kind: spanKind, + links, + parentSpanContext: validParentSpanContext, + attributes: initAttributes, + startTime: options.startTime, + spanProcessor: this._spanProcessor, + spanLimits: this._spanLimits + }); + return span; + } + startActiveSpan(name, arg2, arg3, arg4) { + let opts; + let ctx; + let fn; + if (arguments.length < 2) { + return; + } else if (arguments.length === 2) { + fn = arg2; + } else if (arguments.length === 3) { + opts = arg2; + fn = arg3; + } else { + opts = arg2; + ctx = arg3; + fn = arg4; + } + const parentContext = ctx ?? srcExports$l.context.active(); + const span = this.startSpan(name, opts, parentContext); + const contextWithSpanSet = srcExports$l.trace.setSpan(parentContext, span); + return srcExports$l.context.with(contextWithSpanSet, fn, void 0, span); + } + /** Returns the active {@link GeneralLimits}. */ + getGeneralLimits() { + return this._generalLimits; + } + /** Returns the active {@link SpanLimits}. */ + getSpanLimits() { + return this._spanLimits; + } +} +class MultiSpanProcessor { + _spanProcessors; + constructor(_spanProcessors) { + this._spanProcessors = _spanProcessors; + } + forceFlush() { + const promises = []; + for (const spanProcessor of this._spanProcessors) { + promises.push(spanProcessor.forceFlush()); + } + return new Promise((resolve) => { + Promise.all(promises).then(() => { + resolve(); + }).catch((error2) => { + globalErrorHandler(error2 || new Error("MultiSpanProcessor: forceFlush failed")); + resolve(); + }); + }); + } + onStart(span, context2) { + for (const spanProcessor of this._spanProcessors) { + spanProcessor.onStart(span, context2); + } + } + onEnd(span) { + for (const spanProcessor of this._spanProcessors) { + spanProcessor.onEnd(span); + } + } + shutdown() { + const promises = []; + for (const spanProcessor of this._spanProcessors) { + promises.push(spanProcessor.shutdown()); + } + return new Promise((resolve, reject) => { + Promise.all(promises).then(() => { + resolve(); + }, reject); + }); + } +} +var ForceFlushState; +(function(ForceFlushState2) { + ForceFlushState2[ForceFlushState2["resolved"] = 0] = "resolved"; + ForceFlushState2[ForceFlushState2["timeout"] = 1] = "timeout"; + ForceFlushState2[ForceFlushState2["error"] = 2] = "error"; + ForceFlushState2[ForceFlushState2["unresolved"] = 3] = "unresolved"; +})(ForceFlushState || (ForceFlushState = {})); +class BasicTracerProvider { + _config; + _tracers = /* @__PURE__ */ new Map(); + _resource; + _activeSpanProcessor; + constructor(config2 = {}) { + const mergedConfig = merge({}, loadDefaultConfig(), reconfigureLimits(config2)); + this._resource = mergedConfig.resource ?? defaultResource(); + this._config = Object.assign({}, mergedConfig, { + resource: this._resource + }); + const spanProcessors = []; + if (config2.spanProcessors?.length) { + spanProcessors.push(...config2.spanProcessors); + } + this._activeSpanProcessor = new MultiSpanProcessor(spanProcessors); + } + getTracer(name, version2, options) { + const key = `${name}@${version2 || ""}:${options?.schemaUrl || ""}`; + if (!this._tracers.has(key)) { + this._tracers.set(key, new Tracer({ name, version: version2, schemaUrl: options?.schemaUrl }, this._config, this._resource, this._activeSpanProcessor)); + } + return this._tracers.get(key); + } + forceFlush() { + const timeout = this._config.forceFlushTimeoutMillis; + const promises = this._activeSpanProcessor["_spanProcessors"].map((spanProcessor) => { + return new Promise((resolve) => { + let state; + const timeoutInterval = setTimeout(() => { + resolve(new Error(`Span processor did not completed within timeout period of ${timeout} ms`)); + state = ForceFlushState.timeout; + }, timeout); + spanProcessor.forceFlush().then(() => { + clearTimeout(timeoutInterval); + if (state !== ForceFlushState.timeout) { + state = ForceFlushState.resolved; + resolve(state); + } + }).catch((error2) => { + clearTimeout(timeoutInterval); + state = ForceFlushState.error; + resolve(error2); + }); + }); + }); + return new Promise((resolve, reject) => { + Promise.all(promises).then((results) => { + const errors = results.filter((result) => result !== ForceFlushState.resolved); + if (errors.length > 0) { + reject(errors); + } else { + resolve(); + } + }).catch((error2) => reject([error2])); + }); + } + shutdown() { + return this._activeSpanProcessor.shutdown(); + } +} +const SEMANTIC_ATTRIBUTE_SENTRY_PARENT_IS_REMOTE = "sentry.parentIsRemote"; +const SEMANTIC_ATTRIBUTE_SENTRY_GRAPHQL_OPERATION = "sentry.graphql.operation"; +function getParentSpanId(span) { + if ("parentSpanId" in span) { + return span.parentSpanId; + } else if ("parentSpanContext" in span) { + return span.parentSpanContext?.spanId; + } + return void 0; +} +function spanHasAttributes(span) { + const castSpan = span; + return !!castSpan.attributes && typeof castSpan.attributes === "object"; +} +function spanHasKind(span) { + const castSpan = span; + return typeof castSpan.kind === "number"; +} +function spanHasStatus(span) { + const castSpan = span; + return !!castSpan.status; +} +function spanHasName(span) { + const castSpan = span; + return !!castSpan.name; +} +function getRequestSpanData(span) { + if (!spanHasAttributes(span)) { + return {}; + } + const maybeUrlAttribute = span.attributes[srcExports$k.ATTR_URL_FULL] || span.attributes[srcExports$k.SEMATTRS_HTTP_URL]; + const data = { + url: maybeUrlAttribute, + // eslint-disable-next-line deprecation/deprecation + "http.method": span.attributes[srcExports$k.ATTR_HTTP_REQUEST_METHOD] || span.attributes[srcExports$k.SEMATTRS_HTTP_METHOD] + }; + if (!data["http.method"] && data.url) { + data["http.method"] = "GET"; + } + try { + if (typeof maybeUrlAttribute === "string") { + const url = parseUrl(maybeUrlAttribute); + data.url = getSanitizedUrlString(url); + if (url.search) { + data["http.query"] = url.search; + } + if (url.hash) { + data["http.fragment"] = url.hash; + } + } + } catch { + } + return data; +} +function getSpanKind(span) { + if (spanHasKind(span)) { + return span.kind; + } + return srcExports$l.SpanKind.INTERNAL; +} +const SENTRY_TRACE_HEADER$1 = "sentry-trace"; +const SENTRY_BAGGAGE_HEADER$1 = "baggage"; +const SENTRY_TRACE_STATE_DSC = "sentry.dsc"; +const SENTRY_TRACE_STATE_SAMPLED_NOT_RECORDING = "sentry.sampled_not_recording"; +const SENTRY_TRACE_STATE_URL = "sentry.url"; +const SENTRY_TRACE_STATE_SAMPLE_RAND = "sentry.sample_rand"; +const SENTRY_TRACE_STATE_SAMPLE_RATE = "sentry.sample_rate"; +const SENTRY_SCOPES_CONTEXT_KEY = srcExports$l.createContextKey("sentry_scopes"); +const SENTRY_FORK_ISOLATION_SCOPE_CONTEXT_KEY = srcExports$l.createContextKey("sentry_fork_isolation_scope"); +const SENTRY_FORK_SET_SCOPE_CONTEXT_KEY = srcExports$l.createContextKey("sentry_fork_set_scope"); +const SENTRY_FORK_SET_ISOLATION_SCOPE_CONTEXT_KEY = srcExports$l.createContextKey("sentry_fork_set_isolation_scope"); +const SCOPE_CONTEXT_FIELD = "_scopeContext"; +function getScopesFromContext(context2) { + return context2.getValue(SENTRY_SCOPES_CONTEXT_KEY); +} +function setScopesOnContext(context2, scopes) { + return context2.setValue(SENTRY_SCOPES_CONTEXT_KEY, scopes); +} +function setContextOnScope(scope, context2) { + addNonEnumerableProperty(scope, SCOPE_CONTEXT_FIELD, context2); +} +function getContextFromScope(scope) { + return scope[SCOPE_CONTEXT_FIELD]; +} +function getSamplingDecision(spanContext) { + const { traceFlags, traceState } = spanContext; + const sampledNotRecording = traceState ? traceState.get(SENTRY_TRACE_STATE_SAMPLED_NOT_RECORDING) === "1" : false; + if (traceFlags === srcExports$l.TraceFlags.SAMPLED) { + return true; + } + if (sampledNotRecording) { + return false; + } + const dscString = traceState ? traceState.get(SENTRY_TRACE_STATE_DSC) : void 0; + const dsc = dscString ? baggageHeaderToDynamicSamplingContext(dscString) : void 0; + if (dsc?.sampled === "true") { + return true; + } + if (dsc?.sampled === "false") { + return false; + } + return void 0; +} +function inferSpanData(spanName, attributes, kind) { + const httpMethod = attributes[srcExports$k.ATTR_HTTP_REQUEST_METHOD] || attributes[srcExports$k.SEMATTRS_HTTP_METHOD]; + if (httpMethod) { + return descriptionForHttpMethod({ attributes, name: spanName, kind }, httpMethod); + } + const dbSystem = attributes[srcExports$k.SEMATTRS_DB_SYSTEM]; + const opIsCache = typeof attributes[SEMANTIC_ATTRIBUTE_SENTRY_OP] === "string" && attributes[SEMANTIC_ATTRIBUTE_SENTRY_OP].startsWith("cache."); + if (dbSystem && !opIsCache) { + return descriptionForDbSystem({ attributes, name: spanName }); + } + const customSourceOrRoute = attributes[SEMANTIC_ATTRIBUTE_SENTRY_SOURCE] === "custom" ? "custom" : "route"; + const rpcService = attributes[srcExports$k.SEMATTRS_RPC_SERVICE]; + if (rpcService) { + return { + ...getUserUpdatedNameAndSource(spanName, attributes, "route"), + op: "rpc" + }; + } + const messagingSystem = attributes[srcExports$k.SEMATTRS_MESSAGING_SYSTEM]; + if (messagingSystem) { + return { + ...getUserUpdatedNameAndSource(spanName, attributes, customSourceOrRoute), + op: "message" + }; + } + const faasTrigger = attributes[srcExports$k.SEMATTRS_FAAS_TRIGGER]; + if (faasTrigger) { + return { + ...getUserUpdatedNameAndSource(spanName, attributes, customSourceOrRoute), + op: faasTrigger.toString() + }; + } + return { op: void 0, description: spanName, source: "custom" }; +} +function parseSpanDescription(span) { + const attributes = spanHasAttributes(span) ? span.attributes : {}; + const name = spanHasName(span) ? span.name : ""; + const kind = getSpanKind(span); + return inferSpanData(name, attributes, kind); +} +function descriptionForDbSystem({ attributes, name }) { + const userDefinedName = attributes[SEMANTIC_ATTRIBUTE_SENTRY_CUSTOM_SPAN_NAME]; + if (typeof userDefinedName === "string") { + return { + op: "db", + description: userDefinedName, + source: attributes[SEMANTIC_ATTRIBUTE_SENTRY_SOURCE] || "custom" + }; + } + if (attributes[SEMANTIC_ATTRIBUTE_SENTRY_SOURCE] === "custom") { + return { op: "db", description: name, source: "custom" }; + } + const statement = attributes[srcExports$k.SEMATTRS_DB_STATEMENT]; + const description = statement ? statement.toString() : name; + return { op: "db", description, source: "task" }; +} +function descriptionForHttpMethod({ name, kind, attributes }, httpMethod) { + const opParts = ["http"]; + switch (kind) { + case srcExports$l.SpanKind.CLIENT: + opParts.push("client"); + break; + case srcExports$l.SpanKind.SERVER: + opParts.push("server"); + break; + } + if (attributes["sentry.http.prefetch"]) { + opParts.push("prefetch"); + } + const { urlPath, url, query, fragment, hasRoute } = getSanitizedUrl(attributes, kind); + if (!urlPath) { + return { ...getUserUpdatedNameAndSource(name, attributes), op: opParts.join(".") }; + } + const graphqlOperationsAttribute = attributes[SEMANTIC_ATTRIBUTE_SENTRY_GRAPHQL_OPERATION]; + const baseDescription = `${httpMethod} ${urlPath}`; + const inferredDescription = graphqlOperationsAttribute ? `${baseDescription} (${getGraphqlOperationNamesFromAttribute$1(graphqlOperationsAttribute)})` : baseDescription; + const inferredSource = hasRoute || urlPath === "/" ? "route" : "url"; + const data = {}; + if (url) { + data.url = url; + } + if (query) { + data["http.query"] = query; + } + if (fragment) { + data["http.fragment"] = fragment; + } + const isClientOrServerKind = kind === srcExports$l.SpanKind.CLIENT || kind === srcExports$l.SpanKind.SERVER; + const origin = attributes[SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN] || "manual"; + const isManualSpan = !`${origin}`.startsWith("auto"); + const alreadyHasCustomSource = attributes[SEMANTIC_ATTRIBUTE_SENTRY_SOURCE] === "custom"; + const customSpanName = attributes[SEMANTIC_ATTRIBUTE_SENTRY_CUSTOM_SPAN_NAME]; + const useInferredDescription = !alreadyHasCustomSource && customSpanName == null && (isClientOrServerKind || !isManualSpan); + const { description, source } = useInferredDescription ? { description: inferredDescription, source: inferredSource } : getUserUpdatedNameAndSource(name, attributes); + return { + op: opParts.join("."), + description, + source, + data + }; +} +function getGraphqlOperationNamesFromAttribute$1(attr) { + if (Array.isArray(attr)) { + const sorted = attr.slice().sort(); + if (sorted.length <= 5) { + return sorted.join(", "); + } else { + return `${sorted.slice(0, 5).join(", ")}, +${sorted.length - 5}`; + } + } + return `${attr}`; +} +function getSanitizedUrl(attributes, kind) { + const httpTarget = attributes[srcExports$k.SEMATTRS_HTTP_TARGET]; + const httpUrl = attributes[srcExports$k.SEMATTRS_HTTP_URL] || attributes[srcExports$k.ATTR_URL_FULL]; + const httpRoute = attributes[srcExports$k.ATTR_HTTP_ROUTE]; + const parsedUrl = typeof httpUrl === "string" ? parseUrl(httpUrl) : void 0; + const url = parsedUrl ? getSanitizedUrlString(parsedUrl) : void 0; + const query = parsedUrl?.search || void 0; + const fragment = parsedUrl?.hash || void 0; + if (typeof httpRoute === "string") { + return { urlPath: httpRoute, url, query, fragment, hasRoute: true }; + } + if (kind === srcExports$l.SpanKind.SERVER && typeof httpTarget === "string") { + return { urlPath: stripUrlQueryAndFragment(httpTarget), url, query, fragment, hasRoute: false }; + } + if (parsedUrl) { + return { urlPath: url, url, query, fragment, hasRoute: false }; + } + if (typeof httpTarget === "string") { + return { urlPath: stripUrlQueryAndFragment(httpTarget), url, query, fragment, hasRoute: false }; + } + return { urlPath: void 0, url, query, fragment, hasRoute: false }; +} +function getUserUpdatedNameAndSource(originalName, attributes, fallbackSource = "custom") { + const source = attributes[SEMANTIC_ATTRIBUTE_SENTRY_SOURCE] || fallbackSource; + const description = attributes[SEMANTIC_ATTRIBUTE_SENTRY_CUSTOM_SPAN_NAME]; + if (description && typeof description === "string") { + return { + description, + source + }; + } + return { description: originalName, source }; +} +function enhanceDscWithOpenTelemetryRootSpanName(client) { + client.on("createDsc", (dsc, rootSpan) => { + if (!rootSpan) { + return; + } + const jsonSpan = spanToJSON(rootSpan); + const attributes = jsonSpan.data; + const source = attributes[SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]; + const { description } = spanHasName(rootSpan) ? parseSpanDescription(rootSpan) : { description: void 0 }; + if (source !== "url" && description) { + dsc.transaction = description; + } + if (hasSpansEnabled()) { + const sampled = getSamplingDecision(rootSpan.spanContext()); + dsc.sampled = sampled == void 0 ? void 0 : String(sampled); + } + }); +} +function getActiveSpan() { + return srcExports$l.trace.getActiveSpan(); +} +const DEBUG_BUILD$1 = typeof __SENTRY_DEBUG__ === "undefined" || __SENTRY_DEBUG__; +function makeTraceState({ + dsc, + sampled +}) { + const dscString = dsc ? dynamicSamplingContextToSentryBaggageHeader(dsc) : void 0; + const traceStateBase = new TraceState(); + const traceStateWithDsc = dscString ? traceStateBase.set(SENTRY_TRACE_STATE_DSC, dscString) : traceStateBase; + return sampled === false ? traceStateWithDsc.set(SENTRY_TRACE_STATE_SAMPLED_NOT_RECORDING, "1") : traceStateWithDsc; +} +const setupElements = /* @__PURE__ */ new Set(); +function openTelemetrySetupCheck() { + return Array.from(setupElements); +} +function setIsSetup(element) { + setupElements.add(element); +} +class SentryPropagator extends W3CBaggagePropagator { + /** A map of URLs that have already been checked for if they match tracePropagationTargets. */ + constructor() { + super(); + setIsSetup("SentryPropagator"); + this._urlMatchesTargetsMap = new LRUMap(100); + } + /** + * @inheritDoc + */ + inject(context2, carrier, setter) { + if (isTracingSuppressed(context2)) { + DEBUG_BUILD$1 && debug$2.log("[Tracing] Not injecting trace data for url because tracing is suppressed."); + return; + } + const activeSpan = srcExports$l.trace.getSpan(context2); + const url = activeSpan && getCurrentURL(activeSpan); + const { tracePropagationTargets, propagateTraceparent } = getClient()?.getOptions() || {}; + if (!shouldPropagateTraceForUrl(url, tracePropagationTargets, this._urlMatchesTargetsMap)) { + DEBUG_BUILD$1 && debug$2.log("[Tracing] Not injecting trace data for url because it does not match tracePropagationTargets:", url); + return; + } + const existingBaggageHeader = getExistingBaggage(carrier); + let baggage = srcExports$l.propagation.getBaggage(context2) || srcExports$l.propagation.createBaggage({}); + const { dynamicSamplingContext, traceId, spanId, sampled } = getInjectionData(context2); + if (existingBaggageHeader) { + const baggageEntries = parseBaggageHeader(existingBaggageHeader); + if (baggageEntries) { + Object.entries(baggageEntries).forEach(([key, value]) => { + baggage = baggage.setEntry(key, { value }); + }); + } + } + if (dynamicSamplingContext) { + baggage = Object.entries(dynamicSamplingContext).reduce((b, [dscKey, dscValue]) => { + if (dscValue) { + return b.setEntry(`${SENTRY_BAGGAGE_KEY_PREFIX}${dscKey}`, { value: dscValue }); + } + return b; + }, baggage); + } + if (traceId && traceId !== srcExports$l.INVALID_TRACEID) { + setter.set(carrier, SENTRY_TRACE_HEADER$1, generateSentryTraceHeader(traceId, spanId, sampled)); + if (propagateTraceparent) { + setter.set(carrier, "traceparent", generateTraceparentHeader(traceId, spanId, sampled)); + } + } + super.inject(srcExports$l.propagation.setBaggage(context2, baggage), carrier, setter); + } + /** + * @inheritDoc + */ + extract(context2, carrier, getter) { + const maybeSentryTraceHeader = getter.get(carrier, SENTRY_TRACE_HEADER$1); + const baggage = getter.get(carrier, SENTRY_BAGGAGE_HEADER$1); + const sentryTrace = maybeSentryTraceHeader ? Array.isArray(maybeSentryTraceHeader) ? maybeSentryTraceHeader[0] : maybeSentryTraceHeader : void 0; + return ensureScopesOnContext(getContextWithRemoteActiveSpan(context2, { sentryTrace, baggage })); + } + /** + * @inheritDoc + */ + fields() { + return [SENTRY_TRACE_HEADER$1, SENTRY_BAGGAGE_HEADER$1, "traceparent"]; + } +} +const NOT_PROPAGATED_MESSAGE = "[Tracing] Not injecting trace data for url because it does not match tracePropagationTargets:"; +function shouldPropagateTraceForUrl(url, tracePropagationTargets, decisionMap) { + if (typeof url !== "string" || !tracePropagationTargets) { + return true; + } + const cachedDecision = decisionMap?.get(url); + if (cachedDecision !== void 0) { + DEBUG_BUILD$1 && !cachedDecision && debug$2.log(NOT_PROPAGATED_MESSAGE, url); + return cachedDecision; + } + const decision = stringMatchesSomePattern(url, tracePropagationTargets); + decisionMap?.set(url, decision); + DEBUG_BUILD$1 && !decision && debug$2.log(NOT_PROPAGATED_MESSAGE, url); + return decision; +} +function getInjectionData(context2, options = {}) { + const span = srcExports$l.trace.getSpan(context2); + if (span?.spanContext().isRemote) { + const spanContext = span.spanContext(); + const dynamicSamplingContext2 = getDynamicSamplingContextFromSpan(span); + return { + dynamicSamplingContext: dynamicSamplingContext2, + traceId: spanContext.traceId, + spanId: void 0, + sampled: getSamplingDecision(spanContext) + // TODO: Do we need to change something here? + }; + } + if (span) { + const spanContext = span.spanContext(); + const dynamicSamplingContext2 = getDynamicSamplingContextFromSpan(span); + return { + dynamicSamplingContext: dynamicSamplingContext2, + traceId: spanContext.traceId, + spanId: spanContext.spanId, + sampled: getSamplingDecision(spanContext) + // TODO: Do we need to change something here? + }; + } + const scope = options.scope || getScopesFromContext(context2)?.scope || getCurrentScope(); + const client = options.client || getClient(); + const propagationContext = scope.getPropagationContext(); + const dynamicSamplingContext = client ? getDynamicSamplingContextFromScope(client, scope) : void 0; + return { + dynamicSamplingContext, + traceId: propagationContext.traceId, + spanId: propagationContext.propagationSpanId, + sampled: propagationContext.sampled + }; +} +function getContextWithRemoteActiveSpan(ctx, { sentryTrace, baggage }) { + const propagationContext = propagationContextFromHeaders(sentryTrace, baggage); + const { traceId, parentSpanId, sampled, dsc } = propagationContext; + const client = getClient(); + const incomingDsc = baggageHeaderToDynamicSamplingContext(baggage); + if (!parentSpanId || client && !shouldContinueTrace(client, incomingDsc?.org_id)) { + return ctx; + } + const spanContext = generateRemoteSpanContext({ + traceId, + spanId: parentSpanId, + sampled, + dsc + }); + return srcExports$l.trace.setSpanContext(ctx, spanContext); +} +function continueTraceAsRemoteSpan(ctx, options, callback) { + const ctxWithSpanContext = ensureScopesOnContext(getContextWithRemoteActiveSpan(ctx, options)); + return srcExports$l.context.with(ctxWithSpanContext, callback); +} +function ensureScopesOnContext(ctx) { + const scopes = getScopesFromContext(ctx); + const newScopes = { + // If we have no scope here, this is most likely either the root context or a context manually derived from it + // In this case, we want to fork the current scope, to ensure we do not pollute the root scope + scope: scopes ? scopes.scope : getCurrentScope().clone(), + isolationScope: scopes ? scopes.isolationScope : getIsolationScope() + }; + return setScopesOnContext(ctx, newScopes); +} +function getExistingBaggage(carrier) { + try { + const baggage = carrier[SENTRY_BAGGAGE_HEADER$1]; + return Array.isArray(baggage) ? baggage.join(",") : baggage; + } catch { + return void 0; + } +} +function getCurrentURL(span) { + const spanData = spanToJSON(span).data; + const urlAttribute = spanData[srcExports$k.SEMATTRS_HTTP_URL] || spanData[srcExports$k.ATTR_URL_FULL]; + if (typeof urlAttribute === "string") { + return urlAttribute; + } + const urlTraceState = span.spanContext().traceState?.get(SENTRY_TRACE_STATE_URL); + if (urlTraceState) { + return urlTraceState; + } + return void 0; +} +function generateRemoteSpanContext({ + spanId, + traceId, + sampled, + dsc +}) { + const traceState = makeTraceState({ + dsc, + sampled + }); + const spanContext = { + traceId, + spanId, + isRemote: true, + traceFlags: sampled ? srcExports$l.TraceFlags.SAMPLED : srcExports$l.TraceFlags.NONE, + traceState + }; + return spanContext; +} +function _startSpan(options, callback, autoEnd) { + const tracer = getTracer(); + const { name, parentSpan: customParentSpan } = options; + const wrapper = getActiveSpanWrapper(customParentSpan); + return wrapper(() => { + const activeCtx = getContext(options.scope, options.forceTransaction); + const shouldSkipSpan = options.onlyIfParent && !srcExports$l.trace.getSpan(activeCtx); + const ctx = shouldSkipSpan ? suppressTracing$1(activeCtx) : activeCtx; + const spanOptions = getSpanOptions(options); + if (!hasSpansEnabled()) { + const suppressedCtx = isTracingSuppressed(ctx) ? ctx : suppressTracing$1(ctx); + return srcExports$l.context.with(suppressedCtx, () => { + return tracer.startActiveSpan(name, spanOptions, suppressedCtx, (span) => { + return srcExports$l.context.with(activeCtx, () => { + return handleCallbackErrors( + () => callback(span), + () => { + if (spanToJSON(span).status === void 0) { + span.setStatus({ code: srcExports$l.SpanStatusCode.ERROR }); + } + }, + autoEnd ? () => span.end() : void 0 + ); + }); + }); + }); + } + return tracer.startActiveSpan(name, spanOptions, ctx, (span) => { + return handleCallbackErrors( + () => callback(span), + () => { + if (spanToJSON(span).status === void 0) { + span.setStatus({ code: srcExports$l.SpanStatusCode.ERROR }); + } + }, + autoEnd ? () => span.end() : void 0 + ); + }); + }); +} +function startSpan$1(options, callback) { + return _startSpan(options, callback, true); +} +function startSpanManual(options, callback) { + return _startSpan(options, (span) => callback(span, () => span.end()), false); +} +function startInactiveSpan(options) { + const tracer = getTracer(); + const { name, parentSpan: customParentSpan } = options; + const wrapper = getActiveSpanWrapper(customParentSpan); + return wrapper(() => { + const activeCtx = getContext(options.scope, options.forceTransaction); + const shouldSkipSpan = options.onlyIfParent && !srcExports$l.trace.getSpan(activeCtx); + let ctx = shouldSkipSpan ? suppressTracing$1(activeCtx) : activeCtx; + const spanOptions = getSpanOptions(options); + if (!hasSpansEnabled()) { + ctx = isTracingSuppressed(ctx) ? ctx : suppressTracing$1(ctx); + } + return tracer.startSpan(name, spanOptions, ctx); + }); +} +function withActiveSpan(span, callback) { + const newContextWithActiveSpan = span ? srcExports$l.trace.setSpan(srcExports$l.context.active(), span) : srcExports$l.trace.deleteSpan(srcExports$l.context.active()); + return srcExports$l.context.with(newContextWithActiveSpan, () => callback(getCurrentScope())); +} +function getTracer() { + const client = getClient(); + return client?.tracer || srcExports$l.trace.getTracer("@sentry/opentelemetry", SDK_VERSION); +} +function getSpanOptions(options) { + const { startTime, attributes, kind, op, links } = options; + const fixedStartTime = typeof startTime === "number" ? ensureTimestampInMilliseconds(startTime) : startTime; + return { + attributes: op ? { + [SEMANTIC_ATTRIBUTE_SENTRY_OP]: op, + ...attributes + } : attributes, + kind, + links, + startTime: fixedStartTime + }; +} +function ensureTimestampInMilliseconds(timestamp) { + const isMs = timestamp < 9999999999; + return isMs ? timestamp * 1e3 : timestamp; +} +function getContext(scope, forceTransaction) { + const ctx = getContextForScope(scope); + const parentSpan = srcExports$l.trace.getSpan(ctx); + if (!parentSpan) { + return ctx; + } + if (!forceTransaction) { + return ctx; + } + const ctxWithoutSpan = srcExports$l.trace.deleteSpan(ctx); + const { spanId, traceId } = parentSpan.spanContext(); + const sampled = getSamplingDecision(parentSpan.spanContext()); + const rootSpan = getRootSpan(parentSpan); + const dsc = getDynamicSamplingContextFromSpan(rootSpan); + const traceState = makeTraceState({ + dsc, + sampled + }); + const spanOptions = { + traceId, + spanId, + isRemote: true, + traceFlags: sampled ? srcExports$l.TraceFlags.SAMPLED : srcExports$l.TraceFlags.NONE, + traceState + }; + const ctxWithSpanContext = srcExports$l.trace.setSpanContext(ctxWithoutSpan, spanOptions); + return ctxWithSpanContext; +} +function getContextForScope(scope) { + if (scope) { + const ctx = getContextFromScope(scope); + if (ctx) { + return ctx; + } + } + return srcExports$l.context.active(); +} +function continueTrace(options, callback) { + return continueTraceAsRemoteSpan(srcExports$l.context.active(), options, callback); +} +function getTraceContextForScope(client, scope) { + const ctx = getContextFromScope(scope); + const span = ctx && srcExports$l.trace.getSpan(ctx); + const traceContext = span ? spanToTraceContext(span) : getTraceContextFromScope(scope); + const dynamicSamplingContext = span ? getDynamicSamplingContextFromSpan(span) : getDynamicSamplingContextFromScope(client, scope); + return [dynamicSamplingContext, traceContext]; +} +function getActiveSpanWrapper(parentSpan) { + return parentSpan !== void 0 ? (callback) => { + return withActiveSpan(parentSpan, callback); + } : (callback) => callback(); +} +function suppressTracing(callback) { + const ctx = suppressTracing$1(srcExports$l.context.active()); + return srcExports$l.context.with(ctx, callback); +} +function setupEventContextTrace(client) { + client.on("preprocessEvent", (event) => { + const span = getActiveSpan(); + if (!span || event.type === "transaction") { + return; + } + event.contexts = { + trace: spanToTraceContext(span), + ...event.contexts + }; + const rootSpan = getRootSpan(span); + event.sdkProcessingMetadata = { + dynamicSamplingContext: getDynamicSamplingContextFromSpan(rootSpan), + ...event.sdkProcessingMetadata + }; + return event; + }); +} +function getTraceData({ + span, + scope, + client, + propagateTraceparent +} = {}) { + let ctx = (scope && getContextFromScope(scope)) ?? srcExports$l.context.active(); + if (span) { + const { scope: scope2 } = getCapturedScopesOnSpan(span); + ctx = scope2 && getContextFromScope(scope2) || srcExports$l.trace.setSpan(srcExports$l.context.active(), span); + } + const { traceId, spanId, sampled, dynamicSamplingContext } = getInjectionData(ctx, { scope, client }); + const traceData = { + "sentry-trace": generateSentryTraceHeader(traceId, spanId, sampled), + baggage: dynamicSamplingContextToSentryBaggageHeader(dynamicSamplingContext) + }; + if (propagateTraceparent) { + traceData.traceparent = generateTraceparentHeader(traceId, spanId, sampled); + } + return traceData; +} +function setOpenTelemetryContextAsyncContextStrategy() { + function getScopes() { + const ctx = srcExports$l.context.active(); + const scopes = getScopesFromContext(ctx); + if (scopes) { + return scopes; + } + return { + scope: getDefaultCurrentScope(), + isolationScope: getDefaultIsolationScope() + }; + } + function withScope2(callback) { + const ctx = srcExports$l.context.active(); + return srcExports$l.context.with(ctx, () => { + return callback(getCurrentScope2()); + }); + } + function withSetScope(scope, callback) { + const ctx = getContextFromScope(scope) || srcExports$l.context.active(); + return srcExports$l.context.with(ctx.setValue(SENTRY_FORK_SET_SCOPE_CONTEXT_KEY, scope), () => { + return callback(scope); + }); + } + function withIsolationScope2(callback) { + const ctx = srcExports$l.context.active(); + return srcExports$l.context.with(ctx.setValue(SENTRY_FORK_ISOLATION_SCOPE_CONTEXT_KEY, true), () => { + return callback(getIsolationScope2()); + }); + } + function withSetIsolationScope(isolationScope, callback) { + const ctx = srcExports$l.context.active(); + return srcExports$l.context.with(ctx.setValue(SENTRY_FORK_SET_ISOLATION_SCOPE_CONTEXT_KEY, isolationScope), () => { + return callback(getIsolationScope2()); + }); + } + function getCurrentScope2() { + return getScopes().scope; + } + function getIsolationScope2() { + return getScopes().isolationScope; + } + setAsyncContextStrategy({ + withScope: withScope2, + withSetScope, + withSetIsolationScope, + withIsolationScope: withIsolationScope2, + getCurrentScope: getCurrentScope2, + getIsolationScope: getIsolationScope2, + startSpan: startSpan$1, + startSpanManual, + startInactiveSpan, + getActiveSpan, + suppressTracing, + getTraceData, + continueTrace, + // The types here don't fully align, because our own `Span` type is narrower + // than the OTEL one - but this is OK for here, as we now we'll only have OTEL spans passed around + withActiveSpan + }); +} +function wrapContextManagerClass(ContextManagerClass) { + class SentryContextManager2 extends ContextManagerClass { + constructor(...args) { + super(...args); + setIsSetup("SentryContextManager"); + } + /** + * Overwrite with() of the original AsyncLocalStorageContextManager + * to ensure we also create new scopes per context. + */ + with(context2, fn, thisArg, ...args) { + const currentScopes = getScopesFromContext(context2); + const currentScope = currentScopes?.scope || getCurrentScope(); + const currentIsolationScope = currentScopes?.isolationScope || getIsolationScope(); + const shouldForkIsolationScope = context2.getValue(SENTRY_FORK_ISOLATION_SCOPE_CONTEXT_KEY) === true; + const scope = context2.getValue(SENTRY_FORK_SET_SCOPE_CONTEXT_KEY); + const isolationScope = context2.getValue(SENTRY_FORK_SET_ISOLATION_SCOPE_CONTEXT_KEY); + const newCurrentScope = scope || currentScope.clone(); + const newIsolationScope = isolationScope || (shouldForkIsolationScope ? currentIsolationScope.clone() : currentIsolationScope); + const scopes = { scope: newCurrentScope, isolationScope: newIsolationScope }; + const ctx1 = setScopesOnContext(context2, scopes); + const ctx2 = ctx1.deleteValue(SENTRY_FORK_ISOLATION_SCOPE_CONTEXT_KEY).deleteValue(SENTRY_FORK_SET_SCOPE_CONTEXT_KEY).deleteValue(SENTRY_FORK_SET_ISOLATION_SCOPE_CONTEXT_KEY); + setContextOnScope(newCurrentScope, ctx2); + return super.with(ctx2, fn, thisArg, ...args); + } + /** + * Gets underlying AsyncLocalStorage and symbol to allow lookup of scope. + */ + getAsyncLocalStorageLookup() { + return { + // @ts-expect-error This is on the base class, but not part of the interface + asyncLocalStorage: this._asyncLocalStorage, + contextSymbol: SENTRY_SCOPES_CONTEXT_KEY + }; + } + } + return SentryContextManager2; +} +function groupSpansWithParents(spans) { + const nodeMap = /* @__PURE__ */ new Map(); + for (const span of spans) { + createOrUpdateSpanNodeAndRefs(nodeMap, span); + } + return Array.from(nodeMap, function([_id, spanNode]) { + return spanNode; + }); +} +function getLocalParentId(span) { + const parentIsRemote = span.attributes[SEMANTIC_ATTRIBUTE_SENTRY_PARENT_IS_REMOTE] === true; + return !parentIsRemote ? getParentSpanId(span) : void 0; +} +function createOrUpdateSpanNodeAndRefs(nodeMap, span) { + const id = span.spanContext().spanId; + const parentId = getLocalParentId(span); + if (!parentId) { + createOrUpdateNode(nodeMap, { id, span, children: [] }); + return; + } + const parentNode = createOrGetParentNode(nodeMap, parentId); + const node2 = createOrUpdateNode(nodeMap, { id, span, parentNode, children: [] }); + parentNode.children.push(node2); +} +function createOrGetParentNode(nodeMap, id) { + const existing = nodeMap.get(id); + if (existing) { + return existing; + } + return createOrUpdateNode(nodeMap, { id, children: [] }); +} +function createOrUpdateNode(nodeMap, spanNode) { + const existing = nodeMap.get(spanNode.id); + if (existing?.span) { + return existing; + } + if (existing && !existing.span) { + existing.span = spanNode.span; + existing.parentNode = spanNode.parentNode; + return existing; + } + nodeMap.set(spanNode.id, spanNode); + return spanNode; +} +const canonicalGrpcErrorCodesMap = { + "1": "cancelled", + "2": "unknown_error", + "3": "invalid_argument", + "4": "deadline_exceeded", + "5": "not_found", + "6": "already_exists", + "7": "permission_denied", + "8": "resource_exhausted", + "9": "failed_precondition", + "10": "aborted", + "11": "out_of_range", + "12": "unimplemented", + "13": "internal_error", + "14": "unavailable", + "15": "data_loss", + "16": "unauthenticated" +}; +const isStatusErrorMessageValid = (message) => { + return Object.values(canonicalGrpcErrorCodesMap).includes(message); +}; +function mapStatus(span) { + const attributes = spanHasAttributes(span) ? span.attributes : {}; + const status2 = spanHasStatus(span) ? span.status : void 0; + if (status2) { + if (status2.code === srcExports$l.SpanStatusCode.OK) { + return { code: SPAN_STATUS_OK }; + } else if (status2.code === srcExports$l.SpanStatusCode.ERROR) { + if (typeof status2.message === "undefined") { + const inferredStatus2 = inferStatusFromAttributes(attributes); + if (inferredStatus2) { + return inferredStatus2; + } + } + if (status2.message && isStatusErrorMessageValid(status2.message)) { + return { code: SPAN_STATUS_ERROR, message: status2.message }; + } else { + return { code: SPAN_STATUS_ERROR, message: "internal_error" }; + } + } + } + const inferredStatus = inferStatusFromAttributes(attributes); + if (inferredStatus) { + return inferredStatus; + } + if (status2?.code === srcExports$l.SpanStatusCode.UNSET) { + return { code: SPAN_STATUS_OK }; + } else { + return { code: SPAN_STATUS_ERROR, message: "unknown_error" }; + } +} +function inferStatusFromAttributes(attributes) { + const httpCodeAttribute = attributes[srcExports$k.ATTR_HTTP_RESPONSE_STATUS_CODE] || attributes[srcExports$k.SEMATTRS_HTTP_STATUS_CODE]; + const grpcCodeAttribute = attributes[srcExports$k.SEMATTRS_RPC_GRPC_STATUS_CODE]; + const numberHttpCode = typeof httpCodeAttribute === "number" ? httpCodeAttribute : typeof httpCodeAttribute === "string" ? parseInt(httpCodeAttribute) : void 0; + if (typeof numberHttpCode === "number") { + return getSpanStatusFromHttpCode(numberHttpCode); + } + if (typeof grpcCodeAttribute === "string") { + return { code: SPAN_STATUS_ERROR, message: canonicalGrpcErrorCodesMap[grpcCodeAttribute] || "unknown_error" }; + } + return void 0; +} +const MAX_SPAN_COUNT = 1e3; +const DEFAULT_TIMEOUT = 300; +class SentrySpanExporter { + /* + * A quick explanation on the buckets: We do bucketing of finished spans for efficiency. This span exporter is + * accumulating spans until a root span is encountered and then it flushes all the spans that are descendants of that + * root span. Because it is totally in the realm of possibilities that root spans are never finished, and we don't + * want to accumulate spans indefinitely in memory, we need to periodically evacuate spans. Naively we could simply + * store the spans in an array and each time a new span comes in we could iterate through the entire array and + * evacuate all spans that have an end-timestamp that is older than our limit. This could get quite expensive because + * we would have to iterate a potentially large number of spans every time we evacuate. We want to avoid these large + * bursts of computation. + * + * Instead we go for a bucketing approach and put spans into buckets, based on what second + * (modulo the time limit) the span was put into the exporter. With buckets, when we decide to evacuate, we can + * iterate through the bucket entries instead, which have an upper bound of items, making the evacuation much more + * efficient. Cleaning up also becomes much more efficient since it simply involves de-referencing a bucket within the + * bucket array, and letting garbage collection take care of the rest. + */ + // Essentially a a set of span ids that are already sent. The values are expiration + // times in this cache so we don't hold onto them indefinitely. + /* Internally, we use a debounced flush to give some wiggle room to the span processor to accumulate more spans. */ + constructor(options) { + this._finishedSpanBucketSize = options?.timeout || DEFAULT_TIMEOUT; + this._finishedSpanBuckets = new Array(this._finishedSpanBucketSize).fill(void 0); + this._lastCleanupTimestampInS = Math.floor(Date.now() / 1e3); + this._spansToBucketEntry = /* @__PURE__ */ new WeakMap(); + this._sentSpans = /* @__PURE__ */ new Map(); + this._debouncedFlush = debounce(this.flush.bind(this), 1, { maxWait: 100 }); + } + /** + * Export a single span. + * This is called by the span processor whenever a span is ended. + */ + export(span) { + const currentTimestampInS = Math.floor(Date.now() / 1e3); + if (this._lastCleanupTimestampInS !== currentTimestampInS) { + let droppedSpanCount = 0; + this._finishedSpanBuckets.forEach((bucket, i) => { + if (bucket && bucket.timestampInS <= currentTimestampInS - this._finishedSpanBucketSize) { + droppedSpanCount += bucket.spans.size; + this._finishedSpanBuckets[i] = void 0; + } + }); + if (droppedSpanCount > 0) { + DEBUG_BUILD$1 && debug$2.log( + `SpanExporter dropped ${droppedSpanCount} spans because they were pending for more than ${this._finishedSpanBucketSize} seconds.` + ); + } + this._lastCleanupTimestampInS = currentTimestampInS; + } + const currentBucketIndex = currentTimestampInS % this._finishedSpanBucketSize; + const currentBucket = this._finishedSpanBuckets[currentBucketIndex] || { + timestampInS: currentTimestampInS, + spans: /* @__PURE__ */ new Set() + }; + this._finishedSpanBuckets[currentBucketIndex] = currentBucket; + currentBucket.spans.add(span); + this._spansToBucketEntry.set(span, currentBucket); + const localParentId = getLocalParentId(span); + if (!localParentId || this._sentSpans.has(localParentId)) { + this._debouncedFlush(); + } + } + /** + * Try to flush any pending spans immediately. + * This is called internally by the exporter (via _debouncedFlush), + * but can also be triggered externally if we force-flush. + */ + flush() { + const finishedSpans = this._finishedSpanBuckets.flatMap((bucket) => bucket ? Array.from(bucket.spans) : []); + this._flushSentSpanCache(); + const sentSpans = this._maybeSend(finishedSpans); + const sentSpanCount = sentSpans.size; + const remainingOpenSpanCount = finishedSpans.length - sentSpanCount; + DEBUG_BUILD$1 && debug$2.log( + `SpanExporter exported ${sentSpanCount} spans, ${remainingOpenSpanCount} spans are waiting for their parent spans to finish` + ); + const expirationDate = Date.now() + DEFAULT_TIMEOUT * 1e3; + for (const span of sentSpans) { + this._sentSpans.set(span.spanContext().spanId, expirationDate); + const bucketEntry = this._spansToBucketEntry.get(span); + if (bucketEntry) { + bucketEntry.spans.delete(span); + } + } + this._debouncedFlush.cancel(); + } + /** + * Clear the exporter. + * This is called when the span processor is shut down. + */ + clear() { + this._finishedSpanBuckets = this._finishedSpanBuckets.fill(void 0); + this._sentSpans.clear(); + this._debouncedFlush.cancel(); + } + /** + * Send the given spans, but only if they are part of a finished transaction. + * + * Returns the sent spans. + * Spans remain unsent when their parent span is not yet finished. + * This will happen regularly, as child spans are generally finished before their parents. + * But it _could_ also happen because, for whatever reason, a parent span was lost. + * In this case, we'll eventually need to clean this up. + */ + _maybeSend(spans) { + const grouped = groupSpansWithParents(spans); + const sentSpans = /* @__PURE__ */ new Set(); + const rootNodes = this._getCompletedRootNodes(grouped); + for (const root of rootNodes) { + const span = root.span; + sentSpans.add(span); + const transactionEvent = createTransactionForOtelSpan(span); + if (root.parentNode && this._sentSpans.has(root.parentNode.id)) { + const traceData = transactionEvent.contexts?.trace?.data; + if (traceData) { + traceData["sentry.parent_span_already_sent"] = true; + } + } + const spans2 = transactionEvent.spans || []; + for (const child of root.children) { + createAndFinishSpanForOtelSpan(child, spans2, sentSpans); + } + transactionEvent.spans = spans2.length > MAX_SPAN_COUNT ? spans2.sort((a, b) => a.start_timestamp - b.start_timestamp).slice(0, MAX_SPAN_COUNT) : spans2; + const measurements = timedEventsToMeasurements(span.events); + if (measurements) { + transactionEvent.measurements = measurements; + } + captureEvent(transactionEvent); + } + return sentSpans; + } + /** Remove "expired" span id entries from the _sentSpans cache. */ + _flushSentSpanCache() { + const currentTimestamp = Date.now(); + for (const [spanId, expirationTime] of this._sentSpans.entries()) { + if (expirationTime <= currentTimestamp) { + this._sentSpans.delete(spanId); + } + } + } + /** Check if a node is a completed root node or a node whose parent has already been sent */ + _nodeIsCompletedRootNodeOrHasSentParent(node2) { + return !!node2.span && (!node2.parentNode || this._sentSpans.has(node2.parentNode.id)); + } + /** Get all completed root nodes from a list of nodes */ + _getCompletedRootNodes(nodes) { + return nodes.filter((node2) => this._nodeIsCompletedRootNodeOrHasSentParent(node2)); + } +} +function parseSpan(span) { + const attributes = span.attributes; + const origin = attributes[SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]; + const op = attributes[SEMANTIC_ATTRIBUTE_SENTRY_OP]; + const source = attributes[SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]; + return { origin, op, source }; +} +function createTransactionForOtelSpan(span) { + const { op, description, data, origin = "manual", source } = getSpanData(span); + const capturedSpanScopes = getCapturedScopesOnSpan(span); + const sampleRate = span.attributes[SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE]; + const attributes = { + [SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]: source, + [SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE]: sampleRate, + [SEMANTIC_ATTRIBUTE_SENTRY_OP]: op, + [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: origin, + ...data, + ...removeSentryAttributes(span.attributes) + }; + const { links } = span; + const { traceId: trace_id, spanId: span_id } = span.spanContext(); + const parent_span_id = getParentSpanId(span); + const status2 = mapStatus(span); + const traceContext = { + parent_span_id, + span_id, + trace_id, + data: attributes, + origin, + op, + status: getStatusMessage(status2), + // As per protocol, span status is allowed to be undefined + links: convertSpanLinksForEnvelope(links) + }; + const statusCode = attributes[srcExports$k.ATTR_HTTP_RESPONSE_STATUS_CODE]; + const responseContext = typeof statusCode === "number" ? { response: { status_code: statusCode } } : void 0; + const transactionEvent = { + contexts: { + trace: traceContext, + otel: { + resource: span.resource.attributes + }, + ...responseContext + }, + spans: [], + start_timestamp: spanTimeInputToSeconds(span.startTime), + timestamp: spanTimeInputToSeconds(span.endTime), + transaction: description, + type: "transaction", + sdkProcessingMetadata: { + capturedSpanScope: capturedSpanScopes.scope, + capturedSpanIsolationScope: capturedSpanScopes.isolationScope, + sampleRate, + dynamicSamplingContext: getDynamicSamplingContextFromSpan(span) + }, + ...source && { + transaction_info: { + source + } + } + }; + return transactionEvent; +} +function createAndFinishSpanForOtelSpan(node2, spans, sentSpans) { + const span = node2.span; + if (span) { + sentSpans.add(span); + } + const shouldDrop = !span; + if (shouldDrop) { + node2.children.forEach((child) => { + createAndFinishSpanForOtelSpan(child, spans, sentSpans); + }); + return; + } + const span_id = span.spanContext().spanId; + const trace_id = span.spanContext().traceId; + const parentSpanId = getParentSpanId(span); + const { attributes, startTime, endTime, links } = span; + const { op, description, data, origin = "manual" } = getSpanData(span); + const allData = { + [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: origin, + [SEMANTIC_ATTRIBUTE_SENTRY_OP]: op, + ...removeSentryAttributes(attributes), + ...data + }; + const status2 = mapStatus(span); + const spanJSON = { + span_id, + trace_id, + data: allData, + description, + parent_span_id: parentSpanId, + start_timestamp: spanTimeInputToSeconds(startTime), + // This is [0,0] by default in OTEL, in which case we want to interpret this as no end time + timestamp: spanTimeInputToSeconds(endTime) || void 0, + status: getStatusMessage(status2), + // As per protocol, span status is allowed to be undefined + op, + origin, + measurements: timedEventsToMeasurements(span.events), + links: convertSpanLinksForEnvelope(links) + }; + spans.push(spanJSON); + node2.children.forEach((child) => { + createAndFinishSpanForOtelSpan(child, spans, sentSpans); + }); +} +function getSpanData(span) { + const { op: definedOp, source: definedSource, origin } = parseSpan(span); + const { op: inferredOp, description, source: inferredSource, data: inferredData } = parseSpanDescription(span); + const op = definedOp || inferredOp; + const source = definedSource || inferredSource; + const data = { ...inferredData, ...getData(span) }; + return { + op, + description, + source, + origin, + data + }; +} +function removeSentryAttributes(data) { + const cleanedData = { ...data }; + delete cleanedData[SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE]; + delete cleanedData[SEMANTIC_ATTRIBUTE_SENTRY_PARENT_IS_REMOTE]; + delete cleanedData[SEMANTIC_ATTRIBUTE_SENTRY_CUSTOM_SPAN_NAME]; + return cleanedData; +} +function getData(span) { + const attributes = span.attributes; + const data = {}; + if (span.kind !== srcExports$l.SpanKind.INTERNAL) { + data["otel.kind"] = srcExports$l.SpanKind[span.kind]; + } + const maybeHttpStatusCodeAttribute = attributes[srcExports$k.SEMATTRS_HTTP_STATUS_CODE]; + if (maybeHttpStatusCodeAttribute) { + data[srcExports$k.ATTR_HTTP_RESPONSE_STATUS_CODE] = maybeHttpStatusCodeAttribute; + } + const requestData = getRequestSpanData(span); + if (requestData.url) { + data.url = requestData.url; + } + if (requestData["http.query"]) { + data["http.query"] = requestData["http.query"].slice(1); + } + if (requestData["http.fragment"]) { + data["http.fragment"] = requestData["http.fragment"].slice(1); + } + return data; +} +function onSpanStart(span, parentContext) { + const parentSpan = srcExports$l.trace.getSpan(parentContext); + let scopes = getScopesFromContext(parentContext); + if (parentSpan && !parentSpan.spanContext().isRemote) { + addChildSpanToSpan(parentSpan, span); + } + if (parentSpan?.spanContext().isRemote) { + span.setAttribute(SEMANTIC_ATTRIBUTE_SENTRY_PARENT_IS_REMOTE, true); + } + if (parentContext === srcExports$l.ROOT_CONTEXT) { + scopes = { + scope: getDefaultCurrentScope(), + isolationScope: getDefaultIsolationScope() + }; + } + if (scopes) { + setCapturedScopesOnSpan(span, scopes.scope, scopes.isolationScope); + } + logSpanStart(span); + const client = getClient(); + client?.emit("spanStart", span); +} +function onSpanEnd(span) { + logSpanEnd(span); + const client = getClient(); + client?.emit("spanEnd", span); +} +class SentrySpanProcessor { + constructor(options) { + setIsSetup("SentrySpanProcessor"); + this._exporter = new SentrySpanExporter(options); + } + /** + * @inheritDoc + */ + async forceFlush() { + this._exporter.flush(); + } + /** + * @inheritDoc + */ + async shutdown() { + this._exporter.clear(); + } + /** + * @inheritDoc + */ + onStart(span, parentContext) { + onSpanStart(span, parentContext); + } + /** @inheritDoc */ + onEnd(span) { + onSpanEnd(span); + this._exporter.export(span); + } +} +class SentrySampler { + constructor(client) { + this._client = client; + setIsSetup("SentrySampler"); + } + /** @inheritDoc */ + shouldSample(context2, traceId, spanName, spanKind, spanAttributes, _links) { + const options = this._client.getOptions(); + const parentSpan = getValidSpan(context2); + const parentContext = parentSpan?.spanContext(); + if (!hasSpansEnabled(options)) { + return wrapSamplingDecision({ decision: void 0, context: context2, spanAttributes }); + } + const maybeSpanHttpMethod = spanAttributes[srcExports$k.SEMATTRS_HTTP_METHOD] || spanAttributes[srcExports$k.ATTR_HTTP_REQUEST_METHOD]; + if (spanKind === srcExports$l.SpanKind.CLIENT && maybeSpanHttpMethod && (!parentSpan || parentContext?.isRemote)) { + return wrapSamplingDecision({ decision: void 0, context: context2, spanAttributes }); + } + const parentSampled = parentSpan ? getParentSampled(parentSpan, traceId, spanName) : void 0; + const isRootSpan = !parentSpan || parentContext?.isRemote; + if (!isRootSpan) { + return wrapSamplingDecision({ + decision: parentSampled ? SamplingDecision.RECORD_AND_SAMPLED : SamplingDecision.NOT_RECORD, + context: context2, + spanAttributes + }); + } + const { + description: inferredSpanName, + data: inferredAttributes, + op + } = inferSpanData(spanName, spanAttributes, spanKind); + const mergedAttributes = { + ...inferredAttributes, + ...spanAttributes + }; + if (op) { + mergedAttributes[SEMANTIC_ATTRIBUTE_SENTRY_OP] = op; + } + const mutableSamplingDecision = { decision: true }; + this._client.emit( + "beforeSampling", + { + spanAttributes: mergedAttributes, + spanName: inferredSpanName, + parentSampled, + parentContext + }, + mutableSamplingDecision + ); + if (!mutableSamplingDecision.decision) { + return wrapSamplingDecision({ decision: void 0, context: context2, spanAttributes }); + } + const { isolationScope } = getScopesFromContext(context2) ?? {}; + const dscString = parentContext?.traceState ? parentContext.traceState.get(SENTRY_TRACE_STATE_DSC) : void 0; + const dsc = dscString ? baggageHeaderToDynamicSamplingContext(dscString) : void 0; + const sampleRand = parseSampleRate(dsc?.sample_rand) ?? Math.random(); + const [sampled, sampleRate, localSampleRateWasApplied] = sampleSpan( + options, + { + name: inferredSpanName, + attributes: mergedAttributes, + normalizedRequest: isolationScope?.getScopeData().sdkProcessingMetadata.normalizedRequest, + parentSampled, + parentSampleRate: parseSampleRate(dsc?.sample_rate) + }, + sampleRand + ); + const method = `${maybeSpanHttpMethod}`.toUpperCase(); + if (method === "OPTIONS" || method === "HEAD") { + DEBUG_BUILD$1 && debug$2.log(`[Tracing] Not sampling span because HTTP method is '${method}' for ${spanName}`); + return wrapSamplingDecision({ + decision: SamplingDecision.NOT_RECORD, + context: context2, + spanAttributes, + sampleRand, + downstreamTraceSampleRate: 0 + // we don't want to sample anything in the downstream trace either + }); + } + if (!sampled && // We check for `parentSampled === undefined` because we only want to record client reports for spans that are trace roots (ie. when there was incoming trace) + parentSampled === void 0) { + DEBUG_BUILD$1 && debug$2.log("[Tracing] Discarding root span because its trace was not chosen to be sampled."); + this._client.recordDroppedEvent("sample_rate", "transaction"); + } + return { + ...wrapSamplingDecision({ + decision: sampled ? SamplingDecision.RECORD_AND_SAMPLED : SamplingDecision.NOT_RECORD, + context: context2, + spanAttributes, + sampleRand, + downstreamTraceSampleRate: localSampleRateWasApplied ? sampleRate : void 0 + }), + attributes: { + // We set the sample rate on the span when a local sample rate was applied to better understand how traces were sampled in Sentry + [SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE]: localSampleRateWasApplied ? sampleRate : void 0 + } + }; + } + /** Returns the sampler name or short description with the configuration. */ + toString() { + return "SentrySampler"; + } +} +function getParentSampled(parentSpan, traceId, spanName) { + const parentContext = parentSpan.spanContext(); + if (srcExports$l.isSpanContextValid(parentContext) && parentContext.traceId === traceId) { + if (parentContext.isRemote) { + const parentSampled2 = getSamplingDecision(parentSpan.spanContext()); + DEBUG_BUILD$1 && debug$2.log(`[Tracing] Inheriting remote parent's sampled decision for ${spanName}: ${parentSampled2}`); + return parentSampled2; + } + const parentSampled = getSamplingDecision(parentContext); + DEBUG_BUILD$1 && debug$2.log(`[Tracing] Inheriting parent's sampled decision for ${spanName}: ${parentSampled}`); + return parentSampled; + } + return void 0; +} +function wrapSamplingDecision({ + decision, + context: context2, + spanAttributes, + sampleRand, + downstreamTraceSampleRate +}) { + let traceState = getBaseTraceState(context2, spanAttributes); + if (downstreamTraceSampleRate !== void 0) { + traceState = traceState.set(SENTRY_TRACE_STATE_SAMPLE_RATE, `${downstreamTraceSampleRate}`); + } + if (sampleRand !== void 0) { + traceState = traceState.set(SENTRY_TRACE_STATE_SAMPLE_RAND, `${sampleRand}`); + } + if (decision == void 0) { + return { decision: SamplingDecision.NOT_RECORD, traceState }; + } + if (decision === SamplingDecision.NOT_RECORD) { + return { decision, traceState: traceState.set(SENTRY_TRACE_STATE_SAMPLED_NOT_RECORDING, "1") }; + } + return { decision, traceState }; +} +function getBaseTraceState(context2, spanAttributes) { + const parentSpan = srcExports$l.trace.getSpan(context2); + const parentContext = parentSpan?.spanContext(); + let traceState = parentContext?.traceState || new TraceState(); + const url = spanAttributes[srcExports$k.SEMATTRS_HTTP_URL] || spanAttributes[srcExports$k.ATTR_URL_FULL]; + if (url && typeof url === "string") { + traceState = traceState.set(SENTRY_TRACE_STATE_URL, url); + } + return traceState; +} +function getValidSpan(context2) { + const span = srcExports$l.trace.getSpan(context2); + return span && srcExports$l.isSpanContextValid(span.spanContext()) ? span : void 0; +} +function mergeBaggageHeaders(existing, baggage) { + if (!existing) { + return baggage; + } + const existingBaggageEntries = parseBaggageHeader(existing); + const newBaggageEntries = parseBaggageHeader(baggage); + if (!newBaggageEntries) { + return existing; + } + const mergedBaggageEntries = { ...existingBaggageEntries }; + Object.entries(newBaggageEntries).forEach(([key, value]) => { + if (!mergedBaggageEntries[key]) { + mergedBaggageEntries[key] = value; + } + }); + return objectToBaggageHeader(mergedBaggageEntries); +} +function addRequestBreadcrumb$1(request, response) { + const data = getBreadcrumbData$1(request); + const statusCode = response?.statusCode; + const level = getBreadcrumbLogLevelFromHttpStatusCode(statusCode); + addBreadcrumb( + { + category: "http", + data: { + status_code: statusCode, + ...data + }, + type: "http", + level + }, + { + event: "response", + request, + response + } + ); +} +function addTracePropagationHeadersToOutgoingRequest(request, propagationDecisionMap) { + const url = getRequestUrl(request); + const { tracePropagationTargets, propagateTraceparent } = getClient()?.getOptions() || {}; + const headersToAdd = shouldPropagateTraceForUrl(url, tracePropagationTargets, propagationDecisionMap) ? getTraceData$1({ propagateTraceparent }) : void 0; + if (!headersToAdd) { + return; + } + const { "sentry-trace": sentryTrace, baggage, traceparent } = headersToAdd; + if (sentryTrace && !request.getHeader("sentry-trace")) { + try { + request.setHeader("sentry-trace", sentryTrace); + DEBUG_BUILD$2 && debug$2.log(INSTRUMENTATION_NAME$1, "Added sentry-trace header to outgoing request"); + } catch (error2) { + DEBUG_BUILD$2 && debug$2.error( + INSTRUMENTATION_NAME$1, + "Failed to add sentry-trace header to outgoing request:", + isError(error2) ? error2.message : "Unknown error" + ); + } + } + if (traceparent && !request.getHeader("traceparent")) { + try { + request.setHeader("traceparent", traceparent); + DEBUG_BUILD$2 && debug$2.log(INSTRUMENTATION_NAME$1, "Added traceparent header to outgoing request"); + } catch (error2) { + DEBUG_BUILD$2 && debug$2.error( + INSTRUMENTATION_NAME$1, + "Failed to add traceparent header to outgoing request:", + isError(error2) ? error2.message : "Unknown error" + ); + } + } + if (baggage) { + const newBaggage = mergeBaggageHeaders(request.getHeader("baggage"), baggage); + if (newBaggage) { + try { + request.setHeader("baggage", newBaggage); + DEBUG_BUILD$2 && debug$2.log(INSTRUMENTATION_NAME$1, "Added baggage header to outgoing request"); + } catch (error2) { + DEBUG_BUILD$2 && debug$2.error( + INSTRUMENTATION_NAME$1, + "Failed to add baggage header to outgoing request:", + isError(error2) ? error2.message : "Unknown error" + ); + } + } + } +} +function getBreadcrumbData$1(request) { + try { + const host = request.getHeader("host") || request.host; + const url = new URL(request.path, `${request.protocol}//${host}`); + const parsedUrl = parseUrl(url.toString()); + const data = { + url: getSanitizedUrlString(parsedUrl), + "http.method": request.method || "GET" + }; + if (parsedUrl.search) { + data["http.query"] = parsedUrl.search; + } + if (parsedUrl.hash) { + data["http.fragment"] = parsedUrl.hash; + } + return data; + } catch { + return {}; + } +} +function getRequestOptions(request) { + return { + method: request.method, + protocol: request.protocol, + host: request.host, + hostname: request.host, + path: request.path, + headers: request.getHeaders() + }; +} +function getRequestUrl(request) { + const hostname = request.getHeader("host") || request.host; + const protocol = request.protocol; + const path2 = request.path; + return `${protocol}//${hostname}${path2}`; +} +class SentryHttpInstrumentation extends InstrumentationBase { + constructor(config2 = {}) { + super(INSTRUMENTATION_NAME$1, SDK_VERSION, config2); + this._propagationDecisionMap = new LRUMap(100); + this._ignoreOutgoingRequestsMap = /* @__PURE__ */ new WeakMap(); + } + /** @inheritdoc */ + init() { + let hasRegisteredHandlers = false; + const onHttpClientResponseFinish = ((_data) => { + const data = _data; + this._onOutgoingRequestFinish(data.request, data.response); + }); + const onHttpClientRequestError = ((_data) => { + const data = _data; + this._onOutgoingRequestFinish(data.request, void 0); + }); + const onHttpClientRequestCreated = ((_data) => { + const data = _data; + this._onOutgoingRequestCreated(data.request); + }); + const wrap2 = (moduleExports) => { + if (hasRegisteredHandlers) { + return moduleExports; + } + hasRegisteredHandlers = true; + subscribe("http.client.response.finish", onHttpClientResponseFinish); + subscribe("http.client.request.error", onHttpClientRequestError); + if (this.getConfig().propagateTraceInOutgoingRequests) { + subscribe("http.client.request.created", onHttpClientRequestCreated); + } + return moduleExports; + }; + const unwrap2 = () => { + unsubscribe("http.client.response.finish", onHttpClientResponseFinish); + unsubscribe("http.client.request.error", onHttpClientRequestError); + unsubscribe("http.client.request.created", onHttpClientRequestCreated); + }; + return [ + new InstrumentationNodeModuleDefinition("http", ["*"], wrap2, unwrap2), + new InstrumentationNodeModuleDefinition("https", ["*"], wrap2, unwrap2) + ]; + } + /** + * This is triggered when an outgoing request finishes. + * It has access to the final request and response objects. + */ + _onOutgoingRequestFinish(request, response) { + DEBUG_BUILD$2 && debug$2.log(INSTRUMENTATION_NAME$1, "Handling finished outgoing request"); + const _breadcrumbs = this.getConfig().breadcrumbs; + const breadCrumbsEnabled = typeof _breadcrumbs === "undefined" ? true : _breadcrumbs; + const shouldIgnore = this._ignoreOutgoingRequestsMap.get(request) ?? this._shouldIgnoreOutgoingRequest(request); + this._ignoreOutgoingRequestsMap.set(request, shouldIgnore); + if (breadCrumbsEnabled && !shouldIgnore) { + addRequestBreadcrumb$1(request, response); + } + } + /** + * This is triggered when an outgoing request is created. + * It has access to the request object, and can mutate it before the request is sent. + */ + _onOutgoingRequestCreated(request) { + const shouldIgnore = this._ignoreOutgoingRequestsMap.get(request) ?? this._shouldIgnoreOutgoingRequest(request); + this._ignoreOutgoingRequestsMap.set(request, shouldIgnore); + if (shouldIgnore) { + return; + } + addTracePropagationHeadersToOutgoingRequest(request, this._propagationDecisionMap); + } + /** + * Check if the given outgoing request should be ignored. + */ + _shouldIgnoreOutgoingRequest(request) { + if (isTracingSuppressed(srcExports$l.context.active())) { + return true; + } + const ignoreOutgoingRequests = this.getConfig().ignoreOutgoingRequests; + if (!ignoreOutgoingRequests) { + return false; + } + const options = getRequestOptions(request); + const url = getRequestUrl$1(request); + return ignoreOutgoingRequests(url, options); + } +} +const INTEGRATION_NAME$z = "Http"; +const instrumentSentryHttp$1 = generateInstrumentOnce( + `${INTEGRATION_NAME$z}.sentry`, + (options) => { + return new SentryHttpInstrumentation(options); + } +); +const httpIntegration$1 = defineIntegration((options = {}) => { + const serverOptions = { + sessions: options.trackIncomingRequestsAsSessions, + sessionFlushingDelayMS: options.sessionFlushingDelayMS, + ignoreRequestBody: options.ignoreIncomingRequestBody, + maxRequestBodySize: options.maxIncomingRequestBodySize + }; + const serverSpansOptions = { + ignoreIncomingRequests: options.ignoreIncomingRequests, + ignoreStaticAssets: options.ignoreStaticAssets, + ignoreStatusCodes: options.dropSpansForIncomingRequestStatusCodes + }; + const httpInstrumentationOptions = { + breadcrumbs: options.breadcrumbs, + propagateTraceInOutgoingRequests: true, + ignoreOutgoingRequests: options.ignoreOutgoingRequests + }; + const server = httpServerIntegration(serverOptions); + const serverSpans = httpServerSpansIntegration(serverSpansOptions); + const spans = options.spans ?? false; + const disableIncomingRequestSpans = options.disableIncomingRequestSpans ?? false; + const enabledServerSpans = spans && !disableIncomingRequestSpans; + return { + name: INTEGRATION_NAME$z, + setup(client) { + if (enabledServerSpans) { + serverSpans.setup(client); + } + }, + setupOnce() { + server.setupOnce(); + instrumentSentryHttp$1(httpInstrumentationOptions); + }, + processEvent(event) { + return serverSpans.processEvent(event); + } + }; +}); +const NODE_VERSION = parseSemver(process.versions.node); +const NODE_MAJOR = NODE_VERSION.major; +const NODE_MINOR = NODE_VERSION.minor; +const SENTRY_TRACE_HEADER = "sentry-trace"; +const SENTRY_BAGGAGE_HEADER = "baggage"; +const BAGGAGE_HEADER_REGEX = /baggage: (.*)\r\n/; +class SentryNodeFetchInstrumentation extends InstrumentationBase { + // Keep ref to avoid https://github.com/nodejs/node/issues/42170 bug and for + // unsubscribing. + constructor(config2 = {}) { + super("@sentry/instrumentation-node-fetch", SDK_VERSION, config2); + this._channelSubs = []; + this._propagationDecisionMap = new LRUMap(100); + this._ignoreOutgoingRequestsMap = /* @__PURE__ */ new WeakMap(); + } + /** No need to instrument files/modules. */ + init() { + return void 0; + } + /** Disable the instrumentation. */ + disable() { + super.disable(); + this._channelSubs.forEach((sub) => sub.unsubscribe()); + this._channelSubs = []; + } + /** Enable the instrumentation. */ + enable() { + super.enable(); + this._channelSubs = this._channelSubs || []; + if (this._channelSubs.length > 0) { + return; + } + this._subscribeToChannel("undici:request:create", this._onRequestCreated.bind(this)); + this._subscribeToChannel("undici:request:headers", this._onResponseHeaders.bind(this)); + } + /** + * This method is called when a request is created. + * You can still mutate the request here before it is sent. + */ + // eslint-disable-next-line complexity + _onRequestCreated({ request }) { + const config2 = this.getConfig(); + const enabled2 = config2.enabled !== false; + if (!enabled2) { + return; + } + const shouldIgnore = this._shouldIgnoreOutgoingRequest(request); + this._ignoreOutgoingRequestsMap.set(request, shouldIgnore); + if (shouldIgnore) { + return; + } + const url = getAbsoluteUrl$1(request.origin, request.path); + const { tracePropagationTargets, propagateTraceparent } = getClient()?.getOptions() || {}; + const addedHeaders = shouldPropagateTraceForUrl(url, tracePropagationTargets, this._propagationDecisionMap) ? getTraceData$1({ propagateTraceparent }) : void 0; + if (!addedHeaders) { + return; + } + const { "sentry-trace": sentryTrace, baggage, traceparent } = addedHeaders; + if (Array.isArray(request.headers)) { + const requestHeaders = request.headers; + if (sentryTrace && !requestHeaders.includes(SENTRY_TRACE_HEADER)) { + requestHeaders.push(SENTRY_TRACE_HEADER, sentryTrace); + } + if (traceparent && !requestHeaders.includes("traceparent")) { + requestHeaders.push("traceparent", traceparent); + } + const existingBaggagePos = requestHeaders.findIndex((header) => header === SENTRY_BAGGAGE_HEADER); + if (baggage && existingBaggagePos === -1) { + requestHeaders.push(SENTRY_BAGGAGE_HEADER, baggage); + } else if (baggage) { + const existingBaggage = requestHeaders[existingBaggagePos + 1]; + const merged = mergeBaggageHeaders(existingBaggage, baggage); + if (merged) { + requestHeaders[existingBaggagePos + 1] = merged; + } + } + } else { + const requestHeaders = request.headers; + if (sentryTrace && !requestHeaders.includes(`${SENTRY_TRACE_HEADER}:`)) { + request.headers += `${SENTRY_TRACE_HEADER}: ${sentryTrace}\r +`; + } + if (traceparent && !requestHeaders.includes("traceparent:")) { + request.headers += `traceparent: ${traceparent}\r +`; + } + const existingBaggage = request.headers.match(BAGGAGE_HEADER_REGEX)?.[1]; + if (baggage && !existingBaggage) { + request.headers += `${SENTRY_BAGGAGE_HEADER}: ${baggage}\r +`; + } else if (baggage) { + const merged = mergeBaggageHeaders(existingBaggage, baggage); + if (merged) { + request.headers = request.headers.replace(BAGGAGE_HEADER_REGEX, `baggage: ${merged}\r +`); + } + } + } + } + /** + * This method is called when a response is received. + */ + _onResponseHeaders({ request, response }) { + const config2 = this.getConfig(); + const enabled2 = config2.enabled !== false; + if (!enabled2) { + return; + } + const _breadcrumbs = config2.breadcrumbs; + const breadCrumbsEnabled = typeof _breadcrumbs === "undefined" ? true : _breadcrumbs; + const shouldIgnore = this._ignoreOutgoingRequestsMap.get(request); + if (breadCrumbsEnabled && !shouldIgnore) { + addRequestBreadcrumb(request, response); + } + } + /** Subscribe to a diagnostics channel. */ + _subscribeToChannel(diagnosticChannel, onMessage) { + const useNewSubscribe = NODE_MAJOR > 18 || NODE_MAJOR === 18 && NODE_MINOR >= 19; + let unsubscribe2; + if (useNewSubscribe) { + diagch.subscribe?.(diagnosticChannel, onMessage); + unsubscribe2 = () => diagch.unsubscribe?.(diagnosticChannel, onMessage); + } else { + const channel = diagch.channel(diagnosticChannel); + channel.subscribe(onMessage); + unsubscribe2 = () => channel.unsubscribe(onMessage); + } + this._channelSubs.push({ + name: diagnosticChannel, + unsubscribe: unsubscribe2 + }); + } + /** + * Check if the given outgoing request should be ignored. + */ + _shouldIgnoreOutgoingRequest(request) { + if (isTracingSuppressed(srcExports$l.context.active())) { + return true; + } + const url = getAbsoluteUrl$1(request.origin, request.path); + const ignoreOutgoingRequests = this.getConfig().ignoreOutgoingRequests; + if (typeof ignoreOutgoingRequests !== "function" || !url) { + return false; + } + return ignoreOutgoingRequests(url); + } +} +function addRequestBreadcrumb(request, response) { + const data = getBreadcrumbData(request); + const statusCode = response.statusCode; + const level = getBreadcrumbLogLevelFromHttpStatusCode(statusCode); + addBreadcrumb( + { + category: "http", + data: { + status_code: statusCode, + ...data + }, + type: "http", + level + }, + { + event: "response", + request, + response + } + ); +} +function getBreadcrumbData(request) { + try { + const url = getAbsoluteUrl$1(request.origin, request.path); + const parsedUrl = parseUrl(url); + const data = { + url: getSanitizedUrlString(parsedUrl), + "http.method": request.method || "GET" + }; + if (parsedUrl.search) { + data["http.query"] = parsedUrl.search; + } + if (parsedUrl.hash) { + data["http.fragment"] = parsedUrl.hash; + } + return data; + } catch { + return {}; + } +} +function getAbsoluteUrl$1(origin, path2 = "/") { + try { + const url = new URL(path2, origin); + return url.toString(); + } catch { + const url = `${origin}`; + if (url.endsWith("/") && path2.startsWith("/")) { + return `${url}${path2.slice(1)}`; + } + if (!url.endsWith("/") && !path2.startsWith("/")) { + return `${url}/${path2.slice(1)}`; + } + return `${url}${path2}`; + } +} +const INTEGRATION_NAME$y = "NodeFetch"; +const instrumentSentryNodeFetch$1 = generateInstrumentOnce( + `${INTEGRATION_NAME$y}.sentry`, + SentryNodeFetchInstrumentation, + (options) => { + return options; + } +); +const _nativeNodeFetchIntegration$1 = ((options = {}) => { + return { + name: "NodeFetch", + setupOnce() { + instrumentSentryNodeFetch$1(options); + } + }; +}); +const nativeNodeFetchIntegration$1 = defineIntegration(_nativeNodeFetchIntegration$1); +const readFileAsync = promisify(readFile); +const readDirAsync = promisify(readdir); +const INTEGRATION_NAME$x = "Context"; +const _nodeContextIntegration = ((options = {}) => { + let cachedContext; + const _options = { + app: true, + os: true, + device: true, + culture: true, + cloudResource: true, + ...options + }; + async function addContext(event) { + if (cachedContext === void 0) { + cachedContext = _getContexts(); + } + const updatedContext = _updateContext(await cachedContext); + event.contexts = { + ...event.contexts, + app: { ...updatedContext.app, ...event.contexts?.app }, + os: { ...updatedContext.os, ...event.contexts?.os }, + device: { ...updatedContext.device, ...event.contexts?.device }, + culture: { ...updatedContext.culture, ...event.contexts?.culture }, + cloud_resource: { ...updatedContext.cloud_resource, ...event.contexts?.cloud_resource } + }; + return event; + } + async function _getContexts() { + const contexts = {}; + if (_options.os) { + contexts.os = await getOsContext(); + } + if (_options.app) { + contexts.app = getAppContext(); + } + if (_options.device) { + contexts.device = getDeviceContext(_options.device); + } + if (_options.culture) { + const culture = getCultureContext(); + if (culture) { + contexts.culture = culture; + } + } + if (_options.cloudResource) { + contexts.cloud_resource = getCloudResourceContext(); + } + return contexts; + } + return { + name: INTEGRATION_NAME$x, + processEvent(event) { + return addContext(event); + } + }; +}); +const nodeContextIntegration = defineIntegration(_nodeContextIntegration); +function _updateContext(contexts) { + if (contexts.app?.app_memory) { + contexts.app.app_memory = process.memoryUsage().rss; + } + if (contexts.app?.free_memory && typeof process.availableMemory === "function") { + const freeMemory = process.availableMemory?.(); + if (freeMemory != null) { + contexts.app.free_memory = freeMemory; + } + } + if (contexts.device?.free_memory) { + contexts.device.free_memory = os.freemem(); + } + return contexts; +} +async function getOsContext() { + const platformId = os.platform(); + switch (platformId) { + case "darwin": + return getDarwinInfo(); + case "linux": + return getLinuxInfo(); + default: + return { + name: PLATFORM_NAMES[platformId] || platformId, + version: os.release() + }; + } +} +function getCultureContext() { + try { + if (typeof process.versions.icu !== "string") { + return; + } + const january = /* @__PURE__ */ new Date(9e8); + const spanish = new Intl.DateTimeFormat("es", { month: "long" }); + if (spanish.format(january) === "enero") { + const options = Intl.DateTimeFormat().resolvedOptions(); + return { + locale: options.locale, + timezone: options.timeZone + }; + } + } catch { + } + return; +} +function getAppContext() { + const app_memory = process.memoryUsage().rss; + const app_start_time = new Date(Date.now() - process.uptime() * 1e3).toISOString(); + const appContext = { app_start_time, app_memory }; + if (typeof process.availableMemory === "function") { + const freeMemory = process.availableMemory?.(); + if (freeMemory != null) { + appContext.free_memory = freeMemory; + } + } + return appContext; +} +function getDeviceContext(deviceOpt) { + const device = {}; + let uptime; + try { + uptime = os.uptime(); + } catch { + } + if (typeof uptime === "number") { + device.boot_time = new Date(Date.now() - uptime * 1e3).toISOString(); + } + device.arch = os.arch(); + if (deviceOpt === true || deviceOpt.memory) { + device.memory_size = os.totalmem(); + device.free_memory = os.freemem(); + } + if (deviceOpt === true || deviceOpt.cpu) { + const cpuInfo = os.cpus(); + const firstCpu = cpuInfo?.[0]; + if (firstCpu) { + device.processor_count = cpuInfo.length; + device.cpu_description = firstCpu.model; + device.processor_frequency = firstCpu.speed; + } + } + return device; +} +const PLATFORM_NAMES = { + aix: "IBM AIX", + freebsd: "FreeBSD", + openbsd: "OpenBSD", + sunos: "SunOS", + win32: "Windows", + ohos: "OpenHarmony", + android: "Android" +}; +const LINUX_DISTROS = [ + { name: "fedora-release", distros: ["Fedora"] }, + { name: "redhat-release", distros: ["Red Hat Linux", "Centos"] }, + { name: "redhat_version", distros: ["Red Hat Linux"] }, + { name: "SuSE-release", distros: ["SUSE Linux"] }, + { name: "lsb-release", distros: ["Ubuntu Linux", "Arch Linux"] }, + { name: "debian_version", distros: ["Debian"] }, + { name: "debian_release", distros: ["Debian"] }, + { name: "arch-release", distros: ["Arch Linux"] }, + { name: "gentoo-release", distros: ["Gentoo Linux"] }, + { name: "novell-release", distros: ["SUSE Linux"] }, + { name: "alpine-release", distros: ["Alpine Linux"] } +]; +const LINUX_VERSIONS = { + alpine: (content) => content, + arch: (content) => matchFirst(/distrib_release=(.*)/, content), + centos: (content) => matchFirst(/release ([^ ]+)/, content), + debian: (content) => content, + fedora: (content) => matchFirst(/release (..)/, content), + mint: (content) => matchFirst(/distrib_release=(.*)/, content), + red: (content) => matchFirst(/release ([^ ]+)/, content), + suse: (content) => matchFirst(/VERSION = (.*)\n/, content), + ubuntu: (content) => matchFirst(/distrib_release=(.*)/, content) +}; +function matchFirst(regex, text) { + const match2 = regex.exec(text); + return match2 ? match2[1] : void 0; +} +async function getDarwinInfo() { + const darwinInfo = { + kernel_version: os.release(), + name: "Mac OS X", + version: `10.${Number(os.release().split(".")[0]) - 4}` + }; + try { + const output = await new Promise((resolve, reject) => { + execFile("/usr/bin/sw_vers", (error2, stdout) => { + if (error2) { + reject(error2); + return; + } + resolve(stdout); + }); + }); + darwinInfo.name = matchFirst(/^ProductName:\s+(.*)$/m, output); + darwinInfo.version = matchFirst(/^ProductVersion:\s+(.*)$/m, output); + darwinInfo.build = matchFirst(/^BuildVersion:\s+(.*)$/m, output); + } catch { + } + return darwinInfo; +} +function getLinuxDistroId(name) { + return name.split(" ")[0].toLowerCase(); +} +async function getLinuxInfo() { + const linuxInfo = { + kernel_version: os.release(), + name: "Linux" + }; + try { + const etcFiles = await readDirAsync("/etc"); + const distroFile = LINUX_DISTROS.find((file) => etcFiles.includes(file.name)); + if (!distroFile) { + return linuxInfo; + } + const distroPath = join("/etc", distroFile.name); + const contents = (await readFileAsync(distroPath, { encoding: "utf-8" })).toLowerCase(); + const { distros } = distroFile; + linuxInfo.name = distros.find((d) => contents.indexOf(getLinuxDistroId(d)) >= 0) || distros[0]; + const id = getLinuxDistroId(linuxInfo.name); + linuxInfo.version = LINUX_VERSIONS[id]?.(contents); + } catch { + } + return linuxInfo; +} +function getCloudResourceContext() { + if (process.env.VERCEL) { + return { + "cloud.provider": "vercel", + "cloud.region": process.env.VERCEL_REGION + }; + } else if (process.env.AWS_REGION) { + return { + "cloud.provider": "aws", + "cloud.region": process.env.AWS_REGION, + "cloud.platform": process.env.AWS_EXECUTION_ENV + }; + } else if (process.env.GCP_PROJECT) { + return { + "cloud.provider": "gcp" + }; + } else if (process.env.ALIYUN_REGION_ID) { + return { + "cloud.provider": "alibaba_cloud", + "cloud.region": process.env.ALIYUN_REGION_ID + }; + } else if (process.env.WEBSITE_SITE_NAME && process.env.REGION_NAME) { + return { + "cloud.provider": "azure", + "cloud.region": process.env.REGION_NAME + }; + } else if (process.env.IBM_CLOUD_REGION) { + return { + "cloud.provider": "ibm_cloud", + "cloud.region": process.env.IBM_CLOUD_REGION + }; + } else if (process.env.TENCENTCLOUD_REGION) { + return { + "cloud.provider": "tencent_cloud", + "cloud.region": process.env.TENCENTCLOUD_REGION, + "cloud.account.id": process.env.TENCENTCLOUD_APPID, + "cloud.availability_zone": process.env.TENCENTCLOUD_ZONE + }; + } else if (process.env.NETLIFY) { + return { + "cloud.provider": "netlify" + }; + } else if (process.env.FLY_REGION) { + return { + "cloud.provider": "fly.io", + "cloud.region": process.env.FLY_REGION + }; + } else if (process.env.DYNO) { + return { + "cloud.provider": "heroku" + }; + } else { + return void 0; + } +} +const LRU_FILE_CONTENTS_CACHE = new LRUMap(10); +const LRU_FILE_CONTENTS_FS_READ_FAILED = new LRUMap(20); +const DEFAULT_LINES_OF_CONTEXT = 7; +const INTEGRATION_NAME$w = "ContextLines"; +const MAX_CONTEXTLINES_COLNO = 1e3; +const MAX_CONTEXTLINES_LINENO = 1e4; +function emplace(map, key, contents) { + const value = map.get(key); + if (value === void 0) { + map.set(key, contents); + return contents; + } + return value; +} +function shouldSkipContextLinesForFile(path2) { + if (path2.startsWith("node:")) return true; + if (path2.endsWith(".min.js")) return true; + if (path2.endsWith(".min.cjs")) return true; + if (path2.endsWith(".min.mjs")) return true; + if (path2.startsWith("data:")) return true; + return false; +} +function shouldSkipContextLinesForFrame(frame) { + if (frame.lineno !== void 0 && frame.lineno > MAX_CONTEXTLINES_LINENO) return true; + if (frame.colno !== void 0 && frame.colno > MAX_CONTEXTLINES_COLNO) return true; + return false; +} +function rangeExistsInContentCache(file, range) { + const contents = LRU_FILE_CONTENTS_CACHE.get(file); + if (contents === void 0) return false; + for (let i = range[0]; i <= range[1]; i++) { + if (contents[i] === void 0) { + return false; + } + } + return true; +} +function makeLineReaderRanges(lines, linecontext) { + if (!lines.length) { + return []; + } + let i = 0; + const line = lines[0]; + if (typeof line !== "number") { + return []; + } + let current = makeContextRange(line, linecontext); + const out = []; + while (true) { + if (i === lines.length - 1) { + out.push(current); + break; + } + const next = lines[i + 1]; + if (typeof next !== "number") { + break; + } + if (next <= current[1]) { + current[1] = next + linecontext; + } else { + out.push(current); + current = makeContextRange(next, linecontext); + } + i++; + } + return out; +} +function getContextLinesFromFile(path2, ranges, output) { + return new Promise((resolve, _reject) => { + const stream = createReadStream(path2); + const lineReaded = createInterface({ + input: stream + }); + function destroyStreamAndResolve() { + stream.destroy(); + resolve(); + } + let lineNumber = 0; + let currentRangeIndex = 0; + const range = ranges[currentRangeIndex]; + if (range === void 0) { + destroyStreamAndResolve(); + return; + } + let rangeStart = range[0]; + let rangeEnd = range[1]; + function onStreamError(e) { + LRU_FILE_CONTENTS_FS_READ_FAILED.set(path2, 1); + DEBUG_BUILD$2 && debug$2.error(`Failed to read file: ${path2}. Error: ${e}`); + lineReaded.close(); + lineReaded.removeAllListeners(); + destroyStreamAndResolve(); + } + stream.on("error", onStreamError); + lineReaded.on("error", onStreamError); + lineReaded.on("close", destroyStreamAndResolve); + lineReaded.on("line", (line) => { + lineNumber++; + if (lineNumber < rangeStart) return; + output[lineNumber] = snipLine(line, 0); + if (lineNumber >= rangeEnd) { + if (currentRangeIndex === ranges.length - 1) { + lineReaded.close(); + lineReaded.removeAllListeners(); + return; + } + currentRangeIndex++; + const range2 = ranges[currentRangeIndex]; + if (range2 === void 0) { + lineReaded.close(); + lineReaded.removeAllListeners(); + return; + } + rangeStart = range2[0]; + rangeEnd = range2[1]; + } + }); + }); +} +async function addSourceContext(event, contextLines) { + const filesToLines = {}; + if (contextLines > 0 && event.exception?.values) { + for (const exception of event.exception.values) { + if (!exception.stacktrace?.frames?.length) { + continue; + } + for (let i = exception.stacktrace.frames.length - 1; i >= 0; i--) { + const frame = exception.stacktrace.frames[i]; + const filename = frame?.filename; + if (!frame || typeof filename !== "string" || typeof frame.lineno !== "number" || shouldSkipContextLinesForFile(filename) || shouldSkipContextLinesForFrame(frame)) { + continue; + } + const filesToLinesOutput = filesToLines[filename]; + if (!filesToLinesOutput) filesToLines[filename] = []; + filesToLines[filename].push(frame.lineno); + } + } + } + const files = Object.keys(filesToLines); + if (files.length == 0) { + return event; + } + const readlinePromises = []; + for (const file of files) { + if (LRU_FILE_CONTENTS_FS_READ_FAILED.get(file)) { + continue; + } + const filesToLineRanges = filesToLines[file]; + if (!filesToLineRanges) { + continue; + } + filesToLineRanges.sort((a, b) => a - b); + const ranges = makeLineReaderRanges(filesToLineRanges, contextLines); + if (ranges.every((r) => rangeExistsInContentCache(file, r))) { + continue; + } + const cache = emplace(LRU_FILE_CONTENTS_CACHE, file, {}); + readlinePromises.push(getContextLinesFromFile(file, ranges, cache)); + } + await Promise.all(readlinePromises).catch(() => { + DEBUG_BUILD$2 && debug$2.log("Failed to read one or more source files and resolve context lines"); + }); + if (contextLines > 0 && event.exception?.values) { + for (const exception of event.exception.values) { + if (exception.stacktrace?.frames && exception.stacktrace.frames.length > 0) { + addSourceContextToFrames(exception.stacktrace.frames, contextLines, LRU_FILE_CONTENTS_CACHE); + } + } + } + return event; +} +function addSourceContextToFrames(frames, contextLines, cache) { + for (const frame of frames) { + if (frame.filename && frame.context_line === void 0 && typeof frame.lineno === "number") { + const contents = cache.get(frame.filename); + if (contents === void 0) { + continue; + } + addContextToFrame(frame.lineno, frame, contextLines, contents); + } + } +} +function clearLineContext(frame) { + delete frame.pre_context; + delete frame.context_line; + delete frame.post_context; +} +function addContextToFrame(lineno, frame, contextLines, contents) { + if (frame.lineno === void 0 || contents === void 0) { + DEBUG_BUILD$2 && debug$2.error("Cannot resolve context for frame with no lineno or file contents"); + return; + } + frame.pre_context = []; + for (let i = makeRangeStart(lineno, contextLines); i < lineno; i++) { + const line = contents[i]; + if (line === void 0) { + clearLineContext(frame); + DEBUG_BUILD$2 && debug$2.error(`Could not find line ${i} in file ${frame.filename}`); + return; + } + frame.pre_context.push(line); + } + if (contents[lineno] === void 0) { + clearLineContext(frame); + DEBUG_BUILD$2 && debug$2.error(`Could not find line ${lineno} in file ${frame.filename}`); + return; + } + frame.context_line = contents[lineno]; + const end = makeRangeEnd(lineno, contextLines); + frame.post_context = []; + for (let i = lineno + 1; i <= end; i++) { + const line = contents[i]; + if (line === void 0) { + break; + } + frame.post_context.push(line); + } +} +function makeRangeStart(line, linecontext) { + return Math.max(1, line - linecontext); +} +function makeRangeEnd(line, linecontext) { + return line + linecontext; +} +function makeContextRange(line, linecontext) { + return [makeRangeStart(line, linecontext), makeRangeEnd(line, linecontext)]; +} +const _contextLinesIntegration = ((options = {}) => { + const contextLines = options.frameContextLines !== void 0 ? options.frameContextLines : DEFAULT_LINES_OF_CONTEXT; + return { + name: INTEGRATION_NAME$w, + processEvent(event) { + return addSourceContext(event, contextLines); + } + }; +}); +const contextLinesIntegration = defineIntegration(_contextLinesIntegration); +let cachedDebuggerEnabled; +async function isDebuggerEnabled() { + if (cachedDebuggerEnabled === void 0) { + try { + const inspector = await import("node:inspector"); + cachedDebuggerEnabled = !!inspector.url(); + } catch { + cachedDebuggerEnabled = false; + } + } + return cachedDebuggerEnabled; +} +const LOCAL_VARIABLES_KEY = "__SENTRY_ERROR_LOCAL_VARIABLES__"; +function createRateLimiter(maxPerSecond, enable2, disable2) { + let count = 0; + let retrySeconds = 5; + let disabledTimeout = 0; + setInterval(() => { + if (disabledTimeout === 0) { + if (count > maxPerSecond) { + retrySeconds *= 2; + disable2(retrySeconds); + if (retrySeconds > 86400) { + retrySeconds = 86400; + } + disabledTimeout = retrySeconds; + } + } else { + disabledTimeout -= 1; + if (disabledTimeout === 0) { + enable2(); + } + } + count = 0; + }, 1e3).unref(); + return () => { + count += 1; + }; +} +function isAnonymous(name) { + return name !== void 0 && (name.length === 0 || name === "?" || name === ""); +} +function functionNamesMatch(a, b) { + return a === b || `Object.${a}` === b || a === `Object.${b}` || isAnonymous(a) && isAnonymous(b); +} +const base64WorkerScript = "LyohIEBzZW50cnkvbm9kZS1jb3JlIDEwLjMyLjEgKGJhN2Y5MGFhOCkgfCBodHRwczovL2dpdGh1Yi5jb20vZ2V0c2VudHJ5L3NlbnRyeS1qYXZhc2NyaXB0ICovCmltcG9ydHtTZXNzaW9uIGFzIGV9ZnJvbSJub2RlOmluc3BlY3Rvci9wcm9taXNlcyI7aW1wb3J0e3dvcmtlckRhdGEgYXMgdH1mcm9tIm5vZGU6d29ya2VyX3RocmVhZHMiO2NvbnN0IG49Z2xvYmFsVGhpcyxpPXt9O2NvbnN0IG89Il9fU0VOVFJZX0VSUk9SX0xPQ0FMX1ZBUklBQkxFU19fIjtjb25zdCBhPXQ7ZnVuY3Rpb24gcyguLi5lKXthLmRlYnVnJiZmdW5jdGlvbihlKXtpZighKCJjb25zb2xlImluIG4pKXJldHVybiBlKCk7Y29uc3QgdD1uLmNvbnNvbGUsbz17fSxhPU9iamVjdC5rZXlzKGkpO2EuZm9yRWFjaChlPT57Y29uc3Qgbj1pW2VdO29bZV09dFtlXSx0W2VdPW59KTt0cnl7cmV0dXJuIGUoKX1maW5hbGx5e2EuZm9yRWFjaChlPT57dFtlXT1vW2VdfSl9fSgoKT0+Y29uc29sZS5sb2coIltMb2NhbFZhcmlhYmxlcyBXb3JrZXJdIiwuLi5lKSl9YXN5bmMgZnVuY3Rpb24gYyhlLHQsbixpKXtjb25zdCBvPWF3YWl0IGUucG9zdCgiUnVudGltZS5nZXRQcm9wZXJ0aWVzIix7b2JqZWN0SWQ6dCxvd25Qcm9wZXJ0aWVzOiEwfSk7aVtuXT1vLnJlc3VsdC5maWx0ZXIoZT0+Imxlbmd0aCIhPT1lLm5hbWUmJiFpc05hTihwYXJzZUludChlLm5hbWUsMTApKSkuc29ydCgoZSx0KT0+cGFyc2VJbnQoZS5uYW1lLDEwKS1wYXJzZUludCh0Lm5hbWUsMTApKS5tYXAoZT0+ZS52YWx1ZT8udmFsdWUpfWFzeW5jIGZ1bmN0aW9uIHIoZSx0LG4saSl7Y29uc3Qgbz1hd2FpdCBlLnBvc3QoIlJ1bnRpbWUuZ2V0UHJvcGVydGllcyIse29iamVjdElkOnQsb3duUHJvcGVydGllczohMH0pO2lbbl09by5yZXN1bHQubWFwKGU9PltlLm5hbWUsZS52YWx1ZT8udmFsdWVdKS5yZWR1Y2UoKGUsW3Qsbl0pPT4oZVt0XT1uLGUpLHt9KX1mdW5jdGlvbiB1KGUsdCl7ZS52YWx1ZSYmKCJ2YWx1ZSJpbiBlLnZhbHVlP3ZvaWQgMD09PWUudmFsdWUudmFsdWV8fG51bGw9PT1lLnZhbHVlLnZhbHVlP3RbZS5uYW1lXT1gPCR7ZS52YWx1ZS52YWx1ZX0+YDp0W2UubmFtZV09ZS52YWx1ZS52YWx1ZToiZGVzY3JpcHRpb24iaW4gZS52YWx1ZSYmImZ1bmN0aW9uIiE9PWUudmFsdWUudHlwZT90W2UubmFtZV09YDwke2UudmFsdWUuZGVzY3JpcHRpb259PmA6InVuZGVmaW5lZCI9PT1lLnZhbHVlLnR5cGUmJih0W2UubmFtZV09Ijx1bmRlZmluZWQ+IikpfWFzeW5jIGZ1bmN0aW9uIGwoZSx0KXtjb25zdCBuPWF3YWl0IGUucG9zdCgiUnVudGltZS5nZXRQcm9wZXJ0aWVzIix7b2JqZWN0SWQ6dCxvd25Qcm9wZXJ0aWVzOiEwfSksaT17fTtmb3IoY29uc3QgdCBvZiBuLnJlc3VsdClpZih0LnZhbHVlPy5vYmplY3RJZCYmIkFycmF5Ij09PXQudmFsdWUuY2xhc3NOYW1lKXtjb25zdCBuPXQudmFsdWUub2JqZWN0SWQ7YXdhaXQgYyhlLG4sdC5uYW1lLGkpfWVsc2UgaWYodC52YWx1ZT8ub2JqZWN0SWQmJiJPYmplY3QiPT09dC52YWx1ZS5jbGFzc05hbWUpe2NvbnN0IG49dC52YWx1ZS5vYmplY3RJZDthd2FpdCByKGUsbix0Lm5hbWUsaSl9ZWxzZSB0LnZhbHVlJiZ1KHQsaSk7cmV0dXJuIGl9bGV0IGY7KGFzeW5jIGZ1bmN0aW9uKCl7Y29uc3QgdD1uZXcgZTt0LmNvbm5lY3RUb01haW5UaHJlYWQoKSxzKCJDb25uZWN0ZWQgdG8gbWFpbiB0aHJlYWQiKTtsZXQgbj0hMTt0Lm9uKCJEZWJ1Z2dlci5yZXN1bWVkIiwoKT0+e249ITF9KSx0Lm9uKCJEZWJ1Z2dlci5wYXVzZWQiLGU9PntuPSEwLGFzeW5jIGZ1bmN0aW9uKGUse3JlYXNvbjp0LGRhdGE6e29iamVjdElkOm59LGNhbGxGcmFtZXM6aX0pe2lmKCJleGNlcHRpb24iIT09dCYmInByb21pc2VSZWplY3Rpb24iIT09dClyZXR1cm47aWYoZj8uKCksbnVsbD09bilyZXR1cm47Y29uc3QgYT1bXTtmb3IobGV0IHQ9MDt0PGkubGVuZ3RoO3QrKyl7Y29uc3R7c2NvcGVDaGFpbjpuLGZ1bmN0aW9uTmFtZTpvLHRoaXM6c309aVt0XSxjPW4uZmluZChlPT4ibG9jYWwiPT09ZS50eXBlKSxyPSJnbG9iYWwiIT09cy5jbGFzc05hbWUmJnMuY2xhc3NOYW1lP2Ake3MuY2xhc3NOYW1lfS4ke299YDpvO2lmKHZvaWQgMD09PWM/Lm9iamVjdC5vYmplY3RJZClhW3RdPXtmdW5jdGlvbjpyfTtlbHNle2NvbnN0IG49YXdhaXQgbChlLGMub2JqZWN0Lm9iamVjdElkKTthW3RdPXtmdW5jdGlvbjpyLHZhcnM6bn19fWF3YWl0IGUucG9zdCgiUnVudGltZS5jYWxsRnVuY3Rpb25PbiIse2Z1bmN0aW9uRGVjbGFyYXRpb246YGZ1bmN0aW9uKCkgeyB0aGlzLiR7b30gPSB0aGlzLiR7b30gfHwgJHtKU09OLnN0cmluZ2lmeShhKX07IH1gLHNpbGVudDohMCxvYmplY3RJZDpufSksYXdhaXQgZS5wb3N0KCJSdW50aW1lLnJlbGVhc2VPYmplY3QiLHtvYmplY3RJZDpufSl9KHQsZS5wYXJhbXMpLnRoZW4oYXN5bmMoKT0+e24mJmF3YWl0IHQucG9zdCgiRGVidWdnZXIucmVzdW1lIil9LGFzeW5jIGU9PntuJiZhd2FpdCB0LnBvc3QoIkRlYnVnZ2VyLnJlc3VtZSIpfSl9KSxhd2FpdCB0LnBvc3QoIkRlYnVnZ2VyLmVuYWJsZSIpO2NvbnN0IGk9ITEhPT1hLmNhcHR1cmVBbGxFeGNlcHRpb25zO2lmKGF3YWl0IHQucG9zdCgiRGVidWdnZXIuc2V0UGF1c2VPbkV4Y2VwdGlvbnMiLHtzdGF0ZTppPyJhbGwiOiJ1bmNhdWdodCJ9KSxpKXtjb25zdCBlPWEubWF4RXhjZXB0aW9uc1BlclNlY29uZHx8NTA7Zj1mdW5jdGlvbihlLHQsbil7bGV0IGk9MCxvPTUsYT0wO3JldHVybiBzZXRJbnRlcnZhbCgoKT0+ezA9PT1hP2k+ZSYmKG8qPTIsbihvKSxvPjg2NDAwJiYobz04NjQwMCksYT1vKTooYS09MSwwPT09YSYmdCgpKSxpPTB9LDFlMykudW5yZWYoKSwoKT0+e2krPTF9fShlLGFzeW5jKCk9PntzKCJSYXRlLWxpbWl0IGxpZnRlZC4iKSxhd2FpdCB0LnBvc3QoIkRlYnVnZ2VyLnNldFBhdXNlT25FeGNlcHRpb25zIix7c3RhdGU6ImFsbCJ9KX0sYXN5bmMgZT0+e3MoYFJhdGUtbGltaXQgZXhjZWVkZWQuIERpc2FibGluZyBjYXB0dXJpbmcgb2YgY2F1Z2h0IGV4Y2VwdGlvbnMgZm9yICR7ZX0gc2Vjb25kcy5gKSxhd2FpdCB0LnBvc3QoIkRlYnVnZ2VyLnNldFBhdXNlT25FeGNlcHRpb25zIix7c3RhdGU6InVuY2F1Z2h0In0pfSl9fSkoKS5jYXRjaChlPT57cygiRmFpbGVkIHRvIHN0YXJ0IGRlYnVnZ2VyIixlKX0pLHNldEludGVydmFsKCgpPT57fSwxZTQpOw=="; +function log(...args) { + debug$2.log("[LocalVariables]", ...args); +} +const localVariablesAsyncIntegration = defineIntegration(((integrationOptions = {}) => { + function addLocalVariablesToException(exception, localVariables) { + const frames = (exception.stacktrace?.frames || []).filter((frame) => frame.function !== "new Promise"); + for (let i = 0; i < frames.length; i++) { + const frameIndex = frames.length - i - 1; + const frameLocalVariables = localVariables[i]; + const frame = frames[frameIndex]; + if (!frame || !frameLocalVariables) { + break; + } + if ( + // We need to have vars to add + frameLocalVariables.vars === void 0 || // Only skip out-of-app frames if includeOutOfAppFrames is not true + frame.in_app === false && integrationOptions.includeOutOfAppFrames !== true || // The function names need to match + !functionNamesMatch(frame.function, frameLocalVariables.function) + ) { + continue; + } + frame.vars = frameLocalVariables.vars; + } + } + function addLocalVariablesToEvent(event, hint) { + if (hint.originalException && typeof hint.originalException === "object" && LOCAL_VARIABLES_KEY in hint.originalException && Array.isArray(hint.originalException[LOCAL_VARIABLES_KEY])) { + for (const exception of event.exception?.values || []) { + addLocalVariablesToException(exception, hint.originalException[LOCAL_VARIABLES_KEY]); + } + hint.originalException[LOCAL_VARIABLES_KEY] = void 0; + } + return event; + } + async function startInspector() { + const inspector = await import("node:inspector"); + if (!inspector.url()) { + inspector.open(0); + } + } + function startWorker(options) { + const worker = new Worker(new URL(`data:application/javascript;base64,${base64WorkerScript}`), { + workerData: options, + // We don't want any Node args to be passed to the worker + execArgv: [], + env: { ...process.env, NODE_OPTIONS: void 0 } + }); + process.on("exit", () => { + worker.terminate(); + }); + worker.once("error", (err) => { + log("Worker error", err); + }); + worker.once("exit", (code) => { + log("Worker exit", code); + }); + worker.unref(); + } + return { + name: "LocalVariablesAsync", + async setup(client) { + const clientOptions = client.getOptions(); + if (!clientOptions.includeLocalVariables) { + return; + } + if (await isDebuggerEnabled()) { + debug$2.warn("Local variables capture has been disabled because the debugger was already enabled"); + return; + } + const options = { + ...integrationOptions, + debug: debug$2.isEnabled() + }; + startInspector().then( + () => { + try { + startWorker(options); + } catch (e) { + debug$2.error("Failed to start worker", e); + } + }, + (e) => { + debug$2.error("Failed to start inspector", e); + } + ); + }, + processEvent(event, hint) { + return addLocalVariablesToEvent(event, hint); + } + }; +})); +function hashFrames(frames) { + if (frames === void 0) { + return; + } + return frames.slice(-10).reduce((acc, frame) => `${acc},${frame.function},${frame.lineno},${frame.colno}`, ""); +} +function hashFromStack(stackParser, stack) { + if (stack === void 0) { + return void 0; + } + return hashFrames(stackParser(stack, 1)); +} +function createCallbackList(complete) { + let callbacks = []; + let completedCalled = false; + function checkedComplete(result) { + callbacks = []; + if (completedCalled) { + return; + } + completedCalled = true; + complete(result); + } + callbacks.push(checkedComplete); + function add(fn) { + callbacks.push(fn); + } + function next(result) { + const popped = callbacks.pop() || checkedComplete; + try { + popped(result); + } catch { + checkedComplete(result); + } + } + return { add, next }; +} +class AsyncSession { + /** Throws if inspector API is not available */ + constructor(_session) { + this._session = _session; + } + static async create(orDefault) { + if (orDefault) { + return orDefault; + } + const inspector = await import("node:inspector"); + return new AsyncSession(new inspector.Session()); + } + /** @inheritdoc */ + configureAndConnect(onPause, captureAll) { + this._session.connect(); + this._session.on("Debugger.paused", (event) => { + onPause(event, () => { + this._session.post("Debugger.resume"); + }); + }); + this._session.post("Debugger.enable"); + this._session.post("Debugger.setPauseOnExceptions", { state: captureAll ? "all" : "uncaught" }); + } + setPauseOnExceptions(captureAll) { + this._session.post("Debugger.setPauseOnExceptions", { state: captureAll ? "all" : "uncaught" }); + } + /** @inheritdoc */ + getLocalVariables(objectId, complete) { + this._getProperties(objectId, (props) => { + const { add, next } = createCallbackList(complete); + for (const prop of props) { + if (prop.value?.objectId && prop.value.className === "Array") { + const id = prop.value.objectId; + add((vars) => this._unrollArray(id, prop.name, vars, next)); + } else if (prop.value?.objectId && prop.value.className === "Object") { + const id = prop.value.objectId; + add((vars) => this._unrollObject(id, prop.name, vars, next)); + } else if (prop.value) { + add((vars) => this._unrollOther(prop, vars, next)); + } + } + next({}); + }); + } + /** + * Gets all the PropertyDescriptors of an object + */ + _getProperties(objectId, next) { + this._session.post( + "Runtime.getProperties", + { + objectId, + ownProperties: true + }, + (err, params) => { + if (err) { + next([]); + } else { + next(params.result); + } + } + ); + } + /** + * Unrolls an array property + */ + _unrollArray(objectId, name, vars, next) { + this._getProperties(objectId, (props) => { + vars[name] = props.filter((v) => v.name !== "length" && !isNaN(parseInt(v.name, 10))).sort((a, b) => parseInt(a.name, 10) - parseInt(b.name, 10)).map((v) => v.value?.value); + next(vars); + }); + } + /** + * Unrolls an object property + */ + _unrollObject(objectId, name, vars, next) { + this._getProperties(objectId, (props) => { + vars[name] = props.map((v) => [v.name, v.value?.value]).reduce((obj, [key, val]) => { + obj[key] = val; + return obj; + }, {}); + next(vars); + }); + } + /** + * Unrolls other properties + */ + _unrollOther(prop, vars, next) { + if (prop.value) { + if ("value" in prop.value) { + if (prop.value.value === void 0 || prop.value.value === null) { + vars[prop.name] = `<${prop.value.value}>`; + } else { + vars[prop.name] = prop.value.value; + } + } else if ("description" in prop.value && prop.value.type !== "function") { + vars[prop.name] = `<${prop.value.description}>`; + } else if (prop.value.type === "undefined") { + vars[prop.name] = ""; + } + } + next(vars); + } +} +const INTEGRATION_NAME$v = "LocalVariables"; +const _localVariablesSyncIntegration = ((options = {}, sessionOverride) => { + const cachedFrames = new LRUMap(20); + let rateLimiter; + let shouldProcessEvent = false; + function addLocalVariablesToException(exception) { + const hash = hashFrames(exception.stacktrace?.frames); + if (hash === void 0) { + return; + } + const cachedFrame = cachedFrames.remove(hash); + if (cachedFrame === void 0) { + return; + } + const frames = (exception.stacktrace?.frames || []).filter((frame) => frame.function !== "new Promise"); + for (let i = 0; i < frames.length; i++) { + const frameIndex = frames.length - i - 1; + const cachedFrameVariable = cachedFrame[i]; + const frameVariable = frames[frameIndex]; + if (!frameVariable || !cachedFrameVariable) { + break; + } + if ( + // We need to have vars to add + cachedFrameVariable.vars === void 0 || // Only skip out-of-app frames if includeOutOfAppFrames is not true + frameVariable.in_app === false && options.includeOutOfAppFrames !== true || // The function names need to match + !functionNamesMatch(frameVariable.function, cachedFrameVariable.function) + ) { + continue; + } + frameVariable.vars = cachedFrameVariable.vars; + } + } + function addLocalVariablesToEvent(event) { + for (const exception of event.exception?.values || []) { + addLocalVariablesToException(exception); + } + return event; + } + let setupPromise; + async function setup() { + const client = getClient(); + const clientOptions = client?.getOptions(); + if (!clientOptions?.includeLocalVariables) { + return; + } + const unsupportedNodeVersion = NODE_MAJOR < 18; + if (unsupportedNodeVersion) { + debug$2.log("The `LocalVariables` integration is only supported on Node >= v18."); + return; + } + if (await isDebuggerEnabled()) { + debug$2.warn("Local variables capture has been disabled because the debugger was already enabled"); + return; + } + try { + const session = await AsyncSession.create(sessionOverride); + const handlePaused = (stackParser, { params: { reason, data, callFrames } }, complete) => { + if (reason !== "exception" && reason !== "promiseRejection") { + complete(); + return; + } + rateLimiter?.(); + const exceptionHash = hashFromStack(stackParser, data.description); + if (exceptionHash == void 0) { + complete(); + return; + } + const { add, next } = createCallbackList((frames) => { + cachedFrames.set(exceptionHash, frames); + complete(); + }); + for (let i = 0; i < Math.min(callFrames.length, 5); i++) { + const { scopeChain, functionName, this: obj } = callFrames[i]; + const localScope = scopeChain.find((scope) => scope.type === "local"); + const fn = obj.className === "global" || !obj.className ? functionName : `${obj.className}.${functionName}`; + if (localScope?.object.objectId === void 0) { + add((frames) => { + frames[i] = { function: fn }; + next(frames); + }); + } else { + const id = localScope.object.objectId; + add( + (frames) => session.getLocalVariables(id, (vars) => { + frames[i] = { function: fn, vars }; + next(frames); + }) + ); + } + } + next([]); + }; + const captureAll = options.captureAllExceptions !== false; + session.configureAndConnect( + (ev, complete) => handlePaused(clientOptions.stackParser, ev, complete), + captureAll + ); + if (captureAll) { + const max = options.maxExceptionsPerSecond || 50; + rateLimiter = createRateLimiter( + max, + () => { + debug$2.log("Local variables rate-limit lifted."); + session.setPauseOnExceptions(true); + }, + (seconds) => { + debug$2.log( + `Local variables rate-limit exceeded. Disabling capturing of caught exceptions for ${seconds} seconds.` + ); + session.setPauseOnExceptions(false); + } + ); + } + shouldProcessEvent = true; + } catch (error2) { + debug$2.log("The `LocalVariables` integration failed to start.", error2); + } + } + return { + name: INTEGRATION_NAME$v, + setupOnce() { + setupPromise = setup(); + }, + async processEvent(event) { + await setupPromise; + if (shouldProcessEvent) { + return addLocalVariablesToEvent(event); + } + return event; + }, + // These are entirely for testing + _getCachedFramesCount() { + return cachedFrames.size; + }, + _getFirstCachedFrame() { + return cachedFrames.values()[0]; + } + }; +}); +const localVariablesSyncIntegration = defineIntegration(_localVariablesSyncIntegration); +const localVariablesIntegration = (options = {}) => { + return NODE_VERSION.major < 19 ? localVariablesSyncIntegration(options) : localVariablesAsyncIntegration(options); +}; +function isCjs() { + try { + return typeof module !== "undefined" && typeof module.exports !== "undefined"; + } catch { + return false; + } +} +let hasWarnedAboutNodeVersion; +function supportsEsmLoaderHooks() { + if (isCjs()) { + return false; + } + if (NODE_MAJOR >= 21 || NODE_MAJOR === 20 && NODE_MINOR >= 6 || NODE_MAJOR === 18 && NODE_MINOR >= 19) { + return true; + } + if (!hasWarnedAboutNodeVersion) { + hasWarnedAboutNodeVersion = true; + consoleSandbox(() => { + console.warn( + `[Sentry] You are using Node.js v${process.versions.node} in ESM mode ("import syntax"). The Sentry Node.js SDK is not compatible with ESM in Node.js versions before 18.19.0 or before 20.6.0. Please either build your application with CommonJS ("require() syntax"), or upgrade your Node.js version.` + ); + }); + } + return false; +} +let moduleCache; +const INTEGRATION_NAME$u = "Modules"; +const SERVER_MODULES = typeof __SENTRY_SERVER_MODULES__ === "undefined" ? {} : __SENTRY_SERVER_MODULES__; +const _modulesIntegration = (() => { + return { + name: INTEGRATION_NAME$u, + processEvent(event) { + event.modules = { + ...event.modules, + ..._getModules() + }; + return event; + }, + getModules: _getModules + }; +}); +const modulesIntegration = _modulesIntegration; +function getRequireCachePaths() { + try { + return require.cache ? Object.keys(require.cache) : []; + } catch { + return []; + } +} +function collectModules() { + return { + ...SERVER_MODULES, + ...getModulesFromPackageJson(), + ...isCjs() ? collectRequireModules() : {} + }; +} +function collectRequireModules() { + const mainPaths = require.main?.paths || []; + const paths = getRequireCachePaths(); + const infos = {}; + const seen = /* @__PURE__ */ new Set(); + paths.forEach((path2) => { + let dir = path2; + const updir = () => { + const orig = dir; + dir = dirname$1(orig); + if (!dir || orig === dir || seen.has(orig)) { + return void 0; + } + if (mainPaths.indexOf(dir) < 0) { + return updir(); + } + const pkgfile = join(orig, "package.json"); + seen.add(orig); + if (!existsSync(pkgfile)) { + return updir(); + } + try { + const info = JSON.parse(readFileSync$1(pkgfile, "utf8")); + infos[info.name] = info.version; + } catch { + } + }; + updir(); + }); + return infos; +} +function _getModules() { + if (!moduleCache) { + moduleCache = collectModules(); + } + return moduleCache; +} +function getPackageJson() { + try { + const filePath = join(process.cwd(), "package.json"); + const packageJson = JSON.parse(readFileSync$1(filePath, "utf8")); + return packageJson; + } catch { + return {}; + } +} +function getModulesFromPackageJson() { + const packageJson = getPackageJson(); + return { + ...packageJson.dependencies, + ...packageJson.devDependencies + }; +} +const DEFAULT_SHUTDOWN_TIMEOUT = 2e3; +function logAndExitProcess(error2) { + consoleSandbox(() => { + console.error(error2); + }); + const client = getClient(); + if (client === void 0) { + DEBUG_BUILD$2 && debug$2.warn("No NodeClient was defined, we are exiting the process now."); + global.process.exit(1); + return; + } + const options = client.getOptions(); + const timeout = options?.shutdownTimeout && options.shutdownTimeout > 0 ? options.shutdownTimeout : DEFAULT_SHUTDOWN_TIMEOUT; + client.close(timeout).then( + (result) => { + if (!result) { + DEBUG_BUILD$2 && debug$2.warn("We reached the timeout for emptying the request buffer, still exiting now!"); + } + global.process.exit(1); + }, + (error3) => { + DEBUG_BUILD$2 && debug$2.error(error3); + } + ); +} +const INTEGRATION_NAME$t = "OnUncaughtException"; +const onUncaughtExceptionIntegration = defineIntegration((options = {}) => { + const optionsWithDefaults = { + exitEvenIfOtherHandlersAreRegistered: false, + ...options + }; + return { + name: INTEGRATION_NAME$t, + setup(client) { + global.process.on("uncaughtException", makeErrorHandler(client, optionsWithDefaults)); + } + }; +}); +function makeErrorHandler(client, options) { + const timeout = 2e3; + let caughtFirstError = false; + let caughtSecondError = false; + let calledFatalError = false; + let firstError; + const clientOptions = client.getOptions(); + return Object.assign( + (error2) => { + let onFatalError = logAndExitProcess; + if (options.onFatalError) { + onFatalError = options.onFatalError; + } else if (clientOptions.onFatalError) { + onFatalError = clientOptions.onFatalError; + } + const userProvidedListenersCount = global.process.listeners("uncaughtException").filter( + (listener) => { + return ( + // as soon as we're using domains this listener is attached by node itself + listener.name !== "domainUncaughtExceptionClear" && // the handler we register for tracing + listener.tag !== "sentry_tracingErrorCallback" && // the handler we register in this integration + listener._errorHandler !== true + ); + } + ).length; + const processWouldExit = userProvidedListenersCount === 0; + const shouldApplyFatalHandlingLogic = options.exitEvenIfOtherHandlersAreRegistered || processWouldExit; + if (!caughtFirstError) { + firstError = error2; + caughtFirstError = true; + if (getClient() === client) { + captureException(error2, { + originalException: error2, + captureContext: { + level: "fatal" + }, + mechanism: { + handled: false, + type: "auto.node.onuncaughtexception" + } + }); + } + if (!calledFatalError && shouldApplyFatalHandlingLogic) { + calledFatalError = true; + onFatalError(error2); + } + } else { + if (shouldApplyFatalHandlingLogic) { + if (calledFatalError) { + DEBUG_BUILD$2 && debug$2.warn( + "uncaught exception after calling fatal error shutdown callback - this is bad! forcing shutdown" + ); + logAndExitProcess(error2); + } else if (!caughtSecondError) { + caughtSecondError = true; + setTimeout(() => { + if (!calledFatalError) { + calledFatalError = true; + onFatalError(firstError, error2); + } + }, timeout); + } + } + } + }, + { _errorHandler: true } + ); +} +const INTEGRATION_NAME$s = "OnUnhandledRejection"; +const DEFAULT_IGNORES = [ + { + name: "AI_NoOutputGeneratedError" + // When stream aborts in Vercel AI SDK, Vercel flush() fails with an error + } +]; +const _onUnhandledRejectionIntegration = ((options = {}) => { + const opts = { + mode: options.mode ?? "warn", + ignore: [...DEFAULT_IGNORES, ...options.ignore ?? []] + }; + return { + name: INTEGRATION_NAME$s, + setup(client) { + global.process.on("unhandledRejection", makeUnhandledPromiseHandler(client, opts)); + } + }; +}); +const onUnhandledRejectionIntegration = defineIntegration(_onUnhandledRejectionIntegration); +function extractErrorInfo(reason) { + if (typeof reason !== "object" || reason === null) { + return { name: "", message: String(reason ?? "") }; + } + const errorLike = reason; + const name = typeof errorLike.name === "string" ? errorLike.name : ""; + const message = typeof errorLike.message === "string" ? errorLike.message : String(reason); + return { name, message }; +} +function isMatchingReason(matcher, errorInfo) { + const nameMatches = matcher.name === void 0 || isMatchingPattern(errorInfo.name, matcher.name, true); + const messageMatches = matcher.message === void 0 || isMatchingPattern(errorInfo.message, matcher.message); + return nameMatches && messageMatches; +} +function matchesIgnore(list, reason) { + const errorInfo = extractErrorInfo(reason); + return list.some((matcher) => isMatchingReason(matcher, errorInfo)); +} +function makeUnhandledPromiseHandler(client, options) { + return function sendUnhandledPromise(reason, promise) { + if (getClient() !== client) { + return; + } + if (matchesIgnore(options.ignore ?? [], reason)) { + return; + } + const level = options.mode === "strict" ? "fatal" : "error"; + const activeSpanForError = reason && typeof reason === "object" ? reason._sentry_active_span : void 0; + const activeSpanWrapper = activeSpanForError ? (fn) => withActiveSpan$1(activeSpanForError, fn) : (fn) => fn(); + activeSpanWrapper(() => { + captureException(reason, { + originalException: promise, + captureContext: { + extra: { unhandledPromiseRejection: true }, + level + }, + mechanism: { + handled: false, + type: "auto.node.onunhandledrejection" + } + }); + }); + handleRejection(reason, options.mode); + }; +} +function handleRejection(reason, mode) { + const rejectionWarning = "This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). The promise rejected with the reason:"; + if (mode === "warn") { + consoleSandbox(() => { + console.warn(rejectionWarning); + console.error(reason && typeof reason === "object" && "stack" in reason ? reason.stack : reason); + }); + } else if (mode === "strict") { + consoleSandbox(() => { + console.warn(rejectionWarning); + }); + logAndExitProcess(reason); + } +} +const INTEGRATION_NAME$r = "Spotlight"; +const _spotlightIntegration = ((options = {}) => { + const _options = { + sidecarUrl: options.sidecarUrl || "http://localhost:8969/stream" + }; + return { + name: INTEGRATION_NAME$r, + setup(client) { + try { + if (process.env.NODE_ENV && process.env.NODE_ENV !== "development") { + debug$2.warn("[Spotlight] It seems you're not in dev mode. Do you really want to have Spotlight enabled?"); + } + } catch { + } + connectToSpotlight(client, _options); + } + }; +}); +const spotlightIntegration = defineIntegration(_spotlightIntegration); +function connectToSpotlight(client, options) { + const spotlightUrl = parseSidecarUrl(options.sidecarUrl); + if (!spotlightUrl) { + return; + } + let failedRequests = 0; + client.on("beforeEnvelope", (envelope) => { + if (failedRequests > 3) { + debug$2.warn("[Spotlight] Disabled Sentry -> Spotlight integration due to too many failed requests"); + return; + } + const serializedEnvelope = serializeEnvelope(envelope); + suppressTracing$2(() => { + const req = http$1.request( + { + method: "POST", + path: spotlightUrl.pathname, + hostname: spotlightUrl.hostname, + port: spotlightUrl.port, + headers: { + "Content-Type": "application/x-sentry-envelope" + } + }, + (res) => { + if (res.statusCode && res.statusCode >= 200 && res.statusCode < 400) { + failedRequests = 0; + } + res.on("data", () => { + }); + res.on("end", () => { + }); + res.setEncoding("utf8"); + } + ); + req.on("error", () => { + failedRequests++; + debug$2.warn("[Spotlight] Failed to send envelope to Spotlight Sidecar"); + }); + req.write(serializedEnvelope); + req.end(); + }); + }); +} +function parseSidecarUrl(url) { + try { + return new URL(`${url}`); + } catch { + debug$2.warn(`[Spotlight] Invalid sidecar URL: ${url}`); + return void 0; + } +} +const INTEGRATION_NAME$q = "NodeSystemError"; +function isSystemError(error2) { + if (!(error2 instanceof Error)) { + return false; + } + if (!("errno" in error2) || typeof error2.errno !== "number") { + return false; + } + return util.getSystemErrorMap().has(error2.errno); +} +const systemErrorIntegration = defineIntegration((options = {}) => { + return { + name: INTEGRATION_NAME$q, + processEvent: (event, hint, client) => { + if (!isSystemError(hint.originalException)) { + return event; + } + const error2 = hint.originalException; + const errorContext = { + ...error2 + }; + if (!client.getOptions().sendDefaultPii && options.includePaths !== true) { + delete errorContext.path; + delete errorContext.dest; + } + event.contexts = { + ...event.contexts, + node_system_error: errorContext + }; + for (const exception of event.exception?.values || []) { + if (exception.value) { + if (error2.path && exception.value.includes(error2.path)) { + exception.value = exception.value.replace(`'${error2.path}'`, "").trim(); + } + if (error2.dest && exception.value.includes(error2.dest)) { + exception.value = exception.value.replace(`'${error2.dest}'`, "").trim(); + } + } + } + return event; + } + }; +}); +const INTEGRATION_NAME$p = "ChildProcess"; +const childProcessIntegration = defineIntegration((options = {}) => { + return { + name: INTEGRATION_NAME$p, + setup() { + diagnosticsChannel.channel("child_process").subscribe((event) => { + if (event && typeof event === "object" && "process" in event) { + captureChildProcessEvents(event.process, options); + } + }); + diagnosticsChannel.channel("worker_threads").subscribe((event) => { + if (event && typeof event === "object" && "worker" in event) { + captureWorkerThreadEvents(event.worker, options); + } + }); + } + }; +}); +function captureChildProcessEvents(child, options) { + let hasExited = false; + let data; + child.on("spawn", () => { + if (child.spawnfile === "/usr/bin/sw_vers") { + hasExited = true; + return; + } + data = { spawnfile: child.spawnfile }; + if (options.includeChildProcessArgs) { + data.spawnargs = child.spawnargs; + } + }).on("exit", (code) => { + if (!hasExited) { + hasExited = true; + if (code !== null && code !== 0) { + addBreadcrumb({ + category: "child_process", + message: `Child process exited with code '${code}'`, + level: code === 0 ? "info" : "warning", + data + }); + } + } + }).on("error", (error2) => { + if (!hasExited) { + hasExited = true; + addBreadcrumb({ + category: "child_process", + message: `Child process errored with '${error2.message}'`, + level: "error", + data + }); + } + }); +} +function captureWorkerThreadEvents(worker, options) { + let threadId2; + worker.on("online", () => { + threadId2 = worker.threadId; + }).on("error", (error2) => { + if (options.captureWorkerErrors !== false) { + captureException(error2, { + mechanism: { type: "auto.child_process.worker_thread", handled: false, data: { threadId: String(threadId2) } } + }); + } else { + addBreadcrumb({ + category: "worker_thread", + message: `Worker thread errored with '${error2.message}'`, + level: "error", + data: { threadId: threadId2 } + }); + } + }); +} +var src$k = {}; +var AsyncHooksContextManager = {}; +var AbstractAsyncHooksContextManager = {}; +var hasRequiredAbstractAsyncHooksContextManager; +function requireAbstractAsyncHooksContextManager() { + if (hasRequiredAbstractAsyncHooksContextManager) return AbstractAsyncHooksContextManager; + hasRequiredAbstractAsyncHooksContextManager = 1; + Object.defineProperty(AbstractAsyncHooksContextManager, "__esModule", { value: true }); + AbstractAsyncHooksContextManager.AbstractAsyncHooksContextManager = void 0; + const events_1 = require$$5; + const ADD_LISTENER_METHODS = [ + "addListener", + "on", + "once", + "prependListener", + "prependOnceListener" + ]; + let AbstractAsyncHooksContextManager$1 = class AbstractAsyncHooksContextManager { + /** + * Binds a the certain context or the active one to the target function and then returns the target + * @param context A context (span) to be bind to target + * @param target a function or event emitter. When target or one of its callbacks is called, + * the provided context will be used as the active context for the duration of the call. + */ + bind(context2, target) { + if (target instanceof events_1.EventEmitter) { + return this._bindEventEmitter(context2, target); + } + if (typeof target === "function") { + return this._bindFunction(context2, target); + } + return target; + } + _bindFunction(context2, target) { + const manager = this; + const contextWrapper = function(...args) { + return manager.with(context2, () => target.apply(this, args)); + }; + Object.defineProperty(contextWrapper, "length", { + enumerable: false, + configurable: true, + writable: false, + value: target.length + }); + return contextWrapper; + } + /** + * By default, EventEmitter call their callback with their context, which we do + * not want, instead we will bind a specific context to all callbacks that + * go through it. + * @param context the context we want to bind + * @param ee EventEmitter an instance of EventEmitter to patch + */ + _bindEventEmitter(context2, ee) { + const map = this._getPatchMap(ee); + if (map !== void 0) + return ee; + this._createPatchMap(ee); + ADD_LISTENER_METHODS.forEach((methodName) => { + if (ee[methodName] === void 0) + return; + ee[methodName] = this._patchAddListener(ee, ee[methodName], context2); + }); + if (typeof ee.removeListener === "function") { + ee.removeListener = this._patchRemoveListener(ee, ee.removeListener); + } + if (typeof ee.off === "function") { + ee.off = this._patchRemoveListener(ee, ee.off); + } + if (typeof ee.removeAllListeners === "function") { + ee.removeAllListeners = this._patchRemoveAllListeners(ee, ee.removeAllListeners); + } + return ee; + } + /** + * Patch methods that remove a given listener so that we match the "patched" + * version of that listener (the one that propagate context). + * @param ee EventEmitter instance + * @param original reference to the patched method + */ + _patchRemoveListener(ee, original) { + const contextManager = this; + return function(event, listener) { + const events = contextManager._getPatchMap(ee)?.[event]; + if (events === void 0) { + return original.call(this, event, listener); + } + const patchedListener = events.get(listener); + return original.call(this, event, patchedListener || listener); + }; + } + /** + * Patch methods that remove all listeners so we remove our + * internal references for a given event. + * @param ee EventEmitter instance + * @param original reference to the patched method + */ + _patchRemoveAllListeners(ee, original) { + const contextManager = this; + return function(event) { + const map = contextManager._getPatchMap(ee); + if (map !== void 0) { + if (arguments.length === 0) { + contextManager._createPatchMap(ee); + } else if (map[event] !== void 0) { + delete map[event]; + } + } + return original.apply(this, arguments); + }; + } + /** + * Patch methods on an event emitter instance that can add listeners so we + * can force them to propagate a given context. + * @param ee EventEmitter instance + * @param original reference to the patched method + * @param [context] context to propagate when calling listeners + */ + _patchAddListener(ee, original, context2) { + const contextManager = this; + return function(event, listener) { + if (contextManager._wrapped) { + return original.call(this, event, listener); + } + let map = contextManager._getPatchMap(ee); + if (map === void 0) { + map = contextManager._createPatchMap(ee); + } + let listeners = map[event]; + if (listeners === void 0) { + listeners = /* @__PURE__ */ new WeakMap(); + map[event] = listeners; + } + const patchedListener = contextManager.bind(context2, listener); + listeners.set(listener, patchedListener); + contextManager._wrapped = true; + try { + return original.call(this, event, patchedListener); + } finally { + contextManager._wrapped = false; + } + }; + } + _createPatchMap(ee) { + const map = /* @__PURE__ */ Object.create(null); + ee[this._kOtListeners] = map; + return map; + } + _getPatchMap(ee) { + return ee[this._kOtListeners]; + } + _kOtListeners = Symbol("OtListeners"); + _wrapped = false; + }; + AbstractAsyncHooksContextManager.AbstractAsyncHooksContextManager = AbstractAsyncHooksContextManager$1; + return AbstractAsyncHooksContextManager; +} +var hasRequiredAsyncHooksContextManager; +function requireAsyncHooksContextManager() { + if (hasRequiredAsyncHooksContextManager) return AsyncHooksContextManager; + hasRequiredAsyncHooksContextManager = 1; + Object.defineProperty(AsyncHooksContextManager, "__esModule", { value: true }); + AsyncHooksContextManager.AsyncHooksContextManager = void 0; + const api_1 = /* @__PURE__ */ requireSrc$n(); + const asyncHooks = require$$1$1; + const AbstractAsyncHooksContextManager_1 = /* @__PURE__ */ requireAbstractAsyncHooksContextManager(); + let AsyncHooksContextManager$1 = class AsyncHooksContextManager extends AbstractAsyncHooksContextManager_1.AbstractAsyncHooksContextManager { + _asyncHook; + _contexts = /* @__PURE__ */ new Map(); + _stack = []; + constructor() { + super(); + this._asyncHook = asyncHooks.createHook({ + init: this._init.bind(this), + before: this._before.bind(this), + after: this._after.bind(this), + destroy: this._destroy.bind(this), + promiseResolve: this._destroy.bind(this) + }); + } + active() { + return this._stack[this._stack.length - 1] ?? api_1.ROOT_CONTEXT; + } + with(context2, fn, thisArg, ...args) { + this._enterContext(context2); + try { + return fn.call(thisArg, ...args); + } finally { + this._exitContext(); + } + } + enable() { + this._asyncHook.enable(); + return this; + } + disable() { + this._asyncHook.disable(); + this._contexts.clear(); + this._stack = []; + return this; + } + /** + * Init hook will be called when userland create a async context, setting the + * context as the current one if it exist. + * @param uid id of the async context + * @param type the resource type + */ + _init(uid, type) { + if (type === "TIMERWRAP") + return; + const context2 = this._stack[this._stack.length - 1]; + if (context2 !== void 0) { + this._contexts.set(uid, context2); + } + } + /** + * Destroy hook will be called when a given context is no longer used so we can + * remove its attached context. + * @param uid uid of the async context + */ + _destroy(uid) { + this._contexts.delete(uid); + } + /** + * Before hook is called just before executing a async context. + * @param uid uid of the async context + */ + _before(uid) { + const context2 = this._contexts.get(uid); + if (context2 !== void 0) { + this._enterContext(context2); + } + } + /** + * After hook is called just after completing the execution of a async context. + */ + _after() { + this._exitContext(); + } + /** + * Set the given context as active + */ + _enterContext(context2) { + this._stack.push(context2); + } + /** + * Remove the context at the root of the stack + */ + _exitContext() { + this._stack.pop(); + } + }; + AsyncHooksContextManager.AsyncHooksContextManager = AsyncHooksContextManager$1; + return AsyncHooksContextManager; +} +var AsyncLocalStorageContextManager = {}; +var hasRequiredAsyncLocalStorageContextManager; +function requireAsyncLocalStorageContextManager() { + if (hasRequiredAsyncLocalStorageContextManager) return AsyncLocalStorageContextManager; + hasRequiredAsyncLocalStorageContextManager = 1; + Object.defineProperty(AsyncLocalStorageContextManager, "__esModule", { value: true }); + AsyncLocalStorageContextManager.AsyncLocalStorageContextManager = void 0; + const api_1 = /* @__PURE__ */ requireSrc$n(); + const async_hooks_1 = require$$1$1; + const AbstractAsyncHooksContextManager_1 = /* @__PURE__ */ requireAbstractAsyncHooksContextManager(); + let AsyncLocalStorageContextManager$1 = class AsyncLocalStorageContextManager extends AbstractAsyncHooksContextManager_1.AbstractAsyncHooksContextManager { + _asyncLocalStorage; + constructor() { + super(); + this._asyncLocalStorage = new async_hooks_1.AsyncLocalStorage(); + } + active() { + return this._asyncLocalStorage.getStore() ?? api_1.ROOT_CONTEXT; + } + with(context2, fn, thisArg, ...args) { + const cb = thisArg == null ? fn : fn.bind(thisArg); + return this._asyncLocalStorage.run(context2, cb, ...args); + } + enable() { + return this; + } + disable() { + this._asyncLocalStorage.disable(); + return this; + } + }; + AsyncLocalStorageContextManager.AsyncLocalStorageContextManager = AsyncLocalStorageContextManager$1; + return AsyncLocalStorageContextManager; +} +var hasRequiredSrc$k; +function requireSrc$k() { + if (hasRequiredSrc$k) return src$k; + hasRequiredSrc$k = 1; + (function(exports$1) { + Object.defineProperty(exports$1, "__esModule", { value: true }); + exports$1.AsyncLocalStorageContextManager = exports$1.AsyncHooksContextManager = void 0; + var AsyncHooksContextManager_1 = /* @__PURE__ */ requireAsyncHooksContextManager(); + Object.defineProperty(exports$1, "AsyncHooksContextManager", { enumerable: true, get: function() { + return AsyncHooksContextManager_1.AsyncHooksContextManager; + } }); + var AsyncLocalStorageContextManager_1 = /* @__PURE__ */ requireAsyncLocalStorageContextManager(); + Object.defineProperty(exports$1, "AsyncLocalStorageContextManager", { enumerable: true, get: function() { + return AsyncLocalStorageContextManager_1.AsyncLocalStorageContextManager; + } }); + })(src$k); + return src$k; +} +var srcExports$i = /* @__PURE__ */ requireSrc$k(); +const SentryContextManager = wrapContextManagerClass(srcExports$i.AsyncLocalStorageContextManager); +function setupOpenTelemetryLogger() { + srcExports$l.diag.disable(); + srcExports$l.diag.setLogger( + { + error: debug$2.error, + warn: debug$2.warn, + info: debug$2.log, + debug: debug$2.log, + verbose: debug$2.log + }, + srcExports$l.DiagLogLevel.DEBUG + ); +} +const INTEGRATION_NAME$o = "ProcessSession"; +const processSessionIntegration = defineIntegration(() => { + return { + name: INTEGRATION_NAME$o, + setupOnce() { + startSession(); + process.on("beforeExit", () => { + const session = getIsolationScope().getSession(); + if (session?.status !== "ok") { + endSession(); + } + }); + } + }; +}); +const INTERNAL = Symbol("AgentBaseInternalState"); +class Agent extends http$1.Agent { + // Set by `http.Agent` - missing from `@types/node` + constructor(opts) { + super(opts); + this[INTERNAL] = {}; + } + /** + * Determine whether this is an `http` or `https` request. + */ + isSecureEndpoint(options) { + if (options) { + if (typeof options.secureEndpoint === "boolean") { + return options.secureEndpoint; + } + if (typeof options.protocol === "string") { + return options.protocol === "https:"; + } + } + const { stack } = new Error(); + if (typeof stack !== "string") return false; + return stack.split("\n").some((l) => l.indexOf("(https.js:") !== -1 || l.indexOf("node:https:") !== -1); + } + createSocket(req, options, cb) { + const connectOpts = { + ...options, + secureEndpoint: this.isSecureEndpoint(options) + }; + Promise.resolve().then(() => this.connect(req, connectOpts)).then((socket) => { + if (socket instanceof http$1.Agent) { + return socket.addRequest(req, connectOpts); + } + this[INTERNAL].currentSocket = socket; + super.createSocket(req, options, cb); + }, cb); + } + createConnection() { + const socket = this[INTERNAL].currentSocket; + this[INTERNAL].currentSocket = void 0; + if (!socket) { + throw new Error("No socket was returned in the `connect()` function"); + } + return socket; + } + get defaultPort() { + return this[INTERNAL].defaultPort ?? (this.protocol === "https:" ? 443 : 80); + } + set defaultPort(v) { + if (this[INTERNAL]) { + this[INTERNAL].defaultPort = v; + } + } + get protocol() { + return this[INTERNAL].protocol ?? (this.isSecureEndpoint() ? "https:" : "http:"); + } + set protocol(v) { + if (this[INTERNAL]) { + this[INTERNAL].protocol = v; + } + } +} +function debugLog$1(...args) { + debug$2.log("[https-proxy-agent:parse-proxy-response]", ...args); +} +function parseProxyResponse(socket) { + return new Promise((resolve, reject) => { + let buffersLength = 0; + const buffers = []; + function read() { + const b = socket.read(); + if (b) ondata(b); + else socket.once("readable", read); + } + function cleanup() { + socket.removeListener("end", onend); + socket.removeListener("error", onerror); + socket.removeListener("readable", read); + } + function onend() { + cleanup(); + debugLog$1("onend"); + reject(new Error("Proxy connection ended before receiving CONNECT response")); + } + function onerror(err) { + cleanup(); + debugLog$1("onerror %o", err); + reject(err); + } + function ondata(b) { + buffers.push(b); + buffersLength += b.length; + const buffered = Buffer.concat(buffers, buffersLength); + const endOfHeaders = buffered.indexOf("\r\n\r\n"); + if (endOfHeaders === -1) { + debugLog$1("have not received end of HTTP headers yet..."); + read(); + return; + } + const headerParts = buffered.subarray(0, endOfHeaders).toString("ascii").split("\r\n"); + const firstLine = headerParts.shift(); + if (!firstLine) { + socket.destroy(); + return reject(new Error("No header received from proxy CONNECT response")); + } + const firstLineParts = firstLine.split(" "); + const statusCode = +(firstLineParts[1] || 0); + const statusText = firstLineParts.slice(2).join(" "); + const headers = {}; + for (const header of headerParts) { + if (!header) continue; + const firstColon = header.indexOf(":"); + if (firstColon === -1) { + socket.destroy(); + return reject(new Error(`Invalid header from proxy CONNECT response: "${header}"`)); + } + const key = header.slice(0, firstColon).toLowerCase(); + const value = header.slice(firstColon + 1).trimStart(); + const current = headers[key]; + if (typeof current === "string") { + headers[key] = [current, value]; + } else if (Array.isArray(current)) { + current.push(value); + } else { + headers[key] = value; + } + } + debugLog$1("got proxy server response: %o %o", firstLine, headers); + cleanup(); + resolve({ + connect: { + statusCode, + statusText, + headers + }, + buffered + }); + } + socket.on("error", onerror); + socket.on("end", onend); + read(); + }); +} +function debugLog(...args) { + debug$2.log("[https-proxy-agent]", ...args); +} +class HttpsProxyAgent extends Agent { + static __initStatic() { + this.protocols = ["http", "https"]; + } + constructor(proxy, opts) { + super(opts); + this.options = {}; + this.proxy = typeof proxy === "string" ? new URL(proxy) : proxy; + this.proxyHeaders = opts?.headers ?? {}; + debugLog("Creating new HttpsProxyAgent instance: %o", this.proxy.href); + const host = (this.proxy.hostname || this.proxy.host).replace(/^\[|\]$/g, ""); + const port = this.proxy.port ? parseInt(this.proxy.port, 10) : this.proxy.protocol === "https:" ? 443 : 80; + this.connectOpts = { + // Attempt to negotiate http/1.1 for proxy servers that support http/2 + ALPNProtocols: ["http/1.1"], + ...opts ? omit(opts, "headers") : null, + host, + port + }; + } + /** + * Called when the node-core HTTP client library is creating a + * new HTTP request. + */ + async connect(req, opts) { + const { proxy } = this; + if (!opts.host) { + throw new TypeError('No "host" provided'); + } + let socket; + if (proxy.protocol === "https:") { + debugLog("Creating `tls.Socket`: %o", this.connectOpts); + const servername = this.connectOpts.servername || this.connectOpts.host; + socket = tls.connect({ + ...this.connectOpts, + servername: servername && net.isIP(servername) ? void 0 : servername + }); + } else { + debugLog("Creating `net.Socket`: %o", this.connectOpts); + socket = net.connect(this.connectOpts); + } + const headers = typeof this.proxyHeaders === "function" ? this.proxyHeaders() : { ...this.proxyHeaders }; + const host = net.isIPv6(opts.host) ? `[${opts.host}]` : opts.host; + let payload = `CONNECT ${host}:${opts.port} HTTP/1.1\r +`; + if (proxy.username || proxy.password) { + const auth = `${decodeURIComponent(proxy.username)}:${decodeURIComponent(proxy.password)}`; + headers["Proxy-Authorization"] = `Basic ${Buffer.from(auth).toString("base64")}`; + } + headers.Host = `${host}:${opts.port}`; + if (!headers["Proxy-Connection"]) { + headers["Proxy-Connection"] = this.keepAlive ? "Keep-Alive" : "close"; + } + for (const name of Object.keys(headers)) { + payload += `${name}: ${headers[name]}\r +`; + } + const proxyResponsePromise = parseProxyResponse(socket); + socket.write(`${payload}\r +`); + const { connect, buffered } = await proxyResponsePromise; + req.emit("proxyConnect", connect); + this.emit("proxyConnect", connect, req); + if (connect.statusCode === 200) { + req.once("socket", resume); + if (opts.secureEndpoint) { + debugLog("Upgrading socket connection to TLS"); + const servername = opts.servername || opts.host; + return tls.connect({ + ...omit(opts, "host", "path", "port"), + socket, + servername: net.isIP(servername) ? void 0 : servername + }); + } + return socket; + } + socket.destroy(); + const fakeSocket = new net.Socket({ writable: false }); + fakeSocket.readable = true; + req.once("socket", (s) => { + debugLog("Replaying proxy buffer for failed request"); + s.push(buffered); + s.push(null); + }); + return fakeSocket; + } +} +HttpsProxyAgent.__initStatic(); +function resume(socket) { + socket.resume(); +} +function omit(obj, ...keys) { + const ret = {}; + let key; + for (key in obj) { + if (!keys.includes(key)) { + ret[key] = obj[key]; + } + } + return ret; +} +const GZIP_THRESHOLD = 1024 * 32; +function streamFromBody(body) { + return new Readable({ + read() { + this.push(body); + this.push(null); + } + }); +} +function makeNodeTransport(options) { + let urlSegments; + try { + urlSegments = new URL(options.url); + } catch (e) { + consoleSandbox(() => { + console.warn( + "[@sentry/node]: Invalid dsn or tunnel option, will not send any events. The tunnel option must be a full URL when used." + ); + }); + return createTransport(options, () => Promise.resolve({})); + } + const isHttps = urlSegments.protocol === "https:"; + const proxy = applyNoProxyOption( + urlSegments, + options.proxy || (isHttps ? process.env.https_proxy : void 0) || process.env.http_proxy + ); + const nativeHttpModule = isHttps ? https : http$1; + const keepAlive = options.keepAlive === void 0 ? false : options.keepAlive; + const agent = proxy ? new HttpsProxyAgent(proxy) : new nativeHttpModule.Agent({ keepAlive, maxSockets: 30, timeout: 2e3 }); + const requestExecutor = createRequestExecutor(options, options.httpModule ?? nativeHttpModule, agent); + return createTransport(options, requestExecutor); +} +function applyNoProxyOption(transportUrlSegments, proxy) { + const { no_proxy } = process.env; + const urlIsExemptFromProxy = no_proxy?.split(",").some( + (exemption) => transportUrlSegments.host.endsWith(exemption) || transportUrlSegments.hostname.endsWith(exemption) + ); + if (urlIsExemptFromProxy) { + return void 0; + } else { + return proxy; + } +} +function createRequestExecutor(options, httpModule, agent) { + const { hostname, pathname, port, protocol, search } = new URL(options.url); + return function makeRequest(request) { + return new Promise((resolve, reject) => { + suppressTracing$2(() => { + let body = streamFromBody(request.body); + const headers = { ...options.headers }; + if (request.body.length > GZIP_THRESHOLD) { + headers["content-encoding"] = "gzip"; + body = body.pipe(createGzip()); + } + const hostnameIsIPv6 = hostname.startsWith("["); + const req = httpModule.request( + { + method: "POST", + agent, + headers, + // Remove "[" and "]" from IPv6 hostnames + hostname: hostnameIsIPv6 ? hostname.slice(1, -1) : hostname, + path: `${pathname}${search}`, + port, + protocol, + ca: options.caCerts + }, + (res) => { + res.on("data", () => { + }); + res.on("end", () => { + }); + res.setEncoding("utf8"); + const retryAfterHeader = res.headers["retry-after"] ?? null; + const rateLimitsHeader = res.headers["x-sentry-rate-limits"] ?? null; + resolve({ + statusCode: res.statusCode, + headers: { + "retry-after": retryAfterHeader, + "x-sentry-rate-limits": Array.isArray(rateLimitsHeader) ? rateLimitsHeader[0] || null : rateLimitsHeader + } + }); + } + ); + req.on("error", reject); + body.pipe(req); + }); + }); + }; +} +const FALSY_ENV_VALUES = /* @__PURE__ */ new Set(["false", "f", "n", "no", "off", "0"]); +const TRUTHY_ENV_VALUES = /* @__PURE__ */ new Set(["true", "t", "y", "yes", "on", "1"]); +function envToBool(value, options) { + const normalized = String(value).toLowerCase(); + if (FALSY_ENV_VALUES.has(normalized)) { + return false; + } + if (TRUTHY_ENV_VALUES.has(normalized)) { + return true; + } + return options?.strict ? null : Boolean(value); +} +function normalizeWindowsPath(path2) { + return path2.replace(/^[A-Z]:/, "").replace(/\\/g, "/"); +} +function createGetModuleFromFilename(basePath = process.argv[1] ? dirname(process.argv[1]) : process.cwd(), isWindows = sep$1 === "\\") { + const normalizedBase = isWindows ? normalizeWindowsPath(basePath) : basePath; + return (filename) => { + if (!filename) { + return; + } + const normalizedFilename = isWindows ? normalizeWindowsPath(filename) : filename; + let { dir, base: file, ext: ext2 } = posix.parse(normalizedFilename); + if (ext2 === ".js" || ext2 === ".mjs" || ext2 === ".cjs") { + file = file.slice(0, ext2.length * -1); + } + const decodedFile = decodeURIComponent(file); + if (!dir) { + dir = "."; + } + const n = dir.lastIndexOf("/node_modules"); + if (n > -1) { + return `${dir.slice(n + 14).replace(/\//g, ".")}:${decodedFile}`; + } + if (dir.startsWith(normalizedBase)) { + const moduleName = dir.slice(normalizedBase.length + 1).replace(/\//g, "."); + return moduleName ? `${moduleName}:${decodedFile}` : decodedFile; + } + return decodedFile; + }; +} +function getSentryRelease(fallback) { + if (process.env.SENTRY_RELEASE) { + return process.env.SENTRY_RELEASE; + } + if (GLOBAL_OBJ.SENTRY_RELEASE?.id) { + return GLOBAL_OBJ.SENTRY_RELEASE.id; + } + const possibleReleaseNameOfGitProvider = ( + // GitHub Actions - https://help.github.com/en/actions/configuring-and-managing-workflows/using-environment-variables#default-environment-variables + process.env["GITHUB_SHA"] || // GitLab CI - https://docs.gitlab.com/ee/ci/variables/predefined_variables.html + process.env["CI_MERGE_REQUEST_SOURCE_BRANCH_SHA"] || process.env["CI_BUILD_REF"] || process.env["CI_COMMIT_SHA"] || // Bitbucket - https://support.atlassian.com/bitbucket-cloud/docs/variables-and-secrets/ + process.env["BITBUCKET_COMMIT"] + ); + const possibleReleaseNameOfCiProvidersWithSpecificEnvVar = ( + // AppVeyor - https://www.appveyor.com/docs/environment-variables/ + process.env["APPVEYOR_PULL_REQUEST_HEAD_COMMIT"] || process.env["APPVEYOR_REPO_COMMIT"] || // AWS CodeBuild - https://docs.aws.amazon.com/codebuild/latest/userguide/build-env-ref-env-vars.html + process.env["CODEBUILD_RESOLVED_SOURCE_VERSION"] || // AWS Amplify - https://docs.aws.amazon.com/amplify/latest/userguide/environment-variables.html + process.env["AWS_COMMIT_ID"] || // Azure Pipelines - https://docs.microsoft.com/en-us/azure/devops/pipelines/build/variables?view=azure-devops&tabs=yaml + process.env["BUILD_SOURCEVERSION"] || // Bitrise - https://devcenter.bitrise.io/builds/available-environment-variables/ + process.env["GIT_CLONE_COMMIT_HASH"] || // Buddy CI - https://buddy.works/docs/pipelines/environment-variables#default-environment-variables + process.env["BUDDY_EXECUTION_REVISION"] || // Builtkite - https://buildkite.com/docs/pipelines/environment-variables + process.env["BUILDKITE_COMMIT"] || // CircleCI - https://circleci.com/docs/variables/ + process.env["CIRCLE_SHA1"] || // Cirrus CI - https://cirrus-ci.org/guide/writing-tasks/#environment-variables + process.env["CIRRUS_CHANGE_IN_REPO"] || // Codefresh - https://codefresh.io/docs/docs/codefresh-yaml/variables/ + process.env["CF_REVISION"] || // Codemagic - https://docs.codemagic.io/yaml-basic-configuration/environment-variables/ + process.env["CM_COMMIT"] || // Cloudflare Pages - https://developers.cloudflare.com/pages/platform/build-configuration/#environment-variables + process.env["CF_PAGES_COMMIT_SHA"] || // Drone - https://docs.drone.io/pipeline/environment/reference/ + process.env["DRONE_COMMIT_SHA"] || // Flightcontrol - https://www.flightcontrol.dev/docs/guides/flightcontrol/environment-variables#built-in-environment-variables + process.env["FC_GIT_COMMIT_SHA"] || // Heroku #1 https://devcenter.heroku.com/articles/heroku-ci + process.env["HEROKU_TEST_RUN_COMMIT_VERSION"] || // Heroku #2 https://docs.sentry.io/product/integrations/deployment/heroku/#configure-releases + process.env["HEROKU_SLUG_COMMIT"] || // Railway - https://docs.railway.app/reference/variables#git-variables + process.env["RAILWAY_GIT_COMMIT_SHA"] || // Render - https://render.com/docs/environment-variables + process.env["RENDER_GIT_COMMIT"] || // Semaphore CI - https://docs.semaphoreci.com/ci-cd-environment/environment-variables + process.env["SEMAPHORE_GIT_SHA"] || // TravisCI - https://docs.travis-ci.com/user/environment-variables/#default-environment-variables + process.env["TRAVIS_PULL_REQUEST_SHA"] || // Vercel - https://vercel.com/docs/v2/build-step#system-environment-variables + process.env["VERCEL_GIT_COMMIT_SHA"] || process.env["VERCEL_GITHUB_COMMIT_SHA"] || process.env["VERCEL_GITLAB_COMMIT_SHA"] || process.env["VERCEL_BITBUCKET_COMMIT_SHA"] || // Zeit (now known as Vercel) + process.env["ZEIT_GITHUB_COMMIT_SHA"] || process.env["ZEIT_GITLAB_COMMIT_SHA"] || process.env["ZEIT_BITBUCKET_COMMIT_SHA"] + ); + const possibleReleaseNameOfCiProvidersWithGenericEnvVar = ( + // CloudBees CodeShip - https://docs.cloudbees.com/docs/cloudbees-codeship/latest/pro-builds-and-configuration/environment-variables + process.env["CI_COMMIT_ID"] || // Coolify - https://coolify.io/docs/knowledge-base/environment-variables + process.env["SOURCE_COMMIT"] || // Heroku #3 https://devcenter.heroku.com/changelog-items/630 + process.env["SOURCE_VERSION"] || // Jenkins - https://plugins.jenkins.io/git/#environment-variables + process.env["GIT_COMMIT"] || // Netlify - https://docs.netlify.com/configure-builds/environment-variables/#build-metadata + process.env["COMMIT_REF"] || // TeamCity - https://www.jetbrains.com/help/teamcity/predefined-build-parameters.html + process.env["BUILD_VCS_NUMBER"] || // Woodpecker CI - https://woodpecker-ci.org/docs/usage/environment + process.env["CI_COMMIT_SHA"] + ); + return possibleReleaseNameOfGitProvider || possibleReleaseNameOfCiProvidersWithSpecificEnvVar || possibleReleaseNameOfCiProvidersWithGenericEnvVar || fallback; +} +const defaultStackParser = createStackParser(nodeStackLineParser(createGetModuleFromFilename())); +const DEFAULT_CLIENT_REPORT_FLUSH_INTERVAL_MS = 6e4; +class NodeClient extends ServerRuntimeClient { + constructor(options) { + const serverName = options.includeServerName === false ? void 0 : options.serverName || global.process.env.SENTRY_NAME || os.hostname(); + const clientOptions = { + ...options, + platform: "node", + runtime: { name: "node", version: global.process.version }, + serverName + }; + if (options.openTelemetryInstrumentations) { + registerInstrumentations({ + instrumentations: options.openTelemetryInstrumentations + }); + } + applySdkMetadata(clientOptions, "node"); + debug$2.log(`Initializing Sentry: process: ${process.pid}, thread: ${isMainThread ? "main" : `worker-${threadId}`}.`); + super(clientOptions); + if (this.getOptions().enableLogs) { + this._logOnExitFlushListener = () => { + _INTERNAL_flushLogsBuffer(this); + }; + if (serverName) { + this.on("beforeCaptureLog", (log2) => { + log2.attributes = { + ...log2.attributes, + "server.address": serverName + }; + }); + } + process.on("beforeExit", this._logOnExitFlushListener); + } + } + /** Get the OTEL tracer. */ + get tracer() { + if (this._tracer) { + return this._tracer; + } + const name = "@sentry/node"; + const version2 = SDK_VERSION; + const tracer = srcExports$l.trace.getTracer(name, version2); + this._tracer = tracer; + return tracer; + } + /** @inheritDoc */ + // @ts-expect-error - PromiseLike is a subset of Promise + async flush(timeout) { + await this.traceProvider?.forceFlush(); + if (this.getOptions().sendClientReports) { + this._flushOutcomes(); + } + return super.flush(timeout); + } + /** @inheritDoc */ + // @ts-expect-error - PromiseLike is a subset of Promise + async close(timeout) { + if (this._clientReportInterval) { + clearInterval(this._clientReportInterval); + } + if (this._clientReportOnExitFlushListener) { + process.off("beforeExit", this._clientReportOnExitFlushListener); + } + if (this._logOnExitFlushListener) { + process.off("beforeExit", this._logOnExitFlushListener); + } + const allEventsSent = await super.close(timeout); + if (this.traceProvider) { + await this.traceProvider.shutdown(); + } + return allEventsSent; + } + /** + * Will start tracking client reports for this client. + * + * NOTICE: This method will create an interval that is periodically called and attach a `process.on('beforeExit')` + * hook. To clean up these resources, call `.close()` when you no longer intend to use the client. Not doing so will + * result in a memory leak. + */ + // The reason client reports need to be manually activated with this method instead of just enabling them in a + // constructor, is that if users periodically and unboundedly create new clients, we will create more and more + // intervals and beforeExit listeners, thus leaking memory. In these situations, users are required to call + // `client.close()` in order to dispose of the acquired resources. + // We assume that calling this method in Sentry.init() is a sensible default, because calling Sentry.init() over and + // over again would also result in memory leaks. + // Note: We have experimented with using `FinalizationRegisty` to clear the interval when the client is garbage + // collected, but it did not work, because the cleanup function never got called. + startClientReportTracking() { + const clientOptions = this.getOptions(); + if (clientOptions.sendClientReports) { + this._clientReportOnExitFlushListener = () => { + this._flushOutcomes(); + }; + this._clientReportInterval = setInterval(() => { + DEBUG_BUILD$2 && debug$2.log("Flushing client reports based on interval."); + this._flushOutcomes(); + }, clientOptions.clientReportFlushInterval ?? DEFAULT_CLIENT_REPORT_FLUSH_INTERVAL_MS).unref(); + process.on("beforeExit", this._clientReportOnExitFlushListener); + } + } + /** @inheritDoc */ + _setupIntegrations() { + _INTERNAL_clearAiProviderSkips(); + super._setupIntegrations(); + } + /** Custom implementation for OTEL, so we can handle scope-span linking. */ + _getTraceInfoFromScope(scope) { + if (!scope) { + return [void 0, void 0]; + } + return getTraceContextForScope(this, scope); + } +} +function initializeEsmLoader() { + if (!supportsEsmLoaderHooks()) { + return; + } + if (!GLOBAL_OBJ._sentryEsmLoaderHookRegistered) { + GLOBAL_OBJ._sentryEsmLoaderHookRegistered = true; + try { + const { addHookMessagePort } = importInTheMiddleExports.createAddHookMessageChannel(); + moduleModule.register("import-in-the-middle/hook.mjs", import.meta.url, { + data: { addHookMessagePort, include: [] }, + transferList: [addHookMessagePort] + }); + } catch (error2) { + debug$2.warn("Failed to register 'import-in-the-middle' hook", error2); + } + } +} +function getDefaultIntegrations$1() { + return [ + // Common + // TODO(v11): Replace with `eventFiltersIntegration` once we remove the deprecated `inboundFiltersIntegration` + // eslint-disable-next-line deprecation/deprecation + inboundFiltersIntegration(), + functionToStringIntegration(), + linkedErrorsIntegration(), + requestDataIntegration(), + systemErrorIntegration(), + // Native Wrappers + consoleIntegration(), + httpIntegration$1(), + nativeNodeFetchIntegration$1(), + // Global Handlers + onUncaughtExceptionIntegration(), + onUnhandledRejectionIntegration(), + // Event Info + contextLinesIntegration(), + localVariablesIntegration(), + nodeContextIntegration(), + childProcessIntegration(), + processSessionIntegration(), + modulesIntegration() + ]; +} +function init$2(options = {}) { + return _init$1(options, getDefaultIntegrations$1); +} +function _init$1(_options = {}, getDefaultIntegrationsImpl) { + const options = getClientOptions(_options, getDefaultIntegrationsImpl); + if (options.debug === true) { + if (DEBUG_BUILD$2) { + debug$2.enable(); + } else { + consoleSandbox(() => { + console.warn("[Sentry] Cannot initialize SDK with `debug` option using a non-debug bundle."); + }); + } + } + if (options.registerEsmLoaderHooks !== false) { + initializeEsmLoader(); + } + setOpenTelemetryContextAsyncContextStrategy(); + const scope = getCurrentScope(); + scope.update(options.initialScope); + if (options.spotlight && !options.integrations.some(({ name }) => name === INTEGRATION_NAME$r)) { + options.integrations.push( + spotlightIntegration({ + sidecarUrl: typeof options.spotlight === "string" ? options.spotlight : void 0 + }) + ); + } + applySdkMetadata(options, "node-core"); + const client = new NodeClient(options); + getCurrentScope().setClient(client); + client.init(); + GLOBAL_OBJ._sentryInjectLoaderHookRegister?.(); + debug$2.log(`SDK initialized from ${isCjs() ? "CommonJS" : "ESM"}`); + client.startClientReportTracking(); + updateScopeFromEnvVariables(); + enhanceDscWithOpenTelemetryRootSpanName(client); + setupEventContextTrace(client); + if (process.env.VERCEL) { + process.on("SIGTERM", async () => { + await client.flush(200); + }); + } + return client; +} +function validateOpenTelemetrySetup() { + if (!DEBUG_BUILD$2) { + return; + } + const setup = openTelemetrySetupCheck(); + const required = ["SentryContextManager", "SentryPropagator"]; + if (hasSpansEnabled()) { + required.push("SentrySpanProcessor"); + } + for (const k of required) { + if (!setup.includes(k)) { + debug$2.error( + `You have to set up the ${k}. Without this, the OpenTelemetry & Sentry integration will not work properly.` + ); + } + } + if (!setup.includes("SentrySampler")) { + debug$2.warn( + "You have to set up the SentrySampler. Without this, the OpenTelemetry & Sentry integration may still work, but sample rates set for the Sentry SDK will not be respected. If you use a custom sampler, make sure to use `wrapSamplingDecision`." + ); + } +} +function getClientOptions(options, getDefaultIntegrationsImpl) { + const release = getRelease(options.release); + let spotlight; + if (options.spotlight === false) { + spotlight = false; + } else if (typeof options.spotlight === "string") { + spotlight = options.spotlight; + } else { + const envBool = envToBool(process.env.SENTRY_SPOTLIGHT, { strict: true }); + const envUrl = envBool === null && process.env.SENTRY_SPOTLIGHT ? process.env.SENTRY_SPOTLIGHT : void 0; + spotlight = options.spotlight === true ? envUrl ?? true : envBool ?? envUrl; + } + const tracesSampleRate = getTracesSampleRate(options.tracesSampleRate); + const mergedOptions = { + ...options, + dsn: options.dsn ?? process.env.SENTRY_DSN, + environment: options.environment ?? process.env.SENTRY_ENVIRONMENT, + sendClientReports: options.sendClientReports ?? true, + transport: options.transport ?? makeNodeTransport, + stackParser: stackParserFromStackParserOptions(options.stackParser || defaultStackParser), + release, + tracesSampleRate, + spotlight, + debug: envToBool(options.debug ?? process.env.SENTRY_DEBUG) + }; + const integrations = options.integrations; + const defaultIntegrations = options.defaultIntegrations ?? getDefaultIntegrationsImpl(mergedOptions); + return { + ...mergedOptions, + integrations: getIntegrationsToSetup({ + defaultIntegrations, + integrations + }) + }; +} +function getRelease(release) { + if (release !== void 0) { + return release; + } + const detectedRelease = getSentryRelease(); + if (detectedRelease !== void 0) { + return detectedRelease; + } + return void 0; +} +function getTracesSampleRate(tracesSampleRate) { + if (tracesSampleRate !== void 0) { + return tracesSampleRate; + } + const sampleRateFromEnv = process.env.SENTRY_TRACES_SAMPLE_RATE; + if (!sampleRateFromEnv) { + return void 0; + } + const parsed = parseFloat(sampleRateFromEnv); + return isFinite(parsed) ? parsed : void 0; +} +function updateScopeFromEnvVariables() { + if (envToBool(process.env.SENTRY_USE_ENVIRONMENT) !== false) { + const sentryTraceEnv = process.env.SENTRY_TRACE; + const baggageEnv = process.env.SENTRY_BAGGAGE; + const propagationContext = propagationContextFromHeaders(sentryTraceEnv, baggageEnv); + getCurrentScope().setPropagationContext(propagationContext); + } +} +function addOriginToSpan(span, origin) { + span.setAttribute(SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN, origin); +} +const INTEGRATION_NAME$n = "Http"; +const INSTRUMENTATION_NAME = "@opentelemetry_sentry-patched/instrumentation-http"; +const instrumentSentryHttp = generateInstrumentOnce( + `${INTEGRATION_NAME$n}.sentry`, + (options) => { + return new SentryHttpInstrumentation(options); + } +); +const instrumentOtelHttp = generateInstrumentOnce(INTEGRATION_NAME$n, (config2) => { + const instrumentation2 = new srcExports$j.HttpInstrumentation({ + ...config2, + // This is hard-coded and can never be overridden by the user + disableIncomingRequestInstrumentation: true + }); + try { + instrumentation2["_diag"] = srcExports$l.diag.createComponentLogger({ + namespace: INSTRUMENTATION_NAME + }); + instrumentation2.instrumentationName = INSTRUMENTATION_NAME; + } catch { + } + return instrumentation2; +}); +function _shouldUseOtelHttpInstrumentation(options, clientOptions = {}) { + if (typeof options.spans === "boolean") { + return options.spans; + } + if (clientOptions.skipOpenTelemetrySetup) { + return false; + } + if (!hasSpansEnabled(clientOptions) && NODE_VERSION.major >= 22) { + return false; + } + return true; +} +const httpIntegration = defineIntegration((options = {}) => { + const spans = options.spans ?? true; + const disableIncomingRequestSpans = options.disableIncomingRequestSpans; + const serverOptions = { + sessions: options.trackIncomingRequestsAsSessions, + sessionFlushingDelayMS: options.sessionFlushingDelayMS, + ignoreRequestBody: options.ignoreIncomingRequestBody, + maxRequestBodySize: options.maxIncomingRequestBodySize + }; + const serverSpansOptions = { + ignoreIncomingRequests: options.ignoreIncomingRequests, + ignoreStaticAssets: options.ignoreStaticAssets, + ignoreStatusCodes: options.dropSpansForIncomingRequestStatusCodes, + instrumentation: options.instrumentation, + onSpanCreated: options.incomingRequestSpanHook + }; + const server = httpServerIntegration(serverOptions); + const serverSpans = httpServerSpansIntegration(serverSpansOptions); + const enableServerSpans = spans && !disableIncomingRequestSpans; + return { + name: INTEGRATION_NAME$n, + setup(client) { + const clientOptions = client.getOptions(); + if (enableServerSpans && hasSpansEnabled(clientOptions)) { + serverSpans.setup(client); + } + }, + setupOnce() { + const clientOptions = getClient()?.getOptions() || {}; + const useOtelHttpInstrumentation = _shouldUseOtelHttpInstrumentation(options, clientOptions); + server.setupOnce(); + const sentryHttpInstrumentationOptions = { + breadcrumbs: options.breadcrumbs, + propagateTraceInOutgoingRequests: !useOtelHttpInstrumentation, + ignoreOutgoingRequests: options.ignoreOutgoingRequests + }; + instrumentSentryHttp(sentryHttpInstrumentationOptions); + if (useOtelHttpInstrumentation) { + const instrumentationConfig = getConfigWithDefaults$1(options); + instrumentOtelHttp(instrumentationConfig); + } + }, + processEvent(event) { + return serverSpans.processEvent(event); + } + }; +}); +function getConfigWithDefaults$1(options = {}) { + const instrumentationConfig = { + ignoreOutgoingRequestHook: (request) => { + const url = getRequestUrl$1(request); + if (!url) { + return false; + } + const _ignoreOutgoingRequests = options.ignoreOutgoingRequests; + if (_ignoreOutgoingRequests?.(url, request)) { + return true; + } + return false; + }, + requireParentforOutgoingSpans: false, + requestHook: (span, req) => { + addOriginToSpan(span, "auto.http.otel.http"); + options.instrumentation?.requestHook?.(span, req); + }, + responseHook: (span, res) => { + options.instrumentation?.responseHook?.(span, res); + }, + applyCustomAttributesOnSpan: (span, request, response) => { + options.instrumentation?.applyCustomAttributesOnSpan?.(span, request, response); + } + }; + return instrumentationConfig; +} +var src$j = {}; +var undici = {}; +var version$h = {}; +var hasRequiredVersion$h; +function requireVersion$h() { + if (hasRequiredVersion$h) return version$h; + hasRequiredVersion$h = 1; + Object.defineProperty(version$h, "__esModule", { value: true }); + version$h.PACKAGE_NAME = version$h.PACKAGE_VERSION = void 0; + version$h.PACKAGE_VERSION = "0.19.0"; + version$h.PACKAGE_NAME = "@opentelemetry/instrumentation-undici"; + return version$h; +} +var hasRequiredUndici; +function requireUndici() { + if (hasRequiredUndici) return undici; + hasRequiredUndici = 1; + Object.defineProperty(undici, "__esModule", { value: true }); + undici.UndiciInstrumentation = void 0; + const diagch2 = diagch__default; + const url_1 = require$$2$1; + const instrumentation_1 = require$$2; + const api_1 = /* @__PURE__ */ requireSrc$n(); + const core_1 = require$$1; + const semantic_conventions_1 = /* @__PURE__ */ requireSrc$m(); + const version_1 = /* @__PURE__ */ requireVersion$h(); + class UndiciInstrumentation extends instrumentation_1.InstrumentationBase { + _recordFromReq = /* @__PURE__ */ new WeakMap(); + constructor(config2 = {}) { + super(version_1.PACKAGE_NAME, version_1.PACKAGE_VERSION, config2); + } + // No need to instrument files/modules + init() { + return void 0; + } + disable() { + super.disable(); + this._channelSubs.forEach((sub) => sub.unsubscribe()); + this._channelSubs.length = 0; + } + enable() { + super.enable(); + this._channelSubs = this._channelSubs || []; + if (this._channelSubs.length > 0) { + return; + } + this.subscribeToChannel("undici:request:create", this.onRequestCreated.bind(this)); + this.subscribeToChannel("undici:client:sendHeaders", this.onRequestHeaders.bind(this)); + this.subscribeToChannel("undici:request:headers", this.onResponseHeaders.bind(this)); + this.subscribeToChannel("undici:request:trailers", this.onDone.bind(this)); + this.subscribeToChannel("undici:request:error", this.onError.bind(this)); + } + _updateMetricInstruments() { + this._httpClientDurationHistogram = this.meter.createHistogram(semantic_conventions_1.METRIC_HTTP_CLIENT_REQUEST_DURATION, { + description: "Measures the duration of outbound HTTP requests.", + unit: "s", + valueType: api_1.ValueType.DOUBLE, + advice: { + explicitBucketBoundaries: [ + 5e-3, + 0.01, + 0.025, + 0.05, + 0.075, + 0.1, + 0.25, + 0.5, + 0.75, + 1, + 2.5, + 5, + 7.5, + 10 + ] + } + }); + } + subscribeToChannel(diagnosticChannel, onMessage) { + const [major, minor] = process.version.replace("v", "").split(".").map((n) => Number(n)); + const useNewSubscribe = major > 18 || major === 18 && minor >= 19; + let unsubscribe2; + if (useNewSubscribe) { + diagch2.subscribe?.(diagnosticChannel, onMessage); + unsubscribe2 = () => diagch2.unsubscribe?.(diagnosticChannel, onMessage); + } else { + const channel = diagch2.channel(diagnosticChannel); + channel.subscribe(onMessage); + unsubscribe2 = () => channel.unsubscribe(onMessage); + } + this._channelSubs.push({ + name: diagnosticChannel, + unsubscribe: unsubscribe2 + }); + } + parseRequestHeaders(request) { + const result = /* @__PURE__ */ new Map(); + if (Array.isArray(request.headers)) { + for (let i = 0; i < request.headers.length; i += 2) { + const key = request.headers[i]; + const value = request.headers[i + 1]; + if (typeof key === "string") { + result.set(key.toLowerCase(), value); + } + } + } else if (typeof request.headers === "string") { + const headers = request.headers.split("\r\n"); + for (const line of headers) { + if (!line) { + continue; + } + const colonIndex = line.indexOf(":"); + if (colonIndex === -1) { + continue; + } + const key = line.substring(0, colonIndex).toLowerCase(); + const value = line.substring(colonIndex + 1).trim(); + const allValues = result.get(key); + if (allValues && Array.isArray(allValues)) { + allValues.push(value); + } else if (allValues) { + result.set(key, [allValues, value]); + } else { + result.set(key, value); + } + } + } + return result; + } + // This is the 1st message we receive for each request (fired after request creation). Here we will + // create the span and populate some atttributes, then link the span to the request for further + // span processing + onRequestCreated({ request }) { + const config2 = this.getConfig(); + const enabled2 = config2.enabled !== false; + const shouldIgnoreReq = (0, instrumentation_1.safeExecuteInTheMiddle)(() => !enabled2 || request.method === "CONNECT" || config2.ignoreRequestHook?.(request), (e) => e && this._diag.error("caught ignoreRequestHook error: ", e), true); + if (shouldIgnoreReq) { + return; + } + const startTime = (0, core_1.hrTime)(); + let requestUrl; + try { + requestUrl = new url_1.URL(request.path, request.origin); + } catch (err) { + this._diag.warn("could not determine url.full:", err); + return; + } + const urlScheme = requestUrl.protocol.replace(":", ""); + const requestMethod = this.getRequestMethod(request.method); + const attributes = { + [semantic_conventions_1.ATTR_HTTP_REQUEST_METHOD]: requestMethod, + [semantic_conventions_1.ATTR_HTTP_REQUEST_METHOD_ORIGINAL]: request.method, + [semantic_conventions_1.ATTR_URL_FULL]: requestUrl.toString(), + [semantic_conventions_1.ATTR_URL_PATH]: requestUrl.pathname, + [semantic_conventions_1.ATTR_URL_QUERY]: requestUrl.search, + [semantic_conventions_1.ATTR_URL_SCHEME]: urlScheme + }; + const schemePorts = { https: "443", http: "80" }; + const serverAddress = requestUrl.hostname; + const serverPort = requestUrl.port || schemePorts[urlScheme]; + attributes[semantic_conventions_1.ATTR_SERVER_ADDRESS] = serverAddress; + if (serverPort && !isNaN(Number(serverPort))) { + attributes[semantic_conventions_1.ATTR_SERVER_PORT] = Number(serverPort); + } + const headersMap = this.parseRequestHeaders(request); + const userAgentValues = headersMap.get("user-agent"); + if (userAgentValues) { + const userAgent = Array.isArray(userAgentValues) ? userAgentValues[userAgentValues.length - 1] : userAgentValues; + attributes[semantic_conventions_1.ATTR_USER_AGENT_ORIGINAL] = userAgent; + } + const hookAttributes = (0, instrumentation_1.safeExecuteInTheMiddle)(() => config2.startSpanHook?.(request), (e) => e && this._diag.error("caught startSpanHook error: ", e), true); + if (hookAttributes) { + Object.entries(hookAttributes).forEach(([key, val]) => { + attributes[key] = val; + }); + } + const activeCtx = api_1.context.active(); + const currentSpan = api_1.trace.getSpan(activeCtx); + let span; + if (config2.requireParentforSpans && (!currentSpan || !api_1.trace.isSpanContextValid(currentSpan.spanContext()))) { + span = api_1.trace.wrapSpanContext(api_1.INVALID_SPAN_CONTEXT); + } else { + span = this.tracer.startSpan(requestMethod === "_OTHER" ? "HTTP" : requestMethod, { + kind: api_1.SpanKind.CLIENT, + attributes + }, activeCtx); + } + (0, instrumentation_1.safeExecuteInTheMiddle)(() => config2.requestHook?.(span, request), (e) => e && this._diag.error("caught requestHook error: ", e), true); + const requestContext = api_1.trace.setSpan(api_1.context.active(), span); + const addedHeaders = {}; + api_1.propagation.inject(requestContext, addedHeaders); + const headerEntries = Object.entries(addedHeaders); + for (let i = 0; i < headerEntries.length; i++) { + const [k, v] = headerEntries[i]; + if (typeof request.addHeader === "function") { + request.addHeader(k, v); + } else if (typeof request.headers === "string") { + request.headers += `${k}: ${v}\r +`; + } else if (Array.isArray(request.headers)) { + request.headers.push(k, v); + } + } + this._recordFromReq.set(request, { span, attributes, startTime }); + } + // This is the 2nd message we receive for each request. It is fired when connection with + // the remote is established and about to send the first byte. Here we do have info about the + // remote address and port so we can populate some `network.*` attributes into the span + onRequestHeaders({ request, socket }) { + const record = this._recordFromReq.get(request); + if (!record) { + return; + } + const config2 = this.getConfig(); + const { span } = record; + const { remoteAddress, remotePort } = socket; + const spanAttributes = { + [semantic_conventions_1.ATTR_NETWORK_PEER_ADDRESS]: remoteAddress, + [semantic_conventions_1.ATTR_NETWORK_PEER_PORT]: remotePort + }; + if (config2.headersToSpanAttributes?.requestHeaders) { + const headersToAttribs = new Set(config2.headersToSpanAttributes.requestHeaders.map((n) => n.toLowerCase())); + const headersMap = this.parseRequestHeaders(request); + for (const [name, value] of headersMap.entries()) { + if (headersToAttribs.has(name)) { + const attrValue = Array.isArray(value) ? value.join(", ") : value; + spanAttributes[`http.request.header.${name}`] = attrValue; + } + } + } + span.setAttributes(spanAttributes); + } + // This is the 3rd message we get for each request and it's fired when the server + // headers are received, body may not be accessible yet. + // From the response headers we can set the status and content length + onResponseHeaders({ request, response }) { + const record = this._recordFromReq.get(request); + if (!record) { + return; + } + const { span, attributes } = record; + const spanAttributes = { + [semantic_conventions_1.ATTR_HTTP_RESPONSE_STATUS_CODE]: response.statusCode + }; + const config2 = this.getConfig(); + (0, instrumentation_1.safeExecuteInTheMiddle)(() => config2.responseHook?.(span, { request, response }), (e) => e && this._diag.error("caught responseHook error: ", e), true); + const headersToAttribs = /* @__PURE__ */ new Set(); + if (config2.headersToSpanAttributes?.responseHeaders) { + config2.headersToSpanAttributes?.responseHeaders.forEach((name) => headersToAttribs.add(name.toLowerCase())); + } + for (let idx = 0; idx < response.headers.length; idx = idx + 2) { + const name = response.headers[idx].toString().toLowerCase(); + const value = response.headers[idx + 1]; + if (headersToAttribs.has(name)) { + spanAttributes[`http.response.header.${name}`] = value.toString(); + } + if (name === "content-length") { + const contentLength = Number(value.toString()); + if (!isNaN(contentLength)) { + spanAttributes["http.response.header.content-length"] = contentLength; + } + } + } + span.setAttributes(spanAttributes); + span.setStatus({ + code: response.statusCode >= 400 ? api_1.SpanStatusCode.ERROR : api_1.SpanStatusCode.UNSET + }); + record.attributes = Object.assign(attributes, spanAttributes); + } + // This is the last event we receive if the request went without any errors + onDone({ request }) { + const record = this._recordFromReq.get(request); + if (!record) { + return; + } + const { span, attributes, startTime } = record; + span.end(); + this._recordFromReq.delete(request); + this.recordRequestDuration(attributes, startTime); + } + // This is the event we get when something is wrong in the request like + // - invalid options when calling `fetch` global API or any undici method for request + // - connectivity errors such as unreachable host + // - requests aborted through an `AbortController.signal` + // NOTE: server errors are considered valid responses and it's the lib consumer + // who should deal with that. + onError({ request, error: error2 }) { + const record = this._recordFromReq.get(request); + if (!record) { + return; + } + const { span, attributes, startTime } = record; + span.recordException(error2); + span.setStatus({ + code: api_1.SpanStatusCode.ERROR, + message: error2.message + }); + span.end(); + this._recordFromReq.delete(request); + attributes[semantic_conventions_1.ATTR_ERROR_TYPE] = error2.message; + this.recordRequestDuration(attributes, startTime); + } + recordRequestDuration(attributes, startTime) { + const metricsAttributes = {}; + const keysToCopy = [ + semantic_conventions_1.ATTR_HTTP_RESPONSE_STATUS_CODE, + semantic_conventions_1.ATTR_HTTP_REQUEST_METHOD, + semantic_conventions_1.ATTR_SERVER_ADDRESS, + semantic_conventions_1.ATTR_SERVER_PORT, + semantic_conventions_1.ATTR_URL_SCHEME, + semantic_conventions_1.ATTR_ERROR_TYPE + ]; + keysToCopy.forEach((key) => { + if (key in attributes) { + metricsAttributes[key] = attributes[key]; + } + }); + const durationSeconds = (0, core_1.hrTimeToMilliseconds)((0, core_1.hrTimeDuration)(startTime, (0, core_1.hrTime)())) / 1e3; + this._httpClientDurationHistogram.record(durationSeconds, metricsAttributes); + } + getRequestMethod(original) { + const knownMethods = { + CONNECT: true, + OPTIONS: true, + HEAD: true, + GET: true, + POST: true, + PUT: true, + PATCH: true, + DELETE: true, + TRACE: true + }; + if (original.toUpperCase() in knownMethods) { + return original.toUpperCase(); + } + return "_OTHER"; + } + } + undici.UndiciInstrumentation = UndiciInstrumentation; + return undici; +} +var hasRequiredSrc$j; +function requireSrc$j() { + if (hasRequiredSrc$j) return src$j; + hasRequiredSrc$j = 1; + (function(exports$1) { + Object.defineProperty(exports$1, "__esModule", { value: true }); + exports$1.UndiciInstrumentation = void 0; + var undici_1 = /* @__PURE__ */ requireUndici(); + Object.defineProperty(exports$1, "UndiciInstrumentation", { enumerable: true, get: function() { + return undici_1.UndiciInstrumentation; + } }); + })(src$j); + return src$j; +} +var srcExports$h = /* @__PURE__ */ requireSrc$j(); +const INTEGRATION_NAME$m = "NodeFetch"; +const instrumentOtelNodeFetch = generateInstrumentOnce( + INTEGRATION_NAME$m, + srcExports$h.UndiciInstrumentation, + (options) => { + return getConfigWithDefaults(options); + } +); +const instrumentSentryNodeFetch = generateInstrumentOnce( + `${INTEGRATION_NAME$m}.sentry`, + SentryNodeFetchInstrumentation, + (options) => { + return options; + } +); +const _nativeNodeFetchIntegration = ((options = {}) => { + return { + name: "NodeFetch", + setupOnce() { + const instrumentSpans = _shouldInstrumentSpans(options, getClient()?.getOptions()); + if (instrumentSpans) { + instrumentOtelNodeFetch(options); + } + instrumentSentryNodeFetch(options); + } + }; +}); +const nativeNodeFetchIntegration = defineIntegration(_nativeNodeFetchIntegration); +function getAbsoluteUrl(origin, path2 = "/") { + const url = `${origin}`; + if (url.endsWith("/") && path2.startsWith("/")) { + return `${url}${path2.slice(1)}`; + } + if (!url.endsWith("/") && !path2.startsWith("/")) { + return `${url}/${path2.slice(1)}`; + } + return `${url}${path2}`; +} +function _shouldInstrumentSpans(options, clientOptions = {}) { + return typeof options.spans === "boolean" ? options.spans : !clientOptions.skipOpenTelemetrySetup && hasSpansEnabled(clientOptions); +} +function getConfigWithDefaults(options = {}) { + const instrumentationConfig = { + requireParentforSpans: false, + ignoreRequestHook: (request) => { + const url = getAbsoluteUrl(request.origin, request.path); + const _ignoreOutgoingRequests = options.ignoreOutgoingRequests; + const shouldIgnore = _ignoreOutgoingRequests && url && _ignoreOutgoingRequests(url); + return !!shouldIgnore; + }, + startSpanHook: () => { + return { + [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: "auto.http.otel.node_fetch" + }; + }, + requestHook: options.requestHook, + responseHook: options.responseHook + }; + return instrumentationConfig; +} +var src$i = {}; +var instrumentation$f = {}; +var ExpressLayerType = {}; +var hasRequiredExpressLayerType; +function requireExpressLayerType() { + if (hasRequiredExpressLayerType) return ExpressLayerType; + hasRequiredExpressLayerType = 1; + (function(exports$1) { + Object.defineProperty(exports$1, "__esModule", { value: true }); + exports$1.ExpressLayerType = void 0; + (function(ExpressLayerType2) { + ExpressLayerType2["ROUTER"] = "router"; + ExpressLayerType2["MIDDLEWARE"] = "middleware"; + ExpressLayerType2["REQUEST_HANDLER"] = "request_handler"; + })(exports$1.ExpressLayerType || (exports$1.ExpressLayerType = {})); + })(ExpressLayerType); + return ExpressLayerType; +} +var AttributeNames$8 = {}; +var hasRequiredAttributeNames$6; +function requireAttributeNames$6() { + if (hasRequiredAttributeNames$6) return AttributeNames$8; + hasRequiredAttributeNames$6 = 1; + (function(exports$1) { + Object.defineProperty(exports$1, "__esModule", { value: true }); + exports$1.AttributeNames = void 0; + (function(AttributeNames2) { + AttributeNames2["EXPRESS_TYPE"] = "express.type"; + AttributeNames2["EXPRESS_NAME"] = "express.name"; + })(exports$1.AttributeNames || (exports$1.AttributeNames = {})); + })(AttributeNames$8); + return AttributeNames$8; +} +var utils$d = {}; +var internalTypes$7 = {}; +var hasRequiredInternalTypes$7; +function requireInternalTypes$7() { + if (hasRequiredInternalTypes$7) return internalTypes$7; + hasRequiredInternalTypes$7 = 1; + Object.defineProperty(internalTypes$7, "__esModule", { value: true }); + internalTypes$7._LAYERS_STORE_PROPERTY = internalTypes$7.kLayerPatched = void 0; + internalTypes$7.kLayerPatched = Symbol("express-layer-patched"); + internalTypes$7._LAYERS_STORE_PROPERTY = "__ot_middlewares"; + return internalTypes$7; +} +var hasRequiredUtils$d; +function requireUtils$d() { + if (hasRequiredUtils$d) return utils$d; + hasRequiredUtils$d = 1; + (function(exports$1) { + Object.defineProperty(exports$1, "__esModule", { value: true }); + exports$1.getActualMatchedRoute = exports$1.getConstructedRoute = exports$1.getLayerPath = exports$1.asErrorAndMessage = exports$1.isLayerIgnored = exports$1.getLayerMetadata = exports$1.getRouterPath = exports$1.storeLayerPath = void 0; + const ExpressLayerType_1 = requireExpressLayerType(); + const AttributeNames_1 = requireAttributeNames$6(); + const internal_types_1 = requireInternalTypes$7(); + const storeLayerPath = (request, value) => { + if (Array.isArray(request[internal_types_1._LAYERS_STORE_PROPERTY]) === false) { + Object.defineProperty(request, internal_types_1._LAYERS_STORE_PROPERTY, { + enumerable: false, + value: [] + }); + } + if (value === void 0) + return { isLayerPathStored: false }; + request[internal_types_1._LAYERS_STORE_PROPERTY].push(value); + return { isLayerPathStored: true }; + }; + exports$1.storeLayerPath = storeLayerPath; + const getRouterPath = (path2, layer) => { + const stackLayer = layer.handle?.stack?.[0]; + if (stackLayer?.route?.path) { + return `${path2}${stackLayer.route.path}`; + } + if (stackLayer?.handle?.stack) { + return (0, exports$1.getRouterPath)(path2, stackLayer); + } + return path2; + }; + exports$1.getRouterPath = getRouterPath; + const getLayerMetadata = (route, layer, layerPath) => { + if (layer.name === "router") { + const maybeRouterPath = (0, exports$1.getRouterPath)("", layer); + const extractedRouterPath = maybeRouterPath ? maybeRouterPath : layerPath || route || "/"; + return { + attributes: { + [AttributeNames_1.AttributeNames.EXPRESS_NAME]: extractedRouterPath, + [AttributeNames_1.AttributeNames.EXPRESS_TYPE]: ExpressLayerType_1.ExpressLayerType.ROUTER + }, + name: `router - ${extractedRouterPath}` + }; + } else if (layer.name === "bound dispatch" || layer.name === "handle") { + return { + attributes: { + [AttributeNames_1.AttributeNames.EXPRESS_NAME]: (route || layerPath) ?? "request handler", + [AttributeNames_1.AttributeNames.EXPRESS_TYPE]: ExpressLayerType_1.ExpressLayerType.REQUEST_HANDLER + }, + name: `request handler${layer.path ? ` - ${route || layerPath}` : ""}` + }; + } else { + return { + attributes: { + [AttributeNames_1.AttributeNames.EXPRESS_NAME]: layer.name, + [AttributeNames_1.AttributeNames.EXPRESS_TYPE]: ExpressLayerType_1.ExpressLayerType.MIDDLEWARE + }, + name: `middleware - ${layer.name}` + }; + } + }; + exports$1.getLayerMetadata = getLayerMetadata; + const satisfiesPattern = (constant, pattern) => { + if (typeof pattern === "string") { + return pattern === constant; + } else if (pattern instanceof RegExp) { + return pattern.test(constant); + } else if (typeof pattern === "function") { + return pattern(constant); + } else { + throw new TypeError("Pattern is in unsupported datatype"); + } + }; + const isLayerIgnored = (name, type, config2) => { + if (Array.isArray(config2?.ignoreLayersType) && config2?.ignoreLayersType?.includes(type)) { + return true; + } + if (Array.isArray(config2?.ignoreLayers) === false) + return false; + try { + for (const pattern of config2.ignoreLayers) { + if (satisfiesPattern(name, pattern)) { + return true; + } + } + } catch (e) { + } + return false; + }; + exports$1.isLayerIgnored = isLayerIgnored; + const asErrorAndMessage = (error2) => error2 instanceof Error ? [error2, error2.message] : [String(error2), String(error2)]; + exports$1.asErrorAndMessage = asErrorAndMessage; + const getLayerPath = (args) => { + const firstArg = args[0]; + if (Array.isArray(firstArg)) { + return firstArg.map((arg) => extractLayerPathSegment(arg) || "").join(","); + } + return extractLayerPathSegment(firstArg); + }; + exports$1.getLayerPath = getLayerPath; + const extractLayerPathSegment = (arg) => { + if (typeof arg === "string") { + return arg; + } + if (arg instanceof RegExp || typeof arg === "number") { + return arg.toString(); + } + return; + }; + function getConstructedRoute(req) { + const layersStore = Array.isArray(req[internal_types_1._LAYERS_STORE_PROPERTY]) ? req[internal_types_1._LAYERS_STORE_PROPERTY] : []; + const meaningfulPaths = layersStore.filter((path2) => path2 !== "/" && path2 !== "/*"); + if (meaningfulPaths.length === 1 && meaningfulPaths[0] === "*") { + return "*"; + } + return meaningfulPaths.join("").replace(/\/{2,}/g, "/"); + } + exports$1.getConstructedRoute = getConstructedRoute; + function getActualMatchedRoute(req) { + const layersStore = Array.isArray(req[internal_types_1._LAYERS_STORE_PROPERTY]) ? req[internal_types_1._LAYERS_STORE_PROPERTY] : []; + if (layersStore.length === 0) { + return void 0; + } + if (layersStore.every((path2) => path2 === "/")) { + return req.originalUrl === "/" ? "/" : void 0; + } + const constructedRoute = getConstructedRoute(req); + if (constructedRoute === "*") { + return constructedRoute; + } + if (constructedRoute.includes("/") && (constructedRoute.includes(",") || constructedRoute.includes("\\") || constructedRoute.includes("*") || constructedRoute.includes("["))) { + return constructedRoute; + } + const normalizedRoute = constructedRoute.startsWith("/") ? constructedRoute : `/${constructedRoute}`; + const isValidRoute = normalizedRoute.length > 0 && (req.originalUrl === normalizedRoute || req.originalUrl.startsWith(normalizedRoute) || isRoutePattern(normalizedRoute)); + return isValidRoute ? normalizedRoute : void 0; + } + exports$1.getActualMatchedRoute = getActualMatchedRoute; + function isRoutePattern(route) { + return route.includes(":") || route.includes("*"); + } + })(utils$d); + return utils$d; +} +var version$g = {}; +var hasRequiredVersion$g; +function requireVersion$g() { + if (hasRequiredVersion$g) return version$g; + hasRequiredVersion$g = 1; + Object.defineProperty(version$g, "__esModule", { value: true }); + version$g.PACKAGE_NAME = version$g.PACKAGE_VERSION = void 0; + version$g.PACKAGE_VERSION = "0.57.0"; + version$g.PACKAGE_NAME = "@opentelemetry/instrumentation-express"; + return version$g; +} +var hasRequiredInstrumentation$f; +function requireInstrumentation$f() { + if (hasRequiredInstrumentation$f) return instrumentation$f; + hasRequiredInstrumentation$f = 1; + Object.defineProperty(instrumentation$f, "__esModule", { value: true }); + instrumentation$f.ExpressInstrumentation = void 0; + const core_1 = require$$1; + const api_1 = /* @__PURE__ */ requireSrc$n(); + const ExpressLayerType_1 = requireExpressLayerType(); + const AttributeNames_1 = requireAttributeNames$6(); + const utils_1 = requireUtils$d(); + const version_1 = requireVersion$g(); + const instrumentation_1 = require$$2; + const semantic_conventions_1 = /* @__PURE__ */ requireSrc$m(); + const internal_types_1 = requireInternalTypes$7(); + class ExpressInstrumentation extends instrumentation_1.InstrumentationBase { + constructor(config2 = {}) { + super(version_1.PACKAGE_NAME, version_1.PACKAGE_VERSION, config2); + } + init() { + return [ + new instrumentation_1.InstrumentationNodeModuleDefinition("express", [">=4.0.0 <6"], (moduleExports) => { + const isExpressWithRouterPrototype = typeof moduleExports?.Router?.prototype?.route === "function"; + const routerProto = isExpressWithRouterPrototype ? moduleExports.Router.prototype : moduleExports.Router; + if ((0, instrumentation_1.isWrapped)(routerProto.route)) { + this._unwrap(routerProto, "route"); + } + this._wrap(routerProto, "route", this._getRoutePatch()); + if ((0, instrumentation_1.isWrapped)(routerProto.use)) { + this._unwrap(routerProto, "use"); + } + this._wrap(routerProto, "use", this._getRouterUsePatch()); + if ((0, instrumentation_1.isWrapped)(moduleExports.application.use)) { + this._unwrap(moduleExports.application, "use"); + } + this._wrap( + moduleExports.application, + "use", + // eslint-disable-next-line @typescript-eslint/no-explicit-any + this._getAppUsePatch(isExpressWithRouterPrototype) + ); + return moduleExports; + }, (moduleExports) => { + if (moduleExports === void 0) + return; + const isExpressWithRouterPrototype = typeof moduleExports?.Router?.prototype?.route === "function"; + const routerProto = isExpressWithRouterPrototype ? moduleExports.Router.prototype : moduleExports.Router; + this._unwrap(routerProto, "route"); + this._unwrap(routerProto, "use"); + this._unwrap(moduleExports.application, "use"); + }) + ]; + } + /** + * Get the patch for Router.route function + */ + _getRoutePatch() { + const instrumentation2 = this; + return function(original) { + return function route_trace(...args) { + const route = original.apply(this, args); + const layer = this.stack[this.stack.length - 1]; + instrumentation2._applyPatch(layer, (0, utils_1.getLayerPath)(args)); + return route; + }; + }; + } + /** + * Get the patch for Router.use function + */ + _getRouterUsePatch() { + const instrumentation2 = this; + return function(original) { + return function use(...args) { + const route = original.apply(this, args); + const layer = this.stack[this.stack.length - 1]; + instrumentation2._applyPatch(layer, (0, utils_1.getLayerPath)(args)); + return route; + }; + }; + } + /** + * Get the patch for Application.use function + */ + _getAppUsePatch(isExpressWithRouterPrototype) { + const instrumentation2 = this; + return function(original) { + return function use(...args) { + const router = isExpressWithRouterPrototype ? this.router : this._router; + const route = original.apply(this, args); + if (router) { + const layer = router.stack[router.stack.length - 1]; + instrumentation2._applyPatch(layer, (0, utils_1.getLayerPath)(args)); + } + return route; + }; + }; + } + /** Patch each express layer to create span and propagate context */ + _applyPatch(layer, layerPath) { + const instrumentation2 = this; + if (layer[internal_types_1.kLayerPatched] === true) + return; + layer[internal_types_1.kLayerPatched] = true; + this._wrap(layer, "handle", (original) => { + if (original.length === 4) + return original; + const patched = function(req, res) { + const { isLayerPathStored } = (0, utils_1.storeLayerPath)(req, layerPath); + const constructedRoute = (0, utils_1.getConstructedRoute)(req); + const actualMatchedRoute = (0, utils_1.getActualMatchedRoute)(req); + const attributes = { + [semantic_conventions_1.ATTR_HTTP_ROUTE]: actualMatchedRoute + }; + const metadata = (0, utils_1.getLayerMetadata)(constructedRoute, layer, layerPath); + const type = metadata.attributes[AttributeNames_1.AttributeNames.EXPRESS_TYPE]; + const rpcMetadata = (0, core_1.getRPCMetadata)(api_1.context.active()); + if (rpcMetadata?.type === core_1.RPCType.HTTP) { + rpcMetadata.route = actualMatchedRoute; + } + if ((0, utils_1.isLayerIgnored)(metadata.name, type, instrumentation2.getConfig())) { + if (type === ExpressLayerType_1.ExpressLayerType.MIDDLEWARE) { + req[internal_types_1._LAYERS_STORE_PROPERTY].pop(); + } + return original.apply(this, arguments); + } + if (api_1.trace.getSpan(api_1.context.active()) === void 0) { + return original.apply(this, arguments); + } + const spanName = instrumentation2._getSpanName({ + request: req, + layerType: type, + route: constructedRoute + }, metadata.name); + const span = instrumentation2.tracer.startSpan(spanName, { + attributes: Object.assign(attributes, metadata.attributes) + }); + const parentContext = api_1.context.active(); + let currentContext = api_1.trace.setSpan(parentContext, span); + const { requestHook: requestHook2 } = instrumentation2.getConfig(); + if (requestHook2) { + (0, instrumentation_1.safeExecuteInTheMiddle)(() => requestHook2(span, { + request: req, + layerType: type, + route: constructedRoute + }), (e) => { + if (e) { + api_1.diag.error("express instrumentation: request hook failed", e); + } + }, true); + } + let spanHasEnded = false; + if (metadata.attributes[AttributeNames_1.AttributeNames.EXPRESS_TYPE] === ExpressLayerType_1.ExpressLayerType.ROUTER) { + span.end(); + spanHasEnded = true; + currentContext = parentContext; + } + const onResponseFinish = () => { + if (spanHasEnded === false) { + spanHasEnded = true; + span.end(); + } + }; + const args = Array.from(arguments); + const callbackIdx = args.findIndex((arg) => typeof arg === "function"); + if (callbackIdx >= 0) { + arguments[callbackIdx] = function() { + const maybeError = arguments[0]; + const isError2 = ![void 0, null, "route", "router"].includes(maybeError); + if (!spanHasEnded && isError2) { + const [error2, message] = (0, utils_1.asErrorAndMessage)(maybeError); + span.recordException(error2); + span.setStatus({ + code: api_1.SpanStatusCode.ERROR, + message + }); + } + if (spanHasEnded === false) { + spanHasEnded = true; + req.res?.removeListener("finish", onResponseFinish); + span.end(); + } + if (!(req.route && isError2) && isLayerPathStored) { + req[internal_types_1._LAYERS_STORE_PROPERTY].pop(); + } + const callback = args[callbackIdx]; + return api_1.context.bind(parentContext, callback).apply(this, arguments); + }; + } + try { + return api_1.context.bind(currentContext, original).apply(this, arguments); + } catch (anyError) { + const [error2, message] = (0, utils_1.asErrorAndMessage)(anyError); + span.recordException(error2); + span.setStatus({ + code: api_1.SpanStatusCode.ERROR, + message + }); + throw anyError; + } finally { + if (!spanHasEnded) { + res.once("finish", onResponseFinish); + } + } + }; + for (const key in original) { + Object.defineProperty(patched, key, { + get() { + return original[key]; + }, + set(value) { + original[key] = value; + } + }); + } + return patched; + }); + } + _getSpanName(info, defaultName) { + const { spanNameHook: spanNameHook2 } = this.getConfig(); + if (!(spanNameHook2 instanceof Function)) { + return defaultName; + } + try { + return spanNameHook2(info, defaultName) ?? defaultName; + } catch (err) { + api_1.diag.error("express instrumentation: error calling span name rewrite hook", err); + return defaultName; + } + } + } + instrumentation$f.ExpressInstrumentation = ExpressInstrumentation; + return instrumentation$f; +} +var hasRequiredSrc$i; +function requireSrc$i() { + if (hasRequiredSrc$i) return src$i; + hasRequiredSrc$i = 1; + (function(exports$1) { + Object.defineProperty(exports$1, "__esModule", { value: true }); + exports$1.AttributeNames = exports$1.ExpressLayerType = exports$1.ExpressInstrumentation = void 0; + var instrumentation_1 = requireInstrumentation$f(); + Object.defineProperty(exports$1, "ExpressInstrumentation", { enumerable: true, get: function() { + return instrumentation_1.ExpressInstrumentation; + } }); + var ExpressLayerType_1 = requireExpressLayerType(); + Object.defineProperty(exports$1, "ExpressLayerType", { enumerable: true, get: function() { + return ExpressLayerType_1.ExpressLayerType; + } }); + var AttributeNames_1 = requireAttributeNames$6(); + Object.defineProperty(exports$1, "AttributeNames", { enumerable: true, get: function() { + return AttributeNames_1.AttributeNames; + } }); + })(src$i); + return src$i; +} +var srcExports$g = requireSrc$i(); +const DEBUG_BUILD = typeof __SENTRY_DEBUG__ === "undefined" || __SENTRY_DEBUG__; +const INTEGRATION_NAME$l = "Express"; +function requestHook(span) { + addOriginToSpan(span, "auto.http.otel.express"); + const attributes = spanToJSON(span).data; + const type = attributes["express.type"]; + if (type) { + span.setAttribute(SEMANTIC_ATTRIBUTE_SENTRY_OP, `${type}.express`); + } + const name = attributes["express.name"]; + if (typeof name === "string") { + span.updateName(name); + } +} +function spanNameHook(info, defaultName) { + if (getIsolationScope() === getDefaultIsolationScope()) { + DEBUG_BUILD && debug$2.warn("Isolation scope is still default isolation scope - skipping setting transactionName"); + return defaultName; + } + if (info.layerType === "request_handler") { + const req = info.request; + const method = req.method ? req.method.toUpperCase() : "GET"; + getIsolationScope().setTransactionName(`${method} ${info.route}`); + } + return defaultName; +} +const instrumentExpress = generateInstrumentOnce( + INTEGRATION_NAME$l, + () => new srcExports$g.ExpressInstrumentation({ + requestHook: (span) => requestHook(span), + spanNameHook: (info, defaultName) => spanNameHook(info, defaultName) + }) +); +const _expressIntegration = (() => { + return { + name: INTEGRATION_NAME$l, + setupOnce() { + instrumentExpress(); + } + }; +}); +const expressIntegration = defineIntegration(_expressIntegration); +var balancedMatch; +var hasRequiredBalancedMatch; +function requireBalancedMatch() { + if (hasRequiredBalancedMatch) return balancedMatch; + hasRequiredBalancedMatch = 1; + balancedMatch = balanced; + function balanced(a, b, str) { + if (a instanceof RegExp) a = maybeMatch(a, str); + if (b instanceof RegExp) b = maybeMatch(b, str); + var r = range(a, b, str); + return r && { + start: r[0], + end: r[1], + pre: str.slice(0, r[0]), + body: str.slice(r[0] + a.length, r[1]), + post: str.slice(r[1] + b.length) + }; + } + function maybeMatch(reg, str) { + var m = str.match(reg); + return m ? m[0] : null; + } + balanced.range = range; + function range(a, b, str) { + var begs, beg, left, right, result; + var ai = str.indexOf(a); + var bi = str.indexOf(b, ai + 1); + var i = ai; + if (ai >= 0 && bi > 0) { + if (a === b) { + return [ai, bi]; + } + begs = []; + left = str.length; + while (i >= 0 && !result) { + if (i == ai) { + begs.push(i); + ai = str.indexOf(a, i + 1); + } else if (begs.length == 1) { + result = [begs.pop(), bi]; + } else { + beg = begs.pop(); + if (beg < left) { + left = beg; + right = bi; + } + bi = str.indexOf(b, i + 1); + } + i = ai < bi && ai >= 0 ? ai : bi; + } + if (begs.length) { + result = [left, right]; + } + } + return result; + } + return balancedMatch; +} +var braceExpansion; +var hasRequiredBraceExpansion; +function requireBraceExpansion() { + if (hasRequiredBraceExpansion) return braceExpansion; + hasRequiredBraceExpansion = 1; + var balanced = requireBalancedMatch(); + braceExpansion = expandTop; + var escSlash = "\0SLASH" + Math.random() + "\0"; + var escOpen = "\0OPEN" + Math.random() + "\0"; + var escClose = "\0CLOSE" + Math.random() + "\0"; + var escComma = "\0COMMA" + Math.random() + "\0"; + var escPeriod = "\0PERIOD" + Math.random() + "\0"; + function numeric(str) { + return parseInt(str, 10) == str ? parseInt(str, 10) : str.charCodeAt(0); + } + function escapeBraces(str) { + return str.split("\\\\").join(escSlash).split("\\{").join(escOpen).split("\\}").join(escClose).split("\\,").join(escComma).split("\\.").join(escPeriod); + } + function unescapeBraces(str) { + return str.split(escSlash).join("\\").split(escOpen).join("{").split(escClose).join("}").split(escComma).join(",").split(escPeriod).join("."); + } + function parseCommaParts(str) { + if (!str) + return [""]; + var parts = []; + var m = balanced("{", "}", str); + if (!m) + return str.split(","); + var pre = m.pre; + var body = m.body; + var post = m.post; + var p = pre.split(","); + p[p.length - 1] += "{" + body + "}"; + var postParts = parseCommaParts(post); + if (post.length) { + p[p.length - 1] += postParts.shift(); + p.push.apply(p, postParts); + } + parts.push.apply(parts, p); + return parts; + } + function expandTop(str) { + if (!str) + return []; + if (str.substr(0, 2) === "{}") { + str = "\\{\\}" + str.substr(2); + } + return expand2(escapeBraces(str), true).map(unescapeBraces); + } + function embrace(str) { + return "{" + str + "}"; + } + function isPadded(el) { + return /^-?0\d/.test(el); + } + function lte(i, y) { + return i <= y; + } + function gte(i, y) { + return i >= y; + } + function expand2(str, isTop) { + var expansions = []; + var m = balanced("{", "}", str); + if (!m) return [str]; + var pre = m.pre; + var post = m.post.length ? expand2(m.post, false) : [""]; + if (/\$$/.test(m.pre)) { + for (var k = 0; k < post.length; k++) { + var expansion = pre + "{" + m.body + "}" + post[k]; + expansions.push(expansion); + } + } else { + var isNumericSequence = /^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(m.body); + var isAlphaSequence = /^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(m.body); + var isSequence = isNumericSequence || isAlphaSequence; + var isOptions = m.body.indexOf(",") >= 0; + if (!isSequence && !isOptions) { + if (m.post.match(/,(?!,).*\}/)) { + str = m.pre + "{" + m.body + escClose + m.post; + return expand2(str); + } + return [str]; + } + var n; + if (isSequence) { + n = m.body.split(/\.\./); + } else { + n = parseCommaParts(m.body); + if (n.length === 1) { + n = expand2(n[0], false).map(embrace); + if (n.length === 1) { + return post.map(function(p) { + return m.pre + n[0] + p; + }); + } + } + } + var N; + if (isSequence) { + var x = numeric(n[0]); + var y = numeric(n[1]); + var width = Math.max(n[0].length, n[1].length); + var incr = n.length == 3 ? Math.abs(numeric(n[2])) : 1; + var test = lte; + var reverse = y < x; + if (reverse) { + incr *= -1; + test = gte; + } + var pad = n.some(isPadded); + N = []; + for (var i = x; test(i, y); i += incr) { + var c; + if (isAlphaSequence) { + c = String.fromCharCode(i); + if (c === "\\") + c = ""; + } else { + c = String(i); + if (pad) { + var need = width - c.length; + if (need > 0) { + var z = new Array(need + 1).join("0"); + if (i < 0) + c = "-" + z + c.slice(1); + else + c = z + c; + } + } + } + N.push(c); + } + } else { + N = []; + for (var j = 0; j < n.length; j++) { + N.push.apply(N, expand2(n[j], false)); + } + } + for (var j = 0; j < N.length; j++) { + for (var k = 0; k < post.length; k++) { + var expansion = pre + N[j] + post[k]; + if (!isTop || isSequence || expansion) + expansions.push(expansion); + } + } + } + return expansions; + } + return braceExpansion; +} +var braceExpansionExports = requireBraceExpansion(); +const expand = /* @__PURE__ */ getDefaultExportFromCjs(braceExpansionExports); +const MAX_PATTERN_LENGTH = 1024 * 64; +const assertValidPattern = (pattern) => { + if (typeof pattern !== "string") { + throw new TypeError("invalid pattern"); + } + if (pattern.length > MAX_PATTERN_LENGTH) { + throw new TypeError("pattern is too long"); + } +}; +const posixClasses = { + "[:alnum:]": ["\\p{L}\\p{Nl}\\p{Nd}", true], + "[:alpha:]": ["\\p{L}\\p{Nl}", true], + "[:ascii:]": ["\\x00-\\x7f", false], + "[:blank:]": ["\\p{Zs}\\t", true], + "[:cntrl:]": ["\\p{Cc}", true], + "[:digit:]": ["\\p{Nd}", true], + "[:graph:]": ["\\p{Z}\\p{C}", true, true], + "[:lower:]": ["\\p{Ll}", true], + "[:print:]": ["\\p{C}", true], + "[:punct:]": ["\\p{P}", true], + "[:space:]": ["\\p{Z}\\t\\r\\n\\v\\f", true], + "[:upper:]": ["\\p{Lu}", true], + "[:word:]": ["\\p{L}\\p{Nl}\\p{Nd}\\p{Pc}", true], + "[:xdigit:]": ["A-Fa-f0-9", false] +}; +const braceEscape = (s) => s.replace(/[[\]\\-]/g, "\\$&"); +const regexpEscape = (s) => s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&"); +const rangesToString = (ranges) => ranges.join(""); +const parseClass = (glob, position) => { + const pos = position; + if (glob.charAt(pos) !== "[") { + throw new Error("not in a brace expression"); + } + const ranges = []; + const negs = []; + let i = pos + 1; + let sawStart = false; + let uflag = false; + let escaping = false; + let negate = false; + let endPos = pos; + let rangeStart = ""; + WHILE: while (i < glob.length) { + const c = glob.charAt(i); + if ((c === "!" || c === "^") && i === pos + 1) { + negate = true; + i++; + continue; + } + if (c === "]" && sawStart && !escaping) { + endPos = i + 1; + break; + } + sawStart = true; + if (c === "\\") { + if (!escaping) { + escaping = true; + i++; + continue; + } + } + if (c === "[" && !escaping) { + for (const [cls, [unip, u, neg]] of Object.entries(posixClasses)) { + if (glob.startsWith(cls, i)) { + if (rangeStart) { + return ["$.", false, glob.length - pos, true]; + } + i += cls.length; + if (neg) + negs.push(unip); + else + ranges.push(unip); + uflag = uflag || u; + continue WHILE; + } + } + } + escaping = false; + if (rangeStart) { + if (c > rangeStart) { + ranges.push(braceEscape(rangeStart) + "-" + braceEscape(c)); + } else if (c === rangeStart) { + ranges.push(braceEscape(c)); + } + rangeStart = ""; + i++; + continue; + } + if (glob.startsWith("-]", i + 1)) { + ranges.push(braceEscape(c + "-")); + i += 2; + continue; + } + if (glob.startsWith("-", i + 1)) { + rangeStart = c; + i += 2; + continue; + } + ranges.push(braceEscape(c)); + i++; + } + if (endPos < i) { + return ["", false, 0, false]; + } + if (!ranges.length && !negs.length) { + return ["$.", false, glob.length - pos, true]; + } + if (negs.length === 0 && ranges.length === 1 && /^\\?.$/.test(ranges[0]) && !negate) { + const r = ranges[0].length === 2 ? ranges[0].slice(-1) : ranges[0]; + return [regexpEscape(r), false, endPos - pos, false]; + } + const sranges = "[" + (negate ? "^" : "") + rangesToString(ranges) + "]"; + const snegs = "[" + (negate ? "" : "^") + rangesToString(negs) + "]"; + const comb = ranges.length && negs.length ? "(" + sranges + "|" + snegs + ")" : ranges.length ? sranges : snegs; + return [comb, uflag, endPos - pos, true]; +}; +const unescape = (s, { windowsPathsNoEscape = false } = {}) => { + return windowsPathsNoEscape ? s.replace(/\[([^\/\\])\]/g, "$1") : s.replace(/((?!\\).|^)\[([^\/\\])\]/g, "$1$2").replace(/\\([^\/])/g, "$1"); +}; +const types$3 = /* @__PURE__ */ new Set(["!", "?", "+", "*", "@"]); +const isExtglobType = (c) => types$3.has(c); +const startNoTraversal = "(?!(?:^|/)\\.\\.?(?:$|/))"; +const startNoDot = "(?!\\.)"; +const addPatternStart = /* @__PURE__ */ new Set(["[", "."]); +const justDots = /* @__PURE__ */ new Set(["..", "."]); +const reSpecials = new Set("().*{}+?[]^$\\!"); +const regExpEscape$1 = (s) => s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&"); +const qmark$1 = "[^/]"; +const star$1 = qmark$1 + "*?"; +const starNoEmpty = qmark$1 + "+?"; +class AST { + type; + #root; + #hasMagic; + #uflag = false; + #parts = []; + #parent; + #parentIndex; + #negs; + #filledNegs = false; + #options; + #toString; + // set to true if it's an extglob with no children + // (which really means one child of '') + #emptyExt = false; + constructor(type, parent, options = {}) { + this.type = type; + if (type) + this.#hasMagic = true; + this.#parent = parent; + this.#root = this.#parent ? this.#parent.#root : this; + this.#options = this.#root === this ? options : this.#root.#options; + this.#negs = this.#root === this ? [] : this.#root.#negs; + if (type === "!" && !this.#root.#filledNegs) + this.#negs.push(this); + this.#parentIndex = this.#parent ? this.#parent.#parts.length : 0; + } + get hasMagic() { + if (this.#hasMagic !== void 0) + return this.#hasMagic; + for (const p of this.#parts) { + if (typeof p === "string") + continue; + if (p.type || p.hasMagic) + return this.#hasMagic = true; + } + return this.#hasMagic; + } + // reconstructs the pattern + toString() { + if (this.#toString !== void 0) + return this.#toString; + if (!this.type) { + return this.#toString = this.#parts.map((p) => String(p)).join(""); + } else { + return this.#toString = this.type + "(" + this.#parts.map((p) => String(p)).join("|") + ")"; + } + } + #fillNegs() { + if (this !== this.#root) + throw new Error("should only call on root"); + if (this.#filledNegs) + return this; + this.toString(); + this.#filledNegs = true; + let n; + while (n = this.#negs.pop()) { + if (n.type !== "!") + continue; + let p = n; + let pp = p.#parent; + while (pp) { + for (let i = p.#parentIndex + 1; !pp.type && i < pp.#parts.length; i++) { + for (const part of n.#parts) { + if (typeof part === "string") { + throw new Error("string part in extglob AST??"); + } + part.copyIn(pp.#parts[i]); + } + } + p = pp; + pp = p.#parent; + } + } + return this; + } + push(...parts) { + for (const p of parts) { + if (p === "") + continue; + if (typeof p !== "string" && !(p instanceof AST && p.#parent === this)) { + throw new Error("invalid part: " + p); + } + this.#parts.push(p); + } + } + toJSON() { + const ret = this.type === null ? this.#parts.slice().map((p) => typeof p === "string" ? p : p.toJSON()) : [this.type, ...this.#parts.map((p) => p.toJSON())]; + if (this.isStart() && !this.type) + ret.unshift([]); + if (this.isEnd() && (this === this.#root || this.#root.#filledNegs && this.#parent?.type === "!")) { + ret.push({}); + } + return ret; + } + isStart() { + if (this.#root === this) + return true; + if (!this.#parent?.isStart()) + return false; + if (this.#parentIndex === 0) + return true; + const p = this.#parent; + for (let i = 0; i < this.#parentIndex; i++) { + const pp = p.#parts[i]; + if (!(pp instanceof AST && pp.type === "!")) { + return false; + } + } + return true; + } + isEnd() { + if (this.#root === this) + return true; + if (this.#parent?.type === "!") + return true; + if (!this.#parent?.isEnd()) + return false; + if (!this.type) + return this.#parent?.isEnd(); + const pl = this.#parent ? this.#parent.#parts.length : 0; + return this.#parentIndex === pl - 1; + } + copyIn(part) { + if (typeof part === "string") + this.push(part); + else + this.push(part.clone(this)); + } + clone(parent) { + const c = new AST(this.type, parent); + for (const p of this.#parts) { + c.copyIn(p); + } + return c; + } + static #parseAST(str, ast, pos, opt) { + let escaping = false; + let inBrace = false; + let braceStart = -1; + let braceNeg = false; + if (ast.type === null) { + let i2 = pos; + let acc2 = ""; + while (i2 < str.length) { + const c = str.charAt(i2++); + if (escaping || c === "\\") { + escaping = !escaping; + acc2 += c; + continue; + } + if (inBrace) { + if (i2 === braceStart + 1) { + if (c === "^" || c === "!") { + braceNeg = true; + } + } else if (c === "]" && !(i2 === braceStart + 2 && braceNeg)) { + inBrace = false; + } + acc2 += c; + continue; + } else if (c === "[") { + inBrace = true; + braceStart = i2; + braceNeg = false; + acc2 += c; + continue; + } + if (!opt.noext && isExtglobType(c) && str.charAt(i2) === "(") { + ast.push(acc2); + acc2 = ""; + const ext2 = new AST(c, ast); + i2 = AST.#parseAST(str, ext2, i2, opt); + ast.push(ext2); + continue; + } + acc2 += c; + } + ast.push(acc2); + return i2; + } + let i = pos + 1; + let part = new AST(null, ast); + const parts = []; + let acc = ""; + while (i < str.length) { + const c = str.charAt(i++); + if (escaping || c === "\\") { + escaping = !escaping; + acc += c; + continue; + } + if (inBrace) { + if (i === braceStart + 1) { + if (c === "^" || c === "!") { + braceNeg = true; + } + } else if (c === "]" && !(i === braceStart + 2 && braceNeg)) { + inBrace = false; + } + acc += c; + continue; + } else if (c === "[") { + inBrace = true; + braceStart = i; + braceNeg = false; + acc += c; + continue; + } + if (isExtglobType(c) && str.charAt(i) === "(") { + part.push(acc); + acc = ""; + const ext2 = new AST(c, part); + part.push(ext2); + i = AST.#parseAST(str, ext2, i, opt); + continue; + } + if (c === "|") { + part.push(acc); + acc = ""; + parts.push(part); + part = new AST(null, ast); + continue; + } + if (c === ")") { + if (acc === "" && ast.#parts.length === 0) { + ast.#emptyExt = true; + } + part.push(acc); + acc = ""; + ast.push(...parts, part); + return i; + } + acc += c; + } + ast.type = null; + ast.#hasMagic = void 0; + ast.#parts = [str.substring(pos - 1)]; + return i; + } + static fromGlob(pattern, options = {}) { + const ast = new AST(null, void 0, options); + AST.#parseAST(pattern, ast, 0, options); + return ast; + } + // returns the regular expression if there's magic, or the unescaped + // string if not. + toMMPattern() { + if (this !== this.#root) + return this.#root.toMMPattern(); + const glob = this.toString(); + const [re, body, hasMagic, uflag] = this.toRegExpSource(); + const anyMagic = hasMagic || this.#hasMagic || this.#options.nocase && !this.#options.nocaseMagicOnly && glob.toUpperCase() !== glob.toLowerCase(); + if (!anyMagic) { + return body; + } + const flags = (this.#options.nocase ? "i" : "") + (uflag ? "u" : ""); + return Object.assign(new RegExp(`^${re}$`, flags), { + _src: re, + _glob: glob + }); + } + get options() { + return this.#options; + } + // returns the string match, the regexp source, whether there's magic + // in the regexp (so a regular expression is required) and whether or + // not the uflag is needed for the regular expression (for posix classes) + // TODO: instead of injecting the start/end at this point, just return + // the BODY of the regexp, along with the start/end portions suitable + // for binding the start/end in either a joined full-path makeRe context + // (where we bind to (^|/), or a standalone matchPart context (where + // we bind to ^, and not /). Otherwise slashes get duped! + // + // In part-matching mode, the start is: + // - if not isStart: nothing + // - if traversal possible, but not allowed: ^(?!\.\.?$) + // - if dots allowed or not possible: ^ + // - if dots possible and not allowed: ^(?!\.) + // end is: + // - if not isEnd(): nothing + // - else: $ + // + // In full-path matching mode, we put the slash at the START of the + // pattern, so start is: + // - if first pattern: same as part-matching mode + // - if not isStart(): nothing + // - if traversal possible, but not allowed: /(?!\.\.?(?:$|/)) + // - if dots allowed or not possible: / + // - if dots possible and not allowed: /(?!\.) + // end is: + // - if last pattern, same as part-matching mode + // - else nothing + // + // Always put the (?:$|/) on negated tails, though, because that has to be + // there to bind the end of the negated pattern portion, and it's easier to + // just stick it in now rather than try to inject it later in the middle of + // the pattern. + // + // We can just always return the same end, and leave it up to the caller + // to know whether it's going to be used joined or in parts. + // And, if the start is adjusted slightly, can do the same there: + // - if not isStart: nothing + // - if traversal possible, but not allowed: (?:/|^)(?!\.\.?$) + // - if dots allowed or not possible: (?:/|^) + // - if dots possible and not allowed: (?:/|^)(?!\.) + // + // But it's better to have a simpler binding without a conditional, for + // performance, so probably better to return both start options. + // + // Then the caller just ignores the end if it's not the first pattern, + // and the start always gets applied. + // + // But that's always going to be $ if it's the ending pattern, or nothing, + // so the caller can just attach $ at the end of the pattern when building. + // + // So the todo is: + // - better detect what kind of start is needed + // - return both flavors of starting pattern + // - attach $ at the end of the pattern when creating the actual RegExp + // + // Ah, but wait, no, that all only applies to the root when the first pattern + // is not an extglob. If the first pattern IS an extglob, then we need all + // that dot prevention biz to live in the extglob portions, because eg + // +(*|.x*) can match .xy but not .yx. + // + // So, return the two flavors if it's #root and the first child is not an + // AST, otherwise leave it to the child AST to handle it, and there, + // use the (?:^|/) style of start binding. + // + // Even simplified further: + // - Since the start for a join is eg /(?!\.) and the start for a part + // is ^(?!\.), we can just prepend (?!\.) to the pattern (either root + // or start or whatever) and prepend ^ or / at the Regexp construction. + toRegExpSource(allowDot) { + const dot = allowDot ?? !!this.#options.dot; + if (this.#root === this) + this.#fillNegs(); + if (!this.type) { + const noEmpty = this.isStart() && this.isEnd(); + const src2 = this.#parts.map((p) => { + const [re, _, hasMagic, uflag] = typeof p === "string" ? AST.#parseGlob(p, this.#hasMagic, noEmpty) : p.toRegExpSource(allowDot); + this.#hasMagic = this.#hasMagic || hasMagic; + this.#uflag = this.#uflag || uflag; + return re; + }).join(""); + let start2 = ""; + if (this.isStart()) { + if (typeof this.#parts[0] === "string") { + const dotTravAllowed = this.#parts.length === 1 && justDots.has(this.#parts[0]); + if (!dotTravAllowed) { + const aps = addPatternStart; + const needNoTrav = ( + // dots are allowed, and the pattern starts with [ or . + dot && aps.has(src2.charAt(0)) || // the pattern starts with \., and then [ or . + src2.startsWith("\\.") && aps.has(src2.charAt(2)) || // the pattern starts with \.\., and then [ or . + src2.startsWith("\\.\\.") && aps.has(src2.charAt(4)) + ); + const needNoDot = !dot && !allowDot && aps.has(src2.charAt(0)); + start2 = needNoTrav ? startNoTraversal : needNoDot ? startNoDot : ""; + } + } + } + let end = ""; + if (this.isEnd() && this.#root.#filledNegs && this.#parent?.type === "!") { + end = "(?:$|\\/)"; + } + const final2 = start2 + src2 + end; + return [ + final2, + unescape(src2), + this.#hasMagic = !!this.#hasMagic, + this.#uflag + ]; + } + const repeated = this.type === "*" || this.type === "+"; + const start = this.type === "!" ? "(?:(?!(?:" : "(?:"; + let body = this.#partsToRegExp(dot); + if (this.isStart() && this.isEnd() && !body && this.type !== "!") { + const s = this.toString(); + this.#parts = [s]; + this.type = null; + this.#hasMagic = void 0; + return [s, unescape(this.toString()), false, false]; + } + let bodyDotAllowed = !repeated || allowDot || dot || !startNoDot ? "" : this.#partsToRegExp(true); + if (bodyDotAllowed === body) { + bodyDotAllowed = ""; + } + if (bodyDotAllowed) { + body = `(?:${body})(?:${bodyDotAllowed})*?`; + } + let final = ""; + if (this.type === "!" && this.#emptyExt) { + final = (this.isStart() && !dot ? startNoDot : "") + starNoEmpty; + } else { + const close = this.type === "!" ? ( + // !() must match something,but !(x) can match '' + "))" + (this.isStart() && !dot && !allowDot ? startNoDot : "") + star$1 + ")" + ) : this.type === "@" ? ")" : this.type === "?" ? ")?" : this.type === "+" && bodyDotAllowed ? ")" : this.type === "*" && bodyDotAllowed ? `)?` : `)${this.type}`; + final = start + body + close; + } + return [ + final, + unescape(body), + this.#hasMagic = !!this.#hasMagic, + this.#uflag + ]; + } + #partsToRegExp(dot) { + return this.#parts.map((p) => { + if (typeof p === "string") { + throw new Error("string type in extglob ast??"); + } + const [re, _, _hasMagic, uflag] = p.toRegExpSource(dot); + this.#uflag = this.#uflag || uflag; + return re; + }).filter((p) => !(this.isStart() && this.isEnd()) || !!p).join("|"); + } + static #parseGlob(glob, hasMagic, noEmpty = false) { + let escaping = false; + let re = ""; + let uflag = false; + for (let i = 0; i < glob.length; i++) { + const c = glob.charAt(i); + if (escaping) { + escaping = false; + re += (reSpecials.has(c) ? "\\" : "") + c; + continue; + } + if (c === "\\") { + if (i === glob.length - 1) { + re += "\\\\"; + } else { + escaping = true; + } + continue; + } + if (c === "[") { + const [src2, needUflag, consumed, magic] = parseClass(glob, i); + if (consumed) { + re += src2; + uflag = uflag || needUflag; + i += consumed - 1; + hasMagic = hasMagic || magic; + continue; + } + } + if (c === "*") { + if (noEmpty && glob === "*") + re += starNoEmpty; + else + re += star$1; + hasMagic = true; + continue; + } + if (c === "?") { + re += qmark$1; + hasMagic = true; + continue; + } + re += regExpEscape$1(c); + } + return [re, unescape(glob), !!hasMagic, uflag]; + } +} +const escape = (s, { windowsPathsNoEscape = false } = {}) => { + return windowsPathsNoEscape ? s.replace(/[?*()[\]]/g, "[$&]") : s.replace(/[?*()[\]\\]/g, "\\$&"); +}; +const minimatch = (p, pattern, options = {}) => { + assertValidPattern(pattern); + if (!options.nocomment && pattern.charAt(0) === "#") { + return false; + } + return new Minimatch(pattern, options).match(p); +}; +const starDotExtRE = /^\*+([^+@!?\*\[\(]*)$/; +const starDotExtTest = (ext2) => (f) => !f.startsWith(".") && f.endsWith(ext2); +const starDotExtTestDot = (ext2) => (f) => f.endsWith(ext2); +const starDotExtTestNocase = (ext2) => { + ext2 = ext2.toLowerCase(); + return (f) => !f.startsWith(".") && f.toLowerCase().endsWith(ext2); +}; +const starDotExtTestNocaseDot = (ext2) => { + ext2 = ext2.toLowerCase(); + return (f) => f.toLowerCase().endsWith(ext2); +}; +const starDotStarRE = /^\*+\.\*+$/; +const starDotStarTest = (f) => !f.startsWith(".") && f.includes("."); +const starDotStarTestDot = (f) => f !== "." && f !== ".." && f.includes("."); +const dotStarRE = /^\.\*+$/; +const dotStarTest = (f) => f !== "." && f !== ".." && f.startsWith("."); +const starRE = /^\*+$/; +const starTest = (f) => f.length !== 0 && !f.startsWith("."); +const starTestDot = (f) => f.length !== 0 && f !== "." && f !== ".."; +const qmarksRE = /^\?+([^+@!?\*\[\(]*)?$/; +const qmarksTestNocase = ([$0, ext2 = ""]) => { + const noext = qmarksTestNoExt([$0]); + if (!ext2) + return noext; + ext2 = ext2.toLowerCase(); + return (f) => noext(f) && f.toLowerCase().endsWith(ext2); +}; +const qmarksTestNocaseDot = ([$0, ext2 = ""]) => { + const noext = qmarksTestNoExtDot([$0]); + if (!ext2) + return noext; + ext2 = ext2.toLowerCase(); + return (f) => noext(f) && f.toLowerCase().endsWith(ext2); +}; +const qmarksTestDot = ([$0, ext2 = ""]) => { + const noext = qmarksTestNoExtDot([$0]); + return !ext2 ? noext : (f) => noext(f) && f.endsWith(ext2); +}; +const qmarksTest = ([$0, ext2 = ""]) => { + const noext = qmarksTestNoExt([$0]); + return !ext2 ? noext : (f) => noext(f) && f.endsWith(ext2); +}; +const qmarksTestNoExt = ([$0]) => { + const len = $0.length; + return (f) => f.length === len && !f.startsWith("."); +}; +const qmarksTestNoExtDot = ([$0]) => { + const len = $0.length; + return (f) => f.length === len && f !== "." && f !== ".."; +}; +const defaultPlatform = typeof process === "object" && process ? typeof process.env === "object" && process.env && process.env.__MINIMATCH_TESTING_PLATFORM__ || process.platform : "posix"; +const path = { + win32: { sep: "\\" }, + posix: { sep: "/" } +}; +const sep = defaultPlatform === "win32" ? path.win32.sep : path.posix.sep; +minimatch.sep = sep; +const GLOBSTAR = Symbol("globstar **"); +minimatch.GLOBSTAR = GLOBSTAR; +const qmark = "[^/]"; +const star = qmark + "*?"; +const twoStarDot = "(?:(?!(?:\\/|^)(?:\\.{1,2})($|\\/)).)*?"; +const twoStarNoDot = "(?:(?!(?:\\/|^)\\.).)*?"; +const filter = (pattern, options = {}) => (p) => minimatch(p, pattern, options); +minimatch.filter = filter; +const ext = (a, b = {}) => Object.assign({}, a, b); +const defaults = (def) => { + if (!def || typeof def !== "object" || !Object.keys(def).length) { + return minimatch; + } + const orig = minimatch; + const m = (p, pattern, options = {}) => orig(p, pattern, ext(def, options)); + return Object.assign(m, { + Minimatch: class Minimatch extends orig.Minimatch { + constructor(pattern, options = {}) { + super(pattern, ext(def, options)); + } + static defaults(options) { + return orig.defaults(ext(def, options)).Minimatch; + } + }, + AST: class AST extends orig.AST { + /* c8 ignore start */ + constructor(type, parent, options = {}) { + super(type, parent, ext(def, options)); + } + /* c8 ignore stop */ + static fromGlob(pattern, options = {}) { + return orig.AST.fromGlob(pattern, ext(def, options)); + } + }, + unescape: (s, options = {}) => orig.unescape(s, ext(def, options)), + escape: (s, options = {}) => orig.escape(s, ext(def, options)), + filter: (pattern, options = {}) => orig.filter(pattern, ext(def, options)), + defaults: (options) => orig.defaults(ext(def, options)), + makeRe: (pattern, options = {}) => orig.makeRe(pattern, ext(def, options)), + braceExpand: (pattern, options = {}) => orig.braceExpand(pattern, ext(def, options)), + match: (list, pattern, options = {}) => orig.match(list, pattern, ext(def, options)), + sep: orig.sep, + GLOBSTAR + }); +}; +minimatch.defaults = defaults; +const braceExpand = (pattern, options = {}) => { + assertValidPattern(pattern); + if (options.nobrace || !/\{(?:(?!\{).)*\}/.test(pattern)) { + return [pattern]; + } + return expand(pattern); +}; +minimatch.braceExpand = braceExpand; +const makeRe = (pattern, options = {}) => new Minimatch(pattern, options).makeRe(); +minimatch.makeRe = makeRe; +const match = (list, pattern, options = {}) => { + const mm = new Minimatch(pattern, options); + list = list.filter((f) => mm.match(f)); + if (mm.options.nonull && !list.length) { + list.push(pattern); + } + return list; +}; +minimatch.match = match; +const globMagic = /[?*]|[+@!]\(.*?\)|\[|\]/; +const regExpEscape = (s) => s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&"); +class Minimatch { + options; + set; + pattern; + windowsPathsNoEscape; + nonegate; + negate; + comment; + empty; + preserveMultipleSlashes; + partial; + globSet; + globParts; + nocase; + isWindows; + platform; + windowsNoMagicRoot; + regexp; + constructor(pattern, options = {}) { + assertValidPattern(pattern); + options = options || {}; + this.options = options; + this.pattern = pattern; + this.platform = options.platform || defaultPlatform; + this.isWindows = this.platform === "win32"; + this.windowsPathsNoEscape = !!options.windowsPathsNoEscape || options.allowWindowsEscape === false; + if (this.windowsPathsNoEscape) { + this.pattern = this.pattern.replace(/\\/g, "/"); + } + this.preserveMultipleSlashes = !!options.preserveMultipleSlashes; + this.regexp = null; + this.negate = false; + this.nonegate = !!options.nonegate; + this.comment = false; + this.empty = false; + this.partial = !!options.partial; + this.nocase = !!this.options.nocase; + this.windowsNoMagicRoot = options.windowsNoMagicRoot !== void 0 ? options.windowsNoMagicRoot : !!(this.isWindows && this.nocase); + this.globSet = []; + this.globParts = []; + this.set = []; + this.make(); + } + hasMagic() { + if (this.options.magicalBraces && this.set.length > 1) { + return true; + } + for (const pattern of this.set) { + for (const part of pattern) { + if (typeof part !== "string") + return true; + } + } + return false; + } + debug(..._) { + } + make() { + const pattern = this.pattern; + const options = this.options; + if (!options.nocomment && pattern.charAt(0) === "#") { + this.comment = true; + return; + } + if (!pattern) { + this.empty = true; + return; + } + this.parseNegate(); + this.globSet = [...new Set(this.braceExpand())]; + if (options.debug) { + this.debug = (...args) => console.error(...args); + } + this.debug(this.pattern, this.globSet); + const rawGlobParts = this.globSet.map((s) => this.slashSplit(s)); + this.globParts = this.preprocess(rawGlobParts); + this.debug(this.pattern, this.globParts); + let set = this.globParts.map((s, _, __) => { + if (this.isWindows && this.windowsNoMagicRoot) { + const isUNC = s[0] === "" && s[1] === "" && (s[2] === "?" || !globMagic.test(s[2])) && !globMagic.test(s[3]); + const isDrive = /^[a-z]:/i.test(s[0]); + if (isUNC) { + return [...s.slice(0, 4), ...s.slice(4).map((ss) => this.parse(ss))]; + } else if (isDrive) { + return [s[0], ...s.slice(1).map((ss) => this.parse(ss))]; + } + } + return s.map((ss) => this.parse(ss)); + }); + this.debug(this.pattern, set); + this.set = set.filter((s) => s.indexOf(false) === -1); + if (this.isWindows) { + for (let i = 0; i < this.set.length; i++) { + const p = this.set[i]; + if (p[0] === "" && p[1] === "" && this.globParts[i][2] === "?" && typeof p[3] === "string" && /^[a-z]:$/i.test(p[3])) { + p[2] = "?"; + } + } + } + this.debug(this.pattern, this.set); + } + // various transforms to equivalent pattern sets that are + // faster to process in a filesystem walk. The goal is to + // eliminate what we can, and push all ** patterns as far + // to the right as possible, even if it increases the number + // of patterns that we have to process. + preprocess(globParts) { + if (this.options.noglobstar) { + for (let i = 0; i < globParts.length; i++) { + for (let j = 0; j < globParts[i].length; j++) { + if (globParts[i][j] === "**") { + globParts[i][j] = "*"; + } + } + } + } + const { optimizationLevel = 1 } = this.options; + if (optimizationLevel >= 2) { + globParts = this.firstPhasePreProcess(globParts); + globParts = this.secondPhasePreProcess(globParts); + } else if (optimizationLevel >= 1) { + globParts = this.levelOneOptimize(globParts); + } else { + globParts = this.adjascentGlobstarOptimize(globParts); + } + return globParts; + } + // just get rid of adjascent ** portions + adjascentGlobstarOptimize(globParts) { + return globParts.map((parts) => { + let gs = -1; + while (-1 !== (gs = parts.indexOf("**", gs + 1))) { + let i = gs; + while (parts[i + 1] === "**") { + i++; + } + if (i !== gs) { + parts.splice(gs, i - gs); + } + } + return parts; + }); + } + // get rid of adjascent ** and resolve .. portions + levelOneOptimize(globParts) { + return globParts.map((parts) => { + parts = parts.reduce((set, part) => { + const prev = set[set.length - 1]; + if (part === "**" && prev === "**") { + return set; + } + if (part === "..") { + if (prev && prev !== ".." && prev !== "." && prev !== "**") { + set.pop(); + return set; + } + } + set.push(part); + return set; + }, []); + return parts.length === 0 ? [""] : parts; + }); + } + levelTwoFileOptimize(parts) { + if (!Array.isArray(parts)) { + parts = this.slashSplit(parts); + } + let didSomething = false; + do { + didSomething = false; + if (!this.preserveMultipleSlashes) { + for (let i = 1; i < parts.length - 1; i++) { + const p = parts[i]; + if (i === 1 && p === "" && parts[0] === "") + continue; + if (p === "." || p === "") { + didSomething = true; + parts.splice(i, 1); + i--; + } + } + if (parts[0] === "." && parts.length === 2 && (parts[1] === "." || parts[1] === "")) { + didSomething = true; + parts.pop(); + } + } + let dd = 0; + while (-1 !== (dd = parts.indexOf("..", dd + 1))) { + const p = parts[dd - 1]; + if (p && p !== "." && p !== ".." && p !== "**") { + didSomething = true; + parts.splice(dd - 1, 2); + dd -= 2; + } + } + } while (didSomething); + return parts.length === 0 ? [""] : parts; + } + // First phase: single-pattern processing + //
 is 1 or more portions
+  //  is 1 or more portions
+  // 

is any portion other than ., .., '', or ** + // is . or '' + // + // **/.. is *brutal* for filesystem walking performance, because + // it effectively resets the recursive walk each time it occurs, + // and ** cannot be reduced out by a .. pattern part like a regexp + // or most strings (other than .., ., and '') can be. + // + //

/**/../

/

/ -> {

/../

/

/,

/**/

/

/} + //

// -> 
/
+  // 
/

/../ ->

/
+  // **/**/ -> **/
+  //
+  // **/*/ -> */**/ <== not valid because ** doesn't follow
+  // this WOULD be allowed if ** did follow symlinks, or * didn't
+  firstPhasePreProcess(globParts) {
+    let didSomething = false;
+    do {
+      didSomething = false;
+      for (let parts of globParts) {
+        let gs = -1;
+        while (-1 !== (gs = parts.indexOf("**", gs + 1))) {
+          let gss = gs;
+          while (parts[gss + 1] === "**") {
+            gss++;
+          }
+          if (gss > gs) {
+            parts.splice(gs + 1, gss - gs);
+          }
+          let next = parts[gs + 1];
+          const p = parts[gs + 2];
+          const p2 = parts[gs + 3];
+          if (next !== "..")
+            continue;
+          if (!p || p === "." || p === ".." || !p2 || p2 === "." || p2 === "..") {
+            continue;
+          }
+          didSomething = true;
+          parts.splice(gs, 1);
+          const other = parts.slice(0);
+          other[gs] = "**";
+          globParts.push(other);
+          gs--;
+        }
+        if (!this.preserveMultipleSlashes) {
+          for (let i = 1; i < parts.length - 1; i++) {
+            const p = parts[i];
+            if (i === 1 && p === "" && parts[0] === "")
+              continue;
+            if (p === "." || p === "") {
+              didSomething = true;
+              parts.splice(i, 1);
+              i--;
+            }
+          }
+          if (parts[0] === "." && parts.length === 2 && (parts[1] === "." || parts[1] === "")) {
+            didSomething = true;
+            parts.pop();
+          }
+        }
+        let dd = 0;
+        while (-1 !== (dd = parts.indexOf("..", dd + 1))) {
+          const p = parts[dd - 1];
+          if (p && p !== "." && p !== ".." && p !== "**") {
+            didSomething = true;
+            const needDot = dd === 1 && parts[dd + 1] === "**";
+            const splin = needDot ? ["."] : [];
+            parts.splice(dd - 1, 2, ...splin);
+            if (parts.length === 0)
+              parts.push("");
+            dd -= 2;
+          }
+        }
+      }
+    } while (didSomething);
+    return globParts;
+  }
+  // second phase: multi-pattern dedupes
+  // {
/*/,
/

/} ->

/*/
+  // {
/,
/} -> 
/
+  // {
/**/,
/} -> 
/**/
+  //
+  // {
/**/,
/**/

/} ->

/**/
+  // ^-- not valid because ** doens't follow symlinks
+  secondPhasePreProcess(globParts) {
+    for (let i = 0; i < globParts.length - 1; i++) {
+      for (let j = i + 1; j < globParts.length; j++) {
+        const matched = this.partsMatch(globParts[i], globParts[j], !this.preserveMultipleSlashes);
+        if (matched) {
+          globParts[i] = [];
+          globParts[j] = matched;
+          break;
+        }
+      }
+    }
+    return globParts.filter((gs) => gs.length);
+  }
+  partsMatch(a, b, emptyGSMatch = false) {
+    let ai = 0;
+    let bi = 0;
+    let result = [];
+    let which = "";
+    while (ai < a.length && bi < b.length) {
+      if (a[ai] === b[bi]) {
+        result.push(which === "b" ? b[bi] : a[ai]);
+        ai++;
+        bi++;
+      } else if (emptyGSMatch && a[ai] === "**" && b[bi] === a[ai + 1]) {
+        result.push(a[ai]);
+        ai++;
+      } else if (emptyGSMatch && b[bi] === "**" && a[ai] === b[bi + 1]) {
+        result.push(b[bi]);
+        bi++;
+      } else if (a[ai] === "*" && b[bi] && (this.options.dot || !b[bi].startsWith(".")) && b[bi] !== "**") {
+        if (which === "b")
+          return false;
+        which = "a";
+        result.push(a[ai]);
+        ai++;
+        bi++;
+      } else if (b[bi] === "*" && a[ai] && (this.options.dot || !a[ai].startsWith(".")) && a[ai] !== "**") {
+        if (which === "a")
+          return false;
+        which = "b";
+        result.push(b[bi]);
+        ai++;
+        bi++;
+      } else {
+        return false;
+      }
+    }
+    return a.length === b.length && result;
+  }
+  parseNegate() {
+    if (this.nonegate)
+      return;
+    const pattern = this.pattern;
+    let negate = false;
+    let negateOffset = 0;
+    for (let i = 0; i < pattern.length && pattern.charAt(i) === "!"; i++) {
+      negate = !negate;
+      negateOffset++;
+    }
+    if (negateOffset)
+      this.pattern = pattern.slice(negateOffset);
+    this.negate = negate;
+  }
+  // set partial to true to test if, for example,
+  // "/a/b" matches the start of "/*/b/*/d"
+  // Partial means, if you run out of file before you run
+  // out of pattern, then that's fine, as long as all
+  // the parts match.
+  matchOne(file, pattern, partial = false) {
+    const options = this.options;
+    if (this.isWindows) {
+      const fileDrive = typeof file[0] === "string" && /^[a-z]:$/i.test(file[0]);
+      const fileUNC = !fileDrive && file[0] === "" && file[1] === "" && file[2] === "?" && /^[a-z]:$/i.test(file[3]);
+      const patternDrive = typeof pattern[0] === "string" && /^[a-z]:$/i.test(pattern[0]);
+      const patternUNC = !patternDrive && pattern[0] === "" && pattern[1] === "" && pattern[2] === "?" && typeof pattern[3] === "string" && /^[a-z]:$/i.test(pattern[3]);
+      const fdi = fileUNC ? 3 : fileDrive ? 0 : void 0;
+      const pdi = patternUNC ? 3 : patternDrive ? 0 : void 0;
+      if (typeof fdi === "number" && typeof pdi === "number") {
+        const [fd, pd] = [file[fdi], pattern[pdi]];
+        if (fd.toLowerCase() === pd.toLowerCase()) {
+          pattern[pdi] = fd;
+          if (pdi > fdi) {
+            pattern = pattern.slice(pdi);
+          } else if (fdi > pdi) {
+            file = file.slice(fdi);
+          }
+        }
+      }
+    }
+    const { optimizationLevel = 1 } = this.options;
+    if (optimizationLevel >= 2) {
+      file = this.levelTwoFileOptimize(file);
+    }
+    this.debug("matchOne", this, { file, pattern });
+    this.debug("matchOne", file.length, pattern.length);
+    for (var fi = 0, pi = 0, fl = file.length, pl = pattern.length; fi < fl && pi < pl; fi++, pi++) {
+      this.debug("matchOne loop");
+      var p = pattern[pi];
+      var f = file[fi];
+      this.debug(pattern, p, f);
+      if (p === false) {
+        return false;
+      }
+      if (p === GLOBSTAR) {
+        this.debug("GLOBSTAR", [pattern, p, f]);
+        var fr = fi;
+        var pr = pi + 1;
+        if (pr === pl) {
+          this.debug("** at the end");
+          for (; fi < fl; fi++) {
+            if (file[fi] === "." || file[fi] === ".." || !options.dot && file[fi].charAt(0) === ".")
+              return false;
+          }
+          return true;
+        }
+        while (fr < fl) {
+          var swallowee = file[fr];
+          this.debug("\nglobstar while", file, fr, pattern, pr, swallowee);
+          if (this.matchOne(file.slice(fr), pattern.slice(pr), partial)) {
+            this.debug("globstar found match!", fr, fl, swallowee);
+            return true;
+          } else {
+            if (swallowee === "." || swallowee === ".." || !options.dot && swallowee.charAt(0) === ".") {
+              this.debug("dot detected!", file, fr, pattern, pr);
+              break;
+            }
+            this.debug("globstar swallow a segment, and continue");
+            fr++;
+          }
+        }
+        if (partial) {
+          this.debug("\n>>> no match, partial?", file, fr, pattern, pr);
+          if (fr === fl) {
+            return true;
+          }
+        }
+        return false;
+      }
+      let hit;
+      if (typeof p === "string") {
+        hit = f === p;
+        this.debug("string match", p, f, hit);
+      } else {
+        hit = p.test(f);
+        this.debug("pattern match", p, f, hit);
+      }
+      if (!hit)
+        return false;
+    }
+    if (fi === fl && pi === pl) {
+      return true;
+    } else if (fi === fl) {
+      return partial;
+    } else if (pi === pl) {
+      return fi === fl - 1 && file[fi] === "";
+    } else {
+      throw new Error("wtf?");
+    }
+  }
+  braceExpand() {
+    return braceExpand(this.pattern, this.options);
+  }
+  parse(pattern) {
+    assertValidPattern(pattern);
+    const options = this.options;
+    if (pattern === "**")
+      return GLOBSTAR;
+    if (pattern === "")
+      return "";
+    let m;
+    let fastTest = null;
+    if (m = pattern.match(starRE)) {
+      fastTest = options.dot ? starTestDot : starTest;
+    } else if (m = pattern.match(starDotExtRE)) {
+      fastTest = (options.nocase ? options.dot ? starDotExtTestNocaseDot : starDotExtTestNocase : options.dot ? starDotExtTestDot : starDotExtTest)(m[1]);
+    } else if (m = pattern.match(qmarksRE)) {
+      fastTest = (options.nocase ? options.dot ? qmarksTestNocaseDot : qmarksTestNocase : options.dot ? qmarksTestDot : qmarksTest)(m);
+    } else if (m = pattern.match(starDotStarRE)) {
+      fastTest = options.dot ? starDotStarTestDot : starDotStarTest;
+    } else if (m = pattern.match(dotStarRE)) {
+      fastTest = dotStarTest;
+    }
+    const re = AST.fromGlob(pattern, this.options).toMMPattern();
+    if (fastTest && typeof re === "object") {
+      Reflect.defineProperty(re, "test", { value: fastTest });
+    }
+    return re;
+  }
+  makeRe() {
+    if (this.regexp || this.regexp === false)
+      return this.regexp;
+    const set = this.set;
+    if (!set.length) {
+      this.regexp = false;
+      return this.regexp;
+    }
+    const options = this.options;
+    const twoStar = options.noglobstar ? star : options.dot ? twoStarDot : twoStarNoDot;
+    const flags = new Set(options.nocase ? ["i"] : []);
+    let re = set.map((pattern) => {
+      const pp = pattern.map((p) => {
+        if (p instanceof RegExp) {
+          for (const f of p.flags.split(""))
+            flags.add(f);
+        }
+        return typeof p === "string" ? regExpEscape(p) : p === GLOBSTAR ? GLOBSTAR : p._src;
+      });
+      pp.forEach((p, i) => {
+        const next = pp[i + 1];
+        const prev = pp[i - 1];
+        if (p !== GLOBSTAR || prev === GLOBSTAR) {
+          return;
+        }
+        if (prev === void 0) {
+          if (next !== void 0 && next !== GLOBSTAR) {
+            pp[i + 1] = "(?:\\/|" + twoStar + "\\/)?" + next;
+          } else {
+            pp[i] = twoStar;
+          }
+        } else if (next === void 0) {
+          pp[i - 1] = prev + "(?:\\/|" + twoStar + ")?";
+        } else if (next !== GLOBSTAR) {
+          pp[i - 1] = prev + "(?:\\/|\\/" + twoStar + "\\/)" + next;
+          pp[i + 1] = GLOBSTAR;
+        }
+      });
+      return pp.filter((p) => p !== GLOBSTAR).join("/");
+    }).join("|");
+    const [open, close] = set.length > 1 ? ["(?:", ")"] : ["", ""];
+    re = "^" + open + re + close + "$";
+    if (this.negate)
+      re = "^(?!" + re + ").+$";
+    try {
+      this.regexp = new RegExp(re, [...flags].join(""));
+    } catch (ex) {
+      this.regexp = false;
+    }
+    return this.regexp;
+  }
+  slashSplit(p) {
+    if (this.preserveMultipleSlashes) {
+      return p.split("/");
+    } else if (this.isWindows && /^\/\/[^\/]+/.test(p)) {
+      return ["", ...p.split(/\/+/)];
+    } else {
+      return p.split(/\/+/);
+    }
+  }
+  match(f, partial = this.partial) {
+    this.debug("match", f, this.pattern);
+    if (this.comment) {
+      return false;
+    }
+    if (this.empty) {
+      return f === "";
+    }
+    if (f === "/" && partial) {
+      return true;
+    }
+    const options = this.options;
+    if (this.isWindows) {
+      f = f.split("\\").join("/");
+    }
+    const ff = this.slashSplit(f);
+    this.debug(this.pattern, "split", ff);
+    const set = this.set;
+    this.debug(this.pattern, "set", set);
+    let filename = ff[ff.length - 1];
+    if (!filename) {
+      for (let i = ff.length - 2; !filename && i >= 0; i--) {
+        filename = ff[i];
+      }
+    }
+    for (let i = 0; i < set.length; i++) {
+      const pattern = set[i];
+      let file = ff;
+      if (options.matchBase && pattern.length === 1) {
+        file = [filename];
+      }
+      const hit = this.matchOne(file, pattern, partial);
+      if (hit) {
+        if (options.flipNegate) {
+          return true;
+        }
+        return !this.negate;
+      }
+    }
+    if (options.flipNegate) {
+      return false;
+    }
+    return this.negate;
+  }
+  static defaults(def) {
+    return minimatch.defaults(def).Minimatch;
+  }
+}
+minimatch.AST = AST;
+minimatch.Minimatch = Minimatch;
+minimatch.escape = escape;
+minimatch.unescape = unescape;
+const PACKAGE_NAME$2 = "@fastify/otel";
+const PACKAGE_VERSION$2 = "0.8.0";
+const SUPPORTED_VERSIONS$1 = ">=4.0.0 <6";
+const FASTIFY_HOOKS = [
+  "onRequest",
+  "preParsing",
+  "preValidation",
+  "preHandler",
+  "preSerialization",
+  "onSend",
+  "onResponse",
+  "onError"
+];
+const ATTRIBUTE_NAMES = {
+  HOOK_NAME: "hook.name",
+  FASTIFY_TYPE: "fastify.type",
+  HOOK_CALLBACK_NAME: "hook.callback.name",
+  ROOT: "fastify.root"
+};
+const HOOK_TYPES = {
+  ROUTE: "route-hook",
+  INSTANCE: "hook",
+  HANDLER: "request-handler"
+};
+const ANONYMOUS_FUNCTION_NAME = "anonymous";
+const kInstrumentation = Symbol("fastify otel instance");
+const kRequestSpan = Symbol("fastify otel request spans");
+const kRequestContext = Symbol("fastify otel request context");
+const kAddHookOriginal = Symbol("fastify otel addhook original");
+const kSetNotFoundOriginal = Symbol("fastify otel setnotfound original");
+const kIgnorePaths = Symbol("fastify otel ignore path");
+class FastifyOtelInstrumentation extends InstrumentationBase {
+  constructor(config2) {
+    super(PACKAGE_NAME$2, PACKAGE_VERSION$2, config2);
+    this.servername = config2?.servername ?? process.env.OTEL_SERVICE_NAME ?? "fastify";
+    this[kIgnorePaths] = null;
+    this._logger = srcExports$l.diag.createComponentLogger({ namespace: PACKAGE_NAME$2 });
+    if (config2?.ignorePaths != null || process.env.OTEL_FASTIFY_IGNORE_PATHS != null) {
+      const ignorePaths = config2?.ignorePaths ?? process.env.OTEL_FASTIFY_IGNORE_PATHS;
+      if ((typeof ignorePaths !== "string" || ignorePaths.length === 0) && typeof ignorePaths !== "function") {
+        throw new TypeError("ignorePaths must be a string or a function");
+      }
+      const globMatcher = minimatch;
+      this[kIgnorePaths] = (routeOptions) => {
+        if (typeof ignorePaths === "function") {
+          return ignorePaths(routeOptions);
+        } else {
+          return globMatcher(routeOptions.url, ignorePaths);
+        }
+      };
+    }
+  }
+  enable() {
+    if (this._handleInitialization === void 0 && this.getConfig().registerOnInitialization) {
+      const FastifyInstrumentationPlugin = this.plugin();
+      this._handleInitialization = (message) => {
+        message.fastify.register(FastifyInstrumentationPlugin);
+      };
+      diagnosticsChannel__default.subscribe("fastify.initialization", this._handleInitialization);
+    }
+    return super.enable();
+  }
+  disable() {
+    if (this._handleInitialization) {
+      diagnosticsChannel__default.unsubscribe("fastify.initialization", this._handleInitialization);
+      this._handleInitialization = void 0;
+    }
+    return super.disable();
+  }
+  // We do not do patching in this instrumentation
+  init() {
+    return [];
+  }
+  plugin() {
+    const instrumentation2 = this;
+    FastifyInstrumentationPlugin[Symbol.for("skip-override")] = true;
+    FastifyInstrumentationPlugin[Symbol.for("fastify.display-name")] = "@fastify/otel";
+    FastifyInstrumentationPlugin[Symbol.for("plugin-meta")] = {
+      fastify: SUPPORTED_VERSIONS$1,
+      name: "@fastify/otel"
+    };
+    return FastifyInstrumentationPlugin;
+    function FastifyInstrumentationPlugin(instance, opts, done) {
+      instance.decorate(kInstrumentation, instrumentation2);
+      instance.decorate(kAddHookOriginal, instance.addHook);
+      instance.decorate(kSetNotFoundOriginal, instance.setNotFoundHandler);
+      instance.decorateRequest("opentelemetry", function openetelemetry() {
+        const ctx = this[kRequestContext];
+        const span = this[kRequestSpan];
+        return {
+          span,
+          tracer: instrumentation2.tracer,
+          context: ctx,
+          inject: (carrier, setter) => {
+            return srcExports$l.propagation.inject(ctx, carrier, setter);
+          },
+          extract: (carrier, getter) => {
+            return srcExports$l.propagation.extract(ctx, carrier, getter);
+          }
+        };
+      });
+      instance.decorateRequest(kRequestSpan, null);
+      instance.decorateRequest(kRequestContext, null);
+      instance.addHook("onRoute", function(routeOptions) {
+        if (instrumentation2[kIgnorePaths]?.(routeOptions) === true) {
+          instrumentation2._logger.debug(
+            `Ignoring route instrumentation ${routeOptions.method} ${routeOptions.url} because it matches the ignore path`
+          );
+          return;
+        }
+        for (const hook of FASTIFY_HOOKS) {
+          if (routeOptions[hook] != null) {
+            const handlerLike = routeOptions[hook];
+            if (typeof handlerLike === "function") {
+              routeOptions[hook] = handlerWrapper(handlerLike, {
+                [srcExports$k.ATTR_SERVICE_NAME]: instance[kInstrumentation].servername,
+                [ATTRIBUTE_NAMES.HOOK_NAME]: `${this.pluginName} - route -> ${hook}`,
+                [ATTRIBUTE_NAMES.FASTIFY_TYPE]: HOOK_TYPES.ROUTE,
+                [srcExports$k.ATTR_HTTP_ROUTE]: routeOptions.url,
+                [ATTRIBUTE_NAMES.HOOK_CALLBACK_NAME]: handlerLike.name?.length > 0 ? handlerLike.name : ANONYMOUS_FUNCTION_NAME
+              });
+            } else if (Array.isArray(handlerLike)) {
+              const wrappedHandlers = [];
+              for (const handler of handlerLike) {
+                wrappedHandlers.push(
+                  handlerWrapper(handler, {
+                    [srcExports$k.ATTR_SERVICE_NAME]: instance[kInstrumentation].servername,
+                    [ATTRIBUTE_NAMES.HOOK_NAME]: `${this.pluginName} - route -> ${hook}`,
+                    [ATTRIBUTE_NAMES.FASTIFY_TYPE]: HOOK_TYPES.ROUTE,
+                    [srcExports$k.ATTR_HTTP_ROUTE]: routeOptions.url,
+                    [ATTRIBUTE_NAMES.HOOK_CALLBACK_NAME]: handler.name?.length > 0 ? handler.name : ANONYMOUS_FUNCTION_NAME
+                  })
+                );
+              }
+              routeOptions[hook] = wrappedHandlers;
+            }
+          }
+        }
+        if (routeOptions.onSend != null) {
+          routeOptions.onSend = Array.isArray(routeOptions.onSend) ? [...routeOptions.onSend, onSendHook] : [routeOptions.onSend, onSendHook];
+        } else {
+          routeOptions.onSend = onSendHook;
+        }
+        if (routeOptions.onError != null) {
+          routeOptions.onError = Array.isArray(routeOptions.onError) ? [...routeOptions.onError, onErrorHook] : [routeOptions.onError, onErrorHook];
+        } else {
+          routeOptions.onError = onErrorHook;
+        }
+        routeOptions.handler = handlerWrapper(routeOptions.handler, {
+          [srcExports$k.ATTR_SERVICE_NAME]: instance[kInstrumentation].servername,
+          [ATTRIBUTE_NAMES.HOOK_NAME]: `${this.pluginName} - route-handler`,
+          [ATTRIBUTE_NAMES.FASTIFY_TYPE]: HOOK_TYPES.HANDLER,
+          [srcExports$k.ATTR_HTTP_ROUTE]: routeOptions.url,
+          [ATTRIBUTE_NAMES.HOOK_CALLBACK_NAME]: routeOptions.handler.name.length > 0 ? routeOptions.handler.name : ANONYMOUS_FUNCTION_NAME
+        });
+      });
+      instance.addHook("onRequest", function(request, _reply, hookDone) {
+        if (this[kInstrumentation].isEnabled() === false) {
+          return hookDone();
+        } else if (this[kInstrumentation][kIgnorePaths]?.({
+          url: request.url,
+          method: request.method
+        }) === true) {
+          this[kInstrumentation]._logger.debug(
+            `Ignoring request ${request.method} ${request.url} because it matches the ignore path`
+          );
+          return hookDone();
+        }
+        let ctx = srcExports$l.context.active();
+        if (srcExports$l.trace.getSpan(ctx) == null) {
+          ctx = srcExports$l.propagation.extract(ctx, request.headers);
+        }
+        const rpcMetadata = getRPCMetadata(ctx);
+        if (request.routeOptions.url != null && rpcMetadata?.type === RPCType.HTTP) {
+          rpcMetadata.route = request.routeOptions.url;
+        }
+        const span = this[kInstrumentation].tracer.startSpan(
+          "request",
+          {
+            attributes: {
+              [srcExports$k.ATTR_SERVICE_NAME]: instance[kInstrumentation].servername,
+              [ATTRIBUTE_NAMES.ROOT]: "@fastify/otel",
+              [srcExports$k.ATTR_HTTP_ROUTE]: request.url,
+              [srcExports$k.ATTR_HTTP_REQUEST_METHOD]: request.method
+            }
+          },
+          ctx
+        );
+        request[kRequestContext] = srcExports$l.trace.setSpan(ctx, span);
+        request[kRequestSpan] = span;
+        srcExports$l.context.with(request[kRequestContext], () => {
+          hookDone();
+        });
+      });
+      instance.addHook("onResponse", function(request, reply, hookDone) {
+        const span = request[kRequestSpan];
+        if (span != null) {
+          span.setStatus({
+            code: srcExports$l.SpanStatusCode.OK,
+            message: "OK"
+          });
+          span.setAttributes({
+            [srcExports$k.ATTR_HTTP_RESPONSE_STATUS_CODE]: 404
+          });
+          span.end();
+        }
+        request[kRequestSpan] = null;
+        hookDone();
+      });
+      instance.addHook = addHookPatched;
+      instance.setNotFoundHandler = setNotFoundHandlerPatched;
+      done();
+      function onSendHook(request, reply, payload, hookDone) {
+        const span = request[kRequestSpan];
+        if (span != null) {
+          if (reply.statusCode < 500) {
+            span.setStatus({
+              code: srcExports$l.SpanStatusCode.OK,
+              message: "OK"
+            });
+          }
+          span.setAttributes({
+            [srcExports$k.ATTR_HTTP_RESPONSE_STATUS_CODE]: reply.statusCode
+          });
+          span.end();
+        }
+        request[kRequestSpan] = null;
+        hookDone(null, payload);
+      }
+      function onErrorHook(request, reply, error2, hookDone) {
+        const span = request[kRequestSpan];
+        if (span != null) {
+          span.setStatus({
+            code: srcExports$l.SpanStatusCode.ERROR,
+            message: error2.message
+          });
+          span.recordException(error2);
+        }
+        hookDone();
+      }
+      function addHookPatched(name, hook) {
+        const addHookOriginal = this[kAddHookOriginal];
+        if (FASTIFY_HOOKS.includes(name)) {
+          return addHookOriginal.call(
+            this,
+            name,
+            handlerWrapper(hook, {
+              [srcExports$k.ATTR_SERVICE_NAME]: instance[kInstrumentation].servername,
+              [ATTRIBUTE_NAMES.HOOK_NAME]: `${this.pluginName} - ${name}`,
+              [ATTRIBUTE_NAMES.FASTIFY_TYPE]: HOOK_TYPES.INSTANCE,
+              [ATTRIBUTE_NAMES.HOOK_CALLBACK_NAME]: hook.name?.length > 0 ? hook.name : ANONYMOUS_FUNCTION_NAME
+            })
+          );
+        } else {
+          return addHookOriginal.call(this, name, hook);
+        }
+      }
+      function setNotFoundHandlerPatched(hooks, handler) {
+        const setNotFoundHandlerOriginal = this[kSetNotFoundOriginal];
+        if (typeof hooks === "function") {
+          handler = handlerWrapper(hooks, {
+            [srcExports$k.ATTR_SERVICE_NAME]: instance[kInstrumentation].servername,
+            [ATTRIBUTE_NAMES.HOOK_NAME]: `${this.pluginName} - not-found-handler`,
+            [ATTRIBUTE_NAMES.FASTIFY_TYPE]: HOOK_TYPES.INSTANCE,
+            [ATTRIBUTE_NAMES.HOOK_CALLBACK_NAME]: hooks.name?.length > 0 ? hooks.name : ANONYMOUS_FUNCTION_NAME
+          });
+          setNotFoundHandlerOriginal.call(this, handler);
+        } else {
+          if (hooks.preValidation != null) {
+            hooks.preValidation = handlerWrapper(hooks.preValidation, {
+              [srcExports$k.ATTR_SERVICE_NAME]: instance[kInstrumentation].servername,
+              [ATTRIBUTE_NAMES.HOOK_NAME]: `${this.pluginName} - not-found-handler - preValidation`,
+              [ATTRIBUTE_NAMES.FASTIFY_TYPE]: HOOK_TYPES.INSTANCE,
+              [ATTRIBUTE_NAMES.HOOK_CALLBACK_NAME]: hooks.preValidation.name?.length > 0 ? hooks.preValidation.name : ANONYMOUS_FUNCTION_NAME
+            });
+          }
+          if (hooks.preHandler != null) {
+            hooks.preHandler = handlerWrapper(hooks.preHandler, {
+              [srcExports$k.ATTR_SERVICE_NAME]: instance[kInstrumentation].servername,
+              [ATTRIBUTE_NAMES.HOOK_NAME]: `${this.pluginName} - not-found-handler - preHandler`,
+              [ATTRIBUTE_NAMES.FASTIFY_TYPE]: HOOK_TYPES.INSTANCE,
+              [ATTRIBUTE_NAMES.HOOK_CALLBACK_NAME]: hooks.preHandler.name?.length > 0 ? hooks.preHandler.name : ANONYMOUS_FUNCTION_NAME
+            });
+          }
+          handler = handlerWrapper(handler, {
+            [srcExports$k.ATTR_SERVICE_NAME]: instance[kInstrumentation].servername,
+            [ATTRIBUTE_NAMES.HOOK_NAME]: `${this.pluginName} - not-found-handler`,
+            [ATTRIBUTE_NAMES.FASTIFY_TYPE]: HOOK_TYPES.INSTANCE,
+            [ATTRIBUTE_NAMES.HOOK_CALLBACK_NAME]: handler.name?.length > 0 ? handler.name : ANONYMOUS_FUNCTION_NAME
+          });
+          setNotFoundHandlerOriginal.call(this, hooks, handler);
+        }
+      }
+      function handlerWrapper(handler, spanAttributes = {}) {
+        return function handlerWrapped(...args) {
+          const instrumentation3 = this[kInstrumentation];
+          const [request] = args;
+          if (instrumentation3.isEnabled() === false) {
+            return handler.call(this, ...args);
+          }
+          const ctx = request[kRequestContext] ?? srcExports$l.context.active();
+          const span = instrumentation3.tracer.startSpan(
+            `handler - ${handler.name?.length > 0 ? handler.name : this.pluginName ?? ANONYMOUS_FUNCTION_NAME}`,
+            {
+              attributes: spanAttributes
+            },
+            ctx
+          );
+          return srcExports$l.context.with(
+            srcExports$l.trace.setSpan(ctx, span),
+            function() {
+              try {
+                const res = handler.call(this, ...args);
+                if (typeof res?.then === "function") {
+                  return res.then(
+                    (result) => {
+                      span.end();
+                      return result;
+                    },
+                    (error2) => {
+                      span.setStatus({
+                        code: srcExports$l.SpanStatusCode.ERROR,
+                        message: error2.message
+                      });
+                      span.recordException(error2);
+                      span.end();
+                      return Promise.reject(error2);
+                    }
+                  );
+                }
+                span.end();
+                return res;
+              } catch (error2) {
+                span.setStatus({
+                  code: srcExports$l.SpanStatusCode.ERROR,
+                  message: error2.message
+                });
+                span.recordException(error2);
+                span.end();
+                throw error2;
+              }
+            },
+            this
+          );
+        };
+      }
+    }
+  }
+}
+var AttributeNames$7;
+(function(AttributeNames2) {
+  const FASTIFY_NAME = "fastify.name";
+  AttributeNames2["FASTIFY_NAME"] = FASTIFY_NAME;
+  const FASTIFY_TYPE = "fastify.type";
+  AttributeNames2["FASTIFY_TYPE"] = FASTIFY_TYPE;
+  const HOOK_NAME = "hook.name";
+  AttributeNames2["HOOK_NAME"] = HOOK_NAME;
+  const PLUGIN_NAME = "plugin.name";
+  AttributeNames2["PLUGIN_NAME"] = PLUGIN_NAME;
+})(AttributeNames$7 || (AttributeNames$7 = {}));
+var FastifyTypes;
+(function(FastifyTypes2) {
+  const MIDDLEWARE = "middleware";
+  FastifyTypes2["MIDDLEWARE"] = MIDDLEWARE;
+  const REQUEST_HANDLER = "request_handler";
+  FastifyTypes2["REQUEST_HANDLER"] = REQUEST_HANDLER;
+})(FastifyTypes || (FastifyTypes = {}));
+var FastifyNames;
+(function(FastifyNames2) {
+  const MIDDLEWARE = "middleware";
+  FastifyNames2["MIDDLEWARE"] = MIDDLEWARE;
+  const REQUEST_HANDLER = "request handler";
+  FastifyNames2["REQUEST_HANDLER"] = REQUEST_HANDLER;
+})(FastifyNames || (FastifyNames = {}));
+const spanRequestSymbol = Symbol("opentelemetry.instrumentation.fastify.request_active_span");
+function startSpan(reply, tracer, spanName, spanAttributes = {}) {
+  const span = tracer.startSpan(spanName, { attributes: spanAttributes });
+  const spans = reply[spanRequestSymbol] || [];
+  spans.push(span);
+  Object.defineProperty(reply, spanRequestSymbol, {
+    enumerable: false,
+    configurable: true,
+    value: spans
+  });
+  return span;
+}
+function endSpan$1(reply, err) {
+  const spans = reply[spanRequestSymbol] || [];
+  if (!spans.length) {
+    return;
+  }
+  spans.forEach((span) => {
+    if (err) {
+      span.setStatus({
+        code: srcExports$l.SpanStatusCode.ERROR,
+        message: err.message
+      });
+      span.recordException(err);
+    }
+    span.end();
+  });
+  delete reply[spanRequestSymbol];
+}
+function safeExecuteInTheMiddleMaybePromise(execute, onFinish, preventThrowingError) {
+  let error2;
+  let result = void 0;
+  try {
+    result = execute();
+    if (isPromise(result)) {
+      result.then(
+        (res) => onFinish(void 0, res),
+        (err) => onFinish(err)
+      );
+    }
+  } catch (e) {
+    error2 = e;
+  } finally {
+    if (!isPromise(result)) {
+      onFinish(error2, result);
+      if (error2 && true) {
+        throw error2;
+      }
+    }
+    return result;
+  }
+}
+function isPromise(val) {
+  return typeof val === "object" && val && typeof Object.getOwnPropertyDescriptor(val, "then")?.value === "function" || false;
+}
+const PACKAGE_VERSION$1 = "0.1.0";
+const PACKAGE_NAME$1 = "@sentry/instrumentation-fastify-v3";
+const ANONYMOUS_NAME = "anonymous";
+const hooksNamesToWrap = /* @__PURE__ */ new Set([
+  "onTimeout",
+  "onRequest",
+  "preParsing",
+  "preValidation",
+  "preSerialization",
+  "preHandler",
+  "onSend",
+  "onResponse",
+  "onError"
+]);
+class FastifyInstrumentationV3 extends InstrumentationBase {
+  constructor(config2 = {}) {
+    super(PACKAGE_NAME$1, PACKAGE_VERSION$1, config2);
+  }
+  init() {
+    return [
+      new InstrumentationNodeModuleDefinition("fastify", [">=3.0.0 <4"], (moduleExports) => {
+        return this._patchConstructor(moduleExports);
+      })
+    ];
+  }
+  _hookOnRequest() {
+    const instrumentation2 = this;
+    return function onRequest(request, reply, done) {
+      if (!instrumentation2.isEnabled()) {
+        return done();
+      }
+      instrumentation2._wrap(reply, "send", instrumentation2._patchSend());
+      const anyRequest = request;
+      const rpcMetadata = getRPCMetadata(srcExports$l.context.active());
+      const routeName = anyRequest.routeOptions ? anyRequest.routeOptions.url : request.routerPath;
+      if (routeName && rpcMetadata?.type === RPCType.HTTP) {
+        rpcMetadata.route = routeName;
+      }
+      const method = request.method || "GET";
+      getIsolationScope().setTransactionName(`${method} ${routeName}`);
+      done();
+    };
+  }
+  _wrapHandler(pluginName, hookName, original, syncFunctionWithDone) {
+    const instrumentation2 = this;
+    this._diag.debug("Patching fastify route.handler function");
+    return function(...args) {
+      if (!instrumentation2.isEnabled()) {
+        return original.apply(this, args);
+      }
+      const name = original.name || pluginName || ANONYMOUS_NAME;
+      const spanName = `${FastifyNames.MIDDLEWARE} - ${name}`;
+      const reply = args[1];
+      const span = startSpan(reply, instrumentation2.tracer, spanName, {
+        [AttributeNames$7.FASTIFY_TYPE]: FastifyTypes.MIDDLEWARE,
+        [AttributeNames$7.PLUGIN_NAME]: pluginName,
+        [AttributeNames$7.HOOK_NAME]: hookName
+      });
+      const origDone = syncFunctionWithDone && args[args.length - 1];
+      if (origDone) {
+        args[args.length - 1] = function(...doneArgs) {
+          endSpan$1(reply);
+          origDone.apply(this, doneArgs);
+        };
+      }
+      return srcExports$l.context.with(srcExports$l.trace.setSpan(srcExports$l.context.active(), span), () => {
+        return safeExecuteInTheMiddleMaybePromise(
+          () => {
+            return original.apply(this, args);
+          },
+          (err) => {
+            if (err instanceof Error) {
+              span.setStatus({
+                code: srcExports$l.SpanStatusCode.ERROR,
+                message: err.message
+              });
+              span.recordException(err);
+            }
+            if (!syncFunctionWithDone) {
+              endSpan$1(reply);
+            }
+          }
+        );
+      });
+    };
+  }
+  _wrapAddHook() {
+    const instrumentation2 = this;
+    this._diag.debug("Patching fastify server.addHook function");
+    return function(original) {
+      return function wrappedAddHook(...args) {
+        const name = args[0];
+        const handler = args[1];
+        const pluginName = this.pluginName;
+        if (!hooksNamesToWrap.has(name)) {
+          return original.apply(this, args);
+        }
+        const syncFunctionWithDone = typeof args[args.length - 1] === "function" && handler.constructor.name !== "AsyncFunction";
+        return original.apply(this, [
+          name,
+          instrumentation2._wrapHandler(pluginName, name, handler, syncFunctionWithDone)
+        ]);
+      };
+    };
+  }
+  _patchConstructor(moduleExports) {
+    const instrumentation2 = this;
+    function fastify(...args) {
+      const app = moduleExports.fastify.apply(this, args);
+      app.addHook("onRequest", instrumentation2._hookOnRequest());
+      app.addHook("preHandler", instrumentation2._hookPreHandler());
+      instrumentClient$1();
+      instrumentation2._wrap(app, "addHook", instrumentation2._wrapAddHook());
+      return app;
+    }
+    if (moduleExports.errorCodes !== void 0) {
+      fastify.errorCodes = moduleExports.errorCodes;
+    }
+    fastify.fastify = fastify;
+    fastify.default = fastify;
+    return fastify;
+  }
+  _patchSend() {
+    const instrumentation2 = this;
+    this._diag.debug("Patching fastify reply.send function");
+    return function patchSend(original) {
+      return function send(...args) {
+        const maybeError = args[0];
+        if (!instrumentation2.isEnabled()) {
+          return original.apply(this, args);
+        }
+        return safeExecuteInTheMiddle(
+          () => {
+            return original.apply(this, args);
+          },
+          (err) => {
+            if (!err && maybeError instanceof Error) {
+              err = maybeError;
+            }
+            endSpan$1(this, err);
+          }
+        );
+      };
+    };
+  }
+  _hookPreHandler() {
+    const instrumentation2 = this;
+    this._diag.debug("Patching fastify preHandler function");
+    return function preHandler(request, reply, done) {
+      if (!instrumentation2.isEnabled()) {
+        return done();
+      }
+      const anyRequest = request;
+      const handler = anyRequest.routeOptions?.handler || anyRequest.context?.handler;
+      const handlerName = handler?.name.startsWith("bound ") ? handler.name.substring(6) : handler?.name;
+      const spanName = `${FastifyNames.REQUEST_HANDLER} - ${handlerName || this.pluginName || ANONYMOUS_NAME}`;
+      const spanAttributes = {
+        [AttributeNames$7.PLUGIN_NAME]: this.pluginName,
+        [AttributeNames$7.FASTIFY_TYPE]: FastifyTypes.REQUEST_HANDLER,
+        // eslint-disable-next-line deprecation/deprecation
+        [srcExports$k.SEMATTRS_HTTP_ROUTE]: anyRequest.routeOptions ? anyRequest.routeOptions.url : request.routerPath
+      };
+      if (handlerName) {
+        spanAttributes[AttributeNames$7.FASTIFY_NAME] = handlerName;
+      }
+      const span = startSpan(reply, instrumentation2.tracer, spanName, spanAttributes);
+      addFastifyV3SpanAttributes(span);
+      const { requestHook: requestHook2 } = instrumentation2.getConfig();
+      if (requestHook2) {
+        safeExecuteInTheMiddle(
+          () => requestHook2(span, { request }),
+          (e) => {
+            if (e) {
+              instrumentation2._diag.error("request hook failed", e);
+            }
+          },
+          true
+        );
+      }
+      return srcExports$l.context.with(srcExports$l.trace.setSpan(srcExports$l.context.active(), span), () => {
+        done();
+      });
+    };
+  }
+}
+function instrumentClient$1() {
+  const client = getClient();
+  if (client) {
+    client.on("spanStart", (span) => {
+      addFastifyV3SpanAttributes(span);
+    });
+  }
+}
+function addFastifyV3SpanAttributes(span) {
+  const attributes = spanToJSON(span).data;
+  const type = attributes["fastify.type"];
+  if (attributes[SEMANTIC_ATTRIBUTE_SENTRY_OP] || !type) {
+    return;
+  }
+  span.setAttributes({
+    [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: "auto.http.otel.fastify",
+    [SEMANTIC_ATTRIBUTE_SENTRY_OP]: `${type}.fastify`
+  });
+  const name = attributes["fastify.name"] || attributes["plugin.name"] || attributes["hook.name"];
+  if (typeof name === "string") {
+    const updatedName = name.replace(/^fastify -> /, "").replace(/^@fastify\/otel -> /, "");
+    span.updateName(updatedName);
+  }
+}
+const INTEGRATION_NAME$k = "Fastify";
+const instrumentFastifyV3 = generateInstrumentOnce(
+  `${INTEGRATION_NAME$k}.v3`,
+  () => new FastifyInstrumentationV3()
+);
+function getFastifyIntegration() {
+  const client = getClient();
+  if (!client) {
+    return void 0;
+  } else {
+    return client.getIntegrationByName(INTEGRATION_NAME$k);
+  }
+}
+function handleFastifyError(error2, request, reply, handlerOrigin) {
+  const shouldHandleError = getFastifyIntegration()?.getShouldHandleError() || defaultShouldHandleError;
+  if (handlerOrigin === "diagnostics-channel") {
+    this.diagnosticsChannelExists = true;
+  }
+  if (this.diagnosticsChannelExists && handlerOrigin === "onError-hook") {
+    DEBUG_BUILD && debug$2.warn(
+      "Fastify error handler was already registered via diagnostics channel.",
+      "You can safely remove `setupFastifyErrorHandler` call and set `shouldHandleError` on the integration options."
+    );
+    return;
+  }
+  if (shouldHandleError(error2, request, reply)) {
+    captureException(error2, { mechanism: { handled: false, type: "auto.function.fastify" } });
+  }
+}
+const instrumentFastify = generateInstrumentOnce(`${INTEGRATION_NAME$k}.v5`, () => {
+  const fastifyOtelInstrumentationInstance = new FastifyOtelInstrumentation();
+  const plugin = fastifyOtelInstrumentationInstance.plugin();
+  diagnosticsChannel.subscribe("fastify.initialization", (message) => {
+    const fastifyInstance = message.fastify;
+    fastifyInstance?.register(plugin).after((err) => {
+      if (err) {
+        DEBUG_BUILD && debug$2.error("Failed to setup Fastify instrumentation", err);
+      } else {
+        instrumentClient();
+        if (fastifyInstance) {
+          instrumentOnRequest(fastifyInstance);
+        }
+      }
+    });
+  });
+  diagnosticsChannel.subscribe("tracing:fastify.request.handler:error", (message) => {
+    const { error: error2, request, reply } = message;
+    handleFastifyError.call(handleFastifyError, error2, request, reply, "diagnostics-channel");
+  });
+  return fastifyOtelInstrumentationInstance;
+});
+const _fastifyIntegration = (({ shouldHandleError }) => {
+  let _shouldHandleError;
+  return {
+    name: INTEGRATION_NAME$k,
+    setupOnce() {
+      _shouldHandleError = shouldHandleError || defaultShouldHandleError;
+      instrumentFastifyV3();
+      instrumentFastify();
+    },
+    getShouldHandleError() {
+      return _shouldHandleError;
+    },
+    setShouldHandleError(fn) {
+      _shouldHandleError = fn;
+    }
+  };
+});
+const fastifyIntegration = defineIntegration(
+  (options = {}) => _fastifyIntegration(options)
+);
+function defaultShouldHandleError(_error, _request, reply) {
+  const statusCode = reply.statusCode;
+  return statusCode >= 500 || statusCode <= 299;
+}
+function addFastifySpanAttributes(span) {
+  const spanJSON = spanToJSON(span);
+  const spanName = spanJSON.description;
+  const attributes = spanJSON.data;
+  const type = attributes["fastify.type"];
+  const isHook = type === "hook";
+  const isHandler = type === spanName?.startsWith("handler -");
+  const isRequestHandler = spanName === "request" || type === "request-handler";
+  if (attributes[SEMANTIC_ATTRIBUTE_SENTRY_OP] || !isHandler && !isRequestHandler && !isHook) {
+    return;
+  }
+  const opPrefix = isHook ? "hook" : isHandler ? "middleware" : isRequestHandler ? "request-handler" : "";
+  span.setAttributes({
+    [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: "auto.http.otel.fastify",
+    [SEMANTIC_ATTRIBUTE_SENTRY_OP]: `${opPrefix}.fastify`
+  });
+  const attrName = attributes["fastify.name"] || attributes["plugin.name"] || attributes["hook.name"];
+  if (typeof attrName === "string") {
+    const updatedName = attrName.replace(/^fastify -> /, "").replace(/^@fastify\/otel -> /, "");
+    span.updateName(updatedName);
+  }
+}
+function instrumentClient() {
+  const client = getClient();
+  if (client) {
+    client.on("spanStart", (span) => {
+      addFastifySpanAttributes(span);
+    });
+  }
+}
+function instrumentOnRequest(fastify) {
+  fastify.addHook("onRequest", async (request, _reply) => {
+    if (request.opentelemetry) {
+      const { span } = request.opentelemetry();
+      if (span) {
+        addFastifySpanAttributes(span);
+      }
+    }
+    const routeName = request.routeOptions?.url;
+    const method = request.method || "GET";
+    getIsolationScope().setTransactionName(`${method} ${routeName}`);
+  });
+}
+var src$h = {};
+var instrumentation$e = {};
+var _enum = {};
+var hasRequired_enum;
+function require_enum() {
+  if (hasRequired_enum) return _enum;
+  hasRequired_enum = 1;
+  (function(exports$1) {
+    Object.defineProperty(exports$1, "__esModule", { value: true });
+    exports$1.SpanNames = exports$1.TokenKind = exports$1.AllowedOperationTypes = void 0;
+    (function(AllowedOperationTypes) {
+      AllowedOperationTypes["QUERY"] = "query";
+      AllowedOperationTypes["MUTATION"] = "mutation";
+      AllowedOperationTypes["SUBSCRIPTION"] = "subscription";
+    })(exports$1.AllowedOperationTypes || (exports$1.AllowedOperationTypes = {}));
+    (function(TokenKind) {
+      TokenKind["SOF"] = "";
+      TokenKind["EOF"] = "";
+      TokenKind["BANG"] = "!";
+      TokenKind["DOLLAR"] = "$";
+      TokenKind["AMP"] = "&";
+      TokenKind["PAREN_L"] = "(";
+      TokenKind["PAREN_R"] = ")";
+      TokenKind["SPREAD"] = "...";
+      TokenKind["COLON"] = ":";
+      TokenKind["EQUALS"] = "=";
+      TokenKind["AT"] = "@";
+      TokenKind["BRACKET_L"] = "[";
+      TokenKind["BRACKET_R"] = "]";
+      TokenKind["BRACE_L"] = "{";
+      TokenKind["PIPE"] = "|";
+      TokenKind["BRACE_R"] = "}";
+      TokenKind["NAME"] = "Name";
+      TokenKind["INT"] = "Int";
+      TokenKind["FLOAT"] = "Float";
+      TokenKind["STRING"] = "String";
+      TokenKind["BLOCK_STRING"] = "BlockString";
+      TokenKind["COMMENT"] = "Comment";
+    })(exports$1.TokenKind || (exports$1.TokenKind = {}));
+    (function(SpanNames2) {
+      SpanNames2["EXECUTE"] = "graphql.execute";
+      SpanNames2["PARSE"] = "graphql.parse";
+      SpanNames2["RESOLVE"] = "graphql.resolve";
+      SpanNames2["VALIDATE"] = "graphql.validate";
+      SpanNames2["SCHEMA_VALIDATE"] = "graphql.validateSchema";
+      SpanNames2["SCHEMA_PARSE"] = "graphql.parseSchema";
+    })(exports$1.SpanNames || (exports$1.SpanNames = {}));
+  })(_enum);
+  return _enum;
+}
+var AttributeNames$6 = {};
+var hasRequiredAttributeNames$5;
+function requireAttributeNames$5() {
+  if (hasRequiredAttributeNames$5) return AttributeNames$6;
+  hasRequiredAttributeNames$5 = 1;
+  (function(exports$1) {
+    Object.defineProperty(exports$1, "__esModule", { value: true });
+    exports$1.AttributeNames = void 0;
+    (function(AttributeNames2) {
+      AttributeNames2["SOURCE"] = "graphql.source";
+      AttributeNames2["FIELD_NAME"] = "graphql.field.name";
+      AttributeNames2["FIELD_PATH"] = "graphql.field.path";
+      AttributeNames2["FIELD_TYPE"] = "graphql.field.type";
+      AttributeNames2["OPERATION_TYPE"] = "graphql.operation.type";
+      AttributeNames2["OPERATION_NAME"] = "graphql.operation.name";
+      AttributeNames2["VARIABLES"] = "graphql.variables.";
+      AttributeNames2["ERROR_VALIDATION_NAME"] = "graphql.validation.error";
+    })(exports$1.AttributeNames || (exports$1.AttributeNames = {}));
+  })(AttributeNames$6);
+  return AttributeNames$6;
+}
+var symbols = {};
+var hasRequiredSymbols;
+function requireSymbols() {
+  if (hasRequiredSymbols) return symbols;
+  hasRequiredSymbols = 1;
+  Object.defineProperty(symbols, "__esModule", { value: true });
+  symbols.OTEL_GRAPHQL_DATA_SYMBOL = symbols.OTEL_PATCHED_SYMBOL = void 0;
+  symbols.OTEL_PATCHED_SYMBOL = Symbol.for("opentelemetry.patched");
+  symbols.OTEL_GRAPHQL_DATA_SYMBOL = Symbol.for("opentelemetry.graphql_data");
+  return symbols;
+}
+var internalTypes$6 = {};
+var hasRequiredInternalTypes$6;
+function requireInternalTypes$6() {
+  if (hasRequiredInternalTypes$6) return internalTypes$6;
+  hasRequiredInternalTypes$6 = 1;
+  Object.defineProperty(internalTypes$6, "__esModule", { value: true });
+  internalTypes$6.OPERATION_NOT_SUPPORTED = void 0;
+  requireSymbols();
+  internalTypes$6.OPERATION_NOT_SUPPORTED = "Operation$operationName$not supported";
+  return internalTypes$6;
+}
+var utils$c = {};
+var hasRequiredUtils$c;
+function requireUtils$c() {
+  if (hasRequiredUtils$c) return utils$c;
+  hasRequiredUtils$c = 1;
+  (function(exports$1) {
+    Object.defineProperty(exports$1, "__esModule", { value: true });
+    exports$1.wrapFieldResolver = exports$1.wrapFields = exports$1.getSourceFromLocation = exports$1.getOperation = exports$1.endSpan = exports$1.addSpanSource = exports$1.addInputVariableAttributes = exports$1.isPromise = void 0;
+    const api = /* @__PURE__ */ requireSrc$n();
+    const enum_1 = require_enum();
+    const AttributeNames_1 = requireAttributeNames$5();
+    const symbols_1 = requireSymbols();
+    const OPERATION_VALUES = Object.values(enum_1.AllowedOperationTypes);
+    const isPromise2 = (value) => {
+      return typeof value?.then === "function";
+    };
+    exports$1.isPromise = isPromise2;
+    const isObjectLike2 = (value) => {
+      return typeof value == "object" && value !== null;
+    };
+    function addInputVariableAttribute(span, key, variable) {
+      if (Array.isArray(variable)) {
+        variable.forEach((value, idx) => {
+          addInputVariableAttribute(span, `${key}.${idx}`, value);
+        });
+      } else if (variable instanceof Object) {
+        Object.entries(variable).forEach(([nestedKey, value]) => {
+          addInputVariableAttribute(span, `${key}.${nestedKey}`, value);
+        });
+      } else {
+        span.setAttribute(`${AttributeNames_1.AttributeNames.VARIABLES}${String(key)}`, variable);
+      }
+    }
+    function addInputVariableAttributes(span, variableValues) {
+      Object.entries(variableValues).forEach(([key, value]) => {
+        addInputVariableAttribute(span, key, value);
+      });
+    }
+    exports$1.addInputVariableAttributes = addInputVariableAttributes;
+    function addSpanSource(span, loc, allowValues, start, end) {
+      const source = getSourceFromLocation(loc, allowValues, start, end);
+      span.setAttribute(AttributeNames_1.AttributeNames.SOURCE, source);
+    }
+    exports$1.addSpanSource = addSpanSource;
+    function createFieldIfNotExists(tracer, getConfig, contextValue, info, path2) {
+      let field = getField(contextValue, path2);
+      if (field) {
+        return { field, spanAdded: false };
+      }
+      const config2 = getConfig();
+      const parentSpan = config2.flatResolveSpans ? getRootSpan2(contextValue) : getParentFieldSpan(contextValue, path2);
+      field = {
+        span: createResolverSpan(tracer, getConfig, contextValue, info, path2, parentSpan)
+      };
+      addField(contextValue, path2, field);
+      return { field, spanAdded: true };
+    }
+    function createResolverSpan(tracer, getConfig, contextValue, info, path2, parentSpan) {
+      const attributes = {
+        [AttributeNames_1.AttributeNames.FIELD_NAME]: info.fieldName,
+        [AttributeNames_1.AttributeNames.FIELD_PATH]: path2.join("."),
+        [AttributeNames_1.AttributeNames.FIELD_TYPE]: info.returnType.toString()
+      };
+      const span = tracer.startSpan(`${enum_1.SpanNames.RESOLVE} ${attributes[AttributeNames_1.AttributeNames.FIELD_PATH]}`, {
+        attributes
+      }, parentSpan ? api.trace.setSpan(api.context.active(), parentSpan) : void 0);
+      const document2 = contextValue[symbols_1.OTEL_GRAPHQL_DATA_SYMBOL].source;
+      const fieldNode = info.fieldNodes.find((fieldNode2) => fieldNode2.kind === "Field");
+      if (fieldNode) {
+        addSpanSource(span, document2.loc, getConfig().allowValues, fieldNode.loc?.start, fieldNode.loc?.end);
+      }
+      return span;
+    }
+    function endSpan2(span, error2) {
+      if (error2) {
+        span.recordException(error2);
+      }
+      span.end();
+    }
+    exports$1.endSpan = endSpan2;
+    function getOperation(document2, operationName) {
+      if (!document2 || !Array.isArray(document2.definitions)) {
+        return void 0;
+      }
+      if (operationName) {
+        return document2.definitions.filter((definition) => OPERATION_VALUES.indexOf(definition?.operation) !== -1).find((definition) => operationName === definition?.name?.value);
+      } else {
+        return document2.definitions.find((definition) => OPERATION_VALUES.indexOf(definition?.operation) !== -1);
+      }
+    }
+    exports$1.getOperation = getOperation;
+    function addField(contextValue, path2, field) {
+      return contextValue[symbols_1.OTEL_GRAPHQL_DATA_SYMBOL].fields[path2.join(".")] = field;
+    }
+    function getField(contextValue, path2) {
+      return contextValue[symbols_1.OTEL_GRAPHQL_DATA_SYMBOL].fields[path2.join(".")];
+    }
+    function getParentFieldSpan(contextValue, path2) {
+      for (let i = path2.length - 1; i > 0; i--) {
+        const field = getField(contextValue, path2.slice(0, i));
+        if (field) {
+          return field.span;
+        }
+      }
+      return getRootSpan2(contextValue);
+    }
+    function getRootSpan2(contextValue) {
+      return contextValue[symbols_1.OTEL_GRAPHQL_DATA_SYMBOL].span;
+    }
+    function pathToArray(mergeItems, path2) {
+      const flattened = [];
+      let curr = path2;
+      while (curr) {
+        let key = curr.key;
+        if (mergeItems && typeof key === "number") {
+          key = "*";
+        }
+        flattened.push(String(key));
+        curr = curr.prev;
+      }
+      return flattened.reverse();
+    }
+    function repeatBreak(i) {
+      return repeatChar("\n", i);
+    }
+    function repeatSpace(i) {
+      return repeatChar(" ", i);
+    }
+    function repeatChar(char, to) {
+      let text = "";
+      for (let i = 0; i < to; i++) {
+        text += char;
+      }
+      return text;
+    }
+    const KindsToBeRemoved = [
+      enum_1.TokenKind.FLOAT,
+      enum_1.TokenKind.STRING,
+      enum_1.TokenKind.INT,
+      enum_1.TokenKind.BLOCK_STRING
+    ];
+    function getSourceFromLocation(loc, allowValues = false, inputStart, inputEnd) {
+      let source = "";
+      if (loc?.startToken) {
+        const start = typeof inputStart === "number" ? inputStart : loc.start;
+        const end = typeof inputEnd === "number" ? inputEnd : loc.end;
+        let next = loc.startToken.next;
+        let previousLine = 1;
+        while (next) {
+          if (next.start < start) {
+            next = next.next;
+            previousLine = next?.line;
+            continue;
+          }
+          if (next.end > end) {
+            next = next.next;
+            previousLine = next?.line;
+            continue;
+          }
+          let value = next.value || next.kind;
+          let space = "";
+          if (!allowValues && KindsToBeRemoved.indexOf(next.kind) >= 0) {
+            value = "*";
+          }
+          if (next.kind === enum_1.TokenKind.STRING) {
+            value = `"${value}"`;
+          }
+          if (next.kind === enum_1.TokenKind.EOF) {
+            value = "";
+          }
+          if (next.line > previousLine) {
+            source += repeatBreak(next.line - previousLine);
+            previousLine = next.line;
+            space = repeatSpace(next.column - 1);
+          } else {
+            if (next.line === next.prev?.line) {
+              space = repeatSpace(next.start - (next.prev?.end || 0));
+            }
+          }
+          source += space + value;
+          if (next) {
+            next = next.next;
+          }
+        }
+      }
+      return source;
+    }
+    exports$1.getSourceFromLocation = getSourceFromLocation;
+    function wrapFields(type, tracer, getConfig) {
+      if (!type || type[symbols_1.OTEL_PATCHED_SYMBOL]) {
+        return;
+      }
+      const fields = type.getFields();
+      type[symbols_1.OTEL_PATCHED_SYMBOL] = true;
+      Object.keys(fields).forEach((key) => {
+        const field = fields[key];
+        if (!field) {
+          return;
+        }
+        if (field.resolve) {
+          field.resolve = wrapFieldResolver(tracer, getConfig, field.resolve);
+        }
+        if (field.type) {
+          const unwrappedTypes = unwrapType(field.type);
+          for (const unwrappedType of unwrappedTypes) {
+            wrapFields(unwrappedType, tracer, getConfig);
+          }
+        }
+      });
+    }
+    exports$1.wrapFields = wrapFields;
+    function unwrapType(type) {
+      if ("ofType" in type) {
+        return unwrapType(type.ofType);
+      }
+      if (isGraphQLUnionType(type)) {
+        return type.getTypes();
+      }
+      if (isGraphQLObjectType(type)) {
+        return [type];
+      }
+      return [];
+    }
+    function isGraphQLUnionType(type) {
+      return "getTypes" in type && typeof type.getTypes === "function";
+    }
+    function isGraphQLObjectType(type) {
+      return "getFields" in type && typeof type.getFields === "function";
+    }
+    const handleResolveSpanError = (resolveSpan, err, shouldEndSpan) => {
+      if (!shouldEndSpan) {
+        return;
+      }
+      resolveSpan.recordException(err);
+      resolveSpan.setStatus({
+        code: api.SpanStatusCode.ERROR,
+        message: err.message
+      });
+      resolveSpan.end();
+    };
+    const handleResolveSpanSuccess = (resolveSpan, shouldEndSpan) => {
+      if (!shouldEndSpan) {
+        return;
+      }
+      resolveSpan.end();
+    };
+    function wrapFieldResolver(tracer, getConfig, fieldResolver, isDefaultResolver = false) {
+      if (wrappedFieldResolver[symbols_1.OTEL_PATCHED_SYMBOL] || typeof fieldResolver !== "function") {
+        return fieldResolver;
+      }
+      function wrappedFieldResolver(source, args, contextValue, info) {
+        if (!fieldResolver) {
+          return void 0;
+        }
+        const config2 = getConfig();
+        if (config2.ignoreTrivialResolveSpans && isDefaultResolver && (isObjectLike2(source) || typeof source === "function")) {
+          const property = source[info.fieldName];
+          if (typeof property !== "function") {
+            return fieldResolver.call(this, source, args, contextValue, info);
+          }
+        }
+        if (!contextValue[symbols_1.OTEL_GRAPHQL_DATA_SYMBOL]) {
+          return fieldResolver.call(this, source, args, contextValue, info);
+        }
+        const path2 = pathToArray(config2.mergeItems, info && info.path);
+        const depth = path2.filter((item) => typeof item === "string").length;
+        let span;
+        let shouldEndSpan = false;
+        if (config2.depth >= 0 && config2.depth < depth) {
+          span = getParentFieldSpan(contextValue, path2);
+        } else {
+          const { field, spanAdded } = createFieldIfNotExists(tracer, getConfig, contextValue, info, path2);
+          span = field.span;
+          shouldEndSpan = spanAdded;
+        }
+        return api.context.with(api.trace.setSpan(api.context.active(), span), () => {
+          try {
+            const res = fieldResolver.call(this, source, args, contextValue, info);
+            if ((0, exports$1.isPromise)(res)) {
+              return res.then((r) => {
+                handleResolveSpanSuccess(span, shouldEndSpan);
+                return r;
+              }, (err) => {
+                handleResolveSpanError(span, err, shouldEndSpan);
+                throw err;
+              });
+            } else {
+              handleResolveSpanSuccess(span, shouldEndSpan);
+              return res;
+            }
+          } catch (err) {
+            handleResolveSpanError(span, err, shouldEndSpan);
+            throw err;
+          }
+        });
+      }
+      wrappedFieldResolver[symbols_1.OTEL_PATCHED_SYMBOL] = true;
+      return wrappedFieldResolver;
+    }
+    exports$1.wrapFieldResolver = wrapFieldResolver;
+  })(utils$c);
+  return utils$c;
+}
+var version$f = {};
+var hasRequiredVersion$f;
+function requireVersion$f() {
+  if (hasRequiredVersion$f) return version$f;
+  hasRequiredVersion$f = 1;
+  Object.defineProperty(version$f, "__esModule", { value: true });
+  version$f.PACKAGE_NAME = version$f.PACKAGE_VERSION = void 0;
+  version$f.PACKAGE_VERSION = "0.56.0";
+  version$f.PACKAGE_NAME = "@opentelemetry/instrumentation-graphql";
+  return version$f;
+}
+var hasRequiredInstrumentation$e;
+function requireInstrumentation$e() {
+  if (hasRequiredInstrumentation$e) return instrumentation$e;
+  hasRequiredInstrumentation$e = 1;
+  Object.defineProperty(instrumentation$e, "__esModule", { value: true });
+  instrumentation$e.GraphQLInstrumentation = void 0;
+  const api_1 = /* @__PURE__ */ requireSrc$n();
+  const instrumentation_1 = require$$2;
+  const enum_1 = require_enum();
+  const AttributeNames_1 = requireAttributeNames$5();
+  const symbols_1 = requireSymbols();
+  const internal_types_1 = requireInternalTypes$6();
+  const utils_1 = requireUtils$c();
+  const version_1 = requireVersion$f();
+  const DEFAULT_CONFIG = {
+    mergeItems: false,
+    depth: -1,
+    allowValues: false,
+    ignoreResolveSpans: false
+  };
+  const supportedVersions2 = [">=14.0.0 <17"];
+  class GraphQLInstrumentation extends instrumentation_1.InstrumentationBase {
+    constructor(config2 = {}) {
+      super(version_1.PACKAGE_NAME, version_1.PACKAGE_VERSION, { ...DEFAULT_CONFIG, ...config2 });
+    }
+    setConfig(config2 = {}) {
+      super.setConfig({ ...DEFAULT_CONFIG, ...config2 });
+    }
+    init() {
+      const module2 = new instrumentation_1.InstrumentationNodeModuleDefinition("graphql", supportedVersions2);
+      module2.files.push(this._addPatchingExecute());
+      module2.files.push(this._addPatchingParser());
+      module2.files.push(this._addPatchingValidate());
+      return module2;
+    }
+    _addPatchingExecute() {
+      return new instrumentation_1.InstrumentationNodeModuleFile(
+        "graphql/execution/execute.js",
+        supportedVersions2,
+        // cannot make it work with appropriate type as execute function has 2
+        //types and/cannot import function but only types
+        (moduleExports) => {
+          if ((0, instrumentation_1.isWrapped)(moduleExports.execute)) {
+            this._unwrap(moduleExports, "execute");
+          }
+          this._wrap(moduleExports, "execute", this._patchExecute(moduleExports.defaultFieldResolver));
+          return moduleExports;
+        },
+        (moduleExports) => {
+          if (moduleExports) {
+            this._unwrap(moduleExports, "execute");
+          }
+        }
+      );
+    }
+    _addPatchingParser() {
+      return new instrumentation_1.InstrumentationNodeModuleFile("graphql/language/parser.js", supportedVersions2, (moduleExports) => {
+        if ((0, instrumentation_1.isWrapped)(moduleExports.parse)) {
+          this._unwrap(moduleExports, "parse");
+        }
+        this._wrap(moduleExports, "parse", this._patchParse());
+        return moduleExports;
+      }, (moduleExports) => {
+        if (moduleExports) {
+          this._unwrap(moduleExports, "parse");
+        }
+      });
+    }
+    _addPatchingValidate() {
+      return new instrumentation_1.InstrumentationNodeModuleFile("graphql/validation/validate.js", supportedVersions2, (moduleExports) => {
+        if ((0, instrumentation_1.isWrapped)(moduleExports.validate)) {
+          this._unwrap(moduleExports, "validate");
+        }
+        this._wrap(moduleExports, "validate", this._patchValidate());
+        return moduleExports;
+      }, (moduleExports) => {
+        if (moduleExports) {
+          this._unwrap(moduleExports, "validate");
+        }
+      });
+    }
+    _patchExecute(defaultFieldResolved) {
+      const instrumentation2 = this;
+      return function execute(original) {
+        return function patchExecute() {
+          let processedArgs;
+          if (arguments.length >= 2) {
+            const args = arguments;
+            processedArgs = instrumentation2._wrapExecuteArgs(args[0], args[1], args[2], args[3], args[4], args[5], args[6], args[7], defaultFieldResolved);
+          } else {
+            const args = arguments[0];
+            processedArgs = instrumentation2._wrapExecuteArgs(args.schema, args.document, args.rootValue, args.contextValue, args.variableValues, args.operationName, args.fieldResolver, args.typeResolver, defaultFieldResolved);
+          }
+          const operation = (0, utils_1.getOperation)(processedArgs.document, processedArgs.operationName);
+          const span = instrumentation2._createExecuteSpan(operation, processedArgs);
+          processedArgs.contextValue[symbols_1.OTEL_GRAPHQL_DATA_SYMBOL] = {
+            source: processedArgs.document ? processedArgs.document || processedArgs.document[symbols_1.OTEL_GRAPHQL_DATA_SYMBOL] : void 0,
+            span,
+            fields: {}
+          };
+          return api_1.context.with(api_1.trace.setSpan(api_1.context.active(), span), () => {
+            return (0, instrumentation_1.safeExecuteInTheMiddle)(() => {
+              return original.apply(this, [
+                processedArgs
+              ]);
+            }, (err, result) => {
+              instrumentation2._handleExecutionResult(span, err, result);
+            });
+          });
+        };
+      };
+    }
+    _handleExecutionResult(span, err, result) {
+      const config2 = this.getConfig();
+      if (result === void 0 || err) {
+        (0, utils_1.endSpan)(span, err);
+        return;
+      }
+      if ((0, utils_1.isPromise)(result)) {
+        result.then((resultData) => {
+          if (typeof config2.responseHook !== "function") {
+            (0, utils_1.endSpan)(span);
+            return;
+          }
+          this._executeResponseHook(span, resultData);
+        }, (error2) => {
+          (0, utils_1.endSpan)(span, error2);
+        });
+      } else {
+        if (typeof config2.responseHook !== "function") {
+          (0, utils_1.endSpan)(span);
+          return;
+        }
+        this._executeResponseHook(span, result);
+      }
+    }
+    _executeResponseHook(span, result) {
+      const { responseHook } = this.getConfig();
+      if (!responseHook) {
+        return;
+      }
+      (0, instrumentation_1.safeExecuteInTheMiddle)(() => {
+        responseHook(span, result);
+      }, (err) => {
+        if (err) {
+          this._diag.error("Error running response hook", err);
+        }
+        (0, utils_1.endSpan)(span, void 0);
+      }, true);
+    }
+    _patchParse() {
+      const instrumentation2 = this;
+      return function parse(original) {
+        return function patchParse(source, options) {
+          return instrumentation2._parse(this, original, source, options);
+        };
+      };
+    }
+    _patchValidate() {
+      const instrumentation2 = this;
+      return function validate(original) {
+        return function patchValidate(schema, documentAST, rules, options, typeInfo) {
+          return instrumentation2._validate(this, original, schema, documentAST, rules, typeInfo, options);
+        };
+      };
+    }
+    _parse(obj, original, source, options) {
+      const config2 = this.getConfig();
+      const span = this.tracer.startSpan(enum_1.SpanNames.PARSE);
+      return api_1.context.with(api_1.trace.setSpan(api_1.context.active(), span), () => {
+        return (0, instrumentation_1.safeExecuteInTheMiddle)(() => {
+          return original.call(obj, source, options);
+        }, (err, result) => {
+          if (result) {
+            const operation = (0, utils_1.getOperation)(result);
+            if (!operation) {
+              span.updateName(enum_1.SpanNames.SCHEMA_PARSE);
+            } else if (result.loc) {
+              (0, utils_1.addSpanSource)(span, result.loc, config2.allowValues);
+            }
+          }
+          (0, utils_1.endSpan)(span, err);
+        });
+      });
+    }
+    _validate(obj, original, schema, documentAST, rules, typeInfo, options) {
+      const span = this.tracer.startSpan(enum_1.SpanNames.VALIDATE, {});
+      return api_1.context.with(api_1.trace.setSpan(api_1.context.active(), span), () => {
+        return (0, instrumentation_1.safeExecuteInTheMiddle)(() => {
+          return original.call(obj, schema, documentAST, rules, options, typeInfo);
+        }, (err, errors) => {
+          if (!documentAST.loc) {
+            span.updateName(enum_1.SpanNames.SCHEMA_VALIDATE);
+          }
+          if (errors && errors.length) {
+            span.recordException({
+              name: AttributeNames_1.AttributeNames.ERROR_VALIDATION_NAME,
+              message: JSON.stringify(errors)
+            });
+          }
+          (0, utils_1.endSpan)(span, err);
+        });
+      });
+    }
+    _createExecuteSpan(operation, processedArgs) {
+      const config2 = this.getConfig();
+      const span = this.tracer.startSpan(enum_1.SpanNames.EXECUTE, {});
+      if (operation) {
+        const { operation: operationType, name: nameNode } = operation;
+        span.setAttribute(AttributeNames_1.AttributeNames.OPERATION_TYPE, operationType);
+        const operationName = nameNode?.value;
+        if (operationName) {
+          span.setAttribute(AttributeNames_1.AttributeNames.OPERATION_NAME, operationName);
+          span.updateName(`${operationType} ${operationName}`);
+        } else {
+          span.updateName(operationType);
+        }
+      } else {
+        let operationName = " ";
+        if (processedArgs.operationName) {
+          operationName = ` "${processedArgs.operationName}" `;
+        }
+        operationName = internal_types_1.OPERATION_NOT_SUPPORTED.replace("$operationName$", operationName);
+        span.setAttribute(AttributeNames_1.AttributeNames.OPERATION_NAME, operationName);
+      }
+      if (processedArgs.document?.loc) {
+        (0, utils_1.addSpanSource)(span, processedArgs.document.loc, config2.allowValues);
+      }
+      if (processedArgs.variableValues && config2.allowValues) {
+        (0, utils_1.addInputVariableAttributes)(span, processedArgs.variableValues);
+      }
+      return span;
+    }
+    _wrapExecuteArgs(schema, document2, rootValue, contextValue, variableValues, operationName, fieldResolver, typeResolver, defaultFieldResolved) {
+      if (!contextValue) {
+        contextValue = {};
+      }
+      if (contextValue[symbols_1.OTEL_GRAPHQL_DATA_SYMBOL] || this.getConfig().ignoreResolveSpans) {
+        return {
+          schema,
+          document: document2,
+          rootValue,
+          contextValue,
+          variableValues,
+          operationName,
+          fieldResolver,
+          typeResolver
+        };
+      }
+      const isUsingDefaultResolver = fieldResolver == null;
+      const fieldResolverForExecute = fieldResolver ?? defaultFieldResolved;
+      fieldResolver = (0, utils_1.wrapFieldResolver)(this.tracer, () => this.getConfig(), fieldResolverForExecute, isUsingDefaultResolver);
+      if (schema) {
+        (0, utils_1.wrapFields)(schema.getQueryType(), this.tracer, () => this.getConfig());
+        (0, utils_1.wrapFields)(schema.getMutationType(), this.tracer, () => this.getConfig());
+      }
+      return {
+        schema,
+        document: document2,
+        rootValue,
+        contextValue,
+        variableValues,
+        operationName,
+        fieldResolver,
+        typeResolver
+      };
+    }
+  }
+  instrumentation$e.GraphQLInstrumentation = GraphQLInstrumentation;
+  return instrumentation$e;
+}
+var hasRequiredSrc$h;
+function requireSrc$h() {
+  if (hasRequiredSrc$h) return src$h;
+  hasRequiredSrc$h = 1;
+  (function(exports$1) {
+    Object.defineProperty(exports$1, "__esModule", { value: true });
+    exports$1.GraphQLInstrumentation = void 0;
+    var instrumentation_1 = requireInstrumentation$e();
+    Object.defineProperty(exports$1, "GraphQLInstrumentation", { enumerable: true, get: function() {
+      return instrumentation_1.GraphQLInstrumentation;
+    } });
+  })(src$h);
+  return src$h;
+}
+var srcExports$f = requireSrc$h();
+const INTEGRATION_NAME$j = "Graphql";
+const instrumentGraphql = generateInstrumentOnce(
+  INTEGRATION_NAME$j,
+  srcExports$f.GraphQLInstrumentation,
+  (_options) => {
+    const options = getOptionsWithDefaults(_options);
+    return {
+      ...options,
+      responseHook(span, result) {
+        addOriginToSpan(span, "auto.graphql.otel.graphql");
+        const resultWithMaybeError = result;
+        if (resultWithMaybeError.errors?.length && !spanToJSON(span).status) {
+          span.setStatus({ code: srcExports$l.SpanStatusCode.ERROR });
+        }
+        const attributes = spanToJSON(span).data;
+        const operationType = attributes["graphql.operation.type"];
+        const operationName = attributes["graphql.operation.name"];
+        if (options.useOperationNameForRootSpan && operationType) {
+          const rootSpan = getRootSpan(span);
+          const rootSpanAttributes = spanToJSON(rootSpan).data;
+          const existingOperations = rootSpanAttributes[SEMANTIC_ATTRIBUTE_SENTRY_GRAPHQL_OPERATION] || [];
+          const newOperation = operationName ? `${operationType} ${operationName}` : `${operationType}`;
+          if (Array.isArray(existingOperations)) {
+            existingOperations.push(newOperation);
+            rootSpan.setAttribute(SEMANTIC_ATTRIBUTE_SENTRY_GRAPHQL_OPERATION, existingOperations);
+          } else if (typeof existingOperations === "string") {
+            rootSpan.setAttribute(SEMANTIC_ATTRIBUTE_SENTRY_GRAPHQL_OPERATION, [existingOperations, newOperation]);
+          } else {
+            rootSpan.setAttribute(SEMANTIC_ATTRIBUTE_SENTRY_GRAPHQL_OPERATION, newOperation);
+          }
+          if (!spanToJSON(rootSpan).data["original-description"]) {
+            rootSpan.setAttribute("original-description", spanToJSON(rootSpan).description);
+          }
+          rootSpan.updateName(
+            `${spanToJSON(rootSpan).data["original-description"]} (${getGraphqlOperationNamesFromAttribute(
+              existingOperations
+            )})`
+          );
+        }
+      }
+    };
+  }
+);
+const _graphqlIntegration = ((options = {}) => {
+  return {
+    name: INTEGRATION_NAME$j,
+    setupOnce() {
+      instrumentGraphql(getOptionsWithDefaults(options));
+    }
+  };
+});
+const graphqlIntegration = defineIntegration(_graphqlIntegration);
+function getOptionsWithDefaults(options) {
+  return {
+    ignoreResolveSpans: true,
+    ignoreTrivialResolveSpans: true,
+    useOperationNameForRootSpan: true,
+    ...options
+  };
+}
+function getGraphqlOperationNamesFromAttribute(attr) {
+  if (Array.isArray(attr)) {
+    const sorted = attr.slice().sort();
+    if (sorted.length <= 5) {
+      return sorted.join(", ");
+    } else {
+      return `${sorted.slice(0, 5).join(", ")}, +${sorted.length - 5}`;
+    }
+  }
+  return `${attr}`;
+}
+var src$g = {};
+var instrumentation$d = {};
+var internalTypes$5 = {};
+var hasRequiredInternalTypes$5;
+function requireInternalTypes$5() {
+  if (hasRequiredInternalTypes$5) return internalTypes$5;
+  hasRequiredInternalTypes$5 = 1;
+  Object.defineProperty(internalTypes$5, "__esModule", { value: true });
+  internalTypes$5.EVENT_LISTENERS_SET = void 0;
+  internalTypes$5.EVENT_LISTENERS_SET = Symbol("opentelemetry.instrumentation.kafkajs.eventListenersSet");
+  return internalTypes$5;
+}
+var propagator = {};
+var hasRequiredPropagator;
+function requirePropagator() {
+  if (hasRequiredPropagator) return propagator;
+  hasRequiredPropagator = 1;
+  Object.defineProperty(propagator, "__esModule", { value: true });
+  propagator.bufferTextMapGetter = void 0;
+  propagator.bufferTextMapGetter = {
+    get(carrier, key) {
+      if (!carrier) {
+        return void 0;
+      }
+      const keys = Object.keys(carrier);
+      for (const carrierKey of keys) {
+        if (carrierKey === key || carrierKey.toLowerCase() === key) {
+          return carrier[carrierKey]?.toString();
+        }
+      }
+      return void 0;
+    },
+    keys(carrier) {
+      return carrier ? Object.keys(carrier) : [];
+    }
+  };
+  return propagator;
+}
+var semconv$a = {};
+var hasRequiredSemconv$a;
+function requireSemconv$a() {
+  if (hasRequiredSemconv$a) return semconv$a;
+  hasRequiredSemconv$a = 1;
+  Object.defineProperty(semconv$a, "__esModule", { value: true });
+  semconv$a.METRIC_MESSAGING_PROCESS_DURATION = semconv$a.METRIC_MESSAGING_CLIENT_SENT_MESSAGES = semconv$a.METRIC_MESSAGING_CLIENT_OPERATION_DURATION = semconv$a.METRIC_MESSAGING_CLIENT_CONSUMED_MESSAGES = semconv$a.MESSAGING_SYSTEM_VALUE_KAFKA = semconv$a.MESSAGING_OPERATION_TYPE_VALUE_SEND = semconv$a.MESSAGING_OPERATION_TYPE_VALUE_RECEIVE = semconv$a.MESSAGING_OPERATION_TYPE_VALUE_PROCESS = semconv$a.ATTR_MESSAGING_SYSTEM = semconv$a.ATTR_MESSAGING_OPERATION_TYPE = semconv$a.ATTR_MESSAGING_OPERATION_NAME = semconv$a.ATTR_MESSAGING_KAFKA_OFFSET = semconv$a.ATTR_MESSAGING_KAFKA_MESSAGE_TOMBSTONE = semconv$a.ATTR_MESSAGING_KAFKA_MESSAGE_KEY = semconv$a.ATTR_MESSAGING_DESTINATION_PARTITION_ID = semconv$a.ATTR_MESSAGING_DESTINATION_NAME = semconv$a.ATTR_MESSAGING_BATCH_MESSAGE_COUNT = void 0;
+  semconv$a.ATTR_MESSAGING_BATCH_MESSAGE_COUNT = "messaging.batch.message_count";
+  semconv$a.ATTR_MESSAGING_DESTINATION_NAME = "messaging.destination.name";
+  semconv$a.ATTR_MESSAGING_DESTINATION_PARTITION_ID = "messaging.destination.partition.id";
+  semconv$a.ATTR_MESSAGING_KAFKA_MESSAGE_KEY = "messaging.kafka.message.key";
+  semconv$a.ATTR_MESSAGING_KAFKA_MESSAGE_TOMBSTONE = "messaging.kafka.message.tombstone";
+  semconv$a.ATTR_MESSAGING_KAFKA_OFFSET = "messaging.kafka.offset";
+  semconv$a.ATTR_MESSAGING_OPERATION_NAME = "messaging.operation.name";
+  semconv$a.ATTR_MESSAGING_OPERATION_TYPE = "messaging.operation.type";
+  semconv$a.ATTR_MESSAGING_SYSTEM = "messaging.system";
+  semconv$a.MESSAGING_OPERATION_TYPE_VALUE_PROCESS = "process";
+  semconv$a.MESSAGING_OPERATION_TYPE_VALUE_RECEIVE = "receive";
+  semconv$a.MESSAGING_OPERATION_TYPE_VALUE_SEND = "send";
+  semconv$a.MESSAGING_SYSTEM_VALUE_KAFKA = "kafka";
+  semconv$a.METRIC_MESSAGING_CLIENT_CONSUMED_MESSAGES = "messaging.client.consumed.messages";
+  semconv$a.METRIC_MESSAGING_CLIENT_OPERATION_DURATION = "messaging.client.operation.duration";
+  semconv$a.METRIC_MESSAGING_CLIENT_SENT_MESSAGES = "messaging.client.sent.messages";
+  semconv$a.METRIC_MESSAGING_PROCESS_DURATION = "messaging.process.duration";
+  return semconv$a;
+}
+var version$e = {};
+var hasRequiredVersion$e;
+function requireVersion$e() {
+  if (hasRequiredVersion$e) return version$e;
+  hasRequiredVersion$e = 1;
+  Object.defineProperty(version$e, "__esModule", { value: true });
+  version$e.PACKAGE_NAME = version$e.PACKAGE_VERSION = void 0;
+  version$e.PACKAGE_VERSION = "0.18.0";
+  version$e.PACKAGE_NAME = "@opentelemetry/instrumentation-kafkajs";
+  return version$e;
+}
+var hasRequiredInstrumentation$d;
+function requireInstrumentation$d() {
+  if (hasRequiredInstrumentation$d) return instrumentation$d;
+  hasRequiredInstrumentation$d = 1;
+  Object.defineProperty(instrumentation$d, "__esModule", { value: true });
+  instrumentation$d.KafkaJsInstrumentation = void 0;
+  const api_1 = /* @__PURE__ */ requireSrc$n();
+  const instrumentation_1 = require$$2;
+  const semantic_conventions_1 = /* @__PURE__ */ requireSrc$m();
+  const internal_types_1 = requireInternalTypes$5();
+  const propagator_1 = requirePropagator();
+  const semconv_1 = requireSemconv$a();
+  const version_1 = requireVersion$e();
+  function prepareCounter(meter, value, attributes) {
+    return (errorType) => {
+      meter.add(value, {
+        ...attributes,
+        ...errorType ? { [semantic_conventions_1.ATTR_ERROR_TYPE]: errorType } : {}
+      });
+    };
+  }
+  function prepareDurationHistogram(meter, value, attributes) {
+    return (errorType) => {
+      meter.record((Date.now() - value) / 1e3, {
+        ...attributes,
+        ...errorType ? { [semantic_conventions_1.ATTR_ERROR_TYPE]: errorType } : {}
+      });
+    };
+  }
+  const HISTOGRAM_BUCKET_BOUNDARIES = [
+    5e-3,
+    0.01,
+    0.025,
+    0.05,
+    0.075,
+    0.1,
+    0.25,
+    0.5,
+    0.75,
+    1,
+    2.5,
+    5,
+    7.5,
+    10
+  ];
+  class KafkaJsInstrumentation extends instrumentation_1.InstrumentationBase {
+    constructor(config2 = {}) {
+      super(version_1.PACKAGE_NAME, version_1.PACKAGE_VERSION, config2);
+    }
+    _updateMetricInstruments() {
+      this._clientDuration = this.meter.createHistogram(semconv_1.METRIC_MESSAGING_CLIENT_OPERATION_DURATION, { advice: { explicitBucketBoundaries: HISTOGRAM_BUCKET_BOUNDARIES } });
+      this._sentMessages = this.meter.createCounter(semconv_1.METRIC_MESSAGING_CLIENT_SENT_MESSAGES);
+      this._consumedMessages = this.meter.createCounter(semconv_1.METRIC_MESSAGING_CLIENT_CONSUMED_MESSAGES);
+      this._processDuration = this.meter.createHistogram(semconv_1.METRIC_MESSAGING_PROCESS_DURATION, { advice: { explicitBucketBoundaries: HISTOGRAM_BUCKET_BOUNDARIES } });
+    }
+    init() {
+      const unpatch = (moduleExports) => {
+        if ((0, instrumentation_1.isWrapped)(moduleExports?.Kafka?.prototype.producer)) {
+          this._unwrap(moduleExports.Kafka.prototype, "producer");
+        }
+        if ((0, instrumentation_1.isWrapped)(moduleExports?.Kafka?.prototype.consumer)) {
+          this._unwrap(moduleExports.Kafka.prototype, "consumer");
+        }
+      };
+      const module2 = new instrumentation_1.InstrumentationNodeModuleDefinition("kafkajs", [">=0.3.0 <3"], (moduleExports) => {
+        unpatch(moduleExports);
+        this._wrap(moduleExports?.Kafka?.prototype, "producer", this._getProducerPatch());
+        this._wrap(moduleExports?.Kafka?.prototype, "consumer", this._getConsumerPatch());
+        return moduleExports;
+      }, unpatch);
+      return module2;
+    }
+    _getConsumerPatch() {
+      const instrumentation2 = this;
+      return (original) => {
+        return function consumer(...args) {
+          const newConsumer = original.apply(this, args);
+          if ((0, instrumentation_1.isWrapped)(newConsumer.run)) {
+            instrumentation2._unwrap(newConsumer, "run");
+          }
+          instrumentation2._wrap(newConsumer, "run", instrumentation2._getConsumerRunPatch());
+          instrumentation2._setKafkaEventListeners(newConsumer);
+          return newConsumer;
+        };
+      };
+    }
+    _setKafkaEventListeners(kafkaObj) {
+      if (kafkaObj[internal_types_1.EVENT_LISTENERS_SET])
+        return;
+      if (kafkaObj.events?.REQUEST) {
+        kafkaObj.on(kafkaObj.events.REQUEST, this._recordClientDurationMetric.bind(this));
+      }
+      kafkaObj[internal_types_1.EVENT_LISTENERS_SET] = true;
+    }
+    _recordClientDurationMetric(event) {
+      const [address, port] = event.payload.broker.split(":");
+      this._clientDuration.record(event.payload.duration / 1e3, {
+        [semconv_1.ATTR_MESSAGING_SYSTEM]: semconv_1.MESSAGING_SYSTEM_VALUE_KAFKA,
+        [semconv_1.ATTR_MESSAGING_OPERATION_NAME]: `${event.payload.apiName}`,
+        [semantic_conventions_1.ATTR_SERVER_ADDRESS]: address,
+        [semantic_conventions_1.ATTR_SERVER_PORT]: Number.parseInt(port, 10)
+      });
+    }
+    _getProducerPatch() {
+      const instrumentation2 = this;
+      return (original) => {
+        return function consumer(...args) {
+          const newProducer = original.apply(this, args);
+          if ((0, instrumentation_1.isWrapped)(newProducer.sendBatch)) {
+            instrumentation2._unwrap(newProducer, "sendBatch");
+          }
+          instrumentation2._wrap(newProducer, "sendBatch", instrumentation2._getSendBatchPatch());
+          if ((0, instrumentation_1.isWrapped)(newProducer.send)) {
+            instrumentation2._unwrap(newProducer, "send");
+          }
+          instrumentation2._wrap(newProducer, "send", instrumentation2._getSendPatch());
+          if ((0, instrumentation_1.isWrapped)(newProducer.transaction)) {
+            instrumentation2._unwrap(newProducer, "transaction");
+          }
+          instrumentation2._wrap(newProducer, "transaction", instrumentation2._getProducerTransactionPatch());
+          instrumentation2._setKafkaEventListeners(newProducer);
+          return newProducer;
+        };
+      };
+    }
+    _getConsumerRunPatch() {
+      const instrumentation2 = this;
+      return (original) => {
+        return function run(...args) {
+          const config2 = args[0];
+          if (config2?.eachMessage) {
+            if ((0, instrumentation_1.isWrapped)(config2.eachMessage)) {
+              instrumentation2._unwrap(config2, "eachMessage");
+            }
+            instrumentation2._wrap(config2, "eachMessage", instrumentation2._getConsumerEachMessagePatch());
+          }
+          if (config2?.eachBatch) {
+            if ((0, instrumentation_1.isWrapped)(config2.eachBatch)) {
+              instrumentation2._unwrap(config2, "eachBatch");
+            }
+            instrumentation2._wrap(config2, "eachBatch", instrumentation2._getConsumerEachBatchPatch());
+          }
+          return original.call(this, config2);
+        };
+      };
+    }
+    _getConsumerEachMessagePatch() {
+      const instrumentation2 = this;
+      return (original) => {
+        return function eachMessage(...args) {
+          const payload = args[0];
+          const propagatedContext = api_1.propagation.extract(api_1.ROOT_CONTEXT, payload.message.headers, propagator_1.bufferTextMapGetter);
+          const span = instrumentation2._startConsumerSpan({
+            topic: payload.topic,
+            message: payload.message,
+            operationType: semconv_1.MESSAGING_OPERATION_TYPE_VALUE_PROCESS,
+            ctx: propagatedContext,
+            attributes: {
+              [semconv_1.ATTR_MESSAGING_DESTINATION_PARTITION_ID]: String(payload.partition)
+            }
+          });
+          const pendingMetrics = [
+            prepareDurationHistogram(instrumentation2._processDuration, Date.now(), {
+              [semconv_1.ATTR_MESSAGING_SYSTEM]: semconv_1.MESSAGING_SYSTEM_VALUE_KAFKA,
+              [semconv_1.ATTR_MESSAGING_OPERATION_NAME]: "process",
+              [semconv_1.ATTR_MESSAGING_DESTINATION_NAME]: payload.topic,
+              [semconv_1.ATTR_MESSAGING_DESTINATION_PARTITION_ID]: String(payload.partition)
+            }),
+            prepareCounter(instrumentation2._consumedMessages, 1, {
+              [semconv_1.ATTR_MESSAGING_SYSTEM]: semconv_1.MESSAGING_SYSTEM_VALUE_KAFKA,
+              [semconv_1.ATTR_MESSAGING_OPERATION_NAME]: "process",
+              [semconv_1.ATTR_MESSAGING_DESTINATION_NAME]: payload.topic,
+              [semconv_1.ATTR_MESSAGING_DESTINATION_PARTITION_ID]: String(payload.partition)
+            })
+          ];
+          const eachMessagePromise = api_1.context.with(api_1.trace.setSpan(propagatedContext, span), () => {
+            return original.apply(this, args);
+          });
+          return instrumentation2._endSpansOnPromise([span], pendingMetrics, eachMessagePromise);
+        };
+      };
+    }
+    _getConsumerEachBatchPatch() {
+      return (original) => {
+        const instrumentation2 = this;
+        return function eachBatch(...args) {
+          const payload = args[0];
+          const receivingSpan = instrumentation2._startConsumerSpan({
+            topic: payload.batch.topic,
+            message: void 0,
+            operationType: semconv_1.MESSAGING_OPERATION_TYPE_VALUE_RECEIVE,
+            ctx: api_1.ROOT_CONTEXT,
+            attributes: {
+              [semconv_1.ATTR_MESSAGING_BATCH_MESSAGE_COUNT]: payload.batch.messages.length,
+              [semconv_1.ATTR_MESSAGING_DESTINATION_PARTITION_ID]: String(payload.batch.partition)
+            }
+          });
+          return api_1.context.with(api_1.trace.setSpan(api_1.context.active(), receivingSpan), () => {
+            const startTime = Date.now();
+            const spans = [];
+            const pendingMetrics = [
+              prepareCounter(instrumentation2._consumedMessages, payload.batch.messages.length, {
+                [semconv_1.ATTR_MESSAGING_SYSTEM]: semconv_1.MESSAGING_SYSTEM_VALUE_KAFKA,
+                [semconv_1.ATTR_MESSAGING_OPERATION_NAME]: "process",
+                [semconv_1.ATTR_MESSAGING_DESTINATION_NAME]: payload.batch.topic,
+                [semconv_1.ATTR_MESSAGING_DESTINATION_PARTITION_ID]: String(payload.batch.partition)
+              })
+            ];
+            payload.batch.messages.forEach((message) => {
+              const propagatedContext = api_1.propagation.extract(api_1.ROOT_CONTEXT, message.headers, propagator_1.bufferTextMapGetter);
+              const spanContext = api_1.trace.getSpan(propagatedContext)?.spanContext();
+              let origSpanLink;
+              if (spanContext) {
+                origSpanLink = {
+                  context: spanContext
+                };
+              }
+              spans.push(instrumentation2._startConsumerSpan({
+                topic: payload.batch.topic,
+                message,
+                operationType: semconv_1.MESSAGING_OPERATION_TYPE_VALUE_PROCESS,
+                link: origSpanLink,
+                attributes: {
+                  [semconv_1.ATTR_MESSAGING_DESTINATION_PARTITION_ID]: String(payload.batch.partition)
+                }
+              }));
+              pendingMetrics.push(prepareDurationHistogram(instrumentation2._processDuration, startTime, {
+                [semconv_1.ATTR_MESSAGING_SYSTEM]: semconv_1.MESSAGING_SYSTEM_VALUE_KAFKA,
+                [semconv_1.ATTR_MESSAGING_OPERATION_NAME]: "process",
+                [semconv_1.ATTR_MESSAGING_DESTINATION_NAME]: payload.batch.topic,
+                [semconv_1.ATTR_MESSAGING_DESTINATION_PARTITION_ID]: String(payload.batch.partition)
+              }));
+            });
+            const batchMessagePromise = original.apply(this, args);
+            spans.unshift(receivingSpan);
+            return instrumentation2._endSpansOnPromise(spans, pendingMetrics, batchMessagePromise);
+          });
+        };
+      };
+    }
+    _getProducerTransactionPatch() {
+      const instrumentation2 = this;
+      return (original) => {
+        return function transaction(...args) {
+          const transactionSpan = instrumentation2.tracer.startSpan("transaction");
+          const transactionPromise = original.apply(this, args);
+          transactionPromise.then((transaction2) => {
+            const originalSend = transaction2.send;
+            transaction2.send = function send(...args2) {
+              return api_1.context.with(api_1.trace.setSpan(api_1.context.active(), transactionSpan), () => {
+                const patched = instrumentation2._getSendPatch()(originalSend);
+                return patched.apply(this, args2).catch((err) => {
+                  transactionSpan.setStatus({
+                    code: api_1.SpanStatusCode.ERROR,
+                    message: err?.message
+                  });
+                  transactionSpan.recordException(err);
+                  throw err;
+                });
+              });
+            };
+            const originalSendBatch = transaction2.sendBatch;
+            transaction2.sendBatch = function sendBatch(...args2) {
+              return api_1.context.with(api_1.trace.setSpan(api_1.context.active(), transactionSpan), () => {
+                const patched = instrumentation2._getSendBatchPatch()(originalSendBatch);
+                return patched.apply(this, args2).catch((err) => {
+                  transactionSpan.setStatus({
+                    code: api_1.SpanStatusCode.ERROR,
+                    message: err?.message
+                  });
+                  transactionSpan.recordException(err);
+                  throw err;
+                });
+              });
+            };
+            const originalCommit = transaction2.commit;
+            transaction2.commit = function commit(...args2) {
+              const originCommitPromise = originalCommit.apply(this, args2).then(() => {
+                transactionSpan.setStatus({ code: api_1.SpanStatusCode.OK });
+              });
+              return instrumentation2._endSpansOnPromise([transactionSpan], [], originCommitPromise);
+            };
+            const originalAbort = transaction2.abort;
+            transaction2.abort = function abort(...args2) {
+              const originAbortPromise = originalAbort.apply(this, args2);
+              return instrumentation2._endSpansOnPromise([transactionSpan], [], originAbortPromise);
+            };
+          }).catch((err) => {
+            transactionSpan.setStatus({
+              code: api_1.SpanStatusCode.ERROR,
+              message: err?.message
+            });
+            transactionSpan.recordException(err);
+            transactionSpan.end();
+          });
+          return transactionPromise;
+        };
+      };
+    }
+    _getSendBatchPatch() {
+      const instrumentation2 = this;
+      return (original) => {
+        return function sendBatch(...args) {
+          const batch = args[0];
+          const messages = batch.topicMessages || [];
+          const spans = [];
+          const pendingMetrics = [];
+          messages.forEach((topicMessage) => {
+            topicMessage.messages.forEach((message) => {
+              spans.push(instrumentation2._startProducerSpan(topicMessage.topic, message));
+              pendingMetrics.push(prepareCounter(instrumentation2._sentMessages, 1, {
+                [semconv_1.ATTR_MESSAGING_SYSTEM]: semconv_1.MESSAGING_SYSTEM_VALUE_KAFKA,
+                [semconv_1.ATTR_MESSAGING_OPERATION_NAME]: "send",
+                [semconv_1.ATTR_MESSAGING_DESTINATION_NAME]: topicMessage.topic,
+                ...message.partition !== void 0 ? {
+                  [semconv_1.ATTR_MESSAGING_DESTINATION_PARTITION_ID]: String(message.partition)
+                } : {}
+              }));
+            });
+          });
+          const origSendResult = original.apply(this, args);
+          return instrumentation2._endSpansOnPromise(spans, pendingMetrics, origSendResult);
+        };
+      };
+    }
+    _getSendPatch() {
+      const instrumentation2 = this;
+      return (original) => {
+        return function send(...args) {
+          const record = args[0];
+          const spans = record.messages.map((message) => {
+            return instrumentation2._startProducerSpan(record.topic, message);
+          });
+          const pendingMetrics = record.messages.map((m) => prepareCounter(instrumentation2._sentMessages, 1, {
+            [semconv_1.ATTR_MESSAGING_SYSTEM]: semconv_1.MESSAGING_SYSTEM_VALUE_KAFKA,
+            [semconv_1.ATTR_MESSAGING_OPERATION_NAME]: "send",
+            [semconv_1.ATTR_MESSAGING_DESTINATION_NAME]: record.topic,
+            ...m.partition !== void 0 ? {
+              [semconv_1.ATTR_MESSAGING_DESTINATION_PARTITION_ID]: String(m.partition)
+            } : {}
+          }));
+          const origSendResult = original.apply(this, args);
+          return instrumentation2._endSpansOnPromise(spans, pendingMetrics, origSendResult);
+        };
+      };
+    }
+    _endSpansOnPromise(spans, pendingMetrics, sendPromise) {
+      return Promise.resolve(sendPromise).then((result) => {
+        pendingMetrics.forEach((m) => m());
+        return result;
+      }).catch((reason) => {
+        let errorMessage;
+        let errorType = semantic_conventions_1.ERROR_TYPE_VALUE_OTHER;
+        if (typeof reason === "string" || reason === void 0) {
+          errorMessage = reason;
+        } else if (typeof reason === "object" && Object.prototype.hasOwnProperty.call(reason, "message")) {
+          errorMessage = reason.message;
+          errorType = reason.constructor.name;
+        }
+        pendingMetrics.forEach((m) => m(errorType));
+        spans.forEach((span) => {
+          span.setAttribute(semantic_conventions_1.ATTR_ERROR_TYPE, errorType);
+          span.setStatus({
+            code: api_1.SpanStatusCode.ERROR,
+            message: errorMessage
+          });
+        });
+        throw reason;
+      }).finally(() => {
+        spans.forEach((span) => span.end());
+      });
+    }
+    _startConsumerSpan({ topic, message, operationType, ctx, link, attributes }) {
+      const operationName = operationType === semconv_1.MESSAGING_OPERATION_TYPE_VALUE_RECEIVE ? "poll" : operationType;
+      const span = this.tracer.startSpan(`${operationName} ${topic}`, {
+        kind: operationType === semconv_1.MESSAGING_OPERATION_TYPE_VALUE_RECEIVE ? api_1.SpanKind.CLIENT : api_1.SpanKind.CONSUMER,
+        attributes: {
+          ...attributes,
+          [semconv_1.ATTR_MESSAGING_SYSTEM]: semconv_1.MESSAGING_SYSTEM_VALUE_KAFKA,
+          [semconv_1.ATTR_MESSAGING_DESTINATION_NAME]: topic,
+          [semconv_1.ATTR_MESSAGING_OPERATION_TYPE]: operationType,
+          [semconv_1.ATTR_MESSAGING_OPERATION_NAME]: operationName,
+          [semconv_1.ATTR_MESSAGING_KAFKA_MESSAGE_KEY]: message?.key ? String(message.key) : void 0,
+          [semconv_1.ATTR_MESSAGING_KAFKA_MESSAGE_TOMBSTONE]: message?.key && message.value === null ? true : void 0,
+          [semconv_1.ATTR_MESSAGING_KAFKA_OFFSET]: message?.offset
+        },
+        links: link ? [link] : []
+      }, ctx);
+      const { consumerHook } = this.getConfig();
+      if (consumerHook && message) {
+        (0, instrumentation_1.safeExecuteInTheMiddle)(() => consumerHook(span, { topic, message }), (e) => {
+          if (e)
+            this._diag.error("consumerHook error", e);
+        }, true);
+      }
+      return span;
+    }
+    _startProducerSpan(topic, message) {
+      const span = this.tracer.startSpan(`send ${topic}`, {
+        kind: api_1.SpanKind.PRODUCER,
+        attributes: {
+          [semconv_1.ATTR_MESSAGING_SYSTEM]: semconv_1.MESSAGING_SYSTEM_VALUE_KAFKA,
+          [semconv_1.ATTR_MESSAGING_DESTINATION_NAME]: topic,
+          [semconv_1.ATTR_MESSAGING_KAFKA_MESSAGE_KEY]: message.key ? String(message.key) : void 0,
+          [semconv_1.ATTR_MESSAGING_KAFKA_MESSAGE_TOMBSTONE]: message.key && message.value === null ? true : void 0,
+          [semconv_1.ATTR_MESSAGING_DESTINATION_PARTITION_ID]: message.partition !== void 0 ? String(message.partition) : void 0,
+          [semconv_1.ATTR_MESSAGING_OPERATION_NAME]: "send",
+          [semconv_1.ATTR_MESSAGING_OPERATION_TYPE]: semconv_1.MESSAGING_OPERATION_TYPE_VALUE_SEND
+        }
+      });
+      message.headers = message.headers ?? {};
+      api_1.propagation.inject(api_1.trace.setSpan(api_1.context.active(), span), message.headers);
+      const { producerHook } = this.getConfig();
+      if (producerHook) {
+        (0, instrumentation_1.safeExecuteInTheMiddle)(() => producerHook(span, { topic, message }), (e) => {
+          if (e)
+            this._diag.error("producerHook error", e);
+        }, true);
+      }
+      return span;
+    }
+  }
+  instrumentation$d.KafkaJsInstrumentation = KafkaJsInstrumentation;
+  return instrumentation$d;
+}
+var hasRequiredSrc$g;
+function requireSrc$g() {
+  if (hasRequiredSrc$g) return src$g;
+  hasRequiredSrc$g = 1;
+  (function(exports$1) {
+    Object.defineProperty(exports$1, "__esModule", { value: true });
+    exports$1.KafkaJsInstrumentation = void 0;
+    var instrumentation_1 = requireInstrumentation$d();
+    Object.defineProperty(exports$1, "KafkaJsInstrumentation", { enumerable: true, get: function() {
+      return instrumentation_1.KafkaJsInstrumentation;
+    } });
+  })(src$g);
+  return src$g;
+}
+var srcExports$e = requireSrc$g();
+const INTEGRATION_NAME$i = "Kafka";
+const instrumentKafka = generateInstrumentOnce(
+  INTEGRATION_NAME$i,
+  () => new srcExports$e.KafkaJsInstrumentation({
+    consumerHook(span) {
+      addOriginToSpan(span, "auto.kafkajs.otel.consumer");
+    },
+    producerHook(span) {
+      addOriginToSpan(span, "auto.kafkajs.otel.producer");
+    }
+  })
+);
+const _kafkaIntegration = (() => {
+  return {
+    name: INTEGRATION_NAME$i,
+    setupOnce() {
+      instrumentKafka();
+    }
+  };
+});
+const kafkaIntegration = defineIntegration(_kafkaIntegration);
+var src$f = {};
+var instrumentation$c = {};
+var version$d = {};
+var hasRequiredVersion$d;
+function requireVersion$d() {
+  if (hasRequiredVersion$d) return version$d;
+  hasRequiredVersion$d = 1;
+  Object.defineProperty(version$d, "__esModule", { value: true });
+  version$d.PACKAGE_NAME = version$d.PACKAGE_VERSION = void 0;
+  version$d.PACKAGE_VERSION = "0.53.0";
+  version$d.PACKAGE_NAME = "@opentelemetry/instrumentation-lru-memoizer";
+  return version$d;
+}
+var hasRequiredInstrumentation$c;
+function requireInstrumentation$c() {
+  if (hasRequiredInstrumentation$c) return instrumentation$c;
+  hasRequiredInstrumentation$c = 1;
+  Object.defineProperty(instrumentation$c, "__esModule", { value: true });
+  instrumentation$c.LruMemoizerInstrumentation = void 0;
+  const api_1 = /* @__PURE__ */ requireSrc$n();
+  const instrumentation_1 = require$$2;
+  const version_1 = requireVersion$d();
+  class LruMemoizerInstrumentation extends instrumentation_1.InstrumentationBase {
+    constructor(config2 = {}) {
+      super(version_1.PACKAGE_NAME, version_1.PACKAGE_VERSION, config2);
+    }
+    init() {
+      return [
+        new instrumentation_1.InstrumentationNodeModuleDefinition(
+          "lru-memoizer",
+          [">=1.3 <3"],
+          (moduleExports) => {
+            const asyncMemoizer = function() {
+              const origMemoizer = moduleExports.apply(this, arguments);
+              return function() {
+                const modifiedArguments = [...arguments];
+                const origCallback = modifiedArguments.pop();
+                const callbackWithContext = typeof origCallback === "function" ? api_1.context.bind(api_1.context.active(), origCallback) : origCallback;
+                modifiedArguments.push(callbackWithContext);
+                return origMemoizer.apply(this, modifiedArguments);
+              };
+            };
+            asyncMemoizer.sync = moduleExports.sync;
+            return asyncMemoizer;
+          },
+          void 0
+          // no need to disable as this instrumentation does not create any spans
+        )
+      ];
+    }
+  }
+  instrumentation$c.LruMemoizerInstrumentation = LruMemoizerInstrumentation;
+  return instrumentation$c;
+}
+var hasRequiredSrc$f;
+function requireSrc$f() {
+  if (hasRequiredSrc$f) return src$f;
+  hasRequiredSrc$f = 1;
+  (function(exports$1) {
+    Object.defineProperty(exports$1, "__esModule", { value: true });
+    exports$1.LruMemoizerInstrumentation = void 0;
+    var instrumentation_1 = requireInstrumentation$c();
+    Object.defineProperty(exports$1, "LruMemoizerInstrumentation", { enumerable: true, get: function() {
+      return instrumentation_1.LruMemoizerInstrumentation;
+    } });
+  })(src$f);
+  return src$f;
+}
+var srcExports$d = requireSrc$f();
+const INTEGRATION_NAME$h = "LruMemoizer";
+const instrumentLruMemoizer = generateInstrumentOnce(INTEGRATION_NAME$h, () => new srcExports$d.LruMemoizerInstrumentation());
+const _lruMemoizerIntegration = (() => {
+  return {
+    name: INTEGRATION_NAME$h,
+    setupOnce() {
+      instrumentLruMemoizer();
+    }
+  };
+});
+const lruMemoizerIntegration = defineIntegration(_lruMemoizerIntegration);
+var src$e = {};
+var instrumentation$b = {};
+var semconv$9 = {};
+var hasRequiredSemconv$9;
+function requireSemconv$9() {
+  if (hasRequiredSemconv$9) return semconv$9;
+  hasRequiredSemconv$9 = 1;
+  Object.defineProperty(semconv$9, "__esModule", { value: true });
+  semconv$9.METRIC_DB_CLIENT_CONNECTIONS_USAGE = semconv$9.DB_SYSTEM_VALUE_MONGODB = semconv$9.ATTR_NET_PEER_PORT = semconv$9.ATTR_NET_PEER_NAME = semconv$9.ATTR_DB_SYSTEM = semconv$9.ATTR_DB_STATEMENT = semconv$9.ATTR_DB_OPERATION = semconv$9.ATTR_DB_NAME = semconv$9.ATTR_DB_MONGODB_COLLECTION = semconv$9.ATTR_DB_CONNECTION_STRING = void 0;
+  semconv$9.ATTR_DB_CONNECTION_STRING = "db.connection_string";
+  semconv$9.ATTR_DB_MONGODB_COLLECTION = "db.mongodb.collection";
+  semconv$9.ATTR_DB_NAME = "db.name";
+  semconv$9.ATTR_DB_OPERATION = "db.operation";
+  semconv$9.ATTR_DB_STATEMENT = "db.statement";
+  semconv$9.ATTR_DB_SYSTEM = "db.system";
+  semconv$9.ATTR_NET_PEER_NAME = "net.peer.name";
+  semconv$9.ATTR_NET_PEER_PORT = "net.peer.port";
+  semconv$9.DB_SYSTEM_VALUE_MONGODB = "mongodb";
+  semconv$9.METRIC_DB_CLIENT_CONNECTIONS_USAGE = "db.client.connections.usage";
+  return semconv$9;
+}
+var internalTypes$4 = {};
+var hasRequiredInternalTypes$4;
+function requireInternalTypes$4() {
+  if (hasRequiredInternalTypes$4) return internalTypes$4;
+  hasRequiredInternalTypes$4 = 1;
+  (function(exports$1) {
+    Object.defineProperty(exports$1, "__esModule", { value: true });
+    exports$1.MongodbCommandType = void 0;
+    (function(MongodbCommandType) {
+      MongodbCommandType["CREATE_INDEXES"] = "createIndexes";
+      MongodbCommandType["FIND_AND_MODIFY"] = "findAndModify";
+      MongodbCommandType["IS_MASTER"] = "isMaster";
+      MongodbCommandType["COUNT"] = "count";
+      MongodbCommandType["AGGREGATE"] = "aggregate";
+      MongodbCommandType["UNKNOWN"] = "unknown";
+    })(exports$1.MongodbCommandType || (exports$1.MongodbCommandType = {}));
+  })(internalTypes$4);
+  return internalTypes$4;
+}
+var version$c = {};
+var hasRequiredVersion$c;
+function requireVersion$c() {
+  if (hasRequiredVersion$c) return version$c;
+  hasRequiredVersion$c = 1;
+  Object.defineProperty(version$c, "__esModule", { value: true });
+  version$c.PACKAGE_NAME = version$c.PACKAGE_VERSION = void 0;
+  version$c.PACKAGE_VERSION = "0.61.0";
+  version$c.PACKAGE_NAME = "@opentelemetry/instrumentation-mongodb";
+  return version$c;
+}
+var hasRequiredInstrumentation$b;
+function requireInstrumentation$b() {
+  if (hasRequiredInstrumentation$b) return instrumentation$b;
+  hasRequiredInstrumentation$b = 1;
+  Object.defineProperty(instrumentation$b, "__esModule", { value: true });
+  instrumentation$b.MongoDBInstrumentation = void 0;
+  const api_1 = /* @__PURE__ */ requireSrc$n();
+  const instrumentation_1 = require$$2;
+  const semconv_1 = requireSemconv$9();
+  const internal_types_1 = requireInternalTypes$4();
+  const version_1 = requireVersion$c();
+  const DEFAULT_CONFIG = {
+    requireParentSpan: true
+  };
+  class MongoDBInstrumentation extends instrumentation_1.InstrumentationBase {
+    constructor(config2 = {}) {
+      super(version_1.PACKAGE_NAME, version_1.PACKAGE_VERSION, { ...DEFAULT_CONFIG, ...config2 });
+    }
+    setConfig(config2 = {}) {
+      super.setConfig({ ...DEFAULT_CONFIG, ...config2 });
+    }
+    _updateMetricInstruments() {
+      this._connectionsUsage = this.meter.createUpDownCounter(semconv_1.METRIC_DB_CLIENT_CONNECTIONS_USAGE, {
+        description: "The number of connections that are currently in state described by the state attribute.",
+        unit: "{connection}"
+      });
+    }
+    init() {
+      const { v3PatchConnection, v3UnpatchConnection } = this._getV3ConnectionPatches();
+      const { v4PatchConnect, v4UnpatchConnect } = this._getV4ConnectPatches();
+      const { v4PatchConnectionCallback, v4PatchConnectionPromise, v4UnpatchConnection } = this._getV4ConnectionPatches();
+      const { v4PatchConnectionPool, v4UnpatchConnectionPool } = this._getV4ConnectionPoolPatches();
+      const { v4PatchSessions, v4UnpatchSessions } = this._getV4SessionsPatches();
+      return [
+        new instrumentation_1.InstrumentationNodeModuleDefinition("mongodb", [">=3.3.0 <4"], void 0, void 0, [
+          new instrumentation_1.InstrumentationNodeModuleFile("mongodb/lib/core/wireprotocol/index.js", [">=3.3.0 <4"], v3PatchConnection, v3UnpatchConnection)
+        ]),
+        new instrumentation_1.InstrumentationNodeModuleDefinition("mongodb", [">=4.0.0 <7"], void 0, void 0, [
+          new instrumentation_1.InstrumentationNodeModuleFile("mongodb/lib/cmap/connection.js", [">=4.0.0 <6.4"], v4PatchConnectionCallback, v4UnpatchConnection),
+          new instrumentation_1.InstrumentationNodeModuleFile("mongodb/lib/cmap/connection.js", [">=6.4.0 <7"], v4PatchConnectionPromise, v4UnpatchConnection),
+          new instrumentation_1.InstrumentationNodeModuleFile("mongodb/lib/cmap/connection_pool.js", [">=4.0.0 <6.4"], v4PatchConnectionPool, v4UnpatchConnectionPool),
+          new instrumentation_1.InstrumentationNodeModuleFile("mongodb/lib/cmap/connect.js", [">=4.0.0 <7"], v4PatchConnect, v4UnpatchConnect),
+          new instrumentation_1.InstrumentationNodeModuleFile("mongodb/lib/sessions.js", [">=4.0.0 <7"], v4PatchSessions, v4UnpatchSessions)
+        ])
+      ];
+    }
+    _getV3ConnectionPatches() {
+      return {
+        v3PatchConnection: (moduleExports) => {
+          if ((0, instrumentation_1.isWrapped)(moduleExports.insert)) {
+            this._unwrap(moduleExports, "insert");
+          }
+          this._wrap(moduleExports, "insert", this._getV3PatchOperation("insert"));
+          if ((0, instrumentation_1.isWrapped)(moduleExports.remove)) {
+            this._unwrap(moduleExports, "remove");
+          }
+          this._wrap(moduleExports, "remove", this._getV3PatchOperation("remove"));
+          if ((0, instrumentation_1.isWrapped)(moduleExports.update)) {
+            this._unwrap(moduleExports, "update");
+          }
+          this._wrap(moduleExports, "update", this._getV3PatchOperation("update"));
+          if ((0, instrumentation_1.isWrapped)(moduleExports.command)) {
+            this._unwrap(moduleExports, "command");
+          }
+          this._wrap(moduleExports, "command", this._getV3PatchCommand());
+          if ((0, instrumentation_1.isWrapped)(moduleExports.query)) {
+            this._unwrap(moduleExports, "query");
+          }
+          this._wrap(moduleExports, "query", this._getV3PatchFind());
+          if ((0, instrumentation_1.isWrapped)(moduleExports.getMore)) {
+            this._unwrap(moduleExports, "getMore");
+          }
+          this._wrap(moduleExports, "getMore", this._getV3PatchCursor());
+          return moduleExports;
+        },
+        v3UnpatchConnection: (moduleExports) => {
+          if (moduleExports === void 0)
+            return;
+          this._unwrap(moduleExports, "insert");
+          this._unwrap(moduleExports, "remove");
+          this._unwrap(moduleExports, "update");
+          this._unwrap(moduleExports, "command");
+          this._unwrap(moduleExports, "query");
+          this._unwrap(moduleExports, "getMore");
+        }
+      };
+    }
+    _getV4SessionsPatches() {
+      return {
+        v4PatchSessions: (moduleExports) => {
+          if ((0, instrumentation_1.isWrapped)(moduleExports.acquire)) {
+            this._unwrap(moduleExports, "acquire");
+          }
+          this._wrap(moduleExports.ServerSessionPool.prototype, "acquire", this._getV4AcquireCommand());
+          if ((0, instrumentation_1.isWrapped)(moduleExports.release)) {
+            this._unwrap(moduleExports, "release");
+          }
+          this._wrap(moduleExports.ServerSessionPool.prototype, "release", this._getV4ReleaseCommand());
+          return moduleExports;
+        },
+        v4UnpatchSessions: (moduleExports) => {
+          if (moduleExports === void 0)
+            return;
+          if ((0, instrumentation_1.isWrapped)(moduleExports.acquire)) {
+            this._unwrap(moduleExports, "acquire");
+          }
+          if ((0, instrumentation_1.isWrapped)(moduleExports.release)) {
+            this._unwrap(moduleExports, "release");
+          }
+        }
+      };
+    }
+    _getV4AcquireCommand() {
+      const instrumentation2 = this;
+      return (original) => {
+        return function patchAcquire() {
+          const nSessionsBeforeAcquire = this.sessions.length;
+          const session = original.call(this);
+          const nSessionsAfterAcquire = this.sessions.length;
+          if (nSessionsBeforeAcquire === nSessionsAfterAcquire) {
+            instrumentation2._connectionsUsage.add(1, {
+              state: "used",
+              "pool.name": instrumentation2._poolName
+            });
+          } else if (nSessionsBeforeAcquire - 1 === nSessionsAfterAcquire) {
+            instrumentation2._connectionsUsage.add(-1, {
+              state: "idle",
+              "pool.name": instrumentation2._poolName
+            });
+            instrumentation2._connectionsUsage.add(1, {
+              state: "used",
+              "pool.name": instrumentation2._poolName
+            });
+          }
+          return session;
+        };
+      };
+    }
+    _getV4ReleaseCommand() {
+      const instrumentation2 = this;
+      return (original) => {
+        return function patchRelease(session) {
+          const cmdPromise = original.call(this, session);
+          instrumentation2._connectionsUsage.add(-1, {
+            state: "used",
+            "pool.name": instrumentation2._poolName
+          });
+          instrumentation2._connectionsUsage.add(1, {
+            state: "idle",
+            "pool.name": instrumentation2._poolName
+          });
+          return cmdPromise;
+        };
+      };
+    }
+    _getV4ConnectionPoolPatches() {
+      return {
+        v4PatchConnectionPool: (moduleExports) => {
+          const poolPrototype = moduleExports.ConnectionPool.prototype;
+          if ((0, instrumentation_1.isWrapped)(poolPrototype.checkOut)) {
+            this._unwrap(poolPrototype, "checkOut");
+          }
+          this._wrap(poolPrototype, "checkOut", this._getV4ConnectionPoolCheckOut());
+          return moduleExports;
+        },
+        v4UnpatchConnectionPool: (moduleExports) => {
+          if (moduleExports === void 0)
+            return;
+          this._unwrap(moduleExports.ConnectionPool.prototype, "checkOut");
+        }
+      };
+    }
+    _getV4ConnectPatches() {
+      return {
+        v4PatchConnect: (moduleExports) => {
+          if ((0, instrumentation_1.isWrapped)(moduleExports.connect)) {
+            this._unwrap(moduleExports, "connect");
+          }
+          this._wrap(moduleExports, "connect", this._getV4ConnectCommand());
+          return moduleExports;
+        },
+        v4UnpatchConnect: (moduleExports) => {
+          if (moduleExports === void 0)
+            return;
+          this._unwrap(moduleExports, "connect");
+        }
+      };
+    }
+    // This patch will become unnecessary once
+    // https://jira.mongodb.org/browse/NODE-5639 is done.
+    _getV4ConnectionPoolCheckOut() {
+      return (original) => {
+        return function patchedCheckout(callback) {
+          const patchedCallback = api_1.context.bind(api_1.context.active(), callback);
+          return original.call(this, patchedCallback);
+        };
+      };
+    }
+    _getV4ConnectCommand() {
+      const instrumentation2 = this;
+      return (original) => {
+        return function patchedConnect(options, callback) {
+          if (original.length === 1) {
+            const result = original.call(this, options);
+            if (result && typeof result.then === "function") {
+              result.then(
+                () => instrumentation2.setPoolName(options),
+                // this handler is set to pass the lint rules
+                () => void 0
+              );
+            }
+            return result;
+          }
+          const patchedCallback = function(err, conn) {
+            if (err || !conn) {
+              callback(err, conn);
+              return;
+            }
+            instrumentation2.setPoolName(options);
+            callback(err, conn);
+          };
+          return original.call(this, options, patchedCallback);
+        };
+      };
+    }
+    // eslint-disable-next-line @typescript-eslint/no-unused-vars
+    _getV4ConnectionPatches() {
+      return {
+        v4PatchConnectionCallback: (moduleExports) => {
+          if ((0, instrumentation_1.isWrapped)(moduleExports.Connection.prototype.command)) {
+            this._unwrap(moduleExports.Connection.prototype, "command");
+          }
+          this._wrap(moduleExports.Connection.prototype, "command", this._getV4PatchCommandCallback());
+          return moduleExports;
+        },
+        v4PatchConnectionPromise: (moduleExports) => {
+          if ((0, instrumentation_1.isWrapped)(moduleExports.Connection.prototype.command)) {
+            this._unwrap(moduleExports.Connection.prototype, "command");
+          }
+          this._wrap(moduleExports.Connection.prototype, "command", this._getV4PatchCommandPromise());
+          return moduleExports;
+        },
+        v4UnpatchConnection: (moduleExports) => {
+          if (moduleExports === void 0)
+            return;
+          this._unwrap(moduleExports.Connection.prototype, "command");
+        }
+      };
+    }
+    /** Creates spans for common operations */
+    _getV3PatchOperation(operationName) {
+      const instrumentation2 = this;
+      return (original) => {
+        return function patchedServerCommand(server, ns, ops, options, callback) {
+          const currentSpan = api_1.trace.getSpan(api_1.context.active());
+          const skipInstrumentation = instrumentation2._checkSkipInstrumentation(currentSpan);
+          const resultHandler = typeof options === "function" ? options : callback;
+          if (skipInstrumentation || typeof resultHandler !== "function" || typeof ops !== "object") {
+            if (typeof options === "function") {
+              return original.call(this, server, ns, ops, options);
+            } else {
+              return original.call(this, server, ns, ops, options, callback);
+            }
+          }
+          const span = instrumentation2.tracer.startSpan(`mongodb.${operationName}`, {
+            kind: api_1.SpanKind.CLIENT
+          });
+          instrumentation2._populateV3Attributes(
+            span,
+            ns,
+            server,
+            // eslint-disable-next-line @typescript-eslint/no-explicit-any
+            ops[0],
+            operationName
+          );
+          const patchedCallback = instrumentation2._patchEnd(span, resultHandler);
+          if (typeof options === "function") {
+            return original.call(this, server, ns, ops, patchedCallback);
+          } else {
+            return original.call(this, server, ns, ops, options, patchedCallback);
+          }
+        };
+      };
+    }
+    /** Creates spans for command operation */
+    _getV3PatchCommand() {
+      const instrumentation2 = this;
+      return (original) => {
+        return function patchedServerCommand(server, ns, cmd, options, callback) {
+          const currentSpan = api_1.trace.getSpan(api_1.context.active());
+          const skipInstrumentation = instrumentation2._checkSkipInstrumentation(currentSpan);
+          const resultHandler = typeof options === "function" ? options : callback;
+          if (skipInstrumentation || typeof resultHandler !== "function" || typeof cmd !== "object") {
+            if (typeof options === "function") {
+              return original.call(this, server, ns, cmd, options);
+            } else {
+              return original.call(this, server, ns, cmd, options, callback);
+            }
+          }
+          const commandType = MongoDBInstrumentation._getCommandType(cmd);
+          const type = commandType === internal_types_1.MongodbCommandType.UNKNOWN ? "command" : commandType;
+          const span = instrumentation2.tracer.startSpan(`mongodb.${type}`, {
+            kind: api_1.SpanKind.CLIENT
+          });
+          const operation = commandType === internal_types_1.MongodbCommandType.UNKNOWN ? void 0 : commandType;
+          instrumentation2._populateV3Attributes(span, ns, server, cmd, operation);
+          const patchedCallback = instrumentation2._patchEnd(span, resultHandler);
+          if (typeof options === "function") {
+            return original.call(this, server, ns, cmd, patchedCallback);
+          } else {
+            return original.call(this, server, ns, cmd, options, patchedCallback);
+          }
+        };
+      };
+    }
+    /** Creates spans for command operation */
+    _getV4PatchCommandCallback() {
+      const instrumentation2 = this;
+      return (original) => {
+        return function patchedV4ServerCommand(ns, cmd, options, callback) {
+          const currentSpan = api_1.trace.getSpan(api_1.context.active());
+          const skipInstrumentation = instrumentation2._checkSkipInstrumentation(currentSpan);
+          const resultHandler = callback;
+          const commandType = Object.keys(cmd)[0];
+          if (typeof cmd !== "object" || cmd.ismaster || cmd.hello) {
+            return original.call(this, ns, cmd, options, callback);
+          }
+          let span = void 0;
+          if (!skipInstrumentation) {
+            span = instrumentation2.tracer.startSpan(`mongodb.${commandType}`, {
+              kind: api_1.SpanKind.CLIENT
+            });
+            instrumentation2._populateV4Attributes(span, this, ns, cmd, commandType);
+          }
+          const patchedCallback = instrumentation2._patchEnd(span, resultHandler, this.id, commandType);
+          return original.call(this, ns, cmd, options, patchedCallback);
+        };
+      };
+    }
+    _getV4PatchCommandPromise() {
+      const instrumentation2 = this;
+      return (original) => {
+        return function patchedV4ServerCommand(...args) {
+          const [ns, cmd] = args;
+          const currentSpan = api_1.trace.getSpan(api_1.context.active());
+          const skipInstrumentation = instrumentation2._checkSkipInstrumentation(currentSpan);
+          const commandType = Object.keys(cmd)[0];
+          const resultHandler = () => void 0;
+          if (typeof cmd !== "object" || cmd.ismaster || cmd.hello) {
+            return original.apply(this, args);
+          }
+          let span = void 0;
+          if (!skipInstrumentation) {
+            span = instrumentation2.tracer.startSpan(`mongodb.${commandType}`, {
+              kind: api_1.SpanKind.CLIENT
+            });
+            instrumentation2._populateV4Attributes(span, this, ns, cmd, commandType);
+          }
+          const patchedCallback = instrumentation2._patchEnd(span, resultHandler, this.id, commandType);
+          const result = original.apply(this, args);
+          result.then((res) => patchedCallback(null, res), (err) => patchedCallback(err));
+          return result;
+        };
+      };
+    }
+    /** Creates spans for find operation */
+    _getV3PatchFind() {
+      const instrumentation2 = this;
+      return (original) => {
+        return function patchedServerCommand(server, ns, cmd, cursorState, options, callback) {
+          const currentSpan = api_1.trace.getSpan(api_1.context.active());
+          const skipInstrumentation = instrumentation2._checkSkipInstrumentation(currentSpan);
+          const resultHandler = typeof options === "function" ? options : callback;
+          if (skipInstrumentation || typeof resultHandler !== "function" || typeof cmd !== "object") {
+            if (typeof options === "function") {
+              return original.call(this, server, ns, cmd, cursorState, options);
+            } else {
+              return original.call(this, server, ns, cmd, cursorState, options, callback);
+            }
+          }
+          const span = instrumentation2.tracer.startSpan("mongodb.find", {
+            kind: api_1.SpanKind.CLIENT
+          });
+          instrumentation2._populateV3Attributes(span, ns, server, cmd, "find");
+          const patchedCallback = instrumentation2._patchEnd(span, resultHandler);
+          if (typeof options === "function") {
+            return original.call(this, server, ns, cmd, cursorState, patchedCallback);
+          } else {
+            return original.call(this, server, ns, cmd, cursorState, options, patchedCallback);
+          }
+        };
+      };
+    }
+    /** Creates spans for find operation */
+    _getV3PatchCursor() {
+      const instrumentation2 = this;
+      return (original) => {
+        return function patchedServerCommand(server, ns, cursorState, batchSize, options, callback) {
+          const currentSpan = api_1.trace.getSpan(api_1.context.active());
+          const skipInstrumentation = instrumentation2._checkSkipInstrumentation(currentSpan);
+          const resultHandler = typeof options === "function" ? options : callback;
+          if (skipInstrumentation || typeof resultHandler !== "function") {
+            if (typeof options === "function") {
+              return original.call(this, server, ns, cursorState, batchSize, options);
+            } else {
+              return original.call(this, server, ns, cursorState, batchSize, options, callback);
+            }
+          }
+          const span = instrumentation2.tracer.startSpan("mongodb.getMore", {
+            kind: api_1.SpanKind.CLIENT
+          });
+          instrumentation2._populateV3Attributes(span, ns, server, cursorState.cmd, "getMore");
+          const patchedCallback = instrumentation2._patchEnd(span, resultHandler);
+          if (typeof options === "function") {
+            return original.call(this, server, ns, cursorState, batchSize, patchedCallback);
+          } else {
+            return original.call(this, server, ns, cursorState, batchSize, options, patchedCallback);
+          }
+        };
+      };
+    }
+    /**
+     * Get the mongodb command type from the object.
+     * @param command Internal mongodb command object
+     */
+    static _getCommandType(command) {
+      if (command.createIndexes !== void 0) {
+        return internal_types_1.MongodbCommandType.CREATE_INDEXES;
+      } else if (command.findandmodify !== void 0) {
+        return internal_types_1.MongodbCommandType.FIND_AND_MODIFY;
+      } else if (command.ismaster !== void 0) {
+        return internal_types_1.MongodbCommandType.IS_MASTER;
+      } else if (command.count !== void 0) {
+        return internal_types_1.MongodbCommandType.COUNT;
+      } else if (command.aggregate !== void 0) {
+        return internal_types_1.MongodbCommandType.AGGREGATE;
+      } else {
+        return internal_types_1.MongodbCommandType.UNKNOWN;
+      }
+    }
+    /**
+     * Populate span's attributes by fetching related metadata from the context
+     * @param span span to add attributes to
+     * @param connectionCtx mongodb internal connection context
+     * @param ns mongodb namespace
+     * @param command mongodb internal representation of a command
+     */
+    _populateV4Attributes(span, connectionCtx, ns, command, operation) {
+      let host, port;
+      if (connectionCtx) {
+        const hostParts = typeof connectionCtx.address === "string" ? connectionCtx.address.split(":") : "";
+        if (hostParts.length === 2) {
+          host = hostParts[0];
+          port = hostParts[1];
+        }
+      }
+      let commandObj;
+      if (command?.documents && command.documents[0]) {
+        commandObj = command.documents[0];
+      } else if (command?.cursors) {
+        commandObj = command.cursors;
+      } else {
+        commandObj = command;
+      }
+      this._addAllSpanAttributes(span, ns.db, ns.collection, host, port, commandObj, operation);
+    }
+    /**
+     * Populate span's attributes by fetching related metadata from the context
+     * @param span span to add attributes to
+     * @param ns mongodb namespace
+     * @param topology mongodb internal representation of the network topology
+     * @param command mongodb internal representation of a command
+     */
+    _populateV3Attributes(span, ns, topology, command, operation) {
+      let host;
+      let port;
+      if (topology && topology.s) {
+        host = topology.s.options?.host ?? topology.s.host;
+        port = (topology.s.options?.port ?? topology.s.port)?.toString();
+        if (host == null || port == null) {
+          const address = topology.description?.address;
+          if (address) {
+            const addressSegments = address.split(":");
+            host = addressSegments[0];
+            port = addressSegments[1];
+          }
+        }
+      }
+      const [dbName, dbCollection] = ns.toString().split(".");
+      const commandObj = command?.query ?? command?.q ?? command;
+      this._addAllSpanAttributes(span, dbName, dbCollection, host, port, commandObj, operation);
+    }
+    _addAllSpanAttributes(span, dbName, dbCollection, host, port, commandObj, operation) {
+      span.setAttributes({
+        [semconv_1.ATTR_DB_SYSTEM]: semconv_1.DB_SYSTEM_VALUE_MONGODB,
+        [semconv_1.ATTR_DB_NAME]: dbName,
+        [semconv_1.ATTR_DB_MONGODB_COLLECTION]: dbCollection,
+        [semconv_1.ATTR_DB_OPERATION]: operation,
+        [semconv_1.ATTR_DB_CONNECTION_STRING]: `mongodb://${host}:${port}/${dbName}`
+      });
+      if (host && port) {
+        span.setAttribute(semconv_1.ATTR_NET_PEER_NAME, host);
+        const portNumber = parseInt(port, 10);
+        if (!isNaN(portNumber)) {
+          span.setAttribute(semconv_1.ATTR_NET_PEER_PORT, portNumber);
+        }
+      }
+      if (!commandObj)
+        return;
+      const { dbStatementSerializer: configDbStatementSerializer } = this.getConfig();
+      const dbStatementSerializer = typeof configDbStatementSerializer === "function" ? configDbStatementSerializer : this._defaultDbStatementSerializer.bind(this);
+      (0, instrumentation_1.safeExecuteInTheMiddle)(() => {
+        const query = dbStatementSerializer(commandObj);
+        span.setAttribute(semconv_1.ATTR_DB_STATEMENT, query);
+      }, (err) => {
+        if (err) {
+          this._diag.error("Error running dbStatementSerializer hook", err);
+        }
+      }, true);
+    }
+    _getDefaultDbStatementReplacer() {
+      const seen = /* @__PURE__ */ new WeakSet();
+      return (_key, value) => {
+        if (typeof value !== "object" || !value)
+          return "?";
+        if (seen.has(value))
+          return "[Circular]";
+        seen.add(value);
+        return value;
+      };
+    }
+    _defaultDbStatementSerializer(commandObj) {
+      const { enhancedDatabaseReporting } = this.getConfig();
+      if (enhancedDatabaseReporting) {
+        return JSON.stringify(commandObj);
+      }
+      return JSON.stringify(commandObj, this._getDefaultDbStatementReplacer());
+    }
+    /**
+     * Triggers the response hook in case it is defined.
+     * @param span The span to add the results to.
+     * @param result The command result
+     */
+    _handleExecutionResult(span, result) {
+      const { responseHook } = this.getConfig();
+      if (typeof responseHook === "function") {
+        (0, instrumentation_1.safeExecuteInTheMiddle)(() => {
+          responseHook(span, { data: result });
+        }, (err) => {
+          if (err) {
+            this._diag.error("Error running response hook", err);
+          }
+        }, true);
+      }
+    }
+    /**
+     * Ends a created span.
+     * @param span The created span to end.
+     * @param resultHandler A callback function.
+     * @param connectionId: The connection ID of the Command response.
+     */
+    _patchEnd(span, resultHandler, connectionId, commandType) {
+      const activeContext = api_1.context.active();
+      const instrumentation2 = this;
+      return function patchedEnd(...args) {
+        const error2 = args[0];
+        if (span) {
+          if (error2 instanceof Error) {
+            span?.setStatus({
+              code: api_1.SpanStatusCode.ERROR,
+              message: error2.message
+            });
+          } else {
+            const result = args[1];
+            instrumentation2._handleExecutionResult(span, result);
+          }
+          span.end();
+        }
+        return api_1.context.with(activeContext, () => {
+          if (commandType === "endSessions") {
+            instrumentation2._connectionsUsage.add(-1, {
+              state: "idle",
+              "pool.name": instrumentation2._poolName
+            });
+          }
+          return resultHandler.apply(this, args);
+        });
+      };
+    }
+    setPoolName(options) {
+      const host = options.hostAddress?.host;
+      const port = options.hostAddress?.port;
+      const database = options.dbName;
+      const poolName = `mongodb://${host}:${port}/${database}`;
+      this._poolName = poolName;
+    }
+    _checkSkipInstrumentation(currentSpan) {
+      const requireParentSpan = this.getConfig().requireParentSpan;
+      const hasNoParentSpan = currentSpan === void 0;
+      return requireParentSpan === true && hasNoParentSpan;
+    }
+  }
+  instrumentation$b.MongoDBInstrumentation = MongoDBInstrumentation;
+  return instrumentation$b;
+}
+var types$2 = {};
+var hasRequiredTypes$2;
+function requireTypes$2() {
+  if (hasRequiredTypes$2) return types$2;
+  hasRequiredTypes$2 = 1;
+  (function(exports$1) {
+    Object.defineProperty(exports$1, "__esModule", { value: true });
+    exports$1.MongodbCommandType = void 0;
+    (function(MongodbCommandType) {
+      MongodbCommandType["CREATE_INDEXES"] = "createIndexes";
+      MongodbCommandType["FIND_AND_MODIFY"] = "findAndModify";
+      MongodbCommandType["IS_MASTER"] = "isMaster";
+      MongodbCommandType["COUNT"] = "count";
+      MongodbCommandType["UNKNOWN"] = "unknown";
+    })(exports$1.MongodbCommandType || (exports$1.MongodbCommandType = {}));
+  })(types$2);
+  return types$2;
+}
+var hasRequiredSrc$e;
+function requireSrc$e() {
+  if (hasRequiredSrc$e) return src$e;
+  hasRequiredSrc$e = 1;
+  (function(exports$1) {
+    Object.defineProperty(exports$1, "__esModule", { value: true });
+    exports$1.MongodbCommandType = exports$1.MongoDBInstrumentation = void 0;
+    var instrumentation_1 = requireInstrumentation$b();
+    Object.defineProperty(exports$1, "MongoDBInstrumentation", { enumerable: true, get: function() {
+      return instrumentation_1.MongoDBInstrumentation;
+    } });
+    var types_1 = requireTypes$2();
+    Object.defineProperty(exports$1, "MongodbCommandType", { enumerable: true, get: function() {
+      return types_1.MongodbCommandType;
+    } });
+  })(src$e);
+  return src$e;
+}
+var srcExports$c = requireSrc$e();
+const INTEGRATION_NAME$g = "Mongo";
+const instrumentMongo = generateInstrumentOnce(
+  INTEGRATION_NAME$g,
+  () => new srcExports$c.MongoDBInstrumentation({
+    dbStatementSerializer: _defaultDbStatementSerializer,
+    responseHook(span) {
+      addOriginToSpan(span, "auto.db.otel.mongo");
+    }
+  })
+);
+function _defaultDbStatementSerializer(commandObj) {
+  const resultObj = _scrubStatement(commandObj);
+  return JSON.stringify(resultObj);
+}
+function _scrubStatement(value) {
+  if (Array.isArray(value)) {
+    return value.map((element) => _scrubStatement(element));
+  }
+  if (isCommandObj(value)) {
+    const initial = {};
+    return Object.entries(value).map(([key, element]) => [key, _scrubStatement(element)]).reduce((prev, current) => {
+      if (isCommandEntry(current)) {
+        prev[current[0]] = current[1];
+      }
+      return prev;
+    }, initial);
+  }
+  return "?";
+}
+function isCommandObj(value) {
+  return typeof value === "object" && value !== null && !isBuffer(value);
+}
+function isBuffer(value) {
+  let isBuffer2 = false;
+  if (typeof Buffer !== "undefined") {
+    isBuffer2 = Buffer.isBuffer(value);
+  }
+  return isBuffer2;
+}
+function isCommandEntry(value) {
+  return Array.isArray(value);
+}
+const _mongoIntegration = (() => {
+  return {
+    name: INTEGRATION_NAME$g,
+    setupOnce() {
+      instrumentMongo();
+    }
+  };
+});
+const mongoIntegration = defineIntegration(_mongoIntegration);
+var src$d = {};
+var mongoose = {};
+var utils$b = {};
+var semconv$8 = {};
+var hasRequiredSemconv$8;
+function requireSemconv$8() {
+  if (hasRequiredSemconv$8) return semconv$8;
+  hasRequiredSemconv$8 = 1;
+  Object.defineProperty(semconv$8, "__esModule", { value: true });
+  semconv$8.ATTR_NET_PEER_PORT = semconv$8.ATTR_NET_PEER_NAME = semconv$8.ATTR_DB_USER = semconv$8.ATTR_DB_SYSTEM = semconv$8.ATTR_DB_STATEMENT = semconv$8.ATTR_DB_OPERATION = semconv$8.ATTR_DB_NAME = semconv$8.ATTR_DB_MONGODB_COLLECTION = void 0;
+  semconv$8.ATTR_DB_MONGODB_COLLECTION = "db.mongodb.collection";
+  semconv$8.ATTR_DB_NAME = "db.name";
+  semconv$8.ATTR_DB_OPERATION = "db.operation";
+  semconv$8.ATTR_DB_STATEMENT = "db.statement";
+  semconv$8.ATTR_DB_SYSTEM = "db.system";
+  semconv$8.ATTR_DB_USER = "db.user";
+  semconv$8.ATTR_NET_PEER_NAME = "net.peer.name";
+  semconv$8.ATTR_NET_PEER_PORT = "net.peer.port";
+  return semconv$8;
+}
+var hasRequiredUtils$b;
+function requireUtils$b() {
+  if (hasRequiredUtils$b) return utils$b;
+  hasRequiredUtils$b = 1;
+  Object.defineProperty(utils$b, "__esModule", { value: true });
+  utils$b.handleCallbackResponse = utils$b.handlePromiseResponse = utils$b.getAttributesFromCollection = void 0;
+  const api_1 = /* @__PURE__ */ requireSrc$n();
+  const instrumentation_1 = require$$2;
+  const semconv_1 = requireSemconv$8();
+  function getAttributesFromCollection(collection) {
+    return {
+      [semconv_1.ATTR_DB_MONGODB_COLLECTION]: collection.name,
+      [semconv_1.ATTR_DB_NAME]: collection.conn.name,
+      [semconv_1.ATTR_DB_USER]: collection.conn.user,
+      [semconv_1.ATTR_NET_PEER_NAME]: collection.conn.host,
+      [semconv_1.ATTR_NET_PEER_PORT]: collection.conn.port
+    };
+  }
+  utils$b.getAttributesFromCollection = getAttributesFromCollection;
+  function setErrorStatus(span, error2 = {}) {
+    span.recordException(error2);
+    span.setStatus({
+      code: api_1.SpanStatusCode.ERROR,
+      message: `${error2.message} ${error2.code ? `
+Mongoose Error Code: ${error2.code}` : ""}`
+    });
+  }
+  function applyResponseHook(span, response, responseHook, moduleVersion = void 0) {
+    if (!responseHook) {
+      return;
+    }
+    (0, instrumentation_1.safeExecuteInTheMiddle)(() => responseHook(span, { moduleVersion, response }), (e) => {
+      if (e) {
+        api_1.diag.error("mongoose instrumentation: responseHook error", e);
+      }
+    }, true);
+  }
+  function handlePromiseResponse(execResponse, span, responseHook, moduleVersion = void 0) {
+    if (!(execResponse instanceof Promise)) {
+      applyResponseHook(span, execResponse, responseHook, moduleVersion);
+      span.end();
+      return execResponse;
+    }
+    return execResponse.then((response) => {
+      applyResponseHook(span, response, responseHook, moduleVersion);
+      return response;
+    }).catch((err) => {
+      setErrorStatus(span, err);
+      throw err;
+    }).finally(() => span.end());
+  }
+  utils$b.handlePromiseResponse = handlePromiseResponse;
+  function handleCallbackResponse(callback, exec, originalThis, span, args, responseHook, moduleVersion = void 0) {
+    let callbackArgumentIndex = 0;
+    if (args.length === 2) {
+      callbackArgumentIndex = 1;
+    } else if (args.length === 3) {
+      callbackArgumentIndex = 2;
+    }
+    args[callbackArgumentIndex] = (err, response) => {
+      if (err) {
+        setErrorStatus(span, err);
+      } else {
+        applyResponseHook(span, response, responseHook, moduleVersion);
+      }
+      span.end();
+      return callback(err, response);
+    };
+    return exec.apply(originalThis, args);
+  }
+  utils$b.handleCallbackResponse = handleCallbackResponse;
+  return utils$b;
+}
+var version$b = {};
+var hasRequiredVersion$b;
+function requireVersion$b() {
+  if (hasRequiredVersion$b) return version$b;
+  hasRequiredVersion$b = 1;
+  Object.defineProperty(version$b, "__esModule", { value: true });
+  version$b.PACKAGE_NAME = version$b.PACKAGE_VERSION = void 0;
+  version$b.PACKAGE_VERSION = "0.55.0";
+  version$b.PACKAGE_NAME = "@opentelemetry/instrumentation-mongoose";
+  return version$b;
+}
+var hasRequiredMongoose;
+function requireMongoose() {
+  if (hasRequiredMongoose) return mongoose;
+  hasRequiredMongoose = 1;
+  (function(exports$1) {
+    Object.defineProperty(exports$1, "__esModule", { value: true });
+    exports$1.MongooseInstrumentation = exports$1._STORED_PARENT_SPAN = void 0;
+    const api_1 = /* @__PURE__ */ requireSrc$n();
+    const core_1 = require$$1;
+    const utils_1 = requireUtils$b();
+    const instrumentation_1 = require$$2;
+    const version_1 = requireVersion$b();
+    const semconv_1 = requireSemconv$8();
+    const contextCaptureFunctionsCommon = [
+      "deleteOne",
+      "deleteMany",
+      "find",
+      "findOne",
+      "estimatedDocumentCount",
+      "countDocuments",
+      "distinct",
+      "where",
+      "$where",
+      "findOneAndUpdate",
+      "findOneAndDelete",
+      "findOneAndReplace"
+    ];
+    const contextCaptureFunctions6 = [
+      "remove",
+      "count",
+      "findOneAndRemove",
+      ...contextCaptureFunctionsCommon
+    ];
+    const contextCaptureFunctions7 = [
+      "count",
+      "findOneAndRemove",
+      ...contextCaptureFunctionsCommon
+    ];
+    const contextCaptureFunctions8 = [...contextCaptureFunctionsCommon];
+    function getContextCaptureFunctions(moduleVersion) {
+      if (!moduleVersion) {
+        return contextCaptureFunctionsCommon;
+      } else if (moduleVersion.startsWith("6.") || moduleVersion.startsWith("5.")) {
+        return contextCaptureFunctions6;
+      } else if (moduleVersion.startsWith("7.")) {
+        return contextCaptureFunctions7;
+      } else {
+        return contextCaptureFunctions8;
+      }
+    }
+    function instrumentRemove(moduleVersion) {
+      return moduleVersion && (moduleVersion.startsWith("5.") || moduleVersion.startsWith("6.")) || false;
+    }
+    exports$1._STORED_PARENT_SPAN = Symbol("stored-parent-span");
+    class MongooseInstrumentation extends instrumentation_1.InstrumentationBase {
+      constructor(config2 = {}) {
+        super(version_1.PACKAGE_NAME, version_1.PACKAGE_VERSION, config2);
+      }
+      init() {
+        const module2 = new instrumentation_1.InstrumentationNodeModuleDefinition("mongoose", [">=5.9.7 <9"], this.patch.bind(this), this.unpatch.bind(this));
+        return module2;
+      }
+      patch(module2, moduleVersion) {
+        const moduleExports = module2[Symbol.toStringTag] === "Module" ? module2.default : module2;
+        this._wrap(moduleExports.Model.prototype, "save", this.patchOnModelMethods("save", moduleVersion));
+        moduleExports.Model.prototype.$save = moduleExports.Model.prototype.save;
+        if (instrumentRemove(moduleVersion)) {
+          this._wrap(moduleExports.Model.prototype, "remove", this.patchOnModelMethods("remove", moduleVersion));
+        }
+        this._wrap(moduleExports.Query.prototype, "exec", this.patchQueryExec(moduleVersion));
+        this._wrap(moduleExports.Aggregate.prototype, "exec", this.patchAggregateExec(moduleVersion));
+        const contextCaptureFunctions = getContextCaptureFunctions(moduleVersion);
+        contextCaptureFunctions.forEach((funcName) => {
+          this._wrap(moduleExports.Query.prototype, funcName, this.patchAndCaptureSpanContext(funcName));
+        });
+        this._wrap(moduleExports.Model, "aggregate", this.patchModelAggregate());
+        this._wrap(moduleExports.Model, "insertMany", this.patchModelStatic("insertMany", moduleVersion));
+        this._wrap(moduleExports.Model, "bulkWrite", this.patchModelStatic("bulkWrite", moduleVersion));
+        return moduleExports;
+      }
+      unpatch(module2, moduleVersion) {
+        const moduleExports = module2[Symbol.toStringTag] === "Module" ? module2.default : module2;
+        const contextCaptureFunctions = getContextCaptureFunctions(moduleVersion);
+        this._unwrap(moduleExports.Model.prototype, "save");
+        moduleExports.Model.prototype.$save = moduleExports.Model.prototype.save;
+        if (instrumentRemove(moduleVersion)) {
+          this._unwrap(moduleExports.Model.prototype, "remove");
+        }
+        this._unwrap(moduleExports.Query.prototype, "exec");
+        this._unwrap(moduleExports.Aggregate.prototype, "exec");
+        contextCaptureFunctions.forEach((funcName) => {
+          this._unwrap(moduleExports.Query.prototype, funcName);
+        });
+        this._unwrap(moduleExports.Model, "aggregate");
+        this._unwrap(moduleExports.Model, "insertMany");
+        this._unwrap(moduleExports.Model, "bulkWrite");
+      }
+      patchAggregateExec(moduleVersion) {
+        const self = this;
+        return (originalAggregate) => {
+          return function exec(callback) {
+            if (self.getConfig().requireParentSpan && api_1.trace.getSpan(api_1.context.active()) === void 0) {
+              return originalAggregate.apply(this, arguments);
+            }
+            const parentSpan = this[exports$1._STORED_PARENT_SPAN];
+            const attributes = {};
+            const { dbStatementSerializer } = self.getConfig();
+            if (dbStatementSerializer) {
+              attributes[semconv_1.ATTR_DB_STATEMENT] = dbStatementSerializer("aggregate", {
+                options: this.options,
+                aggregatePipeline: this._pipeline
+              });
+            }
+            const span = self._startSpan(this._model.collection, this._model?.modelName, "aggregate", attributes, parentSpan);
+            return self._handleResponse(span, originalAggregate, this, arguments, callback, moduleVersion);
+          };
+        };
+      }
+      patchQueryExec(moduleVersion) {
+        const self = this;
+        return (originalExec) => {
+          return function exec(callback) {
+            if (self.getConfig().requireParentSpan && api_1.trace.getSpan(api_1.context.active()) === void 0) {
+              return originalExec.apply(this, arguments);
+            }
+            const parentSpan = this[exports$1._STORED_PARENT_SPAN];
+            const attributes = {};
+            const { dbStatementSerializer } = self.getConfig();
+            if (dbStatementSerializer) {
+              attributes[semconv_1.ATTR_DB_STATEMENT] = dbStatementSerializer(this.op, {
+                condition: this._conditions,
+                updates: this._update,
+                options: this.options,
+                fields: this._fields
+              });
+            }
+            const span = self._startSpan(this.mongooseCollection, this.model.modelName, this.op, attributes, parentSpan);
+            return self._handleResponse(span, originalExec, this, arguments, callback, moduleVersion);
+          };
+        };
+      }
+      patchOnModelMethods(op, moduleVersion) {
+        const self = this;
+        return (originalOnModelFunction) => {
+          return function method(options, callback) {
+            if (self.getConfig().requireParentSpan && api_1.trace.getSpan(api_1.context.active()) === void 0) {
+              return originalOnModelFunction.apply(this, arguments);
+            }
+            const serializePayload = { document: this };
+            if (options && !(options instanceof Function)) {
+              serializePayload.options = options;
+            }
+            const attributes = {};
+            const { dbStatementSerializer } = self.getConfig();
+            if (dbStatementSerializer) {
+              attributes[semconv_1.ATTR_DB_STATEMENT] = dbStatementSerializer(op, serializePayload);
+            }
+            const span = self._startSpan(this.constructor.collection, this.constructor.modelName, op, attributes);
+            if (options instanceof Function) {
+              callback = options;
+              options = void 0;
+            }
+            return self._handleResponse(span, originalOnModelFunction, this, arguments, callback, moduleVersion);
+          };
+        };
+      }
+      patchModelStatic(op, moduleVersion) {
+        const self = this;
+        return (original) => {
+          return function patchedStatic(docsOrOps, options, callback) {
+            if (self.getConfig().requireParentSpan && api_1.trace.getSpan(api_1.context.active()) === void 0) {
+              return original.apply(this, arguments);
+            }
+            if (typeof options === "function") {
+              callback = options;
+              options = void 0;
+            }
+            const serializePayload = {};
+            switch (op) {
+              case "insertMany":
+                serializePayload.documents = docsOrOps;
+                break;
+              case "bulkWrite":
+                serializePayload.operations = docsOrOps;
+                break;
+              default:
+                serializePayload.document = docsOrOps;
+                break;
+            }
+            if (options !== void 0) {
+              serializePayload.options = options;
+            }
+            const attributes = {};
+            const { dbStatementSerializer } = self.getConfig();
+            if (dbStatementSerializer) {
+              attributes[semconv_1.ATTR_DB_STATEMENT] = dbStatementSerializer(op, serializePayload);
+            }
+            const span = self._startSpan(this.collection, this.modelName, op, attributes);
+            return self._handleResponse(span, original, this, arguments, callback, moduleVersion);
+          };
+        };
+      }
+      // we want to capture the otel span on the object which is calling exec.
+      // in the special case of aggregate, we need have no function to path
+      // on the Aggregate object to capture the context on, so we patch
+      // the aggregate of Model, and set the context on the Aggregate object
+      patchModelAggregate() {
+        const self = this;
+        return (original) => {
+          return function captureSpanContext() {
+            const currentSpan = api_1.trace.getSpan(api_1.context.active());
+            const aggregate = self._callOriginalFunction(() => original.apply(this, arguments));
+            if (aggregate)
+              aggregate[exports$1._STORED_PARENT_SPAN] = currentSpan;
+            return aggregate;
+          };
+        };
+      }
+      patchAndCaptureSpanContext(funcName) {
+        const self = this;
+        return (original) => {
+          return function captureSpanContext() {
+            this[exports$1._STORED_PARENT_SPAN] = api_1.trace.getSpan(api_1.context.active());
+            return self._callOriginalFunction(() => original.apply(this, arguments));
+          };
+        };
+      }
+      _startSpan(collection, modelName, operation, attributes, parentSpan) {
+        return this.tracer.startSpan(`mongoose.${modelName}.${operation}`, {
+          kind: api_1.SpanKind.CLIENT,
+          attributes: {
+            ...attributes,
+            ...(0, utils_1.getAttributesFromCollection)(collection),
+            [semconv_1.ATTR_DB_OPERATION]: operation,
+            [semconv_1.ATTR_DB_SYSTEM]: "mongoose"
+          }
+        }, parentSpan ? api_1.trace.setSpan(api_1.context.active(), parentSpan) : void 0);
+      }
+      _handleResponse(span, exec, originalThis, args, callback, moduleVersion = void 0) {
+        const self = this;
+        if (callback instanceof Function) {
+          return self._callOriginalFunction(() => (0, utils_1.handleCallbackResponse)(callback, exec, originalThis, span, args, self.getConfig().responseHook, moduleVersion));
+        } else {
+          const response = self._callOriginalFunction(() => exec.apply(originalThis, args));
+          return (0, utils_1.handlePromiseResponse)(response, span, self.getConfig().responseHook, moduleVersion);
+        }
+      }
+      _callOriginalFunction(originalFunction) {
+        if (this.getConfig().suppressInternalInstrumentation) {
+          return api_1.context.with((0, core_1.suppressTracing)(api_1.context.active()), originalFunction);
+        } else {
+          return originalFunction();
+        }
+      }
+    }
+    exports$1.MongooseInstrumentation = MongooseInstrumentation;
+  })(mongoose);
+  return mongoose;
+}
+var hasRequiredSrc$d;
+function requireSrc$d() {
+  if (hasRequiredSrc$d) return src$d;
+  hasRequiredSrc$d = 1;
+  (function(exports$1) {
+    Object.defineProperty(exports$1, "__esModule", { value: true });
+    exports$1.MongooseInstrumentation = void 0;
+    var mongoose_1 = requireMongoose();
+    Object.defineProperty(exports$1, "MongooseInstrumentation", { enumerable: true, get: function() {
+      return mongoose_1.MongooseInstrumentation;
+    } });
+  })(src$d);
+  return src$d;
+}
+var srcExports$b = requireSrc$d();
+const INTEGRATION_NAME$f = "Mongoose";
+const instrumentMongoose = generateInstrumentOnce(
+  INTEGRATION_NAME$f,
+  () => new srcExports$b.MongooseInstrumentation({
+    responseHook(span) {
+      addOriginToSpan(span, "auto.db.otel.mongoose");
+    }
+  })
+);
+const _mongooseIntegration = (() => {
+  return {
+    name: INTEGRATION_NAME$f,
+    setupOnce() {
+      instrumentMongoose();
+    }
+  };
+});
+const mongooseIntegration = defineIntegration(_mongooseIntegration);
+var src$c = {};
+var instrumentation$a = {};
+var semconv$7 = {};
+var hasRequiredSemconv$7;
+function requireSemconv$7() {
+  if (hasRequiredSemconv$7) return semconv$7;
+  hasRequiredSemconv$7 = 1;
+  Object.defineProperty(semconv$7, "__esModule", { value: true });
+  semconv$7.METRIC_DB_CLIENT_CONNECTIONS_USAGE = semconv$7.DB_SYSTEM_VALUE_MYSQL = semconv$7.ATTR_NET_PEER_PORT = semconv$7.ATTR_NET_PEER_NAME = semconv$7.ATTR_DB_USER = semconv$7.ATTR_DB_SYSTEM = semconv$7.ATTR_DB_STATEMENT = semconv$7.ATTR_DB_NAME = semconv$7.ATTR_DB_CONNECTION_STRING = void 0;
+  semconv$7.ATTR_DB_CONNECTION_STRING = "db.connection_string";
+  semconv$7.ATTR_DB_NAME = "db.name";
+  semconv$7.ATTR_DB_STATEMENT = "db.statement";
+  semconv$7.ATTR_DB_SYSTEM = "db.system";
+  semconv$7.ATTR_DB_USER = "db.user";
+  semconv$7.ATTR_NET_PEER_NAME = "net.peer.name";
+  semconv$7.ATTR_NET_PEER_PORT = "net.peer.port";
+  semconv$7.DB_SYSTEM_VALUE_MYSQL = "mysql";
+  semconv$7.METRIC_DB_CLIENT_CONNECTIONS_USAGE = "db.client.connections.usage";
+  return semconv$7;
+}
+var AttributeNames$5 = {};
+var hasRequiredAttributeNames$4;
+function requireAttributeNames$4() {
+  if (hasRequiredAttributeNames$4) return AttributeNames$5;
+  hasRequiredAttributeNames$4 = 1;
+  (function(exports$1) {
+    Object.defineProperty(exports$1, "__esModule", { value: true });
+    exports$1.AttributeNames = void 0;
+    (function(AttributeNames2) {
+      AttributeNames2["MYSQL_VALUES"] = "db.mysql.values";
+    })(exports$1.AttributeNames || (exports$1.AttributeNames = {}));
+  })(AttributeNames$5);
+  return AttributeNames$5;
+}
+var utils$a = {};
+var hasRequiredUtils$a;
+function requireUtils$a() {
+  if (hasRequiredUtils$a) return utils$a;
+  hasRequiredUtils$a = 1;
+  Object.defineProperty(utils$a, "__esModule", { value: true });
+  utils$a.getPoolName = utils$a.arrayStringifyHelper = utils$a.getSpanName = utils$a.getDbValues = utils$a.getDbStatement = utils$a.getConnectionAttributes = void 0;
+  const semconv_1 = requireSemconv$7();
+  function getConnectionAttributes(config2) {
+    const { host, port, database, user } = getConfig(config2);
+    const portNumber = parseInt(port, 10);
+    if (!isNaN(portNumber)) {
+      return {
+        [semconv_1.ATTR_NET_PEER_NAME]: host,
+        [semconv_1.ATTR_NET_PEER_PORT]: portNumber,
+        [semconv_1.ATTR_DB_CONNECTION_STRING]: getJDBCString(host, port, database),
+        [semconv_1.ATTR_DB_NAME]: database,
+        [semconv_1.ATTR_DB_USER]: user
+      };
+    }
+    return {
+      [semconv_1.ATTR_NET_PEER_NAME]: host,
+      [semconv_1.ATTR_DB_CONNECTION_STRING]: getJDBCString(host, port, database),
+      [semconv_1.ATTR_DB_NAME]: database,
+      [semconv_1.ATTR_DB_USER]: user
+    };
+  }
+  utils$a.getConnectionAttributes = getConnectionAttributes;
+  function getConfig(config2) {
+    const { host, port, database, user } = config2 && config2.connectionConfig || config2 || {};
+    return { host, port, database, user };
+  }
+  function getJDBCString(host, port, database) {
+    let jdbcString = `jdbc:mysql://${host || "localhost"}`;
+    if (typeof port === "number") {
+      jdbcString += `:${port}`;
+    }
+    if (typeof database === "string") {
+      jdbcString += `/${database}`;
+    }
+    return jdbcString;
+  }
+  function getDbStatement(query) {
+    if (typeof query === "string") {
+      return query;
+    } else {
+      return query.sql;
+    }
+  }
+  utils$a.getDbStatement = getDbStatement;
+  function getDbValues(query, values) {
+    if (typeof query === "string") {
+      return arrayStringifyHelper(values);
+    } else {
+      return arrayStringifyHelper(values || query.values);
+    }
+  }
+  utils$a.getDbValues = getDbValues;
+  function getSpanName(query) {
+    const rawQuery = typeof query === "object" ? query.sql : query;
+    const firstSpace = rawQuery?.indexOf(" ");
+    if (typeof firstSpace === "number" && firstSpace !== -1) {
+      return rawQuery?.substring(0, firstSpace);
+    }
+    return rawQuery;
+  }
+  utils$a.getSpanName = getSpanName;
+  function arrayStringifyHelper(arr) {
+    if (arr)
+      return `[${arr.toString()}]`;
+    return "";
+  }
+  utils$a.arrayStringifyHelper = arrayStringifyHelper;
+  function getPoolName(pool) {
+    const c = pool.config.connectionConfig;
+    let poolName = "";
+    poolName += c.host ? `host: '${c.host}', ` : "";
+    poolName += c.port ? `port: ${c.port}, ` : "";
+    poolName += c.database ? `database: '${c.database}', ` : "";
+    poolName += c.user ? `user: '${c.user}'` : "";
+    if (!c.user) {
+      poolName = poolName.substring(0, poolName.length - 2);
+    }
+    return poolName.trim();
+  }
+  utils$a.getPoolName = getPoolName;
+  return utils$a;
+}
+var version$a = {};
+var hasRequiredVersion$a;
+function requireVersion$a() {
+  if (hasRequiredVersion$a) return version$a;
+  hasRequiredVersion$a = 1;
+  Object.defineProperty(version$a, "__esModule", { value: true });
+  version$a.PACKAGE_NAME = version$a.PACKAGE_VERSION = void 0;
+  version$a.PACKAGE_VERSION = "0.54.0";
+  version$a.PACKAGE_NAME = "@opentelemetry/instrumentation-mysql";
+  return version$a;
+}
+var hasRequiredInstrumentation$a;
+function requireInstrumentation$a() {
+  if (hasRequiredInstrumentation$a) return instrumentation$a;
+  hasRequiredInstrumentation$a = 1;
+  Object.defineProperty(instrumentation$a, "__esModule", { value: true });
+  instrumentation$a.MySQLInstrumentation = void 0;
+  const api_1 = /* @__PURE__ */ requireSrc$n();
+  const instrumentation_1 = require$$2;
+  const semconv_1 = requireSemconv$7();
+  const AttributeNames_1 = requireAttributeNames$4();
+  const utils_1 = requireUtils$a();
+  const version_1 = requireVersion$a();
+  class MySQLInstrumentation extends instrumentation_1.InstrumentationBase {
+    static COMMON_ATTRIBUTES = {
+      [semconv_1.ATTR_DB_SYSTEM]: semconv_1.DB_SYSTEM_VALUE_MYSQL
+    };
+    constructor(config2 = {}) {
+      super(version_1.PACKAGE_NAME, version_1.PACKAGE_VERSION, config2);
+    }
+    _updateMetricInstruments() {
+      this._connectionsUsage = this.meter.createUpDownCounter(semconv_1.METRIC_DB_CLIENT_CONNECTIONS_USAGE, {
+        description: "The number of connections that are currently in state described by the state attribute.",
+        unit: "{connection}"
+      });
+    }
+    init() {
+      return [
+        new instrumentation_1.InstrumentationNodeModuleDefinition("mysql", [">=2.0.0 <3"], (moduleExports) => {
+          if ((0, instrumentation_1.isWrapped)(moduleExports.createConnection)) {
+            this._unwrap(moduleExports, "createConnection");
+          }
+          this._wrap(moduleExports, "createConnection", this._patchCreateConnection());
+          if ((0, instrumentation_1.isWrapped)(moduleExports.createPool)) {
+            this._unwrap(moduleExports, "createPool");
+          }
+          this._wrap(moduleExports, "createPool", this._patchCreatePool());
+          if ((0, instrumentation_1.isWrapped)(moduleExports.createPoolCluster)) {
+            this._unwrap(moduleExports, "createPoolCluster");
+          }
+          this._wrap(moduleExports, "createPoolCluster", this._patchCreatePoolCluster());
+          return moduleExports;
+        }, (moduleExports) => {
+          if (moduleExports === void 0)
+            return;
+          this._unwrap(moduleExports, "createConnection");
+          this._unwrap(moduleExports, "createPool");
+          this._unwrap(moduleExports, "createPoolCluster");
+        })
+      ];
+    }
+    // global export function
+    _patchCreateConnection() {
+      return (originalCreateConnection) => {
+        const thisPlugin = this;
+        return function createConnection(_connectionUri) {
+          const originalResult = originalCreateConnection(...arguments);
+          thisPlugin._wrap(originalResult, "query", thisPlugin._patchQuery(originalResult));
+          return originalResult;
+        };
+      };
+    }
+    // global export function
+    _patchCreatePool() {
+      return (originalCreatePool) => {
+        const thisPlugin = this;
+        return function createPool(_config) {
+          const pool = originalCreatePool(...arguments);
+          thisPlugin._wrap(pool, "query", thisPlugin._patchQuery(pool));
+          thisPlugin._wrap(pool, "getConnection", thisPlugin._patchGetConnection(pool));
+          thisPlugin._wrap(pool, "end", thisPlugin._patchPoolEnd(pool));
+          thisPlugin._setPoolcallbacks(pool, thisPlugin, "");
+          return pool;
+        };
+      };
+    }
+    _patchPoolEnd(pool) {
+      return (originalPoolEnd) => {
+        const thisPlugin = this;
+        return function end(callback) {
+          const nAll = pool._allConnections.length;
+          const nFree = pool._freeConnections.length;
+          const nUsed = nAll - nFree;
+          const poolName = (0, utils_1.getPoolName)(pool);
+          thisPlugin._connectionsUsage.add(-nUsed, {
+            state: "used",
+            name: poolName
+          });
+          thisPlugin._connectionsUsage.add(-nFree, {
+            state: "idle",
+            name: poolName
+          });
+          originalPoolEnd.apply(pool, arguments);
+        };
+      };
+    }
+    // global export function
+    _patchCreatePoolCluster() {
+      return (originalCreatePoolCluster) => {
+        const thisPlugin = this;
+        return function createPool(_config) {
+          const cluster = originalCreatePoolCluster(...arguments);
+          thisPlugin._wrap(cluster, "getConnection", thisPlugin._patchGetConnection(cluster));
+          thisPlugin._wrap(cluster, "add", thisPlugin._patchAdd(cluster));
+          return cluster;
+        };
+      };
+    }
+    _patchAdd(cluster) {
+      return (originalAdd) => {
+        const thisPlugin = this;
+        return function add(id, config2) {
+          if (!thisPlugin["_enabled"]) {
+            thisPlugin._unwrap(cluster, "add");
+            return originalAdd.apply(cluster, arguments);
+          }
+          originalAdd.apply(cluster, arguments);
+          const nodes = cluster["_nodes"];
+          if (nodes) {
+            const nodeId = typeof id === "object" ? "CLUSTER::" + cluster._lastId : String(id);
+            const pool = nodes[nodeId].pool;
+            thisPlugin._setPoolcallbacks(pool, thisPlugin, id);
+          }
+        };
+      };
+    }
+    // method on cluster or pool
+    _patchGetConnection(pool) {
+      return (originalGetConnection) => {
+        const thisPlugin = this;
+        return function getConnection(arg1, arg2, arg3) {
+          if (!thisPlugin["_enabled"]) {
+            thisPlugin._unwrap(pool, "getConnection");
+            return originalGetConnection.apply(pool, arguments);
+          }
+          if (arguments.length === 1 && typeof arg1 === "function") {
+            const patchFn = thisPlugin._getConnectionCallbackPatchFn(arg1);
+            return originalGetConnection.call(pool, patchFn);
+          }
+          if (arguments.length === 2 && typeof arg2 === "function") {
+            const patchFn = thisPlugin._getConnectionCallbackPatchFn(arg2);
+            return originalGetConnection.call(pool, arg1, patchFn);
+          }
+          if (arguments.length === 3 && typeof arg3 === "function") {
+            const patchFn = thisPlugin._getConnectionCallbackPatchFn(arg3);
+            return originalGetConnection.call(pool, arg1, arg2, patchFn);
+          }
+          return originalGetConnection.apply(pool, arguments);
+        };
+      };
+    }
+    _getConnectionCallbackPatchFn(cb) {
+      const thisPlugin = this;
+      const activeContext = api_1.context.active();
+      return function(err, connection) {
+        if (connection) {
+          if (!(0, instrumentation_1.isWrapped)(connection.query)) {
+            thisPlugin._wrap(connection, "query", thisPlugin._patchQuery(connection));
+          }
+        }
+        if (typeof cb === "function") {
+          api_1.context.with(activeContext, cb, this, err, connection);
+        }
+      };
+    }
+    _patchQuery(connection) {
+      return (originalQuery) => {
+        const thisPlugin = this;
+        return function query(query, _valuesOrCallback, _callback) {
+          if (!thisPlugin["_enabled"]) {
+            thisPlugin._unwrap(connection, "query");
+            return originalQuery.apply(connection, arguments);
+          }
+          const span = thisPlugin.tracer.startSpan((0, utils_1.getSpanName)(query), {
+            kind: api_1.SpanKind.CLIENT,
+            attributes: {
+              ...MySQLInstrumentation.COMMON_ATTRIBUTES,
+              ...(0, utils_1.getConnectionAttributes)(connection.config)
+            }
+          });
+          span.setAttribute(semconv_1.ATTR_DB_STATEMENT, (0, utils_1.getDbStatement)(query));
+          if (thisPlugin.getConfig().enhancedDatabaseReporting) {
+            let values;
+            if (Array.isArray(_valuesOrCallback)) {
+              values = _valuesOrCallback;
+            } else if (arguments[2]) {
+              values = [_valuesOrCallback];
+            }
+            span.setAttribute(AttributeNames_1.AttributeNames.MYSQL_VALUES, (0, utils_1.getDbValues)(query, values));
+          }
+          const cbIndex = Array.from(arguments).findIndex((arg) => typeof arg === "function");
+          const parentContext = api_1.context.active();
+          if (cbIndex === -1) {
+            const streamableQuery = api_1.context.with(api_1.trace.setSpan(api_1.context.active(), span), () => {
+              return originalQuery.apply(connection, arguments);
+            });
+            api_1.context.bind(parentContext, streamableQuery);
+            return streamableQuery.on("error", (err) => span.setStatus({
+              code: api_1.SpanStatusCode.ERROR,
+              message: err.message
+            })).on("end", () => {
+              span.end();
+            });
+          } else {
+            thisPlugin._wrap(arguments, cbIndex, thisPlugin._patchCallbackQuery(span, parentContext));
+            return api_1.context.with(api_1.trace.setSpan(api_1.context.active(), span), () => {
+              return originalQuery.apply(connection, arguments);
+            });
+          }
+        };
+      };
+    }
+    _patchCallbackQuery(span, parentContext) {
+      return (originalCallback) => {
+        return function(err, results, fields) {
+          if (err) {
+            span.setStatus({
+              code: api_1.SpanStatusCode.ERROR,
+              message: err.message
+            });
+          }
+          span.end();
+          return api_1.context.with(parentContext, () => originalCallback(...arguments));
+        };
+      };
+    }
+    _setPoolcallbacks(pool, thisPlugin, id) {
+      const poolName = id || (0, utils_1.getPoolName)(pool);
+      pool.on("connection", (connection) => {
+        thisPlugin._connectionsUsage.add(1, {
+          state: "idle",
+          name: poolName
+        });
+      });
+      pool.on("acquire", (connection) => {
+        thisPlugin._connectionsUsage.add(-1, {
+          state: "idle",
+          name: poolName
+        });
+        thisPlugin._connectionsUsage.add(1, {
+          state: "used",
+          name: poolName
+        });
+      });
+      pool.on("release", (connection) => {
+        thisPlugin._connectionsUsage.add(-1, {
+          state: "used",
+          name: poolName
+        });
+        thisPlugin._connectionsUsage.add(1, {
+          state: "idle",
+          name: poolName
+        });
+      });
+    }
+  }
+  instrumentation$a.MySQLInstrumentation = MySQLInstrumentation;
+  return instrumentation$a;
+}
+var hasRequiredSrc$c;
+function requireSrc$c() {
+  if (hasRequiredSrc$c) return src$c;
+  hasRequiredSrc$c = 1;
+  (function(exports$1) {
+    Object.defineProperty(exports$1, "__esModule", { value: true });
+    exports$1.MySQLInstrumentation = void 0;
+    var instrumentation_1 = requireInstrumentation$a();
+    Object.defineProperty(exports$1, "MySQLInstrumentation", { enumerable: true, get: function() {
+      return instrumentation_1.MySQLInstrumentation;
+    } });
+  })(src$c);
+  return src$c;
+}
+var srcExports$a = requireSrc$c();
+const INTEGRATION_NAME$e = "Mysql";
+const instrumentMysql = generateInstrumentOnce(INTEGRATION_NAME$e, () => new srcExports$a.MySQLInstrumentation({}));
+const _mysqlIntegration = (() => {
+  return {
+    name: INTEGRATION_NAME$e,
+    setupOnce() {
+      instrumentMysql();
+    }
+  };
+});
+const mysqlIntegration = defineIntegration(_mysqlIntegration);
+var src$b = {};
+var instrumentation$9 = {};
+var semconv$6 = {};
+var hasRequiredSemconv$6;
+function requireSemconv$6() {
+  if (hasRequiredSemconv$6) return semconv$6;
+  hasRequiredSemconv$6 = 1;
+  Object.defineProperty(semconv$6, "__esModule", { value: true });
+  semconv$6.DB_SYSTEM_VALUE_MYSQL = semconv$6.ATTR_NET_PEER_PORT = semconv$6.ATTR_NET_PEER_NAME = semconv$6.ATTR_DB_USER = semconv$6.ATTR_DB_SYSTEM = semconv$6.ATTR_DB_STATEMENT = semconv$6.ATTR_DB_NAME = semconv$6.ATTR_DB_CONNECTION_STRING = void 0;
+  semconv$6.ATTR_DB_CONNECTION_STRING = "db.connection_string";
+  semconv$6.ATTR_DB_NAME = "db.name";
+  semconv$6.ATTR_DB_STATEMENT = "db.statement";
+  semconv$6.ATTR_DB_SYSTEM = "db.system";
+  semconv$6.ATTR_DB_USER = "db.user";
+  semconv$6.ATTR_NET_PEER_NAME = "net.peer.name";
+  semconv$6.ATTR_NET_PEER_PORT = "net.peer.port";
+  semconv$6.DB_SYSTEM_VALUE_MYSQL = "mysql";
+  return semconv$6;
+}
+var src$a = {};
+var hasRequiredSrc$b;
+function requireSrc$b() {
+  if (hasRequiredSrc$b) return src$a;
+  hasRequiredSrc$b = 1;
+  Object.defineProperty(src$a, "__esModule", { value: true });
+  src$a.addSqlCommenterComment = void 0;
+  const api_1 = /* @__PURE__ */ requireSrc$n();
+  const core_1 = require$$1;
+  function hasValidSqlComment(query) {
+    const indexOpeningDashDashComment = query.indexOf("--");
+    if (indexOpeningDashDashComment >= 0) {
+      return true;
+    }
+    const indexOpeningSlashComment = query.indexOf("/*");
+    if (indexOpeningSlashComment < 0) {
+      return false;
+    }
+    const indexClosingSlashComment = query.indexOf("*/");
+    return indexOpeningDashDashComment < indexClosingSlashComment;
+  }
+  function fixedEncodeURIComponent(str) {
+    return encodeURIComponent(str).replace(/[!'()*]/g, (c) => `%${c.charCodeAt(0).toString(16).toUpperCase()}`);
+  }
+  function addSqlCommenterComment(span, query) {
+    if (typeof query !== "string" || query.length === 0) {
+      return query;
+    }
+    if (hasValidSqlComment(query)) {
+      return query;
+    }
+    const propagator2 = new core_1.W3CTraceContextPropagator();
+    const headers = {};
+    propagator2.inject(api_1.trace.setSpan(api_1.ROOT_CONTEXT, span), headers, api_1.defaultTextMapSetter);
+    const sortedKeys = Object.keys(headers).sort();
+    if (sortedKeys.length === 0) {
+      return query;
+    }
+    const commentString = sortedKeys.map((key) => {
+      const encodedValue = fixedEncodeURIComponent(headers[key]);
+      return `${key}='${encodedValue}'`;
+    }).join(",");
+    return `${query} /*${commentString}*/`;
+  }
+  src$a.addSqlCommenterComment = addSqlCommenterComment;
+  return src$a;
+}
+var utils$9 = {};
+var hasRequiredUtils$9;
+function requireUtils$9() {
+  if (hasRequiredUtils$9) return utils$9;
+  hasRequiredUtils$9 = 1;
+  Object.defineProperty(utils$9, "__esModule", { value: true });
+  utils$9.getConnectionPrototypeToInstrument = utils$9.once = utils$9.getSpanName = utils$9.getQueryText = utils$9.getConnectionAttributes = void 0;
+  const semconv_1 = requireSemconv$6();
+  const instrumentation_1 = require$$2;
+  const semantic_conventions_1 = /* @__PURE__ */ requireSrc$m();
+  function getConnectionAttributes(config2, dbSemconvStability, netSemconvStability) {
+    const { host, port, database, user } = getConfig(config2);
+    const attrs = {};
+    if (dbSemconvStability & instrumentation_1.SemconvStability.OLD) {
+      attrs[semconv_1.ATTR_DB_CONNECTION_STRING] = getJDBCString(host, port, database);
+      attrs[semconv_1.ATTR_DB_NAME] = database;
+      attrs[semconv_1.ATTR_DB_USER] = user;
+    }
+    if (dbSemconvStability & instrumentation_1.SemconvStability.STABLE) {
+      attrs[semantic_conventions_1.ATTR_DB_NAMESPACE] = database;
+    }
+    const portNumber = parseInt(port, 10);
+    if (netSemconvStability & instrumentation_1.SemconvStability.OLD) {
+      attrs[semconv_1.ATTR_NET_PEER_NAME] = host;
+      if (!isNaN(portNumber)) {
+        attrs[semconv_1.ATTR_NET_PEER_PORT] = portNumber;
+      }
+    }
+    if (netSemconvStability & instrumentation_1.SemconvStability.STABLE) {
+      attrs[semantic_conventions_1.ATTR_SERVER_ADDRESS] = host;
+      if (!isNaN(portNumber)) {
+        attrs[semantic_conventions_1.ATTR_SERVER_PORT] = portNumber;
+      }
+    }
+    return attrs;
+  }
+  utils$9.getConnectionAttributes = getConnectionAttributes;
+  function getConfig(config2) {
+    const { host, port, database, user } = config2 && config2.connectionConfig || config2 || {};
+    return { host, port, database, user };
+  }
+  function getJDBCString(host, port, database) {
+    let jdbcString = `jdbc:mysql://${host || "localhost"}`;
+    if (typeof port === "number") {
+      jdbcString += `:${port}`;
+    }
+    if (typeof database === "string") {
+      jdbcString += `/${database}`;
+    }
+    return jdbcString;
+  }
+  function getQueryText(query, format, values, maskStatement = false, maskStatementHook = defaultMaskingHook) {
+    const [querySql, queryValues] = typeof query === "string" ? [query, values] : [query.sql, hasValues(query) ? values || query.values : values];
+    try {
+      if (maskStatement) {
+        return maskStatementHook(querySql);
+      } else if (format && queryValues) {
+        return format(querySql, queryValues);
+      } else {
+        return querySql;
+      }
+    } catch (e) {
+      return "Could not determine the query due to an error in masking or formatting";
+    }
+  }
+  utils$9.getQueryText = getQueryText;
+  function defaultMaskingHook(query) {
+    return query.replace(/\b\d+\b/g, "?").replace(/(["'])(?:(?=(\\?))\2.)*?\1/g, "?");
+  }
+  function hasValues(obj) {
+    return "values" in obj;
+  }
+  function getSpanName(query) {
+    const rawQuery = typeof query === "object" ? query.sql : query;
+    const firstSpace = rawQuery?.indexOf(" ");
+    if (typeof firstSpace === "number" && firstSpace !== -1) {
+      return rawQuery?.substring(0, firstSpace);
+    }
+    return rawQuery;
+  }
+  utils$9.getSpanName = getSpanName;
+  const once = (fn) => {
+    let called = false;
+    return (...args) => {
+      if (called)
+        return;
+      called = true;
+      return fn(...args);
+    };
+  };
+  utils$9.once = once;
+  function getConnectionPrototypeToInstrument(connection) {
+    const connectionPrototype = connection.prototype;
+    const basePrototype = Object.getPrototypeOf(connectionPrototype);
+    if (typeof basePrototype?.query === "function" && typeof basePrototype?.execute === "function") {
+      return basePrototype;
+    }
+    return connectionPrototype;
+  }
+  utils$9.getConnectionPrototypeToInstrument = getConnectionPrototypeToInstrument;
+  return utils$9;
+}
+var version$9 = {};
+var hasRequiredVersion$9;
+function requireVersion$9() {
+  if (hasRequiredVersion$9) return version$9;
+  hasRequiredVersion$9 = 1;
+  Object.defineProperty(version$9, "__esModule", { value: true });
+  version$9.PACKAGE_NAME = version$9.PACKAGE_VERSION = void 0;
+  version$9.PACKAGE_VERSION = "0.55.0";
+  version$9.PACKAGE_NAME = "@opentelemetry/instrumentation-mysql2";
+  return version$9;
+}
+var hasRequiredInstrumentation$9;
+function requireInstrumentation$9() {
+  if (hasRequiredInstrumentation$9) return instrumentation$9;
+  hasRequiredInstrumentation$9 = 1;
+  Object.defineProperty(instrumentation$9, "__esModule", { value: true });
+  instrumentation$9.MySQL2Instrumentation = void 0;
+  const api = /* @__PURE__ */ requireSrc$n();
+  const instrumentation_1 = require$$2;
+  const semconv_1 = requireSemconv$6();
+  const sql_common_1 = requireSrc$b();
+  const utils_1 = requireUtils$9();
+  const version_1 = requireVersion$9();
+  const semantic_conventions_1 = /* @__PURE__ */ requireSrc$m();
+  const supportedVersions2 = [">=1.4.2 <4"];
+  class MySQL2Instrumentation extends instrumentation_1.InstrumentationBase {
+    _netSemconvStability;
+    _dbSemconvStability;
+    constructor(config2 = {}) {
+      super(version_1.PACKAGE_NAME, version_1.PACKAGE_VERSION, config2);
+      this._setSemconvStabilityFromEnv();
+    }
+    // Used for testing.
+    _setSemconvStabilityFromEnv() {
+      this._netSemconvStability = (0, instrumentation_1.semconvStabilityFromStr)("http", process.env.OTEL_SEMCONV_STABILITY_OPT_IN);
+      this._dbSemconvStability = (0, instrumentation_1.semconvStabilityFromStr)("database", process.env.OTEL_SEMCONV_STABILITY_OPT_IN);
+    }
+    init() {
+      let format;
+      function setFormatFunction(moduleExports) {
+        if (!format && moduleExports.format) {
+          format = moduleExports.format;
+        }
+      }
+      const patch = (ConnectionPrototype) => {
+        if ((0, instrumentation_1.isWrapped)(ConnectionPrototype.query)) {
+          this._unwrap(ConnectionPrototype, "query");
+        }
+        this._wrap(ConnectionPrototype, "query", this._patchQuery(format, false));
+        if ((0, instrumentation_1.isWrapped)(ConnectionPrototype.execute)) {
+          this._unwrap(ConnectionPrototype, "execute");
+        }
+        this._wrap(ConnectionPrototype, "execute", this._patchQuery(format, true));
+      };
+      const unpatch = (ConnectionPrototype) => {
+        this._unwrap(ConnectionPrototype, "query");
+        this._unwrap(ConnectionPrototype, "execute");
+      };
+      return [
+        new instrumentation_1.InstrumentationNodeModuleDefinition("mysql2", supportedVersions2, (moduleExports) => {
+          setFormatFunction(moduleExports);
+          return moduleExports;
+        }, () => {
+        }, [
+          new instrumentation_1.InstrumentationNodeModuleFile("mysql2/promise.js", supportedVersions2, (moduleExports) => {
+            setFormatFunction(moduleExports);
+            return moduleExports;
+          }, () => {
+          }),
+          new instrumentation_1.InstrumentationNodeModuleFile("mysql2/lib/connection.js", supportedVersions2, (moduleExports) => {
+            const ConnectionPrototype = (0, utils_1.getConnectionPrototypeToInstrument)(moduleExports);
+            patch(ConnectionPrototype);
+            return moduleExports;
+          }, (moduleExports) => {
+            if (moduleExports === void 0)
+              return;
+            const ConnectionPrototype = (0, utils_1.getConnectionPrototypeToInstrument)(moduleExports);
+            unpatch(ConnectionPrototype);
+          })
+        ])
+      ];
+    }
+    _patchQuery(format, isPrepared) {
+      return (originalQuery) => {
+        const thisPlugin = this;
+        return function query(query, _valuesOrCallback, _callback) {
+          let values;
+          if (Array.isArray(_valuesOrCallback)) {
+            values = _valuesOrCallback;
+          } else if (arguments[2]) {
+            values = [_valuesOrCallback];
+          }
+          const { maskStatement, maskStatementHook, responseHook } = thisPlugin.getConfig();
+          const attributes = (0, utils_1.getConnectionAttributes)(this.config, thisPlugin._dbSemconvStability, thisPlugin._netSemconvStability);
+          const dbQueryText = (0, utils_1.getQueryText)(query, format, values, maskStatement, maskStatementHook);
+          if (thisPlugin._dbSemconvStability & instrumentation_1.SemconvStability.OLD) {
+            attributes[semconv_1.ATTR_DB_SYSTEM] = semconv_1.DB_SYSTEM_VALUE_MYSQL;
+            attributes[semconv_1.ATTR_DB_STATEMENT] = dbQueryText;
+          }
+          if (thisPlugin._dbSemconvStability & instrumentation_1.SemconvStability.STABLE) {
+            attributes[semantic_conventions_1.ATTR_DB_SYSTEM_NAME] = semantic_conventions_1.DB_SYSTEM_NAME_VALUE_MYSQL;
+            attributes[semantic_conventions_1.ATTR_DB_QUERY_TEXT] = dbQueryText;
+          }
+          const span = thisPlugin.tracer.startSpan((0, utils_1.getSpanName)(query), {
+            kind: api.SpanKind.CLIENT,
+            attributes
+          });
+          if (!isPrepared && thisPlugin.getConfig().addSqlCommenterCommentToQueries) {
+            arguments[0] = query = typeof query === "string" ? (0, sql_common_1.addSqlCommenterComment)(span, query) : Object.assign(query, {
+              sql: (0, sql_common_1.addSqlCommenterComment)(span, query.sql)
+            });
+          }
+          const endSpan2 = (0, utils_1.once)((err, results) => {
+            if (err) {
+              span.setStatus({
+                code: api.SpanStatusCode.ERROR,
+                message: err.message
+              });
+            } else {
+              if (typeof responseHook === "function") {
+                (0, instrumentation_1.safeExecuteInTheMiddle)(() => {
+                  responseHook(span, {
+                    queryResults: results
+                  });
+                }, (err2) => {
+                  if (err2) {
+                    thisPlugin._diag.warn("Failed executing responseHook", err2);
+                  }
+                }, true);
+              }
+            }
+            span.end();
+          });
+          if (arguments.length === 1) {
+            if (typeof query.onResult === "function") {
+              thisPlugin._wrap(query, "onResult", thisPlugin._patchCallbackQuery(endSpan2));
+            }
+            const streamableQuery = originalQuery.apply(this, arguments);
+            streamableQuery.once("error", (err) => {
+              endSpan2(err);
+            }).once("result", (results) => {
+              endSpan2(void 0, results);
+            });
+            return streamableQuery;
+          }
+          if (typeof arguments[1] === "function") {
+            thisPlugin._wrap(arguments, 1, thisPlugin._patchCallbackQuery(endSpan2));
+          } else if (typeof arguments[2] === "function") {
+            thisPlugin._wrap(arguments, 2, thisPlugin._patchCallbackQuery(endSpan2));
+          }
+          return originalQuery.apply(this, arguments);
+        };
+      };
+    }
+    _patchCallbackQuery(endSpan2) {
+      return (originalCallback) => {
+        return function(err, results, fields) {
+          endSpan2(err, results);
+          return originalCallback(...arguments);
+        };
+      };
+    }
+  }
+  instrumentation$9.MySQL2Instrumentation = MySQL2Instrumentation;
+  return instrumentation$9;
+}
+var hasRequiredSrc$a;
+function requireSrc$a() {
+  if (hasRequiredSrc$a) return src$b;
+  hasRequiredSrc$a = 1;
+  (function(exports$1) {
+    Object.defineProperty(exports$1, "__esModule", { value: true });
+    exports$1.MySQL2Instrumentation = void 0;
+    var instrumentation_1 = requireInstrumentation$9();
+    Object.defineProperty(exports$1, "MySQL2Instrumentation", { enumerable: true, get: function() {
+      return instrumentation_1.MySQL2Instrumentation;
+    } });
+  })(src$b);
+  return src$b;
+}
+var srcExports$9 = requireSrc$a();
+const INTEGRATION_NAME$d = "Mysql2";
+const instrumentMysql2 = generateInstrumentOnce(
+  INTEGRATION_NAME$d,
+  () => new srcExports$9.MySQL2Instrumentation({
+    responseHook(span) {
+      addOriginToSpan(span, "auto.db.otel.mysql2");
+    }
+  })
+);
+const _mysql2Integration = (() => {
+  return {
+    name: INTEGRATION_NAME$d,
+    setupOnce() {
+      instrumentMysql2();
+    }
+  };
+});
+const mysql2Integration = defineIntegration(_mysql2Integration);
+var src$9 = {};
+var instrumentation$8 = {};
+var semconv$5 = {};
+var hasRequiredSemconv$5;
+function requireSemconv$5() {
+  if (hasRequiredSemconv$5) return semconv$5;
+  hasRequiredSemconv$5 = 1;
+  Object.defineProperty(semconv$5, "__esModule", { value: true });
+  semconv$5.DB_SYSTEM_VALUE_REDIS = semconv$5.ATTR_NET_PEER_PORT = semconv$5.ATTR_NET_PEER_NAME = semconv$5.ATTR_DB_SYSTEM = semconv$5.ATTR_DB_STATEMENT = semconv$5.ATTR_DB_CONNECTION_STRING = void 0;
+  semconv$5.ATTR_DB_CONNECTION_STRING = "db.connection_string";
+  semconv$5.ATTR_DB_STATEMENT = "db.statement";
+  semconv$5.ATTR_DB_SYSTEM = "db.system";
+  semconv$5.ATTR_NET_PEER_NAME = "net.peer.name";
+  semconv$5.ATTR_NET_PEER_PORT = "net.peer.port";
+  semconv$5.DB_SYSTEM_VALUE_REDIS = "redis";
+  return semconv$5;
+}
+var utils$8 = {};
+var hasRequiredUtils$8;
+function requireUtils$8() {
+  if (hasRequiredUtils$8) return utils$8;
+  hasRequiredUtils$8 = 1;
+  Object.defineProperty(utils$8, "__esModule", { value: true });
+  utils$8.endSpan = void 0;
+  const api_1 = /* @__PURE__ */ requireSrc$n();
+  const endSpan2 = (span, err) => {
+    if (err) {
+      span.recordException(err);
+      span.setStatus({
+        code: api_1.SpanStatusCode.ERROR,
+        message: err.message
+      });
+    }
+    span.end();
+  };
+  utils$8.endSpan = endSpan2;
+  return utils$8;
+}
+var src$8 = {};
+var hasRequiredSrc$9;
+function requireSrc$9() {
+  if (hasRequiredSrc$9) return src$8;
+  hasRequiredSrc$9 = 1;
+  Object.defineProperty(src$8, "__esModule", { value: true });
+  src$8.defaultDbStatementSerializer = void 0;
+  const serializationSubsets = [
+    {
+      regex: /^ECHO/i,
+      args: 0
+    },
+    {
+      regex: /^(LPUSH|MSET|PFA|PUBLISH|RPUSH|SADD|SET|SPUBLISH|XADD|ZADD)/i,
+      args: 1
+    },
+    {
+      regex: /^(HSET|HMSET|LSET|LINSERT)/i,
+      args: 2
+    },
+    {
+      regex: /^(ACL|BIT|B[LRZ]|CLIENT|CLUSTER|CONFIG|COMMAND|DECR|DEL|EVAL|EX|FUNCTION|GEO|GET|HINCR|HMGET|HSCAN|INCR|L[TRLM]|MEMORY|P[EFISTU]|RPOP|S[CDIMORSU]|XACK|X[CDGILPRT]|Z[CDILMPRS])/i,
+      args: -1
+    }
+  ];
+  const defaultDbStatementSerializer = (cmdName, cmdArgs) => {
+    if (Array.isArray(cmdArgs) && cmdArgs.length) {
+      const nArgsToSerialize = serializationSubsets.find(({ regex }) => {
+        return regex.test(cmdName);
+      })?.args ?? 0;
+      const argsToSerialize = nArgsToSerialize >= 0 ? cmdArgs.slice(0, nArgsToSerialize) : cmdArgs;
+      if (cmdArgs.length > argsToSerialize.length) {
+        argsToSerialize.push(`[${cmdArgs.length - nArgsToSerialize} other arguments]`);
+      }
+      return `${cmdName} ${argsToSerialize.join(" ")}`;
+    }
+    return cmdName;
+  };
+  src$8.defaultDbStatementSerializer = defaultDbStatementSerializer;
+  return src$8;
+}
+var version$8 = {};
+var hasRequiredVersion$8;
+function requireVersion$8() {
+  if (hasRequiredVersion$8) return version$8;
+  hasRequiredVersion$8 = 1;
+  Object.defineProperty(version$8, "__esModule", { value: true });
+  version$8.PACKAGE_NAME = version$8.PACKAGE_VERSION = void 0;
+  version$8.PACKAGE_VERSION = "0.56.0";
+  version$8.PACKAGE_NAME = "@opentelemetry/instrumentation-ioredis";
+  return version$8;
+}
+var hasRequiredInstrumentation$8;
+function requireInstrumentation$8() {
+  if (hasRequiredInstrumentation$8) return instrumentation$8;
+  hasRequiredInstrumentation$8 = 1;
+  Object.defineProperty(instrumentation$8, "__esModule", { value: true });
+  instrumentation$8.IORedisInstrumentation = void 0;
+  const api_1 = /* @__PURE__ */ requireSrc$n();
+  const instrumentation_1 = require$$2;
+  const semconv_1 = requireSemconv$5();
+  const instrumentation_2 = require$$2;
+  const utils_1 = requireUtils$8();
+  const redis_common_1 = requireSrc$9();
+  const version_1 = requireVersion$8();
+  const DEFAULT_CONFIG = {
+    requireParentSpan: true
+  };
+  class IORedisInstrumentation extends instrumentation_1.InstrumentationBase {
+    constructor(config2 = {}) {
+      super(version_1.PACKAGE_NAME, version_1.PACKAGE_VERSION, { ...DEFAULT_CONFIG, ...config2 });
+    }
+    setConfig(config2 = {}) {
+      super.setConfig({ ...DEFAULT_CONFIG, ...config2 });
+    }
+    init() {
+      return [
+        new instrumentation_1.InstrumentationNodeModuleDefinition("ioredis", [">=2.0.0 <6"], (module2, moduleVersion) => {
+          const moduleExports = module2[Symbol.toStringTag] === "Module" ? module2.default : module2;
+          if ((0, instrumentation_1.isWrapped)(moduleExports.prototype.sendCommand)) {
+            this._unwrap(moduleExports.prototype, "sendCommand");
+          }
+          this._wrap(moduleExports.prototype, "sendCommand", this._patchSendCommand(moduleVersion));
+          if ((0, instrumentation_1.isWrapped)(moduleExports.prototype.connect)) {
+            this._unwrap(moduleExports.prototype, "connect");
+          }
+          this._wrap(moduleExports.prototype, "connect", this._patchConnection());
+          return module2;
+        }, (module2) => {
+          if (module2 === void 0)
+            return;
+          const moduleExports = module2[Symbol.toStringTag] === "Module" ? module2.default : module2;
+          this._unwrap(moduleExports.prototype, "sendCommand");
+          this._unwrap(moduleExports.prototype, "connect");
+        })
+      ];
+    }
+    /**
+     * Patch send command internal to trace requests
+     */
+    _patchSendCommand(moduleVersion) {
+      return (original) => {
+        return this._traceSendCommand(original, moduleVersion);
+      };
+    }
+    _patchConnection() {
+      return (original) => {
+        return this._traceConnection(original);
+      };
+    }
+    _traceSendCommand(original, moduleVersion) {
+      const instrumentation2 = this;
+      return function(cmd) {
+        if (arguments.length < 1 || typeof cmd !== "object") {
+          return original.apply(this, arguments);
+        }
+        const config2 = instrumentation2.getConfig();
+        const dbStatementSerializer = config2.dbStatementSerializer || redis_common_1.defaultDbStatementSerializer;
+        const hasNoParentSpan = api_1.trace.getSpan(api_1.context.active()) === void 0;
+        if (config2.requireParentSpan === true && hasNoParentSpan) {
+          return original.apply(this, arguments);
+        }
+        const span = instrumentation2.tracer.startSpan(cmd.name, {
+          kind: api_1.SpanKind.CLIENT,
+          attributes: {
+            [semconv_1.ATTR_DB_SYSTEM]: semconv_1.DB_SYSTEM_VALUE_REDIS,
+            [semconv_1.ATTR_DB_STATEMENT]: dbStatementSerializer(cmd.name, cmd.args)
+          }
+        });
+        const { requestHook: requestHook2 } = config2;
+        if (requestHook2) {
+          (0, instrumentation_2.safeExecuteInTheMiddle)(() => requestHook2(span, {
+            moduleVersion,
+            cmdName: cmd.name,
+            cmdArgs: cmd.args
+          }), (e) => {
+            if (e) {
+              api_1.diag.error("ioredis instrumentation: request hook failed", e);
+            }
+          }, true);
+        }
+        const { host, port } = this.options;
+        span.setAttributes({
+          [semconv_1.ATTR_NET_PEER_NAME]: host,
+          [semconv_1.ATTR_NET_PEER_PORT]: port,
+          [semconv_1.ATTR_DB_CONNECTION_STRING]: `redis://${host}:${port}`
+        });
+        try {
+          const result = original.apply(this, arguments);
+          const origResolve = cmd.resolve;
+          cmd.resolve = function(result2) {
+            (0, instrumentation_2.safeExecuteInTheMiddle)(() => config2.responseHook?.(span, cmd.name, cmd.args, result2), (e) => {
+              if (e) {
+                api_1.diag.error("ioredis instrumentation: response hook failed", e);
+              }
+            }, true);
+            (0, utils_1.endSpan)(span, null);
+            origResolve(result2);
+          };
+          const origReject = cmd.reject;
+          cmd.reject = function(err) {
+            (0, utils_1.endSpan)(span, err);
+            origReject(err);
+          };
+          return result;
+        } catch (error2) {
+          (0, utils_1.endSpan)(span, error2);
+          throw error2;
+        }
+      };
+    }
+    _traceConnection(original) {
+      const instrumentation2 = this;
+      return function() {
+        const hasNoParentSpan = api_1.trace.getSpan(api_1.context.active()) === void 0;
+        if (instrumentation2.getConfig().requireParentSpan === true && hasNoParentSpan) {
+          return original.apply(this, arguments);
+        }
+        const span = instrumentation2.tracer.startSpan("connect", {
+          kind: api_1.SpanKind.CLIENT,
+          attributes: {
+            [semconv_1.ATTR_DB_SYSTEM]: semconv_1.DB_SYSTEM_VALUE_REDIS,
+            [semconv_1.ATTR_DB_STATEMENT]: "connect"
+          }
+        });
+        const { host, port } = this.options;
+        span.setAttributes({
+          [semconv_1.ATTR_NET_PEER_NAME]: host,
+          [semconv_1.ATTR_NET_PEER_PORT]: port,
+          [semconv_1.ATTR_DB_CONNECTION_STRING]: `redis://${host}:${port}`
+        });
+        try {
+          const client = original.apply(this, arguments);
+          (0, utils_1.endSpan)(span, null);
+          return client;
+        } catch (error2) {
+          (0, utils_1.endSpan)(span, error2);
+          throw error2;
+        }
+      };
+    }
+  }
+  instrumentation$8.IORedisInstrumentation = IORedisInstrumentation;
+  return instrumentation$8;
+}
+var hasRequiredSrc$8;
+function requireSrc$8() {
+  if (hasRequiredSrc$8) return src$9;
+  hasRequiredSrc$8 = 1;
+  (function(exports$1) {
+    Object.defineProperty(exports$1, "__esModule", { value: true });
+    exports$1.IORedisInstrumentation = void 0;
+    var instrumentation_1 = requireInstrumentation$8();
+    Object.defineProperty(exports$1, "IORedisInstrumentation", { enumerable: true, get: function() {
+      return instrumentation_1.IORedisInstrumentation;
+    } });
+  })(src$9);
+  return src$9;
+}
+var srcExports$8 = requireSrc$8();
+var src$7 = {};
+var redis = {};
+var version$7 = {};
+var hasRequiredVersion$7;
+function requireVersion$7() {
+  if (hasRequiredVersion$7) return version$7;
+  hasRequiredVersion$7 = 1;
+  Object.defineProperty(version$7, "__esModule", { value: true });
+  version$7.PACKAGE_NAME = version$7.PACKAGE_VERSION = void 0;
+  version$7.PACKAGE_VERSION = "0.57.0";
+  version$7.PACKAGE_NAME = "@opentelemetry/instrumentation-redis";
+  return version$7;
+}
+var instrumentation$7 = {};
+var utils$7 = {};
+var hasRequiredUtils$7;
+function requireUtils$7() {
+  if (hasRequiredUtils$7) return utils$7;
+  hasRequiredUtils$7 = 1;
+  Object.defineProperty(utils$7, "__esModule", { value: true });
+  utils$7.getTracedCreateStreamTrace = utils$7.getTracedCreateClient = utils$7.endSpan = void 0;
+  const api_1 = /* @__PURE__ */ requireSrc$n();
+  const endSpan2 = (span, err) => {
+    if (err) {
+      span.setStatus({
+        code: api_1.SpanStatusCode.ERROR,
+        message: err.message
+      });
+    }
+    span.end();
+  };
+  utils$7.endSpan = endSpan2;
+  const getTracedCreateClient = (original) => {
+    return function createClientTrace() {
+      const client = original.apply(this, arguments);
+      return api_1.context.bind(api_1.context.active(), client);
+    };
+  };
+  utils$7.getTracedCreateClient = getTracedCreateClient;
+  const getTracedCreateStreamTrace = (original) => {
+    return function create_stream_trace() {
+      if (!Object.prototype.hasOwnProperty.call(this, "stream")) {
+        Object.defineProperty(this, "stream", {
+          get() {
+            return this._patched_redis_stream;
+          },
+          set(val) {
+            api_1.context.bind(api_1.context.active(), val);
+            this._patched_redis_stream = val;
+          }
+        });
+      }
+      return original.apply(this, arguments);
+    };
+  };
+  utils$7.getTracedCreateStreamTrace = getTracedCreateStreamTrace;
+  return utils$7;
+}
+var semconv$4 = {};
+var hasRequiredSemconv$4;
+function requireSemconv$4() {
+  if (hasRequiredSemconv$4) return semconv$4;
+  hasRequiredSemconv$4 = 1;
+  Object.defineProperty(semconv$4, "__esModule", { value: true });
+  semconv$4.DB_SYSTEM_VALUE_REDIS = semconv$4.DB_SYSTEM_NAME_VALUE_REDIS = semconv$4.ATTR_NET_PEER_PORT = semconv$4.ATTR_NET_PEER_NAME = semconv$4.ATTR_DB_SYSTEM = semconv$4.ATTR_DB_STATEMENT = semconv$4.ATTR_DB_CONNECTION_STRING = void 0;
+  semconv$4.ATTR_DB_CONNECTION_STRING = "db.connection_string";
+  semconv$4.ATTR_DB_STATEMENT = "db.statement";
+  semconv$4.ATTR_DB_SYSTEM = "db.system";
+  semconv$4.ATTR_NET_PEER_NAME = "net.peer.name";
+  semconv$4.ATTR_NET_PEER_PORT = "net.peer.port";
+  semconv$4.DB_SYSTEM_NAME_VALUE_REDIS = "redis";
+  semconv$4.DB_SYSTEM_VALUE_REDIS = "redis";
+  return semconv$4;
+}
+var hasRequiredInstrumentation$7;
+function requireInstrumentation$7() {
+  if (hasRequiredInstrumentation$7) return instrumentation$7;
+  hasRequiredInstrumentation$7 = 1;
+  Object.defineProperty(instrumentation$7, "__esModule", { value: true });
+  instrumentation$7.RedisInstrumentationV2_V3 = void 0;
+  const instrumentation_1 = require$$2;
+  const utils_1 = requireUtils$7();
+  const version_1 = requireVersion$7();
+  const api_1 = /* @__PURE__ */ requireSrc$n();
+  const semantic_conventions_1 = /* @__PURE__ */ requireSrc$m();
+  const semconv_1 = requireSemconv$4();
+  const redis_common_1 = requireSrc$9();
+  class RedisInstrumentationV2_V3 extends instrumentation_1.InstrumentationBase {
+    static COMPONENT = "redis";
+    _semconvStability;
+    constructor(config2 = {}) {
+      super(version_1.PACKAGE_NAME, version_1.PACKAGE_VERSION, config2);
+      this._semconvStability = config2.semconvStability ? config2.semconvStability : (0, instrumentation_1.semconvStabilityFromStr)("database", process.env.OTEL_SEMCONV_STABILITY_OPT_IN);
+    }
+    setConfig(config2 = {}) {
+      super.setConfig(config2);
+      this._semconvStability = config2.semconvStability ? config2.semconvStability : (0, instrumentation_1.semconvStabilityFromStr)("database", process.env.OTEL_SEMCONV_STABILITY_OPT_IN);
+    }
+    init() {
+      return [
+        new instrumentation_1.InstrumentationNodeModuleDefinition("redis", [">=2.6.0 <4"], (moduleExports) => {
+          if ((0, instrumentation_1.isWrapped)(moduleExports.RedisClient.prototype["internal_send_command"])) {
+            this._unwrap(moduleExports.RedisClient.prototype, "internal_send_command");
+          }
+          this._wrap(moduleExports.RedisClient.prototype, "internal_send_command", this._getPatchInternalSendCommand());
+          if ((0, instrumentation_1.isWrapped)(moduleExports.RedisClient.prototype["create_stream"])) {
+            this._unwrap(moduleExports.RedisClient.prototype, "create_stream");
+          }
+          this._wrap(moduleExports.RedisClient.prototype, "create_stream", this._getPatchCreateStream());
+          if ((0, instrumentation_1.isWrapped)(moduleExports.createClient)) {
+            this._unwrap(moduleExports, "createClient");
+          }
+          this._wrap(moduleExports, "createClient", this._getPatchCreateClient());
+          return moduleExports;
+        }, (moduleExports) => {
+          if (moduleExports === void 0)
+            return;
+          this._unwrap(moduleExports.RedisClient.prototype, "internal_send_command");
+          this._unwrap(moduleExports.RedisClient.prototype, "create_stream");
+          this._unwrap(moduleExports, "createClient");
+        })
+      ];
+    }
+    /**
+     * Patch internal_send_command(...) to trace requests
+     */
+    _getPatchInternalSendCommand() {
+      const instrumentation2 = this;
+      return function internal_send_command(original) {
+        return function internal_send_command_trace(cmd) {
+          if (arguments.length !== 1 || typeof cmd !== "object") {
+            return original.apply(this, arguments);
+          }
+          const config2 = instrumentation2.getConfig();
+          const hasNoParentSpan = api_1.trace.getSpan(api_1.context.active()) === void 0;
+          if (config2.requireParentSpan === true && hasNoParentSpan) {
+            return original.apply(this, arguments);
+          }
+          const dbStatementSerializer = config2?.dbStatementSerializer || redis_common_1.defaultDbStatementSerializer;
+          const attributes = {};
+          if (instrumentation2._semconvStability & instrumentation_1.SemconvStability.OLD) {
+            Object.assign(attributes, {
+              [semconv_1.ATTR_DB_SYSTEM]: semconv_1.DB_SYSTEM_VALUE_REDIS,
+              [semconv_1.ATTR_DB_STATEMENT]: dbStatementSerializer(cmd.command, cmd.args)
+            });
+          }
+          if (instrumentation2._semconvStability & instrumentation_1.SemconvStability.STABLE) {
+            Object.assign(attributes, {
+              [semantic_conventions_1.ATTR_DB_SYSTEM_NAME]: semconv_1.DB_SYSTEM_NAME_VALUE_REDIS,
+              [semantic_conventions_1.ATTR_DB_OPERATION_NAME]: cmd.command,
+              [semantic_conventions_1.ATTR_DB_QUERY_TEXT]: dbStatementSerializer(cmd.command, cmd.args)
+            });
+          }
+          const span = instrumentation2.tracer.startSpan(`${RedisInstrumentationV2_V3.COMPONENT}-${cmd.command}`, {
+            kind: api_1.SpanKind.CLIENT,
+            attributes
+          });
+          if (this.connection_options) {
+            const connectionAttributes = {};
+            if (instrumentation2._semconvStability & instrumentation_1.SemconvStability.OLD) {
+              Object.assign(connectionAttributes, {
+                [semconv_1.ATTR_NET_PEER_NAME]: this.connection_options.host,
+                [semconv_1.ATTR_NET_PEER_PORT]: this.connection_options.port
+              });
+            }
+            if (instrumentation2._semconvStability & instrumentation_1.SemconvStability.STABLE) {
+              Object.assign(connectionAttributes, {
+                [semantic_conventions_1.ATTR_SERVER_ADDRESS]: this.connection_options.host,
+                [semantic_conventions_1.ATTR_SERVER_PORT]: this.connection_options.port
+              });
+            }
+            span.setAttributes(connectionAttributes);
+          }
+          if (this.address && instrumentation2._semconvStability & instrumentation_1.SemconvStability.OLD) {
+            span.setAttribute(semconv_1.ATTR_DB_CONNECTION_STRING, `redis://${this.address}`);
+          }
+          const originalCallback = arguments[0].callback;
+          if (originalCallback) {
+            const originalContext = api_1.context.active();
+            arguments[0].callback = function callback(err, reply) {
+              if (config2?.responseHook) {
+                const responseHook = config2.responseHook;
+                (0, instrumentation_1.safeExecuteInTheMiddle)(() => {
+                  responseHook(span, cmd.command, cmd.args, reply);
+                }, (err2) => {
+                  if (err2) {
+                    instrumentation2._diag.error("Error executing responseHook", err2);
+                  }
+                }, true);
+              }
+              (0, utils_1.endSpan)(span, err);
+              return api_1.context.with(originalContext, originalCallback, this, ...arguments);
+            };
+          }
+          try {
+            return original.apply(this, arguments);
+          } catch (rethrow) {
+            (0, utils_1.endSpan)(span, rethrow);
+            throw rethrow;
+          }
+        };
+      };
+    }
+    _getPatchCreateClient() {
+      return function createClient(original) {
+        return (0, utils_1.getTracedCreateClient)(original);
+      };
+    }
+    _getPatchCreateStream() {
+      return function createReadStream2(original) {
+        return (0, utils_1.getTracedCreateStreamTrace)(original);
+      };
+    }
+  }
+  instrumentation$7.RedisInstrumentationV2_V3 = RedisInstrumentationV2_V3;
+  return instrumentation$7;
+}
+var instrumentation$6 = {};
+var utils$6 = {};
+var hasRequiredUtils$6;
+function requireUtils$6() {
+  if (hasRequiredUtils$6) return utils$6;
+  hasRequiredUtils$6 = 1;
+  Object.defineProperty(utils$6, "__esModule", { value: true });
+  utils$6.getClientAttributes = void 0;
+  const semantic_conventions_1 = /* @__PURE__ */ requireSrc$m();
+  const semconv_1 = requireSemconv$4();
+  const instrumentation_1 = require$$2;
+  function getClientAttributes(diag2, options, semconvStability) {
+    const attributes = {};
+    if (semconvStability & instrumentation_1.SemconvStability.OLD) {
+      Object.assign(attributes, {
+        [semconv_1.ATTR_DB_SYSTEM]: semconv_1.DB_SYSTEM_VALUE_REDIS,
+        [semconv_1.ATTR_NET_PEER_NAME]: options?.socket?.host,
+        [semconv_1.ATTR_NET_PEER_PORT]: options?.socket?.port,
+        [semconv_1.ATTR_DB_CONNECTION_STRING]: removeCredentialsFromDBConnectionStringAttribute(diag2, options?.url)
+      });
+    }
+    if (semconvStability & instrumentation_1.SemconvStability.STABLE) {
+      Object.assign(attributes, {
+        [semantic_conventions_1.ATTR_DB_SYSTEM_NAME]: semconv_1.DB_SYSTEM_NAME_VALUE_REDIS,
+        [semantic_conventions_1.ATTR_SERVER_ADDRESS]: options?.socket?.host,
+        [semantic_conventions_1.ATTR_SERVER_PORT]: options?.socket?.port
+      });
+    }
+    return attributes;
+  }
+  utils$6.getClientAttributes = getClientAttributes;
+  function removeCredentialsFromDBConnectionStringAttribute(diag2, url) {
+    if (typeof url !== "string" || !url) {
+      return;
+    }
+    try {
+      const u = new URL(url);
+      u.searchParams.delete("user_pwd");
+      u.username = "";
+      u.password = "";
+      return u.href;
+    } catch (err) {
+      diag2.error("failed to sanitize redis connection url", err);
+    }
+    return;
+  }
+  return utils$6;
+}
+var hasRequiredInstrumentation$6;
+function requireInstrumentation$6() {
+  if (hasRequiredInstrumentation$6) return instrumentation$6;
+  hasRequiredInstrumentation$6 = 1;
+  Object.defineProperty(instrumentation$6, "__esModule", { value: true });
+  instrumentation$6.RedisInstrumentationV4_V5 = void 0;
+  const api_1 = /* @__PURE__ */ requireSrc$n();
+  const instrumentation_1 = require$$2;
+  const utils_1 = requireUtils$6();
+  const redis_common_1 = requireSrc$9();
+  const version_1 = requireVersion$7();
+  const semantic_conventions_1 = /* @__PURE__ */ requireSrc$m();
+  const semconv_1 = requireSemconv$4();
+  const OTEL_OPEN_SPANS = Symbol("opentelemetry.instrumentation.redis.open_spans");
+  const MULTI_COMMAND_OPTIONS = Symbol("opentelemetry.instrumentation.redis.multi_command_options");
+  class RedisInstrumentationV4_V5 extends instrumentation_1.InstrumentationBase {
+    static COMPONENT = "redis";
+    _semconvStability;
+    constructor(config2 = {}) {
+      super(version_1.PACKAGE_NAME, version_1.PACKAGE_VERSION, config2);
+      this._semconvStability = config2.semconvStability ? config2.semconvStability : (0, instrumentation_1.semconvStabilityFromStr)("database", process.env.OTEL_SEMCONV_STABILITY_OPT_IN);
+    }
+    setConfig(config2 = {}) {
+      super.setConfig(config2);
+      this._semconvStability = config2.semconvStability ? config2.semconvStability : (0, instrumentation_1.semconvStabilityFromStr)("database", process.env.OTEL_SEMCONV_STABILITY_OPT_IN);
+    }
+    init() {
+      return [
+        this._getInstrumentationNodeModuleDefinition("@redis/client"),
+        this._getInstrumentationNodeModuleDefinition("@node-redis/client")
+      ];
+    }
+    _getInstrumentationNodeModuleDefinition(basePackageName) {
+      const commanderModuleFile = new instrumentation_1.InstrumentationNodeModuleFile(`${basePackageName}/dist/lib/commander.js`, ["^1.0.0"], (moduleExports, moduleVersion) => {
+        const transformCommandArguments = moduleExports.transformCommandArguments;
+        if (!transformCommandArguments) {
+          this._diag.error("internal instrumentation error, missing transformCommandArguments function");
+          return moduleExports;
+        }
+        const functionToPatch = moduleVersion?.startsWith("1.0.") ? "extendWithCommands" : "attachCommands";
+        if ((0, instrumentation_1.isWrapped)(moduleExports?.[functionToPatch])) {
+          this._unwrap(moduleExports, functionToPatch);
+        }
+        this._wrap(moduleExports, functionToPatch, this._getPatchExtendWithCommands(transformCommandArguments));
+        return moduleExports;
+      }, (moduleExports) => {
+        if ((0, instrumentation_1.isWrapped)(moduleExports?.extendWithCommands)) {
+          this._unwrap(moduleExports, "extendWithCommands");
+        }
+        if ((0, instrumentation_1.isWrapped)(moduleExports?.attachCommands)) {
+          this._unwrap(moduleExports, "attachCommands");
+        }
+      });
+      const multiCommanderModule = new instrumentation_1.InstrumentationNodeModuleFile(`${basePackageName}/dist/lib/client/multi-command.js`, ["^1.0.0", "^5.0.0"], (moduleExports) => {
+        const redisClientMultiCommandPrototype = moduleExports?.default?.prototype;
+        if ((0, instrumentation_1.isWrapped)(redisClientMultiCommandPrototype?.exec)) {
+          this._unwrap(redisClientMultiCommandPrototype, "exec");
+        }
+        this._wrap(redisClientMultiCommandPrototype, "exec", this._getPatchMultiCommandsExec());
+        if ((0, instrumentation_1.isWrapped)(redisClientMultiCommandPrototype?.addCommand)) {
+          this._unwrap(redisClientMultiCommandPrototype, "addCommand");
+        }
+        this._wrap(redisClientMultiCommandPrototype, "addCommand", this._getPatchMultiCommandsAddCommand());
+        return moduleExports;
+      }, (moduleExports) => {
+        const redisClientMultiCommandPrototype = moduleExports?.default?.prototype;
+        if ((0, instrumentation_1.isWrapped)(redisClientMultiCommandPrototype?.exec)) {
+          this._unwrap(redisClientMultiCommandPrototype, "exec");
+        }
+        if ((0, instrumentation_1.isWrapped)(redisClientMultiCommandPrototype?.addCommand)) {
+          this._unwrap(redisClientMultiCommandPrototype, "addCommand");
+        }
+      });
+      const clientIndexModule = new instrumentation_1.InstrumentationNodeModuleFile(`${basePackageName}/dist/lib/client/index.js`, ["^1.0.0", "^5.0.0"], (moduleExports) => {
+        const redisClientPrototype = moduleExports?.default?.prototype;
+        if (redisClientPrototype?.multi) {
+          if ((0, instrumentation_1.isWrapped)(redisClientPrototype?.multi)) {
+            this._unwrap(redisClientPrototype, "multi");
+          }
+          this._wrap(redisClientPrototype, "multi", this._getPatchRedisClientMulti());
+        }
+        if (redisClientPrototype?.MULTI) {
+          if ((0, instrumentation_1.isWrapped)(redisClientPrototype?.MULTI)) {
+            this._unwrap(redisClientPrototype, "MULTI");
+          }
+          this._wrap(redisClientPrototype, "MULTI", this._getPatchRedisClientMulti());
+        }
+        if ((0, instrumentation_1.isWrapped)(redisClientPrototype?.sendCommand)) {
+          this._unwrap(redisClientPrototype, "sendCommand");
+        }
+        this._wrap(redisClientPrototype, "sendCommand", this._getPatchRedisClientSendCommand());
+        this._wrap(redisClientPrototype, "connect", this._getPatchedClientConnect());
+        return moduleExports;
+      }, (moduleExports) => {
+        const redisClientPrototype = moduleExports?.default?.prototype;
+        if ((0, instrumentation_1.isWrapped)(redisClientPrototype?.multi)) {
+          this._unwrap(redisClientPrototype, "multi");
+        }
+        if ((0, instrumentation_1.isWrapped)(redisClientPrototype?.MULTI)) {
+          this._unwrap(redisClientPrototype, "MULTI");
+        }
+        if ((0, instrumentation_1.isWrapped)(redisClientPrototype?.sendCommand)) {
+          this._unwrap(redisClientPrototype, "sendCommand");
+        }
+      });
+      return new instrumentation_1.InstrumentationNodeModuleDefinition(basePackageName, ["^1.0.0", "^5.0.0"], (moduleExports) => {
+        return moduleExports;
+      }, () => {
+      }, [commanderModuleFile, multiCommanderModule, clientIndexModule]);
+    }
+    // serves both for redis 4.0.x where function name is extendWithCommands
+    // and redis ^4.1.0 where function name is attachCommands
+    _getPatchExtendWithCommands(transformCommandArguments) {
+      const plugin = this;
+      return function extendWithCommandsPatchWrapper(original) {
+        return function extendWithCommandsPatch(config2) {
+          if (config2?.BaseClass?.name !== "RedisClient") {
+            return original.apply(this, arguments);
+          }
+          const origExecutor = config2.executor;
+          config2.executor = function(command, args) {
+            const redisCommandArguments = transformCommandArguments(command, args).args;
+            return plugin._traceClientCommand(origExecutor, this, arguments, redisCommandArguments);
+          };
+          return original.apply(this, arguments);
+        };
+      };
+    }
+    _getPatchMultiCommandsExec() {
+      const plugin = this;
+      return function execPatchWrapper(original) {
+        return function execPatch() {
+          const execRes = original.apply(this, arguments);
+          if (typeof execRes?.then !== "function") {
+            plugin._diag.error("got non promise result when patching RedisClientMultiCommand.exec");
+            return execRes;
+          }
+          return execRes.then((redisRes) => {
+            const openSpans = this[OTEL_OPEN_SPANS];
+            plugin._endSpansWithRedisReplies(openSpans, redisRes);
+            return redisRes;
+          }).catch((err) => {
+            const openSpans = this[OTEL_OPEN_SPANS];
+            if (!openSpans) {
+              plugin._diag.error("cannot find open spans to end for redis multi command");
+            } else {
+              const replies = err.constructor.name === "MultiErrorReply" ? err.replies : new Array(openSpans.length).fill(err);
+              plugin._endSpansWithRedisReplies(openSpans, replies);
+            }
+            return Promise.reject(err);
+          });
+        };
+      };
+    }
+    _getPatchMultiCommandsAddCommand() {
+      const plugin = this;
+      return function addCommandWrapper(original) {
+        return function addCommandPatch(args) {
+          return plugin._traceClientCommand(original, this, arguments, args);
+        };
+      };
+    }
+    _getPatchRedisClientMulti() {
+      return function multiPatchWrapper(original) {
+        return function multiPatch() {
+          const multiRes = original.apply(this, arguments);
+          multiRes[MULTI_COMMAND_OPTIONS] = this.options;
+          return multiRes;
+        };
+      };
+    }
+    _getPatchRedisClientSendCommand() {
+      const plugin = this;
+      return function sendCommandWrapper(original) {
+        return function sendCommandPatch(args) {
+          return plugin._traceClientCommand(original, this, arguments, args);
+        };
+      };
+    }
+    _getPatchedClientConnect() {
+      const plugin = this;
+      return function connectWrapper(original) {
+        return function patchedConnect() {
+          const options = this.options;
+          const attributes = (0, utils_1.getClientAttributes)(plugin._diag, options, plugin._semconvStability);
+          const span = plugin.tracer.startSpan(`${RedisInstrumentationV4_V5.COMPONENT}-connect`, {
+            kind: api_1.SpanKind.CLIENT,
+            attributes
+          });
+          const res = api_1.context.with(api_1.trace.setSpan(api_1.context.active(), span), () => {
+            return original.apply(this);
+          });
+          return res.then((result) => {
+            span.end();
+            return result;
+          }).catch((error2) => {
+            span.recordException(error2);
+            span.setStatus({
+              code: api_1.SpanStatusCode.ERROR,
+              message: error2.message
+            });
+            span.end();
+            return Promise.reject(error2);
+          });
+        };
+      };
+    }
+    _traceClientCommand(origFunction, origThis, origArguments, redisCommandArguments) {
+      const hasNoParentSpan = api_1.trace.getSpan(api_1.context.active()) === void 0;
+      if (hasNoParentSpan && this.getConfig().requireParentSpan) {
+        return origFunction.apply(origThis, origArguments);
+      }
+      const clientOptions = origThis.options || origThis[MULTI_COMMAND_OPTIONS];
+      const commandName = redisCommandArguments[0];
+      const commandArgs = redisCommandArguments.slice(1);
+      const dbStatementSerializer = this.getConfig().dbStatementSerializer || redis_common_1.defaultDbStatementSerializer;
+      const attributes = (0, utils_1.getClientAttributes)(this._diag, clientOptions, this._semconvStability);
+      if (this._semconvStability & instrumentation_1.SemconvStability.STABLE) {
+        attributes[semantic_conventions_1.ATTR_DB_OPERATION_NAME] = commandName;
+      }
+      try {
+        const dbStatement = dbStatementSerializer(commandName, commandArgs);
+        if (dbStatement != null) {
+          if (this._semconvStability & instrumentation_1.SemconvStability.OLD) {
+            attributes[semconv_1.ATTR_DB_STATEMENT] = dbStatement;
+          }
+          if (this._semconvStability & instrumentation_1.SemconvStability.STABLE) {
+            attributes[semantic_conventions_1.ATTR_DB_QUERY_TEXT] = dbStatement;
+          }
+        }
+      } catch (e) {
+        this._diag.error("dbStatementSerializer throw an exception", e, {
+          commandName
+        });
+      }
+      const span = this.tracer.startSpan(`${RedisInstrumentationV4_V5.COMPONENT}-${commandName}`, {
+        kind: api_1.SpanKind.CLIENT,
+        attributes
+      });
+      const res = api_1.context.with(api_1.trace.setSpan(api_1.context.active(), span), () => {
+        return origFunction.apply(origThis, origArguments);
+      });
+      if (typeof res?.then === "function") {
+        res.then((redisRes) => {
+          this._endSpanWithResponse(span, commandName, commandArgs, redisRes, void 0);
+        }, (err) => {
+          this._endSpanWithResponse(span, commandName, commandArgs, null, err);
+        });
+      } else {
+        const redisClientMultiCommand = res;
+        redisClientMultiCommand[OTEL_OPEN_SPANS] = redisClientMultiCommand[OTEL_OPEN_SPANS] || [];
+        redisClientMultiCommand[OTEL_OPEN_SPANS].push({
+          span,
+          commandName,
+          commandArgs
+        });
+      }
+      return res;
+    }
+    _endSpansWithRedisReplies(openSpans, replies) {
+      if (!openSpans) {
+        return this._diag.error("cannot find open spans to end for redis multi command");
+      }
+      if (replies.length !== openSpans.length) {
+        return this._diag.error("number of multi command spans does not match response from redis");
+      }
+      for (let i = 0; i < openSpans.length; i++) {
+        const { span, commandName, commandArgs } = openSpans[i];
+        const currCommandRes = replies[i];
+        const [res, err] = currCommandRes instanceof Error ? [null, currCommandRes] : [currCommandRes, void 0];
+        this._endSpanWithResponse(span, commandName, commandArgs, res, err);
+      }
+    }
+    _endSpanWithResponse(span, commandName, commandArgs, response, error2) {
+      const { responseHook } = this.getConfig();
+      if (!error2 && responseHook) {
+        try {
+          responseHook(span, commandName, commandArgs, response);
+        } catch (err) {
+          this._diag.error("responseHook throw an exception", err);
+        }
+      }
+      if (error2) {
+        span.recordException(error2);
+        span.setStatus({ code: api_1.SpanStatusCode.ERROR, message: error2?.message });
+      }
+      span.end();
+    }
+  }
+  instrumentation$6.RedisInstrumentationV4_V5 = RedisInstrumentationV4_V5;
+  return instrumentation$6;
+}
+var hasRequiredRedis;
+function requireRedis() {
+  if (hasRequiredRedis) return redis;
+  hasRequiredRedis = 1;
+  Object.defineProperty(redis, "__esModule", { value: true });
+  redis.RedisInstrumentation = void 0;
+  const instrumentation_1 = require$$2;
+  const version_1 = requireVersion$7();
+  const instrumentation_2 = requireInstrumentation$7();
+  const instrumentation_3 = requireInstrumentation$6();
+  const DEFAULT_CONFIG = {
+    requireParentSpan: false
+  };
+  class RedisInstrumentation extends instrumentation_1.InstrumentationBase {
+    instrumentationV2_V3;
+    instrumentationV4_V5;
+    // this is used to bypass a flaw in the base class constructor, which is calling
+    // member functions before the constructor has a chance to fully initialize the member variables.
+    initialized = false;
+    constructor(config2 = {}) {
+      const resolvedConfig = { ...DEFAULT_CONFIG, ...config2 };
+      super(version_1.PACKAGE_NAME, version_1.PACKAGE_VERSION, resolvedConfig);
+      this.instrumentationV2_V3 = new instrumentation_2.RedisInstrumentationV2_V3(this.getConfig());
+      this.instrumentationV4_V5 = new instrumentation_3.RedisInstrumentationV4_V5(this.getConfig());
+      this.initialized = true;
+    }
+    setConfig(config2 = {}) {
+      const newConfig = { ...DEFAULT_CONFIG, ...config2 };
+      super.setConfig(newConfig);
+      if (!this.initialized) {
+        return;
+      }
+      this.instrumentationV2_V3.setConfig(newConfig);
+      this.instrumentationV4_V5.setConfig(newConfig);
+    }
+    init() {
+    }
+    // Return underlying modules, as consumers (like https://github.com/DrewCorlin/opentelemetry-node-bundler-plugins) may
+    // expect them to be populated without knowing that this module wraps 2 instrumentations
+    getModuleDefinitions() {
+      return [
+        ...this.instrumentationV2_V3.getModuleDefinitions(),
+        ...this.instrumentationV4_V5.getModuleDefinitions()
+      ];
+    }
+    setTracerProvider(tracerProvider) {
+      super.setTracerProvider(tracerProvider);
+      if (!this.initialized) {
+        return;
+      }
+      this.instrumentationV2_V3.setTracerProvider(tracerProvider);
+      this.instrumentationV4_V5.setTracerProvider(tracerProvider);
+    }
+    enable() {
+      super.enable();
+      if (!this.initialized) {
+        return;
+      }
+      this.instrumentationV2_V3.enable();
+      this.instrumentationV4_V5.enable();
+    }
+    disable() {
+      super.disable();
+      if (!this.initialized) {
+        return;
+      }
+      this.instrumentationV2_V3.disable();
+      this.instrumentationV4_V5.disable();
+    }
+  }
+  redis.RedisInstrumentation = RedisInstrumentation;
+  return redis;
+}
+var hasRequiredSrc$7;
+function requireSrc$7() {
+  if (hasRequiredSrc$7) return src$7;
+  hasRequiredSrc$7 = 1;
+  (function(exports$1) {
+    Object.defineProperty(exports$1, "__esModule", { value: true });
+    exports$1.RedisInstrumentation = void 0;
+    var redis_1 = requireRedis();
+    Object.defineProperty(exports$1, "RedisInstrumentation", { enumerable: true, get: function() {
+      return redis_1.RedisInstrumentation;
+    } });
+  })(src$7);
+  return src$7;
+}
+var srcExports$7 = requireSrc$7();
+const SINGLE_ARG_COMMANDS = ["get", "set", "setex"];
+const GET_COMMANDS = ["get", "mget"];
+const SET_COMMANDS = ["set", "setex"];
+function isInCommands(redisCommands, command) {
+  return redisCommands.includes(command.toLowerCase());
+}
+function getCacheOperation(command) {
+  if (isInCommands(GET_COMMANDS, command)) {
+    return "cache.get";
+  } else if (isInCommands(SET_COMMANDS, command)) {
+    return "cache.put";
+  } else {
+    return void 0;
+  }
+}
+function keyHasPrefix(key, prefixes) {
+  return prefixes.some((prefix) => key.startsWith(prefix));
+}
+function getCacheKeySafely(redisCommand, cmdArgs) {
+  try {
+    if (cmdArgs.length === 0) {
+      return void 0;
+    }
+    const processArg = (arg) => {
+      if (typeof arg === "string" || typeof arg === "number" || Buffer.isBuffer(arg)) {
+        return [arg.toString()];
+      } else if (Array.isArray(arg)) {
+        return flatten(arg.map((arg2) => processArg(arg2)));
+      } else {
+        return [""];
+      }
+    };
+    const firstArg = cmdArgs[0];
+    if (isInCommands(SINGLE_ARG_COMMANDS, redisCommand) && firstArg != null) {
+      return processArg(firstArg);
+    }
+    return flatten(cmdArgs.map((arg) => processArg(arg)));
+  } catch {
+    return void 0;
+  }
+}
+function shouldConsiderForCache(redisCommand, keys, prefixes) {
+  if (!getCacheOperation(redisCommand)) {
+    return false;
+  }
+  for (const key of keys) {
+    if (keyHasPrefix(key, prefixes)) {
+      return true;
+    }
+  }
+  return false;
+}
+function calculateCacheItemSize(response) {
+  const getSize = (value) => {
+    try {
+      if (Buffer.isBuffer(value)) return value.byteLength;
+      else if (typeof value === "string") return value.length;
+      else if (typeof value === "number") return value.toString().length;
+      else if (value === null || value === void 0) return 0;
+      return JSON.stringify(value).length;
+    } catch {
+      return void 0;
+    }
+  };
+  return Array.isArray(response) ? response.reduce((acc, curr) => {
+    const size = getSize(curr);
+    return typeof size === "number" ? acc !== void 0 ? acc + size : size : acc;
+  }, 0) : getSize(response);
+}
+function flatten(input) {
+  const result = [];
+  const flattenHelper = (input2) => {
+    input2.forEach((el) => {
+      if (Array.isArray(el)) {
+        flattenHelper(el);
+      } else {
+        result.push(el);
+      }
+    });
+  };
+  flattenHelper(input);
+  return result;
+}
+const INTEGRATION_NAME$c = "Redis";
+let _redisOptions = {};
+const cacheResponseHook = (span, redisCommand, cmdArgs, response) => {
+  span.setAttribute(SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN, "auto.db.otel.redis");
+  const safeKey = getCacheKeySafely(redisCommand, cmdArgs);
+  const cacheOperation = getCacheOperation(redisCommand);
+  if (!safeKey || !cacheOperation || !_redisOptions.cachePrefixes || !shouldConsiderForCache(redisCommand, safeKey, _redisOptions.cachePrefixes)) {
+    return;
+  }
+  const networkPeerAddress = spanToJSON(span).data["net.peer.name"];
+  const networkPeerPort = spanToJSON(span).data["net.peer.port"];
+  if (networkPeerPort && networkPeerAddress) {
+    span.setAttributes({ "network.peer.address": networkPeerAddress, "network.peer.port": networkPeerPort });
+  }
+  const cacheItemSize = calculateCacheItemSize(response);
+  if (cacheItemSize) {
+    span.setAttribute(SEMANTIC_ATTRIBUTE_CACHE_ITEM_SIZE, cacheItemSize);
+  }
+  if (isInCommands(GET_COMMANDS, redisCommand) && cacheItemSize !== void 0) {
+    span.setAttribute(SEMANTIC_ATTRIBUTE_CACHE_HIT, cacheItemSize > 0);
+  }
+  span.setAttributes({
+    [SEMANTIC_ATTRIBUTE_SENTRY_OP]: cacheOperation,
+    [SEMANTIC_ATTRIBUTE_CACHE_KEY]: safeKey
+  });
+  const spanDescription = safeKey.join(", ");
+  span.updateName(
+    _redisOptions.maxCacheKeyLength ? truncate(spanDescription, _redisOptions.maxCacheKeyLength) : spanDescription
+  );
+};
+const instrumentIORedis = generateInstrumentOnce(`${INTEGRATION_NAME$c}.IORedis`, () => {
+  return new srcExports$8.IORedisInstrumentation({
+    responseHook: cacheResponseHook
+  });
+});
+const instrumentRedisModule = generateInstrumentOnce(`${INTEGRATION_NAME$c}.Redis`, () => {
+  return new srcExports$7.RedisInstrumentation({
+    responseHook: cacheResponseHook
+  });
+});
+const instrumentRedis = Object.assign(
+  () => {
+    instrumentIORedis();
+    instrumentRedisModule();
+  },
+  { id: INTEGRATION_NAME$c }
+);
+const _redisIntegration = ((options = {}) => {
+  return {
+    name: INTEGRATION_NAME$c,
+    setupOnce() {
+      _redisOptions = options;
+      instrumentRedis();
+    }
+  };
+});
+const redisIntegration = defineIntegration(_redisIntegration);
+var src$6 = {};
+var instrumentation$5 = {};
+var internalTypes$3 = {};
+var hasRequiredInternalTypes$3;
+function requireInternalTypes$3() {
+  if (hasRequiredInternalTypes$3) return internalTypes$3;
+  hasRequiredInternalTypes$3 = 1;
+  Object.defineProperty(internalTypes$3, "__esModule", { value: true });
+  internalTypes$3.EVENT_LISTENERS_SET = void 0;
+  internalTypes$3.EVENT_LISTENERS_SET = Symbol("opentelemetry.instrumentation.pg.eventListenersSet");
+  return internalTypes$3;
+}
+var utils$5 = {};
+var AttributeNames$4 = {};
+var hasRequiredAttributeNames$3;
+function requireAttributeNames$3() {
+  if (hasRequiredAttributeNames$3) return AttributeNames$4;
+  hasRequiredAttributeNames$3 = 1;
+  (function(exports$1) {
+    Object.defineProperty(exports$1, "__esModule", { value: true });
+    exports$1.AttributeNames = void 0;
+    (function(AttributeNames2) {
+      AttributeNames2["PG_VALUES"] = "db.postgresql.values";
+      AttributeNames2["PG_PLAN"] = "db.postgresql.plan";
+      AttributeNames2["IDLE_TIMEOUT_MILLIS"] = "db.postgresql.idle.timeout.millis";
+      AttributeNames2["MAX_CLIENT"] = "db.postgresql.max.client";
+    })(exports$1.AttributeNames || (exports$1.AttributeNames = {}));
+  })(AttributeNames$4);
+  return AttributeNames$4;
+}
+var semconv$3 = {};
+var hasRequiredSemconv$3;
+function requireSemconv$3() {
+  if (hasRequiredSemconv$3) return semconv$3;
+  hasRequiredSemconv$3 = 1;
+  Object.defineProperty(semconv$3, "__esModule", { value: true });
+  semconv$3.METRIC_DB_CLIENT_CONNECTION_PENDING_REQUESTS = semconv$3.METRIC_DB_CLIENT_CONNECTION_COUNT = semconv$3.DB_SYSTEM_VALUE_POSTGRESQL = semconv$3.DB_CLIENT_CONNECTION_STATE_VALUE_USED = semconv$3.DB_CLIENT_CONNECTION_STATE_VALUE_IDLE = semconv$3.ATTR_NET_PEER_PORT = semconv$3.ATTR_NET_PEER_NAME = semconv$3.ATTR_DB_USER = semconv$3.ATTR_DB_SYSTEM = semconv$3.ATTR_DB_STATEMENT = semconv$3.ATTR_DB_NAME = semconv$3.ATTR_DB_CONNECTION_STRING = semconv$3.ATTR_DB_CLIENT_CONNECTION_STATE = semconv$3.ATTR_DB_CLIENT_CONNECTION_POOL_NAME = void 0;
+  semconv$3.ATTR_DB_CLIENT_CONNECTION_POOL_NAME = "db.client.connection.pool.name";
+  semconv$3.ATTR_DB_CLIENT_CONNECTION_STATE = "db.client.connection.state";
+  semconv$3.ATTR_DB_CONNECTION_STRING = "db.connection_string";
+  semconv$3.ATTR_DB_NAME = "db.name";
+  semconv$3.ATTR_DB_STATEMENT = "db.statement";
+  semconv$3.ATTR_DB_SYSTEM = "db.system";
+  semconv$3.ATTR_DB_USER = "db.user";
+  semconv$3.ATTR_NET_PEER_NAME = "net.peer.name";
+  semconv$3.ATTR_NET_PEER_PORT = "net.peer.port";
+  semconv$3.DB_CLIENT_CONNECTION_STATE_VALUE_IDLE = "idle";
+  semconv$3.DB_CLIENT_CONNECTION_STATE_VALUE_USED = "used";
+  semconv$3.DB_SYSTEM_VALUE_POSTGRESQL = "postgresql";
+  semconv$3.METRIC_DB_CLIENT_CONNECTION_COUNT = "db.client.connection.count";
+  semconv$3.METRIC_DB_CLIENT_CONNECTION_PENDING_REQUESTS = "db.client.connection.pending_requests";
+  return semconv$3;
+}
+var SpanNames = {};
+var hasRequiredSpanNames;
+function requireSpanNames() {
+  if (hasRequiredSpanNames) return SpanNames;
+  hasRequiredSpanNames = 1;
+  (function(exports$1) {
+    Object.defineProperty(exports$1, "__esModule", { value: true });
+    exports$1.SpanNames = void 0;
+    (function(SpanNames2) {
+      SpanNames2["QUERY_PREFIX"] = "pg.query";
+      SpanNames2["CONNECT"] = "pg.connect";
+      SpanNames2["POOL_CONNECT"] = "pg-pool.connect";
+    })(exports$1.SpanNames || (exports$1.SpanNames = {}));
+  })(SpanNames);
+  return SpanNames;
+}
+var hasRequiredUtils$5;
+function requireUtils$5() {
+  if (hasRequiredUtils$5) return utils$5;
+  hasRequiredUtils$5 = 1;
+  Object.defineProperty(utils$5, "__esModule", { value: true });
+  utils$5.sanitizedErrorMessage = utils$5.isObjectWithTextString = utils$5.getErrorMessage = utils$5.patchClientConnectCallback = utils$5.patchCallbackPGPool = utils$5.updateCounter = utils$5.getPoolName = utils$5.patchCallback = utils$5.handleExecutionResult = utils$5.handleConfigQuery = utils$5.shouldSkipInstrumentation = utils$5.getSemanticAttributesFromPoolConnection = utils$5.getSemanticAttributesFromConnection = utils$5.getConnectionString = utils$5.parseAndMaskConnectionString = utils$5.parseNormalizedOperationName = utils$5.getQuerySpanName = void 0;
+  const api_1 = /* @__PURE__ */ requireSrc$n();
+  const AttributeNames_1 = requireAttributeNames$3();
+  const semantic_conventions_1 = /* @__PURE__ */ requireSrc$m();
+  const semconv_1 = requireSemconv$3();
+  const instrumentation_1 = require$$2;
+  const SpanNames_1 = requireSpanNames();
+  function getQuerySpanName(dbName, queryConfig) {
+    if (!queryConfig)
+      return SpanNames_1.SpanNames.QUERY_PREFIX;
+    const command = typeof queryConfig.name === "string" && queryConfig.name ? queryConfig.name : parseNormalizedOperationName(queryConfig.text);
+    return `${SpanNames_1.SpanNames.QUERY_PREFIX}:${command}${dbName ? ` ${dbName}` : ""}`;
+  }
+  utils$5.getQuerySpanName = getQuerySpanName;
+  function parseNormalizedOperationName(queryText) {
+    const indexOfFirstSpace = queryText.indexOf(" ");
+    let sqlCommand = indexOfFirstSpace === -1 ? queryText : queryText.slice(0, indexOfFirstSpace);
+    sqlCommand = sqlCommand.toUpperCase();
+    return sqlCommand.endsWith(";") ? sqlCommand.slice(0, -1) : sqlCommand;
+  }
+  utils$5.parseNormalizedOperationName = parseNormalizedOperationName;
+  function parseAndMaskConnectionString(connectionString) {
+    try {
+      const url = new URL(connectionString);
+      url.username = "";
+      url.password = "";
+      return url.toString();
+    } catch (e) {
+      return "postgresql://localhost:5432/";
+    }
+  }
+  utils$5.parseAndMaskConnectionString = parseAndMaskConnectionString;
+  function getConnectionString(params) {
+    if ("connectionString" in params && params.connectionString) {
+      return parseAndMaskConnectionString(params.connectionString);
+    }
+    const host = params.host || "localhost";
+    const port = params.port || 5432;
+    const database = params.database || "";
+    return `postgresql://${host}:${port}/${database}`;
+  }
+  utils$5.getConnectionString = getConnectionString;
+  function getPort(port) {
+    if (Number.isInteger(port)) {
+      return port;
+    }
+    return void 0;
+  }
+  function getSemanticAttributesFromConnection(params, semconvStability) {
+    let attributes = {};
+    if (semconvStability & instrumentation_1.SemconvStability.OLD) {
+      attributes = {
+        ...attributes,
+        [semconv_1.ATTR_DB_SYSTEM]: semconv_1.DB_SYSTEM_VALUE_POSTGRESQL,
+        [semconv_1.ATTR_DB_NAME]: params.database,
+        [semconv_1.ATTR_DB_CONNECTION_STRING]: getConnectionString(params),
+        [semconv_1.ATTR_DB_USER]: params.user,
+        [semconv_1.ATTR_NET_PEER_NAME]: params.host,
+        [semconv_1.ATTR_NET_PEER_PORT]: getPort(params.port)
+      };
+    }
+    if (semconvStability & instrumentation_1.SemconvStability.STABLE) {
+      attributes = {
+        ...attributes,
+        [semantic_conventions_1.ATTR_DB_SYSTEM_NAME]: semantic_conventions_1.DB_SYSTEM_NAME_VALUE_POSTGRESQL,
+        [semantic_conventions_1.ATTR_DB_NAMESPACE]: params.namespace,
+        [semantic_conventions_1.ATTR_SERVER_ADDRESS]: params.host,
+        [semantic_conventions_1.ATTR_SERVER_PORT]: getPort(params.port)
+      };
+    }
+    return attributes;
+  }
+  utils$5.getSemanticAttributesFromConnection = getSemanticAttributesFromConnection;
+  function getSemanticAttributesFromPoolConnection(params, semconvStability) {
+    let url;
+    try {
+      url = params.connectionString ? new URL(params.connectionString) : void 0;
+    } catch (e) {
+      url = void 0;
+    }
+    let attributes = {
+      [AttributeNames_1.AttributeNames.IDLE_TIMEOUT_MILLIS]: params.idleTimeoutMillis,
+      [AttributeNames_1.AttributeNames.MAX_CLIENT]: params.maxClient
+    };
+    if (semconvStability & instrumentation_1.SemconvStability.OLD) {
+      attributes = {
+        ...attributes,
+        [semconv_1.ATTR_DB_SYSTEM]: semconv_1.DB_SYSTEM_VALUE_POSTGRESQL,
+        [semconv_1.ATTR_DB_NAME]: url?.pathname.slice(1) ?? params.database,
+        [semconv_1.ATTR_DB_CONNECTION_STRING]: getConnectionString(params),
+        [semconv_1.ATTR_NET_PEER_NAME]: url?.hostname ?? params.host,
+        [semconv_1.ATTR_NET_PEER_PORT]: Number(url?.port) || getPort(params.port),
+        [semconv_1.ATTR_DB_USER]: url?.username ?? params.user
+      };
+    }
+    if (semconvStability & instrumentation_1.SemconvStability.STABLE) {
+      attributes = {
+        ...attributes,
+        [semantic_conventions_1.ATTR_DB_SYSTEM_NAME]: semantic_conventions_1.DB_SYSTEM_NAME_VALUE_POSTGRESQL,
+        [semantic_conventions_1.ATTR_DB_NAMESPACE]: params.namespace,
+        [semantic_conventions_1.ATTR_SERVER_ADDRESS]: url?.hostname ?? params.host,
+        [semantic_conventions_1.ATTR_SERVER_PORT]: Number(url?.port) || getPort(params.port)
+      };
+    }
+    return attributes;
+  }
+  utils$5.getSemanticAttributesFromPoolConnection = getSemanticAttributesFromPoolConnection;
+  function shouldSkipInstrumentation(instrumentationConfig) {
+    return instrumentationConfig.requireParentSpan === true && api_1.trace.getSpan(api_1.context.active()) === void 0;
+  }
+  utils$5.shouldSkipInstrumentation = shouldSkipInstrumentation;
+  function handleConfigQuery(tracer, instrumentationConfig, semconvStability, queryConfig) {
+    const { connectionParameters } = this;
+    const dbName = connectionParameters.database;
+    const spanName = getQuerySpanName(dbName, queryConfig);
+    const span = tracer.startSpan(spanName, {
+      kind: api_1.SpanKind.CLIENT,
+      attributes: getSemanticAttributesFromConnection(connectionParameters, semconvStability)
+    });
+    if (!queryConfig) {
+      return span;
+    }
+    if (queryConfig.text) {
+      if (semconvStability & instrumentation_1.SemconvStability.OLD) {
+        span.setAttribute(semconv_1.ATTR_DB_STATEMENT, queryConfig.text);
+      }
+      if (semconvStability & instrumentation_1.SemconvStability.STABLE) {
+        span.setAttribute(semantic_conventions_1.ATTR_DB_QUERY_TEXT, queryConfig.text);
+      }
+    }
+    if (instrumentationConfig.enhancedDatabaseReporting && Array.isArray(queryConfig.values)) {
+      try {
+        const convertedValues = queryConfig.values.map((value) => {
+          if (value == null) {
+            return "null";
+          } else if (value instanceof Buffer) {
+            return value.toString();
+          } else if (typeof value === "object") {
+            if (typeof value.toPostgres === "function") {
+              return value.toPostgres();
+            }
+            return JSON.stringify(value);
+          } else {
+            return value.toString();
+          }
+        });
+        span.setAttribute(AttributeNames_1.AttributeNames.PG_VALUES, convertedValues);
+      } catch (e) {
+        api_1.diag.error("failed to stringify ", queryConfig.values, e);
+      }
+    }
+    if (typeof queryConfig.name === "string") {
+      span.setAttribute(AttributeNames_1.AttributeNames.PG_PLAN, queryConfig.name);
+    }
+    return span;
+  }
+  utils$5.handleConfigQuery = handleConfigQuery;
+  function handleExecutionResult(config2, span, pgResult) {
+    if (typeof config2.responseHook === "function") {
+      (0, instrumentation_1.safeExecuteInTheMiddle)(() => {
+        config2.responseHook(span, {
+          data: pgResult
+        });
+      }, (err) => {
+        if (err) {
+          api_1.diag.error("Error running response hook", err);
+        }
+      }, true);
+    }
+  }
+  utils$5.handleExecutionResult = handleExecutionResult;
+  function patchCallback(instrumentationConfig, span, cb, attributes, recordDuration) {
+    return function patchedCallback(err, res) {
+      if (err) {
+        if (Object.prototype.hasOwnProperty.call(err, "code")) {
+          attributes[semantic_conventions_1.ATTR_ERROR_TYPE] = err["code"];
+        }
+        if (err instanceof Error) {
+          span.recordException(sanitizedErrorMessage(err));
+        }
+        span.setStatus({
+          code: api_1.SpanStatusCode.ERROR,
+          message: err.message
+        });
+      } else {
+        handleExecutionResult(instrumentationConfig, span, res);
+      }
+      recordDuration();
+      span.end();
+      cb.call(this, err, res);
+    };
+  }
+  utils$5.patchCallback = patchCallback;
+  function getPoolName(pool) {
+    let poolName = "";
+    poolName += (pool?.host ? `${pool.host}` : "unknown_host") + ":";
+    poolName += (pool?.port ? `${pool.port}` : "unknown_port") + "/";
+    poolName += pool?.database ? `${pool.database}` : "unknown_database";
+    return poolName.trim();
+  }
+  utils$5.getPoolName = getPoolName;
+  function updateCounter(poolName, pool, connectionCount, connectionPendingRequests, latestCounter) {
+    const all = pool.totalCount;
+    const pending = pool.waitingCount;
+    const idle = pool.idleCount;
+    const used = all - idle;
+    connectionCount.add(used - latestCounter.used, {
+      [semconv_1.ATTR_DB_CLIENT_CONNECTION_STATE]: semconv_1.DB_CLIENT_CONNECTION_STATE_VALUE_USED,
+      [semconv_1.ATTR_DB_CLIENT_CONNECTION_POOL_NAME]: poolName
+    });
+    connectionCount.add(idle - latestCounter.idle, {
+      [semconv_1.ATTR_DB_CLIENT_CONNECTION_STATE]: semconv_1.DB_CLIENT_CONNECTION_STATE_VALUE_IDLE,
+      [semconv_1.ATTR_DB_CLIENT_CONNECTION_POOL_NAME]: poolName
+    });
+    connectionPendingRequests.add(pending - latestCounter.pending, {
+      [semconv_1.ATTR_DB_CLIENT_CONNECTION_POOL_NAME]: poolName
+    });
+    return { used, idle, pending };
+  }
+  utils$5.updateCounter = updateCounter;
+  function patchCallbackPGPool(span, cb) {
+    return function patchedCallback(err, res, done) {
+      if (err) {
+        if (err instanceof Error) {
+          span.recordException(sanitizedErrorMessage(err));
+        }
+        span.setStatus({
+          code: api_1.SpanStatusCode.ERROR,
+          message: err.message
+        });
+      }
+      span.end();
+      cb.call(this, err, res, done);
+    };
+  }
+  utils$5.patchCallbackPGPool = patchCallbackPGPool;
+  function patchClientConnectCallback(span, cb) {
+    return function patchedClientConnectCallback(err) {
+      if (err) {
+        if (err instanceof Error) {
+          span.recordException(sanitizedErrorMessage(err));
+        }
+        span.setStatus({
+          code: api_1.SpanStatusCode.ERROR,
+          message: err.message
+        });
+      }
+      span.end();
+      cb.apply(this, arguments);
+    };
+  }
+  utils$5.patchClientConnectCallback = patchClientConnectCallback;
+  function getErrorMessage(e) {
+    return typeof e === "object" && e !== null && "message" in e ? String(e.message) : void 0;
+  }
+  utils$5.getErrorMessage = getErrorMessage;
+  function isObjectWithTextString(it) {
+    return typeof it === "object" && typeof it?.text === "string";
+  }
+  utils$5.isObjectWithTextString = isObjectWithTextString;
+  function sanitizedErrorMessage(error2) {
+    const name = error2?.name ?? "PostgreSQLError";
+    const code = error2?.code ?? "UNKNOWN";
+    return `PostgreSQL error of type '${name}' occurred (code: ${code})`;
+  }
+  utils$5.sanitizedErrorMessage = sanitizedErrorMessage;
+  return utils$5;
+}
+var version$6 = {};
+var hasRequiredVersion$6;
+function requireVersion$6() {
+  if (hasRequiredVersion$6) return version$6;
+  hasRequiredVersion$6 = 1;
+  Object.defineProperty(version$6, "__esModule", { value: true });
+  version$6.PACKAGE_NAME = version$6.PACKAGE_VERSION = void 0;
+  version$6.PACKAGE_VERSION = "0.61.0";
+  version$6.PACKAGE_NAME = "@opentelemetry/instrumentation-pg";
+  return version$6;
+}
+var hasRequiredInstrumentation$5;
+function requireInstrumentation$5() {
+  if (hasRequiredInstrumentation$5) return instrumentation$5;
+  hasRequiredInstrumentation$5 = 1;
+  Object.defineProperty(instrumentation$5, "__esModule", { value: true });
+  instrumentation$5.PgInstrumentation = void 0;
+  const instrumentation_1 = require$$2;
+  const api_1 = /* @__PURE__ */ requireSrc$n();
+  const internal_types_1 = requireInternalTypes$3();
+  const utils2 = requireUtils$5();
+  const sql_common_1 = requireSrc$b();
+  const version_1 = requireVersion$6();
+  const SpanNames_1 = requireSpanNames();
+  const core_1 = require$$1;
+  const semantic_conventions_1 = /* @__PURE__ */ requireSrc$m();
+  const semconv_1 = requireSemconv$3();
+  function extractModuleExports(module2) {
+    return module2[Symbol.toStringTag] === "Module" ? module2.default : module2;
+  }
+  class PgInstrumentation extends instrumentation_1.InstrumentationBase {
+    // Pool events connect, acquire, release and remove can be called
+    // multiple times without changing the values of total, idle and waiting
+    // connections. The _connectionsCounter is used to keep track of latest
+    // values and only update the metrics _connectionsCount and _connectionPendingRequests
+    // when the value change.
+    _connectionsCounter = {
+      used: 0,
+      idle: 0,
+      pending: 0
+    };
+    _semconvStability;
+    constructor(config2 = {}) {
+      super(version_1.PACKAGE_NAME, version_1.PACKAGE_VERSION, config2);
+      this._semconvStability = (0, instrumentation_1.semconvStabilityFromStr)("database", process.env.OTEL_SEMCONV_STABILITY_OPT_IN);
+    }
+    _updateMetricInstruments() {
+      this._operationDuration = this.meter.createHistogram(semantic_conventions_1.METRIC_DB_CLIENT_OPERATION_DURATION, {
+        description: "Duration of database client operations.",
+        unit: "s",
+        valueType: api_1.ValueType.DOUBLE,
+        advice: {
+          explicitBucketBoundaries: [
+            1e-3,
+            5e-3,
+            0.01,
+            0.05,
+            0.1,
+            0.5,
+            1,
+            5,
+            10
+          ]
+        }
+      });
+      this._connectionsCounter = {
+        idle: 0,
+        pending: 0,
+        used: 0
+      };
+      this._connectionsCount = this.meter.createUpDownCounter(semconv_1.METRIC_DB_CLIENT_CONNECTION_COUNT, {
+        description: "The number of connections that are currently in state described by the state attribute.",
+        unit: "{connection}"
+      });
+      this._connectionPendingRequests = this.meter.createUpDownCounter(semconv_1.METRIC_DB_CLIENT_CONNECTION_PENDING_REQUESTS, {
+        description: "The number of current pending requests for an open connection.",
+        unit: "{connection}"
+      });
+    }
+    init() {
+      const SUPPORTED_PG_VERSIONS = [">=8.0.3 <9"];
+      const SUPPORTED_PG_POOL_VERSIONS = [">=2.0.0 <4"];
+      const modulePgNativeClient = new instrumentation_1.InstrumentationNodeModuleFile("pg/lib/native/client.js", SUPPORTED_PG_VERSIONS, this._patchPgClient.bind(this), this._unpatchPgClient.bind(this));
+      const modulePgClient = new instrumentation_1.InstrumentationNodeModuleFile("pg/lib/client.js", SUPPORTED_PG_VERSIONS, this._patchPgClient.bind(this), this._unpatchPgClient.bind(this));
+      const modulePG = new instrumentation_1.InstrumentationNodeModuleDefinition("pg", SUPPORTED_PG_VERSIONS, (module2) => {
+        const moduleExports = extractModuleExports(module2);
+        this._patchPgClient(moduleExports.Client);
+        return module2;
+      }, (module2) => {
+        const moduleExports = extractModuleExports(module2);
+        this._unpatchPgClient(moduleExports.Client);
+        return module2;
+      }, [modulePgClient, modulePgNativeClient]);
+      const modulePGPool = new instrumentation_1.InstrumentationNodeModuleDefinition("pg-pool", SUPPORTED_PG_POOL_VERSIONS, (module2) => {
+        const moduleExports = extractModuleExports(module2);
+        if ((0, instrumentation_1.isWrapped)(moduleExports.prototype.connect)) {
+          this._unwrap(moduleExports.prototype, "connect");
+        }
+        this._wrap(moduleExports.prototype, "connect", this._getPoolConnectPatch());
+        return moduleExports;
+      }, (module2) => {
+        const moduleExports = extractModuleExports(module2);
+        if ((0, instrumentation_1.isWrapped)(moduleExports.prototype.connect)) {
+          this._unwrap(moduleExports.prototype, "connect");
+        }
+      });
+      return [modulePG, modulePGPool];
+    }
+    _patchPgClient(module2) {
+      if (!module2) {
+        return;
+      }
+      const moduleExports = extractModuleExports(module2);
+      if ((0, instrumentation_1.isWrapped)(moduleExports.prototype.query)) {
+        this._unwrap(moduleExports.prototype, "query");
+      }
+      if ((0, instrumentation_1.isWrapped)(moduleExports.prototype.connect)) {
+        this._unwrap(moduleExports.prototype, "connect");
+      }
+      this._wrap(moduleExports.prototype, "query", this._getClientQueryPatch());
+      this._wrap(moduleExports.prototype, "connect", this._getClientConnectPatch());
+      return module2;
+    }
+    _unpatchPgClient(module2) {
+      const moduleExports = extractModuleExports(module2);
+      if ((0, instrumentation_1.isWrapped)(moduleExports.prototype.query)) {
+        this._unwrap(moduleExports.prototype, "query");
+      }
+      if ((0, instrumentation_1.isWrapped)(moduleExports.prototype.connect)) {
+        this._unwrap(moduleExports.prototype, "connect");
+      }
+      return module2;
+    }
+    _getClientConnectPatch() {
+      const plugin = this;
+      return (original) => {
+        return function connect(callback) {
+          if (utils2.shouldSkipInstrumentation(plugin.getConfig())) {
+            return original.call(this, callback);
+          }
+          const span = plugin.tracer.startSpan(SpanNames_1.SpanNames.CONNECT, {
+            kind: api_1.SpanKind.CLIENT,
+            attributes: utils2.getSemanticAttributesFromConnection(this, plugin._semconvStability)
+          });
+          if (callback) {
+            const parentSpan = api_1.trace.getSpan(api_1.context.active());
+            callback = utils2.patchClientConnectCallback(span, callback);
+            if (parentSpan) {
+              callback = api_1.context.bind(api_1.context.active(), callback);
+            }
+          }
+          const connectResult = api_1.context.with(api_1.trace.setSpan(api_1.context.active(), span), () => {
+            return original.call(this, callback);
+          });
+          return handleConnectResult(span, connectResult);
+        };
+      };
+    }
+    recordOperationDuration(attributes, startTime) {
+      const metricsAttributes = {};
+      const keysToCopy = [
+        semantic_conventions_1.ATTR_DB_NAMESPACE,
+        semantic_conventions_1.ATTR_ERROR_TYPE,
+        semantic_conventions_1.ATTR_SERVER_PORT,
+        semantic_conventions_1.ATTR_SERVER_ADDRESS,
+        semantic_conventions_1.ATTR_DB_OPERATION_NAME
+      ];
+      if (this._semconvStability & instrumentation_1.SemconvStability.OLD) {
+        keysToCopy.push(semconv_1.ATTR_DB_SYSTEM);
+      }
+      if (this._semconvStability & instrumentation_1.SemconvStability.STABLE) {
+        keysToCopy.push(semantic_conventions_1.ATTR_DB_SYSTEM_NAME);
+      }
+      keysToCopy.forEach((key) => {
+        if (key in attributes) {
+          metricsAttributes[key] = attributes[key];
+        }
+      });
+      const durationSeconds = (0, core_1.hrTimeToMilliseconds)((0, core_1.hrTimeDuration)(startTime, (0, core_1.hrTime)())) / 1e3;
+      this._operationDuration.record(durationSeconds, metricsAttributes);
+    }
+    _getClientQueryPatch() {
+      const plugin = this;
+      return (original) => {
+        this._diag.debug("Patching pg.Client.prototype.query");
+        return function query(...args) {
+          if (utils2.shouldSkipInstrumentation(plugin.getConfig())) {
+            return original.apply(this, args);
+          }
+          const startTime = (0, core_1.hrTime)();
+          const arg0 = args[0];
+          const firstArgIsString = typeof arg0 === "string";
+          const firstArgIsQueryObjectWithText = utils2.isObjectWithTextString(arg0);
+          const queryConfig = firstArgIsString ? {
+            text: arg0,
+            values: Array.isArray(args[1]) ? args[1] : void 0
+          } : firstArgIsQueryObjectWithText ? arg0 : void 0;
+          const attributes = {
+            [semconv_1.ATTR_DB_SYSTEM]: semconv_1.DB_SYSTEM_VALUE_POSTGRESQL,
+            [semantic_conventions_1.ATTR_DB_NAMESPACE]: this.database,
+            [semantic_conventions_1.ATTR_SERVER_PORT]: this.connectionParameters.port,
+            [semantic_conventions_1.ATTR_SERVER_ADDRESS]: this.connectionParameters.host
+          };
+          if (queryConfig?.text) {
+            attributes[semantic_conventions_1.ATTR_DB_OPERATION_NAME] = utils2.parseNormalizedOperationName(queryConfig?.text);
+          }
+          const recordDuration = () => {
+            plugin.recordOperationDuration(attributes, startTime);
+          };
+          const instrumentationConfig = plugin.getConfig();
+          const span = utils2.handleConfigQuery.call(this, plugin.tracer, instrumentationConfig, plugin._semconvStability, queryConfig);
+          if (instrumentationConfig.addSqlCommenterCommentToQueries) {
+            if (firstArgIsString) {
+              args[0] = (0, sql_common_1.addSqlCommenterComment)(span, arg0);
+            } else if (firstArgIsQueryObjectWithText && !("name" in arg0)) {
+              args[0] = {
+                ...arg0,
+                text: (0, sql_common_1.addSqlCommenterComment)(span, arg0.text)
+              };
+            }
+          }
+          if (args.length > 0) {
+            const parentSpan = api_1.trace.getSpan(api_1.context.active());
+            if (typeof args[args.length - 1] === "function") {
+              args[args.length - 1] = utils2.patchCallback(
+                instrumentationConfig,
+                span,
+                args[args.length - 1],
+                // nb: not type safe.
+                attributes,
+                recordDuration
+              );
+              if (parentSpan) {
+                args[args.length - 1] = api_1.context.bind(api_1.context.active(), args[args.length - 1]);
+              }
+            } else if (typeof queryConfig?.callback === "function") {
+              let callback = utils2.patchCallback(
+                plugin.getConfig(),
+                span,
+                queryConfig.callback,
+                // nb: not type safe.
+                attributes,
+                recordDuration
+              );
+              if (parentSpan) {
+                callback = api_1.context.bind(api_1.context.active(), callback);
+              }
+              args[0].callback = callback;
+            }
+          }
+          const { requestHook: requestHook2 } = instrumentationConfig;
+          if (typeof requestHook2 === "function" && queryConfig) {
+            (0, instrumentation_1.safeExecuteInTheMiddle)(() => {
+              const { database, host, port, user } = this.connectionParameters;
+              const connection = { database, host, port, user };
+              requestHook2(span, {
+                connection,
+                query: {
+                  text: queryConfig.text,
+                  // nb: if `client.query` is called with illegal arguments
+                  // (e.g., if `queryConfig.values` is passed explicitly, but a
+                  // non-array is given), then the type casts will be wrong. But
+                  // we leave it up to the queryHook to handle that, and we
+                  // catch and swallow any errors it throws. The other options
+                  // are all worse. E.g., we could leave `queryConfig.values`
+                  // and `queryConfig.name` as `unknown`, but then the hook body
+                  // would be forced to validate (or cast) them before using
+                  // them, which seems incredibly cumbersome given that these
+                  // casts will be correct 99.9% of the time -- and pg.query
+                  // will immediately throw during development in the other .1%
+                  // of cases. Alternatively, we could simply skip calling the
+                  // hook when `values` or `name` don't have the expected type,
+                  // but that would add unnecessary validation overhead to every
+                  // hook invocation and possibly be even more confusing/unexpected.
+                  values: queryConfig.values,
+                  name: queryConfig.name
+                }
+              });
+            }, (err) => {
+              if (err) {
+                plugin._diag.error("Error running query hook", err);
+              }
+            }, true);
+          }
+          let result;
+          try {
+            result = original.apply(this, args);
+          } catch (e) {
+            if (e instanceof Error) {
+              span.recordException(utils2.sanitizedErrorMessage(e));
+            }
+            span.setStatus({
+              code: api_1.SpanStatusCode.ERROR,
+              message: utils2.getErrorMessage(e)
+            });
+            span.end();
+            throw e;
+          }
+          if (result instanceof Promise) {
+            return result.then((result2) => {
+              return new Promise((resolve) => {
+                utils2.handleExecutionResult(plugin.getConfig(), span, result2);
+                recordDuration();
+                span.end();
+                resolve(result2);
+              });
+            }).catch((error2) => {
+              return new Promise((_, reject) => {
+                if (error2 instanceof Error) {
+                  span.recordException(utils2.sanitizedErrorMessage(error2));
+                }
+                span.setStatus({
+                  code: api_1.SpanStatusCode.ERROR,
+                  message: error2.message
+                });
+                recordDuration();
+                span.end();
+                reject(error2);
+              });
+            });
+          }
+          return result;
+        };
+      };
+    }
+    _setPoolConnectEventListeners(pgPool) {
+      if (pgPool[internal_types_1.EVENT_LISTENERS_SET])
+        return;
+      const poolName = utils2.getPoolName(pgPool.options);
+      pgPool.on("connect", () => {
+        this._connectionsCounter = utils2.updateCounter(poolName, pgPool, this._connectionsCount, this._connectionPendingRequests, this._connectionsCounter);
+      });
+      pgPool.on("acquire", () => {
+        this._connectionsCounter = utils2.updateCounter(poolName, pgPool, this._connectionsCount, this._connectionPendingRequests, this._connectionsCounter);
+      });
+      pgPool.on("remove", () => {
+        this._connectionsCounter = utils2.updateCounter(poolName, pgPool, this._connectionsCount, this._connectionPendingRequests, this._connectionsCounter);
+      });
+      pgPool.on("release", () => {
+        this._connectionsCounter = utils2.updateCounter(poolName, pgPool, this._connectionsCount, this._connectionPendingRequests, this._connectionsCounter);
+      });
+      pgPool[internal_types_1.EVENT_LISTENERS_SET] = true;
+    }
+    _getPoolConnectPatch() {
+      const plugin = this;
+      return (originalConnect) => {
+        return function connect(callback) {
+          if (utils2.shouldSkipInstrumentation(plugin.getConfig())) {
+            return originalConnect.call(this, callback);
+          }
+          const span = plugin.tracer.startSpan(SpanNames_1.SpanNames.POOL_CONNECT, {
+            kind: api_1.SpanKind.CLIENT,
+            attributes: utils2.getSemanticAttributesFromPoolConnection(this.options, plugin._semconvStability)
+          });
+          plugin._setPoolConnectEventListeners(this);
+          if (callback) {
+            const parentSpan = api_1.trace.getSpan(api_1.context.active());
+            callback = utils2.patchCallbackPGPool(span, callback);
+            if (parentSpan) {
+              callback = api_1.context.bind(api_1.context.active(), callback);
+            }
+          }
+          const connectResult = api_1.context.with(api_1.trace.setSpan(api_1.context.active(), span), () => {
+            return originalConnect.call(this, callback);
+          });
+          return handleConnectResult(span, connectResult);
+        };
+      };
+    }
+  }
+  instrumentation$5.PgInstrumentation = PgInstrumentation;
+  function handleConnectResult(span, connectResult) {
+    if (!(connectResult instanceof Promise)) {
+      return connectResult;
+    }
+    const connectResultPromise = connectResult;
+    return api_1.context.bind(api_1.context.active(), connectResultPromise.then((result) => {
+      span.end();
+      return result;
+    }).catch((error2) => {
+      if (error2 instanceof Error) {
+        span.recordException(utils2.sanitizedErrorMessage(error2));
+      }
+      span.setStatus({
+        code: api_1.SpanStatusCode.ERROR,
+        message: utils2.getErrorMessage(error2)
+      });
+      span.end();
+      return Promise.reject(error2);
+    }));
+  }
+  return instrumentation$5;
+}
+var hasRequiredSrc$6;
+function requireSrc$6() {
+  if (hasRequiredSrc$6) return src$6;
+  hasRequiredSrc$6 = 1;
+  (function(exports$1) {
+    Object.defineProperty(exports$1, "__esModule", { value: true });
+    exports$1.AttributeNames = exports$1.PgInstrumentation = void 0;
+    var instrumentation_1 = requireInstrumentation$5();
+    Object.defineProperty(exports$1, "PgInstrumentation", { enumerable: true, get: function() {
+      return instrumentation_1.PgInstrumentation;
+    } });
+    var AttributeNames_1 = requireAttributeNames$3();
+    Object.defineProperty(exports$1, "AttributeNames", { enumerable: true, get: function() {
+      return AttributeNames_1.AttributeNames;
+    } });
+  })(src$6);
+  return src$6;
+}
+var srcExports$6 = requireSrc$6();
+const INTEGRATION_NAME$b = "Postgres";
+const instrumentPostgres = generateInstrumentOnce(
+  INTEGRATION_NAME$b,
+  () => new srcExports$6.PgInstrumentation({
+    requireParentSpan: true,
+    requestHook(span) {
+      addOriginToSpan(span, "auto.db.otel.postgres");
+    }
+  })
+);
+const _postgresIntegration = (() => {
+  return {
+    name: INTEGRATION_NAME$b,
+    setupOnce() {
+      instrumentPostgres();
+    }
+  };
+});
+const postgresIntegration = defineIntegration(_postgresIntegration);
+const INTEGRATION_NAME$a = "PostgresJs";
+const SUPPORTED_VERSIONS = [">=3.0.0 <4"];
+const SQL_OPERATION_REGEX = /^(SELECT|INSERT|UPDATE|DELETE|CREATE|DROP|ALTER)/i;
+const CONNECTION_CONTEXT_SYMBOL = Symbol("sentryPostgresConnectionContext");
+const INSTRUMENTED_MARKER = Symbol.for("sentry.instrumented.postgresjs");
+const QUERY_FROM_INSTRUMENTED_SQL = Symbol.for("sentry.query.from.instrumented.sql");
+const instrumentPostgresJs = generateInstrumentOnce(
+  INTEGRATION_NAME$a,
+  (options) => new PostgresJsInstrumentation({
+    requireParentSpan: options?.requireParentSpan ?? true,
+    requestHook: options?.requestHook
+  })
+);
+class PostgresJsInstrumentation extends InstrumentationBase {
+  constructor(config2) {
+    super("sentry-postgres-js", SDK_VERSION, config2);
+  }
+  /**
+   * Initializes the instrumentation by patching the postgres module.
+   * Uses two complementary approaches:
+   * 1. Main function wrapper: instruments sql instances created AFTER instrumentation is set up (CJS + ESM)
+   * 2. Query.prototype patch: fallback for sql instances created BEFORE instrumentation (CJS only)
+   */
+  init() {
+    const module2 = new InstrumentationNodeModuleDefinition(
+      "postgres",
+      SUPPORTED_VERSIONS,
+      (exports$1) => {
+        try {
+          return this._patchPostgres(exports$1);
+        } catch (e) {
+          DEBUG_BUILD && debug$2.error("Failed to patch postgres module:", e);
+          return exports$1;
+        }
+      },
+      (exports$1) => exports$1
+    );
+    ["src", "cf/src", "cjs/src"].forEach((path2) => {
+      module2.files.push(
+        new InstrumentationNodeModuleFile(
+          `postgres/${path2}/query.js`,
+          SUPPORTED_VERSIONS,
+          this._patchQueryPrototype.bind(this),
+          this._unpatchQueryPrototype.bind(this)
+        )
+      );
+    });
+    return module2;
+  }
+  /**
+   * Patches the postgres module by wrapping the main export function.
+   * This intercepts the creation of sql instances and instruments them.
+   */
+  _patchPostgres(exports$1) {
+    const isFunction2 = typeof exports$1 === "function";
+    const Original = isFunction2 ? exports$1 : exports$1.default;
+    if (typeof Original !== "function") {
+      DEBUG_BUILD && debug$2.warn("postgres module does not export a function. Skipping instrumentation.");
+      return exports$1;
+    }
+    const self = this;
+    const WrappedPostgres = function(...args) {
+      const sql = Reflect.construct(Original, args);
+      if (!sql || typeof sql !== "function") {
+        DEBUG_BUILD && debug$2.warn("postgres() did not return a valid instance");
+        return sql;
+      }
+      return self._instrumentSqlInstance(sql);
+    };
+    Object.setPrototypeOf(WrappedPostgres, Original);
+    Object.setPrototypeOf(WrappedPostgres.prototype, Original.prototype);
+    for (const key of Object.getOwnPropertyNames(Original)) {
+      if (!["length", "name", "prototype"].includes(key)) {
+        const descriptor = Object.getOwnPropertyDescriptor(Original, key);
+        if (descriptor) {
+          Object.defineProperty(WrappedPostgres, key, descriptor);
+        }
+      }
+    }
+    if (isFunction2) {
+      return WrappedPostgres;
+    } else {
+      replaceExports(exports$1, "default", WrappedPostgres);
+      return exports$1;
+    }
+  }
+  /**
+   * Wraps query-returning methods (unsafe, file) to ensure their queries are instrumented.
+   */
+  _wrapQueryMethod(original, target, proxiedSql) {
+    const self = this;
+    return function(...args) {
+      const query = Reflect.apply(original, target, args);
+      if (query && typeof query === "object" && "handle" in query) {
+        self._wrapSingleQueryHandle(query, proxiedSql);
+      }
+      return query;
+    };
+  }
+  /**
+   * Wraps callback-based methods (begin, reserve) to recursively instrument Sql instances.
+   * Note: These methods can also be used as tagged templates, which we pass through unchanged.
+   *
+   * Savepoint is not wrapped to avoid complex nested transaction instrumentation issues.
+   * Queries within savepoint callbacks are still instrumented through the parent transaction's Sql instance.
+   */
+  _wrapCallbackMethod(original, target, parentSqlInstance) {
+    const self = this;
+    return function(...args) {
+      const parentContext = parentSqlInstance[CONNECTION_CONTEXT_SYMBOL];
+      const isCallbackBased = typeof args[args.length - 1] === "function";
+      if (!isCallbackBased) {
+        const result = Reflect.apply(original, target, args);
+        if (result && typeof result.then === "function") {
+          return result.then((sqlInstance) => {
+            return self._instrumentSqlInstance(sqlInstance, parentContext);
+          });
+        }
+        return result;
+      }
+      const callback = args.length === 1 ? args[0] : args[1];
+      const wrappedCallback = function(sqlInstance) {
+        const instrumentedSql = self._instrumentSqlInstance(sqlInstance, parentContext);
+        return callback(instrumentedSql);
+      };
+      const newArgs = args.length === 1 ? [wrappedCallback] : [args[0], wrappedCallback];
+      return Reflect.apply(original, target, newArgs);
+    };
+  }
+  /**
+   * Sets connection context attributes on a span.
+   */
+  _setConnectionAttributes(span, connectionContext) {
+    if (!connectionContext) {
+      return;
+    }
+    if (connectionContext.ATTR_DB_NAMESPACE) {
+      span.setAttribute(srcExports$k.ATTR_DB_NAMESPACE, connectionContext.ATTR_DB_NAMESPACE);
+    }
+    if (connectionContext.ATTR_SERVER_ADDRESS) {
+      span.setAttribute(srcExports$k.ATTR_SERVER_ADDRESS, connectionContext.ATTR_SERVER_ADDRESS);
+    }
+    if (connectionContext.ATTR_SERVER_PORT !== void 0) {
+      const portNumber = parseInt(connectionContext.ATTR_SERVER_PORT, 10);
+      if (!isNaN(portNumber)) {
+        span.setAttribute(srcExports$k.ATTR_SERVER_PORT, portNumber);
+      }
+    }
+  }
+  /**
+   * Extracts DB operation name from SQL query and sets it on the span.
+   */
+  _setOperationName(span, sanitizedQuery, command) {
+    if (command) {
+      span.setAttribute(srcExports$k.ATTR_DB_OPERATION_NAME, command);
+      return;
+    }
+    const operationMatch = sanitizedQuery?.match(SQL_OPERATION_REGEX);
+    if (operationMatch?.[1]) {
+      span.setAttribute(srcExports$k.ATTR_DB_OPERATION_NAME, operationMatch[1].toUpperCase());
+    }
+  }
+  /**
+   * Extracts and stores connection context from sql.options.
+   */
+  _attachConnectionContext(sql, proxiedSql) {
+    const sqlInstance = sql;
+    if (!sqlInstance.options || typeof sqlInstance.options !== "object") {
+      return;
+    }
+    const opts = sqlInstance.options;
+    const host = opts.host?.[0] || "localhost";
+    const port = opts.port?.[0] || 5432;
+    const connectionContext = {
+      ATTR_DB_NAMESPACE: typeof opts.database === "string" && opts.database !== "" ? opts.database : void 0,
+      ATTR_SERVER_ADDRESS: host,
+      ATTR_SERVER_PORT: String(port)
+    };
+    proxiedSql[CONNECTION_CONTEXT_SYMBOL] = connectionContext;
+  }
+  /**
+   * Instruments a sql instance by wrapping its query execution methods.
+   */
+  _instrumentSqlInstance(sql, parentConnectionContext) {
+    if (sql[INSTRUMENTED_MARKER]) {
+      return sql;
+    }
+    const self = this;
+    const proxiedSql = new Proxy(sql, {
+      apply(target, thisArg, argumentsList) {
+        const query = Reflect.apply(target, thisArg, argumentsList);
+        if (query && typeof query === "object" && "handle" in query) {
+          self._wrapSingleQueryHandle(query, proxiedSql);
+        }
+        return query;
+      },
+      get(target, prop) {
+        const original = target[prop];
+        if (typeof prop !== "string" || typeof original !== "function") {
+          return original;
+        }
+        if (prop === "unsafe" || prop === "file") {
+          return self._wrapQueryMethod(original, target, proxiedSql);
+        }
+        if (prop === "begin" || prop === "reserve") {
+          return self._wrapCallbackMethod(original, target, proxiedSql);
+        }
+        return original;
+      }
+    });
+    if (parentConnectionContext) {
+      proxiedSql[CONNECTION_CONTEXT_SYMBOL] = parentConnectionContext;
+    } else {
+      this._attachConnectionContext(sql, proxiedSql);
+    }
+    sql[INSTRUMENTED_MARKER] = true;
+    proxiedSql[INSTRUMENTED_MARKER] = true;
+    return proxiedSql;
+  }
+  /**
+   * Wraps a single query's handle method to create spans.
+   */
+  _wrapSingleQueryHandle(query, sqlInstance) {
+    if (query.handle?.__sentryWrapped) {
+      return;
+    }
+    query[QUERY_FROM_INSTRUMENTED_SQL] = true;
+    const originalHandle = query.handle;
+    const self = this;
+    const wrappedHandle = async function(...args) {
+      if (!self._shouldCreateSpans()) {
+        return originalHandle.apply(this, args);
+      }
+      const fullQuery = self._reconstructQuery(query.strings);
+      const sanitizedSqlQuery = self._sanitizeSqlQuery(fullQuery);
+      return startSpanManual$1(
+        {
+          name: sanitizedSqlQuery || "postgresjs.query",
+          op: "db"
+        },
+        (span) => {
+          addOriginToSpan(span, "auto.db.postgresjs");
+          span.setAttributes({
+            [srcExports$k.ATTR_DB_SYSTEM_NAME]: "postgres",
+            [srcExports$k.ATTR_DB_QUERY_TEXT]: sanitizedSqlQuery
+          });
+          const connectionContext = sqlInstance ? sqlInstance[CONNECTION_CONTEXT_SYMBOL] : void 0;
+          self._setConnectionAttributes(span, connectionContext);
+          const config2 = self.getConfig();
+          const { requestHook: requestHook2 } = config2;
+          if (requestHook2) {
+            safeExecuteInTheMiddle(
+              () => requestHook2(span, sanitizedSqlQuery, connectionContext),
+              (e) => {
+                if (e) {
+                  span.setAttribute("sentry.hook.error", "requestHook failed");
+                  DEBUG_BUILD && debug$2.error(`Error in requestHook for ${INTEGRATION_NAME$a} integration:`, e);
+                }
+              },
+              true
+            );
+          }
+          const queryWithCallbacks = this;
+          queryWithCallbacks.resolve = new Proxy(queryWithCallbacks.resolve, {
+            apply: (resolveTarget, resolveThisArg, resolveArgs) => {
+              try {
+                self._setOperationName(span, sanitizedSqlQuery, resolveArgs?.[0]?.command);
+                span.end();
+              } catch (e) {
+                DEBUG_BUILD && debug$2.error("Error ending span in resolve callback:", e);
+              }
+              return Reflect.apply(resolveTarget, resolveThisArg, resolveArgs);
+            }
+          });
+          queryWithCallbacks.reject = new Proxy(queryWithCallbacks.reject, {
+            apply: (rejectTarget, rejectThisArg, rejectArgs) => {
+              try {
+                span.setStatus({
+                  code: SPAN_STATUS_ERROR,
+                  message: rejectArgs?.[0]?.message || "unknown_error"
+                });
+                span.setAttribute(srcExports$k.ATTR_DB_RESPONSE_STATUS_CODE, rejectArgs?.[0]?.code || "unknown");
+                span.setAttribute(srcExports$k.ATTR_ERROR_TYPE, rejectArgs?.[0]?.name || "unknown");
+                self._setOperationName(span, sanitizedSqlQuery);
+                span.end();
+              } catch (e) {
+                DEBUG_BUILD && debug$2.error("Error ending span in reject callback:", e);
+              }
+              return Reflect.apply(rejectTarget, rejectThisArg, rejectArgs);
+            }
+          });
+          try {
+            return originalHandle.apply(this, args);
+          } catch (e) {
+            span.setStatus({
+              code: SPAN_STATUS_ERROR,
+              message: e instanceof Error ? e.message : "unknown_error"
+            });
+            span.end();
+            throw e;
+          }
+        }
+      );
+    };
+    wrappedHandle.__sentryWrapped = true;
+    query.handle = wrappedHandle;
+  }
+  /**
+   * Determines whether a span should be created based on the current context.
+   * If `requireParentSpan` is set to true in the configuration, a span will
+   * only be created if there is a parent span available.
+   */
+  _shouldCreateSpans() {
+    const config2 = this.getConfig();
+    const hasParentSpan = srcExports$l.trace.getSpan(srcExports$l.context.active()) !== void 0;
+    return hasParentSpan || !config2.requireParentSpan;
+  }
+  /**
+   * Reconstructs the full SQL query from template strings with PostgreSQL placeholders.
+   *
+   * For sql`SELECT * FROM users WHERE id = ${123} AND name = ${'foo'}`:
+   *   strings = ["SELECT * FROM users WHERE id = ", " AND name = ", ""]
+   *   returns: "SELECT * FROM users WHERE id = $1 AND name = $2"
+   */
+  _reconstructQuery(strings) {
+    if (!strings?.length) {
+      return void 0;
+    }
+    if (strings.length === 1) {
+      return strings[0] || void 0;
+    }
+    return strings.reduce((acc, str, i) => i === 0 ? str : `${acc}$${i}${str}`, "");
+  }
+  /**
+   * Sanitize SQL query as per the OTEL semantic conventions
+   * https://opentelemetry.io/docs/specs/semconv/database/database-spans/#sanitization-of-dbquerytext
+   *
+   * PostgreSQL $n placeholders are preserved per OTEL spec - they're parameterized queries,
+   * not sensitive literals. Only actual values (strings, numbers, booleans) are sanitized.
+   */
+  _sanitizeSqlQuery(sqlQuery) {
+    if (!sqlQuery) {
+      return "Unknown SQL Query";
+    }
+    return sqlQuery.replace(/--.*$/gm, "").replace(/\/\*[\s\S]*?\*\//g, "").replace(/;\s*$/, "").replace(/\s+/g, " ").trim().replace(/\bX'[0-9A-Fa-f]*'/gi, "?").replace(/\bB'[01]*'/gi, "?").replace(/'(?:[^']|'')*'/g, "?").replace(/\b0x[0-9A-Fa-f]+/gi, "?").replace(/\b(?:TRUE|FALSE)\b/gi, "?").replace(/-?\b\d+\.?\d*[eE][+-]?\d+\b/g, "?").replace(/-?\b\d+\.\d+\b/g, "?").replace(/-?\.\d+\b/g, "?").replace(new RegExp("(? {
+          addOriginToSpan(span, "auto.db.postgresjs");
+          span.setAttributes({
+            [srcExports$k.ATTR_DB_SYSTEM_NAME]: "postgres",
+            [srcExports$k.ATTR_DB_QUERY_TEXT]: sanitizedSqlQuery
+          });
+          const config2 = self.getConfig();
+          const { requestHook: requestHook2 } = config2;
+          if (requestHook2) {
+            safeExecuteInTheMiddle(
+              () => requestHook2(span, sanitizedSqlQuery, void 0),
+              (e) => {
+                if (e) {
+                  span.setAttribute("sentry.hook.error", "requestHook failed");
+                  DEBUG_BUILD && debug$2.error(`Error in requestHook for ${INTEGRATION_NAME$a} integration:`, e);
+                }
+              },
+              true
+            );
+          }
+          const originalResolve = this.resolve;
+          this.resolve = new Proxy(originalResolve, {
+            apply: (resolveTarget, resolveThisArg, resolveArgs) => {
+              try {
+                self._setOperationName(span, sanitizedSqlQuery, resolveArgs?.[0]?.command);
+                span.end();
+              } catch (e) {
+                DEBUG_BUILD && debug$2.error("Error ending span in resolve callback:", e);
+              }
+              return Reflect.apply(resolveTarget, resolveThisArg, resolveArgs);
+            }
+          });
+          const originalReject = this.reject;
+          this.reject = new Proxy(originalReject, {
+            apply: (rejectTarget, rejectThisArg, rejectArgs) => {
+              try {
+                span.setStatus({
+                  code: SPAN_STATUS_ERROR,
+                  message: rejectArgs?.[0]?.message || "unknown_error"
+                });
+                span.setAttribute(srcExports$k.ATTR_DB_RESPONSE_STATUS_CODE, rejectArgs?.[0]?.code || "unknown");
+                span.setAttribute(srcExports$k.ATTR_ERROR_TYPE, rejectArgs?.[0]?.name || "unknown");
+                self._setOperationName(span, sanitizedSqlQuery);
+                span.end();
+              } catch (e) {
+                DEBUG_BUILD && debug$2.error("Error ending span in reject callback:", e);
+              }
+              return Reflect.apply(rejectTarget, rejectThisArg, rejectArgs);
+            }
+          });
+          try {
+            return originalHandle.apply(this, args);
+          } catch (e) {
+            span.setStatus({
+              code: SPAN_STATUS_ERROR,
+              message: e instanceof Error ? e.message : "unknown_error"
+            });
+            span.end();
+            throw e;
+          }
+        }
+      );
+    };
+    moduleExports.Query.prototype.handle.__sentry_original__ = originalHandle;
+    return moduleExports;
+  }
+  /**
+   * Restores the original Query.prototype.handle method.
+   */
+  _unpatchQueryPrototype(moduleExports) {
+    if (moduleExports.Query.prototype.handle.__sentry_original__) {
+      moduleExports.Query.prototype.handle = moduleExports.Query.prototype.handle.__sentry_original__;
+    }
+    return moduleExports;
+  }
+}
+const _postgresJsIntegration = ((options) => {
+  return {
+    name: INTEGRATION_NAME$a,
+    setupOnce() {
+      instrumentPostgresJs(options);
+    }
+  };
+});
+const postgresJsIntegration = defineIntegration(_postgresJsIntegration);
+var showAllTraces = process.env.PRISMA_SHOW_ALL_TRACES === "true";
+var nonSampledTraceParent = `00-10-10-00`;
+function engineSpanKindToOtelSpanKind(engineSpanKind) {
+  switch (engineSpanKind) {
+    case "client":
+      return srcExports$l.SpanKind.CLIENT;
+    case "internal":
+    default:
+      return srcExports$l.SpanKind.INTERNAL;
+  }
+}
+var ActiveTracingHelper = class {
+  tracerProvider;
+  ignoreSpanTypes;
+  constructor({ tracerProvider, ignoreSpanTypes }) {
+    this.tracerProvider = tracerProvider;
+    this.ignoreSpanTypes = ignoreSpanTypes;
+  }
+  isEnabled() {
+    return true;
+  }
+  getTraceParent(context2) {
+    const span = srcExports$l.trace.getSpanContext(context2 ?? srcExports$l.context.active());
+    if (span) {
+      return `00-${span.traceId}-${span.spanId}-0${span.traceFlags}`;
+    }
+    return nonSampledTraceParent;
+  }
+  dispatchEngineSpans(spans) {
+    const tracer = this.tracerProvider.getTracer("prisma");
+    const linkIds = /* @__PURE__ */ new Map();
+    const roots = spans.filter((span) => span.parentId === null);
+    for (const root of roots) {
+      dispatchEngineSpan(tracer, root, spans, linkIds, this.ignoreSpanTypes);
+    }
+  }
+  getActiveContext() {
+    return srcExports$l.context.active();
+  }
+  runInChildSpan(options, callback) {
+    if (typeof options === "string") {
+      options = { name: options };
+    }
+    if (options.internal && !showAllTraces) {
+      return callback();
+    }
+    const tracer = this.tracerProvider.getTracer("prisma");
+    const context2 = options.context ?? this.getActiveContext();
+    const name = `prisma:client:${options.name}`;
+    if (shouldIgnoreSpan(name, this.ignoreSpanTypes)) {
+      return callback();
+    }
+    if (options.active === false) {
+      const span = tracer.startSpan(name, options, context2);
+      return endSpan(span, callback(span, context2));
+    }
+    return tracer.startActiveSpan(name, options, (span) => endSpan(span, callback(span, context2)));
+  }
+};
+function dispatchEngineSpan(tracer, engineSpan, allSpans, linkIds, ignoreSpanTypes) {
+  if (shouldIgnoreSpan(engineSpan.name, ignoreSpanTypes)) return;
+  const spanOptions = {
+    attributes: engineSpan.attributes,
+    kind: engineSpanKindToOtelSpanKind(engineSpan.kind),
+    startTime: engineSpan.startTime
+  };
+  tracer.startActiveSpan(engineSpan.name, spanOptions, (span) => {
+    linkIds.set(engineSpan.id, span.spanContext().spanId);
+    if (engineSpan.links) {
+      span.addLinks(
+        engineSpan.links.flatMap((link) => {
+          const linkedId = linkIds.get(link);
+          if (!linkedId) {
+            return [];
+          }
+          return {
+            context: {
+              spanId: linkedId,
+              traceId: span.spanContext().traceId,
+              traceFlags: span.spanContext().traceFlags
+            }
+          };
+        })
+      );
+    }
+    const children = allSpans.filter((s) => s.parentId === engineSpan.id);
+    for (const child of children) {
+      dispatchEngineSpan(tracer, child, allSpans, linkIds, ignoreSpanTypes);
+    }
+    span.end(engineSpan.endTime);
+  });
+}
+function endSpan(span, result) {
+  if (isPromiseLike(result)) {
+    return result.then(
+      (value) => {
+        span.end();
+        return value;
+      },
+      (reason) => {
+        span.end();
+        throw reason;
+      }
+    );
+  }
+  span.end();
+  return result;
+}
+function isPromiseLike(value) {
+  return value != null && typeof value["then"] === "function";
+}
+function shouldIgnoreSpan(spanName, ignoreSpanTypes) {
+  return ignoreSpanTypes.some(
+    (pattern) => typeof pattern === "string" ? pattern === spanName : pattern.test(spanName)
+  );
+}
+var package_default = {
+  name: "@prisma/instrumentation",
+  version: "6.19.0"
+};
+var VERSION = package_default.version;
+var majorVersion = VERSION.split(".")[0];
+var GLOBAL_INSTRUMENTATION_ACCESSOR_KEY = "PRISMA_INSTRUMENTATION";
+var GLOBAL_VERSIONED_INSTRUMENTATION_ACCESSOR_KEY = `V${majorVersion}_PRISMA_INSTRUMENTATION`;
+var NAME = package_default.name;
+var MODULE_NAME = "@prisma/client";
+var PrismaInstrumentation = class extends InstrumentationBase {
+  tracerProvider;
+  constructor(config2 = {}) {
+    super(NAME, VERSION, config2);
+  }
+  setTracerProvider(tracerProvider) {
+    this.tracerProvider = tracerProvider;
+  }
+  init() {
+    const module2 = new InstrumentationNodeModuleDefinition(MODULE_NAME, [VERSION]);
+    return [module2];
+  }
+  enable() {
+    const config2 = this._config;
+    const globalValue = {
+      helper: new ActiveTracingHelper({
+        tracerProvider: this.tracerProvider ?? srcExports$l.trace.getTracerProvider(),
+        ignoreSpanTypes: config2.ignoreSpanTypes ?? []
+      })
+    };
+    global[GLOBAL_INSTRUMENTATION_ACCESSOR_KEY] = globalValue;
+    global[GLOBAL_VERSIONED_INSTRUMENTATION_ACCESSOR_KEY] = globalValue;
+  }
+  disable() {
+    delete global[GLOBAL_INSTRUMENTATION_ACCESSOR_KEY];
+    delete global[GLOBAL_VERSIONED_INSTRUMENTATION_ACCESSOR_KEY];
+  }
+  isEnabled() {
+    return Boolean(global[GLOBAL_VERSIONED_INSTRUMENTATION_ACCESSOR_KEY]);
+  }
+};
+const INTEGRATION_NAME$9 = "Prisma";
+function isPrismaV6TracingHelper(helper) {
+  return !!helper && typeof helper === "object" && "dispatchEngineSpans" in helper;
+}
+function getPrismaTracingHelper() {
+  const prismaInstrumentationObject = globalThis.PRISMA_INSTRUMENTATION;
+  const prismaTracingHelper = prismaInstrumentationObject && typeof prismaInstrumentationObject === "object" && "helper" in prismaInstrumentationObject ? prismaInstrumentationObject.helper : void 0;
+  return prismaTracingHelper;
+}
+class SentryPrismaInteropInstrumentation extends PrismaInstrumentation {
+  constructor() {
+    super();
+  }
+  enable() {
+    super.enable();
+    const prismaTracingHelper = getPrismaTracingHelper();
+    if (isPrismaV6TracingHelper(prismaTracingHelper)) {
+      prismaTracingHelper.createEngineSpan = (engineSpanEvent) => {
+        const tracer = srcExports$l.trace.getTracer("prismaV5Compatibility");
+        const initialIdGenerator = tracer._idGenerator;
+        if (!initialIdGenerator) {
+          consoleSandbox(() => {
+            console.warn(
+              "[Sentry] Could not find _idGenerator on tracer, skipping Prisma v5 compatibility - some Prisma spans may be missing!"
+            );
+          });
+          return;
+        }
+        try {
+          engineSpanEvent.spans.forEach((engineSpan) => {
+            const kind = engineSpanKindToOTELSpanKind(engineSpan.kind);
+            const parentSpanId = engineSpan.parent_span_id;
+            const spanId = engineSpan.span_id;
+            const traceId = engineSpan.trace_id;
+            const links = engineSpan.links?.map((link) => {
+              return {
+                context: {
+                  traceId: link.trace_id,
+                  spanId: link.span_id,
+                  traceFlags: srcExports$l.TraceFlags.SAMPLED
+                }
+              };
+            });
+            const ctx = srcExports$l.trace.setSpanContext(srcExports$l.context.active(), {
+              traceId,
+              spanId: parentSpanId,
+              traceFlags: srcExports$l.TraceFlags.SAMPLED
+            });
+            srcExports$l.context.with(ctx, () => {
+              const temporaryIdGenerator = {
+                generateTraceId: () => {
+                  return traceId;
+                },
+                generateSpanId: () => {
+                  return spanId;
+                }
+              };
+              tracer._idGenerator = temporaryIdGenerator;
+              const span = tracer.startSpan(engineSpan.name, {
+                kind,
+                links,
+                startTime: engineSpan.start_time,
+                attributes: engineSpan.attributes
+              });
+              span.end(engineSpan.end_time);
+              tracer._idGenerator = initialIdGenerator;
+            });
+          });
+        } finally {
+          tracer._idGenerator = initialIdGenerator;
+        }
+      };
+    }
+  }
+}
+function engineSpanKindToOTELSpanKind(engineSpanKind) {
+  switch (engineSpanKind) {
+    case "client":
+      return srcExports$l.SpanKind.CLIENT;
+    case "internal":
+    default:
+      return srcExports$l.SpanKind.INTERNAL;
+  }
+}
+const instrumentPrisma = generateInstrumentOnce(INTEGRATION_NAME$9, (_options) => {
+  return new SentryPrismaInteropInstrumentation();
+});
+const prismaIntegration = defineIntegration((_options) => {
+  return {
+    name: INTEGRATION_NAME$9,
+    setupOnce() {
+      instrumentPrisma();
+    },
+    setup(client) {
+      if (!getPrismaTracingHelper()) {
+        return;
+      }
+      client.on("spanStart", (span) => {
+        const spanJSON = spanToJSON(span);
+        if (spanJSON.description?.startsWith("prisma:")) {
+          span.setAttribute(SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN, "auto.db.otel.prisma");
+        }
+        if (spanJSON.description === "prisma:engine:db_query" && spanJSON.data["db.query.text"]) {
+          span.updateName(spanJSON.data["db.query.text"]);
+        }
+        if (spanJSON.description === "prisma:engine:db_query" && !spanJSON.data["db.system"]) {
+          span.setAttribute("db.system", "prisma");
+        }
+      });
+    }
+  };
+});
+var src$5 = {};
+var instrumentation$4 = {};
+var version$5 = {};
+var hasRequiredVersion$5;
+function requireVersion$5() {
+  if (hasRequiredVersion$5) return version$5;
+  hasRequiredVersion$5 = 1;
+  Object.defineProperty(version$5, "__esModule", { value: true });
+  version$5.PACKAGE_NAME = version$5.PACKAGE_VERSION = void 0;
+  version$5.PACKAGE_VERSION = "0.55.0";
+  version$5.PACKAGE_NAME = "@opentelemetry/instrumentation-hapi";
+  return version$5;
+}
+var internalTypes$2 = {};
+var hasRequiredInternalTypes$2;
+function requireInternalTypes$2() {
+  if (hasRequiredInternalTypes$2) return internalTypes$2;
+  hasRequiredInternalTypes$2 = 1;
+  Object.defineProperty(internalTypes$2, "__esModule", { value: true });
+  internalTypes$2.HapiLifecycleMethodNames = internalTypes$2.HapiLayerType = internalTypes$2.handlerPatched = internalTypes$2.HapiComponentName = void 0;
+  internalTypes$2.HapiComponentName = "@hapi/hapi";
+  internalTypes$2.handlerPatched = Symbol("hapi-handler-patched");
+  internalTypes$2.HapiLayerType = {
+    ROUTER: "router",
+    PLUGIN: "plugin",
+    EXT: "server.ext"
+  };
+  internalTypes$2.HapiLifecycleMethodNames = /* @__PURE__ */ new Set([
+    "onPreAuth",
+    "onCredentials",
+    "onPostAuth",
+    "onPreHandler",
+    "onPostHandler",
+    "onPreResponse",
+    "onRequest"
+  ]);
+  return internalTypes$2;
+}
+var utils$4 = {};
+var semconv$2 = {};
+var hasRequiredSemconv$2;
+function requireSemconv$2() {
+  if (hasRequiredSemconv$2) return semconv$2;
+  hasRequiredSemconv$2 = 1;
+  Object.defineProperty(semconv$2, "__esModule", { value: true });
+  semconv$2.ATTR_HTTP_METHOD = void 0;
+  semconv$2.ATTR_HTTP_METHOD = "http.method";
+  return semconv$2;
+}
+var AttributeNames$3 = {};
+var hasRequiredAttributeNames$2;
+function requireAttributeNames$2() {
+  if (hasRequiredAttributeNames$2) return AttributeNames$3;
+  hasRequiredAttributeNames$2 = 1;
+  (function(exports$1) {
+    Object.defineProperty(exports$1, "__esModule", { value: true });
+    exports$1.AttributeNames = void 0;
+    (function(AttributeNames2) {
+      AttributeNames2["HAPI_TYPE"] = "hapi.type";
+      AttributeNames2["PLUGIN_NAME"] = "hapi.plugin.name";
+      AttributeNames2["EXT_TYPE"] = "server.ext.type";
+    })(exports$1.AttributeNames || (exports$1.AttributeNames = {}));
+  })(AttributeNames$3);
+  return AttributeNames$3;
+}
+var hasRequiredUtils$4;
+function requireUtils$4() {
+  if (hasRequiredUtils$4) return utils$4;
+  hasRequiredUtils$4 = 1;
+  (function(exports$1) {
+    Object.defineProperty(exports$1, "__esModule", { value: true });
+    exports$1.getPluginFromInput = exports$1.getExtMetadata = exports$1.getRouteMetadata = exports$1.isPatchableExtMethod = exports$1.isDirectExtInput = exports$1.isLifecycleExtEventObj = exports$1.isLifecycleExtType = exports$1.getPluginName = void 0;
+    const semantic_conventions_1 = /* @__PURE__ */ requireSrc$m();
+    const semconv_1 = requireSemconv$2();
+    const internal_types_1 = requireInternalTypes$2();
+    const AttributeNames_1 = requireAttributeNames$2();
+    const instrumentation_1 = require$$2;
+    function getPluginName(plugin) {
+      if (plugin.name) {
+        return plugin.name;
+      } else {
+        return plugin.pkg.name;
+      }
+    }
+    exports$1.getPluginName = getPluginName;
+    const isLifecycleExtType = (variableToCheck) => {
+      return typeof variableToCheck === "string" && internal_types_1.HapiLifecycleMethodNames.has(variableToCheck);
+    };
+    exports$1.isLifecycleExtType = isLifecycleExtType;
+    const isLifecycleExtEventObj = (variableToCheck) => {
+      const event = variableToCheck?.type;
+      return event !== void 0 && (0, exports$1.isLifecycleExtType)(event);
+    };
+    exports$1.isLifecycleExtEventObj = isLifecycleExtEventObj;
+    const isDirectExtInput = (variableToCheck) => {
+      return Array.isArray(variableToCheck) && variableToCheck.length <= 3 && (0, exports$1.isLifecycleExtType)(variableToCheck[0]) && typeof variableToCheck[1] === "function";
+    };
+    exports$1.isDirectExtInput = isDirectExtInput;
+    const isPatchableExtMethod = (variableToCheck) => {
+      return !Array.isArray(variableToCheck);
+    };
+    exports$1.isPatchableExtMethod = isPatchableExtMethod;
+    const getRouteMetadata = (route, semconvStability, pluginName) => {
+      const attributes = {
+        [semantic_conventions_1.ATTR_HTTP_ROUTE]: route.path
+      };
+      if (semconvStability & instrumentation_1.SemconvStability.OLD) {
+        attributes[semconv_1.ATTR_HTTP_METHOD] = route.method;
+      }
+      if (semconvStability & instrumentation_1.SemconvStability.STABLE) {
+        attributes[semantic_conventions_1.ATTR_HTTP_REQUEST_METHOD] = route.method;
+      }
+      let name;
+      if (pluginName) {
+        attributes[AttributeNames_1.AttributeNames.HAPI_TYPE] = internal_types_1.HapiLayerType.PLUGIN;
+        attributes[AttributeNames_1.AttributeNames.PLUGIN_NAME] = pluginName;
+        name = `${pluginName}: route - ${route.path}`;
+      } else {
+        attributes[AttributeNames_1.AttributeNames.HAPI_TYPE] = internal_types_1.HapiLayerType.ROUTER;
+        name = `route - ${route.path}`;
+      }
+      return { attributes, name };
+    };
+    exports$1.getRouteMetadata = getRouteMetadata;
+    const getExtMetadata = (extPoint, pluginName) => {
+      if (pluginName) {
+        return {
+          attributes: {
+            [AttributeNames_1.AttributeNames.EXT_TYPE]: extPoint,
+            [AttributeNames_1.AttributeNames.HAPI_TYPE]: internal_types_1.HapiLayerType.EXT,
+            [AttributeNames_1.AttributeNames.PLUGIN_NAME]: pluginName
+          },
+          name: `${pluginName}: ext - ${extPoint}`
+        };
+      }
+      return {
+        attributes: {
+          [AttributeNames_1.AttributeNames.EXT_TYPE]: extPoint,
+          [AttributeNames_1.AttributeNames.HAPI_TYPE]: internal_types_1.HapiLayerType.EXT
+        },
+        name: `ext - ${extPoint}`
+      };
+    };
+    exports$1.getExtMetadata = getExtMetadata;
+    const getPluginFromInput = (pluginObj) => {
+      if ("plugin" in pluginObj) {
+        if ("plugin" in pluginObj.plugin) {
+          return pluginObj.plugin.plugin;
+        }
+        return pluginObj.plugin;
+      }
+      return pluginObj;
+    };
+    exports$1.getPluginFromInput = getPluginFromInput;
+  })(utils$4);
+  return utils$4;
+}
+var hasRequiredInstrumentation$4;
+function requireInstrumentation$4() {
+  if (hasRequiredInstrumentation$4) return instrumentation$4;
+  hasRequiredInstrumentation$4 = 1;
+  Object.defineProperty(instrumentation$4, "__esModule", { value: true });
+  instrumentation$4.HapiInstrumentation = void 0;
+  const api = /* @__PURE__ */ requireSrc$n();
+  const core_1 = require$$1;
+  const instrumentation_1 = require$$2;
+  const version_1 = requireVersion$5();
+  const internal_types_1 = requireInternalTypes$2();
+  const utils_1 = requireUtils$4();
+  class HapiInstrumentation extends instrumentation_1.InstrumentationBase {
+    _semconvStability;
+    constructor(config2 = {}) {
+      super(version_1.PACKAGE_NAME, version_1.PACKAGE_VERSION, config2);
+      this._semconvStability = (0, instrumentation_1.semconvStabilityFromStr)("http", process.env.OTEL_SEMCONV_STABILITY_OPT_IN);
+    }
+    init() {
+      return new instrumentation_1.InstrumentationNodeModuleDefinition(internal_types_1.HapiComponentName, [">=17.0.0 <22"], (module2) => {
+        const moduleExports = module2[Symbol.toStringTag] === "Module" ? module2.default : module2;
+        if (!(0, instrumentation_1.isWrapped)(moduleExports.server)) {
+          this._wrap(moduleExports, "server", this._getServerPatch.bind(this));
+        }
+        if (!(0, instrumentation_1.isWrapped)(moduleExports.Server)) {
+          this._wrap(moduleExports, "Server", this._getServerPatch.bind(this));
+        }
+        return moduleExports;
+      }, (module2) => {
+        const moduleExports = module2[Symbol.toStringTag] === "Module" ? module2.default : module2;
+        this._massUnwrap([moduleExports], ["server", "Server"]);
+      });
+    }
+    /**
+     * Patches the Hapi.server and Hapi.Server functions in order to instrument
+     * the server.route, server.ext, and server.register functions via calls to the
+     * @function _getServerRoutePatch, @function _getServerExtPatch, and
+     * @function _getServerRegisterPatch functions
+     * @param original - the original Hapi Server creation function
+     */
+    _getServerPatch(original) {
+      const instrumentation2 = this;
+      const self = this;
+      return function server(opts) {
+        const newServer = original.apply(this, [opts]);
+        self._wrap(newServer, "route", (originalRouter) => {
+          return instrumentation2._getServerRoutePatch.bind(instrumentation2)(originalRouter);
+        });
+        self._wrap(newServer, "ext", (originalExtHandler) => {
+          return instrumentation2._getServerExtPatch.bind(instrumentation2)(
+            // eslint-disable-next-line @typescript-eslint/no-explicit-any
+            originalExtHandler
+          );
+        });
+        self._wrap(
+          newServer,
+          "register",
+          // eslint-disable-next-line @typescript-eslint/no-explicit-any
+          instrumentation2._getServerRegisterPatch.bind(instrumentation2)
+        );
+        return newServer;
+      };
+    }
+    /**
+     * Patches the plugin register function used by the Hapi Server. This function
+     * goes through each plugin that is being registered and adds instrumentation
+     * via a call to the @function _wrapRegisterHandler function.
+     * @param {RegisterFunction} original - the original register function which
+     * registers each plugin on the server
+     */
+    _getServerRegisterPatch(original) {
+      const instrumentation2 = this;
+      return function register2(pluginInput, options) {
+        if (Array.isArray(pluginInput)) {
+          for (const pluginObj of pluginInput) {
+            const plugin = (0, utils_1.getPluginFromInput)(pluginObj);
+            instrumentation2._wrapRegisterHandler(plugin);
+          }
+        } else {
+          const plugin = (0, utils_1.getPluginFromInput)(pluginInput);
+          instrumentation2._wrapRegisterHandler(plugin);
+        }
+        return original.apply(this, [pluginInput, options]);
+      };
+    }
+    /**
+     * Patches the Server.ext function which adds extension methods to the specified
+     * point along the request lifecycle. This function accepts the full range of
+     * accepted input into the standard Hapi `server.ext` function. For each extension,
+     * it adds instrumentation to the handler via a call to the @function _wrapExtMethods
+     * function.
+     * @param original - the original ext function which adds the extension method to the server
+     * @param {string} [pluginName] - if present, represents the name of the plugin responsible
+     * for adding this server extension. Else, signifies that the extension was added directly
+     */
+    _getServerExtPatch(original, pluginName) {
+      const instrumentation2 = this;
+      return function ext2(...args) {
+        if (Array.isArray(args[0])) {
+          const eventsList = args[0];
+          for (let i = 0; i < eventsList.length; i++) {
+            const eventObj = eventsList[i];
+            if ((0, utils_1.isLifecycleExtType)(eventObj.type)) {
+              const lifecycleEventObj = eventObj;
+              const handler = instrumentation2._wrapExtMethods(lifecycleEventObj.method, eventObj.type, pluginName);
+              lifecycleEventObj.method = handler;
+              eventsList[i] = lifecycleEventObj;
+            }
+          }
+          return original.apply(this, args);
+        } else if ((0, utils_1.isDirectExtInput)(args)) {
+          const extInput = args;
+          const method = extInput[1];
+          const handler = instrumentation2._wrapExtMethods(method, extInput[0], pluginName);
+          return original.apply(this, [extInput[0], handler, extInput[2]]);
+        } else if ((0, utils_1.isLifecycleExtEventObj)(args[0])) {
+          const lifecycleEventObj = args[0];
+          const handler = instrumentation2._wrapExtMethods(lifecycleEventObj.method, lifecycleEventObj.type, pluginName);
+          lifecycleEventObj.method = handler;
+          return original.call(this, lifecycleEventObj);
+        }
+        return original.apply(this, args);
+      };
+    }
+    /**
+     * Patches the Server.route function. This function accepts either one or an array
+     * of Hapi.ServerRoute objects and adds instrumentation on each route via a call to
+     * the @function _wrapRouteHandler function.
+     * @param {HapiServerRouteInputMethod} original - the original route function which adds
+     * the route to the server
+     * @param {string} [pluginName] - if present, represents the name of the plugin responsible
+     * for adding this server route. Else, signifies that the route was added directly
+     */
+    _getServerRoutePatch(original, pluginName) {
+      const instrumentation2 = this;
+      return function route(route) {
+        if (Array.isArray(route)) {
+          for (let i = 0; i < route.length; i++) {
+            const newRoute = instrumentation2._wrapRouteHandler.call(instrumentation2, route[i], pluginName);
+            route[i] = newRoute;
+          }
+        } else {
+          route = instrumentation2._wrapRouteHandler.call(instrumentation2, route, pluginName);
+        }
+        return original.apply(this, [route]);
+      };
+    }
+    /**
+     * Wraps newly registered plugins to add instrumentation to the plugin's clone of
+     * the original server. Specifically, wraps the server.route and server.ext functions
+     * via calls to @function _getServerRoutePatch and @function _getServerExtPatch
+     * @param {Hapi.Plugin} plugin - the new plugin which is being instrumented
+     */
+    _wrapRegisterHandler(plugin) {
+      const instrumentation2 = this;
+      const pluginName = (0, utils_1.getPluginName)(plugin);
+      const oldRegister = plugin.register;
+      const self = this;
+      const newRegisterHandler = function(server, options) {
+        self._wrap(server, "route", (original) => {
+          return instrumentation2._getServerRoutePatch.bind(instrumentation2)(original, pluginName);
+        });
+        self._wrap(server, "ext", (originalExtHandler) => {
+          return instrumentation2._getServerExtPatch.bind(instrumentation2)(
+            // eslint-disable-next-line @typescript-eslint/no-explicit-any
+            originalExtHandler,
+            pluginName
+          );
+        });
+        return oldRegister.call(this, server, options);
+      };
+      plugin.register = newRegisterHandler;
+    }
+    /**
+     * Wraps request extension methods to add instrumentation to each new extension handler.
+     * Patches each individual extension in order to create the
+     * span and propagate context. It does not create spans when there is no parent span.
+     * @param {PatchableExtMethod | PatchableExtMethod[]} method - the request extension
+     * handler which is being instrumented
+     * @param {Hapi.ServerRequestExtType} extPoint - the point in the Hapi request lifecycle
+     * which this extension targets
+     * @param {string} [pluginName] - if present, represents the name of the plugin responsible
+     * for adding this server route. Else, signifies that the route was added directly
+     */
+    _wrapExtMethods(method, extPoint, pluginName) {
+      const instrumentation2 = this;
+      if (method instanceof Array) {
+        for (let i = 0; i < method.length; i++) {
+          method[i] = instrumentation2._wrapExtMethods(method[i], extPoint);
+        }
+        return method;
+      } else if ((0, utils_1.isPatchableExtMethod)(method)) {
+        if (method[internal_types_1.handlerPatched] === true)
+          return method;
+        method[internal_types_1.handlerPatched] = true;
+        const newHandler = async function(...params) {
+          if (api.trace.getSpan(api.context.active()) === void 0) {
+            return await method.apply(this, params);
+          }
+          const metadata = (0, utils_1.getExtMetadata)(extPoint, pluginName);
+          const span = instrumentation2.tracer.startSpan(metadata.name, {
+            attributes: metadata.attributes
+          });
+          try {
+            return await api.context.with(api.trace.setSpan(api.context.active(), span), method, void 0, ...params);
+          } catch (err) {
+            span.recordException(err);
+            span.setStatus({
+              code: api.SpanStatusCode.ERROR,
+              message: err.message
+            });
+            throw err;
+          } finally {
+            span.end();
+          }
+        };
+        return newHandler;
+      }
+      return method;
+    }
+    /**
+     * Patches each individual route handler method in order to create the
+     * span and propagate context. It does not create spans when there is no parent span.
+     * @param {PatchableServerRoute} route - the route handler which is being instrumented
+     * @param {string} [pluginName] - if present, represents the name of the plugin responsible
+     * for adding this server route. Else, signifies that the route was added directly
+     */
+    _wrapRouteHandler(route, pluginName) {
+      const instrumentation2 = this;
+      if (route[internal_types_1.handlerPatched] === true)
+        return route;
+      route[internal_types_1.handlerPatched] = true;
+      const wrapHandler = (oldHandler) => {
+        return async function(...params) {
+          if (api.trace.getSpan(api.context.active()) === void 0) {
+            return await oldHandler.call(this, ...params);
+          }
+          const rpcMetadata = (0, core_1.getRPCMetadata)(api.context.active());
+          if (rpcMetadata?.type === core_1.RPCType.HTTP) {
+            rpcMetadata.route = route.path;
+          }
+          const metadata = (0, utils_1.getRouteMetadata)(route, instrumentation2._semconvStability, pluginName);
+          const span = instrumentation2.tracer.startSpan(metadata.name, {
+            attributes: metadata.attributes
+          });
+          try {
+            return await api.context.with(api.trace.setSpan(api.context.active(), span), () => oldHandler.call(this, ...params));
+          } catch (err) {
+            span.recordException(err);
+            span.setStatus({
+              code: api.SpanStatusCode.ERROR,
+              message: err.message
+            });
+            throw err;
+          } finally {
+            span.end();
+          }
+        };
+      };
+      if (typeof route.handler === "function") {
+        route.handler = wrapHandler(route.handler);
+      } else if (typeof route.options === "function") {
+        const oldOptions = route.options;
+        route.options = function(server) {
+          const options = oldOptions(server);
+          if (typeof options.handler === "function") {
+            options.handler = wrapHandler(options.handler);
+          }
+          return options;
+        };
+      } else if (typeof route.options?.handler === "function") {
+        route.options.handler = wrapHandler(route.options.handler);
+      }
+      return route;
+    }
+  }
+  instrumentation$4.HapiInstrumentation = HapiInstrumentation;
+  return instrumentation$4;
+}
+var hasRequiredSrc$5;
+function requireSrc$5() {
+  if (hasRequiredSrc$5) return src$5;
+  hasRequiredSrc$5 = 1;
+  (function(exports$1) {
+    Object.defineProperty(exports$1, "__esModule", { value: true });
+    exports$1.AttributeNames = exports$1.HapiInstrumentation = void 0;
+    var instrumentation_1 = requireInstrumentation$4();
+    Object.defineProperty(exports$1, "HapiInstrumentation", { enumerable: true, get: function() {
+      return instrumentation_1.HapiInstrumentation;
+    } });
+    var AttributeNames_1 = requireAttributeNames$2();
+    Object.defineProperty(exports$1, "AttributeNames", { enumerable: true, get: function() {
+      return AttributeNames_1.AttributeNames;
+    } });
+  })(src$5);
+  return src$5;
+}
+var srcExports$5 = requireSrc$5();
+const INTEGRATION_NAME$8 = "Hapi";
+const instrumentHapi = generateInstrumentOnce(INTEGRATION_NAME$8, () => new srcExports$5.HapiInstrumentation());
+const _hapiIntegration = (() => {
+  return {
+    name: INTEGRATION_NAME$8,
+    setupOnce() {
+      instrumentHapi();
+    }
+  };
+});
+const hapiIntegration = defineIntegration(_hapiIntegration);
+const AttributeNames$2 = {
+  HONO_TYPE: "hono.type",
+  HONO_NAME: "hono.name"
+};
+const HonoTypes = {
+  MIDDLEWARE: "middleware",
+  REQUEST_HANDLER: "request_handler"
+};
+const PACKAGE_NAME = "@sentry/instrumentation-hono";
+const PACKAGE_VERSION = "0.0.1";
+class HonoInstrumentation extends InstrumentationBase {
+  constructor(config2 = {}) {
+    super(PACKAGE_NAME, PACKAGE_VERSION, config2);
+  }
+  /**
+   * Initialize the instrumentation.
+   */
+  init() {
+    return [
+      new InstrumentationNodeModuleDefinition("hono", [">=4.0.0 <5"], (moduleExports) => this._patch(moduleExports))
+    ];
+  }
+  /**
+   * Patches the module exports to instrument Hono.
+   */
+  _patch(moduleExports) {
+    const instrumentation2 = this;
+    class WrappedHono extends moduleExports.Hono {
+      constructor(...args) {
+        super(...args);
+        instrumentation2._wrap(this, "get", instrumentation2._patchHandler());
+        instrumentation2._wrap(this, "post", instrumentation2._patchHandler());
+        instrumentation2._wrap(this, "put", instrumentation2._patchHandler());
+        instrumentation2._wrap(this, "delete", instrumentation2._patchHandler());
+        instrumentation2._wrap(this, "options", instrumentation2._patchHandler());
+        instrumentation2._wrap(this, "patch", instrumentation2._patchHandler());
+        instrumentation2._wrap(this, "all", instrumentation2._patchHandler());
+        instrumentation2._wrap(this, "on", instrumentation2._patchOnHandler());
+        instrumentation2._wrap(this, "use", instrumentation2._patchMiddlewareHandler());
+      }
+    }
+    try {
+      moduleExports.Hono = WrappedHono;
+    } catch {
+      return { ...moduleExports, Hono: WrappedHono };
+    }
+    return moduleExports;
+  }
+  /**
+   * Patches the route handler to instrument it.
+   */
+  _patchHandler() {
+    const instrumentation2 = this;
+    return function(original) {
+      return function wrappedHandler(...args) {
+        if (typeof args[0] === "string") {
+          const path2 = args[0];
+          if (args.length === 1) {
+            return original.apply(this, [path2]);
+          }
+          const handlers2 = args.slice(1);
+          return original.apply(this, [
+            path2,
+            ...handlers2.map((handler) => instrumentation2._wrapHandler(handler))
+          ]);
+        }
+        return original.apply(
+          this,
+          args.map((handler) => instrumentation2._wrapHandler(handler))
+        );
+      };
+    };
+  }
+  /**
+   * Patches the 'on' handler to instrument it.
+   */
+  _patchOnHandler() {
+    const instrumentation2 = this;
+    return function(original) {
+      return function wrappedHandler(...args) {
+        const handlers2 = args.slice(2);
+        return original.apply(this, [
+          ...args.slice(0, 2),
+          ...handlers2.map((handler) => instrumentation2._wrapHandler(handler))
+        ]);
+      };
+    };
+  }
+  /**
+   * Patches the middleware handler to instrument it.
+   */
+  _patchMiddlewareHandler() {
+    const instrumentation2 = this;
+    return function(original) {
+      return function wrappedHandler(...args) {
+        if (typeof args[0] === "string") {
+          const path2 = args[0];
+          if (args.length === 1) {
+            return original.apply(this, [path2]);
+          }
+          const handlers2 = args.slice(1);
+          return original.apply(this, [
+            path2,
+            ...handlers2.map((handler) => instrumentation2._wrapHandler(handler))
+          ]);
+        }
+        return original.apply(
+          this,
+          args.map((handler) => instrumentation2._wrapHandler(handler))
+        );
+      };
+    };
+  }
+  /**
+   * Wraps a handler or middleware handler to apply instrumentation.
+   */
+  _wrapHandler(handler) {
+    const instrumentation2 = this;
+    return function(c, next) {
+      if (!instrumentation2.isEnabled()) {
+        return handler.apply(this, [c, next]);
+      }
+      const path2 = c.req.path;
+      const span = instrumentation2.tracer.startSpan(path2);
+      return srcExports$l.context.with(srcExports$l.trace.setSpan(srcExports$l.context.active(), span), () => {
+        return instrumentation2._safeExecute(
+          () => {
+            const result = handler.apply(this, [c, next]);
+            if (isThenable(result)) {
+              return result.then((result2) => {
+                const type = instrumentation2._determineHandlerType(result2);
+                span.setAttributes({
+                  [AttributeNames$2.HONO_TYPE]: type,
+                  [AttributeNames$2.HONO_NAME]: type === HonoTypes.REQUEST_HANDLER ? path2 : handler.name || "anonymous"
+                });
+                instrumentation2.getConfig().responseHook?.(span);
+                return result2;
+              });
+            } else {
+              const type = instrumentation2._determineHandlerType(result);
+              span.setAttributes({
+                [AttributeNames$2.HONO_TYPE]: type,
+                [AttributeNames$2.HONO_NAME]: type === HonoTypes.REQUEST_HANDLER ? path2 : handler.name || "anonymous"
+              });
+              instrumentation2.getConfig().responseHook?.(span);
+              return result;
+            }
+          },
+          () => span.end(),
+          (error2) => {
+            instrumentation2._handleError(span, error2);
+            span.end();
+          }
+        );
+      });
+    };
+  }
+  /**
+   * Safely executes a function and handles errors.
+   */
+  // eslint-disable-next-line @typescript-eslint/no-explicit-any
+  _safeExecute(execute, onSuccess, onFailure) {
+    try {
+      const result = execute();
+      if (isThenable(result)) {
+        result.then(
+          () => onSuccess(),
+          (error2) => onFailure(error2)
+        );
+      } else {
+        onSuccess();
+      }
+      return result;
+    } catch (error2) {
+      onFailure(error2);
+      throw error2;
+    }
+  }
+  /**
+   * Determines the handler type based on the result.
+   * @param result
+   * @private
+   */
+  _determineHandlerType(result) {
+    return result === void 0 ? HonoTypes.MIDDLEWARE : HonoTypes.REQUEST_HANDLER;
+  }
+  /**
+   * Handles errors by setting the span status and recording the exception.
+   */
+  _handleError(span, error2) {
+    if (error2 instanceof Error) {
+      span.setStatus({
+        code: srcExports$l.SpanStatusCode.ERROR,
+        message: error2.message
+      });
+      span.recordException(error2);
+    }
+  }
+}
+const INTEGRATION_NAME$7 = "Hono";
+function addHonoSpanAttributes(span) {
+  const attributes = spanToJSON(span).data;
+  const type = attributes[AttributeNames$2.HONO_TYPE];
+  if (attributes[SEMANTIC_ATTRIBUTE_SENTRY_OP] || !type) {
+    return;
+  }
+  span.setAttributes({
+    [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: "auto.http.otel.hono",
+    [SEMANTIC_ATTRIBUTE_SENTRY_OP]: `${type}.hono`
+  });
+  const name = attributes[AttributeNames$2.HONO_NAME];
+  if (typeof name === "string") {
+    span.updateName(name);
+  }
+  if (getIsolationScope() === getDefaultIsolationScope()) {
+    DEBUG_BUILD && debug$2.warn("Isolation scope is default isolation scope - skipping setting transactionName");
+    return;
+  }
+  const route = attributes[srcExports$k.ATTR_HTTP_ROUTE];
+  const method = attributes[srcExports$k.ATTR_HTTP_REQUEST_METHOD];
+  if (typeof route === "string" && typeof method === "string") {
+    getIsolationScope().setTransactionName(`${method} ${route}`);
+  }
+}
+const instrumentHono = generateInstrumentOnce(
+  INTEGRATION_NAME$7,
+  () => new HonoInstrumentation({
+    responseHook: (span) => {
+      addHonoSpanAttributes(span);
+    }
+  })
+);
+const _honoIntegration = (() => {
+  return {
+    name: INTEGRATION_NAME$7,
+    setupOnce() {
+      instrumentHono();
+    }
+  };
+});
+const honoIntegration = defineIntegration(_honoIntegration);
+var src$4 = {};
+var instrumentation$3 = {};
+var types$1 = {};
+var hasRequiredTypes$1;
+function requireTypes$1() {
+  if (hasRequiredTypes$1) return types$1;
+  hasRequiredTypes$1 = 1;
+  (function(exports$1) {
+    Object.defineProperty(exports$1, "__esModule", { value: true });
+    exports$1.KoaLayerType = void 0;
+    (function(KoaLayerType) {
+      KoaLayerType["ROUTER"] = "router";
+      KoaLayerType["MIDDLEWARE"] = "middleware";
+    })(exports$1.KoaLayerType || (exports$1.KoaLayerType = {}));
+  })(types$1);
+  return types$1;
+}
+var version$4 = {};
+var hasRequiredVersion$4;
+function requireVersion$4() {
+  if (hasRequiredVersion$4) return version$4;
+  hasRequiredVersion$4 = 1;
+  Object.defineProperty(version$4, "__esModule", { value: true });
+  version$4.PACKAGE_NAME = version$4.PACKAGE_VERSION = void 0;
+  version$4.PACKAGE_VERSION = "0.57.0";
+  version$4.PACKAGE_NAME = "@opentelemetry/instrumentation-koa";
+  return version$4;
+}
+var utils$3 = {};
+var AttributeNames$1 = {};
+var hasRequiredAttributeNames$1;
+function requireAttributeNames$1() {
+  if (hasRequiredAttributeNames$1) return AttributeNames$1;
+  hasRequiredAttributeNames$1 = 1;
+  (function(exports$1) {
+    Object.defineProperty(exports$1, "__esModule", { value: true });
+    exports$1.AttributeNames = void 0;
+    (function(AttributeNames2) {
+      AttributeNames2["KOA_TYPE"] = "koa.type";
+      AttributeNames2["KOA_NAME"] = "koa.name";
+    })(exports$1.AttributeNames || (exports$1.AttributeNames = {}));
+  })(AttributeNames$1);
+  return AttributeNames$1;
+}
+var hasRequiredUtils$3;
+function requireUtils$3() {
+  if (hasRequiredUtils$3) return utils$3;
+  hasRequiredUtils$3 = 1;
+  Object.defineProperty(utils$3, "__esModule", { value: true });
+  utils$3.isLayerIgnored = utils$3.getMiddlewareMetadata = void 0;
+  const types_1 = requireTypes$1();
+  const AttributeNames_1 = requireAttributeNames$1();
+  const semantic_conventions_1 = /* @__PURE__ */ requireSrc$m();
+  const getMiddlewareMetadata = (context2, layer, isRouter, layerPath) => {
+    if (isRouter) {
+      return {
+        attributes: {
+          [AttributeNames_1.AttributeNames.KOA_NAME]: layerPath?.toString(),
+          [AttributeNames_1.AttributeNames.KOA_TYPE]: types_1.KoaLayerType.ROUTER,
+          [semantic_conventions_1.ATTR_HTTP_ROUTE]: layerPath?.toString()
+        },
+        name: context2._matchedRouteName || `router - ${layerPath}`
+      };
+    } else {
+      return {
+        attributes: {
+          [AttributeNames_1.AttributeNames.KOA_NAME]: layer.name ?? "middleware",
+          [AttributeNames_1.AttributeNames.KOA_TYPE]: types_1.KoaLayerType.MIDDLEWARE
+        },
+        name: `middleware - ${layer.name}`
+      };
+    }
+  };
+  utils$3.getMiddlewareMetadata = getMiddlewareMetadata;
+  const isLayerIgnored = (type, config2) => {
+    return !!(Array.isArray(config2?.ignoreLayersType) && config2?.ignoreLayersType?.includes(type));
+  };
+  utils$3.isLayerIgnored = isLayerIgnored;
+  return utils$3;
+}
+var internalTypes$1 = {};
+var hasRequiredInternalTypes$1;
+function requireInternalTypes$1() {
+  if (hasRequiredInternalTypes$1) return internalTypes$1;
+  hasRequiredInternalTypes$1 = 1;
+  Object.defineProperty(internalTypes$1, "__esModule", { value: true });
+  internalTypes$1.kLayerPatched = void 0;
+  internalTypes$1.kLayerPatched = Symbol("koa-layer-patched");
+  return internalTypes$1;
+}
+var hasRequiredInstrumentation$3;
+function requireInstrumentation$3() {
+  if (hasRequiredInstrumentation$3) return instrumentation$3;
+  hasRequiredInstrumentation$3 = 1;
+  Object.defineProperty(instrumentation$3, "__esModule", { value: true });
+  instrumentation$3.KoaInstrumentation = void 0;
+  const api = /* @__PURE__ */ requireSrc$n();
+  const instrumentation_1 = require$$2;
+  const types_1 = requireTypes$1();
+  const version_1 = requireVersion$4();
+  const utils_1 = requireUtils$3();
+  const core_1 = require$$1;
+  const internal_types_1 = requireInternalTypes$1();
+  class KoaInstrumentation extends instrumentation_1.InstrumentationBase {
+    constructor(config2 = {}) {
+      super(version_1.PACKAGE_NAME, version_1.PACKAGE_VERSION, config2);
+    }
+    init() {
+      return new instrumentation_1.InstrumentationNodeModuleDefinition("koa", [">=2.0.0 <4"], (module2) => {
+        const moduleExports = module2[Symbol.toStringTag] === "Module" ? module2.default : module2;
+        if (moduleExports == null) {
+          return moduleExports;
+        }
+        if ((0, instrumentation_1.isWrapped)(moduleExports.prototype.use)) {
+          this._unwrap(moduleExports.prototype, "use");
+        }
+        this._wrap(moduleExports.prototype, "use", this._getKoaUsePatch.bind(this));
+        return module2;
+      }, (module2) => {
+        const moduleExports = module2[Symbol.toStringTag] === "Module" ? module2.default : module2;
+        if ((0, instrumentation_1.isWrapped)(moduleExports.prototype.use)) {
+          this._unwrap(moduleExports.prototype, "use");
+        }
+      });
+    }
+    /**
+     * Patches the Koa.use function in order to instrument each original
+     * middleware layer which is introduced
+     * @param {KoaMiddleware} middleware - the original middleware function
+     */
+    _getKoaUsePatch(original) {
+      const plugin = this;
+      return function use(middlewareFunction) {
+        let patchedFunction;
+        if (middlewareFunction.router) {
+          patchedFunction = plugin._patchRouterDispatch(middlewareFunction);
+        } else {
+          patchedFunction = plugin._patchLayer(middlewareFunction, false);
+        }
+        return original.apply(this, [patchedFunction]);
+      };
+    }
+    /**
+     * Patches the dispatch function used by @koa/router. This function
+     * goes through each routed middleware and adds instrumentation via a call
+     * to the @function _patchLayer function.
+     * @param {KoaMiddleware} dispatchLayer - the original dispatch function which dispatches
+     * routed middleware
+     */
+    _patchRouterDispatch(dispatchLayer) {
+      api.diag.debug("Patching @koa/router dispatch");
+      const router = dispatchLayer.router;
+      const routesStack = router?.stack ?? [];
+      for (const pathLayer of routesStack) {
+        const path2 = pathLayer.path;
+        const pathStack = pathLayer.stack;
+        for (let j = 0; j < pathStack.length; j++) {
+          const routedMiddleware = pathStack[j];
+          pathStack[j] = this._patchLayer(routedMiddleware, true, path2);
+        }
+      }
+      return dispatchLayer;
+    }
+    /**
+     * Patches each individual @param middlewareLayer function in order to create the
+     * span and propagate context. It does not create spans when there is no parent span.
+     * @param {KoaMiddleware} middlewareLayer - the original middleware function.
+     * @param {boolean} isRouter - tracks whether the original middleware function
+     * was dispatched by the router originally
+     * @param {string?} layerPath - if present, provides additional data from the
+     * router about the routed path which the middleware is attached to
+     */
+    _patchLayer(middlewareLayer, isRouter, layerPath) {
+      const layerType = isRouter ? types_1.KoaLayerType.ROUTER : types_1.KoaLayerType.MIDDLEWARE;
+      if (middlewareLayer[internal_types_1.kLayerPatched] === true || (0, utils_1.isLayerIgnored)(layerType, this.getConfig()))
+        return middlewareLayer;
+      if (middlewareLayer.constructor.name === "GeneratorFunction" || middlewareLayer.constructor.name === "AsyncGeneratorFunction") {
+        api.diag.debug("ignoring generator-based Koa middleware layer");
+        return middlewareLayer;
+      }
+      middlewareLayer[internal_types_1.kLayerPatched] = true;
+      api.diag.debug("patching Koa middleware layer");
+      return async (context2, next) => {
+        const parent = api.trace.getSpan(api.context.active());
+        if (parent === void 0) {
+          return middlewareLayer(context2, next);
+        }
+        const metadata = (0, utils_1.getMiddlewareMetadata)(context2, middlewareLayer, isRouter, layerPath);
+        const span = this.tracer.startSpan(metadata.name, {
+          attributes: metadata.attributes
+        });
+        const rpcMetadata = (0, core_1.getRPCMetadata)(api.context.active());
+        if (rpcMetadata?.type === core_1.RPCType.HTTP && context2._matchedRoute) {
+          rpcMetadata.route = context2._matchedRoute.toString();
+        }
+        const { requestHook: requestHook2 } = this.getConfig();
+        if (requestHook2) {
+          (0, instrumentation_1.safeExecuteInTheMiddle)(() => requestHook2(span, {
+            context: context2,
+            middlewareLayer,
+            layerType
+          }), (e) => {
+            if (e) {
+              api.diag.error("koa instrumentation: request hook failed", e);
+            }
+          }, true);
+        }
+        const newContext = api.trace.setSpan(api.context.active(), span);
+        return api.context.with(newContext, async () => {
+          try {
+            return await middlewareLayer(context2, next);
+          } catch (err) {
+            span.recordException(err);
+            throw err;
+          } finally {
+            span.end();
+          }
+        });
+      };
+    }
+  }
+  instrumentation$3.KoaInstrumentation = KoaInstrumentation;
+  return instrumentation$3;
+}
+var hasRequiredSrc$4;
+function requireSrc$4() {
+  if (hasRequiredSrc$4) return src$4;
+  hasRequiredSrc$4 = 1;
+  (function(exports$1) {
+    Object.defineProperty(exports$1, "__esModule", { value: true });
+    exports$1.KoaLayerType = exports$1.AttributeNames = exports$1.KoaInstrumentation = void 0;
+    var instrumentation_1 = requireInstrumentation$3();
+    Object.defineProperty(exports$1, "KoaInstrumentation", { enumerable: true, get: function() {
+      return instrumentation_1.KoaInstrumentation;
+    } });
+    var AttributeNames_1 = requireAttributeNames$1();
+    Object.defineProperty(exports$1, "AttributeNames", { enumerable: true, get: function() {
+      return AttributeNames_1.AttributeNames;
+    } });
+    var types_1 = requireTypes$1();
+    Object.defineProperty(exports$1, "KoaLayerType", { enumerable: true, get: function() {
+      return types_1.KoaLayerType;
+    } });
+  })(src$4);
+  return src$4;
+}
+var srcExports$4 = requireSrc$4();
+const INTEGRATION_NAME$6 = "Koa";
+const instrumentKoa = generateInstrumentOnce(
+  INTEGRATION_NAME$6,
+  srcExports$4.KoaInstrumentation,
+  (options = {}) => {
+    return {
+      ignoreLayersType: options.ignoreLayersType,
+      requestHook(span, info) {
+        addOriginToSpan(span, "auto.http.otel.koa");
+        const attributes = spanToJSON(span).data;
+        const type = attributes["koa.type"];
+        if (type) {
+          span.setAttribute(SEMANTIC_ATTRIBUTE_SENTRY_OP, `${type}.koa`);
+        }
+        const name = attributes["koa.name"];
+        if (typeof name === "string") {
+          span.updateName(name || "< unknown >");
+        }
+        if (getIsolationScope() === getDefaultIsolationScope()) {
+          DEBUG_BUILD && debug$2.warn("Isolation scope is default isolation scope - skipping setting transactionName");
+          return;
+        }
+        const route = attributes[srcExports$k.ATTR_HTTP_ROUTE];
+        const method = info.context?.request?.method?.toUpperCase() || "GET";
+        if (route) {
+          getIsolationScope().setTransactionName(`${method} ${route}`);
+        }
+      }
+    };
+  }
+);
+const _koaIntegration = ((options = {}) => {
+  return {
+    name: INTEGRATION_NAME$6,
+    setupOnce() {
+      instrumentKoa(options);
+    }
+  };
+});
+const koaIntegration = defineIntegration(_koaIntegration);
+var src$3 = {};
+var instrumentation$2 = {};
+var AttributeNames = {};
+var hasRequiredAttributeNames;
+function requireAttributeNames() {
+  if (hasRequiredAttributeNames) return AttributeNames;
+  hasRequiredAttributeNames = 1;
+  (function(exports$1) {
+    Object.defineProperty(exports$1, "__esModule", { value: true });
+    exports$1.ConnectNames = exports$1.ConnectTypes = exports$1.AttributeNames = void 0;
+    (function(AttributeNames2) {
+      AttributeNames2["CONNECT_TYPE"] = "connect.type";
+      AttributeNames2["CONNECT_NAME"] = "connect.name";
+    })(exports$1.AttributeNames || (exports$1.AttributeNames = {}));
+    (function(ConnectTypes) {
+      ConnectTypes["MIDDLEWARE"] = "middleware";
+      ConnectTypes["REQUEST_HANDLER"] = "request_handler";
+    })(exports$1.ConnectTypes || (exports$1.ConnectTypes = {}));
+    (function(ConnectNames) {
+      ConnectNames["MIDDLEWARE"] = "middleware";
+      ConnectNames["REQUEST_HANDLER"] = "request handler";
+    })(exports$1.ConnectNames || (exports$1.ConnectNames = {}));
+  })(AttributeNames);
+  return AttributeNames;
+}
+var version$3 = {};
+var hasRequiredVersion$3;
+function requireVersion$3() {
+  if (hasRequiredVersion$3) return version$3;
+  hasRequiredVersion$3 = 1;
+  Object.defineProperty(version$3, "__esModule", { value: true });
+  version$3.PACKAGE_NAME = version$3.PACKAGE_VERSION = void 0;
+  version$3.PACKAGE_VERSION = "0.52.0";
+  version$3.PACKAGE_NAME = "@opentelemetry/instrumentation-connect";
+  return version$3;
+}
+var utils$2 = {};
+var internalTypes = {};
+var hasRequiredInternalTypes;
+function requireInternalTypes() {
+  if (hasRequiredInternalTypes) return internalTypes;
+  hasRequiredInternalTypes = 1;
+  Object.defineProperty(internalTypes, "__esModule", { value: true });
+  internalTypes._LAYERS_STORE_PROPERTY = void 0;
+  internalTypes._LAYERS_STORE_PROPERTY = Symbol("opentelemetry.instrumentation-connect.request-route-stack");
+  return internalTypes;
+}
+var hasRequiredUtils$2;
+function requireUtils$2() {
+  if (hasRequiredUtils$2) return utils$2;
+  hasRequiredUtils$2 = 1;
+  Object.defineProperty(utils$2, "__esModule", { value: true });
+  utils$2.generateRoute = utils$2.replaceCurrentStackRoute = utils$2.addNewStackLayer = void 0;
+  const api_1 = /* @__PURE__ */ requireSrc$n();
+  const internal_types_1 = requireInternalTypes();
+  const addNewStackLayer = (request) => {
+    if (Array.isArray(request[internal_types_1._LAYERS_STORE_PROPERTY]) === false) {
+      Object.defineProperty(request, internal_types_1._LAYERS_STORE_PROPERTY, {
+        enumerable: false,
+        value: []
+      });
+    }
+    request[internal_types_1._LAYERS_STORE_PROPERTY].push("/");
+    const stackLength = request[internal_types_1._LAYERS_STORE_PROPERTY].length;
+    return () => {
+      if (stackLength === request[internal_types_1._LAYERS_STORE_PROPERTY].length) {
+        request[internal_types_1._LAYERS_STORE_PROPERTY].pop();
+      } else {
+        api_1.diag.warn("Connect: Trying to pop the stack multiple time");
+      }
+    };
+  };
+  utils$2.addNewStackLayer = addNewStackLayer;
+  const replaceCurrentStackRoute = (request, newRoute) => {
+    if (newRoute) {
+      request[internal_types_1._LAYERS_STORE_PROPERTY].splice(-1, 1, newRoute);
+    }
+  };
+  utils$2.replaceCurrentStackRoute = replaceCurrentStackRoute;
+  const generateRoute = (request) => {
+    return request[internal_types_1._LAYERS_STORE_PROPERTY].reduce((acc, sub) => acc.replace(/\/+$/, "") + sub);
+  };
+  utils$2.generateRoute = generateRoute;
+  return utils$2;
+}
+var hasRequiredInstrumentation$2;
+function requireInstrumentation$2() {
+  if (hasRequiredInstrumentation$2) return instrumentation$2;
+  hasRequiredInstrumentation$2 = 1;
+  (function(exports$1) {
+    Object.defineProperty(exports$1, "__esModule", { value: true });
+    exports$1.ConnectInstrumentation = exports$1.ANONYMOUS_NAME = void 0;
+    const api_1 = /* @__PURE__ */ requireSrc$n();
+    const core_1 = require$$1;
+    const AttributeNames_1 = requireAttributeNames();
+    const version_1 = requireVersion$3();
+    const instrumentation_1 = require$$2;
+    const semantic_conventions_1 = /* @__PURE__ */ requireSrc$m();
+    const utils_1 = requireUtils$2();
+    exports$1.ANONYMOUS_NAME = "anonymous";
+    class ConnectInstrumentation extends instrumentation_1.InstrumentationBase {
+      constructor(config2 = {}) {
+        super(version_1.PACKAGE_NAME, version_1.PACKAGE_VERSION, config2);
+      }
+      init() {
+        return [
+          new instrumentation_1.InstrumentationNodeModuleDefinition("connect", [">=3.0.0 <4"], (moduleExports) => {
+            return this._patchConstructor(moduleExports);
+          })
+        ];
+      }
+      _patchApp(patchedApp) {
+        if (!(0, instrumentation_1.isWrapped)(patchedApp.use)) {
+          this._wrap(patchedApp, "use", this._patchUse.bind(this));
+        }
+        if (!(0, instrumentation_1.isWrapped)(patchedApp.handle)) {
+          this._wrap(patchedApp, "handle", this._patchHandle.bind(this));
+        }
+      }
+      _patchConstructor(original) {
+        const instrumentation2 = this;
+        return function(...args) {
+          const app = original.apply(this, args);
+          instrumentation2._patchApp(app);
+          return app;
+        };
+      }
+      _patchNext(next, finishSpan) {
+        return function nextFunction(err) {
+          const result = next.apply(this, [err]);
+          finishSpan();
+          return result;
+        };
+      }
+      _startSpan(routeName, middleWare) {
+        let connectType;
+        let connectName;
+        let connectTypeName;
+        if (routeName) {
+          connectType = AttributeNames_1.ConnectTypes.REQUEST_HANDLER;
+          connectTypeName = AttributeNames_1.ConnectNames.REQUEST_HANDLER;
+          connectName = routeName;
+        } else {
+          connectType = AttributeNames_1.ConnectTypes.MIDDLEWARE;
+          connectTypeName = AttributeNames_1.ConnectNames.MIDDLEWARE;
+          connectName = middleWare.name || exports$1.ANONYMOUS_NAME;
+        }
+        const spanName = `${connectTypeName} - ${connectName}`;
+        const options = {
+          attributes: {
+            [semantic_conventions_1.ATTR_HTTP_ROUTE]: routeName.length > 0 ? routeName : "/",
+            [AttributeNames_1.AttributeNames.CONNECT_TYPE]: connectType,
+            [AttributeNames_1.AttributeNames.CONNECT_NAME]: connectName
+          }
+        };
+        return this.tracer.startSpan(spanName, options);
+      }
+      _patchMiddleware(routeName, middleWare) {
+        const instrumentation2 = this;
+        const isErrorMiddleware = middleWare.length === 4;
+        function patchedMiddleware() {
+          if (!instrumentation2.isEnabled()) {
+            return middleWare.apply(this, arguments);
+          }
+          const [reqArgIdx, resArgIdx, nextArgIdx] = isErrorMiddleware ? [1, 2, 3] : [0, 1, 2];
+          const req = arguments[reqArgIdx];
+          const res = arguments[resArgIdx];
+          const next = arguments[nextArgIdx];
+          (0, utils_1.replaceCurrentStackRoute)(req, routeName);
+          const rpcMetadata = (0, core_1.getRPCMetadata)(api_1.context.active());
+          if (routeName && rpcMetadata?.type === core_1.RPCType.HTTP) {
+            rpcMetadata.route = (0, utils_1.generateRoute)(req);
+          }
+          let spanName = "";
+          if (routeName) {
+            spanName = `request handler - ${routeName}`;
+          } else {
+            spanName = `middleware - ${middleWare.name || exports$1.ANONYMOUS_NAME}`;
+          }
+          const span = instrumentation2._startSpan(routeName, middleWare);
+          instrumentation2._diag.debug("start span", spanName);
+          let spanFinished = false;
+          function finishSpan() {
+            if (!spanFinished) {
+              spanFinished = true;
+              instrumentation2._diag.debug(`finishing span ${span.name}`);
+              span.end();
+            } else {
+              instrumentation2._diag.debug(`span ${span.name} - already finished`);
+            }
+            res.removeListener("close", finishSpan);
+          }
+          res.addListener("close", finishSpan);
+          arguments[nextArgIdx] = instrumentation2._patchNext(next, finishSpan);
+          return middleWare.apply(this, arguments);
+        }
+        Object.defineProperty(patchedMiddleware, "length", {
+          value: middleWare.length,
+          writable: false,
+          configurable: true
+        });
+        return patchedMiddleware;
+      }
+      _patchUse(original) {
+        const instrumentation2 = this;
+        return function(...args) {
+          const middleWare = args[args.length - 1];
+          const routeName = args[args.length - 2] || "";
+          args[args.length - 1] = instrumentation2._patchMiddleware(routeName, middleWare);
+          return original.apply(this, args);
+        };
+      }
+      _patchHandle(original) {
+        const instrumentation2 = this;
+        return function() {
+          const [reqIdx, outIdx] = [0, 2];
+          const req = arguments[reqIdx];
+          const out = arguments[outIdx];
+          const completeStack = (0, utils_1.addNewStackLayer)(req);
+          if (typeof out === "function") {
+            arguments[outIdx] = instrumentation2._patchOut(out, completeStack);
+          }
+          return original.apply(this, arguments);
+        };
+      }
+      _patchOut(out, completeStack) {
+        return function nextFunction(...args) {
+          completeStack();
+          return Reflect.apply(out, this, args);
+        };
+      }
+    }
+    exports$1.ConnectInstrumentation = ConnectInstrumentation;
+  })(instrumentation$2);
+  return instrumentation$2;
+}
+var hasRequiredSrc$3;
+function requireSrc$3() {
+  if (hasRequiredSrc$3) return src$3;
+  hasRequiredSrc$3 = 1;
+  (function(exports$1) {
+    Object.defineProperty(exports$1, "__esModule", { value: true });
+    exports$1.ConnectTypes = exports$1.ConnectNames = exports$1.AttributeNames = exports$1.ANONYMOUS_NAME = exports$1.ConnectInstrumentation = void 0;
+    var instrumentation_1 = requireInstrumentation$2();
+    Object.defineProperty(exports$1, "ConnectInstrumentation", { enumerable: true, get: function() {
+      return instrumentation_1.ConnectInstrumentation;
+    } });
+    Object.defineProperty(exports$1, "ANONYMOUS_NAME", { enumerable: true, get: function() {
+      return instrumentation_1.ANONYMOUS_NAME;
+    } });
+    var AttributeNames_1 = requireAttributeNames();
+    Object.defineProperty(exports$1, "AttributeNames", { enumerable: true, get: function() {
+      return AttributeNames_1.AttributeNames;
+    } });
+    Object.defineProperty(exports$1, "ConnectNames", { enumerable: true, get: function() {
+      return AttributeNames_1.ConnectNames;
+    } });
+    Object.defineProperty(exports$1, "ConnectTypes", { enumerable: true, get: function() {
+      return AttributeNames_1.ConnectTypes;
+    } });
+  })(src$3);
+  return src$3;
+}
+var srcExports$3 = requireSrc$3();
+const INTEGRATION_NAME$5 = "Connect";
+const instrumentConnect = generateInstrumentOnce(INTEGRATION_NAME$5, () => new srcExports$3.ConnectInstrumentation());
+const _connectIntegration = (() => {
+  return {
+    name: INTEGRATION_NAME$5,
+    setupOnce() {
+      instrumentConnect();
+    }
+  };
+});
+const connectIntegration = defineIntegration(_connectIntegration);
+var src$2 = {};
+var instrumentation$1 = {};
+var semconv$1 = {};
+var hasRequiredSemconv$1;
+function requireSemconv$1() {
+  if (hasRequiredSemconv$1) return semconv$1;
+  hasRequiredSemconv$1 = 1;
+  Object.defineProperty(semconv$1, "__esModule", { value: true });
+  semconv$1.DB_SYSTEM_VALUE_MSSQL = semconv$1.ATTR_NET_PEER_PORT = semconv$1.ATTR_NET_PEER_NAME = semconv$1.ATTR_DB_USER = semconv$1.ATTR_DB_SYSTEM = semconv$1.ATTR_DB_STATEMENT = semconv$1.ATTR_DB_SQL_TABLE = semconv$1.ATTR_DB_NAME = void 0;
+  semconv$1.ATTR_DB_NAME = "db.name";
+  semconv$1.ATTR_DB_SQL_TABLE = "db.sql.table";
+  semconv$1.ATTR_DB_STATEMENT = "db.statement";
+  semconv$1.ATTR_DB_SYSTEM = "db.system";
+  semconv$1.ATTR_DB_USER = "db.user";
+  semconv$1.ATTR_NET_PEER_NAME = "net.peer.name";
+  semconv$1.ATTR_NET_PEER_PORT = "net.peer.port";
+  semconv$1.DB_SYSTEM_VALUE_MSSQL = "mssql";
+  return semconv$1;
+}
+var utils$1 = {};
+var hasRequiredUtils$1;
+function requireUtils$1() {
+  if (hasRequiredUtils$1) return utils$1;
+  hasRequiredUtils$1 = 1;
+  Object.defineProperty(utils$1, "__esModule", { value: true });
+  utils$1.once = utils$1.getSpanName = void 0;
+  function getSpanName(operation, db, sql, bulkLoadTable) {
+    if (operation === "execBulkLoad" && bulkLoadTable && db) {
+      return `${operation} ${bulkLoadTable} ${db}`;
+    }
+    if (operation === "callProcedure") {
+      if (db) {
+        return `${operation} ${sql} ${db}`;
+      }
+      return `${operation} ${sql}`;
+    }
+    if (db) {
+      return `${operation} ${db}`;
+    }
+    return `${operation}`;
+  }
+  utils$1.getSpanName = getSpanName;
+  const once = (fn) => {
+    let called = false;
+    return (...args) => {
+      if (called)
+        return;
+      called = true;
+      return fn(...args);
+    };
+  };
+  utils$1.once = once;
+  return utils$1;
+}
+var version$2 = {};
+var hasRequiredVersion$2;
+function requireVersion$2() {
+  if (hasRequiredVersion$2) return version$2;
+  hasRequiredVersion$2 = 1;
+  Object.defineProperty(version$2, "__esModule", { value: true });
+  version$2.PACKAGE_NAME = version$2.PACKAGE_VERSION = void 0;
+  version$2.PACKAGE_VERSION = "0.27.0";
+  version$2.PACKAGE_NAME = "@opentelemetry/instrumentation-tedious";
+  return version$2;
+}
+var hasRequiredInstrumentation$1;
+function requireInstrumentation$1() {
+  if (hasRequiredInstrumentation$1) return instrumentation$1;
+  hasRequiredInstrumentation$1 = 1;
+  (function(exports$1) {
+    Object.defineProperty(exports$1, "__esModule", { value: true });
+    exports$1.TediousInstrumentation = exports$1.INJECTED_CTX = void 0;
+    const api = /* @__PURE__ */ requireSrc$n();
+    const events_1 = require$$5;
+    const instrumentation_1 = require$$2;
+    const semconv_1 = requireSemconv$1();
+    const utils_1 = requireUtils$1();
+    const version_1 = requireVersion$2();
+    const CURRENT_DATABASE = Symbol("opentelemetry.instrumentation-tedious.current-database");
+    exports$1.INJECTED_CTX = Symbol("opentelemetry.instrumentation-tedious.context-info-injected");
+    const PATCHED_METHODS = [
+      "callProcedure",
+      "execSql",
+      "execSqlBatch",
+      "execBulkLoad",
+      "prepare",
+      "execute"
+    ];
+    function setDatabase(databaseName) {
+      Object.defineProperty(this, CURRENT_DATABASE, {
+        value: databaseName,
+        writable: true
+      });
+    }
+    class TediousInstrumentation extends instrumentation_1.InstrumentationBase {
+      static COMPONENT = "tedious";
+      constructor(config2 = {}) {
+        super(version_1.PACKAGE_NAME, version_1.PACKAGE_VERSION, config2);
+      }
+      init() {
+        return [
+          new instrumentation_1.InstrumentationNodeModuleDefinition(TediousInstrumentation.COMPONENT, [">=1.11.0 <20"], (moduleExports) => {
+            const ConnectionPrototype = moduleExports.Connection.prototype;
+            for (const method of PATCHED_METHODS) {
+              if ((0, instrumentation_1.isWrapped)(ConnectionPrototype[method])) {
+                this._unwrap(ConnectionPrototype, method);
+              }
+              this._wrap(ConnectionPrototype, method, this._patchQuery(method, moduleExports));
+            }
+            if ((0, instrumentation_1.isWrapped)(ConnectionPrototype.connect)) {
+              this._unwrap(ConnectionPrototype, "connect");
+            }
+            this._wrap(ConnectionPrototype, "connect", this._patchConnect);
+            return moduleExports;
+          }, (moduleExports) => {
+            if (moduleExports === void 0)
+              return;
+            const ConnectionPrototype = moduleExports.Connection.prototype;
+            for (const method of PATCHED_METHODS) {
+              this._unwrap(ConnectionPrototype, method);
+            }
+            this._unwrap(ConnectionPrototype, "connect");
+          })
+        ];
+      }
+      _patchConnect(original) {
+        return function patchedConnect() {
+          setDatabase.call(this, this.config?.options?.database);
+          this.removeListener("databaseChange", setDatabase);
+          this.on("databaseChange", setDatabase);
+          this.once("end", () => {
+            this.removeListener("databaseChange", setDatabase);
+          });
+          return original.apply(this, arguments);
+        };
+      }
+      _buildTraceparent(span) {
+        const sc = span.spanContext();
+        return `00-${sc.traceId}-${sc.spanId}-0${Number(sc.traceFlags || api.TraceFlags.NONE).toString(16)}`;
+      }
+      /**
+       * Fire a one-off `SET CONTEXT_INFO @opentelemetry_traceparent` on the same
+       * connection. Marks the request with INJECTED_CTX so our patch skips it.
+       */
+      _injectContextInfo(connection, tediousModule, traceparent) {
+        return new Promise((resolve) => {
+          try {
+            const sql = "set context_info @opentelemetry_traceparent";
+            const req = new tediousModule.Request(sql, (_err) => {
+              resolve();
+            });
+            Object.defineProperty(req, exports$1.INJECTED_CTX, { value: true });
+            const buf = Buffer.from(traceparent, "utf8");
+            req.addParameter("opentelemetry_traceparent", tediousModule.TYPES.VarBinary, buf, { length: buf.length });
+            connection.execSql(req);
+          } catch {
+            resolve();
+          }
+        });
+      }
+      _shouldInjectFor(operation) {
+        return operation === "execSql" || operation === "execSqlBatch" || operation === "callProcedure" || operation === "execute";
+      }
+      _patchQuery(operation, tediousModule) {
+        return (originalMethod) => {
+          const thisPlugin = this;
+          function patchedMethod(request) {
+            if (request?.[exports$1.INJECTED_CTX]) {
+              return originalMethod.apply(this, arguments);
+            }
+            if (!(request instanceof events_1.EventEmitter)) {
+              thisPlugin._diag.warn(`Unexpected invocation of patched ${operation} method. Span not recorded`);
+              return originalMethod.apply(this, arguments);
+            }
+            let procCount = 0;
+            let statementCount = 0;
+            const incrementStatementCount = () => statementCount++;
+            const incrementProcCount = () => procCount++;
+            const databaseName = this[CURRENT_DATABASE];
+            const sql = ((request2) => {
+              if (request2.sqlTextOrProcedure === "sp_prepare" && request2.parametersByName?.stmt?.value) {
+                return request2.parametersByName.stmt.value;
+              }
+              return request2.sqlTextOrProcedure;
+            })(request);
+            const span = thisPlugin.tracer.startSpan((0, utils_1.getSpanName)(operation, databaseName, sql, request.table), {
+              kind: api.SpanKind.CLIENT,
+              attributes: {
+                [semconv_1.ATTR_DB_SYSTEM]: semconv_1.DB_SYSTEM_VALUE_MSSQL,
+                [semconv_1.ATTR_DB_NAME]: databaseName,
+                [semconv_1.ATTR_NET_PEER_PORT]: this.config?.options?.port,
+                [semconv_1.ATTR_NET_PEER_NAME]: this.config?.server,
+                // >=4 uses `authentication` object, older versions just userName and password pair
+                [semconv_1.ATTR_DB_USER]: this.config?.userName ?? this.config?.authentication?.options?.userName,
+                [semconv_1.ATTR_DB_STATEMENT]: sql,
+                [semconv_1.ATTR_DB_SQL_TABLE]: request.table
+              }
+            });
+            const endSpan2 = (0, utils_1.once)((err) => {
+              request.removeListener("done", incrementStatementCount);
+              request.removeListener("doneInProc", incrementStatementCount);
+              request.removeListener("doneProc", incrementProcCount);
+              request.removeListener("error", endSpan2);
+              this.removeListener("end", endSpan2);
+              span.setAttribute("tedious.procedure_count", procCount);
+              span.setAttribute("tedious.statement_count", statementCount);
+              if (err) {
+                span.setStatus({
+                  code: api.SpanStatusCode.ERROR,
+                  message: err.message
+                });
+              }
+              span.end();
+            });
+            request.on("done", incrementStatementCount);
+            request.on("doneInProc", incrementStatementCount);
+            request.on("doneProc", incrementProcCount);
+            request.once("error", endSpan2);
+            this.on("end", endSpan2);
+            if (typeof request.callback === "function") {
+              thisPlugin._wrap(request, "callback", thisPlugin._patchCallbackQuery(endSpan2));
+            } else {
+              thisPlugin._diag.error("Expected request.callback to be a function");
+            }
+            const runUserRequest = () => {
+              return api.context.with(api.trace.setSpan(api.context.active(), span), originalMethod, this, ...arguments);
+            };
+            const cfg = thisPlugin.getConfig();
+            const shouldInject = cfg.enableTraceContextPropagation && thisPlugin._shouldInjectFor(operation);
+            if (!shouldInject)
+              return runUserRequest();
+            const traceparent = thisPlugin._buildTraceparent(span);
+            void thisPlugin._injectContextInfo(this, tediousModule, traceparent).finally(runUserRequest);
+          }
+          Object.defineProperty(patchedMethod, "length", {
+            value: originalMethod.length,
+            writable: false
+          });
+          return patchedMethod;
+        };
+      }
+      _patchCallbackQuery(endSpan2) {
+        return (originalCallback) => {
+          return function(err, rowCount, rows) {
+            endSpan2(err);
+            return originalCallback.apply(this, arguments);
+          };
+        };
+      }
+    }
+    exports$1.TediousInstrumentation = TediousInstrumentation;
+  })(instrumentation$1);
+  return instrumentation$1;
+}
+var hasRequiredSrc$2;
+function requireSrc$2() {
+  if (hasRequiredSrc$2) return src$2;
+  hasRequiredSrc$2 = 1;
+  (function(exports$1) {
+    Object.defineProperty(exports$1, "__esModule", { value: true });
+    exports$1.TediousInstrumentation = void 0;
+    var instrumentation_1 = requireInstrumentation$1();
+    Object.defineProperty(exports$1, "TediousInstrumentation", { enumerable: true, get: function() {
+      return instrumentation_1.TediousInstrumentation;
+    } });
+  })(src$2);
+  return src$2;
+}
+var srcExports$2 = requireSrc$2();
+const TEDIUS_INSTRUMENTED_METHODS = /* @__PURE__ */ new Set([
+  "callProcedure",
+  "execSql",
+  "execSqlBatch",
+  "execBulkLoad",
+  "prepare",
+  "execute"
+]);
+const INTEGRATION_NAME$4 = "Tedious";
+const instrumentTedious = generateInstrumentOnce(INTEGRATION_NAME$4, () => new srcExports$2.TediousInstrumentation({}));
+const _tediousIntegration = (() => {
+  let instrumentationWrappedCallback;
+  return {
+    name: INTEGRATION_NAME$4,
+    setupOnce() {
+      const instrumentation2 = instrumentTedious();
+      instrumentationWrappedCallback = instrumentWhenWrapped(instrumentation2);
+    },
+    setup(client) {
+      instrumentationWrappedCallback?.(
+        () => client.on("spanStart", (span) => {
+          const { description, data } = spanToJSON(span);
+          if (!description || data["db.system"] !== "mssql") {
+            return;
+          }
+          const operation = description.split(" ")[0] || "";
+          if (TEDIUS_INSTRUMENTED_METHODS.has(operation)) {
+            span.setAttribute(SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN, "auto.db.otel.tedious");
+          }
+        })
+      );
+    }
+  };
+});
+const tediousIntegration = defineIntegration(_tediousIntegration);
+var src$1 = {};
+var instrumentation = {};
+var version$1 = {};
+var hasRequiredVersion$1;
+function requireVersion$1() {
+  if (hasRequiredVersion$1) return version$1;
+  hasRequiredVersion$1 = 1;
+  Object.defineProperty(version$1, "__esModule", { value: true });
+  version$1.PACKAGE_NAME = version$1.PACKAGE_VERSION = void 0;
+  version$1.PACKAGE_VERSION = "0.52.0";
+  version$1.PACKAGE_NAME = "@opentelemetry/instrumentation-generic-pool";
+  return version$1;
+}
+var hasRequiredInstrumentation;
+function requireInstrumentation() {
+  if (hasRequiredInstrumentation) return instrumentation;
+  hasRequiredInstrumentation = 1;
+  Object.defineProperty(instrumentation, "__esModule", { value: true });
+  instrumentation.GenericPoolInstrumentation = void 0;
+  const api = /* @__PURE__ */ requireSrc$n();
+  const instrumentation_1 = require$$2;
+  const version_1 = requireVersion$1();
+  const MODULE_NAME2 = "generic-pool";
+  class GenericPoolInstrumentation extends instrumentation_1.InstrumentationBase {
+    // only used for v2 - v2.3)
+    _isDisabled = false;
+    constructor(config2 = {}) {
+      super(version_1.PACKAGE_NAME, version_1.PACKAGE_VERSION, config2);
+    }
+    init() {
+      return [
+        new instrumentation_1.InstrumentationNodeModuleDefinition(MODULE_NAME2, [">=3.0.0 <4"], (moduleExports) => {
+          const Pool = moduleExports.Pool;
+          if ((0, instrumentation_1.isWrapped)(Pool.prototype.acquire)) {
+            this._unwrap(Pool.prototype, "acquire");
+          }
+          this._wrap(Pool.prototype, "acquire", this._acquirePatcher.bind(this));
+          return moduleExports;
+        }, (moduleExports) => {
+          const Pool = moduleExports.Pool;
+          this._unwrap(Pool.prototype, "acquire");
+          return moduleExports;
+        }),
+        new instrumentation_1.InstrumentationNodeModuleDefinition(MODULE_NAME2, [">=2.4.0 <3"], (moduleExports) => {
+          const Pool = moduleExports.Pool;
+          if ((0, instrumentation_1.isWrapped)(Pool.prototype.acquire)) {
+            this._unwrap(Pool.prototype, "acquire");
+          }
+          this._wrap(Pool.prototype, "acquire", this._acquireWithCallbacksPatcher.bind(this));
+          return moduleExports;
+        }, (moduleExports) => {
+          const Pool = moduleExports.Pool;
+          this._unwrap(Pool.prototype, "acquire");
+          return moduleExports;
+        }),
+        new instrumentation_1.InstrumentationNodeModuleDefinition(MODULE_NAME2, [">=2.0.0 <2.4"], (moduleExports) => {
+          this._isDisabled = false;
+          if ((0, instrumentation_1.isWrapped)(moduleExports.Pool)) {
+            this._unwrap(moduleExports, "Pool");
+          }
+          this._wrap(moduleExports, "Pool", this._poolWrapper.bind(this));
+          return moduleExports;
+        }, (moduleExports) => {
+          this._isDisabled = true;
+          return moduleExports;
+        })
+      ];
+    }
+    _acquirePatcher(original) {
+      const instrumentation2 = this;
+      return function wrapped_acquire(...args) {
+        const parent = api.context.active();
+        const span = instrumentation2.tracer.startSpan("generic-pool.acquire", {}, parent);
+        return api.context.with(api.trace.setSpan(parent, span), () => {
+          return original.call(this, ...args).then((value) => {
+            span.end();
+            return value;
+          }, (err) => {
+            span.recordException(err);
+            span.end();
+            throw err;
+          });
+        });
+      };
+    }
+    _poolWrapper(original) {
+      const instrumentation2 = this;
+      return function wrapped_pool() {
+        const pool = original.apply(this, arguments);
+        instrumentation2._wrap(pool, "acquire", instrumentation2._acquireWithCallbacksPatcher.bind(instrumentation2));
+        return pool;
+      };
+    }
+    _acquireWithCallbacksPatcher(original) {
+      const instrumentation2 = this;
+      return function wrapped_acquire(cb, priority) {
+        if (instrumentation2._isDisabled) {
+          return original.call(this, cb, priority);
+        }
+        const parent = api.context.active();
+        const span = instrumentation2.tracer.startSpan("generic-pool.acquire", {}, parent);
+        return api.context.with(api.trace.setSpan(parent, span), () => {
+          original.call(this, (err, client) => {
+            span.end();
+            if (cb) {
+              return cb(err, client);
+            }
+          }, priority);
+        });
+      };
+    }
+  }
+  instrumentation.GenericPoolInstrumentation = GenericPoolInstrumentation;
+  return instrumentation;
+}
+var hasRequiredSrc$1;
+function requireSrc$1() {
+  if (hasRequiredSrc$1) return src$1;
+  hasRequiredSrc$1 = 1;
+  (function(exports$1) {
+    Object.defineProperty(exports$1, "__esModule", { value: true });
+    exports$1.GenericPoolInstrumentation = void 0;
+    var instrumentation_1 = requireInstrumentation();
+    Object.defineProperty(exports$1, "GenericPoolInstrumentation", { enumerable: true, get: function() {
+      return instrumentation_1.GenericPoolInstrumentation;
+    } });
+  })(src$1);
+  return src$1;
+}
+var srcExports$1 = requireSrc$1();
+const INTEGRATION_NAME$3 = "GenericPool";
+const instrumentGenericPool = generateInstrumentOnce(INTEGRATION_NAME$3, () => new srcExports$1.GenericPoolInstrumentation({}));
+const _genericPoolIntegration = (() => {
+  let instrumentationWrappedCallback;
+  return {
+    name: INTEGRATION_NAME$3,
+    setupOnce() {
+      const instrumentation2 = instrumentGenericPool();
+      instrumentationWrappedCallback = instrumentWhenWrapped(instrumentation2);
+    },
+    setup(client) {
+      instrumentationWrappedCallback?.(
+        () => client.on("spanStart", (span) => {
+          const spanJSON = spanToJSON(span);
+          const spanDescription = spanJSON.description;
+          const isGenericPoolSpan = spanDescription === "generic-pool.aquire" || spanDescription === "generic-pool.acquire";
+          if (isGenericPoolSpan) {
+            span.setAttribute(SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN, "auto.db.otel.generic_pool");
+          }
+        })
+      );
+    }
+  };
+});
+const genericPoolIntegration = defineIntegration(_genericPoolIntegration);
+var src = {};
+var amqplib = {};
+var semconv = {};
+var hasRequiredSemconv;
+function requireSemconv() {
+  if (hasRequiredSemconv) return semconv;
+  hasRequiredSemconv = 1;
+  Object.defineProperty(semconv, "__esModule", { value: true });
+  semconv.ATTR_NET_PEER_PORT = semconv.ATTR_NET_PEER_NAME = semconv.ATTR_MESSAGING_SYSTEM = semconv.ATTR_MESSAGING_OPERATION = void 0;
+  semconv.ATTR_MESSAGING_OPERATION = "messaging.operation";
+  semconv.ATTR_MESSAGING_SYSTEM = "messaging.system";
+  semconv.ATTR_NET_PEER_NAME = "net.peer.name";
+  semconv.ATTR_NET_PEER_PORT = "net.peer.port";
+  return semconv;
+}
+var semconvObsolete = {};
+var hasRequiredSemconvObsolete;
+function requireSemconvObsolete() {
+  if (hasRequiredSemconvObsolete) return semconvObsolete;
+  hasRequiredSemconvObsolete = 1;
+  Object.defineProperty(semconvObsolete, "__esModule", { value: true });
+  semconvObsolete.ATTR_MESSAGING_CONVERSATION_ID = semconvObsolete.OLD_ATTR_MESSAGING_MESSAGE_ID = semconvObsolete.MESSAGING_DESTINATION_KIND_VALUE_TOPIC = semconvObsolete.ATTR_MESSAGING_URL = semconvObsolete.ATTR_MESSAGING_PROTOCOL_VERSION = semconvObsolete.ATTR_MESSAGING_PROTOCOL = semconvObsolete.MESSAGING_OPERATION_VALUE_PROCESS = semconvObsolete.ATTR_MESSAGING_RABBITMQ_ROUTING_KEY = semconvObsolete.ATTR_MESSAGING_DESTINATION_KIND = semconvObsolete.ATTR_MESSAGING_DESTINATION = void 0;
+  semconvObsolete.ATTR_MESSAGING_DESTINATION = "messaging.destination";
+  semconvObsolete.ATTR_MESSAGING_DESTINATION_KIND = "messaging.destination_kind";
+  semconvObsolete.ATTR_MESSAGING_RABBITMQ_ROUTING_KEY = "messaging.rabbitmq.routing_key";
+  semconvObsolete.MESSAGING_OPERATION_VALUE_PROCESS = "process";
+  semconvObsolete.ATTR_MESSAGING_PROTOCOL = "messaging.protocol";
+  semconvObsolete.ATTR_MESSAGING_PROTOCOL_VERSION = "messaging.protocol_version";
+  semconvObsolete.ATTR_MESSAGING_URL = "messaging.url";
+  semconvObsolete.MESSAGING_DESTINATION_KIND_VALUE_TOPIC = "topic";
+  semconvObsolete.OLD_ATTR_MESSAGING_MESSAGE_ID = "messaging.message_id";
+  semconvObsolete.ATTR_MESSAGING_CONVERSATION_ID = "messaging.conversation_id";
+  return semconvObsolete;
+}
+var types = {};
+var hasRequiredTypes;
+function requireTypes() {
+  if (hasRequiredTypes) return types;
+  hasRequiredTypes = 1;
+  (function(exports$1) {
+    Object.defineProperty(exports$1, "__esModule", { value: true });
+    exports$1.DEFAULT_CONFIG = exports$1.EndOperation = void 0;
+    (function(EndOperation) {
+      EndOperation["AutoAck"] = "auto ack";
+      EndOperation["Ack"] = "ack";
+      EndOperation["AckAll"] = "ackAll";
+      EndOperation["Reject"] = "reject";
+      EndOperation["Nack"] = "nack";
+      EndOperation["NackAll"] = "nackAll";
+      EndOperation["ChannelClosed"] = "channel closed";
+      EndOperation["ChannelError"] = "channel error";
+      EndOperation["InstrumentationTimeout"] = "instrumentation timeout";
+    })(exports$1.EndOperation || (exports$1.EndOperation = {}));
+    exports$1.DEFAULT_CONFIG = {
+      consumeTimeoutMs: 1e3 * 60,
+      useLinksForConsume: false
+    };
+  })(types);
+  return types;
+}
+var utils = {};
+var hasRequiredUtils;
+function requireUtils() {
+  if (hasRequiredUtils) return utils;
+  hasRequiredUtils = 1;
+  Object.defineProperty(utils, "__esModule", { value: true });
+  utils.isConfirmChannelTracing = utils.unmarkConfirmChannelTracing = utils.markConfirmChannelTracing = utils.getConnectionAttributesFromUrl = utils.getConnectionAttributesFromServer = utils.normalizeExchange = utils.CONNECTION_ATTRIBUTES = utils.CHANNEL_CONSUME_TIMEOUT_TIMER = utils.CHANNEL_SPANS_NOT_ENDED = utils.MESSAGE_STORED_SPAN = void 0;
+  const api_1 = /* @__PURE__ */ requireSrc$n();
+  const semconv_1 = requireSemconv();
+  const semconv_obsolete_1 = requireSemconvObsolete();
+  utils.MESSAGE_STORED_SPAN = Symbol("opentelemetry.amqplib.message.stored-span");
+  utils.CHANNEL_SPANS_NOT_ENDED = Symbol("opentelemetry.amqplib.channel.spans-not-ended");
+  utils.CHANNEL_CONSUME_TIMEOUT_TIMER = Symbol("opentelemetry.amqplib.channel.consumer-timeout-timer");
+  utils.CONNECTION_ATTRIBUTES = Symbol("opentelemetry.amqplib.connection.attributes");
+  const IS_CONFIRM_CHANNEL_CONTEXT_KEY = (0, api_1.createContextKey)("opentelemetry.amqplib.channel.is-confirm-channel");
+  const normalizeExchange = (exchangeName) => exchangeName !== "" ? exchangeName : "";
+  utils.normalizeExchange = normalizeExchange;
+  const censorPassword = (url) => {
+    return url.replace(/:[^:@/]*@/, ":***@");
+  };
+  const getPort = (portFromUrl, resolvedProtocol) => {
+    return portFromUrl || (resolvedProtocol === "AMQP" ? 5672 : 5671);
+  };
+  const getProtocol = (protocolFromUrl) => {
+    const resolvedProtocol = protocolFromUrl || "amqp";
+    const noEndingColon = resolvedProtocol.endsWith(":") ? resolvedProtocol.substring(0, resolvedProtocol.length - 1) : resolvedProtocol;
+    return noEndingColon.toUpperCase();
+  };
+  const getHostname = (hostnameFromUrl) => {
+    return hostnameFromUrl || "localhost";
+  };
+  const extractConnectionAttributeOrLog = (url, attributeKey, attributeValue, nameForLog) => {
+    if (attributeValue) {
+      return { [attributeKey]: attributeValue };
+    } else {
+      api_1.diag.error(`amqplib instrumentation: could not extract connection attribute ${nameForLog} from user supplied url`, {
+        url
+      });
+      return {};
+    }
+  };
+  const getConnectionAttributesFromServer = (conn) => {
+    const product = conn.serverProperties.product?.toLowerCase?.();
+    if (product) {
+      return {
+        [semconv_1.ATTR_MESSAGING_SYSTEM]: product
+      };
+    } else {
+      return {};
+    }
+  };
+  utils.getConnectionAttributesFromServer = getConnectionAttributesFromServer;
+  const getConnectionAttributesFromUrl = (url) => {
+    const attributes = {
+      [semconv_obsolete_1.ATTR_MESSAGING_PROTOCOL_VERSION]: "0.9.1"
+      // this is the only protocol supported by the instrumented library
+    };
+    url = url || "amqp://localhost";
+    if (typeof url === "object") {
+      const connectOptions = url;
+      const protocol = getProtocol(connectOptions?.protocol);
+      Object.assign(attributes, {
+        ...extractConnectionAttributeOrLog(url, semconv_obsolete_1.ATTR_MESSAGING_PROTOCOL, protocol, "protocol")
+      });
+      const hostname = getHostname(connectOptions?.hostname);
+      Object.assign(attributes, {
+        ...extractConnectionAttributeOrLog(url, semconv_1.ATTR_NET_PEER_NAME, hostname, "hostname")
+      });
+      const port = getPort(connectOptions.port, protocol);
+      Object.assign(attributes, {
+        ...extractConnectionAttributeOrLog(url, semconv_1.ATTR_NET_PEER_PORT, port, "port")
+      });
+    } else {
+      const censoredUrl = censorPassword(url);
+      attributes[semconv_obsolete_1.ATTR_MESSAGING_URL] = censoredUrl;
+      try {
+        const urlParts = new URL(censoredUrl);
+        const protocol = getProtocol(urlParts.protocol);
+        Object.assign(attributes, {
+          ...extractConnectionAttributeOrLog(censoredUrl, semconv_obsolete_1.ATTR_MESSAGING_PROTOCOL, protocol, "protocol")
+        });
+        const hostname = getHostname(urlParts.hostname);
+        Object.assign(attributes, {
+          ...extractConnectionAttributeOrLog(censoredUrl, semconv_1.ATTR_NET_PEER_NAME, hostname, "hostname")
+        });
+        const port = getPort(urlParts.port ? parseInt(urlParts.port) : void 0, protocol);
+        Object.assign(attributes, {
+          ...extractConnectionAttributeOrLog(censoredUrl, semconv_1.ATTR_NET_PEER_PORT, port, "port")
+        });
+      } catch (err) {
+        api_1.diag.error("amqplib instrumentation: error while extracting connection details from connection url", {
+          censoredUrl,
+          err
+        });
+      }
+    }
+    return attributes;
+  };
+  utils.getConnectionAttributesFromUrl = getConnectionAttributesFromUrl;
+  const markConfirmChannelTracing = (context2) => {
+    return context2.setValue(IS_CONFIRM_CHANNEL_CONTEXT_KEY, true);
+  };
+  utils.markConfirmChannelTracing = markConfirmChannelTracing;
+  const unmarkConfirmChannelTracing = (context2) => {
+    return context2.deleteValue(IS_CONFIRM_CHANNEL_CONTEXT_KEY);
+  };
+  utils.unmarkConfirmChannelTracing = unmarkConfirmChannelTracing;
+  const isConfirmChannelTracing = (context2) => {
+    return context2.getValue(IS_CONFIRM_CHANNEL_CONTEXT_KEY) === true;
+  };
+  utils.isConfirmChannelTracing = isConfirmChannelTracing;
+  return utils;
+}
+var version = {};
+var hasRequiredVersion;
+function requireVersion() {
+  if (hasRequiredVersion) return version;
+  hasRequiredVersion = 1;
+  Object.defineProperty(version, "__esModule", { value: true });
+  version.PACKAGE_NAME = version.PACKAGE_VERSION = void 0;
+  version.PACKAGE_VERSION = "0.55.0";
+  version.PACKAGE_NAME = "@opentelemetry/instrumentation-amqplib";
+  return version;
+}
+var hasRequiredAmqplib;
+function requireAmqplib() {
+  if (hasRequiredAmqplib) return amqplib;
+  hasRequiredAmqplib = 1;
+  Object.defineProperty(amqplib, "__esModule", { value: true });
+  amqplib.AmqplibInstrumentation = void 0;
+  const api_1 = /* @__PURE__ */ requireSrc$n();
+  const core_1 = require$$1;
+  const instrumentation_1 = require$$2;
+  const semconv_1 = requireSemconv();
+  const semconv_obsolete_1 = requireSemconvObsolete();
+  const types_1 = requireTypes();
+  const utils_1 = requireUtils();
+  const version_1 = requireVersion();
+  const supportedVersions2 = [">=0.5.5 <1"];
+  class AmqplibInstrumentation extends instrumentation_1.InstrumentationBase {
+    constructor(config2 = {}) {
+      super(version_1.PACKAGE_NAME, version_1.PACKAGE_VERSION, { ...types_1.DEFAULT_CONFIG, ...config2 });
+    }
+    setConfig(config2 = {}) {
+      super.setConfig({ ...types_1.DEFAULT_CONFIG, ...config2 });
+    }
+    init() {
+      const channelModelModuleFile = new instrumentation_1.InstrumentationNodeModuleFile("amqplib/lib/channel_model.js", supportedVersions2, this.patchChannelModel.bind(this), this.unpatchChannelModel.bind(this));
+      const callbackModelModuleFile = new instrumentation_1.InstrumentationNodeModuleFile("amqplib/lib/callback_model.js", supportedVersions2, this.patchChannelModel.bind(this), this.unpatchChannelModel.bind(this));
+      const connectModuleFile = new instrumentation_1.InstrumentationNodeModuleFile("amqplib/lib/connect.js", supportedVersions2, this.patchConnect.bind(this), this.unpatchConnect.bind(this));
+      const module2 = new instrumentation_1.InstrumentationNodeModuleDefinition("amqplib", supportedVersions2, void 0, void 0, [channelModelModuleFile, connectModuleFile, callbackModelModuleFile]);
+      return module2;
+    }
+    patchConnect(moduleExports) {
+      moduleExports = this.unpatchConnect(moduleExports);
+      if (!(0, instrumentation_1.isWrapped)(moduleExports.connect)) {
+        this._wrap(moduleExports, "connect", this.getConnectPatch.bind(this));
+      }
+      return moduleExports;
+    }
+    unpatchConnect(moduleExports) {
+      if ((0, instrumentation_1.isWrapped)(moduleExports.connect)) {
+        this._unwrap(moduleExports, "connect");
+      }
+      return moduleExports;
+    }
+    patchChannelModel(moduleExports, moduleVersion) {
+      if (!(0, instrumentation_1.isWrapped)(moduleExports.Channel.prototype.publish)) {
+        this._wrap(moduleExports.Channel.prototype, "publish", this.getPublishPatch.bind(this, moduleVersion));
+      }
+      if (!(0, instrumentation_1.isWrapped)(moduleExports.Channel.prototype.consume)) {
+        this._wrap(moduleExports.Channel.prototype, "consume", this.getConsumePatch.bind(this, moduleVersion));
+      }
+      if (!(0, instrumentation_1.isWrapped)(moduleExports.Channel.prototype.ack)) {
+        this._wrap(moduleExports.Channel.prototype, "ack", this.getAckPatch.bind(this, false, types_1.EndOperation.Ack));
+      }
+      if (!(0, instrumentation_1.isWrapped)(moduleExports.Channel.prototype.nack)) {
+        this._wrap(moduleExports.Channel.prototype, "nack", this.getAckPatch.bind(this, true, types_1.EndOperation.Nack));
+      }
+      if (!(0, instrumentation_1.isWrapped)(moduleExports.Channel.prototype.reject)) {
+        this._wrap(moduleExports.Channel.prototype, "reject", this.getAckPatch.bind(this, true, types_1.EndOperation.Reject));
+      }
+      if (!(0, instrumentation_1.isWrapped)(moduleExports.Channel.prototype.ackAll)) {
+        this._wrap(moduleExports.Channel.prototype, "ackAll", this.getAckAllPatch.bind(this, false, types_1.EndOperation.AckAll));
+      }
+      if (!(0, instrumentation_1.isWrapped)(moduleExports.Channel.prototype.nackAll)) {
+        this._wrap(moduleExports.Channel.prototype, "nackAll", this.getAckAllPatch.bind(this, true, types_1.EndOperation.NackAll));
+      }
+      if (!(0, instrumentation_1.isWrapped)(moduleExports.Channel.prototype.emit)) {
+        this._wrap(moduleExports.Channel.prototype, "emit", this.getChannelEmitPatch.bind(this));
+      }
+      if (!(0, instrumentation_1.isWrapped)(moduleExports.ConfirmChannel.prototype.publish)) {
+        this._wrap(moduleExports.ConfirmChannel.prototype, "publish", this.getConfirmedPublishPatch.bind(this, moduleVersion));
+      }
+      return moduleExports;
+    }
+    unpatchChannelModel(moduleExports) {
+      if ((0, instrumentation_1.isWrapped)(moduleExports.Channel.prototype.publish)) {
+        this._unwrap(moduleExports.Channel.prototype, "publish");
+      }
+      if ((0, instrumentation_1.isWrapped)(moduleExports.Channel.prototype.consume)) {
+        this._unwrap(moduleExports.Channel.prototype, "consume");
+      }
+      if ((0, instrumentation_1.isWrapped)(moduleExports.Channel.prototype.ack)) {
+        this._unwrap(moduleExports.Channel.prototype, "ack");
+      }
+      if ((0, instrumentation_1.isWrapped)(moduleExports.Channel.prototype.nack)) {
+        this._unwrap(moduleExports.Channel.prototype, "nack");
+      }
+      if ((0, instrumentation_1.isWrapped)(moduleExports.Channel.prototype.reject)) {
+        this._unwrap(moduleExports.Channel.prototype, "reject");
+      }
+      if ((0, instrumentation_1.isWrapped)(moduleExports.Channel.prototype.ackAll)) {
+        this._unwrap(moduleExports.Channel.prototype, "ackAll");
+      }
+      if ((0, instrumentation_1.isWrapped)(moduleExports.Channel.prototype.nackAll)) {
+        this._unwrap(moduleExports.Channel.prototype, "nackAll");
+      }
+      if ((0, instrumentation_1.isWrapped)(moduleExports.Channel.prototype.emit)) {
+        this._unwrap(moduleExports.Channel.prototype, "emit");
+      }
+      if ((0, instrumentation_1.isWrapped)(moduleExports.ConfirmChannel.prototype.publish)) {
+        this._unwrap(moduleExports.ConfirmChannel.prototype, "publish");
+      }
+      return moduleExports;
+    }
+    getConnectPatch(original) {
+      return function patchedConnect(url, socketOptions, openCallback) {
+        return original.call(this, url, socketOptions, function(err, conn) {
+          if (err == null) {
+            const urlAttributes = (0, utils_1.getConnectionAttributesFromUrl)(url);
+            const serverAttributes = (0, utils_1.getConnectionAttributesFromServer)(conn);
+            conn[utils_1.CONNECTION_ATTRIBUTES] = {
+              ...urlAttributes,
+              ...serverAttributes
+            };
+          }
+          openCallback.apply(this, arguments);
+        });
+      };
+    }
+    getChannelEmitPatch(original) {
+      const self = this;
+      return function emit(eventName) {
+        if (eventName === "close") {
+          self.endAllSpansOnChannel(this, true, types_1.EndOperation.ChannelClosed, void 0);
+          const activeTimer = this[utils_1.CHANNEL_CONSUME_TIMEOUT_TIMER];
+          if (activeTimer) {
+            clearInterval(activeTimer);
+          }
+          this[utils_1.CHANNEL_CONSUME_TIMEOUT_TIMER] = void 0;
+        } else if (eventName === "error") {
+          self.endAllSpansOnChannel(this, true, types_1.EndOperation.ChannelError, void 0);
+        }
+        return original.apply(this, arguments);
+      };
+    }
+    getAckAllPatch(isRejected, endOperation, original) {
+      const self = this;
+      return function ackAll(requeueOrEmpty) {
+        self.endAllSpansOnChannel(this, isRejected, endOperation, requeueOrEmpty);
+        return original.apply(this, arguments);
+      };
+    }
+    getAckPatch(isRejected, endOperation, original) {
+      const self = this;
+      return function ack(message, allUpToOrRequeue, requeue) {
+        const channel = this;
+        const requeueResolved = endOperation === types_1.EndOperation.Reject ? allUpToOrRequeue : requeue;
+        const spansNotEnded = channel[utils_1.CHANNEL_SPANS_NOT_ENDED] ?? [];
+        const msgIndex = spansNotEnded.findIndex((msgDetails) => msgDetails.msg === message);
+        if (msgIndex < 0) {
+          self.endConsumerSpan(message, isRejected, endOperation, requeueResolved);
+        } else if (endOperation !== types_1.EndOperation.Reject && allUpToOrRequeue) {
+          for (let i = 0; i <= msgIndex; i++) {
+            self.endConsumerSpan(spansNotEnded[i].msg, isRejected, endOperation, requeueResolved);
+          }
+          spansNotEnded.splice(0, msgIndex + 1);
+        } else {
+          self.endConsumerSpan(message, isRejected, endOperation, requeueResolved);
+          spansNotEnded.splice(msgIndex, 1);
+        }
+        return original.apply(this, arguments);
+      };
+    }
+    getConsumePatch(moduleVersion, original) {
+      const self = this;
+      return function consume(queue, onMessage, options) {
+        const channel = this;
+        if (!Object.prototype.hasOwnProperty.call(channel, utils_1.CHANNEL_SPANS_NOT_ENDED)) {
+          const { consumeTimeoutMs } = self.getConfig();
+          if (consumeTimeoutMs) {
+            const timer = setInterval(() => {
+              self.checkConsumeTimeoutOnChannel(channel);
+            }, consumeTimeoutMs);
+            timer.unref();
+            channel[utils_1.CHANNEL_CONSUME_TIMEOUT_TIMER] = timer;
+          }
+          channel[utils_1.CHANNEL_SPANS_NOT_ENDED] = [];
+        }
+        const patchedOnMessage = function(msg) {
+          if (!msg) {
+            return onMessage.call(this, msg);
+          }
+          const headers = msg.properties.headers ?? {};
+          let parentContext = api_1.propagation.extract(api_1.ROOT_CONTEXT, headers);
+          const exchange = msg.fields?.exchange;
+          let links;
+          if (self._config.useLinksForConsume) {
+            const parentSpanContext = parentContext ? api_1.trace.getSpan(parentContext)?.spanContext() : void 0;
+            parentContext = void 0;
+            if (parentSpanContext) {
+              links = [
+                {
+                  context: parentSpanContext
+                }
+              ];
+            }
+          }
+          const span = self.tracer.startSpan(`${queue} process`, {
+            kind: api_1.SpanKind.CONSUMER,
+            attributes: {
+              ...channel?.connection?.[utils_1.CONNECTION_ATTRIBUTES],
+              [semconv_obsolete_1.ATTR_MESSAGING_DESTINATION]: exchange,
+              [semconv_obsolete_1.ATTR_MESSAGING_DESTINATION_KIND]: semconv_obsolete_1.MESSAGING_DESTINATION_KIND_VALUE_TOPIC,
+              [semconv_obsolete_1.ATTR_MESSAGING_RABBITMQ_ROUTING_KEY]: msg.fields?.routingKey,
+              [semconv_1.ATTR_MESSAGING_OPERATION]: semconv_obsolete_1.MESSAGING_OPERATION_VALUE_PROCESS,
+              [semconv_obsolete_1.OLD_ATTR_MESSAGING_MESSAGE_ID]: msg?.properties.messageId,
+              [semconv_obsolete_1.ATTR_MESSAGING_CONVERSATION_ID]: msg?.properties.correlationId
+            },
+            links
+          }, parentContext);
+          const { consumeHook } = self.getConfig();
+          if (consumeHook) {
+            (0, instrumentation_1.safeExecuteInTheMiddle)(() => consumeHook(span, { moduleVersion, msg }), (e) => {
+              if (e) {
+                api_1.diag.error("amqplib instrumentation: consumerHook error", e);
+              }
+            }, true);
+          }
+          if (!options?.noAck) {
+            channel[utils_1.CHANNEL_SPANS_NOT_ENDED].push({
+              msg,
+              timeOfConsume: (0, core_1.hrTime)()
+            });
+            msg[utils_1.MESSAGE_STORED_SPAN] = span;
+          }
+          const setContext = parentContext ? parentContext : api_1.ROOT_CONTEXT;
+          api_1.context.with(api_1.trace.setSpan(setContext, span), () => {
+            onMessage.call(this, msg);
+          });
+          if (options?.noAck) {
+            self.callConsumeEndHook(span, msg, false, types_1.EndOperation.AutoAck);
+            span.end();
+          }
+        };
+        arguments[1] = patchedOnMessage;
+        return original.apply(this, arguments);
+      };
+    }
+    getConfirmedPublishPatch(moduleVersion, original) {
+      const self = this;
+      return function confirmedPublish(exchange, routingKey, content, options, callback) {
+        const channel = this;
+        const { span, modifiedOptions } = self.createPublishSpan(self, exchange, routingKey, channel, options);
+        const { publishHook } = self.getConfig();
+        if (publishHook) {
+          (0, instrumentation_1.safeExecuteInTheMiddle)(() => publishHook(span, {
+            moduleVersion,
+            exchange,
+            routingKey,
+            content,
+            options: modifiedOptions,
+            isConfirmChannel: true
+          }), (e) => {
+            if (e) {
+              api_1.diag.error("amqplib instrumentation: publishHook error", e);
+            }
+          }, true);
+        }
+        const patchedOnConfirm = function(err, ok) {
+          try {
+            callback?.call(this, err, ok);
+          } finally {
+            const { publishConfirmHook } = self.getConfig();
+            if (publishConfirmHook) {
+              (0, instrumentation_1.safeExecuteInTheMiddle)(() => publishConfirmHook(span, {
+                moduleVersion,
+                exchange,
+                routingKey,
+                content,
+                options,
+                isConfirmChannel: true,
+                confirmError: err
+              }), (e) => {
+                if (e) {
+                  api_1.diag.error("amqplib instrumentation: publishConfirmHook error", e);
+                }
+              }, true);
+            }
+            if (err) {
+              span.setStatus({
+                code: api_1.SpanStatusCode.ERROR,
+                message: "message confirmation has been nack'ed"
+              });
+            }
+            span.end();
+          }
+        };
+        const markedContext = (0, utils_1.markConfirmChannelTracing)(api_1.context.active());
+        const argumentsCopy = [...arguments];
+        argumentsCopy[3] = modifiedOptions;
+        argumentsCopy[4] = api_1.context.bind((0, utils_1.unmarkConfirmChannelTracing)(api_1.trace.setSpan(markedContext, span)), patchedOnConfirm);
+        return api_1.context.with(markedContext, original.bind(this, ...argumentsCopy));
+      };
+    }
+    getPublishPatch(moduleVersion, original) {
+      const self = this;
+      return function publish(exchange, routingKey, content, options) {
+        if ((0, utils_1.isConfirmChannelTracing)(api_1.context.active())) {
+          return original.apply(this, arguments);
+        } else {
+          const channel = this;
+          const { span, modifiedOptions } = self.createPublishSpan(self, exchange, routingKey, channel, options);
+          const { publishHook } = self.getConfig();
+          if (publishHook) {
+            (0, instrumentation_1.safeExecuteInTheMiddle)(() => publishHook(span, {
+              moduleVersion,
+              exchange,
+              routingKey,
+              content,
+              options: modifiedOptions,
+              isConfirmChannel: false
+            }), (e) => {
+              if (e) {
+                api_1.diag.error("amqplib instrumentation: publishHook error", e);
+              }
+            }, true);
+          }
+          const argumentsCopy = [...arguments];
+          argumentsCopy[3] = modifiedOptions;
+          const originalRes = original.apply(this, argumentsCopy);
+          span.end();
+          return originalRes;
+        }
+      };
+    }
+    createPublishSpan(self, exchange, routingKey, channel, options) {
+      const normalizedExchange = (0, utils_1.normalizeExchange)(exchange);
+      const span = self.tracer.startSpan(`publish ${normalizedExchange}`, {
+        kind: api_1.SpanKind.PRODUCER,
+        attributes: {
+          ...channel.connection[utils_1.CONNECTION_ATTRIBUTES],
+          [semconv_obsolete_1.ATTR_MESSAGING_DESTINATION]: exchange,
+          [semconv_obsolete_1.ATTR_MESSAGING_DESTINATION_KIND]: semconv_obsolete_1.MESSAGING_DESTINATION_KIND_VALUE_TOPIC,
+          [semconv_obsolete_1.ATTR_MESSAGING_RABBITMQ_ROUTING_KEY]: routingKey,
+          [semconv_obsolete_1.OLD_ATTR_MESSAGING_MESSAGE_ID]: options?.messageId,
+          [semconv_obsolete_1.ATTR_MESSAGING_CONVERSATION_ID]: options?.correlationId
+        }
+      });
+      const modifiedOptions = options ?? {};
+      modifiedOptions.headers = modifiedOptions.headers ?? {};
+      api_1.propagation.inject(api_1.trace.setSpan(api_1.context.active(), span), modifiedOptions.headers);
+      return { span, modifiedOptions };
+    }
+    endConsumerSpan(message, isRejected, operation, requeue) {
+      const storedSpan = message[utils_1.MESSAGE_STORED_SPAN];
+      if (!storedSpan)
+        return;
+      if (isRejected !== false) {
+        storedSpan.setStatus({
+          code: api_1.SpanStatusCode.ERROR,
+          message: operation !== types_1.EndOperation.ChannelClosed && operation !== types_1.EndOperation.ChannelError ? `${operation} called on message${requeue === true ? " with requeue" : requeue === false ? " without requeue" : ""}` : operation
+        });
+      }
+      this.callConsumeEndHook(storedSpan, message, isRejected, operation);
+      storedSpan.end();
+      message[utils_1.MESSAGE_STORED_SPAN] = void 0;
+    }
+    endAllSpansOnChannel(channel, isRejected, operation, requeue) {
+      const spansNotEnded = channel[utils_1.CHANNEL_SPANS_NOT_ENDED] ?? [];
+      spansNotEnded.forEach((msgDetails) => {
+        this.endConsumerSpan(msgDetails.msg, isRejected, operation, requeue);
+      });
+      channel[utils_1.CHANNEL_SPANS_NOT_ENDED] = [];
+    }
+    callConsumeEndHook(span, msg, rejected, endOperation) {
+      const { consumeEndHook } = this.getConfig();
+      if (!consumeEndHook)
+        return;
+      (0, instrumentation_1.safeExecuteInTheMiddle)(() => consumeEndHook(span, { msg, rejected, endOperation }), (e) => {
+        if (e) {
+          api_1.diag.error("amqplib instrumentation: consumerEndHook error", e);
+        }
+      }, true);
+    }
+    checkConsumeTimeoutOnChannel(channel) {
+      const currentTime = (0, core_1.hrTime)();
+      const spansNotEnded = channel[utils_1.CHANNEL_SPANS_NOT_ENDED] ?? [];
+      let i;
+      const { consumeTimeoutMs } = this.getConfig();
+      for (i = 0; i < spansNotEnded.length; i++) {
+        const currMessage = spansNotEnded[i];
+        const timeFromConsume = (0, core_1.hrTimeDuration)(currMessage.timeOfConsume, currentTime);
+        if ((0, core_1.hrTimeToMilliseconds)(timeFromConsume) < consumeTimeoutMs) {
+          break;
+        }
+        this.endConsumerSpan(currMessage.msg, null, types_1.EndOperation.InstrumentationTimeout, true);
+      }
+      spansNotEnded.splice(0, i);
+    }
+  }
+  amqplib.AmqplibInstrumentation = AmqplibInstrumentation;
+  return amqplib;
+}
+var hasRequiredSrc;
+function requireSrc() {
+  if (hasRequiredSrc) return src;
+  hasRequiredSrc = 1;
+  (function(exports$1) {
+    Object.defineProperty(exports$1, "__esModule", { value: true });
+    exports$1.EndOperation = exports$1.DEFAULT_CONFIG = exports$1.AmqplibInstrumentation = void 0;
+    var amqplib_1 = requireAmqplib();
+    Object.defineProperty(exports$1, "AmqplibInstrumentation", { enumerable: true, get: function() {
+      return amqplib_1.AmqplibInstrumentation;
+    } });
+    var types_1 = requireTypes();
+    Object.defineProperty(exports$1, "DEFAULT_CONFIG", { enumerable: true, get: function() {
+      return types_1.DEFAULT_CONFIG;
+    } });
+    Object.defineProperty(exports$1, "EndOperation", { enumerable: true, get: function() {
+      return types_1.EndOperation;
+    } });
+  })(src);
+  return src;
+}
+var srcExports = requireSrc();
+const INTEGRATION_NAME$2 = "Amqplib";
+const config$1 = {
+  consumeEndHook: (span) => {
+    addOriginToSpan(span, "auto.amqplib.otel.consumer");
+  },
+  publishHook: (span) => {
+    addOriginToSpan(span, "auto.amqplib.otel.publisher");
+  }
+};
+const instrumentAmqplib = generateInstrumentOnce(INTEGRATION_NAME$2, () => new srcExports.AmqplibInstrumentation(config$1));
+const _amqplibIntegration = (() => {
+  return {
+    name: INTEGRATION_NAME$2,
+    setupOnce() {
+      instrumentAmqplib();
+    }
+  };
+});
+const amqplibIntegration = defineIntegration(_amqplibIntegration);
+const INTEGRATION_NAME$1 = "VercelAI";
+const INSTRUMENTED_METHODS = [
+  "generateText",
+  "streamText",
+  "generateObject",
+  "streamObject",
+  "embed",
+  "embedMany"
+];
+function isToolError(obj) {
+  if (typeof obj !== "object" || obj === null) {
+    return false;
+  }
+  const candidate = obj;
+  return "type" in candidate && "error" in candidate && "toolName" in candidate && "toolCallId" in candidate && candidate.type === "tool-error" && candidate.error instanceof Error;
+}
+function checkResultForToolErrors(result) {
+  if (typeof result !== "object" || result === null || !("content" in result)) {
+    return;
+  }
+  const resultObj = result;
+  if (!Array.isArray(resultObj.content)) {
+    return;
+  }
+  for (const item of resultObj.content) {
+    if (isToolError(item)) {
+      const associatedSpan = _INTERNAL_getSpanForToolCallId(item.toolCallId);
+      if (associatedSpan) {
+        const spanContext = associatedSpan.spanContext();
+        withScope((scope) => {
+          scope.setContext("trace", {
+            trace_id: spanContext.traceId,
+            span_id: spanContext.spanId
+          });
+          scope.setTag("vercel.ai.tool.name", item.toolName);
+          scope.setTag("vercel.ai.tool.callId", item.toolCallId);
+          scope.setLevel("error");
+          captureException(item.error, {
+            mechanism: {
+              type: "auto.vercelai.otel",
+              handled: false
+            }
+          });
+        });
+        _INTERNAL_cleanupToolCallSpan(item.toolCallId);
+      } else {
+        withScope((scope) => {
+          scope.setTag("vercel.ai.tool.name", item.toolName);
+          scope.setTag("vercel.ai.tool.callId", item.toolCallId);
+          scope.setLevel("error");
+          captureException(item.error, {
+            mechanism: {
+              type: "auto.vercelai.otel",
+              handled: false
+            }
+          });
+        });
+      }
+    }
+  }
+}
+function determineRecordingSettings(integrationRecordingOptions, methodTelemetryOptions, telemetryExplicitlyEnabled, defaultRecordingEnabled) {
+  const recordInputs = integrationRecordingOptions?.recordInputs !== void 0 ? integrationRecordingOptions.recordInputs : methodTelemetryOptions.recordInputs !== void 0 ? methodTelemetryOptions.recordInputs : telemetryExplicitlyEnabled === true ? true : defaultRecordingEnabled;
+  const recordOutputs = integrationRecordingOptions?.recordOutputs !== void 0 ? integrationRecordingOptions.recordOutputs : methodTelemetryOptions.recordOutputs !== void 0 ? methodTelemetryOptions.recordOutputs : telemetryExplicitlyEnabled === true ? true : defaultRecordingEnabled;
+  return { recordInputs, recordOutputs };
+}
+class SentryVercelAiInstrumentation extends InstrumentationBase {
+  __init() {
+    this._isPatched = false;
+  }
+  __init2() {
+    this._callbacks = [];
+  }
+  constructor(config2 = {}) {
+    super("@sentry/instrumentation-vercel-ai", SDK_VERSION, config2);
+    SentryVercelAiInstrumentation.prototype.__init.call(this);
+    SentryVercelAiInstrumentation.prototype.__init2.call(this);
+  }
+  /**
+   * Initializes the instrumentation by defining the modules to be patched.
+   */
+  init() {
+    const module2 = new InstrumentationNodeModuleDefinition("ai", [">=3.0.0 <6"], this._patch.bind(this));
+    return module2;
+  }
+  /**
+   * Call the provided callback when the module is patched.
+   * If it has already been patched, the callback will be called immediately.
+   */
+  callWhenPatched(callback) {
+    if (this._isPatched) {
+      callback();
+    } else {
+      this._callbacks.push(callback);
+    }
+  }
+  /**
+   * Patches module exports to enable Vercel AI telemetry.
+   */
+  _patch(moduleExports) {
+    this._isPatched = true;
+    this._callbacks.forEach((callback) => callback());
+    this._callbacks = [];
+    const generatePatch = (originalMethod) => {
+      return new Proxy(originalMethod, {
+        apply: (target, thisArg, args) => {
+          const existingExperimentalTelemetry = args[0].experimental_telemetry || {};
+          const isEnabled2 = existingExperimentalTelemetry.isEnabled;
+          const client = getClient();
+          const integration = client?.getIntegrationByName(INTEGRATION_NAME$1);
+          const integrationOptions = integration?.options;
+          const shouldRecordInputsAndOutputs = integration ? Boolean(client?.getOptions().sendDefaultPii) : false;
+          const { recordInputs, recordOutputs } = determineRecordingSettings(
+            integrationOptions,
+            existingExperimentalTelemetry,
+            isEnabled2,
+            shouldRecordInputsAndOutputs
+          );
+          args[0].experimental_telemetry = {
+            ...existingExperimentalTelemetry,
+            isEnabled: isEnabled2 !== void 0 ? isEnabled2 : true,
+            recordInputs,
+            recordOutputs
+          };
+          return handleCallbackErrors(
+            () => Reflect.apply(target, thisArg, args),
+            (error2) => {
+              if (error2 && typeof error2 === "object") {
+                addNonEnumerableProperty(error2, "_sentry_active_span", getActiveSpan$1());
+              }
+            },
+            () => {
+            },
+            (result) => {
+              checkResultForToolErrors(result);
+            }
+          );
+        }
+      });
+    };
+    if (Object.prototype.toString.call(moduleExports) === "[object Module]") {
+      for (const method of INSTRUMENTED_METHODS) {
+        moduleExports[method] = generatePatch(moduleExports[method]);
+      }
+      return moduleExports;
+    } else {
+      const patchedModuleExports = INSTRUMENTED_METHODS.reduce((acc, curr) => {
+        acc[curr] = generatePatch(moduleExports[curr]);
+        return acc;
+      }, {});
+      return { ...moduleExports, ...patchedModuleExports };
+    }
+  }
+}
+const instrumentVercelAi = generateInstrumentOnce(INTEGRATION_NAME$1, () => new SentryVercelAiInstrumentation({}));
+function shouldForceIntegration(client) {
+  const modules = client.getIntegrationByName("Modules");
+  return !!modules?.getModules?.()?.ai;
+}
+const _vercelAIIntegration = ((options = {}) => {
+  let instrumentation2;
+  return {
+    name: INTEGRATION_NAME$1,
+    options,
+    setupOnce() {
+      instrumentation2 = instrumentVercelAi();
+    },
+    afterAllSetup(client) {
+      const shouldForce = options.force ?? shouldForceIntegration(client);
+      if (shouldForce) {
+        addVercelAiProcessors(client);
+      } else {
+        instrumentation2?.callWhenPatched(() => addVercelAiProcessors(client));
+      }
+    }
+  };
+});
+const vercelAIIntegration = defineIntegration(_vercelAIIntegration);
+const supportedVersions$4 = [">=4.0.0 <7"];
+class SentryOpenAiInstrumentation extends InstrumentationBase {
+  constructor(config2 = {}) {
+    super("@sentry/instrumentation-openai", SDK_VERSION, config2);
+  }
+  /**
+   * Initializes the instrumentation by defining the modules to be patched.
+   */
+  init() {
+    const module2 = new InstrumentationNodeModuleDefinition("openai", supportedVersions$4, this._patch.bind(this));
+    return module2;
+  }
+  /**
+   * Core patch logic applying instrumentation to the OpenAI and AzureOpenAI client constructors.
+   */
+  _patch(exports$1) {
+    let result = exports$1;
+    result = this._patchClient(result, "OpenAI");
+    result = this._patchClient(result, "AzureOpenAI");
+    return result;
+  }
+  /**
+   * Patch logic applying instrumentation to the specified client constructor.
+   */
+  _patchClient(exports$1, exportKey) {
+    const Original = exports$1[exportKey];
+    if (!Original) {
+      return exports$1;
+    }
+    const config2 = this.getConfig();
+    const WrappedOpenAI = function(...args) {
+      if (_INTERNAL_shouldSkipAiProviderWrapping(OPENAI_INTEGRATION_NAME)) {
+        return Reflect.construct(Original, args);
+      }
+      const instance = Reflect.construct(Original, args);
+      const client = getClient();
+      const defaultPii = Boolean(client?.getOptions().sendDefaultPii);
+      const recordInputs = config2.recordInputs ?? defaultPii;
+      const recordOutputs = config2.recordOutputs ?? defaultPii;
+      return instrumentOpenAiClient(instance, {
+        recordInputs,
+        recordOutputs
+      });
+    };
+    Object.setPrototypeOf(WrappedOpenAI, Original);
+    Object.setPrototypeOf(WrappedOpenAI.prototype, Original.prototype);
+    for (const key of Object.getOwnPropertyNames(Original)) {
+      if (!["length", "name", "prototype"].includes(key)) {
+        const descriptor = Object.getOwnPropertyDescriptor(Original, key);
+        if (descriptor) {
+          Object.defineProperty(WrappedOpenAI, key, descriptor);
+        }
+      }
+    }
+    try {
+      exports$1[exportKey] = WrappedOpenAI;
+    } catch (error2) {
+      Object.defineProperty(exports$1, exportKey, {
+        value: WrappedOpenAI,
+        writable: true,
+        configurable: true,
+        enumerable: true
+      });
+    }
+    if (exports$1.default === Original) {
+      try {
+        exports$1.default = WrappedOpenAI;
+      } catch (error2) {
+        Object.defineProperty(exports$1, "default", {
+          value: WrappedOpenAI,
+          writable: true,
+          configurable: true,
+          enumerable: true
+        });
+      }
+    }
+    return exports$1;
+  }
+}
+const instrumentOpenAi = generateInstrumentOnce(
+  OPENAI_INTEGRATION_NAME,
+  (options) => new SentryOpenAiInstrumentation(options)
+);
+const _openAiIntegration = ((options = {}) => {
+  return {
+    name: OPENAI_INTEGRATION_NAME,
+    setupOnce() {
+      instrumentOpenAi(options);
+    }
+  };
+});
+const openAIIntegration = defineIntegration(_openAiIntegration);
+const supportedVersions$3 = [">=0.19.2 <1.0.0"];
+class SentryAnthropicAiInstrumentation extends InstrumentationBase {
+  constructor(config2 = {}) {
+    super("@sentry/instrumentation-anthropic-ai", SDK_VERSION, config2);
+  }
+  /**
+   * Initializes the instrumentation by defining the modules to be patched.
+   */
+  init() {
+    const module2 = new InstrumentationNodeModuleDefinition(
+      "@anthropic-ai/sdk",
+      supportedVersions$3,
+      this._patch.bind(this)
+    );
+    return module2;
+  }
+  /**
+   * Core patch logic applying instrumentation to the Anthropic AI client constructor.
+   */
+  _patch(exports$1) {
+    const Original = exports$1.Anthropic;
+    const config2 = this.getConfig();
+    const WrappedAnthropic = function(...args) {
+      if (_INTERNAL_shouldSkipAiProviderWrapping(ANTHROPIC_AI_INTEGRATION_NAME)) {
+        return Reflect.construct(Original, args);
+      }
+      const instance = Reflect.construct(Original, args);
+      const client = getClient();
+      const defaultPii = Boolean(client?.getOptions().sendDefaultPii);
+      const recordInputs = config2.recordInputs ?? defaultPii;
+      const recordOutputs = config2.recordOutputs ?? defaultPii;
+      return instrumentAnthropicAiClient(instance, {
+        recordInputs,
+        recordOutputs
+      });
+    };
+    Object.setPrototypeOf(WrappedAnthropic, Original);
+    Object.setPrototypeOf(WrappedAnthropic.prototype, Original.prototype);
+    for (const key of Object.getOwnPropertyNames(Original)) {
+      if (!["length", "name", "prototype"].includes(key)) {
+        const descriptor = Object.getOwnPropertyDescriptor(Original, key);
+        if (descriptor) {
+          Object.defineProperty(WrappedAnthropic, key, descriptor);
+        }
+      }
+    }
+    try {
+      exports$1.Anthropic = WrappedAnthropic;
+    } catch (error2) {
+      Object.defineProperty(exports$1, "Anthropic", {
+        value: WrappedAnthropic,
+        writable: true,
+        configurable: true,
+        enumerable: true
+      });
+    }
+    if (exports$1.default === Original) {
+      try {
+        exports$1.default = WrappedAnthropic;
+      } catch (error2) {
+        Object.defineProperty(exports$1, "default", {
+          value: WrappedAnthropic,
+          writable: true,
+          configurable: true,
+          enumerable: true
+        });
+      }
+    }
+    return exports$1;
+  }
+}
+const instrumentAnthropicAi = generateInstrumentOnce(
+  ANTHROPIC_AI_INTEGRATION_NAME,
+  (options) => new SentryAnthropicAiInstrumentation(options)
+);
+const _anthropicAIIntegration = ((options = {}) => {
+  return {
+    name: ANTHROPIC_AI_INTEGRATION_NAME,
+    options,
+    setupOnce() {
+      instrumentAnthropicAi(options);
+    }
+  };
+});
+const anthropicAIIntegration = defineIntegration(_anthropicAIIntegration);
+const supportedVersions$2 = [">=0.10.0 <2"];
+class SentryGoogleGenAiInstrumentation extends InstrumentationBase {
+  constructor(config2 = {}) {
+    super("@sentry/instrumentation-google-genai", SDK_VERSION, config2);
+  }
+  /**
+   * Initializes the instrumentation by defining the modules to be patched.
+   */
+  init() {
+    const module2 = new InstrumentationNodeModuleDefinition(
+      "@google/genai",
+      supportedVersions$2,
+      (exports$1) => this._patch(exports$1),
+      (exports$1) => exports$1,
+      // In CJS, @google/genai re-exports from (dist/node/index.cjs) file.
+      // Patching only the root module sometimes misses the real implementation or
+      // gets overwritten when that file is loaded. We add a file-level patch so that
+      // _patch runs again on the concrete implementation
+      [
+        new InstrumentationNodeModuleFile(
+          "@google/genai/dist/node/index.cjs",
+          supportedVersions$2,
+          (exports$1) => this._patch(exports$1),
+          (exports$1) => exports$1
+        )
+      ]
+    );
+    return module2;
+  }
+  /**
+   * Core patch logic applying instrumentation to the Google GenAI client constructor.
+   */
+  _patch(exports$1) {
+    const Original = exports$1.GoogleGenAI;
+    const config2 = this.getConfig();
+    if (typeof Original !== "function") {
+      return exports$1;
+    }
+    const WrappedGoogleGenAI = function(...args) {
+      if (_INTERNAL_shouldSkipAiProviderWrapping(GOOGLE_GENAI_INTEGRATION_NAME)) {
+        return Reflect.construct(Original, args);
+      }
+      const instance = Reflect.construct(Original, args);
+      const client = getClient();
+      const defaultPii = Boolean(client?.getOptions().sendDefaultPii);
+      const typedConfig = config2;
+      const recordInputs = typedConfig?.recordInputs ?? defaultPii;
+      const recordOutputs = typedConfig?.recordOutputs ?? defaultPii;
+      return instrumentGoogleGenAIClient(instance, {
+        recordInputs,
+        recordOutputs
+      });
+    };
+    Object.setPrototypeOf(WrappedGoogleGenAI, Original);
+    Object.setPrototypeOf(WrappedGoogleGenAI.prototype, Original.prototype);
+    for (const key of Object.getOwnPropertyNames(Original)) {
+      if (!["length", "name", "prototype"].includes(key)) {
+        const descriptor = Object.getOwnPropertyDescriptor(Original, key);
+        if (descriptor) {
+          Object.defineProperty(WrappedGoogleGenAI, key, descriptor);
+        }
+      }
+    }
+    replaceExports(exports$1, "GoogleGenAI", WrappedGoogleGenAI);
+    return exports$1;
+  }
+}
+const instrumentGoogleGenAI = generateInstrumentOnce(
+  GOOGLE_GENAI_INTEGRATION_NAME,
+  (options) => new SentryGoogleGenAiInstrumentation(options)
+);
+const _googleGenAIIntegration = ((options = {}) => {
+  return {
+    name: GOOGLE_GENAI_INTEGRATION_NAME,
+    setupOnce() {
+      instrumentGoogleGenAI(options);
+    }
+  };
+});
+const googleGenAIIntegration = defineIntegration(_googleGenAIIntegration);
+const supportedVersions$1 = [">=0.1.0 <2.0.0"];
+function augmentCallbackHandlers(handlers2, sentryHandler) {
+  if (!handlers2) {
+    return [sentryHandler];
+  }
+  if (Array.isArray(handlers2)) {
+    if (handlers2.includes(sentryHandler)) {
+      return handlers2;
+    }
+    return [...handlers2, sentryHandler];
+  }
+  if (typeof handlers2 === "object") {
+    return [handlers2, sentryHandler];
+  }
+  return handlers2;
+}
+function wrapRunnableMethod(originalMethod, sentryHandler, _methodName) {
+  return new Proxy(originalMethod, {
+    apply(target, thisArg, args) {
+      const optionsIndex = 1;
+      let options = args[optionsIndex];
+      if (!options || typeof options !== "object" || Array.isArray(options)) {
+        options = {};
+        args[optionsIndex] = options;
+      }
+      const existingCallbacks = options.callbacks;
+      const augmentedCallbacks = augmentCallbackHandlers(existingCallbacks, sentryHandler);
+      options.callbacks = augmentedCallbacks;
+      return Reflect.apply(target, thisArg, args);
+    }
+  });
+}
+class SentryLangChainInstrumentation extends InstrumentationBase {
+  constructor(config2 = {}) {
+    super("@sentry/instrumentation-langchain", SDK_VERSION, config2);
+  }
+  /**
+   * Initializes the instrumentation by defining the modules to be patched.
+   * We patch the BaseChatModel class methods to inject callbacks
+   *
+   * We hook into provider packages (@langchain/anthropic, @langchain/openai, etc.)
+   * because @langchain/core is often bundled and not loaded as a separate module
+   */
+  init() {
+    const modules = [];
+    const providerPackages = [
+      "@langchain/anthropic",
+      "@langchain/openai",
+      "@langchain/google-genai",
+      "@langchain/mistralai",
+      "@langchain/google-vertexai",
+      "@langchain/groq"
+    ];
+    for (const packageName of providerPackages) {
+      modules.push(
+        new InstrumentationNodeModuleDefinition(
+          packageName,
+          supportedVersions$1,
+          this._patch.bind(this),
+          (exports$1) => exports$1,
+          [
+            new InstrumentationNodeModuleFile(
+              `${packageName}/dist/index.cjs`,
+              supportedVersions$1,
+              this._patch.bind(this),
+              (exports$1) => exports$1
+            )
+          ]
+        )
+      );
+    }
+    modules.push(
+      new InstrumentationNodeModuleDefinition(
+        "langchain",
+        supportedVersions$1,
+        this._patch.bind(this),
+        (exports$1) => exports$1,
+        [
+          // To catch the CJS build that contains ConfigurableModel / initChatModel for v1
+          new InstrumentationNodeModuleFile(
+            "langchain/dist/chat_models/universal.cjs",
+            supportedVersions$1,
+            this._patch.bind(this),
+            (exports$1) => exports$1
+          )
+        ]
+      )
+    );
+    return modules;
+  }
+  /**
+   * Core patch logic - patches chat model methods to inject Sentry callbacks
+   * This is called when a LangChain provider package is loaded
+   */
+  _patch(exports$1) {
+    _INTERNAL_skipAiProviderWrapping([
+      OPENAI_INTEGRATION_NAME,
+      ANTHROPIC_AI_INTEGRATION_NAME,
+      GOOGLE_GENAI_INTEGRATION_NAME
+    ]);
+    const client = getClient();
+    const defaultPii = Boolean(client?.getOptions().sendDefaultPii);
+    const config2 = this.getConfig();
+    const recordInputs = config2?.recordInputs ?? defaultPii;
+    const recordOutputs = config2?.recordOutputs ?? defaultPii;
+    const sentryHandler = createLangChainCallbackHandler({
+      recordInputs,
+      recordOutputs
+    });
+    this._patchRunnableMethods(exports$1, sentryHandler);
+    return exports$1;
+  }
+  /**
+   * Patches chat model methods (invoke, stream, batch) to inject Sentry callbacks
+   * Finds a chat model class from the provider package exports and patches its prototype methods
+   */
+  _patchRunnableMethods(exports$1, sentryHandler) {
+    const knownChatModelNames = [
+      "ChatAnthropic",
+      "ChatOpenAI",
+      "ChatGoogleGenerativeAI",
+      "ChatMistralAI",
+      "ChatVertexAI",
+      "ChatGroq",
+      "ConfigurableModel"
+    ];
+    const exportsToPatch = exports$1.universal_exports ?? exports$1;
+    const chatModelClass = Object.values(exportsToPatch).find((exp) => {
+      return typeof exp === "function" && knownChatModelNames.includes(exp.name);
+    });
+    if (!chatModelClass) {
+      return;
+    }
+    const targetProto = chatModelClass.prototype;
+    const methodsToPatch = ["invoke", "stream", "batch"];
+    for (const methodName of methodsToPatch) {
+      const method = targetProto[methodName];
+      if (typeof method === "function") {
+        targetProto[methodName] = wrapRunnableMethod(
+          method,
+          sentryHandler
+        );
+      }
+    }
+  }
+}
+const instrumentLangChain = generateInstrumentOnce(
+  LANGCHAIN_INTEGRATION_NAME,
+  (options) => new SentryLangChainInstrumentation(options)
+);
+const _langChainIntegration = ((options = {}) => {
+  return {
+    name: LANGCHAIN_INTEGRATION_NAME,
+    setupOnce() {
+      instrumentLangChain(options);
+    }
+  };
+});
+const langChainIntegration = defineIntegration(_langChainIntegration);
+const supportedVersions = [">=0.0.0 <2.0.0"];
+class SentryLangGraphInstrumentation extends InstrumentationBase {
+  constructor(config2 = {}) {
+    super("@sentry/instrumentation-langgraph", SDK_VERSION, config2);
+  }
+  /**
+   * Initializes the instrumentation by defining the modules to be patched.
+   */
+  init() {
+    const module2 = new InstrumentationNodeModuleDefinition(
+      "@langchain/langgraph",
+      supportedVersions,
+      this._patch.bind(this),
+      (exports$1) => exports$1,
+      [
+        new InstrumentationNodeModuleFile(
+          /**
+           * In CJS, LangGraph packages re-export from dist/index.cjs files.
+           * Patching only the root module sometimes misses the real implementation or
+           * gets overwritten when that file is loaded. We add a file-level patch so that
+           * _patch runs again on the concrete implementation
+           */
+          "@langchain/langgraph/dist/index.cjs",
+          supportedVersions,
+          this._patch.bind(this),
+          (exports$1) => exports$1
+        )
+      ]
+    );
+    return module2;
+  }
+  /**
+   * Core patch logic applying instrumentation to the LangGraph module.
+   */
+  _patch(exports$1) {
+    const client = getClient();
+    const defaultPii = Boolean(client?.getOptions().sendDefaultPii);
+    const config2 = this.getConfig();
+    const recordInputs = config2.recordInputs ?? defaultPii;
+    const recordOutputs = config2.recordOutputs ?? defaultPii;
+    const options = {
+      recordInputs,
+      recordOutputs
+    };
+    if (exports$1.StateGraph && typeof exports$1.StateGraph === "function") {
+      const StateGraph = exports$1.StateGraph;
+      StateGraph.prototype.compile = instrumentStateGraphCompile(
+        StateGraph.prototype.compile,
+        options
+      );
+    }
+    return exports$1;
+  }
+}
+const instrumentLangGraph = generateInstrumentOnce(
+  LANGGRAPH_INTEGRATION_NAME,
+  (options) => new SentryLangGraphInstrumentation(options)
+);
+const _langGraphIntegration = ((options = {}) => {
+  return {
+    name: LANGGRAPH_INTEGRATION_NAME,
+    setupOnce() {
+      instrumentLangGraph(options);
+    }
+  };
+});
+const langGraphIntegration = defineIntegration(_langGraphIntegration);
+function patchFirestore(tracer, firestoreSupportedVersions2, wrap2, unwrap2, config2) {
+  const defaultFirestoreSpanCreationHook = () => {
+  };
+  let firestoreSpanCreationHook = defaultFirestoreSpanCreationHook;
+  const configFirestoreSpanCreationHook = config2.firestoreSpanCreationHook;
+  if (typeof configFirestoreSpanCreationHook === "function") {
+    firestoreSpanCreationHook = (span) => {
+      safeExecuteInTheMiddle(
+        () => configFirestoreSpanCreationHook(span),
+        (error2) => {
+          if (!error2) {
+            return;
+          }
+          srcExports$l.diag.error(error2?.message);
+        },
+        true
+      );
+    };
+  }
+  const moduleFirestoreCJS = new InstrumentationNodeModuleDefinition(
+    "@firebase/firestore",
+    firestoreSupportedVersions2,
+    // eslint-disable-next-line @typescript-eslint/no-explicit-any
+    (moduleExports) => wrapMethods(moduleExports, wrap2, unwrap2, tracer, firestoreSpanCreationHook)
+  );
+  const files = [
+    "@firebase/firestore/dist/lite/index.node.cjs.js",
+    "@firebase/firestore/dist/lite/index.node.mjs.js",
+    "@firebase/firestore/dist/lite/index.rn.esm2017.js",
+    "@firebase/firestore/dist/lite/index.cjs.js"
+  ];
+  for (const file of files) {
+    moduleFirestoreCJS.files.push(
+      new InstrumentationNodeModuleFile(
+        file,
+        firestoreSupportedVersions2,
+        (moduleExports) => wrapMethods(moduleExports, wrap2, unwrap2, tracer, firestoreSpanCreationHook),
+        (moduleExports) => unwrapMethods(moduleExports, unwrap2)
+      )
+    );
+  }
+  return moduleFirestoreCJS;
+}
+function wrapMethods(moduleExports, wrap2, unwrap2, tracer, firestoreSpanCreationHook) {
+  unwrapMethods(moduleExports, unwrap2);
+  wrap2(moduleExports, "addDoc", patchAddDoc(tracer, firestoreSpanCreationHook));
+  wrap2(moduleExports, "getDocs", patchGetDocs(tracer, firestoreSpanCreationHook));
+  wrap2(moduleExports, "setDoc", patchSetDoc(tracer, firestoreSpanCreationHook));
+  wrap2(moduleExports, "deleteDoc", patchDeleteDoc(tracer, firestoreSpanCreationHook));
+  return moduleExports;
+}
+function unwrapMethods(moduleExports, unwrap2) {
+  for (const method of ["addDoc", "getDocs", "setDoc", "deleteDoc"]) {
+    if (isWrapped(moduleExports[method])) {
+      unwrap2(moduleExports, method);
+    }
+  }
+  return moduleExports;
+}
+function patchAddDoc(tracer, firestoreSpanCreationHook) {
+  return function addDoc(original) {
+    return function(reference, data) {
+      const span = startDBSpan(tracer, "addDoc", reference);
+      firestoreSpanCreationHook(span);
+      return executeContextWithSpan(span, () => {
+        return original(reference, data);
+      });
+    };
+  };
+}
+function patchDeleteDoc(tracer, firestoreSpanCreationHook) {
+  return function deleteDoc(original) {
+    return function(reference) {
+      const span = startDBSpan(tracer, "deleteDoc", reference.parent || reference);
+      firestoreSpanCreationHook(span);
+      return executeContextWithSpan(span, () => {
+        return original(reference);
+      });
+    };
+  };
+}
+function patchGetDocs(tracer, firestoreSpanCreationHook) {
+  return function getDocs(original) {
+    return function(reference) {
+      const span = startDBSpan(tracer, "getDocs", reference);
+      firestoreSpanCreationHook(span);
+      return executeContextWithSpan(span, () => {
+        return original(reference);
+      });
+    };
+  };
+}
+function patchSetDoc(tracer, firestoreSpanCreationHook) {
+  return function setDoc(original) {
+    return function(reference, data, options) {
+      const span = startDBSpan(tracer, "setDoc", reference.parent || reference);
+      firestoreSpanCreationHook(span);
+      return executeContextWithSpan(span, () => {
+        return typeof options !== "undefined" ? original(reference, data, options) : original(reference, data);
+      });
+    };
+  };
+}
+function executeContextWithSpan(span, callback) {
+  return srcExports$l.context.with(srcExports$l.trace.setSpan(srcExports$l.context.active(), span), () => {
+    return safeExecuteInTheMiddle(
+      () => {
+        return callback();
+      },
+      (err) => {
+        if (err) {
+          span.recordException(err);
+        }
+        span.end();
+      },
+      true
+    );
+  });
+}
+function startDBSpan(tracer, spanName, reference) {
+  const span = tracer.startSpan(`${spanName} ${reference.path}`, { kind: srcExports$l.SpanKind.CLIENT });
+  addAttributes(span, reference);
+  span.setAttribute(srcExports$k.ATTR_DB_OPERATION_NAME, spanName);
+  return span;
+}
+function getPortAndAddress(settings) {
+  let address;
+  let port;
+  if (typeof settings.host === "string") {
+    if (settings.host.startsWith("[")) {
+      if (settings.host.endsWith("]")) {
+        address = settings.host.replace(/^\[|\]$/g, "");
+      } else if (settings.host.includes("]:")) {
+        const lastColonIndex = settings.host.lastIndexOf(":");
+        if (lastColonIndex !== -1) {
+          address = settings.host.slice(1, lastColonIndex).replace(/^\[|\]$/g, "");
+          port = settings.host.slice(lastColonIndex + 1);
+        }
+      }
+    } else {
+      if (net.isIPv6(settings.host)) {
+        address = settings.host;
+      } else {
+        const lastColonIndex = settings.host.lastIndexOf(":");
+        if (lastColonIndex !== -1) {
+          address = settings.host.slice(0, lastColonIndex);
+          port = settings.host.slice(lastColonIndex + 1);
+        } else {
+          address = settings.host;
+        }
+      }
+    }
+  }
+  return {
+    address,
+    port: port ? parseInt(port, 10) : void 0
+  };
+}
+function addAttributes(span, reference) {
+  const firestoreApp = reference.firestore.app;
+  const firestoreOptions = firestoreApp.options;
+  const json = reference.firestore.toJSON() || {};
+  const settings = json.settings || {};
+  const attributes = {
+    [srcExports$k.ATTR_DB_COLLECTION_NAME]: reference.path,
+    [srcExports$k.ATTR_DB_NAMESPACE]: firestoreApp.name,
+    [srcExports$k.ATTR_DB_SYSTEM_NAME]: "firebase.firestore",
+    "firebase.firestore.type": reference.type,
+    "firebase.firestore.options.projectId": firestoreOptions.projectId,
+    "firebase.firestore.options.appId": firestoreOptions.appId,
+    "firebase.firestore.options.messagingSenderId": firestoreOptions.messagingSenderId,
+    "firebase.firestore.options.storageBucket": firestoreOptions.storageBucket
+  };
+  const { address, port } = getPortAndAddress(settings);
+  if (address) {
+    attributes[srcExports$k.ATTR_SERVER_ADDRESS] = address;
+  }
+  if (port) {
+    attributes[srcExports$k.ATTR_SERVER_PORT] = port;
+  }
+  span.setAttributes(attributes);
+}
+function patchFunctions(tracer, functionsSupportedVersions2, wrap2, unwrap2, config2) {
+  let requestHook2 = () => {
+  };
+  let responseHook = () => {
+  };
+  const errorHook = config2.functions?.errorHook;
+  const configRequestHook = config2.functions?.requestHook;
+  const configResponseHook = config2.functions?.responseHook;
+  if (typeof configResponseHook === "function") {
+    responseHook = (span, err) => {
+      safeExecuteInTheMiddle(
+        () => configResponseHook(span, err),
+        (error2) => {
+          if (!error2) {
+            return;
+          }
+          srcExports$l.diag.error(error2?.message);
+        },
+        true
+      );
+    };
+  }
+  if (typeof configRequestHook === "function") {
+    requestHook2 = (span) => {
+      safeExecuteInTheMiddle(
+        () => configRequestHook(span),
+        (error2) => {
+          if (!error2) {
+            return;
+          }
+          srcExports$l.diag.error(error2?.message);
+        },
+        true
+      );
+    };
+  }
+  const moduleFunctionsCJS = new InstrumentationNodeModuleDefinition("firebase-functions", functionsSupportedVersions2);
+  const modulesToInstrument = [
+    { name: "firebase-functions/lib/v2/providers/https.js", triggerType: "function" },
+    { name: "firebase-functions/lib/v2/providers/firestore.js", triggerType: "firestore" },
+    { name: "firebase-functions/lib/v2/providers/scheduler.js", triggerType: "scheduler" },
+    { name: "firebase-functions/lib/v2/storage.js", triggerType: "storage" }
+  ];
+  modulesToInstrument.forEach(({ name, triggerType }) => {
+    moduleFunctionsCJS.files.push(
+      new InstrumentationNodeModuleFile(
+        name,
+        functionsSupportedVersions2,
+        (moduleExports) => wrapCommonFunctions(
+          moduleExports,
+          wrap2,
+          unwrap2,
+          tracer,
+          { requestHook: requestHook2, responseHook, errorHook },
+          triggerType
+        ),
+        (moduleExports) => unwrapCommonFunctions(moduleExports, unwrap2)
+      )
+    );
+  });
+  return moduleFunctionsCJS;
+}
+function patchV2Functions(tracer, functionsConfig, triggerType) {
+  return function v2FunctionsWrapper(original) {
+    return function(...args) {
+      const handler = typeof args[0] === "function" ? args[0] : args[1];
+      const documentOrOptions = typeof args[0] === "function" ? void 0 : args[0];
+      if (!handler) {
+        return original.call(this, ...args);
+      }
+      const wrappedHandler = async function(...handlerArgs) {
+        const functionName = process.env.FUNCTION_TARGET || process.env.K_SERVICE || "unknown";
+        const span = tracer.startSpan(`firebase.function.${triggerType}`, {
+          kind: srcExports$l.SpanKind.SERVER
+        });
+        const attributes = {
+          "faas.name": functionName,
+          "faas.trigger": triggerType,
+          "faas.provider": "firebase"
+        };
+        if (process.env.GCLOUD_PROJECT) {
+          attributes["cloud.project_id"] = process.env.GCLOUD_PROJECT;
+        }
+        if (process.env.EVENTARC_CLOUD_EVENT_SOURCE) {
+          attributes["cloud.event_source"] = process.env.EVENTARC_CLOUD_EVENT_SOURCE;
+        }
+        span.setAttributes(attributes);
+        functionsConfig?.requestHook?.(span);
+        return srcExports$l.context.with(srcExports$l.trace.setSpan(srcExports$l.context.active(), span), async () => {
+          let error2;
+          let result;
+          try {
+            result = await handler.apply(this, handlerArgs);
+          } catch (e) {
+            error2 = e;
+          }
+          functionsConfig?.responseHook?.(span, error2);
+          if (error2) {
+            span.recordException(error2);
+          }
+          span.end();
+          if (error2) {
+            await functionsConfig?.errorHook?.(span, error2);
+            throw error2;
+          }
+          return result;
+        });
+      };
+      if (documentOrOptions) {
+        return original.call(this, documentOrOptions, wrappedHandler);
+      } else {
+        return original.call(this, wrappedHandler);
+      }
+    };
+  };
+}
+function wrapCommonFunctions(moduleExports, wrap2, unwrap2, tracer, functionsConfig, triggerType) {
+  unwrapCommonFunctions(moduleExports, unwrap2);
+  switch (triggerType) {
+    case "function":
+      wrap2(moduleExports, "onRequest", patchV2Functions(tracer, functionsConfig, "http.request"));
+      wrap2(moduleExports, "onCall", patchV2Functions(tracer, functionsConfig, "http.call"));
+      break;
+    case "firestore":
+      wrap2(moduleExports, "onDocumentCreated", patchV2Functions(tracer, functionsConfig, "firestore.document.created"));
+      wrap2(moduleExports, "onDocumentUpdated", patchV2Functions(tracer, functionsConfig, "firestore.document.updated"));
+      wrap2(moduleExports, "onDocumentDeleted", patchV2Functions(tracer, functionsConfig, "firestore.document.deleted"));
+      wrap2(moduleExports, "onDocumentWritten", patchV2Functions(tracer, functionsConfig, "firestore.document.written"));
+      wrap2(
+        moduleExports,
+        "onDocumentCreatedWithAuthContext",
+        patchV2Functions(tracer, functionsConfig, "firestore.document.created")
+      );
+      wrap2(
+        moduleExports,
+        "onDocumentUpdatedWithAuthContext",
+        patchV2Functions(tracer, functionsConfig, "firestore.document.updated")
+      );
+      wrap2(
+        moduleExports,
+        "onDocumentDeletedWithAuthContext",
+        patchV2Functions(tracer, functionsConfig, "firestore.document.deleted")
+      );
+      wrap2(
+        moduleExports,
+        "onDocumentWrittenWithAuthContext",
+        patchV2Functions(tracer, functionsConfig, "firestore.document.written")
+      );
+      break;
+    case "scheduler":
+      wrap2(moduleExports, "onSchedule", patchV2Functions(tracer, functionsConfig, "scheduler.scheduled"));
+      break;
+    case "storage":
+      wrap2(moduleExports, "onObjectFinalized", patchV2Functions(tracer, functionsConfig, "storage.object.finalized"));
+      wrap2(moduleExports, "onObjectArchived", patchV2Functions(tracer, functionsConfig, "storage.object.archived"));
+      wrap2(moduleExports, "onObjectDeleted", patchV2Functions(tracer, functionsConfig, "storage.object.deleted"));
+      wrap2(
+        moduleExports,
+        "onObjectMetadataUpdated",
+        patchV2Functions(tracer, functionsConfig, "storage.object.metadataUpdated")
+      );
+      break;
+  }
+  return moduleExports;
+}
+function unwrapCommonFunctions(moduleExports, unwrap2) {
+  const methods = [
+    "onSchedule",
+    "onRequest",
+    "onCall",
+    "onObjectFinalized",
+    "onObjectArchived",
+    "onObjectDeleted",
+    "onObjectMetadataUpdated",
+    "onDocumentCreated",
+    "onDocumentUpdated",
+    "onDocumentDeleted",
+    "onDocumentWritten",
+    "onDocumentCreatedWithAuthContext",
+    "onDocumentUpdatedWithAuthContext",
+    "onDocumentDeletedWithAuthContext",
+    "onDocumentWrittenWithAuthContext"
+  ];
+  for (const method of methods) {
+    if (isWrapped(moduleExports[method])) {
+      unwrap2(moduleExports, method);
+    }
+  }
+  return moduleExports;
+}
+const DefaultFirebaseInstrumentationConfig = {};
+const firestoreSupportedVersions = [">=3.0.0 <5"];
+const functionsSupportedVersions = [">=6.0.0 <7"];
+class FirebaseInstrumentation extends InstrumentationBase {
+  constructor(config2 = DefaultFirebaseInstrumentationConfig) {
+    super("@sentry/instrumentation-firebase", SDK_VERSION, config2);
+  }
+  /**
+   * sets config
+   * @param config
+   */
+  setConfig(config2 = {}) {
+    super.setConfig({ ...DefaultFirebaseInstrumentationConfig, ...config2 });
+  }
+  /**
+   *
+   * @protected
+   */
+  // eslint-disable-next-line @typescript-eslint/naming-convention
+  init() {
+    const modules = [];
+    modules.push(patchFirestore(this.tracer, firestoreSupportedVersions, this._wrap, this._unwrap, this.getConfig()));
+    modules.push(patchFunctions(this.tracer, functionsSupportedVersions, this._wrap, this._unwrap, this.getConfig()));
+    return modules;
+  }
+}
+const INTEGRATION_NAME = "Firebase";
+const config = {
+  firestoreSpanCreationHook: (span) => {
+    addOriginToSpan(span, "auto.firebase.otel.firestore");
+    span.setAttribute(SEMANTIC_ATTRIBUTE_SENTRY_OP, "db.query");
+  },
+  functions: {
+    requestHook: (span) => {
+      addOriginToSpan(span, "auto.firebase.otel.functions");
+      span.setAttribute(SEMANTIC_ATTRIBUTE_SENTRY_OP, "http.request");
+    },
+    errorHook: async (_, error2) => {
+      if (error2) {
+        captureException(error2, {
+          mechanism: {
+            type: "auto.firebase.otel.functions",
+            handled: false
+          }
+        });
+        await flush(2e3);
+      }
+    }
+  }
+};
+const instrumentFirebase = generateInstrumentOnce(INTEGRATION_NAME, () => new FirebaseInstrumentation(config));
+const _firebaseIntegration = (() => {
+  return {
+    name: INTEGRATION_NAME,
+    setupOnce() {
+      instrumentFirebase();
+    }
+  };
+});
+const firebaseIntegration = defineIntegration(_firebaseIntegration);
+function getAutoPerformanceIntegrations() {
+  return [
+    expressIntegration(),
+    fastifyIntegration(),
+    graphqlIntegration(),
+    honoIntegration(),
+    mongoIntegration(),
+    mongooseIntegration(),
+    mysqlIntegration(),
+    mysql2Integration(),
+    redisIntegration(),
+    postgresIntegration(),
+    prismaIntegration(),
+    hapiIntegration(),
+    koaIntegration(),
+    connectIntegration(),
+    tediousIntegration(),
+    genericPoolIntegration(),
+    kafkaIntegration(),
+    amqplibIntegration(),
+    lruMemoizerIntegration(),
+    // AI providers
+    // LangChain must come first to disable AI provider integrations before they instrument
+    langChainIntegration(),
+    langGraphIntegration(),
+    vercelAIIntegration(),
+    openAIIntegration(),
+    anthropicAIIntegration(),
+    googleGenAIIntegration(),
+    postgresJsIntegration(),
+    firebaseIntegration()
+  ];
+}
+const MAX_MAX_SPAN_WAIT_DURATION = 1e6;
+function initOpenTelemetry(client, options = {}) {
+  if (client.getOptions().debug) {
+    setupOpenTelemetryLogger();
+  }
+  const [provider, asyncLocalStorageLookup] = setupOtel(client, options);
+  client.traceProvider = provider;
+  client.asyncLocalStorageLookup = asyncLocalStorageLookup;
+}
+function setupOtel(client, options = {}) {
+  const provider = new BasicTracerProvider({
+    sampler: new SentrySampler(client),
+    resource: defaultResource().merge(
+      resourceFromAttributes({
+        [srcExports$k.ATTR_SERVICE_NAME]: "node",
+        // eslint-disable-next-line deprecation/deprecation
+        [srcExports$k.SEMRESATTRS_SERVICE_NAMESPACE]: "sentry",
+        [srcExports$k.ATTR_SERVICE_VERSION]: SDK_VERSION
+      })
+    ),
+    forceFlushTimeoutMillis: 500,
+    spanProcessors: [
+      new SentrySpanProcessor({
+        timeout: _clampSpanProcessorTimeout(client.getOptions().maxSpanWaitDuration)
+      }),
+      ...options.spanProcessors || []
+    ]
+  });
+  srcExports$l.trace.setGlobalTracerProvider(provider);
+  srcExports$l.propagation.setGlobalPropagator(new SentryPropagator());
+  const ctxManager = new SentryContextManager();
+  srcExports$l.context.setGlobalContextManager(ctxManager);
+  return [provider, ctxManager.getAsyncLocalStorageLookup()];
+}
+function _clampSpanProcessorTimeout(maxSpanWaitDuration) {
+  if (maxSpanWaitDuration == null) {
+    return void 0;
+  }
+  if (maxSpanWaitDuration > MAX_MAX_SPAN_WAIT_DURATION) {
+    DEBUG_BUILD && debug$2.warn(`\`maxSpanWaitDuration\` is too high, using the maximum value of ${MAX_MAX_SPAN_WAIT_DURATION}`);
+    return MAX_MAX_SPAN_WAIT_DURATION;
+  } else if (maxSpanWaitDuration <= 0 || Number.isNaN(maxSpanWaitDuration)) {
+    DEBUG_BUILD && debug$2.warn("`maxSpanWaitDuration` must be a positive number, using default value instead.");
+    return void 0;
+  }
+  return maxSpanWaitDuration;
+}
+function getDefaultIntegrationsWithoutPerformance() {
+  const nodeCoreIntegrations = getDefaultIntegrations$1();
+  return nodeCoreIntegrations.filter((integration) => integration.name !== "Http" && integration.name !== "NodeFetch").concat(httpIntegration(), nativeNodeFetchIntegration());
+}
+function getDefaultIntegrations(options) {
+  return [
+    ...getDefaultIntegrationsWithoutPerformance(),
+    // We only add performance integrations if tracing is enabled
+    // Note that this means that without tracing enabled, e.g. `expressIntegration()` will not be added
+    // This means that generally request isolation will work (because that is done by httpIntegration)
+    // But `transactionName` will not be set automatically
+    ...hasSpansEnabled(options) ? getAutoPerformanceIntegrations() : []
+  ];
+}
+function init$1(options = {}) {
+  return _init(options, getDefaultIntegrations);
+}
+function _init(options = {}, getDefaultIntegrationsImpl) {
+  applySdkMetadata(options, "node");
+  const client = init$2({
+    ...options,
+    // Only use Node SDK defaults if none provided
+    defaultIntegrations: options.defaultIntegrations ?? getDefaultIntegrationsImpl(options)
+  });
+  if (client && !options.skipOpenTelemetrySetup) {
+    initOpenTelemetry(client, {
+      spanProcessors: options.openTelemetrySpanProcessors
+    });
+    validateOpenTelemetrySetup();
+  }
+  return client;
+}
+function init(options) {
+  const sentryOptions = {
+    defaultIntegrations: [...getDefaultIntegrations(options)],
+    ...options
+  };
+  applySdkMetadata(sentryOptions, "tanstackstart-react", ["tanstackstart-react", "node"]);
+  return init$1(sentryOptions);
+}
+const preloadWarning = "Error preloading route! ☝️";
+class BaseRoute {
+  constructor(options) {
+    this.init = (opts) => {
+      this.originalIndex = opts.originalIndex;
+      const options2 = this.options;
+      const isRoot = !options2?.path && !options2?.id;
+      this.parentRoute = this.options.getParentRoute?.();
+      if (isRoot) {
+        this._path = rootRouteId;
+      } else if (!this.parentRoute) {
+        invariant(
+          false,
+          `Child Route instances must pass a 'getParentRoute: () => ParentRoute' option that returns a Route instance.`
+        );
+      }
+      let path2 = isRoot ? rootRouteId : options2?.path;
+      if (path2 && path2 !== "/") {
+        path2 = trimPathLeft(path2);
+      }
+      const customId = options2?.id || path2;
+      let id = isRoot ? rootRouteId : joinPaths([
+        this.parentRoute.id === rootRouteId ? "" : this.parentRoute.id,
+        customId
+      ]);
+      if (path2 === rootRouteId) {
+        path2 = "/";
+      }
+      if (id !== rootRouteId) {
+        id = joinPaths(["/", id]);
+      }
+      const fullPath = id === rootRouteId ? "/" : joinPaths([this.parentRoute.fullPath, path2]);
+      this._path = path2;
+      this._id = id;
+      this._fullPath = fullPath;
+      this._to = fullPath;
+    };
+    this.addChildren = (children) => {
+      return this._addFileChildren(children);
+    };
+    this._addFileChildren = (children) => {
+      if (Array.isArray(children)) {
+        this.children = children;
+      }
+      if (typeof children === "object" && children !== null) {
+        this.children = Object.values(children);
+      }
+      return this;
+    };
+    this._addFileTypes = () => {
+      return this;
+    };
+    this.updateLoader = (options2) => {
+      Object.assign(this.options, options2);
+      return this;
+    };
+    this.update = (options2) => {
+      Object.assign(this.options, options2);
+      return this;
+    };
+    this.lazy = (lazyFn) => {
+      this.lazyFn = lazyFn;
+      return this;
+    };
+    this.options = options || {};
+    this.isRoot = !options?.getParentRoute;
+    if (options?.id && options?.path) {
+      throw new Error(`Route cannot have both an 'id' and a 'path' option.`);
+    }
+  }
+  get to() {
+    return this._to;
+  }
+  get id() {
+    return this._id;
+  }
+  get path() {
+    return this._path;
+  }
+  get fullPath() {
+    return this._fullPath;
+  }
+}
+class BaseRootRoute extends BaseRoute {
+  constructor(options) {
+    super(options);
+  }
+}
+function useMatch(opts) {
+  const nearestMatchId = reactExports.useContext(
+    opts.from ? dummyMatchContext : matchContext
+  );
+  const matchSelection = useRouterState({
+    select: (state) => {
+      const match2 = state.matches.find(
+        (d) => opts.from ? opts.from === d.routeId : d.id === nearestMatchId
+      );
+      invariant(
+        !((opts.shouldThrow ?? true) && !match2),
+        `Could not find ${opts.from ? `an active match from "${opts.from}"` : "a nearest match!"}`
+      );
+      if (match2 === void 0) {
+        return void 0;
+      }
+      return opts.select ? opts.select(match2) : match2;
+    },
+    structuralSharing: opts.structuralSharing
+  });
+  return matchSelection;
+}
+function useLoaderData(opts) {
+  return useMatch({
+    from: opts.from,
+    strict: opts.strict,
+    structuralSharing: opts.structuralSharing,
+    select: (s) => {
+      return opts.select ? opts.select(s.loaderData) : s.loaderData;
+    }
+  });
+}
+function useLoaderDeps(opts) {
+  const { select, ...rest } = opts;
+  return useMatch({
+    ...rest,
+    select: (s) => {
+      return select ? select(s.loaderDeps) : s.loaderDeps;
+    }
+  });
+}
+function useParams(opts) {
+  return useMatch({
+    from: opts.from,
+    shouldThrow: opts.shouldThrow,
+    structuralSharing: opts.structuralSharing,
+    strict: opts.strict,
+    select: (match2) => {
+      const params = opts.strict === false ? match2.params : match2._strictParams;
+      return opts.select ? opts.select(params) : params;
+    }
+  });
+}
+function useSearch(opts) {
+  return useMatch({
+    from: opts.from,
+    strict: opts.strict,
+    shouldThrow: opts.shouldThrow,
+    structuralSharing: opts.structuralSharing,
+    select: (match2) => {
+      return opts.select ? opts.select(match2.search) : match2.search;
+    }
+  });
+}
+function useNavigate(_defaultOpts) {
+  const router = useRouter();
+  return reactExports.useCallback(
+    (options) => {
+      return router.navigate({
+        ...options,
+        from: options.from ?? _defaultOpts?.from
+      });
+    },
+    [_defaultOpts?.from, router]
+  );
+}
+var reactDomExports = requireReactDom();
+function useLinkProps(options, forwardedRef) {
+  const router = useRouter();
+  const [isTransitioning, setIsTransitioning] = reactExports.useState(false);
+  const hasRenderFetched = reactExports.useRef(false);
+  const innerRef = useForwardedRef(forwardedRef);
+  const {
+    // custom props
+    activeProps,
+    inactiveProps,
+    activeOptions,
+    to,
+    preload: userPreload,
+    preloadDelay: userPreloadDelay,
+    hashScrollIntoView,
+    replace,
+    startTransition,
+    resetScroll,
+    viewTransition,
+    // element props
+    children,
+    target,
+    disabled,
+    style,
+    className,
+    onClick,
+    onFocus,
+    onMouseEnter,
+    onMouseLeave,
+    onTouchStart,
+    ignoreBlocker,
+    // prevent these from being returned
+    params: _params,
+    search: _search,
+    hash: _hash,
+    state: _state,
+    mask: _mask,
+    reloadDocument: _reloadDocument,
+    unsafeRelative: _unsafeRelative,
+    from: _from,
+    _fromLocation,
+    ...propsSafeToSpread
+  } = options;
+  const currentSearch = useRouterState({
+    select: (s) => s.location.search,
+    structuralSharing: true
+  });
+  const from = options.from;
+  const _options = reactExports.useMemo(
+    () => {
+      return { ...options, from };
+    },
+    // eslint-disable-next-line react-hooks/exhaustive-deps
+    [
+      router,
+      currentSearch,
+      from,
+      options._fromLocation,
+      options.hash,
+      options.to,
+      options.search,
+      options.params,
+      options.state,
+      options.mask,
+      options.unsafeRelative
+    ]
+  );
+  const next = reactExports.useMemo(
+    () => router.buildLocation({ ..._options }),
+    [router, _options]
+  );
+  const hrefOption = reactExports.useMemo(() => {
+    if (disabled) {
+      return void 0;
+    }
+    let href = next.maskedLocation ? next.maskedLocation.url.href : next.url.href;
+    let external = false;
+    if (router.origin) {
+      if (href.startsWith(router.origin)) {
+        href = router.history.createHref(href.replace(router.origin, "")) || "/";
+      } else {
+        external = true;
+      }
+    }
+    return { href, external };
+  }, [disabled, next.maskedLocation, next.url, router.origin, router.history]);
+  const externalLink = reactExports.useMemo(() => {
+    if (hrefOption?.external) {
+      return hrefOption.href;
+    }
+    try {
+      new URL(to);
+      return to;
+    } catch {
+    }
+    return void 0;
+  }, [to, hrefOption]);
+  const preload = options.reloadDocument || externalLink ? false : userPreload ?? router.options.defaultPreload;
+  const preloadDelay = userPreloadDelay ?? router.options.defaultPreloadDelay ?? 0;
+  const isActive = useRouterState({
+    select: (s) => {
+      if (externalLink) return false;
+      if (activeOptions?.exact) {
+        const testExact = exactPathTest(
+          s.location.pathname,
+          next.pathname,
+          router.basepath
+        );
+        if (!testExact) {
+          return false;
+        }
+      } else {
+        const currentPathSplit = removeTrailingSlash(
+          s.location.pathname,
+          router.basepath
+        );
+        const nextPathSplit = removeTrailingSlash(
+          next.pathname,
+          router.basepath
+        );
+        const pathIsFuzzyEqual = currentPathSplit.startsWith(nextPathSplit) && (currentPathSplit.length === nextPathSplit.length || currentPathSplit[nextPathSplit.length] === "/");
+        if (!pathIsFuzzyEqual) {
+          return false;
+        }
+      }
+      if (activeOptions?.includeSearch ?? true) {
+        const searchTest = deepEqual(s.location.search, next.search, {
+          partial: !activeOptions?.exact,
+          ignoreUndefined: !activeOptions?.explicitUndefined
+        });
+        if (!searchTest) {
+          return false;
+        }
+      }
+      if (activeOptions?.includeHash) {
+        return s.location.hash === next.hash;
+      }
+      return true;
+    }
+  });
+  const doPreload = reactExports.useCallback(() => {
+    router.preloadRoute({ ..._options }).catch((err) => {
+      console.warn(err);
+      console.warn(preloadWarning);
+    });
+  }, [router, _options]);
+  const preloadViewportIoCallback = reactExports.useCallback(
+    (entry) => {
+      if (entry?.isIntersecting) {
+        doPreload();
+      }
+    },
+    [doPreload]
+  );
+  useIntersectionObserver(
+    innerRef,
+    preloadViewportIoCallback,
+    intersectionObserverOptions,
+    { disabled: !!disabled || !(preload === "viewport") }
+  );
+  reactExports.useEffect(() => {
+    if (hasRenderFetched.current) {
+      return;
+    }
+    if (!disabled && preload === "render") {
+      doPreload();
+      hasRenderFetched.current = true;
+    }
+  }, [disabled, doPreload, preload]);
+  const handleClick = (e) => {
+    const elementTarget = e.currentTarget.getAttribute("target");
+    const effectiveTarget = target !== void 0 ? target : elementTarget;
+    if (!disabled && !isCtrlEvent(e) && !e.defaultPrevented && (!effectiveTarget || effectiveTarget === "_self") && e.button === 0) {
+      e.preventDefault();
+      reactDomExports.flushSync(() => {
+        setIsTransitioning(true);
+      });
+      const unsub = router.subscribe("onResolved", () => {
+        unsub();
+        setIsTransitioning(false);
+      });
+      router.navigate({
+        ..._options,
+        replace,
+        resetScroll,
+        hashScrollIntoView,
+        startTransition,
+        viewTransition,
+        ignoreBlocker
+      });
+    }
+  };
+  if (externalLink) {
+    return {
+      ...propsSafeToSpread,
+      ref: innerRef,
+      href: externalLink,
+      ...children && { children },
+      ...target && { target },
+      ...disabled && { disabled },
+      ...style && { style },
+      ...className && { className },
+      ...onClick && { onClick },
+      ...onFocus && { onFocus },
+      ...onMouseEnter && { onMouseEnter },
+      ...onMouseLeave && { onMouseLeave },
+      ...onTouchStart && { onTouchStart }
+    };
+  }
+  const handleFocus = (_) => {
+    if (disabled) return;
+    if (preload) {
+      doPreload();
+    }
+  };
+  const handleTouchStart = handleFocus;
+  const handleEnter = (e) => {
+    if (disabled || !preload) return;
+    if (!preloadDelay) {
+      doPreload();
+    } else {
+      const eventTarget = e.target;
+      if (timeoutMap.has(eventTarget)) {
+        return;
+      }
+      const id = setTimeout(() => {
+        timeoutMap.delete(eventTarget);
+        doPreload();
+      }, preloadDelay);
+      timeoutMap.set(eventTarget, id);
+    }
+  };
+  const handleLeave = (e) => {
+    if (disabled || !preload || !preloadDelay) return;
+    const eventTarget = e.target;
+    const id = timeoutMap.get(eventTarget);
+    if (id) {
+      clearTimeout(id);
+      timeoutMap.delete(eventTarget);
+    }
+  };
+  const resolvedActiveProps = isActive ? functionalUpdate(activeProps, {}) ?? STATIC_ACTIVE_OBJECT : STATIC_EMPTY_OBJECT;
+  const resolvedInactiveProps = isActive ? STATIC_EMPTY_OBJECT : functionalUpdate(inactiveProps, {}) ?? STATIC_EMPTY_OBJECT;
+  const resolvedClassName = [
+    className,
+    resolvedActiveProps.className,
+    resolvedInactiveProps.className
+  ].filter(Boolean).join(" ");
+  const resolvedStyle = (style || resolvedActiveProps.style || resolvedInactiveProps.style) && {
+    ...style,
+    ...resolvedActiveProps.style,
+    ...resolvedInactiveProps.style
+  };
+  return {
+    ...propsSafeToSpread,
+    ...resolvedActiveProps,
+    ...resolvedInactiveProps,
+    href: hrefOption?.href,
+    ref: innerRef,
+    onClick: composeHandlers([onClick, handleClick]),
+    onFocus: composeHandlers([onFocus, handleFocus]),
+    onMouseEnter: composeHandlers([onMouseEnter, handleEnter]),
+    onMouseLeave: composeHandlers([onMouseLeave, handleLeave]),
+    onTouchStart: composeHandlers([onTouchStart, handleTouchStart]),
+    disabled: !!disabled,
+    target,
+    ...resolvedStyle && { style: resolvedStyle },
+    ...resolvedClassName && { className: resolvedClassName },
+    ...disabled && STATIC_DISABLED_PROPS,
+    ...isActive && STATIC_ACTIVE_PROPS,
+    ...isTransitioning && STATIC_TRANSITIONING_PROPS
+  };
+}
+const STATIC_EMPTY_OBJECT = {};
+const STATIC_ACTIVE_OBJECT = { className: "active" };
+const STATIC_DISABLED_PROPS = { role: "link", "aria-disabled": true };
+const STATIC_ACTIVE_PROPS = { "data-status": "active", "aria-current": "page" };
+const STATIC_TRANSITIONING_PROPS = { "data-transitioning": "transitioning" };
+const timeoutMap = /* @__PURE__ */ new WeakMap();
+const intersectionObserverOptions = {
+  rootMargin: "100px"
+};
+const composeHandlers = (handlers2) => (e) => {
+  for (const handler of handlers2) {
+    if (!handler) continue;
+    if (e.defaultPrevented) return;
+    handler(e);
+  }
+};
+const Link = reactExports.forwardRef(
+  (props, ref) => {
+    const { _asChild, ...rest } = props;
+    const {
+      type: _type,
+      ref: innerRef,
+      ...linkProps
+    } = useLinkProps(rest, ref);
+    const children = typeof rest.children === "function" ? rest.children({
+      isActive: linkProps["data-status"] === "active"
+    }) : rest.children;
+    if (_asChild === void 0) {
+      delete linkProps.disabled;
+    }
+    return reactExports.createElement(
+      _asChild ? _asChild : "a",
+      {
+        ...linkProps,
+        ref: innerRef
+      },
+      children
+    );
+  }
+);
+function isCtrlEvent(e) {
+  return !!(e.metaKey || e.altKey || e.ctrlKey || e.shiftKey);
+}
+let Route$6 = class Route extends BaseRoute {
+  /**
+   * @deprecated Use the `createRoute` function instead.
+   */
+  constructor(options) {
+    super(options);
+    this.useMatch = (opts) => {
+      return useMatch({
+        select: opts?.select,
+        from: this.id,
+        structuralSharing: opts?.structuralSharing
+      });
+    };
+    this.useRouteContext = (opts) => {
+      return useMatch({
+        ...opts,
+        from: this.id,
+        select: (d) => opts?.select ? opts.select(d.context) : d.context
+      });
+    };
+    this.useSearch = (opts) => {
+      return useSearch({
+        select: opts?.select,
+        structuralSharing: opts?.structuralSharing,
+        from: this.id
+      });
+    };
+    this.useParams = (opts) => {
+      return useParams({
+        select: opts?.select,
+        structuralSharing: opts?.structuralSharing,
+        from: this.id
+      });
+    };
+    this.useLoaderDeps = (opts) => {
+      return useLoaderDeps({ ...opts, from: this.id });
+    };
+    this.useLoaderData = (opts) => {
+      return useLoaderData({ ...opts, from: this.id });
+    };
+    this.useNavigate = () => {
+      return useNavigate({ from: this.fullPath });
+    };
+    this.Link = React__default.forwardRef(
+      (props, ref) => {
+        return /* @__PURE__ */ jsxRuntimeExports.jsx(Link, { ref, from: this.fullPath, ...props });
+      }
+    );
+    this.$$typeof = Symbol.for("react.memo");
+  }
+};
+function createRoute(options) {
+  return new Route$6(
+    // TODO: Help us TypeChris, you're our only hope!
+    options
+  );
+}
+class RootRoute extends BaseRootRoute {
+  /**
+   * @deprecated `RootRoute` is now an internal implementation detail. Use `createRootRoute()` instead.
+   */
+  constructor(options) {
+    super(options);
+    this.useMatch = (opts) => {
+      return useMatch({
+        select: opts?.select,
+        from: this.id,
+        structuralSharing: opts?.structuralSharing
+      });
+    };
+    this.useRouteContext = (opts) => {
+      return useMatch({
+        ...opts,
+        from: this.id,
+        select: (d) => opts?.select ? opts.select(d.context) : d.context
+      });
+    };
+    this.useSearch = (opts) => {
+      return useSearch({
+        select: opts?.select,
+        structuralSharing: opts?.structuralSharing,
+        from: this.id
+      });
+    };
+    this.useParams = (opts) => {
+      return useParams({
+        select: opts?.select,
+        structuralSharing: opts?.structuralSharing,
+        from: this.id
+      });
+    };
+    this.useLoaderDeps = (opts) => {
+      return useLoaderDeps({ ...opts, from: this.id });
+    };
+    this.useLoaderData = (opts) => {
+      return useLoaderData({ ...opts, from: this.id });
+    };
+    this.useNavigate = () => {
+      return useNavigate({ from: this.fullPath });
+    };
+    this.Link = React__default.forwardRef(
+      (props, ref) => {
+        return /* @__PURE__ */ jsxRuntimeExports.jsx(Link, { ref, from: this.fullPath, ...props });
+      }
+    );
+    this.$$typeof = Symbol.for("react.memo");
+  }
+}
+function createRootRoute(options) {
+  return new RootRoute(options);
+}
+function createFileRoute(path2) {
+  if (typeof path2 === "object") {
+    return new FileRoute(path2, {
+      silent: true
+    }).createRoute(path2);
+  }
+  return new FileRoute(path2, {
+    silent: true
+  }).createRoute;
+}
+class FileRoute {
+  constructor(path2, _opts) {
+    this.path = path2;
+    this.createRoute = (options) => {
+      warning(
+        this.silent,
+        "FileRoute is deprecated and will be removed in the next major version. Use the createFileRoute(path)(options) function instead."
+      );
+      const route = createRoute(options);
+      route.isRoot = false;
+      return route;
+    };
+    this.silent = _opts?.silent;
+  }
+}
+class LazyRoute {
+  constructor(opts) {
+    this.useMatch = (opts2) => {
+      return useMatch({
+        select: opts2?.select,
+        from: this.options.id,
+        structuralSharing: opts2?.structuralSharing
+      });
+    };
+    this.useRouteContext = (opts2) => {
+      return useMatch({
+        from: this.options.id,
+        select: (d) => opts2?.select ? opts2.select(d.context) : d.context
+      });
+    };
+    this.useSearch = (opts2) => {
+      return useSearch({
+        select: opts2?.select,
+        structuralSharing: opts2?.structuralSharing,
+        from: this.options.id
+      });
+    };
+    this.useParams = (opts2) => {
+      return useParams({
+        select: opts2?.select,
+        structuralSharing: opts2?.structuralSharing,
+        from: this.options.id
+      });
+    };
+    this.useLoaderDeps = (opts2) => {
+      return useLoaderDeps({ ...opts2, from: this.options.id });
+    };
+    this.useLoaderData = (opts2) => {
+      return useLoaderData({ ...opts2, from: this.options.id });
+    };
+    this.useNavigate = () => {
+      const router = useRouter();
+      return useNavigate({ from: router.routesById[this.options.id].fullPath });
+    };
+    this.options = opts;
+    this.$$typeof = Symbol.for("react.memo");
+  }
+}
+function createLazyFileRoute(id) {
+  if (typeof id === "object") {
+    return new LazyRoute(id);
+  }
+  return (opts) => new LazyRoute({ id, ...opts });
+}
+function lazyRouteComponent(importer, exportName) {
+  let loadPromise;
+  let comp;
+  let error2;
+  let reload;
+  const load2 = () => {
+    if (!loadPromise) {
+      loadPromise = importer().then((res) => {
+        loadPromise = void 0;
+        comp = res[exportName];
+      }).catch((err) => {
+        error2 = err;
+        if (isModuleNotFoundError(error2)) {
+          if (error2 instanceof Error && typeof window !== "undefined" && typeof sessionStorage !== "undefined") {
+            const storageKey = `tanstack_router_reload:${error2.message}`;
+            if (!sessionStorage.getItem(storageKey)) {
+              sessionStorage.setItem(storageKey, "1");
+              reload = true;
+            }
+          }
+        }
+      });
+    }
+    return loadPromise;
+  };
+  const lazyComp = function Lazy(props) {
+    if (reload) {
+      window.location.reload();
+      throw new Promise(() => {
+      });
+    }
+    if (error2) {
+      throw error2;
+    }
+    if (!comp) {
+      if (reactExports.use) {
+        reactExports.use(load2());
+      } else {
+        throw load2();
+      }
+    }
+    return reactExports.createElement(comp, props);
+  };
+  lazyComp.preload = load2;
+  return lazyComp;
+}
+const createRouter = (options) => {
+  return new Router(options);
+};
+class Router extends RouterCore {
+  constructor(options) {
+    super(options);
+  }
+}
+if (typeof globalThis !== "undefined") {
+  globalThis.createFileRoute = createFileRoute;
+  globalThis.createLazyFileRoute = createLazyFileRoute;
+} else if (typeof window !== "undefined") {
+  window.createFileRoute = createFileRoute;
+  window.createLazyFileRoute = createLazyFileRoute;
+}
+function Asset({
+  tag,
+  attrs,
+  children,
+  nonce
+}) {
+  switch (tag) {
+    case "title":
+      return /* @__PURE__ */ jsxRuntimeExports.jsx("title", { ...attrs, suppressHydrationWarning: true, children });
+    case "meta":
+      return /* @__PURE__ */ jsxRuntimeExports.jsx("meta", { ...attrs, suppressHydrationWarning: true });
+    case "link":
+      return /* @__PURE__ */ jsxRuntimeExports.jsx("link", { ...attrs, nonce, suppressHydrationWarning: true });
+    case "style":
+      return /* @__PURE__ */ jsxRuntimeExports.jsx(
+        "style",
+        {
+          ...attrs,
+          dangerouslySetInnerHTML: { __html: children },
+          nonce
+        }
+      );
+    case "script":
+      return /* @__PURE__ */ jsxRuntimeExports.jsx(Script, { attrs, children });
+    default:
+      return null;
+  }
+}
+function Script({
+  attrs,
+  children
+}) {
+  const router = useRouter();
+  reactExports.useEffect(() => {
+    if (attrs?.src) {
+      const normSrc = (() => {
+        try {
+          const base = document.baseURI || window.location.href;
+          return new URL(attrs.src, base).href;
+        } catch {
+          return attrs.src;
+        }
+      })();
+      const existingScript = Array.from(
+        document.querySelectorAll("script[src]")
+      ).find((el) => el.src === normSrc);
+      if (existingScript) {
+        return;
+      }
+      const script = document.createElement("script");
+      for (const [key, value] of Object.entries(attrs)) {
+        if (key !== "suppressHydrationWarning" && value !== void 0 && value !== false) {
+          script.setAttribute(
+            key,
+            typeof value === "boolean" ? "" : String(value)
+          );
+        }
+      }
+      document.head.appendChild(script);
+      return () => {
+        if (script.parentNode) {
+          script.parentNode.removeChild(script);
+        }
+      };
+    }
+    if (typeof children === "string") {
+      const typeAttr = typeof attrs?.type === "string" ? attrs.type : "text/javascript";
+      const nonceAttr = typeof attrs?.nonce === "string" ? attrs.nonce : void 0;
+      const existingScript = Array.from(
+        document.querySelectorAll("script:not([src])")
+      ).find((el) => {
+        if (!(el instanceof HTMLScriptElement)) return false;
+        const sType = el.getAttribute("type") ?? "text/javascript";
+        const sNonce = el.getAttribute("nonce") ?? void 0;
+        return el.textContent === children && sType === typeAttr && sNonce === nonceAttr;
+      });
+      if (existingScript) {
+        return;
+      }
+      const script = document.createElement("script");
+      script.textContent = children;
+      if (attrs) {
+        for (const [key, value] of Object.entries(attrs)) {
+          if (key !== "suppressHydrationWarning" && value !== void 0 && value !== false) {
+            script.setAttribute(
+              key,
+              typeof value === "boolean" ? "" : String(value)
+            );
+          }
+        }
+      }
+      document.head.appendChild(script);
+      return () => {
+        if (script.parentNode) {
+          script.parentNode.removeChild(script);
+        }
+      };
+    }
+    return void 0;
+  }, [attrs, children]);
+  if (!router.isServer) {
+    const { src: src2, ...rest } = attrs || {};
+    return /* @__PURE__ */ jsxRuntimeExports.jsx(
+      "script",
+      {
+        suppressHydrationWarning: true,
+        dangerouslySetInnerHTML: { __html: "" },
+        ...rest
+      }
+    );
+  }
+  if (attrs?.src && typeof attrs.src === "string") {
+    return /* @__PURE__ */ jsxRuntimeExports.jsx("script", { ...attrs, suppressHydrationWarning: true });
+  }
+  if (typeof children === "string") {
+    return /* @__PURE__ */ jsxRuntimeExports.jsx(
+      "script",
+      {
+        ...attrs,
+        dangerouslySetInnerHTML: { __html: children },
+        suppressHydrationWarning: true
+      }
+    );
+  }
+  return null;
+}
+const useTags = () => {
+  const router = useRouter();
+  const nonce = router.options.ssr?.nonce;
+  const routeMeta = useRouterState({
+    select: (state) => {
+      return state.matches.map((match2) => match2.meta).filter(Boolean);
+    }
+  });
+  const meta = reactExports.useMemo(() => {
+    const resultMeta = [];
+    const metaByAttribute = {};
+    let title;
+    for (let i = routeMeta.length - 1; i >= 0; i--) {
+      const metas = routeMeta[i];
+      for (let j = metas.length - 1; j >= 0; j--) {
+        const m = metas[j];
+        if (!m) continue;
+        if (m.title) {
+          if (!title) {
+            title = {
+              tag: "title",
+              children: m.title
+            };
+          }
+        } else {
+          const attribute = m.name ?? m.property;
+          if (attribute) {
+            if (metaByAttribute[attribute]) {
+              continue;
+            } else {
+              metaByAttribute[attribute] = true;
+            }
+          }
+          resultMeta.push({
+            tag: "meta",
+            attrs: {
+              ...m,
+              nonce
+            }
+          });
+        }
+      }
+    }
+    if (title) {
+      resultMeta.push(title);
+    }
+    if (nonce) {
+      resultMeta.push({
+        tag: "meta",
+        attrs: {
+          property: "csp-nonce",
+          content: nonce
+        }
+      });
+    }
+    resultMeta.reverse();
+    return resultMeta;
+  }, [routeMeta, nonce]);
+  const links = useRouterState({
+    select: (state) => {
+      const constructed = state.matches.map((match2) => match2.links).filter(Boolean).flat(1).map((link) => ({
+        tag: "link",
+        attrs: {
+          ...link,
+          nonce
+        }
+      }));
+      const manifest = router.ssr?.manifest;
+      const assets = state.matches.map((match2) => manifest?.routes[match2.routeId]?.assets ?? []).filter(Boolean).flat(1).filter((asset) => asset.tag === "link").map(
+        (asset) => ({
+          tag: "link",
+          attrs: {
+            ...asset.attrs,
+            suppressHydrationWarning: true,
+            nonce
+          }
+        })
+      );
+      return [...constructed, ...assets];
+    },
+    structuralSharing: true
+  });
+  const preloadLinks = useRouterState({
+    select: (state) => {
+      const preloadLinks2 = [];
+      state.matches.map((match2) => router.looseRoutesById[match2.routeId]).forEach(
+        (route) => router.ssr?.manifest?.routes[route.id]?.preloads?.filter(Boolean).forEach((preload) => {
+          preloadLinks2.push({
+            tag: "link",
+            attrs: {
+              rel: "modulepreload",
+              href: preload,
+              nonce
+            }
+          });
+        })
+      );
+      return preloadLinks2;
+    },
+    structuralSharing: true
+  });
+  const styles = useRouterState({
+    select: (state) => state.matches.map((match2) => match2.styles).flat(1).filter(Boolean).map(({ children, ...attrs }) => ({
+      tag: "style",
+      attrs,
+      children,
+      nonce
+    })),
+    structuralSharing: true
+  });
+  const headScripts = useRouterState({
+    select: (state) => state.matches.map((match2) => match2.headScripts).flat(1).filter(Boolean).map(({ children, ...script }) => ({
+      tag: "script",
+      attrs: {
+        ...script,
+        nonce
+      },
+      children
+    })),
+    structuralSharing: true
+  });
+  return uniqBy(
+    [
+      ...meta,
+      ...preloadLinks,
+      ...links,
+      ...styles,
+      ...headScripts
+    ],
+    (d) => {
+      return JSON.stringify(d);
+    }
+  );
+};
+function HeadContent() {
+  const tags = useTags();
+  const router = useRouter();
+  const nonce = router.options.ssr?.nonce;
+  return tags.map((tag) => /* @__PURE__ */ reactExports.createElement(Asset, { ...tag, key: `tsr-meta-${JSON.stringify(tag)}`, nonce }));
+}
+function uniqBy(arr, fn) {
+  const seen = /* @__PURE__ */ new Set();
+  return arr.filter((item) => {
+    const key = fn(item);
+    if (seen.has(key)) {
+      return false;
+    }
+    seen.add(key);
+    return true;
+  });
+}
+const Scripts = () => {
+  const router = useRouter();
+  const nonce = router.options.ssr?.nonce;
+  const assetScripts = useRouterState({
+    select: (state) => {
+      const assetScripts2 = [];
+      const manifest = router.ssr?.manifest;
+      if (!manifest) {
+        return [];
+      }
+      state.matches.map((match2) => router.looseRoutesById[match2.routeId]).forEach(
+        (route) => manifest.routes[route.id]?.assets?.filter((d) => d.tag === "script").forEach((asset) => {
+          assetScripts2.push({
+            tag: "script",
+            attrs: { ...asset.attrs, nonce },
+            children: asset.children
+          });
+        })
+      );
+      return assetScripts2;
+    },
+    structuralSharing: true
+  });
+  const { scripts } = useRouterState({
+    select: (state) => ({
+      scripts: state.matches.map((match2) => match2.scripts).flat(1).filter(Boolean).map(({ children, ...script }) => ({
+        tag: "script",
+        attrs: {
+          ...script,
+          suppressHydrationWarning: true,
+          nonce
+        },
+        children
+      }))
+    }),
+    structuralSharing: true
+  });
+  let serverBufferedScript = void 0;
+  if (router.serverSsr) {
+    serverBufferedScript = router.serverSsr.takeBufferedScripts();
+  }
+  const allScripts = [...scripts, ...assetScripts];
+  if (serverBufferedScript) {
+    allScripts.unshift(serverBufferedScript);
+  }
+  return /* @__PURE__ */ jsxRuntimeExports.jsx(jsxRuntimeExports.Fragment, { children: allScripts.map((asset, i) => /* @__PURE__ */ reactExports.createElement(Asset, { ...asset, key: `tsr-scripts-${asset.tag}-${i}` })) });
+};
+const Route$5 = createRootRoute({
+  head: () => ({
+    meta: [
+      {
+        charSet: "utf-8"
+      },
+      {
+        name: "viewport",
+        content: "width=device-width, initial-scale=1"
+      },
+      {
+        title: "TanStack Start Starter"
+      }
+    ]
+  }),
+  component: RootComponent
+});
+function RootComponent() {
+  return /* @__PURE__ */ jsxRuntimeExports.jsx(RootDocument, { children: /* @__PURE__ */ jsxRuntimeExports.jsx(Outlet, {}) });
+}
+function RootDocument({ children }) {
+  return /* @__PURE__ */ jsxRuntimeExports.jsxs("html", { children: [
+    /* @__PURE__ */ jsxRuntimeExports.jsx("head", { children: /* @__PURE__ */ jsxRuntimeExports.jsx(HeadContent, {}) }),
+    /* @__PURE__ */ jsxRuntimeExports.jsxs("body", { children: [
+      children,
+      /* @__PURE__ */ jsxRuntimeExports.jsx(Scripts, {})
+    ] })
+  ] });
+}
+const $$splitComponentImporter$2 = () => import("./test-serverFn-BuIGT-94.js");
+const Route$4 = createFileRoute("/test-serverFn")({
+  component: lazyRouteComponent($$splitComponentImporter$2, "component")
+});
+const $$splitComponentImporter$1 = () => import("./test-middleware-B3Fw5htt.js");
+const Route$3 = createFileRoute("/test-middleware")({
+  component: lazyRouteComponent($$splitComponentImporter$1, "component")
+});
+const $$splitComponentImporter = () => import("./index-D3FWW_HK.js");
+const Route$2 = createFileRoute("/")({
+  component: lazyRouteComponent($$splitComponentImporter, "component")
+});
+const Route$1 = createFileRoute("/api/test-middleware")({
+  server: {
+    middleware: [wrappedServerRouteRequestMiddleware],
+    handlers: {
+      GET: async () => {
+        return { message: "Server route middleware test" };
+      }
+    }
+  }
+});
+const Route2 = createFileRoute("/api/error")({
+  server: {
+    handlers: {
+      GET: async () => {
+        try {
+          throw new Error("Sentry API Route Test Error");
+        } catch (error2) {
+          captureException(error2);
+          throw error2;
+        }
+      }
+    }
+  }
+});
+const TestServerFnRoute = Route$4.update({
+  id: "/test-serverFn",
+  path: "/test-serverFn",
+  getParentRoute: () => Route$5
+});
+const TestMiddlewareRoute = Route$3.update({
+  id: "/test-middleware",
+  path: "/test-middleware",
+  getParentRoute: () => Route$5
+});
+const IndexRoute = Route$2.update({
+  id: "/",
+  path: "/",
+  getParentRoute: () => Route$5
+});
+const ApiTestMiddlewareRoute = Route$1.update({
+  id: "/api/test-middleware",
+  path: "/api/test-middleware",
+  getParentRoute: () => Route$5
+});
+const ApiErrorRoute = Route2.update({
+  id: "/api/error",
+  path: "/api/error",
+  getParentRoute: () => Route$5
+});
+const rootRouteChildren = {
+  IndexRoute,
+  TestMiddlewareRoute,
+  TestServerFnRoute,
+  ApiErrorRoute,
+  ApiTestMiddlewareRoute
+};
+const routeTree = Route$5._addFileChildren(rootRouteChildren)._addFileTypes();
+const getRouter = () => {
+  const router = createRouter({
+    routeTree,
+    scrollRestoration: true
+  });
+  if (!router.isServer) {
+    init({
+      environment: "qa",
+      // dynamic sampling bias to keep transactions
+      dsn: "https://public@dsn.ingest.sentry.io/1337",
+      integrations: [(void 0)(router)],
+      // We recommend adjusting this value in production, or using tracesSampler
+      // for finer control
+      tracesSampleRate: 1,
+      release: "e2e-test",
+      tunnel: "http://localhost:3031/"
+      // proxy server
+    });
+  }
+  return router;
+};
+export {
+  getRouter
+};
diff --git a/dev-packages/e2e-tests/test-applications/tanstackstart-react/.nitro/vite/services/ssr/assets/start-CoL2Pr07.js b/dev-packages/e2e-tests/test-applications/tanstackstart-react/.nitro/vite/services/ssr/assets/start-CoL2Pr07.js
new file mode 100644
index 000000000000..a712cce3cbbb
--- /dev/null
+++ b/dev-packages/e2e-tests/test-applications/tanstackstart-react/.nitro/vite/services/ssr/assets/start-CoL2Pr07.js
@@ -0,0 +1,46 @@
+import { c as createMiddleware, a as wrappedGlobalFunctionMiddleware, b as wrappedGlobalRequestMiddleware } from "./middleware-BDyeOn_H.js";
+import "../server.js";
+import "node:async_hooks";
+import "node:stream";
+import "util";
+import "crypto";
+import "async_hooks";
+import "stream";
+import "node:stream/web";
+function dedupeSerializationAdapters(deduped, serializationAdapters) {
+  for (let i = 0, len = serializationAdapters.length; i < len; i++) {
+    const current = serializationAdapters[i];
+    if (!deduped.has(current)) {
+      deduped.add(current);
+      if (current.extends) {
+        dedupeSerializationAdapters(deduped, current.extends);
+      }
+    }
+  }
+}
+const createStart = (getOptions) => {
+  return {
+    getOptions: async () => {
+      const options = await getOptions();
+      if (options.serializationAdapters) {
+        const deduped = /* @__PURE__ */ new Set();
+        dedupeSerializationAdapters(
+          deduped,
+          options.serializationAdapters
+        );
+        options.serializationAdapters = Array.from(deduped);
+      }
+      return options;
+    },
+    createMiddleware
+  };
+};
+const startInstance = createStart(() => {
+  return {
+    requestMiddleware: [wrappedGlobalRequestMiddleware],
+    functionMiddleware: [wrappedGlobalFunctionMiddleware]
+  };
+});
+export {
+  startInstance
+};
diff --git a/dev-packages/e2e-tests/test-applications/tanstackstart-react/.nitro/vite/services/ssr/assets/test-middleware-B3Fw5htt.js b/dev-packages/e2e-tests/test-applications/tanstackstart-react/.nitro/vite/services/ssr/assets/test-middleware-B3Fw5htt.js
new file mode 100644
index 000000000000..4c8b163c60d4
--- /dev/null
+++ b/dev-packages/e2e-tests/test-applications/tanstackstart-react/.nitro/vite/services/ssr/assets/test-middleware-B3Fw5htt.js
@@ -0,0 +1,26 @@
+import { bj as jsxRuntimeExports, bp as createServerFn } from "../server.js";
+import { c as createSsrRpc } from "./createSsrRpc-mJR5gjC5.js";
+import { d as wrappedServerFnMiddleware } from "./middleware-BDyeOn_H.js";
+import "node:async_hooks";
+import "node:stream";
+import "util";
+import "crypto";
+import "async_hooks";
+import "stream";
+import "node:stream/web";
+const serverFnWithMiddleware = createServerFn().middleware([wrappedServerFnMiddleware]).handler(createSsrRpc("42e6d6882d88c00a77d72cf2cca6c8d21f83261791d4de84ca75175410abed98"));
+const serverFnWithoutMiddleware = createServerFn().handler(createSsrRpc("b4335b6f85930e6253fc1633f58be8021f4702741b923704df0d41b27b8e47f0"));
+function TestMiddleware() {
+  return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
+    /* @__PURE__ */ jsxRuntimeExports.jsx("h1", { children: "Test Middleware Page" }),
+    /* @__PURE__ */ jsxRuntimeExports.jsx("button", { id: "server-fn-middleware-btn", type: "button", onClick: async () => {
+      await serverFnWithMiddleware();
+    }, children: "Call server function with middleware" }),
+    /* @__PURE__ */ jsxRuntimeExports.jsx("button", { id: "server-fn-global-only-btn", type: "button", onClick: async () => {
+      await serverFnWithoutMiddleware();
+    }, children: "Call server function (global middleware only)" })
+  ] });
+}
+export {
+  TestMiddleware as component
+};
diff --git a/dev-packages/e2e-tests/test-applications/tanstackstart-react/.nitro/vite/services/ssr/assets/test-middleware-D8HJv8ES.js b/dev-packages/e2e-tests/test-applications/tanstackstart-react/.nitro/vite/services/ssr/assets/test-middleware-D8HJv8ES.js
new file mode 100644
index 000000000000..e7e48e9befd4
--- /dev/null
+++ b/dev-packages/e2e-tests/test-applications/tanstackstart-react/.nitro/vite/services/ssr/assets/test-middleware-D8HJv8ES.js
@@ -0,0 +1,27 @@
+import { bo as createServerRpc, bp as createServerFn } from "../server.js";
+import { d as wrappedServerFnMiddleware } from "./middleware-BDyeOn_H.js";
+import "node:async_hooks";
+import "node:stream";
+import "util";
+import "crypto";
+import "async_hooks";
+import "stream";
+import "node:stream/web";
+const serverFnWithMiddleware_createServerFn_handler = createServerRpc("42e6d6882d88c00a77d72cf2cca6c8d21f83261791d4de84ca75175410abed98", (opts, signal) => serverFnWithMiddleware.__executeServer(opts, signal));
+const serverFnWithMiddleware = createServerFn().middleware([wrappedServerFnMiddleware]).handler(serverFnWithMiddleware_createServerFn_handler, async () => {
+  console.log("Server function with specific middleware executed");
+  return {
+    message: "Server function middleware test"
+  };
+});
+const serverFnWithoutMiddleware_createServerFn_handler = createServerRpc("b4335b6f85930e6253fc1633f58be8021f4702741b923704df0d41b27b8e47f0", (opts, signal) => serverFnWithoutMiddleware.__executeServer(opts, signal));
+const serverFnWithoutMiddleware = createServerFn().handler(serverFnWithoutMiddleware_createServerFn_handler, async () => {
+  console.log("Server function without specific middleware executed");
+  return {
+    message: "Global middleware only test"
+  };
+});
+export {
+  serverFnWithMiddleware_createServerFn_handler,
+  serverFnWithoutMiddleware_createServerFn_handler
+};
diff --git a/dev-packages/e2e-tests/test-applications/tanstackstart-react/.nitro/vite/services/ssr/assets/test-serverFn-BuIGT-94.js b/dev-packages/e2e-tests/test-applications/tanstackstart-react/.nitro/vite/services/ssr/assets/test-serverFn-BuIGT-94.js
new file mode 100644
index 000000000000..50b987e171e6
--- /dev/null
+++ b/dev-packages/e2e-tests/test-applications/tanstackstart-react/.nitro/vite/services/ssr/assets/test-serverFn-BuIGT-94.js
@@ -0,0 +1,25 @@
+import { bj as jsxRuntimeExports, bp as createServerFn } from "../server.js";
+import { c as createSsrRpc } from "./createSsrRpc-mJR5gjC5.js";
+import "node:async_hooks";
+import "node:stream";
+import "util";
+import "crypto";
+import "async_hooks";
+import "stream";
+import "node:stream/web";
+const testLog = createServerFn().handler(createSsrRpc("06bf4c870ccc821429ab5eab89d0d2de36d7b33456a003e6ad402f73a5001414"));
+const testNestedLog = createServerFn().handler(createSsrRpc("1ac31c23f613ec7e58631cf789642e2feb86c58e3128324cf00d746474a044bf"));
+function TestLog() {
+  return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
+    /* @__PURE__ */ jsxRuntimeExports.jsx("h1", { children: "Test Log Page" }),
+    /* @__PURE__ */ jsxRuntimeExports.jsx("button", { type: "button", onClick: async () => {
+      await testLog();
+    }, children: "Call server function" }),
+    /* @__PURE__ */ jsxRuntimeExports.jsx("button", { type: "button", onClick: async () => {
+      await testNestedLog();
+    }, children: "Call server function nested" })
+  ] });
+}
+export {
+  TestLog as component
+};
diff --git a/dev-packages/e2e-tests/test-applications/tanstackstart-react/.nitro/vite/services/ssr/assets/test-serverFn-DsUG4NI8.js b/dev-packages/e2e-tests/test-applications/tanstackstart-react/.nitro/vite/services/ssr/assets/test-serverFn-DsUG4NI8.js
new file mode 100644
index 000000000000..64b8b8a94be6
--- /dev/null
+++ b/dev-packages/e2e-tests/test-applications/tanstackstart-react/.nitro/vite/services/ssr/assets/test-serverFn-DsUG4NI8.js
@@ -0,0 +1,31 @@
+import { bo as createServerRpc, bp as createServerFn, ao as startSpan } from "../server.js";
+import "node:async_hooks";
+import "node:stream";
+import "util";
+import "crypto";
+import "async_hooks";
+import "stream";
+import "node:stream/web";
+const testLog_createServerFn_handler = createServerRpc("06bf4c870ccc821429ab5eab89d0d2de36d7b33456a003e6ad402f73a5001414", (opts, signal) => testLog.__executeServer(opts, signal));
+const testLog = createServerFn().handler(testLog_createServerFn_handler, async () => {
+  console.log("Test log from server function");
+  return {
+    message: "Log created"
+  };
+});
+const testNestedLog_createServerFn_handler = createServerRpc("1ac31c23f613ec7e58631cf789642e2feb86c58e3128324cf00d746474a044bf", (opts, signal) => testNestedLog.__executeServer(opts, signal));
+const testNestedLog = createServerFn().handler(testNestedLog_createServerFn_handler, async () => {
+  await startSpan({
+    name: "testNestedLog"
+  }, async () => {
+    await testLog();
+  });
+  console.log("Outer test log from server function");
+  return {
+    message: "Nested log created"
+  };
+});
+export {
+  testLog_createServerFn_handler,
+  testNestedLog_createServerFn_handler
+};
diff --git a/dev-packages/e2e-tests/test-applications/tanstackstart-react/.nitro/vite/services/ssr/server.js b/dev-packages/e2e-tests/test-applications/tanstackstart-react/.nitro/vite/services/ssr/server.js
new file mode 100644
index 000000000000..d6538c78ad47
--- /dev/null
+++ b/dev-packages/e2e-tests/test-applications/tanstackstart-react/.nitro/vite/services/ssr/server.js
@@ -0,0 +1,40638 @@
+import { AsyncLocalStorage } from "node:async_hooks";
+import { Readable, PassThrough } from "node:stream";
+import require$$0 from "util";
+import require$$1$1 from "crypto";
+import require$$1 from "async_hooks";
+import require$$5 from "stream";
+import { ReadableStream as ReadableStream$1 } from "node:stream/web";
+var commonjsGlobal = typeof globalThis !== "undefined" ? globalThis : typeof window !== "undefined" ? window : typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : {};
+function getDefaultExportFromCjs(x2) {
+  return x2 && x2.__esModule && Object.prototype.hasOwnProperty.call(x2, "default") ? x2["default"] : x2;
+}
+function getAugmentedNamespace(n) {
+  if (Object.prototype.hasOwnProperty.call(n, "__esModule")) return n;
+  var f2 = n.default;
+  if (typeof f2 == "function") {
+    var a = function a2() {
+      var isInstance = false;
+      try {
+        isInstance = this instanceof a2;
+      } catch {
+      }
+      if (isInstance) {
+        return Reflect.construct(f2, arguments, this.constructor);
+      }
+      return f2.apply(this, arguments);
+    };
+    a.prototype = f2.prototype;
+  } else a = {};
+  Object.defineProperty(a, "__esModule", { value: true });
+  Object.keys(n).forEach(function(k2) {
+    var d = Object.getOwnPropertyDescriptor(n, k2);
+    Object.defineProperty(a, k2, d.get ? d : {
+      enumerable: true,
+      get: function() {
+        return n[k2];
+      }
+    });
+  });
+  return a;
+}
+const DEBUG_BUILD = typeof __SENTRY_DEBUG__ === "undefined" || __SENTRY_DEBUG__;
+const GLOBAL_OBJ = globalThis;
+const SDK_VERSION = "10.32.1";
+function getMainCarrier() {
+  getSentryCarrier(GLOBAL_OBJ);
+  return GLOBAL_OBJ;
+}
+function getSentryCarrier(carrier) {
+  const __SENTRY__ = carrier.__SENTRY__ = carrier.__SENTRY__ || {};
+  __SENTRY__.version = __SENTRY__.version || SDK_VERSION;
+  return __SENTRY__[SDK_VERSION] = __SENTRY__[SDK_VERSION] || {};
+}
+function getGlobalSingleton(name, creator, obj = GLOBAL_OBJ) {
+  const __SENTRY__ = obj.__SENTRY__ = obj.__SENTRY__ || {};
+  const carrier = __SENTRY__[SDK_VERSION] = __SENTRY__[SDK_VERSION] || {};
+  return carrier[name] || (carrier[name] = creator());
+}
+const CONSOLE_LEVELS = [
+  "debug",
+  "info",
+  "warn",
+  "error",
+  "log",
+  "assert",
+  "trace"
+];
+const PREFIX = "Sentry Logger ";
+const originalConsoleMethods = {};
+function consoleSandbox(callback) {
+  if (!("console" in GLOBAL_OBJ)) {
+    return callback();
+  }
+  const console2 = GLOBAL_OBJ.console;
+  const wrappedFuncs = {};
+  const wrappedLevels = Object.keys(originalConsoleMethods);
+  wrappedLevels.forEach((level) => {
+    const originalConsoleMethod = originalConsoleMethods[level];
+    wrappedFuncs[level] = console2[level];
+    console2[level] = originalConsoleMethod;
+  });
+  try {
+    return callback();
+  } finally {
+    wrappedLevels.forEach((level) => {
+      console2[level] = wrappedFuncs[level];
+    });
+  }
+}
+function enable() {
+  _getLoggerSettings().enabled = true;
+}
+function disable() {
+  _getLoggerSettings().enabled = false;
+}
+function isEnabled() {
+  return _getLoggerSettings().enabled;
+}
+function log(...args) {
+  _maybeLog("log", ...args);
+}
+function warn(...args) {
+  _maybeLog("warn", ...args);
+}
+function error(...args) {
+  _maybeLog("error", ...args);
+}
+function _maybeLog(level, ...args) {
+  if (!DEBUG_BUILD) {
+    return;
+  }
+  if (isEnabled()) {
+    consoleSandbox(() => {
+      GLOBAL_OBJ.console[level](`${PREFIX}[${level}]:`, ...args);
+    });
+  }
+}
+function _getLoggerSettings() {
+  if (!DEBUG_BUILD) {
+    return { enabled: false };
+  }
+  return getGlobalSingleton("loggerSettings", () => ({ enabled: false }));
+}
+const debug = {
+  /** Enable logging. */
+  enable,
+  /** Disable logging. */
+  disable,
+  /** Check if logging is enabled. */
+  isEnabled,
+  /** Log a message. */
+  log,
+  /** Log a warning. */
+  warn,
+  /** Log an error. */
+  error
+};
+const STACKTRACE_FRAME_LIMIT = 50;
+const UNKNOWN_FUNCTION = "?";
+const WEBPACK_ERROR_REGEXP = /\(error: (.*)\)/;
+const STRIP_FRAME_REGEXP = /captureMessage|captureException/;
+function createStackParser(...parsers) {
+  const sortedParsers = parsers.sort((a, b2) => a[0] - b2[0]).map((p2) => p2[1]);
+  return (stack, skipFirstLines = 0, framesToPop = 0) => {
+    const frames = [];
+    const lines = stack.split("\n");
+    for (let i = skipFirstLines; i < lines.length; i++) {
+      let line = lines[i];
+      if (line.length > 1024) {
+        line = line.slice(0, 1024);
+      }
+      const cleanedLine = WEBPACK_ERROR_REGEXP.test(line) ? line.replace(WEBPACK_ERROR_REGEXP, "$1") : line;
+      if (cleanedLine.match(/\S*Error: /)) {
+        continue;
+      }
+      for (const parser of sortedParsers) {
+        const frame = parser(cleanedLine);
+        if (frame) {
+          frames.push(frame);
+          break;
+        }
+      }
+      if (frames.length >= STACKTRACE_FRAME_LIMIT + framesToPop) {
+        break;
+      }
+    }
+    return stripSentryFramesAndReverse(frames.slice(framesToPop));
+  };
+}
+function stackParserFromStackParserOptions(stackParser) {
+  if (Array.isArray(stackParser)) {
+    return createStackParser(...stackParser);
+  }
+  return stackParser;
+}
+function stripSentryFramesAndReverse(stack) {
+  if (!stack.length) {
+    return [];
+  }
+  const localStack = Array.from(stack);
+  if (/sentryWrapped/.test(getLastStackFrame(localStack).function || "")) {
+    localStack.pop();
+  }
+  localStack.reverse();
+  if (STRIP_FRAME_REGEXP.test(getLastStackFrame(localStack).function || "")) {
+    localStack.pop();
+    if (STRIP_FRAME_REGEXP.test(getLastStackFrame(localStack).function || "")) {
+      localStack.pop();
+    }
+  }
+  return localStack.slice(0, STACKTRACE_FRAME_LIMIT).map((frame) => ({
+    ...frame,
+    filename: frame.filename || getLastStackFrame(localStack).filename,
+    function: frame.function || UNKNOWN_FUNCTION
+  }));
+}
+function getLastStackFrame(arr) {
+  return arr[arr.length - 1] || {};
+}
+const defaultFunctionName = "";
+function getFunctionName(fn2) {
+  try {
+    if (!fn2 || typeof fn2 !== "function") {
+      return defaultFunctionName;
+    }
+    return fn2.name || defaultFunctionName;
+  } catch {
+    return defaultFunctionName;
+  }
+}
+function getVueInternalName(value) {
+  const isVNode = "__v_isVNode" in value && value.__v_isVNode;
+  return isVNode ? "[VueVNode]" : "[VueViewModel]";
+}
+const objectToString = Object.prototype.toString;
+function isError(wat) {
+  switch (objectToString.call(wat)) {
+    case "[object Error]":
+    case "[object Exception]":
+    case "[object DOMException]":
+    case "[object WebAssembly.Exception]":
+      return true;
+    default:
+      return isInstanceOf(wat, Error);
+  }
+}
+function isBuiltin(wat, className) {
+  return objectToString.call(wat) === `[object ${className}]`;
+}
+function isErrorEvent(wat) {
+  return isBuiltin(wat, "ErrorEvent");
+}
+function isString(wat) {
+  return isBuiltin(wat, "String");
+}
+function isParameterizedString(wat) {
+  return typeof wat === "object" && wat !== null && "__sentry_template_string__" in wat && "__sentry_template_values__" in wat;
+}
+function isPrimitive(wat) {
+  return wat === null || isParameterizedString(wat) || typeof wat !== "object" && typeof wat !== "function";
+}
+function isPlainObject$1(wat) {
+  return isBuiltin(wat, "Object");
+}
+function isEvent(wat) {
+  return typeof Event !== "undefined" && isInstanceOf(wat, Event);
+}
+function isElement(wat) {
+  return typeof Element !== "undefined" && isInstanceOf(wat, Element);
+}
+function isRegExp(wat) {
+  return isBuiltin(wat, "RegExp");
+}
+function isThenable(wat) {
+  return Boolean(wat?.then && typeof wat.then === "function");
+}
+function isSyntheticEvent(wat) {
+  return isPlainObject$1(wat) && "nativeEvent" in wat && "preventDefault" in wat && "stopPropagation" in wat;
+}
+function isInstanceOf(wat, base) {
+  try {
+    return wat instanceof base;
+  } catch {
+    return false;
+  }
+}
+function isVueViewModel(wat) {
+  return !!(typeof wat === "object" && wat !== null && (wat.__isVue || wat._isVue || wat.__v_isVNode));
+}
+const WINDOW = GLOBAL_OBJ;
+const DEFAULT_MAX_STRING_LENGTH = 80;
+function htmlTreeAsString(elem, options = {}) {
+  if (!elem) {
+    return "";
+  }
+  try {
+    let currentElem = elem;
+    const MAX_TRAVERSE_HEIGHT = 5;
+    const out = [];
+    let height = 0;
+    let len = 0;
+    const separator = " > ";
+    const sepLength = separator.length;
+    let nextStr;
+    const keyAttrs = Array.isArray(options) ? options : options.keyAttrs;
+    const maxStringLength = !Array.isArray(options) && options.maxStringLength || DEFAULT_MAX_STRING_LENGTH;
+    while (currentElem && height++ < MAX_TRAVERSE_HEIGHT) {
+      nextStr = _htmlElementAsString(currentElem, keyAttrs);
+      if (nextStr === "html" || height > 1 && len + out.length * sepLength + nextStr.length >= maxStringLength) {
+        break;
+      }
+      out.push(nextStr);
+      len += nextStr.length;
+      currentElem = currentElem.parentNode;
+    }
+    return out.reverse().join(separator);
+  } catch {
+    return "";
+  }
+}
+function _htmlElementAsString(el, keyAttrs) {
+  const elem = el;
+  const out = [];
+  if (!elem?.tagName) {
+    return "";
+  }
+  if (WINDOW.HTMLElement) {
+    if (elem instanceof HTMLElement && elem.dataset) {
+      if (elem.dataset["sentryComponent"]) {
+        return elem.dataset["sentryComponent"];
+      }
+      if (elem.dataset["sentryElement"]) {
+        return elem.dataset["sentryElement"];
+      }
+    }
+  }
+  out.push(elem.tagName.toLowerCase());
+  const keyAttrPairs = keyAttrs?.length ? keyAttrs.filter((keyAttr) => elem.getAttribute(keyAttr)).map((keyAttr) => [keyAttr, elem.getAttribute(keyAttr)]) : null;
+  if (keyAttrPairs?.length) {
+    keyAttrPairs.forEach((keyAttrPair) => {
+      out.push(`[${keyAttrPair[0]}="${keyAttrPair[1]}"]`);
+    });
+  } else {
+    if (elem.id) {
+      out.push(`#${elem.id}`);
+    }
+    const className = elem.className;
+    if (className && isString(className)) {
+      const classes = className.split(/\s+/);
+      for (const c2 of classes) {
+        out.push(`.${c2}`);
+      }
+    }
+  }
+  const allowedAttrs = ["aria-label", "type", "name", "title", "alt"];
+  for (const k2 of allowedAttrs) {
+    const attr = elem.getAttribute(k2);
+    if (attr) {
+      out.push(`[${k2}="${attr}"]`);
+    }
+  }
+  return out.join("");
+}
+function fill(source, name, replacementFactory) {
+  if (!(name in source)) {
+    return;
+  }
+  const original = source[name];
+  if (typeof original !== "function") {
+    return;
+  }
+  const wrapped = replacementFactory(original);
+  if (typeof wrapped === "function") {
+    markFunctionWrapped(wrapped, original);
+  }
+  try {
+    source[name] = wrapped;
+  } catch {
+    DEBUG_BUILD && debug.log(`Failed to replace method "${name}" in object`, source);
+  }
+}
+function addNonEnumerableProperty(obj, name, value) {
+  try {
+    Object.defineProperty(obj, name, {
+      // enumerable: false, // the default, so we can save on bundle size by not explicitly setting it
+      value,
+      writable: true,
+      configurable: true
+    });
+  } catch {
+    DEBUG_BUILD && debug.log(`Failed to add non-enumerable property "${name}" to object`, obj);
+  }
+}
+function markFunctionWrapped(wrapped, original) {
+  try {
+    const proto = original.prototype || {};
+    wrapped.prototype = original.prototype = proto;
+    addNonEnumerableProperty(wrapped, "__sentry_original__", original);
+  } catch {
+  }
+}
+function getOriginalFunction(func) {
+  return func.__sentry_original__;
+}
+function convertToPlainObject(value) {
+  if (isError(value)) {
+    return {
+      message: value.message,
+      name: value.name,
+      stack: value.stack,
+      ...getOwnProperties(value)
+    };
+  } else if (isEvent(value)) {
+    const newObj = {
+      type: value.type,
+      target: serializeEventTarget(value.target),
+      currentTarget: serializeEventTarget(value.currentTarget),
+      ...getOwnProperties(value)
+    };
+    if (typeof CustomEvent !== "undefined" && isInstanceOf(value, CustomEvent)) {
+      newObj.detail = value.detail;
+    }
+    return newObj;
+  } else {
+    return value;
+  }
+}
+function serializeEventTarget(target) {
+  try {
+    return isElement(target) ? htmlTreeAsString(target) : Object.prototype.toString.call(target);
+  } catch {
+    return "";
+  }
+}
+function getOwnProperties(obj) {
+  if (typeof obj === "object" && obj !== null) {
+    const extractedProps = {};
+    for (const property in obj) {
+      if (Object.prototype.hasOwnProperty.call(obj, property)) {
+        extractedProps[property] = obj[property];
+      }
+    }
+    return extractedProps;
+  } else {
+    return {};
+  }
+}
+function extractExceptionKeysForMessage(exception) {
+  const keys = Object.keys(convertToPlainObject(exception));
+  keys.sort();
+  return !keys[0] ? "[object has no keys]" : keys.join(", ");
+}
+function truncate(str, max = 0) {
+  if (typeof str !== "string" || max === 0) {
+    return str;
+  }
+  return str.length <= max ? str : `${str.slice(0, max)}...`;
+}
+function snipLine(line, colno) {
+  let newLine = line;
+  const lineLength = newLine.length;
+  if (lineLength <= 150) {
+    return newLine;
+  }
+  if (colno > lineLength) {
+    colno = lineLength;
+  }
+  let start = Math.max(colno - 60, 0);
+  if (start < 5) {
+    start = 0;
+  }
+  let end = Math.min(start + 140, lineLength);
+  if (end > lineLength - 5) {
+    end = lineLength;
+  }
+  if (end === lineLength) {
+    start = Math.max(end - 140, 0);
+  }
+  newLine = newLine.slice(start, end);
+  if (start > 0) {
+    newLine = `'{snip} ${newLine}`;
+  }
+  if (end < lineLength) {
+    newLine += " {snip}";
+  }
+  return newLine;
+}
+function safeJoin(input, delimiter) {
+  if (!Array.isArray(input)) {
+    return "";
+  }
+  const output = [];
+  for (let i = 0; i < input.length; i++) {
+    const value = input[i];
+    try {
+      if (isVueViewModel(value)) {
+        output.push(getVueInternalName(value));
+      } else {
+        output.push(String(value));
+      }
+    } catch {
+      output.push("[value cannot be serialized]");
+    }
+  }
+  return output.join(delimiter);
+}
+function isMatchingPattern(value, pattern2, requireExactStringMatch = false) {
+  if (!isString(value)) {
+    return false;
+  }
+  if (isRegExp(pattern2)) {
+    return pattern2.test(value);
+  }
+  if (isString(pattern2)) {
+    return requireExactStringMatch ? value === pattern2 : value.includes(pattern2);
+  }
+  return false;
+}
+function stringMatchesSomePattern(testString, patterns = [], requireExactStringMatch = false) {
+  return patterns.some((pattern2) => isMatchingPattern(testString, pattern2, requireExactStringMatch));
+}
+function getCrypto() {
+  const gbl = GLOBAL_OBJ;
+  return gbl.crypto || gbl.msCrypto;
+}
+let emptyUuid;
+function getRandomByte() {
+  return Math.random() * 16;
+}
+function uuid4(crypto = getCrypto()) {
+  try {
+    if (crypto?.randomUUID) {
+      return crypto.randomUUID().replace(/-/g, "");
+    }
+  } catch {
+  }
+  if (!emptyUuid) {
+    emptyUuid = "10000000100040008000" + 1e11;
+  }
+  return emptyUuid.replace(
+    /[018]/g,
+    (c2) => (
+      // eslint-disable-next-line no-bitwise
+      (c2 ^ (getRandomByte() & 15) >> c2 / 4).toString(16)
+    )
+  );
+}
+function getFirstException(event) {
+  return event.exception?.values?.[0];
+}
+function getEventDescription(event) {
+  const { message, event_id: eventId } = event;
+  if (message) {
+    return message;
+  }
+  const firstException = getFirstException(event);
+  if (firstException) {
+    if (firstException.type && firstException.value) {
+      return `${firstException.type}: ${firstException.value}`;
+    }
+    return firstException.type || firstException.value || eventId || "";
+  }
+  return eventId || "";
+}
+function addExceptionTypeValue(event, value, type) {
+  const exception = event.exception = event.exception || {};
+  const values = exception.values = exception.values || [];
+  const firstException = values[0] = values[0] || {};
+  if (!firstException.value) {
+    firstException.value = "";
+  }
+  if (!firstException.type) {
+    firstException.type = "Error";
+  }
+}
+function addExceptionMechanism(event, newMechanism) {
+  const firstException = getFirstException(event);
+  if (!firstException) {
+    return;
+  }
+  const defaultMechanism = { type: "generic", handled: true };
+  const currentMechanism = firstException.mechanism;
+  firstException.mechanism = { ...defaultMechanism, ...currentMechanism, ...newMechanism };
+  if (newMechanism && "data" in newMechanism) {
+    const mergedData = { ...currentMechanism?.data, ...newMechanism.data };
+    firstException.mechanism.data = mergedData;
+  }
+}
+const SEMVER_REGEXP = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\+([0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*))?$/;
+function _parseInt(input) {
+  return parseInt(input || "", 10);
+}
+function parseSemver(input) {
+  const match = input.match(SEMVER_REGEXP) || [];
+  const major = _parseInt(match[1]);
+  const minor = _parseInt(match[2]);
+  const patch = _parseInt(match[3]);
+  return {
+    buildmetadata: match[5],
+    major: isNaN(major) ? void 0 : major,
+    minor: isNaN(minor) ? void 0 : minor,
+    patch: isNaN(patch) ? void 0 : patch,
+    prerelease: match[4]
+  };
+}
+function checkOrSetAlreadyCaught(exception) {
+  if (isAlreadyCaptured(exception)) {
+    return true;
+  }
+  try {
+    addNonEnumerableProperty(exception, "__sentry_captured__", true);
+  } catch {
+  }
+  return false;
+}
+function isAlreadyCaptured(exception) {
+  try {
+    return exception.__sentry_captured__;
+  } catch {
+  }
+}
+const ONE_SECOND_IN_MS = 1e3;
+function dateTimestampInSeconds() {
+  return Date.now() / ONE_SECOND_IN_MS;
+}
+function createUnixTimestampInSecondsFunc() {
+  const { performance: performance2 } = GLOBAL_OBJ;
+  if (!performance2?.now || !performance2.timeOrigin) {
+    return dateTimestampInSeconds;
+  }
+  const timeOrigin = performance2.timeOrigin;
+  return () => {
+    return (timeOrigin + performance2.now()) / ONE_SECOND_IN_MS;
+  };
+}
+let _cachedTimestampInSeconds;
+function timestampInSeconds() {
+  const func = _cachedTimestampInSeconds ?? (_cachedTimestampInSeconds = createUnixTimestampInSecondsFunc());
+  return func();
+}
+function makeSession(context) {
+  const startingTime = timestampInSeconds();
+  const session = {
+    sid: uuid4(),
+    init: true,
+    timestamp: startingTime,
+    started: startingTime,
+    duration: 0,
+    status: "ok",
+    errors: 0,
+    ignoreDuration: false,
+    toJSON: () => sessionToJSON(session)
+  };
+  if (context) {
+    updateSession(session, context);
+  }
+  return session;
+}
+function updateSession(session, context = {}) {
+  if (context.user) {
+    if (!session.ipAddress && context.user.ip_address) {
+      session.ipAddress = context.user.ip_address;
+    }
+    if (!session.did && !context.did) {
+      session.did = context.user.id || context.user.email || context.user.username;
+    }
+  }
+  session.timestamp = context.timestamp || timestampInSeconds();
+  if (context.abnormal_mechanism) {
+    session.abnormal_mechanism = context.abnormal_mechanism;
+  }
+  if (context.ignoreDuration) {
+    session.ignoreDuration = context.ignoreDuration;
+  }
+  if (context.sid) {
+    session.sid = context.sid.length === 32 ? context.sid : uuid4();
+  }
+  if (context.init !== void 0) {
+    session.init = context.init;
+  }
+  if (!session.did && context.did) {
+    session.did = `${context.did}`;
+  }
+  if (typeof context.started === "number") {
+    session.started = context.started;
+  }
+  if (session.ignoreDuration) {
+    session.duration = void 0;
+  } else if (typeof context.duration === "number") {
+    session.duration = context.duration;
+  } else {
+    const duration = session.timestamp - session.started;
+    session.duration = duration >= 0 ? duration : 0;
+  }
+  if (context.release) {
+    session.release = context.release;
+  }
+  if (context.environment) {
+    session.environment = context.environment;
+  }
+  if (!session.ipAddress && context.ipAddress) {
+    session.ipAddress = context.ipAddress;
+  }
+  if (!session.userAgent && context.userAgent) {
+    session.userAgent = context.userAgent;
+  }
+  if (typeof context.errors === "number") {
+    session.errors = context.errors;
+  }
+  if (context.status) {
+    session.status = context.status;
+  }
+}
+function closeSession(session, status) {
+  let context = {};
+  if (session.status === "ok") {
+    context = { status: "exited" };
+  }
+  updateSession(session, context);
+}
+function sessionToJSON(session) {
+  return {
+    sid: `${session.sid}`,
+    init: session.init,
+    // Make sure that sec is converted to ms for date constructor
+    started: new Date(session.started * 1e3).toISOString(),
+    timestamp: new Date(session.timestamp * 1e3).toISOString(),
+    status: session.status,
+    errors: session.errors,
+    did: typeof session.did === "number" || typeof session.did === "string" ? `${session.did}` : void 0,
+    duration: session.duration,
+    abnormal_mechanism: session.abnormal_mechanism,
+    attrs: {
+      release: session.release,
+      environment: session.environment,
+      ip_address: session.ipAddress,
+      user_agent: session.userAgent
+    }
+  };
+}
+function merge(initialObj, mergeObj, levels = 2) {
+  if (!mergeObj || typeof mergeObj !== "object" || levels <= 0) {
+    return mergeObj;
+  }
+  if (initialObj && Object.keys(mergeObj).length === 0) {
+    return initialObj;
+  }
+  const output = { ...initialObj };
+  for (const key in mergeObj) {
+    if (Object.prototype.hasOwnProperty.call(mergeObj, key)) {
+      output[key] = merge(output[key], mergeObj[key], levels - 1);
+    }
+  }
+  return output;
+}
+function generateTraceId() {
+  return uuid4();
+}
+function generateSpanId() {
+  return uuid4().substring(16);
+}
+const SCOPE_SPAN_FIELD = "_sentrySpan";
+function _setSpanForScope(scope, span) {
+  if (span) {
+    addNonEnumerableProperty(scope, SCOPE_SPAN_FIELD, span);
+  } else {
+    delete scope[SCOPE_SPAN_FIELD];
+  }
+}
+function _getSpanForScope(scope) {
+  return scope[SCOPE_SPAN_FIELD];
+}
+const DEFAULT_MAX_BREADCRUMBS = 100;
+class Scope {
+  /** Flag if notifying is happening. */
+  /** Callback for client to receive scope changes. */
+  /** Callback list that will be called during event processing. */
+  /** Array of breadcrumbs. */
+  /** User */
+  /** Tags */
+  /** Attributes */
+  /** Extra */
+  /** Contexts */
+  /** Attachments */
+  /** Propagation Context for distributed tracing */
+  /**
+   * A place to stash data which is needed at some point in the SDK's event processing pipeline but which shouldn't get
+   * sent to Sentry
+   */
+  /** Fingerprint */
+  /** Severity */
+  /**
+   * Transaction Name
+   *
+   * IMPORTANT: The transaction name on the scope has nothing to do with root spans/transaction objects.
+   * It's purpose is to assign a transaction to the scope that's added to non-transaction events.
+   */
+  /** Session */
+  /** The client on this scope */
+  /** Contains the last event id of a captured event.  */
+  // NOTE: Any field which gets added here should get added not only to the constructor but also to the `clone` method.
+  constructor() {
+    this._notifyingListeners = false;
+    this._scopeListeners = [];
+    this._eventProcessors = [];
+    this._breadcrumbs = [];
+    this._attachments = [];
+    this._user = {};
+    this._tags = {};
+    this._attributes = {};
+    this._extra = {};
+    this._contexts = {};
+    this._sdkProcessingMetadata = {};
+    this._propagationContext = {
+      traceId: generateTraceId(),
+      sampleRand: Math.random()
+    };
+  }
+  /**
+   * Clone all data from this scope into a new scope.
+   */
+  clone() {
+    const newScope = new Scope();
+    newScope._breadcrumbs = [...this._breadcrumbs];
+    newScope._tags = { ...this._tags };
+    newScope._attributes = { ...this._attributes };
+    newScope._extra = { ...this._extra };
+    newScope._contexts = { ...this._contexts };
+    if (this._contexts.flags) {
+      newScope._contexts.flags = {
+        values: [...this._contexts.flags.values]
+      };
+    }
+    newScope._user = this._user;
+    newScope._level = this._level;
+    newScope._session = this._session;
+    newScope._transactionName = this._transactionName;
+    newScope._fingerprint = this._fingerprint;
+    newScope._eventProcessors = [...this._eventProcessors];
+    newScope._attachments = [...this._attachments];
+    newScope._sdkProcessingMetadata = { ...this._sdkProcessingMetadata };
+    newScope._propagationContext = { ...this._propagationContext };
+    newScope._client = this._client;
+    newScope._lastEventId = this._lastEventId;
+    _setSpanForScope(newScope, _getSpanForScope(this));
+    return newScope;
+  }
+  /**
+   * Update the client assigned to this scope.
+   * Note that not every scope will have a client assigned - isolation scopes & the global scope will generally not have a client,
+   * as well as manually created scopes.
+   */
+  setClient(client) {
+    this._client = client;
+  }
+  /**
+   * Set the ID of the last captured error event.
+   * This is generally only captured on the isolation scope.
+   */
+  setLastEventId(lastEventId) {
+    this._lastEventId = lastEventId;
+  }
+  /**
+   * Get the client assigned to this scope.
+   */
+  getClient() {
+    return this._client;
+  }
+  /**
+   * Get the ID of the last captured error event.
+   * This is generally only available on the isolation scope.
+   */
+  lastEventId() {
+    return this._lastEventId;
+  }
+  /**
+   * @inheritDoc
+   */
+  addScopeListener(callback) {
+    this._scopeListeners.push(callback);
+  }
+  /**
+   * Add an event processor that will be called before an event is sent.
+   */
+  addEventProcessor(callback) {
+    this._eventProcessors.push(callback);
+    return this;
+  }
+  /**
+   * Set the user for this scope.
+   * Set to `null` to unset the user.
+   */
+  setUser(user) {
+    this._user = user || {
+      email: void 0,
+      id: void 0,
+      ip_address: void 0,
+      username: void 0
+    };
+    if (this._session) {
+      updateSession(this._session, { user });
+    }
+    this._notifyScopeListeners();
+    return this;
+  }
+  /**
+   * Get the user from this scope.
+   */
+  getUser() {
+    return this._user;
+  }
+  /**
+   * Set an object that will be merged into existing tags on the scope,
+   * and will be sent as tags data with the event.
+   */
+  setTags(tags) {
+    this._tags = {
+      ...this._tags,
+      ...tags
+    };
+    this._notifyScopeListeners();
+    return this;
+  }
+  /**
+   * Set a single tag that will be sent as tags data with the event.
+   */
+  setTag(key, value) {
+    return this.setTags({ [key]: value });
+  }
+  /**
+   * Sets attributes onto the scope.
+   *
+   * These attributes are currently only applied to logs.
+   * In the future, they will also be applied to metrics and spans.
+   *
+   * Important: For now, only strings, numbers and boolean attributes are supported, despite types allowing for
+   * more complex attribute types. We'll add this support in the future but already specify the wider type to
+   * avoid a breaking change in the future.
+   *
+   * @param newAttributes - The attributes to set on the scope. You can either pass in key-value pairs, or
+   * an object with a `value` and an optional `unit` (if applicable to your attribute).
+   *
+   * @example
+   * ```typescript
+   * scope.setAttributes({
+   *   is_admin: true,
+   *   payment_selection: 'credit_card',
+   *   render_duration: { value: 'render_duration', unit: 'ms' },
+   * });
+   * ```
+   */
+  setAttributes(newAttributes) {
+    this._attributes = {
+      ...this._attributes,
+      ...newAttributes
+    };
+    this._notifyScopeListeners();
+    return this;
+  }
+  /**
+   * Sets an attribute onto the scope.
+   *
+   * These attributes are currently only applied to logs.
+   * In the future, they will also be applied to metrics and spans.
+   *
+   * Important: For now, only strings, numbers and boolean attributes are supported, despite types allowing for
+   * more complex attribute types. We'll add this support in the future but already specify the wider type to
+   * avoid a breaking change in the future.
+   *
+   * @param key - The attribute key.
+   * @param value - the attribute value. You can either pass in a raw value, or an attribute
+   * object with a `value` and an optional `unit` (if applicable to your attribute).
+   *
+   * @example
+   * ```typescript
+   * scope.setAttribute('is_admin', true);
+   * scope.setAttribute('render_duration', { value: 'render_duration', unit: 'ms' });
+   * ```
+   */
+  // eslint-disable-next-line @typescript-eslint/no-explicit-any
+  setAttribute(key, value) {
+    return this.setAttributes({ [key]: value });
+  }
+  /**
+   * Removes the attribute with the given key from the scope.
+   *
+   * @param key - The attribute key.
+   *
+   * @example
+   * ```typescript
+   * scope.removeAttribute('is_admin');
+   * ```
+   */
+  removeAttribute(key) {
+    if (key in this._attributes) {
+      delete this._attributes[key];
+      this._notifyScopeListeners();
+    }
+    return this;
+  }
+  /**
+   * Set an object that will be merged into existing extra on the scope,
+   * and will be sent as extra data with the event.
+   */
+  setExtras(extras) {
+    this._extra = {
+      ...this._extra,
+      ...extras
+    };
+    this._notifyScopeListeners();
+    return this;
+  }
+  /**
+   * Set a single key:value extra entry that will be sent as extra data with the event.
+   */
+  setExtra(key, extra) {
+    this._extra = { ...this._extra, [key]: extra };
+    this._notifyScopeListeners();
+    return this;
+  }
+  /**
+   * Sets the fingerprint on the scope to send with the events.
+   * @param {string[]} fingerprint Fingerprint to group events in Sentry.
+   */
+  setFingerprint(fingerprint) {
+    this._fingerprint = fingerprint;
+    this._notifyScopeListeners();
+    return this;
+  }
+  /**
+   * Sets the level on the scope for future events.
+   */
+  setLevel(level) {
+    this._level = level;
+    this._notifyScopeListeners();
+    return this;
+  }
+  /**
+   * Sets the transaction name on the scope so that the name of e.g. taken server route or
+   * the page location is attached to future events.
+   *
+   * IMPORTANT: Calling this function does NOT change the name of the currently active
+   * root span. If you want to change the name of the active root span, use
+   * `Sentry.updateSpanName(rootSpan, 'new name')` instead.
+   *
+   * By default, the SDK updates the scope's transaction name automatically on sensible
+   * occasions, such as a page navigation or when handling a new request on the server.
+   */
+  setTransactionName(name) {
+    this._transactionName = name;
+    this._notifyScopeListeners();
+    return this;
+  }
+  /**
+   * Sets context data with the given name.
+   * Data passed as context will be normalized. You can also pass `null` to unset the context.
+   * Note that context data will not be merged - calling `setContext` will overwrite an existing context with the same key.
+   */
+  setContext(key, context) {
+    if (context === null) {
+      delete this._contexts[key];
+    } else {
+      this._contexts[key] = context;
+    }
+    this._notifyScopeListeners();
+    return this;
+  }
+  /**
+   * Set the session for the scope.
+   */
+  setSession(session) {
+    if (!session) {
+      delete this._session;
+    } else {
+      this._session = session;
+    }
+    this._notifyScopeListeners();
+    return this;
+  }
+  /**
+   * Get the session from the scope.
+   */
+  getSession() {
+    return this._session;
+  }
+  /**
+   * Updates the scope with provided data. Can work in three variations:
+   * - plain object containing updatable attributes
+   * - Scope instance that'll extract the attributes from
+   * - callback function that'll receive the current scope as an argument and allow for modifications
+   */
+  update(captureContext) {
+    if (!captureContext) {
+      return this;
+    }
+    const scopeToMerge = typeof captureContext === "function" ? captureContext(this) : captureContext;
+    const scopeInstance = scopeToMerge instanceof Scope ? scopeToMerge.getScopeData() : isPlainObject$1(scopeToMerge) ? captureContext : void 0;
+    const {
+      tags,
+      attributes,
+      extra,
+      user,
+      contexts,
+      level,
+      fingerprint = [],
+      propagationContext
+    } = scopeInstance || {};
+    this._tags = { ...this._tags, ...tags };
+    this._attributes = { ...this._attributes, ...attributes };
+    this._extra = { ...this._extra, ...extra };
+    this._contexts = { ...this._contexts, ...contexts };
+    if (user && Object.keys(user).length) {
+      this._user = user;
+    }
+    if (level) {
+      this._level = level;
+    }
+    if (fingerprint.length) {
+      this._fingerprint = fingerprint;
+    }
+    if (propagationContext) {
+      this._propagationContext = propagationContext;
+    }
+    return this;
+  }
+  /**
+   * Clears the current scope and resets its properties.
+   * Note: The client will not be cleared.
+   */
+  clear() {
+    this._breadcrumbs = [];
+    this._tags = {};
+    this._attributes = {};
+    this._extra = {};
+    this._user = {};
+    this._contexts = {};
+    this._level = void 0;
+    this._transactionName = void 0;
+    this._fingerprint = void 0;
+    this._session = void 0;
+    _setSpanForScope(this, void 0);
+    this._attachments = [];
+    this.setPropagationContext({ traceId: generateTraceId(), sampleRand: Math.random() });
+    this._notifyScopeListeners();
+    return this;
+  }
+  /**
+   * Adds a breadcrumb to the scope.
+   * By default, the last 100 breadcrumbs are kept.
+   */
+  addBreadcrumb(breadcrumb, maxBreadcrumbs) {
+    const maxCrumbs = typeof maxBreadcrumbs === "number" ? maxBreadcrumbs : DEFAULT_MAX_BREADCRUMBS;
+    if (maxCrumbs <= 0) {
+      return this;
+    }
+    const mergedBreadcrumb = {
+      timestamp: dateTimestampInSeconds(),
+      ...breadcrumb,
+      // Breadcrumb messages can theoretically be infinitely large and they're held in memory so we truncate them not to leak (too much) memory
+      message: breadcrumb.message ? truncate(breadcrumb.message, 2048) : breadcrumb.message
+    };
+    this._breadcrumbs.push(mergedBreadcrumb);
+    if (this._breadcrumbs.length > maxCrumbs) {
+      this._breadcrumbs = this._breadcrumbs.slice(-maxCrumbs);
+      this._client?.recordDroppedEvent("buffer_overflow", "log_item");
+    }
+    this._notifyScopeListeners();
+    return this;
+  }
+  /**
+   * Get the last breadcrumb of the scope.
+   */
+  getLastBreadcrumb() {
+    return this._breadcrumbs[this._breadcrumbs.length - 1];
+  }
+  /**
+   * Clear all breadcrumbs from the scope.
+   */
+  clearBreadcrumbs() {
+    this._breadcrumbs = [];
+    this._notifyScopeListeners();
+    return this;
+  }
+  /**
+   * Add an attachment to the scope.
+   */
+  addAttachment(attachment) {
+    this._attachments.push(attachment);
+    return this;
+  }
+  /**
+   * Clear all attachments from the scope.
+   */
+  clearAttachments() {
+    this._attachments = [];
+    return this;
+  }
+  /**
+   * Get the data of this scope, which should be applied to an event during processing.
+   */
+  getScopeData() {
+    return {
+      breadcrumbs: this._breadcrumbs,
+      attachments: this._attachments,
+      contexts: this._contexts,
+      tags: this._tags,
+      attributes: this._attributes,
+      extra: this._extra,
+      user: this._user,
+      level: this._level,
+      fingerprint: this._fingerprint || [],
+      eventProcessors: this._eventProcessors,
+      propagationContext: this._propagationContext,
+      sdkProcessingMetadata: this._sdkProcessingMetadata,
+      transactionName: this._transactionName,
+      span: _getSpanForScope(this)
+    };
+  }
+  /**
+   * Add data which will be accessible during event processing but won't get sent to Sentry.
+   */
+  setSDKProcessingMetadata(newData) {
+    this._sdkProcessingMetadata = merge(this._sdkProcessingMetadata, newData, 2);
+    return this;
+  }
+  /**
+   * Add propagation context to the scope, used for distributed tracing
+   */
+  setPropagationContext(context) {
+    this._propagationContext = context;
+    return this;
+  }
+  /**
+   * Get propagation context from the scope, used for distributed tracing
+   */
+  getPropagationContext() {
+    return this._propagationContext;
+  }
+  /**
+   * Capture an exception for this scope.
+   *
+   * @returns {string} The id of the captured Sentry event.
+   */
+  captureException(exception, hint) {
+    const eventId = hint?.event_id || uuid4();
+    if (!this._client) {
+      DEBUG_BUILD && debug.warn("No client configured on scope - will not capture exception!");
+      return eventId;
+    }
+    const syntheticException = new Error("Sentry syntheticException");
+    this._client.captureException(
+      exception,
+      {
+        originalException: exception,
+        syntheticException,
+        ...hint,
+        event_id: eventId
+      },
+      this
+    );
+    return eventId;
+  }
+  /**
+   * Capture a message for this scope.
+   *
+   * @returns {string} The id of the captured message.
+   */
+  captureMessage(message, level, hint) {
+    const eventId = hint?.event_id || uuid4();
+    if (!this._client) {
+      DEBUG_BUILD && debug.warn("No client configured on scope - will not capture message!");
+      return eventId;
+    }
+    const syntheticException = hint?.syntheticException ?? new Error(message);
+    this._client.captureMessage(
+      message,
+      level,
+      {
+        originalException: message,
+        syntheticException,
+        ...hint,
+        event_id: eventId
+      },
+      this
+    );
+    return eventId;
+  }
+  /**
+   * Capture a Sentry event for this scope.
+   *
+   * @returns {string} The id of the captured event.
+   */
+  captureEvent(event, hint) {
+    const eventId = hint?.event_id || uuid4();
+    if (!this._client) {
+      DEBUG_BUILD && debug.warn("No client configured on scope - will not capture event!");
+      return eventId;
+    }
+    this._client.captureEvent(event, { ...hint, event_id: eventId }, this);
+    return eventId;
+  }
+  /**
+   * This will be called on every set call.
+   */
+  _notifyScopeListeners() {
+    if (!this._notifyingListeners) {
+      this._notifyingListeners = true;
+      this._scopeListeners.forEach((callback) => {
+        callback(this);
+      });
+      this._notifyingListeners = false;
+    }
+  }
+}
+function getDefaultCurrentScope() {
+  return getGlobalSingleton("defaultCurrentScope", () => new Scope());
+}
+function getDefaultIsolationScope() {
+  return getGlobalSingleton("defaultIsolationScope", () => new Scope());
+}
+class AsyncContextStack {
+  constructor(scope, isolationScope) {
+    let assignedScope;
+    if (!scope) {
+      assignedScope = new Scope();
+    } else {
+      assignedScope = scope;
+    }
+    let assignedIsolationScope;
+    if (!isolationScope) {
+      assignedIsolationScope = new Scope();
+    } else {
+      assignedIsolationScope = isolationScope;
+    }
+    this._stack = [{ scope: assignedScope }];
+    this._isolationScope = assignedIsolationScope;
+  }
+  /**
+   * Fork a scope for the stack.
+   */
+  withScope(callback) {
+    const scope = this._pushScope();
+    let maybePromiseResult;
+    try {
+      maybePromiseResult = callback(scope);
+    } catch (e) {
+      this._popScope();
+      throw e;
+    }
+    if (isThenable(maybePromiseResult)) {
+      return maybePromiseResult.then(
+        (res) => {
+          this._popScope();
+          return res;
+        },
+        (e) => {
+          this._popScope();
+          throw e;
+        }
+      );
+    }
+    this._popScope();
+    return maybePromiseResult;
+  }
+  /**
+   * Get the client of the stack.
+   */
+  getClient() {
+    return this.getStackTop().client;
+  }
+  /**
+   * Returns the scope of the top stack.
+   */
+  getScope() {
+    return this.getStackTop().scope;
+  }
+  /**
+   * Get the isolation scope for the stack.
+   */
+  getIsolationScope() {
+    return this._isolationScope;
+  }
+  /**
+   * Returns the topmost scope layer in the order domain > local > process.
+   */
+  getStackTop() {
+    return this._stack[this._stack.length - 1];
+  }
+  /**
+   * Push a scope to the stack.
+   */
+  _pushScope() {
+    const scope = this.getScope().clone();
+    this._stack.push({
+      client: this.getClient(),
+      scope
+    });
+    return scope;
+  }
+  /**
+   * Pop a scope from the stack.
+   */
+  _popScope() {
+    if (this._stack.length <= 1) return false;
+    return !!this._stack.pop();
+  }
+}
+function getAsyncContextStack() {
+  const registry = getMainCarrier();
+  const sentry = getSentryCarrier(registry);
+  return sentry.stack = sentry.stack || new AsyncContextStack(getDefaultCurrentScope(), getDefaultIsolationScope());
+}
+function withScope$1(callback) {
+  return getAsyncContextStack().withScope(callback);
+}
+function withSetScope(scope, callback) {
+  const stack = getAsyncContextStack();
+  return stack.withScope(() => {
+    stack.getStackTop().scope = scope;
+    return callback(scope);
+  });
+}
+function withIsolationScope$1(callback) {
+  return getAsyncContextStack().withScope(() => {
+    return callback(getAsyncContextStack().getIsolationScope());
+  });
+}
+function getStackAsyncContextStrategy() {
+  return {
+    withIsolationScope: withIsolationScope$1,
+    withScope: withScope$1,
+    withSetScope,
+    withSetIsolationScope: (_isolationScope, callback) => {
+      return withIsolationScope$1(callback);
+    },
+    getCurrentScope: () => getAsyncContextStack().getScope(),
+    getIsolationScope: () => getAsyncContextStack().getIsolationScope()
+  };
+}
+function setAsyncContextStrategy(strategy) {
+  const registry = getMainCarrier();
+  const sentry = getSentryCarrier(registry);
+  sentry.acs = strategy;
+}
+function getAsyncContextStrategy(carrier) {
+  const sentry = getSentryCarrier(carrier);
+  if (sentry.acs) {
+    return sentry.acs;
+  }
+  return getStackAsyncContextStrategy();
+}
+function getCurrentScope() {
+  const carrier = getMainCarrier();
+  const acs = getAsyncContextStrategy(carrier);
+  return acs.getCurrentScope();
+}
+function getIsolationScope() {
+  const carrier = getMainCarrier();
+  const acs = getAsyncContextStrategy(carrier);
+  return acs.getIsolationScope();
+}
+function getGlobalScope() {
+  return getGlobalSingleton("globalScope", () => new Scope());
+}
+function withScope(...rest) {
+  const carrier = getMainCarrier();
+  const acs = getAsyncContextStrategy(carrier);
+  if (rest.length === 2) {
+    const [scope, callback] = rest;
+    if (!scope) {
+      return acs.withScope(callback);
+    }
+    return acs.withSetScope(scope, callback);
+  }
+  return acs.withScope(rest[0]);
+}
+function withIsolationScope(...rest) {
+  const carrier = getMainCarrier();
+  const acs = getAsyncContextStrategy(carrier);
+  if (rest.length === 2) {
+    const [isolationScope, callback] = rest;
+    if (!isolationScope) {
+      return acs.withIsolationScope(callback);
+    }
+    return acs.withSetIsolationScope(isolationScope, callback);
+  }
+  return acs.withIsolationScope(rest[0]);
+}
+function getClient() {
+  return getCurrentScope().getClient();
+}
+function getTraceContextFromScope(scope) {
+  const propagationContext = scope.getPropagationContext();
+  const { traceId, parentSpanId, propagationSpanId } = propagationContext;
+  const traceContext = {
+    trace_id: traceId,
+    span_id: propagationSpanId || generateSpanId()
+  };
+  if (parentSpanId) {
+    traceContext.parent_span_id = parentSpanId;
+  }
+  return traceContext;
+}
+const SEMANTIC_ATTRIBUTE_SENTRY_SOURCE = "sentry.source";
+const SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE = "sentry.sample_rate";
+const SEMANTIC_ATTRIBUTE_SENTRY_PREVIOUS_TRACE_SAMPLE_RATE = "sentry.previous_trace_sample_rate";
+const SEMANTIC_ATTRIBUTE_SENTRY_OP = "sentry.op";
+const SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN = "sentry.origin";
+const SEMANTIC_ATTRIBUTE_SENTRY_MEASUREMENT_UNIT = "sentry.measurement_unit";
+const SEMANTIC_ATTRIBUTE_SENTRY_MEASUREMENT_VALUE = "sentry.measurement_value";
+const SEMANTIC_ATTRIBUTE_SENTRY_CUSTOM_SPAN_NAME = "sentry.custom_span_name";
+const SEMANTIC_ATTRIBUTE_PROFILE_ID = "sentry.profile_id";
+const SEMANTIC_ATTRIBUTE_EXCLUSIVE_TIME = "sentry.exclusive_time";
+const SEMANTIC_ATTRIBUTE_CACHE_HIT = "cache.hit";
+const SEMANTIC_ATTRIBUTE_CACHE_KEY = "cache.key";
+const SEMANTIC_ATTRIBUTE_CACHE_ITEM_SIZE = "cache.item_size";
+const SPAN_STATUS_UNSET = 0;
+const SPAN_STATUS_OK = 1;
+const SPAN_STATUS_ERROR = 2;
+function getSpanStatusFromHttpCode(httpStatus) {
+  if (httpStatus < 400 && httpStatus >= 100) {
+    return { code: SPAN_STATUS_OK };
+  }
+  if (httpStatus >= 400 && httpStatus < 500) {
+    switch (httpStatus) {
+      case 401:
+        return { code: SPAN_STATUS_ERROR, message: "unauthenticated" };
+      case 403:
+        return { code: SPAN_STATUS_ERROR, message: "permission_denied" };
+      case 404:
+        return { code: SPAN_STATUS_ERROR, message: "not_found" };
+      case 409:
+        return { code: SPAN_STATUS_ERROR, message: "already_exists" };
+      case 413:
+        return { code: SPAN_STATUS_ERROR, message: "failed_precondition" };
+      case 429:
+        return { code: SPAN_STATUS_ERROR, message: "resource_exhausted" };
+      case 499:
+        return { code: SPAN_STATUS_ERROR, message: "cancelled" };
+      default:
+        return { code: SPAN_STATUS_ERROR, message: "invalid_argument" };
+    }
+  }
+  if (httpStatus >= 500 && httpStatus < 600) {
+    switch (httpStatus) {
+      case 501:
+        return { code: SPAN_STATUS_ERROR, message: "unimplemented" };
+      case 503:
+        return { code: SPAN_STATUS_ERROR, message: "unavailable" };
+      case 504:
+        return { code: SPAN_STATUS_ERROR, message: "deadline_exceeded" };
+      default:
+        return { code: SPAN_STATUS_ERROR, message: "internal_error" };
+    }
+  }
+  return { code: SPAN_STATUS_ERROR, message: "internal_error" };
+}
+const SCOPE_ON_START_SPAN_FIELD = "_sentryScope";
+const ISOLATION_SCOPE_ON_START_SPAN_FIELD = "_sentryIsolationScope";
+function wrapScopeWithWeakRef(scope) {
+  try {
+    const WeakRefClass = GLOBAL_OBJ.WeakRef;
+    if (typeof WeakRefClass === "function") {
+      return new WeakRefClass(scope);
+    }
+  } catch {
+  }
+  return scope;
+}
+function unwrapScopeFromWeakRef(scopeRef) {
+  if (!scopeRef) {
+    return void 0;
+  }
+  if (typeof scopeRef === "object" && "deref" in scopeRef && typeof scopeRef.deref === "function") {
+    try {
+      return scopeRef.deref();
+    } catch {
+      return void 0;
+    }
+  }
+  return scopeRef;
+}
+function setCapturedScopesOnSpan(span, scope, isolationScope) {
+  if (span) {
+    addNonEnumerableProperty(span, ISOLATION_SCOPE_ON_START_SPAN_FIELD, wrapScopeWithWeakRef(isolationScope));
+    addNonEnumerableProperty(span, SCOPE_ON_START_SPAN_FIELD, scope);
+  }
+}
+function getCapturedScopesOnSpan(span) {
+  const spanWithScopes = span;
+  return {
+    scope: spanWithScopes[SCOPE_ON_START_SPAN_FIELD],
+    isolationScope: unwrapScopeFromWeakRef(spanWithScopes[ISOLATION_SCOPE_ON_START_SPAN_FIELD])
+  };
+}
+const SENTRY_BAGGAGE_KEY_PREFIX = "sentry-";
+const SENTRY_BAGGAGE_KEY_PREFIX_REGEX = /^sentry-/;
+const MAX_BAGGAGE_STRING_LENGTH = 8192;
+function baggageHeaderToDynamicSamplingContext(baggageHeader) {
+  const baggageObject = parseBaggageHeader(baggageHeader);
+  if (!baggageObject) {
+    return void 0;
+  }
+  const dynamicSamplingContext = Object.entries(baggageObject).reduce((acc, [key, value]) => {
+    if (key.match(SENTRY_BAGGAGE_KEY_PREFIX_REGEX)) {
+      const nonPrefixedKey = key.slice(SENTRY_BAGGAGE_KEY_PREFIX.length);
+      acc[nonPrefixedKey] = value;
+    }
+    return acc;
+  }, {});
+  if (Object.keys(dynamicSamplingContext).length > 0) {
+    return dynamicSamplingContext;
+  } else {
+    return void 0;
+  }
+}
+function dynamicSamplingContextToSentryBaggageHeader(dynamicSamplingContext) {
+  if (!dynamicSamplingContext) {
+    return void 0;
+  }
+  const sentryPrefixedDSC = Object.entries(dynamicSamplingContext).reduce(
+    (acc, [dscKey, dscValue]) => {
+      if (dscValue) {
+        acc[`${SENTRY_BAGGAGE_KEY_PREFIX}${dscKey}`] = dscValue;
+      }
+      return acc;
+    },
+    {}
+  );
+  return objectToBaggageHeader(sentryPrefixedDSC);
+}
+function parseBaggageHeader(baggageHeader) {
+  if (!baggageHeader || !isString(baggageHeader) && !Array.isArray(baggageHeader)) {
+    return void 0;
+  }
+  if (Array.isArray(baggageHeader)) {
+    return baggageHeader.reduce((acc, curr) => {
+      const currBaggageObject = baggageHeaderToObject(curr);
+      Object.entries(currBaggageObject).forEach(([key, value]) => {
+        acc[key] = value;
+      });
+      return acc;
+    }, {});
+  }
+  return baggageHeaderToObject(baggageHeader);
+}
+function baggageHeaderToObject(baggageHeader) {
+  return baggageHeader.split(",").map((baggageEntry) => {
+    const eqIdx = baggageEntry.indexOf("=");
+    if (eqIdx === -1) {
+      return [];
+    }
+    const key = baggageEntry.slice(0, eqIdx);
+    const value = baggageEntry.slice(eqIdx + 1);
+    return [key, value].map((keyOrValue) => {
+      try {
+        return decodeURIComponent(keyOrValue.trim());
+      } catch {
+        return;
+      }
+    });
+  }).reduce((acc, [key, value]) => {
+    if (key && value) {
+      acc[key] = value;
+    }
+    return acc;
+  }, {});
+}
+function objectToBaggageHeader(object) {
+  if (Object.keys(object).length === 0) {
+    return void 0;
+  }
+  return Object.entries(object).reduce((baggageHeader, [objectKey, objectValue], currentIndex) => {
+    const baggageEntry = `${encodeURIComponent(objectKey)}=${encodeURIComponent(objectValue)}`;
+    const newBaggageHeader = currentIndex === 0 ? baggageEntry : `${baggageHeader},${baggageEntry}`;
+    if (newBaggageHeader.length > MAX_BAGGAGE_STRING_LENGTH) {
+      DEBUG_BUILD && debug.warn(
+        `Not adding key: ${objectKey} with val: ${objectValue} to baggage header due to exceeding baggage size limits.`
+      );
+      return baggageHeader;
+    } else {
+      return newBaggageHeader;
+    }
+  }, "");
+}
+const ORG_ID_REGEX = /^o(\d+)\./;
+const DSN_REGEX = /^(?:(\w+):)\/\/(?:(\w+)(?::(\w+)?)?@)((?:\[[:.%\w]+\]|[\w.-]+))(?::(\d+))?\/(.+)/;
+function isValidProtocol(protocol) {
+  return protocol === "http" || protocol === "https";
+}
+function dsnToString(dsn, withPassword = false) {
+  const { host, path, pass, port, projectId, protocol, publicKey } = dsn;
+  return `${protocol}://${publicKey}${withPassword && pass ? `:${pass}` : ""}@${host}${port ? `:${port}` : ""}/${path ? `${path}/` : path}${projectId}`;
+}
+function dsnFromString(str) {
+  const match = DSN_REGEX.exec(str);
+  if (!match) {
+    consoleSandbox(() => {
+      console.error(`Invalid Sentry Dsn: ${str}`);
+    });
+    return void 0;
+  }
+  const [protocol, publicKey, pass = "", host = "", port = "", lastPath = ""] = match.slice(1);
+  let path = "";
+  let projectId = lastPath;
+  const split = projectId.split("/");
+  if (split.length > 1) {
+    path = split.slice(0, -1).join("/");
+    projectId = split.pop();
+  }
+  if (projectId) {
+    const projectMatch = projectId.match(/^\d+/);
+    if (projectMatch) {
+      projectId = projectMatch[0];
+    }
+  }
+  return dsnFromComponents({ host, pass, path, projectId, port, protocol, publicKey });
+}
+function dsnFromComponents(components) {
+  return {
+    protocol: components.protocol,
+    publicKey: components.publicKey || "",
+    pass: components.pass || "",
+    host: components.host,
+    port: components.port || "",
+    path: components.path || "",
+    projectId: components.projectId
+  };
+}
+function validateDsn(dsn) {
+  if (!DEBUG_BUILD) {
+    return true;
+  }
+  const { port, projectId, protocol } = dsn;
+  const requiredComponents = ["protocol", "publicKey", "host", "projectId"];
+  const hasMissingRequiredComponent = requiredComponents.find((component) => {
+    if (!dsn[component]) {
+      debug.error(`Invalid Sentry Dsn: ${component} missing`);
+      return true;
+    }
+    return false;
+  });
+  if (hasMissingRequiredComponent) {
+    return false;
+  }
+  if (!projectId.match(/^\d+$/)) {
+    debug.error(`Invalid Sentry Dsn: Invalid projectId ${projectId}`);
+    return false;
+  }
+  if (!isValidProtocol(protocol)) {
+    debug.error(`Invalid Sentry Dsn: Invalid protocol ${protocol}`);
+    return false;
+  }
+  if (port && isNaN(parseInt(port, 10))) {
+    debug.error(`Invalid Sentry Dsn: Invalid port ${port}`);
+    return false;
+  }
+  return true;
+}
+function extractOrgIdFromDsnHost(host) {
+  const match = host.match(ORG_ID_REGEX);
+  return match?.[1];
+}
+function extractOrgIdFromClient(client) {
+  const options = client.getOptions();
+  const { host } = client.getDsn() || {};
+  let org_id;
+  if (options.orgId) {
+    org_id = String(options.orgId);
+  } else if (host) {
+    org_id = extractOrgIdFromDsnHost(host);
+  }
+  return org_id;
+}
+function makeDsn(from) {
+  const components = typeof from === "string" ? dsnFromString(from) : dsnFromComponents(from);
+  if (!components || !validateDsn(components)) {
+    return void 0;
+  }
+  return components;
+}
+function parseSampleRate(sampleRate) {
+  if (typeof sampleRate === "boolean") {
+    return Number(sampleRate);
+  }
+  const rate = typeof sampleRate === "string" ? parseFloat(sampleRate) : sampleRate;
+  if (typeof rate !== "number" || isNaN(rate) || rate < 0 || rate > 1) {
+    return void 0;
+  }
+  return rate;
+}
+const TRACEPARENT_REGEXP = new RegExp(
+  "^[ \\t]*([0-9a-f]{32})?-?([0-9a-f]{16})?-?([01])?[ \\t]*$"
+  // whitespace
+);
+function extractTraceparentData(traceparent) {
+  if (!traceparent) {
+    return void 0;
+  }
+  const matches = traceparent.match(TRACEPARENT_REGEXP);
+  if (!matches) {
+    return void 0;
+  }
+  let parentSampled;
+  if (matches[3] === "1") {
+    parentSampled = true;
+  } else if (matches[3] === "0") {
+    parentSampled = false;
+  }
+  return {
+    traceId: matches[1],
+    parentSampled,
+    parentSpanId: matches[2]
+  };
+}
+function propagationContextFromHeaders(sentryTrace, baggage) {
+  const traceparentData = extractTraceparentData(sentryTrace);
+  const dynamicSamplingContext = baggageHeaderToDynamicSamplingContext(baggage);
+  if (!traceparentData?.traceId) {
+    return {
+      traceId: generateTraceId(),
+      sampleRand: Math.random()
+    };
+  }
+  const sampleRand = getSampleRandFromTraceparentAndDsc(traceparentData, dynamicSamplingContext);
+  if (dynamicSamplingContext) {
+    dynamicSamplingContext.sample_rand = sampleRand.toString();
+  }
+  const { traceId, parentSpanId, parentSampled } = traceparentData;
+  return {
+    traceId,
+    parentSpanId,
+    sampled: parentSampled,
+    dsc: dynamicSamplingContext || {},
+    // If we have traceparent data but no DSC it means we are not head of trace and we must freeze it
+    sampleRand
+  };
+}
+function generateSentryTraceHeader(traceId = generateTraceId(), spanId = generateSpanId(), sampled) {
+  let sampledString = "";
+  if (sampled !== void 0) {
+    sampledString = sampled ? "-1" : "-0";
+  }
+  return `${traceId}-${spanId}${sampledString}`;
+}
+function generateTraceparentHeader(traceId = generateTraceId(), spanId = generateSpanId(), sampled) {
+  return `00-${traceId}-${spanId}-${sampled ? "01" : "00"}`;
+}
+function getSampleRandFromTraceparentAndDsc(traceparentData, dsc) {
+  const parsedSampleRand = parseSampleRate(dsc?.sample_rand);
+  if (parsedSampleRand !== void 0) {
+    return parsedSampleRand;
+  }
+  const parsedSampleRate = parseSampleRate(dsc?.sample_rate);
+  if (parsedSampleRate && traceparentData?.parentSampled !== void 0) {
+    return traceparentData.parentSampled ? (
+      // Returns a sample rand with positive sampling decision [0, sampleRate)
+      Math.random() * parsedSampleRate
+    ) : (
+      // Returns a sample rand with negative sampling decision [sampleRate, 1)
+      parsedSampleRate + Math.random() * (1 - parsedSampleRate)
+    );
+  } else {
+    return Math.random();
+  }
+}
+function shouldContinueTrace(client, baggageOrgId) {
+  const clientOrgId = extractOrgIdFromClient(client);
+  if (baggageOrgId && clientOrgId && baggageOrgId !== clientOrgId) {
+    debug.log(
+      `Won't continue trace because org IDs don't match (incoming baggage: ${baggageOrgId}, SDK options: ${clientOrgId})`
+    );
+    return false;
+  }
+  const strictTraceContinuation = client.getOptions().strictTraceContinuation || false;
+  if (strictTraceContinuation) {
+    if (baggageOrgId && !clientOrgId || !baggageOrgId && clientOrgId) {
+      debug.log(
+        `Starting a new trace because strict trace continuation is enabled but one org ID is missing (incoming baggage: ${baggageOrgId}, Sentry client: ${clientOrgId})`
+      );
+      return false;
+    }
+  }
+  return true;
+}
+const TRACE_FLAG_NONE = 0;
+const TRACE_FLAG_SAMPLED = 1;
+let hasShownSpanDropWarning = false;
+function spanToTransactionTraceContext(span) {
+  const { spanId: span_id, traceId: trace_id } = span.spanContext();
+  const { data, op, parent_span_id, status, origin, links } = spanToJSON(span);
+  return {
+    parent_span_id,
+    span_id,
+    trace_id,
+    data,
+    op,
+    status,
+    origin,
+    links
+  };
+}
+function spanToTraceContext(span) {
+  const { spanId, traceId: trace_id, isRemote } = span.spanContext();
+  const parent_span_id = isRemote ? spanId : spanToJSON(span).parent_span_id;
+  const scope = getCapturedScopesOnSpan(span).scope;
+  const span_id = isRemote ? scope?.getPropagationContext().propagationSpanId || generateSpanId() : spanId;
+  return {
+    parent_span_id,
+    span_id,
+    trace_id
+  };
+}
+function spanToTraceHeader(span) {
+  const { traceId, spanId } = span.spanContext();
+  const sampled = spanIsSampled(span);
+  return generateSentryTraceHeader(traceId, spanId, sampled);
+}
+function spanToTraceparentHeader(span) {
+  const { traceId, spanId } = span.spanContext();
+  const sampled = spanIsSampled(span);
+  return generateTraceparentHeader(traceId, spanId, sampled);
+}
+function convertSpanLinksForEnvelope(links) {
+  if (links && links.length > 0) {
+    return links.map(({ context: { spanId, traceId, traceFlags, ...restContext }, attributes }) => ({
+      span_id: spanId,
+      trace_id: traceId,
+      sampled: traceFlags === TRACE_FLAG_SAMPLED,
+      attributes,
+      ...restContext
+    }));
+  } else {
+    return void 0;
+  }
+}
+function spanTimeInputToSeconds(input) {
+  if (typeof input === "number") {
+    return ensureTimestampInSeconds(input);
+  }
+  if (Array.isArray(input)) {
+    return input[0] + input[1] / 1e9;
+  }
+  if (input instanceof Date) {
+    return ensureTimestampInSeconds(input.getTime());
+  }
+  return timestampInSeconds();
+}
+function ensureTimestampInSeconds(timestamp) {
+  const isMs = timestamp > 9999999999;
+  return isMs ? timestamp / 1e3 : timestamp;
+}
+function spanToJSON(span) {
+  if (spanIsSentrySpan(span)) {
+    return span.getSpanJSON();
+  }
+  const { spanId: span_id, traceId: trace_id } = span.spanContext();
+  if (spanIsOpenTelemetrySdkTraceBaseSpan(span)) {
+    const { attributes, startTime, name, endTime, status, links } = span;
+    const parentSpanId = "parentSpanId" in span ? span.parentSpanId : "parentSpanContext" in span ? span.parentSpanContext?.spanId : void 0;
+    return {
+      span_id,
+      trace_id,
+      data: attributes,
+      description: name,
+      parent_span_id: parentSpanId,
+      start_timestamp: spanTimeInputToSeconds(startTime),
+      // This is [0,0] by default in OTEL, in which case we want to interpret this as no end time
+      timestamp: spanTimeInputToSeconds(endTime) || void 0,
+      status: getStatusMessage(status),
+      op: attributes[SEMANTIC_ATTRIBUTE_SENTRY_OP],
+      origin: attributes[SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN],
+      links: convertSpanLinksForEnvelope(links)
+    };
+  }
+  return {
+    span_id,
+    trace_id,
+    start_timestamp: 0,
+    data: {}
+  };
+}
+function spanIsOpenTelemetrySdkTraceBaseSpan(span) {
+  const castSpan = span;
+  return !!castSpan.attributes && !!castSpan.startTime && !!castSpan.name && !!castSpan.endTime && !!castSpan.status;
+}
+function spanIsSentrySpan(span) {
+  return typeof span.getSpanJSON === "function";
+}
+function spanIsSampled(span) {
+  const { traceFlags } = span.spanContext();
+  return traceFlags === TRACE_FLAG_SAMPLED;
+}
+function getStatusMessage(status) {
+  if (!status || status.code === SPAN_STATUS_UNSET) {
+    return void 0;
+  }
+  if (status.code === SPAN_STATUS_OK) {
+    return "ok";
+  }
+  return status.message || "internal_error";
+}
+const CHILD_SPANS_FIELD = "_sentryChildSpans";
+const ROOT_SPAN_FIELD = "_sentryRootSpan";
+function addChildSpanToSpan(span, childSpan) {
+  const rootSpan = span[ROOT_SPAN_FIELD] || span;
+  addNonEnumerableProperty(childSpan, ROOT_SPAN_FIELD, rootSpan);
+  if (span[CHILD_SPANS_FIELD]) {
+    span[CHILD_SPANS_FIELD].add(childSpan);
+  } else {
+    addNonEnumerableProperty(span, CHILD_SPANS_FIELD, /* @__PURE__ */ new Set([childSpan]));
+  }
+}
+function getSpanDescendants(span) {
+  const resultSet = /* @__PURE__ */ new Set();
+  function addSpanChildren(span2) {
+    if (resultSet.has(span2)) {
+      return;
+    } else if (spanIsSampled(span2)) {
+      resultSet.add(span2);
+      const childSpans = span2[CHILD_SPANS_FIELD] ? Array.from(span2[CHILD_SPANS_FIELD]) : [];
+      for (const childSpan of childSpans) {
+        addSpanChildren(childSpan);
+      }
+    }
+  }
+  addSpanChildren(span);
+  return Array.from(resultSet);
+}
+function getRootSpan(span) {
+  return span[ROOT_SPAN_FIELD] || span;
+}
+function getActiveSpan() {
+  const carrier = getMainCarrier();
+  const acs = getAsyncContextStrategy(carrier);
+  if (acs.getActiveSpan) {
+    return acs.getActiveSpan();
+  }
+  return _getSpanForScope(getCurrentScope());
+}
+function showSpanDropWarning() {
+  if (!hasShownSpanDropWarning) {
+    consoleSandbox(() => {
+      console.warn(
+        "[Sentry] Returning null from `beforeSendSpan` is disallowed. To drop certain spans, configure the respective integrations directly or use `ignoreSpans`."
+      );
+    });
+    hasShownSpanDropWarning = true;
+  }
+}
+function hasSpansEnabled(maybeOptions) {
+  if (typeof __SENTRY_TRACING__ === "boolean" && !__SENTRY_TRACING__) {
+    return false;
+  }
+  const options = maybeOptions || getClient()?.getOptions();
+  return !!options && // Note: This check is `!= null`, meaning "nullish". `0` is not "nullish", `undefined` and `null` are. (This comment was brought to you by 15 minutes of questioning life)
+  (options.tracesSampleRate != null || !!options.tracesSampler);
+}
+function logIgnoredSpan(droppedSpan) {
+  debug.log(`Ignoring span ${droppedSpan.op} - ${droppedSpan.description} because it matches \`ignoreSpans\`.`);
+}
+function shouldIgnoreSpan(span, ignoreSpans) {
+  if (!ignoreSpans?.length || !span.description) {
+    return false;
+  }
+  for (const pattern2 of ignoreSpans) {
+    if (isStringOrRegExp(pattern2)) {
+      if (isMatchingPattern(span.description, pattern2)) {
+        DEBUG_BUILD && logIgnoredSpan(span);
+        return true;
+      }
+      continue;
+    }
+    if (!pattern2.name && !pattern2.op) {
+      continue;
+    }
+    const nameMatches = pattern2.name ? isMatchingPattern(span.description, pattern2.name) : true;
+    const opMatches = pattern2.op ? span.op && isMatchingPattern(span.op, pattern2.op) : true;
+    if (nameMatches && opMatches) {
+      DEBUG_BUILD && logIgnoredSpan(span);
+      return true;
+    }
+  }
+  return false;
+}
+function reparentChildSpans(spans, dropSpan) {
+  const droppedSpanParentId = dropSpan.parent_span_id;
+  const droppedSpanId = dropSpan.span_id;
+  if (!droppedSpanParentId) {
+    return;
+  }
+  for (const span of spans) {
+    if (span.parent_span_id === droppedSpanId) {
+      span.parent_span_id = droppedSpanParentId;
+    }
+  }
+}
+function isStringOrRegExp(value) {
+  return typeof value === "string" || value instanceof RegExp;
+}
+const DEFAULT_ENVIRONMENT = "production";
+const FROZEN_DSC_FIELD = "_frozenDsc";
+function freezeDscOnSpan(span, dsc) {
+  const spanWithMaybeDsc = span;
+  addNonEnumerableProperty(spanWithMaybeDsc, FROZEN_DSC_FIELD, dsc);
+}
+function getDynamicSamplingContextFromClient(trace_id, client) {
+  const options = client.getOptions();
+  const { publicKey: public_key } = client.getDsn() || {};
+  const dsc = {
+    environment: options.environment || DEFAULT_ENVIRONMENT,
+    release: options.release,
+    public_key,
+    trace_id,
+    org_id: extractOrgIdFromClient(client)
+  };
+  client.emit("createDsc", dsc);
+  return dsc;
+}
+function getDynamicSamplingContextFromScope(client, scope) {
+  const propagationContext = scope.getPropagationContext();
+  return propagationContext.dsc || getDynamicSamplingContextFromClient(propagationContext.traceId, client);
+}
+function getDynamicSamplingContextFromSpan(span) {
+  const client = getClient();
+  if (!client) {
+    return {};
+  }
+  const rootSpan = getRootSpan(span);
+  const rootSpanJson = spanToJSON(rootSpan);
+  const rootSpanAttributes = rootSpanJson.data;
+  const traceState = rootSpan.spanContext().traceState;
+  const rootSpanSampleRate = traceState?.get("sentry.sample_rate") ?? rootSpanAttributes[SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE] ?? rootSpanAttributes[SEMANTIC_ATTRIBUTE_SENTRY_PREVIOUS_TRACE_SAMPLE_RATE];
+  function applyLocalSampleRateToDsc(dsc2) {
+    if (typeof rootSpanSampleRate === "number" || typeof rootSpanSampleRate === "string") {
+      dsc2.sample_rate = `${rootSpanSampleRate}`;
+    }
+    return dsc2;
+  }
+  const frozenDsc = rootSpan[FROZEN_DSC_FIELD];
+  if (frozenDsc) {
+    return applyLocalSampleRateToDsc(frozenDsc);
+  }
+  const traceStateDsc = traceState?.get("sentry.dsc");
+  const dscOnTraceState = traceStateDsc && baggageHeaderToDynamicSamplingContext(traceStateDsc);
+  if (dscOnTraceState) {
+    return applyLocalSampleRateToDsc(dscOnTraceState);
+  }
+  const dsc = getDynamicSamplingContextFromClient(span.spanContext().traceId, client);
+  const source = rootSpanAttributes[SEMANTIC_ATTRIBUTE_SENTRY_SOURCE];
+  const name = rootSpanJson.description;
+  if (source !== "url" && name) {
+    dsc.transaction = name;
+  }
+  if (hasSpansEnabled()) {
+    dsc.sampled = String(spanIsSampled(rootSpan));
+    dsc.sample_rand = // In OTEL we store the sample rand on the trace state because we cannot access scopes for NonRecordingSpans
+    // The Sentry OTEL SpanSampler takes care of writing the sample rand on the root span
+    traceState?.get("sentry.sample_rand") ?? // On all other platforms we can actually get the scopes from a root span (we use this as a fallback)
+    getCapturedScopesOnSpan(rootSpan).scope?.getPropagationContext().sampleRand.toString();
+  }
+  applyLocalSampleRateToDsc(dsc);
+  client.emit("createDsc", dsc, rootSpan);
+  return dsc;
+}
+class SentryNonRecordingSpan {
+  constructor(spanContext = {}) {
+    this._traceId = spanContext.traceId || generateTraceId();
+    this._spanId = spanContext.spanId || generateSpanId();
+  }
+  /** @inheritdoc */
+  spanContext() {
+    return {
+      spanId: this._spanId,
+      traceId: this._traceId,
+      traceFlags: TRACE_FLAG_NONE
+    };
+  }
+  /** @inheritdoc */
+  end(_timestamp) {
+  }
+  /** @inheritdoc */
+  setAttribute(_key, _value) {
+    return this;
+  }
+  /** @inheritdoc */
+  setAttributes(_values) {
+    return this;
+  }
+  /** @inheritdoc */
+  setStatus(_status) {
+    return this;
+  }
+  /** @inheritdoc */
+  updateName(_name) {
+    return this;
+  }
+  /** @inheritdoc */
+  isRecording() {
+    return false;
+  }
+  /** @inheritdoc */
+  addEvent(_name, _attributesOrStartTime, _startTime) {
+    return this;
+  }
+  /** @inheritDoc */
+  addLink(_link) {
+    return this;
+  }
+  /** @inheritDoc */
+  addLinks(_links) {
+    return this;
+  }
+  /**
+   * This should generally not be used,
+   * but we need it for being compliant with the OTEL Span interface.
+   *
+   * @hidden
+   * @internal
+   */
+  recordException(_exception, _time) {
+  }
+}
+function normalize$1(input, depth = 100, maxProperties = Infinity) {
+  try {
+    return visit("", input, depth, maxProperties);
+  } catch (err) {
+    return { ERROR: `**non-serializable** (${err})` };
+  }
+}
+function normalizeToSize(object, depth = 3, maxSize = 100 * 1024) {
+  const normalized = normalize$1(object, depth);
+  if (jsonSize(normalized) > maxSize) {
+    return normalizeToSize(object, depth - 1, maxSize);
+  }
+  return normalized;
+}
+function visit(key, value, depth = Infinity, maxProperties = Infinity, memo = memoBuilder()) {
+  const [memoize, unmemoize] = memo;
+  if (value == null || // this matches null and undefined -> eqeq not eqeqeq
+  ["boolean", "string"].includes(typeof value) || typeof value === "number" && Number.isFinite(value)) {
+    return value;
+  }
+  const stringified = stringifyValue(key, value);
+  if (!stringified.startsWith("[object ")) {
+    return stringified;
+  }
+  if (value["__sentry_skip_normalization__"]) {
+    return value;
+  }
+  const remainingDepth = typeof value["__sentry_override_normalization_depth__"] === "number" ? value["__sentry_override_normalization_depth__"] : depth;
+  if (remainingDepth === 0) {
+    return stringified.replace("object ", "");
+  }
+  if (memoize(value)) {
+    return "[Circular ~]";
+  }
+  const valueWithToJSON = value;
+  if (valueWithToJSON && typeof valueWithToJSON.toJSON === "function") {
+    try {
+      const jsonValue = valueWithToJSON.toJSON();
+      return visit("", jsonValue, remainingDepth - 1, maxProperties, memo);
+    } catch {
+    }
+  }
+  const normalized = Array.isArray(value) ? [] : {};
+  let numAdded = 0;
+  const visitable = convertToPlainObject(value);
+  for (const visitKey in visitable) {
+    if (!Object.prototype.hasOwnProperty.call(visitable, visitKey)) {
+      continue;
+    }
+    if (numAdded >= maxProperties) {
+      normalized[visitKey] = "[MaxProperties ~]";
+      break;
+    }
+    const visitValue = visitable[visitKey];
+    normalized[visitKey] = visit(visitKey, visitValue, remainingDepth - 1, maxProperties, memo);
+    numAdded++;
+  }
+  unmemoize(value);
+  return normalized;
+}
+function stringifyValue(key, value) {
+  try {
+    if (key === "domain" && value && typeof value === "object" && value._events) {
+      return "[Domain]";
+    }
+    if (key === "domainEmitter") {
+      return "[DomainEmitter]";
+    }
+    if (typeof global !== "undefined" && value === global) {
+      return "[Global]";
+    }
+    if (typeof window !== "undefined" && value === window) {
+      return "[Window]";
+    }
+    if (typeof document !== "undefined" && value === document) {
+      return "[Document]";
+    }
+    if (isVueViewModel(value)) {
+      return getVueInternalName(value);
+    }
+    if (isSyntheticEvent(value)) {
+      return "[SyntheticEvent]";
+    }
+    if (typeof value === "number" && !Number.isFinite(value)) {
+      return `[${value}]`;
+    }
+    if (typeof value === "function") {
+      return `[Function: ${getFunctionName(value)}]`;
+    }
+    if (typeof value === "symbol") {
+      return `[${String(value)}]`;
+    }
+    if (typeof value === "bigint") {
+      return `[BigInt: ${String(value)}]`;
+    }
+    const objName = getConstructorName(value);
+    if (/^HTML(\w*)Element$/.test(objName)) {
+      return `[HTMLElement: ${objName}]`;
+    }
+    return `[object ${objName}]`;
+  } catch (err) {
+    return `**non-serializable** (${err})`;
+  }
+}
+function getConstructorName(value) {
+  const prototype = Object.getPrototypeOf(value);
+  return prototype?.constructor ? prototype.constructor.name : "null prototype";
+}
+function utf8Length(value) {
+  return ~-encodeURI(value).split(/%..|./).length;
+}
+function jsonSize(value) {
+  return utf8Length(JSON.stringify(value));
+}
+function memoBuilder() {
+  const inner = /* @__PURE__ */ new WeakSet();
+  function memoize(obj) {
+    if (inner.has(obj)) {
+      return true;
+    }
+    inner.add(obj);
+    return false;
+  }
+  function unmemoize(obj) {
+    inner.delete(obj);
+  }
+  return [memoize, unmemoize];
+}
+function createEnvelope(headers, items = []) {
+  return [headers, items];
+}
+function addItemToEnvelope(envelope, newItem) {
+  const [headers, items] = envelope;
+  return [headers, [...items, newItem]];
+}
+function forEachEnvelopeItem(envelope, callback) {
+  const envelopeItems = envelope[1];
+  for (const envelopeItem of envelopeItems) {
+    const envelopeItemType = envelopeItem[0].type;
+    const result = callback(envelopeItem, envelopeItemType);
+    if (result) {
+      return true;
+    }
+  }
+  return false;
+}
+function encodeUTF8(input) {
+  const carrier = getSentryCarrier(GLOBAL_OBJ);
+  return carrier.encodePolyfill ? carrier.encodePolyfill(input) : new TextEncoder().encode(input);
+}
+function serializeEnvelope(envelope) {
+  const [envHeaders, items] = envelope;
+  let parts = JSON.stringify(envHeaders);
+  function append(next) {
+    if (typeof parts === "string") {
+      parts = typeof next === "string" ? parts + next : [encodeUTF8(parts), next];
+    } else {
+      parts.push(typeof next === "string" ? encodeUTF8(next) : next);
+    }
+  }
+  for (const item of items) {
+    const [itemHeaders, payload] = item;
+    append(`
+${JSON.stringify(itemHeaders)}
+`);
+    if (typeof payload === "string" || payload instanceof Uint8Array) {
+      append(payload);
+    } else {
+      let stringifiedPayload;
+      try {
+        stringifiedPayload = JSON.stringify(payload);
+      } catch {
+        stringifiedPayload = JSON.stringify(normalize$1(payload));
+      }
+      append(stringifiedPayload);
+    }
+  }
+  return typeof parts === "string" ? parts : concatBuffers(parts);
+}
+function concatBuffers(buffers) {
+  const totalLength = buffers.reduce((acc, buf) => acc + buf.length, 0);
+  const merged = new Uint8Array(totalLength);
+  let offset = 0;
+  for (const buffer of buffers) {
+    merged.set(buffer, offset);
+    offset += buffer.length;
+  }
+  return merged;
+}
+function createSpanEnvelopeItem(spanJson) {
+  const spanHeaders = {
+    type: "span"
+  };
+  return [spanHeaders, spanJson];
+}
+function createAttachmentEnvelopeItem(attachment) {
+  const buffer = typeof attachment.data === "string" ? encodeUTF8(attachment.data) : attachment.data;
+  return [
+    {
+      type: "attachment",
+      length: buffer.length,
+      filename: attachment.filename,
+      content_type: attachment.contentType,
+      attachment_type: attachment.attachmentType
+    },
+    buffer
+  ];
+}
+const ITEM_TYPE_TO_DATA_CATEGORY_MAP = {
+  session: "session",
+  sessions: "session",
+  attachment: "attachment",
+  transaction: "transaction",
+  event: "error",
+  client_report: "internal",
+  user_report: "default",
+  profile: "profile",
+  profile_chunk: "profile",
+  replay_event: "replay",
+  replay_recording: "replay",
+  check_in: "monitor",
+  feedback: "feedback",
+  span: "span",
+  raw_security: "security",
+  log: "log_item",
+  metric: "metric",
+  trace_metric: "metric"
+};
+function envelopeItemTypeToDataCategory(type) {
+  return ITEM_TYPE_TO_DATA_CATEGORY_MAP[type];
+}
+function getSdkMetadataForEnvelopeHeader(metadataOrEvent) {
+  if (!metadataOrEvent?.sdk) {
+    return;
+  }
+  const { name, version } = metadataOrEvent.sdk;
+  return { name, version };
+}
+function createEventEnvelopeHeaders(event, sdkInfo, tunnel, dsn) {
+  const dynamicSamplingContext = event.sdkProcessingMetadata?.dynamicSamplingContext;
+  return {
+    event_id: event.event_id,
+    sent_at: (/* @__PURE__ */ new Date()).toISOString(),
+    ...sdkInfo && { sdk: sdkInfo },
+    ...!!tunnel && dsn && { dsn: dsnToString(dsn) },
+    ...dynamicSamplingContext && {
+      trace: dynamicSamplingContext
+    }
+  };
+}
+function _enhanceEventWithSdkInfo(event, newSdkInfo) {
+  if (!newSdkInfo) {
+    return event;
+  }
+  const eventSdkInfo = event.sdk || {};
+  event.sdk = {
+    ...eventSdkInfo,
+    name: eventSdkInfo.name || newSdkInfo.name,
+    version: eventSdkInfo.version || newSdkInfo.version,
+    integrations: [...event.sdk?.integrations || [], ...newSdkInfo.integrations || []],
+    packages: [...event.sdk?.packages || [], ...newSdkInfo.packages || []],
+    settings: event.sdk?.settings || newSdkInfo.settings ? {
+      ...event.sdk?.settings,
+      ...newSdkInfo.settings
+    } : void 0
+  };
+  return event;
+}
+function createSessionEnvelope(session, dsn, metadata, tunnel) {
+  const sdkInfo = getSdkMetadataForEnvelopeHeader(metadata);
+  const envelopeHeaders = {
+    sent_at: (/* @__PURE__ */ new Date()).toISOString(),
+    ...sdkInfo && { sdk: sdkInfo },
+    ...!!tunnel && dsn && { dsn: dsnToString(dsn) }
+  };
+  const envelopeItem = "aggregates" in session ? [{ type: "sessions" }, session] : [{ type: "session" }, session.toJSON()];
+  return createEnvelope(envelopeHeaders, [envelopeItem]);
+}
+function createEventEnvelope(event, dsn, metadata, tunnel) {
+  const sdkInfo = getSdkMetadataForEnvelopeHeader(metadata);
+  const eventType = event.type && event.type !== "replay_event" ? event.type : "event";
+  _enhanceEventWithSdkInfo(event, metadata?.sdk);
+  const envelopeHeaders = createEventEnvelopeHeaders(event, sdkInfo, tunnel, dsn);
+  delete event.sdkProcessingMetadata;
+  const eventItem = [{ type: eventType }, event];
+  return createEnvelope(envelopeHeaders, [eventItem]);
+}
+function createSpanEnvelope(spans, client) {
+  function dscHasRequiredProps(dsc2) {
+    return !!dsc2.trace_id && !!dsc2.public_key;
+  }
+  const dsc = getDynamicSamplingContextFromSpan(spans[0]);
+  const dsn = client?.getDsn();
+  const tunnel = client?.getOptions().tunnel;
+  const headers = {
+    sent_at: (/* @__PURE__ */ new Date()).toISOString(),
+    ...dscHasRequiredProps(dsc) && { trace: dsc },
+    ...!!tunnel && dsn && { dsn: dsnToString(dsn) }
+  };
+  const { beforeSendSpan, ignoreSpans } = client?.getOptions() || {};
+  const filteredSpans = ignoreSpans?.length ? spans.filter((span) => !shouldIgnoreSpan(spanToJSON(span), ignoreSpans)) : spans;
+  const droppedSpans = spans.length - filteredSpans.length;
+  if (droppedSpans) {
+    client?.recordDroppedEvent("before_send", "span", droppedSpans);
+  }
+  const convertToSpanJSON = beforeSendSpan ? (span) => {
+    const spanJson = spanToJSON(span);
+    const processedSpan = beforeSendSpan(spanJson);
+    if (!processedSpan) {
+      showSpanDropWarning();
+      return spanJson;
+    }
+    return processedSpan;
+  } : spanToJSON;
+  const items = [];
+  for (const span of filteredSpans) {
+    const spanJson = convertToSpanJSON(span);
+    if (spanJson) {
+      items.push(createSpanEnvelopeItem(spanJson));
+    }
+  }
+  return createEnvelope(headers, items);
+}
+function logSpanStart(span) {
+  if (!DEBUG_BUILD) return;
+  const { description = "< unknown name >", op = "< unknown op >", parent_span_id: parentSpanId } = spanToJSON(span);
+  const { spanId } = span.spanContext();
+  const sampled = spanIsSampled(span);
+  const rootSpan = getRootSpan(span);
+  const isRootSpan = rootSpan === span;
+  const header = `[Tracing] Starting ${sampled ? "sampled" : "unsampled"} ${isRootSpan ? "root " : ""}span`;
+  const infoParts = [`op: ${op}`, `name: ${description}`, `ID: ${spanId}`];
+  if (parentSpanId) {
+    infoParts.push(`parent ID: ${parentSpanId}`);
+  }
+  if (!isRootSpan) {
+    const { op: op2, description: description2 } = spanToJSON(rootSpan);
+    infoParts.push(`root ID: ${rootSpan.spanContext().spanId}`);
+    if (op2) {
+      infoParts.push(`root op: ${op2}`);
+    }
+    if (description2) {
+      infoParts.push(`root description: ${description2}`);
+    }
+  }
+  debug.log(`${header}
+  ${infoParts.join("\n  ")}`);
+}
+function logSpanEnd(span) {
+  if (!DEBUG_BUILD) return;
+  const { description = "< unknown name >", op = "< unknown op >" } = spanToJSON(span);
+  const { spanId } = span.spanContext();
+  const rootSpan = getRootSpan(span);
+  const isRootSpan = rootSpan === span;
+  const msg = `[Tracing] Finishing "${op}" ${isRootSpan ? "root " : ""}span "${description}" with ID ${spanId}`;
+  debug.log(msg);
+}
+function timedEventsToMeasurements(events) {
+  if (!events || events.length === 0) {
+    return void 0;
+  }
+  const measurements = {};
+  events.forEach((event) => {
+    const attributes = event.attributes || {};
+    const unit = attributes[SEMANTIC_ATTRIBUTE_SENTRY_MEASUREMENT_UNIT];
+    const value = attributes[SEMANTIC_ATTRIBUTE_SENTRY_MEASUREMENT_VALUE];
+    if (typeof unit === "string" && typeof value === "number") {
+      measurements[event.name] = { value, unit };
+    }
+  });
+  return measurements;
+}
+const MAX_SPAN_COUNT = 1e3;
+class SentrySpan {
+  /** Epoch timestamp in seconds when the span started. */
+  /** Epoch timestamp in seconds when the span ended. */
+  /** Internal keeper of the status */
+  /** The timed events added to this span. */
+  /** if true, treat span as a standalone span (not part of a transaction) */
+  /**
+   * You should never call the constructor manually, always use `Sentry.startSpan()`
+   * or other span methods.
+   * @internal
+   * @hideconstructor
+   * @hidden
+   */
+  constructor(spanContext = {}) {
+    this._traceId = spanContext.traceId || generateTraceId();
+    this._spanId = spanContext.spanId || generateSpanId();
+    this._startTime = spanContext.startTimestamp || timestampInSeconds();
+    this._links = spanContext.links;
+    this._attributes = {};
+    this.setAttributes({
+      [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: "manual",
+      [SEMANTIC_ATTRIBUTE_SENTRY_OP]: spanContext.op,
+      ...spanContext.attributes
+    });
+    this._name = spanContext.name;
+    if (spanContext.parentSpanId) {
+      this._parentSpanId = spanContext.parentSpanId;
+    }
+    if ("sampled" in spanContext) {
+      this._sampled = spanContext.sampled;
+    }
+    if (spanContext.endTimestamp) {
+      this._endTime = spanContext.endTimestamp;
+    }
+    this._events = [];
+    this._isStandaloneSpan = spanContext.isStandalone;
+    if (this._endTime) {
+      this._onSpanEnded();
+    }
+  }
+  /** @inheritDoc */
+  addLink(link) {
+    if (this._links) {
+      this._links.push(link);
+    } else {
+      this._links = [link];
+    }
+    return this;
+  }
+  /** @inheritDoc */
+  addLinks(links) {
+    if (this._links) {
+      this._links.push(...links);
+    } else {
+      this._links = links;
+    }
+    return this;
+  }
+  /**
+   * This should generally not be used,
+   * but it is needed for being compliant with the OTEL Span interface.
+   *
+   * @hidden
+   * @internal
+   */
+  recordException(_exception, _time) {
+  }
+  /** @inheritdoc */
+  spanContext() {
+    const { _spanId: spanId, _traceId: traceId, _sampled: sampled } = this;
+    return {
+      spanId,
+      traceId,
+      traceFlags: sampled ? TRACE_FLAG_SAMPLED : TRACE_FLAG_NONE
+    };
+  }
+  /** @inheritdoc */
+  setAttribute(key, value) {
+    if (value === void 0) {
+      delete this._attributes[key];
+    } else {
+      this._attributes[key] = value;
+    }
+    return this;
+  }
+  /** @inheritdoc */
+  setAttributes(attributes) {
+    Object.keys(attributes).forEach((key) => this.setAttribute(key, attributes[key]));
+    return this;
+  }
+  /**
+   * This should generally not be used,
+   * but we need it for browser tracing where we want to adjust the start time afterwards.
+   * USE THIS WITH CAUTION!
+   *
+   * @hidden
+   * @internal
+   */
+  updateStartTime(timeInput) {
+    this._startTime = spanTimeInputToSeconds(timeInput);
+  }
+  /**
+   * @inheritDoc
+   */
+  setStatus(value) {
+    this._status = value;
+    return this;
+  }
+  /**
+   * @inheritDoc
+   */
+  updateName(name) {
+    this._name = name;
+    this.setAttribute(SEMANTIC_ATTRIBUTE_SENTRY_SOURCE, "custom");
+    return this;
+  }
+  /** @inheritdoc */
+  end(endTimestamp) {
+    if (this._endTime) {
+      return;
+    }
+    this._endTime = spanTimeInputToSeconds(endTimestamp);
+    logSpanEnd(this);
+    this._onSpanEnded();
+  }
+  /**
+   * Get JSON representation of this span.
+   *
+   * @hidden
+   * @internal This method is purely for internal purposes and should not be used outside
+   * of SDK code. If you need to get a JSON representation of a span,
+   * use `spanToJSON(span)` instead.
+   */
+  getSpanJSON() {
+    return {
+      data: this._attributes,
+      description: this._name,
+      op: this._attributes[SEMANTIC_ATTRIBUTE_SENTRY_OP],
+      parent_span_id: this._parentSpanId,
+      span_id: this._spanId,
+      start_timestamp: this._startTime,
+      status: getStatusMessage(this._status),
+      timestamp: this._endTime,
+      trace_id: this._traceId,
+      origin: this._attributes[SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN],
+      profile_id: this._attributes[SEMANTIC_ATTRIBUTE_PROFILE_ID],
+      exclusive_time: this._attributes[SEMANTIC_ATTRIBUTE_EXCLUSIVE_TIME],
+      measurements: timedEventsToMeasurements(this._events),
+      is_segment: this._isStandaloneSpan && getRootSpan(this) === this || void 0,
+      segment_id: this._isStandaloneSpan ? getRootSpan(this).spanContext().spanId : void 0,
+      links: convertSpanLinksForEnvelope(this._links)
+    };
+  }
+  /** @inheritdoc */
+  isRecording() {
+    return !this._endTime && !!this._sampled;
+  }
+  /**
+   * @inheritdoc
+   */
+  addEvent(name, attributesOrStartTime, startTime) {
+    DEBUG_BUILD && debug.log("[Tracing] Adding an event to span:", name);
+    const time = isSpanTimeInput(attributesOrStartTime) ? attributesOrStartTime : startTime || timestampInSeconds();
+    const attributes = isSpanTimeInput(attributesOrStartTime) ? {} : attributesOrStartTime || {};
+    const event = {
+      name,
+      time: spanTimeInputToSeconds(time),
+      attributes
+    };
+    this._events.push(event);
+    return this;
+  }
+  /**
+   * This method should generally not be used,
+   * but for now we need a way to publicly check if the `_isStandaloneSpan` flag is set.
+   * USE THIS WITH CAUTION!
+   * @internal
+   * @hidden
+   * @experimental
+   */
+  isStandaloneSpan() {
+    return !!this._isStandaloneSpan;
+  }
+  /** Emit `spanEnd` when the span is ended. */
+  _onSpanEnded() {
+    const client = getClient();
+    if (client) {
+      client.emit("spanEnd", this);
+    }
+    const isSegmentSpan = this._isStandaloneSpan || this === getRootSpan(this);
+    if (!isSegmentSpan) {
+      return;
+    }
+    if (this._isStandaloneSpan) {
+      if (this._sampled) {
+        sendSpanEnvelope(createSpanEnvelope([this], client));
+      } else {
+        DEBUG_BUILD && debug.log("[Tracing] Discarding standalone span because its trace was not chosen to be sampled.");
+        if (client) {
+          client.recordDroppedEvent("sample_rate", "span");
+        }
+      }
+      return;
+    }
+    const transactionEvent = this._convertSpanToTransaction();
+    if (transactionEvent) {
+      const scope = getCapturedScopesOnSpan(this).scope || getCurrentScope();
+      scope.captureEvent(transactionEvent);
+    }
+  }
+  /**
+   * Finish the transaction & prepare the event to send to Sentry.
+   */
+  _convertSpanToTransaction() {
+    if (!isFullFinishedSpan(spanToJSON(this))) {
+      return void 0;
+    }
+    if (!this._name) {
+      DEBUG_BUILD && debug.warn("Transaction has no name, falling back to ``.");
+      this._name = "";
+    }
+    const { scope: capturedSpanScope, isolationScope: capturedSpanIsolationScope } = getCapturedScopesOnSpan(this);
+    const normalizedRequest = capturedSpanScope?.getScopeData().sdkProcessingMetadata?.normalizedRequest;
+    if (this._sampled !== true) {
+      return void 0;
+    }
+    const finishedSpans = getSpanDescendants(this).filter((span) => span !== this && !isStandaloneSpan(span));
+    const spans = finishedSpans.map((span) => spanToJSON(span)).filter(isFullFinishedSpan);
+    const source = this._attributes[SEMANTIC_ATTRIBUTE_SENTRY_SOURCE];
+    delete this._attributes[SEMANTIC_ATTRIBUTE_SENTRY_CUSTOM_SPAN_NAME];
+    spans.forEach((span) => {
+      delete span.data[SEMANTIC_ATTRIBUTE_SENTRY_CUSTOM_SPAN_NAME];
+    });
+    const transaction = {
+      contexts: {
+        trace: spanToTransactionTraceContext(this)
+      },
+      spans: (
+        // spans.sort() mutates the array, but `spans` is already a copy so we can safely do this here
+        // we do not use spans anymore after this point
+        spans.length > MAX_SPAN_COUNT ? spans.sort((a, b2) => a.start_timestamp - b2.start_timestamp).slice(0, MAX_SPAN_COUNT) : spans
+      ),
+      start_timestamp: this._startTime,
+      timestamp: this._endTime,
+      transaction: this._name,
+      type: "transaction",
+      sdkProcessingMetadata: {
+        capturedSpanScope,
+        capturedSpanIsolationScope,
+        dynamicSamplingContext: getDynamicSamplingContextFromSpan(this)
+      },
+      request: normalizedRequest,
+      ...source && {
+        transaction_info: {
+          source
+        }
+      }
+    };
+    const measurements = timedEventsToMeasurements(this._events);
+    const hasMeasurements = measurements && Object.keys(measurements).length;
+    if (hasMeasurements) {
+      DEBUG_BUILD && debug.log(
+        "[Measurements] Adding measurements to transaction event",
+        JSON.stringify(measurements, void 0, 2)
+      );
+      transaction.measurements = measurements;
+    }
+    return transaction;
+  }
+}
+function isSpanTimeInput(value) {
+  return value && typeof value === "number" || value instanceof Date || Array.isArray(value);
+}
+function isFullFinishedSpan(input) {
+  return !!input.start_timestamp && !!input.timestamp && !!input.span_id && !!input.trace_id;
+}
+function isStandaloneSpan(span) {
+  return span instanceof SentrySpan && span.isStandaloneSpan();
+}
+function sendSpanEnvelope(envelope) {
+  const client = getClient();
+  if (!client) {
+    return;
+  }
+  const spanItems = envelope[1];
+  if (!spanItems || spanItems.length === 0) {
+    client.recordDroppedEvent("before_send", "span");
+    return;
+  }
+  client.sendEnvelope(envelope);
+}
+function handleCallbackErrors(fn2, onError, onFinally = () => {
+}, onSuccess = () => {
+}) {
+  let maybePromiseResult;
+  try {
+    maybePromiseResult = fn2();
+  } catch (e) {
+    onError(e);
+    onFinally();
+    throw e;
+  }
+  return maybeHandlePromiseRejection(maybePromiseResult, onError, onFinally, onSuccess);
+}
+function maybeHandlePromiseRejection(value, onError, onFinally, onSuccess) {
+  if (isThenable(value)) {
+    return value.then(
+      (res) => {
+        onFinally();
+        onSuccess(res);
+        return res;
+      },
+      (e) => {
+        onError(e);
+        onFinally();
+        throw e;
+      }
+    );
+  }
+  onFinally();
+  onSuccess(value);
+  return value;
+}
+function sampleSpan(options, samplingContext, sampleRand) {
+  if (!hasSpansEnabled(options)) {
+    return [false];
+  }
+  let localSampleRateWasApplied = void 0;
+  let sampleRate;
+  if (typeof options.tracesSampler === "function") {
+    sampleRate = options.tracesSampler({
+      ...samplingContext,
+      inheritOrSampleWith: (fallbackSampleRate) => {
+        if (typeof samplingContext.parentSampleRate === "number") {
+          return samplingContext.parentSampleRate;
+        }
+        if (typeof samplingContext.parentSampled === "boolean") {
+          return Number(samplingContext.parentSampled);
+        }
+        return fallbackSampleRate;
+      }
+    });
+    localSampleRateWasApplied = true;
+  } else if (samplingContext.parentSampled !== void 0) {
+    sampleRate = samplingContext.parentSampled;
+  } else if (typeof options.tracesSampleRate !== "undefined") {
+    sampleRate = options.tracesSampleRate;
+    localSampleRateWasApplied = true;
+  }
+  const parsedSampleRate = parseSampleRate(sampleRate);
+  if (parsedSampleRate === void 0) {
+    DEBUG_BUILD && debug.warn(
+      `[Tracing] Discarding root span because of invalid sample rate. Sample rate must be a boolean or a number between 0 and 1. Got ${JSON.stringify(
+        sampleRate
+      )} of type ${JSON.stringify(typeof sampleRate)}.`
+    );
+    return [false];
+  }
+  if (!parsedSampleRate) {
+    DEBUG_BUILD && debug.log(
+      `[Tracing] Discarding transaction because ${typeof options.tracesSampler === "function" ? "tracesSampler returned 0 or false" : "a negative sampling decision was inherited or tracesSampleRate is set to 0"}`
+    );
+    return [false, parsedSampleRate, localSampleRateWasApplied];
+  }
+  const shouldSample = sampleRand < parsedSampleRate;
+  if (!shouldSample) {
+    DEBUG_BUILD && debug.log(
+      `[Tracing] Discarding transaction because it's not included in the random sample (sampling rate = ${Number(
+        sampleRate
+      )})`
+    );
+  }
+  return [shouldSample, parsedSampleRate, localSampleRateWasApplied];
+}
+const SUPPRESS_TRACING_KEY = "__SENTRY_SUPPRESS_TRACING__";
+function startSpan(options, callback) {
+  const acs = getAcs();
+  if (acs.startSpan) {
+    return acs.startSpan(options, callback);
+  }
+  const spanArguments = parseSentrySpanArguments(options);
+  const { forceTransaction, parentSpan: customParentSpan, scope: customScope } = options;
+  const customForkedScope = customScope?.clone();
+  return withScope(customForkedScope, () => {
+    const wrapper = getActiveSpanWrapper(customParentSpan);
+    return wrapper(() => {
+      const scope = getCurrentScope();
+      const parentSpan = getParentSpan(scope, customParentSpan);
+      const shouldSkipSpan = options.onlyIfParent && !parentSpan;
+      const activeSpan = shouldSkipSpan ? new SentryNonRecordingSpan() : createChildOrRootSpan({
+        parentSpan,
+        spanArguments,
+        forceTransaction,
+        scope
+      });
+      _setSpanForScope(scope, activeSpan);
+      return handleCallbackErrors(
+        () => callback(activeSpan),
+        () => {
+          const { status } = spanToJSON(activeSpan);
+          if (activeSpan.isRecording() && (!status || status === "ok")) {
+            activeSpan.setStatus({ code: SPAN_STATUS_ERROR, message: "internal_error" });
+          }
+        },
+        () => {
+          activeSpan.end();
+        }
+      );
+    });
+  });
+}
+function startSpanManual(options, callback) {
+  const acs = getAcs();
+  if (acs.startSpanManual) {
+    return acs.startSpanManual(options, callback);
+  }
+  const spanArguments = parseSentrySpanArguments(options);
+  const { forceTransaction, parentSpan: customParentSpan, scope: customScope } = options;
+  const customForkedScope = customScope?.clone();
+  return withScope(customForkedScope, () => {
+    const wrapper = getActiveSpanWrapper(customParentSpan);
+    return wrapper(() => {
+      const scope = getCurrentScope();
+      const parentSpan = getParentSpan(scope, customParentSpan);
+      const shouldSkipSpan = options.onlyIfParent && !parentSpan;
+      const activeSpan = shouldSkipSpan ? new SentryNonRecordingSpan() : createChildOrRootSpan({
+        parentSpan,
+        spanArguments,
+        forceTransaction,
+        scope
+      });
+      _setSpanForScope(scope, activeSpan);
+      return handleCallbackErrors(
+        // We pass the `finish` function to the callback, so the user can finish the span manually
+        // this is mainly here for historic purposes because previously, we instructed users to call
+        // `finish` instead of `span.end()` to also clean up the scope. Nowadays, calling `span.end()`
+        // or `finish` has the same effect and we simply leave it here to avoid breaking user code.
+        () => callback(activeSpan, () => activeSpan.end()),
+        () => {
+          const { status } = spanToJSON(activeSpan);
+          if (activeSpan.isRecording() && (!status || status === "ok")) {
+            activeSpan.setStatus({ code: SPAN_STATUS_ERROR, message: "internal_error" });
+          }
+        }
+      );
+    });
+  });
+}
+function withActiveSpan(span, callback) {
+  const acs = getAcs();
+  if (acs.withActiveSpan) {
+    return acs.withActiveSpan(span, callback);
+  }
+  return withScope((scope) => {
+    _setSpanForScope(scope, span || void 0);
+    return callback(scope);
+  });
+}
+function suppressTracing(callback) {
+  const acs = getAcs();
+  if (acs.suppressTracing) {
+    return acs.suppressTracing(callback);
+  }
+  return withScope((scope) => {
+    scope.setSDKProcessingMetadata({ [SUPPRESS_TRACING_KEY]: true });
+    const res = callback();
+    scope.setSDKProcessingMetadata({ [SUPPRESS_TRACING_KEY]: void 0 });
+    return res;
+  });
+}
+function createChildOrRootSpan({
+  parentSpan,
+  spanArguments,
+  forceTransaction,
+  scope
+}) {
+  if (!hasSpansEnabled()) {
+    const span2 = new SentryNonRecordingSpan();
+    if (forceTransaction || !parentSpan) {
+      const dsc = {
+        sampled: "false",
+        sample_rate: "0",
+        transaction: spanArguments.name,
+        ...getDynamicSamplingContextFromSpan(span2)
+      };
+      freezeDscOnSpan(span2, dsc);
+    }
+    return span2;
+  }
+  const isolationScope = getIsolationScope();
+  let span;
+  if (parentSpan && !forceTransaction) {
+    span = _startChildSpan(parentSpan, scope, spanArguments);
+    addChildSpanToSpan(parentSpan, span);
+  } else if (parentSpan) {
+    const dsc = getDynamicSamplingContextFromSpan(parentSpan);
+    const { traceId, spanId: parentSpanId } = parentSpan.spanContext();
+    const parentSampled = spanIsSampled(parentSpan);
+    span = _startRootSpan(
+      {
+        traceId,
+        parentSpanId,
+        ...spanArguments
+      },
+      scope,
+      parentSampled
+    );
+    freezeDscOnSpan(span, dsc);
+  } else {
+    const {
+      traceId,
+      dsc,
+      parentSpanId,
+      sampled: parentSampled
+    } = {
+      ...isolationScope.getPropagationContext(),
+      ...scope.getPropagationContext()
+    };
+    span = _startRootSpan(
+      {
+        traceId,
+        parentSpanId,
+        ...spanArguments
+      },
+      scope,
+      parentSampled
+    );
+    if (dsc) {
+      freezeDscOnSpan(span, dsc);
+    }
+  }
+  logSpanStart(span);
+  setCapturedScopesOnSpan(span, scope, isolationScope);
+  return span;
+}
+function parseSentrySpanArguments(options) {
+  const exp = options.experimental || {};
+  const initialCtx = {
+    isStandalone: exp.standalone,
+    ...options
+  };
+  if (options.startTime) {
+    const ctx = { ...initialCtx };
+    ctx.startTimestamp = spanTimeInputToSeconds(options.startTime);
+    delete ctx.startTime;
+    return ctx;
+  }
+  return initialCtx;
+}
+function getAcs() {
+  const carrier = getMainCarrier();
+  return getAsyncContextStrategy(carrier);
+}
+function _startRootSpan(spanArguments, scope, parentSampled) {
+  const client = getClient();
+  const options = client?.getOptions() || {};
+  const { name = "" } = spanArguments;
+  const mutableSpanSamplingData = { spanAttributes: { ...spanArguments.attributes }, spanName: name, parentSampled };
+  client?.emit("beforeSampling", mutableSpanSamplingData, { decision: false });
+  const finalParentSampled = mutableSpanSamplingData.parentSampled ?? parentSampled;
+  const finalAttributes = mutableSpanSamplingData.spanAttributes;
+  const currentPropagationContext = scope.getPropagationContext();
+  const [sampled, sampleRate, localSampleRateWasApplied] = scope.getScopeData().sdkProcessingMetadata[SUPPRESS_TRACING_KEY] ? [false] : sampleSpan(
+    options,
+    {
+      name,
+      parentSampled: finalParentSampled,
+      attributes: finalAttributes,
+      parentSampleRate: parseSampleRate(currentPropagationContext.dsc?.sample_rate)
+    },
+    currentPropagationContext.sampleRand
+  );
+  const rootSpan = new SentrySpan({
+    ...spanArguments,
+    attributes: {
+      [SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]: "custom",
+      [SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE]: sampleRate !== void 0 && localSampleRateWasApplied ? sampleRate : void 0,
+      ...finalAttributes
+    },
+    sampled
+  });
+  if (!sampled && client) {
+    DEBUG_BUILD && debug.log("[Tracing] Discarding root span because its trace was not chosen to be sampled.");
+    client.recordDroppedEvent("sample_rate", "transaction");
+  }
+  if (client) {
+    client.emit("spanStart", rootSpan);
+  }
+  return rootSpan;
+}
+function _startChildSpan(parentSpan, scope, spanArguments) {
+  const { spanId, traceId } = parentSpan.spanContext();
+  const sampled = scope.getScopeData().sdkProcessingMetadata[SUPPRESS_TRACING_KEY] ? false : spanIsSampled(parentSpan);
+  const childSpan = sampled ? new SentrySpan({
+    ...spanArguments,
+    parentSpanId: spanId,
+    traceId,
+    sampled
+  }) : new SentryNonRecordingSpan({ traceId });
+  addChildSpanToSpan(parentSpan, childSpan);
+  const client = getClient();
+  if (client) {
+    client.emit("spanStart", childSpan);
+    if (spanArguments.endTimestamp) {
+      client.emit("spanEnd", childSpan);
+    }
+  }
+  return childSpan;
+}
+function getParentSpan(scope, customParentSpan) {
+  if (customParentSpan) {
+    return customParentSpan;
+  }
+  if (customParentSpan === null) {
+    return void 0;
+  }
+  const span = _getSpanForScope(scope);
+  if (!span) {
+    return void 0;
+  }
+  const client = getClient();
+  const options = client ? client.getOptions() : {};
+  if (options.parentSpanIsAlwaysRootSpan) {
+    return getRootSpan(span);
+  }
+  return span;
+}
+function getActiveSpanWrapper(parentSpan) {
+  return parentSpan !== void 0 ? (callback) => {
+    return withActiveSpan(parentSpan, callback);
+  } : (callback) => callback();
+}
+function extractServerFunctionSha256(pathname) {
+  const serverFnMatch = pathname.match(/\/_serverFn\/([a-f0-9]{64})/i);
+  return serverFnMatch?.[1] ?? "unknown";
+}
+function getMiddlewareSpanOptions(name) {
+  return {
+    op: "middleware.tanstackstart",
+    name,
+    attributes: {
+      [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: "manual.middleware.tanstackstart",
+      [SEMANTIC_ATTRIBUTE_SENTRY_OP]: "middleware.tanstackstart"
+    }
+  };
+}
+function wrapFetchWithSentry(serverEntry) {
+  if (serverEntry.fetch) {
+    serverEntry.fetch = new Proxy(serverEntry.fetch, {
+      apply: (target, thisArg, args) => {
+        const request = args[0];
+        const url = new URL(request.url);
+        const method = request.method || "GET";
+        if (url.pathname.includes("_serverFn") || url.pathname.includes("createServerFn")) {
+          const functionSha256 = extractServerFunctionSha256(url.pathname);
+          const op = "function.tanstackstart";
+          const serverFunctionSpanAttributes = {
+            [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: "auto.function.tanstackstart.server",
+            [SEMANTIC_ATTRIBUTE_SENTRY_OP]: op,
+            "tanstackstart.function.hash.sha256": functionSha256
+          };
+          return startSpan(
+            {
+              op,
+              name: `${method} ${url.pathname}`,
+              attributes: serverFunctionSpanAttributes
+            },
+            () => {
+              return target.apply(thisArg, args);
+            }
+          );
+        }
+        return target.apply(thisArg, args);
+      }
+    });
+  }
+  return serverEntry;
+}
+var jsxRuntime = { exports: {} };
+var reactJsxRuntime_production = {};
+var hasRequiredReactJsxRuntime_production;
+function requireReactJsxRuntime_production() {
+  if (hasRequiredReactJsxRuntime_production) return reactJsxRuntime_production;
+  hasRequiredReactJsxRuntime_production = 1;
+  var REACT_ELEMENT_TYPE = Symbol.for("react.transitional.element"), REACT_FRAGMENT_TYPE = Symbol.for("react.fragment");
+  function jsxProd(type, config, maybeKey) {
+    var key = null;
+    void 0 !== maybeKey && (key = "" + maybeKey);
+    void 0 !== config.key && (key = "" + config.key);
+    if ("key" in config) {
+      maybeKey = {};
+      for (var propName in config)
+        "key" !== propName && (maybeKey[propName] = config[propName]);
+    } else maybeKey = config;
+    config = maybeKey.ref;
+    return {
+      $$typeof: REACT_ELEMENT_TYPE,
+      type,
+      key,
+      ref: void 0 !== config ? config : null,
+      props: maybeKey
+    };
+  }
+  reactJsxRuntime_production.Fragment = REACT_FRAGMENT_TYPE;
+  reactJsxRuntime_production.jsx = jsxProd;
+  reactJsxRuntime_production.jsxs = jsxProd;
+  return reactJsxRuntime_production;
+}
+var reactJsxRuntime_development = {};
+var react = { exports: {} };
+var react_production = {};
+var hasRequiredReact_production;
+function requireReact_production() {
+  if (hasRequiredReact_production) return react_production;
+  hasRequiredReact_production = 1;
+  var REACT_ELEMENT_TYPE = Symbol.for("react.transitional.element"), REACT_PORTAL_TYPE = Symbol.for("react.portal"), REACT_FRAGMENT_TYPE = Symbol.for("react.fragment"), REACT_STRICT_MODE_TYPE = Symbol.for("react.strict_mode"), REACT_PROFILER_TYPE = Symbol.for("react.profiler"), REACT_CONSUMER_TYPE = Symbol.for("react.consumer"), REACT_CONTEXT_TYPE = Symbol.for("react.context"), REACT_FORWARD_REF_TYPE = Symbol.for("react.forward_ref"), REACT_SUSPENSE_TYPE = Symbol.for("react.suspense"), REACT_MEMO_TYPE = Symbol.for("react.memo"), REACT_LAZY_TYPE = Symbol.for("react.lazy"), REACT_ACTIVITY_TYPE = Symbol.for("react.activity"), MAYBE_ITERATOR_SYMBOL = Symbol.iterator;
+  function getIteratorFn(maybeIterable) {
+    if (null === maybeIterable || "object" !== typeof maybeIterable) return null;
+    maybeIterable = MAYBE_ITERATOR_SYMBOL && maybeIterable[MAYBE_ITERATOR_SYMBOL] || maybeIterable["@@iterator"];
+    return "function" === typeof maybeIterable ? maybeIterable : null;
+  }
+  var ReactNoopUpdateQueue = {
+    isMounted: function() {
+      return false;
+    },
+    enqueueForceUpdate: function() {
+    },
+    enqueueReplaceState: function() {
+    },
+    enqueueSetState: function() {
+    }
+  }, assign = Object.assign, emptyObject = {};
+  function Component(props, context, updater) {
+    this.props = props;
+    this.context = context;
+    this.refs = emptyObject;
+    this.updater = updater || ReactNoopUpdateQueue;
+  }
+  Component.prototype.isReactComponent = {};
+  Component.prototype.setState = function(partialState, callback) {
+    if ("object" !== typeof partialState && "function" !== typeof partialState && null != partialState)
+      throw Error(
+        "takes an object of state variables to update or a function which returns an object of state variables."
+      );
+    this.updater.enqueueSetState(this, partialState, callback, "setState");
+  };
+  Component.prototype.forceUpdate = function(callback) {
+    this.updater.enqueueForceUpdate(this, callback, "forceUpdate");
+  };
+  function ComponentDummy() {
+  }
+  ComponentDummy.prototype = Component.prototype;
+  function PureComponent(props, context, updater) {
+    this.props = props;
+    this.context = context;
+    this.refs = emptyObject;
+    this.updater = updater || ReactNoopUpdateQueue;
+  }
+  var pureComponentPrototype = PureComponent.prototype = new ComponentDummy();
+  pureComponentPrototype.constructor = PureComponent;
+  assign(pureComponentPrototype, Component.prototype);
+  pureComponentPrototype.isPureReactComponent = true;
+  var isArrayImpl = Array.isArray;
+  function noop() {
+  }
+  var ReactSharedInternals = { H: null, A: null, T: null, S: null }, hasOwnProperty = Object.prototype.hasOwnProperty;
+  function ReactElement(type, key, props) {
+    var refProp = props.ref;
+    return {
+      $$typeof: REACT_ELEMENT_TYPE,
+      type,
+      key,
+      ref: void 0 !== refProp ? refProp : null,
+      props
+    };
+  }
+  function cloneAndReplaceKey(oldElement, newKey) {
+    return ReactElement(oldElement.type, newKey, oldElement.props);
+  }
+  function isValidElement(object) {
+    return "object" === typeof object && null !== object && object.$$typeof === REACT_ELEMENT_TYPE;
+  }
+  function escape(key) {
+    var escaperLookup = { "=": "=0", ":": "=2" };
+    return "$" + key.replace(/[=:]/g, function(match) {
+      return escaperLookup[match];
+    });
+  }
+  var userProvidedKeyEscapeRegex = /\/+/g;
+  function getElementKey(element, index) {
+    return "object" === typeof element && null !== element && null != element.key ? escape("" + element.key) : index.toString(36);
+  }
+  function resolveThenable(thenable) {
+    switch (thenable.status) {
+      case "fulfilled":
+        return thenable.value;
+      case "rejected":
+        throw thenable.reason;
+      default:
+        switch ("string" === typeof thenable.status ? thenable.then(noop, noop) : (thenable.status = "pending", thenable.then(
+          function(fulfilledValue) {
+            "pending" === thenable.status && (thenable.status = "fulfilled", thenable.value = fulfilledValue);
+          },
+          function(error2) {
+            "pending" === thenable.status && (thenable.status = "rejected", thenable.reason = error2);
+          }
+        )), thenable.status) {
+          case "fulfilled":
+            return thenable.value;
+          case "rejected":
+            throw thenable.reason;
+        }
+    }
+    throw thenable;
+  }
+  function mapIntoArray(children, array, escapedPrefix, nameSoFar, callback) {
+    var type = typeof children;
+    if ("undefined" === type || "boolean" === type) children = null;
+    var invokeCallback = false;
+    if (null === children) invokeCallback = true;
+    else
+      switch (type) {
+        case "bigint":
+        case "string":
+        case "number":
+          invokeCallback = true;
+          break;
+        case "object":
+          switch (children.$$typeof) {
+            case REACT_ELEMENT_TYPE:
+            case REACT_PORTAL_TYPE:
+              invokeCallback = true;
+              break;
+            case REACT_LAZY_TYPE:
+              return invokeCallback = children._init, mapIntoArray(
+                invokeCallback(children._payload),
+                array,
+                escapedPrefix,
+                nameSoFar,
+                callback
+              );
+          }
+      }
+    if (invokeCallback)
+      return callback = callback(children), invokeCallback = "" === nameSoFar ? "." + getElementKey(children, 0) : nameSoFar, isArrayImpl(callback) ? (escapedPrefix = "", null != invokeCallback && (escapedPrefix = invokeCallback.replace(userProvidedKeyEscapeRegex, "$&/") + "/"), mapIntoArray(callback, array, escapedPrefix, "", function(c2) {
+        return c2;
+      })) : null != callback && (isValidElement(callback) && (callback = cloneAndReplaceKey(
+        callback,
+        escapedPrefix + (null == callback.key || children && children.key === callback.key ? "" : ("" + callback.key).replace(
+          userProvidedKeyEscapeRegex,
+          "$&/"
+        ) + "/") + invokeCallback
+      )), array.push(callback)), 1;
+    invokeCallback = 0;
+    var nextNamePrefix = "" === nameSoFar ? "." : nameSoFar + ":";
+    if (isArrayImpl(children))
+      for (var i = 0; i < children.length; i++)
+        nameSoFar = children[i], type = nextNamePrefix + getElementKey(nameSoFar, i), invokeCallback += mapIntoArray(
+          nameSoFar,
+          array,
+          escapedPrefix,
+          type,
+          callback
+        );
+    else if (i = getIteratorFn(children), "function" === typeof i)
+      for (children = i.call(children), i = 0; !(nameSoFar = children.next()).done; )
+        nameSoFar = nameSoFar.value, type = nextNamePrefix + getElementKey(nameSoFar, i++), invokeCallback += mapIntoArray(
+          nameSoFar,
+          array,
+          escapedPrefix,
+          type,
+          callback
+        );
+    else if ("object" === type) {
+      if ("function" === typeof children.then)
+        return mapIntoArray(
+          resolveThenable(children),
+          array,
+          escapedPrefix,
+          nameSoFar,
+          callback
+        );
+      array = String(children);
+      throw Error(
+        "Objects are not valid as a React child (found: " + ("[object Object]" === array ? "object with keys {" + Object.keys(children).join(", ") + "}" : array) + "). If you meant to render a collection of children, use an array instead."
+      );
+    }
+    return invokeCallback;
+  }
+  function mapChildren(children, func, context) {
+    if (null == children) return children;
+    var result = [], count = 0;
+    mapIntoArray(children, result, "", "", function(child) {
+      return func.call(context, child, count++);
+    });
+    return result;
+  }
+  function lazyInitializer(payload) {
+    if (-1 === payload._status) {
+      var ctor = payload._result;
+      ctor = ctor();
+      ctor.then(
+        function(moduleObject) {
+          if (0 === payload._status || -1 === payload._status)
+            payload._status = 1, payload._result = moduleObject;
+        },
+        function(error2) {
+          if (0 === payload._status || -1 === payload._status)
+            payload._status = 2, payload._result = error2;
+        }
+      );
+      -1 === payload._status && (payload._status = 0, payload._result = ctor);
+    }
+    if (1 === payload._status) return payload._result.default;
+    throw payload._result;
+  }
+  var reportGlobalError = "function" === typeof reportError ? reportError : function(error2) {
+    if ("object" === typeof window && "function" === typeof window.ErrorEvent) {
+      var event = new window.ErrorEvent("error", {
+        bubbles: true,
+        cancelable: true,
+        message: "object" === typeof error2 && null !== error2 && "string" === typeof error2.message ? String(error2.message) : String(error2),
+        error: error2
+      });
+      if (!window.dispatchEvent(event)) return;
+    } else if ("object" === typeof process && "function" === typeof process.emit) {
+      process.emit("uncaughtException", error2);
+      return;
+    }
+    console.error(error2);
+  }, Children = {
+    map: mapChildren,
+    forEach: function(children, forEachFunc, forEachContext) {
+      mapChildren(
+        children,
+        function() {
+          forEachFunc.apply(this, arguments);
+        },
+        forEachContext
+      );
+    },
+    count: function(children) {
+      var n = 0;
+      mapChildren(children, function() {
+        n++;
+      });
+      return n;
+    },
+    toArray: function(children) {
+      return mapChildren(children, function(child) {
+        return child;
+      }) || [];
+    },
+    only: function(children) {
+      if (!isValidElement(children))
+        throw Error(
+          "React.Children.only expected to receive a single React element child."
+        );
+      return children;
+    }
+  };
+  react_production.Activity = REACT_ACTIVITY_TYPE;
+  react_production.Children = Children;
+  react_production.Component = Component;
+  react_production.Fragment = REACT_FRAGMENT_TYPE;
+  react_production.Profiler = REACT_PROFILER_TYPE;
+  react_production.PureComponent = PureComponent;
+  react_production.StrictMode = REACT_STRICT_MODE_TYPE;
+  react_production.Suspense = REACT_SUSPENSE_TYPE;
+  react_production.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE = ReactSharedInternals;
+  react_production.__COMPILER_RUNTIME = {
+    __proto__: null,
+    c: function(size) {
+      return ReactSharedInternals.H.useMemoCache(size);
+    }
+  };
+  react_production.cache = function(fn2) {
+    return function() {
+      return fn2.apply(null, arguments);
+    };
+  };
+  react_production.cacheSignal = function() {
+    return null;
+  };
+  react_production.cloneElement = function(element, config, children) {
+    if (null === element || void 0 === element)
+      throw Error(
+        "The argument must be a React element, but you passed " + element + "."
+      );
+    var props = assign({}, element.props), key = element.key;
+    if (null != config)
+      for (propName in void 0 !== config.key && (key = "" + config.key), config)
+        !hasOwnProperty.call(config, propName) || "key" === propName || "__self" === propName || "__source" === propName || "ref" === propName && void 0 === config.ref || (props[propName] = config[propName]);
+    var propName = arguments.length - 2;
+    if (1 === propName) props.children = children;
+    else if (1 < propName) {
+      for (var childArray = Array(propName), i = 0; i < propName; i++)
+        childArray[i] = arguments[i + 2];
+      props.children = childArray;
+    }
+    return ReactElement(element.type, key, props);
+  };
+  react_production.createContext = function(defaultValue) {
+    defaultValue = {
+      $$typeof: REACT_CONTEXT_TYPE,
+      _currentValue: defaultValue,
+      _currentValue2: defaultValue,
+      _threadCount: 0,
+      Provider: null,
+      Consumer: null
+    };
+    defaultValue.Provider = defaultValue;
+    defaultValue.Consumer = {
+      $$typeof: REACT_CONSUMER_TYPE,
+      _context: defaultValue
+    };
+    return defaultValue;
+  };
+  react_production.createElement = function(type, config, children) {
+    var propName, props = {}, key = null;
+    if (null != config)
+      for (propName in void 0 !== config.key && (key = "" + config.key), config)
+        hasOwnProperty.call(config, propName) && "key" !== propName && "__self" !== propName && "__source" !== propName && (props[propName] = config[propName]);
+    var childrenLength = arguments.length - 2;
+    if (1 === childrenLength) props.children = children;
+    else if (1 < childrenLength) {
+      for (var childArray = Array(childrenLength), i = 0; i < childrenLength; i++)
+        childArray[i] = arguments[i + 2];
+      props.children = childArray;
+    }
+    if (type && type.defaultProps)
+      for (propName in childrenLength = type.defaultProps, childrenLength)
+        void 0 === props[propName] && (props[propName] = childrenLength[propName]);
+    return ReactElement(type, key, props);
+  };
+  react_production.createRef = function() {
+    return { current: null };
+  };
+  react_production.forwardRef = function(render) {
+    return { $$typeof: REACT_FORWARD_REF_TYPE, render };
+  };
+  react_production.isValidElement = isValidElement;
+  react_production.lazy = function(ctor) {
+    return {
+      $$typeof: REACT_LAZY_TYPE,
+      _payload: { _status: -1, _result: ctor },
+      _init: lazyInitializer
+    };
+  };
+  react_production.memo = function(type, compare) {
+    return {
+      $$typeof: REACT_MEMO_TYPE,
+      type,
+      compare: void 0 === compare ? null : compare
+    };
+  };
+  react_production.startTransition = function(scope) {
+    var prevTransition = ReactSharedInternals.T, currentTransition = {};
+    ReactSharedInternals.T = currentTransition;
+    try {
+      var returnValue = scope(), onStartTransitionFinish = ReactSharedInternals.S;
+      null !== onStartTransitionFinish && onStartTransitionFinish(currentTransition, returnValue);
+      "object" === typeof returnValue && null !== returnValue && "function" === typeof returnValue.then && returnValue.then(noop, reportGlobalError);
+    } catch (error2) {
+      reportGlobalError(error2);
+    } finally {
+      null !== prevTransition && null !== currentTransition.types && (prevTransition.types = currentTransition.types), ReactSharedInternals.T = prevTransition;
+    }
+  };
+  react_production.unstable_useCacheRefresh = function() {
+    return ReactSharedInternals.H.useCacheRefresh();
+  };
+  react_production.use = function(usable) {
+    return ReactSharedInternals.H.use(usable);
+  };
+  react_production.useActionState = function(action, initialState, permalink) {
+    return ReactSharedInternals.H.useActionState(action, initialState, permalink);
+  };
+  react_production.useCallback = function(callback, deps) {
+    return ReactSharedInternals.H.useCallback(callback, deps);
+  };
+  react_production.useContext = function(Context) {
+    return ReactSharedInternals.H.useContext(Context);
+  };
+  react_production.useDebugValue = function() {
+  };
+  react_production.useDeferredValue = function(value, initialValue) {
+    return ReactSharedInternals.H.useDeferredValue(value, initialValue);
+  };
+  react_production.useEffect = function(create, deps) {
+    return ReactSharedInternals.H.useEffect(create, deps);
+  };
+  react_production.useEffectEvent = function(callback) {
+    return ReactSharedInternals.H.useEffectEvent(callback);
+  };
+  react_production.useId = function() {
+    return ReactSharedInternals.H.useId();
+  };
+  react_production.useImperativeHandle = function(ref, create, deps) {
+    return ReactSharedInternals.H.useImperativeHandle(ref, create, deps);
+  };
+  react_production.useInsertionEffect = function(create, deps) {
+    return ReactSharedInternals.H.useInsertionEffect(create, deps);
+  };
+  react_production.useLayoutEffect = function(create, deps) {
+    return ReactSharedInternals.H.useLayoutEffect(create, deps);
+  };
+  react_production.useMemo = function(create, deps) {
+    return ReactSharedInternals.H.useMemo(create, deps);
+  };
+  react_production.useOptimistic = function(passthrough, reducer) {
+    return ReactSharedInternals.H.useOptimistic(passthrough, reducer);
+  };
+  react_production.useReducer = function(reducer, initialArg, init) {
+    return ReactSharedInternals.H.useReducer(reducer, initialArg, init);
+  };
+  react_production.useRef = function(initialValue) {
+    return ReactSharedInternals.H.useRef(initialValue);
+  };
+  react_production.useState = function(initialState) {
+    return ReactSharedInternals.H.useState(initialState);
+  };
+  react_production.useSyncExternalStore = function(subscribe2, getSnapshot, getServerSnapshot) {
+    return ReactSharedInternals.H.useSyncExternalStore(
+      subscribe2,
+      getSnapshot,
+      getServerSnapshot
+    );
+  };
+  react_production.useTransition = function() {
+    return ReactSharedInternals.H.useTransition();
+  };
+  react_production.version = "19.2.3";
+  return react_production;
+}
+var react_development = { exports: {} };
+react_development.exports;
+var hasRequiredReact_development;
+function requireReact_development() {
+  if (hasRequiredReact_development) return react_development.exports;
+  hasRequiredReact_development = 1;
+  (function(module, exports$1) {
+    "production" !== process.env.NODE_ENV && (function() {
+      function defineDeprecationWarning(methodName, info) {
+        Object.defineProperty(Component.prototype, methodName, {
+          get: function() {
+            console.warn(
+              "%s(...) is deprecated in plain JavaScript React classes. %s",
+              info[0],
+              info[1]
+            );
+          }
+        });
+      }
+      function getIteratorFn(maybeIterable) {
+        if (null === maybeIterable || "object" !== typeof maybeIterable)
+          return null;
+        maybeIterable = MAYBE_ITERATOR_SYMBOL && maybeIterable[MAYBE_ITERATOR_SYMBOL] || maybeIterable["@@iterator"];
+        return "function" === typeof maybeIterable ? maybeIterable : null;
+      }
+      function warnNoop(publicInstance, callerName) {
+        publicInstance = (publicInstance = publicInstance.constructor) && (publicInstance.displayName || publicInstance.name) || "ReactClass";
+        var warningKey = publicInstance + "." + callerName;
+        didWarnStateUpdateForUnmountedComponent[warningKey] || (console.error(
+          "Can't call %s on a component that is not yet mounted. This is a no-op, but it might indicate a bug in your application. Instead, assign to `this.state` directly or define a `state = {};` class property with the desired state in the %s component.",
+          callerName,
+          publicInstance
+        ), didWarnStateUpdateForUnmountedComponent[warningKey] = true);
+      }
+      function Component(props, context, updater) {
+        this.props = props;
+        this.context = context;
+        this.refs = emptyObject;
+        this.updater = updater || ReactNoopUpdateQueue;
+      }
+      function ComponentDummy() {
+      }
+      function PureComponent(props, context, updater) {
+        this.props = props;
+        this.context = context;
+        this.refs = emptyObject;
+        this.updater = updater || ReactNoopUpdateQueue;
+      }
+      function noop() {
+      }
+      function testStringCoercion(value) {
+        return "" + value;
+      }
+      function checkKeyStringCoercion(value) {
+        try {
+          testStringCoercion(value);
+          var JSCompiler_inline_result = false;
+        } catch (e) {
+          JSCompiler_inline_result = true;
+        }
+        if (JSCompiler_inline_result) {
+          JSCompiler_inline_result = console;
+          var JSCompiler_temp_const = JSCompiler_inline_result.error;
+          var JSCompiler_inline_result$jscomp$0 = "function" === typeof Symbol && Symbol.toStringTag && value[Symbol.toStringTag] || value.constructor.name || "Object";
+          JSCompiler_temp_const.call(
+            JSCompiler_inline_result,
+            "The provided key is an unsupported type %s. This value must be coerced to a string before using it here.",
+            JSCompiler_inline_result$jscomp$0
+          );
+          return testStringCoercion(value);
+        }
+      }
+      function getComponentNameFromType(type) {
+        if (null == type) return null;
+        if ("function" === typeof type)
+          return type.$$typeof === REACT_CLIENT_REFERENCE ? null : type.displayName || type.name || null;
+        if ("string" === typeof type) return type;
+        switch (type) {
+          case REACT_FRAGMENT_TYPE:
+            return "Fragment";
+          case REACT_PROFILER_TYPE:
+            return "Profiler";
+          case REACT_STRICT_MODE_TYPE:
+            return "StrictMode";
+          case REACT_SUSPENSE_TYPE:
+            return "Suspense";
+          case REACT_SUSPENSE_LIST_TYPE:
+            return "SuspenseList";
+          case REACT_ACTIVITY_TYPE:
+            return "Activity";
+        }
+        if ("object" === typeof type)
+          switch ("number" === typeof type.tag && console.error(
+            "Received an unexpected object in getComponentNameFromType(). This is likely a bug in React. Please file an issue."
+          ), type.$$typeof) {
+            case REACT_PORTAL_TYPE:
+              return "Portal";
+            case REACT_CONTEXT_TYPE:
+              return type.displayName || "Context";
+            case REACT_CONSUMER_TYPE:
+              return (type._context.displayName || "Context") + ".Consumer";
+            case REACT_FORWARD_REF_TYPE:
+              var innerType = type.render;
+              type = type.displayName;
+              type || (type = innerType.displayName || innerType.name || "", type = "" !== type ? "ForwardRef(" + type + ")" : "ForwardRef");
+              return type;
+            case REACT_MEMO_TYPE:
+              return innerType = type.displayName || null, null !== innerType ? innerType : getComponentNameFromType(type.type) || "Memo";
+            case REACT_LAZY_TYPE:
+              innerType = type._payload;
+              type = type._init;
+              try {
+                return getComponentNameFromType(type(innerType));
+              } catch (x2) {
+              }
+          }
+        return null;
+      }
+      function getTaskName(type) {
+        if (type === REACT_FRAGMENT_TYPE) return "<>";
+        if ("object" === typeof type && null !== type && type.$$typeof === REACT_LAZY_TYPE)
+          return "<...>";
+        try {
+          var name = getComponentNameFromType(type);
+          return name ? "<" + name + ">" : "<...>";
+        } catch (x2) {
+          return "<...>";
+        }
+      }
+      function getOwner() {
+        var dispatcher = ReactSharedInternals.A;
+        return null === dispatcher ? null : dispatcher.getOwner();
+      }
+      function UnknownOwner() {
+        return Error("react-stack-top-frame");
+      }
+      function hasValidKey(config) {
+        if (hasOwnProperty.call(config, "key")) {
+          var getter = Object.getOwnPropertyDescriptor(config, "key").get;
+          if (getter && getter.isReactWarning) return false;
+        }
+        return void 0 !== config.key;
+      }
+      function defineKeyPropWarningGetter(props, displayName) {
+        function warnAboutAccessingKey() {
+          specialPropKeyWarningShown || (specialPropKeyWarningShown = true, console.error(
+            "%s: `key` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://react.dev/link/special-props)",
+            displayName
+          ));
+        }
+        warnAboutAccessingKey.isReactWarning = true;
+        Object.defineProperty(props, "key", {
+          get: warnAboutAccessingKey,
+          configurable: true
+        });
+      }
+      function elementRefGetterWithDeprecationWarning() {
+        var componentName = getComponentNameFromType(this.type);
+        didWarnAboutElementRef[componentName] || (didWarnAboutElementRef[componentName] = true, console.error(
+          "Accessing element.ref was removed in React 19. ref is now a regular prop. It will be removed from the JSX Element type in a future release."
+        ));
+        componentName = this.props.ref;
+        return void 0 !== componentName ? componentName : null;
+      }
+      function ReactElement(type, key, props, owner, debugStack, debugTask) {
+        var refProp = props.ref;
+        type = {
+          $$typeof: REACT_ELEMENT_TYPE,
+          type,
+          key,
+          props,
+          _owner: owner
+        };
+        null !== (void 0 !== refProp ? refProp : null) ? Object.defineProperty(type, "ref", {
+          enumerable: false,
+          get: elementRefGetterWithDeprecationWarning
+        }) : Object.defineProperty(type, "ref", { enumerable: false, value: null });
+        type._store = {};
+        Object.defineProperty(type._store, "validated", {
+          configurable: false,
+          enumerable: false,
+          writable: true,
+          value: 0
+        });
+        Object.defineProperty(type, "_debugInfo", {
+          configurable: false,
+          enumerable: false,
+          writable: true,
+          value: null
+        });
+        Object.defineProperty(type, "_debugStack", {
+          configurable: false,
+          enumerable: false,
+          writable: true,
+          value: debugStack
+        });
+        Object.defineProperty(type, "_debugTask", {
+          configurable: false,
+          enumerable: false,
+          writable: true,
+          value: debugTask
+        });
+        Object.freeze && (Object.freeze(type.props), Object.freeze(type));
+        return type;
+      }
+      function cloneAndReplaceKey(oldElement, newKey) {
+        newKey = ReactElement(
+          oldElement.type,
+          newKey,
+          oldElement.props,
+          oldElement._owner,
+          oldElement._debugStack,
+          oldElement._debugTask
+        );
+        oldElement._store && (newKey._store.validated = oldElement._store.validated);
+        return newKey;
+      }
+      function validateChildKeys(node) {
+        isValidElement(node) ? node._store && (node._store.validated = 1) : "object" === typeof node && null !== node && node.$$typeof === REACT_LAZY_TYPE && ("fulfilled" === node._payload.status ? isValidElement(node._payload.value) && node._payload.value._store && (node._payload.value._store.validated = 1) : node._store && (node._store.validated = 1));
+      }
+      function isValidElement(object) {
+        return "object" === typeof object && null !== object && object.$$typeof === REACT_ELEMENT_TYPE;
+      }
+      function escape(key) {
+        var escaperLookup = { "=": "=0", ":": "=2" };
+        return "$" + key.replace(/[=:]/g, function(match) {
+          return escaperLookup[match];
+        });
+      }
+      function getElementKey(element, index) {
+        return "object" === typeof element && null !== element && null != element.key ? (checkKeyStringCoercion(element.key), escape("" + element.key)) : index.toString(36);
+      }
+      function resolveThenable(thenable) {
+        switch (thenable.status) {
+          case "fulfilled":
+            return thenable.value;
+          case "rejected":
+            throw thenable.reason;
+          default:
+            switch ("string" === typeof thenable.status ? thenable.then(noop, noop) : (thenable.status = "pending", thenable.then(
+              function(fulfilledValue) {
+                "pending" === thenable.status && (thenable.status = "fulfilled", thenable.value = fulfilledValue);
+              },
+              function(error2) {
+                "pending" === thenable.status && (thenable.status = "rejected", thenable.reason = error2);
+              }
+            )), thenable.status) {
+              case "fulfilled":
+                return thenable.value;
+              case "rejected":
+                throw thenable.reason;
+            }
+        }
+        throw thenable;
+      }
+      function mapIntoArray(children, array, escapedPrefix, nameSoFar, callback) {
+        var type = typeof children;
+        if ("undefined" === type || "boolean" === type) children = null;
+        var invokeCallback = false;
+        if (null === children) invokeCallback = true;
+        else
+          switch (type) {
+            case "bigint":
+            case "string":
+            case "number":
+              invokeCallback = true;
+              break;
+            case "object":
+              switch (children.$$typeof) {
+                case REACT_ELEMENT_TYPE:
+                case REACT_PORTAL_TYPE:
+                  invokeCallback = true;
+                  break;
+                case REACT_LAZY_TYPE:
+                  return invokeCallback = children._init, mapIntoArray(
+                    invokeCallback(children._payload),
+                    array,
+                    escapedPrefix,
+                    nameSoFar,
+                    callback
+                  );
+              }
+          }
+        if (invokeCallback) {
+          invokeCallback = children;
+          callback = callback(invokeCallback);
+          var childKey = "" === nameSoFar ? "." + getElementKey(invokeCallback, 0) : nameSoFar;
+          isArrayImpl(callback) ? (escapedPrefix = "", null != childKey && (escapedPrefix = childKey.replace(userProvidedKeyEscapeRegex, "$&/") + "/"), mapIntoArray(callback, array, escapedPrefix, "", function(c2) {
+            return c2;
+          })) : null != callback && (isValidElement(callback) && (null != callback.key && (invokeCallback && invokeCallback.key === callback.key || checkKeyStringCoercion(callback.key)), escapedPrefix = cloneAndReplaceKey(
+            callback,
+            escapedPrefix + (null == callback.key || invokeCallback && invokeCallback.key === callback.key ? "" : ("" + callback.key).replace(
+              userProvidedKeyEscapeRegex,
+              "$&/"
+            ) + "/") + childKey
+          ), "" !== nameSoFar && null != invokeCallback && isValidElement(invokeCallback) && null == invokeCallback.key && invokeCallback._store && !invokeCallback._store.validated && (escapedPrefix._store.validated = 2), callback = escapedPrefix), array.push(callback));
+          return 1;
+        }
+        invokeCallback = 0;
+        childKey = "" === nameSoFar ? "." : nameSoFar + ":";
+        if (isArrayImpl(children))
+          for (var i = 0; i < children.length; i++)
+            nameSoFar = children[i], type = childKey + getElementKey(nameSoFar, i), invokeCallback += mapIntoArray(
+              nameSoFar,
+              array,
+              escapedPrefix,
+              type,
+              callback
+            );
+        else if (i = getIteratorFn(children), "function" === typeof i)
+          for (i === children.entries && (didWarnAboutMaps || console.warn(
+            "Using Maps as children is not supported. Use an array of keyed ReactElements instead."
+          ), didWarnAboutMaps = true), children = i.call(children), i = 0; !(nameSoFar = children.next()).done; )
+            nameSoFar = nameSoFar.value, type = childKey + getElementKey(nameSoFar, i++), invokeCallback += mapIntoArray(
+              nameSoFar,
+              array,
+              escapedPrefix,
+              type,
+              callback
+            );
+        else if ("object" === type) {
+          if ("function" === typeof children.then)
+            return mapIntoArray(
+              resolveThenable(children),
+              array,
+              escapedPrefix,
+              nameSoFar,
+              callback
+            );
+          array = String(children);
+          throw Error(
+            "Objects are not valid as a React child (found: " + ("[object Object]" === array ? "object with keys {" + Object.keys(children).join(", ") + "}" : array) + "). If you meant to render a collection of children, use an array instead."
+          );
+        }
+        return invokeCallback;
+      }
+      function mapChildren(children, func, context) {
+        if (null == children) return children;
+        var result = [], count = 0;
+        mapIntoArray(children, result, "", "", function(child) {
+          return func.call(context, child, count++);
+        });
+        return result;
+      }
+      function lazyInitializer(payload) {
+        if (-1 === payload._status) {
+          var ioInfo = payload._ioInfo;
+          null != ioInfo && (ioInfo.start = ioInfo.end = performance.now());
+          ioInfo = payload._result;
+          var thenable = ioInfo();
+          thenable.then(
+            function(moduleObject) {
+              if (0 === payload._status || -1 === payload._status) {
+                payload._status = 1;
+                payload._result = moduleObject;
+                var _ioInfo = payload._ioInfo;
+                null != _ioInfo && (_ioInfo.end = performance.now());
+                void 0 === thenable.status && (thenable.status = "fulfilled", thenable.value = moduleObject);
+              }
+            },
+            function(error2) {
+              if (0 === payload._status || -1 === payload._status) {
+                payload._status = 2;
+                payload._result = error2;
+                var _ioInfo2 = payload._ioInfo;
+                null != _ioInfo2 && (_ioInfo2.end = performance.now());
+                void 0 === thenable.status && (thenable.status = "rejected", thenable.reason = error2);
+              }
+            }
+          );
+          ioInfo = payload._ioInfo;
+          if (null != ioInfo) {
+            ioInfo.value = thenable;
+            var displayName = thenable.displayName;
+            "string" === typeof displayName && (ioInfo.name = displayName);
+          }
+          -1 === payload._status && (payload._status = 0, payload._result = thenable);
+        }
+        if (1 === payload._status)
+          return ioInfo = payload._result, void 0 === ioInfo && console.error(
+            "lazy: Expected the result of a dynamic import() call. Instead received: %s\n\nYour code should look like: \n  const MyComponent = lazy(() => import('./MyComponent'))\n\nDid you accidentally put curly braces around the import?",
+            ioInfo
+          ), "default" in ioInfo || console.error(
+            "lazy: Expected the result of a dynamic import() call. Instead received: %s\n\nYour code should look like: \n  const MyComponent = lazy(() => import('./MyComponent'))",
+            ioInfo
+          ), ioInfo.default;
+        throw payload._result;
+      }
+      function resolveDispatcher() {
+        var dispatcher = ReactSharedInternals.H;
+        null === dispatcher && console.error(
+          "Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:\n1. You might have mismatching versions of React and the renderer (such as React DOM)\n2. You might be breaking the Rules of Hooks\n3. You might have more than one copy of React in the same app\nSee https://react.dev/link/invalid-hook-call for tips about how to debug and fix this problem."
+        );
+        return dispatcher;
+      }
+      function releaseAsyncTransition() {
+        ReactSharedInternals.asyncTransitions--;
+      }
+      function enqueueTask(task) {
+        if (null === enqueueTaskImpl)
+          try {
+            var requireString = ("require" + Math.random()).slice(0, 7);
+            enqueueTaskImpl = (module && module[requireString]).call(
+              module,
+              "timers"
+            ).setImmediate;
+          } catch (_err) {
+            enqueueTaskImpl = function(callback) {
+              false === didWarnAboutMessageChannel && (didWarnAboutMessageChannel = true, "undefined" === typeof MessageChannel && console.error(
+                "This browser does not have a MessageChannel implementation, so enqueuing tasks via await act(async () => ...) will fail. Please file an issue at https://github.com/facebook/react/issues if you encounter this warning."
+              ));
+              var channel = new MessageChannel();
+              channel.port1.onmessage = callback;
+              channel.port2.postMessage(void 0);
+            };
+          }
+        return enqueueTaskImpl(task);
+      }
+      function aggregateErrors(errors) {
+        return 1 < errors.length && "function" === typeof AggregateError ? new AggregateError(errors) : errors[0];
+      }
+      function popActScope(prevActQueue, prevActScopeDepth) {
+        prevActScopeDepth !== actScopeDepth - 1 && console.error(
+          "You seem to have overlapping act() calls, this is not supported. Be sure to await previous act() calls before making a new one. "
+        );
+        actScopeDepth = prevActScopeDepth;
+      }
+      function recursivelyFlushAsyncActWork(returnValue, resolve, reject) {
+        var queue = ReactSharedInternals.actQueue;
+        if (null !== queue)
+          if (0 !== queue.length)
+            try {
+              flushActQueue(queue);
+              enqueueTask(function() {
+                return recursivelyFlushAsyncActWork(returnValue, resolve, reject);
+              });
+              return;
+            } catch (error2) {
+              ReactSharedInternals.thrownErrors.push(error2);
+            }
+          else ReactSharedInternals.actQueue = null;
+        0 < ReactSharedInternals.thrownErrors.length ? (queue = aggregateErrors(ReactSharedInternals.thrownErrors), ReactSharedInternals.thrownErrors.length = 0, reject(queue)) : resolve(returnValue);
+      }
+      function flushActQueue(queue) {
+        if (!isFlushing) {
+          isFlushing = true;
+          var i = 0;
+          try {
+            for (; i < queue.length; i++) {
+              var callback = queue[i];
+              do {
+                ReactSharedInternals.didUsePromise = false;
+                var continuation = callback(false);
+                if (null !== continuation) {
+                  if (ReactSharedInternals.didUsePromise) {
+                    queue[i] = callback;
+                    queue.splice(0, i);
+                    return;
+                  }
+                  callback = continuation;
+                } else break;
+              } while (1);
+            }
+            queue.length = 0;
+          } catch (error2) {
+            queue.splice(0, i + 1), ReactSharedInternals.thrownErrors.push(error2);
+          } finally {
+            isFlushing = false;
+          }
+        }
+      }
+      "undefined" !== typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ && "function" === typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart && __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart(Error());
+      var REACT_ELEMENT_TYPE = Symbol.for("react.transitional.element"), REACT_PORTAL_TYPE = Symbol.for("react.portal"), REACT_FRAGMENT_TYPE = Symbol.for("react.fragment"), REACT_STRICT_MODE_TYPE = Symbol.for("react.strict_mode"), REACT_PROFILER_TYPE = Symbol.for("react.profiler"), REACT_CONSUMER_TYPE = Symbol.for("react.consumer"), REACT_CONTEXT_TYPE = Symbol.for("react.context"), REACT_FORWARD_REF_TYPE = Symbol.for("react.forward_ref"), REACT_SUSPENSE_TYPE = Symbol.for("react.suspense"), REACT_SUSPENSE_LIST_TYPE = Symbol.for("react.suspense_list"), REACT_MEMO_TYPE = Symbol.for("react.memo"), REACT_LAZY_TYPE = Symbol.for("react.lazy"), REACT_ACTIVITY_TYPE = Symbol.for("react.activity"), MAYBE_ITERATOR_SYMBOL = Symbol.iterator, didWarnStateUpdateForUnmountedComponent = {}, ReactNoopUpdateQueue = {
+        isMounted: function() {
+          return false;
+        },
+        enqueueForceUpdate: function(publicInstance) {
+          warnNoop(publicInstance, "forceUpdate");
+        },
+        enqueueReplaceState: function(publicInstance) {
+          warnNoop(publicInstance, "replaceState");
+        },
+        enqueueSetState: function(publicInstance) {
+          warnNoop(publicInstance, "setState");
+        }
+      }, assign = Object.assign, emptyObject = {};
+      Object.freeze(emptyObject);
+      Component.prototype.isReactComponent = {};
+      Component.prototype.setState = function(partialState, callback) {
+        if ("object" !== typeof partialState && "function" !== typeof partialState && null != partialState)
+          throw Error(
+            "takes an object of state variables to update or a function which returns an object of state variables."
+          );
+        this.updater.enqueueSetState(this, partialState, callback, "setState");
+      };
+      Component.prototype.forceUpdate = function(callback) {
+        this.updater.enqueueForceUpdate(this, callback, "forceUpdate");
+      };
+      var deprecatedAPIs = {
+        isMounted: [
+          "isMounted",
+          "Instead, make sure to clean up subscriptions and pending requests in componentWillUnmount to prevent memory leaks."
+        ],
+        replaceState: [
+          "replaceState",
+          "Refactor your code to use setState instead (see https://github.com/facebook/react/issues/3236)."
+        ]
+      };
+      for (fnName in deprecatedAPIs)
+        deprecatedAPIs.hasOwnProperty(fnName) && defineDeprecationWarning(fnName, deprecatedAPIs[fnName]);
+      ComponentDummy.prototype = Component.prototype;
+      deprecatedAPIs = PureComponent.prototype = new ComponentDummy();
+      deprecatedAPIs.constructor = PureComponent;
+      assign(deprecatedAPIs, Component.prototype);
+      deprecatedAPIs.isPureReactComponent = true;
+      var isArrayImpl = Array.isArray, REACT_CLIENT_REFERENCE = Symbol.for("react.client.reference"), ReactSharedInternals = {
+        H: null,
+        A: null,
+        T: null,
+        S: null,
+        actQueue: null,
+        asyncTransitions: 0,
+        isBatchingLegacy: false,
+        didScheduleLegacyUpdate: false,
+        didUsePromise: false,
+        thrownErrors: [],
+        getCurrentStack: null,
+        recentlyCreatedOwnerStacks: 0
+      }, hasOwnProperty = Object.prototype.hasOwnProperty, createTask = console.createTask ? console.createTask : function() {
+        return null;
+      };
+      deprecatedAPIs = {
+        react_stack_bottom_frame: function(callStackForError) {
+          return callStackForError();
+        }
+      };
+      var specialPropKeyWarningShown, didWarnAboutOldJSXRuntime;
+      var didWarnAboutElementRef = {};
+      var unknownOwnerDebugStack = deprecatedAPIs.react_stack_bottom_frame.bind(
+        deprecatedAPIs,
+        UnknownOwner
+      )();
+      var unknownOwnerDebugTask = createTask(getTaskName(UnknownOwner));
+      var didWarnAboutMaps = false, userProvidedKeyEscapeRegex = /\/+/g, reportGlobalError = "function" === typeof reportError ? reportError : function(error2) {
+        if ("object" === typeof window && "function" === typeof window.ErrorEvent) {
+          var event = new window.ErrorEvent("error", {
+            bubbles: true,
+            cancelable: true,
+            message: "object" === typeof error2 && null !== error2 && "string" === typeof error2.message ? String(error2.message) : String(error2),
+            error: error2
+          });
+          if (!window.dispatchEvent(event)) return;
+        } else if ("object" === typeof process && "function" === typeof process.emit) {
+          process.emit("uncaughtException", error2);
+          return;
+        }
+        console.error(error2);
+      }, didWarnAboutMessageChannel = false, enqueueTaskImpl = null, actScopeDepth = 0, didWarnNoAwaitAct = false, isFlushing = false, queueSeveralMicrotasks = "function" === typeof queueMicrotask ? function(callback) {
+        queueMicrotask(function() {
+          return queueMicrotask(callback);
+        });
+      } : enqueueTask;
+      deprecatedAPIs = Object.freeze({
+        __proto__: null,
+        c: function(size) {
+          return resolveDispatcher().useMemoCache(size);
+        }
+      });
+      var fnName = {
+        map: mapChildren,
+        forEach: function(children, forEachFunc, forEachContext) {
+          mapChildren(
+            children,
+            function() {
+              forEachFunc.apply(this, arguments);
+            },
+            forEachContext
+          );
+        },
+        count: function(children) {
+          var n = 0;
+          mapChildren(children, function() {
+            n++;
+          });
+          return n;
+        },
+        toArray: function(children) {
+          return mapChildren(children, function(child) {
+            return child;
+          }) || [];
+        },
+        only: function(children) {
+          if (!isValidElement(children))
+            throw Error(
+              "React.Children.only expected to receive a single React element child."
+            );
+          return children;
+        }
+      };
+      exports$1.Activity = REACT_ACTIVITY_TYPE;
+      exports$1.Children = fnName;
+      exports$1.Component = Component;
+      exports$1.Fragment = REACT_FRAGMENT_TYPE;
+      exports$1.Profiler = REACT_PROFILER_TYPE;
+      exports$1.PureComponent = PureComponent;
+      exports$1.StrictMode = REACT_STRICT_MODE_TYPE;
+      exports$1.Suspense = REACT_SUSPENSE_TYPE;
+      exports$1.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE = ReactSharedInternals;
+      exports$1.__COMPILER_RUNTIME = deprecatedAPIs;
+      exports$1.act = function(callback) {
+        var prevActQueue = ReactSharedInternals.actQueue, prevActScopeDepth = actScopeDepth;
+        actScopeDepth++;
+        var queue = ReactSharedInternals.actQueue = null !== prevActQueue ? prevActQueue : [], didAwaitActCall = false;
+        try {
+          var result = callback();
+        } catch (error2) {
+          ReactSharedInternals.thrownErrors.push(error2);
+        }
+        if (0 < ReactSharedInternals.thrownErrors.length)
+          throw popActScope(prevActQueue, prevActScopeDepth), callback = aggregateErrors(ReactSharedInternals.thrownErrors), ReactSharedInternals.thrownErrors.length = 0, callback;
+        if (null !== result && "object" === typeof result && "function" === typeof result.then) {
+          var thenable = result;
+          queueSeveralMicrotasks(function() {
+            didAwaitActCall || didWarnNoAwaitAct || (didWarnNoAwaitAct = true, console.error(
+              "You called act(async () => ...) without await. This could lead to unexpected testing behaviour, interleaving multiple act calls and mixing their scopes. You should - await act(async () => ...);"
+            ));
+          });
+          return {
+            then: function(resolve, reject) {
+              didAwaitActCall = true;
+              thenable.then(
+                function(returnValue) {
+                  popActScope(prevActQueue, prevActScopeDepth);
+                  if (0 === prevActScopeDepth) {
+                    try {
+                      flushActQueue(queue), enqueueTask(function() {
+                        return recursivelyFlushAsyncActWork(
+                          returnValue,
+                          resolve,
+                          reject
+                        );
+                      });
+                    } catch (error$0) {
+                      ReactSharedInternals.thrownErrors.push(error$0);
+                    }
+                    if (0 < ReactSharedInternals.thrownErrors.length) {
+                      var _thrownError = aggregateErrors(
+                        ReactSharedInternals.thrownErrors
+                      );
+                      ReactSharedInternals.thrownErrors.length = 0;
+                      reject(_thrownError);
+                    }
+                  } else resolve(returnValue);
+                },
+                function(error2) {
+                  popActScope(prevActQueue, prevActScopeDepth);
+                  0 < ReactSharedInternals.thrownErrors.length ? (error2 = aggregateErrors(
+                    ReactSharedInternals.thrownErrors
+                  ), ReactSharedInternals.thrownErrors.length = 0, reject(error2)) : reject(error2);
+                }
+              );
+            }
+          };
+        }
+        var returnValue$jscomp$0 = result;
+        popActScope(prevActQueue, prevActScopeDepth);
+        0 === prevActScopeDepth && (flushActQueue(queue), 0 !== queue.length && queueSeveralMicrotasks(function() {
+          didAwaitActCall || didWarnNoAwaitAct || (didWarnNoAwaitAct = true, console.error(
+            "A component suspended inside an `act` scope, but the `act` call was not awaited. When testing React components that depend on asynchronous data, you must await the result:\n\nawait act(() => ...)"
+          ));
+        }), ReactSharedInternals.actQueue = null);
+        if (0 < ReactSharedInternals.thrownErrors.length)
+          throw callback = aggregateErrors(ReactSharedInternals.thrownErrors), ReactSharedInternals.thrownErrors.length = 0, callback;
+        return {
+          then: function(resolve, reject) {
+            didAwaitActCall = true;
+            0 === prevActScopeDepth ? (ReactSharedInternals.actQueue = queue, enqueueTask(function() {
+              return recursivelyFlushAsyncActWork(
+                returnValue$jscomp$0,
+                resolve,
+                reject
+              );
+            })) : resolve(returnValue$jscomp$0);
+          }
+        };
+      };
+      exports$1.cache = function(fn2) {
+        return function() {
+          return fn2.apply(null, arguments);
+        };
+      };
+      exports$1.cacheSignal = function() {
+        return null;
+      };
+      exports$1.captureOwnerStack = function() {
+        var getCurrentStack = ReactSharedInternals.getCurrentStack;
+        return null === getCurrentStack ? null : getCurrentStack();
+      };
+      exports$1.cloneElement = function(element, config, children) {
+        if (null === element || void 0 === element)
+          throw Error(
+            "The argument must be a React element, but you passed " + element + "."
+          );
+        var props = assign({}, element.props), key = element.key, owner = element._owner;
+        if (null != config) {
+          var JSCompiler_inline_result;
+          a: {
+            if (hasOwnProperty.call(config, "ref") && (JSCompiler_inline_result = Object.getOwnPropertyDescriptor(
+              config,
+              "ref"
+            ).get) && JSCompiler_inline_result.isReactWarning) {
+              JSCompiler_inline_result = false;
+              break a;
+            }
+            JSCompiler_inline_result = void 0 !== config.ref;
+          }
+          JSCompiler_inline_result && (owner = getOwner());
+          hasValidKey(config) && (checkKeyStringCoercion(config.key), key = "" + config.key);
+          for (propName in config)
+            !hasOwnProperty.call(config, propName) || "key" === propName || "__self" === propName || "__source" === propName || "ref" === propName && void 0 === config.ref || (props[propName] = config[propName]);
+        }
+        var propName = arguments.length - 2;
+        if (1 === propName) props.children = children;
+        else if (1 < propName) {
+          JSCompiler_inline_result = Array(propName);
+          for (var i = 0; i < propName; i++)
+            JSCompiler_inline_result[i] = arguments[i + 2];
+          props.children = JSCompiler_inline_result;
+        }
+        props = ReactElement(
+          element.type,
+          key,
+          props,
+          owner,
+          element._debugStack,
+          element._debugTask
+        );
+        for (key = 2; key < arguments.length; key++)
+          validateChildKeys(arguments[key]);
+        return props;
+      };
+      exports$1.createContext = function(defaultValue) {
+        defaultValue = {
+          $$typeof: REACT_CONTEXT_TYPE,
+          _currentValue: defaultValue,
+          _currentValue2: defaultValue,
+          _threadCount: 0,
+          Provider: null,
+          Consumer: null
+        };
+        defaultValue.Provider = defaultValue;
+        defaultValue.Consumer = {
+          $$typeof: REACT_CONSUMER_TYPE,
+          _context: defaultValue
+        };
+        defaultValue._currentRenderer = null;
+        defaultValue._currentRenderer2 = null;
+        return defaultValue;
+      };
+      exports$1.createElement = function(type, config, children) {
+        for (var i = 2; i < arguments.length; i++)
+          validateChildKeys(arguments[i]);
+        i = {};
+        var key = null;
+        if (null != config)
+          for (propName in didWarnAboutOldJSXRuntime || !("__self" in config) || "key" in config || (didWarnAboutOldJSXRuntime = true, console.warn(
+            "Your app (or one of its dependencies) is using an outdated JSX transform. Update to the modern JSX transform for faster performance: https://react.dev/link/new-jsx-transform"
+          )), hasValidKey(config) && (checkKeyStringCoercion(config.key), key = "" + config.key), config)
+            hasOwnProperty.call(config, propName) && "key" !== propName && "__self" !== propName && "__source" !== propName && (i[propName] = config[propName]);
+        var childrenLength = arguments.length - 2;
+        if (1 === childrenLength) i.children = children;
+        else if (1 < childrenLength) {
+          for (var childArray = Array(childrenLength), _i = 0; _i < childrenLength; _i++)
+            childArray[_i] = arguments[_i + 2];
+          Object.freeze && Object.freeze(childArray);
+          i.children = childArray;
+        }
+        if (type && type.defaultProps)
+          for (propName in childrenLength = type.defaultProps, childrenLength)
+            void 0 === i[propName] && (i[propName] = childrenLength[propName]);
+        key && defineKeyPropWarningGetter(
+          i,
+          "function" === typeof type ? type.displayName || type.name || "Unknown" : type
+        );
+        var propName = 1e4 > ReactSharedInternals.recentlyCreatedOwnerStacks++;
+        return ReactElement(
+          type,
+          key,
+          i,
+          getOwner(),
+          propName ? Error("react-stack-top-frame") : unknownOwnerDebugStack,
+          propName ? createTask(getTaskName(type)) : unknownOwnerDebugTask
+        );
+      };
+      exports$1.createRef = function() {
+        var refObject = { current: null };
+        Object.seal(refObject);
+        return refObject;
+      };
+      exports$1.forwardRef = function(render) {
+        null != render && render.$$typeof === REACT_MEMO_TYPE ? console.error(
+          "forwardRef requires a render function but received a `memo` component. Instead of forwardRef(memo(...)), use memo(forwardRef(...))."
+        ) : "function" !== typeof render ? console.error(
+          "forwardRef requires a render function but was given %s.",
+          null === render ? "null" : typeof render
+        ) : 0 !== render.length && 2 !== render.length && console.error(
+          "forwardRef render functions accept exactly two parameters: props and ref. %s",
+          1 === render.length ? "Did you forget to use the ref parameter?" : "Any additional parameter will be undefined."
+        );
+        null != render && null != render.defaultProps && console.error(
+          "forwardRef render functions do not support defaultProps. Did you accidentally pass a React component?"
+        );
+        var elementType = { $$typeof: REACT_FORWARD_REF_TYPE, render }, ownName;
+        Object.defineProperty(elementType, "displayName", {
+          enumerable: false,
+          configurable: true,
+          get: function() {
+            return ownName;
+          },
+          set: function(name) {
+            ownName = name;
+            render.name || render.displayName || (Object.defineProperty(render, "name", { value: name }), render.displayName = name);
+          }
+        });
+        return elementType;
+      };
+      exports$1.isValidElement = isValidElement;
+      exports$1.lazy = function(ctor) {
+        ctor = { _status: -1, _result: ctor };
+        var lazyType = {
+          $$typeof: REACT_LAZY_TYPE,
+          _payload: ctor,
+          _init: lazyInitializer
+        }, ioInfo = {
+          name: "lazy",
+          start: -1,
+          end: -1,
+          value: null,
+          owner: null,
+          debugStack: Error("react-stack-top-frame"),
+          debugTask: console.createTask ? console.createTask("lazy()") : null
+        };
+        ctor._ioInfo = ioInfo;
+        lazyType._debugInfo = [{ awaited: ioInfo }];
+        return lazyType;
+      };
+      exports$1.memo = function(type, compare) {
+        null == type && console.error(
+          "memo: The first argument must be a component. Instead received: %s",
+          null === type ? "null" : typeof type
+        );
+        compare = {
+          $$typeof: REACT_MEMO_TYPE,
+          type,
+          compare: void 0 === compare ? null : compare
+        };
+        var ownName;
+        Object.defineProperty(compare, "displayName", {
+          enumerable: false,
+          configurable: true,
+          get: function() {
+            return ownName;
+          },
+          set: function(name) {
+            ownName = name;
+            type.name || type.displayName || (Object.defineProperty(type, "name", { value: name }), type.displayName = name);
+          }
+        });
+        return compare;
+      };
+      exports$1.startTransition = function(scope) {
+        var prevTransition = ReactSharedInternals.T, currentTransition = {};
+        currentTransition._updatedFibers = /* @__PURE__ */ new Set();
+        ReactSharedInternals.T = currentTransition;
+        try {
+          var returnValue = scope(), onStartTransitionFinish = ReactSharedInternals.S;
+          null !== onStartTransitionFinish && onStartTransitionFinish(currentTransition, returnValue);
+          "object" === typeof returnValue && null !== returnValue && "function" === typeof returnValue.then && (ReactSharedInternals.asyncTransitions++, returnValue.then(releaseAsyncTransition, releaseAsyncTransition), returnValue.then(noop, reportGlobalError));
+        } catch (error2) {
+          reportGlobalError(error2);
+        } finally {
+          null === prevTransition && currentTransition._updatedFibers && (scope = currentTransition._updatedFibers.size, currentTransition._updatedFibers.clear(), 10 < scope && console.warn(
+            "Detected a large number of updates inside startTransition. If this is due to a subscription please re-write it to use React provided hooks. Otherwise concurrent mode guarantees are off the table."
+          )), null !== prevTransition && null !== currentTransition.types && (null !== prevTransition.types && prevTransition.types !== currentTransition.types && console.error(
+            "We expected inner Transitions to have transferred the outer types set and that you cannot add to the outer Transition while inside the inner.This is a bug in React."
+          ), prevTransition.types = currentTransition.types), ReactSharedInternals.T = prevTransition;
+        }
+      };
+      exports$1.unstable_useCacheRefresh = function() {
+        return resolveDispatcher().useCacheRefresh();
+      };
+      exports$1.use = function(usable) {
+        return resolveDispatcher().use(usable);
+      };
+      exports$1.useActionState = function(action, initialState, permalink) {
+        return resolveDispatcher().useActionState(
+          action,
+          initialState,
+          permalink
+        );
+      };
+      exports$1.useCallback = function(callback, deps) {
+        return resolveDispatcher().useCallback(callback, deps);
+      };
+      exports$1.useContext = function(Context) {
+        var dispatcher = resolveDispatcher();
+        Context.$$typeof === REACT_CONSUMER_TYPE && console.error(
+          "Calling useContext(Context.Consumer) is not supported and will cause bugs. Did you mean to call useContext(Context) instead?"
+        );
+        return dispatcher.useContext(Context);
+      };
+      exports$1.useDebugValue = function(value, formatterFn) {
+        return resolveDispatcher().useDebugValue(value, formatterFn);
+      };
+      exports$1.useDeferredValue = function(value, initialValue) {
+        return resolveDispatcher().useDeferredValue(value, initialValue);
+      };
+      exports$1.useEffect = function(create, deps) {
+        null == create && console.warn(
+          "React Hook useEffect requires an effect callback. Did you forget to pass a callback to the hook?"
+        );
+        return resolveDispatcher().useEffect(create, deps);
+      };
+      exports$1.useEffectEvent = function(callback) {
+        return resolveDispatcher().useEffectEvent(callback);
+      };
+      exports$1.useId = function() {
+        return resolveDispatcher().useId();
+      };
+      exports$1.useImperativeHandle = function(ref, create, deps) {
+        return resolveDispatcher().useImperativeHandle(ref, create, deps);
+      };
+      exports$1.useInsertionEffect = function(create, deps) {
+        null == create && console.warn(
+          "React Hook useInsertionEffect requires an effect callback. Did you forget to pass a callback to the hook?"
+        );
+        return resolveDispatcher().useInsertionEffect(create, deps);
+      };
+      exports$1.useLayoutEffect = function(create, deps) {
+        null == create && console.warn(
+          "React Hook useLayoutEffect requires an effect callback. Did you forget to pass a callback to the hook?"
+        );
+        return resolveDispatcher().useLayoutEffect(create, deps);
+      };
+      exports$1.useMemo = function(create, deps) {
+        return resolveDispatcher().useMemo(create, deps);
+      };
+      exports$1.useOptimistic = function(passthrough, reducer) {
+        return resolveDispatcher().useOptimistic(passthrough, reducer);
+      };
+      exports$1.useReducer = function(reducer, initialArg, init) {
+        return resolveDispatcher().useReducer(reducer, initialArg, init);
+      };
+      exports$1.useRef = function(initialValue) {
+        return resolveDispatcher().useRef(initialValue);
+      };
+      exports$1.useState = function(initialState) {
+        return resolveDispatcher().useState(initialState);
+      };
+      exports$1.useSyncExternalStore = function(subscribe2, getSnapshot, getServerSnapshot) {
+        return resolveDispatcher().useSyncExternalStore(
+          subscribe2,
+          getSnapshot,
+          getServerSnapshot
+        );
+      };
+      exports$1.useTransition = function() {
+        return resolveDispatcher().useTransition();
+      };
+      exports$1.version = "19.2.3";
+      "undefined" !== typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ && "function" === typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop && __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop(Error());
+    })();
+  })(react_development, react_development.exports);
+  return react_development.exports;
+}
+var hasRequiredReact;
+function requireReact() {
+  if (hasRequiredReact) return react.exports;
+  hasRequiredReact = 1;
+  if (process.env.NODE_ENV === "production") {
+    react.exports = requireReact_production();
+  } else {
+    react.exports = requireReact_development();
+  }
+  return react.exports;
+}
+var hasRequiredReactJsxRuntime_development;
+function requireReactJsxRuntime_development() {
+  if (hasRequiredReactJsxRuntime_development) return reactJsxRuntime_development;
+  hasRequiredReactJsxRuntime_development = 1;
+  "production" !== process.env.NODE_ENV && (function() {
+    function getComponentNameFromType(type) {
+      if (null == type) return null;
+      if ("function" === typeof type)
+        return type.$$typeof === REACT_CLIENT_REFERENCE ? null : type.displayName || type.name || null;
+      if ("string" === typeof type) return type;
+      switch (type) {
+        case REACT_FRAGMENT_TYPE:
+          return "Fragment";
+        case REACT_PROFILER_TYPE:
+          return "Profiler";
+        case REACT_STRICT_MODE_TYPE:
+          return "StrictMode";
+        case REACT_SUSPENSE_TYPE:
+          return "Suspense";
+        case REACT_SUSPENSE_LIST_TYPE:
+          return "SuspenseList";
+        case REACT_ACTIVITY_TYPE:
+          return "Activity";
+      }
+      if ("object" === typeof type)
+        switch ("number" === typeof type.tag && console.error(
+          "Received an unexpected object in getComponentNameFromType(). This is likely a bug in React. Please file an issue."
+        ), type.$$typeof) {
+          case REACT_PORTAL_TYPE:
+            return "Portal";
+          case REACT_CONTEXT_TYPE:
+            return type.displayName || "Context";
+          case REACT_CONSUMER_TYPE:
+            return (type._context.displayName || "Context") + ".Consumer";
+          case REACT_FORWARD_REF_TYPE:
+            var innerType = type.render;
+            type = type.displayName;
+            type || (type = innerType.displayName || innerType.name || "", type = "" !== type ? "ForwardRef(" + type + ")" : "ForwardRef");
+            return type;
+          case REACT_MEMO_TYPE:
+            return innerType = type.displayName || null, null !== innerType ? innerType : getComponentNameFromType(type.type) || "Memo";
+          case REACT_LAZY_TYPE:
+            innerType = type._payload;
+            type = type._init;
+            try {
+              return getComponentNameFromType(type(innerType));
+            } catch (x2) {
+            }
+        }
+      return null;
+    }
+    function testStringCoercion(value) {
+      return "" + value;
+    }
+    function checkKeyStringCoercion(value) {
+      try {
+        testStringCoercion(value);
+        var JSCompiler_inline_result = false;
+      } catch (e) {
+        JSCompiler_inline_result = true;
+      }
+      if (JSCompiler_inline_result) {
+        JSCompiler_inline_result = console;
+        var JSCompiler_temp_const = JSCompiler_inline_result.error;
+        var JSCompiler_inline_result$jscomp$0 = "function" === typeof Symbol && Symbol.toStringTag && value[Symbol.toStringTag] || value.constructor.name || "Object";
+        JSCompiler_temp_const.call(
+          JSCompiler_inline_result,
+          "The provided key is an unsupported type %s. This value must be coerced to a string before using it here.",
+          JSCompiler_inline_result$jscomp$0
+        );
+        return testStringCoercion(value);
+      }
+    }
+    function getTaskName(type) {
+      if (type === REACT_FRAGMENT_TYPE) return "<>";
+      if ("object" === typeof type && null !== type && type.$$typeof === REACT_LAZY_TYPE)
+        return "<...>";
+      try {
+        var name = getComponentNameFromType(type);
+        return name ? "<" + name + ">" : "<...>";
+      } catch (x2) {
+        return "<...>";
+      }
+    }
+    function getOwner() {
+      var dispatcher = ReactSharedInternals.A;
+      return null === dispatcher ? null : dispatcher.getOwner();
+    }
+    function UnknownOwner() {
+      return Error("react-stack-top-frame");
+    }
+    function hasValidKey(config) {
+      if (hasOwnProperty.call(config, "key")) {
+        var getter = Object.getOwnPropertyDescriptor(config, "key").get;
+        if (getter && getter.isReactWarning) return false;
+      }
+      return void 0 !== config.key;
+    }
+    function defineKeyPropWarningGetter(props, displayName) {
+      function warnAboutAccessingKey() {
+        specialPropKeyWarningShown || (specialPropKeyWarningShown = true, console.error(
+          "%s: `key` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://react.dev/link/special-props)",
+          displayName
+        ));
+      }
+      warnAboutAccessingKey.isReactWarning = true;
+      Object.defineProperty(props, "key", {
+        get: warnAboutAccessingKey,
+        configurable: true
+      });
+    }
+    function elementRefGetterWithDeprecationWarning() {
+      var componentName = getComponentNameFromType(this.type);
+      didWarnAboutElementRef[componentName] || (didWarnAboutElementRef[componentName] = true, console.error(
+        "Accessing element.ref was removed in React 19. ref is now a regular prop. It will be removed from the JSX Element type in a future release."
+      ));
+      componentName = this.props.ref;
+      return void 0 !== componentName ? componentName : null;
+    }
+    function ReactElement(type, key, props, owner, debugStack, debugTask) {
+      var refProp = props.ref;
+      type = {
+        $$typeof: REACT_ELEMENT_TYPE,
+        type,
+        key,
+        props,
+        _owner: owner
+      };
+      null !== (void 0 !== refProp ? refProp : null) ? Object.defineProperty(type, "ref", {
+        enumerable: false,
+        get: elementRefGetterWithDeprecationWarning
+      }) : Object.defineProperty(type, "ref", { enumerable: false, value: null });
+      type._store = {};
+      Object.defineProperty(type._store, "validated", {
+        configurable: false,
+        enumerable: false,
+        writable: true,
+        value: 0
+      });
+      Object.defineProperty(type, "_debugInfo", {
+        configurable: false,
+        enumerable: false,
+        writable: true,
+        value: null
+      });
+      Object.defineProperty(type, "_debugStack", {
+        configurable: false,
+        enumerable: false,
+        writable: true,
+        value: debugStack
+      });
+      Object.defineProperty(type, "_debugTask", {
+        configurable: false,
+        enumerable: false,
+        writable: true,
+        value: debugTask
+      });
+      Object.freeze && (Object.freeze(type.props), Object.freeze(type));
+      return type;
+    }
+    function jsxDEVImpl(type, config, maybeKey, isStaticChildren, debugStack, debugTask) {
+      var children = config.children;
+      if (void 0 !== children)
+        if (isStaticChildren)
+          if (isArrayImpl(children)) {
+            for (isStaticChildren = 0; isStaticChildren < children.length; isStaticChildren++)
+              validateChildKeys(children[isStaticChildren]);
+            Object.freeze && Object.freeze(children);
+          } else
+            console.error(
+              "React.jsx: Static children should always be an array. You are likely explicitly calling React.jsxs or React.jsxDEV. Use the Babel transform instead."
+            );
+        else validateChildKeys(children);
+      if (hasOwnProperty.call(config, "key")) {
+        children = getComponentNameFromType(type);
+        var keys = Object.keys(config).filter(function(k2) {
+          return "key" !== k2;
+        });
+        isStaticChildren = 0 < keys.length ? "{key: someKey, " + keys.join(": ..., ") + ": ...}" : "{key: someKey}";
+        didWarnAboutKeySpread[children + isStaticChildren] || (keys = 0 < keys.length ? "{" + keys.join(": ..., ") + ": ...}" : "{}", console.error(
+          'A props object containing a "key" prop is being spread into JSX:\n  let props = %s;\n  <%s {...props} />\nReact keys must be passed directly to JSX without using spread:\n  let props = %s;\n  <%s key={someKey} {...props} />',
+          isStaticChildren,
+          children,
+          keys,
+          children
+        ), didWarnAboutKeySpread[children + isStaticChildren] = true);
+      }
+      children = null;
+      void 0 !== maybeKey && (checkKeyStringCoercion(maybeKey), children = "" + maybeKey);
+      hasValidKey(config) && (checkKeyStringCoercion(config.key), children = "" + config.key);
+      if ("key" in config) {
+        maybeKey = {};
+        for (var propName in config)
+          "key" !== propName && (maybeKey[propName] = config[propName]);
+      } else maybeKey = config;
+      children && defineKeyPropWarningGetter(
+        maybeKey,
+        "function" === typeof type ? type.displayName || type.name || "Unknown" : type
+      );
+      return ReactElement(
+        type,
+        children,
+        maybeKey,
+        getOwner(),
+        debugStack,
+        debugTask
+      );
+    }
+    function validateChildKeys(node) {
+      isValidElement(node) ? node._store && (node._store.validated = 1) : "object" === typeof node && null !== node && node.$$typeof === REACT_LAZY_TYPE && ("fulfilled" === node._payload.status ? isValidElement(node._payload.value) && node._payload.value._store && (node._payload.value._store.validated = 1) : node._store && (node._store.validated = 1));
+    }
+    function isValidElement(object) {
+      return "object" === typeof object && null !== object && object.$$typeof === REACT_ELEMENT_TYPE;
+    }
+    var React = requireReact(), REACT_ELEMENT_TYPE = Symbol.for("react.transitional.element"), REACT_PORTAL_TYPE = Symbol.for("react.portal"), REACT_FRAGMENT_TYPE = Symbol.for("react.fragment"), REACT_STRICT_MODE_TYPE = Symbol.for("react.strict_mode"), REACT_PROFILER_TYPE = Symbol.for("react.profiler"), REACT_CONSUMER_TYPE = Symbol.for("react.consumer"), REACT_CONTEXT_TYPE = Symbol.for("react.context"), REACT_FORWARD_REF_TYPE = Symbol.for("react.forward_ref"), REACT_SUSPENSE_TYPE = Symbol.for("react.suspense"), REACT_SUSPENSE_LIST_TYPE = Symbol.for("react.suspense_list"), REACT_MEMO_TYPE = Symbol.for("react.memo"), REACT_LAZY_TYPE = Symbol.for("react.lazy"), REACT_ACTIVITY_TYPE = Symbol.for("react.activity"), REACT_CLIENT_REFERENCE = Symbol.for("react.client.reference"), ReactSharedInternals = React.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE, hasOwnProperty = Object.prototype.hasOwnProperty, isArrayImpl = Array.isArray, createTask = console.createTask ? console.createTask : function() {
+      return null;
+    };
+    React = {
+      react_stack_bottom_frame: function(callStackForError) {
+        return callStackForError();
+      }
+    };
+    var specialPropKeyWarningShown;
+    var didWarnAboutElementRef = {};
+    var unknownOwnerDebugStack = React.react_stack_bottom_frame.bind(
+      React,
+      UnknownOwner
+    )();
+    var unknownOwnerDebugTask = createTask(getTaskName(UnknownOwner));
+    var didWarnAboutKeySpread = {};
+    reactJsxRuntime_development.Fragment = REACT_FRAGMENT_TYPE;
+    reactJsxRuntime_development.jsx = function(type, config, maybeKey) {
+      var trackActualOwner = 1e4 > ReactSharedInternals.recentlyCreatedOwnerStacks++;
+      return jsxDEVImpl(
+        type,
+        config,
+        maybeKey,
+        false,
+        trackActualOwner ? Error("react-stack-top-frame") : unknownOwnerDebugStack,
+        trackActualOwner ? createTask(getTaskName(type)) : unknownOwnerDebugTask
+      );
+    };
+    reactJsxRuntime_development.jsxs = function(type, config, maybeKey) {
+      var trackActualOwner = 1e4 > ReactSharedInternals.recentlyCreatedOwnerStacks++;
+      return jsxDEVImpl(
+        type,
+        config,
+        maybeKey,
+        true,
+        trackActualOwner ? Error("react-stack-top-frame") : unknownOwnerDebugStack,
+        trackActualOwner ? createTask(getTaskName(type)) : unknownOwnerDebugTask
+      );
+    };
+  })();
+  return reactJsxRuntime_development;
+}
+var hasRequiredJsxRuntime;
+function requireJsxRuntime() {
+  if (hasRequiredJsxRuntime) return jsxRuntime.exports;
+  hasRequiredJsxRuntime = 1;
+  if (process.env.NODE_ENV === "production") {
+    jsxRuntime.exports = requireReactJsxRuntime_production();
+  } else {
+    jsxRuntime.exports = requireReactJsxRuntime_development();
+  }
+  return jsxRuntime.exports;
+}
+var jsxRuntimeExports = requireJsxRuntime();
+const __storeToDerived = /* @__PURE__ */ new WeakMap();
+const __derivedToStore = /* @__PURE__ */ new WeakMap();
+const __depsThatHaveWrittenThisTick = {
+  current: []
+};
+let __isFlushing = false;
+let __batchDepth = 0;
+const __pendingUpdates = /* @__PURE__ */ new Set();
+const __initialBatchValues = /* @__PURE__ */ new Map();
+function __flush_internals(relatedVals) {
+  for (const derived of relatedVals) {
+    if (__depsThatHaveWrittenThisTick.current.includes(derived)) {
+      continue;
+    }
+    __depsThatHaveWrittenThisTick.current.push(derived);
+    derived.recompute();
+    const stores = __derivedToStore.get(derived);
+    if (stores) {
+      for (const store of stores) {
+        const relatedLinkedDerivedVals = __storeToDerived.get(store);
+        if (!(relatedLinkedDerivedVals == null ? void 0 : relatedLinkedDerivedVals.length)) continue;
+        __flush_internals(relatedLinkedDerivedVals);
+      }
+    }
+  }
+}
+function __notifyListeners(store) {
+  const value = {
+    prevVal: store.prevState,
+    currentVal: store.state
+  };
+  for (const listener of store.listeners) {
+    listener(value);
+  }
+}
+function __notifyDerivedListeners(derived) {
+  const value = {
+    prevVal: derived.prevState,
+    currentVal: derived.state
+  };
+  for (const listener of derived.listeners) {
+    listener(value);
+  }
+}
+function __flush(store) {
+  if (__batchDepth > 0 && !__initialBatchValues.has(store)) {
+    __initialBatchValues.set(store, store.prevState);
+  }
+  __pendingUpdates.add(store);
+  if (__batchDepth > 0) return;
+  if (__isFlushing) return;
+  try {
+    __isFlushing = true;
+    while (__pendingUpdates.size > 0) {
+      const stores = Array.from(__pendingUpdates);
+      __pendingUpdates.clear();
+      for (const store2 of stores) {
+        const prevState = __initialBatchValues.get(store2) ?? store2.prevState;
+        store2.prevState = prevState;
+        __notifyListeners(store2);
+      }
+      for (const store2 of stores) {
+        const derivedVals = __storeToDerived.get(store2);
+        if (!derivedVals) continue;
+        __depsThatHaveWrittenThisTick.current.push(store2);
+        __flush_internals(derivedVals);
+      }
+      for (const store2 of stores) {
+        const derivedVals = __storeToDerived.get(store2);
+        if (!derivedVals) continue;
+        for (const derived of derivedVals) {
+          __notifyDerivedListeners(derived);
+        }
+      }
+    }
+  } finally {
+    __isFlushing = false;
+    __depsThatHaveWrittenThisTick.current = [];
+    __initialBatchValues.clear();
+  }
+}
+function batch(fn2) {
+  __batchDepth++;
+  try {
+    fn2();
+  } finally {
+    __batchDepth--;
+    if (__batchDepth === 0) {
+      const pendingUpdateToFlush = __pendingUpdates.values().next().value;
+      if (pendingUpdateToFlush) {
+        __flush(pendingUpdateToFlush);
+      }
+    }
+  }
+}
+function isUpdaterFunction(updater) {
+  return typeof updater === "function";
+}
+class Store {
+  constructor(initialState, options) {
+    this.listeners = /* @__PURE__ */ new Set();
+    this.subscribe = (listener) => {
+      var _a, _b;
+      this.listeners.add(listener);
+      const unsub = (_b = (_a = this.options) == null ? void 0 : _a.onSubscribe) == null ? void 0 : _b.call(_a, listener, this);
+      return () => {
+        this.listeners.delete(listener);
+        unsub == null ? void 0 : unsub();
+      };
+    };
+    this.prevState = initialState;
+    this.state = initialState;
+    this.options = options;
+  }
+  setState(updater) {
+    var _a, _b, _c;
+    this.prevState = this.state;
+    if ((_a = this.options) == null ? void 0 : _a.updateFn) {
+      this.state = this.options.updateFn(this.prevState)(updater);
+    } else {
+      if (isUpdaterFunction(updater)) {
+        this.state = updater(this.prevState);
+      } else {
+        this.state = updater;
+      }
+    }
+    (_c = (_b = this.options) == null ? void 0 : _b.onUpdate) == null ? void 0 : _c.call(_b);
+    __flush(this);
+  }
+}
+const stateIndexKey = "__TSR_index";
+const popStateEvent = "popstate";
+const beforeUnloadEvent = "beforeunload";
+function createHistory(opts) {
+  let location = opts.getLocation();
+  const subscribers = /* @__PURE__ */ new Set();
+  const notify = (action) => {
+    location = opts.getLocation();
+    subscribers.forEach((subscriber) => subscriber({ location, action }));
+  };
+  const handleIndexChange = (action) => {
+    if (opts.notifyOnIndexChange ?? true) notify(action);
+    else location = opts.getLocation();
+  };
+  const tryNavigation = async ({
+    task,
+    navigateOpts,
+    ...actionInfo
+  }) => {
+    const ignoreBlocker = navigateOpts?.ignoreBlocker ?? false;
+    if (ignoreBlocker) {
+      task();
+      return;
+    }
+    const blockers = opts.getBlockers?.() ?? [];
+    const isPushOrReplace = actionInfo.type === "PUSH" || actionInfo.type === "REPLACE";
+    if (typeof document !== "undefined" && blockers.length && isPushOrReplace) {
+      for (const blocker of blockers) {
+        const nextLocation = parseHref(actionInfo.path, actionInfo.state);
+        const isBlocked = await blocker.blockerFn({
+          currentLocation: location,
+          nextLocation,
+          action: actionInfo.type
+        });
+        if (isBlocked) {
+          opts.onBlocked?.();
+          return;
+        }
+      }
+    }
+    task();
+  };
+  return {
+    get location() {
+      return location;
+    },
+    get length() {
+      return opts.getLength();
+    },
+    subscribers,
+    subscribe: (cb) => {
+      subscribers.add(cb);
+      return () => {
+        subscribers.delete(cb);
+      };
+    },
+    push: (path, state, navigateOpts) => {
+      const currentIndex = location.state[stateIndexKey];
+      state = assignKeyAndIndex(currentIndex + 1, state);
+      tryNavigation({
+        task: () => {
+          opts.pushState(path, state);
+          notify({ type: "PUSH" });
+        },
+        navigateOpts,
+        type: "PUSH",
+        path,
+        state
+      });
+    },
+    replace: (path, state, navigateOpts) => {
+      const currentIndex = location.state[stateIndexKey];
+      state = assignKeyAndIndex(currentIndex, state);
+      tryNavigation({
+        task: () => {
+          opts.replaceState(path, state);
+          notify({ type: "REPLACE" });
+        },
+        navigateOpts,
+        type: "REPLACE",
+        path,
+        state
+      });
+    },
+    go: (index, navigateOpts) => {
+      tryNavigation({
+        task: () => {
+          opts.go(index);
+          handleIndexChange({ type: "GO", index });
+        },
+        navigateOpts,
+        type: "GO"
+      });
+    },
+    back: (navigateOpts) => {
+      tryNavigation({
+        task: () => {
+          opts.back(navigateOpts?.ignoreBlocker ?? false);
+          handleIndexChange({ type: "BACK" });
+        },
+        navigateOpts,
+        type: "BACK"
+      });
+    },
+    forward: (navigateOpts) => {
+      tryNavigation({
+        task: () => {
+          opts.forward(navigateOpts?.ignoreBlocker ?? false);
+          handleIndexChange({ type: "FORWARD" });
+        },
+        navigateOpts,
+        type: "FORWARD"
+      });
+    },
+    canGoBack: () => location.state[stateIndexKey] !== 0,
+    createHref: (str) => opts.createHref(str),
+    block: (blocker) => {
+      if (!opts.setBlockers) return () => {
+      };
+      const blockers = opts.getBlockers?.() ?? [];
+      opts.setBlockers([...blockers, blocker]);
+      return () => {
+        const blockers2 = opts.getBlockers?.() ?? [];
+        opts.setBlockers?.(blockers2.filter((b2) => b2 !== blocker));
+      };
+    },
+    flush: () => opts.flush?.(),
+    destroy: () => opts.destroy?.(),
+    notify
+  };
+}
+function assignKeyAndIndex(index, state) {
+  if (!state) {
+    state = {};
+  }
+  const key = createRandomKey();
+  return {
+    ...state,
+    key,
+    // TODO: Remove in v2 - use __TSR_key instead
+    __TSR_key: key,
+    [stateIndexKey]: index
+  };
+}
+function createBrowserHistory(opts) {
+  const win = typeof document !== "undefined" ? window : void 0;
+  const originalPushState = win.history.pushState;
+  const originalReplaceState = win.history.replaceState;
+  let blockers = [];
+  const _getBlockers = () => blockers;
+  const _setBlockers = (newBlockers) => blockers = newBlockers;
+  const createHref = ((path) => path);
+  const parseLocation = (() => parseHref(
+    `${win.location.pathname}${win.location.search}${win.location.hash}`,
+    win.history.state
+  ));
+  if (!win.history.state?.__TSR_key && !win.history.state?.key) {
+    const addedKey = createRandomKey();
+    win.history.replaceState(
+      {
+        [stateIndexKey]: 0,
+        key: addedKey,
+        // TODO: Remove in v2 - use __TSR_key instead
+        __TSR_key: addedKey
+      },
+      ""
+    );
+  }
+  let currentLocation = parseLocation();
+  let rollbackLocation;
+  let nextPopIsGo = false;
+  let ignoreNextPop = false;
+  let skipBlockerNextPop = false;
+  let ignoreNextBeforeUnload = false;
+  const getLocation = () => currentLocation;
+  let next;
+  let scheduled;
+  const flush = () => {
+    if (!next) {
+      return;
+    }
+    history._ignoreSubscribers = true;
+    (next.isPush ? win.history.pushState : win.history.replaceState)(
+      next.state,
+      "",
+      next.href
+    );
+    history._ignoreSubscribers = false;
+    next = void 0;
+    scheduled = void 0;
+    rollbackLocation = void 0;
+  };
+  const queueHistoryAction = (type, destHref, state) => {
+    const href = createHref(destHref);
+    if (!scheduled) {
+      rollbackLocation = currentLocation;
+    }
+    currentLocation = parseHref(destHref, state);
+    next = {
+      href,
+      state,
+      isPush: next?.isPush || type === "push"
+    };
+    if (!scheduled) {
+      scheduled = Promise.resolve().then(() => flush());
+    }
+  };
+  const onPushPop = (type) => {
+    currentLocation = parseLocation();
+    history.notify({ type });
+  };
+  const onPushPopEvent = async () => {
+    if (ignoreNextPop) {
+      ignoreNextPop = false;
+      return;
+    }
+    const nextLocation = parseLocation();
+    const delta = nextLocation.state[stateIndexKey] - currentLocation.state[stateIndexKey];
+    const isForward = delta === 1;
+    const isBack = delta === -1;
+    const isGo = !isForward && !isBack || nextPopIsGo;
+    nextPopIsGo = false;
+    const action = isGo ? "GO" : isBack ? "BACK" : "FORWARD";
+    const notify = isGo ? {
+      type: "GO",
+      index: delta
+    } : {
+      type: isBack ? "BACK" : "FORWARD"
+    };
+    if (skipBlockerNextPop) {
+      skipBlockerNextPop = false;
+    } else {
+      const blockers2 = _getBlockers();
+      if (typeof document !== "undefined" && blockers2.length) {
+        for (const blocker of blockers2) {
+          const isBlocked = await blocker.blockerFn({
+            currentLocation,
+            nextLocation,
+            action
+          });
+          if (isBlocked) {
+            ignoreNextPop = true;
+            win.history.go(1);
+            history.notify(notify);
+            return;
+          }
+        }
+      }
+    }
+    currentLocation = parseLocation();
+    history.notify(notify);
+  };
+  const onBeforeUnload = (e) => {
+    if (ignoreNextBeforeUnload) {
+      ignoreNextBeforeUnload = false;
+      return;
+    }
+    let shouldBlock = false;
+    const blockers2 = _getBlockers();
+    if (typeof document !== "undefined" && blockers2.length) {
+      for (const blocker of blockers2) {
+        const shouldHaveBeforeUnload = blocker.enableBeforeUnload ?? true;
+        if (shouldHaveBeforeUnload === true) {
+          shouldBlock = true;
+          break;
+        }
+        if (typeof shouldHaveBeforeUnload === "function" && shouldHaveBeforeUnload() === true) {
+          shouldBlock = true;
+          break;
+        }
+      }
+    }
+    if (shouldBlock) {
+      e.preventDefault();
+      return e.returnValue = "";
+    }
+    return;
+  };
+  const history = createHistory({
+    getLocation,
+    getLength: () => win.history.length,
+    pushState: (href, state) => queueHistoryAction("push", href, state),
+    replaceState: (href, state) => queueHistoryAction("replace", href, state),
+    back: (ignoreBlocker) => {
+      if (ignoreBlocker) skipBlockerNextPop = true;
+      ignoreNextBeforeUnload = true;
+      return win.history.back();
+    },
+    forward: (ignoreBlocker) => {
+      if (ignoreBlocker) skipBlockerNextPop = true;
+      ignoreNextBeforeUnload = true;
+      win.history.forward();
+    },
+    go: (n) => {
+      nextPopIsGo = true;
+      win.history.go(n);
+    },
+    createHref: (href) => createHref(href),
+    flush,
+    destroy: () => {
+      win.history.pushState = originalPushState;
+      win.history.replaceState = originalReplaceState;
+      win.removeEventListener(beforeUnloadEvent, onBeforeUnload, {
+        capture: true
+      });
+      win.removeEventListener(popStateEvent, onPushPopEvent);
+    },
+    onBlocked: () => {
+      if (rollbackLocation && currentLocation !== rollbackLocation) {
+        currentLocation = rollbackLocation;
+      }
+    },
+    getBlockers: _getBlockers,
+    setBlockers: _setBlockers,
+    notifyOnIndexChange: false
+  });
+  win.addEventListener(beforeUnloadEvent, onBeforeUnload, { capture: true });
+  win.addEventListener(popStateEvent, onPushPopEvent);
+  win.history.pushState = function(...args) {
+    const res = originalPushState.apply(win.history, args);
+    if (!history._ignoreSubscribers) onPushPop("PUSH");
+    return res;
+  };
+  win.history.replaceState = function(...args) {
+    const res = originalReplaceState.apply(win.history, args);
+    if (!history._ignoreSubscribers) onPushPop("REPLACE");
+    return res;
+  };
+  return history;
+}
+function createMemoryHistory(opts = {
+  initialEntries: ["/"]
+}) {
+  const entries = opts.initialEntries;
+  let index = opts.initialIndex ? Math.min(Math.max(opts.initialIndex, 0), entries.length - 1) : entries.length - 1;
+  const states = entries.map(
+    (_entry, index2) => assignKeyAndIndex(index2, void 0)
+  );
+  const getLocation = () => parseHref(entries[index], states[index]);
+  return createHistory({
+    getLocation,
+    getLength: () => entries.length,
+    pushState: (path, state) => {
+      if (index < entries.length - 1) {
+        entries.splice(index + 1);
+        states.splice(index + 1);
+      }
+      states.push(state);
+      entries.push(path);
+      index = Math.max(entries.length - 1, 0);
+    },
+    replaceState: (path, state) => {
+      states[index] = state;
+      entries[index] = path;
+    },
+    back: () => {
+      index = Math.max(index - 1, 0);
+    },
+    forward: () => {
+      index = Math.min(index + 1, entries.length - 1);
+    },
+    go: (n) => {
+      index = Math.min(Math.max(index + n, 0), entries.length - 1);
+    },
+    createHref: (path) => path
+  });
+}
+function parseHref(href, state) {
+  const hashIndex = href.indexOf("#");
+  const searchIndex = href.indexOf("?");
+  const addedKey = createRandomKey();
+  return {
+    href,
+    pathname: href.substring(
+      0,
+      hashIndex > 0 ? searchIndex > 0 ? Math.min(hashIndex, searchIndex) : hashIndex : searchIndex > 0 ? searchIndex : href.length
+    ),
+    hash: hashIndex > -1 ? href.substring(hashIndex) : "",
+    search: searchIndex > -1 ? href.slice(searchIndex, hashIndex === -1 ? void 0 : hashIndex) : "",
+    state: state || { [stateIndexKey]: 0, key: addedKey, __TSR_key: addedKey }
+  };
+}
+function createRandomKey() {
+  return (Math.random() + 1).toString(36).substring(7);
+}
+function last(arr) {
+  return arr[arr.length - 1];
+}
+function isFunction(d) {
+  return typeof d === "function";
+}
+function functionalUpdate(updater, previous) {
+  if (isFunction(updater)) {
+    return updater(previous);
+  }
+  return updater;
+}
+const hasOwn = Object.prototype.hasOwnProperty;
+function replaceEqualDeep(prev, _next) {
+  if (prev === _next) {
+    return prev;
+  }
+  const next = _next;
+  const array = isPlainArray(prev) && isPlainArray(next);
+  if (!array && !(isPlainObject(prev) && isPlainObject(next))) return next;
+  const prevItems = array ? prev : getEnumerableOwnKeys(prev);
+  if (!prevItems) return next;
+  const nextItems = array ? next : getEnumerableOwnKeys(next);
+  if (!nextItems) return next;
+  const prevSize = prevItems.length;
+  const nextSize = nextItems.length;
+  const copy = array ? new Array(nextSize) : {};
+  let equalItems = 0;
+  for (let i = 0; i < nextSize; i++) {
+    const key = array ? i : nextItems[i];
+    const p2 = prev[key];
+    const n = next[key];
+    if (p2 === n) {
+      copy[key] = p2;
+      if (array ? i < prevSize : hasOwn.call(prev, key)) equalItems++;
+      continue;
+    }
+    if (p2 === null || n === null || typeof p2 !== "object" || typeof n !== "object") {
+      copy[key] = n;
+      continue;
+    }
+    const v2 = replaceEqualDeep(p2, n);
+    copy[key] = v2;
+    if (v2 === p2) equalItems++;
+  }
+  return prevSize === nextSize && equalItems === prevSize ? prev : copy;
+}
+function getEnumerableOwnKeys(o2) {
+  const keys = [];
+  const names = Object.getOwnPropertyNames(o2);
+  for (const name of names) {
+    if (!Object.prototype.propertyIsEnumerable.call(o2, name)) return false;
+    keys.push(name);
+  }
+  const symbols = Object.getOwnPropertySymbols(o2);
+  for (const symbol of symbols) {
+    if (!Object.prototype.propertyIsEnumerable.call(o2, symbol)) return false;
+    keys.push(symbol);
+  }
+  return keys;
+}
+function isPlainObject(o2) {
+  if (!hasObjectPrototype(o2)) {
+    return false;
+  }
+  const ctor = o2.constructor;
+  if (typeof ctor === "undefined") {
+    return true;
+  }
+  const prot = ctor.prototype;
+  if (!hasObjectPrototype(prot)) {
+    return false;
+  }
+  if (!prot.hasOwnProperty("isPrototypeOf")) {
+    return false;
+  }
+  return true;
+}
+function hasObjectPrototype(o2) {
+  return Object.prototype.toString.call(o2) === "[object Object]";
+}
+function isPlainArray(value) {
+  return Array.isArray(value) && value.length === Object.keys(value).length;
+}
+function deepEqual(a, b2, opts) {
+  if (a === b2) {
+    return true;
+  }
+  if (typeof a !== typeof b2) {
+    return false;
+  }
+  if (Array.isArray(a) && Array.isArray(b2)) {
+    if (a.length !== b2.length) return false;
+    for (let i = 0, l = a.length; i < l; i++) {
+      if (!deepEqual(a[i], b2[i], opts)) return false;
+    }
+    return true;
+  }
+  if (isPlainObject(a) && isPlainObject(b2)) {
+    const ignoreUndefined = opts?.ignoreUndefined ?? true;
+    if (opts?.partial) {
+      for (const k2 in b2) {
+        if (!ignoreUndefined || b2[k2] !== void 0) {
+          if (!deepEqual(a[k2], b2[k2], opts)) return false;
+        }
+      }
+      return true;
+    }
+    let aCount = 0;
+    if (!ignoreUndefined) {
+      aCount = Object.keys(a).length;
+    } else {
+      for (const k2 in a) {
+        if (a[k2] !== void 0) aCount++;
+      }
+    }
+    let bCount = 0;
+    for (const k2 in b2) {
+      if (!ignoreUndefined || b2[k2] !== void 0) {
+        bCount++;
+        if (bCount > aCount || !deepEqual(a[k2], b2[k2], opts)) return false;
+      }
+    }
+    return aCount === bCount;
+  }
+  return false;
+}
+function createControlledPromise(onResolve) {
+  let resolveLoadPromise;
+  let rejectLoadPromise;
+  const controlledPromise = new Promise((resolve, reject) => {
+    resolveLoadPromise = resolve;
+    rejectLoadPromise = reject;
+  });
+  controlledPromise.status = "pending";
+  controlledPromise.resolve = (value) => {
+    controlledPromise.status = "resolved";
+    controlledPromise.value = value;
+    resolveLoadPromise(value);
+    onResolve?.(value);
+  };
+  controlledPromise.reject = (e) => {
+    controlledPromise.status = "rejected";
+    rejectLoadPromise(e);
+  };
+  return controlledPromise;
+}
+function isModuleNotFoundError(error2) {
+  if (typeof error2?.message !== "string") return false;
+  return error2.message.startsWith("Failed to fetch dynamically imported module") || error2.message.startsWith("error loading dynamically imported module") || error2.message.startsWith("Importing a module script failed");
+}
+function isPromise(value) {
+  return Boolean(
+    value && typeof value === "object" && typeof value.then === "function"
+  );
+}
+function findLast(array, predicate) {
+  for (let i = array.length - 1; i >= 0; i--) {
+    const item = array[i];
+    if (predicate(item)) return item;
+  }
+  return void 0;
+}
+function decodeSegment(segment) {
+  try {
+    return decodeURI(segment);
+  } catch {
+    return segment.replaceAll(/%[0-9A-F]{2}/gi, (match) => {
+      try {
+        return decodeURI(match);
+      } catch {
+        return match;
+      }
+    });
+  }
+}
+function decodePath(path, decodeIgnore) {
+  if (!path) return path;
+  const re2 = /%25|%5C/gi;
+  let cursor = 0;
+  let result = "";
+  let match;
+  while (null !== (match = re2.exec(path))) {
+    result += decodeSegment(path.slice(cursor, match.index)) + match[0];
+    cursor = re2.lastIndex;
+  }
+  return result + decodeSegment(cursor ? path.slice(cursor) : path);
+}
+var isProduction$1 = process.env.NODE_ENV === "production";
+var prefix = "Invariant failed";
+function invariant(condition, message) {
+  if (condition) {
+    return;
+  }
+  if (isProduction$1) {
+    throw new Error(prefix);
+  }
+  var provided = typeof message === "function" ? message() : message;
+  var value = provided ? "".concat(prefix, ": ").concat(provided) : prefix;
+  throw new Error(value);
+}
+function createLRUCache(max) {
+  const cache = /* @__PURE__ */ new Map();
+  let oldest;
+  let newest;
+  const touch = (entry) => {
+    if (!entry.next) return;
+    if (!entry.prev) {
+      entry.next.prev = void 0;
+      oldest = entry.next;
+      entry.next = void 0;
+      if (newest) {
+        entry.prev = newest;
+        newest.next = entry;
+      }
+    } else {
+      entry.prev.next = entry.next;
+      entry.next.prev = entry.prev;
+      entry.next = void 0;
+      if (newest) {
+        newest.next = entry;
+        entry.prev = newest;
+      }
+    }
+    newest = entry;
+  };
+  return {
+    get(key) {
+      const entry = cache.get(key);
+      if (!entry) return void 0;
+      touch(entry);
+      return entry.value;
+    },
+    set(key, value) {
+      if (cache.size >= max && oldest) {
+        const toDelete = oldest;
+        cache.delete(toDelete.key);
+        if (toDelete.next) {
+          oldest = toDelete.next;
+          toDelete.next.prev = void 0;
+        }
+        if (toDelete === newest) {
+          newest = void 0;
+        }
+      }
+      const existing = cache.get(key);
+      if (existing) {
+        existing.value = value;
+        touch(existing);
+      } else {
+        const entry = { key, value, prev: newest };
+        if (newest) newest.next = entry;
+        newest = entry;
+        if (!oldest) oldest = entry;
+        cache.set(key, entry);
+      }
+    },
+    clear() {
+      cache.clear();
+      oldest = void 0;
+      newest = void 0;
+    }
+  };
+}
+const SEGMENT_TYPE_PATHNAME = 0;
+const SEGMENT_TYPE_PARAM = 1;
+const SEGMENT_TYPE_WILDCARD = 2;
+const SEGMENT_TYPE_OPTIONAL_PARAM = 3;
+const SEGMENT_TYPE_INDEX = 4;
+const PARAM_W_CURLY_BRACES_RE = /^([^{]*)\{\$([a-zA-Z_$][a-zA-Z0-9_$]*)\}([^}]*)$/;
+const OPTIONAL_PARAM_W_CURLY_BRACES_RE = /^([^{]*)\{-\$([a-zA-Z_$][a-zA-Z0-9_$]*)\}([^}]*)$/;
+const WILDCARD_W_CURLY_BRACES_RE = /^([^{]*)\{\$\}([^}]*)$/;
+function parseSegment(path, start, output = new Uint16Array(6)) {
+  const next = path.indexOf("/", start);
+  const end = next === -1 ? path.length : next;
+  const part = path.substring(start, end);
+  if (!part || !part.includes("$")) {
+    output[0] = SEGMENT_TYPE_PATHNAME;
+    output[1] = start;
+    output[2] = start;
+    output[3] = end;
+    output[4] = end;
+    output[5] = end;
+    return output;
+  }
+  if (part === "$") {
+    const total = path.length;
+    output[0] = SEGMENT_TYPE_WILDCARD;
+    output[1] = start;
+    output[2] = start;
+    output[3] = total;
+    output[4] = total;
+    output[5] = total;
+    return output;
+  }
+  if (part.charCodeAt(0) === 36) {
+    output[0] = SEGMENT_TYPE_PARAM;
+    output[1] = start;
+    output[2] = start + 1;
+    output[3] = end;
+    output[4] = end;
+    output[5] = end;
+    return output;
+  }
+  const wildcardBracesMatch = part.match(WILDCARD_W_CURLY_BRACES_RE);
+  if (wildcardBracesMatch) {
+    const prefix2 = wildcardBracesMatch[1];
+    const pLength = prefix2.length;
+    output[0] = SEGMENT_TYPE_WILDCARD;
+    output[1] = start + pLength;
+    output[2] = start + pLength + 1;
+    output[3] = start + pLength + 2;
+    output[4] = start + pLength + 3;
+    output[5] = path.length;
+    return output;
+  }
+  const optionalParamBracesMatch = part.match(OPTIONAL_PARAM_W_CURLY_BRACES_RE);
+  if (optionalParamBracesMatch) {
+    const prefix2 = optionalParamBracesMatch[1];
+    const paramName = optionalParamBracesMatch[2];
+    const suffix = optionalParamBracesMatch[3];
+    const pLength = prefix2.length;
+    output[0] = SEGMENT_TYPE_OPTIONAL_PARAM;
+    output[1] = start + pLength;
+    output[2] = start + pLength + 3;
+    output[3] = start + pLength + 3 + paramName.length;
+    output[4] = end - suffix.length;
+    output[5] = end;
+    return output;
+  }
+  const paramBracesMatch = part.match(PARAM_W_CURLY_BRACES_RE);
+  if (paramBracesMatch) {
+    const prefix2 = paramBracesMatch[1];
+    const paramName = paramBracesMatch[2];
+    const suffix = paramBracesMatch[3];
+    const pLength = prefix2.length;
+    output[0] = SEGMENT_TYPE_PARAM;
+    output[1] = start + pLength;
+    output[2] = start + pLength + 2;
+    output[3] = start + pLength + 2 + paramName.length;
+    output[4] = end - suffix.length;
+    output[5] = end;
+    return output;
+  }
+  output[0] = SEGMENT_TYPE_PATHNAME;
+  output[1] = start;
+  output[2] = start;
+  output[3] = end;
+  output[4] = end;
+  output[5] = end;
+  return output;
+}
+function parseSegments(defaultCaseSensitive, data, route, start, node, depth, onRoute) {
+  onRoute?.(route);
+  let cursor = start;
+  {
+    const path = route.fullPath ?? route.from;
+    const length = path.length;
+    const caseSensitive = route.options?.caseSensitive ?? defaultCaseSensitive;
+    while (cursor < length) {
+      const segment = parseSegment(path, cursor, data);
+      let nextNode;
+      const start2 = cursor;
+      const end = segment[5];
+      cursor = end + 1;
+      depth++;
+      const kind = segment[0];
+      switch (kind) {
+        case SEGMENT_TYPE_PATHNAME: {
+          const value = path.substring(segment[2], segment[3]);
+          if (caseSensitive) {
+            const existingNode = node.static?.get(value);
+            if (existingNode) {
+              nextNode = existingNode;
+            } else {
+              node.static ??= /* @__PURE__ */ new Map();
+              const next = createStaticNode(
+                route.fullPath ?? route.from
+              );
+              next.parent = node;
+              next.depth = depth;
+              nextNode = next;
+              node.static.set(value, next);
+            }
+          } else {
+            const name = value.toLowerCase();
+            const existingNode = node.staticInsensitive?.get(name);
+            if (existingNode) {
+              nextNode = existingNode;
+            } else {
+              node.staticInsensitive ??= /* @__PURE__ */ new Map();
+              const next = createStaticNode(
+                route.fullPath ?? route.from
+              );
+              next.parent = node;
+              next.depth = depth;
+              nextNode = next;
+              node.staticInsensitive.set(name, next);
+            }
+          }
+          break;
+        }
+        case SEGMENT_TYPE_PARAM: {
+          const prefix_raw = path.substring(start2, segment[1]);
+          const suffix_raw = path.substring(segment[4], end);
+          const actuallyCaseSensitive = caseSensitive && !!(prefix_raw || suffix_raw);
+          const prefix2 = !prefix_raw ? void 0 : actuallyCaseSensitive ? prefix_raw : prefix_raw.toLowerCase();
+          const suffix = !suffix_raw ? void 0 : actuallyCaseSensitive ? suffix_raw : suffix_raw.toLowerCase();
+          const existingNode = node.dynamic?.find(
+            (s) => s.caseSensitive === actuallyCaseSensitive && s.prefix === prefix2 && s.suffix === suffix
+          );
+          if (existingNode) {
+            nextNode = existingNode;
+          } else {
+            const next = createDynamicNode(
+              SEGMENT_TYPE_PARAM,
+              route.fullPath ?? route.from,
+              actuallyCaseSensitive,
+              prefix2,
+              suffix
+            );
+            nextNode = next;
+            next.depth = depth;
+            next.parent = node;
+            node.dynamic ??= [];
+            node.dynamic.push(next);
+          }
+          break;
+        }
+        case SEGMENT_TYPE_OPTIONAL_PARAM: {
+          const prefix_raw = path.substring(start2, segment[1]);
+          const suffix_raw = path.substring(segment[4], end);
+          const actuallyCaseSensitive = caseSensitive && !!(prefix_raw || suffix_raw);
+          const prefix2 = !prefix_raw ? void 0 : actuallyCaseSensitive ? prefix_raw : prefix_raw.toLowerCase();
+          const suffix = !suffix_raw ? void 0 : actuallyCaseSensitive ? suffix_raw : suffix_raw.toLowerCase();
+          const existingNode = node.optional?.find(
+            (s) => s.caseSensitive === actuallyCaseSensitive && s.prefix === prefix2 && s.suffix === suffix
+          );
+          if (existingNode) {
+            nextNode = existingNode;
+          } else {
+            const next = createDynamicNode(
+              SEGMENT_TYPE_OPTIONAL_PARAM,
+              route.fullPath ?? route.from,
+              actuallyCaseSensitive,
+              prefix2,
+              suffix
+            );
+            nextNode = next;
+            next.parent = node;
+            next.depth = depth;
+            node.optional ??= [];
+            node.optional.push(next);
+          }
+          break;
+        }
+        case SEGMENT_TYPE_WILDCARD: {
+          const prefix_raw = path.substring(start2, segment[1]);
+          const suffix_raw = path.substring(segment[4], end);
+          const actuallyCaseSensitive = caseSensitive && !!(prefix_raw || suffix_raw);
+          const prefix2 = !prefix_raw ? void 0 : actuallyCaseSensitive ? prefix_raw : prefix_raw.toLowerCase();
+          const suffix = !suffix_raw ? void 0 : actuallyCaseSensitive ? suffix_raw : suffix_raw.toLowerCase();
+          const next = createDynamicNode(
+            SEGMENT_TYPE_WILDCARD,
+            route.fullPath ?? route.from,
+            actuallyCaseSensitive,
+            prefix2,
+            suffix
+          );
+          nextNode = next;
+          next.parent = node;
+          next.depth = depth;
+          node.wildcard ??= [];
+          node.wildcard.push(next);
+        }
+      }
+      node = nextNode;
+    }
+    const isLeaf = (route.path || !route.children) && !route.isRoot;
+    if (isLeaf && path.endsWith("/")) {
+      const indexNode = createStaticNode(
+        route.fullPath ?? route.from
+      );
+      indexNode.kind = SEGMENT_TYPE_INDEX;
+      indexNode.parent = node;
+      depth++;
+      indexNode.depth = depth;
+      node.index = indexNode;
+      node = indexNode;
+    }
+    if (isLeaf && !node.route) {
+      node.route = route;
+      node.fullPath = route.fullPath ?? route.from;
+    }
+  }
+  if (route.children)
+    for (const child of route.children) {
+      parseSegments(
+        defaultCaseSensitive,
+        data,
+        child,
+        cursor,
+        node,
+        depth,
+        onRoute
+      );
+    }
+}
+function sortDynamic(a, b2) {
+  if (a.prefix && b2.prefix && a.prefix !== b2.prefix) {
+    if (a.prefix.startsWith(b2.prefix)) return -1;
+    if (b2.prefix.startsWith(a.prefix)) return 1;
+  }
+  if (a.suffix && b2.suffix && a.suffix !== b2.suffix) {
+    if (a.suffix.endsWith(b2.suffix)) return -1;
+    if (b2.suffix.endsWith(a.suffix)) return 1;
+  }
+  if (a.prefix && !b2.prefix) return -1;
+  if (!a.prefix && b2.prefix) return 1;
+  if (a.suffix && !b2.suffix) return -1;
+  if (!a.suffix && b2.suffix) return 1;
+  if (a.caseSensitive && !b2.caseSensitive) return -1;
+  if (!a.caseSensitive && b2.caseSensitive) return 1;
+  return 0;
+}
+function sortTreeNodes(node) {
+  if (node.static) {
+    for (const child of node.static.values()) {
+      sortTreeNodes(child);
+    }
+  }
+  if (node.staticInsensitive) {
+    for (const child of node.staticInsensitive.values()) {
+      sortTreeNodes(child);
+    }
+  }
+  if (node.dynamic?.length) {
+    node.dynamic.sort(sortDynamic);
+    for (const child of node.dynamic) {
+      sortTreeNodes(child);
+    }
+  }
+  if (node.optional?.length) {
+    node.optional.sort(sortDynamic);
+    for (const child of node.optional) {
+      sortTreeNodes(child);
+    }
+  }
+  if (node.wildcard?.length) {
+    node.wildcard.sort(sortDynamic);
+    for (const child of node.wildcard) {
+      sortTreeNodes(child);
+    }
+  }
+}
+function createStaticNode(fullPath) {
+  return {
+    kind: SEGMENT_TYPE_PATHNAME,
+    depth: 0,
+    index: null,
+    static: null,
+    staticInsensitive: null,
+    dynamic: null,
+    optional: null,
+    wildcard: null,
+    route: null,
+    fullPath,
+    parent: null
+  };
+}
+function createDynamicNode(kind, fullPath, caseSensitive, prefix2, suffix) {
+  return {
+    kind,
+    depth: 0,
+    index: null,
+    static: null,
+    staticInsensitive: null,
+    dynamic: null,
+    optional: null,
+    wildcard: null,
+    route: null,
+    fullPath,
+    parent: null,
+    caseSensitive,
+    prefix: prefix2,
+    suffix
+  };
+}
+function processRouteMasks(routeList, processedTree) {
+  const segmentTree = createStaticNode("/");
+  const data = new Uint16Array(6);
+  for (const route of routeList) {
+    parseSegments(false, data, route, 1, segmentTree, 0);
+  }
+  sortTreeNodes(segmentTree);
+  processedTree.masksTree = segmentTree;
+  processedTree.flatCache = createLRUCache(1e3);
+}
+function findFlatMatch(path, processedTree) {
+  path ||= "/";
+  const cached = processedTree.flatCache.get(path);
+  if (cached) return cached;
+  const result = findMatch(path, processedTree.masksTree);
+  processedTree.flatCache.set(path, result);
+  return result;
+}
+function findSingleMatch(from, caseSensitive, fuzzy, path, processedTree) {
+  from ||= "/";
+  path ||= "/";
+  const key = caseSensitive ? `case\0${from}` : from;
+  let tree = processedTree.singleCache.get(key);
+  if (!tree) {
+    tree = createStaticNode("/");
+    const data = new Uint16Array(6);
+    parseSegments(caseSensitive, data, { from }, 1, tree, 0);
+    processedTree.singleCache.set(key, tree);
+  }
+  return findMatch(path, tree, fuzzy);
+}
+function findRouteMatch(path, processedTree, fuzzy = false) {
+  const key = fuzzy ? path : `nofuzz\0${path}`;
+  const cached = processedTree.matchCache.get(key);
+  if (cached !== void 0) return cached;
+  path ||= "/";
+  const result = findMatch(
+    path,
+    processedTree.segmentTree,
+    fuzzy
+  );
+  if (result) result.branch = buildRouteBranch(result.route);
+  processedTree.matchCache.set(key, result);
+  return result;
+}
+function trimPathRight$1(path) {
+  return path === "/" ? path : path.replace(/\/{1,}$/, "");
+}
+function processRouteTree(routeTree, caseSensitive = false, initRoute) {
+  const segmentTree = createStaticNode(routeTree.fullPath);
+  const data = new Uint16Array(6);
+  const routesById = {};
+  const routesByPath = {};
+  let index = 0;
+  parseSegments(caseSensitive, data, routeTree, 1, segmentTree, 0, (route) => {
+    initRoute?.(route, index);
+    invariant(
+      !(route.id in routesById),
+      `Duplicate routes found with id: ${String(route.id)}`
+    );
+    routesById[route.id] = route;
+    if (index !== 0 && route.path) {
+      const trimmedFullPath = trimPathRight$1(route.fullPath);
+      if (!routesByPath[trimmedFullPath] || route.fullPath.endsWith("/")) {
+        routesByPath[trimmedFullPath] = route;
+      }
+    }
+    index++;
+  });
+  sortTreeNodes(segmentTree);
+  const processedTree = {
+    segmentTree,
+    singleCache: createLRUCache(1e3),
+    matchCache: createLRUCache(1e3),
+    flatCache: null,
+    masksTree: null
+  };
+  return {
+    processedTree,
+    routesById,
+    routesByPath
+  };
+}
+function findMatch(path, segmentTree, fuzzy = false) {
+  const parts = path.split("/");
+  const leaf = getNodeMatch(path, parts, segmentTree, fuzzy);
+  if (!leaf) return null;
+  const params = extractParams(path, parts, leaf);
+  if ("**" in leaf) params["**"] = leaf["**"];
+  const route = leaf.node.route;
+  return {
+    route,
+    params
+  };
+}
+function extractParams(path, parts, leaf) {
+  const list = buildBranch(leaf.node);
+  let nodeParts = null;
+  const params = {};
+  for (let partIndex = 0, nodeIndex = 0, pathIndex = 0; nodeIndex < list.length; partIndex++, nodeIndex++, pathIndex++) {
+    const node = list[nodeIndex];
+    const part = parts[partIndex];
+    const currentPathIndex = pathIndex;
+    if (part) pathIndex += part.length;
+    if (node.kind === SEGMENT_TYPE_PARAM) {
+      nodeParts ??= leaf.node.fullPath.split("/");
+      const nodePart = nodeParts[nodeIndex];
+      const preLength = node.prefix?.length ?? 0;
+      const isCurlyBraced = nodePart.charCodeAt(preLength) === 123;
+      if (isCurlyBraced) {
+        const sufLength = node.suffix?.length ?? 0;
+        const name = nodePart.substring(
+          preLength + 2,
+          nodePart.length - sufLength - 1
+        );
+        const value = part.substring(preLength, part.length - sufLength);
+        params[name] = decodeURIComponent(value);
+      } else {
+        const name = nodePart.substring(1);
+        params[name] = decodeURIComponent(part);
+      }
+    } else if (node.kind === SEGMENT_TYPE_OPTIONAL_PARAM) {
+      if (leaf.skipped & 1 << nodeIndex) {
+        partIndex--;
+        continue;
+      }
+      nodeParts ??= leaf.node.fullPath.split("/");
+      const nodePart = nodeParts[nodeIndex];
+      const preLength = node.prefix?.length ?? 0;
+      const sufLength = node.suffix?.length ?? 0;
+      const name = nodePart.substring(
+        preLength + 3,
+        nodePart.length - sufLength - 1
+      );
+      const value = node.suffix || node.prefix ? part.substring(preLength, part.length - sufLength) : part;
+      if (value) params[name] = decodeURIComponent(value);
+    } else if (node.kind === SEGMENT_TYPE_WILDCARD) {
+      const n = node;
+      const value = path.substring(
+        currentPathIndex + (n.prefix?.length ?? 0),
+        path.length - (n.suffix?.length ?? 0)
+      );
+      const splat = decodeURIComponent(value);
+      params["*"] = splat;
+      params._splat = splat;
+      break;
+    }
+  }
+  return params;
+}
+function buildRouteBranch(route) {
+  const list = [route];
+  while (route.parentRoute) {
+    route = route.parentRoute;
+    list.push(route);
+  }
+  list.reverse();
+  return list;
+}
+function buildBranch(node) {
+  const list = Array(node.depth + 1);
+  do {
+    list[node.depth] = node;
+    node = node.parent;
+  } while (node);
+  return list;
+}
+function getNodeMatch(path, parts, segmentTree, fuzzy) {
+  if (path === "/" && segmentTree.index)
+    return { node: segmentTree.index, skipped: 0 };
+  const trailingSlash = !last(parts);
+  const pathIsIndex = trailingSlash && path !== "/";
+  const partsLength = parts.length - (trailingSlash ? 1 : 0);
+  const stack = [
+    {
+      node: segmentTree,
+      index: 1,
+      skipped: 0,
+      depth: 1,
+      statics: 1,
+      dynamics: 0,
+      optionals: 0
+    }
+  ];
+  let wildcardMatch = null;
+  let bestFuzzy = null;
+  let bestMatch = null;
+  while (stack.length) {
+    const frame = stack.pop();
+    let { node, index, skipped, depth, statics, dynamics, optionals } = frame;
+    if (fuzzy && node.route && node.kind !== SEGMENT_TYPE_INDEX && isFrameMoreSpecific(bestFuzzy, frame)) {
+      bestFuzzy = frame;
+    }
+    const isBeyondPath = index === partsLength;
+    if (isBeyondPath) {
+      if (node.route && !pathIsIndex && isFrameMoreSpecific(bestMatch, frame)) {
+        bestMatch = frame;
+      }
+      if (!node.optional && !node.wildcard && !node.index) continue;
+    }
+    const part = isBeyondPath ? void 0 : parts[index];
+    let lowerPart;
+    if (isBeyondPath && node.index) {
+      const indexFrame = {
+        node: node.index,
+        index,
+        skipped,
+        depth: depth + 1,
+        statics,
+        dynamics,
+        optionals
+      };
+      if (statics === partsLength && !dynamics && !optionals && !skipped) {
+        return indexFrame;
+      }
+      if (isFrameMoreSpecific(bestMatch, indexFrame)) {
+        bestMatch = indexFrame;
+      }
+    }
+    if (node.wildcard && isFrameMoreSpecific(wildcardMatch, frame)) {
+      for (const segment of node.wildcard) {
+        const { prefix: prefix2, suffix } = segment;
+        if (prefix2) {
+          if (isBeyondPath) continue;
+          const casePart = segment.caseSensitive ? part : lowerPart ??= part.toLowerCase();
+          if (!casePart.startsWith(prefix2)) continue;
+        }
+        if (suffix) {
+          if (isBeyondPath) continue;
+          const end = parts.slice(index).join("/").slice(-suffix.length);
+          const casePart = segment.caseSensitive ? end : end.toLowerCase();
+          if (casePart !== suffix) continue;
+        }
+        wildcardMatch = {
+          node: segment,
+          index: partsLength,
+          skipped,
+          depth,
+          statics,
+          dynamics,
+          optionals
+        };
+        break;
+      }
+    }
+    if (node.optional) {
+      const nextSkipped = skipped | 1 << depth;
+      const nextDepth = depth + 1;
+      for (let i = node.optional.length - 1; i >= 0; i--) {
+        const segment = node.optional[i];
+        stack.push({
+          node: segment,
+          index,
+          skipped: nextSkipped,
+          depth: nextDepth,
+          statics,
+          dynamics,
+          optionals
+        });
+      }
+      if (!isBeyondPath) {
+        for (let i = node.optional.length - 1; i >= 0; i--) {
+          const segment = node.optional[i];
+          const { prefix: prefix2, suffix } = segment;
+          if (prefix2 || suffix) {
+            const casePart = segment.caseSensitive ? part : lowerPart ??= part.toLowerCase();
+            if (prefix2 && !casePart.startsWith(prefix2)) continue;
+            if (suffix && !casePart.endsWith(suffix)) continue;
+          }
+          stack.push({
+            node: segment,
+            index: index + 1,
+            skipped,
+            depth: nextDepth,
+            statics,
+            dynamics,
+            optionals: optionals + 1
+          });
+        }
+      }
+    }
+    if (!isBeyondPath && node.dynamic && part) {
+      for (let i = node.dynamic.length - 1; i >= 0; i--) {
+        const segment = node.dynamic[i];
+        const { prefix: prefix2, suffix } = segment;
+        if (prefix2 || suffix) {
+          const casePart = segment.caseSensitive ? part : lowerPart ??= part.toLowerCase();
+          if (prefix2 && !casePart.startsWith(prefix2)) continue;
+          if (suffix && !casePart.endsWith(suffix)) continue;
+        }
+        stack.push({
+          node: segment,
+          index: index + 1,
+          skipped,
+          depth: depth + 1,
+          statics,
+          dynamics: dynamics + 1,
+          optionals
+        });
+      }
+    }
+    if (!isBeyondPath && node.staticInsensitive) {
+      const match = node.staticInsensitive.get(
+        lowerPart ??= part.toLowerCase()
+      );
+      if (match) {
+        stack.push({
+          node: match,
+          index: index + 1,
+          skipped,
+          depth: depth + 1,
+          statics: statics + 1,
+          dynamics,
+          optionals
+        });
+      }
+    }
+    if (!isBeyondPath && node.static) {
+      const match = node.static.get(part);
+      if (match) {
+        stack.push({
+          node: match,
+          index: index + 1,
+          skipped,
+          depth: depth + 1,
+          statics: statics + 1,
+          dynamics,
+          optionals
+        });
+      }
+    }
+  }
+  if (bestMatch && wildcardMatch) {
+    return isFrameMoreSpecific(wildcardMatch, bestMatch) ? bestMatch : wildcardMatch;
+  }
+  if (bestMatch) return bestMatch;
+  if (wildcardMatch) return wildcardMatch;
+  if (fuzzy && bestFuzzy) {
+    let sliceIndex = bestFuzzy.index;
+    for (let i = 0; i < bestFuzzy.index; i++) {
+      sliceIndex += parts[i].length;
+    }
+    const splat = sliceIndex === path.length ? "/" : path.slice(sliceIndex);
+    return {
+      node: bestFuzzy.node,
+      skipped: bestFuzzy.skipped,
+      "**": decodeURIComponent(splat)
+    };
+  }
+  return null;
+}
+function isFrameMoreSpecific(prev, next) {
+  if (!prev) return true;
+  return next.statics > prev.statics || next.statics === prev.statics && (next.dynamics > prev.dynamics || next.dynamics === prev.dynamics && (next.optionals > prev.optionals || next.optionals === prev.optionals && ((next.node.kind === SEGMENT_TYPE_INDEX) > (prev.node.kind === SEGMENT_TYPE_INDEX) || next.node.kind === SEGMENT_TYPE_INDEX === (prev.node.kind === SEGMENT_TYPE_INDEX) && next.depth > prev.depth)));
+}
+function joinPaths(paths) {
+  return cleanPath(
+    paths.filter((val) => {
+      return val !== void 0;
+    }).join("/")
+  );
+}
+function cleanPath(path) {
+  return path.replace(/\/{2,}/g, "/");
+}
+function trimPathLeft(path) {
+  return path === "/" ? path : path.replace(/^\/{1,}/, "");
+}
+function trimPathRight(path) {
+  const len = path.length;
+  return len > 1 && path[len - 1] === "/" ? path.replace(/\/{1,}$/, "") : path;
+}
+function trimPath(path) {
+  return trimPathRight(trimPathLeft(path));
+}
+function removeTrailingSlash(value, basepath) {
+  if (value?.endsWith("/") && value !== "/" && value !== `${basepath}/`) {
+    return value.slice(0, -1);
+  }
+  return value;
+}
+function exactPathTest(pathName1, pathName2, basepath) {
+  return removeTrailingSlash(pathName1, basepath) === removeTrailingSlash(pathName2, basepath);
+}
+function resolvePath({
+  base,
+  to: to2,
+  trailingSlash = "never",
+  cache
+}) {
+  const isAbsolute = to2.startsWith("/");
+  const isBase = !isAbsolute && to2 === ".";
+  let key;
+  if (cache) {
+    key = isAbsolute ? to2 : isBase ? base : base + "\0" + to2;
+    const cached = cache.get(key);
+    if (cached) return cached;
+  }
+  let baseSegments;
+  if (isBase) {
+    baseSegments = base.split("/");
+  } else if (isAbsolute) {
+    baseSegments = to2.split("/");
+  } else {
+    baseSegments = base.split("/");
+    while (baseSegments.length > 1 && last(baseSegments) === "") {
+      baseSegments.pop();
+    }
+    const toSegments = to2.split("/");
+    for (let index = 0, length = toSegments.length; index < length; index++) {
+      const value = toSegments[index];
+      if (value === "") {
+        if (!index) {
+          baseSegments = [value];
+        } else if (index === length - 1) {
+          baseSegments.push(value);
+        } else ;
+      } else if (value === "..") {
+        baseSegments.pop();
+      } else if (value === ".") ;
+      else {
+        baseSegments.push(value);
+      }
+    }
+  }
+  if (baseSegments.length > 1) {
+    if (last(baseSegments) === "") {
+      if (trailingSlash === "never") {
+        baseSegments.pop();
+      }
+    } else if (trailingSlash === "always") {
+      baseSegments.push("");
+    }
+  }
+  let segment;
+  let joined = "";
+  for (let i = 0; i < baseSegments.length; i++) {
+    if (i > 0) joined += "/";
+    const part = baseSegments[i];
+    if (!part) continue;
+    segment = parseSegment(part, 0, segment);
+    const kind = segment[0];
+    if (kind === SEGMENT_TYPE_PATHNAME) {
+      joined += part;
+      continue;
+    }
+    const end = segment[5];
+    const prefix2 = part.substring(0, segment[1]);
+    const suffix = part.substring(segment[4], end);
+    const value = part.substring(segment[2], segment[3]);
+    if (kind === SEGMENT_TYPE_PARAM) {
+      joined += prefix2 || suffix ? `${prefix2}{$${value}}${suffix}` : `$${value}`;
+    } else if (kind === SEGMENT_TYPE_WILDCARD) {
+      joined += prefix2 || suffix ? `${prefix2}{$}${suffix}` : "$";
+    } else {
+      joined += `${prefix2}{-$${value}}${suffix}`;
+    }
+  }
+  joined = cleanPath(joined);
+  const result = joined || "/";
+  if (key && cache) cache.set(key, result);
+  return result;
+}
+function encodeParam(key, params, decodeCharMap) {
+  const value = params[key];
+  if (typeof value !== "string") return value;
+  if (key === "_splat") {
+    return encodeURI(value);
+  } else {
+    return encodePathParam(value, decodeCharMap);
+  }
+}
+function interpolatePath({
+  path,
+  params,
+  decodeCharMap
+}) {
+  let isMissingParams = false;
+  const usedParams = {};
+  if (!path || path === "/")
+    return { interpolatedPath: "/", usedParams, isMissingParams };
+  if (!path.includes("$"))
+    return { interpolatedPath: path, usedParams, isMissingParams };
+  const length = path.length;
+  let cursor = 0;
+  let segment;
+  let joined = "";
+  while (cursor < length) {
+    const start = cursor;
+    segment = parseSegment(path, start, segment);
+    const end = segment[5];
+    cursor = end + 1;
+    if (start === end) continue;
+    const kind = segment[0];
+    if (kind === SEGMENT_TYPE_PATHNAME) {
+      joined += "/" + path.substring(start, end);
+      continue;
+    }
+    if (kind === SEGMENT_TYPE_WILDCARD) {
+      const splat = params._splat;
+      usedParams._splat = splat;
+      usedParams["*"] = splat;
+      const prefix2 = path.substring(start, segment[1]);
+      const suffix = path.substring(segment[4], end);
+      if (!splat) {
+        isMissingParams = true;
+        if (prefix2 || suffix) {
+          joined += "/" + prefix2 + suffix;
+        }
+        continue;
+      }
+      const value = encodeParam("_splat", params, decodeCharMap);
+      joined += "/" + prefix2 + value + suffix;
+      continue;
+    }
+    if (kind === SEGMENT_TYPE_PARAM) {
+      const key = path.substring(segment[2], segment[3]);
+      if (!isMissingParams && !(key in params)) {
+        isMissingParams = true;
+      }
+      usedParams[key] = params[key];
+      const prefix2 = path.substring(start, segment[1]);
+      const suffix = path.substring(segment[4], end);
+      const value = encodeParam(key, params, decodeCharMap) ?? "undefined";
+      joined += "/" + prefix2 + value + suffix;
+      continue;
+    }
+    if (kind === SEGMENT_TYPE_OPTIONAL_PARAM) {
+      const key = path.substring(segment[2], segment[3]);
+      const valueRaw = params[key];
+      if (valueRaw == null) continue;
+      usedParams[key] = valueRaw;
+      const prefix2 = path.substring(start, segment[1]);
+      const suffix = path.substring(segment[4], end);
+      const value = encodeParam(key, params, decodeCharMap) ?? "";
+      joined += "/" + prefix2 + value + suffix;
+      continue;
+    }
+  }
+  if (path.endsWith("/")) joined += "/";
+  const interpolatedPath = joined || "/";
+  return { usedParams, interpolatedPath, isMissingParams };
+}
+function encodePathParam(value, decodeCharMap) {
+  let encoded = encodeURIComponent(value);
+  if (decodeCharMap) {
+    for (const [encodedChar, char] of decodeCharMap) {
+      encoded = encoded.replaceAll(encodedChar, char);
+    }
+  }
+  return encoded;
+}
+function isNotFound(obj) {
+  return !!obj?.isNotFound;
+}
+function getSafeSessionStorage() {
+  try {
+    if (typeof window !== "undefined" && typeof window.sessionStorage === "object") {
+      return window.sessionStorage;
+    }
+  } catch {
+  }
+  return void 0;
+}
+const storageKey = "tsr-scroll-restoration-v1_3";
+const throttle = (fn2, wait) => {
+  let timeout;
+  return (...args) => {
+    if (!timeout) {
+      timeout = setTimeout(() => {
+        fn2(...args);
+        timeout = null;
+      }, wait);
+    }
+  };
+};
+function createScrollRestorationCache() {
+  const safeSessionStorage = getSafeSessionStorage();
+  if (!safeSessionStorage) {
+    return null;
+  }
+  const persistedState = safeSessionStorage.getItem(storageKey);
+  let state = persistedState ? JSON.parse(persistedState) : {};
+  return {
+    state,
+    // This setter is simply to make sure that we set the sessionStorage right
+    // after the state is updated. It doesn't necessarily need to be a functional
+    // update.
+    set: (updater) => (state = functionalUpdate(updater, state) || state, safeSessionStorage.setItem(storageKey, JSON.stringify(state)))
+  };
+}
+const scrollRestorationCache = createScrollRestorationCache();
+const defaultGetScrollRestorationKey = (location) => {
+  return location.state.__TSR_key || location.href;
+};
+function getCssSelector(el) {
+  const path = [];
+  let parent;
+  while (parent = el.parentNode) {
+    path.push(
+      `${el.tagName}:nth-child(${Array.prototype.indexOf.call(parent.children, el) + 1})`
+    );
+    el = parent;
+  }
+  return `${path.reverse().join(" > ")}`.toLowerCase();
+}
+let ignoreScroll = false;
+function restoreScroll({
+  storageKey: storageKey2,
+  key,
+  behavior,
+  shouldScrollRestoration,
+  scrollToTopSelectors,
+  location
+}) {
+  let byKey;
+  try {
+    byKey = JSON.parse(sessionStorage.getItem(storageKey2) || "{}");
+  } catch (error2) {
+    console.error(error2);
+    return;
+  }
+  const resolvedKey = key || window.history.state?.__TSR_key;
+  const elementEntries = byKey[resolvedKey];
+  ignoreScroll = true;
+  scroll: {
+    if (shouldScrollRestoration && elementEntries && Object.keys(elementEntries).length > 0) {
+      for (const elementSelector in elementEntries) {
+        const entry = elementEntries[elementSelector];
+        if (elementSelector === "window") {
+          window.scrollTo({
+            top: entry.scrollY,
+            left: entry.scrollX,
+            behavior
+          });
+        } else if (elementSelector) {
+          const element = document.querySelector(elementSelector);
+          if (element) {
+            element.scrollLeft = entry.scrollX;
+            element.scrollTop = entry.scrollY;
+          }
+        }
+      }
+      break scroll;
+    }
+    const hash = (location ?? window.location).hash.split("#", 2)[1];
+    if (hash) {
+      const hashScrollIntoViewOptions = window.history.state?.__hashScrollIntoViewOptions ?? true;
+      if (hashScrollIntoViewOptions) {
+        const el = document.getElementById(hash);
+        if (el) {
+          el.scrollIntoView(hashScrollIntoViewOptions);
+        }
+      }
+      break scroll;
+    }
+    const scrollOptions = { top: 0, left: 0, behavior };
+    window.scrollTo(scrollOptions);
+    if (scrollToTopSelectors) {
+      for (const selector of scrollToTopSelectors) {
+        if (selector === "window") continue;
+        const element = typeof selector === "function" ? selector() : document.querySelector(selector);
+        if (element) element.scrollTo(scrollOptions);
+      }
+    }
+  }
+  ignoreScroll = false;
+}
+function setupScrollRestoration(router, force) {
+  if (!scrollRestorationCache && !router.isServer) {
+    return;
+  }
+  const shouldScrollRestoration = router.options.scrollRestoration ?? false;
+  if (shouldScrollRestoration) {
+    router.isScrollRestoring = true;
+  }
+  if (router.isServer || router.isScrollRestorationSetup || !scrollRestorationCache) {
+    return;
+  }
+  router.isScrollRestorationSetup = true;
+  ignoreScroll = false;
+  const getKey = router.options.getScrollRestorationKey || defaultGetScrollRestorationKey;
+  window.history.scrollRestoration = "manual";
+  const onScroll = (event) => {
+    if (ignoreScroll || !router.isScrollRestoring) {
+      return;
+    }
+    let elementSelector = "";
+    if (event.target === document || event.target === window) {
+      elementSelector = "window";
+    } else {
+      const attrId = event.target.getAttribute(
+        "data-scroll-restoration-id"
+      );
+      if (attrId) {
+        elementSelector = `[data-scroll-restoration-id="${attrId}"]`;
+      } else {
+        elementSelector = getCssSelector(event.target);
+      }
+    }
+    const restoreKey = getKey(router.state.location);
+    scrollRestorationCache.set((state) => {
+      const keyEntry = state[restoreKey] ||= {};
+      const elementEntry = keyEntry[elementSelector] ||= {};
+      if (elementSelector === "window") {
+        elementEntry.scrollX = window.scrollX || 0;
+        elementEntry.scrollY = window.scrollY || 0;
+      } else if (elementSelector) {
+        const element = document.querySelector(elementSelector);
+        if (element) {
+          elementEntry.scrollX = element.scrollLeft || 0;
+          elementEntry.scrollY = element.scrollTop || 0;
+        }
+      }
+      return state;
+    });
+  };
+  if (typeof document !== "undefined") {
+    document.addEventListener("scroll", throttle(onScroll, 100), true);
+  }
+  router.subscribe("onRendered", (event) => {
+    const cacheKey = getKey(event.toLocation);
+    if (!router.resetNextScroll) {
+      router.resetNextScroll = true;
+      return;
+    }
+    if (typeof router.options.scrollRestoration === "function") {
+      const shouldRestore = router.options.scrollRestoration({
+        location: router.latestLocation
+      });
+      if (!shouldRestore) {
+        return;
+      }
+    }
+    restoreScroll({
+      storageKey,
+      key: cacheKey,
+      behavior: router.options.scrollRestorationBehavior,
+      shouldScrollRestoration: router.isScrollRestoring,
+      scrollToTopSelectors: router.options.scrollToTopSelectors,
+      location: router.history.location
+    });
+    if (router.isScrollRestoring) {
+      scrollRestorationCache.set((state) => {
+        state[cacheKey] ||= {};
+        return state;
+      });
+    }
+  });
+}
+function handleHashScroll(router) {
+  if (typeof document !== "undefined" && document.querySelector) {
+    const hashScrollIntoViewOptions = router.state.location.state.__hashScrollIntoViewOptions ?? true;
+    if (hashScrollIntoViewOptions && router.state.location.hash !== "") {
+      const el = document.getElementById(router.state.location.hash);
+      if (el) {
+        el.scrollIntoView(hashScrollIntoViewOptions);
+      }
+    }
+  }
+}
+function encode(obj, stringify = String) {
+  const result = new URLSearchParams();
+  for (const key in obj) {
+    const val = obj[key];
+    if (val !== void 0) {
+      result.set(key, stringify(val));
+    }
+  }
+  return result.toString();
+}
+function toValue(str) {
+  if (!str) return "";
+  if (str === "false") return false;
+  if (str === "true") return true;
+  return +str * 0 === 0 && +str + "" === str ? +str : str;
+}
+function decode(str) {
+  const searchParams = new URLSearchParams(str);
+  const result = {};
+  for (const [key, value] of searchParams.entries()) {
+    const previousValue = result[key];
+    if (previousValue == null) {
+      result[key] = toValue(value);
+    } else if (Array.isArray(previousValue)) {
+      previousValue.push(toValue(value));
+    } else {
+      result[key] = [previousValue, toValue(value)];
+    }
+  }
+  return result;
+}
+const defaultParseSearch = parseSearchWith(JSON.parse);
+const defaultStringifySearch = stringifySearchWith(
+  JSON.stringify,
+  JSON.parse
+);
+function parseSearchWith(parser) {
+  return (searchStr) => {
+    if (searchStr[0] === "?") {
+      searchStr = searchStr.substring(1);
+    }
+    const query = decode(searchStr);
+    for (const key in query) {
+      const value = query[key];
+      if (typeof value === "string") {
+        try {
+          query[key] = parser(value);
+        } catch (_err) {
+        }
+      }
+    }
+    return query;
+  };
+}
+function stringifySearchWith(stringify, parser) {
+  const hasParser = typeof parser === "function";
+  function stringifyValue2(val) {
+    if (typeof val === "object" && val !== null) {
+      try {
+        return stringify(val);
+      } catch (_err) {
+      }
+    } else if (hasParser && typeof val === "string") {
+      try {
+        parser(val);
+        return stringify(val);
+      } catch (_err) {
+      }
+    }
+    return val;
+  }
+  return (search) => {
+    const searchStr = encode(search, stringifyValue2);
+    return searchStr ? `?${searchStr}` : "";
+  };
+}
+const rootRouteId = "__root__";
+function redirect(opts) {
+  opts.statusCode = opts.statusCode || opts.code || 307;
+  if (!opts.reloadDocument && typeof opts.href === "string") {
+    try {
+      new URL(opts.href);
+      opts.reloadDocument = true;
+    } catch {
+    }
+  }
+  const headers = new Headers(opts.headers);
+  if (opts.href && headers.get("Location") === null) {
+    headers.set("Location", opts.href);
+  }
+  const response = new Response(null, {
+    status: opts.statusCode,
+    headers
+  });
+  response.options = opts;
+  if (opts.throw) {
+    throw response;
+  }
+  return response;
+}
+function isRedirect(obj) {
+  return obj instanceof Response && !!obj.options;
+}
+function isResolvedRedirect(obj) {
+  return isRedirect(obj) && !!obj.options.href;
+}
+function parseRedirect(obj) {
+  if (obj !== null && typeof obj === "object" && obj.isSerializedRedirect) {
+    return redirect(obj);
+  }
+  return void 0;
+}
+const triggerOnReady = (inner) => {
+  if (!inner.rendered) {
+    inner.rendered = true;
+    return inner.onReady?.();
+  }
+};
+const resolvePreload = (inner, matchId) => {
+  return !!(inner.preload && !inner.router.state.matches.some((d) => d.id === matchId));
+};
+const buildMatchContext = (inner, index, includeCurrentMatch = true) => {
+  const context = {
+    ...inner.router.options.context ?? {}
+  };
+  const end = includeCurrentMatch ? index : index - 1;
+  for (let i = 0; i <= end; i++) {
+    const innerMatch = inner.matches[i];
+    if (!innerMatch) continue;
+    const m2 = inner.router.getMatch(innerMatch.id);
+    if (!m2) continue;
+    Object.assign(context, m2.__routeContext, m2.__beforeLoadContext);
+  }
+  return context;
+};
+const _handleNotFound = (inner, err) => {
+  const routeCursor = inner.router.routesById[err.routeId ?? ""] ?? inner.router.routeTree;
+  if (!routeCursor.options.notFoundComponent && inner.router.options?.defaultNotFoundComponent) {
+    routeCursor.options.notFoundComponent = inner.router.options.defaultNotFoundComponent;
+  }
+  invariant(
+    routeCursor.options.notFoundComponent,
+    "No notFoundComponent found. Please set a notFoundComponent on your route or provide a defaultNotFoundComponent to the router."
+  );
+  const matchForRoute = inner.matches.find((m2) => m2.routeId === routeCursor.id);
+  invariant(matchForRoute, "Could not find match for route: " + routeCursor.id);
+  inner.updateMatch(matchForRoute.id, (prev) => ({
+    ...prev,
+    status: "notFound",
+    error: err,
+    isFetching: false
+  }));
+  if (err.routerCode === "BEFORE_LOAD" && routeCursor.parentRoute) {
+    err.routeId = routeCursor.parentRoute.id;
+    _handleNotFound(inner, err);
+  }
+};
+const handleRedirectAndNotFound = (inner, match, err) => {
+  if (!isRedirect(err) && !isNotFound(err)) return;
+  if (isRedirect(err) && err.redirectHandled && !err.options.reloadDocument) {
+    throw err;
+  }
+  if (match) {
+    match._nonReactive.beforeLoadPromise?.resolve();
+    match._nonReactive.loaderPromise?.resolve();
+    match._nonReactive.beforeLoadPromise = void 0;
+    match._nonReactive.loaderPromise = void 0;
+    const status = isRedirect(err) ? "redirected" : "notFound";
+    match._nonReactive.error = err;
+    inner.updateMatch(match.id, (prev) => ({
+      ...prev,
+      status,
+      isFetching: false,
+      error: err
+    }));
+    if (isNotFound(err) && !err.routeId) {
+      err.routeId = match.routeId;
+    }
+    match._nonReactive.loadPromise?.resolve();
+  }
+  if (isRedirect(err)) {
+    inner.rendered = true;
+    err.options._fromLocation = inner.location;
+    err.redirectHandled = true;
+    err = inner.router.resolveRedirect(err);
+    throw err;
+  } else {
+    _handleNotFound(inner, err);
+    throw err;
+  }
+};
+const shouldSkipLoader = (inner, matchId) => {
+  const match = inner.router.getMatch(matchId);
+  if (!inner.router.isServer && match._nonReactive.dehydrated) {
+    return true;
+  }
+  if (inner.router.isServer && match.ssr === false) {
+    return true;
+  }
+  return false;
+};
+const handleSerialError = (inner, index, err, routerCode) => {
+  const { id: matchId, routeId } = inner.matches[index];
+  const route = inner.router.looseRoutesById[routeId];
+  if (err instanceof Promise) {
+    throw err;
+  }
+  err.routerCode = routerCode;
+  inner.firstBadMatchIndex ??= index;
+  handleRedirectAndNotFound(inner, inner.router.getMatch(matchId), err);
+  try {
+    route.options.onError?.(err);
+  } catch (errorHandlerErr) {
+    err = errorHandlerErr;
+    handleRedirectAndNotFound(inner, inner.router.getMatch(matchId), err);
+  }
+  inner.updateMatch(matchId, (prev) => {
+    prev._nonReactive.beforeLoadPromise?.resolve();
+    prev._nonReactive.beforeLoadPromise = void 0;
+    prev._nonReactive.loadPromise?.resolve();
+    return {
+      ...prev,
+      error: err,
+      status: "error",
+      isFetching: false,
+      updatedAt: Date.now(),
+      abortController: new AbortController()
+    };
+  });
+};
+const isBeforeLoadSsr = (inner, matchId, index, route) => {
+  const existingMatch = inner.router.getMatch(matchId);
+  const parentMatchId = inner.matches[index - 1]?.id;
+  const parentMatch = parentMatchId ? inner.router.getMatch(parentMatchId) : void 0;
+  if (inner.router.isShell()) {
+    existingMatch.ssr = route.id === rootRouteId;
+    return;
+  }
+  if (parentMatch?.ssr === false) {
+    existingMatch.ssr = false;
+    return;
+  }
+  const parentOverride = (tempSsr2) => {
+    if (tempSsr2 === true && parentMatch?.ssr === "data-only") {
+      return "data-only";
+    }
+    return tempSsr2;
+  };
+  const defaultSsr = inner.router.options.defaultSsr ?? true;
+  if (route.options.ssr === void 0) {
+    existingMatch.ssr = parentOverride(defaultSsr);
+    return;
+  }
+  if (typeof route.options.ssr !== "function") {
+    existingMatch.ssr = parentOverride(route.options.ssr);
+    return;
+  }
+  const { search, params } = existingMatch;
+  const ssrFnContext = {
+    search: makeMaybe(search, existingMatch.searchError),
+    params: makeMaybe(params, existingMatch.paramsError),
+    location: inner.location,
+    matches: inner.matches.map((match) => ({
+      index: match.index,
+      pathname: match.pathname,
+      fullPath: match.fullPath,
+      staticData: match.staticData,
+      id: match.id,
+      routeId: match.routeId,
+      search: makeMaybe(match.search, match.searchError),
+      params: makeMaybe(match.params, match.paramsError),
+      ssr: match.ssr
+    }))
+  };
+  const tempSsr = route.options.ssr(ssrFnContext);
+  if (isPromise(tempSsr)) {
+    return tempSsr.then((ssr) => {
+      existingMatch.ssr = parentOverride(ssr ?? defaultSsr);
+    });
+  }
+  existingMatch.ssr = parentOverride(tempSsr ?? defaultSsr);
+  return;
+};
+const setupPendingTimeout = (inner, matchId, route, match) => {
+  if (match._nonReactive.pendingTimeout !== void 0) return;
+  const pendingMs = route.options.pendingMs ?? inner.router.options.defaultPendingMs;
+  const shouldPending = !!(inner.onReady && !inner.router.isServer && !resolvePreload(inner, matchId) && (route.options.loader || route.options.beforeLoad || routeNeedsPreload(route)) && typeof pendingMs === "number" && pendingMs !== Infinity && (route.options.pendingComponent ?? inner.router.options?.defaultPendingComponent));
+  if (shouldPending) {
+    const pendingTimeout = setTimeout(() => {
+      triggerOnReady(inner);
+    }, pendingMs);
+    match._nonReactive.pendingTimeout = pendingTimeout;
+  }
+};
+const preBeforeLoadSetup = (inner, matchId, route) => {
+  const existingMatch = inner.router.getMatch(matchId);
+  if (!existingMatch._nonReactive.beforeLoadPromise && !existingMatch._nonReactive.loaderPromise)
+    return;
+  setupPendingTimeout(inner, matchId, route, existingMatch);
+  const then = () => {
+    const match = inner.router.getMatch(matchId);
+    if (match.preload && (match.status === "redirected" || match.status === "notFound")) {
+      handleRedirectAndNotFound(inner, match, match.error);
+    }
+  };
+  return existingMatch._nonReactive.beforeLoadPromise ? existingMatch._nonReactive.beforeLoadPromise.then(then) : then();
+};
+const executeBeforeLoad = (inner, matchId, index, route) => {
+  const match = inner.router.getMatch(matchId);
+  const prevLoadPromise = match._nonReactive.loadPromise;
+  match._nonReactive.loadPromise = createControlledPromise(() => {
+    prevLoadPromise?.resolve();
+  });
+  const { paramsError, searchError } = match;
+  if (paramsError) {
+    handleSerialError(inner, index, paramsError, "PARSE_PARAMS");
+  }
+  if (searchError) {
+    handleSerialError(inner, index, searchError, "VALIDATE_SEARCH");
+  }
+  setupPendingTimeout(inner, matchId, route, match);
+  const abortController = new AbortController();
+  const parentMatchId = inner.matches[index - 1]?.id;
+  const parentMatch = parentMatchId ? inner.router.getMatch(parentMatchId) : void 0;
+  parentMatch?.context ?? inner.router.options.context ?? void 0;
+  let isPending = false;
+  const pending = () => {
+    if (isPending) return;
+    isPending = true;
+    inner.updateMatch(matchId, (prev) => ({
+      ...prev,
+      isFetching: "beforeLoad",
+      fetchCount: prev.fetchCount + 1,
+      abortController
+      // Note: We intentionally don't update context here.
+      // Context should only be updated after beforeLoad resolves to avoid
+      // components seeing incomplete context during async beforeLoad execution.
+    }));
+  };
+  const resolve = () => {
+    match._nonReactive.beforeLoadPromise?.resolve();
+    match._nonReactive.beforeLoadPromise = void 0;
+    inner.updateMatch(matchId, (prev) => ({
+      ...prev,
+      isFetching: false
+    }));
+  };
+  if (!route.options.beforeLoad) {
+    batch(() => {
+      pending();
+      resolve();
+    });
+    return;
+  }
+  match._nonReactive.beforeLoadPromise = createControlledPromise();
+  const context = {
+    ...buildMatchContext(inner, index, false),
+    ...match.__routeContext
+  };
+  const { search, params, cause } = match;
+  const preload = resolvePreload(inner, matchId);
+  const beforeLoadFnContext = {
+    search,
+    abortController,
+    params,
+    preload,
+    context,
+    location: inner.location,
+    navigate: (opts) => inner.router.navigate({
+      ...opts,
+      _fromLocation: inner.location
+    }),
+    buildLocation: inner.router.buildLocation,
+    cause: preload ? "preload" : cause,
+    matches: inner.matches,
+    ...inner.router.options.additionalContext
+  };
+  const updateContext = (beforeLoadContext2) => {
+    if (beforeLoadContext2 === void 0) {
+      batch(() => {
+        pending();
+        resolve();
+      });
+      return;
+    }
+    if (isRedirect(beforeLoadContext2) || isNotFound(beforeLoadContext2)) {
+      pending();
+      handleSerialError(inner, index, beforeLoadContext2, "BEFORE_LOAD");
+    }
+    batch(() => {
+      pending();
+      inner.updateMatch(matchId, (prev) => ({
+        ...prev,
+        __beforeLoadContext: beforeLoadContext2
+      }));
+      resolve();
+    });
+  };
+  let beforeLoadContext;
+  try {
+    beforeLoadContext = route.options.beforeLoad(beforeLoadFnContext);
+    if (isPromise(beforeLoadContext)) {
+      pending();
+      return beforeLoadContext.catch((err) => {
+        handleSerialError(inner, index, err, "BEFORE_LOAD");
+      }).then(updateContext);
+    }
+  } catch (err) {
+    pending();
+    handleSerialError(inner, index, err, "BEFORE_LOAD");
+  }
+  updateContext(beforeLoadContext);
+  return;
+};
+const handleBeforeLoad = (inner, index) => {
+  const { id: matchId, routeId } = inner.matches[index];
+  const route = inner.router.looseRoutesById[routeId];
+  const serverSsr = () => {
+    if (inner.router.isServer) {
+      const maybePromise = isBeforeLoadSsr(inner, matchId, index, route);
+      if (isPromise(maybePromise)) return maybePromise.then(queueExecution);
+    }
+    return queueExecution();
+  };
+  const execute = () => executeBeforeLoad(inner, matchId, index, route);
+  const queueExecution = () => {
+    if (shouldSkipLoader(inner, matchId)) return;
+    const result = preBeforeLoadSetup(inner, matchId, route);
+    return isPromise(result) ? result.then(execute) : execute();
+  };
+  return serverSsr();
+};
+const executeHead = (inner, matchId, route) => {
+  const match = inner.router.getMatch(matchId);
+  if (!match) {
+    return;
+  }
+  if (!route.options.head && !route.options.scripts && !route.options.headers) {
+    return;
+  }
+  const assetContext = {
+    matches: inner.matches,
+    match,
+    params: match.params,
+    loaderData: match.loaderData
+  };
+  return Promise.all([
+    route.options.head?.(assetContext),
+    route.options.scripts?.(assetContext),
+    route.options.headers?.(assetContext)
+  ]).then(([headFnContent, scripts, headers]) => {
+    const meta = headFnContent?.meta;
+    const links = headFnContent?.links;
+    const headScripts = headFnContent?.scripts;
+    const styles = headFnContent?.styles;
+    return {
+      meta,
+      links,
+      headScripts,
+      headers,
+      scripts,
+      styles
+    };
+  });
+};
+const getLoaderContext = (inner, matchId, index, route) => {
+  const parentMatchPromise = inner.matchPromises[index - 1];
+  const { params, loaderDeps, abortController, cause } = inner.router.getMatch(matchId);
+  const context = buildMatchContext(inner, index);
+  const preload = resolvePreload(inner, matchId);
+  return {
+    params,
+    deps: loaderDeps,
+    preload: !!preload,
+    parentMatchPromise,
+    abortController,
+    context,
+    location: inner.location,
+    navigate: (opts) => inner.router.navigate({
+      ...opts,
+      _fromLocation: inner.location
+    }),
+    cause: preload ? "preload" : cause,
+    route,
+    ...inner.router.options.additionalContext
+  };
+};
+const runLoader = async (inner, matchId, index, route) => {
+  try {
+    const match = inner.router.getMatch(matchId);
+    try {
+      if (!inner.router.isServer || match.ssr === true) {
+        loadRouteChunk(route);
+      }
+      const loaderResult = route.options.loader?.(
+        getLoaderContext(inner, matchId, index, route)
+      );
+      const loaderResultIsPromise = route.options.loader && isPromise(loaderResult);
+      const willLoadSomething = !!(loaderResultIsPromise || route._lazyPromise || route._componentsPromise || route.options.head || route.options.scripts || route.options.headers || match._nonReactive.minPendingPromise);
+      if (willLoadSomething) {
+        inner.updateMatch(matchId, (prev) => ({
+          ...prev,
+          isFetching: "loader"
+        }));
+      }
+      if (route.options.loader) {
+        const loaderData = loaderResultIsPromise ? await loaderResult : loaderResult;
+        handleRedirectAndNotFound(
+          inner,
+          inner.router.getMatch(matchId),
+          loaderData
+        );
+        if (loaderData !== void 0) {
+          inner.updateMatch(matchId, (prev) => ({
+            ...prev,
+            loaderData
+          }));
+        }
+      }
+      if (route._lazyPromise) await route._lazyPromise;
+      const pendingPromise = match._nonReactive.minPendingPromise;
+      if (pendingPromise) await pendingPromise;
+      if (route._componentsPromise) await route._componentsPromise;
+      inner.updateMatch(matchId, (prev) => ({
+        ...prev,
+        error: void 0,
+        status: "success",
+        isFetching: false,
+        updatedAt: Date.now()
+      }));
+    } catch (e) {
+      let error2 = e;
+      const pendingPromise = match._nonReactive.minPendingPromise;
+      if (pendingPromise) await pendingPromise;
+      if (isNotFound(e)) {
+        await route.options.notFoundComponent?.preload?.();
+      }
+      handleRedirectAndNotFound(inner, inner.router.getMatch(matchId), e);
+      try {
+        route.options.onError?.(e);
+      } catch (onErrorError) {
+        error2 = onErrorError;
+        handleRedirectAndNotFound(
+          inner,
+          inner.router.getMatch(matchId),
+          onErrorError
+        );
+      }
+      inner.updateMatch(matchId, (prev) => ({
+        ...prev,
+        error: error2,
+        status: "error",
+        isFetching: false
+      }));
+    }
+  } catch (err) {
+    const match = inner.router.getMatch(matchId);
+    if (match) {
+      match._nonReactive.loaderPromise = void 0;
+    }
+    handleRedirectAndNotFound(inner, match, err);
+  }
+};
+const loadRouteMatch = async (inner, index) => {
+  const { id: matchId, routeId } = inner.matches[index];
+  let loaderShouldRunAsync = false;
+  let loaderIsRunningAsync = false;
+  const route = inner.router.looseRoutesById[routeId];
+  const commitContext = () => {
+    inner.updateMatch(matchId, (prev) => ({
+      ...prev,
+      context: buildMatchContext(inner, index)
+    }));
+  };
+  if (shouldSkipLoader(inner, matchId)) {
+    if (inner.router.isServer) {
+      return inner.router.getMatch(matchId);
+    }
+  } else {
+    const prevMatch = inner.router.getMatch(matchId);
+    if (prevMatch._nonReactive.loaderPromise) {
+      if (prevMatch.status === "success" && !inner.sync && !prevMatch.preload) {
+        return prevMatch;
+      }
+      await prevMatch._nonReactive.loaderPromise;
+      const match2 = inner.router.getMatch(matchId);
+      const error2 = match2._nonReactive.error || match2.error;
+      if (error2) {
+        handleRedirectAndNotFound(inner, match2, error2);
+      }
+    } else {
+      const age = Date.now() - prevMatch.updatedAt;
+      const preload = resolvePreload(inner, matchId);
+      const staleAge = preload ? route.options.preloadStaleTime ?? inner.router.options.defaultPreloadStaleTime ?? 3e4 : route.options.staleTime ?? inner.router.options.defaultStaleTime ?? 0;
+      const shouldReloadOption = route.options.shouldReload;
+      const shouldReload = typeof shouldReloadOption === "function" ? shouldReloadOption(getLoaderContext(inner, matchId, index, route)) : shouldReloadOption;
+      const nextPreload = !!preload && !inner.router.state.matches.some((d) => d.id === matchId);
+      const match2 = inner.router.getMatch(matchId);
+      match2._nonReactive.loaderPromise = createControlledPromise();
+      if (nextPreload !== match2.preload) {
+        inner.updateMatch(matchId, (prev) => ({
+          ...prev,
+          preload: nextPreload
+        }));
+      }
+      const { status, invalid } = match2;
+      loaderShouldRunAsync = status === "success" && (invalid || (shouldReload ?? age > staleAge));
+      if (preload && route.options.preload === false) ;
+      else if (loaderShouldRunAsync && !inner.sync) {
+        loaderIsRunningAsync = true;
+        (async () => {
+          try {
+            await runLoader(inner, matchId, index, route);
+            commitContext();
+            const match3 = inner.router.getMatch(matchId);
+            match3._nonReactive.loaderPromise?.resolve();
+            match3._nonReactive.loadPromise?.resolve();
+            match3._nonReactive.loaderPromise = void 0;
+          } catch (err) {
+            if (isRedirect(err)) {
+              await inner.router.navigate(err.options);
+            }
+          }
+        })();
+      } else if (status !== "success" || loaderShouldRunAsync && inner.sync) {
+        await runLoader(inner, matchId, index, route);
+      }
+    }
+  }
+  const match = inner.router.getMatch(matchId);
+  if (!loaderIsRunningAsync) {
+    match._nonReactive.loaderPromise?.resolve();
+    match._nonReactive.loadPromise?.resolve();
+  }
+  clearTimeout(match._nonReactive.pendingTimeout);
+  match._nonReactive.pendingTimeout = void 0;
+  if (!loaderIsRunningAsync) match._nonReactive.loaderPromise = void 0;
+  match._nonReactive.dehydrated = void 0;
+  if (!loaderIsRunningAsync) {
+    commitContext();
+  }
+  const nextIsFetching = loaderIsRunningAsync ? match.isFetching : false;
+  if (nextIsFetching !== match.isFetching || match.invalid !== false) {
+    inner.updateMatch(matchId, (prev) => ({
+      ...prev,
+      isFetching: nextIsFetching,
+      invalid: false
+    }));
+    return inner.router.getMatch(matchId);
+  } else {
+    return match;
+  }
+};
+async function loadMatches(arg) {
+  const inner = Object.assign(arg, {
+    matchPromises: []
+  });
+  if (!inner.router.isServer && inner.router.state.matches.some((d) => d._forcePending)) {
+    triggerOnReady(inner);
+  }
+  try {
+    for (let i = 0; i < inner.matches.length; i++) {
+      const beforeLoad = handleBeforeLoad(inner, i);
+      if (isPromise(beforeLoad)) await beforeLoad;
+    }
+    const max = inner.firstBadMatchIndex ?? inner.matches.length;
+    for (let i = 0; i < max; i++) {
+      inner.matchPromises.push(loadRouteMatch(inner, i));
+    }
+    const results = await Promise.allSettled(inner.matchPromises);
+    const failures = results.filter(
+      (result) => result.status === "rejected"
+    ).map((result) => result.reason);
+    let firstNotFound;
+    for (const err of failures) {
+      if (isRedirect(err)) {
+        throw err;
+      }
+      if (!firstNotFound && isNotFound(err)) {
+        firstNotFound = err;
+      }
+    }
+    for (const match of inner.matches) {
+      const { id: matchId, routeId } = match;
+      const route = inner.router.looseRoutesById[routeId];
+      try {
+        const headResult = executeHead(inner, matchId, route);
+        if (headResult) {
+          const head = await headResult;
+          inner.updateMatch(matchId, (prev) => ({
+            ...prev,
+            ...head
+          }));
+        }
+      } catch (err) {
+        console.error(`Error executing head for route ${routeId}:`, err);
+      }
+    }
+    if (firstNotFound) {
+      throw firstNotFound;
+    }
+    const readyPromise = triggerOnReady(inner);
+    if (isPromise(readyPromise)) await readyPromise;
+  } catch (err) {
+    if (isNotFound(err) && !inner.preload) {
+      const readyPromise = triggerOnReady(inner);
+      if (isPromise(readyPromise)) await readyPromise;
+      throw err;
+    }
+    if (isRedirect(err)) {
+      throw err;
+    }
+  }
+  return inner.matches;
+}
+async function loadRouteChunk(route) {
+  if (!route._lazyLoaded && route._lazyPromise === void 0) {
+    if (route.lazyFn) {
+      route._lazyPromise = route.lazyFn().then((lazyRoute) => {
+        const { id: _id, ...options } = lazyRoute.options;
+        Object.assign(route.options, options);
+        route._lazyLoaded = true;
+        route._lazyPromise = void 0;
+      });
+    } else {
+      route._lazyLoaded = true;
+    }
+  }
+  if (!route._componentsLoaded && route._componentsPromise === void 0) {
+    const loadComponents = () => {
+      const preloads = [];
+      for (const type of componentTypes) {
+        const preload = route.options[type]?.preload;
+        if (preload) preloads.push(preload());
+      }
+      if (preloads.length)
+        return Promise.all(preloads).then(() => {
+          route._componentsLoaded = true;
+          route._componentsPromise = void 0;
+        });
+      route._componentsLoaded = true;
+      route._componentsPromise = void 0;
+      return;
+    };
+    route._componentsPromise = route._lazyPromise ? route._lazyPromise.then(loadComponents) : loadComponents();
+  }
+  return route._componentsPromise;
+}
+function makeMaybe(value, error2) {
+  if (error2) {
+    return { status: "error", error: error2 };
+  }
+  return { status: "success", value };
+}
+function routeNeedsPreload(route) {
+  for (const componentType of componentTypes) {
+    if (route.options[componentType]?.preload) {
+      return true;
+    }
+  }
+  return false;
+}
+const componentTypes = [
+  "component",
+  "errorComponent",
+  "pendingComponent",
+  "notFoundComponent"
+];
+function composeRewrites(rewrites) {
+  return {
+    input: ({ url }) => {
+      for (const rewrite of rewrites) {
+        url = executeRewriteInput(rewrite, url);
+      }
+      return url;
+    },
+    output: ({ url }) => {
+      for (let i = rewrites.length - 1; i >= 0; i--) {
+        url = executeRewriteOutput(rewrites[i], url);
+      }
+      return url;
+    }
+  };
+}
+function rewriteBasepath(opts) {
+  const trimmedBasepath = trimPath(opts.basepath);
+  const normalizedBasepath = `/${trimmedBasepath}`;
+  const normalizedBasepathWithSlash = `${normalizedBasepath}/`;
+  const checkBasepath = opts.caseSensitive ? normalizedBasepath : normalizedBasepath.toLowerCase();
+  const checkBasepathWithSlash = opts.caseSensitive ? normalizedBasepathWithSlash : normalizedBasepathWithSlash.toLowerCase();
+  return {
+    input: ({ url }) => {
+      const pathname = opts.caseSensitive ? url.pathname : url.pathname.toLowerCase();
+      if (pathname === checkBasepath) {
+        url.pathname = "/";
+      } else if (pathname.startsWith(checkBasepathWithSlash)) {
+        url.pathname = url.pathname.slice(normalizedBasepath.length);
+      }
+      return url;
+    },
+    output: ({ url }) => {
+      url.pathname = joinPaths(["/", trimmedBasepath, url.pathname]);
+      return url;
+    }
+  };
+}
+function executeRewriteInput(rewrite, url) {
+  const res = rewrite?.input?.({ url });
+  if (res) {
+    if (typeof res === "string") {
+      return new URL(res);
+    } else if (res instanceof URL) {
+      return res;
+    }
+  }
+  return url;
+}
+function executeRewriteOutput(rewrite, url) {
+  const res = rewrite?.output?.({ url });
+  if (res) {
+    if (typeof res === "string") {
+      return new URL(res);
+    } else if (res instanceof URL) {
+      return res;
+    }
+  }
+  return url;
+}
+function getLocationChangeInfo(routerState) {
+  const fromLocation = routerState.resolvedLocation;
+  const toLocation = routerState.location;
+  const pathChanged = fromLocation?.pathname !== toLocation.pathname;
+  const hrefChanged = fromLocation?.href !== toLocation.href;
+  const hashChanged = fromLocation?.hash !== toLocation.hash;
+  return { fromLocation, toLocation, pathChanged, hrefChanged, hashChanged };
+}
+class RouterCore {
+  /**
+   * @deprecated Use the `createRouter` function instead
+   */
+  constructor(options) {
+    this.tempLocationKey = `${Math.round(
+      Math.random() * 1e7
+    )}`;
+    this.resetNextScroll = true;
+    this.shouldViewTransition = void 0;
+    this.isViewTransitionTypesSupported = void 0;
+    this.subscribers = /* @__PURE__ */ new Set();
+    this.isScrollRestoring = false;
+    this.isScrollRestorationSetup = false;
+    this.startTransition = (fn2) => fn2();
+    this.update = (newOptions) => {
+      if (newOptions.notFoundRoute) {
+        console.warn(
+          "The notFoundRoute API is deprecated and will be removed in the next major version. See https://tanstack.com/router/v1/docs/framework/react/guide/not-found-errors#migrating-from-notfoundroute for more info."
+        );
+      }
+      const prevOptions = this.options;
+      const prevBasepath = this.basepath ?? prevOptions?.basepath ?? "/";
+      const basepathWasUnset = this.basepath === void 0;
+      const prevRewriteOption = prevOptions?.rewrite;
+      this.options = {
+        ...prevOptions,
+        ...newOptions
+      };
+      this.isServer = this.options.isServer ?? typeof document === "undefined";
+      this.pathParamsDecodeCharMap = this.options.pathParamsAllowedCharacters ? new Map(
+        this.options.pathParamsAllowedCharacters.map((char) => [
+          encodeURIComponent(char),
+          char
+        ])
+      ) : void 0;
+      if (!this.history || this.options.history && this.options.history !== this.history) {
+        if (!this.options.history) {
+          if (!this.isServer) {
+            this.history = createBrowserHistory();
+          }
+        } else {
+          this.history = this.options.history;
+        }
+      }
+      this.origin = this.options.origin;
+      if (!this.origin) {
+        if (!this.isServer && window?.origin && window.origin !== "null") {
+          this.origin = window.origin;
+        } else {
+          this.origin = "http://localhost";
+        }
+      }
+      if (this.history) {
+        this.updateLatestLocation();
+      }
+      if (this.options.routeTree !== this.routeTree) {
+        this.routeTree = this.options.routeTree;
+        this.buildRouteTree();
+      }
+      if (!this.__store && this.latestLocation) {
+        this.__store = new Store(getInitialRouterState(this.latestLocation), {
+          onUpdate: () => {
+            this.__store.state = {
+              ...this.state,
+              cachedMatches: this.state.cachedMatches.filter(
+                (d) => !["redirected"].includes(d.status)
+              )
+            };
+          }
+        });
+        setupScrollRestoration(this);
+      }
+      let needsLocationUpdate = false;
+      const nextBasepath = this.options.basepath ?? "/";
+      const nextRewriteOption = this.options.rewrite;
+      const basepathChanged = basepathWasUnset || prevBasepath !== nextBasepath;
+      const rewriteChanged = prevRewriteOption !== nextRewriteOption;
+      if (basepathChanged || rewriteChanged) {
+        this.basepath = nextBasepath;
+        const rewrites = [];
+        if (trimPath(nextBasepath) !== "") {
+          rewrites.push(
+            rewriteBasepath({
+              basepath: nextBasepath
+            })
+          );
+        }
+        if (nextRewriteOption) {
+          rewrites.push(nextRewriteOption);
+        }
+        this.rewrite = rewrites.length === 0 ? void 0 : rewrites.length === 1 ? rewrites[0] : composeRewrites(rewrites);
+        if (this.history) {
+          this.updateLatestLocation();
+        }
+        needsLocationUpdate = true;
+      }
+      if (needsLocationUpdate && this.__store) {
+        this.__store.state = {
+          ...this.state,
+          location: this.latestLocation
+        };
+      }
+      if (typeof window !== "undefined" && "CSS" in window && typeof window.CSS?.supports === "function") {
+        this.isViewTransitionTypesSupported = window.CSS.supports(
+          "selector(:active-view-transition-type(a)"
+        );
+      }
+    };
+    this.updateLatestLocation = () => {
+      this.latestLocation = this.parseLocation(
+        this.history.location,
+        this.latestLocation
+      );
+    };
+    this.buildRouteTree = () => {
+      const { routesById, routesByPath, processedTree } = processRouteTree(
+        this.routeTree,
+        this.options.caseSensitive,
+        (route, i) => {
+          route.init({
+            originalIndex: i
+          });
+        }
+      );
+      if (this.options.routeMasks) {
+        processRouteMasks(this.options.routeMasks, processedTree);
+      }
+      this.routesById = routesById;
+      this.routesByPath = routesByPath;
+      this.processedTree = processedTree;
+      const notFoundRoute = this.options.notFoundRoute;
+      if (notFoundRoute) {
+        notFoundRoute.init({
+          originalIndex: 99999999999
+        });
+        this.routesById[notFoundRoute.id] = notFoundRoute;
+      }
+    };
+    this.subscribe = (eventType, fn2) => {
+      const listener = {
+        eventType,
+        fn: fn2
+      };
+      this.subscribers.add(listener);
+      return () => {
+        this.subscribers.delete(listener);
+      };
+    };
+    this.emit = (routerEvent) => {
+      this.subscribers.forEach((listener) => {
+        if (listener.eventType === routerEvent.type) {
+          listener.fn(routerEvent);
+        }
+      });
+    };
+    this.parseLocation = (locationToParse, previousLocation) => {
+      const parse = ({
+        href,
+        state
+      }) => {
+        const fullUrl = new URL(href, this.origin);
+        const url = executeRewriteInput(this.rewrite, fullUrl);
+        const parsedSearch = this.options.parseSearch(url.search);
+        const searchStr = this.options.stringifySearch(parsedSearch);
+        url.search = searchStr;
+        const fullPath = url.href.replace(url.origin, "");
+        return {
+          href: fullPath,
+          publicHref: href,
+          url,
+          pathname: decodePath(url.pathname),
+          searchStr,
+          search: replaceEqualDeep(previousLocation?.search, parsedSearch),
+          hash: url.hash.split("#").reverse()[0] ?? "",
+          state: replaceEqualDeep(previousLocation?.state, state)
+        };
+      };
+      const location = parse(locationToParse);
+      const { __tempLocation, __tempKey } = location.state;
+      if (__tempLocation && (!__tempKey || __tempKey === this.tempLocationKey)) {
+        const parsedTempLocation = parse(__tempLocation);
+        parsedTempLocation.state.key = location.state.key;
+        parsedTempLocation.state.__TSR_key = location.state.__TSR_key;
+        delete parsedTempLocation.state.__tempLocation;
+        return {
+          ...parsedTempLocation,
+          maskedLocation: location
+        };
+      }
+      return location;
+    };
+    this.resolvePathCache = createLRUCache(1e3);
+    this.resolvePathWithBase = (from, path) => {
+      const resolvedPath = resolvePath({
+        base: from,
+        to: cleanPath(path),
+        trailingSlash: this.options.trailingSlash,
+        cache: this.resolvePathCache
+      });
+      return resolvedPath;
+    };
+    this.matchRoutes = (pathnameOrNext, locationSearchOrOpts, opts) => {
+      if (typeof pathnameOrNext === "string") {
+        return this.matchRoutesInternal(
+          {
+            pathname: pathnameOrNext,
+            search: locationSearchOrOpts
+          },
+          opts
+        );
+      }
+      return this.matchRoutesInternal(pathnameOrNext, locationSearchOrOpts);
+    };
+    this.getMatchedRoutes = (pathname) => {
+      return getMatchedRoutes({
+        pathname,
+        routesById: this.routesById,
+        processedTree: this.processedTree
+      });
+    };
+    this.cancelMatch = (id) => {
+      const match = this.getMatch(id);
+      if (!match) return;
+      match.abortController.abort();
+      clearTimeout(match._nonReactive.pendingTimeout);
+      match._nonReactive.pendingTimeout = void 0;
+    };
+    this.cancelMatches = () => {
+      const currentPendingMatches = this.state.matches.filter(
+        (match) => match.status === "pending"
+      );
+      const currentLoadingMatches = this.state.matches.filter(
+        (match) => match.isFetching === "loader"
+      );
+      const matchesToCancelArray = /* @__PURE__ */ new Set([
+        ...this.state.pendingMatches ?? [],
+        ...currentPendingMatches,
+        ...currentLoadingMatches
+      ]);
+      matchesToCancelArray.forEach((match) => {
+        this.cancelMatch(match.id);
+      });
+    };
+    this.buildLocation = (opts) => {
+      const build = (dest = {}) => {
+        const currentLocation = dest._fromLocation || this.pendingBuiltLocation || this.latestLocation;
+        const allCurrentLocationMatches = this.matchRoutes(currentLocation, {
+          _buildLocation: true
+        });
+        const lastMatch = last(allCurrentLocationMatches);
+        if (dest.from && process.env.NODE_ENV !== "production" && dest._isNavigate) {
+          const allFromMatches = this.getMatchedRoutes(dest.from).matchedRoutes;
+          const matchedFrom = findLast(allCurrentLocationMatches, (d) => {
+            return comparePaths(d.fullPath, dest.from);
+          });
+          const matchedCurrent = findLast(allFromMatches, (d) => {
+            return comparePaths(d.fullPath, lastMatch.fullPath);
+          });
+          if (!matchedFrom && !matchedCurrent) {
+            console.warn(`Could not find match for from: ${dest.from}`);
+          }
+        }
+        const defaultedFromPath = dest.unsafeRelative === "path" ? currentLocation.pathname : dest.from ?? lastMatch.fullPath;
+        const fromPath = this.resolvePathWithBase(defaultedFromPath, ".");
+        const fromSearch = lastMatch.search;
+        const fromParams = { ...lastMatch.params };
+        const nextTo = dest.to ? this.resolvePathWithBase(fromPath, `${dest.to}`) : this.resolvePathWithBase(fromPath, ".");
+        const nextParams = dest.params === false || dest.params === null ? {} : (dest.params ?? true) === true ? fromParams : Object.assign(
+          fromParams,
+          functionalUpdate(dest.params, fromParams)
+        );
+        const interpolatedNextTo = interpolatePath({
+          path: nextTo,
+          params: nextParams
+        }).interpolatedPath;
+        const destRoutes = this.matchRoutes(interpolatedNextTo, void 0, {
+          _buildLocation: true
+        }).map((d) => this.looseRoutesById[d.routeId]);
+        if (Object.keys(nextParams).length > 0) {
+          for (const route of destRoutes) {
+            const fn2 = route.options.params?.stringify ?? route.options.stringifyParams;
+            if (fn2) {
+              Object.assign(nextParams, fn2(nextParams));
+            }
+          }
+        }
+        const nextPathname = opts.leaveParams ? (
+          // Use the original template path for interpolation
+          // This preserves the original parameter syntax including optional parameters
+          nextTo
+        ) : decodePath(
+          interpolatePath({
+            path: nextTo,
+            params: nextParams,
+            decodeCharMap: this.pathParamsDecodeCharMap
+          }).interpolatedPath
+        );
+        let nextSearch = fromSearch;
+        if (opts._includeValidateSearch && this.options.search?.strict) {
+          const validatedSearch = {};
+          destRoutes.forEach((route) => {
+            if (route.options.validateSearch) {
+              try {
+                Object.assign(
+                  validatedSearch,
+                  validateSearch(route.options.validateSearch, {
+                    ...validatedSearch,
+                    ...nextSearch
+                  })
+                );
+              } catch {
+              }
+            }
+          });
+          nextSearch = validatedSearch;
+        }
+        nextSearch = applySearchMiddleware({
+          search: nextSearch,
+          dest,
+          destRoutes,
+          _includeValidateSearch: opts._includeValidateSearch
+        });
+        nextSearch = replaceEqualDeep(fromSearch, nextSearch);
+        const searchStr = this.options.stringifySearch(nextSearch);
+        const hash = dest.hash === true ? currentLocation.hash : dest.hash ? functionalUpdate(dest.hash, currentLocation.hash) : void 0;
+        const hashStr = hash ? `#${hash}` : "";
+        let nextState = dest.state === true ? currentLocation.state : dest.state ? functionalUpdate(dest.state, currentLocation.state) : {};
+        nextState = replaceEqualDeep(currentLocation.state, nextState);
+        const fullPath = `${nextPathname}${searchStr}${hashStr}`;
+        const url = new URL(fullPath, this.origin);
+        const rewrittenUrl = executeRewriteOutput(this.rewrite, url);
+        return {
+          publicHref: rewrittenUrl.pathname + rewrittenUrl.search + rewrittenUrl.hash,
+          href: fullPath,
+          url: rewrittenUrl,
+          pathname: nextPathname,
+          search: nextSearch,
+          searchStr,
+          state: nextState,
+          hash: hash ?? "",
+          unmaskOnReload: dest.unmaskOnReload
+        };
+      };
+      const buildWithMatches = (dest = {}, maskedDest) => {
+        const next = build(dest);
+        let maskedNext = maskedDest ? build(maskedDest) : void 0;
+        if (!maskedNext) {
+          const params = {};
+          if (this.options.routeMasks) {
+            const match = findFlatMatch(
+              next.pathname,
+              this.processedTree
+            );
+            if (match) {
+              Object.assign(params, match.params);
+              const {
+                from: _from,
+                params: maskParams,
+                ...maskProps
+              } = match.route;
+              const nextParams = maskParams === false || maskParams === null ? {} : (maskParams ?? true) === true ? params : Object.assign(params, functionalUpdate(maskParams, params));
+              maskedDest = {
+                from: opts.from,
+                ...maskProps,
+                params: nextParams
+              };
+              maskedNext = build(maskedDest);
+            }
+          }
+        }
+        if (maskedNext) {
+          next.maskedLocation = maskedNext;
+        }
+        return next;
+      };
+      if (opts.mask) {
+        return buildWithMatches(opts, {
+          from: opts.from,
+          ...opts.mask
+        });
+      }
+      return buildWithMatches(opts);
+    };
+    this.commitLocation = ({
+      viewTransition,
+      ignoreBlocker,
+      ...next
+    }) => {
+      const isSameState = () => {
+        const ignoredProps = [
+          "key",
+          // TODO: Remove in v2 - use __TSR_key instead
+          "__TSR_key",
+          "__TSR_index",
+          "__hashScrollIntoViewOptions"
+        ];
+        ignoredProps.forEach((prop) => {
+          next.state[prop] = this.latestLocation.state[prop];
+        });
+        const isEqual = deepEqual(next.state, this.latestLocation.state);
+        ignoredProps.forEach((prop) => {
+          delete next.state[prop];
+        });
+        return isEqual;
+      };
+      const isSameUrl = trimPathRight(this.latestLocation.href) === trimPathRight(next.href);
+      const previousCommitPromise = this.commitLocationPromise;
+      this.commitLocationPromise = createControlledPromise(() => {
+        previousCommitPromise?.resolve();
+      });
+      if (isSameUrl && isSameState()) {
+        this.load();
+      } else {
+        let {
+          // eslint-disable-next-line prefer-const
+          maskedLocation,
+          // eslint-disable-next-line prefer-const
+          hashScrollIntoView,
+          // don't pass url into history since it is a URL instance that cannot be serialized
+          // eslint-disable-next-line prefer-const
+          url: _url,
+          ...nextHistory
+        } = next;
+        if (maskedLocation) {
+          nextHistory = {
+            ...maskedLocation,
+            state: {
+              ...maskedLocation.state,
+              __tempKey: void 0,
+              __tempLocation: {
+                ...nextHistory,
+                search: nextHistory.searchStr,
+                state: {
+                  ...nextHistory.state,
+                  __tempKey: void 0,
+                  __tempLocation: void 0,
+                  __TSR_key: void 0,
+                  key: void 0
+                  // TODO: Remove in v2 - use __TSR_key instead
+                }
+              }
+            }
+          };
+          if (nextHistory.unmaskOnReload ?? this.options.unmaskOnReload ?? false) {
+            nextHistory.state.__tempKey = this.tempLocationKey;
+          }
+        }
+        nextHistory.state.__hashScrollIntoViewOptions = hashScrollIntoView ?? this.options.defaultHashScrollIntoView ?? true;
+        this.shouldViewTransition = viewTransition;
+        this.history[next.replace ? "replace" : "push"](
+          nextHistory.publicHref,
+          nextHistory.state,
+          { ignoreBlocker }
+        );
+      }
+      this.resetNextScroll = next.resetScroll ?? true;
+      if (!this.history.subscribers.size) {
+        this.load();
+      }
+      return this.commitLocationPromise;
+    };
+    this.buildAndCommitLocation = ({
+      replace,
+      resetScroll,
+      hashScrollIntoView,
+      viewTransition,
+      ignoreBlocker,
+      href,
+      ...rest
+    } = {}) => {
+      if (href) {
+        const currentIndex = this.history.location.state.__TSR_index;
+        const parsed = parseHref(href, {
+          __TSR_index: replace ? currentIndex : currentIndex + 1
+        });
+        rest.to = parsed.pathname;
+        rest.search = this.options.parseSearch(parsed.search);
+        rest.hash = parsed.hash.slice(1);
+      }
+      const location = this.buildLocation({
+        ...rest,
+        _includeValidateSearch: true
+      });
+      this.pendingBuiltLocation = location;
+      const commitPromise = this.commitLocation({
+        ...location,
+        viewTransition,
+        replace,
+        resetScroll,
+        hashScrollIntoView,
+        ignoreBlocker
+      });
+      Promise.resolve().then(() => {
+        if (this.pendingBuiltLocation === location) {
+          this.pendingBuiltLocation = void 0;
+        }
+      });
+      return commitPromise;
+    };
+    this.navigate = async ({
+      to: to2,
+      reloadDocument,
+      href,
+      publicHref,
+      ...rest
+    }) => {
+      let hrefIsUrl = false;
+      if (href) {
+        try {
+          new URL(`${href}`);
+          hrefIsUrl = true;
+        } catch {
+        }
+      }
+      if (hrefIsUrl && !reloadDocument) {
+        reloadDocument = true;
+      }
+      if (reloadDocument) {
+        if (!href || !publicHref && !hrefIsUrl) {
+          const location = this.buildLocation({ to: to2, ...rest });
+          href = href ?? location.url.href;
+          publicHref = publicHref ?? location.url.href;
+        }
+        const reloadHref = !hrefIsUrl && publicHref ? publicHref : href;
+        if (!rest.ignoreBlocker) {
+          const historyWithBlockers = this.history;
+          const blockers = historyWithBlockers.getBlockers?.() ?? [];
+          for (const blocker of blockers) {
+            if (blocker?.blockerFn) {
+              const shouldBlock = await blocker.blockerFn({
+                currentLocation: this.latestLocation,
+                nextLocation: this.latestLocation,
+                // External URLs don't have a next location in our router
+                action: "PUSH"
+              });
+              if (shouldBlock) {
+                return Promise.resolve();
+              }
+            }
+          }
+        }
+        if (rest.replace) {
+          window.location.replace(reloadHref);
+        } else {
+          window.location.href = reloadHref;
+        }
+        return Promise.resolve();
+      }
+      return this.buildAndCommitLocation({
+        ...rest,
+        href,
+        to: to2,
+        _isNavigate: true
+      });
+    };
+    this.beforeLoad = () => {
+      this.cancelMatches();
+      this.updateLatestLocation();
+      if (this.isServer) {
+        const nextLocation = this.buildLocation({
+          to: this.latestLocation.pathname,
+          search: true,
+          params: true,
+          hash: true,
+          state: true,
+          _includeValidateSearch: true
+        });
+        if (this.latestLocation.publicHref !== nextLocation.publicHref || nextLocation.url.origin !== this.origin) {
+          const href = this.getParsedLocationHref(nextLocation);
+          throw redirect({ href });
+        }
+      }
+      const pendingMatches = this.matchRoutes(this.latestLocation);
+      this.__store.setState((s) => ({
+        ...s,
+        status: "pending",
+        statusCode: 200,
+        isLoading: true,
+        location: this.latestLocation,
+        pendingMatches,
+        // If a cached moved to pendingMatches, remove it from cachedMatches
+        cachedMatches: s.cachedMatches.filter(
+          (d) => !pendingMatches.some((e) => e.id === d.id)
+        )
+      }));
+    };
+    this.load = async (opts) => {
+      let redirect2;
+      let notFound;
+      let loadPromise;
+      loadPromise = new Promise((resolve) => {
+        this.startTransition(async () => {
+          try {
+            this.beforeLoad();
+            const next = this.latestLocation;
+            const prevLocation = this.state.resolvedLocation;
+            if (!this.state.redirect) {
+              this.emit({
+                type: "onBeforeNavigate",
+                ...getLocationChangeInfo({
+                  resolvedLocation: prevLocation,
+                  location: next
+                })
+              });
+            }
+            this.emit({
+              type: "onBeforeLoad",
+              ...getLocationChangeInfo({
+                resolvedLocation: prevLocation,
+                location: next
+              })
+            });
+            await loadMatches({
+              router: this,
+              sync: opts?.sync,
+              matches: this.state.pendingMatches,
+              location: next,
+              updateMatch: this.updateMatch,
+              // eslint-disable-next-line @typescript-eslint/require-await
+              onReady: async () => {
+                this.startTransition(() => {
+                  this.startViewTransition(async () => {
+                    let exitingMatches = [];
+                    let enteringMatches = [];
+                    let stayingMatches = [];
+                    batch(() => {
+                      this.__store.setState((s) => {
+                        const previousMatches = s.matches;
+                        const newMatches = s.pendingMatches || s.matches;
+                        exitingMatches = previousMatches.filter(
+                          (match) => !newMatches.some((d) => d.id === match.id)
+                        );
+                        enteringMatches = newMatches.filter(
+                          (match) => !previousMatches.some((d) => d.id === match.id)
+                        );
+                        stayingMatches = newMatches.filter(
+                          (match) => previousMatches.some((d) => d.id === match.id)
+                        );
+                        return {
+                          ...s,
+                          isLoading: false,
+                          loadedAt: Date.now(),
+                          matches: newMatches,
+                          pendingMatches: void 0,
+                          /**
+                           * When committing new matches, cache any exiting matches that are still usable.
+                           * Routes that resolved with `status: 'error'` or `status: 'notFound'` are
+                           * deliberately excluded from `cachedMatches` so that subsequent invalidations
+                           * or reloads re-run their loaders instead of reusing the failed/not-found data.
+                           */
+                          cachedMatches: [
+                            ...s.cachedMatches,
+                            ...exitingMatches.filter(
+                              (d) => d.status !== "error" && d.status !== "notFound"
+                            )
+                          ]
+                        };
+                      });
+                      this.clearExpiredCache();
+                    });
+                    [
+                      [exitingMatches, "onLeave"],
+                      [enteringMatches, "onEnter"],
+                      [stayingMatches, "onStay"]
+                    ].forEach(([matches, hook]) => {
+                      matches.forEach((match) => {
+                        this.looseRoutesById[match.routeId].options[hook]?.(
+                          match
+                        );
+                      });
+                    });
+                  });
+                });
+              }
+            });
+          } catch (err) {
+            if (isRedirect(err)) {
+              redirect2 = err;
+              if (!this.isServer) {
+                this.navigate({
+                  ...redirect2.options,
+                  replace: true,
+                  ignoreBlocker: true
+                });
+              }
+            } else if (isNotFound(err)) {
+              notFound = err;
+            }
+            this.__store.setState((s) => ({
+              ...s,
+              statusCode: redirect2 ? redirect2.status : notFound ? 404 : s.matches.some((d) => d.status === "error") ? 500 : 200,
+              redirect: redirect2
+            }));
+          }
+          if (this.latestLoadPromise === loadPromise) {
+            this.commitLocationPromise?.resolve();
+            this.latestLoadPromise = void 0;
+            this.commitLocationPromise = void 0;
+          }
+          resolve();
+        });
+      });
+      this.latestLoadPromise = loadPromise;
+      await loadPromise;
+      while (this.latestLoadPromise && loadPromise !== this.latestLoadPromise) {
+        await this.latestLoadPromise;
+      }
+      let newStatusCode = void 0;
+      if (this.hasNotFoundMatch()) {
+        newStatusCode = 404;
+      } else if (this.__store.state.matches.some((d) => d.status === "error")) {
+        newStatusCode = 500;
+      }
+      if (newStatusCode !== void 0) {
+        this.__store.setState((s) => ({
+          ...s,
+          statusCode: newStatusCode
+        }));
+      }
+    };
+    this.startViewTransition = (fn2) => {
+      const shouldViewTransition = this.shouldViewTransition ?? this.options.defaultViewTransition;
+      delete this.shouldViewTransition;
+      if (shouldViewTransition && typeof document !== "undefined" && "startViewTransition" in document && typeof document.startViewTransition === "function") {
+        let startViewTransitionParams;
+        if (typeof shouldViewTransition === "object" && this.isViewTransitionTypesSupported) {
+          const next = this.latestLocation;
+          const prevLocation = this.state.resolvedLocation;
+          const resolvedViewTransitionTypes = typeof shouldViewTransition.types === "function" ? shouldViewTransition.types(
+            getLocationChangeInfo({
+              resolvedLocation: prevLocation,
+              location: next
+            })
+          ) : shouldViewTransition.types;
+          if (resolvedViewTransitionTypes === false) {
+            fn2();
+            return;
+          }
+          startViewTransitionParams = {
+            update: fn2,
+            types: resolvedViewTransitionTypes
+          };
+        } else {
+          startViewTransitionParams = fn2;
+        }
+        document.startViewTransition(startViewTransitionParams);
+      } else {
+        fn2();
+      }
+    };
+    this.updateMatch = (id, updater) => {
+      this.startTransition(() => {
+        const matchesKey = this.state.pendingMatches?.some((d) => d.id === id) ? "pendingMatches" : this.state.matches.some((d) => d.id === id) ? "matches" : this.state.cachedMatches.some((d) => d.id === id) ? "cachedMatches" : "";
+        if (matchesKey) {
+          this.__store.setState((s) => ({
+            ...s,
+            [matchesKey]: s[matchesKey]?.map(
+              (d) => d.id === id ? updater(d) : d
+            )
+          }));
+        }
+      });
+    };
+    this.getMatch = (matchId) => {
+      const findFn = (d) => d.id === matchId;
+      return this.state.cachedMatches.find(findFn) ?? this.state.pendingMatches?.find(findFn) ?? this.state.matches.find(findFn);
+    };
+    this.invalidate = (opts) => {
+      const invalidate = (d) => {
+        if (opts?.filter?.(d) ?? true) {
+          return {
+            ...d,
+            invalid: true,
+            ...opts?.forcePending || d.status === "error" || d.status === "notFound" ? { status: "pending", error: void 0 } : void 0
+          };
+        }
+        return d;
+      };
+      this.__store.setState((s) => ({
+        ...s,
+        matches: s.matches.map(invalidate),
+        cachedMatches: s.cachedMatches.map(invalidate),
+        pendingMatches: s.pendingMatches?.map(invalidate)
+      }));
+      this.shouldViewTransition = false;
+      return this.load({ sync: opts?.sync });
+    };
+    this.getParsedLocationHref = (location) => {
+      let href = location.url.href;
+      if (this.origin && location.url.origin === this.origin) {
+        href = href.replace(this.origin, "") || "/";
+      }
+      return href;
+    };
+    this.resolveRedirect = (redirect2) => {
+      if (!redirect2.options.href) {
+        const location = this.buildLocation(redirect2.options);
+        const href = this.getParsedLocationHref(location);
+        redirect2.options.href = location.href;
+        redirect2.headers.set("Location", href);
+      }
+      if (!redirect2.headers.get("Location")) {
+        redirect2.headers.set("Location", redirect2.options.href);
+      }
+      return redirect2;
+    };
+    this.clearCache = (opts) => {
+      const filter = opts?.filter;
+      if (filter !== void 0) {
+        this.__store.setState((s) => {
+          return {
+            ...s,
+            cachedMatches: s.cachedMatches.filter(
+              (m2) => !filter(m2)
+            )
+          };
+        });
+      } else {
+        this.__store.setState((s) => {
+          return {
+            ...s,
+            cachedMatches: []
+          };
+        });
+      }
+    };
+    this.clearExpiredCache = () => {
+      const filter = (d) => {
+        const route = this.looseRoutesById[d.routeId];
+        if (!route.options.loader) {
+          return true;
+        }
+        const gcTime = (d.preload ? route.options.preloadGcTime ?? this.options.defaultPreloadGcTime : route.options.gcTime ?? this.options.defaultGcTime) ?? 5 * 60 * 1e3;
+        const isError2 = d.status === "error";
+        if (isError2) return true;
+        const gcEligible = Date.now() - d.updatedAt >= gcTime;
+        return gcEligible;
+      };
+      this.clearCache({ filter });
+    };
+    this.loadRouteChunk = loadRouteChunk;
+    this.preloadRoute = async (opts) => {
+      const next = this.buildLocation(opts);
+      let matches = this.matchRoutes(next, {
+        throwOnError: true,
+        preload: true,
+        dest: opts
+      });
+      const activeMatchIds = new Set(
+        [...this.state.matches, ...this.state.pendingMatches ?? []].map(
+          (d) => d.id
+        )
+      );
+      const loadedMatchIds = /* @__PURE__ */ new Set([
+        ...activeMatchIds,
+        ...this.state.cachedMatches.map((d) => d.id)
+      ]);
+      batch(() => {
+        matches.forEach((match) => {
+          if (!loadedMatchIds.has(match.id)) {
+            this.__store.setState((s) => ({
+              ...s,
+              cachedMatches: [...s.cachedMatches, match]
+            }));
+          }
+        });
+      });
+      try {
+        matches = await loadMatches({
+          router: this,
+          matches,
+          location: next,
+          preload: true,
+          updateMatch: (id, updater) => {
+            if (activeMatchIds.has(id)) {
+              matches = matches.map((d) => d.id === id ? updater(d) : d);
+            } else {
+              this.updateMatch(id, updater);
+            }
+          }
+        });
+        return matches;
+      } catch (err) {
+        if (isRedirect(err)) {
+          if (err.options.reloadDocument) {
+            return void 0;
+          }
+          return await this.preloadRoute({
+            ...err.options,
+            _fromLocation: next
+          });
+        }
+        if (!isNotFound(err)) {
+          console.error(err);
+        }
+        return void 0;
+      }
+    };
+    this.matchRoute = (location, opts) => {
+      const matchLocation = {
+        ...location,
+        to: location.to ? this.resolvePathWithBase(
+          location.from || "",
+          location.to
+        ) : void 0,
+        params: location.params || {},
+        leaveParams: true
+      };
+      const next = this.buildLocation(matchLocation);
+      if (opts?.pending && this.state.status !== "pending") {
+        return false;
+      }
+      const pending = opts?.pending === void 0 ? !this.state.isLoading : opts.pending;
+      const baseLocation = pending ? this.latestLocation : this.state.resolvedLocation || this.state.location;
+      const match = findSingleMatch(
+        next.pathname,
+        opts?.caseSensitive ?? false,
+        opts?.fuzzy ?? false,
+        baseLocation.pathname,
+        this.processedTree
+      );
+      if (!match) {
+        return false;
+      }
+      if (location.params) {
+        if (!deepEqual(match.params, location.params, { partial: true })) {
+          return false;
+        }
+      }
+      if (opts?.includeSearch ?? true) {
+        return deepEqual(baseLocation.search, next.search, { partial: true }) ? match.params : false;
+      }
+      return match.params;
+    };
+    this.hasNotFoundMatch = () => {
+      return this.__store.state.matches.some(
+        (d) => d.status === "notFound" || d.globalNotFound
+      );
+    };
+    this.update({
+      defaultPreloadDelay: 50,
+      defaultPendingMs: 1e3,
+      defaultPendingMinMs: 500,
+      context: void 0,
+      ...options,
+      caseSensitive: options.caseSensitive ?? false,
+      notFoundMode: options.notFoundMode ?? "fuzzy",
+      stringifySearch: options.stringifySearch ?? defaultStringifySearch,
+      parseSearch: options.parseSearch ?? defaultParseSearch
+    });
+    if (typeof document !== "undefined") {
+      self.__TSR_ROUTER__ = this;
+    }
+  }
+  isShell() {
+    return !!this.options.isShell;
+  }
+  isPrerendering() {
+    return !!this.options.isPrerendering;
+  }
+  get state() {
+    return this.__store.state;
+  }
+  get looseRoutesById() {
+    return this.routesById;
+  }
+  matchRoutesInternal(next, opts) {
+    const matchedRoutesResult = this.getMatchedRoutes(next.pathname);
+    const { foundRoute, routeParams } = matchedRoutesResult;
+    let { matchedRoutes } = matchedRoutesResult;
+    let isGlobalNotFound = false;
+    if (
+      // If we found a route, and it's not an index route and we have left over path
+      foundRoute ? foundRoute.path !== "/" && routeParams["**"] : (
+        // Or if we didn't find a route and we have left over path
+        trimPathRight(next.pathname)
+      )
+    ) {
+      if (this.options.notFoundRoute) {
+        matchedRoutes = [...matchedRoutes, this.options.notFoundRoute];
+      } else {
+        isGlobalNotFound = true;
+      }
+    }
+    const globalNotFoundRouteId = (() => {
+      if (!isGlobalNotFound) {
+        return void 0;
+      }
+      if (this.options.notFoundMode !== "root") {
+        for (let i = matchedRoutes.length - 1; i >= 0; i--) {
+          const route = matchedRoutes[i];
+          if (route.children) {
+            return route.id;
+          }
+        }
+      }
+      return rootRouteId;
+    })();
+    const matches = [];
+    const getParentContext = (parentMatch) => {
+      const parentMatchId = parentMatch?.id;
+      const parentContext = !parentMatchId ? this.options.context ?? void 0 : parentMatch.context ?? this.options.context ?? void 0;
+      return parentContext;
+    };
+    matchedRoutes.forEach((route, index) => {
+      const parentMatch = matches[index - 1];
+      const [preMatchSearch, strictMatchSearch, searchError] = (() => {
+        const parentSearch = parentMatch?.search ?? next.search;
+        const parentStrictSearch = parentMatch?._strictSearch ?? void 0;
+        try {
+          const strictSearch = validateSearch(route.options.validateSearch, { ...parentSearch }) ?? void 0;
+          return [
+            {
+              ...parentSearch,
+              ...strictSearch
+            },
+            { ...parentStrictSearch, ...strictSearch },
+            void 0
+          ];
+        } catch (err) {
+          let searchParamError = err;
+          if (!(err instanceof SearchParamError)) {
+            searchParamError = new SearchParamError(err.message, {
+              cause: err
+            });
+          }
+          if (opts?.throwOnError) {
+            throw searchParamError;
+          }
+          return [parentSearch, {}, searchParamError];
+        }
+      })();
+      const loaderDeps = route.options.loaderDeps?.({
+        search: preMatchSearch
+      }) ?? "";
+      const loaderDepsHash = loaderDeps ? JSON.stringify(loaderDeps) : "";
+      const { interpolatedPath, usedParams } = interpolatePath({
+        path: route.fullPath,
+        params: routeParams,
+        decodeCharMap: this.pathParamsDecodeCharMap
+      });
+      const matchId = (
+        // route.id for disambiguation
+        route.id + // interpolatedPath for param changes
+        interpolatedPath + // explicit deps
+        loaderDepsHash
+      );
+      const existingMatch = this.getMatch(matchId);
+      const previousMatch = this.state.matches.find(
+        (d) => d.routeId === route.id
+      );
+      const strictParams = existingMatch?._strictParams ?? usedParams;
+      let paramsError = void 0;
+      if (!existingMatch) {
+        const strictParseParams = route.options.params?.parse ?? route.options.parseParams;
+        if (strictParseParams) {
+          try {
+            Object.assign(
+              strictParams,
+              strictParseParams(strictParams)
+            );
+          } catch (err) {
+            if (isNotFound(err) || isRedirect(err)) {
+              paramsError = err;
+            } else {
+              paramsError = new PathParamError(err.message, {
+                cause: err
+              });
+            }
+            if (opts?.throwOnError) {
+              throw paramsError;
+            }
+          }
+        }
+      }
+      Object.assign(routeParams, strictParams);
+      const cause = previousMatch ? "stay" : "enter";
+      let match;
+      if (existingMatch) {
+        match = {
+          ...existingMatch,
+          cause,
+          params: previousMatch ? replaceEqualDeep(previousMatch.params, routeParams) : routeParams,
+          _strictParams: strictParams,
+          search: previousMatch ? replaceEqualDeep(previousMatch.search, preMatchSearch) : replaceEqualDeep(existingMatch.search, preMatchSearch),
+          _strictSearch: strictMatchSearch
+        };
+      } else {
+        const status = route.options.loader || route.options.beforeLoad || route.lazyFn || routeNeedsPreload(route) ? "pending" : "success";
+        match = {
+          id: matchId,
+          ssr: this.isServer ? void 0 : route.options.ssr,
+          index,
+          routeId: route.id,
+          params: previousMatch ? replaceEqualDeep(previousMatch.params, routeParams) : routeParams,
+          _strictParams: strictParams,
+          pathname: interpolatedPath,
+          updatedAt: Date.now(),
+          search: previousMatch ? replaceEqualDeep(previousMatch.search, preMatchSearch) : preMatchSearch,
+          _strictSearch: strictMatchSearch,
+          searchError: void 0,
+          status,
+          isFetching: false,
+          error: void 0,
+          paramsError,
+          __routeContext: void 0,
+          _nonReactive: {
+            loadPromise: createControlledPromise()
+          },
+          __beforeLoadContext: void 0,
+          context: {},
+          abortController: new AbortController(),
+          fetchCount: 0,
+          cause,
+          loaderDeps: previousMatch ? replaceEqualDeep(previousMatch.loaderDeps, loaderDeps) : loaderDeps,
+          invalid: false,
+          preload: false,
+          links: void 0,
+          scripts: void 0,
+          headScripts: void 0,
+          meta: void 0,
+          staticData: route.options.staticData || {},
+          fullPath: route.fullPath
+        };
+      }
+      if (!opts?.preload) {
+        match.globalNotFound = globalNotFoundRouteId === route.id;
+      }
+      match.searchError = searchError;
+      const parentContext = getParentContext(parentMatch);
+      match.context = {
+        ...parentContext,
+        ...match.__routeContext,
+        ...match.__beforeLoadContext
+      };
+      matches.push(match);
+    });
+    matches.forEach((match, index) => {
+      const route = this.looseRoutesById[match.routeId];
+      const existingMatch = this.getMatch(match.id);
+      if (!existingMatch && opts?._buildLocation !== true) {
+        const parentMatch = matches[index - 1];
+        const parentContext = getParentContext(parentMatch);
+        if (route.options.context) {
+          const contextFnContext = {
+            deps: match.loaderDeps,
+            params: match.params,
+            context: parentContext ?? {},
+            location: next,
+            navigate: (opts2) => this.navigate({ ...opts2, _fromLocation: next }),
+            buildLocation: this.buildLocation,
+            cause: match.cause,
+            abortController: match.abortController,
+            preload: !!match.preload,
+            matches
+          };
+          match.__routeContext = route.options.context(contextFnContext) ?? void 0;
+        }
+        match.context = {
+          ...parentContext,
+          ...match.__routeContext,
+          ...match.__beforeLoadContext
+        };
+      }
+    });
+    return matches;
+  }
+}
+class SearchParamError extends Error {
+}
+class PathParamError extends Error {
+}
+const normalize = (str) => str.endsWith("/") && str.length > 1 ? str.slice(0, -1) : str;
+function comparePaths(a, b2) {
+  return normalize(a) === normalize(b2);
+}
+function getInitialRouterState(location) {
+  return {
+    loadedAt: 0,
+    isLoading: false,
+    isTransitioning: false,
+    status: "idle",
+    resolvedLocation: void 0,
+    location,
+    matches: [],
+    pendingMatches: [],
+    cachedMatches: [],
+    statusCode: 200
+  };
+}
+function validateSearch(validateSearch2, input) {
+  if (validateSearch2 == null) return {};
+  if ("~standard" in validateSearch2) {
+    const result = validateSearch2["~standard"].validate(input);
+    if (result instanceof Promise)
+      throw new SearchParamError("Async validation not supported");
+    if (result.issues)
+      throw new SearchParamError(JSON.stringify(result.issues, void 0, 2), {
+        cause: result
+      });
+    return result.value;
+  }
+  if ("parse" in validateSearch2) {
+    return validateSearch2.parse(input);
+  }
+  if (typeof validateSearch2 === "function") {
+    return validateSearch2(input);
+  }
+  return {};
+}
+function getMatchedRoutes({
+  pathname,
+  routesById,
+  processedTree
+}) {
+  const routeParams = {};
+  const trimmedPath = trimPathRight(pathname);
+  let foundRoute = void 0;
+  const match = findRouteMatch(trimmedPath, processedTree, true);
+  if (match) {
+    foundRoute = match.route;
+    Object.assign(routeParams, match.params);
+  }
+  const matchedRoutes = match?.branch || [routesById[rootRouteId]];
+  return { matchedRoutes, routeParams, foundRoute };
+}
+function applySearchMiddleware({
+  search,
+  dest,
+  destRoutes,
+  _includeValidateSearch
+}) {
+  const allMiddlewares = destRoutes.reduce(
+    (acc, route) => {
+      const middlewares = [];
+      if ("search" in route.options) {
+        if (route.options.search?.middlewares) {
+          middlewares.push(...route.options.search.middlewares);
+        }
+      } else if (route.options.preSearchFilters || route.options.postSearchFilters) {
+        const legacyMiddleware = ({
+          search: search2,
+          next
+        }) => {
+          let nextSearch = search2;
+          if ("preSearchFilters" in route.options && route.options.preSearchFilters) {
+            nextSearch = route.options.preSearchFilters.reduce(
+              (prev, next2) => next2(prev),
+              search2
+            );
+          }
+          const result = next(nextSearch);
+          if ("postSearchFilters" in route.options && route.options.postSearchFilters) {
+            return route.options.postSearchFilters.reduce(
+              (prev, next2) => next2(prev),
+              result
+            );
+          }
+          return result;
+        };
+        middlewares.push(legacyMiddleware);
+      }
+      if (_includeValidateSearch && route.options.validateSearch) {
+        const validate = ({ search: search2, next }) => {
+          const result = next(search2);
+          try {
+            const validatedSearch = {
+              ...result,
+              ...validateSearch(route.options.validateSearch, result) ?? void 0
+            };
+            return validatedSearch;
+          } catch {
+            return result;
+          }
+        };
+        middlewares.push(validate);
+      }
+      return acc.concat(middlewares);
+    },
+    []
+  ) ?? [];
+  const final = ({ search: search2 }) => {
+    if (!dest.search) {
+      return {};
+    }
+    if (dest.search === true) {
+      return search2;
+    }
+    return functionalUpdate(dest.search, search2);
+  };
+  allMiddlewares.push(final);
+  const applyNext = (index, currentSearch) => {
+    if (index >= allMiddlewares.length) {
+      return currentSearch;
+    }
+    const middleware = allMiddlewares[index];
+    const next = (newSearch) => {
+      return applyNext(index + 1, newSearch);
+    };
+    return middleware({ search: currentSearch, next });
+  };
+  return applyNext(0, search);
+}
+var L = ((i) => (i[i.AggregateError = 1] = "AggregateError", i[i.ArrowFunction = 2] = "ArrowFunction", i[i.ErrorPrototypeStack = 4] = "ErrorPrototypeStack", i[i.ObjectAssign = 8] = "ObjectAssign", i[i.BigIntTypedArray = 16] = "BigIntTypedArray", i[i.RegExp = 32] = "RegExp", i))(L || {});
+var N = Symbol.asyncIterator, fr = Symbol.hasInstance, I = Symbol.isConcatSpreadable, b = Symbol.iterator, Sr = Symbol.match, mr = Symbol.matchAll, pr = Symbol.replace, dr = Symbol.search, gr = Symbol.species, yr = Symbol.split, Nr = Symbol.toPrimitive, P$1 = Symbol.toStringTag, br = Symbol.unscopables;
+var qr = { 0: "Symbol.asyncIterator", 1: "Symbol.hasInstance", 2: "Symbol.isConcatSpreadable", 3: "Symbol.iterator", 4: "Symbol.match", 5: "Symbol.matchAll", 6: "Symbol.replace", 7: "Symbol.search", 8: "Symbol.species", 9: "Symbol.split", 10: "Symbol.toPrimitive", 11: "Symbol.toStringTag", 12: "Symbol.unscopables" }, Ce = { [N]: 0, [fr]: 1, [I]: 2, [b]: 3, [Sr]: 4, [mr]: 5, [pr]: 6, [dr]: 7, [gr]: 8, [yr]: 9, [Nr]: 10, [P$1]: 11, [br]: 12 }, Xr = { 0: N, 1: fr, 2: I, 3: b, 4: Sr, 5: mr, 6: pr, 7: dr, 8: gr, 9: yr, 10: Nr, 11: P$1, 12: br }, Qr = { 2: "!0", 3: "!1", 1: "void 0", 0: "null", 4: "-0", 5: "1/0", 6: "-1/0", 7: "0/0" }, o = void 0, et = { 2: true, 3: false, 1: o, 0: null, 4: -0, 5: Number.POSITIVE_INFINITY, 6: Number.NEGATIVE_INFINITY, 7: Number.NaN };
+var ve = { 0: "Error", 1: "EvalError", 2: "RangeError", 3: "ReferenceError", 4: "SyntaxError", 5: "TypeError", 6: "URIError" }, rt = { 0: Error, 1: EvalError, 2: RangeError, 3: ReferenceError, 4: SyntaxError, 5: TypeError, 6: URIError };
+function c(e, r, t, n, a, s, i, u2, l, g, S, d) {
+  return { t: e, i: r, s: t, c: n, m: a, p: s, e: i, a: u2, f: l, b: g, o: S, l: d };
+}
+function D(e) {
+  return c(2, o, e, o, o, o, o, o, o, o, o, o);
+}
+var Z = D(2), $ = D(3), Ae = D(1), Re = D(0), tt = D(4), nt = D(5), ot = D(6), at = D(7);
+function sn(e) {
+  switch (e) {
+    case '"':
+      return '\\"';
+    case "\\":
+      return "\\\\";
+    case `
+`:
+      return "\\n";
+    case "\r":
+      return "\\r";
+    case "\b":
+      return "\\b";
+    case "	":
+      return "\\t";
+    case "\f":
+      return "\\f";
+    case "<":
+      return "\\x3C";
+    case "\u2028":
+      return "\\u2028";
+    case "\u2029":
+      return "\\u2029";
+    default:
+      return o;
+  }
+}
+function y(e) {
+  let r = "", t = 0, n;
+  for (let a = 0, s = e.length; a < s; a++) n = sn(e[a]), n && (r += e.slice(t, a) + n, t = a + 1);
+  return t === 0 ? r = e : r += e.slice(t), r;
+}
+function un(e) {
+  switch (e) {
+    case "\\\\":
+      return "\\";
+    case '\\"':
+      return '"';
+    case "\\n":
+      return `
+`;
+    case "\\r":
+      return "\r";
+    case "\\b":
+      return "\b";
+    case "\\t":
+      return "	";
+    case "\\f":
+      return "\f";
+    case "\\x3C":
+      return "<";
+    case "\\u2028":
+      return "\u2028";
+    case "\\u2029":
+      return "\u2029";
+    default:
+      return e;
+  }
+}
+function F(e) {
+  return e.replace(/(\\\\|\\"|\\n|\\r|\\b|\\t|\\f|\\u2028|\\u2029|\\x3C)/g, un);
+}
+var U = "__SEROVAL_REFS__", ce = "$R", Ee = `self.${ce}`;
+function ln(e) {
+  return e == null ? `${Ee}=${Ee}||[]` : `(${Ee}=${Ee}||{})["${y(e)}"]=[]`;
+}
+var Cr = /* @__PURE__ */ new Map(), j = /* @__PURE__ */ new Map();
+function vr(e) {
+  return Cr.has(e);
+}
+function fn(e) {
+  return j.has(e);
+}
+function st(e) {
+  if (vr(e)) return Cr.get(e);
+  throw new Ie(e);
+}
+function it(e) {
+  if (fn(e)) return j.get(e);
+  throw new Pe(e);
+}
+typeof globalThis != "undefined" ? Object.defineProperty(globalThis, U, { value: j, configurable: true, writable: false, enumerable: false }) : typeof window != "undefined" ? Object.defineProperty(window, U, { value: j, configurable: true, writable: false, enumerable: false }) : typeof self != "undefined" ? Object.defineProperty(self, U, { value: j, configurable: true, writable: false, enumerable: false }) : typeof global != "undefined" && Object.defineProperty(global, U, { value: j, configurable: true, writable: false, enumerable: false });
+function xe(e) {
+  return e instanceof EvalError ? 1 : e instanceof RangeError ? 2 : e instanceof ReferenceError ? 3 : e instanceof SyntaxError ? 4 : e instanceof TypeError ? 5 : e instanceof URIError ? 6 : 0;
+}
+function Sn(e) {
+  let r = ve[xe(e)];
+  return e.name !== r ? { name: e.name } : e.constructor.name !== r ? { name: e.constructor.name } : {};
+}
+function q(e, r) {
+  let t = Sn(e), n = Object.getOwnPropertyNames(e);
+  for (let a = 0, s = n.length, i; a < s; a++) i = n[a], i !== "name" && i !== "message" && (i === "stack" ? r & 4 && (t = t || {}, t[i] = e[i]) : (t = t || {}, t[i] = e[i]));
+  return t;
+}
+function Te(e) {
+  return Object.isFrozen(e) ? 3 : Object.isSealed(e) ? 2 : Object.isExtensible(e) ? 0 : 1;
+}
+function Oe(e) {
+  switch (e) {
+    case Number.POSITIVE_INFINITY:
+      return nt;
+    case Number.NEGATIVE_INFINITY:
+      return ot;
+  }
+  return e !== e ? at : Object.is(e, -0) ? tt : c(0, o, e, o, o, o, o, o, o, o, o, o);
+}
+function X(e) {
+  return c(1, o, y(e), o, o, o, o, o, o, o, o, o);
+}
+function we(e) {
+  return c(3, o, "" + e, o, o, o, o, o, o, o, o, o);
+}
+function lt(e) {
+  return c(4, e, o, o, o, o, o, o, o, o, o, o);
+}
+function he(e, r) {
+  let t = r.valueOf();
+  return c(5, e, t !== t ? "" : r.toISOString(), o, o, o, o, o, o, o, o, o);
+}
+function ze(e, r) {
+  return c(6, e, o, y(r.source), r.flags, o, o, o, o, o, o, o);
+}
+function ct(e, r) {
+  return c(17, e, Ce[r], o, o, o, o, o, o, o, o, o);
+}
+function ft(e, r) {
+  return c(18, e, y(st(r)), o, o, o, o, o, o, o, o, o);
+}
+function fe(e, r, t) {
+  return c(25, e, t, y(r), o, o, o, o, o, o, o, o);
+}
+function _e(e, r, t) {
+  return c(9, e, o, o, o, o, o, t, o, o, Te(r), o);
+}
+function ke(e, r) {
+  return c(21, e, o, o, o, o, o, o, r, o, o, o);
+}
+function De(e, r, t) {
+  return c(15, e, o, r.constructor.name, o, o, o, o, t, r.byteOffset, o, r.length);
+}
+function Fe(e, r, t) {
+  return c(16, e, o, r.constructor.name, o, o, o, o, t, r.byteOffset, o, r.byteLength);
+}
+function Be(e, r, t) {
+  return c(20, e, o, o, o, o, o, o, t, r.byteOffset, o, r.byteLength);
+}
+function Me(e, r, t) {
+  return c(13, e, xe(r), o, y(r.message), t, o, o, o, o, o, o);
+}
+function Ve(e, r, t) {
+  return c(14, e, xe(r), o, y(r.message), t, o, o, o, o, o, o);
+}
+function Le(e, r) {
+  return c(7, e, o, o, o, o, o, r, o, o, o, o);
+}
+function Ue(e, r) {
+  return c(28, o, o, o, o, o, o, [e, r], o, o, o, o);
+}
+function je(e, r) {
+  return c(30, o, o, o, o, o, o, [e, r], o, o, o, o);
+}
+function Ye(e, r, t) {
+  return c(31, e, o, o, o, o, o, t, r, o, o, o);
+}
+function We(e, r) {
+  return c(32, e, o, o, o, o, o, o, r, o, o, o);
+}
+function Ge(e, r) {
+  return c(33, e, o, o, o, o, o, o, r, o, o, o);
+}
+function Ke(e, r) {
+  return c(34, e, o, o, o, o, o, o, r, o, o, o);
+}
+var mn = { parsing: 1, serialization: 2, deserialization: 3 };
+function pn(e) {
+  return `Seroval Error (step: ${mn[e]})`;
+}
+var dn = (e, r) => pn(e), Se = class extends Error {
+  constructor(t, n) {
+    super(dn(t));
+    this.cause = n;
+  }
+}, z = class extends Se {
+  constructor(r) {
+    super("parsing", r);
+  }
+}, He = class extends Se {
+  constructor(r) {
+    super("deserialization", r);
+  }
+};
+function _(e) {
+  return `Seroval Error (specific: ${e})`;
+}
+var x = class extends Error {
+  constructor(t) {
+    super(_(1));
+    this.value = t;
+  }
+}, O = class extends Error {
+  constructor(r) {
+    super(_(2));
+  }
+}, Q = class extends Error {
+  constructor(r) {
+    super(_(3));
+  }
+}, B = class extends Error {
+  constructor(r) {
+    super(_(4));
+  }
+}, Ie = class extends Error {
+  constructor(t) {
+    super(_(5));
+    this.value = t;
+  }
+}, Pe = class extends Error {
+  constructor(r) {
+    super(_(6));
+  }
+}, Je = class extends Error {
+  constructor(r) {
+    super(_(7));
+  }
+}, w$1 = class w extends Error {
+  constructor(r) {
+    super(_(8));
+  }
+}, ee$1 = class ee extends Error {
+  constructor(r) {
+    super(_(9));
+  }
+};
+var Y = class {
+  constructor(r, t) {
+    this.value = r;
+    this.replacement = t;
+  }
+};
+var re$1 = () => {
+  let e = { p: 0, s: 0, f: 0 };
+  return e.p = new Promise((r, t) => {
+    e.s = r, e.f = t;
+  }), e;
+}, gn = (e, r) => {
+  e.s(r), e.p.s = 1, e.p.v = r;
+}, yn = (e, r) => {
+  e.f(r), e.p.s = 2, e.p.v = r;
+}, mt = re$1.toString(), pt = gn.toString(), dt = yn.toString(), Rr = () => {
+  let e = [], r = [], t = true, n = false, a = 0, s = (l, g, S) => {
+    for (S = 0; S < a; S++) r[S] && r[S][g](l);
+  }, i = (l, g, S, d) => {
+    for (g = 0, S = e.length; g < S; g++) d = e[g], !t && g === S - 1 ? l[n ? "return" : "throw"](d) : l.next(d);
+  }, u2 = (l, g) => (t && (g = a++, r[g] = l), i(l), () => {
+    t && (r[g] = r[a], r[a--] = void 0);
+  });
+  return { __SEROVAL_STREAM__: true, on: (l) => u2(l), next: (l) => {
+    t && (e.push(l), s(l, "next"));
+  }, throw: (l) => {
+    t && (e.push(l), s(l, "throw"), t = false, n = false, r.length = 0);
+  }, return: (l) => {
+    t && (e.push(l), s(l, "return"), t = false, n = true, r.length = 0);
+  } };
+}, gt = Rr.toString(), Er = (e) => (r) => () => {
+  let t = 0, n = { [e]: () => n, next: () => {
+    if (t > r.d) return { done: true, value: void 0 };
+    let a = t++, s = r.v[a];
+    if (a === r.t) throw s;
+    return { done: a === r.d, value: s };
+  } };
+  return n;
+}, yt = Er.toString(), Ir = (e, r) => (t) => () => {
+  let n = 0, a = -1, s = false, i = [], u2 = [], l = (S = 0, d = u2.length) => {
+    for (; S < d; S++) u2[S].s({ done: true, value: void 0 });
+  };
+  t.on({ next: (S) => {
+    let d = u2.shift();
+    d && d.s({ done: false, value: S }), i.push(S);
+  }, throw: (S) => {
+    let d = u2.shift();
+    d && d.f(S), l(), a = i.length, s = true, i.push(S);
+  }, return: (S) => {
+    let d = u2.shift();
+    d && d.s({ done: true, value: S }), l(), a = i.length, i.push(S);
+  } });
+  let g = { [e]: () => g, next: () => {
+    if (a === -1) {
+      let H = n++;
+      if (H >= i.length) {
+        let $r = r();
+        return u2.push($r), $r.p;
+      }
+      return { done: false, value: i[H] };
+    }
+    if (n > a) return { done: true, value: void 0 };
+    let S = n++, d = i[S];
+    if (S !== a) return { done: false, value: d };
+    if (s) throw d;
+    return { done: true, value: d };
+  } };
+  return g;
+}, Nt = Ir.toString(), Pr = (e) => {
+  let r = atob(e), t = r.length, n = new Uint8Array(t);
+  for (let a = 0; a < t; a++) n[a] = r.charCodeAt(a);
+  return n.buffer;
+}, bt = Pr.toString();
+var Ct = {}, vt = {};
+var At = { 0: {}, 1: {}, 2: {}, 3: {}, 4: {}, 5: {} }, Rt = { 0: "[]", 1: mt, 2: pt, 3: dt, 4: gt, 5: bt };
+function M(e) {
+  return "__SEROVAL_STREAM__" in e;
+}
+function te() {
+  return Rr();
+}
+function Ze(e) {
+  let r = te(), t = e[N]();
+  async function n() {
+    try {
+      let a = await t.next();
+      a.done ? r.return(a.value) : (r.next(a.value), await n());
+    } catch (a) {
+      r.throw(a);
+    }
+  }
+  return n().catch(() => {
+  }), r;
+}
+var Nn = Ir(N, re$1);
+function Et(e) {
+  return Nn(e);
+}
+function $e(e) {
+  let r = [], t = -1, n = -1, a = e[b]();
+  for (; ; ) try {
+    let s = a.next();
+    if (r.push(s.value), s.done) {
+      n = r.length - 1;
+      break;
+    }
+  } catch (s) {
+    t = r.length, r.push(s);
+  }
+  return { v: r, t, d: n };
+}
+var bn = Er(b);
+function It(e) {
+  return bn(e);
+}
+async function xr(e) {
+  try {
+    return [1, await e];
+  } catch (r) {
+    return [0, r];
+  }
+}
+function pe(e, r) {
+  return { plugins: r.plugins, mode: e, marked: /* @__PURE__ */ new Set(), features: 63 ^ (r.disabledFeatures || 0), refs: r.refs || /* @__PURE__ */ new Map(), depthLimit: r.depthLimit || 1e3 };
+}
+function de(e, r) {
+  e.marked.add(r);
+}
+function Tr(e, r) {
+  let t = e.refs.size;
+  return e.refs.set(r, t), t;
+}
+function qe(e, r) {
+  let t = e.refs.get(r);
+  return t != null ? (de(e, t), { type: 1, value: lt(t) }) : { type: 0, value: Tr(e, r) };
+}
+function W(e, r) {
+  let t = qe(e, r);
+  return t.type === 1 ? t : vr(r) ? { type: 2, value: ft(t.value, r) } : t;
+}
+function E(e, r) {
+  let t = W(e, r);
+  if (t.type !== 0) return t.value;
+  if (r in Ce) return ct(t.value, r);
+  throw new x(r);
+}
+function k(e, r) {
+  let t = qe(e, At[r]);
+  return t.type === 1 ? t.value : c(26, t.value, r, o, o, o, o, o, o, o, o, o);
+}
+function Xe(e) {
+  let r = qe(e, Ct);
+  return r.type === 1 ? r.value : c(27, r.value, o, o, o, o, o, o, E(e, b), o, o, o);
+}
+function Qe(e) {
+  let r = qe(e, vt);
+  return r.type === 1 ? r.value : c(29, r.value, o, o, o, o, o, [k(e, 1), E(e, N)], o, o, o, o);
+}
+function er(e, r, t, n) {
+  return c(t ? 11 : 10, e, o, o, o, n, o, o, o, o, Te(r), o);
+}
+function rr(e, r, t, n) {
+  return c(8, r, o, o, o, o, { k: t, v: n }, o, k(e, 0), o, o, o);
+}
+function xt(e, r, t) {
+  return c(22, r, t, o, o, o, o, o, k(e, 1), o, o, o);
+}
+function tr(e, r, t) {
+  let n = new Uint8Array(t), a = "";
+  for (let s = 0, i = n.length; s < i; s++) a += String.fromCharCode(n[s]);
+  return c(19, r, y(btoa(a)), o, o, o, o, o, k(e, 5), o, o, o);
+}
+function ne(e, r) {
+  return { base: pe(e, r), child: void 0 };
+}
+var wr = class {
+  constructor(r, t) {
+    this._p = r;
+    this.depth = t;
+  }
+  parse(r) {
+    return C(this._p, this.depth, r);
+  }
+};
+async function vn(e, r, t) {
+  let n = [];
+  for (let a = 0, s = t.length; a < s; a++) a in t ? n[a] = await C(e, r, t[a]) : n[a] = 0;
+  return n;
+}
+async function An(e, r, t, n) {
+  return _e(t, n, await vn(e, r, n));
+}
+async function hr(e, r, t) {
+  let n = Object.entries(t), a = [], s = [];
+  for (let i = 0, u2 = n.length; i < u2; i++) a.push(y(n[i][0])), s.push(await C(e, r, n[i][1]));
+  return b in t && (a.push(E(e.base, b)), s.push(Ue(Xe(e.base), await C(e, r, $e(t))))), N in t && (a.push(E(e.base, N)), s.push(je(Qe(e.base), await C(e, r, Ze(t))))), P$1 in t && (a.push(E(e.base, P$1)), s.push(X(t[P$1]))), I in t && (a.push(E(e.base, I)), s.push(t[I] ? Z : $)), { k: a, v: s };
+}
+async function Or(e, r, t, n, a) {
+  return er(t, n, a, await hr(e, r, n));
+}
+async function Rn(e, r, t, n) {
+  return ke(t, await C(e, r, n.valueOf()));
+}
+async function En(e, r, t, n) {
+  return De(t, n, await C(e, r, n.buffer));
+}
+async function In(e, r, t, n) {
+  return Fe(t, n, await C(e, r, n.buffer));
+}
+async function Pn(e, r, t, n) {
+  return Be(t, n, await C(e, r, n.buffer));
+}
+async function Tt(e, r, t, n) {
+  let a = q(n, e.base.features);
+  return Me(t, n, a ? await hr(e, r, a) : o);
+}
+async function xn(e, r, t, n) {
+  let a = q(n, e.base.features);
+  return Ve(t, n, a ? await hr(e, r, a) : o);
+}
+async function Tn(e, r, t, n) {
+  let a = [], s = [];
+  for (let [i, u2] of n.entries()) a.push(await C(e, r, i)), s.push(await C(e, r, u2));
+  return rr(e.base, t, a, s);
+}
+async function On(e, r, t, n) {
+  let a = [];
+  for (let s of n.keys()) a.push(await C(e, r, s));
+  return Le(t, a);
+}
+async function Ot(e, r, t, n) {
+  let a = e.base.plugins;
+  if (a) for (let s = 0, i = a.length; s < i; s++) {
+    let u2 = a[s];
+    if (u2.parse.async && u2.test(n)) return fe(t, u2.tag, await u2.parse.async(n, new wr(e, r), { id: t }));
+  }
+  return o;
+}
+async function wn(e, r, t, n) {
+  let [a, s] = await xr(n);
+  return c(12, t, a, o, o, o, o, o, await C(e, r, s), o, o, o);
+}
+function hn(e, r, t, n, a) {
+  let s = [], i = t.on({ next: (u2) => {
+    de(this.base, r), C(this, e, u2).then((l) => {
+      s.push(We(r, l));
+    }, (l) => {
+      a(l), i();
+    });
+  }, throw: (u2) => {
+    de(this.base, r), C(this, e, u2).then((l) => {
+      s.push(Ge(r, l)), n(s), i();
+    }, (l) => {
+      a(l), i();
+    });
+  }, return: (u2) => {
+    de(this.base, r), C(this, e, u2).then((l) => {
+      s.push(Ke(r, l)), n(s), i();
+    }, (l) => {
+      a(l), i();
+    });
+  } });
+}
+async function zn(e, r, t, n) {
+  return Ye(t, k(e.base, 4), await new Promise(hn.bind(e, r, t, n)));
+}
+async function _n(e, r, t, n) {
+  if (Array.isArray(n)) return An(e, r, t, n);
+  if (M(n)) return zn(e, r, t, n);
+  let a = n.constructor;
+  if (a === Y) return C(e, r, n.replacement);
+  let s = await Ot(e, r, t, n);
+  if (s) return s;
+  switch (a) {
+    case Object:
+      return Or(e, r, t, n, false);
+    case o:
+      return Or(e, r, t, n, true);
+    case Date:
+      return he(t, n);
+    case Error:
+    case EvalError:
+    case RangeError:
+    case ReferenceError:
+    case SyntaxError:
+    case TypeError:
+    case URIError:
+      return Tt(e, r, t, n);
+    case Number:
+    case Boolean:
+    case String:
+    case BigInt:
+      return Rn(e, r, t, n);
+    case ArrayBuffer:
+      return tr(e.base, t, n);
+    case Int8Array:
+    case Int16Array:
+    case Int32Array:
+    case Uint8Array:
+    case Uint16Array:
+    case Uint32Array:
+    case Uint8ClampedArray:
+    case Float32Array:
+    case Float64Array:
+      return En(e, r, t, n);
+    case DataView:
+      return Pn(e, r, t, n);
+    case Map:
+      return Tn(e, r, t, n);
+    case Set:
+      return On(e, r, t, n);
+  }
+  if (a === Promise || n instanceof Promise) return wn(e, r, t, n);
+  let i = e.base.features;
+  if (i & 32 && a === RegExp) return ze(t, n);
+  if (i & 16) switch (a) {
+    case BigInt64Array:
+    case BigUint64Array:
+      return In(e, r, t, n);
+  }
+  if (i & 1 && typeof AggregateError != "undefined" && (a === AggregateError || n instanceof AggregateError)) return xn(e, r, t, n);
+  if (n instanceof Error) return Tt(e, r, t, n);
+  if (b in n || N in n) return Or(e, r, t, n, !!a);
+  throw new x(n);
+}
+async function kn(e, r, t) {
+  let n = W(e.base, t);
+  if (n.type !== 0) return n.value;
+  let a = await Ot(e, r, n.value, t);
+  if (a) return a;
+  throw new x(t);
+}
+async function C(e, r, t) {
+  switch (typeof t) {
+    case "boolean":
+      return t ? Z : $;
+    case "undefined":
+      return Ae;
+    case "string":
+      return X(t);
+    case "number":
+      return Oe(t);
+    case "bigint":
+      return we(t);
+    case "object": {
+      if (t) {
+        let n = W(e.base, t);
+        return n.type === 0 ? await _n(e, r + 1, n.value, t) : n.value;
+      }
+      return Re;
+    }
+    case "symbol":
+      return E(e.base, t);
+    case "function":
+      return kn(e, r, t);
+    default:
+      throw new x(t);
+  }
+}
+async function oe(e, r) {
+  try {
+    return await C(e, 0, r);
+  } catch (t) {
+    throw t instanceof z ? t : new z(t);
+  }
+}
+var ae = ((t) => (t[t.Vanilla = 1] = "Vanilla", t[t.Cross = 2] = "Cross", t))(ae || {});
+function Js(e) {
+  return e;
+}
+function wt(e, r) {
+  for (let t = 0, n = r.length; t < n; t++) {
+    let a = r[t];
+    e.has(a) || (e.add(a), a.extends && wt(e, a.extends));
+  }
+}
+function A(e) {
+  if (e) {
+    let r = /* @__PURE__ */ new Set();
+    return wt(r, e), [...r];
+  }
+}
+function ht(e) {
+  switch (e) {
+    case "Int8Array":
+      return Int8Array;
+    case "Int16Array":
+      return Int16Array;
+    case "Int32Array":
+      return Int32Array;
+    case "Uint8Array":
+      return Uint8Array;
+    case "Uint16Array":
+      return Uint16Array;
+    case "Uint32Array":
+      return Uint32Array;
+    case "Uint8ClampedArray":
+      return Uint8ClampedArray;
+    case "Float32Array":
+      return Float32Array;
+    case "Float64Array":
+      return Float64Array;
+    case "BigInt64Array":
+      return BigInt64Array;
+    case "BigUint64Array":
+      return BigUint64Array;
+    default:
+      throw new Je(e);
+  }
+}
+var Dn = 1e6, Fn = 1e4, Bn = 2e4;
+function _t(e, r) {
+  switch (r) {
+    case 3:
+      return Object.freeze(e);
+    case 1:
+      return Object.preventExtensions(e);
+    case 2:
+      return Object.seal(e);
+    default:
+      return e;
+  }
+}
+var Mn = 1e3;
+function kt(e, r) {
+  var t;
+  return { mode: e, plugins: r.plugins, refs: r.refs || /* @__PURE__ */ new Map(), features: (t = r.features) != null ? t : 63 ^ (r.disabledFeatures || 0), depthLimit: r.depthLimit || Mn };
+}
+function Dt(e) {
+  return { mode: 1, base: kt(1, e), child: o, state: { marked: new Set(e.markedRefs) } };
+}
+var zr = class {
+  constructor(r, t) {
+    this._p = r;
+    this.depth = t;
+  }
+  deserialize(r) {
+    return p$1(this._p, this.depth, r);
+  }
+};
+function Bt(e, r) {
+  if (r < 0 || !Number.isFinite(r) || !Number.isInteger(r)) throw new w$1({ t: 4, i: r });
+  if (e.refs.has(r)) throw new Error("Conflicted ref id: " + r);
+}
+function Vn(e, r, t) {
+  return Bt(e.base, r), e.state.marked.has(r) && e.base.refs.set(r, t), t;
+}
+function Ln(e, r, t) {
+  return Bt(e.base, r), e.base.refs.set(r, t), t;
+}
+function v(e, r, t) {
+  return e.mode === 1 ? Vn(e, r, t) : Ln(e, r, t);
+}
+function _r(e, r, t) {
+  if (Object.hasOwn(r, t)) return r[t];
+  throw new w$1(e);
+}
+function Un(e, r) {
+  return v(e, r.i, it(F(r.s)));
+}
+function jn(e, r, t) {
+  let n = t.a, a = n.length, s = v(e, t.i, new Array(a));
+  for (let i = 0, u2; i < a; i++) u2 = n[i], u2 && (s[i] = p$1(e, r, u2));
+  return _t(s, t.o), s;
+}
+function Yn(e) {
+  switch (e) {
+    case "constructor":
+    case "__proto__":
+    case "prototype":
+    case "__defineGetter__":
+    case "__defineSetter__":
+    case "__lookupGetter__":
+    case "__lookupSetter__":
+      return false;
+    default:
+      return true;
+  }
+}
+function Wn(e) {
+  switch (e) {
+    case N:
+    case I:
+    case P$1:
+    case b:
+      return true;
+    default:
+      return false;
+  }
+}
+function zt(e, r, t) {
+  Yn(r) ? e[r] = t : Object.defineProperty(e, r, { value: t, configurable: true, enumerable: true, writable: true });
+}
+function Gn(e, r, t, n, a) {
+  if (typeof n == "string") zt(t, n, p$1(e, r, a));
+  else {
+    let s = p$1(e, r, n);
+    switch (typeof s) {
+      case "string":
+        zt(t, s, p$1(e, r, a));
+        break;
+      case "symbol":
+        Wn(s) && (t[s] = p$1(e, r, a));
+        break;
+      default:
+        throw new w$1(n);
+    }
+  }
+}
+function Mt(e, r, t, n) {
+  let a = t.k;
+  if (a.length > 0) for (let i = 0, u2 = t.v, l = a.length; i < l; i++) Gn(e, r, n, a[i], u2[i]);
+  return n;
+}
+function Kn(e, r, t) {
+  let n = v(e, t.i, t.t === 10 ? {} : /* @__PURE__ */ Object.create(null));
+  return Mt(e, r, t.p, n), _t(n, t.o), n;
+}
+function Hn(e, r) {
+  return v(e, r.i, new Date(r.s));
+}
+function Jn(e, r) {
+  if (e.base.features & 32) {
+    let t = F(r.c);
+    if (t.length > Bn) throw new w$1(r);
+    return v(e, r.i, new RegExp(t, r.m));
+  }
+  throw new O(r);
+}
+function Zn(e, r, t) {
+  let n = v(e, t.i, /* @__PURE__ */ new Set());
+  for (let a = 0, s = t.a, i = s.length; a < i; a++) n.add(p$1(e, r, s[a]));
+  return n;
+}
+function $n(e, r, t) {
+  let n = v(e, t.i, /* @__PURE__ */ new Map());
+  for (let a = 0, s = t.e.k, i = t.e.v, u2 = s.length; a < u2; a++) n.set(p$1(e, r, s[a]), p$1(e, r, i[a]));
+  return n;
+}
+function qn(e, r) {
+  if (r.s.length > Dn) throw new w$1(r);
+  return v(e, r.i, Pr(F(r.s)));
+}
+function Xn(e, r, t) {
+  var u2;
+  let n = ht(t.c), a = p$1(e, r, t.f), s = (u2 = t.b) != null ? u2 : 0;
+  if (s < 0 || s > a.byteLength) throw new w$1(t);
+  return v(e, t.i, new n(a, s, t.l));
+}
+function Qn(e, r, t) {
+  var i;
+  let n = p$1(e, r, t.f), a = (i = t.b) != null ? i : 0;
+  if (a < 0 || a > n.byteLength) throw new w$1(t);
+  return v(e, t.i, new DataView(n, a, t.l));
+}
+function Vt(e, r, t, n) {
+  if (t.p) {
+    let a = Mt(e, r, t.p, {});
+    Object.defineProperties(n, Object.getOwnPropertyDescriptors(a));
+  }
+  return n;
+}
+function eo(e, r, t) {
+  let n = v(e, t.i, new AggregateError([], F(t.m)));
+  return Vt(e, r, t, n);
+}
+function ro(e, r, t) {
+  let n = _r(t, rt, t.s), a = v(e, t.i, new n(F(t.m)));
+  return Vt(e, r, t, a);
+}
+function to(e, r, t) {
+  let n = re$1(), a = v(e, t.i, n.p), s = p$1(e, r, t.f);
+  return t.s ? n.s(s) : n.f(s), a;
+}
+function no(e, r, t) {
+  return v(e, t.i, Object(p$1(e, r, t.f)));
+}
+function oo(e, r, t) {
+  let n = e.base.plugins;
+  if (n) {
+    let a = F(t.c);
+    for (let s = 0, i = n.length; s < i; s++) {
+      let u2 = n[s];
+      if (u2.tag === a) return v(e, t.i, u2.deserialize(t.s, new zr(e, r), { id: t.i }));
+    }
+  }
+  throw new Q(t.c);
+}
+function ao(e, r) {
+  return v(e, r.i, v(e, r.s, re$1()).p);
+}
+function so(e, r, t) {
+  let n = e.base.refs.get(t.i);
+  if (n) return n.s(p$1(e, r, t.a[1])), o;
+  throw new B("Promise");
+}
+function io(e, r, t) {
+  let n = e.base.refs.get(t.i);
+  if (n) return n.f(p$1(e, r, t.a[1])), o;
+  throw new B("Promise");
+}
+function uo(e, r, t) {
+  p$1(e, r, t.a[0]);
+  let n = p$1(e, r, t.a[1]);
+  return It(n);
+}
+function lo(e, r, t) {
+  p$1(e, r, t.a[0]);
+  let n = p$1(e, r, t.a[1]);
+  return Et(n);
+}
+function co(e, r, t) {
+  let n = v(e, t.i, te()), a = t.a, s = a.length;
+  if (s) for (let i = 0; i < s; i++) p$1(e, r, a[i]);
+  return n;
+}
+function fo(e, r, t) {
+  let n = e.base.refs.get(t.i);
+  if (n && M(n)) return n.next(p$1(e, r, t.f)), o;
+  throw new B("Stream");
+}
+function So(e, r, t) {
+  let n = e.base.refs.get(t.i);
+  if (n && M(n)) return n.throw(p$1(e, r, t.f)), o;
+  throw new B("Stream");
+}
+function mo(e, r, t) {
+  let n = e.base.refs.get(t.i);
+  if (n && M(n)) return n.return(p$1(e, r, t.f)), o;
+  throw new B("Stream");
+}
+function po(e, r, t) {
+  return p$1(e, r, t.f), o;
+}
+function go(e, r, t) {
+  return p$1(e, r, t.a[1]), o;
+}
+function p$1(e, r, t) {
+  if (r > e.base.depthLimit) throw new ee$1(e.base.depthLimit);
+  switch (r += 1, t.t) {
+    case 2:
+      return _r(t, et, t.s);
+    case 0:
+      return Number(t.s);
+    case 1:
+      return F(String(t.s));
+    case 3:
+      if (String(t.s).length > Fn) throw new w$1(t);
+      return BigInt(t.s);
+    case 4:
+      return e.base.refs.get(t.i);
+    case 18:
+      return Un(e, t);
+    case 9:
+      return jn(e, r, t);
+    case 10:
+    case 11:
+      return Kn(e, r, t);
+    case 5:
+      return Hn(e, t);
+    case 6:
+      return Jn(e, t);
+    case 7:
+      return Zn(e, r, t);
+    case 8:
+      return $n(e, r, t);
+    case 19:
+      return qn(e, t);
+    case 16:
+    case 15:
+      return Xn(e, r, t);
+    case 20:
+      return Qn(e, r, t);
+    case 14:
+      return eo(e, r, t);
+    case 13:
+      return ro(e, r, t);
+    case 12:
+      return to(e, r, t);
+    case 17:
+      return _r(t, Xr, t.s);
+    case 21:
+      return no(e, r, t);
+    case 25:
+      return oo(e, r, t);
+    case 22:
+      return ao(e, t);
+    case 23:
+      return so(e, r, t);
+    case 24:
+      return io(e, r, t);
+    case 28:
+      return uo(e, r, t);
+    case 30:
+      return lo(e, r, t);
+    case 31:
+      return co(e, r, t);
+    case 32:
+      return fo(e, r, t);
+    case 33:
+      return So(e, r, t);
+    case 34:
+      return mo(e, r, t);
+    case 27:
+      return po(e, r, t);
+    case 29:
+      return go(e, r, t);
+    default:
+      throw new O(t);
+  }
+}
+function nr(e, r) {
+  try {
+    return p$1(e, 0, r);
+  } catch (t) {
+    throw new He(t);
+  }
+}
+var yo = () => T, No = yo.toString(), Lt = /=>/.test(No);
+function or(e, r) {
+  return Lt ? (e.length === 1 ? e[0] : "(" + e.join(",") + ")") + "=>" + (r.startsWith("{") ? "(" + r + ")" : r) : "function(" + e.join(",") + "){return " + r + "}";
+}
+function Ut(e, r) {
+  return Lt ? (e.length === 1 ? e[0] : "(" + e.join(",") + ")") + "=>{" + r + "}" : "function(" + e.join(",") + "){" + r + "}";
+}
+var Wt = "hjkmoquxzABCDEFGHIJKLNPQRTUVWXYZ$_", jt = Wt.length, Gt = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789$_", Yt = Gt.length;
+function kr(e) {
+  let r = e % jt, t = Wt[r];
+  for (e = (e - r) / jt; e > 0; ) r = e % Yt, t += Gt[r], e = (e - r) / Yt;
+  return t;
+}
+var bo = /^[$A-Z_][0-9A-Z_$]*$/i;
+function Dr(e) {
+  let r = e[0];
+  return (r === "$" || r === "_" || r >= "A" && r <= "Z" || r >= "a" && r <= "z") && bo.test(e);
+}
+function ye(e) {
+  switch (e.t) {
+    case 0:
+      return e.s + "=" + e.v;
+    case 2:
+      return e.s + ".set(" + e.k + "," + e.v + ")";
+    case 1:
+      return e.s + ".add(" + e.v + ")";
+    case 3:
+      return e.s + ".delete(" + e.k + ")";
+  }
+}
+function Co(e) {
+  let r = [], t = e[0];
+  for (let n = 1, a = e.length, s, i = t; n < a; n++) s = e[n], s.t === 0 && s.v === i.v ? t = { t: 0, s: s.s, k: o, v: ye(t) } : s.t === 2 && s.s === i.s ? t = { t: 2, s: ye(t), k: s.k, v: s.v } : s.t === 1 && s.s === i.s ? t = { t: 1, s: ye(t), k: o, v: s.v } : s.t === 3 && s.s === i.s ? t = { t: 3, s: ye(t), k: s.k, v: o } : (r.push(t), t = s), i = s;
+  return r.push(t), r;
+}
+function qt(e) {
+  if (e.length) {
+    let r = "", t = Co(e);
+    for (let n = 0, a = t.length; n < a; n++) r += ye(t[n]) + ",";
+    return r;
+  }
+  return o;
+}
+var vo = "Object.create(null)", Ao = "new Set", Ro = "new Map", Eo = "Promise.resolve", Io = "Promise.reject", Po = { 3: "Object.freeze", 2: "Object.seal", 1: "Object.preventExtensions", 0: o };
+function Xt(e, r) {
+  return { mode: e, plugins: r.plugins, features: r.features, marked: new Set(r.markedRefs), stack: [], flags: [], assignments: [] };
+}
+function sr(e) {
+  return { mode: 2, base: Xt(2, e), state: e, child: o };
+}
+var Fr = class {
+  constructor(r) {
+    this._p = r;
+  }
+  serialize(r) {
+    return f(this._p, r);
+  }
+};
+function To(e, r) {
+  let t = e.valid.get(r);
+  t == null && (t = e.valid.size, e.valid.set(r, t));
+  let n = e.vars[t];
+  return n == null && (n = kr(t), e.vars[t] = n), n;
+}
+function Oo(e) {
+  return ce + "[" + e + "]";
+}
+function m(e, r) {
+  return e.mode === 1 ? To(e.state, r) : Oo(r);
+}
+function h(e, r) {
+  e.marked.add(r);
+}
+function Br(e, r) {
+  return e.marked.has(r);
+}
+function Vr(e, r, t) {
+  r !== 0 && (h(e.base, t), e.base.flags.push({ type: r, value: m(e, t) }));
+}
+function wo(e) {
+  let r = "";
+  for (let t = 0, n = e.flags, a = n.length; t < a; t++) {
+    let s = n[t];
+    r += Po[s.type] + "(" + s.value + "),";
+  }
+  return r;
+}
+function Qt(e) {
+  let r = qt(e.assignments), t = wo(e);
+  return r ? t ? r + t : r : t;
+}
+function en(e, r, t) {
+  e.assignments.push({ t: 0, s: r, k: o, v: t });
+}
+function ho(e, r, t) {
+  e.base.assignments.push({ t: 1, s: m(e, r), k: o, v: t });
+}
+function ge(e, r, t, n) {
+  e.base.assignments.push({ t: 2, s: m(e, r), k: t, v: n });
+}
+function Kt(e, r, t) {
+  e.base.assignments.push({ t: 3, s: m(e, r), k: t, v: o });
+}
+function Ne(e, r, t, n) {
+  en(e.base, m(e, r) + "[" + t + "]", n);
+}
+function Mr(e, r, t, n) {
+  en(e.base, m(e, r) + "." + t, n);
+}
+function V(e, r) {
+  return r.t === 4 && e.stack.includes(r.i);
+}
+function se(e, r, t) {
+  return e.mode === 1 && !Br(e.base, r) ? t : m(e, r) + "=" + t;
+}
+function zo(e) {
+  return U + '.get("' + e.s + '")';
+}
+function Ht(e, r, t, n) {
+  return t ? V(e.base, t) ? (h(e.base, r), Ne(e, r, n, m(e, t.i)), "") : f(e, t) : "";
+}
+function _o(e, r) {
+  let t = r.i, n = r.a, a = n.length;
+  if (a > 0) {
+    e.base.stack.push(t);
+    let s = Ht(e, t, n[0], 0), i = s === "";
+    for (let u2 = 1, l; u2 < a; u2++) l = Ht(e, t, n[u2], u2), s += "," + l, i = l === "";
+    return e.base.stack.pop(), Vr(e, r.o, r.i), "[" + s + (i ? ",]" : "]");
+  }
+  return "[]";
+}
+function Jt(e, r, t, n) {
+  if (typeof t == "string") {
+    let a = Number(t), s = a >= 0 && a.toString() === t || Dr(t);
+    if (V(e.base, n)) {
+      let i = m(e, n.i);
+      return h(e.base, r.i), s && a !== a ? Mr(e, r.i, t, i) : Ne(e, r.i, s ? t : '"' + t + '"', i), "";
+    }
+    return (s ? t : '"' + t + '"') + ":" + f(e, n);
+  }
+  return "[" + f(e, t) + "]:" + f(e, n);
+}
+function rn(e, r, t) {
+  let n = t.k, a = n.length;
+  if (a > 0) {
+    let s = t.v;
+    e.base.stack.push(r.i);
+    let i = Jt(e, r, n[0], s[0]);
+    for (let u2 = 1, l = i; u2 < a; u2++) l = Jt(e, r, n[u2], s[u2]), i += (l && i && ",") + l;
+    return e.base.stack.pop(), "{" + i + "}";
+  }
+  return "{}";
+}
+function ko(e, r) {
+  return Vr(e, r.o, r.i), rn(e, r, r.p);
+}
+function Do(e, r, t, n) {
+  let a = rn(e, r, t);
+  return a !== "{}" ? "Object.assign(" + n + "," + a + ")" : n;
+}
+function Fo(e, r, t, n, a) {
+  let s = e.base, i = f(e, a), u2 = Number(n), l = u2 >= 0 && u2.toString() === n || Dr(n);
+  if (V(s, a)) l && u2 !== u2 ? Mr(e, r.i, n, i) : Ne(e, r.i, l ? n : '"' + n + '"', i);
+  else {
+    let g = s.assignments;
+    s.assignments = t, l && u2 !== u2 ? Mr(e, r.i, n, i) : Ne(e, r.i, l ? n : '"' + n + '"', i), s.assignments = g;
+  }
+}
+function Bo(e, r, t, n, a) {
+  if (typeof n == "string") Fo(e, r, t, n, a);
+  else {
+    let s = e.base, i = s.stack;
+    s.stack = [];
+    let u2 = f(e, a);
+    s.stack = i;
+    let l = s.assignments;
+    s.assignments = t, Ne(e, r.i, f(e, n), u2), s.assignments = l;
+  }
+}
+function Mo(e, r, t) {
+  let n = t.k, a = n.length;
+  if (a > 0) {
+    let s = [], i = t.v;
+    e.base.stack.push(r.i);
+    for (let u2 = 0; u2 < a; u2++) Bo(e, r, s, n[u2], i[u2]);
+    return e.base.stack.pop(), qt(s);
+  }
+  return o;
+}
+function Lr(e, r, t) {
+  if (r.p) {
+    let n = e.base;
+    if (n.features & 8) t = Do(e, r, r.p, t);
+    else {
+      h(n, r.i);
+      let a = Mo(e, r, r.p);
+      if (a) return "(" + se(e, r.i, t) + "," + a + m(e, r.i) + ")";
+    }
+  }
+  return t;
+}
+function Vo(e, r) {
+  return Vr(e, r.o, r.i), Lr(e, r, vo);
+}
+function Lo(e) {
+  return 'new Date("' + e.s + '")';
+}
+function Uo(e, r) {
+  if (e.base.features & 32) return "/" + r.c + "/" + r.m;
+  throw new O(r);
+}
+function Zt(e, r, t) {
+  let n = e.base;
+  return V(n, t) ? (h(n, r), ho(e, r, m(e, t.i)), "") : f(e, t);
+}
+function jo(e, r) {
+  let t = Ao, n = r.a, a = n.length, s = r.i;
+  if (a > 0) {
+    e.base.stack.push(s);
+    let i = Zt(e, s, n[0]);
+    for (let u2 = 1, l = i; u2 < a; u2++) l = Zt(e, s, n[u2]), i += (l && i && ",") + l;
+    e.base.stack.pop(), i && (t += "([" + i + "])");
+  }
+  return t;
+}
+function $t(e, r, t, n, a) {
+  let s = e.base;
+  if (V(s, t)) {
+    let i = m(e, t.i);
+    if (h(s, r), V(s, n)) {
+      let l = m(e, n.i);
+      return ge(e, r, i, l), "";
+    }
+    if (n.t !== 4 && n.i != null && Br(s, n.i)) {
+      let l = "(" + f(e, n) + ",[" + a + "," + a + "])";
+      return ge(e, r, i, m(e, n.i)), Kt(e, r, a), l;
+    }
+    let u2 = s.stack;
+    return s.stack = [], ge(e, r, i, f(e, n)), s.stack = u2, "";
+  }
+  if (V(s, n)) {
+    let i = m(e, n.i);
+    if (h(s, r), t.t !== 4 && t.i != null && Br(s, t.i)) {
+      let l = "(" + f(e, t) + ",[" + a + "," + a + "])";
+      return ge(e, r, m(e, t.i), i), Kt(e, r, a), l;
+    }
+    let u2 = s.stack;
+    return s.stack = [], ge(e, r, f(e, t), i), s.stack = u2, "";
+  }
+  return "[" + f(e, t) + "," + f(e, n) + "]";
+}
+function Yo(e, r) {
+  let t = Ro, n = r.e.k, a = n.length, s = r.i, i = r.f, u2 = m(e, i.i), l = e.base;
+  if (a > 0) {
+    let g = r.e.v;
+    l.stack.push(s);
+    let S = $t(e, s, n[0], g[0], u2);
+    for (let d = 1, H = S; d < a; d++) H = $t(e, s, n[d], g[d], u2), S += (H && S && ",") + H;
+    l.stack.pop(), S && (t += "([" + S + "])");
+  }
+  return i.t === 26 && (h(l, i.i), t = "(" + f(e, i) + "," + t + ")"), t;
+}
+function Wo(e, r) {
+  return G(e, r.f) + '("' + r.s + '")';
+}
+function Go(e, r) {
+  return "new " + r.c + "(" + f(e, r.f) + "," + r.b + "," + r.l + ")";
+}
+function Ko(e, r) {
+  return "new DataView(" + f(e, r.f) + "," + r.b + "," + r.l + ")";
+}
+function Ho(e, r) {
+  let t = r.i;
+  e.base.stack.push(t);
+  let n = Lr(e, r, 'new AggregateError([],"' + r.m + '")');
+  return e.base.stack.pop(), n;
+}
+function Jo(e, r) {
+  return Lr(e, r, "new " + ve[r.s] + '("' + r.m + '")');
+}
+function Zo(e, r) {
+  let t, n = r.f, a = r.i, s = r.s ? Eo : Io, i = e.base;
+  if (V(i, n)) {
+    let u2 = m(e, n.i);
+    t = s + (r.s ? "().then(" + or([], u2) + ")" : "().catch(" + Ut([], "throw " + u2) + ")");
+  } else {
+    i.stack.push(a);
+    let u2 = f(e, n);
+    i.stack.pop(), t = s + "(" + u2 + ")";
+  }
+  return t;
+}
+function $o(e, r) {
+  return "Object(" + f(e, r.f) + ")";
+}
+function G(e, r) {
+  let t = f(e, r);
+  return r.t === 4 ? t : "(" + t + ")";
+}
+function qo(e, r) {
+  if (e.mode === 1) throw new O(r);
+  return "(" + se(e, r.s, G(e, r.f) + "()") + ").p";
+}
+function Xo(e, r) {
+  if (e.mode === 1) throw new O(r);
+  return G(e, r.a[0]) + "(" + m(e, r.i) + "," + f(e, r.a[1]) + ")";
+}
+function Qo(e, r) {
+  if (e.mode === 1) throw new O(r);
+  return G(e, r.a[0]) + "(" + m(e, r.i) + "," + f(e, r.a[1]) + ")";
+}
+function ea(e, r) {
+  let t = e.base.plugins;
+  if (t) for (let n = 0, a = t.length; n < a; n++) {
+    let s = t[n];
+    if (s.tag === r.c) return e.child == null && (e.child = new Fr(e)), s.serialize(r.s, e.child, { id: r.i });
+  }
+  throw new Q(r.c);
+}
+function ra(e, r) {
+  let t = "", n = false;
+  return r.f.t !== 4 && (h(e.base, r.f.i), t = "(" + f(e, r.f) + ",", n = true), t += se(e, r.i, "(" + yt + ")(" + m(e, r.f.i) + ")"), n && (t += ")"), t;
+}
+function ta(e, r) {
+  return G(e, r.a[0]) + "(" + f(e, r.a[1]) + ")";
+}
+function na(e, r) {
+  let t = r.a[0], n = r.a[1], a = e.base, s = "";
+  t.t !== 4 && (h(a, t.i), s += "(" + f(e, t)), n.t !== 4 && (h(a, n.i), s += (s ? "," : "(") + f(e, n)), s && (s += ",");
+  let i = se(e, r.i, "(" + Nt + ")(" + m(e, n.i) + "," + m(e, t.i) + ")");
+  return s ? s + i + ")" : i;
+}
+function oa(e, r) {
+  return G(e, r.a[0]) + "(" + f(e, r.a[1]) + ")";
+}
+function aa(e, r) {
+  let t = se(e, r.i, G(e, r.f) + "()"), n = r.a.length;
+  if (n) {
+    let a = f(e, r.a[0]);
+    for (let s = 1; s < n; s++) a += "," + f(e, r.a[s]);
+    return "(" + t + "," + a + "," + m(e, r.i) + ")";
+  }
+  return t;
+}
+function sa(e, r) {
+  return m(e, r.i) + ".next(" + f(e, r.f) + ")";
+}
+function ia(e, r) {
+  return m(e, r.i) + ".throw(" + f(e, r.f) + ")";
+}
+function ua(e, r) {
+  return m(e, r.i) + ".return(" + f(e, r.f) + ")";
+}
+function la(e, r) {
+  switch (r.t) {
+    case 17:
+      return qr[r.s];
+    case 18:
+      return zo(r);
+    case 9:
+      return _o(e, r);
+    case 10:
+      return ko(e, r);
+    case 11:
+      return Vo(e, r);
+    case 5:
+      return Lo(r);
+    case 6:
+      return Uo(e, r);
+    case 7:
+      return jo(e, r);
+    case 8:
+      return Yo(e, r);
+    case 19:
+      return Wo(e, r);
+    case 16:
+    case 15:
+      return Go(e, r);
+    case 20:
+      return Ko(e, r);
+    case 14:
+      return Ho(e, r);
+    case 13:
+      return Jo(e, r);
+    case 12:
+      return Zo(e, r);
+    case 21:
+      return $o(e, r);
+    case 22:
+      return qo(e, r);
+    case 25:
+      return ea(e, r);
+    case 26:
+      return Rt[r.s];
+    default:
+      throw new O(r);
+  }
+}
+function f(e, r) {
+  switch (r.t) {
+    case 2:
+      return Qr[r.s];
+    case 0:
+      return "" + r.s;
+    case 1:
+      return '"' + r.s + '"';
+    case 3:
+      return r.s + "n";
+    case 4:
+      return m(e, r.i);
+    case 23:
+      return Xo(e, r);
+    case 24:
+      return Qo(e, r);
+    case 27:
+      return ra(e, r);
+    case 28:
+      return ta(e, r);
+    case 29:
+      return na(e, r);
+    case 30:
+      return oa(e, r);
+    case 31:
+      return aa(e, r);
+    case 32:
+      return sa(e, r);
+    case 33:
+      return ia(e, r);
+    case 34:
+      return ua(e, r);
+    default:
+      return se(e, r.i, la(e, r));
+  }
+}
+function ur(e, r) {
+  let t = f(e, r), n = r.i;
+  if (n == null) return t;
+  let a = Qt(e.base), s = m(e, n), i = e.state.scopeId, u2 = i == null ? "" : ce, l = a ? "(" + t + "," + a + s + ")" : t;
+  if (u2 === "") return r.t === 10 && !a ? "(" + l + ")" : l;
+  let g = i == null ? "()" : "(" + ce + '["' + y(i) + '"])';
+  return "(" + or([u2], l) + ")" + g;
+}
+var jr = class {
+  constructor(r, t) {
+    this._p = r;
+    this.depth = t;
+  }
+  parse(r) {
+    return R(this._p, this.depth, r);
+  }
+}, Yr = class {
+  constructor(r, t) {
+    this._p = r;
+    this.depth = t;
+  }
+  parse(r) {
+    return R(this._p, this.depth, r);
+  }
+  parseWithError(r) {
+    return K(this._p, this.depth, r);
+  }
+  isAlive() {
+    return this._p.state.alive;
+  }
+  pushPendingState() {
+    Jr(this._p);
+  }
+  popPendingState() {
+    be(this._p);
+  }
+  onParse(r) {
+    ie(this._p, r);
+  }
+  onError(r) {
+    Kr(this._p, r);
+  }
+};
+function ca(e) {
+  return { alive: true, pending: 0, initial: true, buffer: [], onParse: e.onParse, onError: e.onError, onDone: e.onDone };
+}
+function Wr(e) {
+  return { type: 2, base: pe(2, e), state: ca(e) };
+}
+function fa(e, r, t) {
+  let n = [];
+  for (let a = 0, s = t.length; a < s; a++) a in t ? n[a] = R(e, r, t[a]) : n[a] = 0;
+  return n;
+}
+function Sa(e, r, t, n) {
+  return _e(t, n, fa(e, r, n));
+}
+function Gr(e, r, t) {
+  let n = Object.entries(t), a = [], s = [];
+  for (let i = 0, u2 = n.length; i < u2; i++) a.push(y(n[i][0])), s.push(R(e, r, n[i][1]));
+  return b in t && (a.push(E(e.base, b)), s.push(Ue(Xe(e.base), R(e, r, $e(t))))), N in t && (a.push(E(e.base, N)), s.push(je(Qe(e.base), R(e, r, e.type === 1 ? te() : Ze(t))))), P$1 in t && (a.push(E(e.base, P$1)), s.push(X(t[P$1]))), I in t && (a.push(E(e.base, I)), s.push(t[I] ? Z : $)), { k: a, v: s };
+}
+function Ur(e, r, t, n, a) {
+  return er(t, n, a, Gr(e, r, n));
+}
+function ma(e, r, t, n) {
+  return ke(t, R(e, r, n.valueOf()));
+}
+function pa(e, r, t, n) {
+  return De(t, n, R(e, r, n.buffer));
+}
+function da(e, r, t, n) {
+  return Fe(t, n, R(e, r, n.buffer));
+}
+function ga(e, r, t, n) {
+  return Be(t, n, R(e, r, n.buffer));
+}
+function tn(e, r, t, n) {
+  let a = q(n, e.base.features);
+  return Me(t, n, a ? Gr(e, r, a) : o);
+}
+function ya(e, r, t, n) {
+  let a = q(n, e.base.features);
+  return Ve(t, n, a ? Gr(e, r, a) : o);
+}
+function Na(e, r, t, n) {
+  let a = [], s = [];
+  for (let [i, u2] of n.entries()) a.push(R(e, r, i)), s.push(R(e, r, u2));
+  return rr(e.base, t, a, s);
+}
+function ba(e, r, t, n) {
+  let a = [];
+  for (let s of n.keys()) a.push(R(e, r, s));
+  return Le(t, a);
+}
+function Ca(e, r, t, n) {
+  let a = Ye(t, k(e.base, 4), []);
+  return e.type === 1 || (Jr(e), n.on({ next: (s) => {
+    if (e.state.alive) {
+      let i = K(e, r, s);
+      i && ie(e, We(t, i));
+    }
+  }, throw: (s) => {
+    if (e.state.alive) {
+      let i = K(e, r, s);
+      i && ie(e, Ge(t, i));
+    }
+    be(e);
+  }, return: (s) => {
+    if (e.state.alive) {
+      let i = K(e, r, s);
+      i && ie(e, Ke(t, i));
+    }
+    be(e);
+  } })), a;
+}
+function va(e, r, t) {
+  if (this.state.alive) {
+    let n = K(this, r, t);
+    n && ie(this, c(23, e, o, o, o, o, o, [k(this.base, 2), n], o, o, o, o)), be(this);
+  }
+}
+function Aa(e, r, t) {
+  if (this.state.alive) {
+    let n = K(this, r, t);
+    n && ie(this, c(24, e, o, o, o, o, o, [k(this.base, 3), n], o, o, o, o));
+  }
+  be(this);
+}
+function Ra(e, r, t, n) {
+  let a = Tr(e.base, {});
+  return e.type === 2 && (Jr(e), n.then(va.bind(e, a, r), Aa.bind(e, a, r))), xt(e.base, t, a);
+}
+function Ea(e, r, t, n, a) {
+  for (let s = 0, i = a.length; s < i; s++) {
+    let u2 = a[s];
+    if (u2.parse.sync && u2.test(n)) return fe(t, u2.tag, u2.parse.sync(n, new jr(e, r), { id: t }));
+  }
+  return o;
+}
+function Ia(e, r, t, n, a) {
+  for (let s = 0, i = a.length; s < i; s++) {
+    let u2 = a[s];
+    if (u2.parse.stream && u2.test(n)) return fe(t, u2.tag, u2.parse.stream(n, new Yr(e, r), { id: t }));
+  }
+  return o;
+}
+function nn(e, r, t, n) {
+  let a = e.base.plugins;
+  return a ? e.type === 1 ? Ea(e, r, t, n, a) : Ia(e, r, t, n, a) : o;
+}
+function Pa(e, r, t, n, a) {
+  switch (a) {
+    case Object:
+      return Ur(e, r, t, n, false);
+    case o:
+      return Ur(e, r, t, n, true);
+    case Date:
+      return he(t, n);
+    case Error:
+    case EvalError:
+    case RangeError:
+    case ReferenceError:
+    case SyntaxError:
+    case TypeError:
+    case URIError:
+      return tn(e, r, t, n);
+    case Number:
+    case Boolean:
+    case String:
+    case BigInt:
+      return ma(e, r, t, n);
+    case ArrayBuffer:
+      return tr(e.base, t, n);
+    case Int8Array:
+    case Int16Array:
+    case Int32Array:
+    case Uint8Array:
+    case Uint16Array:
+    case Uint32Array:
+    case Uint8ClampedArray:
+    case Float32Array:
+    case Float64Array:
+      return pa(e, r, t, n);
+    case DataView:
+      return ga(e, r, t, n);
+    case Map:
+      return Na(e, r, t, n);
+    case Set:
+      return ba(e, r, t, n);
+  }
+  if (a === Promise || n instanceof Promise) return Ra(e, r, t, n);
+  let s = e.base.features;
+  if (s & 32 && a === RegExp) return ze(t, n);
+  if (s & 16) switch (a) {
+    case BigInt64Array:
+    case BigUint64Array:
+      return da(e, r, t, n);
+  }
+  if (s & 1 && typeof AggregateError != "undefined" && (a === AggregateError || n instanceof AggregateError)) return ya(e, r, t, n);
+  if (n instanceof Error) return tn(e, r, t, n);
+  if (b in n || N in n) return Ur(e, r, t, n, !!a);
+  throw new x(n);
+}
+function xa(e, r, t, n) {
+  if (Array.isArray(n)) return Sa(e, r, t, n);
+  if (M(n)) return Ca(e, r, t, n);
+  let a = n.constructor;
+  if (a === Y) return R(e, r, n.replacement);
+  let s = nn(e, r, t, n);
+  return s || Pa(e, r, t, n, a);
+}
+function Ta(e, r, t) {
+  let n = W(e.base, t);
+  if (n.type !== 0) return n.value;
+  let a = nn(e, r, n.value, t);
+  if (a) return a;
+  throw new x(t);
+}
+function R(e, r, t) {
+  if (r >= e.base.depthLimit) throw new ee$1(e.base.depthLimit);
+  switch (typeof t) {
+    case "boolean":
+      return t ? Z : $;
+    case "undefined":
+      return Ae;
+    case "string":
+      return X(t);
+    case "number":
+      return Oe(t);
+    case "bigint":
+      return we(t);
+    case "object": {
+      if (t) {
+        let n = W(e.base, t);
+        return n.type === 0 ? xa(e, r + 1, n.value, t) : n.value;
+      }
+      return Re;
+    }
+    case "symbol":
+      return E(e.base, t);
+    case "function":
+      return Ta(e, r, t);
+    default:
+      throw new x(t);
+  }
+}
+function ie(e, r) {
+  e.state.initial ? e.state.buffer.push(r) : Hr(e, r, false);
+}
+function Kr(e, r) {
+  if (e.state.onError) e.state.onError(r);
+  else throw r instanceof z ? r : new z(r);
+}
+function on(e) {
+  e.state.onDone && e.state.onDone();
+}
+function Hr(e, r, t) {
+  try {
+    e.state.onParse(r, t);
+  } catch (n) {
+    Kr(e, n);
+  }
+}
+function Jr(e) {
+  e.state.pending++;
+}
+function be(e) {
+  --e.state.pending <= 0 && on(e);
+}
+function K(e, r, t) {
+  try {
+    return R(e, r, t);
+  } catch (n) {
+    return Kr(e, n), o;
+  }
+}
+function Zr(e, r) {
+  let t = K(e, 0, r);
+  t && (Hr(e, t, true), e.state.initial = false, Oa(e, e.state), e.state.pending <= 0 && lr(e));
+}
+function Oa(e, r) {
+  for (let t = 0, n = r.buffer.length; t < n; t++) Hr(e, r.buffer[t], false);
+}
+function lr(e) {
+  e.state.alive && (on(e), e.state.alive = false);
+}
+async function Zi(e, r = {}) {
+  let t = A(r.plugins), n = ne(2, { plugins: t, disabledFeatures: r.disabledFeatures, refs: r.refs });
+  return await oe(n, e);
+}
+function an(e, r) {
+  let t = A(r.plugins), n = Wr({ plugins: t, refs: r.refs, disabledFeatures: r.disabledFeatures, onParse(a, s) {
+    let i = sr({ plugins: t, features: n.base.features, scopeId: r.scopeId, markedRefs: n.base.marked }), u2;
+    try {
+      u2 = ur(i, a);
+    } catch (l) {
+      r.onError && r.onError(l);
+      return;
+    }
+    r.onSerialize(u2, s);
+  }, onError: r.onError, onDone: r.onDone });
+  return Zr(n, e), lr.bind(null, n);
+}
+function $i(e, r) {
+  let t = A(r.plugins), n = Wr({ plugins: t, refs: r.refs, disabledFeatures: r.disabledFeatures, onParse: r.onParse, onError: r.onError, onDone: r.onDone });
+  return Zr(n, e), lr.bind(null, n);
+}
+function du(e, r = {}) {
+  var i;
+  let t = A(r.plugins), n = r.disabledFeatures || 0, a = (i = e.f) != null ? i : 63, s = Dt({ plugins: t, markedRefs: e.m, features: a & ~n, disabledFeatures: n });
+  return nr(s, e.t);
+}
+const GLOBAL_TSR = "$_TSR";
+const TSR_SCRIPT_BARRIER_ID = "$tsr-stream-barrier";
+function createSerializationAdapter(opts) {
+  return opts;
+}
+function makeSsrSerovalPlugin(serializationAdapter, options) {
+  return Js({
+    tag: "$TSR/t/" + serializationAdapter.key,
+    test: serializationAdapter.test,
+    parse: {
+      stream(value, ctx) {
+        return ctx.parse(serializationAdapter.toSerializable(value));
+      }
+    },
+    serialize(node, ctx) {
+      options.didRun = true;
+      return GLOBAL_TSR + '.t.get("' + serializationAdapter.key + '")(' + ctx.serialize(node) + ")";
+    },
+    // we never deserialize on the server during SSR
+    deserialize: void 0
+  });
+}
+function makeSerovalPlugin(serializationAdapter) {
+  return Js({
+    tag: "$TSR/t/" + serializationAdapter.key,
+    test: serializationAdapter.test,
+    parse: {
+      sync(value, ctx) {
+        return ctx.parse(serializationAdapter.toSerializable(value));
+      },
+      async async(value, ctx) {
+        return await ctx.parse(serializationAdapter.toSerializable(value));
+      },
+      stream(value, ctx) {
+        return ctx.parse(serializationAdapter.toSerializable(value));
+      }
+    },
+    // we don't generate JS code outside of SSR (for now)
+    serialize: void 0,
+    deserialize(node, ctx) {
+      return serializationAdapter.fromSerializable(ctx.deserialize(node));
+    }
+  });
+}
+var p = {}, P = (e) => new ReadableStream({ start: (r) => {
+  e.on({ next: (a) => {
+    try {
+      r.enqueue(a);
+    } catch (t) {
+    }
+  }, throw: (a) => {
+    r.error(a);
+  }, return: () => {
+    try {
+      r.close();
+    } catch (a) {
+    }
+  } });
+} }), ee2 = Js({ tag: "seroval-plugins/web/ReadableStreamFactory", test(e) {
+  return e === p;
+}, parse: { sync() {
+}, async async() {
+  return await Promise.resolve(void 0);
+}, stream() {
+} }, serialize() {
+  return P.toString();
+}, deserialize() {
+  return p;
+} });
+function w2(e) {
+  let r = te(), a = e.getReader();
+  async function t() {
+    try {
+      let n = await a.read();
+      n.done ? r.return(n.value) : (r.next(n.value), await t());
+    } catch (n) {
+      r.throw(n);
+    }
+  }
+  return t().catch(() => {
+  }), r;
+}
+var re = Js({ tag: "seroval/plugins/web/ReadableStream", extends: [ee2], test(e) {
+  return typeof ReadableStream == "undefined" ? false : e instanceof ReadableStream;
+}, parse: { sync(e, r) {
+  return { factory: r.parse(p), stream: r.parse(te()) };
+}, async async(e, r) {
+  return { factory: await r.parse(p), stream: await r.parse(w2(e)) };
+}, stream(e, r) {
+  return { factory: r.parse(p), stream: r.parse(w2(e)) };
+} }, serialize(e, r) {
+  return "(" + r.serialize(e.factory) + ")(" + r.serialize(e.stream) + ")";
+}, deserialize(e, r) {
+  let a = r.deserialize(e.stream);
+  return P(a);
+} }), u = re;
+const ShallowErrorPlugin = /* @__PURE__ */ Js({
+  tag: "$TSR/Error",
+  test(value) {
+    return value instanceof Error;
+  },
+  parse: {
+    sync(value, ctx) {
+      return {
+        message: ctx.parse(value.message)
+      };
+    },
+    async async(value, ctx) {
+      return {
+        message: await ctx.parse(value.message)
+      };
+    },
+    stream(value, ctx) {
+      return {
+        message: ctx.parse(value.message)
+      };
+    }
+  },
+  serialize(node, ctx) {
+    return "new Error(" + ctx.serialize(node.message) + ")";
+  },
+  deserialize(node, ctx) {
+    return new Error(ctx.deserialize(node.message));
+  }
+});
+class RawStream {
+  constructor(stream, options) {
+    this.stream = stream;
+    this.hint = options?.hint ?? "binary";
+  }
+}
+const BufferCtor = globalThis.Buffer;
+const hasNodeBuffer = !!BufferCtor && typeof BufferCtor.from === "function";
+function uint8ArrayToBase64(bytes) {
+  if (bytes.length === 0) return "";
+  if (hasNodeBuffer) {
+    return BufferCtor.from(bytes).toString("base64");
+  }
+  const CHUNK_SIZE = 32768;
+  const chunks = [];
+  for (let i = 0; i < bytes.length; i += CHUNK_SIZE) {
+    const chunk = bytes.subarray(i, i + CHUNK_SIZE);
+    chunks.push(String.fromCharCode.apply(null, chunk));
+  }
+  return btoa(chunks.join(""));
+}
+function base64ToUint8Array(base64) {
+  if (base64.length === 0) return new Uint8Array(0);
+  if (hasNodeBuffer) {
+    const buf = BufferCtor.from(base64, "base64");
+    return new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength);
+  }
+  const binary = atob(base64);
+  const bytes = new Uint8Array(binary.length);
+  for (let i = 0; i < binary.length; i++) {
+    bytes[i] = binary.charCodeAt(i);
+  }
+  return bytes;
+}
+const RAW_STREAM_FACTORY_BINARY = /* @__PURE__ */ Object.create(null);
+const RAW_STREAM_FACTORY_TEXT = /* @__PURE__ */ Object.create(null);
+const RAW_STREAM_FACTORY_CONSTRUCTOR_BINARY = (stream) => new ReadableStream({
+  start(controller) {
+    stream.on({
+      next(base64) {
+        try {
+          controller.enqueue(base64ToUint8Array(base64));
+        } catch {
+        }
+      },
+      throw(error2) {
+        controller.error(error2);
+      },
+      return() {
+        try {
+          controller.close();
+        } catch {
+        }
+      }
+    });
+  }
+});
+const textEncoderForFactory = new TextEncoder();
+const RAW_STREAM_FACTORY_CONSTRUCTOR_TEXT = (stream) => {
+  return new ReadableStream({
+    start(controller) {
+      stream.on({
+        next(value) {
+          try {
+            if (typeof value === "string") {
+              controller.enqueue(textEncoderForFactory.encode(value));
+            } else {
+              controller.enqueue(base64ToUint8Array(value.$b64));
+            }
+          } catch {
+          }
+        },
+        throw(error2) {
+          controller.error(error2);
+        },
+        return() {
+          try {
+            controller.close();
+          } catch {
+          }
+        }
+      });
+    }
+  });
+};
+const FACTORY_BINARY = `(s=>new ReadableStream({start(c){s.on({next(b){try{const d=atob(b),a=new Uint8Array(d.length);for(let i=0;i{const e=new TextEncoder();return new ReadableStream({start(c){s.on({next(v){try{if(typeof v==='string'){c.enqueue(e.encode(v))}else{const d=atob(v.$b64),a=new Uint8Array(d.length);for(let i=0;i {
+    try {
+      while (true) {
+        const { done, value } = await reader.read();
+        if (done) {
+          stream.return(void 0);
+          break;
+        }
+        stream.next(uint8ArrayToBase64(value));
+      }
+    } catch (error2) {
+      stream.throw(error2);
+    } finally {
+      reader.releaseLock();
+    }
+  })();
+  return stream;
+}
+function toTextStream(readable) {
+  const stream = te();
+  const reader = readable.getReader();
+  const decoder = new TextDecoder("utf-8", { fatal: true });
+  (async () => {
+    try {
+      while (true) {
+        const { done, value } = await reader.read();
+        if (done) {
+          try {
+            const remaining = decoder.decode();
+            if (remaining.length > 0) {
+              stream.next(remaining);
+            }
+          } catch {
+          }
+          stream.return(void 0);
+          break;
+        }
+        try {
+          const text = decoder.decode(value, { stream: true });
+          if (text.length > 0) {
+            stream.next(text);
+          }
+        } catch {
+          stream.next({ $b64: uint8ArrayToBase64(value) });
+        }
+      }
+    } catch (error2) {
+      stream.throw(error2);
+    } finally {
+      reader.releaseLock();
+    }
+  })();
+  return stream;
+}
+const RawStreamFactoryBinaryPlugin = Js({
+  tag: "tss/RawStreamFactory",
+  test(value) {
+    return value === RAW_STREAM_FACTORY_BINARY;
+  },
+  parse: {
+    sync() {
+      return void 0;
+    },
+    async() {
+      return Promise.resolve(void 0);
+    },
+    stream() {
+      return void 0;
+    }
+  },
+  serialize() {
+    return FACTORY_BINARY;
+  },
+  deserialize() {
+    return RAW_STREAM_FACTORY_BINARY;
+  }
+});
+const RawStreamFactoryTextPlugin = Js({
+  tag: "tss/RawStreamFactoryText",
+  test(value) {
+    return value === RAW_STREAM_FACTORY_TEXT;
+  },
+  parse: {
+    sync() {
+      return void 0;
+    },
+    async() {
+      return Promise.resolve(void 0);
+    },
+    stream() {
+      return void 0;
+    }
+  },
+  serialize() {
+    return FACTORY_TEXT;
+  },
+  deserialize() {
+    return RAW_STREAM_FACTORY_TEXT;
+  }
+});
+const RawStreamSSRPlugin = Js({
+  tag: "tss/RawStream",
+  extends: [RawStreamFactoryBinaryPlugin, RawStreamFactoryTextPlugin],
+  test(value) {
+    return value instanceof RawStream;
+  },
+  parse: {
+    sync(value, ctx) {
+      const factory = value.hint === "text" ? RAW_STREAM_FACTORY_TEXT : RAW_STREAM_FACTORY_BINARY;
+      return {
+        hint: value.hint,
+        factory: ctx.parse(factory),
+        stream: ctx.parse(te())
+      };
+    },
+    async async(value, ctx) {
+      const factory = value.hint === "text" ? RAW_STREAM_FACTORY_TEXT : RAW_STREAM_FACTORY_BINARY;
+      const encodedStream = value.hint === "text" ? toTextStream(value.stream) : toBinaryStream(value.stream);
+      return {
+        hint: value.hint,
+        factory: await ctx.parse(factory),
+        stream: await ctx.parse(encodedStream)
+      };
+    },
+    stream(value, ctx) {
+      const factory = value.hint === "text" ? RAW_STREAM_FACTORY_TEXT : RAW_STREAM_FACTORY_BINARY;
+      const encodedStream = value.hint === "text" ? toTextStream(value.stream) : toBinaryStream(value.stream);
+      return {
+        hint: value.hint,
+        factory: ctx.parse(factory),
+        stream: ctx.parse(encodedStream)
+      };
+    }
+  },
+  serialize(node, ctx) {
+    return "(" + ctx.serialize(node.factory) + ")(" + ctx.serialize(node.stream) + ")";
+  },
+  deserialize(node, ctx) {
+    const stream = ctx.deserialize(node.stream);
+    return node.hint === "text" ? RAW_STREAM_FACTORY_CONSTRUCTOR_TEXT(stream) : RAW_STREAM_FACTORY_CONSTRUCTOR_BINARY(stream);
+  }
+});
+function createRawStreamRPCPlugin(onRawStream) {
+  let nextStreamId = 1;
+  return Js({
+    tag: "tss/RawStream",
+    test(value) {
+      return value instanceof RawStream;
+    },
+    parse: {
+      async(value) {
+        const streamId = nextStreamId++;
+        onRawStream(streamId, value.stream);
+        return Promise.resolve({ streamId });
+      },
+      stream(value) {
+        const streamId = nextStreamId++;
+        onRawStream(streamId, value.stream);
+        return { streamId };
+      }
+    },
+    serialize() {
+      throw new Error(
+        "RawStreamRPCPlugin.serialize should not be called. RPC uses JSON serialization, not JS code generation."
+      );
+    },
+    deserialize() {
+      throw new Error(
+        "RawStreamRPCPlugin.deserialize should not be called. Use createRawStreamDeserializePlugin on client."
+      );
+    }
+  });
+}
+const defaultSerovalPlugins = [
+  ShallowErrorPlugin,
+  // RawStreamSSRPlugin must come before ReadableStreamPlugin to match first
+  RawStreamSSRPlugin,
+  // ReadableStreamNode is not exported by seroval
+  u
+];
+var reactExports = requireReact();
+const React__default = /* @__PURE__ */ getDefaultExportFromCjs(reactExports);
+function CatchBoundary(props) {
+  const errorComponent = props.errorComponent ?? ErrorComponent;
+  return /* @__PURE__ */ jsxRuntimeExports.jsx(
+    CatchBoundaryImpl,
+    {
+      getResetKey: props.getResetKey,
+      onCatch: props.onCatch,
+      children: ({ error: error2, reset }) => {
+        if (error2) {
+          return reactExports.createElement(errorComponent, {
+            error: error2,
+            reset
+          });
+        }
+        return props.children;
+      }
+    }
+  );
+}
+class CatchBoundaryImpl extends reactExports.Component {
+  constructor() {
+    super(...arguments);
+    this.state = { error: null };
+  }
+  static getDerivedStateFromProps(props) {
+    return { resetKey: props.getResetKey() };
+  }
+  static getDerivedStateFromError(error2) {
+    return { error: error2 };
+  }
+  reset() {
+    this.setState({ error: null });
+  }
+  componentDidUpdate(prevProps, prevState) {
+    if (prevState.error && prevState.resetKey !== this.state.resetKey) {
+      this.reset();
+    }
+  }
+  componentDidCatch(error2, errorInfo) {
+    if (this.props.onCatch) {
+      this.props.onCatch(error2, errorInfo);
+    }
+  }
+  render() {
+    return this.props.children({
+      error: this.state.resetKey !== this.props.getResetKey() ? null : this.state.error,
+      reset: () => {
+        this.reset();
+      }
+    });
+  }
+}
+function ErrorComponent({ error: error2 }) {
+  const [show, setShow] = reactExports.useState(process.env.NODE_ENV !== "production");
+  return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { style: { padding: ".5rem", maxWidth: "100%" }, children: [
+    /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { style: { display: "flex", alignItems: "center", gap: ".5rem" }, children: [
+      /* @__PURE__ */ jsxRuntimeExports.jsx("strong", { style: { fontSize: "1rem" }, children: "Something went wrong!" }),
+      /* @__PURE__ */ jsxRuntimeExports.jsx(
+        "button",
+        {
+          style: {
+            appearance: "none",
+            fontSize: ".6em",
+            border: "1px solid currentColor",
+            padding: ".1rem .2rem",
+            fontWeight: "bold",
+            borderRadius: ".25rem"
+          },
+          onClick: () => setShow((d) => !d),
+          children: show ? "Hide Error" : "Show Error"
+        }
+      )
+    ] }),
+    /* @__PURE__ */ jsxRuntimeExports.jsx("div", { style: { height: ".25rem" } }),
+    show ? /* @__PURE__ */ jsxRuntimeExports.jsx("div", { children: /* @__PURE__ */ jsxRuntimeExports.jsx(
+      "pre",
+      {
+        style: {
+          fontSize: ".7em",
+          border: "1px solid red",
+          borderRadius: ".25rem",
+          padding: ".3rem",
+          color: "red",
+          overflow: "auto"
+        },
+        children: error2.message ? /* @__PURE__ */ jsxRuntimeExports.jsx("code", { children: error2.message }) : null
+      }
+    ) }) : null
+  ] });
+}
+function ClientOnly({ children, fallback = null }) {
+  return useHydrated() ? /* @__PURE__ */ jsxRuntimeExports.jsx(React__default.Fragment, { children }) : /* @__PURE__ */ jsxRuntimeExports.jsx(React__default.Fragment, { children: fallback });
+}
+function useHydrated() {
+  return React__default.useSyncExternalStore(
+    subscribe,
+    () => true,
+    () => false
+  );
+}
+function subscribe() {
+  return () => {
+  };
+}
+var isProduction = process.env.NODE_ENV === "production";
+function warning(condition, message) {
+  if (!isProduction) {
+    if (condition) {
+      return;
+    }
+    var text = "Warning: " + message;
+    if (typeof console !== "undefined") {
+      console.warn(text);
+    }
+    try {
+      throw Error(text);
+    } catch (x2) {
+    }
+  }
+}
+var withSelector = { exports: {} };
+var withSelector_production = {};
+var shim = { exports: {} };
+var useSyncExternalStoreShim_production = {};
+var hasRequiredUseSyncExternalStoreShim_production;
+function requireUseSyncExternalStoreShim_production() {
+  if (hasRequiredUseSyncExternalStoreShim_production) return useSyncExternalStoreShim_production;
+  hasRequiredUseSyncExternalStoreShim_production = 1;
+  var React = requireReact();
+  function is(x2, y2) {
+    return x2 === y2 && (0 !== x2 || 1 / x2 === 1 / y2) || x2 !== x2 && y2 !== y2;
+  }
+  var objectIs = "function" === typeof Object.is ? Object.is : is, useState = React.useState, useEffect = React.useEffect, useLayoutEffect2 = React.useLayoutEffect, useDebugValue = React.useDebugValue;
+  function useSyncExternalStore$2(subscribe2, getSnapshot) {
+    var value = getSnapshot(), _useState = useState({ inst: { value, getSnapshot } }), inst = _useState[0].inst, forceUpdate = _useState[1];
+    useLayoutEffect2(
+      function() {
+        inst.value = value;
+        inst.getSnapshot = getSnapshot;
+        checkIfSnapshotChanged(inst) && forceUpdate({ inst });
+      },
+      [subscribe2, value, getSnapshot]
+    );
+    useEffect(
+      function() {
+        checkIfSnapshotChanged(inst) && forceUpdate({ inst });
+        return subscribe2(function() {
+          checkIfSnapshotChanged(inst) && forceUpdate({ inst });
+        });
+      },
+      [subscribe2]
+    );
+    useDebugValue(value);
+    return value;
+  }
+  function checkIfSnapshotChanged(inst) {
+    var latestGetSnapshot = inst.getSnapshot;
+    inst = inst.value;
+    try {
+      var nextValue = latestGetSnapshot();
+      return !objectIs(inst, nextValue);
+    } catch (error2) {
+      return true;
+    }
+  }
+  function useSyncExternalStore$1(subscribe2, getSnapshot) {
+    return getSnapshot();
+  }
+  var shim2 = "undefined" === typeof window || "undefined" === typeof window.document || "undefined" === typeof window.document.createElement ? useSyncExternalStore$1 : useSyncExternalStore$2;
+  useSyncExternalStoreShim_production.useSyncExternalStore = void 0 !== React.useSyncExternalStore ? React.useSyncExternalStore : shim2;
+  return useSyncExternalStoreShim_production;
+}
+var useSyncExternalStoreShim_development = {};
+var hasRequiredUseSyncExternalStoreShim_development;
+function requireUseSyncExternalStoreShim_development() {
+  if (hasRequiredUseSyncExternalStoreShim_development) return useSyncExternalStoreShim_development;
+  hasRequiredUseSyncExternalStoreShim_development = 1;
+  "production" !== process.env.NODE_ENV && (function() {
+    function is(x2, y2) {
+      return x2 === y2 && (0 !== x2 || 1 / x2 === 1 / y2) || x2 !== x2 && y2 !== y2;
+    }
+    function useSyncExternalStore$2(subscribe2, getSnapshot) {
+      didWarnOld18Alpha || void 0 === React.startTransition || (didWarnOld18Alpha = true, console.error(
+        "You are using an outdated, pre-release alpha of React 18 that does not support useSyncExternalStore. The use-sync-external-store shim will not work correctly. Upgrade to a newer pre-release."
+      ));
+      var value = getSnapshot();
+      if (!didWarnUncachedGetSnapshot) {
+        var cachedValue = getSnapshot();
+        objectIs(value, cachedValue) || (console.error(
+          "The result of getSnapshot should be cached to avoid an infinite loop"
+        ), didWarnUncachedGetSnapshot = true);
+      }
+      cachedValue = useState({
+        inst: { value, getSnapshot }
+      });
+      var inst = cachedValue[0].inst, forceUpdate = cachedValue[1];
+      useLayoutEffect2(
+        function() {
+          inst.value = value;
+          inst.getSnapshot = getSnapshot;
+          checkIfSnapshotChanged(inst) && forceUpdate({ inst });
+        },
+        [subscribe2, value, getSnapshot]
+      );
+      useEffect(
+        function() {
+          checkIfSnapshotChanged(inst) && forceUpdate({ inst });
+          return subscribe2(function() {
+            checkIfSnapshotChanged(inst) && forceUpdate({ inst });
+          });
+        },
+        [subscribe2]
+      );
+      useDebugValue(value);
+      return value;
+    }
+    function checkIfSnapshotChanged(inst) {
+      var latestGetSnapshot = inst.getSnapshot;
+      inst = inst.value;
+      try {
+        var nextValue = latestGetSnapshot();
+        return !objectIs(inst, nextValue);
+      } catch (error2) {
+        return true;
+      }
+    }
+    function useSyncExternalStore$1(subscribe2, getSnapshot) {
+      return getSnapshot();
+    }
+    "undefined" !== typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ && "function" === typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart && __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart(Error());
+    var React = requireReact(), objectIs = "function" === typeof Object.is ? Object.is : is, useState = React.useState, useEffect = React.useEffect, useLayoutEffect2 = React.useLayoutEffect, useDebugValue = React.useDebugValue, didWarnOld18Alpha = false, didWarnUncachedGetSnapshot = false, shim2 = "undefined" === typeof window || "undefined" === typeof window.document || "undefined" === typeof window.document.createElement ? useSyncExternalStore$1 : useSyncExternalStore$2;
+    useSyncExternalStoreShim_development.useSyncExternalStore = void 0 !== React.useSyncExternalStore ? React.useSyncExternalStore : shim2;
+    "undefined" !== typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ && "function" === typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop && __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop(Error());
+  })();
+  return useSyncExternalStoreShim_development;
+}
+var hasRequiredShim;
+function requireShim() {
+  if (hasRequiredShim) return shim.exports;
+  hasRequiredShim = 1;
+  if (process.env.NODE_ENV === "production") {
+    shim.exports = requireUseSyncExternalStoreShim_production();
+  } else {
+    shim.exports = requireUseSyncExternalStoreShim_development();
+  }
+  return shim.exports;
+}
+var hasRequiredWithSelector_production;
+function requireWithSelector_production() {
+  if (hasRequiredWithSelector_production) return withSelector_production;
+  hasRequiredWithSelector_production = 1;
+  var React = requireReact(), shim2 = requireShim();
+  function is(x2, y2) {
+    return x2 === y2 && (0 !== x2 || 1 / x2 === 1 / y2) || x2 !== x2 && y2 !== y2;
+  }
+  var objectIs = "function" === typeof Object.is ? Object.is : is, useSyncExternalStore = shim2.useSyncExternalStore, useRef = React.useRef, useEffect = React.useEffect, useMemo = React.useMemo, useDebugValue = React.useDebugValue;
+  withSelector_production.useSyncExternalStoreWithSelector = function(subscribe2, getSnapshot, getServerSnapshot, selector, isEqual) {
+    var instRef = useRef(null);
+    if (null === instRef.current) {
+      var inst = { hasValue: false, value: null };
+      instRef.current = inst;
+    } else inst = instRef.current;
+    instRef = useMemo(
+      function() {
+        function memoizedSelector(nextSnapshot) {
+          if (!hasMemo) {
+            hasMemo = true;
+            memoizedSnapshot = nextSnapshot;
+            nextSnapshot = selector(nextSnapshot);
+            if (void 0 !== isEqual && inst.hasValue) {
+              var currentSelection = inst.value;
+              if (isEqual(currentSelection, nextSnapshot))
+                return memoizedSelection = currentSelection;
+            }
+            return memoizedSelection = nextSnapshot;
+          }
+          currentSelection = memoizedSelection;
+          if (objectIs(memoizedSnapshot, nextSnapshot)) return currentSelection;
+          var nextSelection = selector(nextSnapshot);
+          if (void 0 !== isEqual && isEqual(currentSelection, nextSelection))
+            return memoizedSnapshot = nextSnapshot, currentSelection;
+          memoizedSnapshot = nextSnapshot;
+          return memoizedSelection = nextSelection;
+        }
+        var hasMemo = false, memoizedSnapshot, memoizedSelection, maybeGetServerSnapshot = void 0 === getServerSnapshot ? null : getServerSnapshot;
+        return [
+          function() {
+            return memoizedSelector(getSnapshot());
+          },
+          null === maybeGetServerSnapshot ? void 0 : function() {
+            return memoizedSelector(maybeGetServerSnapshot());
+          }
+        ];
+      },
+      [getSnapshot, getServerSnapshot, selector, isEqual]
+    );
+    var value = useSyncExternalStore(subscribe2, instRef[0], instRef[1]);
+    useEffect(
+      function() {
+        inst.hasValue = true;
+        inst.value = value;
+      },
+      [value]
+    );
+    useDebugValue(value);
+    return value;
+  };
+  return withSelector_production;
+}
+var withSelector_development = {};
+var hasRequiredWithSelector_development;
+function requireWithSelector_development() {
+  if (hasRequiredWithSelector_development) return withSelector_development;
+  hasRequiredWithSelector_development = 1;
+  "production" !== process.env.NODE_ENV && (function() {
+    function is(x2, y2) {
+      return x2 === y2 && (0 !== x2 || 1 / x2 === 1 / y2) || x2 !== x2 && y2 !== y2;
+    }
+    "undefined" !== typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ && "function" === typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart && __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart(Error());
+    var React = requireReact(), shim2 = requireShim(), objectIs = "function" === typeof Object.is ? Object.is : is, useSyncExternalStore = shim2.useSyncExternalStore, useRef = React.useRef, useEffect = React.useEffect, useMemo = React.useMemo, useDebugValue = React.useDebugValue;
+    withSelector_development.useSyncExternalStoreWithSelector = function(subscribe2, getSnapshot, getServerSnapshot, selector, isEqual) {
+      var instRef = useRef(null);
+      if (null === instRef.current) {
+        var inst = { hasValue: false, value: null };
+        instRef.current = inst;
+      } else inst = instRef.current;
+      instRef = useMemo(
+        function() {
+          function memoizedSelector(nextSnapshot) {
+            if (!hasMemo) {
+              hasMemo = true;
+              memoizedSnapshot = nextSnapshot;
+              nextSnapshot = selector(nextSnapshot);
+              if (void 0 !== isEqual && inst.hasValue) {
+                var currentSelection = inst.value;
+                if (isEqual(currentSelection, nextSnapshot))
+                  return memoizedSelection = currentSelection;
+              }
+              return memoizedSelection = nextSnapshot;
+            }
+            currentSelection = memoizedSelection;
+            if (objectIs(memoizedSnapshot, nextSnapshot))
+              return currentSelection;
+            var nextSelection = selector(nextSnapshot);
+            if (void 0 !== isEqual && isEqual(currentSelection, nextSelection))
+              return memoizedSnapshot = nextSnapshot, currentSelection;
+            memoizedSnapshot = nextSnapshot;
+            return memoizedSelection = nextSelection;
+          }
+          var hasMemo = false, memoizedSnapshot, memoizedSelection, maybeGetServerSnapshot = void 0 === getServerSnapshot ? null : getServerSnapshot;
+          return [
+            function() {
+              return memoizedSelector(getSnapshot());
+            },
+            null === maybeGetServerSnapshot ? void 0 : function() {
+              return memoizedSelector(maybeGetServerSnapshot());
+            }
+          ];
+        },
+        [getSnapshot, getServerSnapshot, selector, isEqual]
+      );
+      var value = useSyncExternalStore(subscribe2, instRef[0], instRef[1]);
+      useEffect(
+        function() {
+          inst.hasValue = true;
+          inst.value = value;
+        },
+        [value]
+      );
+      useDebugValue(value);
+      return value;
+    };
+    "undefined" !== typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ && "function" === typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop && __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop(Error());
+  })();
+  return withSelector_development;
+}
+var hasRequiredWithSelector;
+function requireWithSelector() {
+  if (hasRequiredWithSelector) return withSelector.exports;
+  hasRequiredWithSelector = 1;
+  if (process.env.NODE_ENV === "production") {
+    withSelector.exports = requireWithSelector_production();
+  } else {
+    withSelector.exports = requireWithSelector_development();
+  }
+  return withSelector.exports;
+}
+var withSelectorExports = requireWithSelector();
+function useStore(store, selector = (d) => d, options = {}) {
+  const equal = options.equal ?? shallow;
+  const slice = withSelectorExports.useSyncExternalStoreWithSelector(
+    store.subscribe,
+    () => store.state,
+    () => store.state,
+    selector,
+    equal
+  );
+  return slice;
+}
+function shallow(objA, objB) {
+  if (Object.is(objA, objB)) {
+    return true;
+  }
+  if (typeof objA !== "object" || objA === null || typeof objB !== "object" || objB === null) {
+    return false;
+  }
+  if (objA instanceof Map && objB instanceof Map) {
+    if (objA.size !== objB.size) return false;
+    for (const [k2, v2] of objA) {
+      if (!objB.has(k2) || !Object.is(v2, objB.get(k2))) return false;
+    }
+    return true;
+  }
+  if (objA instanceof Set && objB instanceof Set) {
+    if (objA.size !== objB.size) return false;
+    for (const v2 of objA) {
+      if (!objB.has(v2)) return false;
+    }
+    return true;
+  }
+  if (objA instanceof Date && objB instanceof Date) {
+    if (objA.getTime() !== objB.getTime()) return false;
+    return true;
+  }
+  const keysA = getOwnKeys(objA);
+  if (keysA.length !== getOwnKeys(objB).length) {
+    return false;
+  }
+  for (let i = 0; i < keysA.length; i++) {
+    if (!Object.prototype.hasOwnProperty.call(objB, keysA[i]) || !Object.is(objA[keysA[i]], objB[keysA[i]])) {
+      return false;
+    }
+  }
+  return true;
+}
+function getOwnKeys(obj) {
+  return Object.keys(obj).concat(
+    Object.getOwnPropertySymbols(obj)
+  );
+}
+const routerContext = reactExports.createContext(null);
+function getRouterContext() {
+  if (typeof document === "undefined") {
+    return routerContext;
+  }
+  if (window.__TSR_ROUTER_CONTEXT__) {
+    return window.__TSR_ROUTER_CONTEXT__;
+  }
+  window.__TSR_ROUTER_CONTEXT__ = routerContext;
+  return routerContext;
+}
+function useRouter(opts) {
+  const value = reactExports.useContext(getRouterContext());
+  warning(
+    !((opts?.warn ?? true) && !value),
+    "useRouter must be used inside a  component!"
+  );
+  return value;
+}
+function useRouterState(opts) {
+  const contextRouter = useRouter({
+    warn: opts?.router === void 0
+  });
+  const router = opts?.router || contextRouter;
+  const previousResult = reactExports.useRef(void 0);
+  return useStore(router.__store, (state) => {
+    if (opts?.select) {
+      if (opts.structuralSharing ?? router.options.defaultStructuralSharing) {
+        const newSlice = replaceEqualDeep(
+          previousResult.current,
+          opts.select(state)
+        );
+        previousResult.current = newSlice;
+        return newSlice;
+      }
+      return opts.select(state);
+    }
+    return state;
+  });
+}
+const matchContext = reactExports.createContext(void 0);
+const dummyMatchContext = reactExports.createContext(
+  void 0
+);
+const useLayoutEffect = typeof window !== "undefined" ? reactExports.useLayoutEffect : reactExports.useEffect;
+function usePrevious(value) {
+  const ref = reactExports.useRef({
+    value,
+    prev: null
+  });
+  const current = ref.current.value;
+  if (value !== current) {
+    ref.current = {
+      value,
+      prev: current
+    };
+  }
+  return ref.current.prev;
+}
+function useIntersectionObserver(ref, callback, intersectionObserverOptions = {}, options = {}) {
+  reactExports.useEffect(() => {
+    if (!ref.current || options.disabled || typeof IntersectionObserver !== "function") {
+      return;
+    }
+    const observer = new IntersectionObserver(([entry]) => {
+      callback(entry);
+    }, intersectionObserverOptions);
+    observer.observe(ref.current);
+    return () => {
+      observer.disconnect();
+    };
+  }, [callback, intersectionObserverOptions, options.disabled, ref]);
+}
+function useForwardedRef(ref) {
+  const innerRef = reactExports.useRef(null);
+  reactExports.useImperativeHandle(ref, () => innerRef.current, []);
+  return innerRef;
+}
+var reactDom = { exports: {} };
+var reactDom_production = {};
+var hasRequiredReactDom_production;
+function requireReactDom_production() {
+  if (hasRequiredReactDom_production) return reactDom_production;
+  hasRequiredReactDom_production = 1;
+  var React = requireReact();
+  function formatProdErrorMessage(code) {
+    var url = "https://react.dev/errors/" + code;
+    if (1 < arguments.length) {
+      url += "?args[]=" + encodeURIComponent(arguments[1]);
+      for (var i = 2; i < arguments.length; i++)
+        url += "&args[]=" + encodeURIComponent(arguments[i]);
+    }
+    return "Minified React error #" + code + "; visit " + url + " for the full message or use the non-minified dev environment for full errors and additional helpful warnings.";
+  }
+  function noop() {
+  }
+  var Internals = {
+    d: {
+      f: noop,
+      r: function() {
+        throw Error(formatProdErrorMessage(522));
+      },
+      D: noop,
+      C: noop,
+      L: noop,
+      m: noop,
+      X: noop,
+      S: noop,
+      M: noop
+    },
+    p: 0,
+    findDOMNode: null
+  }, REACT_PORTAL_TYPE = Symbol.for("react.portal");
+  function createPortal$1(children, containerInfo, implementation) {
+    var key = 3 < arguments.length && void 0 !== arguments[3] ? arguments[3] : null;
+    return {
+      $$typeof: REACT_PORTAL_TYPE,
+      key: null == key ? null : "" + key,
+      children,
+      containerInfo,
+      implementation
+    };
+  }
+  var ReactSharedInternals = React.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE;
+  function getCrossOriginStringAs(as, input) {
+    if ("font" === as) return "";
+    if ("string" === typeof input)
+      return "use-credentials" === input ? input : "";
+  }
+  reactDom_production.__DOM_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE = Internals;
+  reactDom_production.createPortal = function(children, container) {
+    var key = 2 < arguments.length && void 0 !== arguments[2] ? arguments[2] : null;
+    if (!container || 1 !== container.nodeType && 9 !== container.nodeType && 11 !== container.nodeType)
+      throw Error(formatProdErrorMessage(299));
+    return createPortal$1(children, container, null, key);
+  };
+  reactDom_production.flushSync = function(fn2) {
+    var previousTransition = ReactSharedInternals.T, previousUpdatePriority = Internals.p;
+    try {
+      if (ReactSharedInternals.T = null, Internals.p = 2, fn2) return fn2();
+    } finally {
+      ReactSharedInternals.T = previousTransition, Internals.p = previousUpdatePriority, Internals.d.f();
+    }
+  };
+  reactDom_production.preconnect = function(href, options) {
+    "string" === typeof href && (options ? (options = options.crossOrigin, options = "string" === typeof options ? "use-credentials" === options ? options : "" : void 0) : options = null, Internals.d.C(href, options));
+  };
+  reactDom_production.prefetchDNS = function(href) {
+    "string" === typeof href && Internals.d.D(href);
+  };
+  reactDom_production.preinit = function(href, options) {
+    if ("string" === typeof href && options && "string" === typeof options.as) {
+      var as = options.as, crossOrigin = getCrossOriginStringAs(as, options.crossOrigin), integrity = "string" === typeof options.integrity ? options.integrity : void 0, fetchPriority = "string" === typeof options.fetchPriority ? options.fetchPriority : void 0;
+      "style" === as ? Internals.d.S(
+        href,
+        "string" === typeof options.precedence ? options.precedence : void 0,
+        {
+          crossOrigin,
+          integrity,
+          fetchPriority
+        }
+      ) : "script" === as && Internals.d.X(href, {
+        crossOrigin,
+        integrity,
+        fetchPriority,
+        nonce: "string" === typeof options.nonce ? options.nonce : void 0
+      });
+    }
+  };
+  reactDom_production.preinitModule = function(href, options) {
+    if ("string" === typeof href)
+      if ("object" === typeof options && null !== options) {
+        if (null == options.as || "script" === options.as) {
+          var crossOrigin = getCrossOriginStringAs(
+            options.as,
+            options.crossOrigin
+          );
+          Internals.d.M(href, {
+            crossOrigin,
+            integrity: "string" === typeof options.integrity ? options.integrity : void 0,
+            nonce: "string" === typeof options.nonce ? options.nonce : void 0
+          });
+        }
+      } else null == options && Internals.d.M(href);
+  };
+  reactDom_production.preload = function(href, options) {
+    if ("string" === typeof href && "object" === typeof options && null !== options && "string" === typeof options.as) {
+      var as = options.as, crossOrigin = getCrossOriginStringAs(as, options.crossOrigin);
+      Internals.d.L(href, as, {
+        crossOrigin,
+        integrity: "string" === typeof options.integrity ? options.integrity : void 0,
+        nonce: "string" === typeof options.nonce ? options.nonce : void 0,
+        type: "string" === typeof options.type ? options.type : void 0,
+        fetchPriority: "string" === typeof options.fetchPriority ? options.fetchPriority : void 0,
+        referrerPolicy: "string" === typeof options.referrerPolicy ? options.referrerPolicy : void 0,
+        imageSrcSet: "string" === typeof options.imageSrcSet ? options.imageSrcSet : void 0,
+        imageSizes: "string" === typeof options.imageSizes ? options.imageSizes : void 0,
+        media: "string" === typeof options.media ? options.media : void 0
+      });
+    }
+  };
+  reactDom_production.preloadModule = function(href, options) {
+    if ("string" === typeof href)
+      if (options) {
+        var crossOrigin = getCrossOriginStringAs(options.as, options.crossOrigin);
+        Internals.d.m(href, {
+          as: "string" === typeof options.as && "script" !== options.as ? options.as : void 0,
+          crossOrigin,
+          integrity: "string" === typeof options.integrity ? options.integrity : void 0
+        });
+      } else Internals.d.m(href);
+  };
+  reactDom_production.requestFormReset = function(form) {
+    Internals.d.r(form);
+  };
+  reactDom_production.unstable_batchedUpdates = function(fn2, a) {
+    return fn2(a);
+  };
+  reactDom_production.useFormState = function(action, initialState, permalink) {
+    return ReactSharedInternals.H.useFormState(action, initialState, permalink);
+  };
+  reactDom_production.useFormStatus = function() {
+    return ReactSharedInternals.H.useHostTransitionStatus();
+  };
+  reactDom_production.version = "19.2.3";
+  return reactDom_production;
+}
+var reactDom_development = {};
+var hasRequiredReactDom_development;
+function requireReactDom_development() {
+  if (hasRequiredReactDom_development) return reactDom_development;
+  hasRequiredReactDom_development = 1;
+  "production" !== process.env.NODE_ENV && (function() {
+    function noop() {
+    }
+    function testStringCoercion(value) {
+      return "" + value;
+    }
+    function createPortal$1(children, containerInfo, implementation) {
+      var key = 3 < arguments.length && void 0 !== arguments[3] ? arguments[3] : null;
+      try {
+        testStringCoercion(key);
+        var JSCompiler_inline_result = false;
+      } catch (e) {
+        JSCompiler_inline_result = true;
+      }
+      JSCompiler_inline_result && (console.error(
+        "The provided key is an unsupported type %s. This value must be coerced to a string before using it here.",
+        "function" === typeof Symbol && Symbol.toStringTag && key[Symbol.toStringTag] || key.constructor.name || "Object"
+      ), testStringCoercion(key));
+      return {
+        $$typeof: REACT_PORTAL_TYPE,
+        key: null == key ? null : "" + key,
+        children,
+        containerInfo,
+        implementation
+      };
+    }
+    function getCrossOriginStringAs(as, input) {
+      if ("font" === as) return "";
+      if ("string" === typeof input)
+        return "use-credentials" === input ? input : "";
+    }
+    function getValueDescriptorExpectingObjectForWarning(thing) {
+      return null === thing ? "`null`" : void 0 === thing ? "`undefined`" : "" === thing ? "an empty string" : 'something with type "' + typeof thing + '"';
+    }
+    function getValueDescriptorExpectingEnumForWarning(thing) {
+      return null === thing ? "`null`" : void 0 === thing ? "`undefined`" : "" === thing ? "an empty string" : "string" === typeof thing ? JSON.stringify(thing) : "number" === typeof thing ? "`" + thing + "`" : 'something with type "' + typeof thing + '"';
+    }
+    function resolveDispatcher() {
+      var dispatcher = ReactSharedInternals.H;
+      null === dispatcher && console.error(
+        "Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:\n1. You might have mismatching versions of React and the renderer (such as React DOM)\n2. You might be breaking the Rules of Hooks\n3. You might have more than one copy of React in the same app\nSee https://react.dev/link/invalid-hook-call for tips about how to debug and fix this problem."
+      );
+      return dispatcher;
+    }
+    "undefined" !== typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ && "function" === typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart && __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart(Error());
+    var React = requireReact(), Internals = {
+      d: {
+        f: noop,
+        r: function() {
+          throw Error(
+            "Invalid form element. requestFormReset must be passed a form that was rendered by React."
+          );
+        },
+        D: noop,
+        C: noop,
+        L: noop,
+        m: noop,
+        X: noop,
+        S: noop,
+        M: noop
+      },
+      p: 0,
+      findDOMNode: null
+    }, REACT_PORTAL_TYPE = Symbol.for("react.portal"), ReactSharedInternals = React.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE;
+    "function" === typeof Map && null != Map.prototype && "function" === typeof Map.prototype.forEach && "function" === typeof Set && null != Set.prototype && "function" === typeof Set.prototype.clear && "function" === typeof Set.prototype.forEach || console.error(
+      "React depends on Map and Set built-in types. Make sure that you load a polyfill in older browsers. https://reactjs.org/link/react-polyfills"
+    );
+    reactDom_development.__DOM_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE = Internals;
+    reactDom_development.createPortal = function(children, container) {
+      var key = 2 < arguments.length && void 0 !== arguments[2] ? arguments[2] : null;
+      if (!container || 1 !== container.nodeType && 9 !== container.nodeType && 11 !== container.nodeType)
+        throw Error("Target container is not a DOM element.");
+      return createPortal$1(children, container, null, key);
+    };
+    reactDom_development.flushSync = function(fn2) {
+      var previousTransition = ReactSharedInternals.T, previousUpdatePriority = Internals.p;
+      try {
+        if (ReactSharedInternals.T = null, Internals.p = 2, fn2)
+          return fn2();
+      } finally {
+        ReactSharedInternals.T = previousTransition, Internals.p = previousUpdatePriority, Internals.d.f() && console.error(
+          "flushSync was called from inside a lifecycle method. React cannot flush when React is already rendering. Consider moving this call to a scheduler task or micro task."
+        );
+      }
+    };
+    reactDom_development.preconnect = function(href, options) {
+      "string" === typeof href && href ? null != options && "object" !== typeof options ? console.error(
+        "ReactDOM.preconnect(): Expected the `options` argument (second) to be an object but encountered %s instead. The only supported option at this time is `crossOrigin` which accepts a string.",
+        getValueDescriptorExpectingEnumForWarning(options)
+      ) : null != options && "string" !== typeof options.crossOrigin && console.error(
+        "ReactDOM.preconnect(): Expected the `crossOrigin` option (second argument) to be a string but encountered %s instead. Try removing this option or passing a string value instead.",
+        getValueDescriptorExpectingObjectForWarning(options.crossOrigin)
+      ) : console.error(
+        "ReactDOM.preconnect(): Expected the `href` argument (first) to be a non-empty string but encountered %s instead.",
+        getValueDescriptorExpectingObjectForWarning(href)
+      );
+      "string" === typeof href && (options ? (options = options.crossOrigin, options = "string" === typeof options ? "use-credentials" === options ? options : "" : void 0) : options = null, Internals.d.C(href, options));
+    };
+    reactDom_development.prefetchDNS = function(href) {
+      if ("string" !== typeof href || !href)
+        console.error(
+          "ReactDOM.prefetchDNS(): Expected the `href` argument (first) to be a non-empty string but encountered %s instead.",
+          getValueDescriptorExpectingObjectForWarning(href)
+        );
+      else if (1 < arguments.length) {
+        var options = arguments[1];
+        "object" === typeof options && options.hasOwnProperty("crossOrigin") ? console.error(
+          "ReactDOM.prefetchDNS(): Expected only one argument, `href`, but encountered %s as a second argument instead. This argument is reserved for future options and is currently disallowed. It looks like the you are attempting to set a crossOrigin property for this DNS lookup hint. Browsers do not perform DNS queries using CORS and setting this attribute on the resource hint has no effect. Try calling ReactDOM.prefetchDNS() with just a single string argument, `href`.",
+          getValueDescriptorExpectingEnumForWarning(options)
+        ) : console.error(
+          "ReactDOM.prefetchDNS(): Expected only one argument, `href`, but encountered %s as a second argument instead. This argument is reserved for future options and is currently disallowed. Try calling ReactDOM.prefetchDNS() with just a single string argument, `href`.",
+          getValueDescriptorExpectingEnumForWarning(options)
+        );
+      }
+      "string" === typeof href && Internals.d.D(href);
+    };
+    reactDom_development.preinit = function(href, options) {
+      "string" === typeof href && href ? null == options || "object" !== typeof options ? console.error(
+        "ReactDOM.preinit(): Expected the `options` argument (second) to be an object with an `as` property describing the type of resource to be preinitialized but encountered %s instead.",
+        getValueDescriptorExpectingEnumForWarning(options)
+      ) : "style" !== options.as && "script" !== options.as && console.error(
+        'ReactDOM.preinit(): Expected the `as` property in the `options` argument (second) to contain a valid value describing the type of resource to be preinitialized but encountered %s instead. Valid values for `as` are "style" and "script".',
+        getValueDescriptorExpectingEnumForWarning(options.as)
+      ) : console.error(
+        "ReactDOM.preinit(): Expected the `href` argument (first) to be a non-empty string but encountered %s instead.",
+        getValueDescriptorExpectingObjectForWarning(href)
+      );
+      if ("string" === typeof href && options && "string" === typeof options.as) {
+        var as = options.as, crossOrigin = getCrossOriginStringAs(as, options.crossOrigin), integrity = "string" === typeof options.integrity ? options.integrity : void 0, fetchPriority = "string" === typeof options.fetchPriority ? options.fetchPriority : void 0;
+        "style" === as ? Internals.d.S(
+          href,
+          "string" === typeof options.precedence ? options.precedence : void 0,
+          {
+            crossOrigin,
+            integrity,
+            fetchPriority
+          }
+        ) : "script" === as && Internals.d.X(href, {
+          crossOrigin,
+          integrity,
+          fetchPriority,
+          nonce: "string" === typeof options.nonce ? options.nonce : void 0
+        });
+      }
+    };
+    reactDom_development.preinitModule = function(href, options) {
+      var encountered = "";
+      "string" === typeof href && href || (encountered += " The `href` argument encountered was " + getValueDescriptorExpectingObjectForWarning(href) + ".");
+      void 0 !== options && "object" !== typeof options ? encountered += " The `options` argument encountered was " + getValueDescriptorExpectingObjectForWarning(options) + "." : options && "as" in options && "script" !== options.as && (encountered += " The `as` option encountered was " + getValueDescriptorExpectingEnumForWarning(options.as) + ".");
+      if (encountered)
+        console.error(
+          "ReactDOM.preinitModule(): Expected up to two arguments, a non-empty `href` string and, optionally, an `options` object with a valid `as` property.%s",
+          encountered
+        );
+      else
+        switch (encountered = options && "string" === typeof options.as ? options.as : "script", encountered) {
+          case "script":
+            break;
+          default:
+            encountered = getValueDescriptorExpectingEnumForWarning(encountered), console.error(
+              'ReactDOM.preinitModule(): Currently the only supported "as" type for this function is "script" but received "%s" instead. This warning was generated for `href` "%s". In the future other module types will be supported, aligning with the import-attributes proposal. Learn more here: (https://github.com/tc39/proposal-import-attributes)',
+              encountered,
+              href
+            );
+        }
+      if ("string" === typeof href)
+        if ("object" === typeof options && null !== options) {
+          if (null == options.as || "script" === options.as)
+            encountered = getCrossOriginStringAs(
+              options.as,
+              options.crossOrigin
+            ), Internals.d.M(href, {
+              crossOrigin: encountered,
+              integrity: "string" === typeof options.integrity ? options.integrity : void 0,
+              nonce: "string" === typeof options.nonce ? options.nonce : void 0
+            });
+        } else null == options && Internals.d.M(href);
+    };
+    reactDom_development.preload = function(href, options) {
+      var encountered = "";
+      "string" === typeof href && href || (encountered += " The `href` argument encountered was " + getValueDescriptorExpectingObjectForWarning(href) + ".");
+      null == options || "object" !== typeof options ? encountered += " The `options` argument encountered was " + getValueDescriptorExpectingObjectForWarning(options) + "." : "string" === typeof options.as && options.as || (encountered += " The `as` option encountered was " + getValueDescriptorExpectingObjectForWarning(options.as) + ".");
+      encountered && console.error(
+        'ReactDOM.preload(): Expected two arguments, a non-empty `href` string and an `options` object with an `as` property valid for a `` tag.%s',
+        encountered
+      );
+      if ("string" === typeof href && "object" === typeof options && null !== options && "string" === typeof options.as) {
+        encountered = options.as;
+        var crossOrigin = getCrossOriginStringAs(
+          encountered,
+          options.crossOrigin
+        );
+        Internals.d.L(href, encountered, {
+          crossOrigin,
+          integrity: "string" === typeof options.integrity ? options.integrity : void 0,
+          nonce: "string" === typeof options.nonce ? options.nonce : void 0,
+          type: "string" === typeof options.type ? options.type : void 0,
+          fetchPriority: "string" === typeof options.fetchPriority ? options.fetchPriority : void 0,
+          referrerPolicy: "string" === typeof options.referrerPolicy ? options.referrerPolicy : void 0,
+          imageSrcSet: "string" === typeof options.imageSrcSet ? options.imageSrcSet : void 0,
+          imageSizes: "string" === typeof options.imageSizes ? options.imageSizes : void 0,
+          media: "string" === typeof options.media ? options.media : void 0
+        });
+      }
+    };
+    reactDom_development.preloadModule = function(href, options) {
+      var encountered = "";
+      "string" === typeof href && href || (encountered += " The `href` argument encountered was " + getValueDescriptorExpectingObjectForWarning(href) + ".");
+      void 0 !== options && "object" !== typeof options ? encountered += " The `options` argument encountered was " + getValueDescriptorExpectingObjectForWarning(options) + "." : options && "as" in options && "string" !== typeof options.as && (encountered += " The `as` option encountered was " + getValueDescriptorExpectingObjectForWarning(options.as) + ".");
+      encountered && console.error(
+        'ReactDOM.preloadModule(): Expected two arguments, a non-empty `href` string and, optionally, an `options` object with an `as` property valid for a `` tag.%s',
+        encountered
+      );
+      "string" === typeof href && (options ? (encountered = getCrossOriginStringAs(
+        options.as,
+        options.crossOrigin
+      ), Internals.d.m(href, {
+        as: "string" === typeof options.as && "script" !== options.as ? options.as : void 0,
+        crossOrigin: encountered,
+        integrity: "string" === typeof options.integrity ? options.integrity : void 0
+      })) : Internals.d.m(href));
+    };
+    reactDom_development.requestFormReset = function(form) {
+      Internals.d.r(form);
+    };
+    reactDom_development.unstable_batchedUpdates = function(fn2, a) {
+      return fn2(a);
+    };
+    reactDom_development.useFormState = function(action, initialState, permalink) {
+      return resolveDispatcher().useFormState(action, initialState, permalink);
+    };
+    reactDom_development.useFormStatus = function() {
+      return resolveDispatcher().useHostTransitionStatus();
+    };
+    reactDom_development.version = "19.2.3";
+    "undefined" !== typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ && "function" === typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop && __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop(Error());
+  })();
+  return reactDom_development;
+}
+var hasRequiredReactDom;
+function requireReactDom() {
+  if (hasRequiredReactDom) return reactDom.exports;
+  hasRequiredReactDom = 1;
+  function checkDCE() {
+    if (typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ === "undefined" || typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE !== "function") {
+      return;
+    }
+    if (process.env.NODE_ENV !== "production") {
+      throw new Error("^_^");
+    }
+    try {
+      __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(checkDCE);
+    } catch (err) {
+      console.error(err);
+    }
+  }
+  if (process.env.NODE_ENV === "production") {
+    checkDCE();
+    reactDom.exports = requireReactDom_production();
+  } else {
+    reactDom.exports = requireReactDom_development();
+  }
+  return reactDom.exports;
+}
+function Transitioner() {
+  const router = useRouter();
+  const mountLoadForRouter = reactExports.useRef({ router, mounted: false });
+  const [isTransitioning, setIsTransitioning] = reactExports.useState(false);
+  const { hasPendingMatches, isLoading } = useRouterState({
+    select: (s) => ({
+      isLoading: s.isLoading,
+      hasPendingMatches: s.matches.some((d) => d.status === "pending")
+    }),
+    structuralSharing: true
+  });
+  const previousIsLoading = usePrevious(isLoading);
+  const isAnyPending = isLoading || isTransitioning || hasPendingMatches;
+  const previousIsAnyPending = usePrevious(isAnyPending);
+  const isPagePending = isLoading || hasPendingMatches;
+  const previousIsPagePending = usePrevious(isPagePending);
+  router.startTransition = (fn2) => {
+    setIsTransitioning(true);
+    reactExports.startTransition(() => {
+      fn2();
+      setIsTransitioning(false);
+    });
+  };
+  reactExports.useEffect(() => {
+    const unsub = router.history.subscribe(router.load);
+    const nextLocation = router.buildLocation({
+      to: router.latestLocation.pathname,
+      search: true,
+      params: true,
+      hash: true,
+      state: true,
+      _includeValidateSearch: true
+    });
+    if (trimPathRight(router.latestLocation.publicHref) !== trimPathRight(nextLocation.publicHref)) {
+      router.commitLocation({ ...nextLocation, replace: true });
+    }
+    return () => {
+      unsub();
+    };
+  }, [router, router.history]);
+  useLayoutEffect(() => {
+    if (
+      // if we are hydrating from SSR, loading is triggered in ssr-client
+      typeof window !== "undefined" && router.ssr || mountLoadForRouter.current.router === router && mountLoadForRouter.current.mounted
+    ) {
+      return;
+    }
+    mountLoadForRouter.current = { router, mounted: true };
+    const tryLoad = async () => {
+      try {
+        await router.load();
+      } catch (err) {
+        console.error(err);
+      }
+    };
+    tryLoad();
+  }, [router]);
+  useLayoutEffect(() => {
+    if (previousIsLoading && !isLoading) {
+      router.emit({
+        type: "onLoad",
+        // When the new URL has committed, when the new matches have been loaded into state.matches
+        ...getLocationChangeInfo(router.state)
+      });
+    }
+  }, [previousIsLoading, router, isLoading]);
+  useLayoutEffect(() => {
+    if (previousIsPagePending && !isPagePending) {
+      router.emit({
+        type: "onBeforeRouteMount",
+        ...getLocationChangeInfo(router.state)
+      });
+    }
+  }, [isPagePending, previousIsPagePending, router]);
+  useLayoutEffect(() => {
+    if (previousIsAnyPending && !isAnyPending) {
+      const changeInfo = getLocationChangeInfo(router.state);
+      router.emit({
+        type: "onResolved",
+        ...changeInfo
+      });
+      router.__store.setState((s) => ({
+        ...s,
+        status: "idle",
+        resolvedLocation: s.location
+      }));
+      if (changeInfo.hrefChanged) {
+        handleHashScroll(router);
+      }
+    }
+  }, [isAnyPending, previousIsAnyPending, router]);
+  return null;
+}
+function CatchNotFound(props) {
+  const resetKey = useRouterState({
+    select: (s) => `not-found-${s.location.pathname}-${s.status}`
+  });
+  return /* @__PURE__ */ jsxRuntimeExports.jsx(
+    CatchBoundary,
+    {
+      getResetKey: () => resetKey,
+      onCatch: (error2, errorInfo) => {
+        if (isNotFound(error2)) {
+          props.onCatch?.(error2, errorInfo);
+        } else {
+          throw error2;
+        }
+      },
+      errorComponent: ({ error: error2 }) => {
+        if (isNotFound(error2)) {
+          return props.fallback?.(error2);
+        } else {
+          throw error2;
+        }
+      },
+      children: props.children
+    }
+  );
+}
+function DefaultGlobalNotFound() {
+  return /* @__PURE__ */ jsxRuntimeExports.jsx("p", { children: "Not Found" });
+}
+function SafeFragment(props) {
+  return /* @__PURE__ */ jsxRuntimeExports.jsx(jsxRuntimeExports.Fragment, { children: props.children });
+}
+function renderRouteNotFound(router, route, data) {
+  if (!route.options.notFoundComponent) {
+    if (router.options.defaultNotFoundComponent) {
+      return /* @__PURE__ */ jsxRuntimeExports.jsx(router.options.defaultNotFoundComponent, { ...data });
+    }
+    if (process.env.NODE_ENV === "development") {
+      warning(
+        route.options.notFoundComponent,
+        `A notFoundError was encountered on the route with ID "${route.id}", but a notFoundComponent option was not configured, nor was a router level defaultNotFoundComponent configured. Consider configuring at least one of these to avoid TanStack Router's overly generic defaultNotFoundComponent (

Not Found

)` + ); + } + return /* @__PURE__ */ jsxRuntimeExports.jsx(DefaultGlobalNotFound, {}); + } + return /* @__PURE__ */ jsxRuntimeExports.jsx(route.options.notFoundComponent, { ...data }); +} +function ScriptOnce({ children }) { + const router = useRouter(); + if (!router.isServer) { + return null; + } + return /* @__PURE__ */ jsxRuntimeExports.jsx( + "script", + { + nonce: router.options.ssr?.nonce, + dangerouslySetInnerHTML: { + __html: children + ";document.currentScript.remove()" + } + } + ); +} +function ScrollRestoration() { + const router = useRouter(); + if (!router.isScrollRestoring || !router.isServer) { + return null; + } + if (typeof router.options.scrollRestoration === "function") { + const shouldRestore = router.options.scrollRestoration({ + location: router.latestLocation + }); + if (!shouldRestore) { + return null; + } + } + const getKey = router.options.getScrollRestorationKey || defaultGetScrollRestorationKey; + const userKey = getKey(router.latestLocation); + const resolvedKey = userKey !== defaultGetScrollRestorationKey(router.latestLocation) ? userKey : void 0; + const restoreScrollOptions = { + storageKey, + shouldScrollRestoration: true + }; + if (resolvedKey) { + restoreScrollOptions.key = resolvedKey; + } + return /* @__PURE__ */ jsxRuntimeExports.jsx( + ScriptOnce, + { + children: `(${restoreScroll.toString()})(${JSON.stringify(restoreScrollOptions)})` + } + ); +} +const Match = reactExports.memo(function MatchImpl({ + matchId +}) { + const router = useRouter(); + const matchState = useRouterState({ + select: (s) => { + const match = s.matches.find((d) => d.id === matchId); + invariant( + match, + `Could not find match for matchId "${matchId}". Please file an issue!` + ); + return { + routeId: match.routeId, + ssr: match.ssr, + _displayPending: match._displayPending + }; + }, + structuralSharing: true + }); + const route = router.routesById[matchState.routeId]; + const PendingComponent = route.options.pendingComponent ?? router.options.defaultPendingComponent; + const pendingElement = PendingComponent ? /* @__PURE__ */ jsxRuntimeExports.jsx(PendingComponent, {}) : null; + const routeErrorComponent = route.options.errorComponent ?? router.options.defaultErrorComponent; + const routeOnCatch = route.options.onCatch ?? router.options.defaultOnCatch; + const routeNotFoundComponent = route.isRoot ? ( + // If it's the root route, use the globalNotFound option, with fallback to the notFoundRoute's component + route.options.notFoundComponent ?? router.options.notFoundRoute?.options.component + ) : route.options.notFoundComponent; + const resolvedNoSsr = matchState.ssr === false || matchState.ssr === "data-only"; + const ResolvedSuspenseBoundary = ( + // If we're on the root route, allow forcefully wrapping in suspense + (!route.isRoot || route.options.wrapInSuspense || resolvedNoSsr) && (route.options.wrapInSuspense ?? PendingComponent ?? (route.options.errorComponent?.preload || resolvedNoSsr)) ? reactExports.Suspense : SafeFragment + ); + const ResolvedCatchBoundary = routeErrorComponent ? CatchBoundary : SafeFragment; + const ResolvedNotFoundBoundary = routeNotFoundComponent ? CatchNotFound : SafeFragment; + const resetKey = useRouterState({ + select: (s) => s.loadedAt + }); + const parentRouteId = useRouterState({ + select: (s) => { + const index = s.matches.findIndex((d) => d.id === matchId); + return s.matches[index - 1]?.routeId; + } + }); + const ShellComponent = route.isRoot ? route.options.shellComponent ?? SafeFragment : SafeFragment; + return /* @__PURE__ */ jsxRuntimeExports.jsxs(ShellComponent, { children: [ + /* @__PURE__ */ jsxRuntimeExports.jsx(matchContext.Provider, { value: matchId, children: /* @__PURE__ */ jsxRuntimeExports.jsx(ResolvedSuspenseBoundary, { fallback: pendingElement, children: /* @__PURE__ */ jsxRuntimeExports.jsx( + ResolvedCatchBoundary, + { + getResetKey: () => resetKey, + errorComponent: routeErrorComponent || ErrorComponent, + onCatch: (error2, errorInfo) => { + if (isNotFound(error2)) throw error2; + warning(false, `Error in route match: ${matchId}`); + routeOnCatch?.(error2, errorInfo); + }, + children: /* @__PURE__ */ jsxRuntimeExports.jsx( + ResolvedNotFoundBoundary, + { + fallback: (error2) => { + if (!routeNotFoundComponent || error2.routeId && error2.routeId !== matchState.routeId || !error2.routeId && !route.isRoot) + throw error2; + return reactExports.createElement(routeNotFoundComponent, error2); + }, + children: resolvedNoSsr || matchState._displayPending ? /* @__PURE__ */ jsxRuntimeExports.jsx(ClientOnly, { fallback: pendingElement, children: /* @__PURE__ */ jsxRuntimeExports.jsx(MatchInner, { matchId }) }) : /* @__PURE__ */ jsxRuntimeExports.jsx(MatchInner, { matchId }) + } + ) + } + ) }) }), + parentRouteId === rootRouteId && router.options.scrollRestoration ? /* @__PURE__ */ jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment, { children: [ + /* @__PURE__ */ jsxRuntimeExports.jsx(OnRendered, {}), + /* @__PURE__ */ jsxRuntimeExports.jsx(ScrollRestoration, {}) + ] }) : null + ] }); +}); +function OnRendered() { + const router = useRouter(); + const prevLocationRef = reactExports.useRef( + void 0 + ); + return /* @__PURE__ */ jsxRuntimeExports.jsx( + "script", + { + suppressHydrationWarning: true, + ref: (el) => { + if (el && (prevLocationRef.current === void 0 || prevLocationRef.current.href !== router.latestLocation.href)) { + router.emit({ + type: "onRendered", + ...getLocationChangeInfo(router.state) + }); + prevLocationRef.current = router.latestLocation; + } + } + }, + router.latestLocation.state.__TSR_key + ); +} +const MatchInner = reactExports.memo(function MatchInnerImpl({ + matchId +}) { + const router = useRouter(); + const { match, key, routeId } = useRouterState({ + select: (s) => { + const match2 = s.matches.find((d) => d.id === matchId); + const routeId2 = match2.routeId; + const remountFn = router.routesById[routeId2].options.remountDeps ?? router.options.defaultRemountDeps; + const remountDeps = remountFn?.({ + routeId: routeId2, + loaderDeps: match2.loaderDeps, + params: match2._strictParams, + search: match2._strictSearch + }); + const key2 = remountDeps ? JSON.stringify(remountDeps) : void 0; + return { + key: key2, + routeId: routeId2, + match: { + id: match2.id, + status: match2.status, + error: match2.error, + invalid: match2.invalid, + _forcePending: match2._forcePending, + _displayPending: match2._displayPending + } + }; + }, + structuralSharing: true + }); + const route = router.routesById[routeId]; + const out = reactExports.useMemo(() => { + const Comp = route.options.component ?? router.options.defaultComponent; + if (Comp) { + return /* @__PURE__ */ jsxRuntimeExports.jsx(Comp, {}, key); + } + return /* @__PURE__ */ jsxRuntimeExports.jsx(Outlet, {}); + }, [key, route.options.component, router.options.defaultComponent]); + if (match._displayPending) { + throw router.getMatch(match.id)?._nonReactive.displayPendingPromise; + } + if (match._forcePending) { + throw router.getMatch(match.id)?._nonReactive.minPendingPromise; + } + if (match.status === "pending") { + const pendingMinMs = route.options.pendingMinMs ?? router.options.defaultPendingMinMs; + if (pendingMinMs) { + const routerMatch = router.getMatch(match.id); + if (routerMatch && !routerMatch._nonReactive.minPendingPromise) { + if (!router.isServer) { + const minPendingPromise = createControlledPromise(); + routerMatch._nonReactive.minPendingPromise = minPendingPromise; + setTimeout(() => { + minPendingPromise.resolve(); + routerMatch._nonReactive.minPendingPromise = void 0; + }, pendingMinMs); + } + } + } + throw router.getMatch(match.id)?._nonReactive.loadPromise; + } + if (match.status === "notFound") { + invariant(isNotFound(match.error), "Expected a notFound error"); + return renderRouteNotFound(router, route, match.error); + } + if (match.status === "redirected") { + invariant(isRedirect(match.error), "Expected a redirect error"); + throw router.getMatch(match.id)?._nonReactive.loadPromise; + } + if (match.status === "error") { + if (router.isServer) { + const RouteErrorComponent = (route.options.errorComponent ?? router.options.defaultErrorComponent) || ErrorComponent; + return /* @__PURE__ */ jsxRuntimeExports.jsx( + RouteErrorComponent, + { + error: match.error, + reset: void 0, + info: { + componentStack: "" + } + } + ); + } + throw match.error; + } + return out; +}); +const Outlet = reactExports.memo(function OutletImpl() { + const router = useRouter(); + const matchId = reactExports.useContext(matchContext); + const routeId = useRouterState({ + select: (s) => s.matches.find((d) => d.id === matchId)?.routeId + }); + const route = router.routesById[routeId]; + const parentGlobalNotFound = useRouterState({ + select: (s) => { + const matches = s.matches; + const parentMatch = matches.find((d) => d.id === matchId); + invariant( + parentMatch, + `Could not find parent match for matchId "${matchId}"` + ); + return parentMatch.globalNotFound; + } + }); + const childMatchId = useRouterState({ + select: (s) => { + const matches = s.matches; + const index = matches.findIndex((d) => d.id === matchId); + return matches[index + 1]?.id; + } + }); + const pendingElement = router.options.defaultPendingComponent ? /* @__PURE__ */ jsxRuntimeExports.jsx(router.options.defaultPendingComponent, {}) : null; + if (parentGlobalNotFound) { + return renderRouteNotFound(router, route, void 0); + } + if (!childMatchId) { + return null; + } + const nextMatch = /* @__PURE__ */ jsxRuntimeExports.jsx(Match, { matchId: childMatchId }); + if (routeId === rootRouteId) { + return /* @__PURE__ */ jsxRuntimeExports.jsx(reactExports.Suspense, { fallback: pendingElement, children: nextMatch }); + } + return nextMatch; +}); +function Matches() { + const router = useRouter(); + const rootRoute = router.routesById[rootRouteId]; + const PendingComponent = rootRoute.options.pendingComponent ?? router.options.defaultPendingComponent; + const pendingElement = PendingComponent ? /* @__PURE__ */ jsxRuntimeExports.jsx(PendingComponent, {}) : null; + const ResolvedSuspense = router.isServer || typeof document !== "undefined" && router.ssr ? SafeFragment : reactExports.Suspense; + const inner = /* @__PURE__ */ jsxRuntimeExports.jsxs(ResolvedSuspense, { fallback: pendingElement, children: [ + !router.isServer && /* @__PURE__ */ jsxRuntimeExports.jsx(Transitioner, {}), + /* @__PURE__ */ jsxRuntimeExports.jsx(MatchesInner, {}) + ] }); + return router.options.InnerWrap ? /* @__PURE__ */ jsxRuntimeExports.jsx(router.options.InnerWrap, { children: inner }) : inner; +} +function MatchesInner() { + const router = useRouter(); + const matchId = useRouterState({ + select: (s) => { + return s.matches[0]?.id; + } + }); + const resetKey = useRouterState({ + select: (s) => s.loadedAt + }); + const matchComponent = matchId ? /* @__PURE__ */ jsxRuntimeExports.jsx(Match, { matchId }) : null; + return /* @__PURE__ */ jsxRuntimeExports.jsx(matchContext.Provider, { value: matchId, children: router.options.disableGlobalCatchBoundary ? matchComponent : /* @__PURE__ */ jsxRuntimeExports.jsx( + CatchBoundary, + { + getResetKey: () => resetKey, + errorComponent: ErrorComponent, + onCatch: (error2) => { + warning( + false, + `The following error wasn't caught by any route! At the very least, consider setting an 'errorComponent' in your RootRoute!` + ); + warning(false, error2.message || error2.toString()); + }, + children: matchComponent + } + ) }); +} +function RouterContextProvider({ + router, + children, + ...rest +}) { + if (Object.keys(rest).length > 0) { + router.update({ + ...router.options, + ...rest, + context: { + ...router.options.context, + ...rest.context + } + }); + } + const routerContext2 = getRouterContext(); + const provider = /* @__PURE__ */ jsxRuntimeExports.jsx(routerContext2.Provider, { value: router, children }); + if (router.options.Wrap) { + return /* @__PURE__ */ jsxRuntimeExports.jsx(router.options.Wrap, { children: provider }); + } + return provider; +} +function RouterProvider({ router, ...rest }) { + return /* @__PURE__ */ jsxRuntimeExports.jsx(RouterContextProvider, { router, ...rest, children: /* @__PURE__ */ jsxRuntimeExports.jsx(Matches, {}) }); +} +function StartServer(props) { + return /* @__PURE__ */ jsxRuntimeExports.jsx(RouterProvider, { router: props.router }); +} +function splitSetCookieString(cookiesString) { + if (Array.isArray(cookiesString)) { + return cookiesString.flatMap((c2) => splitSetCookieString(c2)); + } + if (typeof cookiesString !== "string") { + return []; + } + const cookiesStrings = []; + let pos = 0; + let start; + let ch; + let lastComma; + let nextStart; + let cookiesSeparatorFound; + const skipWhitespace = () => { + while (pos < cookiesString.length && /\s/.test(cookiesString.charAt(pos))) { + pos += 1; + } + return pos < cookiesString.length; + }; + const notSpecialChar = () => { + ch = cookiesString.charAt(pos); + return ch !== "=" && ch !== ";" && ch !== ","; + }; + while (pos < cookiesString.length) { + start = pos; + cookiesSeparatorFound = false; + while (skipWhitespace()) { + ch = cookiesString.charAt(pos); + if (ch === ",") { + lastComma = pos; + pos += 1; + skipWhitespace(); + nextStart = pos; + while (pos < cookiesString.length && notSpecialChar()) { + pos += 1; + } + if (pos < cookiesString.length && cookiesString.charAt(pos) === "=") { + cookiesSeparatorFound = true; + pos = nextStart; + cookiesStrings.push(cookiesString.slice(start, lastComma)); + start = pos; + } else { + pos = lastComma + 1; + } + } else { + pos += 1; + } + } + if (!cookiesSeparatorFound || pos >= cookiesString.length) { + cookiesStrings.push(cookiesString.slice(start)); + } + } + return cookiesStrings; +} +function toHeadersInstance(init) { + if (init instanceof Headers) { + return new Headers(init); + } else if (Array.isArray(init)) { + return new Headers(init); + } else if (typeof init === "object") { + return new Headers(init); + } else { + return new Headers(); + } +} +function mergeHeaders(...headers) { + return headers.reduce((acc, header) => { + const headersInstance = toHeadersInstance(header); + for (const [key, value] of headersInstance.entries()) { + if (key === "set-cookie") { + const splitCookies = splitSetCookieString(value); + splitCookies.forEach((cookie) => acc.append("set-cookie", cookie)); + } else { + acc.set(key, value); + } + } + return acc; + }, new Headers()); +} +const minifiedTsrBootStrapScript = "self.$_TSR={h(){this.hydrated=!0,this.c()},e(){this.streamEnded=!0,this.c()},c(){this.hydrated&&this.streamEnded&&(delete self.$_TSR,delete self.$R.tsr)},p(e){this.initialized?e():this.buffer.push(e)},buffer:[]};\n"; +const SCOPE_ID = "tsr"; +function dehydrateMatch(match) { + const dehydratedMatch = { + i: match.id, + u: match.updatedAt, + s: match.status + }; + const properties = [ + ["__beforeLoadContext", "b"], + ["loaderData", "l"], + ["error", "e"], + ["ssr", "ssr"] + ]; + for (const [key, shorthand] of properties) { + if (match[key] !== void 0) { + dehydratedMatch[shorthand] = match[key]; + } + } + return dehydratedMatch; +} +const INITIAL_SCRIPTS = [ + ln(SCOPE_ID), + minifiedTsrBootStrapScript +]; +class ScriptBuffer { + constructor(router) { + this._scriptBarrierLifted = false; + this._cleanedUp = false; + this._pendingMicrotask = false; + this.router = router; + this._queue = INITIAL_SCRIPTS.slice(); + } + enqueue(script) { + if (this._cleanedUp) return; + this._queue.push(script); + if (this._scriptBarrierLifted && !this._pendingMicrotask) { + this._pendingMicrotask = true; + queueMicrotask(() => { + this._pendingMicrotask = false; + this.injectBufferedScripts(); + }); + } + } + liftBarrier() { + if (this._scriptBarrierLifted || this._cleanedUp) return; + this._scriptBarrierLifted = true; + if (this._queue.length > 0 && !this._pendingMicrotask) { + this._pendingMicrotask = true; + queueMicrotask(() => { + this._pendingMicrotask = false; + this.injectBufferedScripts(); + }); + } + } + /** + * Flushes any pending scripts synchronously. + * Call this before emitting onSerializationFinished to ensure all scripts are injected. + * + * IMPORTANT: Only injects if the barrier has been lifted. Before the barrier is lifted, + * scripts should remain in the queue so takeBufferedScripts() can retrieve them + */ + flush() { + if (!this._scriptBarrierLifted) return; + if (this._cleanedUp) return; + this._pendingMicrotask = false; + const scriptsToInject = this.takeAll(); + if (scriptsToInject && this.router?.serverSsr) { + this.router.serverSsr.injectScript(scriptsToInject); + } + } + takeAll() { + const bufferedScripts = this._queue; + this._queue = []; + if (bufferedScripts.length === 0) { + return void 0; + } + return bufferedScripts.join(";") + ";document.currentScript.remove()"; + } + injectBufferedScripts() { + if (this._cleanedUp) return; + if (this._queue.length === 0) return; + const scriptsToInject = this.takeAll(); + if (scriptsToInject && this.router?.serverSsr) { + this.router.serverSsr.injectScript(scriptsToInject); + } + } + cleanup() { + this._cleanedUp = true; + this._queue = []; + this.router = void 0; + } +} +function attachRouterServerSsrUtils({ + router, + manifest: manifest2 +}) { + router.ssr = { + manifest: manifest2 + }; + let _dehydrated = false; + let _serializationFinished = false; + const renderFinishedListeners = []; + const serializationFinishedListeners = []; + const scriptBuffer = new ScriptBuffer(router); + let injectedHtmlBuffer = []; + router.serverSsr = { + injectHtml: (html) => { + if (!html) return; + injectedHtmlBuffer.push(html); + router.emit({ + type: "onInjectedHtml" + }); + }, + injectScript: (script) => { + if (!script) return; + const html = `${script}<\/script>`; + router.serverSsr.injectHtml(html); + }, + dehydrate: async () => { + invariant(!_dehydrated, "router is already dehydrated!"); + let matchesToDehydrate = router.state.matches; + if (router.isShell()) { + matchesToDehydrate = matchesToDehydrate.slice(0, 1); + } + const matches = matchesToDehydrate.map(dehydrateMatch); + let manifestToDehydrate = void 0; + if (manifest2) { + const currentRouteIds = new Set( + router.state.matches.map((k2) => k2.routeId) + ); + const filteredRoutes = Object.fromEntries( + Object.entries(manifest2.routes).flatMap( + ([routeId, routeManifest]) => { + if (currentRouteIds.has(routeId)) { + return [[routeId, routeManifest]]; + } else if (routeManifest.assets && routeManifest.assets.length > 0) { + return [ + [ + routeId, + { + assets: routeManifest.assets + } + ] + ]; + } + return []; + } + ) + ); + manifestToDehydrate = { + routes: filteredRoutes + }; + } + const dehydratedRouter = { + manifest: manifestToDehydrate, + matches + }; + const lastMatchId = matchesToDehydrate[matchesToDehydrate.length - 1]?.id; + if (lastMatchId) { + dehydratedRouter.lastMatchId = lastMatchId; + } + const dehydratedData = await router.options.dehydrate?.(); + if (dehydratedData) { + dehydratedRouter.dehydratedData = dehydratedData; + } + _dehydrated = true; + const trackPlugins = { didRun: false }; + const serializationAdapters = router.options.serializationAdapters; + const plugins = serializationAdapters ? serializationAdapters.map((t) => makeSsrSerovalPlugin(t, trackPlugins)).concat(defaultSerovalPlugins) : defaultSerovalPlugins; + const signalSerializationComplete = () => { + _serializationFinished = true; + try { + serializationFinishedListeners.forEach((l) => l()); + router.emit({ type: "onSerializationFinished" }); + } catch (err) { + console.error("Serialization listener error:", err); + } finally { + serializationFinishedListeners.length = 0; + renderFinishedListeners.length = 0; + } + }; + an(dehydratedRouter, { + refs: /* @__PURE__ */ new Map(), + plugins, + onSerialize: (data, initial) => { + let serialized = initial ? GLOBAL_TSR + ".router=" + data : data; + if (trackPlugins.didRun) { + serialized = GLOBAL_TSR + ".p(()=>" + serialized + ")"; + } + scriptBuffer.enqueue(serialized); + }, + scopeId: SCOPE_ID, + onDone: () => { + scriptBuffer.enqueue(GLOBAL_TSR + ".e()"); + scriptBuffer.flush(); + signalSerializationComplete(); + }, + onError: (err) => { + console.error("Serialization error:", err); + signalSerializationComplete(); + } + }); + }, + isDehydrated() { + return _dehydrated; + }, + isSerializationFinished() { + return _serializationFinished; + }, + onRenderFinished: (listener) => renderFinishedListeners.push(listener), + onSerializationFinished: (listener) => serializationFinishedListeners.push(listener), + setRenderFinished: () => { + try { + renderFinishedListeners.forEach((l) => l()); + } catch (err) { + console.error("Error in render finished listener:", err); + } finally { + renderFinishedListeners.length = 0; + } + scriptBuffer.liftBarrier(); + }, + takeBufferedScripts() { + const scripts = scriptBuffer.takeAll(); + const serverBufferedScript = { + tag: "script", + attrs: { + nonce: router.options.ssr?.nonce, + className: "$tsr", + id: TSR_SCRIPT_BARRIER_ID + }, + children: scripts + }; + return serverBufferedScript; + }, + liftScriptBarrier() { + scriptBuffer.liftBarrier(); + }, + takeBufferedHtml() { + if (injectedHtmlBuffer.length === 0) { + return void 0; + } + const buffered = injectedHtmlBuffer.join(""); + injectedHtmlBuffer = []; + return buffered; + }, + cleanup() { + if (!router.serverSsr) return; + renderFinishedListeners.length = 0; + serializationFinishedListeners.length = 0; + injectedHtmlBuffer = []; + scriptBuffer.cleanup(); + router.serverSsr = void 0; + } + }; +} +function getOrigin(request) { + const originHeader = request.headers.get("Origin"); + if (originHeader) { + try { + new URL(originHeader); + return originHeader; + } catch { + } + } + try { + return new URL(request.url).origin; + } catch { + } + return "http://localhost"; +} +function defineHandlerCallback(handler) { + return handler; +} +function transformReadableStreamWithRouter(router, routerStream) { + return transformStreamWithRouter(router, routerStream); +} +function transformPipeableStreamWithRouter(router, routerStream) { + return Readable.fromWeb( + transformStreamWithRouter(router, Readable.toWeb(routerStream)) + ); +} +const BODY_END_TAG = ""; +const HTML_END_TAG = ""; +const MIN_CLOSING_TAG_LENGTH = 4; +const DEFAULT_SERIALIZATION_TIMEOUT_MS = 6e4; +const DEFAULT_LIFETIME_TIMEOUT_MS = 6e4; +const textEncoder$2 = new TextEncoder(); +function findLastClosingTagEnd(str) { + const len = str.length; + if (len < MIN_CLOSING_TAG_LENGTH) return -1; + let i = len - 1; + while (i >= MIN_CLOSING_TAG_LENGTH - 1) { + if (str.charCodeAt(i) === 62) { + let j2 = i - 1; + while (j2 >= 1) { + const code = str.charCodeAt(j2); + if (code >= 97 && code <= 122 || // a-z + code >= 65 && code <= 90 || // A-Z + code >= 48 && code <= 57 || // 0-9 + code === 95 || // _ + code === 58 || // : + code === 46 || // . + code === 45) { + j2--; + } else { + break; + } + } + const tagNameStart = j2 + 1; + if (tagNameStart < i) { + const startCode = str.charCodeAt(tagNameStart); + if (startCode >= 97 && startCode <= 122 || startCode >= 65 && startCode <= 90) { + if (j2 >= 1 && str.charCodeAt(j2) === 47 && str.charCodeAt(j2 - 1) === 60) { + return i + 1; + } + } + } + } + i--; + } + return -1; +} +function transformStreamWithRouter(router, appStream, opts) { + let stopListeningToInjectedHtml; + let stopListeningToSerializationFinished; + let serializationTimeoutHandle; + let lifetimeTimeoutHandle; + let cleanedUp = false; + let controller; + let isStreamClosed = false; + const serializationAlreadyFinished = router.serverSsr?.isSerializationFinished() ?? false; + function cleanup() { + if (cleanedUp) return; + cleanedUp = true; + try { + stopListeningToInjectedHtml?.(); + stopListeningToSerializationFinished?.(); + } catch (e) { + } + stopListeningToInjectedHtml = void 0; + stopListeningToSerializationFinished = void 0; + if (serializationTimeoutHandle !== void 0) { + clearTimeout(serializationTimeoutHandle); + serializationTimeoutHandle = void 0; + } + if (lifetimeTimeoutHandle !== void 0) { + clearTimeout(lifetimeTimeoutHandle); + lifetimeTimeoutHandle = void 0; + } + pendingRouterHtmlParts = []; + leftover = ""; + pendingClosingTags = ""; + router.serverSsr?.cleanup(); + } + const textDecoder = new TextDecoder(); + function safeEnqueue(chunk) { + if (isStreamClosed) return; + if (typeof chunk === "string") { + controller.enqueue(textEncoder$2.encode(chunk)); + } else { + controller.enqueue(chunk); + } + } + function safeClose() { + if (isStreamClosed) return; + isStreamClosed = true; + try { + controller.close(); + } catch { + } + } + function safeError(error2) { + if (isStreamClosed) return; + isStreamClosed = true; + try { + controller.error(error2); + } catch { + } + } + const stream = new ReadableStream$1({ + start(c2) { + controller = c2; + }, + cancel() { + isStreamClosed = true; + cleanup(); + } + }); + let isAppRendering = true; + let streamBarrierLifted = false; + let leftover = ""; + let pendingClosingTags = ""; + let serializationFinished = serializationAlreadyFinished; + let pendingRouterHtmlParts = []; + const bufferedHtml = router.serverSsr?.takeBufferedHtml(); + if (bufferedHtml) { + pendingRouterHtmlParts.push(bufferedHtml); + } + function flushPendingRouterHtml() { + if (pendingRouterHtmlParts.length > 0) { + safeEnqueue(pendingRouterHtmlParts.join("")); + pendingRouterHtmlParts = []; + } + } + function tryFinish() { + if (isAppRendering || !serializationFinished) return; + if (cleanedUp || isStreamClosed) return; + if (serializationTimeoutHandle !== void 0) { + clearTimeout(serializationTimeoutHandle); + serializationTimeoutHandle = void 0; + } + const decoderRemainder = textDecoder.decode(); + if (leftover) safeEnqueue(leftover); + if (decoderRemainder) safeEnqueue(decoderRemainder); + flushPendingRouterHtml(); + if (pendingClosingTags) safeEnqueue(pendingClosingTags); + safeClose(); + cleanup(); + } + const lifetimeMs = DEFAULT_LIFETIME_TIMEOUT_MS; + lifetimeTimeoutHandle = setTimeout(() => { + if (!cleanedUp && !isStreamClosed) { + console.warn( + `SSR stream transform exceeded maximum lifetime (${lifetimeMs}ms), forcing cleanup` + ); + safeError(new Error("Stream lifetime exceeded")); + cleanup(); + } + }, lifetimeMs); + if (!serializationAlreadyFinished) { + stopListeningToInjectedHtml = router.subscribe("onInjectedHtml", () => { + if (cleanedUp || isStreamClosed) return; + const html = router.serverSsr?.takeBufferedHtml(); + if (!html) return; + if (isAppRendering) { + pendingRouterHtmlParts.push(html); + } else { + safeEnqueue(html); + } + }); + stopListeningToSerializationFinished = router.subscribe( + "onSerializationFinished", + () => { + serializationFinished = true; + tryFinish(); + } + ); + } + (async () => { + const reader = appStream.getReader(); + try { + while (true) { + const { done, value } = await reader.read(); + if (done) break; + if (cleanedUp || isStreamClosed) return; + const text = value instanceof Uint8Array ? textDecoder.decode(value, { stream: true }) : String(value); + const chunkString = leftover + text; + if (!streamBarrierLifted) { + if (chunkString.includes(TSR_SCRIPT_BARRIER_ID)) { + streamBarrierLifted = true; + router.serverSsr?.liftScriptBarrier(); + } + } + const bodyEndIndex = chunkString.indexOf(BODY_END_TAG); + const htmlEndIndex = chunkString.indexOf(HTML_END_TAG); + if (bodyEndIndex !== -1 && htmlEndIndex !== -1 && bodyEndIndex < htmlEndIndex) { + pendingClosingTags = chunkString.slice(bodyEndIndex); + safeEnqueue(chunkString.slice(0, bodyEndIndex)); + flushPendingRouterHtml(); + leftover = ""; + continue; + } + const lastClosingTagEnd = findLastClosingTagEnd(chunkString); + if (lastClosingTagEnd > 0) { + safeEnqueue(chunkString.slice(0, lastClosingTagEnd)); + flushPendingRouterHtml(); + leftover = chunkString.slice(lastClosingTagEnd); + } else { + leftover = chunkString; + } + } + if (cleanedUp || isStreamClosed) return; + isAppRendering = false; + router.serverSsr?.setRenderFinished(); + if (serializationFinished) { + tryFinish(); + } else { + const timeoutMs = opts?.timeoutMs ?? DEFAULT_SERIALIZATION_TIMEOUT_MS; + serializationTimeoutHandle = setTimeout(() => { + if (!cleanedUp && !isStreamClosed) { + console.error("Serialization timeout after app render finished"); + safeError( + new Error("Serialization timeout after app render finished") + ); + cleanup(); + } + }, timeoutMs); + } + } catch (error2) { + if (cleanedUp) return; + console.error("Error reading appStream:", error2); + isAppRendering = false; + router.serverSsr?.setRenderFinished(); + safeError(error2); + cleanup(); + } finally { + reader.releaseLock(); + } + })().catch((error2) => { + if (cleanedUp) return; + console.error("Error in stream transform:", error2); + safeError(error2); + cleanup(); + }); + return stream; +} +var server_node = {}; +var reactDomServerLegacy_node_production = {}; +var hasRequiredReactDomServerLegacy_node_production; +function requireReactDomServerLegacy_node_production() { + if (hasRequiredReactDomServerLegacy_node_production) return reactDomServerLegacy_node_production; + hasRequiredReactDomServerLegacy_node_production = 1; + var React = requireReact(), ReactDOM = requireReactDom(), REACT_ELEMENT_TYPE = Symbol.for("react.transitional.element"), REACT_PORTAL_TYPE = Symbol.for("react.portal"), REACT_FRAGMENT_TYPE = Symbol.for("react.fragment"), REACT_STRICT_MODE_TYPE = Symbol.for("react.strict_mode"), REACT_PROFILER_TYPE = Symbol.for("react.profiler"), REACT_CONSUMER_TYPE = Symbol.for("react.consumer"), REACT_CONTEXT_TYPE = Symbol.for("react.context"), REACT_FORWARD_REF_TYPE = Symbol.for("react.forward_ref"), REACT_SUSPENSE_TYPE = Symbol.for("react.suspense"), REACT_SUSPENSE_LIST_TYPE = Symbol.for("react.suspense_list"), REACT_MEMO_TYPE = Symbol.for("react.memo"), REACT_LAZY_TYPE = Symbol.for("react.lazy"), REACT_SCOPE_TYPE = Symbol.for("react.scope"), REACT_ACTIVITY_TYPE = Symbol.for("react.activity"), REACT_LEGACY_HIDDEN_TYPE = Symbol.for("react.legacy_hidden"), REACT_MEMO_CACHE_SENTINEL = Symbol.for("react.memo_cache_sentinel"), REACT_VIEW_TRANSITION_TYPE = Symbol.for("react.view_transition"), MAYBE_ITERATOR_SYMBOL = Symbol.iterator; + function getIteratorFn(maybeIterable) { + if (null === maybeIterable || "object" !== typeof maybeIterable) return null; + maybeIterable = MAYBE_ITERATOR_SYMBOL && maybeIterable[MAYBE_ITERATOR_SYMBOL] || maybeIterable["@@iterator"]; + return "function" === typeof maybeIterable ? maybeIterable : null; + } + var isArrayImpl = Array.isArray; + function murmurhash3_32_gc(key, seed) { + var remainder = key.length & 3; + var bytes = key.length - remainder; + var h1 = seed; + for (seed = 0; seed < bytes; ) { + var k1 = key.charCodeAt(seed) & 255 | (key.charCodeAt(++seed) & 255) << 8 | (key.charCodeAt(++seed) & 255) << 16 | (key.charCodeAt(++seed) & 255) << 24; + ++seed; + k1 = 3432918353 * (k1 & 65535) + ((3432918353 * (k1 >>> 16) & 65535) << 16) & 4294967295; + k1 = k1 << 15 | k1 >>> 17; + k1 = 461845907 * (k1 & 65535) + ((461845907 * (k1 >>> 16) & 65535) << 16) & 4294967295; + h1 ^= k1; + h1 = h1 << 13 | h1 >>> 19; + h1 = 5 * (h1 & 65535) + ((5 * (h1 >>> 16) & 65535) << 16) & 4294967295; + h1 = (h1 & 65535) + 27492 + (((h1 >>> 16) + 58964 & 65535) << 16); + } + k1 = 0; + switch (remainder) { + case 3: + k1 ^= (key.charCodeAt(seed + 2) & 255) << 16; + case 2: + k1 ^= (key.charCodeAt(seed + 1) & 255) << 8; + case 1: + k1 ^= key.charCodeAt(seed) & 255, k1 = 3432918353 * (k1 & 65535) + ((3432918353 * (k1 >>> 16) & 65535) << 16) & 4294967295, k1 = k1 << 15 | k1 >>> 17, h1 ^= 461845907 * (k1 & 65535) + ((461845907 * (k1 >>> 16) & 65535) << 16) & 4294967295; + } + h1 ^= key.length; + h1 ^= h1 >>> 16; + h1 = 2246822507 * (h1 & 65535) + ((2246822507 * (h1 >>> 16) & 65535) << 16) & 4294967295; + h1 ^= h1 >>> 13; + h1 = 3266489909 * (h1 & 65535) + ((3266489909 * (h1 >>> 16) & 65535) << 16) & 4294967295; + return (h1 ^ h1 >>> 16) >>> 0; + } + var assign = Object.assign, hasOwnProperty = Object.prototype.hasOwnProperty, VALID_ATTRIBUTE_NAME_REGEX = RegExp( + "^[:A-Z_a-z\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD][:A-Z_a-z\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD\\-.0-9\\u00B7\\u0300-\\u036F\\u203F-\\u2040]*$" + ), illegalAttributeNameCache = {}, validatedAttributeNameCache = {}; + function isAttributeNameSafe(attributeName) { + if (hasOwnProperty.call(validatedAttributeNameCache, attributeName)) + return true; + if (hasOwnProperty.call(illegalAttributeNameCache, attributeName)) return false; + if (VALID_ATTRIBUTE_NAME_REGEX.test(attributeName)) + return validatedAttributeNameCache[attributeName] = true; + illegalAttributeNameCache[attributeName] = true; + return false; + } + var unitlessNumbers = new Set( + "animationIterationCount aspectRatio borderImageOutset borderImageSlice borderImageWidth boxFlex boxFlexGroup boxOrdinalGroup columnCount columns flex flexGrow flexPositive flexShrink flexNegative flexOrder gridArea gridRow gridRowEnd gridRowSpan gridRowStart gridColumn gridColumnEnd gridColumnSpan gridColumnStart fontWeight lineClamp lineHeight opacity order orphans scale tabSize widows zIndex zoom fillOpacity floodOpacity stopOpacity strokeDasharray strokeDashoffset strokeMiterlimit strokeOpacity strokeWidth MozAnimationIterationCount MozBoxFlex MozBoxFlexGroup MozLineClamp msAnimationIterationCount msFlex msZoom msFlexGrow msFlexNegative msFlexOrder msFlexPositive msFlexShrink msGridColumn msGridColumnSpan msGridRow msGridRowSpan WebkitAnimationIterationCount WebkitBoxFlex WebKitBoxFlexGroup WebkitBoxOrdinalGroup WebkitColumnCount WebkitColumns WebkitFlex WebkitFlexGrow WebkitFlexPositive WebkitFlexShrink WebkitLineClamp".split( + " " + ) + ), aliases = /* @__PURE__ */ new Map([ + ["acceptCharset", "accept-charset"], + ["htmlFor", "for"], + ["httpEquiv", "http-equiv"], + ["crossOrigin", "crossorigin"], + ["accentHeight", "accent-height"], + ["alignmentBaseline", "alignment-baseline"], + ["arabicForm", "arabic-form"], + ["baselineShift", "baseline-shift"], + ["capHeight", "cap-height"], + ["clipPath", "clip-path"], + ["clipRule", "clip-rule"], + ["colorInterpolation", "color-interpolation"], + ["colorInterpolationFilters", "color-interpolation-filters"], + ["colorProfile", "color-profile"], + ["colorRendering", "color-rendering"], + ["dominantBaseline", "dominant-baseline"], + ["enableBackground", "enable-background"], + ["fillOpacity", "fill-opacity"], + ["fillRule", "fill-rule"], + ["floodColor", "flood-color"], + ["floodOpacity", "flood-opacity"], + ["fontFamily", "font-family"], + ["fontSize", "font-size"], + ["fontSizeAdjust", "font-size-adjust"], + ["fontStretch", "font-stretch"], + ["fontStyle", "font-style"], + ["fontVariant", "font-variant"], + ["fontWeight", "font-weight"], + ["glyphName", "glyph-name"], + ["glyphOrientationHorizontal", "glyph-orientation-horizontal"], + ["glyphOrientationVertical", "glyph-orientation-vertical"], + ["horizAdvX", "horiz-adv-x"], + ["horizOriginX", "horiz-origin-x"], + ["imageRendering", "image-rendering"], + ["letterSpacing", "letter-spacing"], + ["lightingColor", "lighting-color"], + ["markerEnd", "marker-end"], + ["markerMid", "marker-mid"], + ["markerStart", "marker-start"], + ["overlinePosition", "overline-position"], + ["overlineThickness", "overline-thickness"], + ["paintOrder", "paint-order"], + ["panose-1", "panose-1"], + ["pointerEvents", "pointer-events"], + ["renderingIntent", "rendering-intent"], + ["shapeRendering", "shape-rendering"], + ["stopColor", "stop-color"], + ["stopOpacity", "stop-opacity"], + ["strikethroughPosition", "strikethrough-position"], + ["strikethroughThickness", "strikethrough-thickness"], + ["strokeDasharray", "stroke-dasharray"], + ["strokeDashoffset", "stroke-dashoffset"], + ["strokeLinecap", "stroke-linecap"], + ["strokeLinejoin", "stroke-linejoin"], + ["strokeMiterlimit", "stroke-miterlimit"], + ["strokeOpacity", "stroke-opacity"], + ["strokeWidth", "stroke-width"], + ["textAnchor", "text-anchor"], + ["textDecoration", "text-decoration"], + ["textRendering", "text-rendering"], + ["transformOrigin", "transform-origin"], + ["underlinePosition", "underline-position"], + ["underlineThickness", "underline-thickness"], + ["unicodeBidi", "unicode-bidi"], + ["unicodeRange", "unicode-range"], + ["unitsPerEm", "units-per-em"], + ["vAlphabetic", "v-alphabetic"], + ["vHanging", "v-hanging"], + ["vIdeographic", "v-ideographic"], + ["vMathematical", "v-mathematical"], + ["vectorEffect", "vector-effect"], + ["vertAdvY", "vert-adv-y"], + ["vertOriginX", "vert-origin-x"], + ["vertOriginY", "vert-origin-y"], + ["wordSpacing", "word-spacing"], + ["writingMode", "writing-mode"], + ["xmlnsXlink", "xmlns:xlink"], + ["xHeight", "x-height"] + ]), matchHtmlRegExp = /["'&<>]/; + function escapeTextForBrowser(text) { + if ("boolean" === typeof text || "number" === typeof text || "bigint" === typeof text) + return "" + text; + text = "" + text; + var match = matchHtmlRegExp.exec(text); + if (match) { + var html = "", index, lastIndex = 0; + for (index = match.index; index < text.length; index++) { + switch (text.charCodeAt(index)) { + case 34: + match = """; + break; + case 38: + match = "&"; + break; + case 39: + match = "'"; + break; + case 60: + match = "<"; + break; + case 62: + match = ">"; + break; + default: + continue; + } + lastIndex !== index && (html += text.slice(lastIndex, index)); + lastIndex = index + 1; + html += match; + } + text = lastIndex !== index ? html + text.slice(lastIndex, index) : html; + } + return text; + } + var uppercasePattern = /([A-Z])/g, msPattern = /^ms-/, isJavaScriptProtocol = /^[\u0000-\u001F ]*j[\r\n\t]*a[\r\n\t]*v[\r\n\t]*a[\r\n\t]*s[\r\n\t]*c[\r\n\t]*r[\r\n\t]*i[\r\n\t]*p[\r\n\t]*t[\r\n\t]*:/i; + function sanitizeURL(url) { + return isJavaScriptProtocol.test("" + url) ? "javascript:throw new Error('React has blocked a javascript: URL as a security precaution.')" : url; + } + var ReactSharedInternals = React.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE, ReactDOMSharedInternals = ReactDOM.__DOM_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE, sharedNotPendingObject = { + pending: false, + data: null, + method: null, + action: null + }, previousDispatcher = ReactDOMSharedInternals.d; + ReactDOMSharedInternals.d = { + f: previousDispatcher.f, + r: previousDispatcher.r, + D: prefetchDNS, + C: preconnect, + L: preload, + m: preloadModule, + X: preinitScript, + S: preinitStyle, + M: preinitModuleScript + }; + var PRELOAD_NO_CREDS = [], currentlyFlushingRenderState = null, scriptRegex = /(<\/|<)(s)(cript)/gi; + function scriptReplacer(match, prefix3, s, suffix2) { + return "" + prefix3 + ("s" === s ? "\\u0073" : "\\u0053") + suffix2; + } + function createResumableState(identifierPrefix, externalRuntimeConfig, bootstrapScriptContent, bootstrapScripts, bootstrapModules) { + return { + idPrefix: void 0 === identifierPrefix ? "" : identifierPrefix, + nextFormID: 0, + streamingFormat: 0, + bootstrapScriptContent, + bootstrapScripts, + bootstrapModules, + instructions: 0, + hasBody: false, + hasHtml: false, + unknownResources: {}, + dnsResources: {}, + connectResources: { default: {}, anonymous: {}, credentials: {} }, + imageResources: {}, + styleResources: {}, + scriptResources: {}, + moduleUnknownResources: {}, + moduleScriptResources: {} + }; + } + function createFormatContext(insertionMode, selectedValue, tagScope, viewTransition) { + return { + insertionMode, + selectedValue, + tagScope, + viewTransition + }; + } + function getChildFormatContext(parentContext, type, props) { + var subtreeScope = parentContext.tagScope & -25; + switch (type) { + case "noscript": + return createFormatContext(2, null, subtreeScope | 1, null); + case "select": + return createFormatContext( + 2, + null != props.value ? props.value : props.defaultValue, + subtreeScope, + null + ); + case "svg": + return createFormatContext(4, null, subtreeScope, null); + case "picture": + return createFormatContext(2, null, subtreeScope | 2, null); + case "math": + return createFormatContext(5, null, subtreeScope, null); + case "foreignObject": + return createFormatContext(2, null, subtreeScope, null); + case "table": + return createFormatContext(6, null, subtreeScope, null); + case "thead": + case "tbody": + case "tfoot": + return createFormatContext(7, null, subtreeScope, null); + case "colgroup": + return createFormatContext(9, null, subtreeScope, null); + case "tr": + return createFormatContext(8, null, subtreeScope, null); + case "head": + if (2 > parentContext.insertionMode) + return createFormatContext(3, null, subtreeScope, null); + break; + case "html": + if (0 === parentContext.insertionMode) + return createFormatContext(1, null, subtreeScope, null); + } + return 6 <= parentContext.insertionMode || 2 > parentContext.insertionMode ? createFormatContext(2, null, subtreeScope, null) : parentContext.tagScope !== subtreeScope ? createFormatContext( + parentContext.insertionMode, + parentContext.selectedValue, + subtreeScope, + null + ) : parentContext; + } + function getSuspenseViewTransition(parentViewTransition) { + return null === parentViewTransition ? null : { + update: parentViewTransition.update, + enter: "none", + exit: "none", + share: parentViewTransition.update, + name: parentViewTransition.autoName, + autoName: parentViewTransition.autoName, + nameIdx: 0 + }; + } + function getSuspenseFallbackFormatContext(resumableState, parentContext) { + parentContext.tagScope & 32 && (resumableState.instructions |= 128); + return createFormatContext( + parentContext.insertionMode, + parentContext.selectedValue, + parentContext.tagScope | 12, + getSuspenseViewTransition(parentContext.viewTransition) + ); + } + function getSuspenseContentFormatContext(resumableState, parentContext) { + resumableState = getSuspenseViewTransition(parentContext.viewTransition); + var subtreeScope = parentContext.tagScope | 16; + null !== resumableState && "none" !== resumableState.share && (subtreeScope |= 64); + return createFormatContext( + parentContext.insertionMode, + parentContext.selectedValue, + subtreeScope, + resumableState + ); + } + var styleNameCache = /* @__PURE__ */ new Map(); + function pushStyleAttribute(target, style) { + if ("object" !== typeof style) + throw Error( + "The `style` prop expects a mapping from style properties to values, not a string. For example, style={{marginRight: spacing + 'em'}} when using JSX." + ); + var isFirst = true, styleName; + for (styleName in style) + if (hasOwnProperty.call(style, styleName)) { + var styleValue = style[styleName]; + if (null != styleValue && "boolean" !== typeof styleValue && "" !== styleValue) { + if (0 === styleName.indexOf("--")) { + var nameChunk = escapeTextForBrowser(styleName); + styleValue = escapeTextForBrowser(("" + styleValue).trim()); + } else + nameChunk = styleNameCache.get(styleName), void 0 === nameChunk && (nameChunk = escapeTextForBrowser( + styleName.replace(uppercasePattern, "-$1").toLowerCase().replace(msPattern, "-ms-") + ), styleNameCache.set(styleName, nameChunk)), styleValue = "number" === typeof styleValue ? 0 === styleValue || unitlessNumbers.has(styleName) ? "" + styleValue : styleValue + "px" : escapeTextForBrowser(("" + styleValue).trim()); + isFirst ? (isFirst = false, target.push(' style="', nameChunk, ":", styleValue)) : target.push(";", nameChunk, ":", styleValue); + } + } + isFirst || target.push('"'); + } + function pushBooleanAttribute(target, name, value) { + value && "function" !== typeof value && "symbol" !== typeof value && target.push(" ", name, '=""'); + } + function pushStringAttribute(target, name, value) { + "function" !== typeof value && "symbol" !== typeof value && "boolean" !== typeof value && target.push(" ", name, '="', escapeTextForBrowser(value), '"'); + } + var actionJavaScriptURL = escapeTextForBrowser( + "javascript:throw new Error('React form unexpectedly submitted.')" + ); + function pushAdditionalFormField(value, key) { + this.push('"); + } + function validateAdditionalFormField(value) { + if ("string" !== typeof value) + throw Error( + "File/Blob fields are not yet supported in progressive forms. Will fallback to client hydration." + ); + } + function getCustomFormFields(resumableState, formAction) { + if ("function" === typeof formAction.$$FORM_ACTION) { + var id = resumableState.nextFormID++; + resumableState = resumableState.idPrefix + id; + try { + var customFields = formAction.$$FORM_ACTION(resumableState); + if (customFields) { + var formData = customFields.data; + null != formData && formData.forEach(validateAdditionalFormField); + } + return customFields; + } catch (x2) { + if ("object" === typeof x2 && null !== x2 && "function" === typeof x2.then) + throw x2; + } + } + return null; + } + function pushFormActionAttribute(target, resumableState, renderState, formAction, formEncType, formMethod, formTarget, name) { + var formData = null; + if ("function" === typeof formAction) { + var customFields = getCustomFormFields(resumableState, formAction); + null !== customFields ? (name = customFields.name, formAction = customFields.action || "", formEncType = customFields.encType, formMethod = customFields.method, formTarget = customFields.target, formData = customFields.data) : (target.push(" ", "formAction", '="', actionJavaScriptURL, '"'), formTarget = formMethod = formEncType = formAction = name = null, injectFormReplayingRuntime(resumableState, renderState)); + } + null != name && pushAttribute(target, "name", name); + null != formAction && pushAttribute(target, "formAction", formAction); + null != formEncType && pushAttribute(target, "formEncType", formEncType); + null != formMethod && pushAttribute(target, "formMethod", formMethod); + null != formTarget && pushAttribute(target, "formTarget", formTarget); + return formData; + } + function pushAttribute(target, name, value) { + switch (name) { + case "className": + pushStringAttribute(target, "class", value); + break; + case "tabIndex": + pushStringAttribute(target, "tabindex", value); + break; + case "dir": + case "role": + case "viewBox": + case "width": + case "height": + pushStringAttribute(target, name, value); + break; + case "style": + pushStyleAttribute(target, value); + break; + case "src": + case "href": + if ("" === value) break; + case "action": + case "formAction": + if (null == value || "function" === typeof value || "symbol" === typeof value || "boolean" === typeof value) + break; + value = sanitizeURL("" + value); + target.push(" ", name, '="', escapeTextForBrowser(value), '"'); + break; + case "defaultValue": + case "defaultChecked": + case "innerHTML": + case "suppressContentEditableWarning": + case "suppressHydrationWarning": + case "ref": + break; + case "autoFocus": + case "multiple": + case "muted": + pushBooleanAttribute(target, name.toLowerCase(), value); + break; + case "xlinkHref": + if ("function" === typeof value || "symbol" === typeof value || "boolean" === typeof value) + break; + value = sanitizeURL("" + value); + target.push(" ", "xlink:href", '="', escapeTextForBrowser(value), '"'); + break; + case "contentEditable": + case "spellCheck": + case "draggable": + case "value": + case "autoReverse": + case "externalResourcesRequired": + case "focusable": + case "preserveAlpha": + "function" !== typeof value && "symbol" !== typeof value && target.push(" ", name, '="', escapeTextForBrowser(value), '"'); + break; + case "inert": + case "allowFullScreen": + case "async": + case "autoPlay": + case "controls": + case "default": + case "defer": + case "disabled": + case "disablePictureInPicture": + case "disableRemotePlayback": + case "formNoValidate": + case "hidden": + case "loop": + case "noModule": + case "noValidate": + case "open": + case "playsInline": + case "readOnly": + case "required": + case "reversed": + case "scoped": + case "seamless": + case "itemScope": + value && "function" !== typeof value && "symbol" !== typeof value && target.push(" ", name, '=""'); + break; + case "capture": + case "download": + true === value ? target.push(" ", name, '=""') : false !== value && "function" !== typeof value && "symbol" !== typeof value && target.push(" ", name, '="', escapeTextForBrowser(value), '"'); + break; + case "cols": + case "rows": + case "size": + case "span": + "function" !== typeof value && "symbol" !== typeof value && !isNaN(value) && 1 <= value && target.push(" ", name, '="', escapeTextForBrowser(value), '"'); + break; + case "rowSpan": + case "start": + "function" === typeof value || "symbol" === typeof value || isNaN(value) || target.push(" ", name, '="', escapeTextForBrowser(value), '"'); + break; + case "xlinkActuate": + pushStringAttribute(target, "xlink:actuate", value); + break; + case "xlinkArcrole": + pushStringAttribute(target, "xlink:arcrole", value); + break; + case "xlinkRole": + pushStringAttribute(target, "xlink:role", value); + break; + case "xlinkShow": + pushStringAttribute(target, "xlink:show", value); + break; + case "xlinkTitle": + pushStringAttribute(target, "xlink:title", value); + break; + case "xlinkType": + pushStringAttribute(target, "xlink:type", value); + break; + case "xmlBase": + pushStringAttribute(target, "xml:base", value); + break; + case "xmlLang": + pushStringAttribute(target, "xml:lang", value); + break; + case "xmlSpace": + pushStringAttribute(target, "xml:space", value); + break; + default: + if (!(2 < name.length) || "o" !== name[0] && "O" !== name[0] || "n" !== name[1] && "N" !== name[1]) { + if (name = aliases.get(name) || name, isAttributeNameSafe(name)) { + switch (typeof value) { + case "function": + case "symbol": + return; + case "boolean": + var prefix$8 = name.toLowerCase().slice(0, 5); + if ("data-" !== prefix$8 && "aria-" !== prefix$8) return; + } + target.push(" ", name, '="', escapeTextForBrowser(value), '"'); + } + } + } + } + function pushInnerHTML(target, innerHTML, children) { + if (null != innerHTML) { + if (null != children) + throw Error( + "Can only set one of `children` or `props.dangerouslySetInnerHTML`." + ); + if ("object" !== typeof innerHTML || !("__html" in innerHTML)) + throw Error( + "`props.dangerouslySetInnerHTML` must be in the form `{__html: ...}`. Please visit https://react.dev/link/dangerously-set-inner-html for more information." + ); + innerHTML = innerHTML.__html; + null !== innerHTML && void 0 !== innerHTML && target.push("" + innerHTML); + } + } + function flattenOptionChildren(children) { + var content = ""; + React.Children.forEach(children, function(child) { + null != child && (content += child); + }); + return content; + } + function injectFormReplayingRuntime(resumableState, renderState) { + if (0 === (resumableState.instructions & 16)) { + resumableState.instructions |= 16; + var preamble = renderState.preamble, bootstrapChunks = renderState.bootstrapChunks; + (preamble.htmlChunks || preamble.headChunks) && 0 === bootstrapChunks.length ? (bootstrapChunks.push(renderState.startInlineScript), pushCompletedShellIdAttribute(bootstrapChunks, resumableState), bootstrapChunks.push( + ">", + `addEventListener("submit",function(a){if(!a.defaultPrevented){var c=a.target,d=a.submitter,e=c.action,b=d;if(d){var f=d.getAttribute("formAction");null!=f&&(e=f,b=null)}"javascript:throw new Error('React form unexpectedly submitted.')"===e&&(a.preventDefault(),b?(a=document.createElement("input"),a.name=b.name,a.value=b.value,b.parentNode.insertBefore(a,b),b=new FormData(c),a.parentNode.removeChild(a)):b=new FormData(c),a=c.ownerDocument||c,(a.$$reactFormReplay=a.$$reactFormReplay||[]).push(c,d,b))}});`, + "<\/script>" + )) : bootstrapChunks.unshift( + renderState.startInlineScript, + ">", + `addEventListener("submit",function(a){if(!a.defaultPrevented){var c=a.target,d=a.submitter,e=c.action,b=d;if(d){var f=d.getAttribute("formAction");null!=f&&(e=f,b=null)}"javascript:throw new Error('React form unexpectedly submitted.')"===e&&(a.preventDefault(),b?(a=document.createElement("input"),a.name=b.name,a.value=b.value,b.parentNode.insertBefore(a,b),b=new FormData(c),a.parentNode.removeChild(a)):b=new FormData(c),a=c.ownerDocument||c,(a.$$reactFormReplay=a.$$reactFormReplay||[]).push(c,d,b))}});`, + "<\/script>" + ); + } + } + function pushLinkImpl(target, props) { + target.push(startChunkForTag("link")); + for (var propKey in props) + if (hasOwnProperty.call(props, propKey)) { + var propValue = props[propKey]; + if (null != propValue) + switch (propKey) { + case "children": + case "dangerouslySetInnerHTML": + throw Error( + "link is a self-closing tag and must neither have `children` nor use `dangerouslySetInnerHTML`." + ); + default: + pushAttribute(target, propKey, propValue); + } + } + target.push("/>"); + return null; + } + var styleRegex = /(<\/|<)(s)(tyle)/gi; + function styleReplacer(match, prefix3, s, suffix2) { + return "" + prefix3 + ("s" === s ? "\\73 " : "\\53 ") + suffix2; + } + function pushSelfClosing(target, props, tag) { + target.push(startChunkForTag(tag)); + for (var propKey in props) + if (hasOwnProperty.call(props, propKey)) { + var propValue = props[propKey]; + if (null != propValue) + switch (propKey) { + case "children": + case "dangerouslySetInnerHTML": + throw Error( + tag + " is a self-closing tag and must neither have `children` nor use `dangerouslySetInnerHTML`." + ); + default: + pushAttribute(target, propKey, propValue); + } + } + target.push("/>"); + return null; + } + function pushTitleImpl(target, props) { + target.push(startChunkForTag("title")); + var children = null, innerHTML = null, propKey; + for (propKey in props) + if (hasOwnProperty.call(props, propKey)) { + var propValue = props[propKey]; + if (null != propValue) + switch (propKey) { + case "children": + children = propValue; + break; + case "dangerouslySetInnerHTML": + innerHTML = propValue; + break; + default: + pushAttribute(target, propKey, propValue); + } + } + target.push(">"); + props = Array.isArray(children) ? 2 > children.length ? children[0] : null : children; + "function" !== typeof props && "symbol" !== typeof props && null !== props && void 0 !== props && target.push(escapeTextForBrowser("" + props)); + pushInnerHTML(target, innerHTML, children); + target.push(endChunkForTag("title")); + return null; + } + function pushScriptImpl(target, props) { + target.push(startChunkForTag("script")); + var children = null, innerHTML = null, propKey; + for (propKey in props) + if (hasOwnProperty.call(props, propKey)) { + var propValue = props[propKey]; + if (null != propValue) + switch (propKey) { + case "children": + children = propValue; + break; + case "dangerouslySetInnerHTML": + innerHTML = propValue; + break; + default: + pushAttribute(target, propKey, propValue); + } + } + target.push(">"); + pushInnerHTML(target, innerHTML, children); + "string" === typeof children && target.push(("" + children).replace(scriptRegex, scriptReplacer)); + target.push(endChunkForTag("script")); + return null; + } + function pushStartSingletonElement(target, props, tag) { + target.push(startChunkForTag(tag)); + var innerHTML = tag = null, propKey; + for (propKey in props) + if (hasOwnProperty.call(props, propKey)) { + var propValue = props[propKey]; + if (null != propValue) + switch (propKey) { + case "children": + tag = propValue; + break; + case "dangerouslySetInnerHTML": + innerHTML = propValue; + break; + default: + pushAttribute(target, propKey, propValue); + } + } + target.push(">"); + pushInnerHTML(target, innerHTML, tag); + return tag; + } + function pushStartGenericElement(target, props, tag) { + target.push(startChunkForTag(tag)); + var innerHTML = tag = null, propKey; + for (propKey in props) + if (hasOwnProperty.call(props, propKey)) { + var propValue = props[propKey]; + if (null != propValue) + switch (propKey) { + case "children": + tag = propValue; + break; + case "dangerouslySetInnerHTML": + innerHTML = propValue; + break; + default: + pushAttribute(target, propKey, propValue); + } + } + target.push(">"); + pushInnerHTML(target, innerHTML, tag); + return "string" === typeof tag ? (target.push(escapeTextForBrowser(tag)), null) : tag; + } + var VALID_TAG_REGEX = /^[a-zA-Z][a-zA-Z:_\.\-\d]*$/, validatedTagCache = /* @__PURE__ */ new Map(); + function startChunkForTag(tag) { + var tagStartChunk = validatedTagCache.get(tag); + if (void 0 === tagStartChunk) { + if (!VALID_TAG_REGEX.test(tag)) throw Error("Invalid tag: " + tag); + tagStartChunk = "<" + tag; + validatedTagCache.set(tag, tagStartChunk); + } + return tagStartChunk; + } + function pushStartInstance(target$jscomp$0, type, props, resumableState, renderState, preambleState, hoistableState, formatContext, textEmbedded) { + switch (type) { + case "div": + case "span": + case "svg": + case "path": + break; + case "a": + target$jscomp$0.push(startChunkForTag("a")); + var children = null, innerHTML = null, propKey; + for (propKey in props) + if (hasOwnProperty.call(props, propKey)) { + var propValue = props[propKey]; + if (null != propValue) + switch (propKey) { + case "children": + children = propValue; + break; + case "dangerouslySetInnerHTML": + innerHTML = propValue; + break; + case "href": + "" === propValue ? pushStringAttribute(target$jscomp$0, "href", "") : pushAttribute(target$jscomp$0, propKey, propValue); + break; + default: + pushAttribute(target$jscomp$0, propKey, propValue); + } + } + target$jscomp$0.push(">"); + pushInnerHTML(target$jscomp$0, innerHTML, children); + if ("string" === typeof children) { + target$jscomp$0.push(escapeTextForBrowser(children)); + var JSCompiler_inline_result = null; + } else JSCompiler_inline_result = children; + return JSCompiler_inline_result; + case "g": + case "p": + case "li": + break; + case "select": + target$jscomp$0.push(startChunkForTag("select")); + var children$jscomp$0 = null, innerHTML$jscomp$0 = null, propKey$jscomp$0; + for (propKey$jscomp$0 in props) + if (hasOwnProperty.call(props, propKey$jscomp$0)) { + var propValue$jscomp$0 = props[propKey$jscomp$0]; + if (null != propValue$jscomp$0) + switch (propKey$jscomp$0) { + case "children": + children$jscomp$0 = propValue$jscomp$0; + break; + case "dangerouslySetInnerHTML": + innerHTML$jscomp$0 = propValue$jscomp$0; + break; + case "defaultValue": + case "value": + break; + default: + pushAttribute( + target$jscomp$0, + propKey$jscomp$0, + propValue$jscomp$0 + ); + } + } + target$jscomp$0.push(">"); + pushInnerHTML(target$jscomp$0, innerHTML$jscomp$0, children$jscomp$0); + return children$jscomp$0; + case "option": + var selectedValue = formatContext.selectedValue; + target$jscomp$0.push(startChunkForTag("option")); + var children$jscomp$1 = null, value = null, selected = null, innerHTML$jscomp$1 = null, propKey$jscomp$1; + for (propKey$jscomp$1 in props) + if (hasOwnProperty.call(props, propKey$jscomp$1)) { + var propValue$jscomp$1 = props[propKey$jscomp$1]; + if (null != propValue$jscomp$1) + switch (propKey$jscomp$1) { + case "children": + children$jscomp$1 = propValue$jscomp$1; + break; + case "selected": + selected = propValue$jscomp$1; + break; + case "dangerouslySetInnerHTML": + innerHTML$jscomp$1 = propValue$jscomp$1; + break; + case "value": + value = propValue$jscomp$1; + default: + pushAttribute( + target$jscomp$0, + propKey$jscomp$1, + propValue$jscomp$1 + ); + } + } + if (null != selectedValue) { + var stringValue = null !== value ? "" + value : flattenOptionChildren(children$jscomp$1); + if (isArrayImpl(selectedValue)) + for (var i = 0; i < selectedValue.length; i++) { + if ("" + selectedValue[i] === stringValue) { + target$jscomp$0.push(' selected=""'); + break; + } + } + else + "" + selectedValue === stringValue && target$jscomp$0.push(' selected=""'); + } else selected && target$jscomp$0.push(' selected=""'); + target$jscomp$0.push(">"); + pushInnerHTML(target$jscomp$0, innerHTML$jscomp$1, children$jscomp$1); + return children$jscomp$1; + case "textarea": + target$jscomp$0.push(startChunkForTag("textarea")); + var value$jscomp$0 = null, defaultValue = null, children$jscomp$2 = null, propKey$jscomp$2; + for (propKey$jscomp$2 in props) + if (hasOwnProperty.call(props, propKey$jscomp$2)) { + var propValue$jscomp$2 = props[propKey$jscomp$2]; + if (null != propValue$jscomp$2) + switch (propKey$jscomp$2) { + case "children": + children$jscomp$2 = propValue$jscomp$2; + break; + case "value": + value$jscomp$0 = propValue$jscomp$2; + break; + case "defaultValue": + defaultValue = propValue$jscomp$2; + break; + case "dangerouslySetInnerHTML": + throw Error( + "`dangerouslySetInnerHTML` does not make sense on