@sentry/browser 11.2.0 → 11.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/build/npm/cjs/dev/client.js +4 -0
- package/build/npm/cjs/dev/client.js.map +1 -1
- package/build/npm/cjs/dev/index.js +6 -0
- package/build/npm/cjs/dev/index.js.map +1 -1
- package/build/npm/cjs/dev/integrations/bfcacheMetrics.js +3 -1
- package/build/npm/cjs/dev/integrations/bfcacheMetrics.js.map +1 -1
- package/build/npm/cjs/dev/integrations/graphqlClient.js +1 -1
- package/build/npm/cjs/dev/integrations/graphqlClient.js.map +1 -1
- package/build/npm/cjs/dev/tracing/linkedTraces.js +1 -1
- package/build/npm/cjs/dev/tracing/linkedTraces.js.map +1 -1
- package/build/npm/cjs/prod/client.js +4 -0
- package/build/npm/cjs/prod/client.js.map +1 -1
- package/build/npm/cjs/prod/index.js +6 -0
- package/build/npm/cjs/prod/index.js.map +1 -1
- package/build/npm/cjs/prod/integrations/bfcacheMetrics.js +3 -1
- package/build/npm/cjs/prod/integrations/bfcacheMetrics.js.map +1 -1
- package/build/npm/cjs/prod/integrations/graphqlClient.js +1 -1
- package/build/npm/cjs/prod/integrations/graphqlClient.js.map +1 -1
- package/build/npm/cjs/prod/tracing/linkedTraces.js +1 -1
- package/build/npm/cjs/prod/tracing/linkedTraces.js.map +1 -1
- package/build/npm/esm/dev/client.js +4 -0
- package/build/npm/esm/dev/client.js.map +1 -1
- package/build/npm/esm/dev/index.js +1 -1
- package/build/npm/esm/dev/integrations/bfcacheMetrics.js +3 -2
- package/build/npm/esm/dev/integrations/bfcacheMetrics.js.map +1 -1
- package/build/npm/esm/dev/integrations/graphqlClient.js +3 -3
- package/build/npm/esm/dev/integrations/graphqlClient.js.map +1 -1
- package/build/npm/esm/dev/package.json +1 -1
- package/build/npm/esm/dev/tracing/linkedTraces.js +3 -3
- package/build/npm/esm/dev/tracing/linkedTraces.js.map +1 -1
- package/build/npm/esm/prod/client.js +4 -0
- package/build/npm/esm/prod/client.js.map +1 -1
- package/build/npm/esm/prod/index.js +1 -1
- package/build/npm/esm/prod/integrations/bfcacheMetrics.js +3 -2
- package/build/npm/esm/prod/integrations/bfcacheMetrics.js.map +1 -1
- package/build/npm/esm/prod/integrations/graphqlClient.js +3 -3
- package/build/npm/esm/prod/integrations/graphqlClient.js.map +1 -1
- package/build/npm/esm/prod/package.json +1 -1
- package/build/npm/esm/prod/tracing/linkedTraces.js +3 -3
- package/build/npm/esm/prod/tracing/linkedTraces.js.map +1 -1
- package/build/npm/types/client.d.ts +8 -0
- package/build/npm/types/client.d.ts.map +1 -1
- package/build/npm/types/index.d.ts +2 -0
- package/build/npm/types/index.d.ts.map +1 -1
- package/build/npm/types/integrations/bfcacheMetrics.d.ts +14 -0
- package/build/npm/types/integrations/bfcacheMetrics.d.ts.map +1 -1
- package/build/npm/types/integrations/graphqlClient.d.ts.map +1 -1
- package/build/npm/types/tracing/linkedTraces.d.ts.map +1 -1
- package/package.json +8 -8
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"graphqlClient.js","sources":["../../../../../src/integrations/graphqlClient.ts"],"sourcesContent":["import type { Client, IntegrationFn } from '@sentry/core';\nimport {\n defineIntegration,\n hasSpanStreamingEnabled,\n isObjectLike,\n isString,\n SEMANTIC_ATTRIBUTE_HTTP_REQUEST_METHOD,\n spanToJSON,\n stringMatchesSomePattern,\n} from '@sentry/core';\nimport type { FetchHint, XhrHint } from '@sentry/browser-utils';\nimport { getBodyString, getFetchRequestArgBody, SENTRY_XHR_DATA_KEY } from '@sentry/browser-utils';\nimport {\n GRAPHQL_DOCUMENT,\n GRAPHQL_OPERATION_NAME,\n GRAPHQL_OPERATION_TYPE,\n HTTP_METHOD,\n SENTRY_OP,\n URL_FULL,\n} from '@sentry/conventions/attributes';\n\ninterface GraphQLClientOptions {\n endpoints: Array<string | RegExp>;\n}\n\n/** Standard graphql request shape: https://graphql.org/learn/serving-over-http/#post-request-and-body */\ninterface GraphQLStandardRequest {\n query: string;\n operationName?: string;\n variables?: Record<string, unknown>;\n extensions?: Record<string, unknown>;\n}\n\n/** Persisted operation request */\ninterface GraphQLPersistedRequest {\n operationName: string;\n variables?: Record<string, unknown>;\n extensions: {\n persistedQuery: {\n version: number;\n sha256Hash: string;\n };\n } & Record<string, unknown>;\n}\n\ntype GraphQLRequestPayload = GraphQLStandardRequest | GraphQLPersistedRequest;\n\ninterface GraphQLOperation {\n operationType?: string;\n operationName?: string;\n}\n\nconst INTEGRATION_NAME = 'GraphQLClient' as const;\n\nconst _graphqlClientIntegration = ((options: GraphQLClientOptions) => {\n return {\n name: INTEGRATION_NAME,\n setup(client: Client) {\n _updateSpanWithGraphQLData(client, options);\n _updateBreadcrumbWithGraphQLData(client, options);\n },\n };\n}) satisfies IntegrationFn;\n\nfunction _updateSpanWithGraphQLData(client: Client, options: GraphQLClientOptions): void {\n client.on('beforeOutgoingRequestSpan', (span, hint) => {\n const spanJSON = spanToJSON(span);\n\n const spanAttributes = spanJSON.attributes;\n const spanOp = spanAttributes[SENTRY_OP];\n\n const isHttpClientSpan = spanOp === 'http.client';\n\n if (!isHttpClientSpan) {\n return;\n }\n\n const httpUrl = spanAttributes[URL_FULL];\n // oxlint-disable-next-line typescript/no-deprecated\n const httpMethod = spanAttributes[SEMANTIC_ATTRIBUTE_HTTP_REQUEST_METHOD] || spanAttributes[HTTP_METHOD];\n\n if (!isString(httpUrl) || !isString(httpMethod)) {\n return;\n }\n\n const { endpoints } = options;\n const isTracedGraphqlEndpoint = stringMatchesSomePattern(httpUrl, endpoints);\n const payload = getRequestPayloadXhrOrFetch(hint as XhrHint | FetchHint);\n\n if (isTracedGraphqlEndpoint && payload) {\n const graphqlBody = getGraphQLRequestPayload(payload);\n\n if (graphqlBody) {\n // With span streaming the span already carries a low-cardinality name, so it must not be\n // renamed back to one containing the URL. The operation stays reachable as an attribute.\n if (!hasSpanStreamingEnabled(client)) {\n span.updateName(`${httpMethod} ${httpUrl} (${_getGraphQLOperation(graphqlBody)})`);\n }\n\n const { operationName, operationType } = _getGraphQLOperationDetails(graphqlBody);\n span.setAttribute(GRAPHQL_OPERATION_NAME, operationName);\n span.setAttribute(GRAPHQL_OPERATION_TYPE, operationType);\n\n // Handle standard requests - capture the query document when enabled via dataCollection (default true)\n if (isStandardRequest(graphqlBody) && client.getDataCollectionOptions().graphQL.document === true) {\n span.setAttribute(GRAPHQL_DOCUMENT, graphqlBody.query);\n }\n\n // Handle persisted operations - capture hash for debugging\n if (isPersistedRequest(graphqlBody)) {\n span.setAttribute('graphql.persisted_query.hash.sha256', graphqlBody.extensions.persistedQuery.sha256Hash);\n span.setAttribute('graphql.persisted_query.version', graphqlBody.extensions.persistedQuery.version);\n }\n }\n }\n });\n}\n\nfunction _updateBreadcrumbWithGraphQLData(client: Client, options: GraphQLClientOptions): void {\n client.on('beforeOutgoingRequestBreadcrumb', (breadcrumb, handlerData) => {\n const { category, type, data } = breadcrumb;\n\n const isFetch = category === 'fetch';\n const isXhr = category === 'xhr';\n const isHttpBreadcrumb = type === 'http';\n\n if (isHttpBreadcrumb && (isFetch || isXhr)) {\n const httpUrl = data?.url;\n const { endpoints } = options;\n\n const isTracedGraphqlEndpoint = stringMatchesSomePattern(httpUrl, endpoints);\n const payload = getRequestPayloadXhrOrFetch(handlerData as XhrHint | FetchHint);\n\n if (isTracedGraphqlEndpoint && data && payload) {\n const graphqlBody = getGraphQLRequestPayload(payload);\n\n if (!data.graphql && graphqlBody) {\n const operationInfo = _getGraphQLOperation(graphqlBody);\n\n data['graphql.operation'] = operationInfo;\n\n if (isStandardRequest(graphqlBody) && client.getDataCollectionOptions().graphQL.document === true) {\n data[GRAPHQL_DOCUMENT] = graphqlBody.query;\n }\n\n if (isPersistedRequest(graphqlBody)) {\n data['graphql.persisted_query.hash.sha256'] = graphqlBody.extensions.persistedQuery.sha256Hash;\n data['graphql.persisted_query.version'] = graphqlBody.extensions.persistedQuery.version;\n }\n }\n }\n }\n });\n}\n\n/**\n * The operation name and type of a GraphQL request. Persisted operations carry no query document, so\n * their type is unknown.\n */\nfunction _getGraphQLOperationDetails(requestBody: GraphQLRequestPayload): GraphQLOperation {\n if (isPersistedRequest(requestBody)) {\n return { operationName: requestBody.operationName, operationType: undefined };\n }\n\n if (isStandardRequest(requestBody)) {\n const { query: graphqlQuery, operationName: graphqlOperationName } = requestBody;\n const { operationName = graphqlOperationName, operationType } = parseGraphQLQuery(graphqlQuery);\n return { operationName, operationType };\n }\n\n return { operationName: undefined, operationType: undefined };\n}\n\n/**\n * @param requestBody - GraphQL request\n * @returns A formatted version of the request: 'TYPE NAME' or 'TYPE' or 'persisted NAME'\n */\nexport function _getGraphQLOperation(requestBody: GraphQLRequestPayload): string {\n // Handle persisted operations\n if (isPersistedRequest(requestBody)) {\n return `persisted ${requestBody.operationName}`;\n }\n\n // Handle standard GraphQL requests\n if (isStandardRequest(requestBody)) {\n const { operationName, operationType } = _getGraphQLOperationDetails(requestBody);\n return operationName ? `${operationType} ${operationName}` : `${operationType}`;\n }\n\n // Fallback for unknown request types\n return 'unknown';\n}\n\n/**\n * Get the request body/payload based on the shape of the hint.\n *\n * Exported for tests only.\n */\nexport function getRequestPayloadXhrOrFetch(hint: XhrHint | FetchHint): string | undefined {\n const isXhr = 'xhr' in hint;\n\n let body: string | undefined;\n\n if (isXhr) {\n const sentryXhrData = hint.xhr[SENTRY_XHR_DATA_KEY];\n body = sentryXhrData && getBodyString(sentryXhrData.body)[0];\n } else {\n const sentryFetchData = getFetchRequestArgBody(hint.input);\n body = getBodyString(sentryFetchData)[0];\n }\n\n return body;\n}\n\n/**\n * Extract the name and type of the operation from the GraphQL query.\n *\n * Exported for tests only.\n */\nexport function parseGraphQLQuery(query: string): GraphQLOperation {\n const namedQueryRe = /^(?:\\s*)(query|mutation|subscription)(?:\\s*)(\\w+)(?:\\s*)[{(]/;\n const unnamedQueryRe = /^(?:\\s*)(query|mutation|subscription)(?:\\s*)[{(]/;\n\n const namedMatch = query.match(namedQueryRe);\n if (namedMatch) {\n return {\n operationType: namedMatch[1],\n operationName: namedMatch[2],\n };\n }\n\n const unnamedMatch = query.match(unnamedQueryRe);\n if (unnamedMatch) {\n return {\n operationType: unnamedMatch[1],\n operationName: undefined,\n };\n }\n return {\n operationType: undefined,\n operationName: undefined,\n };\n}\n\n/**\n * Helper to safely check if a value is a non-null object\n */\n\n/**\n * Type guard to check if a request is a standard GraphQL request\n */\nfunction isStandardRequest(payload: unknown): payload is GraphQLStandardRequest {\n return isObjectLike(payload) && typeof payload.query === 'string';\n}\n\n/**\n * Type guard to check if a request is a persisted operation request\n */\nfunction isPersistedRequest(payload: unknown): payload is GraphQLPersistedRequest {\n return (\n isObjectLike(payload) &&\n typeof payload.operationName === 'string' &&\n isObjectLike(payload.extensions) &&\n isObjectLike(payload.extensions.persistedQuery) &&\n typeof payload.extensions.persistedQuery.sha256Hash === 'string' &&\n typeof payload.extensions.persistedQuery.version === 'number'\n );\n}\n\n/**\n * Extract the payload of a request if it's GraphQL.\n * Exported for tests only.\n * @param payload - A valid JSON string\n * @returns A POJO or undefined\n */\nexport function getGraphQLRequestPayload(payload: string): GraphQLRequestPayload | undefined {\n try {\n const requestBody = JSON.parse(payload);\n\n // Return any valid GraphQL request (standard, persisted, or APQ retry with both)\n if (isStandardRequest(requestBody) || isPersistedRequest(requestBody)) {\n return requestBody;\n }\n\n // Not a GraphQL request\n return undefined;\n } catch {\n // Invalid JSON\n return undefined;\n }\n}\n\n/**\n * This integration ensures that GraphQL requests made in the browser\n * have their GraphQL-specific data captured and attached to spans and breadcrumbs.\n */\nexport const graphqlClientIntegration = defineIntegration(_graphqlClientIntegration);\n"],"names":["spanToJSON","SENTRY_OP","URL_FULL","SEMANTIC_ATTRIBUTE_HTTP_REQUEST_METHOD","HTTP_METHOD","isString","stringMatchesSomePattern","hasSpanStreamingEnabled","GRAPHQL_OPERATION_NAME","GRAPHQL_OPERATION_TYPE","GRAPHQL_DOCUMENT","SENTRY_XHR_DATA_KEY","getBodyString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M,OAAO,CAAA;AAGtC,IAAA,IAAI,iBAAA,CAAkB,WAAW,CAAA,IAAK,kBAAA,CAAmB,WAAW,CAAA,EAAG;AACrE,MAAA,OAAO,WAAA;AAAA,IACT;AAGA,IAAA,OAAO,KAAA,CAAA;AAAA,EACT,CAAA,CAAA,MAAQ;AAEN,IAAA,OAAO,MAAA;AAAA,EACT;AACF;AAMO,MAAM,wBAAA,GAA2BC,uBAAkB,yBAAyB;;;;;;;;"}
|
|
1
|
+
{"version":3,"file":"graphqlClient.js","sources":["../../../../../src/integrations/graphqlClient.ts"],"sourcesContent":["import type { Client, IntegrationFn } from '@sentry/core';\nimport {\n defineIntegration,\n hasSpanStreamingEnabled,\n isObjectLike,\n isString,\n spanToJSON,\n stringMatchesSomePattern,\n} from '@sentry/core';\nimport type { FetchHint, XhrHint } from '@sentry/browser-utils';\nimport { getBodyString, getFetchRequestArgBody, SENTRY_XHR_DATA_KEY } from '@sentry/browser-utils';\nimport {\n GRAPHQL_DOCUMENT,\n GRAPHQL_OPERATION_NAME,\n GRAPHQL_OPERATION_TYPE,\n HTTP_METHOD,\n HTTP_REQUEST_METHOD,\n SENTRY_OP,\n URL_FULL,\n} from '@sentry/conventions/attributes';\n\ninterface GraphQLClientOptions {\n endpoints: Array<string | RegExp>;\n}\n\n/** Standard graphql request shape: https://graphql.org/learn/serving-over-http/#post-request-and-body */\ninterface GraphQLStandardRequest {\n query: string;\n operationName?: string;\n variables?: Record<string, unknown>;\n extensions?: Record<string, unknown>;\n}\n\n/** Persisted operation request */\ninterface GraphQLPersistedRequest {\n operationName: string;\n variables?: Record<string, unknown>;\n extensions: {\n persistedQuery: {\n version: number;\n sha256Hash: string;\n };\n } & Record<string, unknown>;\n}\n\ntype GraphQLRequestPayload = GraphQLStandardRequest | GraphQLPersistedRequest;\n\ninterface GraphQLOperation {\n operationType?: string;\n operationName?: string;\n}\n\nconst INTEGRATION_NAME = 'GraphQLClient' as const;\n\nconst _graphqlClientIntegration = ((options: GraphQLClientOptions) => {\n return {\n name: INTEGRATION_NAME,\n setup(client: Client) {\n _updateSpanWithGraphQLData(client, options);\n _updateBreadcrumbWithGraphQLData(client, options);\n },\n };\n}) satisfies IntegrationFn;\n\nfunction _updateSpanWithGraphQLData(client: Client, options: GraphQLClientOptions): void {\n client.on('beforeOutgoingRequestSpan', (span, hint) => {\n const spanJSON = spanToJSON(span);\n\n const spanAttributes = spanJSON.attributes;\n const spanOp = spanAttributes[SENTRY_OP];\n\n const isHttpClientSpan = spanOp === 'http.client';\n\n if (!isHttpClientSpan) {\n return;\n }\n\n const httpUrl = spanAttributes[URL_FULL];\n // oxlint-disable-next-line typescript/no-deprecated\n const httpMethod = spanAttributes[HTTP_REQUEST_METHOD] || spanAttributes[HTTP_METHOD];\n\n if (!isString(httpUrl) || !isString(httpMethod)) {\n return;\n }\n\n const { endpoints } = options;\n const isTracedGraphqlEndpoint = stringMatchesSomePattern(httpUrl, endpoints);\n const payload = getRequestPayloadXhrOrFetch(hint as XhrHint | FetchHint);\n\n if (isTracedGraphqlEndpoint && payload) {\n const graphqlBody = getGraphQLRequestPayload(payload);\n\n if (graphqlBody) {\n // With span streaming the span already carries a low-cardinality name, so it must not be\n // renamed back to one containing the URL. The operation stays reachable as an attribute.\n if (!hasSpanStreamingEnabled(client)) {\n span.updateName(`${httpMethod} ${httpUrl} (${_getGraphQLOperation(graphqlBody)})`);\n }\n\n const { operationName, operationType } = _getGraphQLOperationDetails(graphqlBody);\n span.setAttribute(GRAPHQL_OPERATION_NAME, operationName);\n span.setAttribute(GRAPHQL_OPERATION_TYPE, operationType);\n\n // Handle standard requests - capture the query document when enabled via dataCollection (default true)\n if (isStandardRequest(graphqlBody) && client.getDataCollectionOptions().graphQL.document === true) {\n span.setAttribute(GRAPHQL_DOCUMENT, graphqlBody.query);\n }\n\n // Handle persisted operations - capture hash for debugging\n if (isPersistedRequest(graphqlBody)) {\n span.setAttribute('graphql.persisted_query.hash.sha256', graphqlBody.extensions.persistedQuery.sha256Hash);\n span.setAttribute('graphql.persisted_query.version', graphqlBody.extensions.persistedQuery.version);\n }\n }\n }\n });\n}\n\nfunction _updateBreadcrumbWithGraphQLData(client: Client, options: GraphQLClientOptions): void {\n client.on('beforeOutgoingRequestBreadcrumb', (breadcrumb, handlerData) => {\n const { category, type, data } = breadcrumb;\n\n const isFetch = category === 'fetch';\n const isXhr = category === 'xhr';\n const isHttpBreadcrumb = type === 'http';\n\n if (isHttpBreadcrumb && (isFetch || isXhr)) {\n const httpUrl = data?.url;\n const { endpoints } = options;\n\n const isTracedGraphqlEndpoint = stringMatchesSomePattern(httpUrl, endpoints);\n const payload = getRequestPayloadXhrOrFetch(handlerData as XhrHint | FetchHint);\n\n if (isTracedGraphqlEndpoint && data && payload) {\n const graphqlBody = getGraphQLRequestPayload(payload);\n\n if (!data.graphql && graphqlBody) {\n const operationInfo = _getGraphQLOperation(graphqlBody);\n\n data['graphql.operation'] = operationInfo;\n\n if (isStandardRequest(graphqlBody) && client.getDataCollectionOptions().graphQL.document === true) {\n data[GRAPHQL_DOCUMENT] = graphqlBody.query;\n }\n\n if (isPersistedRequest(graphqlBody)) {\n data['graphql.persisted_query.hash.sha256'] = graphqlBody.extensions.persistedQuery.sha256Hash;\n data['graphql.persisted_query.version'] = graphqlBody.extensions.persistedQuery.version;\n }\n }\n }\n }\n });\n}\n\n/**\n * The operation name and type of a GraphQL request. Persisted operations carry no query document, so\n * their type is unknown.\n */\nfunction _getGraphQLOperationDetails(requestBody: GraphQLRequestPayload): GraphQLOperation {\n if (isPersistedRequest(requestBody)) {\n return { operationName: requestBody.operationName, operationType: undefined };\n }\n\n if (isStandardRequest(requestBody)) {\n const { query: graphqlQuery, operationName: graphqlOperationName } = requestBody;\n const { operationName = graphqlOperationName, operationType } = parseGraphQLQuery(graphqlQuery);\n return { operationName, operationType };\n }\n\n return { operationName: undefined, operationType: undefined };\n}\n\n/**\n * @param requestBody - GraphQL request\n * @returns A formatted version of the request: 'TYPE NAME' or 'TYPE' or 'persisted NAME'\n */\nexport function _getGraphQLOperation(requestBody: GraphQLRequestPayload): string {\n // Handle persisted operations\n if (isPersistedRequest(requestBody)) {\n return `persisted ${requestBody.operationName}`;\n }\n\n // Handle standard GraphQL requests\n if (isStandardRequest(requestBody)) {\n const { operationName, operationType } = _getGraphQLOperationDetails(requestBody);\n return operationName ? `${operationType} ${operationName}` : `${operationType}`;\n }\n\n // Fallback for unknown request types\n return 'unknown';\n}\n\n/**\n * Get the request body/payload based on the shape of the hint.\n *\n * Exported for tests only.\n */\nexport function getRequestPayloadXhrOrFetch(hint: XhrHint | FetchHint): string | undefined {\n const isXhr = 'xhr' in hint;\n\n let body: string | undefined;\n\n if (isXhr) {\n const sentryXhrData = hint.xhr[SENTRY_XHR_DATA_KEY];\n body = sentryXhrData && getBodyString(sentryXhrData.body)[0];\n } else {\n const sentryFetchData = getFetchRequestArgBody(hint.input);\n body = getBodyString(sentryFetchData)[0];\n }\n\n return body;\n}\n\n/**\n * Extract the name and type of the operation from the GraphQL query.\n *\n * Exported for tests only.\n */\nexport function parseGraphQLQuery(query: string): GraphQLOperation {\n const namedQueryRe = /^(?:\\s*)(query|mutation|subscription)(?:\\s*)(\\w+)(?:\\s*)[{(]/;\n const unnamedQueryRe = /^(?:\\s*)(query|mutation|subscription)(?:\\s*)[{(]/;\n\n const namedMatch = query.match(namedQueryRe);\n if (namedMatch) {\n return {\n operationType: namedMatch[1],\n operationName: namedMatch[2],\n };\n }\n\n const unnamedMatch = query.match(unnamedQueryRe);\n if (unnamedMatch) {\n return {\n operationType: unnamedMatch[1],\n operationName: undefined,\n };\n }\n return {\n operationType: undefined,\n operationName: undefined,\n };\n}\n\n/**\n * Helper to safely check if a value is a non-null object\n */\n\n/**\n * Type guard to check if a request is a standard GraphQL request\n */\nfunction isStandardRequest(payload: unknown): payload is GraphQLStandardRequest {\n return isObjectLike(payload) && typeof payload.query === 'string';\n}\n\n/**\n * Type guard to check if a request is a persisted operation request\n */\nfunction isPersistedRequest(payload: unknown): payload is GraphQLPersistedRequest {\n return (\n isObjectLike(payload) &&\n typeof payload.operationName === 'string' &&\n isObjectLike(payload.extensions) &&\n isObjectLike(payload.extensions.persistedQuery) &&\n typeof payload.extensions.persistedQuery.sha256Hash === 'string' &&\n typeof payload.extensions.persistedQuery.version === 'number'\n );\n}\n\n/**\n * Extract the payload of a request if it's GraphQL.\n * Exported for tests only.\n * @param payload - A valid JSON string\n * @returns A POJO or undefined\n */\nexport function getGraphQLRequestPayload(payload: string): GraphQLRequestPayload | undefined {\n try {\n const requestBody = JSON.parse(payload);\n\n // Return any valid GraphQL request (standard, persisted, or APQ retry with both)\n if (isStandardRequest(requestBody) || isPersistedRequest(requestBody)) {\n return requestBody;\n }\n\n // Not a GraphQL request\n return undefined;\n } catch {\n // Invalid JSON\n return undefined;\n }\n}\n\n/**\n * This integration ensures that GraphQL requests made in the browser\n * have their GraphQL-specific data captured and attached to spans and breadcrumbs.\n */\nexport const graphqlClientIntegration = defineIntegration(_graphqlClientIntegration);\n"],"names":["spanToJSON","SENTRY_OP","URL_FULL","HTTP_REQUEST_METHOD","HTTP_METHOD","isString","stringMatchesSomePattern","hasSpanStreamingEnabled","GRAPHQL_OPERATION_NAME","GRAPHQL_OPERATION_TYPE","GRAPHQL_DOCUMENT","SENTRY_XHR_DATA_KEY","getBodyString","getFetchRequestArgBody","isObjectLike","defineIntegration"],"mappings":";;;;;;AAoDA,MAAM,gBAAA,GAAmB,eAAA;AAEzB,MAAM,yBAAA,IAA6B,CAAC,OAAA,KAAkC;AACpE,EAAA,OAAO;AAAA,IACL,IAAA,EAAM,gBAAA;AAAA,IACN,MAAM,MAAA,EAAgB;AACpB,MAAA,0BAAA,CAA2B,QAAQ,OAAO,CAAA;AAC1C,MAAA,gCAAA,CAAiC,QAAQ,OAAO,CAAA;AAAA,IAClD;AAAA,GACF;AACF,CAAA,CAAA;AAEA,SAAS,0BAAA,CAA2B,QAAgB,OAAA,EAAqC;AACvF,EAAA,MAAA,CAAO,EAAA,CAAG,2B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es: {
|
|
102
|
-
[
|
|
102
|
+
[attributes.SENTRY_LINK_TYPE]: "previous_trace"
|
|
103
103
|
}
|
|
104
104
|
});
|
|
105
105
|
span.setAttribute(
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"linkedTraces.js","sources":["../../../../../src/tracing/linkedTraces.ts"],"sourcesContent":["import type { Client, PropagationContext, Span, SpanContextData } from '@sentry/core';\nimport {\n debug,\n getCurrentScope,\n getRootSpan,\n SEMANTIC_ATTRIBUTE_SENTRY_PREVIOUS_TRACE_SAMPLE_RATE,\n SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE,\n SEMANTIC_LINK_ATTRIBUTE_LINK_TYPE,\n spanToJSON,\n} from '@sentry/core';\nimport { DEBUG_BUILD } from '../debug-build';\nimport { WINDOW } from '../exports';\nimport { SENTRY_OP } from '@sentry/conventions/attributes';\n\nexport interface PreviousTraceInfo {\n /**\n * Span context of the previous trace's local root span\n */\n spanContext: SpanContextData;\n\n /**\n * Timestamp in seconds when the previous trace was started\n */\n startTimestamp: number;\n\n /**\n * sample rate of the previous trace\n */\n sampleRate: number;\n\n /**\n * The sample rand of the previous trace\n */\n sampleRand: number;\n}\n\n// 1h in seconds\nexport const PREVIOUS_TRACE_MAX_DURATION = 3600;\n\n// session storage key\nexport const PREVIOUS_TRACE_KEY = 'sentry_previous_trace';\n\nexport const PREVIOUS_TRACE_TMP_SPAN_ATTRIBUTE = 'sentry.previous_trace';\n\n/**\n * Takes care of linking traces and applying the (consistent) sampling behavoiour based on the passed options\n * @param options - options for linking traces and consistent trace sampling (@see BrowserTracingOptions)\n * @param client - Sentry client\n */\nexport function linkTraces(\n client: Client,\n {\n linkPreviousTrace,\n consistentTraceSampling,\n }: {\n linkPreviousTrace: 'session-storage' | 'in-memory';\n consistentTraceSampling: boolean;\n },\n): void {\n const useSessionStorage = linkPreviousTrace === 'session-storage';\n\n let inMemoryPreviousTraceInfo = useSessionStorage ? getPreviousTraceFromSessionStorage() : undefined;\n\n client.on('spanStart', span => {\n if (getRootSpan(span) !== span) {\n return;\n }\n\n const oldPropagationContext = getCurrentScope().getPropagationContext();\n inMemoryPreviousTraceInfo = addPreviousTraceSpanLink(inMemoryPreviousTraceInfo, span, oldPropagationContext);\n\n if (useSessionStorage) {\n storePreviousTraceInSessionStorage(inMemoryPreviousTraceInfo);\n }\n });\n\n let isFirstTraceOnPageload = true;\n if (consistentTraceSampling) {\n /*\n When users opt into `consistentTraceSampling`, we need to ensure that we propagate\n the previous trace's sample rate and rand to the current trace. This is necessary because otherwise, span\n metric extrapolation is inaccurate, as we'd propagate too high of a sample rate for the subsequent traces.\n\n So therefore, we pretend that the previous trace was the parent trace of the newly started trace. To do that,\n we mutate the propagation context of the current trace and set the sample rate and sample rand of the previous trace.\n Timing-wise, it is fine because it happens before we even sample the root span.\n\n @see https://github.com/getsentry/sentry-javascript/issues/15754\n */\n client.on('beforeSampling', mutableSamplingContextData => {\n if (!inMemoryPreviousTraceInfo) {\n return;\n }\n\n const scope = getCurrentScope();\n const currentPropagationContext = scope.getPropagationContext();\n\n // We do not want to force-continue the sampling decision if we continue a trace\n // that was started on the backend. Most prominently, this will happen in MPAs where\n // users hard-navigate between pages. In this case, the sampling decision of a potentially\n // started trace on the server takes precedence.\n // Why? We want to prioritize inter-trace consistency over intra-trace consistency.\n if (isFirstTraceOnPageload && currentPropagationContext.parentSpanId) {\n isFirstTraceOnPageload = false;\n return;\n }\n\n scope.setPropagationContext({\n ...currentPropagationContext,\n dsc: {\n ...currentPropagationContext.dsc,\n sample_rate: String(inMemoryPreviousTraceInfo.sampleRate),\n sampled: String(spanContextSampled(inMemoryPreviousTraceInfo.spanContext)),\n },\n sampleRand: inMemoryPreviousTraceInfo.sampleRand,\n });\n\n mutableSamplingContextData.parentSampled = spanContextSampled(inMemoryPreviousTraceInfo.spanContext);\n mutableSamplingContextData.parentSampleRate = inMemoryPreviousTraceInfo.sampleRate;\n\n mutableSamplingContextData.spanAttributes = {\n ...mutableSamplingContextData.spanAttributes,\n [SEMANTIC_ATTRIBUTE_SENTRY_PREVIOUS_TRACE_SAMPLE_RATE]: inMemoryPreviousTraceInfo.sampleRate,\n };\n });\n }\n}\n\n/**\n * Adds a previous_trace span link to the passed span if the passed\n * previousTraceInfo is still valid.\n *\n * @returns the updated previous trace info (based on the current span/trace) to\n * be used on the next call\n */\nexport function addPreviousTraceSpanLink(\n previousTraceInfo: PreviousTraceInfo | undefined,\n span: Span,\n oldPropagationContext: PropagationContext,\n): PreviousTraceInfo {\n const spanJson = spanToJSON(span);\n\n function getSampleRate(): number {\n try {\n const oldSampleRate = Number(\n spanJson.attributes[SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE] ?? oldPropagationContext.dsc?.sample_rate,\n );\n return Number.isNaN(oldSampleRate) ? 0 : oldSampleRate;\n } catch {\n return 0;\n }\n }\n\n const updatedPreviousTraceInfo = {\n spanContext: span.spanContext(),\n startTimestamp: spanJson.start_timestamp,\n sampleRate: getSampleRate(),\n sampleRand: oldPropagationContext.sampleRand,\n };\n\n if (!previousTraceInfo) {\n return updatedPreviousTraceInfo;\n }\n\n const previousTraceSpanCtx = previousTraceInfo.spanContext;\n if (previousTraceSpanCtx.traceId === spanJson.trace_id) {\n // This means, we're still in the same trace so let's not update the previous trace info\n // or add a link to the current span.\n // Once we move away from the long-lived, route-based trace model, we can remove this cases\n return previousTraceInfo;\n }\n\n // Only add the link if the startTimeStamp of the previous trace's root span is within\n // PREVIOUS_TRACE_MAX_DURATION (1h) of the current root span's startTimestamp\n // This is done to\n // - avoid adding links to \"stale\" traces\n // - enable more efficient querying for previous/next traces in Sentry\n if (Date.now() / 1000 - previousTraceInfo.startTimestamp <= PREVIOUS_TRACE_MAX_DURATION) {\n if (DEBUG_BUILD) {\n debug.log(\n `Adding previous_trace \\`${JSON.stringify(previousTraceSpanCtx)}\\` link to span \\`${JSON.stringify({\n op: spanJson.attributes[SENTRY_OP],\n ...span.spanContext(),\n })}\\``,\n );\n }\n\n span.addLink({\n context: previousTraceSpanCtx,\n attributes: {\n [SEMANTIC_LINK_ATTRIBUTE_LINK_TYPE]: 'previous_trace',\n },\n });\n\n // TODO(v12): Remove this once the Sentry trace view finds linked traces via span links. EAP stores\n // span links, but the trace view still reads this attribute to navigate to the previous/next trace.\n span.setAttribute(\n PREVIOUS_TRACE_TMP_SPAN_ATTRIBUTE,\n `${previousTraceSpanCtx.traceId}-${previousTraceSpanCtx.spanId}-${\n spanContextSampled(previousTraceSpanCtx) ? 1 : 0\n }`,\n );\n }\n\n return updatedPreviousTraceInfo;\n}\n\n/**\n * Stores @param previousTraceInfo in sessionStorage.\n */\nexport function storePreviousTraceInSessionStorage(previousTraceInfo: PreviousTraceInfo): void {\n try {\n WINDOW.sessionStorage.setItem(PREVIOUS_TRACE_KEY, JSON.stringify(previousTraceInfo));\n } catch (e) {\n // Ignore potential errors (e.g. if sessionStorage is not available)\n DEBUG_BUILD && debug.warn('Could not store previous trace in sessionStorage', e);\n }\n}\n\n/**\n * Retrieves the previous trace from sessionStorage if available.\n */\nexport function getPreviousTraceFromSessionStorage(): PreviousTraceInfo | undefined {\n try {\n const previousTraceInfo = WINDOW.sessionStorage?.getItem(PREVIOUS_TRACE_KEY);\n // @ts-expect-error - intentionally risking JSON.parse throwing when previousTraceInfo is null to save bundle size\n return JSON.parse(previousTraceInfo);\n } catch {\n return undefined;\n }\n}\n\n/**\n * see {@link import('@sentry/core').spanIsSampled}\n */\nexport function spanContextSampled(ctx: SpanContextData): boolean {\n return ctx.traceFlags === 0x1;\n}\n"],"names":["getRootSpan","getCurrentScope","SEMANTIC_ATTRIBUTE_SENTRY_PREVIOUS_TRACE_SAMPLE_RATE","spanToJSON","SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE","DEBUG_BUILD","debug","SENTRY_OP","SEMANTIC_LINK_ATTRIBUTE_LINK_TYPE","WINDOW"],"mappings":";;;;;;;;;;;;;;;AAqCO,MAAM,2BAAA,GAA8B;AAGpC,MAAM,kBAAA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AAA,GAAoBG,cAAA,CAAO,cAAA,EAAgB,OAAA,CAAQ,kBAAkB,CAAA;AAE3E,IAAA,OAAO,IAAA,CAAK,MAAM,iBAAiB,CAAA;AAAA,EACrC,CAAA,CAAA,MAAQ;AACN,IAAA,OAAO,MAAA;AAAA,EACT;AACF;AAKO,SAAS,mBAAmB,GAAA,EAA+B;AAChE,EAAA,OAAO,IAAI,UAAA,KAAe,CAAA;AAC5B;;;;;;;;;;;"}
|
|
1
|
+
{"version":3,"file":"linkedTraces.js","sources":["../../../../../src/tracing/linkedTraces.ts"],"sourcesContent":["import type { Client, PropagationContext, Span, SpanContextData } from '@sentry/core';\nimport {\n debug,\n getCurrentScope,\n getRootSpan,\n SEMANTIC_ATTRIBUTE_SENTRY_PREVIOUS_TRACE_SAMPLE_RATE,\n SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE,\n spanToJSON,\n} from '@sentry/core';\nimport { DEBUG_BUILD } from '../debug-build';\nimport { WINDOW } from '../exports';\nimport { SENTRY_LINK_TYPE, SENTRY_OP } from '@sentry/conventions/attributes';\n\nexport interface PreviousTraceInfo {\n /**\n * Span context of the previous trace's local root span\n */\n spanContext: SpanContextData;\n\n /**\n * Timestamp in seconds when the previous trace was started\n */\n startTimestamp: number;\n\n /**\n * sample rate of the previous trace\n */\n sampleRate: number;\n\n /**\n * The sample rand of the previous trace\n */\n sampleRand: number;\n}\n\n// 1h in seconds\nexport const PREVIOUS_TRACE_MAX_DURATION = 3600;\n\n// session storage key\nexport const PREVIOUS_TRACE_KEY = 'sentry_previous_trace';\n\nexport const PREVIOUS_TRACE_TMP_SPAN_ATTRIBUTE = 'sentry.previous_trace';\n\n/**\n * Takes care of linking traces and applying the (consistent) sampling behavoiour based on the passed options\n * @param options - options for linking traces and consistent trace sampling (@see BrowserTracingOptions)\n * @param client - Sentry client\n */\nexport function linkTraces(\n client: Client,\n {\n linkPreviousTrace,\n consistentTraceSampling,\n }: {\n linkPreviousTrace: 'session-storage' | 'in-memory';\n consistentTraceSampling: boolean;\n },\n): void {\n const useSessionStorage = linkPreviousTrace === 'session-storage';\n\n let inMemoryPreviousTraceInfo = useSessionStorage ? getPreviousTraceFromSessionStorage() : undefined;\n\n client.on('spanStart', span => {\n if (getRootSpan(span) !== span) {\n return;\n }\n\n const oldPropagationContext = getCurrentScope().getPropagationContext();\n inMemoryPreviousTraceInfo = addPreviousTraceSpanLink(inMemoryPreviousTraceInfo, span, oldPropagationContext);\n\n if (useSessionStorage) {\n storePreviousTraceInSessionStorage(inMemoryPreviousTraceInfo);\n }\n });\n\n let isFirstTraceOnPageload = true;\n if (consistentTraceSampling) {\n /*\n When users opt into `consistentTraceSampling`, we need to ensure that we propagate\n the previous trace's sample rate and rand to the current trace. This is necessary because otherwise, span\n metric extrapolation is inaccurate, as we'd propagate too high of a sample rate for the subsequent traces.\n\n So therefore, we pretend that the previous trace was the parent trace of the newly started trace. To do that,\n we mutate the propagation context of the current trace and set the sample rate and sample rand of the previous trace.\n Timing-wise, it is fine because it happens before we even sample the root span.\n\n @see https://github.com/getsentry/sentry-javascript/issues/15754\n */\n client.on('beforeSampling', mutableSamplingContextData => {\n if (!inMemoryPreviousTraceInfo) {\n return;\n }\n\n const scope = getCurrentScope();\n const currentPropagationContext = scope.getPropagationContext();\n\n // We do not want to force-continue the sampling decision if we continue a trace\n // that was started on the backend. Most prominently, this will happen in MPAs where\n // users hard-navigate between pages. In this case, the sampling decision of a potentially\n // started trace on the server takes precedence.\n // Why? We want to prioritize inter-trace consistency over intra-trace consistency.\n if (isFirstTraceOnPageload && currentPropagationContext.parentSpanId) {\n isFirstTraceOnPageload = false;\n return;\n }\n\n scope.setPropagationContext({\n ...currentPropagationContext,\n dsc: {\n ...currentPropagationContext.dsc,\n sample_rate: String(inMemoryPreviousTraceInfo.sampleRate),\n sampled: String(spanContextSampled(inMemoryPreviousTraceInfo.spanContext)),\n },\n sampleRand: inMemoryPreviousTraceInfo.sampleRand,\n });\n\n mutableSamplingContextData.parentSampled = spanContextSampled(inMemoryPreviousTraceInfo.spanContext);\n mutableSamplingContextData.parentSampleRate = inMemoryPreviousTraceInfo.sampleRate;\n\n mutableSamplingContextData.spanAttributes = {\n ...mutableSamplingContextData.spanAttributes,\n [SEMANTIC_ATTRIBUTE_SENTRY_PREVIOUS_TRACE_SAMPLE_RATE]: inMemoryPreviousTraceInfo.sampleRate,\n };\n });\n }\n}\n\n/**\n * Adds a previous_trace span link to the passed span if the passed\n * previousTraceInfo is still valid.\n *\n * @returns the updated previous trace info (based on the current span/trace) to\n * be used on the next call\n */\nexport function addPreviousTraceSpanLink(\n previousTraceInfo: PreviousTraceInfo | undefined,\n span: Span,\n oldPropagationContext: PropagationContext,\n): PreviousTraceInfo {\n const spanJson = spanToJSON(span);\n\n function getSampleRate(): number {\n try {\n const oldSampleRate = Number(\n spanJson.attributes[SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE] ?? oldPropagationContext.dsc?.sample_rate,\n );\n return Number.isNaN(oldSampleRate) ? 0 : oldSampleRate;\n } catch {\n return 0;\n }\n }\n\n const updatedPreviousTraceInfo = {\n spanContext: span.spanContext(),\n startTimestamp: spanJson.start_timestamp,\n sampleRate: getSampleRate(),\n sampleRand: oldPropagationContext.sampleRand,\n };\n\n if (!previousTraceInfo) {\n return updatedPreviousTraceInfo;\n }\n\n const previousTraceSpanCtx = previousTraceInfo.spanContext;\n if (previousTraceSpanCtx.traceId === spanJson.trace_id) {\n // This means, we're still in the same trace so let's not update the previous trace info\n // or add a link to the current span.\n // Once we move away from the long-lived, route-based trace model, we can remove this cases\n return previousTraceInfo;\n }\n\n // Only add the link if the startTimeStamp of the previous trace's root span is within\n // PREVIOUS_TRACE_MAX_DURATION (1h) of the current root span's startTimestamp\n // This is done to\n // - avoid adding links to \"stale\" traces\n // - enable more efficient querying for previous/next traces in Sentry\n if (Date.now() / 1000 - previousTraceInfo.startTimestamp <= PREVIOUS_TRACE_MAX_DURATION) {\n if (DEBUG_BUILD) {\n debug.log(\n `Adding previous_trace \\`${JSON.stringify(previousTraceSpanCtx)}\\` link to span \\`${JSON.stringify({\n op: spanJson.attributes[SENTRY_OP],\n ...span.spanContext(),\n })}\\``,\n );\n }\n\n span.addLink({\n context: previousTraceSpanCtx,\n attributes: {\n [SENTRY_LINK_TYPE]: 'previous_trace',\n },\n });\n\n // TODO(v12): Remove this once the Sentry trace view finds linked traces via span links. EAP stores\n // span links, but the trace view still reads this attribute to navigate to the previous/next trace.\n span.setAttribute(\n PREVIOUS_TRACE_TMP_SPAN_ATTRIBUTE,\n `${previousTraceSpanCtx.traceId}-${previousTraceSpanCtx.spanId}-${\n spanContextSampled(previousTraceSpanCtx) ? 1 : 0\n }`,\n );\n }\n\n return updatedPreviousTraceInfo;\n}\n\n/**\n * Stores @param previousTraceInfo in sessionStorage.\n */\nexport function storePreviousTraceInSessionStorage(previousTraceInfo: PreviousTraceInfo): void {\n try {\n WINDOW.sessionStorage.setItem(PREVIOUS_TRACE_KEY, JSON.stringify(previousTraceInfo));\n } catch (e) {\n // Ignore potential errors (e.g. if sessionStorage is not available)\n DEBUG_BUILD && debug.warn('Could not store previous trace in sessionStorage', e);\n }\n}\n\n/**\n * Retrieves the previous trace from sessionStorage if available.\n */\nexport function getPreviousTraceFromSessionStorage(): PreviousTraceInfo | undefined {\n try {\n const previousTraceInfo = WINDOW.sessionStorage?.getItem(PREVIOUS_TRACE_KEY);\n // @ts-expect-error - intentionally risking JSON.parse throwing when previousTraceInfo is null to save bundle size\n return JSON.parse(previousTraceInfo);\n } catch {\n return undefined;\n }\n}\n\n/**\n * see {@link import('@sentry/core').spanIsSampled}\n */\nexport function spanContextSampled(ctx: SpanContextData): boolean {\n return ctx.traceFlags === 0x1;\n}\n"],"names":["getRootSpan","getCurrentScope","SEMANTIC_ATTRIBUTE_SENTRY_PREVIOUS_TRACE_SAMPLE_RATE","spanToJSON","SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE","DEBUG_BUILD","debug","SENTRY_OP","SENTRY_LINK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CAAA;AAAA,EACjF;AACF;AAKO,SAAS,kCAAA,GAAoE;AAClF,EAAA,IAAI;AACF,IAAA,MAAM,iBAAA,GAAoBG,cAAA,CAAO,cAAA,EAAgB,OAAA,CAAQ,kBAAkB,CAAA;AAE3E,IAAA,OAAO,IAAA,CAAK,MAAM,iBAAiB,CAAA;AAAA,EACrC,CAAA,CAAA,MAAQ;AACN,IAAA,OAAO,MAAA;AAAA,EACT;AACF;AAKO,SAAS,mBAAmB,GAAA,EAA+B;AAChE,EAAA,OAAO,IAAI,UAAA,KAAe,CAAA;AAC5B;;;;;;;;;;;"}
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { setRouteProvider } from '@sentry/browser-utils';
|
|
1
2
|
import { Client, getSDKSource, applySdkMetadata, addAutoIpAddressToSession } from '@sentry/core';
|
|
2
3
|
import { eventFromException, eventFromMessage } from './eventbuilder.js';
|
|
3
4
|
import { WINDOW } from './helpers.js';
|
|
@@ -13,6 +14,9 @@ class BrowserClient extends Client {
|
|
|
13
14
|
const sdkSource = WINDOW.SENTRY_SDK_SOURCE || getSDKSource();
|
|
14
15
|
applySdkMetadata(opts, "browser", ["browser"], sdkSource);
|
|
15
16
|
super(opts);
|
|
17
|
+
if (opts.routeProvider) {
|
|
18
|
+
setRouteProvider(opts.routeProvider, this);
|
|
19
|
+
}
|
|
16
20
|
this._unhandledSessionStatus = "unhandled";
|
|
17
21
|
const { userInfo } = this.getDataCollectionOptions();
|
|
18
22
|
if (opts._metadata?.sdk) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"client.js","sources":["../../../../src/client.ts"],"sourcesContent":["import type {\n ClientOptions,\n Event,\n EventHint,\n Options as CoreOptions,\n ParameterizedString,\n Scope,\n SeverityLevel,\n} from '@sentry/core';\nimport type { BrowserClientReplayOptions } from '@sentry/core/browser';\nimport { addAutoIpAddressToSession, applySdkMetadata, Client, getSDKSource } from '@sentry/core';\nimport { eventFromException, eventFromMessage } from './eventbuilder';\nimport { WINDOW } from './helpers';\nimport type { BrowserTransportOptions } from './transports/types';\n\n/**\n * A magic string that build tooling can leverage in order to inject a release value into the SDK.\n */\ndeclare const __SENTRY_RELEASE__: string | undefined;\n\nexport type BrowserClientProfilingOptions = {\n /**\n * Sets profiling session sample rate for the entire profiling session.\n *\n * A profiling session corresponds to a user session, meaning it is set once at integration initialization and\n * persisted until the next page reload. This rate determines what percentage of user sessions will have profiling enabled.\n * @default 0\n */\n profileSessionSampleRate?: number;\n\n /**\n * Set the lifecycle mode of the profiler.\n * - **manual**: The profiler will be manually started and stopped via `startProfiler`/`stopProfiler`.\n * If a session is sampled, is dependent on the `profileSessionSampleRate`.\n * - **trace**: The profiler will be automatically started when a root span exists and stopped when there are no\n * more sampled root spans. Whether a session is sampled, is dependent on the `profileSessionSampleRate` and the\n * existing sampling configuration for tracing (`tracesSampleRate`/`tracesSampler`).\n *\n * @default 'manual'\n */\n profileLifecycle?: 'manual' | 'trace';\n};\n\ntype BrowserSpecificOptions = BrowserClientReplayOptions &\n BrowserClientProfilingOptions & {\n /** If configured, this URL will be used as base URL for lazy loading integration. */\n cdnBaseUrl?: string;\n\n /**\n * Important: Only set this option if you know what you are doing!\n *\n * By default, the SDK will check if `Sentry.init` is called in a browser extension.\n * In case it is, it will stop initialization and log a warning\n * because browser extensions require a different Sentry initialization process:\n * https://docs.sentry.io/platforms/javascript/best-practices/shared-environments/\n *\n * Setting up the SDK in a browser extension with global error monitoring is not recommended\n * and will likely flood you with errors from other web sites or extensions. This can heavily\n * impact your quota and cause interference with your and other Sentry SDKs in shared environments.\n *\n * If this check wrongfully flags your setup as a browser extension, you can set this\n * option to `true` to skip the check.\n *\n * @default false\n */\n skipBrowserExtensionCheck?: boolean;\n\n /**\n * If you use Spotlight by Sentry during development, use\n * this option to forward captured Sentry events to Spotlight.\n *\n * Either set it to true, or provide a specific Spotlight Sidecar URL.\n *\n * More details: https://spotlightjs.com/\n *\n * IMPORTANT: Only set this option to `true` while developing, not in production!\n */\n spotlight?: boolean | string;\n };\n/**\n * Configuration options for the Sentry Browser SDK.\n * @see @sentry/core Options for more information.\n */\nexport type BrowserOptions = CoreOptions<BrowserTransportOptions> & BrowserSpecificOptions;\n\n/**\n * Configuration options for the Sentry Browser SDK Client class\n * @see BrowserClient for more information.\n */\nexport type BrowserClientOptions = ClientOptions<BrowserTransportOptions> & BrowserSpecificOptions;\n\n/**\n * The Sentry Browser SDK Client.\n *\n * @see BrowserOptions for documentation on configuration options.\n * @see SentryClient for usage documentation.\n */\nexport class BrowserClient extends Client<BrowserClientOptions> {\n /**\n * Creates a new Browser SDK instance.\n *\n * @param options Configuration options for this SDK.\n */\n public constructor(options: BrowserClientOptions) {\n const opts = applyDefaultOptions(options);\n const sdkSource = WINDOW.SENTRY_SDK_SOURCE || getSDKSource();\n applySdkMetadata(opts, 'browser', ['browser'], sdkSource);\n\n super(opts);\n\n // Unhandled errors don't actually crash the browser, so we report `unhandled` rather than `crashed`.\n this._unhandledSessionStatus = 'unhandled';\n\n const { userInfo } = this.getDataCollectionOptions();\n\n if (opts._metadata?.sdk) {\n opts._metadata.sdk.settings = {\n // Only allow IP inferral by Relay if the user opted in via dataCollection\n infer_ip: userInfo ? 'auto' : 'never',\n // purposefully allowing already passed settings to override the default\n ...opts._metadata.sdk.settings,\n };\n }\n\n const { sendClientReports } = this._options;\n\n // Flush buffered data when the page becomes hidden (e.g. tab switch, navigation, or the page\n // being discarded). `flush()` emits the `flush` hook, which drains the span (streaming), log and\n // metric buffers and hands the resulting envelopes to the transport (which uses `keepalive`).\n // Client report outcomes don't listen to the `flush` hook, so we flush them separately.\n if (WINDOW.document) {\n WINDOW.document.addEventListener('visibilitychange', () => {\n if (WINDOW.document.visibilityState === 'hidden') {\n if (sendClientReports) {\n this._flushOutcomes();\n }\n // Defer the flush to a microtask so that visibilitychange listeners registered after this\n // one have already run. In particular, browser tracing's background-tab detection ends the\n // active pageload/navigation (segment) span when the page is hidden. Deferring ensures that\n // segment span has been added to the streaming buffer before we flush, so it is sent\n // together with its child spans instead of being orphaned.\n queueMicrotask(() => {\n void this.flush();\n });\n }\n });\n }\n\n if (userInfo) {\n this.on('beforeSendSession', addAutoIpAddressToSession);\n }\n }\n\n /**\n * @inheritDoc\n */\n public eventFromException(exception: unknown, hint?: EventHint): PromiseLike<Event> {\n return eventFromException(this._options.stackParser, exception, hint, this._options.attachStacktrace);\n }\n\n /**\n * @inheritDoc\n */\n public eventFromMessage(\n message: ParameterizedString,\n level: SeverityLevel = 'info',\n hint?: EventHint,\n ): PromiseLike<Event> {\n return eventFromMessage(this._options.stackParser, message, level, hint, this._options.attachStacktrace);\n }\n\n /**\n * @inheritDoc\n */\n protected _prepareEvent(\n event: Event,\n hint: EventHint,\n currentScope: Scope,\n isolationScope: Scope,\n ): PromiseLike<Event | null> {\n event.platform = event.platform || 'javascript';\n\n return super._prepareEvent(event, hint, currentScope, isolationScope);\n }\n}\n\n/** Exported only for tests. */\nexport function applyDefaultOptions<T extends Partial<BrowserClientOptions>>(optionsArg: T): T {\n return {\n release:\n typeof __SENTRY_RELEASE__ === 'string' // This allows build tooling to find-and-replace __SENTRY_RELEASE__ to inject a release value\n ? __SENTRY_RELEASE__\n : WINDOW.SENTRY_RELEASE?.id, // This supports the variable that sentry-webpack-plugin injects\n sendClientReports: true,\n // We default this to true, as it is the safer scenario\n parentSpanIsAlwaysRootSpan: true,\n ...optionsArg,\n };\n}\n"],"names":[],"mappings":";;;;AAiGO,MAAM,sBAAsB,MAAA,CAA6B;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAMvD,YAAY,OAAA,EAA+B;AAChD,IAAA,MAAM,IAAA,GAAO,oBAAoB,OAAO,CAAA;AACxC,IAAA,MAAM,SAAA,GAAY,MAAA,CAAO,iBAAA,IAAqB,YAAA,EAAa;AAC3D,IAAA,gBAAA,CAAiB,IAAA,EAAM,SAAA,EAAW,CAAC,SAAS,GAAG,SAAS,CAAA;AAExD,IAAA,KAAA,CAAM,IAAI,CAAA;AAGV,IAA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QAAA,CAAS,WAAA,EAAa,SAAS,KAAA,EAAO,IAAA,EAAM,IAAA,CAAK,QAAA,CAAS,gBAAgB,CAAA;AAAA,EACzG;AAAA;AAAA;AAAA;AAAA,EAKU,aAAA,CACR,KAAA,EACA,IAAA,EACA,YAAA,EACA,cAAA,EAC2B;AAC3B,IAAA,KAAA,CAAM,QAAA,GAAW,MAAM,QAAA,IAAY,YAAA;AAEnC,IAAA,OAAO,KAAA,CAAM,aAAA,CAAc,KAAA,EAAO,IAAA,EAAM,cAAc,cAAc,CAAA;AAAA,EACtE;AACF;AAGO,SAAS,oBAA6D,UAAA,EAAkB;AAC7F,EAAA,OAAO;AAAA,IACL,SACE,OAAO,kBAAA,KAAuB,QAAA,GAC1B,kBAAA,GACA,OAAO,cAAA,EAAgB,EAAA;AAAA;AAAA,IAC7B,iBAAA,EAAmB,IAAA;AAAA;AAAA,IAEnB,0BAAA,EAA4B,IAAA;AAAA,IAC5B,GAAG;AAAA,GACL;AACF;;;;"}
|
|
1
|
+
{"version":3,"file":"client.js","sources":["../../../../src/client.ts"],"sourcesContent":["import type {\n ClientOptions,\n Event,\n EventHint,\n Options as CoreOptions,\n ParameterizedString,\n Scope,\n SeverityLevel,\n} from '@sentry/core';\nimport type { BrowserClientReplayOptions } from '@sentry/core/browser';\nimport type { RouteProvider } from '@sentry/browser-utils';\nimport { setRouteProvider } from '@sentry/browser-utils';\nimport { addAutoIpAddressToSession, applySdkMetadata, Client, getSDKSource } from '@sentry/core';\nimport { eventFromException, eventFromMessage } from './eventbuilder';\nimport { WINDOW } from './helpers';\nimport type { BrowserTransportOptions } from './transports/types';\n\n/**\n * A magic string that build tooling can leverage in order to inject a release value into the SDK.\n */\ndeclare const __SENTRY_RELEASE__: string | undefined;\n\nexport type BrowserClientProfilingOptions = {\n /**\n * Sets profiling session sample rate for the entire profiling session.\n *\n * A profiling session corresponds to a user session, meaning it is set once at integration initialization and\n * persisted until the next page reload. This rate determines what percentage of user sessions will have profiling enabled.\n * @default 0\n */\n profileSessionSampleRate?: number;\n\n /**\n * Set the lifecycle mode of the profiler.\n * - **manual**: The profiler will be manually started and stopped via `startProfiler`/`stopProfiler`.\n * If a session is sampled, is dependent on the `profileSessionSampleRate`.\n * - **trace**: The profiler will be automatically started when a root span exists and stopped when there are no\n * more sampled root spans. Whether a session is sampled, is dependent on the `profileSessionSampleRate` and the\n * existing sampling configuration for tracing (`tracesSampleRate`/`tracesSampler`).\n *\n * @default 'manual'\n */\n profileLifecycle?: 'manual' | 'trace';\n};\n\ntype BrowserSpecificOptions = BrowserClientReplayOptions &\n BrowserClientProfilingOptions & {\n /** If configured, this URL will be used as base URL for lazy loading integration. */\n cdnBaseUrl?: string;\n\n /**\n * Important: Only set this option if you know what you are doing!\n *\n * By default, the SDK will check if `Sentry.init` is called in a browser extension.\n * In case it is, it will stop initialization and log a warning\n * because browser extensions require a different Sentry initialization process:\n * https://docs.sentry.io/platforms/javascript/best-practices/shared-environments/\n *\n * Setting up the SDK in a browser extension with global error monitoring is not recommended\n * and will likely flood you with errors from other web sites or extensions. This can heavily\n * impact your quota and cause interference with your and other Sentry SDKs in shared environments.\n *\n * If this check wrongfully flags your setup as a browser extension, you can set this\n * option to `true` to skip the check.\n *\n * @default false\n */\n skipBrowserExtensionCheck?: boolean;\n\n /**\n * If you use Spotlight by Sentry during development, use\n * this option to forward captured Sentry events to Spotlight.\n *\n * Either set it to true, or provide a specific Spotlight Sidecar URL.\n *\n * More details: https://spotlightjs.com/\n *\n * IMPORTANT: Only set this option to `true` while developing, not in production!\n */\n spotlight?: boolean | string;\n\n /**\n * Resolves URLs to low-cardinality route names, e.g. `/users/42` -> `/users/:id`.\n *\n * Framework SDKs set this for you. Set it yourself to name routes for a router the SDK has no\n * integration for. `setRouteProvider` replaces it at runtime.\n */\n routeProvider?: RouteProvider;\n };\n/**\n * Configuration options for the Sentry Browser SDK.\n * @see @sentry/core Options for more information.\n */\nexport type BrowserOptions = CoreOptions<BrowserTransportOptions> & BrowserSpecificOptions;\n\n/**\n * Configuration options for the Sentry Browser SDK Client class\n * @see BrowserClient for more information.\n */\nexport type BrowserClientOptions = ClientOptions<BrowserTransportOptions> & BrowserSpecificOptions;\n\n/**\n * The Sentry Browser SDK Client.\n *\n * @see BrowserOptions for documentation on configuration options.\n * @see SentryClient for usage documentation.\n */\nexport class BrowserClient extends Client<BrowserClientOptions> {\n /**\n * Creates a new Browser SDK instance.\n *\n * @param options Configuration options for this SDK.\n */\n public constructor(options: BrowserClientOptions) {\n const opts = applyDefaultOptions(options);\n const sdkSource = WINDOW.SENTRY_SDK_SOURCE || getSDKSource();\n applySdkMetadata(opts, 'browser', ['browser'], sdkSource);\n\n super(opts);\n\n if (opts.routeProvider) {\n setRouteProvider(opts.routeProvider, this);\n }\n\n // Unhandled errors don't actually crash the browser, so we report `unhandled` rather than `crashed`.\n this._unhandledSessionStatus = 'unhandled';\n\n const { userInfo } = this.getDataCollectionOptions();\n\n if (opts._metadata?.sdk) {\n opts._metadata.sdk.settings = {\n // Only allow IP inferral by Relay if the user opted in via dataCollection\n infer_ip: userInfo ? 'auto' : 'never',\n // purposefully allowing already passed settings to override the default\n ...opts._metadata.sdk.settings,\n };\n }\n\n const { sendClientReports } = this._options;\n\n // Flush buffered data when the page becomes hidden (e.g. tab switch, navigation, or the page\n // being discarded). `flush()` emits the `flush` hook, which drains the span (streaming), log and\n // metric buffers and hands the resulting envelopes to the transport (which uses `keepalive`).\n // Client report outcomes don't listen to the `flush` hook, so we flush them separately.\n if (WINDOW.document) {\n WINDOW.document.addEventListener('visibilitychange', () => {\n if (WINDOW.document.visibilityState === 'hidden') {\n if (sendClientReports) {\n this._flushOutcomes();\n }\n // Defer the flush to a microtask so that visibilitychange listeners registered after this\n // one have already run. In particular, browser tracing's background-tab detection ends the\n // active pageload/navigation (segment) span when the page is hidden. Deferring ensures that\n // segment span has been added to the streaming buffer before we flush, so it is sent\n // together with its child spans instead of being orphaned.\n queueMicrotask(() => {\n void this.flush();\n });\n }\n });\n }\n\n if (userInfo) {\n this.on('beforeSendSession', addAutoIpAddressToSession);\n }\n }\n\n /**\n * @inheritDoc\n */\n public eventFromException(exception: unknown, hint?: EventHint): PromiseLike<Event> {\n return eventFromException(this._options.stackParser, exception, hint, this._options.attachStacktrace);\n }\n\n /**\n * @inheritDoc\n */\n public eventFromMessage(\n message: ParameterizedString,\n level: SeverityLevel = 'info',\n hint?: EventHint,\n ): PromiseLike<Event> {\n return eventFromMessage(this._options.stackParser, message, level, hint, this._options.attachStacktrace);\n }\n\n /**\n * @inheritDoc\n */\n protected _prepareEvent(\n event: Event,\n hint: EventHint,\n currentScope: Scope,\n isolationScope: Scope,\n ): PromiseLike<Event | null> {\n event.platform = event.platform || 'javascript';\n\n return super._prepareEvent(event, hint, currentScope, isolationScope);\n }\n}\n\n/** Exported only for tests. */\nexport function applyDefaultOptions<T extends Partial<BrowserClientOptions>>(optionsArg: T): T {\n return {\n release:\n typeof __SENTRY_RELEASE__ === 'string' // This allows build tooling to find-and-replace __SENTRY_RELEASE__ to inject a release value\n ? __SENTRY_RELEASE__\n : WINDOW.SENTRY_RELEASE?.id, // This supports the variable that sentry-webpack-plugin injects\n sendClientReports: true,\n // We default this to true, as it is the safer scenario\n parentSpanIsAlwaysRootSpan: true,\n ...optionsArg,\n };\n}\n"],"names":[],"mappings":";;;;;AA2GO,MAAM,sBAAsB,MAAA,CAA6B;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAMvD,YAAY,OAAA,EAA+B;AAChD,IAAA,MAAM,IAAA,GAAO,oBAAoB,OAAO,CAAA;AACxC,IAAA,MAAM,SAAA,GAAY,MAAA,CAAO,iBAAA,IAAqB,YAAA,EAAa;AAC3D,IAAA,gBAAA,CAAiB,IAAA,EAAM,SAAA,EAAW,CAAC,SAAS,GAAG,SAAS,CAAA;AAExD,IAAA,KAAA,CAAM,IAAI,CAAA;AAEV,IAAA,IAAI,KAAK,aAAA,EAAe;AACtB,MAAA,gBAAA,CAAiB,IAAA,CAAK,eAAe,IA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IAAA,OAAO,gBAAA,CAAiB,KAAK,QAAA,CAAS,WAAA,EAAa,SAAS,KAAA,EAAO,IAAA,EAAM,IAAA,CAAK,QAAA,CAAS,gBAAgB,CAAA;AAAA,EACzG;AAAA;AAAA;AAAA;AAAA,EAKU,aAAA,CACR,KAAA,EACA,IAAA,EACA,YAAA,EACA,cAAA,EAC2B;AAC3B,IAAA,KAAA,CAAM,QAAA,GAAW,MAAM,QAAA,IAAY,YAAA;AAEnC,IAAA,OAAO,KAAA,CAAM,aAAA,CAAc,KAAA,EAAO,IAAA,EAAM,cAAc,cAAc,CAAA;AAAA,EACtE;AACF;AAGO,SAAS,oBAA6D,UAAA,EAAkB;AAC7F,EAAA,OAAO;AAAA,IACL,SACE,OAAO,kBAAA,KAAuB,QAAA,GAC1B,kBAAA,GACA,OAAO,cAAA,EAAgB,EAAA;AAAA;AAAA,IAC7B,iBAAA,EAAmB,IAAA;AAAA;AAAA,IAEnB,0BAAA,EAA4B,IAAA;AAAA,IAC5B,GAAG;AAAA,GACL;AACF;;;;"}
|
|
@@ -27,7 +27,7 @@ export { replayCanvasIntegration } from '@sentry/replay-canvas';
|
|
|
27
27
|
export { getFeedback, sendFeedback } from '@sentry/feedback';
|
|
28
28
|
export { defaultRequestInstrumentationOptions, instrumentOutgoingRequests } from './tracing/request.js';
|
|
29
29
|
export { browserTracingIntegration, startBrowserTracingNavigationSpan, startBrowserTracingPageLoadSpan } from './tracing/browserTracingIntegration.js';
|
|
30
|
-
export { elementTimingIntegration, getAbsoluteUrl, interactionsIntegration, isBotUserAgent, userTimingIntegration } from '@sentry/browser-utils';
|
|
30
|
+
export { createCachedRouteProvider, createUrlRouteProvider, elementTimingIntegration, getAbsoluteUrl, getRouteProvider, interactionsIntegration, isBotUserAgent, resolveCurrentRoute, resolveRoute, setRouteProvider, userTimingIntegration } from '@sentry/browser-utils';
|
|
31
31
|
export { normalizeStringifyValue } from './normalizeStringifyValue.js';
|
|
32
32
|
export { reportPageLoaded } from './tracing/reportPageLoaded.js';
|
|
33
33
|
export { setActiveSpanInBrowser } from './tracing/setActiveSpan.js';
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { SENTRY_ORIGIN, SENTRY_SEGMENT_NAME, BROWSER_BFCACHE_FRAME, BROWSER_BFCACHE_REASON, BROWSER_BFCACHE_NOT_RESTORED_REASON_COUNT, BROWSER_BFCACHE_OUTCOME } from '@sentry/conventions/attributes';
|
|
2
2
|
import { defineIntegration, debug, metrics, getCurrentScope } from '@sentry/core';
|
|
3
|
+
import { resolveCurrentRoute } from '@sentry/browser-utils';
|
|
3
4
|
import { DEBUG_BUILD } from '../debug-build.js';
|
|
4
5
|
import { WINDOW } from '../helpers.js';
|
|
5
6
|
|
|
@@ -61,7 +62,7 @@ function _captureBFCacheReason({ reason, frame }, routeName) {
|
|
|
61
62
|
});
|
|
62
63
|
}
|
|
63
64
|
function _getSegmentName() {
|
|
64
|
-
return getCurrentScope().getScopeData().transactionName || WINDOW.location?.pathname;
|
|
65
|
+
return resolveCurrentRoute() || getCurrentScope().getScopeData().transactionName || WINDOW.location?.pathname;
|
|
65
66
|
}
|
|
66
67
|
function _resolveMaxReasons(maxReasons) {
|
|
67
68
|
if (maxReasons == null) {
|
|
@@ -107,5 +108,5 @@ function _withOriginAttr(attributes) {
|
|
|
107
108
|
return attributes;
|
|
108
109
|
}
|
|
109
110
|
|
|
110
|
-
export { _collectNotRestoredReasons, _resolveMaxReasons, bfcacheMetricsIntegration };
|
|
111
|
+
export { _collectNotRestoredReasons, _getSegmentName, _resolveMaxReasons, bfcacheMetricsIntegration };
|
|
111
112
|
//# sourceMappingURL=bfcacheMetrics.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"bfcacheMetrics.js","sources":["../../../../../src/integrations/bfcacheMetrics.ts"],"sourcesContent":["import {\n SENTRY_SEGMENT_NAME,\n BROWSER_BFCACHE_FRAME,\n BROWSER_BFCACHE_NOT_RESTORED_REASON_COUNT,\n BROWSER_BFCACHE_OUTCOME,\n BROWSER_BFCACHE_REASON,\n SENTRY_ORIGIN,\n} from '@sentry/conventions/attributes';\nimport type { IntegrationFn, SpanAttributes } from '@sentry/core';\nimport { debug, defineIntegration, getCurrentScope, metrics } from '@sentry/core';\nimport { DEBUG_BUILD } from '../debug-build';\nimport { WINDOW } from '../helpers';\n\nconst INTEGRATION_NAME = 'BfcacheMetrics';\n\ntype BFCacheOutcome = 'hit' | 'miss';\n\ntype BFCacheFrame = 'top' | 'child';\n\ninterface BFCacheMetricsIntegrationOptions {\n /**\n * Maximum number of not-restored reasons to emit per miss.\n *\n * By default every reason is reported. Set this to cap the number emitted per miss.\n * Values below 1 are clamped to 1.\n */\n maxReasons: number;\n}\n\ninterface NotRestoredReason {\n reason?: string;\n}\n\ninterface NotRestoredReasons {\n children?: NotRestoredReasons[] | null;\n reasons?: (NotRestoredReason | string)[] | null;\n}\n\ninterface NavigationTimingWithNotRestoredReasons extends PerformanceNavigationTiming {\n notRestoredReasons?: NotRestoredReasons | null;\n}\n\ninterface CollectedReason {\n reason: string;\n frame: BFCacheFrame;\n}\n\n/**\n * Captures bfcache hit/miss counters and Chromium notRestoredReasons when available.\n */\nexport const bfcacheMetricsIntegration = defineIntegration(\n (options: Partial<BFCacheMetricsIntegrationOptions> = {}) => {\n const maxReasons = _resolveMaxReasons(options.maxReasons);\n\n return {\n name: INTEGRATION_NAME,\n\n setupOnce() {\n if (!WINDOW.addEventListener || !WINDOW.performance?.getEntriesByType) {\n DEBUG_BUILD && debug.log(`[${INTEGRATION_NAME}] Browser APIs unavailable, skipping instrumentation.`);\n return;\n }\n\n function onPageShow(event: PageTransitionEvent) {\n const routeName = _getSegmentName();\n if (event.persisted) {\n _captureBFCacheNavigation('hit', 0, routeName);\n return;\n }\n\n const navigationEntry = WINDOW.performance.getEntriesByType('navigation')[0] as\n | NavigationTimingWithNotRestoredReasons\n | undefined;\n\n if (navigationEntry?.type !== 'back_forward') {\n return;\n }\n\n const reasons = _collectNotRestoredReasons(navigationEntry.notRestoredReasons, maxReasons);\n _captureBFCacheNavigation('miss', reasons.length, routeName);\n\n // Measures how expensive the fallback reload was when a back/forward navigation missed bfcache.\n if (typeof navigationEntry.duration === 'number' && navigationEntry.duration > 0) {\n metrics.distribution('browser.bfcache.reload.duration', navigationEntry.duration, {\n unit: 'millisecond',\n attributes: _withOriginAttr({\n [SENTRY_SEGMENT_NAME]: routeName,\n }),\n });\n }\n\n reasons.forEach(r => _captureBFCacheReason(r, routeName));\n }\n\n // Listener should stay active because the event can trigger for an initial show before the bfcache entry coming into the second one.\n // This can be platform-dependent so we need to skip as many events till we get to the one containing the entry.\n // So we can't have { once } or a cleanup logic here, which is fine because `setupOnce` registers it a single time regardless of how many clients are created.\n WINDOW.addEventListener('pageshow', onPageShow, true);\n },\n };\n },\n) satisfies IntegrationFn;\n\n/**\n * Captures a bf navigation as a metric and records the outcome and reason count.\n */\nfunction _captureBFCacheNavigation(outcome: BFCacheOutcome, reasonCount: number, routeName?: string): void {\n metrics.count('browser.bfcache.navigation', 1, {\n attributes: _withOriginAttr({\n [BROWSER_BFCACHE_OUTCOME]: outcome,\n // Attribute should be present if reasons are >= 1\n [BROWSER_BFCACHE_NOT_RESTORED_REASON_COUNT]: reasonCount || undefined,\n [SENTRY_SEGMENT_NAME]: routeName,\n }),\n });\n}\n\n/**\n * Maps a collected reason to a metric and captures/sends it.\n */\nfunction _captureBFCacheReason({ reason, frame }: CollectedReason, routeName?: string) {\n metrics.count('browser.bfcache.not_restored', 1, {\n attributes: _withOriginAttr({\n [BROWSER_BFCACHE_REASON]: reason,\n [BROWSER_BFCACHE_FRAME]: frame,\n [SENTRY_SEGMENT_NAME]: routeName,\n }),\n });\n}\n\n/**\n * The segment name for a bfcache navigation, read from the scope rather than any span.\n *\n * A hit restore is silent to tracing (no pageload span), but the frozen scope still holds the last\n * transaction name a downstream SDK (Vue/React/etc.) set before the freeze, so we reuse that. On a miss the\n * page reloads with a fresh scope, so this is the new pageload name. Falls back to the raw pathname when unset.\n */\nfunction _getSegmentName(): string | undefined {\n return getCurrentScope().getScopeData().transactionName || WINDOW.location?.pathname;\n}\n\n/**\n * Resolves the configured `maxReasons` cap. Reports every reason by default and clamps values below 1 to 1,\n * since a cap under 1 would silently drop all reasons.\n *\n * Exported for tests only.\n */\nexport function _resolveMaxReasons(maxReasons: number | undefined): number {\n if (maxReasons == null) {\n return Infinity;\n }\n\n if (maxReasons < 1) {\n DEBUG_BUILD &&\n debug.warn(`[${INTEGRATION_NAME}] \\`maxReasons\\` must be at least 1, got ${maxReasons}. Using 1 instead.`);\n return 1;\n }\n\n return maxReasons;\n}\n\n/**\n * Flattens the (possibly nested) bfcache `notRestoredReasons` tree into a capped list of reasons.\n *\n * Exported for tests only.\n */\nexport function _collectNotRestoredReasons(\n notRestoredReasons: NotRestoredReasons | null | undefined,\n maxReasons: number,\n): CollectedReason[] {\n const reasons: CollectedReason[] = [];\n\n if (!notRestoredReasons || maxReasons <= 0) {\n return reasons;\n }\n\n _collectReasonsFromFrame(notRestoredReasons, 'top', reasons, maxReasons);\n\n return reasons;\n}\n\nfunction _collectReasonsFromFrame(\n frame: NotRestoredReasons,\n frameType: BFCacheFrame,\n collectedReasons: CollectedReason[],\n maxReasons: number,\n): void {\n if (collectedReasons.length >= maxReasons) {\n return;\n }\n\n frame.reasons?.forEach(reason => {\n if (collectedReasons.length >= maxReasons) {\n return;\n }\n\n const reasonValue = typeof reason === 'string' ? reason : reason.reason;\n if (!reasonValue) {\n return;\n }\n\n collectedReasons.push({\n reason: reasonValue,\n frame: frameType,\n });\n });\n\n frame.children?.forEach(child => {\n _collectReasonsFromFrame(child, 'child', collectedReasons, maxReasons);\n });\n}\n\n/**\n * Adds the origin attributes to a set of attributes, it mutates the original attributes.\n */\nfunction _withOriginAttr(attributes: SpanAttributes): SpanAttributes {\n attributes[SENTRY_ORIGIN] = 'auto.browser.bfcache';\n\n return attributes;\n}\n"],"names":[],"mappings":";;;;;AAaA,MAAM,gBAAA,GAAmB,gB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+
{"version":3,"file":"bfcacheMetrics.js","sources":["../../../../../src/integrations/bfcacheMetrics.ts"],"sourcesContent":["import {\n SENTRY_SEGMENT_NAME,\n BROWSER_BFCACHE_FRAME,\n BROWSER_BFCACHE_NOT_RESTORED_REASON_COUNT,\n BROWSER_BFCACHE_OUTCOME,\n BROWSER_BFCACHE_REASON,\n SENTRY_ORIGIN,\n} from '@sentry/conventions/attributes';\nimport type { IntegrationFn, SpanAttributes } from '@sentry/core';\nimport { debug, defineIntegration, getCurrentScope, metrics } from '@sentry/core';\nimport { resolveCurrentRoute } from '@sentry/browser-utils';\nimport { DEBUG_BUILD } from '../debug-build';\nimport { WINDOW } from '../helpers';\n\nconst INTEGRATION_NAME = 'BfcacheMetrics';\n\ntype BFCacheOutcome = 'hit' | 'miss';\n\ntype BFCacheFrame = 'top' | 'child';\n\ninterface BFCacheMetricsIntegrationOptions {\n /**\n * Maximum number of not-restored reasons to emit per miss.\n *\n * By default every reason is reported. Set this to cap the number emitted per miss.\n * Values below 1 are clamped to 1.\n */\n maxReasons: number;\n}\n\ninterface NotRestoredReason {\n reason?: string;\n}\n\ninterface NotRestoredReasons {\n children?: NotRestoredReasons[] | null;\n reasons?: (NotRestoredReason | string)[] | null;\n}\n\ninterface NavigationTimingWithNotRestoredReasons extends PerformanceNavigationTiming {\n notRestoredReasons?: NotRestoredReasons | null;\n}\n\ninterface CollectedReason {\n reason: string;\n frame: BFCacheFrame;\n}\n\n/**\n * Captures bfcache hit/miss counters and Chromium notRestoredReasons when available.\n */\nexport const bfcacheMetricsIntegration = defineIntegration(\n (options: Partial<BFCacheMetricsIntegrationOptions> = {}) => {\n const maxReasons = _resolveMaxReasons(options.maxReasons);\n\n return {\n name: INTEGRATION_NAME,\n\n setupOnce() {\n if (!WINDOW.addEventListener || !WINDOW.performance?.getEntriesByType) {\n DEBUG_BUILD && debug.log(`[${INTEGRATION_NAME}] Browser APIs unavailable, skipping instrumentation.`);\n return;\n }\n\n function onPageShow(event: PageTransitionEvent) {\n const routeName = _getSegmentName();\n if (event.persisted) {\n _captureBFCacheNavigation('hit', 0, routeName);\n return;\n }\n\n const navigationEntry = WINDOW.performance.getEntriesByType('navigation')[0] as\n | NavigationTimingWithNotRestoredReasons\n | undefined;\n\n if (navigationEntry?.type !== 'back_forward') {\n return;\n }\n\n const reasons = _collectNotRestoredReasons(navigationEntry.notRestoredReasons, maxReasons);\n _captureBFCacheNavigation('miss', reasons.length, routeName);\n\n // Measures how expensive the fallback reload was when a back/forward navigation missed bfcache.\n if (typeof navigationEntry.duration === 'number' && navigationEntry.duration > 0) {\n metrics.distribution('browser.bfcache.reload.duration', navigationEntry.duration, {\n unit: 'millisecond',\n attributes: _withOriginAttr({\n [SENTRY_SEGMENT_NAME]: routeName,\n }),\n });\n }\n\n reasons.forEach(r => _captureBFCacheReason(r, routeName));\n }\n\n // Listener should stay active because the event can trigger for an initial show before the bfcache entry coming into the second one.\n // This can be platform-dependent so we need to skip as many events till we get to the one containing the entry.\n // So we can't have { once } or a cleanup logic here, which is fine because `setupOnce` registers it a single time regardless of how many clients are created.\n WINDOW.addEventListener('pageshow', onPageShow, true);\n },\n };\n },\n) satisfies IntegrationFn;\n\n/**\n * Captures a bf navigation as a metric and records the outcome and reason count.\n */\nfunction _captureBFCacheNavigation(outcome: BFCacheOutcome, reasonCount: number, routeName?: string): void {\n metrics.count('browser.bfcache.navigation', 1, {\n attributes: _withOriginAttr({\n [BROWSER_BFCACHE_OUTCOME]: outcome,\n // Attribute should be present if reasons are >= 1\n [BROWSER_BFCACHE_NOT_RESTORED_REASON_COUNT]: reasonCount || undefined,\n [SENTRY_SEGMENT_NAME]: routeName,\n }),\n });\n}\n\n/**\n * Maps a collected reason to a metric and captures/sends it.\n */\nfunction _captureBFCacheReason({ reason, frame }: CollectedReason, routeName?: string) {\n metrics.count('browser.bfcache.not_restored', 1, {\n attributes: _withOriginAttr({\n [BROWSER_BFCACHE_REASON]: reason,\n [BROWSER_BFCACHE_FRAME]: frame,\n [SENTRY_SEGMENT_NAME]: routeName,\n }),\n });\n}\n\n/**\n * The segment name for a bfcache navigation.\n *\n * A registered route provider is preferred because it is parameterized, which matters more here than\n * elsewhere: this ends up as a metric dimension, where a raw URL is unbounded cardinality.\n *\n * Without one we fall back to the scope. A hit restore is silent to tracing (no pageload span), but the\n * frozen scope still holds the last transaction name a downstream SDK (Vue/React/etc.) set before the\n * freeze, so we reuse that. On a miss the page reloads with a fresh scope, so this is the new pageload\n * name. Falls back to the raw pathname when unset.\n *\n * Exported for tests only.\n */\nexport function _getSegmentName(): string | undefined {\n return resolveCurrentRoute() || getCurrentScope().getScopeData().transactionName || WINDOW.location?.pathname;\n}\n\n/**\n * Resolves the configured `maxReasons` cap. Reports every reason by default and clamps values below 1 to 1,\n * since a cap under 1 would silently drop all reasons.\n *\n * Exported for tests only.\n */\nexport function _resolveMaxReasons(maxReasons: number | undefined): number {\n if (maxReasons == null) {\n return Infinity;\n }\n\n if (maxReasons < 1) {\n DEBUG_BUILD &&\n debug.warn(`[${INTEGRATION_NAME}] \\`maxReasons\\` must be at least 1, got ${maxReasons}. Using 1 instead.`);\n return 1;\n }\n\n return maxReasons;\n}\n\n/**\n * Flattens the (possibly nested) bfcache `notRestoredReasons` tree into a capped list of reasons.\n *\n * Exported for tests only.\n */\nexport function _collectNotRestoredReasons(\n notRestoredReasons: NotRestoredReasons | null | undefined,\n maxReasons: number,\n): CollectedReason[] {\n const reasons: CollectedReason[] = [];\n\n if (!notRestoredReasons || maxReasons <= 0) {\n return reasons;\n }\n\n _collectReasonsFromFrame(notRestoredReasons, 'top', reasons, maxReasons);\n\n return reasons;\n}\n\nfunction _collectReasonsFromFrame(\n frame: NotRestoredReasons,\n frameType: BFCacheFrame,\n collectedReasons: CollectedReason[],\n maxReasons: number,\n): void {\n if (collectedReasons.length >= maxReasons) {\n return;\n }\n\n frame.reasons?.forEach(reason => {\n if (collectedReasons.length >= maxReasons) {\n return;\n }\n\n const reasonValue = typeof reason === 'string' ? reason : reason.reason;\n if (!reasonValue) {\n return;\n }\n\n collectedReasons.push({\n reason: reasonValue,\n frame: frameType,\n });\n });\n\n frame.children?.forEach(child => {\n _collectReasonsFromFrame(child, 'child', collectedReasons, maxReasons);\n });\n}\n\n/**\n * Adds the origin attributes to a set of attributes, it mutates the original attributes.\n */\nfunction _withOriginAttr(attributes: SpanAttributes): SpanAttributes {\n attributes[SENTRY_ORIGIN] = 'auto.browser.bfcache';\n\n return attributes;\n}\n"],"names":[],"mappings":";;;;;;AAcA,MAAM,gBAAA,GAAmB,gBAAA;AAqClB,MAAM,yBAAA,GAA4B,iBAAA;AAAA,EACvC,CAAC,OAAA,GAAqD,EAAC,KAAM;AAC3D,IAAA,MAAM,UAAA,GAAa,kBAAA,CAAmB,OAAA,CAAQ,UAAU,CAAA;AAExD,IAAA,OAAO;AAAA,MACL,IAAA,EAAM,gBAAA;AAAA,MAEN,SAAA,GAAY;AACV,QAAA,IAAI,CAAC,MAAA,CAAO,gBAAA,IAAoB,CAAC,MAAA,CAAO,aAAa,gBAAA,EAAkB;AACrE,UAAA,WAAA,IAAe,KAAA,CAAM,GAAA,CAAI,CAAA,CAAA,EAAI,gBAAgB,CAAA,qDAAA,CAAuD,CAAA;AACpG,UAAA;AAAA,QACF;AAEA,QAAA,SAAS,WAAW,KAAA,EAA4B;AAC9C,UAAA,MAAM,YAAY,eAAA,EAAgB;AAClC,UAAA,IAAI,MAAM,SAAA,EAAW;AACnB,YAAA,yBAAA,CAA0B,KAAA,EAAO,GAAG,SAAS,CAAA;AAC7C,YAAA;AAAA,UACF;AAEA,UAAA,MAAM,kBAAkB,MAAA,CAAO,WAAA,CAAY,gBAAA,CAAiB,YAAY,EAAE,CAAC,CAAA;AAI3E,UAAA,IAAI,eAAA,EAAiB,SAAS,cAAA,EAAgB;AAC5C,YAAA;AAAA,UACF;AAEA,UAAA,MAAM,OAAA,GAAU,0BAAA,CAA2B,eAAA,CAAgB,kBAAA,EAAoB,UAAU,CAAA;AACzF,UAAA,yBAAA,CA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EAAO;AAAA,KACR,CAAA;AAAA,EACH,CAAC,CAAA;AAED,EAAA,KAAA,CAAM,QAAA,EAAU,QAAQ,CAAA,KAAA,KAAS;AAC/B,IAAA,wBAAA,CAAyB,KAAA,EAAO,OAAA,EAAS,gBAAA,EAAkB,UAAU,CAAA;AAAA,EACvE,CAAC,CAAA;AACH;AAKA,SAAS,gBAAgB,UAAA,EAA4C;AACnE,EAAA,UAAA,CAAW,aAAa,CAAA,GAAI,sBAAA;AAE5B,EAAA,OAAO,UAAA;AACT;;;;"}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { defineIntegration, spanToJSON,
|
|
1
|
+
import { defineIntegration, spanToJSON, isString, stringMatchesSomePattern, hasSpanStreamingEnabled, isObjectLike } from '@sentry/core';
|
|
2
2
|
import { SENTRY_XHR_DATA_KEY, getBodyString, getFetchRequestArgBody } from '@sentry/browser-utils';
|
|
3
|
-
import { SENTRY_OP, URL_FULL, HTTP_METHOD, GRAPHQL_OPERATION_NAME, GRAPHQL_OPERATION_TYPE, GRAPHQL_DOCUMENT } from '@sentry/conventions/attributes';
|
|
3
|
+
import { SENTRY_OP, URL_FULL, HTTP_REQUEST_METHOD, HTTP_METHOD, GRAPHQL_OPERATION_NAME, GRAPHQL_OPERATION_TYPE, GRAPHQL_DOCUMENT } from '@sentry/conventions/attributes';
|
|
4
4
|
|
|
5
5
|
const INTEGRATION_NAME = "GraphQLClient";
|
|
6
6
|
const _graphqlClientIntegration = ((options) => {
|
|
@@ -22,7 +22,7 @@ function _updateSpanWithGraphQLData(client, options) {
|
|
|
22
22
|
return;
|
|
23
23
|
}
|
|
24
24
|
const httpUrl = spanAttributes[URL_FULL];
|
|
25
|
-
const httpMethod = spanAttributes[
|
|
25
|
+
const httpMethod = spanAttributes[HTTP_REQUEST_METHOD] || spanAttributes[HTTP_METHOD];
|
|
26
26
|
if (!isString(httpUrl) || !isString(httpMethod)) {
|
|
27
27
|
return;
|
|
28
28
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"graphqlClient.js","sources":["../../../../../src/integrations/graphqlClient.ts"],"sourcesContent":["import type { Client, IntegrationFn } from '@sentry/core';\nimport {\n defineIntegration,\n hasSpanStreamingEnabled,\n isObjectLike,\n isString,\n SEMANTIC_ATTRIBUTE_HTTP_REQUEST_METHOD,\n spanToJSON,\n stringMatchesSomePattern,\n} from '@sentry/core';\nimport type { FetchHint, XhrHint } from '@sentry/browser-utils';\nimport { getBodyString, getFetchRequestArgBody, SENTRY_XHR_DATA_KEY } from '@sentry/browser-utils';\nimport {\n GRAPHQL_DOCUMENT,\n GRAPHQL_OPERATION_NAME,\n GRAPHQL_OPERATION_TYPE,\n HTTP_METHOD,\n SENTRY_OP,\n URL_FULL,\n} from '@sentry/conventions/attributes';\n\ninterface GraphQLClientOptions {\n endpoints: Array<string | RegExp>;\n}\n\n/** Standard graphql request shape: https://graphql.org/learn/serving-over-http/#post-request-and-body */\ninterface GraphQLStandardRequest {\n query: string;\n operationName?: string;\n variables?: Record<string, unknown>;\n extensions?: Record<string, unknown>;\n}\n\n/** Persisted operation request */\ninterface GraphQLPersistedRequest {\n operationName: string;\n variables?: Record<string, unknown>;\n extensions: {\n persistedQuery: {\n version: number;\n sha256Hash: string;\n };\n } & Record<string, unknown>;\n}\n\ntype GraphQLRequestPayload = GraphQLStandardRequest | GraphQLPersistedRequest;\n\ninterface GraphQLOperation {\n operationType?: string;\n operationName?: string;\n}\n\nconst INTEGRATION_NAME = 'GraphQLClient' as const;\n\nconst _graphqlClientIntegration = ((options: GraphQLClientOptions) => {\n return {\n name: INTEGRATION_NAME,\n setup(client: Client) {\n _updateSpanWithGraphQLData(client, options);\n _updateBreadcrumbWithGraphQLData(client, options);\n },\n };\n}) satisfies IntegrationFn;\n\nfunction _updateSpanWithGraphQLData(client: Client, options: GraphQLClientOptions): void {\n client.on('beforeOutgoingRequestSpan', (span, hint) => {\n const spanJSON = spanToJSON(span);\n\n const spanAttributes = spanJSON.attributes;\n const spanOp = spanAttributes[SENTRY_OP];\n\n const isHttpClientSpan = spanOp === 'http.client';\n\n if (!isHttpClientSpan) {\n return;\n }\n\n const httpUrl = spanAttributes[URL_FULL];\n // oxlint-disable-next-line typescript/no-deprecated\n const httpMethod = spanAttributes[SEMANTIC_ATTRIBUTE_HTTP_REQUEST_METHOD] || spanAttributes[HTTP_METHOD];\n\n if (!isString(httpUrl) || !isString(httpMethod)) {\n return;\n }\n\n const { endpoints } = options;\n const isTracedGraphqlEndpoint = stringMatchesSomePattern(httpUrl, endpoints);\n const payload = getRequestPayloadXhrOrFetch(hint as XhrHint | FetchHint);\n\n if (isTracedGraphqlEndpoint && payload) {\n const graphqlBody = getGraphQLRequestPayload(payload);\n\n if (graphqlBody) {\n // With span streaming the span already carries a low-cardinality name, so it must not be\n // renamed back to one containing the URL. The operation stays reachable as an attribute.\n if (!hasSpanStreamingEnabled(client)) {\n span.updateName(`${httpMethod} ${httpUrl} (${_getGraphQLOperation(graphqlBody)})`);\n }\n\n const { operationName, operationType } = _getGraphQLOperationDetails(graphqlBody);\n span.setAttribute(GRAPHQL_OPERATION_NAME, operationName);\n span.setAttribute(GRAPHQL_OPERATION_TYPE, operationType);\n\n // Handle standard requests - capture the query document when enabled via dataCollection (default true)\n if (isStandardRequest(graphqlBody) && client.getDataCollectionOptions().graphQL.document === true) {\n span.setAttribute(GRAPHQL_DOCUMENT, graphqlBody.query);\n }\n\n // Handle persisted operations - capture hash for debugging\n if (isPersistedRequest(graphqlBody)) {\n span.setAttribute('graphql.persisted_query.hash.sha256', graphqlBody.extensions.persistedQuery.sha256Hash);\n span.setAttribute('graphql.persisted_query.version', graphqlBody.extensions.persistedQuery.version);\n }\n }\n }\n });\n}\n\nfunction _updateBreadcrumbWithGraphQLData(client: Client, options: GraphQLClientOptions): void {\n client.on('beforeOutgoingRequestBreadcrumb', (breadcrumb, handlerData) => {\n const { category, type, data } = breadcrumb;\n\n const isFetch = category === 'fetch';\n const isXhr = category === 'xhr';\n const isHttpBreadcrumb = type === 'http';\n\n if (isHttpBreadcrumb && (isFetch || isXhr)) {\n const httpUrl = data?.url;\n const { endpoints } = options;\n\n const isTracedGraphqlEndpoint = stringMatchesSomePattern(httpUrl, endpoints);\n const payload = getRequestPayloadXhrOrFetch(handlerData as XhrHint | FetchHint);\n\n if (isTracedGraphqlEndpoint && data && payload) {\n const graphqlBody = getGraphQLRequestPayload(payload);\n\n if (!data.graphql && graphqlBody) {\n const operationInfo = _getGraphQLOperation(graphqlBody);\n\n data['graphql.operation'] = operationInfo;\n\n if (isStandardRequest(graphqlBody) && client.getDataCollectionOptions().graphQL.document === true) {\n data[GRAPHQL_DOCUMENT] = graphqlBody.query;\n }\n\n if (isPersistedRequest(graphqlBody)) {\n data['graphql.persisted_query.hash.sha256'] = graphqlBody.extensions.persistedQuery.sha256Hash;\n data['graphql.persisted_query.version'] = graphqlBody.extensions.persistedQuery.version;\n }\n }\n }\n }\n });\n}\n\n/**\n * The operation name and type of a GraphQL request. Persisted operations carry no query document, so\n * their type is unknown.\n */\nfunction _getGraphQLOperationDetails(requestBody: GraphQLRequestPayload): GraphQLOperation {\n if (isPersistedRequest(requestBody)) {\n return { operationName: requestBody.operationName, operationType: undefined };\n }\n\n if (isStandardRequest(requestBody)) {\n const { query: graphqlQuery, operationName: graphqlOperationName } = requestBody;\n const { operationName = graphqlOperationName, operationType } = parseGraphQLQuery(graphqlQuery);\n return { operationName, operationType };\n }\n\n return { operationName: undefined, operationType: undefined };\n}\n\n/**\n * @param requestBody - GraphQL request\n * @returns A formatted version of the request: 'TYPE NAME' or 'TYPE' or 'persisted NAME'\n */\nexport function _getGraphQLOperation(requestBody: GraphQLRequestPayload): string {\n // Handle persisted operations\n if (isPersistedRequest(requestBody)) {\n return `persisted ${requestBody.operationName}`;\n }\n\n // Handle standard GraphQL requests\n if (isStandardRequest(requestBody)) {\n const { operationName, operationType } = _getGraphQLOperationDetails(requestBody);\n return operationName ? `${operationType} ${operationName}` : `${operationType}`;\n }\n\n // Fallback for unknown request types\n return 'unknown';\n}\n\n/**\n * Get the request body/payload based on the shape of the hint.\n *\n * Exported for tests only.\n */\nexport function getRequestPayloadXhrOrFetch(hint: XhrHint | FetchHint): string | undefined {\n const isXhr = 'xhr' in hint;\n\n let body: string | undefined;\n\n if (isXhr) {\n const sentryXhrData = hint.xhr[SENTRY_XHR_DATA_KEY];\n body = sentryXhrData && getBodyString(sentryXhrData.body)[0];\n } else {\n const sentryFetchData = getFetchRequestArgBody(hint.input);\n body = getBodyString(sentryFetchData)[0];\n }\n\n return body;\n}\n\n/**\n * Extract the name and type of the operation from the GraphQL query.\n *\n * Exported for tests only.\n */\nexport function parseGraphQLQuery(query: string): GraphQLOperation {\n const namedQueryRe = /^(?:\\s*)(query|mutation|subscription)(?:\\s*)(\\w+)(?:\\s*)[{(]/;\n const unnamedQueryRe = /^(?:\\s*)(query|mutation|subscription)(?:\\s*)[{(]/;\n\n const namedMatch = query.match(namedQueryRe);\n if (namedMatch) {\n return {\n operationType: namedMatch[1],\n operationName: namedMatch[2],\n };\n }\n\n const unnamedMatch = query.match(unnamedQueryRe);\n if (unnamedMatch) {\n return {\n operationType: unnamedMatch[1],\n operationName: undefined,\n };\n }\n return {\n operationType: undefined,\n operationName: undefined,\n };\n}\n\n/**\n * Helper to safely check if a value is a non-null object\n */\n\n/**\n * Type guard to check if a request is a standard GraphQL request\n */\nfunction isStandardRequest(payload: unknown): payload is GraphQLStandardRequest {\n return isObjectLike(payload) && typeof payload.query === 'string';\n}\n\n/**\n * Type guard to check if a request is a persisted operation request\n */\nfunction isPersistedRequest(payload: unknown): payload is GraphQLPersistedRequest {\n return (\n isObjectLike(payload) &&\n typeof payload.operationName === 'string' &&\n isObjectLike(payload.extensions) &&\n isObjectLike(payload.extensions.persistedQuery) &&\n typeof payload.extensions.persistedQuery.sha256Hash === 'string' &&\n typeof payload.extensions.persistedQuery.version === 'number'\n );\n}\n\n/**\n * Extract the payload of a request if it's GraphQL.\n * Exported for tests only.\n * @param payload - A valid JSON string\n * @returns A POJO or undefined\n */\nexport function getGraphQLRequestPayload(payload: string): GraphQLRequestPayload | undefined {\n try {\n const requestBody = JSON.parse(payload);\n\n // Return any valid GraphQL request (standard, persisted, or APQ retry with both)\n if (isStandardRequest(requestBody) || isPersistedRequest(requestBody)) {\n return requestBody;\n }\n\n // Not a GraphQL request\n return undefined;\n } catch {\n // Invalid JSON\n return undefined;\n }\n}\n\n/**\n * This integration ensures that GraphQL requests made in the browser\n * have their GraphQL-specific data captured and attached to spans and breadcrumbs.\n */\nexport const graphqlClientIntegration = defineIntegration(_graphqlClientIntegration);\n"],"names":[],"mappings":";;;;AAoDA,MAAM,gBAAA,GAAmB,eAAA;AAEzB,MAAM,yBAAA,IAA6B,CAAC,OAAA,KAAkC;AACpE,EAAA,OAAO;AAAA,IACL,IAAA,EAAM,gBAAA;AAAA,IACN,MAAM,MAAA,EAAgB;AACpB,MAAA,0BAAA,CAA2B,QAAQ,OAAO,CAAA;AAC1C,MAAA,gCAAA,CAAiC,QAAQ,OAAO,CAAA;AAAA,IAClD;AAAA,GACF;AACF,CAAA,CAAA;AAEA,SAAS,0BAAA,CAA2B,QAAgB,OAAA,EAAqC;AACvF,EAAA,MAAA,CAAO,EAAA,CAAG,2BAAA,EAA6B,CAAC,IAAA,EAAM,IAAA,KAAS;AACrD,IAAA,MAAM,QAAA,GAAW,WAAW,IAAI,CAAA;AAEhC,IAAA,MAAM,iBAAiB,QAAA,CAAS,UAAA;AAChC,IAAA,MAAM,MAAA,GAAS,eAAe,SAAS,CAAA;AAEvC,IAAA,MAAM,mBAAmB,MAAA,KAAW,aAAA;AAEpC,IAAA,IAAI,CAAC,gBAAA,EAAkB;AACrB,MAAA;AAAA,IACF;AAEA,IAAA,MAAM,OAAA,GAAU,eAAe,QAAQ,CAAA;AAEvC,IAAA,MAAM,UAAA,GAAa,cAAA,CAAe,sCAAsC,CAAA,IAAK,eAAe,WAAW,CAAA;AAEvG,IAAA,IAAI,CAAC,QAAA,CAAS,OA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UAAU,CAAA,IAC/B,YAAA,CAAa,OAAA,CAAQ,WAAW,cAAc,CAAA,IAC9C,OAAO,OAAA,CAAQ,UAAA,CAAW,cAAA,CAAe,UAAA,KAAe,QAAA,IACxD,OAAO,OAAA,CAAQ,UAAA,CAAW,cAAA,CAAe,OAAA,KAAY,QAAA;AAEzD;AAQO,SAAS,yBAAyB,OAAA,EAAoD;AAC3F,EAAA,IAAI;AACF,IAAA,MAAM,WAAA,GAAc,IAAA,CAAK,KAAA,CAAM,OAAO,CAAA;AAGtC,IAAA,IAAI,iBAAA,CAAkB,WAAW,CAAA,IAAK,kBAAA,CAAmB,WAAW,CAAA,EAAG;AACrE,MAAA,OAAO,WAAA;AAAA,IACT;AAGA,IAAA,OAAO,KAAA,CAAA;AAAA,EACT,CAAA,CAAA,MAAQ;AAEN,IAAA,OAAO,MAAA;AAAA,EACT;AACF;AAMO,MAAM,wBAAA,GAA2B,kBAAkB,yBAAyB;;;;"}
|
|
1
|
+
{"version":3,"file":"graphqlClient.js","sources":["../../../../../src/integrations/graphqlClient.ts"],"sourcesContent":["import type { Client, IntegrationFn } from '@sentry/core';\nimport {\n defineIntegration,\n hasSpanStreamingEnabled,\n isObjectLike,\n isString,\n spanToJSON,\n stringMatchesSomePattern,\n} from '@sentry/core';\nimport type { FetchHint, XhrHint } from '@sentry/browser-utils';\nimport { getBodyString, getFetchRequestArgBody, SENTRY_XHR_DATA_KEY } from '@sentry/browser-utils';\nimport {\n GRAPHQL_DOCUMENT,\n GRAPHQL_OPERATION_NAME,\n GRAPHQL_OPERATION_TYPE,\n HTTP_METHOD,\n HTTP_REQUEST_METHOD,\n SENTRY_OP,\n URL_FULL,\n} from '@sentry/conventions/attributes';\n\ninterface GraphQLClientOptions {\n endpoints: Array<string | RegExp>;\n}\n\n/** Standard graphql request shape: https://graphql.org/learn/serving-over-http/#post-request-and-body */\ninterface GraphQLStandardRequest {\n query: string;\n operationName?: string;\n variables?: Record<string, unknown>;\n extensions?: Record<string, unknown>;\n}\n\n/** Persisted operation request */\ninterface GraphQLPersistedRequest {\n operationName: string;\n variables?: Record<string, unknown>;\n extensions: {\n persistedQuery: {\n version: number;\n sha256Hash: string;\n };\n } & Record<string, unknown>;\n}\n\ntype GraphQLRequestPayload = GraphQLStandardRequest | GraphQLPersistedRequest;\n\ninterface GraphQLOperation {\n operationType?: string;\n operationName?: string;\n}\n\nconst INTEGRATION_NAME = 'GraphQLClient' as const;\n\nconst _graphqlClientIntegration = ((options: GraphQLClientOptions) => {\n return {\n name: INTEGRATION_NAME,\n setup(client: Client) {\n _updateSpanWithGraphQLData(client, options);\n _updateBreadcrumbWithGraphQLData(client, options);\n },\n };\n}) satisfies IntegrationFn;\n\nfunction _updateSpanWithGraphQLData(client: Client, options: GraphQLClientOptions): void {\n client.on('beforeOutgoingRequestSpan', (span, hint) => {\n const spanJSON = spanToJSON(span);\n\n const spanAttributes = spanJSON.attributes;\n const spanOp = spanAttributes[SENTRY_OP];\n\n const isHttpClientSpan = spanOp === 'http.client';\n\n if (!isHttpClientSpan) {\n return;\n }\n\n const httpUrl = spanAttributes[URL_FULL];\n // oxlint-disable-next-line typescript/no-deprecated\n const httpMethod = spanAttributes[HTTP_REQUEST_METHOD] || spanAttributes[HTTP_METHOD];\n\n if (!isString(httpUrl) || !isString(httpMethod)) {\n return;\n }\n\n const { endpoints } = options;\n const isTracedGraphqlEndpoint = stringMatchesSomePattern(httpUrl, endpoints);\n const payload = getRequestPayloadXhrOrFetch(hint as XhrHint | FetchHint);\n\n if (isTracedGraphqlEndpoint && payload) {\n const graphqlBody = getGraphQLRequestPayload(payload);\n\n if (graphqlBody) {\n // With span streaming the span already carries a low-cardinality name, so it must not be\n // renamed back to one containing the URL. The operation stays reachable as an attribute.\n if (!hasSpanStreamingEnabled(client)) {\n span.updateName(`${httpMethod} ${httpUrl} (${_getGraphQLOperation(graphqlBody)})`);\n }\n\n const { operationName, operationType } = _getGraphQLOperationDetails(graphqlBody);\n span.setAttribute(GRAPHQL_OPERATION_NAME, operationName);\n span.setAttribute(GRAPHQL_OPERATION_TYPE, operationType);\n\n // Handle standard requests - capture the query document when enabled via dataCollection (default true)\n if (isStandardRequest(graphqlBody) && client.getDataCollectionOptions().graphQL.document === true) {\n span.setAttribute(GRAPHQL_DOCUMENT, graphqlBody.query);\n }\n\n // Handle persisted operations - capture hash for debugging\n if (isPersistedRequest(graphqlBody)) {\n span.setAttribute('graphql.persisted_query.hash.sha256', graphqlBody.extensions.persistedQuery.sha256Hash);\n span.setAttribute('graphql.persisted_query.version', graphqlBody.extensions.persistedQuery.version);\n }\n }\n }\n });\n}\n\nfunction _updateBreadcrumbWithGraphQLData(client: Client, options: GraphQLClientOptions): void {\n client.on('beforeOutgoingRequestBreadcrumb', (breadcrumb, handlerData) => {\n const { category, type, data } = breadcrumb;\n\n const isFetch = category === 'fetch';\n const isXhr = category === 'xhr';\n const isHttpBreadcrumb = type === 'http';\n\n if (isHttpBreadcrumb && (isFetch || isXhr)) {\n const httpUrl = data?.url;\n const { endpoints } = options;\n\n const isTracedGraphqlEndpoint = stringMatchesSomePattern(httpUrl, endpoints);\n const payload = getRequestPayloadXhrOrFetch(handlerData as XhrHint | FetchHint);\n\n if (isTracedGraphqlEndpoint && data && payload) {\n const graphqlBody = getGraphQLRequestPayload(payload);\n\n if (!data.graphql && graphqlBody) {\n const operationInfo = _getGraphQLOperation(graphqlBody);\n\n data['graphql.operation'] = operationInfo;\n\n if (isStandardRequest(graphqlBody) && client.getDataCollectionOptions().graphQL.document === true) {\n data[GRAPHQL_DOCUMENT] = graphqlBody.query;\n }\n\n if (isPersistedRequest(graphqlBody)) {\n data['graphql.persisted_query.hash.sha256'] = graphqlBody.extensions.persistedQuery.sha256Hash;\n data['graphql.persisted_query.version'] = graphqlBody.extensions.persistedQuery.version;\n }\n }\n }\n }\n });\n}\n\n/**\n * The operation name and type of a GraphQL request. Persisted operations carry no query document, so\n * their type is unknown.\n */\nfunction _getGraphQLOperationDetails(requestBody: GraphQLRequestPayload): GraphQLOperation {\n if (isPersistedRequest(requestBody)) {\n return { operationName: requestBody.operationName, operationType: undefined };\n }\n\n if (isStandardRequest(requestBody)) {\n const { query: graphqlQuery, operationName: graphqlOperationName } = requestBody;\n const { operationName = graphqlOperationName, operationType } = parseGraphQLQuery(graphqlQuery);\n return { operationName, operationType };\n }\n\n return { operationName: undefined, operationType: undefined };\n}\n\n/**\n * @param requestBody - GraphQL request\n * @returns A formatted version of the request: 'TYPE NAME' or 'TYPE' or 'persisted NAME'\n */\nexport function _getGraphQLOperation(requestBody: GraphQLRequestPayload): string {\n // Handle persisted operations\n if (isPersistedRequest(requestBody)) {\n return `persisted ${requestBody.operationName}`;\n }\n\n // Handle standard GraphQL requests\n if (isStandardRequest(requestBody)) {\n const { operationName, operationType } = _getGraphQLOperationDetails(requestBody);\n return operationName ? `${operationType} ${operationName}` : `${operationType}`;\n }\n\n // Fallback for unknown request types\n return 'unknown';\n}\n\n/**\n * Get the request body/payload based on the shape of the hint.\n *\n * Exported for tests only.\n */\nexport function getRequestPayloadXhrOrFetch(hint: XhrHint | FetchHint): string | undefined {\n const isXhr = 'xhr' in hint;\n\n let body: string | undefined;\n\n if (isXhr) {\n const sentryXhrData = hint.xhr[SENTRY_XHR_DATA_KEY];\n body = sentryXhrData && getBodyString(sentryXhrData.body)[0];\n } else {\n const sentryFetchData = getFetchRequestArgBody(hint.input);\n body = getBodyString(sentryFetchData)[0];\n }\n\n return body;\n}\n\n/**\n * Extract the name and type of the operation from the GraphQL query.\n *\n * Exported for tests only.\n */\nexport function parseGraphQLQuery(query: string): GraphQLOperation {\n const namedQueryRe = /^(?:\\s*)(query|mutation|subscription)(?:\\s*)(\\w+)(?:\\s*)[{(]/;\n const unnamedQueryRe = /^(?:\\s*)(query|mutation|subscription)(?:\\s*)[{(]/;\n\n const namedMatch = query.match(namedQueryRe);\n if (namedMatch) {\n return {\n operationType: namedMatch[1],\n operationName: namedMatch[2],\n };\n }\n\n const unnamedMatch = query.match(unnamedQueryRe);\n if (unnamedMatch) {\n return {\n operationType: unnamedMatch[1],\n operationName: undefined,\n };\n }\n return {\n operationType: undefined,\n operationName: undefined,\n };\n}\n\n/**\n * Helper to safely check if a value is a non-null object\n */\n\n/**\n * Type guard to check if a request is a standard GraphQL request\n */\nfunction isStandardRequest(payload: unknown): payload is GraphQLStandardRequest {\n return isObjectLike(payload) && typeof payload.query === 'string';\n}\n\n/**\n * Type guard to check if a request is a persisted operation request\n */\nfunction isPersistedRequest(payload: unknown): payload is GraphQLPersistedRequest {\n return (\n isObjectLike(payload) &&\n typeof payload.operationName === 'string' &&\n isObjectLike(payload.extensions) &&\n isObjectLike(payload.extensions.persistedQuery) &&\n typeof payload.extensions.persistedQuery.sha256Hash === 'string' &&\n typeof payload.extensions.persistedQuery.version === 'number'\n );\n}\n\n/**\n * Extract the payload of a request if it's GraphQL.\n * Exported for tests only.\n * @param payload - A valid JSON string\n * @returns A POJO or undefined\n */\nexport function getGraphQLRequestPayload(payload: string): GraphQLRequestPayload | undefined {\n try {\n const requestBody = JSON.parse(payload);\n\n // Return any valid GraphQL request (standard, persisted, or APQ retry with both)\n if (isStandardRequest(requestBody) || isPersistedRequest(requestBody)) {\n return requestBody;\n }\n\n // Not a GraphQL request\n return undefined;\n } catch {\n // Invalid JSON\n return undefined;\n }\n}\n\n/**\n * This integration ensures that GraphQL requests made in the browser\n * have their GraphQL-specific data captured and attached to spans and breadcrumbs.\n */\nexport const graphqlClientIntegration = defineIntegration(_graphqlClientIntegration);\n"],"names":[],"mappings":";;;;AAoDA,MAAM,gBAAA,GAAmB,eAAA;AAEzB,MAAM,yBAAA,IAA6B,CAAC,OAAA,KAAkC;AACpE,EAAA,OAAO;AAAA,IACL,IAAA,EAAM,gBAAA;AAAA,IACN,MAAM,MAAA,EAAgB;AACpB,MAAA,0BAAA,CAA2B,QAAQ,OAAO,CAAA;AAC1C,MAAA,gCAAA,CAAiC,QAAQ,OAAO,CAAA;AAAA,IAClD;AAAA,GACF;AACF,CAAA,CAAA;AA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
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { getRootSpan, getCurrentScope, SEMANTIC_ATTRIBUTE_SENTRY_PREVIOUS_TRACE_SAMPLE_RATE, spanToJSON, debug,
|
|
1
|
+
import { getRootSpan, getCurrentScope, SEMANTIC_ATTRIBUTE_SENTRY_PREVIOUS_TRACE_SAMPLE_RATE, spanToJSON, debug, SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE } from '@sentry/core';
|
|
2
2
|
import { DEBUG_BUILD } from '../debug-build.js';
|
|
3
3
|
import { WINDOW } from '../helpers.js';
|
|
4
4
|
import '../stack-parsers.js';
|
|
@@ -10,7 +10,7 @@ import '../integrations/globalhandlers.js';
|
|
|
10
10
|
import '../integrations/httpcontext.js';
|
|
11
11
|
import '../integrations/linkederrors.js';
|
|
12
12
|
import '../integrations/spotlight.js';
|
|
13
|
-
import { SENTRY_OP } from '@sentry/conventions/attributes';
|
|
13
|
+
import { SENTRY_OP, SENTRY_LINK_TYPE } from '@sentry/conventions/attributes';
|
|
14
14
|
|
|
15
15
|
const PREVIOUS_TRACE_MAX_DURATION = 3600;
|
|
16
16
|
const PREVIOUS_TRACE_KEY = "sentry_previous_trace";
|
|
@@ -98,7 +98,7 @@ function addPreviousTraceSpanLink(previousTraceInfo, span, oldPropagationContext
|
|
|
98
98
|
span.addLink({
|
|
99
99
|
context: previousTraceSpanCtx,
|
|
100
100
|
attributes: {
|
|
101
|
-
[
|
|
101
|
+
[SENTRY_LINK_TYPE]: "previous_trace"
|
|
102
102
|
}
|
|
103
103
|
});
|
|
104
104
|
span.setAttribute(
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"linkedTraces.js","sources":["../../../../../src/tracing/linkedTraces.ts"],"sourcesContent":["import type { Client, PropagationContext, Span, SpanContextData } from '@sentry/core';\nimport {\n debug,\n getCurrentScope,\n getRootSpan,\n SEMANTIC_ATTRIBUTE_SENTRY_PREVIOUS_TRACE_SAMPLE_RATE,\n SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE,\n SEMANTIC_LINK_ATTRIBUTE_LINK_TYPE,\n spanToJSON,\n} from '@sentry/core';\nimport { DEBUG_BUILD } from '../debug-build';\nimport { WINDOW } from '../exports';\nimport { SENTRY_OP } from '@sentry/conventions/attributes';\n\nexport interface PreviousTraceInfo {\n /**\n * Span context of the previous trace's local root span\n */\n spanContext: SpanContextData;\n\n /**\n * Timestamp in seconds when the previous trace was started\n */\n startTimestamp: number;\n\n /**\n * sample rate of the previous trace\n */\n sampleRate: number;\n\n /**\n * The sample rand of the previous trace\n */\n sampleRand: number;\n}\n\n// 1h in seconds\nexport const PREVIOUS_TRACE_MAX_DURATION = 3600;\n\n// session storage key\nexport const PREVIOUS_TRACE_KEY = 'sentry_previous_trace';\n\nexport const PREVIOUS_TRACE_TMP_SPAN_ATTRIBUTE = 'sentry.previous_trace';\n\n/**\n * Takes care of linking traces and applying the (consistent) sampling behavoiour based on the passed options\n * @param options - options for linking traces and consistent trace sampling (@see BrowserTracingOptions)\n * @param client - Sentry client\n */\nexport function linkTraces(\n client: Client,\n {\n linkPreviousTrace,\n consistentTraceSampling,\n }: {\n linkPreviousTrace: 'session-storage' | 'in-memory';\n consistentTraceSampling: boolean;\n },\n): void {\n const useSessionStorage = linkPreviousTrace === 'session-storage';\n\n let inMemoryPreviousTraceInfo = useSessionStorage ? getPreviousTraceFromSessionStorage() : undefined;\n\n client.on('spanStart', span => {\n if (getRootSpan(span) !== span) {\n return;\n }\n\n const oldPropagationContext = getCurrentScope().getPropagationContext();\n inMemoryPreviousTraceInfo = addPreviousTraceSpanLink(inMemoryPreviousTraceInfo, span, oldPropagationContext);\n\n if (useSessionStorage) {\n storePreviousTraceInSessionStorage(inMemoryPreviousTraceInfo);\n }\n });\n\n let isFirstTraceOnPageload = true;\n if (consistentTraceSampling) {\n /*\n When users opt into `consistentTraceSampling`, we need to ensure that we propagate\n the previous trace's sample rate and rand to the current trace. This is necessary because otherwise, span\n metric extrapolation is inaccurate, as we'd propagate too high of a sample rate for the subsequent traces.\n\n So therefore, we pretend that the previous trace was the parent trace of the newly started trace. To do that,\n we mutate the propagation context of the current trace and set the sample rate and sample rand of the previous trace.\n Timing-wise, it is fine because it happens before we even sample the root span.\n\n @see https://github.com/getsentry/sentry-javascript/issues/15754\n */\n client.on('beforeSampling', mutableSamplingContextData => {\n if (!inMemoryPreviousTraceInfo) {\n return;\n }\n\n const scope = getCurrentScope();\n const currentPropagationContext = scope.getPropagationContext();\n\n // We do not want to force-continue the sampling decision if we continue a trace\n // that was started on the backend. Most prominently, this will happen in MPAs where\n // users hard-navigate between pages. In this case, the sampling decision of a potentially\n // started trace on the server takes precedence.\n // Why? We want to prioritize inter-trace consistency over intra-trace consistency.\n if (isFirstTraceOnPageload && currentPropagationContext.parentSpanId) {\n isFirstTraceOnPageload = false;\n return;\n }\n\n scope.setPropagationContext({\n ...currentPropagationContext,\n dsc: {\n ...currentPropagationContext.dsc,\n sample_rate: String(inMemoryPreviousTraceInfo.sampleRate),\n sampled: String(spanContextSampled(inMemoryPreviousTraceInfo.spanContext)),\n },\n sampleRand: inMemoryPreviousTraceInfo.sampleRand,\n });\n\n mutableSamplingContextData.parentSampled = spanContextSampled(inMemoryPreviousTraceInfo.spanContext);\n mutableSamplingContextData.parentSampleRate = inMemoryPreviousTraceInfo.sampleRate;\n\n mutableSamplingContextData.spanAttributes = {\n ...mutableSamplingContextData.spanAttributes,\n [SEMANTIC_ATTRIBUTE_SENTRY_PREVIOUS_TRACE_SAMPLE_RATE]: inMemoryPreviousTraceInfo.sampleRate,\n };\n });\n }\n}\n\n/**\n * Adds a previous_trace span link to the passed span if the passed\n * previousTraceInfo is still valid.\n *\n * @returns the updated previous trace info (based on the current span/trace) to\n * be used on the next call\n */\nexport function addPreviousTraceSpanLink(\n previousTraceInfo: PreviousTraceInfo | undefined,\n span: Span,\n oldPropagationContext: PropagationContext,\n): PreviousTraceInfo {\n const spanJson = spanToJSON(span);\n\n function getSampleRate(): number {\n try {\n const oldSampleRate = Number(\n spanJson.attributes[SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE] ?? oldPropagationContext.dsc?.sample_rate,\n );\n return Number.isNaN(oldSampleRate) ? 0 : oldSampleRate;\n } catch {\n return 0;\n }\n }\n\n const updatedPreviousTraceInfo = {\n spanContext: span.spanContext(),\n startTimestamp: spanJson.start_timestamp,\n sampleRate: getSampleRate(),\n sampleRand: oldPropagationContext.sampleRand,\n };\n\n if (!previousTraceInfo) {\n return updatedPreviousTraceInfo;\n }\n\n const previousTraceSpanCtx = previousTraceInfo.spanContext;\n if (previousTraceSpanCtx.traceId === spanJson.trace_id) {\n // This means, we're still in the same trace so let's not update the previous trace info\n // or add a link to the current span.\n // Once we move away from the long-lived, route-based trace model, we can remove this cases\n return previousTraceInfo;\n }\n\n // Only add the link if the startTimeStamp of the previous trace's root span is within\n // PREVIOUS_TRACE_MAX_DURATION (1h) of the current root span's startTimestamp\n // This is done to\n // - avoid adding links to \"stale\" traces\n // - enable more efficient querying for previous/next traces in Sentry\n if (Date.now() / 1000 - previousTraceInfo.startTimestamp <= PREVIOUS_TRACE_MAX_DURATION) {\n if (DEBUG_BUILD) {\n debug.log(\n `Adding previous_trace \\`${JSON.stringify(previousTraceSpanCtx)}\\` link to span \\`${JSON.stringify({\n op: spanJson.attributes[SENTRY_OP],\n ...span.spanContext(),\n })}\\``,\n );\n }\n\n span.addLink({\n context: previousTraceSpanCtx,\n attributes: {\n [SEMANTIC_LINK_ATTRIBUTE_LINK_TYPE]: 'previous_trace',\n },\n });\n\n // TODO(v12): Remove this once the Sentry trace view finds linked traces via span links. EAP stores\n // span links, but the trace view still reads this attribute to navigate to the previous/next trace.\n span.setAttribute(\n PREVIOUS_TRACE_TMP_SPAN_ATTRIBUTE,\n `${previousTraceSpanCtx.traceId}-${previousTraceSpanCtx.spanId}-${\n spanContextSampled(previousTraceSpanCtx) ? 1 : 0\n }`,\n );\n }\n\n return updatedPreviousTraceInfo;\n}\n\n/**\n * Stores @param previousTraceInfo in sessionStorage.\n */\nexport function storePreviousTraceInSessionStorage(previousTraceInfo: PreviousTraceInfo): void {\n try {\n WINDOW.sessionStorage.setItem(PREVIOUS_TRACE_KEY, JSON.stringify(previousTraceInfo));\n } catch (e) {\n // Ignore potential errors (e.g. if sessionStorage is not available)\n DEBUG_BUILD && debug.warn('Could not store previous trace in sessionStorage', e);\n }\n}\n\n/**\n * Retrieves the previous trace from sessionStorage if available.\n */\nexport function getPreviousTraceFromSessionStorage(): PreviousTraceInfo | undefined {\n try {\n const previousTraceInfo = WINDOW.sessionStorage?.getItem(PREVIOUS_TRACE_KEY);\n // @ts-expect-error - intentionally risking JSON.parse throwing when previousTraceInfo is null to save bundle size\n return JSON.parse(previousTraceInfo);\n } catch {\n return undefined;\n }\n}\n\n/**\n * see {@link import('@sentry/core').spanIsSampled}\n */\nexport function spanContextSampled(ctx: SpanContextData): boolean {\n return ctx.traceFlags === 0x1;\n}\n"],"names":[],"mappings":";;;;;;;;;;;;;;AAqCO,MAAM,2BAAA,GAA8B;AAGpC,MAAM,kBAAA,GAAqB;AAE3B,MAAM,iCAAA,GAAoC;AAO1C,SAAS,WACd,MAAA,EACA;AAAA,EACE,iBAAA;AAAA,EACA;AACF,CAAA,EAIM;AACN,EAAA,MAAM,oBAAoB,iBAAA,KAAsB,iBAAA;AAEhD,EAAA,IAAI,yBAAA,GAA4B,iBAAA,GAAoB,kCAAA,EAAmC,GAAI,MAAA;AAE3F,EAAA,MAAA,CAAO,EAAA,CAAG,aAAa,CAAA,IAAA,KAAQ;AAC7B,IAAA,IAAI,WAAA,CAAY,IAAI,CAAA,KAAM,IAAA,EAAM;AAC9B,MAAA;AAAA,IACF;AAEA,IAAA,MAAM,qBAAA,GAAwB,eAAA,EAAgB,CAAE,qBAAA,EAAsB;AACtE,IAAA,yBAAA,GAA4B,wBAAA,CAAyB,yBAAA,EAA2B,IAAA,EAAM,qBAAqB,CAAA;AAE3G,IAAA,IAAI,iBAAA,EAAmB;A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QACV,CAAC,iCAAiC,GAAG;AAAA;AACvC,KACD,CAAA;AAID,IAAA,IAAA,CAAK,YAAA;AAAA,MACH,iCAAA;AAAA,MACA,CAAA,EAAG,oBAAA,CAAqB,OAAO,CAAA,CAAA,EAAI,oBAAA,CAAqB,MAAM,CAAA,CAAA,EAC5D,kBAAA,CAAmB,oBAAoB,CAAA,GAAI,CAAA,GAAI,CACjD,CAAA;AAAA,KACF;AAAA,EACF;AAEA,EAAA,OAAO,wBAAA;AACT;AAKO,SAAS,mCAAmC,iBAAA,EAA4C;AAC7F,EAAA,IAAI;AACF,IAAA,MAAA,CAAO,eAAe,OAAA,CAAQ,kBAAA,EAAoB,IAAA,CAAK,SAAA,CAAU,iBAAiB,CAAC,CAAA;AAAA,EACrF,SAAS,CAAA,EAAG;AAEV,IAAA,WAAA,IAAe,KAAA,CAAM,IAAA,CAAK,kDAAA,EAAoD,CAAC,CAAA;AAAA,EACjF;AACF;AAKO,SAAS,kCAAA,GAAoE;AAClF,EAAA,IAAI;AACF,IAAA,MAAM,iBAAA,GAAoB,MAAA,CAAO,cAAA,EAAgB,OAAA,CAAQ,kBAAkB,CAAA;AAE3E,IAAA,OAAO,IAAA,CAAK,MAAM,iBAAiB,CAAA;AAAA,EACrC,CAAA,CAAA,MAAQ;AACN,IAAA,OAAO,MAAA;AAAA,EACT;AACF;AAKO,SAAS,mBAAmB,GAAA,EAA+B;AAChE,EAAA,OAAO,IAAI,UAAA,KAAe,CAAA;AAC5B;;;;"}
|
|
1
|
+
{"version":3,"file":"linkedTraces.js","sources":["../../../../../src/tracing/linkedTraces.ts"],"sourcesContent":["import type { Client, PropagationContext, Span, SpanContextData } from '@sentry/core';\nimport {\n debug,\n getCurrentScope,\n getRootSpan,\n SEMANTIC_ATTRIBUTE_SENTRY_PREVIOUS_TRACE_SAMPLE_RATE,\n SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE,\n spanToJSON,\n} from '@sentry/core';\nimport { DEBUG_BUILD } from '../debug-build';\nimport { WINDOW } from '../exports';\nimport { SENTRY_LINK_TYPE, SENTRY_OP } from '@sentry/conventions/attributes';\n\nexport interface PreviousTraceInfo {\n /**\n * Span context of the previous trace's local root span\n */\n spanContext: SpanContextData;\n\n /**\n * Timestamp in seconds when the previous trace was started\n */\n startTimestamp: number;\n\n /**\n * sample rate of the previous trace\n */\n sampleRate: number;\n\n /**\n * The sample rand of the previous trace\n */\n sampleRand: number;\n}\n\n// 1h in seconds\nexport const PREVIOUS_TRACE_MAX_DURATION = 3600;\n\n// session storage key\nexport const PREVIOUS_TRACE_KEY = 'sentry_previous_trace';\n\nexport const PREVIOUS_TRACE_TMP_SPAN_ATTRIBUTE = 'sentry.previous_trace';\n\n/**\n * Takes care of linking traces and applying the (consistent) sampling behavoiour based on the passed options\n * @param options - options for linking traces and consistent trace sampling (@see BrowserTracingOptions)\n * @param client - Sentry client\n */\nexport function linkTraces(\n client: Client,\n {\n linkPreviousTrace,\n consistentTraceSampling,\n }: {\n linkPreviousTrace: 'session-storage' | 'in-memory';\n consistentTraceSampling: boolean;\n },\n): void {\n const useSessionStorage = linkPreviousTrace === 'session-storage';\n\n let inMemoryPreviousTraceInfo = useSessionStorage ? getPreviousTraceFromSessionStorage() : undefined;\n\n client.on('spanStart', span => {\n if (getRootSpan(span) !== span) {\n return;\n }\n\n const oldPropagationContext = getCurrentScope().getPropagationContext();\n inMemoryPreviousTraceInfo = addPreviousTraceSpanLink(inMemoryPreviousTraceInfo, span, oldPropagationContext);\n\n if (useSessionStorage) {\n storePreviousTraceInSessionStorage(inMemoryPreviousTraceInfo);\n }\n });\n\n let isFirstTraceOnPageload = true;\n if (consistentTraceSampling) {\n /*\n When users opt into `consistentTraceSampling`, we need to ensure that we propagate\n the previous trace's sample rate and rand to the current trace. This is necessary because otherwise, span\n metric extrapolation is inaccurate, as we'd propagate too high of a sample rate for the subsequent traces.\n\n So therefore, we pretend that the previous trace was the parent trace of the newly started trace. To do that,\n we mutate the propagation context of the current trace and set the sample rate and sample rand of the previous trace.\n Timing-wise, it is fine because it happens before we even sample the root span.\n\n @see https://github.com/getsentry/sentry-javascript/issues/15754\n */\n client.on('beforeSampling', mutableSamplingContextData => {\n if (!inMemoryPreviousTraceInfo) {\n return;\n }\n\n const scope = getCurrentScope();\n const currentPropagationContext = scope.getPropagationContext();\n\n // We do not want to force-continue the sampling decision if we continue a trace\n // that was started on the backend. Most prominently, this will happen in MPAs where\n // users hard-navigate between pages. In this case, the sampling decision of a potentially\n // started trace on the server takes precedence.\n // Why? We want to prioritize inter-trace consistency over intra-trace consistency.\n if (isFirstTraceOnPageload && currentPropagationContext.parentSpanId) {\n isFirstTraceOnPageload = false;\n return;\n }\n\n scope.setPropagationContext({\n ...currentPropagationContext,\n dsc: {\n ...currentPropagationContext.dsc,\n sample_rate: String(inMemoryPreviousTraceInfo.sampleRate),\n sampled: String(spanContextSampled(inMemoryPreviousTraceInfo.spanContext)),\n },\n sampleRand: inMemoryPreviousTraceInfo.sampleRand,\n });\n\n mutableSamplingContextData.parentSampled = spanContextSampled(inMemoryPreviousTraceInfo.spanContext);\n mutableSamplingContextData.parentSampleRate = inMemoryPreviousTraceInfo.sampleRate;\n\n mutableSamplingContextData.spanAttributes = {\n ...mutableSamplingContextData.spanAttributes,\n [SEMANTIC_ATTRIBUTE_SENTRY_PREVIOUS_TRACE_SAMPLE_RATE]: inMemoryPreviousTraceInfo.sampleRate,\n };\n });\n }\n}\n\n/**\n * Adds a previous_trace span link to the passed span if the passed\n * previousTraceInfo is still valid.\n *\n * @returns the updated previous trace info (based on the current span/trace) to\n * be used on the next call\n */\nexport function addPreviousTraceSpanLink(\n previousTraceInfo: PreviousTraceInfo | undefined,\n span: Span,\n oldPropagationContext: PropagationContext,\n): PreviousTraceInfo {\n const spanJson = spanToJSON(span);\n\n function getSampleRate(): number {\n try {\n const oldSampleRate = Number(\n spanJson.attributes[SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE] ?? oldPropagationContext.dsc?.sample_rate,\n );\n return Number.isNaN(oldSampleRate) ? 0 : oldSampleRate;\n } catch {\n return 0;\n }\n }\n\n const updatedPreviousTraceInfo = {\n spanContext: span.spanContext(),\n startTimestamp: spanJson.start_timestamp,\n sampleRate: getSampleRate(),\n sampleRand: oldPropagationContext.sampleRand,\n };\n\n if (!previousTraceInfo) {\n return updatedPreviousTraceInfo;\n }\n\n const previousTraceSpanCtx = previousTraceInfo.spanContext;\n if (previousTraceSpanCtx.traceId === spanJson.trace_id) {\n // This means, we're still in the same trace so let's not update the previous trace info\n // or add a link to the current span.\n // Once we move away from the long-lived, route-based trace model, we can remove this cases\n return previousTraceInfo;\n }\n\n // Only add the link if the startTimeStamp of the previous trace's root span is within\n // PREVIOUS_TRACE_MAX_DURATION (1h) of the current root span's startTimestamp\n // This is done to\n // - avoid adding links to \"stale\" traces\n // - enable more efficient querying for previous/next traces in Sentry\n if (Date.now() / 1000 - previousTraceInfo.startTimestamp <= PREVIOUS_TRACE_MAX_DURATION) {\n if (DEBUG_BUILD) {\n debug.log(\n `Adding previous_trace \\`${JSON.stringify(previousTraceSpanCtx)}\\` link to span \\`${JSON.stringify({\n op: spanJson.attributes[SENTRY_OP],\n ...span.spanContext(),\n })}\\``,\n );\n }\n\n span.addLink({\n context: previousTraceSpanCtx,\n attributes: {\n [SENTRY_LINK_TYPE]: 'previous_trace',\n },\n });\n\n // TODO(v12): Remove this once the Sentry trace view finds linked traces via span links. EAP stores\n // span links, but the trace view still reads this attribute to navigate to the previous/next trace.\n span.setAttribute(\n PREVIOUS_TRACE_TMP_SPAN_ATTRIBUTE,\n `${previousTraceSpanCtx.traceId}-${previousTraceSpanCtx.spanId}-${\n spanContextSampled(previousTraceSpanCtx) ? 1 : 0\n }`,\n );\n }\n\n return updatedPreviousTraceInfo;\n}\n\n/**\n * Stores @param previousTraceInfo in sessionStorage.\n */\nexport function storePreviousTraceInSessionStorage(previousTraceInfo: PreviousTraceInfo): void {\n try {\n WINDOW.sessionStorage.setItem(PREVIOUS_TRACE_KEY, JSON.stringify(previousTraceInfo));\n } catch (e) {\n // Ignore potential errors (e.g. if sessionStorage is not available)\n DEBUG_BUILD && debug.warn('Could not store previous trace in sessionStorage', e);\n }\n}\n\n/**\n * Retrieves the previous trace from sessionStorage if available.\n */\nexport function getPreviousTraceFromSessionStorage(): PreviousTraceInfo | undefined {\n try {\n const previousTraceInfo = WINDOW.sessionStorage?.getItem(PREVIOUS_TRACE_KEY);\n // @ts-expect-error - intentionally risking JSON.parse throwing when previousTraceInfo is null to save bundle size\n return JSON.parse(previousTraceInfo);\n } catch {\n return undefined;\n }\n}\n\n/**\n * see {@link import('@sentry/core').spanIsSampled}\n */\nexport function spanContextSampled(ctx: SpanContextData): boolean {\n return ctx.traceFlags === 0x1;\n}\n"],"names":[],"mappings":";;;;;;;;;;;;;;AAoCO,MAAM,2BAAA,GAA8B;AAGpC,MAAM,kBAAA,GAAqB;AAE3B,MAAM,iCAAA,GAAoC;AAO1C,SAAS,WACd,MAAA,EACA;AAAA,EACE,iBAAA;AAAA,EACA;AACF,CAAA,EAIM;AACN,EAAA,MAAM,oBAAoB,iBAAA,KAAsB,iBAAA;AAEhD,EAAA,IAAI,yBAAA,GAA4B,iBAAA,GAAoB,kCAAA,EAAmC,GAAI,MAAA;AAE3F,EAAA,MAAA,CAAO,EAAA,CAAG,aAAa,CAAA,IAAA,KAAQ;AAC7B,IAAA,IAAI,WAAA,CAAY,IAAI,CAAA,KAAM,IAAA,EAAM;AAC9B,MAAA;AAAA,IACF;AAEA,IAAA,MAAM,qBAAA,GAAwB,eAAA,EAAgB,CAAE,qBAAA,EAAsB;AACtE,IAAA,yBAAA,GAA4B,wBAAA,CAAyB,yBAAA,EAA2B,IAAA,EAAM,qBAAqB,CAAA;AAE3G,IAAA,IAAI,iBAAA,EAAmB;AACrB,MAAA,kCAAA,CAAmC,yBAAyB,CAAA;AAAA,IAC9D;AAAA,EACF,CAAC,CAAA;AAED,EAAA,IAAI,sBAAA,GAAyB,IAAA;AAC7B,EAAA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CAAqB,OAAO,CAAA,CAAA,EAAI,oBAAA,CAAqB,MAAM,CAAA,CAAA,EAC5D,kBAAA,CAAmB,oBAAoB,CAAA,GAAI,CAAA,GAAI,CACjD,CAAA;AAAA,KACF;AAAA,EACF;AAEA,EAAA,OAAO,wBAAA;AACT;AAKO,SAAS,mCAAmC,iBAAA,EAA4C;AAC7F,EAAA,IAAI;AACF,IAAA,MAAA,CAAO,eAAe,OAAA,CAAQ,kBAAA,EAAoB,IAAA,CAAK,SAAA,CAAU,iBAAiB,CAAC,CAAA;AAAA,EACrF,SAAS,CAAA,EAAG;AAEV,IAAA,WAAA,IAAe,KAAA,CAAM,IAAA,CAAK,kDAAA,EAAoD,CAAC,CAAA;AAAA,EACjF;AACF;AAKO,SAAS,kCAAA,GAAoE;AAClF,EAAA,IAAI;AACF,IAAA,MAAM,iBAAA,GAAoB,MAAA,CAAO,cAAA,EAAgB,OAAA,CAAQ,kBAAkB,CAAA;AAE3E,IAAA,OAAO,IAAA,CAAK,MAAM,iBAAiB,CAAA;AAAA,EACrC,CAAA,CAAA,MAAQ;AACN,IAAA,OAAO,MAAA;AAAA,EACT;AACF;AAKO,SAAS,mBAAmB,GAAA,EAA+B;AAChE,EAAA,OAAO,IAAI,UAAA,KAAe,CAAA;AAC5B;;;;"}
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { setRouteProvider } from '@sentry/browser-utils';
|
|
1
2
|
import { Client, getSDKSource, applySdkMetadata, addAutoIpAddressToSession } from '@sentry/core';
|
|
2
3
|
import { eventFromException, eventFromMessage } from './eventbuilder.js';
|
|
3
4
|
import { WINDOW } from './helpers.js';
|
|
@@ -13,6 +14,9 @@ class BrowserClient extends Client {
|
|
|
13
14
|
const sdkSource = WINDOW.SENTRY_SDK_SOURCE || getSDKSource();
|
|
14
15
|
applySdkMetadata(opts, "browser", ["browser"], sdkSource);
|
|
15
16
|
super(opts);
|
|
17
|
+
if (opts.routeProvider) {
|
|
18
|
+
setRouteProvider(opts.routeProvider, this);
|
|
19
|
+
}
|
|
16
20
|
this._unhandledSessionStatus = "unhandled";
|
|
17
21
|
const { userInfo } = this.getDataCollectionOptions();
|
|
18
22
|
if (opts._metadata?.sdk) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"client.js","sources":["../../../../src/client.ts"],"sourcesContent":["import type {\n ClientOptions,\n Event,\n EventHint,\n Options as CoreOptions,\n ParameterizedString,\n Scope,\n SeverityLevel,\n} from '@sentry/core';\nimport type { BrowserClientReplayOptions } from '@sentry/core/browser';\nimport { addAutoIpAddressToSession, applySdkMetadata, Client, getSDKSource } from '@sentry/core';\nimport { eventFromException, eventFromMessage } from './eventbuilder';\nimport { WINDOW } from './helpers';\nimport type { BrowserTransportOptions } from './transports/types';\n\n/**\n * A magic string that build tooling can leverage in order to inject a release value into the SDK.\n */\ndeclare const __SENTRY_RELEASE__: string | undefined;\n\nexport type BrowserClientProfilingOptions = {\n /**\n * Sets profiling session sample rate for the entire profiling session.\n *\n * A profiling session corresponds to a user session, meaning it is set once at integration initialization and\n * persisted until the next page reload. This rate determines what percentage of user sessions will have profiling enabled.\n * @default 0\n */\n profileSessionSampleRate?: number;\n\n /**\n * Set the lifecycle mode of the profiler.\n * - **manual**: The profiler will be manually started and stopped via `startProfiler`/`stopProfiler`.\n * If a session is sampled, is dependent on the `profileSessionSampleRate`.\n * - **trace**: The profiler will be automatically started when a root span exists and stopped when there are no\n * more sampled root spans. Whether a session is sampled, is dependent on the `profileSessionSampleRate` and the\n * existing sampling configuration for tracing (`tracesSampleRate`/`tracesSampler`).\n *\n * @default 'manual'\n */\n profileLifecycle?: 'manual' | 'trace';\n};\n\ntype BrowserSpecificOptions = BrowserClientReplayOptions &\n BrowserClientProfilingOptions & {\n /** If configured, this URL will be used as base URL for lazy loading integration. */\n cdnBaseUrl?: string;\n\n /**\n * Important: Only set this option if you know what you are doing!\n *\n * By default, the SDK will check if `Sentry.init` is called in a browser extension.\n * In case it is, it will stop initialization and log a warning\n * because browser extensions require a different Sentry initialization process:\n * https://docs.sentry.io/platforms/javascript/best-practices/shared-environments/\n *\n * Setting up the SDK in a browser extension with global error monitoring is not recommended\n * and will likely flood you with errors from other web sites or extensions. This can heavily\n * impact your quota and cause interference with your and other Sentry SDKs in shared environments.\n *\n * If this check wrongfully flags your setup as a browser extension, you can set this\n * option to `true` to skip the check.\n *\n * @default false\n */\n skipBrowserExtensionCheck?: boolean;\n\n /**\n * If you use Spotlight by Sentry during development, use\n * this option to forward captured Sentry events to Spotlight.\n *\n * Either set it to true, or provide a specific Spotlight Sidecar URL.\n *\n * More details: https://spotlightjs.com/\n *\n * IMPORTANT: Only set this option to `true` while developing, not in production!\n */\n spotlight?: boolean | string;\n };\n/**\n * Configuration options for the Sentry Browser SDK.\n * @see @sentry/core Options for more information.\n */\nexport type BrowserOptions = CoreOptions<BrowserTransportOptions> & BrowserSpecificOptions;\n\n/**\n * Configuration options for the Sentry Browser SDK Client class\n * @see BrowserClient for more information.\n */\nexport type BrowserClientOptions = ClientOptions<BrowserTransportOptions> & BrowserSpecificOptions;\n\n/**\n * The Sentry Browser SDK Client.\n *\n * @see BrowserOptions for documentation on configuration options.\n * @see SentryClient for usage documentation.\n */\nexport class BrowserClient extends Client<BrowserClientOptions> {\n /**\n * Creates a new Browser SDK instance.\n *\n * @param options Configuration options for this SDK.\n */\n public constructor(options: BrowserClientOptions) {\n const opts = applyDefaultOptions(options);\n const sdkSource = WINDOW.SENTRY_SDK_SOURCE || getSDKSource();\n applySdkMetadata(opts, 'browser', ['browser'], sdkSource);\n\n super(opts);\n\n // Unhandled errors don't actually crash the browser, so we report `unhandled` rather than `crashed`.\n this._unhandledSessionStatus = 'unhandled';\n\n const { userInfo } = this.getDataCollectionOptions();\n\n if (opts._metadata?.sdk) {\n opts._metadata.sdk.settings = {\n // Only allow IP inferral by Relay if the user opted in via dataCollection\n infer_ip: userInfo ? 'auto' : 'never',\n // purposefully allowing already passed settings to override the default\n ...opts._metadata.sdk.settings,\n };\n }\n\n const { sendClientReports } = this._options;\n\n // Flush buffered data when the page becomes hidden (e.g. tab switch, navigation, or the page\n // being discarded). `flush()` emits the `flush` hook, which drains the span (streaming), log and\n // metric buffers and hands the resulting envelopes to the transport (which uses `keepalive`).\n // Client report outcomes don't listen to the `flush` hook, so we flush them separately.\n if (WINDOW.document) {\n WINDOW.document.addEventListener('visibilitychange', () => {\n if (WINDOW.document.visibilityState === 'hidden') {\n if (sendClientReports) {\n this._flushOutcomes();\n }\n // Defer the flush to a microtask so that visibilitychange listeners registered after this\n // one have already run. In particular, browser tracing's background-tab detection ends the\n // active pageload/navigation (segment) span when the page is hidden. Deferring ensures that\n // segment span has been added to the streaming buffer before we flush, so it is sent\n // together with its child spans instead of being orphaned.\n queueMicrotask(() => {\n void this.flush();\n });\n }\n });\n }\n\n if (userInfo) {\n this.on('beforeSendSession', addAutoIpAddressToSession);\n }\n }\n\n /**\n * @inheritDoc\n */\n public eventFromException(exception: unknown, hint?: EventHint): PromiseLike<Event> {\n return eventFromException(this._options.stackParser, exception, hint, this._options.attachStacktrace);\n }\n\n /**\n * @inheritDoc\n */\n public eventFromMessage(\n message: ParameterizedString,\n level: SeverityLevel = 'info',\n hint?: EventHint,\n ): PromiseLike<Event> {\n return eventFromMessage(this._options.stackParser, message, level, hint, this._options.attachStacktrace);\n }\n\n /**\n * @inheritDoc\n */\n protected _prepareEvent(\n event: Event,\n hint: EventHint,\n currentScope: Scope,\n isolationScope: Scope,\n ): PromiseLike<Event | null> {\n event.platform = event.platform || 'javascript';\n\n return super._prepareEvent(event, hint, currentScope, isolationScope);\n }\n}\n\n/** Exported only for tests. */\nexport function applyDefaultOptions<T extends Partial<BrowserClientOptions>>(optionsArg: T): T {\n return {\n release:\n typeof __SENTRY_RELEASE__ === 'string' // This allows build tooling to find-and-replace __SENTRY_RELEASE__ to inject a release value\n ? __SENTRY_RELEASE__\n : WINDOW.SENTRY_RELEASE?.id, // This supports the variable that sentry-webpack-plugin injects\n sendClientReports: true,\n // We default this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,IAAA,IAAI,QAAA,EAAU;AACZ,MAAA,IAAA,CAAK,EAAA,CAAG,qBAAqB,yBAAyB,CAAA;AAAA,IACxD;AAAA,EACF;AAAA;AAAA;AAAA;AAAA,EAKO,kBAAA,CAAmB,WAAoB,IAAA,EAAsC;AAClF,IAAA,OAAO,kBAAA,CAAmB,KAAK,QAAA,CAAS,WAAA,EAAa,WAAW,IAAA,EAAM,IAAA,CAAK,SAAS,gBAAgB,CAAA;AAAA,EACtG;AAAA;AAAA;AAAA;AAAA,EAKO,gBAAA,CACL,OAAA,EACA,KAAA,GAAuB,MAAA,EACvB,IAAA,EACoB;AACpB,IAAA,OAAO,gBAAA,CAAiB,KAAK,QAAA,CAAS,WAAA,EAAa,SAAS,KAAA,EAAO,IAAA,EAAM,IAAA,CAAK,QAAA,CAAS,gBAAgB,CAAA;AAAA,EACzG;AAAA;AAAA;AAAA;AAAA,EAKU,aAAA,CACR,KAAA,EACA,IAAA,EACA,YAAA,EACA,cAAA,EAC2B;AAC3B,IAAA,KAAA,CAAM,QAAA,GAAW,MAAM,QAAA,IAAY,YAAA;AAEnC,IAAA,OAAO,KAAA,CAAM,aAAA,CAAc,KAAA,EAAO,IAAA,EAAM,cAAc,cAAc,CAAA;AAAA,EACtE;AACF;AAGO,SAAS,oBAA6D,UAAA,EAAkB;AAC7F,EAAA,OAAO;AAAA,IACL,SACE,OAAO,kBAAA,KAAuB,QAAA,GAC1B,kBAAA,GACA,OAAO,cAAA,EAAgB,EAAA;AAAA;AAAA,IAC7B,iBAAA,EAAmB,IAAA;AAAA;AAAA,IAEnB,0BAAA,EAA4B,IAAA;AAAA,IAC5B,GAAG;AAAA,GACL;AACF;;;;"}
|
|
1
|
+
{"version":3,"file":"client.js","sources":["../../../../src/client.ts"],"sourcesContent":["import type {\n ClientOptions,\n Event,\n EventHint,\n Options as CoreOptions,\n ParameterizedString,\n Scope,\n SeverityLevel,\n} from '@sentry/core';\nimport type { BrowserClientReplayOptions } from '@sentry/core/browser';\nimport type { RouteProvider } from '@sentry/browser-utils';\nimport { setRouteProvider } from '@sentry/browser-utils';\nimport { addAutoIpAddressToSession, applySdkMetadata, Client, getSDKSource } from '@sentry/core';\nimport { eventFromException, eventFromMessage } from './eventbuilder';\nimport { WINDOW } from './helpers';\nimport type { BrowserTransportOptions } from './transports/types';\n\n/**\n * A magic string that build tooling can leverage in order to inject a release value into the SDK.\n */\ndeclare const __SENTRY_RELEASE__: string | undefined;\n\nexport type BrowserClientProfilingOptions = {\n /**\n * Sets profiling session sample rate for the entire profiling session.\n *\n * A profiling session corresponds to a user session, meaning it is set once at integration initialization and\n * persisted until the next page reload. This rate determines what percentage of user sessions will have profiling enabled.\n * @default 0\n */\n profileSessionSampleRate?: number;\n\n /**\n * Set the lifecycle mode of the profiler.\n * - **manual**: The profiler will be manually started and stopped via `startProfiler`/`stopProfiler`.\n * If a session is sampled, is dependent on the `profileSessionSampleRate`.\n * - **trace**: The profiler will be automatically started when a root span exists and stopped when there are no\n * more sampled root spans. Whether a session is sampled, is dependent on the `profileSessionSampleRate` and the\n * existing sampling configuration for tracing (`tracesSampleRate`/`tracesSampler`).\n *\n * @default 'manual'\n */\n profileLifecycle?: 'manual' | 'trace';\n};\n\ntype BrowserSpecificOptions = BrowserClientReplayOptions &\n BrowserClientProfilingOptions & {\n /** If configured, this URL will be used as base URL for lazy loading integration. */\n cdnBaseUrl?: string;\n\n /**\n * Important: Only set this option if you know what you are doing!\n *\n * By default, the SDK will check if `Sentry.init` is called in a browser extension.\n * In case it is, it will stop initialization and log a warning\n * because browser extensions require a different Sentry initialization process:\n * https://docs.sentry.io/platforms/javascript/best-practices/shared-environments/\n *\n * Setting up the SDK in a browser extension with global error monitoring is not recommended\n * and will likely flood you with errors from other web sites or extensions. This can heavily\n * impact your quota and cause interference with your and other Sentry SDKs in shared environments.\n *\n * If this check wrongfully flags your setup as a browser extension, you can set this\n * option to `true` to skip the check.\n *\n * @default false\n */\n skipBrowserExtensionCheck?: boolean;\n\n /**\n * If you use Spotlight by Sentry during development, use\n * this option to forward captured Sentry events to Spotlight.\n *\n * Either set it to true, or provide a specific Spotlight Sidecar URL.\n *\n * More details: https://spotlightjs.com/\n *\n * IMPORTANT: Only set this option to `true` while developing, not in production!\n */\n spotlight?: boolean | string;\n\n /**\n * Resolves URLs to low-cardinality route names, e.g. `/users/42` -> `/users/:id`.\n *\n * Framework SDKs set this for you. Set it yourself to name routes for a router the SDK has no\n * integration for. `setRouteProvider` replaces it at runtime.\n */\n routeProvider?: RouteProvider;\n };\n/**\n * Configuration options for the Sentry Browser SDK.\n * @see @sentry/core Options for more information.\n */\nexport type BrowserOptions = CoreOptions<BrowserTransportOptions> & BrowserSpecificOptions;\n\n/**\n * Configuration options for the Sentry Browser SDK Client class\n * @see BrowserClient for more information.\n */\nexport type BrowserClientOptions = ClientOptions<BrowserTransportOptions> & BrowserSpecificOptions;\n\n/**\n * The Sentry Browser SDK Client.\n *\n * @see BrowserOptions for documentation on configuration options.\n * @see SentryClient for usage documentation.\n */\nexport class BrowserClient extends Client<BrowserClientOptions> {\n /**\n * Creates a new Browser SDK instance.\n *\n * @param options Configuration options for this SDK.\n */\n public constructor(options: BrowserClientOptions) {\n const opts = applyDefaultOptions(options);\n const sdkSource = WINDOW.SENTRY_SDK_SOURCE || getSDKSource();\n applySdkMetadata(opts, 'browser', ['browser'], sdkSource);\n\n super(opts);\n\n if (opts.routeProvider) {\n setRouteProvider(opts.routeProvider, this);\n }\n\n // Unhandled errors don't actually crash the browser, so we report `unhandled` rather than `crashed`.\n this._unhandledSessionStatus = 'unhandled';\n\n const { userInfo } = this.getDataCollectionOptions();\n\n if (opts._metadata?.sdk) {\n opts._metadata.sdk.settings = {\n // Only allow IP inferral by Relay if the user opted in via dataCollection\n infer_ip: userInfo ? 'auto' : 'never',\n // purposefully allowing already passed settings to override the default\n ...opts._metadata.sdk.settings,\n };\n }\n\n const { sendClientReports } = this._options;\n\n // Flush buffered data when the page becomes hidden (e.g. tab switch, navigation, or the page\n // being discarded). `flush()` emits the `flush` hook, which drains the span (streaming), log and\n // metric buffers and hands the resulting envelopes to the transport (which uses `keepalive`).\n // Client report outcomes don't listen to the `flush` hook, so we flush them separately.\n if (WINDOW.document) {\n WINDOW.document.addEventListener('visibilitychange', () => {\n if (WINDOW.document.visibilityState === 'hidden') {\n if (sendClientReports) {\n this._flushOutcomes();\n }\n // Defer the flush to a microtask so that visibilitychange listeners registered after this\n // one have already run. In particular, browser tracing's background-tab detection ends the\n // active pageload/navigation (segment) span when the page is hidden. Deferring ensures that\n // segment span has been added to the streaming buffer before we flush, so it is sent\n // together with its child spans instead of being orphaned.\n queueMicrotask(() => {\n void this.flush();\n });\n }\n });\n }\n\n if (userInfo) {\n this.on('beforeSendSession', addAutoIpAddressToSession);\n }\n }\n\n /**\n * @inheritDoc\n */\n public eventFromException(exception: unknown, hint?: EventHint): PromiseLike<Event> {\n return eventFromException(this._options.stackParser, exception, hint, this._options.attachStacktrace);\n }\n\n /**\n * @inheritDoc\n */\n public eventFromMessage(\n message: ParameterizedString,\n level: SeverityLevel = 'info',\n hint?: EventHint,\n ): PromiseLike<Event> {\n return eventFromMessage(this._options.stackParser, message, level, hint, this._options.attachStacktrace);\n }\n\n /**\n * @inheritDoc\n */\n protected _prepareEvent(\n event: Event,\n hint: EventHint,\n currentScope: Scope,\n isolationScope: Scope,\n ): PromiseLike<Event | null> {\n event.platform = event.platform || 'javascript';\n\n return super._prepareEvent(event, hint, currentScope, isolationScope);\n }\n}\n\n/** Exported only for tests. */\nexport function applyDefaultOptions<T extends Partial<BrowserClientOptions>>(optionsArg: T): T {\n return {\n release:\n typeof __SENTRY_RELEASE__ === 'string' // This allows build tooling to find-and-replace __SENTRY_RELEASE__ to inject a release value\n ? __SENTRY_RELEASE__\n : WINDOW.SENTRY_RELEASE?.id, // This supports the variable that sentry-webpack-plugin injects\n sendClientReports: true,\n // We default this to true, as it is the safer scenario\n parentSpanIsAlwaysRootSpan: true,\n ...optionsArg,\n };\n}\n"],"names":[],"mapp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MACF,CAAC,CAAA;AAAA,IACH;AAEA,IAAA,IAAI,QAAA,EAAU;AACZ,MAAA,IAAA,CAAK,EAAA,CAAG,qBAAqB,yBAAyB,CAAA;AAAA,IACxD;AAAA,EACF;AAAA;AAAA;AAAA;AAAA,EAKO,kBAAA,CAAmB,WAAoB,IAAA,EAAsC;AAClF,IAAA,OAAO,kBAAA,CAAmB,KAAK,QAAA,CAAS,WAAA,EAAa,WAAW,IAAA,EAAM,IAAA,CAAK,SAAS,gBAAgB,CAAA;AAAA,EACtG;AAAA;AAAA;AAAA;AAAA,EAKO,gBAAA,CACL,OAAA,EACA,KAAA,GAAuB,MAAA,EACvB,IAAA,EACoB;AACpB,IAAA,OAAO,gBAAA,CAAiB,KAAK,QAAA,CAAS,WAAA,EAAa,SAAS,KAAA,EAAO,IAAA,EAAM,IAAA,CAAK,QAAA,CAAS,gBAAgB,CAAA;AAAA,EACzG;AAAA;AAAA;AAAA;AAAA,EAKU,aAAA,CACR,KAAA,EACA,IAAA,EACA,YAAA,EACA,cAAA,EAC2B;AAC3B,IAAA,KAAA,CAAM,QAAA,GAAW,MAAM,QAAA,IAAY,YAAA;AAEnC,IAAA,OAAO,KAAA,CAAM,aAAA,CAAc,KAAA,EAAO,IAAA,EAAM,cAAc,cAAc,CAAA;AAAA,EACtE;AACF;AAGO,SAAS,oBAA6D,UAAA,EAAkB;AAC7F,EAAA,OAAO;AAAA,IACL,SACE,OAAO,kBAAA,KAAuB,QAAA,GAC1B,kBAAA,GACA,OAAO,cAAA,EAAgB,EAAA;AAAA;AAAA,IAC7B,iBAAA,EAAmB,IAAA;AAAA;AAAA,IAEnB,0BAAA,EAA4B,IAAA;AAAA,IAC5B,GAAG;AAAA,GACL;AACF;;;;"}
|
|
@@ -27,7 +27,7 @@ export { replayCanvasIntegration } from '@sentry/replay-canvas';
|
|
|
27
27
|
export { getFeedback, sendFeedback } from '@sentry/feedback';
|
|
28
28
|
export { defaultRequestInstrumentationOptions, instrumentOutgoingRequests } from './tracing/request.js';
|
|
29
29
|
export { browserTracingIntegration, startBrowserTracingNavigationSpan, startBrowserTracingPageLoadSpan } from './tracing/browserTracingIntegration.js';
|
|
30
|
-
export { elementTimingIntegration, getAbsoluteUrl, interactionsIntegration, isBotUserAgent, userTimingIntegration } from '@sentry/browser-utils';
|
|
30
|
+
export { createCachedRouteProvider, createUrlRouteProvider, elementTimingIntegration, getAbsoluteUrl, getRouteProvider, interactionsIntegration, isBotUserAgent, resolveCurrentRoute, resolveRoute, setRouteProvider, userTimingIntegration } from '@sentry/browser-utils';
|
|
31
31
|
export { normalizeStringifyValue } from './normalizeStringifyValue.js';
|
|
32
32
|
export { reportPageLoaded } from './tracing/reportPageLoaded.js';
|
|
33
33
|
export { setActiveSpanInBrowser } from './tracing/setActiveSpan.js';
|