reconstruct and build @anthropic-ai/claude-code source from source map

- Extract 4756 source files from cli.js.map (57MB)
- Set up Bun build system with bun:bundle feature flag shim
- Configure 90+ compile-time feature flags matching production defaults
- Inject MACRO constants (VERSION, BUILD_TIME, etc.)
- Create stubs for private packages (color-diff-napi, modifiers-napi, etc.)
- Install all public dependencies via pnpm
- Patch commander v14 to allow multi-char short flags (-d2e)
- Build output: dist/cli.js (22MB), verified working
This commit is contained in:
janlaywss
2026-03-31 19:19:50 +08:00
commit 6187147b74
37865 changed files with 5438634 additions and 0 deletions

View File

@@ -0,0 +1,104 @@
"use strict";
/*
* Copyright The OpenTelemetry Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.BasicTracerProvider = exports.ForceFlushState = void 0;
const core_1 = require("@opentelemetry/core");
const resources_1 = require("@opentelemetry/resources");
const Tracer_1 = require("./Tracer");
const config_1 = require("./config");
const MultiSpanProcessor_1 = require("./MultiSpanProcessor");
const utility_1 = require("./utility");
var ForceFlushState;
(function (ForceFlushState) {
ForceFlushState[ForceFlushState["resolved"] = 0] = "resolved";
ForceFlushState[ForceFlushState["timeout"] = 1] = "timeout";
ForceFlushState[ForceFlushState["error"] = 2] = "error";
ForceFlushState[ForceFlushState["unresolved"] = 3] = "unresolved";
})(ForceFlushState = exports.ForceFlushState || (exports.ForceFlushState = {}));
/**
* This class represents a basic tracer provider which platform libraries can extend
*/
class BasicTracerProvider {
_config;
_tracers = new Map();
_resource;
_activeSpanProcessor;
constructor(config = {}) {
const mergedConfig = (0, core_1.merge)({}, (0, config_1.loadDefaultConfig)(), (0, utility_1.reconfigureLimits)(config));
this._resource = mergedConfig.resource ?? (0, resources_1.defaultResource)();
this._config = Object.assign({}, mergedConfig, {
resource: this._resource,
});
const spanProcessors = [];
if (config.spanProcessors?.length) {
spanProcessors.push(...config.spanProcessors);
}
this._activeSpanProcessor = new MultiSpanProcessor_1.MultiSpanProcessor(spanProcessors);
}
getTracer(name, version, options) {
const key = `${name}@${version || ''}:${options?.schemaUrl || ''}`;
if (!this._tracers.has(key)) {
this._tracers.set(key, new Tracer_1.Tracer({ name, version, schemaUrl: options?.schemaUrl }, this._config, this._resource, this._activeSpanProcessor));
}
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
return this._tracers.get(key);
}
forceFlush() {
const timeout = this._config.forceFlushTimeoutMillis;
const promises = this._activeSpanProcessor['_spanProcessors'].map((spanProcessor) => {
return new Promise(resolve => {
let state;
const timeoutInterval = setTimeout(() => {
resolve(new Error(`Span processor did not completed within timeout period of ${timeout} ms`));
state = ForceFlushState.timeout;
}, timeout);
spanProcessor
.forceFlush()
.then(() => {
clearTimeout(timeoutInterval);
if (state !== ForceFlushState.timeout) {
state = ForceFlushState.resolved;
resolve(state);
}
})
.catch(error => {
clearTimeout(timeoutInterval);
state = ForceFlushState.error;
resolve(error);
});
});
});
return new Promise((resolve, reject) => {
Promise.all(promises)
.then(results => {
const errors = results.filter(result => result !== ForceFlushState.resolved);
if (errors.length > 0) {
reject(errors);
}
else {
resolve();
}
})
.catch(error => reject([error]));
});
}
shutdown() {
return this._activeSpanProcessor.shutdown();
}
}
exports.BasicTracerProvider = BasicTracerProvider;
//# sourceMappingURL=BasicTracerProvider.js.map

View File

@@ -0,0 +1,68 @@
"use strict";
/*
* Copyright The OpenTelemetry Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.MultiSpanProcessor = void 0;
const core_1 = require("@opentelemetry/core");
/**
* Implementation of the {@link SpanProcessor} that simply forwards all
* received events to a list of {@link SpanProcessor}s.
*/
class MultiSpanProcessor {
_spanProcessors;
constructor(_spanProcessors) {
this._spanProcessors = _spanProcessors;
}
forceFlush() {
const promises = [];
for (const spanProcessor of this._spanProcessors) {
promises.push(spanProcessor.forceFlush());
}
return new Promise(resolve => {
Promise.all(promises)
.then(() => {
resolve();
})
.catch(error => {
(0, core_1.globalErrorHandler)(error || new Error('MultiSpanProcessor: forceFlush failed'));
resolve();
});
});
}
onStart(span, context) {
for (const spanProcessor of this._spanProcessors) {
spanProcessor.onStart(span, context);
}
}
onEnd(span) {
for (const spanProcessor of this._spanProcessors) {
spanProcessor.onEnd(span);
}
}
shutdown() {
const promises = [];
for (const spanProcessor of this._spanProcessors) {
promises.push(spanProcessor.shutdown());
}
return new Promise((resolve, reject) => {
Promise.all(promises).then(() => {
resolve();
}, reject);
});
}
}
exports.MultiSpanProcessor = MultiSpanProcessor;
//# sourceMappingURL=MultiSpanProcessor.js.map

View File

@@ -0,0 +1,41 @@
"use strict";
/*
* Copyright The OpenTelemetry Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.SamplingDecision = void 0;
/**
* A sampling decision that determines how a {@link Span} will be recorded
* and collected.
*/
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=Sampler.js.map

View File

