feat: complete MDX migration, stabilize routing and lead capture

Former-commit-id: ab5cc38c97e5f73d6e821465b90d199fb6e6edc9
This commit is contained in:
2026-05-03 21:06:47 +02:00
parent b13f628b55
commit f2fdea96ec
7175 changed files with 371649 additions and 1078689 deletions

File diff suppressed because it is too large Load Diff

View File

@@ -1 +0,0 @@
module.exports = require("./color.cjs").default;

View File

@@ -1,58 +0,0 @@
{
"name": "@img/colour",
"version": "1.1.0",
"description": "The ESM-only 'color' package made compatible for use with CommonJS runtimes",
"license": "MIT",
"main": "index.cjs",
"types": "index.d.ts",
"exports": {
".": {
"types": "./index.d.ts",
"require": "./index.cjs",
"default": "./index.cjs"
},
"./package.json": "./package.json"
},
"authors": [
"Heather Arthur <fayearthur@gmail.com>",
"Josh Junon <josh@junon.me>",
"Maxime Thirouin",
"Dyma Ywanov <dfcreative@gmail.com>",
"LitoMore (https://github.com/LitoMore)"
],
"engines": {
"node": ">=18"
},
"files": [
"color.cjs",
"index.d.ts"
],
"publishConfig": {
"access": "public"
},
"repository": {
"type": "git",
"url": "git+https://github.com/lovell/colour.git"
},
"type": "commonjs",
"keywords": [
"color",
"colour",
"cjs",
"commonjs"
],
"scripts": {
"build:cjs": "esbuild node_modules/color/index.js --bundle --platform=node --outfile=color.cjs",
"build:dts": "dts-bundle-generator ./dts-src.ts -o index.d.ts --project tsconfig.build.json --external-inlines color --external-inlines color-convert --export-referenced-types=false",
"build": "npm run build:cjs && npm run build:dts",
"test": "node --test"
},
"devDependencies": {
"color": "5.0.3",
"color-convert": "3.1.3",
"color-name": "2.1.0",
"color-string": "2.1.4",
"dts-bundle-generator": "^9.5.1",
"esbuild": "^0.27.3"
}
}

View File

@@ -1,40 +0,0 @@
{
"name": "@img/sharp-darwin-arm64",
"version": "0.34.5",
"description": "Prebuilt sharp for use with macOS 64-bit ARM",
"author": "Lovell Fuller <npm@lovell.info>",
"homepage": "https://sharp.pixelplumbing.com",
"repository": {
"type": "git",
"url": "git+https://github.com/lovell/sharp.git",
"directory": "npm/darwin-arm64"
},
"license": "Apache-2.0",
"funding": {
"url": "https://opencollective.com/libvips"
},
"preferUnplugged": true,
"optionalDependencies": {
"@img/sharp-libvips-darwin-arm64": "1.2.4"
},
"files": [
"lib"
],
"publishConfig": {
"access": "public"
},
"type": "commonjs",
"exports": {
"./sharp.node": "./lib/sharp-darwin-arm64.node",
"./package": "./package.json"
},
"engines": {
"node": "^18.17.0 || ^20.3.0 || >=21.0.0"
},
"os": [
"darwin"
],
"cpu": [
"arm64"
]
}

View File

@@ -1 +0,0 @@
../../../@img+sharp-libvips-darwin-arm64@1.2.4/node_modules/@img/sharp-libvips-darwin-arm64

View File