@@ -0,0 +1,312 @@
"use strict";
/*
* Copyright The OpenTelemetry Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.SpanImpl = void 0;
const api_1 = require("@opentelemetry/api");
const core_1 = require("@opentelemetry/core");
const semantic_conventions_1 = require("@opentelemetry/semantic-conventions");
const enums_1 = require("./enums");
/**
* This class represents a span.
*/
class SpanImpl {
// Below properties are included to implement ReadableSpan for export
// purposes but are not intended to be written-to directly.
_spanContext;
kind;
parentSpanContext;
attributes = {};
links = [];
events = [];
startTime;
resource;
instrumentationScope;
_droppedAttributesCount = 0;
_droppedEventsCount = 0;
_droppedLinksCount = 0;
name;
status = {
code: api_1.SpanStatusCode.UNSET,
};
endTime = [0, 0];
_ended = false;
_duration = [-1, -1];
_spanProcessor;
_spanLimits;
_attributeValueLengthLimit;
_performanceStartTime;
_performanceOffset;
_startTimeProvided;
/**
* Constructs a new SpanImpl instance.
*/
constructor(opts) {
const now = Date.now();
this._spanContext = opts.spanContext;
this._performanceStartTime = core_1.otperformance.now();
this._performanceOffset =
now - (this._performanceStartTime + (0, core_1.getTimeOrigin)());
this._startTimeProvided = opts.startTime != null;
this._spanLimits = opts.spanLimits;
this._attributeValueLengthLimit =
this._spanLimits.attributeValueLengthLimit || 0;
this._spanProcessor = opts.spanProcessor;
this.name = opts.name;
this.parentSpanContext = opts.parentSpanContext;
this.kind = opts.kind;
this.links = opts.links || [];
this.startTime = this._getTime(opts.startTime ?? now);
this.resource = opts.resource;
this.instrumentationScope = opts.scope;
if (opts.attributes != null) {
this.setAttributes(opts.attributes);
}
this._spanProcessor.onStart(this, opts.context);
}
spanContext() {
return this._spanContext;
}
setAttribute(key, value) {
if (value == null || this._isSpanEnded())
return this;
if (key.length === 0) {
api_1.diag.warn(`Invalid attribute key: ${key}`);
return this;
}
if (!(0, core_1.isAttributeValue)(value)) {
api_1.diag.warn(`Invalid attribute value set for key: ${key}`);
return this;
}
const { attributeCountLimit } = this._spanLimits;
if (attributeCountLimit !== undefined &&
Object.keys(this.attributes).length >= attributeCountLimit &&
!Object.prototype.hasOwnProperty.call(this.attributes, key)) {
this._droppedAttributesCount++;
return this;
}
this.attributes[key] = this._truncateToSize(value);
return this;
}
setAttributes(attributes) {
for (const [k, v] of Object.entries(attributes)) {
this.setAttribute(k, v);
}
return this;
}
/**
*
* @param name Span Name
* @param [attributesOrStartTime] Span attributes or start time
* if type is {@type TimeInput} and 3rd param is undefined
* @param [timeStamp] Specified time stamp for the event
*/
addEvent(name, attributesOrStartTime, timeStamp) {
if (this._isSpanEnded())
return this;
const { eventCountLimit } = this._spanLimits;
if (eventCountLimit === 0) {
api_1.diag.warn('No events allowed.');
this._droppedEventsCount++;
return this;
}
if (eventCountLimit !== undefined &&
this.events.length >= eventCountLimit) {
if (this._droppedEventsCount === 0) {
api_1.diag.debug('Dropping extra events.');
}
this.events.shift();
this._droppedEventsCount++;
}
if ((0, core_1.isTimeInput)(attributesOrStartTime)) {
if (!(0, core_1.isTimeInput)(timeStamp)) {
timeStamp = attributesOrStartTime;
}
attributesOrStartTime = undefined;
}
const attributes = (0, core_1.sanitizeAttributes)(attributesOrStartTime);
this.events.push({
name,
attributes,
time: this._getTime(timeStamp),
droppedAttributesCount: 0,
});
return this;
}
addLink(link) {
this.links.push(link);
return this;
}
addLinks(links) {
this.links.push(...links);
return this;
}
setStatus(status) {
if (this._isSpanEnded())
return this;
this.status = { ...status };
// When using try-catch, the caught "error" is of type `any`. When then assigning `any` to `status.message`,
// TypeScript will not error. While this can happen during use of any API, it is more common on Span#setStatus()
// as it's likely used in a catch-block. Therefore, we validate if `status.message` is actually a string, null, or
// undefined to avoid an incorrect type causing issues downstream.
if (this.status.message != null && typeof status.message !== 'string') {
api_1.diag.warn(`Dropping invalid status.message of type '${typeof status.message}', expected 'string'`);
delete this.status.message;
}
return this;
}
updateName(name) {
if (this._isSpanEnded())
return this;
this.name = name;
return this;
}
end(endTime) {
if (this._isSpanEnded()) {
api_1.diag.error(`${this.name} ${this._spanContext.traceId}-${this._spanContext.spanId} - You can only call end() on a span once.`);
return;
}
this._ended = true;
this.endTime = this._getTime(endTime);
this._duration = (0, core_1.hrTimeDuration)(this.startTime, this.endTime);
if (this._duration[0] < 0) {
api_1.diag.warn('Inconsistent start and end time, startTime > endTime. Setting span duration to 0ms.', this.startTime, this.endTime);
this.endTime = this.startTime.slice();
this._duration = [0, 0];
}
if (this._droppedEventsCount > 0) {
api_1.diag.warn(`Dropped ${this._droppedEventsCount} events because eventCountLimit reached`);
}
this._spanProcessor.onEnd(this);
}
_getTime(inp) {
if (typeof inp === 'number' && inp <= core_1.otperformance.now()) {
// must be a performance timestamp
// apply correction and convert to hrtime
return (0, core_1.hrTime)(inp + this._performanceOffset);
}
if (typeof inp === 'number') {
return (0, core_1.millisToHrTime)(inp);
}
if (inp instanceof Date) {
return (0, core_1.millisToHrTime)(inp.getTime());
}
if ((0, core_1.isTimeInputHrTime)(inp)) {
return inp;
}
if (this._startTimeProvided) {
// if user provided a time for the start manually
// we can't use duration to calculate event/end times
return (0, core_1.millisToHrTime)(Date.now());
}
const msDuration = core_1.otperformance.now() - this._performanceStartTime;
return (0, core_1.addHrTimes)(this.startTime, (0, core_1.millisToHrTime)(msDuration));
}
isRecording() {
return this._ended === false;
}
recordException(exception, time) {
const attributes = {};
if (typeof exception === 'string') {
attributes[semantic_conventions_1.ATTR_EXCEPTION_MESSAGE] = exception;
}
else if (exception) {
if (exception.code) {
attributes[semantic_conventions_1.ATTR_EXCEPTION_TYPE] = exception.code.toString();
}
else if (exception.name) {
attributes[semantic_conventions_1.ATTR_EXCEPTION_TYPE] = exception.name;
}
if (exception.message) {
attributes[semantic_conventions_1.ATTR_EXCEPTION_MESSAGE] = exception.message;
}
if (exception.stack) {
attributes[semantic_conventions_1.ATTR_EXCEPTION_STACKTRACE] = exception.stack;
}
}
// these are minimum requirements from spec
if (attributes[semantic_conventions_1.ATTR_EXCEPTION_TYPE] || attributes[semantic_conventions_1.ATTR_EXCEPTION_MESSAGE]) {
this.addEvent(enums_1.ExceptionEventName, attributes, time);
}
else {
api_1.diag.warn(`Failed to record an exception ${exception}`);
}
}
get duration() {
return this._duration;
}
get ended() {
return this._ended;
}
get droppedAttributesCount() {
return this._droppedAttributesCount;
}
get droppedEventsCount() {
return this._droppedEventsCount;
}
get droppedLinksCount() {
return this._droppedLinksCount;
}
_isSpanEnded() {
if (this._ended) {
const error = new Error(`Operation attempted on ended Span {traceId: ${this._spanContext.traceId}, spanId: ${this._spanContext.spanId}}`);
api_1.diag.warn(`Cannot execute the operation on ended Span {traceId: ${this._spanContext.traceId}, spanId: ${this._spanContext.spanId}}`, error);
}
return this._ended;
}
// Utility function to truncate given value within size
// for value type of string, will truncate to given limit
// for type of non-string, will return same value
_truncateToLimitUtil(value, limit) {
if (value.length <= limit) {
return value;
}
return value.substring(0, limit);
}
/**
* If the given attribute value is of type string and has more characters than given {@code attributeValueLengthLimit} then
* return string with truncated to {@code attributeValueLengthLimit} characters
*
* If the given attribute value is array of strings then
* return new array of strings with each element truncated to {@code attributeValueLengthLimit} characters
*
* Otherwise return same Attribute {@code value}
*
* @param value Attribute value
* @returns truncated attribute value if required, otherwise same value
*/
_truncateToSize(value) {
const limit = this._attributeValueLengthLimit;
// Check limit
if (limit <= 0) {
// Negative values are invalid, so do not truncate
api_1.diag.warn(`Attribute value limit must be positive, got ${limit}`);
return value;
}
// String
if (typeof value === 'string') {
return this._truncateToLimitUtil(value, limit);
}
// Array of strings
if (Array.isArray(value)) {
return value.map(val => typeof val === 'string' ? this._truncateToLimitUtil(val, limit) : val);
}
// Other types, no need to apply value length limit
return value;
}
}
exports.SpanImpl = SpanImpl;
//# sourceMappingURL=Span.js.map

View File

@@ -0,0 +1,152 @@
"use strict";
/*
* Copyright The OpenTelemetry Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.Tracer = void 0;
const api = require("@opentelemetry/api");
const core_1 = require("@opentelemetry/core");
const Span_1 = require("./Span");
const utility_1 = require("./utility");
const platform_1 = require("./platform");
/**
* This class represents a basic tracer.
*/
class Tracer {
_sampler;
_generalLimits;
_spanLimits;
_idGenerator;
instrumentationScope;
_resource;
_spanProcessor;
/**
* Constructs a new Tracer instance.
*/
constructor(instrumentationScope, config, resource, spanProcessor) {
const localConfig = (0, utility_1.mergeConfig)(config);
this._sampler = localConfig.sampler;
this._generalLimits = localConfig.generalLimits;
this._spanLimits = localConfig.spanLimits;
this._idGenerator = config.idGenerator || new platform_1.RandomIdGenerator();
this._resource = resource;
this._spanProcessor = spanProcessor;
this.instrumentationScope = instrumentationScope;
}
/**
* Starts a new Span or returns the default NoopSpan based on the sampling
* decision.
*/
startSpan(name, options = {}, context = api.context.active()) {
// remove span from context in case a root span is requested via options
if (options.root) {
context = api.trace.deleteSpan(context);
}
const parentSpan = api.trace.getSpan(context);
if ((0, core_1.isTracingSuppressed)(context)) {
api.diag.debug('Instrumentation suppressed, returning Noop Span');
const nonRecordingSpan = api.trace.wrapSpanContext(api.INVALID_SPAN_CONTEXT);
return nonRecordingSpan;
}
const parentSpanContext = parentSpan?.spanContext();
const spanId = this._idGenerator.generateSpanId();
let validParentSpanContext;
let traceId;
let traceState;
if (!parentSpanContext ||
!api.trace.isSpanContextValid(parentSpanContext)) {
// New root span.
traceId = this._idGenerator.generateTraceId();
}
else {
// New child span.
traceId = parentSpanContext.traceId;
traceState = parentSpanContext.traceState;
validParentSpanContext = parentSpanContext;
}
const spanKind = options.kind ?? api.SpanKind.INTERNAL;
const links = (options.links ?? []).map(link => {
return {
context: link.context,
attributes: (0, core_1.sanitizeAttributes)(link.attributes),
};
});
const attributes = (0, core_1.sanitizeAttributes)(options.attributes);
// make sampling decision
const samplingResult = this._sampler.shouldSample(context, traceId, name, spanKind, attributes, links);
traceState = samplingResult.traceState ?? traceState;
const traceFlags = samplingResult.decision === api.SamplingDecision.RECORD_AND_SAMPLED
? api.TraceFlags.SAMPLED
: api.TraceFlags.NONE;
const spanContext = { traceId, spanId, traceFlags, traceState };
if (samplingResult.decision === api.SamplingDecision.NOT_RECORD) {
api.diag.debug('Recording is off, propagating context in a non-recording span');
const nonRecordingSpan = api.trace.wrapSpanContext(spanContext);
return nonRecordingSpan;
}
// Set initial span attributes. The attributes object may have been mutated
// by the sampler, so we sanitize the merged attributes before setting them.
const initAttributes = (0, core_1.sanitizeAttributes)(Object.assign(attributes, samplingResult.attributes));
const span = new Span_1.SpanImpl({
resource: this._resource,
scope: this.instrumentationScope,
context,
spanContext,
name,
kind: spanKind,
links,
parentSpanContext: validParentSpanContext,
attributes: initAttributes,
startTime: options.startTime,
spanProcessor: this._spanProcessor,
spanLimits: this._spanLimits,
});
return span;
}
startActiveSpan(name, arg2, arg3, arg4) {
let opts;
let ctx;
let fn;
if (arguments.length < 2) {
return;
}
else if (arguments.length === 2) {
fn = arg2;
}
else if (arguments.length === 3) {
opts = arg2;
fn = arg3;
}
else {
opts = arg2;
ctx = arg3;
fn = arg4;
}
const parentContext = ctx ?? api.context.active();
const span = this.startSpan(name, opts, parentContext);
const contextWithSpanSet = api.trace.setSpan(parentContext, span);
return api.context.with(contextWithSpanSet, fn, undefined, span);
}
/** Returns the active {@link GeneralLimits}. */
getGeneralLimits() {
return this._generalLimits;
}
/** Returns the active {@link SpanLimits}. */
getSpanLimits() {
return this._spanLimits;
}
}
exports.Tracer = Tracer;
//# sourceMappingURL=Tracer.js.map

View File