@@ -1,46 +0,0 @@
# `@img/sharp-libvips-darwin-arm64`
Prebuilt libvips and dependencies for use with sharp on macOS 64-bit ARM.
## Licensing
This software contains third-party libraries
used under the terms of the following licences:
| Library | Used under the terms of |
|---------------|-----------------------------------------------------------------------------------------------------------|
| aom | BSD 2-Clause + [Alliance for Open Media Patent License 1.0](https://aomedia.org/license/patent-license/) |
| cairo | Mozilla Public License 2.0 |
| cgif | MIT Licence |
| expat | MIT Licence |
| fontconfig | [fontconfig Licence](https://gitlab.freedesktop.org/fontconfig/fontconfig/blob/main/COPYING) (BSD-like) |
| freetype | [freetype Licence](https://git.savannah.gnu.org/cgit/freetype/freetype2.git/tree/docs/FTL.TXT) (BSD-like) |
| fribidi | LGPLv3 |
| glib | LGPLv3 |
| harfbuzz | MIT Licence |
| highway | Apache-2.0 License, BSD 3-Clause |
| lcms | MIT Licence |
| libarchive | BSD 2-Clause |
| libexif | LGPLv3 |
| libffi | MIT Licence |
| libheif | LGPLv3 |
| libimagequant | [BSD 2-Clause](https://github.com/lovell/libimagequant/blob/main/COPYRIGHT) |
| libnsgif | MIT Licence |
| libpng | [libpng License](https://github.com/pnggroup/libpng/blob/master/LICENSE) |
| librsvg | LGPLv3 |
| libspng | [BSD 2-Clause, libpng License](https://github.com/randy408/libspng/blob/master/LICENSE) |
| libtiff | [libtiff License](https://gitlab.com/libtiff/libtiff/blob/master/LICENSE.md) (BSD-like) |
| libvips | LGPLv3 |
| libwebp | New BSD License |
| libxml2 | MIT Licence |
| mozjpeg | [zlib License, IJG License, BSD-3-Clause](https://github.com/mozilla/mozjpeg/blob/master/LICENSE.md) |
| pango | LGPLv3 |
| pixman | MIT Licence |
| proxy-libintl | LGPLv3 |
| zlib-ng | [zlib Licence](https://github.com/zlib-ng/zlib-ng/blob/develop/LICENSE.md) |
Use of libraries under the terms of the LGPLv3 is via the
"any later version" clause of the LGPLv2 or LGPLv2.1.
Please report any errors or omissions via
https://github.com/lovell/sharp-libvips/issues/new

View File

@@ -1,220 +0,0 @@
/* glibconfig.h
*
* This is a generated file. Please modify 'glibconfig.h.in'
*/
#ifndef __GLIBCONFIG_H__
#define __GLIBCONFIG_H__
#include <glib/gmacros.h>
#include <limits.h>
#include <float.h>
#define GLIB_HAVE_ALLOCA_H
#define GLIB_STATIC_COMPILATION 1
#define GOBJECT_STATIC_COMPILATION 1
#define GIO_STATIC_COMPILATION 1
#define GMODULE_STATIC_COMPILATION 1
#define GI_STATIC_COMPILATION 1
#define G_INTL_STATIC_COMPILATION 1
#define FFI_STATIC_BUILD 1
/* Specifies that GLib's g_print*() functions wrap the
* system printf functions. This is useful to know, for example,
* when using glibc's register_printf_function().
*/
#define GLIB_USING_SYSTEM_PRINTF
G_BEGIN_DECLS
#define G_MINFLOAT FLT_MIN
#define G_MAXFLOAT FLT_MAX
#define G_MINDOUBLE DBL_MIN
#define G_MAXDOUBLE DBL_MAX
#define G_MINSHORT SHRT_MIN
#define G_MAXSHORT SHRT_MAX
#define G_MAXUSHORT USHRT_MAX
#define G_MININT INT_MIN
#define G_MAXINT INT_MAX
#define G_MAXUINT UINT_MAX
#define G_MINLONG LONG_MIN
#define G_MAXLONG LONG_MAX
#define G_MAXULONG ULONG_MAX
typedef signed char gint8;
typedef unsigned char guint8;
typedef signed short gint16;
typedef unsigned short guint16;
#define G_GINT16_MODIFIER "h"
#define G_GINT16_FORMAT "hi"
#define G_GUINT16_FORMAT "hu"
typedef signed int gint32;
typedef unsigned int guint32;
#define G_GINT32_MODIFIER ""
#define G_GINT32_FORMAT "i"
#define G_GUINT32_FORMAT "u"
#define G_HAVE_GINT64 1 /* deprecated, always true */
G_GNUC_EXTENSION typedef signed long long gint64;
G_GNUC_EXTENSION typedef unsigned long long guint64;
#define G_GINT64_CONSTANT(val) (G_GNUC_EXTENSION (val##LL))
#define G_GUINT64_CONSTANT(val) (G_GNUC_EXTENSION (val##ULL))
#define G_GINT64_MODIFIER "ll"
#define G_GINT64_FORMAT "lli"
#define G_GUINT64_FORMAT "llu"
#define GLIB_SIZEOF_VOID_P 8
#define GLIB_SIZEOF_LONG 8
#define GLIB_SIZEOF_SIZE_T 8
#define GLIB_SIZEOF_SSIZE_T 8
typedef signed long gssize;
typedef unsigned long gsize;
#define G_GSIZE_MODIFIER "l"
#define G_GSSIZE_MODIFIER "l"
#define G_GSIZE_FORMAT "lu"
#define G_GSSIZE_FORMAT "li"
#define G_MAXSIZE G_MAXULONG
#define G_MINSSIZE G_MINLONG
#define G_MAXSSIZE G_MAXLONG
typedef gint64 goffset;
#define G_MINOFFSET G_MININT64
#define G_MAXOFFSET G_MAXINT64
#define G_GOFFSET_MODIFIER G_GINT64_MODIFIER
#define G_GOFFSET_FORMAT G_GINT64_FORMAT
#define G_GOFFSET_CONSTANT(val) G_GINT64_CONSTANT(val)
#define G_POLLFD_FORMAT "%d"
#define GPOINTER_TO_INT(p) ((gint) (glong) (p))
#define GPOINTER_TO_UINT(p) ((guint) (gulong) (p))
#define GINT_TO_POINTER(i) ((gpointer) (glong) (i))
#define GUINT_TO_POINTER(u) ((gpointer) (gulong) (u))
typedef signed long gintptr;
typedef unsigned long guintptr;
#define G_GINTPTR_MODIFIER "l"
#define G_GINTPTR_FORMAT "li"
#define G_GUINTPTR_FORMAT "lu"
#define GLIB_MAJOR_VERSION 2
#define GLIB_MINOR_VERSION 86
#define GLIB_MICRO_VERSION 1
#define G_OS_UNIX
#define G_VA_COPY va_copy
#define G_HAVE_ISO_VARARGS 1
/* gcc-2.95.x supports both gnu style and ISO varargs, but if -ansi
* is passed ISO vararg support is turned off, and there is no work
* around to turn it on, so we unconditionally turn it off.
*/
#if __GNUC__ == 2 && __GNUC_MINOR__ == 95
# undef G_HAVE_ISO_VARARGS
#endif
#define G_HAVE_GROWING_STACK 0
#ifndef _MSC_VER
# define G_HAVE_GNUC_VARARGS 1
#endif
#if defined(__SUNPRO_C) && (__SUNPRO_C >= 0x590)
#define G_GNUC_INTERNAL __attribute__((visibility("hidden")))
#elif defined(__SUNPRO_C) && (__SUNPRO_C >= 0x550)
#define G_GNUC_INTERNAL __hidden
#elif defined (__GNUC__) && defined (G_HAVE_GNUC_VISIBILITY)
#define G_GNUC_INTERNAL __attribute__((visibility("hidden")))
#else
#define G_GNUC_INTERNAL
#endif
#define G_THREADS_ENABLED
#define G_THREADS_IMPL_POSIX
#define G_ATOMIC_LOCK_FREE
#define GINT16_TO_LE(val) ((gint16) (val))
#define GUINT16_TO_LE(val) ((guint16) (val))
#define GINT16_TO_BE(val) ((gint16) GUINT16_SWAP_LE_BE (val))
#define GUINT16_TO_BE(val) (GUINT16_SWAP_LE_BE (val))
#define GINT32_TO_LE(val) ((gint32) (val))
#define GUINT32_TO_LE(val) ((guint32) (val))
#define GINT32_TO_BE(val) ((gint32) GUINT32_SWAP_LE_BE (val))
#define GUINT32_TO_BE(val) (GUINT32_SWAP_LE_BE (val))
#define GINT64_TO_LE(val) ((gint64) (val))
#define GUINT64_TO_LE(val) ((guint64) (val))
#define GINT64_TO_BE(val) ((gint64) GUINT64_SWAP_LE_BE (val))
#define GUINT64_TO_BE(val) (GUINT64_SWAP_LE_BE (val))
#define GLONG_TO_LE(val) ((glong) GINT64_TO_LE (val))
#define GULONG_TO_LE(val) ((gulong) GUINT64_TO_LE (val))
#define GLONG_TO_BE(val) ((glong) GINT64_TO_BE (val))
#define GULONG_TO_BE(val) ((gulong) GUINT64_TO_BE (val))
#define GINT_TO_LE(val) ((gint) GINT32_TO_LE (val))
#define GUINT_TO_LE(val) ((guint) GUINT32_TO_LE (val))
#define GINT_TO_BE(val) ((gint) GINT32_TO_BE (val))
#define GUINT_TO_BE(val) ((guint) GUINT32_TO_BE (val))
#define GSIZE_TO_LE(val) ((gsize) GUINT64_TO_LE (val))
#define GSSIZE_TO_LE(val) ((gssize) GINT64_TO_LE (val))
#define GSIZE_TO_BE(val) ((gsize) GUINT64_TO_BE (val))
#define GSSIZE_TO_BE(val) ((gssize) GINT64_TO_BE (val))
#define G_BYTE_ORDER G_LITTLE_ENDIAN
#define GLIB_SYSDEF_POLLIN =1
#define GLIB_SYSDEF_POLLOUT =4
#define GLIB_SYSDEF_POLLPRI =2
#define GLIB_SYSDEF_POLLHUP =16
#define GLIB_SYSDEF_POLLERR =8
#define GLIB_SYSDEF_POLLNVAL =32
/* No way to disable deprecation warnings for macros, so only emit deprecation
* warnings on platforms where usage of this macro is broken */
#if defined(__APPLE__) || defined(_MSC_VER) || defined(__CYGWIN__)
#define G_MODULE_SUFFIX "so" GLIB_DEPRECATED_MACRO_IN_2_76
#else
#define G_MODULE_SUFFIX "so"
#endif
typedef int GPid;
#define G_PID_FORMAT "i"
#define GLIB_SYSDEF_AF_UNIX 1
#define GLIB_SYSDEF_AF_INET 2
#define GLIB_SYSDEF_AF_INET6 30
#define GLIB_SYSDEF_MSG_OOB 1
#define GLIB_SYSDEF_MSG_PEEK 2
#define GLIB_SYSDEF_MSG_DONTROUTE 4
#define G_DIR_SEPARATOR '/'
#define G_DIR_SEPARATOR_S "/"
#define G_SEARCHPATH_SEPARATOR ':'
#define G_SEARCHPATH_SEPARATOR_S ":"
#undef G_HAVE_FREE_SIZED
G_END_DECLS
#endif /* __GLIBCONFIG_H__ */

View File

@@ -1,36 +0,0 @@
{
"name": "@img/sharp-libvips-darwin-arm64",
"version": "1.2.4",
"description": "Prebuilt libvips and dependencies for use with sharp on macOS 64-bit ARM",
"author": "Lovell Fuller <npm@lovell.info>",
"homepage": "https://sharp.pixelplumbing.com",
"repository": {
"type": "git",
"url": "git+https://github.com/lovell/sharp-libvips.git",
"directory": "npm/darwin-arm64"
},
"license": "LGPL-3.0-or-later",
"funding": {
"url": "https://opencollective.com/libvips"
},
"preferUnplugged": true,
"publishConfig": {
"access": "public"
},
"files": [
"lib",
"versions.json"
],
"type": "commonjs",
"exports": {
"./lib": "./lib/index.js",
"./package": "./package.json",
"./versions": "./versions.json"
},
"os": [
"darwin"
],
"cpu": [
"arm64"
]
}

View File

@@ -1,30 +0,0 @@
{
"aom": "3.13.1",
"archive": "3.8.2",
"cairo": "1.18.4",
"cgif": "0.5.0",
"exif": "0.6.25",
"expat": "2.7.3",
"ffi": "3.5.2",
"fontconfig": "2.17.1",
"freetype": "2.14.1",
"fribidi": "1.0.16",
"glib": "2.86.1",
"harfbuzz": "12.1.0",
"heif": "1.20.2",
"highway": "1.3.0",
"imagequant": "2.4.1",
"lcms": "2.17",
"mozjpeg": "0826579",
"pango": "1.57.0",
"pixman": "0.46.4",
"png": "1.6.50",
"proxy-libintl": "0.5",
"rsvg": "2.61.2",
"spng": "0.7.4",
"tiff": "4.7.1",
"vips": "8.17.3",
"webp": "1.6.0",
"xml2": "2.15.1",
"zlib-ng": "2.2.5"
}

File diff suppressed because one or more lines are too long

View File

@@ -1,36 +0,0 @@
{
"name": "@next/env",
"version": "16.1.6",
"keywords": [
"react",
"next",
"next.js",
"dotenv"
],
"description": "Next.js dotenv file loading",
"repository": {
"type": "git",
"url": "https://github.com/vercel/next.js",
"directory": "packages/next-env"
},
"author": "Next.js Team <support@vercel.com>",
"license": "MIT",
"main": "dist/index.js",
"types": "dist/index.d.ts",
"files": [
"dist"
],
"scripts": {
"dev": "ncc build ./index.ts -w -o dist/",
"prebuild:source": "node ../../scripts/rm.mjs dist",
"types": "tsc --declaration --emitDeclarationOnly --declarationDir dist",
"build:source": "ncc build ./index.ts -o ./dist/ --minify --no-cache --no-source-map-register",
"build": "pnpm build:source && pnpm types",
"prepublishOnly": "cd ../../ && turbo run build"
},
"devDependencies": {
"@vercel/ncc": "0.34.0",
"dotenv": "16.3.1",
"dotenv-expand": "10.0.0"
}
}

View File

@@ -1,72 +0,0 @@
"use strict";
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.ContextAPI = void 0;
const NoopContextManager_1 = require("../context/NoopContextManager");
const global_utils_1 = require("../internal/global-utils");
const diag_1 = require("./diag");
const API_NAME = 'context';
const NOOP_CONTEXT_MANAGER = new NoopContextManager_1.NoopContextManager();
/**
* Singleton object which represents the entry point to the OpenTelemetry Context API
*
* @since 1.0.0
*/
class ContextAPI {
/** Empty private constructor prevents end users from constructing a new instance of the API */
constructor() { }
/** Get the singleton instance of the Context API */
static getInstance() {
if (!this._instance) {
this._instance = new ContextAPI();
}
return this._instance;
}
/**
* Set the current context manager.
*
* @returns true if the context manager was successfully registered, else false
*/
setGlobalContextManager(contextManager) {
return (0, global_utils_1.registerGlobal)(API_NAME, contextManager, diag_1.DiagAPI.instance());
}
/**
* Get the currently active context
*/
active() {
return this._getContextManager().active();
}
/**
* Execute a function with an active context
*
* @param context context to be active during function execution
* @param fn function to execute in a context
* @param thisArg optional receiver to be used for calling fn
* @param args optional arguments forwarded to fn
*/
with(context, fn, thisArg, ...args) {
return this._getContextManager().with(context, fn, thisArg, ...args);
}
/**
* Bind a context to a target function or event emitter
*
* @param context context to bind to the event emitter or function. Defaults to the currently active context
* @param target function or event emitter to bind
*/
bind(context, target) {
return this._getContextManager().bind(context, target);
}
_getContextManager() {
return (0, global_utils_1.getGlobal)(API_NAME) || NOOP_CONTEXT_MANAGER;
}
/** Disable and remove the global context manager */
disable() {
this._getContextManager().disable();
(0, global_utils_1.unregisterGlobal)(API_NAME, diag_1.DiagAPI.instance());
}
}
exports.ContextAPI = ContextAPI;
//# sourceMappingURL=context.js.map

View File

@@ -1,84 +0,0 @@
"use strict";
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.DiagAPI = void 0;
const ComponentLogger_1 = require("../diag/ComponentLogger");
const logLevelLogger_1 = require("../diag/internal/logLevelLogger");
const types_1 = require("../diag/types");
const global_utils_1 = require("../internal/global-utils");
const API_NAME = 'diag';
/**
* Singleton object which represents the entry point to the OpenTelemetry internal
* diagnostic API
*
* @since 1.0.0
*/
class DiagAPI {
/** Get the singleton instance of the DiagAPI API */
static instance() {
if (!this._instance) {
this._instance = new DiagAPI();
}
return this._instance;
}
/**
* Private internal constructor
* @private
*/
constructor() {
function _logProxy(funcName) {
return function (...args) {
const logger = (0, global_utils_1.getGlobal)('diag');
// shortcut if logger not set
if (!logger)
return;
return logger[funcName](...args);
};
}
// Using self local variable for minification purposes as 'this' cannot be minified
const self = this;
// DiagAPI specific functions
const setLogger = (logger, optionsOrLogLevel = { logLevel: types_1.DiagLogLevel.INFO }) => {
var _a, _b, _c;
if (logger === self) {
// There isn't much we can do here.
// Logging to the console might break the user application.
// Try to log to self. If a logger was previously registered it will receive the log.
const err = new Error('Cannot use diag as the logger for itself. Please use a DiagLogger implementation like ConsoleDiagLogger or a custom implementation');
self.error((_a = err.stack) !== null && _a !== void 0 ? _a : err.message);
return false;
}
if (typeof optionsOrLogLevel === 'number') {
optionsOrLogLevel = {
logLevel: optionsOrLogLevel,
};
}
const oldLogger = (0, global_utils_1.getGlobal)('diag');
const newLogger = (0, logLevelLogger_1.createLogLevelDiagLogger)((_b = optionsOrLogLevel.logLevel) !== null && _b !== void 0 ? _b : types_1.DiagLogLevel.INFO, logger);
// There already is an logger registered. We'll let it know before overwriting it.
if (oldLogger && !optionsOrLogLevel.suppressOverrideMessage) {
const stack = (_c = new Error().stack) !== null && _c !== void 0 ? _c : '<failed to generate stacktrace>';
oldLogger.warn(`Current logger will be overwritten from ${stack}`);
newLogger.warn(`Current logger will overwrite one already registered from ${stack}`);
}
return (0, global_utils_1.registerGlobal)('diag', newLogger, self, true);
};
self.setLogger = setLogger;
self.disable = () => {
(0, global_utils_1.unregisterGlobal)(API_NAME, self);
};
self.createComponentLogger = (options) => {
return new ComponentLogger_1.DiagComponentLogger(options);
};
self.verbose = _logProxy('verbose');
self.debug = _logProxy('debug');
self.info = _logProxy('info');
self.warn = _logProxy('warn');
self.error = _logProxy('error');
}
}
exports.DiagAPI = DiagAPI;
//# sourceMappingURL=diag.js.map

View File

@@ -1,50 +0,0 @@
"use strict";
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.MetricsAPI = void 0;
const NoopMeterProvider_1 = require("../metrics/NoopMeterProvider");
const global_utils_1 = require("../internal/global-utils");
const diag_1 = require("./diag");
const API_NAME = 'metrics';
/**
* Singleton object which represents the entry point to the OpenTelemetry Metrics API
*/
class MetricsAPI {
/** Empty private constructor prevents end users from constructing a new instance of the API */
constructor() { }
/** Get the singleton instance of the Metrics API */
static getInstance() {
if (!this._instance) {
this._instance = new MetricsAPI();
}
return this._instance;
}
/**
* Set the current global meter provider.
* Returns true if the meter provider was successfully registered, else false.
*/
setGlobalMeterProvider(provider) {
return (0, global_utils_1.registerGlobal)(API_NAME, provider, diag_1.DiagAPI.instance());
}
/**
* Returns the global meter provider.
*/
getMeterProvider() {
return (0, global_utils_1.getGlobal)(API_NAME) || NoopMeterProvider_1.NOOP_METER_PROVIDER;
}
/**
* Returns a meter from the global meter provider.
*/
getMeter(name, version, options) {
return this.getMeterProvider().getMeter(name, version, options);
}
/** Remove the global meter provider */
disable() {
(0, global_utils_1.unregisterGlobal)(API_NAME, diag_1.DiagAPI.instance());
}
}
exports.MetricsAPI = MetricsAPI;
//# sourceMappingURL=metrics.js.map

View File

@@ -1,80 +0,0 @@
"use strict";
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.PropagationAPI = void 0;
const global_utils_1 = require("../internal/global-utils");
const NoopTextMapPropagator_1 = require("../propagation/NoopTextMapPropagator");
const TextMapPropagator_1 = require("../propagation/TextMapPropagator");
const context_helpers_1 = require("../baggage/context-helpers");
const utils_1 = require("../baggage/utils");
const diag_1 = require("./diag");
const API_NAME = 'propagation';
const NOOP_TEXT_MAP_PROPAGATOR = new NoopTextMapPropagator_1.NoopTextMapPropagator();
/**
* Singleton object which represents the entry point to the OpenTelemetry Propagation API
*
* @since 1.0.0
*/
class PropagationAPI {
/** Empty private constructor prevents end users from constructing a new instance of the API */
constructor() {
this.createBaggage = utils_1.createBaggage;
this.getBaggage = context_helpers_1.getBaggage;
this.getActiveBaggage = context_helpers_1.getActiveBaggage;
this.setBaggage = context_helpers_1.setBaggage;
this.deleteBaggage = context_helpers_1.deleteBaggage;
}
/** Get the singleton instance of the Propagator API */
static getInstance() {
if (!this._instance) {
this._instance = new PropagationAPI();
}
return this._instance;
}
/**
* Set the current propagator.
*
* @returns true if the propagator was successfully registered, else false
*/
setGlobalPropagator(propagator) {
return (0, global_utils_1.registerGlobal)(API_NAME, propagator, diag_1.DiagAPI.instance());
}
/**
* Inject context into a carrier to be propagated inter-process
*
* @param context Context carrying tracing data to inject
* @param carrier carrier to inject context into
* @param setter Function used to set values on the carrier
*/
inject(context, carrier, setter = TextMapPropagator_1.defaultTextMapSetter) {
return this._getGlobalPropagator().inject(context, carrier, setter);
}
/**
* Extract context from a carrier
*
* @param context Context which the newly created context will inherit from
* @param carrier Carrier to extract context from
* @param getter Function used to extract keys from a carrier
*/
extract(context, carrier, getter = TextMapPropagator_1.defaultTextMapGetter) {
return this._getGlobalPropagator().extract(context, carrier, getter);
}
/**
* Return a list of all fields which may be used by the propagator.
*/
fields() {
return this._getGlobalPropagator().fields();
}
/** Remove the global propagator */
disable() {
(0, global_utils_1.unregisterGlobal)(API_NAME, diag_1.DiagAPI.instance());
}
_getGlobalPropagator() {
return (0, global_utils_1.getGlobal)(API_NAME) || NOOP_TEXT_MAP_PROPAGATOR;
}
}
exports.PropagationAPI = PropagationAPI;
//# sourceMappingURL=propagation.js.map

View File

@@ -1,70 +0,0 @@
"use strict";
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.TraceAPI = void 0;
const global_utils_1 = require("../internal/global-utils");
const ProxyTracerProvider_1 = require("../trace/ProxyTracerProvider");
const spancontext_utils_1 = require("../trace/spancontext-utils");
const context_utils_1 = require("../trace/context-utils");
const diag_1 = require("./diag");
const API_NAME = 'trace';
/**
* Singleton object which represents the entry point to the OpenTelemetry Tracing API
*
* @since 1.0.0
*/
class TraceAPI {
/** Empty private constructor prevents end users from constructing a new instance of the API */
constructor() {
this._proxyTracerProvider = new ProxyTracerProvider_1.ProxyTracerProvider();
this.wrapSpanContext = spancontext_utils_1.wrapSpanContext;
this.isSpanContextValid = spancontext_utils_1.isSpanContextValid;
this.deleteSpan = context_utils_1.deleteSpan;
this.getSpan = context_utils_1.getSpan;
this.getActiveSpan = context_utils_1.getActiveSpan;
this.getSpanContext = context_utils_1.getSpanContext;
this.setSpan = context_utils_1.setSpan;
this.setSpanContext = context_utils_1.setSpanContext;
}
/** Get the singleton instance of the Trace API */
static getInstance() {
if (!this._instance) {
this._instance = new TraceAPI();
}
return this._instance;
}
/**
* Set the current global tracer.
*
* @returns true if the tracer provider was successfully registered, else false
*/
setGlobalTracerProvider(provider) {
const success = (0, global_utils_1.registerGlobal)(API_NAME, this._proxyTracerProvider, diag_1.DiagAPI.instance());
if (success) {
this._proxyTracerProvider.setDelegate(provider);
}
return success;
}
/**
* Returns the global tracer provider.
*/
getTracerProvider() {
return (0, global_utils_1.getGlobal)(API_NAME) || this._proxyTracerProvider;
}
/**
* Returns a tracer from the global tracer provider.
*/
getTracer(name, version) {
return this.getTracerProvider().getTracer(name, version);
}
/** Remove the global tracer provider */
disable() {
(0, global_utils_1.unregisterGlobal)(API_NAME, diag_1.DiagAPI.instance());
this._proxyTracerProvider = new ProxyTracerProvider_1.ProxyTracerProvider();
}
}
exports.TraceAPI = TraceAPI;
//# sourceMappingURL=trace.js.map

View File

@@ -1,52 +0,0 @@
"use strict";
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.deleteBaggage = exports.setBaggage = exports.getActiveBaggage = exports.getBaggage = void 0;
const context_1 = require("../api/context");
const context_2 = require("../context/context");
/**
* Baggage key
*/
const BAGGAGE_KEY = (0, context_2.createContextKey)('OpenTelemetry Baggage Key');
/**
* Retrieve the current baggage from the given context
*
* @param {Context} Context that manage all context values
* @returns {Baggage} Extracted baggage from the context
*/
function getBaggage(context) {
return context.getValue(BAGGAGE_KEY) || undefined;
}
exports.getBaggage = getBaggage;
/**
* Retrieve the current baggage from the active/current context
*
* @returns {Baggage} Extracted baggage from the context
*/
function getActiveBaggage() {
return getBaggage(context_1.ContextAPI.getInstance().active());
}
exports.getActiveBaggage = getActiveBaggage;
/**
* Store a baggage in the given context
*
* @param {Context} Context that manage all context values
* @param {Baggage} baggage that will be set in the actual context
*/
function setBaggage(context, baggage) {
return context.setValue(BAGGAGE_KEY, baggage);
}
exports.setBaggage = setBaggage;
/**
* Delete the baggage stored in the given context
*
* @param {Context} Context that manage all context values
*/
function deleteBaggage(context) {
return context.deleteValue(BAGGAGE_KEY);
}
exports.deleteBaggage = deleteBaggage;
//# sourceMappingURL=context-helpers.js.map

View File

@@ -1,44 +0,0 @@
"use strict";
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.BaggageImpl = void 0;
class BaggageImpl {
constructor(entries) {
this._entries = entries ? new Map(entries) : new Map();
}
getEntry(key) {
const entry = this._entries.get(key);
if (!entry) {
return undefined;
}
return Object.assign({}, entry);
}
getAllEntries() {
return Array.from(this._entries.entries());
}
setEntry(key, entry) {
const newBaggage = new BaggageImpl(this._entries);
newBaggage._entries.set(key, entry);
return newBaggage;
}
removeEntry(key) {
const newBaggage = new BaggageImpl(this._entries);
newBaggage._entries.delete(key);
return newBaggage;
}
removeEntries(...keys) {
const newBaggage = new BaggageImpl(this._entries);
for (const key of keys) {
newBaggage._entries.delete(key);
}
return newBaggage;
}
clear() {
return new BaggageImpl();
}
}
exports.BaggageImpl = BaggageImpl;
//# sourceMappingURL=baggage-impl.js.map

View File

@@ -1,12 +0,0 @@
"use strict";
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.baggageEntryMetadataSymbol = void 0;
/**
* Symbol used to make BaggageEntryMetadata an opaque type
*/
exports.baggageEntryMetadataSymbol = Symbol('BaggageEntryMetadata');
//# sourceMappingURL=symbol.js.map

View File

@@ -1,41 +0,0 @@
"use strict";
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.baggageEntryMetadataFromString = exports.createBaggage = void 0;
const diag_1 = require("../api/diag");
const baggage_impl_1 = require("./internal/baggage-impl");
const symbol_1 = require("./internal/symbol");
const diag = diag_1.DiagAPI.instance();
/**
* Create a new Baggage with optional entries
*
* @param entries An array of baggage entries the new baggage should contain
*/
function createBaggage(entries = {}) {
return new baggage_impl_1.BaggageImpl(new Map(Object.entries(entries)));
}
exports.createBaggage = createBaggage;
/**
* Create a serializable BaggageEntryMetadata object from a string.
*
* @param str string metadata. Format is currently not defined by the spec and has no special meaning.
*
* @since 1.0.0
*/
function baggageEntryMetadataFromString(str) {
if (typeof str !== 'string') {
diag.error(`Cannot create baggage metadata from unknown type: ${typeof str}`);
str = '';
}
return {
__TYPE__: symbol_1.baggageEntryMetadataSymbol,
toString() {
return str;
},
};
}
exports.baggageEntryMetadataFromString = baggageEntryMetadataFromString;
//# sourceMappingURL=utils.js.map

View File

@@ -1,16 +0,0 @@
"use strict";
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.context = void 0;
// Split module-level variable definition into separate files to allow
// tree-shaking on each api instance.
const context_1 = require("./api/context");
/**
* Entrypoint for context API
* @since 1.0.0
*/
exports.context = context_1.ContextAPI.getInstance();
//# sourceMappingURL=context-api.js.map

View File

@@ -1,27 +0,0 @@
"use strict";
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.NoopContextManager = void 0;
const context_1 = require("./context");
class NoopContextManager {
active() {
return context_1.ROOT_CONTEXT;
}
with(_context, fn, thisArg, ...args) {
return fn.call(thisArg, ...args);
}
bind(_context, target) {
return target;
}
enable() {
return this;
}
disable() {
return this;
}
}
exports.NoopContextManager = NoopContextManager;
//# sourceMappingURL=NoopContextManager.js.map

View File

@@ -1,52 +0,0 @@
"use strict";
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.ROOT_CONTEXT = exports.createContextKey = void 0;
/**
* Get a key to uniquely identify a context value
*
* @since 1.0.0
*/
function createContextKey(description) {
// The specification states that for the same input, multiple calls should
// return different keys. Due to the nature of the JS dependency management
// system, this creates problems where multiple versions of some package
// could hold different keys for the same property.
//
// Therefore, we use Symbol.for which returns the same key for the same input.
return Symbol.for(description);
}
exports.createContextKey = createContextKey;
class BaseContext {
/**
* Construct a new context which inherits values from an optional parent context.
*
* @param parentContext a context from which to inherit values
*/
constructor(parentContext) {
// for minification
const self = this;
self._currentContext = parentContext ? new Map(parentContext) : new Map();
self.getValue = (key) => self._currentContext.get(key);
self.setValue = (key, value) => {
const context = new BaseContext(self._currentContext);
context._currentContext.set(key, value);
return context;
};
self.deleteValue = (key) => {
const context = new BaseContext(self._currentContext);
context._currentContext.delete(key);
return context;
};
}
}
/**
* The root context is used as the default parent context when there is no active context
*
* @since 1.0.0
*/
exports.ROOT_CONTEXT = new BaseContext();
//# sourceMappingURL=context.js.map

View File

@@ -1,20 +0,0 @@
"use strict";
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.diag = void 0;
// Split module-level variable definition into separate files to allow
// tree-shaking on each api instance.
const diag_1 = require("./api/diag");
/**
* Entrypoint for Diag API.
* Defines Diagnostic handler used for internal diagnostic logging operations.
* The default provides a Noop DiagLogger implementation which may be changed via the
* diag.setLogger(logger: DiagLogger) function.
*
* @since 1.0.0
*/
exports.diag = diag_1.DiagAPI.instance();
//# sourceMappingURL=diag-api.js.map

View File

@@ -1,47 +0,0 @@
"use strict";
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.DiagComponentLogger = void 0;
const global_utils_1 = require("../internal/global-utils");
/**
* Component Logger which is meant to be used as part of any component which
* will add automatically additional namespace in front of the log message.
* It will then forward all message to global diag logger
* @example
* const cLogger = diag.createComponentLogger({ namespace: '@opentelemetry/instrumentation-http' });
* cLogger.debug('test');
* // @opentelemetry/instrumentation-http test
*/
class DiagComponentLogger {
constructor(props) {
this._namespace = props.namespace || 'DiagComponentLogger';
}
debug(...args) {
return logProxy('debug', this._namespace, args);
}
error(...args) {
return logProxy('error', this._namespace, args);
}
info(...args) {
return logProxy('info', this._namespace, args);
}
warn(...args) {
return logProxy('warn', this._namespace, args);
}
verbose(...args) {
return logProxy('verbose', this._namespace, args);
}
}
exports.DiagComponentLogger = DiagComponentLogger;
function logProxy(funcName, namespace, args) {
const logger = (0, global_utils_1.getGlobal)('diag');
// shortcut if logger not set
if (!logger) {
return;
}
return logger[funcName](namespace, ...args);
}
//# sourceMappingURL=ComponentLogger.js.map

View File

@@ -1,73 +0,0 @@
"use strict";
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.DiagConsoleLogger = exports._originalConsoleMethods = void 0;
const consoleMap = [
{ n: 'error', c: 'error' },
{ n: 'warn', c: 'warn' },
{ n: 'info', c: 'info' },
{ n: 'debug', c: 'debug' },
{ n: 'verbose', c: 'trace' },
];
// Save original console methods at module load time, before any instrumentation
// can wrap them. This ensures DiagConsoleLogger calls the unwrapped originals.
// Exported for testing only — not part of the public API.
exports._originalConsoleMethods = {};
if (typeof console !== 'undefined') {
const keys = [
'error',
'warn',
'info',
'debug',
'trace',
'log',
];
for (const key of keys) {
// eslint-disable-next-line no-console
if (typeof console[key] === 'function') {
// eslint-disable-next-line no-console
exports._originalConsoleMethods[key] = console[key];
}
}
}
/**
* A simple Immutable Console based diagnostic logger which will output any messages to the Console.
* If you want to limit the amount of logging to a specific level or lower use the
* {@link createLogLevelDiagLogger}
*
* @since 1.0.0
*/
class DiagConsoleLogger {
constructor() {
function _consoleFunc(funcName) {
return function (...args) {
// Prefer original (pre-instrumentation) methods saved at module load time.
let theFunc = exports._originalConsoleMethods[funcName];
// Some environments only expose the console when the F12 developer console is open
if (typeof theFunc !== 'function') {
theFunc = exports._originalConsoleMethods['log'];
}
// Fall back in case console was not available at module load time but became available later.
if (typeof theFunc !== 'function' && console) {
// eslint-disable-next-line no-console
theFunc = console[funcName];
if (typeof theFunc !== 'function') {
// eslint-disable-next-line no-console
theFunc = console.log;
}
}
if (typeof theFunc === 'function') {
return theFunc.apply(console, args);
}
};
}
for (let i = 0; i < consoleMap.length; i++) {
this[consoleMap[i].n] = _consoleFunc(consoleMap[i].c);
}
}
}
exports.DiagConsoleLogger = DiagConsoleLogger;
//# sourceMappingURL=consoleLogger.js.map

View File

@@ -1,34 +0,0 @@
"use strict";
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.createLogLevelDiagLogger = void 0;
const types_1 = require("../types");
function createLogLevelDiagLogger(maxLevel, logger) {
if (maxLevel < types_1.DiagLogLevel.NONE) {
maxLevel = types_1.DiagLogLevel.NONE;
}
else if (maxLevel > types_1.DiagLogLevel.ALL) {
maxLevel = types_1.DiagLogLevel.ALL;
}
// In case the logger is null or undefined
logger = logger || {};
function _filterFunc(funcName, theLevel) {
const theFunc = logger[funcName];
if (typeof theFunc === 'function' && maxLevel >= theLevel) {
return theFunc.bind(logger);
}
return function () { };
}
return {
error: _filterFunc('error', types_1.DiagLogLevel.ERROR),
warn: _filterFunc('warn', types_1.DiagLogLevel.WARN),
info: _filterFunc('info', types_1.DiagLogLevel.INFO),
debug: _filterFunc('debug', types_1.DiagLogLevel.DEBUG),
verbose: _filterFunc('verbose', types_1.DiagLogLevel.VERBOSE),
};
}
exports.createLogLevelDiagLogger = createLogLevelDiagLogger;
//# sourceMappingURL=logLevelLogger.js.map

View File

@@ -1,33 +0,0 @@
"use strict";
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.DiagLogLevel = void 0;
/**
* Defines the available internal logging levels for the diagnostic logger, the numeric values
* of the levels are defined to match the original values from the initial LogLevel to avoid
* compatibility/migration issues for any implementation that assume the numeric ordering.
*/
var DiagLogLevel;
(function (DiagLogLevel) {
/** Diagnostic Logging level setting to disable all logging (except and forced logs) */
DiagLogLevel[DiagLogLevel["NONE"] = 0] = "NONE";
/** Identifies an error scenario */
DiagLogLevel[DiagLogLevel["ERROR"] = 30] = "ERROR";
/** Identifies a warning scenario */
DiagLogLevel[DiagLogLevel["WARN"] = 50] = "WARN";
/** General informational log message */
DiagLogLevel[DiagLogLevel["INFO"] = 60] = "INFO";
/** General debug log message */
DiagLogLevel[DiagLogLevel["DEBUG"] = 70] = "DEBUG";
/**
* Detailed trace level logging should only be used for development, should only be set
* in a development environment.
*/
DiagLogLevel[DiagLogLevel["VERBOSE"] = 80] = "VERBOSE";
/** Used to set the logging level to include all logging */
DiagLogLevel[DiagLogLevel["ALL"] = 9999] = "ALL";
})(DiagLogLevel = exports.DiagLogLevel || (exports.DiagLogLevel = {}));
//# sourceMappingURL=types.js.map

View File

@@ -1,71 +0,0 @@
"use strict";
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.trace = exports.propagation = exports.metrics = exports.diag = exports.context = exports.INVALID_SPAN_CONTEXT = exports.INVALID_TRACEID = exports.INVALID_SPANID = exports.isValidSpanId = exports.isValidTraceId = exports.isSpanContextValid = exports.createTraceState = exports.TraceFlags = exports.SpanStatusCode = exports.SpanKind = exports.SamplingDecision = exports.ProxyTracerProvider = exports.ProxyTracer = exports.defaultTextMapSetter = exports.defaultTextMapGetter = exports.ValueType = exports.createNoopMeter = exports.DiagLogLevel = exports.DiagConsoleLogger = exports.ROOT_CONTEXT = exports.createContextKey = exports.baggageEntryMetadataFromString = void 0;
var utils_1 = require("./baggage/utils");
Object.defineProperty(exports, "baggageEntryMetadataFromString", { enumerable: true, get: function () { return utils_1.baggageEntryMetadataFromString; } });
// Context APIs
var context_1 = require("./context/context");
Object.defineProperty(exports, "createContextKey", { enumerable: true, get: function () { return context_1.createContextKey; } });
Object.defineProperty(exports, "ROOT_CONTEXT", { enumerable: true, get: function () { return context_1.ROOT_CONTEXT; } });
// Diag APIs
var consoleLogger_1 = require("./diag/consoleLogger");
Object.defineProperty(exports, "DiagConsoleLogger", { enumerable: true, get: function () { return consoleLogger_1.DiagConsoleLogger; } });
var types_1 = require("./diag/types");
Object.defineProperty(exports, "DiagLogLevel", { enumerable: true, get: function () { return types_1.DiagLogLevel; } });
// Metrics APIs
var NoopMeter_1 = require("./metrics/NoopMeter");
Object.defineProperty(exports, "createNoopMeter", { enumerable: true, get: function () { return NoopMeter_1.createNoopMeter; } });
var Metric_1 = require("./metrics/Metric");
Object.defineProperty(exports, "ValueType", { enumerable: true, get: function () { return Metric_1.ValueType; } });
// Propagation APIs
var TextMapPropagator_1 = require("./propagation/TextMapPropagator");
Object.defineProperty(exports, "defaultTextMapGetter", { enumerable: true, get: function () { return TextMapPropagator_1.defaultTextMapGetter; } });
Object.defineProperty(exports, "defaultTextMapSetter", { enumerable: true, get: function () { return TextMapPropagator_1.defaultTextMapSetter; } });
var ProxyTracer_1 = require("./trace/ProxyTracer");
Object.defineProperty(exports, "ProxyTracer", { enumerable: true, get: function () { return ProxyTracer_1.ProxyTracer; } });
// TODO: Remove ProxyTracerProvider export in the next major version.
var ProxyTracerProvider_1 = require("./trace/ProxyTracerProvider");
Object.defineProperty(exports, "ProxyTracerProvider", { enumerable: true, get: function () { return ProxyTracerProvider_1.ProxyTracerProvider; } });
var SamplingResult_1 = require("./trace/SamplingResult");
Object.defineProperty(exports, "SamplingDecision", { enumerable: true, get: function () { return SamplingResult_1.SamplingDecision; } });
var span_kind_1 = require("./trace/span_kind");
Object.defineProperty(exports, "SpanKind", { enumerable: true, get: function () { return span_kind_1.SpanKind; } });
var status_1 = require("./trace/status");
Object.defineProperty(exports, "SpanStatusCode", { enumerable: true, get: function () { return status_1.SpanStatusCode; } });
var trace_flags_1 = require("./trace/trace_flags");
Object.defineProperty(exports, "TraceFlags", { enumerable: true, get: function () { return trace_flags_1.TraceFlags; } });
var utils_2 = require("./trace/internal/utils");
Object.defineProperty(exports, "createTraceState", { enumerable: true, get: function () { return utils_2.createTraceState; } });
var spancontext_utils_1 = require("./trace/spancontext-utils");
Object.defineProperty(exports, "isSpanContextValid", { enumerable: true, get: function () { return spancontext_utils_1.isSpanContextValid; } });
Object.defineProperty(exports, "isValidTraceId", { enumerable: true, get: function () { return spancontext_utils_1.isValidTraceId; } });
Object.defineProperty(exports, "isValidSpanId", { enumerable: true, get: function () { return spancontext_utils_1.isValidSpanId; } });
var invalid_span_constants_1 = require("./trace/invalid-span-constants");
Object.defineProperty(exports, "INVALID_SPANID", { enumerable: true, get: function () { return invalid_span_constants_1.INVALID_SPANID; } });
Object.defineProperty(exports, "INVALID_TRACEID", { enumerable: true, get: function () { return invalid_span_constants_1.INVALID_TRACEID; } });
Object.defineProperty(exports, "INVALID_SPAN_CONTEXT", { enumerable: true, get: function () { return invalid_span_constants_1.INVALID_SPAN_CONTEXT; } });
// Split module-level variable definition into separate files to allow
// tree-shaking on each api instance.
const context_api_1 = require("./context-api");
Object.defineProperty(exports, "context", { enumerable: true, get: function () { return context_api_1.context; } });
const diag_api_1 = require("./diag-api");
Object.defineProperty(exports, "diag", { enumerable: true, get: function () { return diag_api_1.diag; } });
const metrics_api_1 = require("./metrics-api");
Object.defineProperty(exports, "metrics", { enumerable: true, get: function () { return metrics_api_1.metrics; } });
const propagation_api_1 = require("./propagation-api");
Object.defineProperty(exports, "propagation", { enumerable: true, get: function () { return propagation_api_1.propagation; } });
const trace_api_1 = require("./trace-api");
Object.defineProperty(exports, "trace", { enumerable: true, get: function () { return trace_api_1.trace; } });
// Default export.
exports.default = {
context: context_api_1.context,
diag: diag_api_1.diag,
metrics: metrics_api_1.metrics,
propagation: propagation_api_1.propagation,
trace: trace_api_1.trace,
};
//# sourceMappingURL=index.js.map

View File

@@ -1,60 +0,0 @@
"use strict";
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.unregisterGlobal = exports.getGlobal = exports.registerGlobal = void 0;
const version_1 = require("../version");
const semver_1 = require("./semver");
const major = version_1.VERSION.split('.')[0];
const GLOBAL_OPENTELEMETRY_API_KEY = Symbol.for(`opentelemetry.js.api.${major}`);
const _global = (typeof globalThis === 'object'
? globalThis
: typeof self === 'object'
? self
: typeof window === 'object'
? window
: typeof global === 'object'
? global
: {});
function registerGlobal(type, instance, diag, allowOverride = false) {
var _a;
const api = (_global[GLOBAL_OPENTELEMETRY_API_KEY] = (_a = _global[GLOBAL_OPENTELEMETRY_API_KEY]) !== null && _a !== void 0 ? _a : {
version: version_1.VERSION,
});
if (!allowOverride && api[type]) {
// already registered an API of this type
const err = new Error(`@opentelemetry/api: Attempted duplicate registration of API: ${type}`);
diag.error(err.stack || err.message);
return false;
}
if (api.version !== version_1.VERSION) {
// All registered APIs must be of the same version exactly
const err = new Error(`@opentelemetry/api: Registration of version v${api.version} for ${type} does not match previously registered API v${version_1.VERSION}`);
diag.error(err.stack || err.message);
return false;
}
api[type] = instance;
diag.debug(`@opentelemetry/api: Registered a global for ${type} v${version_1.VERSION}.`);
return true;
}
exports.registerGlobal = registerGlobal;
function getGlobal(type) {
var _a, _b;
const globalVersion = (_a = _global[GLOBAL_OPENTELEMETRY_API_KEY]) === null || _a === void 0 ? void 0 : _a.version;
if (!globalVersion || !(0, semver_1.isCompatible)(globalVersion)) {
return;
}
return (_b = _global[GLOBAL_OPENTELEMETRY_API_KEY]) === null || _b === void 0 ? void 0 : _b[type];
}
exports.getGlobal = getGlobal;
function unregisterGlobal(type, diag) {
diag.debug(`@opentelemetry/api: Unregistering a global for ${type} v${version_1.VERSION}.`);
const api = _global[GLOBAL_OPENTELEMETRY_API_KEY];
if (api) {
delete api[type];
}
}
exports.unregisterGlobal = unregisterGlobal;
//# sourceMappingURL=global-utils.js.map

View File

@@ -1,111 +0,0 @@
"use strict";
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.isCompatible = exports._makeCompatibilityCheck = void 0;
const version_1 = require("../version");
const re = /^(\d+)\.(\d+)\.(\d+)(-(.+))?$/;
/**
* Create a function to test an API version to see if it is compatible with the provided ownVersion.
*
* The returned function has the following semantics:
* - Exact match is always compatible
* - Major versions must match exactly
* - 1.x package cannot use global 2.x package
* - 2.x package cannot use global 1.x package
* - The minor version of the API module requesting access to the global API must be less than or equal to the minor version of this API
* - 1.3 package may use 1.4 global because the later global contains all functions 1.3 expects
* - 1.4 package may NOT use 1.3 global because it may try to call functions which don't exist on 1.3
* - If the major version is 0, the minor version is treated as the major and the patch is treated as the minor
* - Patch and build tag differences are not considered at this time
*
* @param ownVersion version which should be checked against
*/
function _makeCompatibilityCheck(ownVersion) {
const acceptedVersions = new Set([ownVersion]);
const rejectedVersions = new Set();
const myVersionMatch = ownVersion.match(re);
if (!myVersionMatch) {
// we cannot guarantee compatibility so we always return noop
return () => false;
}
const ownVersionParsed = {
major: +myVersionMatch[1],
minor: +myVersionMatch[2],
patch: +myVersionMatch[3],
prerelease: myVersionMatch[4],
};
// if ownVersion has a prerelease tag, versions must match exactly
if (ownVersionParsed.prerelease != null) {
return function isExactmatch(globalVersion) {
return globalVersion === ownVersion;
};
}
function _reject(v) {
rejectedVersions.add(v);
return false;
}
function _accept(v) {
acceptedVersions.add(v);
return true;
}
return function isCompatible(globalVersion) {
if (acceptedVersions.has(globalVersion)) {
return true;
}
if (rejectedVersions.has(globalVersion)) {
return false;
}
const globalVersionMatch = globalVersion.match(re);
if (!globalVersionMatch) {
// cannot parse other version
// we cannot guarantee compatibility so we always noop
return _reject(globalVersion);
}
const globalVersionParsed = {
major: +globalVersionMatch[1],
minor: +globalVersionMatch[2],
patch: +globalVersionMatch[3],
prerelease: globalVersionMatch[4],
};
// if globalVersion has a prerelease tag, versions must match exactly
if (globalVersionParsed.prerelease != null) {
return _reject(globalVersion);
}
// major versions must match
if (ownVersionParsed.major !== globalVersionParsed.major) {
return _reject(globalVersion);
}
if (ownVersionParsed.major === 0) {
if (ownVersionParsed.minor === globalVersionParsed.minor &&
ownVersionParsed.patch <= globalVersionParsed.patch) {
return _accept(globalVersion);
}
return _reject(globalVersion);
}
if (ownVersionParsed.minor <= globalVersionParsed.minor) {
return _accept(globalVersion);
}
return _reject(globalVersion);
};
}
exports._makeCompatibilityCheck = _makeCompatibilityCheck;
/**
* Test an API version to see if it is compatible with this API.
*
* - Exact match is always compatible
* - Major versions must match exactly
* - 1.x package cannot use global 2.x package
* - 2.x package cannot use global 1.x package
* - The minor version of the API module requesting access to the global API must be less than or equal to the minor version of this API
* - 1.3 package may use 1.4 global because the later global contains all functions 1.3 expects
* - 1.4 package may NOT use 1.3 global because it may try to call functions which don't exist on 1.3
* - If the major version is 0, the minor version is treated as the major and the patch is treated as the minor
* - Patch and build tag differences are not considered at this time
*
* @param version version of the API requesting an instance of the global API
*/
exports.isCompatible = _makeCompatibilityCheck(version_1.VERSION);
//# sourceMappingURL=semver.js.map

View File

@@ -1,17 +0,0 @@
"use strict";
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.metrics = void 0;
// Split module-level variable definition into separate files to allow
// tree-shaking on each api instance.
const metrics_1 = require("./api/metrics");
/**
* Entrypoint for metrics API
*
* @since 1.3.0
*/
exports.metrics = metrics_1.MetricsAPI.getInstance();
//# sourceMappingURL=metrics-api.js.map

View File

@@ -1,18 +0,0 @@
"use strict";
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.ValueType = void 0;
/**
* The Type of value. It describes how the data is reported.
*
* @since 1.3.0
*/
var ValueType;
(function (ValueType) {
ValueType[ValueType["INT"] = 0] = "INT";
ValueType[ValueType["DOUBLE"] = 1] = "DOUBLE";
})(ValueType = exports.ValueType || (exports.ValueType = {}));
//# sourceMappingURL=Metric.js.map

View File

@@ -1,118 +0,0 @@
"use strict";
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.createNoopMeter = exports.NOOP_OBSERVABLE_UP_DOWN_COUNTER_METRIC = exports.NOOP_OBSERVABLE_GAUGE_METRIC = exports.NOOP_OBSERVABLE_COUNTER_METRIC = exports.NOOP_UP_DOWN_COUNTER_METRIC = exports.NOOP_HISTOGRAM_METRIC = exports.NOOP_GAUGE_METRIC = exports.NOOP_COUNTER_METRIC = exports.NOOP_METER = exports.NoopObservableUpDownCounterMetric = exports.NoopObservableGaugeMetric = exports.NoopObservableCounterMetric = exports.NoopObservableMetric = exports.NoopHistogramMetric = exports.NoopGaugeMetric = exports.NoopUpDownCounterMetric = exports.NoopCounterMetric = exports.NoopMetric = exports.NoopMeter = void 0;
/**
* NoopMeter is a noop implementation of the {@link Meter} interface. It reuses
* constant NoopMetrics for all of its methods.
*/
class NoopMeter {
constructor() { }
/**
* @see {@link Meter.createGauge}
*/
createGauge(_name, _options) {
return exports.NOOP_GAUGE_METRIC;
}
/**
* @see {@link Meter.createHistogram}
*/
createHistogram(_name, _options) {
return exports.NOOP_HISTOGRAM_METRIC;
}
/**
* @see {@link Meter.createCounter}
*/
createCounter(_name, _options) {
return exports.NOOP_COUNTER_METRIC;
}
/**
* @see {@link Meter.createUpDownCounter}
*/
createUpDownCounter(_name, _options) {
return exports.NOOP_UP_DOWN_COUNTER_METRIC;
}
/**
* @see {@link Meter.createObservableGauge}
*/
createObservableGauge(_name, _options) {
return exports.NOOP_OBSERVABLE_GAUGE_METRIC;
}
/**
* @see {@link Meter.createObservableCounter}
*/
createObservableCounter(_name, _options) {
return exports.NOOP_OBSERVABLE_COUNTER_METRIC;
}
/**
* @see {@link Meter.createObservableUpDownCounter}
*/
createObservableUpDownCounter(_name, _options) {
return exports.NOOP_OBSERVABLE_UP_DOWN_COUNTER_METRIC;
}
/**
* @see {@link Meter.addBatchObservableCallback}
*/
addBatchObservableCallback(_callback, _observables) { }
/**
* @see {@link Meter.removeBatchObservableCallback}
*/
removeBatchObservableCallback(_callback) { }
}
exports.NoopMeter = NoopMeter;
class NoopMetric {
}
exports.NoopMetric = NoopMetric;
class NoopCounterMetric extends NoopMetric {
add(_value, _attributes) { }
}
exports.NoopCounterMetric = NoopCounterMetric;
class NoopUpDownCounterMetric extends NoopMetric {
add(_value, _attributes) { }
}
exports.NoopUpDownCounterMetric = NoopUpDownCounterMetric;
class NoopGaugeMetric extends NoopMetric {
record(_value, _attributes) { }
}
exports.NoopGaugeMetric = NoopGaugeMetric;
class NoopHistogramMetric extends NoopMetric {
record(_value, _attributes) { }
}
exports.NoopHistogramMetric = NoopHistogramMetric;
class NoopObservableMetric {
addCallback(_callback) { }
removeCallback(_callback) { }
}
exports.NoopObservableMetric = NoopObservableMetric;
class NoopObservableCounterMetric extends NoopObservableMetric {
}
exports.NoopObservableCounterMetric = NoopObservableCounterMetric;
class NoopObservableGaugeMetric extends NoopObservableMetric {
}
exports.NoopObservableGaugeMetric = NoopObservableGaugeMetric;
class NoopObservableUpDownCounterMetric extends NoopObservableMetric {
}
exports.NoopObservableUpDownCounterMetric = NoopObservableUpDownCounterMetric;
exports.NOOP_METER = new NoopMeter();
// Synchronous instruments
exports.NOOP_COUNTER_METRIC = new NoopCounterMetric();
exports.NOOP_GAUGE_METRIC = new NoopGaugeMetric();
exports.NOOP_HISTOGRAM_METRIC = new NoopHistogramMetric();
exports.NOOP_UP_DOWN_COUNTER_METRIC = new NoopUpDownCounterMetric();
// Asynchronous instruments
exports.NOOP_OBSERVABLE_COUNTER_METRIC = new NoopObservableCounterMetric();
exports.NOOP_OBSERVABLE_GAUGE_METRIC = new NoopObservableGaugeMetric();
exports.NOOP_OBSERVABLE_UP_DOWN_COUNTER_METRIC = new NoopObservableUpDownCounterMetric();
/**
* Create a no-op Meter
*
* @since 1.3.0
*/
function createNoopMeter() {
return exports.NOOP_METER;
}
exports.createNoopMeter = createNoopMeter;
//# sourceMappingURL=NoopMeter.js.map

View File

@@ -1,20 +0,0 @@
"use strict";
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.NOOP_METER_PROVIDER = exports.NoopMeterProvider = void 0;
const NoopMeter_1 = require("./NoopMeter");
/**
* An implementation of the {@link MeterProvider} which returns an impotent Meter
* for all calls to `getMeter`
*/
class NoopMeterProvider {
getMeter(_name, _version, _options) {
return NoopMeter_1.NOOP_METER;
}
}
exports.NoopMeterProvider = NoopMeterProvider;
exports.NOOP_METER_PROVIDER = new NoopMeterProvider();
//# sourceMappingURL=NoopMeterProvider.js.map

View File

@@ -1,17 +0,0 @@
"use strict";
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.propagation = void 0;
// Split module-level variable definition into separate files to allow
// tree-shaking on each api instance.
const propagation_1 = require("./api/propagation");
/**
* Entrypoint for propagation API
*
* @since 1.0.0
*/
exports.propagation = propagation_1.PropagationAPI.getInstance();
//# sourceMappingURL=propagation-api.js.map

View File

@@ -1,23 +0,0 @@
"use strict";
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.NoopTextMapPropagator = void 0;
/**
* No-op implementations of {@link TextMapPropagator}.
*/
class NoopTextMapPropagator {
/** Noop inject function does nothing */
inject(_context, _carrier) { }
/** Noop extract function does nothing and returns the input context */
extract(context, _carrier) {
return context;
}
fields() {
return [];
}
}
exports.NoopTextMapPropagator = NoopTextMapPropagator;
//# sourceMappingURL=NoopTextMapPropagator.js.map

View File

@@ -1,36 +0,0 @@
"use strict";
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.defaultTextMapSetter = exports.defaultTextMapGetter = void 0;
/**
* @since 1.0.0
*/
exports.defaultTextMapGetter = {
get(carrier, key) {
if (carrier == null) {
return undefined;
}
return carrier[key];
},
keys(carrier) {
if (carrier == null) {
return [];
}
return Object.keys(carrier);
},
};
/**
* @since 1.0.0
*/
exports.defaultTextMapSetter = {
set(carrier, key, value) {
if (carrier == null) {
return;
}
carrier[key] = value;
},
};
//# sourceMappingURL=TextMapPropagator.js.map

View File

@@ -1,17 +0,0 @@
"use strict";
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.trace = void 0;
// Split module-level variable definition into separate files to allow
// tree-shaking on each api instance.
const trace_1 = require("./api/trace");
/**
* Entrypoint for trace API
*
* @since 1.0.0
*/
exports.trace = trace_1.TraceAPI.getInstance();
//# sourceMappingURL=trace-api.js.map

View File

@@ -1,58 +0,0 @@
"use strict";
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.NonRecordingSpan = void 0;
const invalid_span_constants_1 = require("./invalid-span-constants");
/**
* The NonRecordingSpan is the default {@link Span} that is used when no Span
* implementation is available. All operations are no-op including context
* propagation.
*/
class NonRecordingSpan {
constructor(spanContext = invalid_span_constants_1.INVALID_SPAN_CONTEXT) {
this._spanContext = spanContext;
}
// Returns a SpanContext.
spanContext() {
return this._spanContext;
}
// By default does nothing
setAttribute(_key, _value) {
return this;
}
// By default does nothing
setAttributes(_attributes) {
return this;
}
// By default does nothing
addEvent(_name, _attributes) {
return this;
}
addLink(_link) {
return this;
}
addLinks(_links) {
return this;
}
// By default does nothing
setStatus(_status) {
return this;
}
// By default does nothing
updateName(_name) {
return this;
}
// By default does nothing
end(_endTime) { }
// isRecording always returns false for NonRecordingSpan.
isRecording() {
return false;
}
// By default does nothing
recordException(_exception, _time) { }
}
exports.NonRecordingSpan = NonRecordingSpan;
//# sourceMappingURL=NonRecordingSpan.js.map

View File

@@ -1,68 +0,0 @@
"use strict";
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.NoopTracer = void 0;
const context_1 = require("../api/context");
const context_utils_1 = require("../trace/context-utils");
const NonRecordingSpan_1 = require("./NonRecordingSpan");
const spancontext_utils_1 = require("./spancontext-utils");
const contextApi = context_1.ContextAPI.getInstance();
/**
* No-op implementations of {@link Tracer}.
*/
class NoopTracer {
// startSpan starts a noop span.
startSpan(name, options, context = contextApi.active()) {
const root = Boolean(options === null || options === void 0 ? void 0 : options.root);
if (root) {
return new NonRecordingSpan_1.NonRecordingSpan();
}
const parentFromContext = context && (0, context_utils_1.getSpanContext)(context);
if (isSpanContext(parentFromContext) &&
(0, spancontext_utils_1.isSpanContextValid)(parentFromContext)) {
return new NonRecordingSpan_1.NonRecordingSpan(parentFromContext);
}
else {
return new NonRecordingSpan_1.NonRecordingSpan();
}
}
startActiveSpan(name, arg2, arg3, arg4) {
let opts;
let ctx;
let fn;
if (arguments.length < 2) {
return;
}
else if (arguments.length === 2) {
fn = arg2;
}
else if (arguments.length === 3) {
opts = arg2;
fn = arg3;
}
else {
opts = arg2;
ctx = arg3;
fn = arg4;
}
const parentContext = ctx !== null && ctx !== void 0 ? ctx : contextApi.active();
const span = this.startSpan(name, opts, parentContext);
const contextWithSpanSet = (0, context_utils_1.setSpan)(parentContext, span);
return contextApi.with(contextWithSpanSet, fn, undefined, span);
}
}
exports.NoopTracer = NoopTracer;
function isSpanContext(spanContext) {
return (spanContext !== null &&
typeof spanContext === 'object' &&
'spanId' in spanContext &&
typeof spanContext['spanId'] === 'string' &&
'traceId' in spanContext &&
typeof spanContext['traceId'] === 'string' &&
'traceFlags' in spanContext &&
typeof spanContext['traceFlags'] === 'number');
}
//# sourceMappingURL=NoopTracer.js.map

View File

@@ -1,21 +0,0 @@
"use strict";
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.NoopTracerProvider = void 0;
const NoopTracer_1 = require("./NoopTracer");
/**
* An implementation of the {@link TracerProvider} which returns an impotent
* Tracer for all calls to `getTracer`.
*
* All operations are no-op.
*/
class NoopTracerProvider {
getTracer(_name, _version, _options) {
return new NoopTracer_1.NoopTracer();
}
}
exports.NoopTracerProvider = NoopTracerProvider;
//# sourceMappingURL=NoopTracerProvider.js.map

View File

@@ -1,46 +0,0 @@
"use strict";
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.ProxyTracer = void 0;
const NoopTracer_1 = require("./NoopTracer");
const NOOP_TRACER = new NoopTracer_1.NoopTracer();
/**
* Proxy tracer provided by the proxy tracer provider
*
* @since 1.0.0
*/
class ProxyTracer {
constructor(provider, name, version, options) {
this._provider = provider;
this.name = name;
this.version = version;
this.options = options;
}
startSpan(name, options, context) {
return this._getTracer().startSpan(name, options, context);
}
startActiveSpan(_name, _options, _context, _fn) {
const tracer = this._getTracer();
return Reflect.apply(tracer.startActiveSpan, tracer, arguments);
}
/**
* Try to get a tracer from the proxy tracer provider.
* If the proxy tracer provider has no delegate, return a noop tracer.
*/
_getTracer() {
if (this._delegate) {
return this._delegate;
}
const tracer = this._provider.getDelegateTracer(this.name, this.version, this.options);
if (!tracer) {
return NOOP_TRACER;
}
this._delegate = tracer;
return this._delegate;
}
}
exports.ProxyTracer = ProxyTracer;
//# sourceMappingURL=ProxyTracer.js.map

View File

@@ -1,46 +0,0 @@
"use strict";
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.ProxyTracerProvider = void 0;
const ProxyTracer_1 = require("./ProxyTracer");
const NoopTracerProvider_1 = require("./NoopTracerProvider");
const NOOP_TRACER_PROVIDER = new NoopTracerProvider_1.NoopTracerProvider();
/**
* Tracer provider which provides {@link ProxyTracer}s.
*
* Before a delegate is set, tracers provided are NoOp.
* When a delegate is set, traces are provided from the delegate.
* When a delegate is set after tracers have already been provided,
* all tracers already provided will use the provided delegate implementation.
*
* @deprecated This will be removed in the next major version.
* @since 1.0.0
*/
class ProxyTracerProvider {
/**
* Get a {@link ProxyTracer}
*/
getTracer(name, version, options) {
var _a;
return ((_a = this.getDelegateTracer(name, version, options)) !== null && _a !== void 0 ? _a : new ProxyTracer_1.ProxyTracer(this, name, version, options));
}
getDelegate() {
var _a;
return (_a = this._delegate) !== null && _a !== void 0 ? _a : NOOP_TRACER_PROVIDER;
}
/**
* Set the delegate tracer provider
*/
setDelegate(delegate) {
this._delegate = delegate;
}
getDelegateTracer(name, version, options) {
var _a;
return (_a = this._delegate) === null || _a === void 0 ? void 0 : _a.getTracer(name, version, options);
}
}
exports.ProxyTracerProvider = ProxyTracerProvider;
//# sourceMappingURL=ProxyTracerProvider.js.map

View File

@@ -1,33 +0,0 @@
"use strict";
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.SamplingDecision = void 0;
/**
* @deprecated use the one declared in @opentelemetry/sdk-trace-base instead.
* A sampling decision that determines how a {@link Span} will be recorded
* and collected.
*
* @since 1.0.0
*/
var SamplingDecision;
(function (SamplingDecision) {
/**
* `Span.isRecording() === false`, span will not be recorded and all events
* and attributes will be dropped.
*/
SamplingDecision[SamplingDecision["NOT_RECORD"] = 0] = "NOT_RECORD";
/**
* `Span.isRecording() === true`, but `Sampled` flag in {@link TraceFlags}
* MUST NOT be set.
*/
SamplingDecision[SamplingDecision["RECORD"] = 1] = "RECORD";
/**
* `Span.isRecording() === true` AND `Sampled` flag in {@link TraceFlags}
* MUST be set.
*/
SamplingDecision[SamplingDecision["RECORD_AND_SAMPLED"] = 2] = "RECORD_AND_SAMPLED";
})(SamplingDecision = exports.SamplingDecision || (exports.SamplingDecision = {}));
//# sourceMappingURL=SamplingResult.js.map

View File

@@ -1,71 +0,0 @@
"use strict";
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.getSpanContext = exports.setSpanContext = exports.deleteSpan = exports.setSpan = exports.getActiveSpan = exports.getSpan = void 0;
const context_1 = require("../context/context");
const NonRecordingSpan_1 = require("./NonRecordingSpan");
const context_2 = require("../api/context");
/**
* span key
*/
const SPAN_KEY = (0, context_1.createContextKey)('OpenTelemetry Context Key SPAN');
/**
* Return the span if one exists
*
* @param context context to get span from
*/
function getSpan(context) {
return context.getValue(SPAN_KEY) || undefined;
}
exports.getSpan = getSpan;
/**
* Gets the span from the current context, if one exists.
*/
function getActiveSpan() {
return getSpan(context_2.ContextAPI.getInstance().active());
}
exports.getActiveSpan = getActiveSpan;
/**
* Set the span on a context
*
* @param context context to use as parent
* @param span span to set active
*/
function setSpan(context, span) {
return context.setValue(SPAN_KEY, span);
}
exports.setSpan = setSpan;
/**
* Remove current span stored in the context
*
* @param context context to delete span from
*/
function deleteSpan(context) {
return context.deleteValue(SPAN_KEY);
}
exports.deleteSpan = deleteSpan;
/**
* Wrap span context in a NoopSpan and set as span in a new
* context
*
* @param context context to set active span on
* @param spanContext span context to be wrapped
*/
function setSpanContext(context, spanContext) {
return setSpan(context, new NonRecordingSpan_1.NonRecordingSpan(spanContext));
}
exports.setSpanContext = setSpanContext;
/**
* Get the span context of the span if it exists.
*
* @param context context to get values from
*/
function getSpanContext(context) {
var _a;
return (_a = getSpan(context)) === null || _a === void 0 ? void 0 : _a.spanContext();
}
exports.getSpanContext = getSpanContext;
//# sourceMappingURL=context-utils.js.map

View File

@@ -1,94 +0,0 @@
"use strict";
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.TraceStateImpl = void 0;
const tracestate_validators_1 = require("./tracestate-validators");
const MAX_TRACE_STATE_ITEMS = 32;
const MAX_TRACE_STATE_LEN = 512;
const LIST_MEMBERS_SEPARATOR = ',';
const LIST_MEMBER_KEY_VALUE_SPLITTER = '=';
/**
* TraceState must be a class and not a simple object type because of the spec
* requirement (https://www.w3.org/TR/trace-context/#tracestate-field).
*
* Here is the list of allowed mutations:
* - New key-value pair should be added into the beginning of the list
* - The value of any key can be updated. Modified keys MUST be moved to the
* beginning of the list.
*/
class TraceStateImpl {
constructor(rawTraceState) {
this._internalState = new Map();
if (rawTraceState)
this._parse(rawTraceState);
}
set(key, value) {
// TODO: Benchmark the different approaches(map vs list) and
// use the faster one.
const traceState = this._clone();
if (traceState._internalState.has(key)) {
traceState._internalState.delete(key);
}
traceState._internalState.set(key, value);
return traceState;
}
unset(key) {
const traceState = this._clone();
traceState._internalState.delete(key);
return traceState;
}
get(key) {
return this._internalState.get(key);
}
serialize() {
return (Array.from(this._internalState.keys())
// Use reduceRight() because keys are stored in reverse insertion order.
.reduceRight((agg, key) => {
agg.push(key + LIST_MEMBER_KEY_VALUE_SPLITTER + this.get(key));
return agg;
}, [])
.join(LIST_MEMBERS_SEPARATOR));
}
_parse(rawTraceState) {
if (rawTraceState.length > MAX_TRACE_STATE_LEN)
return;
this._internalState = rawTraceState
.split(LIST_MEMBERS_SEPARATOR)
// Use reduceRight() so new keys (.set(...)) will be placed at the beginning
.reduceRight((agg, part) => {
const listMember = part.trim(); // Optional Whitespace (OWS) handling
const i = listMember.indexOf(LIST_MEMBER_KEY_VALUE_SPLITTER);
if (i !== -1) {
const key = listMember.slice(0, i);
const value = listMember.slice(i + 1, part.length);
if ((0, tracestate_validators_1.validateKey)(key) && (0, tracestate_validators_1.validateValue)(value)) {
agg.set(key, value);
}
else {
// TODO: Consider to add warning log
}
}
return agg;
}, new Map());
// Because of the reverse() requirement, trunc must be done after map is created
if (this._internalState.size > MAX_TRACE_STATE_ITEMS) {
this._internalState = new Map(Array.from(this._internalState.entries())
.reverse() // Use reverse same as original tracestate parse chain
.slice(0, MAX_TRACE_STATE_ITEMS));
}
}
// @ts-expect-error TS6133 Accessed in tests only.
_keys() {
return Array.from(this._internalState.keys()).reverse();
}
_clone() {
const traceState = new TraceStateImpl();
traceState._internalState = new Map(this._internalState);
return traceState;
}
}
exports.TraceStateImpl = TraceStateImpl;
//# sourceMappingURL=tracestate-impl.js.map

View File

@@ -1,35 +0,0 @@
"use strict";
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.validateValue = exports.validateKey = void 0;
const VALID_KEY_CHAR_RANGE = '[_0-9a-z-*/]';
const VALID_KEY = `[a-z]${VALID_KEY_CHAR_RANGE}{0,255}`;
const VALID_VENDOR_KEY = `[a-z0-9]${VALID_KEY_CHAR_RANGE}{0,240}@[a-z]${VALID_KEY_CHAR_RANGE}{0,13}`;
const VALID_KEY_REGEX = new RegExp(`^(?:${VALID_KEY}|${VALID_VENDOR_KEY})$`);
const VALID_VALUE_BASE_REGEX = /^[ -~]{0,255}[!-~]$/;
const INVALID_VALUE_COMMA_EQUAL_REGEX = /,|=/;
/**
* Key is opaque string up to 256 characters printable. It MUST begin with a
* lowercase letter, and can only contain lowercase letters a-z, digits 0-9,
* underscores _, dashes -, asterisks *, and forward slashes /.
* For multi-tenant vendor scenarios, an at sign (@) can be used to prefix the
* vendor name. Vendors SHOULD set the tenant ID at the beginning of the key.
* see https://www.w3.org/TR/trace-context/#key
*/
function validateKey(key) {
return VALID_KEY_REGEX.test(key);
}
exports.validateKey = validateKey;
/**
* Value is opaque string up to 256 characters printable ASCII RFC0020
* characters (i.e., the range 0x20 to 0x7E) except comma , and =.
*/
function validateValue(value) {
return (VALID_VALUE_BASE_REGEX.test(value) &&
!INVALID_VALUE_COMMA_EQUAL_REGEX.test(value));
}
exports.validateValue = validateValue;
//# sourceMappingURL=tracestate-validators.js.map

View File

@@ -1,16 +0,0 @@
"use strict";
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.createTraceState = void 0;
const tracestate_impl_1 = require("./tracestate-impl");
/**
* @since 1.1.0
*/
function createTraceState(rawTraceState) {
return new tracestate_impl_1.TraceStateImpl(rawTraceState);
}
exports.createTraceState = createTraceState;
//# sourceMappingURL=utils.js.map

View File

@@ -1,25 +0,0 @@
"use strict";
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.INVALID_SPAN_CONTEXT = exports.INVALID_TRACEID = exports.INVALID_SPANID = void 0;
const trace_flags_1 = require("./trace_flags");
/**
* @since 1.0.0
*/
exports.INVALID_SPANID = '0000000000000000';
/**
* @since 1.0.0
*/
exports.INVALID_TRACEID = '00000000000000000000000000000000';
/**
* @since 1.0.0
*/
exports.INVALID_SPAN_CONTEXT = {
traceId: exports.INVALID_TRACEID,
spanId: exports.INVALID_SPANID,
traceFlags: trace_flags_1.TraceFlags.NONE,
};
//# sourceMappingURL=invalid-span-constants.js.map

View File

@@ -1,38 +0,0 @@
"use strict";
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.SpanKind = void 0;
/**
* @since 1.0.0
*/
var SpanKind;
(function (SpanKind) {
/** Default value. Indicates that the span is used internally. */
SpanKind[SpanKind["INTERNAL"] = 0] = "INTERNAL";
/**
* Indicates that the span covers server-side handling of an RPC or other
* remote request.
*/
SpanKind[SpanKind["SERVER"] = 1] = "SERVER";
/**
* Indicates that the span covers the client-side wrapper around an RPC or
* other remote request.
*/
SpanKind[SpanKind["CLIENT"] = 2] = "CLIENT";
/**
* Indicates that the span describes producer sending a message to a
* broker. Unlike client and server, there is no direct critical path latency
* relationship between producer and consumer spans.
*/
SpanKind[SpanKind["PRODUCER"] = 3] = "PRODUCER";
/**
* Indicates that the span describes consumer receiving a message from a
* broker. Unlike client and server, there is no direct critical path latency
* relationship between producer and consumer spans.
*/
SpanKind[SpanKind["CONSUMER"] = 4] = "CONSUMER";
})(SpanKind = exports.SpanKind || (exports.SpanKind = {}));
//# sourceMappingURL=span_kind.js.map

View File

@@ -1,66 +0,0 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.wrapSpanContext = exports.isSpanContextValid = exports.isValidSpanId = exports.isValidTraceId = void 0;
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
const invalid_span_constants_1 = require("./invalid-span-constants");
const NonRecordingSpan_1 = require("./NonRecordingSpan");
// Valid characters (0-9, a-f, A-F) are marked as 1.
const isHex = new Uint8Array([
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1,
]);
function isValidHex(id, length) {
// As of 1.9.0 the id was allowed to be a non-string value,
// even though it was not possible in the types.
if (typeof id !== 'string' || id.length !== length)
return false;
let r = 0;
for (let i = 0; i < id.length; i += 4) {
r +=
(isHex[id.charCodeAt(i)] | 0) +
(isHex[id.charCodeAt(i + 1)] | 0) +
(isHex[id.charCodeAt(i + 2)] | 0) +
(isHex[id.charCodeAt(i + 3)] | 0);
}
return r === length;
}
/**
* @since 1.0.0
*/
function isValidTraceId(traceId) {
return isValidHex(traceId, 32) && traceId !== invalid_span_constants_1.INVALID_TRACEID;
}
exports.isValidTraceId = isValidTraceId;
/**
* @since 1.0.0
*/
function isValidSpanId(spanId) {
return isValidHex(spanId, 16) && spanId !== invalid_span_constants_1.INVALID_SPANID;
}
exports.isValidSpanId = isValidSpanId;
/**
* Returns true if this {@link SpanContext} is valid.
* @return true if this {@link SpanContext} is valid.
*
* @since 1.0.0
*/
function isSpanContextValid(spanContext) {
return (isValidTraceId(spanContext.traceId) && isValidSpanId(spanContext.spanId));
}
exports.isSpanContextValid = isSpanContextValid;
/**
* Wrap the given {@link SpanContext} in a new non-recording {@link Span}
*
* @param spanContext span context to be wrapped
* @returns a new non-recording {@link Span} with the provided context
*/
function wrapSpanContext(spanContext) {
return new NonRecordingSpan_1.NonRecordingSpan(spanContext);
}
exports.wrapSpanContext = wrapSpanContext;
//# sourceMappingURL=spancontext-utils.js.map

View File

@@ -1,29 +0,0 @@
"use strict";
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.SpanStatusCode = void 0;
/**
* An enumeration of status codes.
*
* @since 1.0.0
*/
var SpanStatusCode;
(function (SpanStatusCode) {
/**
* The default status.
*/
SpanStatusCode[SpanStatusCode["UNSET"] = 0] = "UNSET";
/**
* The operation has been validated by an Application developer or
* Operator to have completed successfully.
*/
SpanStatusCode[SpanStatusCode["OK"] = 1] = "OK";
/**
* The operation contains an error.
*/
SpanStatusCode[SpanStatusCode["ERROR"] = 2] = "ERROR";
})(SpanStatusCode = exports.SpanStatusCode || (exports.SpanStatusCode = {}));
//# sourceMappingURL=status.js.map

View File

@@ -1,18 +0,0 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.TraceFlags = void 0;
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
/**
* @since 1.0.0
*/
var TraceFlags;
(function (TraceFlags) {
/** Represents no flag set. */
TraceFlags[TraceFlags["NONE"] = 0] = "NONE";
/** Bit to represent whether trace is sampled in trace flags. */
TraceFlags[TraceFlags["SAMPLED"] = 1] = "SAMPLED";
})(TraceFlags = exports.TraceFlags || (exports.TraceFlags = {}));
//# sourceMappingURL=trace_flags.js.map

View File

@@ -1,10 +0,0 @@
"use strict";
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.VERSION = void 0;
// this is autogenerated file, see scripts/version-update.js
exports.VERSION = '1.9.1';
//# sourceMappingURL=version.js.map

View File

@@ -1,96 +0,0 @@
{
"name": "@opentelemetry/api",
"version": "1.9.1",
"description": "Public API for OpenTelemetry",
"main": "build/src/index.js",
"module": "build/esm/index.js",
"esnext": "build/esnext/index.js",
"types": "build/src/index.d.ts",
"exports": {
".": {
"esnext": "./build/esnext/index.js",
"module": "./build/esm/index.js",
"types": "./build/src/index.d.ts",
"default": "./build/src/index.js"
},
"./experimental": {
"esnext": "./build/esnext/experimental/index.js",
"module": "./build/esm/experimental/index.js",
"types": "./build/src/experimental/index.d.ts",
"default": "./build/src/experimental/index.js"
}
},
"repository": "open-telemetry/opentelemetry-js",
"scripts": {
"clean": "tsc --build --clean tsconfig.json tsconfig.esm.json tsconfig.esnext.json",
"compile": "tsc --build tsconfig.json tsconfig.esm.json tsconfig.esnext.json",
"lint:fix": "eslint . --ext .ts --fix",
"lint": "eslint . --ext .ts && npm run cycle-check",
"test:browser": "karma start --single-run",
"test": "nyc mocha 'test/**/*.test.ts'",
"test:node8-compat": "node test/backcompat/node8-compat.js",
"test:webworker": "karma start karma.worker.js --single-run",
"cycle-check": "dpdm --exit-code circular:1 src/index.ts",
"version": "node ../scripts/version-update.js",
"prewatch": "npm run precompile",
"watch": "tsc --build --watch tsconfig.json tsconfig.esm.json tsconfig.esnext.json",
"peer-api-check": "node ../scripts/peer-api-check.js"
},
"keywords": [
"opentelemetry",
"nodejs",
"browser",
"tracing",
"profiling",
"stats",
"monitoring"
],
"author": "OpenTelemetry Authors",
"license": "Apache-2.0",
"engines": {
"node": ">=8.0.0"
},
"files": [
"build/esm/**/*.js",
"build/esm/**/*.js.map",
"build/esm/**/*.d.ts",
"build/esnext/**/*.js",
"build/esnext/**/*.js.map",
"build/esnext/**/*.d.ts",
"build/src/**/*.js",
"build/src/**/*.js.map",
"build/src/**/*.d.ts",
"LICENSE",
"README.md"
],
"publishConfig": {
"access": "public"
},
"devDependencies": {
"@types/mocha": "10.0.10",
"@types/node": "^8.10.66",
"@types/sinon": "17.0.4",
"@types/webpack": "5.28.5",
"@types/webpack-env": "1.16.3",
"babel-plugin-istanbul": "7.0.1",
"dpdm": "4.0.1",
"karma": "6.4.4",
"karma-chrome-launcher": "3.1.0",
"karma-coverage": "2.2.1",
"karma-mocha": "2.0.1",
"karma-mocha-webworker": "1.3.0",
"karma-spec-reporter": "0.0.36",
"karma-webpack": "5.0.1",
"memfs": "3.5.3",
"mocha": "11.7.5",
"nyc": "17.1.0",
"sinon": "18.0.1",
"ts-loader": "9.5.4",
"typescript": "5.0.4",
"unionfs": "4.5.4",
"webpack": "5.104.1"
},
"homepage": "https://github.com/open-telemetry/opentelemetry-js/tree/main/api",
"sideEffects": false,
"gitHead": "7e74509a4d848e94b2970bb5262dd3e8efeed0a2"
}

View File

@@ -1,8 +0,0 @@
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
import * as child_process from 'child_process';
import * as util from 'util';
export const execAsync = util.promisify(child_process.exec);
//# sourceMappingURL=execAsync.js.map

View File

@@ -1,25 +0,0 @@
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
import { promises as fs } from 'fs';
import { execAsync } from './execAsync';
import { diag } from '@opentelemetry/api';
export async function getMachineId() {
try {
const result = await fs.readFile('/etc/hostid', { encoding: 'utf8' });
return result.trim();
}
catch (e) {
diag.debug(`error reading machine id: ${e}`);
}
try {
const result = await execAsync('kenv -q smbios.system.uuid');
return result.stdout.trim();
}
catch (e) {
diag.debug(`error reading machine id: ${e}`);
}
return undefined;
}
//# sourceMappingURL=getMachineId-bsd.js.map

View File

@@ -1,26 +0,0 @@
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
import { execAsync } from './execAsync';
import { diag } from '@opentelemetry/api';
export async function getMachineId() {
try {
const result = await execAsync('ioreg -rd1 -c "IOPlatformExpertDevice"');
const idLine = result.stdout
.split('\n')
.find(line => line.includes('IOPlatformUUID'));
if (!idLine) {
return undefined;
}
const parts = idLine.split('" = "');
if (parts.length === 2) {
return parts[1].slice(0, -1);
}
}
catch (e) {
diag.debug(`error reading machine id: ${e}`);
}
return undefined;
}
//# sourceMappingURL=getMachineId-darwin.js.map

View File

@@ -1,20 +0,0 @@
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
import { promises as fs } from 'fs';
import { diag } from '@opentelemetry/api';
export async function getMachineId() {
const paths = ['/etc/machine-id', '/var/lib/dbus/machine-id'];
for (const path of paths) {
try {
const result = await fs.readFile(path, { encoding: 'utf8' });
return result.trim();
}
catch (e) {
diag.debug(`error reading machine id: ${e}`);
}
}
return undefined;
}
//# sourceMappingURL=getMachineId-linux.js.map

View File

@@ -1,10 +0,0 @@
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
import { diag } from '@opentelemetry/api';
export async function getMachineId() {
diag.debug('could not read machine-id: unsupported platform');
return undefined;
}
//# sourceMappingURL=getMachineId-unsupported.js.map

View File

@@ -1,26 +0,0 @@
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
import * as process from 'process';
import { execAsync } from './execAsync';
import { diag } from '@opentelemetry/api';
export async function getMachineId() {
const args = 'QUERY HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Cryptography /v MachineGuid';
let command = '%windir%\\System32\\REG.exe';
if (process.arch === 'ia32' && 'PROCESSOR_ARCHITEW6432' in process.env) {
command = '%windir%\\sysnative\\cmd.exe /c ' + command;
}
try {
const result = await execAsync(`${command} ${args}`);
const parts = result.stdout.split('REG_SZ');
if (parts.length === 2) {
return parts[1].trim();
}
}
catch (e) {
diag.debug(`error reading machine id: ${e}`);
}
return undefined;
}
//# sourceMappingURL=getMachineId-win.js.map

View File

@@ -1,32 +0,0 @@
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
import * as process from 'process';
let getMachineIdImpl;
export async function getMachineId() {
if (!getMachineIdImpl) {
switch (process.platform) {
case 'darwin':
getMachineIdImpl = (await import('./getMachineId-darwin.js'))
.getMachineId;
break;
case 'linux':
getMachineIdImpl = (await import('./getMachineId-linux.js'))
.getMachineId;
break;
case 'freebsd':
getMachineIdImpl = (await import('./getMachineId-bsd.js')).getMachineId;
break;
case 'win32':
getMachineIdImpl = (await import('./getMachineId-win.js')).getMachineId;
break;
default:
getMachineIdImpl = (await import('./getMachineId-unsupported.js'))
.getMachineId;
break;
}
}
return getMachineIdImpl();
}
//# sourceMappingURL=getMachineId.js.map

View File

@@ -1,529 +0,0 @@
'use strict'
function deepClone (obj) {
if (obj === null || typeof obj !== 'object') {
return obj
}
if (obj instanceof Date) {
return new Date(obj.getTime())
}
if (obj instanceof Array) {
const cloned = []
for (let i = 0; i < obj.length; i++) {
cloned[i] = deepClone(obj[i])
}
return cloned
}
if (typeof obj === 'object') {
const cloned = Object.create(Object.getPrototypeOf(obj))
for (const key in obj) {
if (Object.prototype.hasOwnProperty.call(obj, key)) {
cloned[key] = deepClone(obj[key])
}
}
return cloned
}
return obj
}
function parsePath (path) {
const parts = []
let current = ''
let inBrackets = false
let inQuotes = false
let quoteChar = ''
for (let i = 0; i < path.length; i++) {
const char = path[i]
if (!inBrackets && char === '.') {
if (current) {
parts.push(current)
current = ''
}
} else if (char === '[') {
if (current) {
parts.push(current)
current = ''
}
inBrackets = true
} else if (char === ']' && inBrackets) {
// Always push the current value when closing brackets, even if it's an empty string
parts.push(current)
current = ''
inBrackets = false
inQuotes = false
} else if ((char === '"' || char === "'") && inBrackets) {
if (!inQuotes) {
inQuotes = true
quoteChar = char
} else if (char === quoteChar) {
inQuotes = false
quoteChar = ''
} else {
current += char
}
} else {
current += char
}
}
if (current) {
parts.push(current)
}
return parts
}
function setValue (obj, parts, value) {
let current = obj
for (let i = 0; i < parts.length - 1; i++) {
const key = parts[i]
// Type safety: Check if current is an object before using 'in' operator
if (typeof current !== 'object' || current === null || !(key in current)) {
return false // Path doesn't exist, don't create it
}
if (typeof current[key] !== 'object' || current[key] === null) {
return false // Path doesn't exist properly
}
current = current[key]
}
const lastKey = parts[parts.length - 1]
if (lastKey === '*') {
if (Array.isArray(current)) {
for (let i = 0; i < current.length; i++) {
current[i] = value
}
} else if (typeof current === 'object' && current !== null) {
for (const key in current) {
if (Object.prototype.hasOwnProperty.call(current, key)) {
current[key] = value
}
}
}
} else {
// Type safety: Check if current is an object before using 'in' operator
if (typeof current === 'object' && current !== null && lastKey in current && Object.prototype.hasOwnProperty.call(current, lastKey)) {
current[lastKey] = value
}
}
return true
}
function removeKey (obj, parts) {
let current = obj
for (let i = 0; i < parts.length - 1; i++) {
const key = parts[i]
// Type safety: Check if current is an object before using 'in' operator
if (typeof current !== 'object' || current === null || !(key in current)) {
return false // Path doesn't exist, don't create it
}
if (typeof current[key] !== 'object' || current[key] === null) {
return false // Path doesn't exist properly
}
current = current[key]
}
const lastKey = parts[parts.length - 1]
if (lastKey === '*') {
if (Array.isArray(current)) {
// For arrays, we can't really "remove" all items as that would change indices
// Instead, we set them to undefined which will be omitted by JSON.stringify
for (let i = 0; i < current.length; i++) {
current[i] = undefined
}
} else if (typeof current === 'object' && current !== null) {
for (const key in current) {
if (Object.prototype.hasOwnProperty.call(current, key)) {
delete current[key]
}
}
}
} else {
// Type safety: Check if current is an object before using 'in' operator
if (typeof current === 'object' && current !== null && lastKey in current && Object.prototype.hasOwnProperty.call(current, lastKey)) {
delete current[lastKey]
}
}
return true
}
// Sentinel object to distinguish between undefined value and non-existent path
const PATH_NOT_FOUND = Symbol('PATH_NOT_FOUND')
function getValueIfExists (obj, parts) {
let current = obj
for (const part of parts) {
if (current === null || current === undefined) {
return PATH_NOT_FOUND
}
// Type safety: Check if current is an object before property access
if (typeof current !== 'object' || current === null) {
return PATH_NOT_FOUND
}
// Check if the property exists before accessing it
if (!(part in current)) {
return PATH_NOT_FOUND
}
current = current[part]
}
return current
}
function getValue (obj, parts) {
let current = obj
for (const part of parts) {
if (current === null || current === undefined) {
return undefined
}
// Type safety: Check if current is an object before property access
if (typeof current !== 'object' || current === null) {
return undefined
}
current = current[part]
}
return current
}
function redactPaths (obj, paths, censor, remove = false) {
for (const path of paths) {
const parts = parsePath(path)
if (parts.includes('*')) {
redactWildcardPath(obj, parts, censor, path, remove)
} else {
if (remove) {
removeKey(obj, parts)
} else {
// Get value only if path exists - single traversal
const value = getValueIfExists(obj, parts)
if (value === PATH_NOT_FOUND) {
continue
}
const actualCensor = typeof censor === 'function'
? censor(value, parts)
: censor
setValue(obj, parts, actualCensor)
}
}
}
}
function redactWildcardPath (obj, parts, censor, originalPath, remove = false) {
const wildcardIndex = parts.indexOf('*')
if (wildcardIndex === parts.length - 1) {
const parentParts = parts.slice(0, -1)
let current = obj
for (const part of parentParts) {
if (current === null || current === undefined) return
// Type safety: Check if current is an object before property access
if (typeof current !== 'object' || current === null) return
current = current[part]
}
if (Array.isArray(current)) {
if (remove) {
// For arrays, set all items to undefined which will be omitted by JSON.stringify
for (let i = 0; i < current.length; i++) {
current[i] = undefined
}
} else {
for (let i = 0; i < current.length; i++) {
const indexPath = [...parentParts, i.toString()]
const actualCensor = typeof censor === 'function'
? censor(current[i], indexPath)
: censor
current[i] = actualCensor
}
}
} else if (typeof current === 'object' && current !== null) {
if (remove) {
// Collect keys to delete to avoid issues with deleting during iteration
const keysToDelete = []
for (const key in current) {
if (Object.prototype.hasOwnProperty.call(current, key)) {
keysToDelete.push(key)
}
}
for (const key of keysToDelete) {
delete current[key]
}
} else {
for (const key in current) {
const keyPath = [...parentParts, key]
const actualCensor = typeof censor === 'function'
? censor(current[key], keyPath)
: censor
current[key] = actualCensor
}
}
}
} else {
redactIntermediateWildcard(obj, parts, censor, wildcardIndex, originalPath, remove)
}
}
function redactIntermediateWildcard (obj, parts, censor, wildcardIndex, originalPath, remove = false) {
const beforeWildcard = parts.slice(0, wildcardIndex)
const afterWildcard = parts.slice(wildcardIndex + 1)
const pathArray = [] // Cached array to avoid allocations
function traverse (current, pathLength) {
if (pathLength === beforeWildcard.length) {
if (Array.isArray(current)) {
for (let i = 0; i < current.length; i++) {
pathArray[pathLength] = i.toString()
traverse(current[i], pathLength + 1)
}
} else if (typeof current === 'object' && current !== null) {
for (const key in current) {
pathArray[pathLength] = key
traverse(current[key], pathLength + 1)
}
}
} else if (pathLength < beforeWildcard.length) {
const nextKey = beforeWildcard[pathLength]
// Type safety: Check if current is an object before using 'in' operator
if (current && typeof current === 'object' && current !== null && nextKey in current) {
pathArray[pathLength] = nextKey
traverse(current[nextKey], pathLength + 1)
}
} else {
// Check if afterWildcard contains more wildcards
if (afterWildcard.includes('*')) {
// Recursively handle remaining wildcards
// Wrap censor to prepend current path context
const wrappedCensor = typeof censor === 'function'
? (value, path) => {
const fullPath = [...pathArray.slice(0, pathLength), ...path]
return censor(value, fullPath)
}
: censor
redactWildcardPath(current, afterWildcard, wrappedCensor, originalPath, remove)
} else {
// No more wildcards, apply the redaction directly
if (remove) {
removeKey(current, afterWildcard)
} else {
const actualCensor = typeof censor === 'function'
? censor(getValue(current, afterWildcard), [...pathArray.slice(0, pathLength), ...afterWildcard])
: censor
setValue(current, afterWildcard, actualCensor)
}
}
}
}
if (beforeWildcard.length === 0) {
traverse(obj, 0)
} else {
let current = obj
for (let i = 0; i < beforeWildcard.length; i++) {
const part = beforeWildcard[i]
if (current === null || current === undefined) return
// Type safety: Check if current is an object before property access
if (typeof current !== 'object' || current === null) return
current = current[part]
pathArray[i] = part
}
if (current !== null && current !== undefined) {
traverse(current, beforeWildcard.length)
}
}
}
function buildPathStructure (pathsToClone) {
if (pathsToClone.length === 0) {
return null // No paths to redact
}
// Parse all paths and organize by depth
const pathStructure = new Map()
for (const path of pathsToClone) {
const parts = parsePath(path)
let current = pathStructure
for (let i = 0; i < parts.length; i++) {
const part = parts[i]
if (!current.has(part)) {
current.set(part, new Map())
}
current = current.get(part)
}
}
return pathStructure
}
function selectiveClone (obj, pathStructure) {
if (!pathStructure) {
return obj // No paths to redact, return original
}
function cloneSelectively (source, pathMap, depth = 0) {
if (!pathMap || pathMap.size === 0) {
return source // No more paths to clone, return reference
}
if (source === null || typeof source !== 'object') {
return source
}
if (source instanceof Date) {
return new Date(source.getTime())
}
if (Array.isArray(source)) {
const cloned = []
for (let i = 0; i < source.length; i++) {
const indexStr = i.toString()
if (pathMap.has(indexStr) || pathMap.has('*')) {
cloned[i] = cloneSelectively(source[i], pathMap.get(indexStr) || pathMap.get('*'))
} else {
cloned[i] = source[i] // Share reference for non-redacted items
}
}
return cloned
}
// Handle objects
const cloned = Object.create(Object.getPrototypeOf(source))
for (const key in source) {
if (Object.prototype.hasOwnProperty.call(source, key)) {
if (pathMap.has(key) || pathMap.has('*')) {
cloned[key] = cloneSelectively(source[key], pathMap.get(key) || pathMap.get('*'))
} else {
cloned[key] = source[key] // Share reference for non-redacted properties
}
}
}
return cloned
}
return cloneSelectively(obj, pathStructure)
}
function validatePath (path) {
if (typeof path !== 'string') {
throw new Error('Paths must be (non-empty) strings')
}
if (path === '') {
throw new Error('Invalid redaction path ()')
}
// Check for double dots
if (path.includes('..')) {
throw new Error(`Invalid redaction path (${path})`)
}
// Check for comma-separated paths (invalid syntax)
if (path.includes(',')) {
throw new Error(`Invalid redaction path (${path})`)
}
// Check for unmatched brackets
let bracketCount = 0
let inQuotes = false
let quoteChar = ''
for (let i = 0; i < path.length; i++) {
const char = path[i]
if ((char === '"' || char === "'") && bracketCount > 0) {
if (!inQuotes) {
inQuotes = true
quoteChar = char
} else if (char === quoteChar) {
inQuotes = false
quoteChar = ''
}
} else if (char === '[' && !inQuotes) {
bracketCount++
} else if (char === ']' && !inQuotes) {
bracketCount--
if (bracketCount < 0) {
throw new Error(`Invalid redaction path (${path})`)
}
}
}
if (bracketCount !== 0) {
throw new Error(`Invalid redaction path (${path})`)
}
}
function validatePaths (paths) {
if (!Array.isArray(paths)) {
throw new TypeError('paths must be an array')
}
for (const path of paths) {
validatePath(path)
}
}
function slowRedact (options = {}) {
const {
paths = [],
censor = '[REDACTED]',
serialize = JSON.stringify,
strict = true,
remove = false
} = options
// Validate paths upfront to match fast-redact behavior
validatePaths(paths)
// Build path structure once during setup, not on every call
const pathStructure = buildPathStructure(paths)
return function redact (obj) {
if (strict && (obj === null || typeof obj !== 'object')) {
if (obj === null || obj === undefined) {
return serialize ? serialize(obj) : obj
}
if (typeof obj !== 'object') {
return serialize ? serialize(obj) : obj
}
}
// Only clone paths that need redaction
const cloned = selectiveClone(obj, pathStructure)
const original = obj // Keep reference to original for restore
let actualCensor = censor
if (typeof censor === 'function') {
actualCensor = censor
}
redactPaths(cloned, paths, actualCensor, remove)
if (serialize === false) {
cloned.restore = function () {
return deepClone(original) // Full clone only when restore is called
}
return cloned
}
if (typeof serialize === 'function') {
return serialize(cloned)
}
return JSON.stringify(cloned)
}
}
module.exports = slowRedact

View File

@@ -1,37 +0,0 @@
{
"name": "@pinojs/redact",
"version": "0.4.0",
"description": "Redact JS objects",
"main": "index.js",
"types": "index.d.ts",
"scripts": {
"test": "node --test && npm run test:types",
"test:integration": "node --test test/integration.test.js",
"test:types": "tsd",
"test:all": "node --test test/*.test.js",
"lint": "eslint .",
"lint:fix": "eslint . --fix",
"bench": "node benchmarks/basic.js"
},
"repository": {
"type": "git",
"url": "git+https://github.com/pinojs/redact.git"
},
"keywords": [
"redact"
],
"author": "Matteo Collina <hello@matteocollina.com>",
"license": "MIT",
"bugs": {
"url": "https://github.com/pinojs/redact/issues"
},
"homepage": "https://github.com/pinojs/redact#readme",
"devDependencies": {
"eslint": "^9.36.0",
"fast-redact": "^3.5.0",
"mitata": "^1.0.34",
"neostandard": "^0.12.2",
"tsd": "^0.33.0",
"typescript": "^5.9.2"
}
}

View File

@@ -1,51 +0,0 @@
Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
const react = require('@sentry/react');
const nextRoutingInstrumentation = require('./routing/nextRoutingInstrumentation.js');
/**
* A custom browser tracing integration for Next.js.
*/
function browserTracingIntegration(
options = {},
) {
const browserTracingIntegrationInstance = react.browserTracingIntegration({
...options,
instrumentNavigation: false,
instrumentPageLoad: false,
onRequestSpanStart(...args) {
const [span, { headers }] = args;
// Next.js prefetch requests have a `next-router-prefetch` header
if (headers?.get('next-router-prefetch')) {
span?.setAttribute('http.request.prefetch', true);
}
return options.onRequestSpanStart?.(...args);
},
});
const { instrumentPageLoad = true, instrumentNavigation = true } = options;
return {
...browserTracingIntegrationInstance,
afterAllSetup(client) {
// We need to run the navigation span instrumentation before the `afterAllSetup` hook on the normal browser
// tracing integration because we need to ensure the order of execution is as follows:
// Instrumentation to start span on RSC fetch request runs -> Instrumentation to put tracing headers from active span on fetch runs
// If it were the other way around, the RSC fetch request would not receive the tracing headers from the navigation transaction.
if (instrumentNavigation) {
nextRoutingInstrumentation.nextRouterInstrumentNavigation(client);
}
browserTracingIntegrationInstance.afterAllSetup(client);
if (instrumentPageLoad) {
nextRoutingInstrumentation.nextRouterInstrumentPageLoad(client);
}
},
};
}
exports.browserTracingIntegration = browserTracingIntegration;
//# sourceMappingURL=browserTracingIntegration.js.map

View File

@@ -1,96 +0,0 @@
Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
const core = require('@sentry/core');
const react = require('@sentry/react');
const nextjsClientStackFrameNormalizationIntegration = core.defineIntegration(
({
assetPrefix,
basePath,
rewriteFramesAssetPrefixPath,
experimentalThirdPartyOriginStackFrames,
}
) => {
const rewriteFramesInstance = react.rewriteFramesIntegration({
// Turn `<origin>/<path>/_next/static/...` into `app:///_next/static/...`
iteratee: frame => {
if (experimentalThirdPartyOriginStackFrames) {
// Not sure why but access to global WINDOW from @sentry/Browser causes hideous ci errors
// oxlint-disable-next-line typescript/prefer-optional-chain no-restricted-globals
const windowOrigin = typeof window !== 'undefined' && window.location ? window.location.origin : '';
// A filename starting with the local origin and not ending with JS is most likely JS in HTML which we do not want to rewrite
if (frame.filename?.startsWith(windowOrigin) && !frame.filename.endsWith('.js')) {
return frame;
}
if (assetPrefix) {
// If the user defined an asset prefix, we need to strip it so that we can match it with uploaded sourcemaps.
// assetPrefix always takes priority over basePath.
if (frame.filename?.startsWith(assetPrefix)) {
frame.filename = frame.filename.replace(assetPrefix, 'app://');
}
} else if (basePath) {
// If the user defined a base path, we need to strip it to match with uploaded sourcemaps.
// We should only do this for same-origin filenames though, so that third party assets are not rewritten.
try {
const { origin: frameOrigin } = new URL(frame.filename );
if (frameOrigin === windowOrigin) {
frame.filename = frame.filename?.replace(frameOrigin, 'app://').replace(basePath, '');
}
} catch {
// Filename wasn't a properly formed URL, so there's nothing we can do
}
}
} else {
try {
const { origin } = new URL(frame.filename );
frame.filename = frame.filename?.replace(origin, 'app://').replace(rewriteFramesAssetPrefixPath, '');
} catch {
// Filename wasn't a properly formed URL, so there's nothing we can do
}
}
// We need to URI-decode the filename because Next.js has wildcard routes like "/users/[id].js" which show up as "/users/%5id%5.js" in Error stacktraces.
// The corresponding sources that Next.js generates have proper brackets so we also need proper brackets in the frame so that source map resolving works.
if (experimentalThirdPartyOriginStackFrames) {
if (frame.filename?.includes('/_next')) {
frame.filename = decodeURI(frame.filename);
}
if (
frame.filename?.match(
/\/_next\/static\/chunks\/(main-|main-app-|polyfills-|webpack-|framework-|framework\.)[0-9a-f]+\.js$/,
)
) {
// We don't care about these frames. It's Next.js internal code.
frame.in_app = false;
}
} else {
if (frame.filename?.startsWith('app:///_next')) {
frame.filename = decodeURI(frame.filename);
}
if (
frame.filename?.match(
/^app:\/\/\/_next\/static\/chunks\/(main-|main-app-|polyfills-|webpack-|framework-|framework\.)[0-9a-f]+\.js$/,
)
) {
// We don't care about these frames. It's Next.js internal code.
frame.in_app = false;
}
}
return frame;
},
});
return {
...rewriteFramesInstance,
name: 'NextjsClientStackFrameNormalization',
};
},
);
exports.nextjsClientStackFrameNormalizationIntegration = nextjsClientStackFrameNormalizationIntegration;
//# sourceMappingURL=clientNormalizationIntegration.js.map

View File

@@ -1,186 +0,0 @@
"use client";
Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
const core = require('@sentry/core');
const react = require('@sentry/react');
const debugBuild = require('../common/debug-build.js');
const devErrorSymbolicationEventProcessor = require('../common/devErrorSymbolicationEventProcessor.js');
const getVercelEnv = require('../common/getVercelEnv.js');
const nextNavigationErrorUtils = require('../common/nextNavigationErrorUtils.js');
const browserTracingIntegration = require('./browserTracingIntegration.js');
const clientNormalizationIntegration = require('./clientNormalizationIntegration.js');
const appRouterRoutingInstrumentation = require('./routing/appRouterRoutingInstrumentation.js');
const isrRoutingTracing = require('./routing/isrRoutingTracing.js');
const tunnelRoute = require('./tunnelRoute.js');
const wrapGetStaticPropsWithSentry = require('../common/pages-router-instrumentation/wrapGetStaticPropsWithSentry.js');
const wrapGetInitialPropsWithSentry = require('../common/pages-router-instrumentation/wrapGetInitialPropsWithSentry.js');
const wrapAppGetInitialPropsWithSentry = require('../common/pages-router-instrumentation/wrapAppGetInitialPropsWithSentry.js');
const wrapDocumentGetInitialPropsWithSentry = require('../common/pages-router-instrumentation/wrapDocumentGetInitialPropsWithSentry.js');
const wrapErrorGetInitialPropsWithSentry = require('../common/pages-router-instrumentation/wrapErrorGetInitialPropsWithSentry.js');
const wrapGetServerSidePropsWithSentry = require('../common/pages-router-instrumentation/wrapGetServerSidePropsWithSentry.js');
const wrapServerComponentWithSentry = require('../common/wrapServerComponentWithSentry.js');
const wrapRouteHandlerWithSentry = require('../common/wrapRouteHandlerWithSentry.js');
const wrapApiHandlerWithSentryVercelCrons = require('../common/pages-router-instrumentation/wrapApiHandlerWithSentryVercelCrons.js');
const wrapMiddlewareWithSentry = require('../common/wrapMiddlewareWithSentry.js');
const wrapPageComponentWithSentry = require('../common/pages-router-instrumentation/wrapPageComponentWithSentry.js');
const wrapGenerationFunctionWithSentry = require('../common/wrapGenerationFunctionWithSentry.js');
const withServerActionInstrumentation = require('../common/withServerActionInstrumentation.js');
const captureRequestError = require('../common/captureRequestError.js');
const _error = require('../common/pages-router-instrumentation/_error.js');
const nextSpan = require('../common/utils/nextSpan.js');
let clientIsInitialized = false;
const globalWithInjectedValues = core.GLOBAL_OBJ
;
// Treeshakable guard to remove all code related to tracing
/** Inits the Sentry NextJS SDK on the browser with the React SDK. */
function init(options) {
if (clientIsInitialized) {
core.consoleSandbox(() => {
// eslint-disable-next-line no-console
console.warn(
'[@sentry/nextjs] You are calling `Sentry.init()` more than once on the client. This can happen if you have both a `sentry.client.config.ts` and a `instrumentation-client.ts` file with `Sentry.init()` calls. It is recommended to call `Sentry.init()` once in `instrumentation-client.ts`.',
);
});
}
clientIsInitialized = true;
if (!debugBuild.DEBUG_BUILD && options.debug) {
core.consoleSandbox(() => {
// eslint-disable-next-line no-console
console.warn(
'[@sentry/nextjs] You have enabled `debug: true`, but Sentry debug logging was removed from your bundle (likely via `withSentryConfig({ disableLogger: true })` / `webpack.treeshake.removeDebugLogging: true`). Set that option to `false` to see Sentry debug output.',
);
});
}
// Remove cached trace meta tags for ISR/SSG pages before initializing
// This prevents the browser tracing integration from using stale trace IDs
if (typeof __SENTRY_TRACING__ === 'undefined' || __SENTRY_TRACING__) {
isrRoutingTracing.removeIsrSsgTraceMetaTags();
}
const opts = {
environment: options.environment || process.env.SENTRY_ENVIRONMENT || getVercelEnv.getVercelEnv(true) || process.env.NODE_ENV,
defaultIntegrations: getDefaultIntegrations(options),
release: process.env._sentryRelease || globalWithInjectedValues._sentryRelease,
...options,
} ;
tunnelRoute.applyTunnelRouteOption(opts);
core.applySdkMetadata(opts, 'nextjs', ['nextjs', 'react']);
const client = react.init(opts);
const filterTransactions = event =>
event.type === 'transaction' && event.transaction === '/404' ? null : event;
filterTransactions.id = 'NextClient404Filter';
core.addEventProcessor(filterTransactions);
const filterIncompleteNavigationTransactions = event =>
event.type === 'transaction' && event.transaction === appRouterRoutingInstrumentation.INCOMPLETE_APP_ROUTER_INSTRUMENTATION_TRANSACTION_NAME
? null
: event;
filterIncompleteNavigationTransactions.id = 'IncompleteTransactionFilter';
core.addEventProcessor(filterIncompleteNavigationTransactions);
const filterNextRedirectError = (event, hint) =>
nextNavigationErrorUtils.isRedirectNavigationError(hint?.originalException) || event.exception?.values?.[0]?.value === 'NEXT_REDIRECT'
? null
: event;
filterNextRedirectError.id = 'NextRedirectErrorFilter';
core.addEventProcessor(filterNextRedirectError);
if (process.env.NODE_ENV === 'development') {
core.addEventProcessor(devErrorSymbolicationEventProcessor.devErrorSymbolicationEventProcessor);
}
try {
// @ts-expect-error `process.turbopack` is a magic string that will be replaced by Next.js
if (process.turbopack) {
core.getGlobalScope().setTag('turbopack', true);
}
} catch {
// Noop
// The statement above can throw because process is not defined on the client
}
return client;
}
function getDefaultIntegrations(options) {
const customDefaultIntegrations = react.getDefaultIntegrations(options);
// This evaluates to true unless __SENTRY_TRACING__ is text-replaced with "false",
// in which case everything inside will get tree-shaken away
if (typeof __SENTRY_TRACING__ === 'undefined' || __SENTRY_TRACING__) {
customDefaultIntegrations.push(browserTracingIntegration.browserTracingIntegration());
}
// These values are injected at build time, based on the output directory specified in the build config. Though a default
// is set there, we set it here as well, just in case something has gone wrong with the injection.
const rewriteFramesAssetPrefixPath =
process.env._sentryRewriteFramesAssetPrefixPath ||
globalWithInjectedValues._sentryRewriteFramesAssetPrefixPath ||
'';
const assetPrefix = process.env._sentryAssetPrefix || globalWithInjectedValues._sentryAssetPrefix;
const basePath = process.env._sentryBasePath || globalWithInjectedValues._sentryBasePath;
const experimentalThirdPartyOriginStackFrames =
process.env._experimentalThirdPartyOriginStackFrames === 'true' ||
globalWithInjectedValues._experimentalThirdPartyOriginStackFrames === 'true';
customDefaultIntegrations.push(
clientNormalizationIntegration.nextjsClientStackFrameNormalizationIntegration({
assetPrefix,
basePath,
rewriteFramesAssetPrefixPath,
experimentalThirdPartyOriginStackFrames,
}),
);
return customDefaultIntegrations;
}
/**
* Just a passthrough in case this is imported from the client.
*/
function withSentryConfig(exportedUserNextConfig) {
return exportedUserNextConfig;
}
exports.browserTracingIntegration = browserTracingIntegration.browserTracingIntegration;
exports.captureRouterTransitionStart = appRouterRoutingInstrumentation.captureRouterTransitionStart;
exports.wrapGetStaticPropsWithSentry = wrapGetStaticPropsWithSentry.wrapGetStaticPropsWithSentry;
exports.wrapGetInitialPropsWithSentry = wrapGetInitialPropsWithSentry.wrapGetInitialPropsWithSentry;
exports.wrapAppGetInitialPropsWithSentry = wrapAppGetInitialPropsWithSentry.wrapAppGetInitialPropsWithSentry;
exports.wrapDocumentGetInitialPropsWithSentry = wrapDocumentGetInitialPropsWithSentry.wrapDocumentGetInitialPropsWithSentry;
exports.wrapErrorGetInitialPropsWithSentry = wrapErrorGetInitialPropsWithSentry.wrapErrorGetInitialPropsWithSentry;
exports.wrapGetServerSidePropsWithSentry = wrapGetServerSidePropsWithSentry.wrapGetServerSidePropsWithSentry;
exports.wrapServerComponentWithSentry = wrapServerComponentWithSentry.wrapServerComponentWithSentry;
exports.wrapRouteHandlerWithSentry = wrapRouteHandlerWithSentry.wrapRouteHandlerWithSentry;
exports.wrapApiHandlerWithSentryVercelCrons = wrapApiHandlerWithSentryVercelCrons.wrapApiHandlerWithSentryVercelCrons;
exports.wrapMiddlewareWithSentry = wrapMiddlewareWithSentry.wrapMiddlewareWithSentry;
exports.wrapPageComponentWithSentry = wrapPageComponentWithSentry.wrapPageComponentWithSentry;
exports.wrapGenerationFunctionWithSentry = wrapGenerationFunctionWithSentry.wrapGenerationFunctionWithSentry;
exports.withServerActionInstrumentation = withServerActionInstrumentation.withServerActionInstrumentation;
exports.captureRequestError = captureRequestError.captureRequestError;
exports.captureUnderscoreErrorException = _error.captureUnderscoreErrorException;
exports.startInactiveSpan = nextSpan.startInactiveSpan;
exports.startSpan = nextSpan.startSpan;
exports.startSpanManual = nextSpan.startSpanManual;
exports.init = init;
exports.withSentryConfig = withSentryConfig;
Object.prototype.hasOwnProperty.call(react, '__proto__') &&
!Object.prototype.hasOwnProperty.call(exports, '__proto__') &&
Object.defineProperty(exports, '__proto__', {
enumerable: true,
value: react['__proto__']
});
Object.keys(react).forEach(k => {
if (k !== 'default' && !Object.prototype.hasOwnProperty.call(exports, k)) exports[k] = react[k];
});
//# sourceMappingURL=index.js.map

View File

@@ -1,250 +0,0 @@
Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
const core = require('@sentry/core');
const react = require('@sentry/react');
const parameterization = require('./parameterization.js');
/**
* Strips trailing slash from a pathname, unless it's the root path.
* This normalizes paths like '/about/' to '/about' to handle Next.js `trailingSlash: true` config.
*/
function stripTrailingSlash(pathname) {
return pathname.length > 1 && pathname.endsWith('/') ? pathname.slice(0, -1) : pathname;
}
const INCOMPLETE_APP_ROUTER_INSTRUMENTATION_TRANSACTION_NAME = 'incomplete-app-router-transaction';
/**
* This mutable keeps track of what router navigation instrumentation mechanism we are using.
*
* The default one is 'router-patch' which is a way of instrumenting that worked up until Next.js 15.3.0 was released.
* For this method we took the global router instance and simply monkey patched all the router methods like push(), replace(), and so on.
* This worked because Next.js itself called the router methods for things like the <Link /> component.
* Vercel decided that it is not good to call these public API methods from within the framework so they switched to an internal system that completely bypasses our monkey patching. This happened in 15.3.0.
*
* We raised with Vercel that this breaks our SDK so together with them we came up with an API for `instrumentation-client.ts` called `onRouterTransitionStart` that is called whenever a navigation is kicked off.
*
* Now we have the problem of version compatibility.
* For older Next.js versions we cannot use the new hook so we need to always patch the router.
* For newer Next.js versions we cannot know whether the user actually registered our handler for the `onRouterTransitionStart` hook, so we need to wait until it was called at least once before switching the instrumentation mechanism.
* The problem is, that the user may still have registered a hook and then call a patched router method.
* First, the monkey patched router method will be called, starting a navigation span, then the hook will also called.
* We need to handle this case and not create two separate navigation spans but instead update the current navigation span and then switch to the new instrumentation mode.
* This is all denoted by this `navigationRoutingMode` variable.
*/
let navigationRoutingMode = 'router-patch';
const currentRouterPatchingNavigationSpanRef = { current: undefined };
/** Instruments the Next.js app router for pageloads. */
function appRouterInstrumentPageLoad(client) {
const pathname = stripTrailingSlash(react.WINDOW.location.pathname);
const parameterizedPathname = parameterization.maybeParameterizeRoute(pathname);
const origin = core.browserPerformanceTimeOrigin();
react.startBrowserTracingPageLoadSpan(client, {
name: parameterizedPathname ?? pathname,
// pageload should always start at timeOrigin (and needs to be in s, not ms)
startTime: origin ? origin / 1000 : undefined,
attributes: {
[core.SEMANTIC_ATTRIBUTE_SENTRY_OP]: 'pageload',
[core.SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.pageload.nextjs.app_router_instrumentation',
[core.SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]: parameterizedPathname ? 'route' : 'url',
},
});
}
// Yes, yes, I know we shouldn't depend on these internals. But that's where we are at. We write the ugly code, so you don't have to.
const GLOBAL_OBJ_WITH_NEXT_ROUTER = core.GLOBAL_OBJ
;
const globalWithInjectedBasePath = core.GLOBAL_OBJ
;
/*
* The routing instrumentation needs to handle a few cases:
* - Router operations:
* - router.push() (either explicitly called or implicitly through <Link /> tags)
* - router.replace() (either explicitly called or implicitly through <Link replace /> tags)
* - router.back()
* - router.forward()
* - Browser operations:
* - native Browser-back / popstate event (implicitly called by router.back())
* - native Browser-forward / popstate event (implicitly called by router.forward())
*/
/** Instruments the Next.js app router for navigation. */
function appRouterInstrumentNavigation(client) {
routerTransitionHandler = (href, navigationType) => {
const basePath = process.env._sentryBasePath ?? globalWithInjectedBasePath._sentryBasePath;
const normalizedHref = basePath && !href.startsWith(basePath) ? `${basePath}${href}` : href;
const unparameterizedPathname = stripTrailingSlash(new URL(normalizedHref, react.WINDOW.location.href).pathname);
const parameterizedPathname = parameterization.maybeParameterizeRoute(unparameterizedPathname);
const pathname = parameterizedPathname ?? unparameterizedPathname;
if (navigationRoutingMode === 'router-patch') {
navigationRoutingMode = 'transition-start-hook';
}
const currentNavigationSpan = currentRouterPatchingNavigationSpanRef.current;
if (currentNavigationSpan) {
currentNavigationSpan.updateName(pathname);
currentNavigationSpan.setAttributes({
'navigation.type': `router.${navigationType}`,
[core.SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]: parameterizedPathname ? 'route' : 'url',
});
currentRouterPatchingNavigationSpanRef.current = undefined;
} else {
react.startBrowserTracingNavigationSpan(client, {
name: pathname,
attributes: {
[core.SEMANTIC_ATTRIBUTE_SENTRY_OP]: 'navigation',
[core.SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.navigation.nextjs.app_router_instrumentation',
[core.SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]: parameterizedPathname ? 'route' : 'url',
'navigation.type': `router.${navigationType}`,
},
});
}
};
react.WINDOW.addEventListener('popstate', () => {
const pathname = stripTrailingSlash(react.WINDOW.location.pathname);
const parameterizedPathname = parameterization.maybeParameterizeRoute(pathname);
if (currentRouterPatchingNavigationSpanRef.current?.isRecording()) {
currentRouterPatchingNavigationSpanRef.current.updateName(parameterizedPathname ?? pathname);
currentRouterPatchingNavigationSpanRef.current.setAttribute(
core.SEMANTIC_ATTRIBUTE_SENTRY_SOURCE,
parameterizedPathname ? 'route' : 'url',
);
} else {
currentRouterPatchingNavigationSpanRef.current = react.startBrowserTracingNavigationSpan(client, {
name: parameterizedPathname ?? pathname,
attributes: {
[core.SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.navigation.nextjs.app_router_instrumentation',
[core.SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]: parameterizedPathname ? 'route' : 'url',
'navigation.type': 'browser.popstate',
},
});
}
});
let routerPatched = false;
let triesToFindRouter = 0;
const MAX_TRIES_TO_FIND_ROUTER = 500;
const ROUTER_AVAILABILITY_CHECK_INTERVAL_MS = 20;
const checkForRouterAvailabilityInterval = setInterval(() => {
triesToFindRouter++;
const router = GLOBAL_OBJ_WITH_NEXT_ROUTER?.next?.router ?? GLOBAL_OBJ_WITH_NEXT_ROUTER?.nd?.router;
if (routerPatched || triesToFindRouter > MAX_TRIES_TO_FIND_ROUTER) {
clearInterval(checkForRouterAvailabilityInterval);
} else if (router) {
clearInterval(checkForRouterAvailabilityInterval);
routerPatched = true;
patchRouter(client, router, currentRouterPatchingNavigationSpanRef);
// If the router at any point gets overridden - patch again
(['nd', 'next'] ).forEach(globalValueName => {
const globalValue = GLOBAL_OBJ_WITH_NEXT_ROUTER[globalValueName];
if (globalValue) {
GLOBAL_OBJ_WITH_NEXT_ROUTER[globalValueName] = new Proxy(globalValue, {
set(target, p, newValue) {
if (p === 'router' && typeof newValue === 'object' && newValue !== null) {
patchRouter(client, newValue, currentRouterPatchingNavigationSpanRef);
}
// @ts-expect-error we cannot possibly type this
target[p] = newValue;
return true;
},
});
}
});
}
}, ROUTER_AVAILABILITY_CHECK_INTERVAL_MS);
}
function transactionNameifyRouterArgument(target) {
try {
// We provide an arbitrary base because we only care about the pathname and it makes URL parsing more resilient.
return new URL(target, 'http://example.com/').pathname;
} catch {
return '/';
}
}
const patchedRouters = new WeakSet();
function patchRouter(client, router, currentNavigationSpanRef) {
if (patchedRouters.has(router)) {
return;
}
patchedRouters.add(router);
(['back', 'forward', 'push', 'replace'] ).forEach(routerFunctionName => {
if (router?.[routerFunctionName]) {
// @ts-expect-error Weird type error related to not knowing how to associate return values with the individual functions - we can just ignore
router[routerFunctionName] = new Proxy(router[routerFunctionName], {
apply(target, thisArg, argArray) {
if (navigationRoutingMode !== 'router-patch') {
return target.apply(thisArg, argArray);
}
let transactionName = INCOMPLETE_APP_ROUTER_INSTRUMENTATION_TRANSACTION_NAME;
const transactionAttributes = {
[core.SEMANTIC_ATTRIBUTE_SENTRY_OP]: 'navigation',
[core.SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.navigation.nextjs.app_router_instrumentation',
[core.SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]: 'url',
};
const href = argArray[0];
const basePath = process.env._sentryBasePath ?? globalWithInjectedBasePath._sentryBasePath;
const normalizedHref =
basePath && typeof href === 'string' && !href.startsWith(basePath) ? `${basePath}${href}` : href;
if (routerFunctionName === 'push') {
transactionName = stripTrailingSlash(transactionNameifyRouterArgument(normalizedHref));
transactionAttributes['navigation.type'] = 'router.push';
} else if (routerFunctionName === 'replace') {
transactionName = stripTrailingSlash(transactionNameifyRouterArgument(normalizedHref));
transactionAttributes['navigation.type'] = 'router.replace';
} else if (routerFunctionName === 'back') {
transactionAttributes['navigation.type'] = 'router.back';
} else if (routerFunctionName === 'forward') {
transactionAttributes['navigation.type'] = 'router.forward';
}
const parameterizedPathname = parameterization.maybeParameterizeRoute(transactionName);
currentNavigationSpanRef.current = react.startBrowserTracingNavigationSpan(client, {
name: parameterizedPathname ?? transactionName,
attributes: {
...transactionAttributes,
[core.SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]: parameterizedPathname ? 'route' : 'url',
},
});
return target.apply(thisArg, argArray);
},
});
}
});
}
let routerTransitionHandler = undefined;
/**
* A handler for Next.js' `onRouterTransitionStart` hook in `instrumentation-client.ts` to record navigation spans in Sentry.
*/
function captureRouterTransitionStart(href, navigationType) {
if (routerTransitionHandler) {
routerTransitionHandler(href, navigationType);
}
}
exports.INCOMPLETE_APP_ROUTER_INSTRUMENTATION_TRANSACTION_NAME = INCOMPLETE_APP_ROUTER_INSTRUMENTATION_TRANSACTION_NAME;
exports.appRouterInstrumentNavigation = appRouterInstrumentNavigation;
exports.appRouterInstrumentPageLoad = appRouterInstrumentPageLoad;
exports.captureRouterTransitionStart = captureRouterTransitionStart;
//# sourceMappingURL=appRouterRoutingInstrumentation.js.map

View File

@@ -1,70 +0,0 @@
Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
const core = require('@sentry/core');
const react = require('@sentry/react');
const parameterization = require('./parameterization.js');
/**
* Cache for ISR/SSG route checks. Exported for testing purposes.
* @internal
*/
const IS_ISR_SSG_ROUTE_CACHE = new core.LRUMap(100);
/**
* Check if the current page is an ISR/SSG route by checking the route manifest.
* @internal Exported for testing purposes.
*/
function isIsrSsgRoute(pathname) {
// Early parameterization to get the cache key
const parameterizedPath = parameterization.maybeParameterizeRoute(pathname);
const pathToCheck = parameterizedPath || pathname;
// Check cache using the parameterized path as the key
const cachedResult = IS_ISR_SSG_ROUTE_CACHE.get(pathToCheck);
if (cachedResult !== undefined) {
return cachedResult;
}
// Cache miss get the manifest
const manifest = parameterization.getManifest();
if (!manifest?.isrRoutes || !Array.isArray(manifest.isrRoutes) || manifest.isrRoutes.length === 0) {
IS_ISR_SSG_ROUTE_CACHE.set(pathToCheck, false);
return false;
}
const isIsrSsgRoute = manifest.isrRoutes.includes(pathToCheck);
IS_ISR_SSG_ROUTE_CACHE.set(pathToCheck, isIsrSsgRoute);
return isIsrSsgRoute;
}
/**
* Remove sentry-trace and baggage meta tags from the DOM if this is an ISR/SSG page.
* This prevents the browser tracing integration from using stale/cached trace IDs.
*/
function removeIsrSsgTraceMetaTags() {
if (!react.WINDOW.document || !isIsrSsgRoute(react.WINDOW.location.pathname)) {
return;
}
// Helper function to remove a meta tag
function removeMetaTag(metaName) {
try {
const meta = react.WINDOW.document.querySelector(`meta[name="${metaName}"]`);
if (meta) {
meta.remove();
}
} catch {
// ignore errors when removing the meta tag
}
}
// Remove the meta tags so browserTracingIntegration won't pick them up
removeMetaTag('sentry-trace');
removeMetaTag('baggage');
}
exports.IS_ISR_SSG_ROUTE_CACHE = IS_ISR_SSG_ROUTE_CACHE;
exports.isIsrSsgRoute = isIsrSsgRoute;
exports.removeIsrSsgTraceMetaTags = removeIsrSsgTraceMetaTags;
//# sourceMappingURL=isrRoutingTracing.js.map

View File

@@ -1,33 +0,0 @@
Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
const react = require('@sentry/react');
const appRouterRoutingInstrumentation = require('./appRouterRoutingInstrumentation.js');
const pagesRouterRoutingInstrumentation = require('./pagesRouterRoutingInstrumentation.js');
/**
* Instruments the Next.js Client Router for page loads.
*/
function nextRouterInstrumentPageLoad(client) {
const isAppRouter = !react.WINDOW.document.getElementById('__NEXT_DATA__');
if (isAppRouter) {
appRouterRoutingInstrumentation.appRouterInstrumentPageLoad(client);
} else {
pagesRouterRoutingInstrumentation.pagesRouterInstrumentPageLoad(client);
}
}
/**
* Instruments the Next.js Client Router for navigation.
*/
function nextRouterInstrumentNavigation(client) {
const isAppRouter = !react.WINDOW.document.getElementById('__NEXT_DATA__');
if (isAppRouter) {
appRouterRoutingInstrumentation.appRouterInstrumentNavigation(client);
} else {
pagesRouterRoutingInstrumentation.pagesRouterInstrumentNavigation(client);
}
}
exports.nextRouterInstrumentNavigation = nextRouterInstrumentNavigation;
exports.nextRouterInstrumentPageLoad = nextRouterInstrumentPageLoad;
//# sourceMappingURL=nextRoutingInstrumentation.js.map

View File

@@ -1,201 +0,0 @@
Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
const core = require('@sentry/core');
const react = require('@sentry/react');
const RouterImport = require('next/router');
const debugBuild = require('../../common/debug-build.js');
// next/router v10 is CJS
//
// For ESM/CJS interoperability 'reasons', depending on how this file is loaded, Router might be on the default export
const Router = RouterImport.default.events
? RouterImport.default
: (RouterImport.default ).default;
const globalObject = react.WINDOW
;
/**
* Describes data located in the __NEXT_DATA__ script tag. This tag is present on every page of a Next.js app.
*/
/**
* Every Next.js page (static and dynamic ones) comes with a script tag with the id "__NEXT_DATA__". This script tag
* contains a JSON object with data that was either generated at build time for static pages (`getStaticProps`), or at
* runtime with data fetchers like `getServerSideProps.`.
*
* We can use this information to:
* - Always get the parameterized route we're in when loading a page.
* - Send trace information (trace-id, baggage) from the server to the client.
*
* This function extracts this information.
*/
function extractNextDataTagInformation() {
let nextData;
// Let's be on the safe side and actually check first if there is really a __NEXT_DATA__ script tag on the page.
// Theoretically this should always be the case though.
const nextDataTag = globalObject.document.getElementById('__NEXT_DATA__');
if (nextDataTag?.innerHTML) {
try {
nextData = JSON.parse(nextDataTag.innerHTML);
} catch {
debugBuild.DEBUG_BUILD && core.debug.warn('Could not extract __NEXT_DATA__');
}
}
if (!nextData) {
return {};
}
const nextDataTagInfo = {};
const { page, query, props } = nextData;
// `nextData.page` always contains the parameterized route - except for when an error occurs in a data fetching
// function, then it is "/_error", but that isn't a problem since users know which route threw by looking at the
// parent transaction
// TODO: Actually this is a problem (even though it is not that big), because the DSC and the transaction payload will contain
// a different transaction name. Maybe we can fix this. Idea: Also send transaction name via pageProps when available.
nextDataTagInfo.route = page;
nextDataTagInfo.params = query;
if (props?.pageProps) {
nextDataTagInfo.sentryTrace = props.pageProps._sentryTraceData;
nextDataTagInfo.baggage = props.pageProps._sentryBaggage;
}
return nextDataTagInfo;
}
/**
* Instruments the Next.js pages router for pageloads.
* Only supported for client side routing. Works for Next >= 10.
*
* Leverages the SingletonRouter from the `next/router` to
* generate pageload/navigation transactions and parameterize
* transaction names.
*/
function pagesRouterInstrumentPageLoad(client) {
const { route, params, sentryTrace, baggage } = extractNextDataTagInformation();
const parsedBaggage = core.parseBaggageHeader(baggage);
let name = route || globalObject.location.pathname;
// /_error is the fallback page for all errors. If there is a transaction name for /_error, use that instead
if (parsedBaggage?.['sentry-transaction'] && name === '/_error') {
name = parsedBaggage['sentry-transaction'];
// Strip any HTTP method from the span name
name = name.replace(/^(GET|POST|PUT|DELETE|PATCH|HEAD|OPTIONS|TRACE|CONNECT)\s+/i, '');
}
const origin = core.browserPerformanceTimeOrigin();
react.startBrowserTracingPageLoadSpan(
client,
{
name,
// pageload should always start at timeOrigin (and needs to be in s, not ms)
startTime: origin ? origin / 1000 : undefined,
attributes: {
[core.SEMANTIC_ATTRIBUTE_SENTRY_OP]: 'pageload',
[core.SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.pageload.nextjs.pages_router_instrumentation',
[core.SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]: route ? 'route' : 'url',
...(params && client.getOptions().sendDefaultPii && { ...params }),
},
},
{ sentryTrace, baggage },
);
}
/**
* Instruments the Next.js pages router for navigation.
* Only supported for client side routing. Works for Next >= 10.
*
* Leverages the SingletonRouter from the `next/router` to
* generate pageload/navigation transactions and parameterize
* transaction names.
*/
function pagesRouterInstrumentNavigation(client) {
Router.events.on('routeChangeStart', (navigationTarget) => {
const strippedNavigationTarget = core.stripUrlQueryAndFragment(navigationTarget);
const matchedRoute = getNextRouteFromPathname(strippedNavigationTarget);
let newLocation;
let spanSource;
if (matchedRoute) {
newLocation = matchedRoute;
spanSource = 'route';
} else {
newLocation = strippedNavigationTarget;
spanSource = 'url';
}
react.startBrowserTracingNavigationSpan(client, {
name: newLocation,
attributes: {
[core.SEMANTIC_ATTRIBUTE_SENTRY_OP]: 'navigation',
[core.SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.navigation.nextjs.pages_router_instrumentation',
[core.SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]: spanSource,
},
});
});
}
function getNextRouteFromPathname(pathname) {
const pageRoutes = globalObject.__BUILD_MANIFEST?.sortedPages;
// Page route should in 99.999% of the cases be defined by now but just to be sure we make a check here
if (!pageRoutes) {
return;
}
return pageRoutes.find(route => {
const routeRegExp = convertNextRouteToRegExp(route);
return pathname.match(routeRegExp);
});
}
/**
* Converts a Next.js style route to a regular expression that matches on pathnames (no query params or URL fragments).
*
* In general this involves replacing any instances of square brackets in a route with a wildcard:
* e.g. "/users/[id]/info" becomes /\/users\/([^/]+?)\/info/
*
* Some additional edgecases need to be considered:
* - All routes have an optional slash at the end, meaning users can navigate to "/users/[id]/info" or
* "/users/[id]/info/" - both will be resolved to "/users/[id]/info".
* - Non-optional "catchall"s at the end of a route must be considered when matching (e.g. "/users/[...params]").
* - Optional "catchall"s at the end of a route must be considered when matching (e.g. "/users/[[...params]]").
*
* @param route A Next.js style route as it is found in `global.__BUILD_MANIFEST.sortedPages`
*/
function convertNextRouteToRegExp(route) {
// We can assume a route is at least "/".
const routeParts = route.split('/');
let optionalCatchallWildcardRegex = '';
if (routeParts[routeParts.length - 1]?.match(/^\[\[\.\.\..+\]\]$/)) {
// If last route part has pattern "[[...xyz]]" we pop the latest route part to get rid of the required trailing
// slash that would come before it if we didn't pop it.
routeParts.pop();
optionalCatchallWildcardRegex = '(?:/(.+?))?';
}
const rejoinedRouteParts = routeParts
.map(
routePart =>
routePart
.replace(/^\[\.\.\..+\]$/, '(.+?)') // Replace catch all wildcard with regex wildcard
.replace(/^\[.*\]$/, '([^/]+?)'), // Replace route wildcards with lazy regex wildcards
)
.join('/');
// oxlint-disable-next-line sdk/no-regexp-constructor -- routeParts are from the build manifest, so no raw user input
return new RegExp(
`^${rejoinedRouteParts}${optionalCatchallWildcardRegex}(?:/)?$`, // optional slash at the end
);
}
exports.pagesRouterInstrumentNavigation = pagesRouterInstrumentNavigation;
exports.pagesRouterInstrumentPageLoad = pagesRouterInstrumentPageLoad;
//# sourceMappingURL=pagesRouterRoutingInstrumentation.js.map

View File

@@ -1,211 +0,0 @@
Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
const core = require('@sentry/core');
const debugBuild = require('../../common/debug-build.js');
const globalWithInjectedManifest = core.GLOBAL_OBJ
;
// Some performance caches
let cachedManifest = null;
let cachedManifestString = undefined;
const compiledRegexCache = new Map();
const routeResultCache = new Map();
/**
* Calculate the specificity score for a route path.
* Lower scores indicate more specific routes.
*/
function getRouteSpecificity(routePath) {
const segments = routePath.split('/').filter(Boolean);
let score = 0;
for (const segment of segments) {
if (segment.startsWith(':')) {
const paramName = segment.substring(1);
if (paramName.endsWith('*?')) {
// Optional catch-all: [[...param]]
score += 1000;
} else if (paramName.endsWith('*')) {
// Required catch-all: [...param]
score += 100;
} else {
// Regular dynamic segment: [param]
score += 10;
}
}
// Static segments add 0 to score as they are most specific
}
if (segments.length > 0) {
// Add a small penalty based on inverse of segment count
// This ensures that routes with more segments are preferred
// e.g., '/:locale/foo' is more specific than '/:locale'
// We use a small value (1 / segments.length) so it doesn't override the main scoring
// but breaks ties between routes with the same number of dynamic segments
const segmentCountPenalty = 1 / segments.length;
score += segmentCountPenalty;
}
return score;
}
/**
* Get compiled regex from cache or create and cache it.
*/
function getCompiledRegex(regexString) {
if (compiledRegexCache.has(regexString)) {
return compiledRegexCache.get(regexString) ?? null;
}
try {
// oxlint-disable-next-line sdk/no-regexp-constructor -- regex patterns are from build-time route manifest, not user input
const regex = new RegExp(regexString);
compiledRegexCache.set(regexString, regex);
return regex;
} catch (error) {
debugBuild.DEBUG_BUILD && core.debug.warn('Could not compile regex', { regexString, error });
// Cache the failure to avoid repeated attempts by storing undefined
return null;
}
}
/**
* Get and cache the route manifest from the global object.
* @returns The parsed route manifest or null if not available/invalid.
*/
function getManifest() {
if (
!globalWithInjectedManifest?._sentryRouteManifest ||
typeof globalWithInjectedManifest._sentryRouteManifest !== 'string'
) {
return null;
}
const currentManifestString = globalWithInjectedManifest._sentryRouteManifest;
// Return cached manifest if the string hasn't changed
if (cachedManifest && cachedManifestString === currentManifestString) {
return cachedManifest;
}
// Clear caches when manifest changes
compiledRegexCache.clear();
routeResultCache.clear();
let manifest = {
staticRoutes: [],
dynamicRoutes: [],
isrRoutes: [],
};
// Shallow check if the manifest is actually what we expect it to be
try {
manifest = JSON.parse(currentManifestString);
if (!Array.isArray(manifest.staticRoutes) || !Array.isArray(manifest.dynamicRoutes)) {
return null;
}
// Cache the successfully parsed manifest
cachedManifest = manifest;
cachedManifestString = currentManifestString;
return manifest;
} catch {
// Something went wrong while parsing the manifest, so we'll fallback to no parameterization
debugBuild.DEBUG_BUILD && core.debug.warn('Could not extract route manifest');
return null;
}
}
/**
* Find matching routes from static and dynamic route collections.
* @param route - The route to match against.
* @param staticRoutes - Array of static route objects.
* @param dynamicRoutes - Array of dynamic route objects.
* @returns Array of matching route paths.
*/
function findMatchingRoutes(
route,
staticRoutes,
dynamicRoutes,
) {
const matches = [];
// Static path: no parameterization needed, return empty array
if (staticRoutes.some(r => r.path === route)) {
return matches;
}
// Dynamic path: find the route pattern that matches the concrete route
for (const dynamicRoute of dynamicRoutes) {
if (dynamicRoute.regex) {
const regex = getCompiledRegex(dynamicRoute.regex);
if (regex?.test(route)) {
matches.push(dynamicRoute.path);
}
}
}
// Try matching with optional prefix segments (for i18n routing patterns)
// This handles cases like '/foo' matching '/:locale/foo' when using next-intl with localePrefix: "as-needed"
// We do this regardless of whether we found direct matches, as we want the most specific match
if (!route.startsWith('/:')) {
for (const dynamicRoute of dynamicRoutes) {
if (dynamicRoute.hasOptionalPrefix && dynamicRoute.regex) {
// Prepend a placeholder segment to simulate the optional prefix
// e.g., '/foo' becomes '/PLACEHOLDER/foo' to match '/:locale/foo'
// Special case: '/' becomes '/PLACEHOLDER' (not '/PLACEHOLDER/') to match '/:locale' pattern
const routeWithPrefix = route === '/' ? '/SENTRY_OPTIONAL_PREFIX' : `/SENTRY_OPTIONAL_PREFIX${route}`;
const regex = getCompiledRegex(dynamicRoute.regex);
if (regex?.test(routeWithPrefix)) {
matches.push(dynamicRoute.path);
}
}
}
}
return matches;
}
/**
* Parameterize a route using the route manifest.
*
* @param route - The route to parameterize.
* @returns The parameterized route or undefined if no parameterization is needed.
*/
const maybeParameterizeRoute = (route) => {
const manifest = getManifest();
if (!manifest) {
return undefined;
}
// Normalize trailing slashes to handle `trailingSlash: true` in Next.js config.
// When trailingSlash is enabled, all URLs get a trailing slash appended (e.g. '/about' becomes '/about/'),
// but route manifests store paths without trailing slashes. Without normalization, static routes fail
// exact-match checks and dynamic route regexes don't match, causing all routes to fall through to
// catch-all patterns. See: https://github.com/getsentry/sentry-javascript/issues/19241
const normalizedRoute = route.length > 1 && route.endsWith('/') ? route.slice(0, -1) : route;
// Check route result cache after manifest validation
if (routeResultCache.has(normalizedRoute)) {
return routeResultCache.get(normalizedRoute);
}
const { staticRoutes, dynamicRoutes } = manifest;
if (!Array.isArray(staticRoutes) || !Array.isArray(dynamicRoutes)) {
return undefined;
}
const matches = findMatchingRoutes(normalizedRoute, staticRoutes, dynamicRoutes);
// We can always do the `sort()` call, it will short-circuit when it has one array item
const result = matches.sort((a, b) => getRouteSpecificity(a) - getRouteSpecificity(b))[0];
routeResultCache.set(normalizedRoute, result);
return result;
};
exports.getManifest = getManifest;
exports.maybeParameterizeRoute = maybeParameterizeRoute;
//# sourceMappingURL=parameterization.js.map

View File

@@ -1,37 +0,0 @@
Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
const core = require('@sentry/core');
const debugBuild = require('../common/debug-build.js');
const globalWithInjectedValues = core.GLOBAL_OBJ
;
/**
* Applies the `tunnel` option to the Next.js SDK options based on `withSentryConfig`'s `tunnelRoute` option.
*/
function applyTunnelRouteOption(options) {
const tunnelRouteOption = process.env._sentryRewritesTunnelPath || globalWithInjectedValues._sentryRewritesTunnelPath;
if (tunnelRouteOption && options.dsn) {
const dsnComponents = core.dsnFromString(options.dsn);
if (!dsnComponents) {
return;
}
const sentrySaasDsnMatch = dsnComponents.host.match(/^o(\d+)\.ingest(?:\.([a-z]{2}))?\.sentry\.io$/);
if (sentrySaasDsnMatch) {
const orgId = sentrySaasDsnMatch[1];
const regionCode = sentrySaasDsnMatch[2];
let tunnelPath = `${tunnelRouteOption}?o=${orgId}&p=${dsnComponents.projectId}`;
if (regionCode) {
tunnelPath += `&r=${regionCode}`;
}
options.tunnel = tunnelPath;
debugBuild.DEBUG_BUILD && core.debug.log(`Tunneling events to "${tunnelPath}"`);
} else {
debugBuild.DEBUG_BUILD && core.debug.warn('Provided DSN is not a Sentry SaaS DSN. Will not tunnel events.');
}
}
}
exports.applyTunnelRouteOption = applyTunnelRouteOption;
//# sourceMappingURL=tunnelRoute.js.map

View File

@@ -1,39 +0,0 @@
Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
const core = require('@sentry/core');
const responseEnd = require('./utils/responseEnd.js');
/**
* Reports errors passed to the the Next.js `onRequestError` instrumentation hook.
*/
function captureRequestError(error, request, errorContext) {
core.withScope(scope => {
scope.setSDKProcessingMetadata({
normalizedRequest: {
headers: core.headersToDict(request.headers),
method: request.method,
} ,
});
scope.setContext('nextjs', {
request_path: request.path,
router_kind: errorContext.routerKind,
router_path: errorContext.routePath,
route_type: errorContext.routeType,
});
scope.setTransactionName(`${request.method} ${errorContext.routePath}`);
core.captureException(error, {
mechanism: {
handled: false,
type: 'auto.function.nextjs.on_request_error',
},
});
responseEnd.waitUntil(responseEnd.flushSafelyWithTimeout());
});
}
exports.captureRequestError = captureRequestError;
//# sourceMappingURL=captureRequestError.js.map

View File

@@ -1,11 +0,0 @@
Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
/**
* This serves as a build time flag that will be true by default, but false in non-debug builds or if users replace `__SENTRY_DEBUG__` in their generated code.
*
* ATTENTION: This constant must never cross package boundaries (i.e. be exported) to guarantee that it can be used for tree shaking.
*/
const DEBUG_BUILD = (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__);
exports.DEBUG_BUILD = DEBUG_BUILD;
//# sourceMappingURL=debug-build.js.map

View File

@@ -1,299 +0,0 @@
Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
const core = require('@sentry/core');
const stackTraceParser = require('stacktrace-parser');
const debugBuild = require('./debug-build.js');
const globalWithInjectedValues = core.GLOBAL_OBJ
;
/**
* Constructs the base URL for the Next.js dev server, including the port and base path.
* Returns only the base path when running in the browser (client-side) for relative URLs.
*/
function getDevServerBaseUrl() {
let basePath = process.env._sentryBasePath ?? globalWithInjectedValues._sentryBasePath ?? '';
// Prefix the basepath with a slash if it doesn't have one
if (basePath !== '' && !basePath.match(/^\//)) {
basePath = `/${basePath}`;
}
// eslint-disable-next-line no-restricted-globals
if (typeof window !== 'undefined') {
return basePath;
}
const devServerPort = process.env.PORT || '3000';
return `http://localhost:${devServerPort}${basePath}`;
}
/**
* Fetches a URL with a 3-second timeout using AbortController.
*/
async function fetchWithTimeout(url, options = {}) {
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), 3000);
return core.suppressTracing(() =>
fetch(url, {
...options,
signal: controller.signal,
}).finally(() => {
clearTimeout(timer);
}),
);
}
/**
* Event processor that will symbolicate errors by using the webpack/nextjs dev server that is used to show stack traces
* in the dev overlay.
*/
async function devErrorSymbolicationEventProcessor(event, hint) {
// Filter out spans for requests resolving source maps for stack frames in dev mode
if (event.type === 'transaction') {
event.spans = event.spans?.filter(span => {
const httpUrlAttribute = span.data?.['http.url'];
if (typeof httpUrlAttribute === 'string') {
return !httpUrlAttribute.includes('__nextjs_original-stack-frame'); // could also be __nextjs_original-stack-frames (plural)
}
return true;
});
}
// Due to changes across Next.js versions, there are a million things that can go wrong here so we just try-catch the
// entire event processor. Symbolicated stack traces are just a nice to have.
try {
// oxlint-disable-next-line typescript/prefer-optional-chain
if (hint.originalException && hint.originalException instanceof Error && hint.originalException.stack) {
const frames = stackTraceParser.parse(hint.originalException.stack);
const nextJsVersion = globalWithInjectedValues._sentryNextJsVersion;
// If we for whatever reason don't have a Next.js version,
// we don't want to symbolicate as this previously lead to infinite loops
if (!nextJsVersion) {
return event;
}
const parsedNextjsVersion = core.parseSemver(nextJsVersion);
let resolvedFrames
;
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
if (parsedNextjsVersion.major > 15 || (parsedNextjsVersion.major === 15 && parsedNextjsVersion.minor >= 2)) {
const r = await resolveStackFrames(frames);
if (r === null) {
return event;
}
resolvedFrames = r;
} else {
resolvedFrames = await Promise.all(
frames.map(frame => resolveStackFrame(frame, hint.originalException )),
);
}
if (event.exception?.values?.[0]?.stacktrace?.frames) {
event.exception.values[0].stacktrace.frames = event.exception.values[0].stacktrace.frames.map(
(frame, i, frames) => {
const resolvedFrame = resolvedFrames[frames.length - 1 - i];
if (!resolvedFrame?.originalStackFrame || !resolvedFrame.originalCodeFrame) {
return {
...frame,
platform: frame.filename?.startsWith('node:internal') ? 'nodejs' : undefined, // simple hack that will prevent a source mapping error from showing up
in_app: false,
};
}
const { contextLine, preContextLines, postContextLines } = parseOriginalCodeFrame(
resolvedFrame.originalCodeFrame,
);
return {
...frame,
pre_context: preContextLines,
context_line: contextLine,
post_context: postContextLines,
function: resolvedFrame.originalStackFrame.methodName,
filename: resolvedFrame.originalStackFrame.file
? stripWebpackInternalPrefix(resolvedFrame.originalStackFrame.file)
: undefined,
lineno:
resolvedFrame.originalStackFrame.lineNumber || resolvedFrame.originalStackFrame.line1 || undefined,
colno: resolvedFrame.originalStackFrame.column || resolvedFrame.originalStackFrame.column1 || undefined,
};
},
);
}
}
} catch {
return event;
}
return event;
}
async function resolveStackFrame(
frame,
error,
) {
try {
if (!(frame.file?.startsWith('webpack-internal:') || frame.file?.startsWith('file:'))) {
return null;
}
const params = new URLSearchParams();
params.append('isServer', String(false)); // doesn't matter since it is overwritten by isAppDirectory
params.append('isEdgeServer', String(false)); // doesn't matter since it is overwritten by isAppDirectory
params.append('isAppDirectory', String(true)); // will force server to do more thorough checking
params.append('errorMessage', error.toString());
Object.keys(frame).forEach(key => {
params.append(key, (frame[key ] ?? '').toString());
});
const baseUrl = getDevServerBaseUrl();
const res = await fetchWithTimeout(`${baseUrl}/__nextjs_original-stack-frame?${params.toString()}`);
if (!res.ok || res.status === 204) {
return null;
}
const body = await res.json();
return {
originalCodeFrame: body.originalCodeFrame,
originalStackFrame: body.originalStackFrame,
};
} catch (e) {
debugBuild.DEBUG_BUILD && core.debug.error('Failed to symbolicate event with Next.js dev server', e);
return null;
}
}
async function resolveStackFrames(
frames,
) {
try {
const postBody = {
frames: frames
.filter(frame => {
return !!frame.file;
})
.map(frame => {
// https://github.com/vercel/next.js/blob/df0573a478baa8b55478a7963c473dddd59a5e40/packages/next/src/client/components/react-dev-overlay/server/middleware-turbopack.ts#L129
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
frame.file = frame.file.replace(/^rsc:\/\/React\/[^/]+\//, '').replace(/\?\d+$/, '');
return {
file: frame.file,
methodName: frame.methodName ?? '<unknown>',
arguments: [],
lineNumber: frame.lineNumber ?? 0,
column: frame.column ?? 0,
line1: frame.lineNumber ?? 0,
column1: frame.column ?? 0,
};
}),
isServer: false,
isEdgeServer: false,
isAppDirectory: true,
};
const baseUrl = getDevServerBaseUrl();
const res = await fetchWithTimeout(`${baseUrl}/__nextjs_original-stack-frames`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(postBody),
});
if (!res.ok || res.status === 204) {
return null;
}
const body = await res.json();
return body.map(frame => {
return {
originalCodeFrame: frame.value.originalCodeFrame,
originalStackFrame: frame.value.originalStackFrame,
};
});
} catch (e) {
debugBuild.DEBUG_BUILD && core.debug.error('Failed to symbolicate event with Next.js dev server', e);
return null;
}
}
function parseOriginalCodeFrame(codeFrame)
{
const preProcessedLines = codeFrame
// Remove ASCII control characters that are used for syntax highlighting
.replace(
// eslint-disable-next-line no-control-regex
/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/g, // https://stackoverflow.com/a/29497680
'',
)
.split('\n')
// Remove line that is supposed to indicate where the error happened
.filter(line => !line.match(/^\s*\|/))
// Find the error line
.map(line => ({
line,
isErrorLine: !!line.match(/^>/),
}))
// Remove the leading part that is just for prettier output
.map(lineObj => ({
...lineObj,
line: lineObj.line.replace(/^.*\|/, ''),
}));
const preContextLines = [];
let contextLine = undefined;
const postContextLines = [];
let reachedContextLine = false;
for (const preProcessedLine of preProcessedLines) {
if (preProcessedLine.isErrorLine) {
contextLine = preProcessedLine.line;
reachedContextLine = true;
} else if (reachedContextLine) {
postContextLines.push(preProcessedLine.line);
} else {
preContextLines.push(preProcessedLine.line);
}
}
return {
contextLine,
preContextLines,
postContextLines,
};
}
/**
* Strips webpack-internal prefixes from filenames to clean up stack traces.
*
* Examples:
* - "webpack-internal:///./components/file.tsx" -> "./components/file.tsx"
* - "webpack-internal:///(app-pages-browser)/./components/file.tsx" -> "./components/file.tsx"
*/
function stripWebpackInternalPrefix(filename) {
if (!filename) {
return filename;
}
const webpackInternalRegex = /^webpack-internal:(?:\/+)?(?:\([^)]*\)\/)?(.+)$/;
const match = filename.match(webpackInternalRegex);
return match ? match[1] : filename;
}
exports.devErrorSymbolicationEventProcessor = devErrorSymbolicationEventProcessor;
//# sourceMappingURL=devErrorSymbolicationEventProcessor.js.map

View File

@@ -1,14 +0,0 @@
Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
/**
* Returns an environment setting value determined by Vercel's `VERCEL_ENV` environment variable.
*
* @param isClient Flag to indicate whether to use the `NEXT_PUBLIC_` prefixed version of the environment variable.
*/
function getVercelEnv(isClient) {
const vercelEnvVar = isClient ? process.env.NEXT_PUBLIC_VERCEL_ENV : process.env.VERCEL_ENV;
return vercelEnvVar ? `vercel-${vercelEnvVar}` : undefined;
}
exports.getVercelEnv = getVercelEnv;
//# sourceMappingURL=getVercelEnv.js.map

View File

@@ -1,32 +0,0 @@
Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
const core = require('@sentry/core');
/**
* Determines whether input is a Next.js not-found error.
* https://beta.nextjs.org/docs/api-reference/notfound#notfound
*/
function isNotFoundNavigationError(subject) {
return (
core.isError(subject) &&
['NEXT_NOT_FOUND', 'NEXT_HTTP_ERROR_FALLBACK;404'].includes(
(subject ).digest ,
)
);
}
/**
* Determines whether input is a Next.js redirect error.
* https://beta.nextjs.org/docs/api-reference/redirect#redirect
*/
function isRedirectNavigationError(subject) {
return (
core.isError(subject) &&
typeof (subject ).digest === 'string' &&
(subject ).digest.startsWith('NEXT_REDIRECT;') // a redirect digest looks like "NEXT_REDIRECT;[redirect path]"
);
}
exports.isNotFoundNavigationError = isNotFoundNavigationError;
exports.isRedirectNavigationError = isRedirectNavigationError;
//# sourceMappingURL=nextNavigationErrorUtils.js.map

View File

@@ -1,12 +0,0 @@
Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
const ATTR_NEXT_SPAN_TYPE = 'next.span_type';
const ATTR_NEXT_SPAN_NAME = 'next.span_name';
const ATTR_NEXT_ROUTE = 'next.route';
const ATTR_NEXT_SEGMENT = 'next.segment';
exports.ATTR_NEXT_ROUTE = ATTR_NEXT_ROUTE;
exports.ATTR_NEXT_SEGMENT = ATTR_NEXT_SEGMENT;
exports.ATTR_NEXT_SPAN_NAME = ATTR_NEXT_SPAN_NAME;
exports.ATTR_NEXT_SPAN_TYPE = ATTR_NEXT_SPAN_TYPE;
//# sourceMappingURL=nextSpanAttributes.js.map

View File

@@ -1,75 +0,0 @@
Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
const core = require('@sentry/core');
const responseEnd = require('../utils/responseEnd.js');
/**
* Capture the exception passed by nextjs to the `_error` page, adding context data as appropriate.
*
* This will not capture the exception if the status code is < 500 or if the pathname is not provided and will thus not return an event ID.
*
* @param contextOrProps The data passed to either `getInitialProps` or `render` by nextjs
* @returns The Sentry event ID, or `undefined` if no event was captured
*/
async function captureUnderscoreErrorException(contextOrProps) {
const { req, res, err } = contextOrProps;
// 404s (and other 400-y friends) can trigger `_error`, but we don't want to send them to Sentry
const statusCode = res?.statusCode || contextOrProps.statusCode;
if (statusCode && statusCode < 500) {
return;
}
// In previous versions of the suggested `_error.js` page in which this function is meant to be used, there was a
// workaround for https://github.com/vercel/next.js/issues/8592 which involved an extra call to this function, in the
// custom error component's `render` method, just in case it hadn't been called by `getInitialProps`. Now that that
// issue has been fixed, the second call is unnecessary, but since it lives in user code rather than our code, users
// have to be the ones to get rid of it, and guaraneteedly, not all of them will. So, rather than capture the error
// twice, we just bail if we sense we're in that now-extraneous second call. (We can tell which function we're in
// because Nextjs passes `pathname` to `getInitialProps` but not to `render`.)
if (!contextOrProps.pathname) {
return;
}
// If the error was already captured (e.g., by wrapped functions in data fetchers),
// return the existing event ID instead of capturing it again (needed for lastEventId() to work)
if (err && core.isAlreadyCaptured(err)) {
responseEnd.waitUntil(responseEnd.flushSafelyWithTimeout());
const storedEventId =
typeof err === 'object' ? (err ).__sentry_event_id__ : undefined;
if (typeof storedEventId === 'string') {
core.getIsolationScope().setLastEventId(storedEventId);
return storedEventId;
}
return core.getIsolationScope().lastEventId();
}
const eventId = core.withScope(scope => {
if (req) {
const normalizedRequest = core.httpRequestToRequestData(req);
scope.setSDKProcessingMetadata({ normalizedRequest });
}
// If third-party libraries (or users themselves) throw something falsy, we want to capture it as a message (which
// is what passing a string to `captureException` will wind up doing)
return core.captureException(err || `_error.js called with falsy error (${err})`, {
mechanism: {
type: 'auto.function.nextjs.underscore_error',
handled: false,
data: {
function: '_error.getInitialProps',
},
},
});
});
responseEnd.waitUntil(responseEnd.flushSafelyWithTimeout());
return eventId;
}
exports.captureUnderscoreErrorException = captureUnderscoreErrorException;
//# sourceMappingURL=_error.js.map

View File

@@ -1,127 +0,0 @@
Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
const core = require('@sentry/core');
const responseEnd = require('../utils/responseEnd.js');
const tracingUtils = require('../utils/tracingUtils.js');
/**
* Wrap the given API route handler with error nad performance monitoring.
*
* @param apiHandler The handler exported from the user's API page route file, which may or may not already be
* wrapped with `withSentry`
* @param parameterizedRoute The page's parameterized route.
* @returns The wrapped handler which will always return a Promise.
*/
function wrapApiHandlerWithSentry(apiHandler, parameterizedRoute) {
return new Proxy(apiHandler, {
apply: (
wrappingTarget,
thisArg,
args,
) => {
tracingUtils.dropNextjsRootContext();
return tracingUtils.escapeNextjsTracing(() => {
const [req, res] = args;
if (!req) {
core.debug.log(
`Wrapped API handler on route "${parameterizedRoute}" was not passed a request object. Will not instrument.`,
);
return wrappingTarget.apply(thisArg, args);
} else if (!res) {
core.debug.log(
`Wrapped API handler on route "${parameterizedRoute}" was not passed a response object. Will not instrument.`,
);
return wrappingTarget.apply(thisArg, args);
}
// Prevent double wrapping of the same request.
if (req.__withSentry_applied__) {
return wrappingTarget.apply(thisArg, args);
}
req.__withSentry_applied__ = true;
return core.withIsolationScope(isolationScope => {
// Normally, there is an active span here (from Next.js OTEL) and we just use that as parent
// Else, we manually continueTrace from the incoming headers
const continueTraceIfNoActiveSpan = core.getActiveSpan()
? (_opts, callback) => callback()
: core.continueTrace;
return continueTraceIfNoActiveSpan(
{
sentryTrace:
req.headers && core.isString(req.headers['sentry-trace']) ? req.headers['sentry-trace'] : undefined,
baggage: req.headers?.baggage,
},
() => {
const reqMethod = `${(req.method || 'GET').toUpperCase()} `;
const normalizedRequest = core.httpRequestToRequestData(req);
isolationScope.setSDKProcessingMetadata({ normalizedRequest });
isolationScope.setTransactionName(`${reqMethod}${parameterizedRoute}`);
return core.startSpanManual(
{
name: `${reqMethod}${parameterizedRoute}`,
op: 'http.server',
forceTransaction: true,
attributes: {
[core.SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]: 'route',
[core.SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.http.nextjs',
},
},
async span => {
// eslint-disable-next-line @typescript-eslint/unbound-method
res.end = new Proxy(res.end, {
apply(target, thisArg, argArray) {
core.setHttpStatus(span, res.statusCode);
span.end();
responseEnd.waitUntil(responseEnd.flushSafelyWithTimeout());
return target.apply(thisArg, argArray);
},
});
try {
return await wrappingTarget.apply(thisArg, args);
} catch (e) {
// In case we have a primitive, wrap it in the equivalent wrapper class (string -> String, etc.) so that we can
// store a seen flag on it. (Because of the one-way-on-Vercel-one-way-off-of-Vercel approach we've been forced
// to take, it can happen that the same thrown object gets caught in two different ways, and flagging it is a
// way to prevent it from actually being reported twice.)
const objectifiedErr = core.objectify(e);
core.captureException(objectifiedErr, {
mechanism: {
type: 'auto.http.nextjs.api_handler',
handled: false,
data: {
wrapped_handler: wrappingTarget.name,
function: 'withSentry',
},
},
});
core.setHttpStatus(span, 500);
span.end();
// we need to await the flush here to ensure that the error is captured
// as the runtime freezes as soon as the error is thrown below
await responseEnd.flushSafelyWithTimeout();
// We rethrow here so that nextjs can do with the error whatever it would normally do. (Sometimes "whatever it
// would normally do" is to allow the error to bubble up to the global handlers - another reason we need to mark
// the error as already having been captured.)
throw objectifiedErr;
}
},
);
},
);
});
});
},
});
}
exports.wrapApiHandlerWithSentry = wrapApiHandlerWithSentry;
//# sourceMappingURL=wrapApiHandlerWithSentry.js.map

View File

@@ -1,105 +0,0 @@
Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
const core = require('@sentry/core');
/**
* Wraps a function with Sentry crons instrumentation by automatically sending check-ins for the given Vercel crons config.
*/
// eslint-disable-next-line @typescript-eslint/no-explicit-any
function wrapApiHandlerWithSentryVercelCrons(
handler,
vercelCronsConfig,
) {
return new Proxy(handler, {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
apply: (originalFunction, thisArg, args) => {
if (!args?.[0]) {
return originalFunction.apply(thisArg, args);
}
const [req] = args ;
let maybePromiseResult;
const cronsKey = 'nextUrl' in req ? req.nextUrl.pathname : req.url;
const userAgentHeader = 'nextUrl' in req ? req.headers.get('user-agent') : req.headers['user-agent'];
if (
!vercelCronsConfig || // do nothing if vercel crons config is missing
!userAgentHeader?.includes('vercel-cron') // do nothing if endpoint is not called from vercel crons
) {
return originalFunction.apply(thisArg, args);
}
const vercelCron = vercelCronsConfig.find(vercelCron => vercelCron.path === cronsKey);
if (!vercelCron?.path || !vercelCron.schedule) {
return originalFunction.apply(thisArg, args);
}
const monitorSlug = vercelCron.path;
const checkInId = core.captureCheckIn(
{
monitorSlug,
status: 'in_progress',
},
{
maxRuntime: 60 * 12, // (minutes) so 12 hours - just a very high arbitrary number since we don't know the actual duration of the users cron job
schedule: {
type: 'crontab',
value: vercelCron.schedule,
},
},
);
const startTime = core._INTERNAL_safeDateNow() / 1000;
const handleErrorCase = () => {
core.captureCheckIn({
checkInId,
monitorSlug,
status: 'error',
duration: core._INTERNAL_safeDateNow() / 1000 - startTime,
});
};
try {
maybePromiseResult = originalFunction.apply(thisArg, args);
} catch (e) {
handleErrorCase();
throw e;
}
if (typeof maybePromiseResult === 'object' && maybePromiseResult !== null && 'then' in maybePromiseResult) {
Promise.resolve(maybePromiseResult).then(
() => {
core.captureCheckIn({
checkInId,
monitorSlug,
status: 'ok',
duration: core._INTERNAL_safeDateNow() / 1000 - startTime,
});
},
() => {
handleErrorCase();
},
);
// It is very important that we return the original promise here, because Next.js attaches various properties
// to that promise and will throw if they are not on the returned value.
return maybePromiseResult;
} else {
core.captureCheckIn({
checkInId,
monitorSlug,
status: 'ok',
duration: core._INTERNAL_safeDateNow() / 1000 - startTime,
});
return maybePromiseResult;
}
},
});
}
exports.wrapApiHandlerWithSentryVercelCrons = wrapApiHandlerWithSentryVercelCrons;
//# sourceMappingURL=wrapApiHandlerWithSentryVercelCrons.js.map

View File

@@ -1,74 +0,0 @@
Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
const isBuild = require('../utils/isBuild.js');
const wrapperUtils = require('../utils/wrapperUtils.js');
/**
* Create a wrapped version of the user's exported `getInitialProps` function in
* a custom app ("_app.js").
*
* @param origAppGetInitialProps The user's `getInitialProps` function
* @param parameterizedRoute The page's parameterized route
* @returns A wrapped version of the function
*/
function wrapAppGetInitialPropsWithSentry(origAppGetInitialProps) {
return new Proxy(origAppGetInitialProps, {
apply: async (wrappingTarget, thisArg, args) => {
if (isBuild.isBuild()) {
return wrappingTarget.apply(thisArg, args);
}
const [context] = args;
const { req, res } = context.ctx;
const errorWrappedAppGetInitialProps = wrapperUtils.withErrorInstrumentation(wrappingTarget);
// Generally we can assume that `req` and `res` are always defined on the server:
// https://nextjs.org/docs/api-reference/data-fetching/get-initial-props#context-object
// This does not seem to be the case in dev mode. Because we have no clean way of associating the the data fetcher
// span with each other when there are no req or res objects, we simply do not trace them at all here.
if (req && res) {
const tracedGetInitialProps = wrapperUtils.withTracedServerSideDataFetcher(errorWrappedAppGetInitialProps, req, res, {
dataFetcherRouteName: '/_app',
requestedRouteName: context.ctx.pathname,
dataFetchingMethodName: 'getInitialProps',
});
const {
data: appGetInitialProps,
sentryTrace,
baggage,
}
= await tracedGetInitialProps.apply(thisArg, args);
if (typeof appGetInitialProps === 'object' && appGetInitialProps !== null) {
// Per definition, `pageProps` is not optional, however an increased amount of users doesn't seem to call
// `App.getInitialProps(appContext)` in their custom `_app` pages which is required as per
// https://nextjs.org/docs/advanced-features/custom-app - resulting in missing `pageProps`.
// For this reason, we just handle the case where `pageProps` doesn't exist explicitly.
if (!(appGetInitialProps ).pageProps) {
(appGetInitialProps ).pageProps = {};
}
// The Next.js serializer throws on undefined values so we need to guard for it (#12102)
if (sentryTrace) {
(appGetInitialProps ).pageProps._sentryTraceData = sentryTrace;
}
// The Next.js serializer throws on undefined values so we need to guard for it (#12102)
if (baggage) {
(appGetInitialProps ).pageProps._sentryBaggage = baggage;
}
}
return appGetInitialProps;
} else {
return errorWrappedAppGetInitialProps.apply(thisArg, args);
}
},
});
}
exports.wrapAppGetInitialPropsWithSentry = wrapAppGetInitialPropsWithSentry;
//# sourceMappingURL=wrapAppGetInitialPropsWithSentry.js.map

View File

@@ -1,48 +0,0 @@
Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
const isBuild = require('../utils/isBuild.js');
const wrapperUtils = require('../utils/wrapperUtils.js');
/**
* Create a wrapped version of the user's exported `getInitialProps` function in
* a custom document ("_document.js").
*
* @param origDocumentGetInitialProps The user's `getInitialProps` function
* @param parameterizedRoute The page's parameterized route
* @returns A wrapped version of the function
*/
function wrapDocumentGetInitialPropsWithSentry(
origDocumentGetInitialProps,
) {
return new Proxy(origDocumentGetInitialProps, {
apply: async (wrappingTarget, thisArg, args) => {
if (isBuild.isBuild()) {
return wrappingTarget.apply(thisArg, args);
}
const [context] = args;
const { req, res } = context;
const errorWrappedGetInitialProps = wrapperUtils.withErrorInstrumentation(wrappingTarget);
// Generally we can assume that `req` and `res` are always defined on the server:
// https://nextjs.org/docs/api-reference/data-fetching/get-initial-props#context-object
// This does not seem to be the case in dev mode. Because we have no clean way of associating the the data fetcher
// span with each other when there are no req or res objects, we simply do not trace them at all here.
if (req && res) {
const tracedGetInitialProps = wrapperUtils.withTracedServerSideDataFetcher(errorWrappedGetInitialProps, req, res, {
dataFetcherRouteName: '/_document',
requestedRouteName: context.pathname,
dataFetchingMethodName: 'getInitialProps',
});
const { data } = await tracedGetInitialProps.apply(thisArg, args);
return data;
} else {
return errorWrappedGetInitialProps.apply(thisArg, args);
}
},
});
}
exports.wrapDocumentGetInitialPropsWithSentry = wrapDocumentGetInitialPropsWithSentry;
//# sourceMappingURL=wrapDocumentGetInitialPropsWithSentry.js.map

View File

@@ -1,67 +0,0 @@
Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
const isBuild = require('../utils/isBuild.js');
const wrapperUtils = require('../utils/wrapperUtils.js');
/**
* Create a wrapped version of the user's exported `getInitialProps` function in
* a custom error page ("_error.js").
*
* @param origErrorGetInitialProps The user's `getInitialProps` function
* @param parameterizedRoute The page's parameterized route
* @returns A wrapped version of the function
*/
function wrapErrorGetInitialPropsWithSentry(
origErrorGetInitialProps,
) {
return new Proxy(origErrorGetInitialProps, {
apply: async (wrappingTarget, thisArg, args) => {
if (isBuild.isBuild()) {
return wrappingTarget.apply(thisArg, args);
}
const [context] = args;
const { req, res } = context;
const errorWrappedGetInitialProps = wrapperUtils.withErrorInstrumentation(wrappingTarget);
// Generally we can assume that `req` and `res` are always defined on the server:
// https://nextjs.org/docs/api-reference/data-fetching/get-initial-props#context-object
// This does not seem to be the case in dev mode. Because we have no clean way of associating the the data fetcher
// span with each other when there are no req or res objects, we simply do not trace them at all here.
if (req && res) {
const tracedGetInitialProps = wrapperUtils.withTracedServerSideDataFetcher(errorWrappedGetInitialProps, req, res, {
dataFetcherRouteName: '/_error',
requestedRouteName: context.pathname,
dataFetchingMethodName: 'getInitialProps',
});
const {
data: errorGetInitialProps,
baggage,
sentryTrace,
}
= await tracedGetInitialProps.apply(thisArg, args);
if (typeof errorGetInitialProps === 'object' && errorGetInitialProps !== null) {
if (sentryTrace) {
// The Next.js serializer throws on undefined values so we need to guard for it (#12102)
(errorGetInitialProps )._sentryTraceData = sentryTrace;
}
// The Next.js serializer throws on undefined values so we need to guard for it (#12102)
if (baggage) {
(errorGetInitialProps )._sentryBaggage = baggage;
}
}
return errorGetInitialProps;
} else {
return errorWrappedGetInitialProps.apply(thisArg, args);
}
},
});
}
exports.wrapErrorGetInitialPropsWithSentry = wrapErrorGetInitialPropsWithSentry;
//# sourceMappingURL=wrapErrorGetInitialPropsWithSentry.js.map

View File

@@ -1,64 +0,0 @@
Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
const isBuild = require('../utils/isBuild.js');
const wrapperUtils = require('../utils/wrapperUtils.js');
/**
* Create a wrapped version of the user's exported `getInitialProps` function
*
* @param origGetInitialProps The user's `getInitialProps` function
* @param parameterizedRoute The page's parameterized route
* @returns A wrapped version of the function
*/
function wrapGetInitialPropsWithSentry(origGetInitialProps) {
return new Proxy(origGetInitialProps, {
apply: async (wrappingTarget, thisArg, args) => {
if (isBuild.isBuild()) {
return wrappingTarget.apply(thisArg, args);
}
const [context] = args;
const { req, res } = context;
const errorWrappedGetInitialProps = wrapperUtils.withErrorInstrumentation(wrappingTarget);
// Generally we can assume that `req` and `res` are always defined on the server:
// https://nextjs.org/docs/api-reference/data-fetching/get-initial-props#context-object
// This does not seem to be the case in dev mode. Because we have no clean way of associating the the data fetcher
// span with each other when there are no req or res objects, we simply do not trace them at all here.
if (req && res) {
const tracedGetInitialProps = wrapperUtils.withTracedServerSideDataFetcher(errorWrappedGetInitialProps, req, res, {
dataFetcherRouteName: context.pathname,
requestedRouteName: context.pathname,
dataFetchingMethodName: 'getInitialProps',
});
const {
data: initialProps,
baggage,
sentryTrace,
}
= (await tracedGetInitialProps.apply(thisArg, args)) ?? {}; // Next.js allows undefined to be returned from a getInitialPropsFunction.
if (typeof initialProps === 'object' && initialProps !== null) {
// The Next.js serializer throws on undefined values so we need to guard for it (#12102)
if (sentryTrace) {
(initialProps )._sentryTraceData = sentryTrace;
}
// The Next.js serializer throws on undefined values so we need to guard for it (#12102)
if (baggage) {
(initialProps )._sentryBaggage = baggage;
}
}
return initialProps;
} else {
return errorWrappedGetInitialProps.apply(thisArg, args);
}
},
});
}
exports.wrapGetInitialPropsWithSentry = wrapGetInitialPropsWithSentry;
//# sourceMappingURL=wrapGetInitialPropsWithSentry.js.map

View File

@@ -1,59 +0,0 @@
Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
const isBuild = require('../utils/isBuild.js');
const wrapperUtils = require('../utils/wrapperUtils.js');
/**
* Create a wrapped version of the user's exported `getServerSideProps` function
*
* @param origGetServerSideProps The user's `getServerSideProps` function
* @param parameterizedRoute The page's parameterized route
* @returns A wrapped version of the function
*/
function wrapGetServerSidePropsWithSentry(
origGetServerSideProps,
parameterizedRoute,
) {
return new Proxy(origGetServerSideProps, {
apply: async (wrappingTarget, thisArg, args) => {
if (isBuild.isBuild()) {
return wrappingTarget.apply(thisArg, args);
}
const [context] = args;
const { req, res } = context;
const errorWrappedGetServerSideProps = wrapperUtils.withErrorInstrumentation(wrappingTarget);
const tracedGetServerSideProps = wrapperUtils.withTracedServerSideDataFetcher(errorWrappedGetServerSideProps, req, res, {
dataFetcherRouteName: parameterizedRoute,
requestedRouteName: parameterizedRoute,
dataFetchingMethodName: 'getServerSideProps',
});
const {
data: serverSideProps,
baggage,
sentryTrace,
}
= await (tracedGetServerSideProps.apply(thisArg, args) );
if (typeof serverSideProps === 'object' && serverSideProps !== null && 'props' in serverSideProps) {
// The Next.js serializer throws on undefined values so we need to guard for it (#12102)
if (sentryTrace) {
(serverSideProps.props )._sentryTraceData = sentryTrace;
}
// The Next.js serializer throws on undefined values so we need to guard for it (#12102)
if (baggage) {
(serverSideProps.props )._sentryBaggage = baggage;
}
}
return serverSideProps;
},
});
}
exports.wrapGetServerSidePropsWithSentry = wrapGetServerSidePropsWithSentry;
//# sourceMappingURL=wrapGetServerSidePropsWithSentry.js.map

View File

@@ -1,30 +0,0 @@
Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
const isBuild = require('../utils/isBuild.js');
const wrapperUtils = require('../utils/wrapperUtils.js');
/**
* Create a wrapped version of the user's exported `getStaticProps` function
*
* @param origGetStaticProps The user's `getStaticProps` function
* @param parameterizedRoute The page's parameterized route
* @returns A wrapped version of the function
*/
function wrapGetStaticPropsWithSentry(
origGetStaticPropsa,
_parameterizedRoute,
) {
return new Proxy(origGetStaticPropsa, {
apply: async (wrappingTarget, thisArg, args) => {
if (isBuild.isBuild()) {
return wrappingTarget.apply(thisArg, args);
}
const errorWrappedGetStaticProps = wrapperUtils.withErrorInstrumentation(wrappingTarget);
return wrapperUtils.callDataFetcherTraced(errorWrappedGetStaticProps, args);
},
});
}
exports.wrapGetStaticPropsWithSentry = wrapGetStaticPropsWithSentry;
//# sourceMappingURL=wrapGetStaticPropsWithSentry.js.map

View File

@@ -1,94 +0,0 @@
Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
const core = require('@sentry/core');
function storeCapturedEventIdOnError(error, eventId) {
if (error && typeof error === 'object') {
core.addNonEnumerableProperty(error , '__sentry_event_id__', eventId);
}
}
function isReactClassComponent(target) {
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
return typeof target === 'function' && target?.prototype?.isReactComponent;
}
/**
* Wraps a page component with Sentry error instrumentation.
*/
function wrapPageComponentWithSentry(pageComponent) {
if (isReactClassComponent(pageComponent)) {
return class SentryWrappedPageComponent extends pageComponent {
render(...args) {
return core.withIsolationScope(() => {
const scope = core.getCurrentScope();
// We extract the sentry trace data that is put in the component props by datafetcher wrappers
const sentryTraceData =
typeof this.props === 'object' &&
this.props !== null &&
'_sentryTraceData' in this.props &&
typeof this.props._sentryTraceData === 'string'
? this.props._sentryTraceData
: undefined;
if (sentryTraceData) {
const traceparentData = core.extractTraceparentData(sentryTraceData);
scope.setContext('trace', {
span_id: traceparentData?.parentSpanId,
trace_id: traceparentData?.traceId,
});
}
try {
return super.render(...args);
} catch (e) {
const eventId = core.captureException(e, {
mechanism: {
handled: false,
type: 'auto.function.nextjs.page_class',
},
});
storeCapturedEventIdOnError(e, eventId);
throw e;
}
});
}
};
} else if (typeof pageComponent === 'function') {
return new Proxy(pageComponent, {
apply(target, thisArg, argArray) {
return core.withIsolationScope(() => {
const scope = core.getCurrentScope();
// We extract the sentry trace data that is put in the component props by datafetcher wrappers
const sentryTraceData = argArray?.[0]?._sentryTraceData;
if (sentryTraceData) {
const traceparentData = core.extractTraceparentData(sentryTraceData);
scope.setContext('trace', {
span_id: traceparentData?.parentSpanId,
trace_id: traceparentData?.traceId,
});
}
try {
return target.apply(thisArg, argArray);
} catch (e) {
const eventId = core.captureException(e, {
mechanism: {
handled: false,
type: 'auto.function.nextjs.page_function',
},
});
storeCapturedEventIdOnError(e, eventId);
throw e;
}
});
},
});
} else {
return pageComponent;
}
}
exports.wrapPageComponentWithSentry = wrapPageComponentWithSentry;
//# sourceMappingURL=wrapPageComponentWithSentry.js.map

View File

@@ -1,15 +0,0 @@
Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
/**
* If this attribute is attached to a transaction, the Next.js SDK will drop that transaction.
*/
const TRANSACTION_ATTR_SHOULD_DROP_TRANSACTION = 'sentry.drop_transaction';
const TRANSACTION_ATTR_SENTRY_TRACE_BACKFILL = 'sentry.sentry_trace_backfill';
const TRANSACTION_ATTR_SENTRY_ROUTE_BACKFILL = 'sentry.route_backfill';
exports.TRANSACTION_ATTR_SENTRY_ROUTE_BACKFILL = TRANSACTION_ATTR_SENTRY_ROUTE_BACKFILL;
exports.TRANSACTION_ATTR_SENTRY_TRACE_BACKFILL = TRANSACTION_ATTR_SENTRY_TRACE_BACKFILL;
exports.TRANSACTION_ATTR_SHOULD_DROP_TRANSACTION = TRANSACTION_ATTR_SHOULD_DROP_TRANSACTION;
//# sourceMappingURL=span-attributes-with-logic-attached.js.map

View File

@@ -1,31 +0,0 @@
Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
const core = require('@sentry/core');
/**
* Extracts HTTP request headers as span attributes and optionally applies them to a span.
*/
function addHeadersAsAttributes(
headers,
span,
) {
if (!headers) {
return {};
}
const headersDict =
headers instanceof Headers || (typeof headers === 'object' && 'get' in headers)
? core.winterCGHeadersToDict(headers )
: headers;
const headerAttributes = core.httpHeadersToSpanAttributes(headersDict, core.getClient()?.getOptions().sendDefaultPii ?? false);
if (span) {
span.setAttributes(headerAttributes);
}
return headerAttributes;
}
exports.addHeadersAsAttributes = addHeadersAsAttributes;
//# sourceMappingURL=addHeadersAsAttributes.js.map

View File

@@ -1,71 +0,0 @@
Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
const semanticConventions = require('@opentelemetry/semantic-conventions');
const core = require('@sentry/core');
const opentelemetry = require('@sentry/opentelemetry');
const nextSpanAttributes = require('../nextSpanAttributes.js');
const spanAttributesWithLogicAttached = require('../span-attributes-with-logic-attached.js');
const globalWithInjectedValues = core.GLOBAL_OBJ
;
/**
* Drops spans for tunnel requests from middleware, fetch instrumentation, or BaseServer.handleRequest.
* This catches:
* 1. Requests to the local tunnel route (before rewrite) via middleware or BaseServer.handleRequest
* 2. Requests to Sentry ingest (after rewrite) via fetch spans
*/
function dropMiddlewareTunnelRequests(span, attrs) {
// When the user brings their own OTel setup (skipOpenTelemetrySetup: true), we should not
// mutate their spans with Sentry-internal attributes as it pollutes their tracing backends.
if ((core.getClient()?.getOptions() )?.skipOpenTelemetrySetup) {
return;
}
// Only filter middleware spans, HTTP fetch spans, or BaseServer.handleRequest spans
const isMiddleware = attrs?.[nextSpanAttributes.ATTR_NEXT_SPAN_TYPE] === 'Middleware.execute';
// The fetch span could be originating from rewrites re-writing a tunnel request
// So we want to filter it out
const isFetchSpan = attrs?.[core.SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN] === 'auto.http.otel.node_fetch';
const isBaseServerHandleRequest = attrs?.[nextSpanAttributes.ATTR_NEXT_SPAN_TYPE] === 'BaseServer.handleRequest';
// If the span is not a middleware span, fetch span, or BaseServer.handleRequest span, return
if (!isMiddleware && !isFetchSpan && !isBaseServerHandleRequest) {
return;
}
// Check if this is either a tunnel route request or a Sentry ingest request
const isTunnel = isTunnelRouteSpan(attrs || {});
const isSentry = opentelemetry.isSentryRequestSpan(span);
if (isTunnel || isSentry) {
// Mark the span to be dropped
span.setAttribute(spanAttributesWithLogicAttached.TRANSACTION_ATTR_SHOULD_DROP_TRANSACTION, true);
}
}
/**
* Checks if a span's HTTP target matches the tunnel route.
*/
function isTunnelRouteSpan(spanAttributes) {
const tunnelPath = globalWithInjectedValues._sentryRewritesTunnelPath || process.env._sentryRewritesTunnelPath;
if (!tunnelPath) {
return false;
}
// eslint-disable-next-line deprecation/deprecation
const httpTarget = spanAttributes[semanticConventions.SEMATTRS_HTTP_TARGET];
if (typeof httpTarget === 'string') {
// Extract pathname from the target (e.g., "/tunnel?o=123&p=456" -> "/tunnel")
const pathname = httpTarget.split('?')[0] || '';
return pathname === tunnelPath || pathname.startsWith(`${tunnelPath}/`);
}
return false;
}
exports.dropMiddlewareTunnelRequests = dropMiddlewareTunnelRequests;
//# sourceMappingURL=dropMiddlewareTunnelRequests.js.map

View File

@@ -1,13 +0,0 @@
Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
const constants = require('next/constants');
/**
* Decide if the currently running process is part of the build phase or happening at runtime.
*/
function isBuild() {
return process.env.NEXT_PHASE === constants.PHASE_PRODUCTION_BUILD;
}
exports.isBuild = isBuild;
//# sourceMappingURL=isBuild.js.map

View File

@@ -1,50 +0,0 @@
Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
// Vendored from: https://github.com/vercel/next.js/blob/canary/packages/next/src/lib/client-and-server-references.ts
function extractInfoFromServerReferenceId(id) {
const infoByte = parseInt(id.slice(0, 2), 16);
// eslint-disable-next-line no-bitwise
const typeBit = (infoByte >> 7) & 0x1;
// eslint-disable-next-line no-bitwise
const argMask = (infoByte >> 1) & 0x3f;
// eslint-disable-next-line no-bitwise
const restArgs = infoByte & 0x1;
const usedArgs = Array(6);
for (let index = 0; index < 6; index++) {
const bitPosition = 5 - index;
// eslint-disable-next-line no-bitwise
const bit = (argMask >> bitPosition) & 0x1;
usedArgs[index] = bit === 1;
}
return {
type: typeBit === 1 ? 'use-cache' : 'server-action',
usedArgs: usedArgs ,
hasRestArgs: restArgs === 1,
};
}
function isServerReference(value) {
return value.$$typeof === Symbol.for('react.server.reference');
}
/**
* Check if the function is a use cache function.
*
* @param value - The function to check.
* @returns true if the function is a use cache function, false otherwise.
*/
function isUseCacheFunction(value) {
if (!isServerReference(value)) {
return false;
}
const { type } = extractInfoFromServerReferenceId(value.$$id);
return type === 'use-cache';
}
exports.isUseCacheFunction = isUseCacheFunction;
//# sourceMappingURL=isUseCacheFunction.js.map

View File

@@ -1,82 +0,0 @@
Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
const core = require('@sentry/core');
const debugBuild = require('../debug-build.js');
const isBuild = require('./isBuild.js');
const isUseCacheFunction = require('./isUseCacheFunction.js');
function shouldNoopSpan(callback) {
const isBuildContext = isBuild.isBuild();
const isUseCacheFunctionContext = callback ? isUseCacheFunction.isUseCacheFunction(callback) : false;
if (isUseCacheFunctionContext) {
debugBuild.DEBUG_BUILD && core.debug.log('Skipping span creation in Cache Components context');
}
return isBuildContext || isUseCacheFunctionContext;
}
function createNonRecordingSpan() {
return new core.SentryNonRecordingSpan({
traceId: '00000000000000000000000000000000',
spanId: '0000000000000000',
});
}
/**
* Next.js-specific implementation of `startSpan` that skips span creation
* in Cache Components contexts (which render at build time).
*
* When in a Cache Components context, we execute the callback with a non-recording span
* and return early without creating an actual span, since spans don't make sense at build/cache time.
*
* @param options - Options for starting the span
* @param callback - Callback function that receives the span
* @returns The return value of the callback
*/
function startSpan(options, callback) {
if (shouldNoopSpan(callback)) {
return callback(createNonRecordingSpan());
}
return core.startSpan(options, callback);
}
/**
*
* When in a Cache Components context, we execute the callback with a non-recording span
* and return early without creating an actual span, since spans don't make sense at build/cache time.
*
* @param options - Options for starting the span
* @param callback - Callback function that receives the span and finish function
* @returns The return value of the callback
*/
function startSpanManual(options, callback) {
if (shouldNoopSpan(callback)) {
const nonRecordingSpan = createNonRecordingSpan();
return callback(nonRecordingSpan, () => nonRecordingSpan.end());
}
return core.startSpanManual(options, callback);
}
/**
*
* When in a Cache Components context, we return a non-recording span and return early
* without creating an actual span, since spans don't make sense at build/cache time.
*
* @param options - Options for starting the span
* @returns A non-recording span (in Cache Components context) or the created span
*/
function startInactiveSpan(options) {
if (shouldNoopSpan()) {
return createNonRecordingSpan();
}
return core.startInactiveSpan(options);
}
exports.startInactiveSpan = startInactiveSpan;
exports.startSpan = startSpan;
exports.startSpanManual = startSpanManual;
//# sourceMappingURL=nextSpan.js.map

Some files were not shown because too many files have changed in this diff Show More