@@ -0,0 +1,107 @@
"use strict";
/*
* Copyright The OpenTelemetry Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.buildSamplerFromEnv = exports.loadDefaultConfig = void 0;
const api_1 = require("@opentelemetry/api");
const core_1 = require("@opentelemetry/core");
const AlwaysOffSampler_1 = require("./sampler/AlwaysOffSampler");
const AlwaysOnSampler_1 = require("./sampler/AlwaysOnSampler");
const ParentBasedSampler_1 = require("./sampler/ParentBasedSampler");
const TraceIdRatioBasedSampler_1 = require("./sampler/TraceIdRatioBasedSampler");
var TracesSamplerValues;
(function (TracesSamplerValues) {
TracesSamplerValues["AlwaysOff"] = "always_off";
TracesSamplerValues["AlwaysOn"] = "always_on";
TracesSamplerValues["ParentBasedAlwaysOff"] = "parentbased_always_off";
TracesSamplerValues["ParentBasedAlwaysOn"] = "parentbased_always_on";
TracesSamplerValues["ParentBasedTraceIdRatio"] = "parentbased_traceidratio";
TracesSamplerValues["TraceIdRatio"] = "traceidratio";
})(TracesSamplerValues || (TracesSamplerValues = {}));
const DEFAULT_RATIO = 1;
/**
* Load default configuration. For fields with primitive values, any user-provided
* value will override the corresponding default value. For fields with
* non-primitive values (like `spanLimits`), the user-provided value will be
* used to extend the default value.
*/
// object needs to be wrapped in this function and called when needed otherwise
// envs are parsed before tests are ran - causes tests using these envs to fail
function loadDefaultConfig() {
return {
sampler: buildSamplerFromEnv(),
forceFlushTimeoutMillis: 30000,
generalLimits: {
attributeValueLengthLimit: (0, core_1.getNumberFromEnv)('OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT') ?? Infinity,
attributeCountLimit: (0, core_1.getNumberFromEnv)('OTEL_ATTRIBUTE_COUNT_LIMIT') ?? 128,
},
spanLimits: {
attributeValueLengthLimit: (0, core_1.getNumberFromEnv)('OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT') ?? Infinity,
attributeCountLimit: (0, core_1.getNumberFromEnv)('OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT') ?? 128,
linkCountLimit: (0, core_1.getNumberFromEnv)('OTEL_SPAN_LINK_COUNT_LIMIT') ?? 128,
eventCountLimit: (0, core_1.getNumberFromEnv)('OTEL_SPAN_EVENT_COUNT_LIMIT') ?? 128,
attributePerEventCountLimit: (0, core_1.getNumberFromEnv)('OTEL_SPAN_ATTRIBUTE_PER_EVENT_COUNT_LIMIT') ?? 128,
attributePerLinkCountLimit: (0, core_1.getNumberFromEnv)('OTEL_SPAN_ATTRIBUTE_PER_LINK_COUNT_LIMIT') ?? 128,
},
};
}
exports.loadDefaultConfig = loadDefaultConfig;
/**
* Based on environment, builds a sampler, complies with specification.
*/
function buildSamplerFromEnv() {
const sampler = (0, core_1.getStringFromEnv)('OTEL_TRACES_SAMPLER') ??
TracesSamplerValues.ParentBasedAlwaysOn;
switch (sampler) {
case TracesSamplerValues.AlwaysOn:
return new AlwaysOnSampler_1.AlwaysOnSampler();
case TracesSamplerValues.AlwaysOff:
return new AlwaysOffSampler_1.AlwaysOffSampler();
case TracesSamplerValues.ParentBasedAlwaysOn:
return new ParentBasedSampler_1.ParentBasedSampler({
root: new AlwaysOnSampler_1.AlwaysOnSampler(),
});
case TracesSamplerValues.ParentBasedAlwaysOff:
return new ParentBasedSampler_1.ParentBasedSampler({
root: new AlwaysOffSampler_1.AlwaysOffSampler(),
});
case TracesSamplerValues.TraceIdRatio:
return new TraceIdRatioBasedSampler_1.TraceIdRatioBasedSampler(getSamplerProbabilityFromEnv());
case TracesSamplerValues.ParentBasedTraceIdRatio:
return new ParentBasedSampler_1.ParentBasedSampler({
root: new TraceIdRatioBasedSampler_1.TraceIdRatioBasedSampler(getSamplerProbabilityFromEnv()),
});
default:
api_1.diag.error(`OTEL_TRACES_SAMPLER value "${sampler}" invalid, defaulting to "${TracesSamplerValues.ParentBasedAlwaysOn}".`);
return new ParentBasedSampler_1.ParentBasedSampler({
root: new AlwaysOnSampler_1.AlwaysOnSampler(),
});
}
}
exports.buildSamplerFromEnv = buildSamplerFromEnv;
function getSamplerProbabilityFromEnv() {
const probability = (0, core_1.getNumberFromEnv)('OTEL_TRACES_SAMPLER_ARG');
if (probability == null) {
api_1.diag.error(`OTEL_TRACES_SAMPLER_ARG is blank, defaulting to ${DEFAULT_RATIO}.`);
return DEFAULT_RATIO;
}
if (probability < 0 || probability > 1) {
api_1.diag.error(`OTEL_TRACES_SAMPLER_ARG=${probability} was given, but it is out of range ([0..1]), defaulting to ${DEFAULT_RATIO}.`);
return DEFAULT_RATIO;
}
return probability;
}
//# sourceMappingURL=config.js.map

View File

@@ -0,0 +1,21 @@
"use strict";
/*
* Copyright The OpenTelemetry Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.ExceptionEventName = void 0;
// Event name definitions
exports.ExceptionEventName = 'exception';
//# sourceMappingURL=enums.js.map

View File

@@ -0,0 +1,223 @@
"use strict";
/*
* Copyright The OpenTelemetry Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.BatchSpanProcessorBase = void 0;
const api_1 = require("@opentelemetry/api");
const core_1 = require("@opentelemetry/core");
/**
* Implementation of the {@link SpanProcessor} that batches spans exported by
* the SDK then pushes them to the exporter pipeline.
*/
class BatchSpanProcessorBase {
_exporter;
_maxExportBatchSize;
_maxQueueSize;
_scheduledDelayMillis;
_exportTimeoutMillis;
_isExporting = false;
_finishedSpans = [];
_timer;
_shutdownOnce;
_droppedSpansCount = 0;
constructor(_exporter, config) {
this._exporter = _exporter;
this._maxExportBatchSize =
typeof config?.maxExportBatchSize === 'number'
? config.maxExportBatchSize
: ((0, core_1.getNumberFromEnv)('OTEL_BSP_MAX_EXPORT_BATCH_SIZE') ?? 512);
this._maxQueueSize =
typeof config?.maxQueueSize === 'number'
? config.maxQueueSize
: ((0, core_1.getNumberFromEnv)('OTEL_BSP_MAX_QUEUE_SIZE') ?? 2048);
this._scheduledDelayMillis =
typeof config?.scheduledDelayMillis === 'number'
? config.scheduledDelayMillis
: ((0, core_1.getNumberFromEnv)('OTEL_BSP_SCHEDULE_DELAY') ?? 5000);
this._exportTimeoutMillis =
typeof config?.exportTimeoutMillis === 'number'
? config.exportTimeoutMillis
: ((0, core_1.getNumberFromEnv)('OTEL_BSP_EXPORT_TIMEOUT') ?? 30000);
this._shutdownOnce = new core_1.BindOnceFuture(this._shutdown, this);
if (this._maxExportBatchSize > this._maxQueueSize) {
api_1.diag.warn('BatchSpanProcessor: maxExportBatchSize must be smaller or equal to maxQueueSize, setting maxExportBatchSize to match maxQueueSize');
this._maxExportBatchSize = this._maxQueueSize;
}
}
forceFlush() {
if (this._shutdownOnce.isCalled) {
return this._shutdownOnce.promise;
}
return this._flushAll();
}
// does nothing.
onStart(_span, _parentContext) { }
onEnd(span) {
if (this._shutdownOnce.isCalled) {
return;
}
if ((span.spanContext().traceFlags & api_1.TraceFlags.SAMPLED) === 0) {
return;
}
this._addToBuffer(span);
}
shutdown() {
return this._shutdownOnce.call();
}
_shutdown() {
return Promise.resolve()
.then(() => {
return this.onShutdown();
})
.then(() => {
return this._flushAll();
})
.then(() => {
return this._exporter.shutdown();
});
}
/** Add a span in the buffer. */
_addToBuffer(span) {
if (this._finishedSpans.length >= this._maxQueueSize) {
// limit reached, drop span
if (this._droppedSpansCount === 0) {
api_1.diag.debug('maxQueueSize reached, dropping spans');
}
this._droppedSpansCount++;
return;
}
if (this._droppedSpansCount > 0) {
// some spans were dropped, log once with count of spans dropped
api_1.diag.warn(`Dropped ${this._droppedSpansCount} spans because maxQueueSize reached`);
this._droppedSpansCount = 0;
}
this._finishedSpans.push(span);
this._maybeStartTimer();
}
/**
* Send all spans to the exporter respecting the batch size limit
* This function is used only on forceFlush or shutdown,
* for all other cases _flush should be used
* */
_flushAll() {
return new Promise((resolve, reject) => {
const promises = [];
// calculate number of batches
const count = Math.ceil(this._finishedSpans.length / this._maxExportBatchSize);
for (let i = 0, j = count; i < j; i++) {
promises.push(this._flushOneBatch());
}
Promise.all(promises)
.then(() => {
resolve();
})
.catch(reject);
});
}
_flushOneBatch() {
this._clearTimer();
if (this._finishedSpans.length === 0) {
return Promise.resolve();
}
return new Promise((resolve, reject) => {
const timer = setTimeout(() => {
// don't wait anymore for export, this way the next batch can start
reject(new Error('Timeout'));
}, this._exportTimeoutMillis);
// prevent downstream exporter calls from generating spans
api_1.context.with((0, core_1.suppressTracing)(api_1.context.active()), () => {
// Reset the finished spans buffer here because the next invocations of the _flush method
// could pass the same finished spans to the exporter if the buffer is cleared
// outside the execution of this callback.
let spans;
if (this._finishedSpans.length <= this._maxExportBatchSize) {
spans = this._finishedSpans;
this._finishedSpans = [];
}
else {
spans = this._finishedSpans.splice(0, this._maxExportBatchSize);
}
const doExport = () => this._exporter.export(spans, result => {
clearTimeout(timer);
if (result.code === core_1.ExportResultCode.SUCCESS) {
resolve();
}
else {
reject(result.error ??
new Error('BatchSpanProcessor: span export failed'));
}
});
let pendingResources = null;
for (let i = 0, len = spans.length; i < len; i++) {
const span = spans[i];
if (span.resource.asyncAttributesPending &&
span.resource.waitForAsyncAttributes) {
pendingResources ??= [];
pendingResources.push(span.resource.waitForAsyncAttributes());
}
}
// Avoid scheduling a promise to make the behavior more predictable and easier to test
if (pendingResources === null) {
doExport();
}
else {
Promise.all(pendingResources).then(doExport, err => {
(0, core_1.globalErrorHandler)(err);
reject(err);
});
}
});
});
}
_maybeStartTimer() {
if (this._isExporting)
return;
const flush = () => {
this._isExporting = true;
this._flushOneBatch()
.finally(() => {
this._isExporting = false;
if (this._finishedSpans.length > 0) {
this._clearTimer();
this._maybeStartTimer();
}
})
.catch(e => {
this._isExporting = false;
(0, core_1.globalErrorHandler)(e);
});
};
// we only wait if the queue doesn't have enough elements yet
if (this._finishedSpans.length >= this._maxExportBatchSize) {
return flush();
}
if (this._timer !== undefined)
return;
this._timer = setTimeout(() => flush(), this._scheduledDelayMillis);
// depending on runtime, this may be a 'number' or NodeJS.Timeout
if (typeof this._timer !== 'number') {
this._timer.unref();
}
}
_clearTimer() {
if (this._timer !== undefined) {
clearTimeout(this._timer);
this._timer = undefined;
}
}
}
exports.BatchSpanProcessorBase = BatchSpanProcessorBase;
//# sourceMappingURL=BatchSpanProcessorBase.js.map

View File

@@ -0,0 +1,88 @@
"use strict";
/*
* Copyright The OpenTelemetry Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.ConsoleSpanExporter = void 0;
const core_1 = require("@opentelemetry/core");
/**
* This is implementation of {@link SpanExporter} that prints spans to the
* console. This class can be used for diagnostic purposes.
*
* NOTE: This {@link SpanExporter} is intended for diagnostics use only, output rendered to the console may change at any time.
*/
/* eslint-disable no-console */
class ConsoleSpanExporter {
/**
* Export spans.
* @param spans
* @param resultCallback
*/
export(spans, resultCallback) {
return this._sendSpans(spans, resultCallback);
}
/**
* Shutdown the exporter.
*/
shutdown() {
this._sendSpans([]);
return this.forceFlush();
}
/**
* Exports any pending spans in exporter
*/
forceFlush() {
return Promise.resolve();
}
/**
* converts span info into more readable format
* @param span
*/
_exportInfo(span) {
return {
resource: {
attributes: span.resource.attributes,
},
instrumentationScope: span.instrumentationScope,
traceId: span.spanContext().traceId,
parentSpanContext: span.parentSpanContext,
traceState: span.spanContext().traceState?.serialize(),
name: span.name,
id: span.spanContext().spanId,
kind: span.kind,
timestamp: (0, core_1.hrTimeToMicroseconds)(span.startTime),
duration: (0, core_1.hrTimeToMicroseconds)(span.duration),
attributes: span.attributes,
status: span.status,
events: span.events,
links: span.links,
};
}
/**
* Showing spans in console
* @param spans
* @param done
*/
_sendSpans(spans, done) {
for (const span of spans) {
console.dir(this._exportInfo(span), { depth: 3 });
}
if (done) {
return done({ code: core_1.ExportResultCode.SUCCESS });
}
}
}
exports.ConsoleSpanExporter = ConsoleSpanExporter;
//# sourceMappingURL=ConsoleSpanExporter.js.map

View File

@@ -0,0 +1,60 @@
"use strict";
/*
* Copyright The OpenTelemetry Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.InMemorySpanExporter = void 0;
const core_1 = require("@opentelemetry/core");
/**
* This class can be used for testing purposes. It stores the exported spans
* in a list in memory that can be retrieved using the `getFinishedSpans()`
* method.
*/
class InMemorySpanExporter {
_finishedSpans = [];
/**
* Indicates if the exporter has been "shutdown."
* When false, exported spans will not be stored in-memory.
*/
_stopped = false;
export(spans, resultCallback) {
if (this._stopped)
return resultCallback({
code: core_1.ExportResultCode.FAILED,
error: new Error('Exporter has been stopped'),
});
this._finishedSpans.push(...spans);
setTimeout(() => resultCallback({ code: core_1.ExportResultCode.SUCCESS }), 0);
}
shutdown() {
this._stopped = true;
this._finishedSpans = [];
return this.forceFlush();
}
/**
* Exports any pending spans in the exporter
*/
forceFlush() {
return Promise.resolve();
}
reset() {
this._finishedSpans = [];
}
getFinishedSpans() {
return this._finishedSpans;
}
}
exports.InMemorySpanExporter = InMemorySpanExporter;
//# sourceMappingURL=InMemorySpanExporter.js.map

View File

@@ -0,0 +1,31 @@
"use strict";
/*
* Copyright The OpenTelemetry Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.NoopSpanProcessor = void 0;
/** No-op implementation of SpanProcessor */
class NoopSpanProcessor {
onStart(_span, _context) { }
onEnd(_span) { }
shutdown() {
return Promise.resolve();
}
forceFlush() {
return Promise.resolve();
}
}
exports.NoopSpanProcessor = NoopSpanProcessor;
//# sourceMappingURL=NoopSpanProcessor.js.map

View File

@@ -0,0 +1,76 @@
"use strict";
/*
* Copyright The OpenTelemetry Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.SimpleSpanProcessor = void 0;
const api_1 = require("@opentelemetry/api");
const core_1 = require("@opentelemetry/core");
/**
* An implementation of the {@link SpanProcessor} that converts the {@link Span}
* to {@link ReadableSpan} and passes it to the configured exporter.
*
* Only spans that are sampled are converted.
*
* NOTE: This {@link SpanProcessor} exports every ended span individually instead of batching spans together, which causes significant performance overhead with most exporters. For production use, please consider using the {@link BatchSpanProcessor} instead.
*/
class SimpleSpanProcessor {
_exporter;
_shutdownOnce;
_pendingExports;
constructor(_exporter) {
this._exporter = _exporter;
this._shutdownOnce = new core_1.BindOnceFuture(this._shutdown, this);
this._pendingExports = new Set();
}
async forceFlush() {
await Promise.all(Array.from(this._pendingExports));
if (this._exporter.forceFlush) {
await this._exporter.forceFlush();
}
}
onStart(_span, _parentContext) { }
onEnd(span) {
if (this._shutdownOnce.isCalled) {
return;
}
if ((span.spanContext().traceFlags & api_1.TraceFlags.SAMPLED) === 0) {
return;
}
const pendingExport = this._doExport(span).catch(err => (0, core_1.globalErrorHandler)(err));
// Enqueue this export to the pending list so it can be flushed by the user.
this._pendingExports.add(pendingExport);
void pendingExport.finally(() => this._pendingExports.delete(pendingExport));
}
async _doExport(span) {
if (span.resource.asyncAttributesPending) {
// Ensure resource is fully resolved before exporting.
await span.resource.waitForAsyncAttributes?.();
}
const result = await core_1.internal._export(this._exporter, [span]);
if (result.code !== core_1.ExportResultCode.SUCCESS) {
throw (result.error ??
new Error(`SimpleSpanProcessor: span export failed (status ${result})`));
}
}
shutdown() {
return this._shutdownOnce.call();
}
_shutdown() {
return this._exporter.shutdown();
}
}
exports.SimpleSpanProcessor = SimpleSpanProcessor;
//# sourceMappingURL=SimpleSpanProcessor.js.map

View File

@@ -0,0 +1,42 @@
"use strict";
/*
* Copyright The OpenTelemetry Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.SamplingDecision = exports.TraceIdRatioBasedSampler = exports.ParentBasedSampler = exports.AlwaysOnSampler = exports.AlwaysOffSampler = exports.NoopSpanProcessor = exports.SimpleSpanProcessor = exports.InMemorySpanExporter = exports.ConsoleSpanExporter = exports.RandomIdGenerator = exports.BatchSpanProcessor = exports.BasicTracerProvider = void 0;
var BasicTracerProvider_1 = require("./BasicTracerProvider");
Object.defineProperty(exports, "BasicTracerProvider", { enumerable: true, get: function () { return BasicTracerProvider_1.BasicTracerProvider; } });
var platform_1 = require("./platform");
Object.defineProperty(exports, "BatchSpanProcessor", { enumerable: true, get: function () { return platform_1.BatchSpanProcessor; } });
Object.defineProperty(exports, "RandomIdGenerator", { enumerable: true, get: function () { return platform_1.RandomIdGenerator; } });
var ConsoleSpanExporter_1 = require("./export/ConsoleSpanExporter");
Object.defineProperty(exports, "ConsoleSpanExporter", { enumerable: true, get: function () { return ConsoleSpanExporter_1.ConsoleSpanExporter; } });
var InMemorySpanExporter_1 = require("./export/InMemorySpanExporter");
Object.defineProperty(exports, "InMemorySpanExporter", { enumerable: true, get: function () { return InMemorySpanExporter_1.InMemorySpanExporter; } });
var SimpleSpanProcessor_1 = require("./export/SimpleSpanProcessor");
Object.defineProperty(exports, "SimpleSpanProcessor", { enumerable: true, get: function () { return SimpleSpanProcessor_1.SimpleSpanProcessor; } });
var NoopSpanProcessor_1 = require("./export/NoopSpanProcessor");
Object.defineProperty(exports, "NoopSpanProcessor", { enumerable: true, get: function () { return NoopSpanProcessor_1.NoopSpanProcessor; } });
var AlwaysOffSampler_1 = require("./sampler/AlwaysOffSampler");
Object.defineProperty(exports, "AlwaysOffSampler", { enumerable: true, get: function () { return AlwaysOffSampler_1.AlwaysOffSampler; } });
var AlwaysOnSampler_1 = require("./sampler/AlwaysOnSampler");
Object.defineProperty(exports, "AlwaysOnSampler", { enumerable: true, get: function () { return AlwaysOnSampler_1.AlwaysOnSampler; } });
var ParentBasedSampler_1 = require("./sampler/ParentBasedSampler");
Object.defineProperty(exports, "ParentBasedSampler", { enumerable: true, get: function () { return ParentBasedSampler_1.ParentBasedSampler; } });
var TraceIdRatioBasedSampler_1 = require("./sampler/TraceIdRatioBasedSampler");
Object.defineProperty(exports, "TraceIdRatioBasedSampler", { enumerable: true, get: function () { return TraceIdRatioBasedSampler_1.TraceIdRatioBasedSampler; } });
var Sampler_1 = require("./Sampler");
Object.defineProperty(exports, "SamplingDecision", { enumerable: true, get: function () { return Sampler_1.SamplingDecision; } });
//# sourceMappingURL=index.js.map

View File

@@ -0,0 +1,22 @@
"use strict";
/*
* Copyright The OpenTelemetry Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.RandomIdGenerator = exports.BatchSpanProcessor = void 0;
var node_1 = require("./node");
Object.defineProperty(exports, "BatchSpanProcessor", { enumerable: true, get: function () { return node_1.BatchSpanProcessor; } });
Object.defineProperty(exports, "RandomIdGenerator", { enumerable: true, get: function () { return node_1.RandomIdGenerator; } });
//# sourceMappingURL=index.js.map

View File

@@ -0,0 +1,54 @@
"use strict";
/*
* Copyright The OpenTelemetry Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.RandomIdGenerator = void 0;
const SPAN_ID_BYTES = 8;
const TRACE_ID_BYTES = 16;
class RandomIdGenerator {
/**
* Returns a random 16-byte trace ID formatted/encoded as a 32 lowercase hex
* characters corresponding to 128 bits.
*/
generateTraceId = getIdGenerator(TRACE_ID_BYTES);
/**
* Returns a random 8-byte span ID formatted/encoded as a 16 lowercase hex
* characters corresponding to 64 bits.
*/
generateSpanId = getIdGenerator(SPAN_ID_BYTES);
}
exports.RandomIdGenerator = RandomIdGenerator;
const SHARED_BUFFER = Buffer.allocUnsafe(TRACE_ID_BYTES);
function getIdGenerator(bytes) {
return function generateId() {
for (let i = 0; i < bytes / 4; i++) {
// unsigned right shift drops decimal part of the number
// it is required because if a number between 2**32 and 2**32 - 1 is generated, an out of range error is thrown by writeUInt32BE
SHARED_BUFFER.writeUInt32BE((Math.random() * 2 ** 32) >>> 0, i * 4);
}
// If buffer is all 0, set the last byte to 1 to guarantee a valid w3c id is generated
for (let i = 0; i < bytes; i++) {
if (SHARED_BUFFER[i] > 0) {
break;
}
else if (i === bytes - 1) {
SHARED_BUFFER[bytes - 1] = 1;
}
}
return SHARED_BUFFER.toString('hex', 0, bytes);
};
}
//# sourceMappingURL=RandomIdGenerator.js.map

View File

@@ -0,0 +1,24 @@
"use strict";
/*
* Copyright The OpenTelemetry Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.BatchSpanProcessor = void 0;
const BatchSpanProcessorBase_1 = require("../../../export/BatchSpanProcessorBase");
class BatchSpanProcessor extends BatchSpanProcessorBase_1.BatchSpanProcessorBase {
onShutdown() { }
}
exports.BatchSpanProcessor = BatchSpanProcessor;
//# sourceMappingURL=BatchSpanProcessor.js.map

View File

@@ -0,0 +1,23 @@
"use strict";
/*
* Copyright The OpenTelemetry Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.RandomIdGenerator = exports.BatchSpanProcessor = void 0;
var BatchSpanProcessor_1 = require("./export/BatchSpanProcessor");
Object.defineProperty(exports, "BatchSpanProcessor", { enumerable: true, get: function () { return BatchSpanProcessor_1.BatchSpanProcessor; } });
var RandomIdGenerator_1 = require("./RandomIdGenerator");
Object.defineProperty(exports, "RandomIdGenerator", { enumerable: true, get: function () { return RandomIdGenerator_1.RandomIdGenerator; } });
//# sourceMappingURL=index.js.map

View File

@@ -0,0 +1,32 @@
"use strict";
/*
* Copyright The OpenTelemetry Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.AlwaysOffSampler = void 0;
const Sampler_1 = require("../Sampler");
/** Sampler that samples no traces. */
class AlwaysOffSampler {
shouldSample() {
return {
decision: Sampler_1.SamplingDecision.NOT_RECORD,
};
}
toString() {
return 'AlwaysOffSampler';
}
}
exports.AlwaysOffSampler = AlwaysOffSampler;
//# sourceMappingURL=AlwaysOffSampler.js.map

View File

@@ -0,0 +1,32 @@
"use strict";
/*
* Copyright The OpenTelemetry Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.AlwaysOnSampler = void 0;
const Sampler_1 = require("../Sampler");
/** Sampler that samples all traces. */
class AlwaysOnSampler {
shouldSample() {
return {
decision: Sampler_1.SamplingDecision.RECORD_AND_SAMPLED,
};
}
toString() {
return 'AlwaysOnSampler';
}
}
exports.AlwaysOnSampler = AlwaysOnSampler;
//# sourceMappingURL=AlwaysOnSampler.js.map

View File

@@ -0,0 +1,69 @@
"use strict";
/*
* Copyright The OpenTelemetry Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.ParentBasedSampler = void 0;
const api_1 = require("@opentelemetry/api");
const core_1 = require("@opentelemetry/core");
const AlwaysOffSampler_1 = require("./AlwaysOffSampler");
const AlwaysOnSampler_1 = require("./AlwaysOnSampler");
/**
* A composite sampler that either respects the parent span's sampling decision
* or delegates to `delegateSampler` for root spans.
*/
class ParentBasedSampler {
_root;
_remoteParentSampled;
_remoteParentNotSampled;
_localParentSampled;
_localParentNotSampled;
constructor(config) {
this._root = config.root;
if (!this._root) {
(0, core_1.globalErrorHandler)(new Error('ParentBasedSampler must have a root sampler configured'));
this._root = new AlwaysOnSampler_1.AlwaysOnSampler();
}
this._remoteParentSampled =
config.remoteParentSampled ?? new AlwaysOnSampler_1.AlwaysOnSampler();
this._remoteParentNotSampled =
config.remoteParentNotSampled ?? new AlwaysOffSampler_1.AlwaysOffSampler();
this._localParentSampled =
config.localParentSampled ?? new AlwaysOnSampler_1.AlwaysOnSampler();
this._localParentNotSampled =
config.localParentNotSampled ?? new AlwaysOffSampler_1.AlwaysOffSampler();
}
shouldSample(context, traceId, spanName, spanKind, attributes, links) {
const parentContext = api_1.trace.getSpanContext(context);
if (!parentContext || !(0, api_1.isSpanContextValid)(parentContext)) {
return this._root.shouldSample(context, traceId, spanName, spanKind, attributes, links);
}
if (parentContext.isRemote) {
if (parentContext.traceFlags & api_1.TraceFlags.SAMPLED) {
return this._remoteParentSampled.shouldSample(context, traceId, spanName, spanKind, attributes, links);
}
return this._remoteParentNotSampled.shouldSample(context, traceId, spanName, spanKind, attributes, links);
}
if (parentContext.traceFlags & api_1.TraceFlags.SAMPLED) {
return this._localParentSampled.shouldSample(context, traceId, spanName, spanKind, attributes, links);
}
return this._localParentNotSampled.shouldSample(context, traceId, spanName, spanKind, attributes, links);
}
toString() {
return `ParentBased{root=${this._root.toString()}, remoteParentSampled=${this._remoteParentSampled.toString()}, remoteParentNotSampled=${this._remoteParentNotSampled.toString()}, localParentSampled=${this._localParentSampled.toString()}, localParentNotSampled=${this._localParentNotSampled.toString()}}`;
}
}
exports.ParentBasedSampler = ParentBasedSampler;
//# sourceMappingURL=ParentBasedSampler.js.map

View File

@@ -0,0 +1,56 @@
"use strict";
/*
* Copyright The OpenTelemetry Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.TraceIdRatioBasedSampler = void 0;
const api_1 = require("@opentelemetry/api");
const Sampler_1 = require("../Sampler");
/** Sampler that samples a given fraction of traces based of trace id deterministically. */
class TraceIdRatioBasedSampler {
_ratio;
_upperBound;
constructor(_ratio = 0) {
this._ratio = _ratio;
this._ratio = this._normalize(_ratio);
this._upperBound = Math.floor(this._ratio * 0xffffffff);
}
shouldSample(context, traceId) {
return {
decision: (0, api_1.isValidTraceId)(traceId) && this._accumulate(traceId) < this._upperBound
? Sampler_1.SamplingDecision.RECORD_AND_SAMPLED
: Sampler_1.SamplingDecision.NOT_RECORD,
};
}
toString() {
return `TraceIdRatioBased{${this._ratio}}`;
}
_normalize(ratio) {
if (typeof ratio !== 'number' || isNaN(ratio))
return 0;
return ratio >= 1 ? 1 : ratio <= 0 ? 0 : ratio;
}
_accumulate(traceId) {
let accumulation = 0;
for (let i = 0; i < traceId.length / 8; i++) {
const pos = i * 8;
const part = parseInt(traceId.slice(pos, pos + 8), 16);
accumulation = (accumulation ^ part) >>> 0;
}
return accumulation;
}
}
exports.TraceIdRatioBasedSampler = TraceIdRatioBasedSampler;
//# sourceMappingURL=TraceIdRatioBasedSampler.js.map

View File

@@ -0,0 +1,66 @@
"use strict";
/*
* Copyright The OpenTelemetry Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.reconfigureLimits = exports.mergeConfig = exports.DEFAULT_ATTRIBUTE_VALUE_LENGTH_LIMIT = exports.DEFAULT_ATTRIBUTE_COUNT_LIMIT = void 0;
const config_1 = require("./config");
const core_1 = require("@opentelemetry/core");
exports.DEFAULT_ATTRIBUTE_COUNT_LIMIT = 128;
exports.DEFAULT_ATTRIBUTE_VALUE_LENGTH_LIMIT = Infinity;
/**
* Function to merge Default configuration (as specified in './config') with
* user provided configurations.
*/
function mergeConfig(userConfig) {
const perInstanceDefaults = {
sampler: (0, config_1.buildSamplerFromEnv)(),
};
const DEFAULT_CONFIG = (0, config_1.loadDefaultConfig)();
const target = Object.assign({}, DEFAULT_CONFIG, perInstanceDefaults, userConfig);
target.generalLimits = Object.assign({}, DEFAULT_CONFIG.generalLimits, userConfig.generalLimits || {});
target.spanLimits = Object.assign({}, DEFAULT_CONFIG.spanLimits, userConfig.spanLimits || {});
return target;
}
exports.mergeConfig = mergeConfig;
/**
* When general limits are provided and model specific limits are not,
* configures the model specific limits by using the values from the general ones.
* @param userConfig User provided tracer configuration
*/
function reconfigureLimits(userConfig) {
const spanLimits = Object.assign({}, userConfig.spanLimits);
/**
* Reassign span attribute count limit to use first non null value defined by user or use default value
*/
spanLimits.attributeCountLimit =
userConfig.spanLimits?.attributeCountLimit ??
userConfig.generalLimits?.attributeCountLimit ??
(0, core_1.getNumberFromEnv)('OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT') ??
(0, core_1.getNumberFromEnv)('OTEL_ATTRIBUTE_COUNT_LIMIT') ??
exports.DEFAULT_ATTRIBUTE_COUNT_LIMIT;
/**
* Reassign span attribute value length limit to use first non null value defined by user or use default value
*/
spanLimits.attributeValueLengthLimit =
userConfig.spanLimits?.attributeValueLengthLimit ??
userConfig.generalLimits?.attributeValueLengthLimit ??
(0, core_1.getNumberFromEnv)('OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT') ??
(0, core_1.getNumberFromEnv)('OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT') ??
exports.DEFAULT_ATTRIBUTE_VALUE_LENGTH_LIMIT;
return Object.assign({}, userConfig, { spanLimits });
}
exports.reconfigureLimits = reconfigureLimits;
//# sourceMappingURL=utility.js.map