@glasstrace/sdk 0.20.0 → 0.20.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/chunk-BT2OCXCG.js +178 -0
- package/dist/chunk-BT2OCXCG.js.map +1 -0
- package/dist/{chunk-F2TZRBEH.js → chunk-DO2YPMQ5.js} +9 -181
- package/dist/chunk-DO2YPMQ5.js.map +1 -0
- package/dist/{chunk-YPXW2TN3.js → chunk-IP4NMDJK.js} +2 -2
- package/dist/{chunk-VN3GZDV6.js → chunk-IQN6TRMQ.js} +2 -2
- package/dist/{chunk-6JRI4OGB.js → chunk-LU3PPAOQ.js} +5 -3
- package/dist/{chunk-6JRI4OGB.js.map → chunk-LU3PPAOQ.js.map} +1 -1
- package/dist/chunk-R4DAIPXD.js +4461 -0
- package/dist/chunk-R4DAIPXD.js.map +1 -0
- package/dist/{chunk-5N2IR4EO.js → chunk-TQ54WLCZ.js} +1 -1
- package/dist/{chunk-5N2IR4EO.js.map → chunk-TQ54WLCZ.js.map} +1 -1
- package/dist/chunk-Z2EGETTT.js +204 -0
- package/dist/chunk-Z2EGETTT.js.map +1 -0
- package/dist/cli/init.cjs +5 -3
- package/dist/cli/init.cjs.map +1 -1
- package/dist/cli/init.js +8 -6
- package/dist/cli/init.js.map +1 -1
- package/dist/cli/mcp-add.cjs.map +1 -1
- package/dist/cli/mcp-add.js +2 -2
- package/dist/cli/uninit.cjs +3 -1
- package/dist/cli/uninit.cjs.map +1 -1
- package/dist/cli/uninit.js +2 -2
- package/dist/edge-entry-Ds2fNOeh.d.ts +157 -0
- package/dist/edge-entry-FJFKkeFF.d.cts +157 -0
- package/dist/edge-entry.cjs +14939 -0
- package/dist/edge-entry.cjs.map +1 -0
- package/dist/edge-entry.d.cts +6 -0
- package/dist/edge-entry.d.ts +6 -0
- package/dist/edge-entry.js +16 -0
- package/dist/index.cjs +4 -4
- package/dist/index.cjs.map +1 -1
- package/dist/index.d-DgeH-pNJ.d.cts +191 -0
- package/dist/index.d-DgeH-pNJ.d.ts +191 -0
- package/dist/index.d.cts +9 -461
- package/dist/index.d.ts +9 -461
- package/dist/index.js +32 -4618
- package/dist/index.js.map +1 -1
- package/dist/node-entry.cjs +22492 -0
- package/dist/node-entry.cjs.map +1 -0
- package/dist/node-entry.d.cts +10 -0
- package/dist/node-entry.d.ts +10 -0
- package/dist/node-entry.js +101 -0
- package/dist/node-entry.js.map +1 -0
- package/dist/node-subpath.cjs +14506 -0
- package/dist/node-subpath.cjs.map +1 -0
- package/dist/node-subpath.d.cts +132 -0
- package/dist/node-subpath.d.ts +132 -0
- package/dist/node-subpath.js +30 -0
- package/dist/node-subpath.js.map +1 -0
- package/dist/{source-map-uploader-VPDZWWM2.js → source-map-uploader-YXWO6JLN.js} +3 -3
- package/dist/source-map-uploader-YXWO6JLN.js.map +1 -0
- package/package.json +4 -1
- package/dist/chunk-F2TZRBEH.js.map +0 -1
- /package/dist/{chunk-YPXW2TN3.js.map → chunk-IP4NMDJK.js.map} +0 -0
- /package/dist/{chunk-VN3GZDV6.js.map → chunk-IQN6TRMQ.js.map} +0 -0
- /package/dist/{source-map-uploader-VPDZWWM2.js.map → edge-entry.js.map} +0 -0
package/dist/index.js
CHANGED
|
@@ -1,34 +1,47 @@
|
|
|
1
|
+
import {
|
|
2
|
+
GlasstraceExporter,
|
|
3
|
+
SessionManager,
|
|
4
|
+
captureError,
|
|
5
|
+
classifyFetchTarget,
|
|
6
|
+
createGlasstraceSpanProcessor,
|
|
7
|
+
getDateString,
|
|
8
|
+
getDiscoveryHandler,
|
|
9
|
+
getOrigin,
|
|
10
|
+
getStatus,
|
|
11
|
+
isReady,
|
|
12
|
+
registerGlasstrace,
|
|
13
|
+
waitForReady,
|
|
14
|
+
withGlasstraceConfig
|
|
15
|
+
} from "./chunk-R4DAIPXD.js";
|
|
16
|
+
import {
|
|
17
|
+
GlasstraceSpanProcessor,
|
|
18
|
+
SdkError,
|
|
19
|
+
captureCorrelationId,
|
|
20
|
+
createDiscoveryHandler
|
|
21
|
+
} from "./chunk-Z2EGETTT.js";
|
|
22
|
+
import "./chunk-DQ25VOKK.js";
|
|
1
23
|
import {
|
|
2
24
|
PRESIGNED_THRESHOLD_BYTES,
|
|
3
25
|
collectSourceMaps,
|
|
4
26
|
computeBuildHash,
|
|
5
27
|
discoverSourceMapFiles,
|
|
6
|
-
installConsoleCapture,
|
|
7
|
-
maybeShowMcpNudge,
|
|
8
|
-
maybeShowServerActionNudge,
|
|
9
|
-
sdkLog,
|
|
10
28
|
uploadSourceMaps,
|
|
11
29
|
uploadSourceMapsAuto,
|
|
12
30
|
uploadSourceMapsPresigned
|
|
13
|
-
} from "./chunk-
|
|
31
|
+
} from "./chunk-IQN6TRMQ.js";
|
|
14
32
|
import {
|
|
15
|
-
_setCurrentConfig,
|
|
16
|
-
buildImportGraph,
|
|
17
|
-
collectHealthReport,
|
|
18
|
-
consumeRateLimitFlag,
|
|
19
|
-
didLastInitSucceed,
|
|
20
|
-
discoverTestFiles,
|
|
21
|
-
extractImports,
|
|
22
33
|
getActiveConfig,
|
|
23
|
-
getClaimResult,
|
|
24
34
|
getLinkedAccountId,
|
|
25
35
|
loadCachedConfig,
|
|
26
36
|
performInit,
|
|
27
|
-
recordSpansDropped,
|
|
28
|
-
recordSpansExported,
|
|
29
37
|
saveCachedConfig,
|
|
30
38
|
sendInitRequest
|
|
31
|
-
} from "./chunk-
|
|
39
|
+
} from "./chunk-DO2YPMQ5.js";
|
|
40
|
+
import {
|
|
41
|
+
buildImportGraph,
|
|
42
|
+
discoverTestFiles,
|
|
43
|
+
extractImports
|
|
44
|
+
} from "./chunk-BT2OCXCG.js";
|
|
32
45
|
import {
|
|
33
46
|
isAnonymousMode,
|
|
34
47
|
isProductionDisabled,
|
|
@@ -38,4610 +51,11 @@ import {
|
|
|
38
51
|
import {
|
|
39
52
|
getOrCreateAnonKey,
|
|
40
53
|
readAnonKey
|
|
41
|
-
} from "./chunk-
|
|
54
|
+
} from "./chunk-IP4NMDJK.js";
|
|
42
55
|
import {
|
|
43
|
-
GLASSTRACE_ATTRIBUTE_NAMES,
|
|
44
56
|
deriveSessionId
|
|
45
|
-
} from "./chunk-
|
|
46
|
-
import
|
|
47
|
-
DiagLogLevel,
|
|
48
|
-
INVALID_SPAN_CONTEXT,
|
|
49
|
-
ROOT_CONTEXT,
|
|
50
|
-
SamplingDecision,
|
|
51
|
-
SpanKind,
|
|
52
|
-
SpanStatusCode,
|
|
53
|
-
TraceFlags,
|
|
54
|
-
baggageEntryMetadataFromString,
|
|
55
|
-
context,
|
|
56
|
-
createContextKey,
|
|
57
|
-
createNoopMeter,
|
|
58
|
-
diag,
|
|
59
|
-
isSpanContextValid,
|
|
60
|
-
isValidTraceId,
|
|
61
|
-
trace
|
|
62
|
-
} from "./chunk-DQ25VOKK.js";
|
|
63
|
-
import {
|
|
64
|
-
__require
|
|
65
|
-
} from "./chunk-NSBPE2FW.js";
|
|
66
|
-
|
|
67
|
-
// src/errors.ts
|
|
68
|
-
var SdkError = class extends Error {
|
|
69
|
-
code;
|
|
70
|
-
constructor(code, message, cause) {
|
|
71
|
-
super(message, { cause });
|
|
72
|
-
this.name = "SdkError";
|
|
73
|
-
this.code = code;
|
|
74
|
-
}
|
|
75
|
-
};
|
|
76
|
-
|
|
77
|
-
// src/session.ts
|
|
78
|
-
var FOUR_HOURS_MS = 4 * 60 * 60 * 1e3;
|
|
79
|
-
var cachedGlasstraceEnv = process.env.GLASSTRACE_ENV;
|
|
80
|
-
var cachedPort = process.env.PORT ?? "3000";
|
|
81
|
-
function getOrigin() {
|
|
82
|
-
if (cachedGlasstraceEnv) {
|
|
83
|
-
return cachedGlasstraceEnv;
|
|
84
|
-
}
|
|
85
|
-
return `localhost:${cachedPort}`;
|
|
86
|
-
}
|
|
87
|
-
function getDateString() {
|
|
88
|
-
const now = /* @__PURE__ */ new Date();
|
|
89
|
-
const year = now.getUTCFullYear();
|
|
90
|
-
const month = String(now.getUTCMonth() + 1).padStart(2, "0");
|
|
91
|
-
const day = String(now.getUTCDate()).padStart(2, "0");
|
|
92
|
-
return `${year}-${month}-${day}`;
|
|
93
|
-
}
|
|
94
|
-
var SessionManager = class {
|
|
95
|
-
windowIndex = 0;
|
|
96
|
-
lastActivityTimestamp = 0;
|
|
97
|
-
lastDate = "";
|
|
98
|
-
lastApiKey = "";
|
|
99
|
-
currentSessionId = null;
|
|
100
|
-
/**
|
|
101
|
-
* Returns the current session ID, deriving a new one if:
|
|
102
|
-
* - More than 4 hours have elapsed since last activity
|
|
103
|
-
* - The UTC date has changed (resets window index to 0)
|
|
104
|
-
* - The API key has changed (e.g., deferred anonymous key swap)
|
|
105
|
-
* - This is the first call
|
|
106
|
-
*
|
|
107
|
-
* @param apiKey - The project's API key used in session derivation.
|
|
108
|
-
* @returns The current or newly derived SessionId.
|
|
109
|
-
*/
|
|
110
|
-
getSessionId(apiKey) {
|
|
111
|
-
const now = Date.now();
|
|
112
|
-
const currentDate = getDateString();
|
|
113
|
-
const origin = getOrigin();
|
|
114
|
-
const elapsed = now - this.lastActivityTimestamp;
|
|
115
|
-
const dateChanged = currentDate !== this.lastDate;
|
|
116
|
-
const apiKeyChanged = apiKey !== this.lastApiKey;
|
|
117
|
-
if (dateChanged) {
|
|
118
|
-
this.windowIndex = 0;
|
|
119
|
-
this.lastDate = currentDate;
|
|
120
|
-
this.lastApiKey = apiKey;
|
|
121
|
-
this.currentSessionId = deriveSessionId(apiKey, origin, currentDate, this.windowIndex);
|
|
122
|
-
} else if (apiKeyChanged) {
|
|
123
|
-
this.lastApiKey = apiKey;
|
|
124
|
-
this.currentSessionId = deriveSessionId(apiKey, origin, currentDate, this.windowIndex);
|
|
125
|
-
} else if (this.currentSessionId === null || elapsed > FOUR_HOURS_MS) {
|
|
126
|
-
if (this.currentSessionId !== null) {
|
|
127
|
-
this.windowIndex++;
|
|
128
|
-
}
|
|
129
|
-
this.lastApiKey = apiKey;
|
|
130
|
-
this.currentSessionId = deriveSessionId(apiKey, origin, currentDate, this.windowIndex);
|
|
131
|
-
this.lastDate = currentDate;
|
|
132
|
-
}
|
|
133
|
-
this.lastActivityTimestamp = now;
|
|
134
|
-
return this.currentSessionId;
|
|
135
|
-
}
|
|
136
|
-
};
|
|
137
|
-
|
|
138
|
-
// src/fetch-classifier.ts
|
|
139
|
-
var cachedPort2 = process.env.PORT ?? "3000";
|
|
140
|
-
function classifyFetchTarget(url) {
|
|
141
|
-
let parsed;
|
|
142
|
-
try {
|
|
143
|
-
parsed = new URL(url);
|
|
144
|
-
} catch {
|
|
145
|
-
return "unknown";
|
|
146
|
-
}
|
|
147
|
-
const hostname = parsed.hostname.toLowerCase();
|
|
148
|
-
if (hostname === "supabase.co" || hostname.endsWith(".supabase.co") || hostname === "supabase.in" || hostname.endsWith(".supabase.in")) {
|
|
149
|
-
return "supabase";
|
|
150
|
-
}
|
|
151
|
-
if (hostname === "stripe.com" || hostname.endsWith(".stripe.com")) {
|
|
152
|
-
return "stripe";
|
|
153
|
-
}
|
|
154
|
-
const internalOrigin = `localhost:${cachedPort2}`;
|
|
155
|
-
const parsedPort = parsed.port || (parsed.protocol === "https:" ? "443" : "80");
|
|
156
|
-
const urlOrigin = `${hostname}:${parsedPort}`;
|
|
157
|
-
if (urlOrigin === internalOrigin) {
|
|
158
|
-
return "internal";
|
|
159
|
-
}
|
|
160
|
-
return "unknown";
|
|
161
|
-
}
|
|
162
|
-
|
|
163
|
-
// src/span-processor.ts
|
|
164
|
-
var GlasstraceSpanProcessor = class {
|
|
165
|
-
wrappedProcessor;
|
|
166
|
-
/* eslint-disable @typescript-eslint/no-unused-vars -- backward compat signature */
|
|
167
|
-
constructor(wrappedProcessor, _sessionManager2, _apiKey, _getConfig, _environment) {
|
|
168
|
-
this.wrappedProcessor = wrappedProcessor;
|
|
169
|
-
}
|
|
170
|
-
onStart(span, parentContext) {
|
|
171
|
-
this.wrappedProcessor.onStart(span, parentContext);
|
|
172
|
-
}
|
|
173
|
-
onEnd(readableSpan) {
|
|
174
|
-
this.wrappedProcessor.onEnd(readableSpan);
|
|
175
|
-
}
|
|
176
|
-
async shutdown() {
|
|
177
|
-
return this.wrappedProcessor.shutdown();
|
|
178
|
-
}
|
|
179
|
-
async forceFlush() {
|
|
180
|
-
return this.wrappedProcessor.forceFlush();
|
|
181
|
-
}
|
|
182
|
-
};
|
|
183
|
-
|
|
184
|
-
// src/enriching-exporter.ts
|
|
185
|
-
var ATTR = GLASSTRACE_ATTRIBUTE_NAMES;
|
|
186
|
-
var API_KEY_PENDING = "pending";
|
|
187
|
-
var MAX_PENDING_SPANS = 1024;
|
|
188
|
-
var GlasstraceExporter = class {
|
|
189
|
-
getApiKey;
|
|
190
|
-
sessionManager;
|
|
191
|
-
getConfig;
|
|
192
|
-
environment;
|
|
193
|
-
endpointUrl;
|
|
194
|
-
createDelegateFn;
|
|
195
|
-
verbose;
|
|
196
|
-
delegate = null;
|
|
197
|
-
delegateKey = null;
|
|
198
|
-
pendingBatches = [];
|
|
199
|
-
pendingSpanCount = 0;
|
|
200
|
-
overflowLogged = false;
|
|
201
|
-
constructor(options) {
|
|
202
|
-
this.getApiKey = options.getApiKey;
|
|
203
|
-
this.sessionManager = options.sessionManager;
|
|
204
|
-
this.getConfig = options.getConfig;
|
|
205
|
-
this.environment = options.environment;
|
|
206
|
-
this.endpointUrl = options.endpointUrl;
|
|
207
|
-
this.createDelegateFn = options.createDelegate;
|
|
208
|
-
this.verbose = options.verbose ?? false;
|
|
209
|
-
this[/* @__PURE__ */ Symbol.for("glasstrace.exporter")] = true;
|
|
210
|
-
}
|
|
211
|
-
export(spans, resultCallback) {
|
|
212
|
-
const currentKey = this.getApiKey();
|
|
213
|
-
if (currentKey === API_KEY_PENDING) {
|
|
214
|
-
this.bufferSpans(spans, resultCallback);
|
|
215
|
-
return;
|
|
216
|
-
}
|
|
217
|
-
const enrichedSpans = spans.map((span) => this.enrichSpan(span));
|
|
218
|
-
const exporter = this.ensureDelegate();
|
|
219
|
-
if (exporter) {
|
|
220
|
-
exporter.export(enrichedSpans, (result) => {
|
|
221
|
-
if (result.code !== 0) {
|
|
222
|
-
sdkLog("warn", `[glasstrace] Span export failed: ${result.error?.message ?? "unknown error"}`);
|
|
223
|
-
}
|
|
224
|
-
resultCallback(result);
|
|
225
|
-
});
|
|
226
|
-
recordSpansExported(enrichedSpans.length);
|
|
227
|
-
} else {
|
|
228
|
-
recordSpansDropped(enrichedSpans.length);
|
|
229
|
-
resultCallback({ code: 0 });
|
|
230
|
-
}
|
|
231
|
-
}
|
|
232
|
-
/**
|
|
233
|
-
* Called when the API key transitions from "pending" to a resolved value.
|
|
234
|
-
* Creates the delegate exporter and flushes all buffered spans.
|
|
235
|
-
*/
|
|
236
|
-
notifyKeyResolved() {
|
|
237
|
-
this.flushPending();
|
|
238
|
-
}
|
|
239
|
-
async shutdown() {
|
|
240
|
-
const currentKey = this.getApiKey();
|
|
241
|
-
if (currentKey !== API_KEY_PENDING && this.pendingBatches.length > 0) {
|
|
242
|
-
this.flushPending();
|
|
243
|
-
} else if (this.pendingBatches.length > 0) {
|
|
244
|
-
console.warn(
|
|
245
|
-
`[glasstrace] Shutdown with ${this.pendingSpanCount} buffered spans \u2014 API key never resolved, spans lost.`
|
|
246
|
-
);
|
|
247
|
-
recordSpansDropped(this.pendingSpanCount);
|
|
248
|
-
for (const batch of this.pendingBatches) {
|
|
249
|
-
batch.resultCallback({ code: 0 });
|
|
250
|
-
}
|
|
251
|
-
this.pendingBatches = [];
|
|
252
|
-
this.pendingSpanCount = 0;
|
|
253
|
-
}
|
|
254
|
-
if (this.delegate) {
|
|
255
|
-
return this.delegate.shutdown();
|
|
256
|
-
}
|
|
257
|
-
}
|
|
258
|
-
/**
|
|
259
|
-
* Flushes any pending buffered spans (if the API key has resolved) and
|
|
260
|
-
* delegates to the underlying exporter's forceFlush to drain its queue.
|
|
261
|
-
*/
|
|
262
|
-
forceFlush() {
|
|
263
|
-
if (this.getApiKey() !== API_KEY_PENDING && this.pendingBatches.length > 0) {
|
|
264
|
-
this.flushPending();
|
|
265
|
-
}
|
|
266
|
-
if (this.delegate?.forceFlush) {
|
|
267
|
-
return this.delegate.forceFlush();
|
|
268
|
-
}
|
|
269
|
-
return Promise.resolve();
|
|
270
|
-
}
|
|
271
|
-
/**
|
|
272
|
-
* Enriches a ReadableSpan with all glasstrace.* attributes.
|
|
273
|
-
* Returns a new ReadableSpan wrapper; the original span is not mutated.
|
|
274
|
-
*
|
|
275
|
-
* Only {@link SessionManager.getSessionId} is individually guarded because
|
|
276
|
-
* it calls into crypto and schema validation — a session ID failure should
|
|
277
|
-
* not prevent the rest of enrichment. The other helper calls
|
|
278
|
-
* ({@link deriveErrorCategory}, {@link deriveOrmProvider},
|
|
279
|
-
* {@link classifyFetchTarget}) are pure functions on typed string inputs
|
|
280
|
-
* and rely on the outer catch for any unexpected failure.
|
|
281
|
-
*
|
|
282
|
-
* On total failure, returns the original span unchanged.
|
|
283
|
-
*/
|
|
284
|
-
enrichSpan(span) {
|
|
285
|
-
try {
|
|
286
|
-
const attrs = span.attributes ?? {};
|
|
287
|
-
const name = span.name ?? "";
|
|
288
|
-
const extra = {};
|
|
289
|
-
extra[ATTR.TRACE_TYPE] = "server";
|
|
290
|
-
try {
|
|
291
|
-
const sessionId = this.sessionManager.getSessionId(this.getApiKey());
|
|
292
|
-
extra[ATTR.SESSION_ID] = sessionId;
|
|
293
|
-
} catch {
|
|
294
|
-
}
|
|
295
|
-
const env = this.environment ?? process.env.GLASSTRACE_ENV;
|
|
296
|
-
if (env) {
|
|
297
|
-
extra[ATTR.ENVIRONMENT] = env;
|
|
298
|
-
}
|
|
299
|
-
const existingCid = attrs["glasstrace.correlation.id"];
|
|
300
|
-
if (typeof existingCid === "string") {
|
|
301
|
-
extra[ATTR.CORRELATION_ID] = existingCid;
|
|
302
|
-
}
|
|
303
|
-
const rawRoute = attrs["http.route"];
|
|
304
|
-
const route = typeof rawRoute === "string" ? rawRoute : name;
|
|
305
|
-
if (route) {
|
|
306
|
-
extra[ATTR.ROUTE] = route;
|
|
307
|
-
}
|
|
308
|
-
const rawUrl = attrs["http.url"] ?? attrs["url.full"] ?? attrs["http.target"];
|
|
309
|
-
const trpcUrl = typeof rawUrl === "string" ? rawUrl : void 0;
|
|
310
|
-
if (trpcUrl) {
|
|
311
|
-
const trpcMatch = trpcUrl.match(/\/api\/trpc\/([^/?#]+)/);
|
|
312
|
-
if (trpcMatch) {
|
|
313
|
-
let procedure;
|
|
314
|
-
try {
|
|
315
|
-
procedure = decodeURIComponent(trpcMatch[1]);
|
|
316
|
-
} catch {
|
|
317
|
-
procedure = trpcMatch[1];
|
|
318
|
-
}
|
|
319
|
-
if (procedure) {
|
|
320
|
-
extra[ATTR.TRPC_PROCEDURE] = procedure;
|
|
321
|
-
}
|
|
322
|
-
}
|
|
323
|
-
}
|
|
324
|
-
const method = attrs["http.method"] ?? attrs["http.request.method"];
|
|
325
|
-
if (method) {
|
|
326
|
-
extra[ATTR.HTTP_METHOD] = method;
|
|
327
|
-
}
|
|
328
|
-
const actionRoute = extractLeadingPath(route);
|
|
329
|
-
if (method === "POST" && actionRoute) {
|
|
330
|
-
const isApiRoute = actionRoute === "/api" || actionRoute.startsWith("/api/");
|
|
331
|
-
const isInternalRoute = actionRoute.startsWith("/_next/");
|
|
332
|
-
if (!isApiRoute && !isInternalRoute) {
|
|
333
|
-
extra[ATTR.NEXT_ACTION_DETECTED] = true;
|
|
334
|
-
if (typeof extra[ATTR.CORRELATION_ID] !== "string") {
|
|
335
|
-
maybeShowServerActionNudge();
|
|
336
|
-
}
|
|
337
|
-
}
|
|
338
|
-
}
|
|
339
|
-
const statusCode = attrs["http.status_code"] ?? attrs["http.response.status_code"];
|
|
340
|
-
if (statusCode !== void 0) {
|
|
341
|
-
extra[ATTR.HTTP_STATUS_CODE] = statusCode;
|
|
342
|
-
}
|
|
343
|
-
const isErrorByStatus = span.status?.code === SpanStatusCode.ERROR;
|
|
344
|
-
const isErrorByEvent = hasExceptionEvent(span);
|
|
345
|
-
const isErrorByAttrs = typeof attrs["exception.type"] === "string" || typeof attrs["exception.message"] === "string";
|
|
346
|
-
const statusNotExplicitlyOK = span.status?.code !== SpanStatusCode.OK;
|
|
347
|
-
if (this.verbose && method) {
|
|
348
|
-
sdkLog(
|
|
349
|
-
"info",
|
|
350
|
-
`[glasstrace] enrichSpan "${name}": status.code=${span.status?.code}, http.status_code=${statusCode}, isErrorByStatus=${isErrorByStatus}, isErrorByEvent=${isErrorByEvent}, isErrorByAttrs=${isErrorByAttrs}`
|
|
351
|
-
);
|
|
352
|
-
}
|
|
353
|
-
if (method && statusNotExplicitlyOK && (isErrorByStatus || isErrorByEvent || isErrorByAttrs)) {
|
|
354
|
-
if (statusCode === void 0 || statusCode === 0 || statusCode === 200) {
|
|
355
|
-
const httpErrorType = attrs["error.type"];
|
|
356
|
-
if (typeof httpErrorType === "string") {
|
|
357
|
-
const parsed = parseInt(httpErrorType, 10);
|
|
358
|
-
if (!isNaN(parsed) && parsed >= 400 && parsed <= 599) {
|
|
359
|
-
extra[ATTR.HTTP_STATUS_CODE] = parsed;
|
|
360
|
-
} else {
|
|
361
|
-
extra[ATTR.HTTP_STATUS_CODE] = 500;
|
|
362
|
-
}
|
|
363
|
-
} else {
|
|
364
|
-
extra[ATTR.HTTP_STATUS_CODE] = 500;
|
|
365
|
-
}
|
|
366
|
-
if (this.verbose) {
|
|
367
|
-
sdkLog(
|
|
368
|
-
"info",
|
|
369
|
-
`[glasstrace] enrichSpan "${name}": inferred status_code=${extra[ATTR.HTTP_STATUS_CODE]} (was ${statusCode}), error.type=${attrs["error.type"]}`
|
|
370
|
-
);
|
|
371
|
-
}
|
|
372
|
-
}
|
|
373
|
-
}
|
|
374
|
-
if (span.startTime && span.endTime) {
|
|
375
|
-
const [startSec, startNano] = span.startTime;
|
|
376
|
-
const [endSec, endNano] = span.endTime;
|
|
377
|
-
const durationMs = (endSec - startSec) * 1e3 + (endNano - startNano) / 1e6;
|
|
378
|
-
if (durationMs >= 0) {
|
|
379
|
-
extra[ATTR.HTTP_DURATION_MS] = durationMs;
|
|
380
|
-
}
|
|
381
|
-
}
|
|
382
|
-
const eventDetails = statusNotExplicitlyOK ? getExceptionEventDetails(span) : { type: void 0, message: void 0 };
|
|
383
|
-
const errorMessage = attrs["exception.message"];
|
|
384
|
-
if (typeof errorMessage === "string") {
|
|
385
|
-
extra[ATTR.ERROR_MESSAGE] = errorMessage;
|
|
386
|
-
} else if (eventDetails.message) {
|
|
387
|
-
extra[ATTR.ERROR_MESSAGE] = eventDetails.message;
|
|
388
|
-
}
|
|
389
|
-
const errorType = attrs["exception.type"];
|
|
390
|
-
if (typeof errorType === "string") {
|
|
391
|
-
extra[ATTR.ERROR_CODE] = errorType;
|
|
392
|
-
extra[ATTR.ERROR_CATEGORY] = deriveErrorCategory(errorType);
|
|
393
|
-
} else if (eventDetails.type) {
|
|
394
|
-
extra[ATTR.ERROR_CODE] = eventDetails.type;
|
|
395
|
-
extra[ATTR.ERROR_CATEGORY] = deriveErrorCategory(eventDetails.type);
|
|
396
|
-
}
|
|
397
|
-
if (this.verbose && (extra[ATTR.ERROR_MESSAGE] || extra[ATTR.ERROR_CODE])) {
|
|
398
|
-
const msgSource = typeof errorMessage === "string" ? "attrs" : eventDetails.message ? "event" : "none";
|
|
399
|
-
const typeSource = typeof errorType === "string" ? "attrs" : eventDetails.type ? "event" : "none";
|
|
400
|
-
sdkLog(
|
|
401
|
-
"info",
|
|
402
|
-
`[glasstrace] enrichSpan "${name}": error.message source=${msgSource}, error.code source=${typeSource}`
|
|
403
|
-
);
|
|
404
|
-
}
|
|
405
|
-
const errorField = attrs["error.field"];
|
|
406
|
-
if (typeof errorField === "string") {
|
|
407
|
-
extra[ATTR.ERROR_FIELD] = errorField;
|
|
408
|
-
}
|
|
409
|
-
if (this.getConfig().errorResponseBodies) {
|
|
410
|
-
const responseBody = attrs["glasstrace.internal.response_body"];
|
|
411
|
-
if (typeof responseBody === "string") {
|
|
412
|
-
extra[ATTR.ERROR_RESPONSE_BODY] = responseBody.slice(0, 500);
|
|
413
|
-
}
|
|
414
|
-
}
|
|
415
|
-
const spanAny = span;
|
|
416
|
-
const instrumentationName = spanAny.instrumentationScope?.name ?? spanAny.instrumentationLibrary?.name ?? "";
|
|
417
|
-
const ormProvider = deriveOrmProvider(instrumentationName);
|
|
418
|
-
if (ormProvider) {
|
|
419
|
-
extra[ATTR.ORM_PROVIDER] = ormProvider;
|
|
420
|
-
const table = attrs["db.sql.table"];
|
|
421
|
-
const prismaModel = attrs["db.prisma.model"];
|
|
422
|
-
const model = typeof table === "string" ? table : typeof prismaModel === "string" ? prismaModel : void 0;
|
|
423
|
-
if (model) {
|
|
424
|
-
extra[ATTR.ORM_MODEL] = model;
|
|
425
|
-
}
|
|
426
|
-
const operation = attrs["db.operation"];
|
|
427
|
-
if (typeof operation === "string") {
|
|
428
|
-
extra[ATTR.ORM_OPERATION] = operation;
|
|
429
|
-
}
|
|
430
|
-
}
|
|
431
|
-
const httpUrl = attrs["http.url"];
|
|
432
|
-
const fullUrl = attrs["url.full"];
|
|
433
|
-
const url = typeof httpUrl === "string" ? httpUrl : typeof fullUrl === "string" ? fullUrl : void 0;
|
|
434
|
-
if (url && span.kind === SpanKind.CLIENT) {
|
|
435
|
-
extra[ATTR.FETCH_TARGET] = classifyFetchTarget(url);
|
|
436
|
-
}
|
|
437
|
-
return createEnrichedSpan(span, extra);
|
|
438
|
-
} catch {
|
|
439
|
-
return span;
|
|
440
|
-
}
|
|
441
|
-
}
|
|
442
|
-
/**
|
|
443
|
-
* Lazily creates the delegate OTLP exporter once the API key is resolved.
|
|
444
|
-
* Recreates the delegate if the key has changed (e.g., after key rotation)
|
|
445
|
-
* so the Authorization header stays current.
|
|
446
|
-
*/
|
|
447
|
-
ensureDelegate() {
|
|
448
|
-
if (!this.createDelegateFn) return null;
|
|
449
|
-
const currentKey = this.getApiKey();
|
|
450
|
-
if (currentKey === API_KEY_PENDING) return null;
|
|
451
|
-
if (this.delegate && this.delegateKey === currentKey) {
|
|
452
|
-
return this.delegate;
|
|
453
|
-
}
|
|
454
|
-
if (this.delegate) {
|
|
455
|
-
void this.delegate.shutdown?.().catch(() => {
|
|
456
|
-
});
|
|
457
|
-
}
|
|
458
|
-
this.delegate = this.createDelegateFn(this.endpointUrl, {
|
|
459
|
-
Authorization: `Bearer ${currentKey}`
|
|
460
|
-
});
|
|
461
|
-
this.delegateKey = currentKey;
|
|
462
|
-
return this.delegate;
|
|
463
|
-
}
|
|
464
|
-
/**
|
|
465
|
-
* Buffers raw (unenriched) spans while the API key is pending.
|
|
466
|
-
* Evicts oldest batches if the buffer exceeds MAX_PENDING_SPANS.
|
|
467
|
-
* Re-checks the key after buffering to close the race window where
|
|
468
|
-
* the key resolves between the caller's check and this buffer call.
|
|
469
|
-
*/
|
|
470
|
-
bufferSpans(spans, resultCallback) {
|
|
471
|
-
this.pendingBatches.push({ spans, resultCallback });
|
|
472
|
-
this.pendingSpanCount += spans.length;
|
|
473
|
-
while (this.pendingSpanCount > MAX_PENDING_SPANS && this.pendingBatches.length > 1) {
|
|
474
|
-
const evicted = this.pendingBatches.shift();
|
|
475
|
-
this.pendingSpanCount -= evicted.spans.length;
|
|
476
|
-
recordSpansDropped(evicted.spans.length);
|
|
477
|
-
evicted.resultCallback({ code: 0 });
|
|
478
|
-
if (!this.overflowLogged) {
|
|
479
|
-
this.overflowLogged = true;
|
|
480
|
-
console.warn(
|
|
481
|
-
"[glasstrace] Pending span buffer overflow \u2014 oldest spans evicted. This usually means the API key is taking too long to resolve."
|
|
482
|
-
);
|
|
483
|
-
}
|
|
484
|
-
}
|
|
485
|
-
if (this.getApiKey() !== API_KEY_PENDING) {
|
|
486
|
-
this.flushPending();
|
|
487
|
-
}
|
|
488
|
-
}
|
|
489
|
-
/**
|
|
490
|
-
* Flushes all buffered spans through the delegate exporter.
|
|
491
|
-
* Enriches spans at flush time (not buffer time) so that session IDs
|
|
492
|
-
* are computed with the resolved API key instead of the "pending" sentinel.
|
|
493
|
-
*/
|
|
494
|
-
flushPending() {
|
|
495
|
-
if (this.pendingBatches.length === 0) return;
|
|
496
|
-
const exporter = this.ensureDelegate();
|
|
497
|
-
if (!exporter) {
|
|
498
|
-
let discardedCount = 0;
|
|
499
|
-
for (const batch of this.pendingBatches) {
|
|
500
|
-
discardedCount += batch.spans.length;
|
|
501
|
-
batch.resultCallback({ code: 0 });
|
|
502
|
-
}
|
|
503
|
-
recordSpansDropped(discardedCount);
|
|
504
|
-
this.pendingBatches = [];
|
|
505
|
-
this.pendingSpanCount = 0;
|
|
506
|
-
return;
|
|
507
|
-
}
|
|
508
|
-
const batches = this.pendingBatches;
|
|
509
|
-
this.pendingBatches = [];
|
|
510
|
-
this.pendingSpanCount = 0;
|
|
511
|
-
for (const batch of batches) {
|
|
512
|
-
const enriched = batch.spans.map((span) => this.enrichSpan(span));
|
|
513
|
-
exporter.export(enriched, (result) => {
|
|
514
|
-
if (result.code !== 0) {
|
|
515
|
-
sdkLog("warn", `[glasstrace] Span export failed: ${result.error?.message ?? "unknown error"}`);
|
|
516
|
-
}
|
|
517
|
-
batch.resultCallback(result);
|
|
518
|
-
});
|
|
519
|
-
recordSpansExported(enriched.length);
|
|
520
|
-
}
|
|
521
|
-
}
|
|
522
|
-
};
|
|
523
|
-
function createEnrichedSpan(span, extra) {
|
|
524
|
-
const enrichedAttributes = { ...span.attributes, ...extra };
|
|
525
|
-
return Object.create(span, {
|
|
526
|
-
attributes: {
|
|
527
|
-
value: enrichedAttributes,
|
|
528
|
-
enumerable: true
|
|
529
|
-
}
|
|
530
|
-
});
|
|
531
|
-
}
|
|
532
|
-
function hasExceptionEvent(span) {
|
|
533
|
-
return span.events?.some((e) => e.name === "exception") ?? false;
|
|
534
|
-
}
|
|
535
|
-
function getExceptionEventDetails(span) {
|
|
536
|
-
const event = span.events?.find((e) => e.name === "exception");
|
|
537
|
-
if (!event?.attributes) {
|
|
538
|
-
return { type: void 0, message: void 0 };
|
|
539
|
-
}
|
|
540
|
-
const type = event.attributes["exception.type"];
|
|
541
|
-
const message = event.attributes["exception.message"];
|
|
542
|
-
return {
|
|
543
|
-
type: typeof type === "string" ? type : void 0,
|
|
544
|
-
message: typeof message === "string" ? message : void 0
|
|
545
|
-
};
|
|
546
|
-
}
|
|
547
|
-
function extractLeadingPath(raw) {
|
|
548
|
-
if (!raw) return void 0;
|
|
549
|
-
const trimmed = raw.trim();
|
|
550
|
-
if (trimmed.length === 0) return void 0;
|
|
551
|
-
if (trimmed.startsWith("/")) {
|
|
552
|
-
const firstSpace = trimmed.indexOf(" ");
|
|
553
|
-
return firstSpace === -1 ? trimmed : trimmed.slice(0, firstSpace);
|
|
554
|
-
}
|
|
555
|
-
for (const token of trimmed.split(/\s+/)) {
|
|
556
|
-
if (token.startsWith("/")) {
|
|
557
|
-
return token;
|
|
558
|
-
}
|
|
559
|
-
}
|
|
560
|
-
return void 0;
|
|
561
|
-
}
|
|
562
|
-
function deriveOrmProvider(instrumentationName) {
|
|
563
|
-
const lower = instrumentationName.toLowerCase();
|
|
564
|
-
if (lower.includes("prisma")) {
|
|
565
|
-
return "prisma";
|
|
566
|
-
}
|
|
567
|
-
if (lower.includes("drizzle")) {
|
|
568
|
-
return "drizzle";
|
|
569
|
-
}
|
|
570
|
-
return null;
|
|
571
|
-
}
|
|
572
|
-
function deriveErrorCategory(errorType) {
|
|
573
|
-
const lower = errorType.toLowerCase();
|
|
574
|
-
if (lower.includes("validation") || lower.includes("zod")) {
|
|
575
|
-
return "validation";
|
|
576
|
-
}
|
|
577
|
-
if (lower.includes("network") || lower.includes("econnrefused") || lower.includes("fetch") || lower.includes("timeout")) {
|
|
578
|
-
return "network";
|
|
579
|
-
}
|
|
580
|
-
if (lower.includes("auth") || lower.includes("unauthorized") || lower.includes("forbidden")) {
|
|
581
|
-
return "auth";
|
|
582
|
-
}
|
|
583
|
-
if (lower.includes("notfound") || lower.includes("not_found")) {
|
|
584
|
-
return "not-found";
|
|
585
|
-
}
|
|
586
|
-
return "internal";
|
|
587
|
-
}
|
|
588
|
-
|
|
589
|
-
// src/discovery-endpoint.ts
|
|
590
|
-
var runtimeHandlerDeprecationWarned = false;
|
|
591
|
-
function warnRuntimeHandlerDeprecatedOnce() {
|
|
592
|
-
if (runtimeHandlerDeprecationWarned) return;
|
|
593
|
-
runtimeHandlerDeprecationWarned = true;
|
|
594
|
-
console.warn(
|
|
595
|
-
"[glasstrace] createDiscoveryHandler is deprecated. Run `npx glasstrace init` to generate a static file at public/.well-known/glasstrace.json (or static/.well-known/glasstrace.json on SvelteKit). The runtime handler will be removed in v1.0.0."
|
|
596
|
-
);
|
|
597
|
-
}
|
|
598
|
-
function isAllowedOrigin(origin) {
|
|
599
|
-
if (origin === null) return true;
|
|
600
|
-
if (origin.startsWith("chrome-extension://")) return true;
|
|
601
|
-
if (origin.startsWith("moz-extension://")) return true;
|
|
602
|
-
if (origin.startsWith("safari-web-extension://")) return true;
|
|
603
|
-
return false;
|
|
604
|
-
}
|
|
605
|
-
function buildCorsHeaders(origin) {
|
|
606
|
-
const headers = {
|
|
607
|
-
"Content-Type": "application/json",
|
|
608
|
-
Vary: "Origin"
|
|
609
|
-
};
|
|
610
|
-
if (origin && isAllowedOrigin(origin)) {
|
|
611
|
-
headers["Access-Control-Allow-Origin"] = origin;
|
|
612
|
-
}
|
|
613
|
-
return headers;
|
|
614
|
-
}
|
|
615
|
-
function createDiscoveryHandler(getAnonKey, getSessionId, getClaimState) {
|
|
616
|
-
return async (request) => {
|
|
617
|
-
let url;
|
|
618
|
-
try {
|
|
619
|
-
url = new URL(request.url);
|
|
620
|
-
} catch {
|
|
621
|
-
return null;
|
|
622
|
-
}
|
|
623
|
-
if (url.pathname !== "/__glasstrace/config") {
|
|
624
|
-
return null;
|
|
625
|
-
}
|
|
626
|
-
warnRuntimeHandlerDeprecatedOnce();
|
|
627
|
-
const origin = request.headers.get("Origin");
|
|
628
|
-
const corsHeaders = buildCorsHeaders(origin);
|
|
629
|
-
if (request.method === "OPTIONS") {
|
|
630
|
-
return new Response(null, {
|
|
631
|
-
status: 204,
|
|
632
|
-
headers: {
|
|
633
|
-
...corsHeaders,
|
|
634
|
-
"Access-Control-Allow-Methods": "GET, OPTIONS",
|
|
635
|
-
"Access-Control-Allow-Headers": "Content-Type"
|
|
636
|
-
}
|
|
637
|
-
});
|
|
638
|
-
}
|
|
639
|
-
if (request.method !== "GET") {
|
|
640
|
-
return new Response(
|
|
641
|
-
JSON.stringify({ error: "method_not_allowed" }),
|
|
642
|
-
{
|
|
643
|
-
status: 405,
|
|
644
|
-
headers: corsHeaders
|
|
645
|
-
}
|
|
646
|
-
);
|
|
647
|
-
}
|
|
648
|
-
try {
|
|
649
|
-
const anonKey = await getAnonKey();
|
|
650
|
-
if (anonKey === null) {
|
|
651
|
-
return new Response(
|
|
652
|
-
JSON.stringify({ error: "not_ready" }),
|
|
653
|
-
{
|
|
654
|
-
status: 503,
|
|
655
|
-
headers: corsHeaders
|
|
656
|
-
}
|
|
657
|
-
);
|
|
658
|
-
}
|
|
659
|
-
const sessionId = getSessionId();
|
|
660
|
-
const responseBody = { key: anonKey, sessionId };
|
|
661
|
-
const claimState = getClaimState?.();
|
|
662
|
-
if (claimState?.claimed) {
|
|
663
|
-
responseBody.claimed = true;
|
|
664
|
-
if (claimState.accountHint) {
|
|
665
|
-
responseBody.accountHint = claimState.accountHint;
|
|
666
|
-
}
|
|
667
|
-
}
|
|
668
|
-
return new Response(
|
|
669
|
-
JSON.stringify(responseBody),
|
|
670
|
-
{
|
|
671
|
-
status: 200,
|
|
672
|
-
headers: corsHeaders
|
|
673
|
-
}
|
|
674
|
-
);
|
|
675
|
-
} catch {
|
|
676
|
-
return new Response(
|
|
677
|
-
JSON.stringify({ error: "internal_error" }),
|
|
678
|
-
{
|
|
679
|
-
status: 500,
|
|
680
|
-
headers: corsHeaders
|
|
681
|
-
}
|
|
682
|
-
);
|
|
683
|
-
}
|
|
684
|
-
};
|
|
685
|
-
}
|
|
686
|
-
|
|
687
|
-
// ../../node_modules/@opentelemetry/otlp-exporter-base/build/esm/OTLPExporterBase.js
|
|
688
|
-
var OTLPExporterBase = class {
|
|
689
|
-
_delegate;
|
|
690
|
-
constructor(delegate) {
|
|
691
|
-
this._delegate = delegate;
|
|
692
|
-
}
|
|
693
|
-
/**
|
|
694
|
-
* Export items.
|
|
695
|
-
* @param items
|
|
696
|
-
* @param resultCallback
|
|
697
|
-
*/
|
|
698
|
-
export(items, resultCallback) {
|
|
699
|
-
this._delegate.export(items, resultCallback);
|
|
700
|
-
}
|
|
701
|
-
forceFlush() {
|
|
702
|
-
return this._delegate.forceFlush();
|
|
703
|
-
}
|
|
704
|
-
shutdown() {
|
|
705
|
-
return this._delegate.shutdown();
|
|
706
|
-
}
|
|
707
|
-
};
|
|
708
|
-
|
|
709
|
-
// ../../node_modules/@opentelemetry/otlp-exporter-base/build/esm/types.js
|
|
710
|
-
var OTLPExporterError = class extends Error {
|
|
711
|
-
code;
|
|
712
|
-
name = "OTLPExporterError";
|
|
713
|
-
data;
|
|
714
|
-
constructor(message, code, data) {
|
|
715
|
-
super(message);
|
|
716
|
-
this.data = data;
|
|
717
|
-
this.code = code;
|
|
718
|
-
}
|
|
719
|
-
};
|
|
720
|
-
|
|
721
|
-
// ../../node_modules/@opentelemetry/otlp-exporter-base/build/esm/configuration/shared-configuration.js
|
|
722
|
-
function validateTimeoutMillis(timeoutMillis) {
|
|
723
|
-
if (Number.isFinite(timeoutMillis) && timeoutMillis > 0) {
|
|
724
|
-
return timeoutMillis;
|
|
725
|
-
}
|
|
726
|
-
throw new Error(`Configuration: timeoutMillis is invalid, expected number greater than 0 (actual: '${timeoutMillis}')`);
|
|
727
|
-
}
|
|
728
|
-
function wrapStaticHeadersInFunction(headers) {
|
|
729
|
-
if (headers == null) {
|
|
730
|
-
return void 0;
|
|
731
|
-
}
|
|
732
|
-
return async () => headers;
|
|
733
|
-
}
|
|
734
|
-
function mergeOtlpSharedConfigurationWithDefaults(userProvidedConfiguration, fallbackConfiguration, defaultConfiguration) {
|
|
735
|
-
return {
|
|
736
|
-
timeoutMillis: validateTimeoutMillis(userProvidedConfiguration.timeoutMillis ?? fallbackConfiguration.timeoutMillis ?? defaultConfiguration.timeoutMillis),
|
|
737
|
-
concurrencyLimit: userProvidedConfiguration.concurrencyLimit ?? fallbackConfiguration.concurrencyLimit ?? defaultConfiguration.concurrencyLimit,
|
|
738
|
-
compression: userProvidedConfiguration.compression ?? fallbackConfiguration.compression ?? defaultConfiguration.compression
|
|
739
|
-
};
|
|
740
|
-
}
|
|
741
|
-
function getSharedConfigurationDefaults() {
|
|
742
|
-
return {
|
|
743
|
-
timeoutMillis: 1e4,
|
|
744
|
-
concurrencyLimit: 30,
|
|
745
|
-
compression: "none"
|
|
746
|
-
};
|
|
747
|
-
}
|
|
748
|
-
|
|
749
|
-
// ../../node_modules/@opentelemetry/otlp-exporter-base/build/esm/bounded-queue-export-promise-handler.js
|
|
750
|
-
var BoundedQueueExportPromiseHandler = class {
|
|
751
|
-
_concurrencyLimit;
|
|
752
|
-
_sendingPromises = [];
|
|
753
|
-
/**
|
|
754
|
-
* @param concurrencyLimit maximum promises allowed in a queue at the same time.
|
|
755
|
-
*/
|
|
756
|
-
constructor(concurrencyLimit) {
|
|
757
|
-
this._concurrencyLimit = concurrencyLimit;
|
|
758
|
-
}
|
|
759
|
-
pushPromise(promise) {
|
|
760
|
-
if (this.hasReachedLimit()) {
|
|
761
|
-
throw new Error("Concurrency Limit reached");
|
|
762
|
-
}
|
|
763
|
-
this._sendingPromises.push(promise);
|
|
764
|
-
const popPromise = () => {
|
|
765
|
-
const index = this._sendingPromises.indexOf(promise);
|
|
766
|
-
void this._sendingPromises.splice(index, 1);
|
|
767
|
-
};
|
|
768
|
-
promise.then(popPromise, popPromise);
|
|
769
|
-
}
|
|
770
|
-
hasReachedLimit() {
|
|
771
|
-
return this._sendingPromises.length >= this._concurrencyLimit;
|
|
772
|
-
}
|
|
773
|
-
async awaitAll() {
|
|
774
|
-
await Promise.all(this._sendingPromises);
|
|
775
|
-
}
|
|
776
|
-
};
|
|
777
|
-
function createBoundedQueueExportPromiseHandler(options) {
|
|
778
|
-
return new BoundedQueueExportPromiseHandler(options.concurrencyLimit);
|
|
779
|
-
}
|
|
780
|
-
|
|
781
|
-
// ../../node_modules/@opentelemetry/core/build/esm/trace/suppress-tracing.js
|
|
782
|
-
var SUPPRESS_TRACING_KEY = createContextKey("OpenTelemetry SDK Context Key SUPPRESS_TRACING");
|
|
783
|
-
function suppressTracing(context2) {
|
|
784
|
-
return context2.setValue(SUPPRESS_TRACING_KEY, true);
|
|
785
|
-
}
|
|
786
|
-
function isTracingSuppressed(context2) {
|
|
787
|
-
return context2.getValue(SUPPRESS_TRACING_KEY) === true;
|
|
788
|
-
}
|
|
789
|
-
|
|
790
|
-
// ../../node_modules/@opentelemetry/core/build/esm/baggage/constants.js
|
|
791
|
-
var BAGGAGE_KEY_PAIR_SEPARATOR = "=";
|
|
792
|
-
var BAGGAGE_PROPERTIES_SEPARATOR = ";";
|
|
793
|
-
var BAGGAGE_ITEMS_SEPARATOR = ",";
|
|
794
|
-
|
|
795
|
-
// ../../node_modules/@opentelemetry/core/build/esm/baggage/utils.js
|
|
796
|
-
function parsePairKeyValue(entry) {
|
|
797
|
-
if (!entry)
|
|
798
|
-
return;
|
|
799
|
-
const metadataSeparatorIndex = entry.indexOf(BAGGAGE_PROPERTIES_SEPARATOR);
|
|
800
|
-
const keyPairPart = metadataSeparatorIndex === -1 ? entry : entry.substring(0, metadataSeparatorIndex);
|
|
801
|
-
const separatorIndex = keyPairPart.indexOf(BAGGAGE_KEY_PAIR_SEPARATOR);
|
|
802
|
-
if (separatorIndex <= 0)
|
|
803
|
-
return;
|
|
804
|
-
const rawKey = keyPairPart.substring(0, separatorIndex).trim();
|
|
805
|
-
const rawValue = keyPairPart.substring(separatorIndex + 1).trim();
|
|
806
|
-
if (!rawKey || !rawValue)
|
|
807
|
-
return;
|
|
808
|
-
let key;
|
|
809
|
-
let value;
|
|
810
|
-
try {
|
|
811
|
-
key = decodeURIComponent(rawKey);
|
|
812
|
-
value = decodeURIComponent(rawValue);
|
|
813
|
-
} catch {
|
|
814
|
-
return;
|
|
815
|
-
}
|
|
816
|
-
let metadata;
|
|
817
|
-
if (metadataSeparatorIndex !== -1 && metadataSeparatorIndex < entry.length - 1) {
|
|
818
|
-
const metadataString = entry.substring(metadataSeparatorIndex + 1);
|
|
819
|
-
metadata = baggageEntryMetadataFromString(metadataString);
|
|
820
|
-
}
|
|
821
|
-
return { key, value, metadata };
|
|
822
|
-
}
|
|
823
|
-
function parseKeyPairsIntoRecord(value) {
|
|
824
|
-
const result = {};
|
|
825
|
-
if (typeof value === "string" && value.length > 0) {
|
|
826
|
-
value.split(BAGGAGE_ITEMS_SEPARATOR).forEach((entry) => {
|
|
827
|
-
const keyPair = parsePairKeyValue(entry);
|
|
828
|
-
if (keyPair !== void 0 && keyPair.value.length > 0) {
|
|
829
|
-
result[keyPair.key] = keyPair.value;
|
|
830
|
-
}
|
|
831
|
-
});
|
|
832
|
-
}
|
|
833
|
-
return result;
|
|
834
|
-
}
|
|
835
|
-
|
|
836
|
-
// ../../node_modules/@opentelemetry/core/build/esm/common/attributes.js
|
|
837
|
-
function sanitizeAttributes(attributes) {
|
|
838
|
-
const out = {};
|
|
839
|
-
if (typeof attributes !== "object" || attributes == null) {
|
|
840
|
-
return out;
|
|
841
|
-
}
|
|
842
|
-
for (const key in attributes) {
|
|
843
|
-
if (!Object.prototype.hasOwnProperty.call(attributes, key)) {
|
|
844
|
-
continue;
|
|
845
|
-
}
|
|
846
|
-
if (!isAttributeKey(key)) {
|
|
847
|
-
diag.warn(`Invalid attribute key: ${key}`);
|
|
848
|
-
continue;
|
|
849
|
-
}
|
|
850
|
-
const val = attributes[key];
|
|
851
|
-
if (!isAttributeValue(val)) {
|
|
852
|
-
diag.warn(`Invalid attribute value set for key: ${key}`);
|
|
853
|
-
continue;
|
|
854
|
-
}
|
|
855
|
-
if (Array.isArray(val)) {
|
|
856
|
-
out[key] = val.slice();
|
|
857
|
-
} else {
|
|
858
|
-
out[key] = val;
|
|
859
|
-
}
|
|
860
|
-
}
|
|
861
|
-
return out;
|
|
862
|
-
}
|
|
863
|
-
function isAttributeKey(key) {
|
|
864
|
-
return typeof key === "string" && key !== "";
|
|
865
|
-
}
|
|
866
|
-
function isAttributeValue(val) {
|
|
867
|
-
if (val == null) {
|
|
868
|
-
return true;
|
|
869
|
-
}
|
|
870
|
-
if (Array.isArray(val)) {
|
|
871
|
-
return isHomogeneousAttributeValueArray(val);
|
|
872
|
-
}
|
|
873
|
-
return isValidPrimitiveAttributeValueType(typeof val);
|
|
874
|
-
}
|
|
875
|
-
function isHomogeneousAttributeValueArray(arr) {
|
|
876
|
-
let type;
|
|
877
|
-
for (const element of arr) {
|
|
878
|
-
if (element == null)
|
|
879
|
-
continue;
|
|
880
|
-
const elementType = typeof element;
|
|
881
|
-
if (elementType === type) {
|
|
882
|
-
continue;
|
|
883
|
-
}
|
|
884
|
-
if (!type) {
|
|
885
|
-
if (isValidPrimitiveAttributeValueType(elementType)) {
|
|
886
|
-
type = elementType;
|
|
887
|
-
continue;
|
|
888
|
-
}
|
|
889
|
-
return false;
|
|
890
|
-
}
|
|
891
|
-
return false;
|
|
892
|
-
}
|
|
893
|
-
return true;
|
|
894
|
-
}
|
|
895
|
-
function isValidPrimitiveAttributeValueType(valType) {
|
|
896
|
-
switch (valType) {
|
|
897
|
-
case "number":
|
|
898
|
-
case "boolean":
|
|
899
|
-
case "string":
|
|
900
|
-
return true;
|
|
901
|
-
}
|
|
902
|
-
return false;
|
|
903
|
-
}
|
|
904
|
-
|
|
905
|
-
// ../../node_modules/@opentelemetry/core/build/esm/common/logging-error-handler.js
|
|
906
|
-
function loggingErrorHandler() {
|
|
907
|
-
return (ex) => {
|
|
908
|
-
diag.error(stringifyException(ex));
|
|
909
|
-
};
|
|
910
|
-
}
|
|
911
|
-
function stringifyException(ex) {
|
|
912
|
-
if (typeof ex === "string") {
|
|
913
|
-
return ex;
|
|
914
|
-
} else {
|
|
915
|
-
return JSON.stringify(flattenException(ex));
|
|
916
|
-
}
|
|
917
|
-
}
|
|
918
|
-
function flattenException(ex) {
|
|
919
|
-
const result = {};
|
|
920
|
-
let current = ex;
|
|
921
|
-
while (current !== null) {
|
|
922
|
-
Object.getOwnPropertyNames(current).forEach((propertyName) => {
|
|
923
|
-
if (result[propertyName])
|
|
924
|
-
return;
|
|
925
|
-
const value = current[propertyName];
|
|
926
|
-
if (value) {
|
|
927
|
-
result[propertyName] = String(value);
|
|
928
|
-
}
|
|
929
|
-
});
|
|
930
|
-
current = Object.getPrototypeOf(current);
|
|
931
|
-
}
|
|
932
|
-
return result;
|
|
933
|
-
}
|
|
934
|
-
|
|
935
|
-
// ../../node_modules/@opentelemetry/core/build/esm/common/global-error-handler.js
|
|
936
|
-
var delegateHandler = loggingErrorHandler();
|
|
937
|
-
function globalErrorHandler(ex) {
|
|
938
|
-
try {
|
|
939
|
-
delegateHandler(ex);
|
|
940
|
-
} catch {
|
|
941
|
-
}
|
|
942
|
-
}
|
|
943
|
-
|
|
944
|
-
// ../../node_modules/@opentelemetry/core/build/esm/platform/node/environment.js
|
|
945
|
-
import { inspect } from "util";
|
|
946
|
-
function getNumberFromEnv(key) {
|
|
947
|
-
const raw = process.env[key];
|
|
948
|
-
if (raw == null || raw.trim() === "") {
|
|
949
|
-
return void 0;
|
|
950
|
-
}
|
|
951
|
-
const value = Number(raw);
|
|
952
|
-
if (isNaN(value)) {
|
|
953
|
-
diag.warn(`Unknown value ${inspect(raw)} for ${key}, expected a number, using defaults`);
|
|
954
|
-
return void 0;
|
|
955
|
-
}
|
|
956
|
-
return value;
|
|
957
|
-
}
|
|
958
|
-
function getStringFromEnv(key) {
|
|
959
|
-
const raw = process.env[key];
|
|
960
|
-
if (raw == null || raw.trim() === "") {
|
|
961
|
-
return void 0;
|
|
962
|
-
}
|
|
963
|
-
return raw;
|
|
964
|
-
}
|
|
965
|
-
|
|
966
|
-
// ../../node_modules/@opentelemetry/core/build/esm/version.js
|
|
967
|
-
var VERSION = "2.6.1";
|
|
968
|
-
|
|
969
|
-
// ../../node_modules/@opentelemetry/semantic-conventions/build/esm/stable_attributes.js
|
|
970
|
-
var ATTR_EXCEPTION_MESSAGE = "exception.message";
|
|
971
|
-
var ATTR_EXCEPTION_STACKTRACE = "exception.stacktrace";
|
|
972
|
-
var ATTR_EXCEPTION_TYPE = "exception.type";
|
|
973
|
-
var ATTR_SERVICE_NAME = "service.name";
|
|
974
|
-
var ATTR_TELEMETRY_SDK_LANGUAGE = "telemetry.sdk.language";
|
|
975
|
-
var TELEMETRY_SDK_LANGUAGE_VALUE_NODEJS = "nodejs";
|
|
976
|
-
var ATTR_TELEMETRY_SDK_NAME = "telemetry.sdk.name";
|
|
977
|
-
var ATTR_TELEMETRY_SDK_VERSION = "telemetry.sdk.version";
|
|
978
|
-
|
|
979
|
-
// ../../node_modules/@opentelemetry/core/build/esm/semconv.js
|
|
980
|
-
var ATTR_PROCESS_RUNTIME_NAME = "process.runtime.name";
|
|
981
|
-
|
|
982
|
-
// ../../node_modules/@opentelemetry/core/build/esm/platform/node/sdk-info.js
|
|
983
|
-
var SDK_INFO = {
|
|
984
|
-
[ATTR_TELEMETRY_SDK_NAME]: "opentelemetry",
|
|
985
|
-
[ATTR_PROCESS_RUNTIME_NAME]: "node",
|
|
986
|
-
[ATTR_TELEMETRY_SDK_LANGUAGE]: TELEMETRY_SDK_LANGUAGE_VALUE_NODEJS,
|
|
987
|
-
[ATTR_TELEMETRY_SDK_VERSION]: VERSION
|
|
988
|
-
};
|
|
989
|
-
|
|
990
|
-
// ../../node_modules/@opentelemetry/core/build/esm/platform/node/index.js
|
|
991
|
-
var otperformance = performance;
|
|
992
|
-
|
|
993
|
-
// ../../node_modules/@opentelemetry/core/build/esm/common/time.js
|
|
994
|
-
var NANOSECOND_DIGITS = 9;
|
|
995
|
-
var NANOSECOND_DIGITS_IN_MILLIS = 6;
|
|
996
|
-
var MILLISECONDS_TO_NANOSECONDS = Math.pow(10, NANOSECOND_DIGITS_IN_MILLIS);
|
|
997
|
-
var SECOND_TO_NANOSECONDS = Math.pow(10, NANOSECOND_DIGITS);
|
|
998
|
-
function millisToHrTime(epochMillis) {
|
|
999
|
-
const epochSeconds = epochMillis / 1e3;
|
|
1000
|
-
const seconds = Math.trunc(epochSeconds);
|
|
1001
|
-
const nanos = Math.round(epochMillis % 1e3 * MILLISECONDS_TO_NANOSECONDS);
|
|
1002
|
-
return [seconds, nanos];
|
|
1003
|
-
}
|
|
1004
|
-
function hrTime(performanceNow) {
|
|
1005
|
-
const timeOrigin = millisToHrTime(otperformance.timeOrigin);
|
|
1006
|
-
const now = millisToHrTime(typeof performanceNow === "number" ? performanceNow : otperformance.now());
|
|
1007
|
-
return addHrTimes(timeOrigin, now);
|
|
1008
|
-
}
|
|
1009
|
-
function hrTimeDuration(startTime, endTime) {
|
|
1010
|
-
let seconds = endTime[0] - startTime[0];
|
|
1011
|
-
let nanos = endTime[1] - startTime[1];
|
|
1012
|
-
if (nanos < 0) {
|
|
1013
|
-
seconds -= 1;
|
|
1014
|
-
nanos += SECOND_TO_NANOSECONDS;
|
|
1015
|
-
}
|
|
1016
|
-
return [seconds, nanos];
|
|
1017
|
-
}
|
|
1018
|
-
function hrTimeToNanoseconds(time) {
|
|
1019
|
-
return time[0] * SECOND_TO_NANOSECONDS + time[1];
|
|
1020
|
-
}
|
|
1021
|
-
function isTimeInputHrTime(value) {
|
|
1022
|
-
return Array.isArray(value) && value.length === 2 && typeof value[0] === "number" && typeof value[1] === "number";
|
|
1023
|
-
}
|
|
1024
|
-
function isTimeInput(value) {
|
|
1025
|
-
return isTimeInputHrTime(value) || typeof value === "number" || value instanceof Date;
|
|
1026
|
-
}
|
|
1027
|
-
function addHrTimes(time1, time2) {
|
|
1028
|
-
const out = [time1[0] + time2[0], time1[1] + time2[1]];
|
|
1029
|
-
if (out[1] >= SECOND_TO_NANOSECONDS) {
|
|
1030
|
-
out[1] -= SECOND_TO_NANOSECONDS;
|
|
1031
|
-
out[0] += 1;
|
|
1032
|
-
}
|
|
1033
|
-
return out;
|
|
1034
|
-
}
|
|
1035
|
-
|
|
1036
|
-
// ../../node_modules/@opentelemetry/core/build/esm/ExportResult.js
|
|
1037
|
-
var ExportResultCode;
|
|
1038
|
-
(function(ExportResultCode2) {
|
|
1039
|
-
ExportResultCode2[ExportResultCode2["SUCCESS"] = 0] = "SUCCESS";
|
|
1040
|
-
ExportResultCode2[ExportResultCode2["FAILED"] = 1] = "FAILED";
|
|
1041
|
-
})(ExportResultCode || (ExportResultCode = {}));
|
|
1042
|
-
|
|
1043
|
-
// ../../node_modules/@opentelemetry/core/build/esm/utils/lodash.merge.js
|
|
1044
|
-
var objectTag = "[object Object]";
|
|
1045
|
-
var nullTag = "[object Null]";
|
|
1046
|
-
var undefinedTag = "[object Undefined]";
|
|
1047
|
-
var funcProto = Function.prototype;
|
|
1048
|
-
var funcToString = funcProto.toString;
|
|
1049
|
-
var objectCtorString = funcToString.call(Object);
|
|
1050
|
-
var getPrototypeOf = Object.getPrototypeOf;
|
|
1051
|
-
var objectProto = Object.prototype;
|
|
1052
|
-
var hasOwnProperty = objectProto.hasOwnProperty;
|
|
1053
|
-
var symToStringTag = Symbol ? Symbol.toStringTag : void 0;
|
|
1054
|
-
var nativeObjectToString = objectProto.toString;
|
|
1055
|
-
function isPlainObject(value) {
|
|
1056
|
-
if (!isObjectLike(value) || baseGetTag(value) !== objectTag) {
|
|
1057
|
-
return false;
|
|
1058
|
-
}
|
|
1059
|
-
const proto = getPrototypeOf(value);
|
|
1060
|
-
if (proto === null) {
|
|
1061
|
-
return true;
|
|
1062
|
-
}
|
|
1063
|
-
const Ctor = hasOwnProperty.call(proto, "constructor") && proto.constructor;
|
|
1064
|
-
return typeof Ctor == "function" && Ctor instanceof Ctor && funcToString.call(Ctor) === objectCtorString;
|
|
1065
|
-
}
|
|
1066
|
-
function isObjectLike(value) {
|
|
1067
|
-
return value != null && typeof value == "object";
|
|
1068
|
-
}
|
|
1069
|
-
function baseGetTag(value) {
|
|
1070
|
-
if (value == null) {
|
|
1071
|
-
return value === void 0 ? undefinedTag : nullTag;
|
|
1072
|
-
}
|
|
1073
|
-
return symToStringTag && symToStringTag in Object(value) ? getRawTag(value) : objectToString(value);
|
|
1074
|
-
}
|
|
1075
|
-
function getRawTag(value) {
|
|
1076
|
-
const isOwn = hasOwnProperty.call(value, symToStringTag), tag = value[symToStringTag];
|
|
1077
|
-
let unmasked = false;
|
|
1078
|
-
try {
|
|
1079
|
-
value[symToStringTag] = void 0;
|
|
1080
|
-
unmasked = true;
|
|
1081
|
-
} catch {
|
|
1082
|
-
}
|
|
1083
|
-
const result = nativeObjectToString.call(value);
|
|
1084
|
-
if (unmasked) {
|
|
1085
|
-
if (isOwn) {
|
|
1086
|
-
value[symToStringTag] = tag;
|
|
1087
|
-
} else {
|
|
1088
|
-
delete value[symToStringTag];
|
|
1089
|
-
}
|
|
1090
|
-
}
|
|
1091
|
-
return result;
|
|
1092
|
-
}
|
|
1093
|
-
function objectToString(value) {
|
|
1094
|
-
return nativeObjectToString.call(value);
|
|
1095
|
-
}
|
|
1096
|
-
|
|
1097
|
-
// ../../node_modules/@opentelemetry/core/build/esm/utils/merge.js
|
|
1098
|
-
var MAX_LEVEL = 20;
|
|
1099
|
-
function merge(...args) {
|
|
1100
|
-
let result = args.shift();
|
|
1101
|
-
const objects = /* @__PURE__ */ new WeakMap();
|
|
1102
|
-
while (args.length > 0) {
|
|
1103
|
-
result = mergeTwoObjects(result, args.shift(), 0, objects);
|
|
1104
|
-
}
|
|
1105
|
-
return result;
|
|
1106
|
-
}
|
|
1107
|
-
function takeValue(value) {
|
|
1108
|
-
if (isArray(value)) {
|
|
1109
|
-
return value.slice();
|
|
1110
|
-
}
|
|
1111
|
-
return value;
|
|
1112
|
-
}
|
|
1113
|
-
function mergeTwoObjects(one, two, level = 0, objects) {
|
|
1114
|
-
let result;
|
|
1115
|
-
if (level > MAX_LEVEL) {
|
|
1116
|
-
return void 0;
|
|
1117
|
-
}
|
|
1118
|
-
level++;
|
|
1119
|
-
if (isPrimitive(one) || isPrimitive(two) || isFunction(two)) {
|
|
1120
|
-
result = takeValue(two);
|
|
1121
|
-
} else if (isArray(one)) {
|
|
1122
|
-
result = one.slice();
|
|
1123
|
-
if (isArray(two)) {
|
|
1124
|
-
for (let i = 0, j = two.length; i < j; i++) {
|
|
1125
|
-
result.push(takeValue(two[i]));
|
|
1126
|
-
}
|
|
1127
|
-
} else if (isObject(two)) {
|
|
1128
|
-
const keys = Object.keys(two);
|
|
1129
|
-
for (let i = 0, j = keys.length; i < j; i++) {
|
|
1130
|
-
const key = keys[i];
|
|
1131
|
-
result[key] = takeValue(two[key]);
|
|
1132
|
-
}
|
|
1133
|
-
}
|
|
1134
|
-
} else if (isObject(one)) {
|
|
1135
|
-
if (isObject(two)) {
|
|
1136
|
-
if (!shouldMerge(one, two)) {
|
|
1137
|
-
return two;
|
|
1138
|
-
}
|
|
1139
|
-
result = Object.assign({}, one);
|
|
1140
|
-
const keys = Object.keys(two);
|
|
1141
|
-
for (let i = 0, j = keys.length; i < j; i++) {
|
|
1142
|
-
const key = keys[i];
|
|
1143
|
-
const twoValue = two[key];
|
|
1144
|
-
if (isPrimitive(twoValue)) {
|
|
1145
|
-
if (typeof twoValue === "undefined") {
|
|
1146
|
-
delete result[key];
|
|
1147
|
-
} else {
|
|
1148
|
-
result[key] = twoValue;
|
|
1149
|
-
}
|
|
1150
|
-
} else {
|
|
1151
|
-
const obj1 = result[key];
|
|
1152
|
-
const obj2 = twoValue;
|
|
1153
|
-
if (wasObjectReferenced(one, key, objects) || wasObjectReferenced(two, key, objects)) {
|
|
1154
|
-
delete result[key];
|
|
1155
|
-
} else {
|
|
1156
|
-
if (isObject(obj1) && isObject(obj2)) {
|
|
1157
|
-
const arr1 = objects.get(obj1) || [];
|
|
1158
|
-
const arr2 = objects.get(obj2) || [];
|
|
1159
|
-
arr1.push({ obj: one, key });
|
|
1160
|
-
arr2.push({ obj: two, key });
|
|
1161
|
-
objects.set(obj1, arr1);
|
|
1162
|
-
objects.set(obj2, arr2);
|
|
1163
|
-
}
|
|
1164
|
-
result[key] = mergeTwoObjects(result[key], twoValue, level, objects);
|
|
1165
|
-
}
|
|
1166
|
-
}
|
|
1167
|
-
}
|
|
1168
|
-
} else {
|
|
1169
|
-
result = two;
|
|
1170
|
-
}
|
|
1171
|
-
}
|
|
1172
|
-
return result;
|
|
1173
|
-
}
|
|
1174
|
-
function wasObjectReferenced(obj, key, objects) {
|
|
1175
|
-
const arr = objects.get(obj[key]) || [];
|
|
1176
|
-
for (let i = 0, j = arr.length; i < j; i++) {
|
|
1177
|
-
const info = arr[i];
|
|
1178
|
-
if (info.key === key && info.obj === obj) {
|
|
1179
|
-
return true;
|
|
1180
|
-
}
|
|
1181
|
-
}
|
|
1182
|
-
return false;
|
|
1183
|
-
}
|
|
1184
|
-
function isArray(value) {
|
|
1185
|
-
return Array.isArray(value);
|
|
1186
|
-
}
|
|
1187
|
-
function isFunction(value) {
|
|
1188
|
-
return typeof value === "function";
|
|
1189
|
-
}
|
|
1190
|
-
function isObject(value) {
|
|
1191
|
-
return !isPrimitive(value) && !isArray(value) && !isFunction(value) && typeof value === "object";
|
|
1192
|
-
}
|
|
1193
|
-
function isPrimitive(value) {
|
|
1194
|
-
return typeof value === "string" || typeof value === "number" || typeof value === "boolean" || typeof value === "undefined" || value instanceof Date || value instanceof RegExp || value === null;
|
|
1195
|
-
}
|
|
1196
|
-
function shouldMerge(one, two) {
|
|
1197
|
-
if (!isPlainObject(one) || !isPlainObject(two)) {
|
|
1198
|
-
return false;
|
|
1199
|
-
}
|
|
1200
|
-
return true;
|
|
1201
|
-
}
|
|
1202
|
-
|
|
1203
|
-
// ../../node_modules/@opentelemetry/core/build/esm/utils/promise.js
|
|
1204
|
-
var Deferred = class {
|
|
1205
|
-
_promise;
|
|
1206
|
-
_resolve;
|
|
1207
|
-
_reject;
|
|
1208
|
-
constructor() {
|
|
1209
|
-
this._promise = new Promise((resolve2, reject) => {
|
|
1210
|
-
this._resolve = resolve2;
|
|
1211
|
-
this._reject = reject;
|
|
1212
|
-
});
|
|
1213
|
-
}
|
|
1214
|
-
get promise() {
|
|
1215
|
-
return this._promise;
|
|
1216
|
-
}
|
|
1217
|
-
resolve(val) {
|
|
1218
|
-
this._resolve(val);
|
|
1219
|
-
}
|
|
1220
|
-
reject(err) {
|
|
1221
|
-
this._reject(err);
|
|
1222
|
-
}
|
|
1223
|
-
};
|
|
1224
|
-
|
|
1225
|
-
// ../../node_modules/@opentelemetry/core/build/esm/utils/callback.js
|
|
1226
|
-
var BindOnceFuture = class {
|
|
1227
|
-
_isCalled = false;
|
|
1228
|
-
_deferred = new Deferred();
|
|
1229
|
-
_callback;
|
|
1230
|
-
_that;
|
|
1231
|
-
constructor(callback, that) {
|
|
1232
|
-
this._callback = callback;
|
|
1233
|
-
this._that = that;
|
|
1234
|
-
}
|
|
1235
|
-
get isCalled() {
|
|
1236
|
-
return this._isCalled;
|
|
1237
|
-
}
|
|
1238
|
-
get promise() {
|
|
1239
|
-
return this._deferred.promise;
|
|
1240
|
-
}
|
|
1241
|
-
call(...args) {
|
|
1242
|
-
if (!this._isCalled) {
|
|
1243
|
-
this._isCalled = true;
|
|
1244
|
-
try {
|
|
1245
|
-
Promise.resolve(this._callback.call(this._that, ...args)).then((val) => this._deferred.resolve(val), (err) => this._deferred.reject(err));
|
|
1246
|
-
} catch (err) {
|
|
1247
|
-
this._deferred.reject(err);
|
|
1248
|
-
}
|
|
1249
|
-
}
|
|
1250
|
-
return this._deferred.promise;
|
|
1251
|
-
}
|
|
1252
|
-
};
|
|
1253
|
-
|
|
1254
|
-
// ../../node_modules/@opentelemetry/otlp-exporter-base/build/esm/logging-response-handler.js
|
|
1255
|
-
function isPartialSuccessResponse(response) {
|
|
1256
|
-
return Object.prototype.hasOwnProperty.call(response, "partialSuccess");
|
|
1257
|
-
}
|
|
1258
|
-
function createLoggingPartialSuccessResponseHandler() {
|
|
1259
|
-
return {
|
|
1260
|
-
handleResponse(response) {
|
|
1261
|
-
if (response == null || !isPartialSuccessResponse(response) || response.partialSuccess == null || Object.keys(response.partialSuccess).length === 0) {
|
|
1262
|
-
return;
|
|
1263
|
-
}
|
|
1264
|
-
diag.warn("Received Partial Success response:", JSON.stringify(response.partialSuccess));
|
|
1265
|
-
}
|
|
1266
|
-
};
|
|
1267
|
-
}
|
|
1268
|
-
|
|
1269
|
-
// ../../node_modules/@opentelemetry/otlp-exporter-base/build/esm/otlp-export-delegate.js
|
|
1270
|
-
var OTLPExportDelegate = class {
|
|
1271
|
-
_diagLogger;
|
|
1272
|
-
_transport;
|
|
1273
|
-
_serializer;
|
|
1274
|
-
_responseHandler;
|
|
1275
|
-
_promiseQueue;
|
|
1276
|
-
_timeout;
|
|
1277
|
-
constructor(transport, serializer, responseHandler, promiseQueue, timeout) {
|
|
1278
|
-
this._transport = transport;
|
|
1279
|
-
this._serializer = serializer;
|
|
1280
|
-
this._responseHandler = responseHandler;
|
|
1281
|
-
this._promiseQueue = promiseQueue;
|
|
1282
|
-
this._timeout = timeout;
|
|
1283
|
-
this._diagLogger = diag.createComponentLogger({
|
|
1284
|
-
namespace: "OTLPExportDelegate"
|
|
1285
|
-
});
|
|
1286
|
-
}
|
|
1287
|
-
export(internalRepresentation, resultCallback) {
|
|
1288
|
-
this._diagLogger.debug("items to be sent", internalRepresentation);
|
|
1289
|
-
if (this._promiseQueue.hasReachedLimit()) {
|
|
1290
|
-
resultCallback({
|
|
1291
|
-
code: ExportResultCode.FAILED,
|
|
1292
|
-
error: new Error("Concurrent export limit reached")
|
|
1293
|
-
});
|
|
1294
|
-
return;
|
|
1295
|
-
}
|
|
1296
|
-
const serializedRequest = this._serializer.serializeRequest(internalRepresentation);
|
|
1297
|
-
if (serializedRequest == null) {
|
|
1298
|
-
resultCallback({
|
|
1299
|
-
code: ExportResultCode.FAILED,
|
|
1300
|
-
error: new Error("Nothing to send")
|
|
1301
|
-
});
|
|
1302
|
-
return;
|
|
1303
|
-
}
|
|
1304
|
-
this._promiseQueue.pushPromise(this._transport.send(serializedRequest, this._timeout).then((response) => {
|
|
1305
|
-
if (response.status === "success") {
|
|
1306
|
-
if (response.data != null) {
|
|
1307
|
-
try {
|
|
1308
|
-
this._responseHandler.handleResponse(this._serializer.deserializeResponse(response.data));
|
|
1309
|
-
} catch (e) {
|
|
1310
|
-
this._diagLogger.warn("Export succeeded but could not deserialize response - is the response specification compliant?", e, response.data);
|
|
1311
|
-
}
|
|
1312
|
-
}
|
|
1313
|
-
resultCallback({
|
|
1314
|
-
code: ExportResultCode.SUCCESS
|
|
1315
|
-
});
|
|
1316
|
-
return;
|
|
1317
|
-
} else if (response.status === "failure" && response.error) {
|
|
1318
|
-
resultCallback({
|
|
1319
|
-
code: ExportResultCode.FAILED,
|
|
1320
|
-
error: response.error
|
|
1321
|
-
});
|
|
1322
|
-
return;
|
|
1323
|
-
} else if (response.status === "retryable") {
|
|
1324
|
-
resultCallback({
|
|
1325
|
-
code: ExportResultCode.FAILED,
|
|
1326
|
-
error: response.error ?? new OTLPExporterError("Export failed with retryable status")
|
|
1327
|
-
});
|
|
1328
|
-
} else {
|
|
1329
|
-
resultCallback({
|
|
1330
|
-
code: ExportResultCode.FAILED,
|
|
1331
|
-
error: new OTLPExporterError("Export failed with unknown error")
|
|
1332
|
-
});
|
|
1333
|
-
}
|
|
1334
|
-
}, (reason) => resultCallback({
|
|
1335
|
-
code: ExportResultCode.FAILED,
|
|
1336
|
-
error: reason
|
|
1337
|
-
})));
|
|
1338
|
-
}
|
|
1339
|
-
forceFlush() {
|
|
1340
|
-
return this._promiseQueue.awaitAll();
|
|
1341
|
-
}
|
|
1342
|
-
async shutdown() {
|
|
1343
|
-
this._diagLogger.debug("shutdown started");
|
|
1344
|
-
await this.forceFlush();
|
|
1345
|
-
this._transport.shutdown();
|
|
1346
|
-
}
|
|
1347
|
-
};
|
|
1348
|
-
function createOtlpExportDelegate(components, settings) {
|
|
1349
|
-
return new OTLPExportDelegate(components.transport, components.serializer, createLoggingPartialSuccessResponseHandler(), components.promiseHandler, settings.timeout);
|
|
1350
|
-
}
|
|
1351
|
-
|
|
1352
|
-
// ../../node_modules/@opentelemetry/otlp-transformer/build/esm/common/internal.js
|
|
1353
|
-
function createResource(resource, encoder) {
|
|
1354
|
-
const result = {
|
|
1355
|
-
attributes: toAttributes(resource.attributes, encoder),
|
|
1356
|
-
droppedAttributesCount: 0
|
|
1357
|
-
};
|
|
1358
|
-
const schemaUrl = resource.schemaUrl;
|
|
1359
|
-
if (schemaUrl && schemaUrl !== "")
|
|
1360
|
-
result.schemaUrl = schemaUrl;
|
|
1361
|
-
return result;
|
|
1362
|
-
}
|
|
1363
|
-
function createInstrumentationScope(scope) {
|
|
1364
|
-
return {
|
|
1365
|
-
name: scope.name,
|
|
1366
|
-
version: scope.version
|
|
1367
|
-
};
|
|
1368
|
-
}
|
|
1369
|
-
function toAttributes(attributes, encoder) {
|
|
1370
|
-
return Object.keys(attributes).map((key) => toKeyValue(key, attributes[key], encoder));
|
|
1371
|
-
}
|
|
1372
|
-
function toKeyValue(key, value, encoder) {
|
|
1373
|
-
return {
|
|
1374
|
-
key,
|
|
1375
|
-
value: toAnyValue(value, encoder)
|
|
1376
|
-
};
|
|
1377
|
-
}
|
|
1378
|
-
function toAnyValue(value, encoder) {
|
|
1379
|
-
const t = typeof value;
|
|
1380
|
-
if (t === "string")
|
|
1381
|
-
return { stringValue: value };
|
|
1382
|
-
if (t === "number") {
|
|
1383
|
-
if (!Number.isInteger(value))
|
|
1384
|
-
return { doubleValue: value };
|
|
1385
|
-
return { intValue: value };
|
|
1386
|
-
}
|
|
1387
|
-
if (t === "boolean")
|
|
1388
|
-
return { boolValue: value };
|
|
1389
|
-
if (value instanceof Uint8Array)
|
|
1390
|
-
return { bytesValue: encoder.encodeUint8Array(value) };
|
|
1391
|
-
if (Array.isArray(value)) {
|
|
1392
|
-
const values = new Array(value.length);
|
|
1393
|
-
for (let i = 0; i < value.length; i++) {
|
|
1394
|
-
values[i] = toAnyValue(value[i], encoder);
|
|
1395
|
-
}
|
|
1396
|
-
return { arrayValue: { values } };
|
|
1397
|
-
}
|
|
1398
|
-
if (t === "object" && value != null) {
|
|
1399
|
-
const keys = Object.keys(value);
|
|
1400
|
-
const values = new Array(keys.length);
|
|
1401
|
-
for (let i = 0; i < keys.length; i++) {
|
|
1402
|
-
values[i] = {
|
|
1403
|
-
key: keys[i],
|
|
1404
|
-
value: toAnyValue(value[keys[i]], encoder)
|
|
1405
|
-
};
|
|
1406
|
-
}
|
|
1407
|
-
return { kvlistValue: { values } };
|
|
1408
|
-
}
|
|
1409
|
-
return {};
|
|
1410
|
-
}
|
|
1411
|
-
|
|
1412
|
-
// ../../node_modules/@opentelemetry/otlp-transformer/build/esm/common/utils.js
|
|
1413
|
-
function hrTimeToNanos(hrTime2) {
|
|
1414
|
-
const NANOSECONDS = BigInt(1e9);
|
|
1415
|
-
return BigInt(Math.trunc(hrTime2[0])) * NANOSECONDS + BigInt(Math.trunc(hrTime2[1]));
|
|
1416
|
-
}
|
|
1417
|
-
function encodeAsString(hrTime2) {
|
|
1418
|
-
const nanos = hrTimeToNanos(hrTime2);
|
|
1419
|
-
return nanos.toString();
|
|
1420
|
-
}
|
|
1421
|
-
var encodeTimestamp = typeof BigInt !== "undefined" ? encodeAsString : hrTimeToNanoseconds;
|
|
1422
|
-
function identity(value) {
|
|
1423
|
-
return value;
|
|
1424
|
-
}
|
|
1425
|
-
var JSON_ENCODER = {
|
|
1426
|
-
encodeHrTime: encodeTimestamp,
|
|
1427
|
-
encodeSpanContext: identity,
|
|
1428
|
-
encodeOptionalSpanContext: identity,
|
|
1429
|
-
encodeUint8Array: (bytes) => {
|
|
1430
|
-
if (typeof Buffer !== "undefined") {
|
|
1431
|
-
return Buffer.from(bytes).toString("base64");
|
|
1432
|
-
}
|
|
1433
|
-
const chars = new Array(bytes.length);
|
|
1434
|
-
for (let i = 0; i < bytes.length; i++) {
|
|
1435
|
-
chars[i] = String.fromCharCode(bytes[i]);
|
|
1436
|
-
}
|
|
1437
|
-
return btoa(chars.join(""));
|
|
1438
|
-
}
|
|
1439
|
-
};
|
|
1440
|
-
|
|
1441
|
-
// ../../node_modules/@opentelemetry/resources/build/esm/default-service-name.js
|
|
1442
|
-
var serviceName;
|
|
1443
|
-
function defaultServiceName() {
|
|
1444
|
-
if (serviceName === void 0) {
|
|
1445
|
-
try {
|
|
1446
|
-
const argv0 = globalThis.process.argv0;
|
|
1447
|
-
serviceName = argv0 ? `unknown_service:${argv0}` : "unknown_service";
|
|
1448
|
-
} catch {
|
|
1449
|
-
serviceName = "unknown_service";
|
|
1450
|
-
}
|
|
1451
|
-
}
|
|
1452
|
-
return serviceName;
|
|
1453
|
-
}
|
|
1454
|
-
|
|
1455
|
-
// ../../node_modules/@opentelemetry/resources/build/esm/utils.js
|
|
1456
|
-
var isPromiseLike = (val) => {
|
|
1457
|
-
return val !== null && typeof val === "object" && typeof val.then === "function";
|
|
1458
|
-
};
|
|
1459
|
-
|
|
1460
|
-
// ../../node_modules/@opentelemetry/resources/build/esm/ResourceImpl.js
|
|
1461
|
-
var ResourceImpl = class _ResourceImpl {
|
|
1462
|
-
_rawAttributes;
|
|
1463
|
-
_asyncAttributesPending = false;
|
|
1464
|
-
_schemaUrl;
|
|
1465
|
-
_memoizedAttributes;
|
|
1466
|
-
static FromAttributeList(attributes, options) {
|
|
1467
|
-
const res = new _ResourceImpl({}, options);
|
|
1468
|
-
res._rawAttributes = guardedRawAttributes(attributes);
|
|
1469
|
-
res._asyncAttributesPending = attributes.filter(([_, val]) => isPromiseLike(val)).length > 0;
|
|
1470
|
-
return res;
|
|
1471
|
-
}
|
|
1472
|
-
constructor(resource, options) {
|
|
1473
|
-
const attributes = resource.attributes ?? {};
|
|
1474
|
-
this._rawAttributes = Object.entries(attributes).map(([k, v]) => {
|
|
1475
|
-
if (isPromiseLike(v)) {
|
|
1476
|
-
this._asyncAttributesPending = true;
|
|
1477
|
-
}
|
|
1478
|
-
return [k, v];
|
|
1479
|
-
});
|
|
1480
|
-
this._rawAttributes = guardedRawAttributes(this._rawAttributes);
|
|
1481
|
-
this._schemaUrl = validateSchemaUrl(options?.schemaUrl);
|
|
1482
|
-
}
|
|
1483
|
-
get asyncAttributesPending() {
|
|
1484
|
-
return this._asyncAttributesPending;
|
|
1485
|
-
}
|
|
1486
|
-
async waitForAsyncAttributes() {
|
|
1487
|
-
if (!this.asyncAttributesPending) {
|
|
1488
|
-
return;
|
|
1489
|
-
}
|
|
1490
|
-
for (let i = 0; i < this._rawAttributes.length; i++) {
|
|
1491
|
-
const [k, v] = this._rawAttributes[i];
|
|
1492
|
-
this._rawAttributes[i] = [k, isPromiseLike(v) ? await v : v];
|
|
1493
|
-
}
|
|
1494
|
-
this._asyncAttributesPending = false;
|
|
1495
|
-
}
|
|
1496
|
-
get attributes() {
|
|
1497
|
-
if (this.asyncAttributesPending) {
|
|
1498
|
-
diag.error("Accessing resource attributes before async attributes settled");
|
|
1499
|
-
}
|
|
1500
|
-
if (this._memoizedAttributes) {
|
|
1501
|
-
return this._memoizedAttributes;
|
|
1502
|
-
}
|
|
1503
|
-
const attrs = {};
|
|
1504
|
-
for (const [k, v] of this._rawAttributes) {
|
|
1505
|
-
if (isPromiseLike(v)) {
|
|
1506
|
-
diag.debug(`Unsettled resource attribute ${k} skipped`);
|
|
1507
|
-
continue;
|
|
1508
|
-
}
|
|
1509
|
-
if (v != null) {
|
|
1510
|
-
attrs[k] ??= v;
|
|
1511
|
-
}
|
|
1512
|
-
}
|
|
1513
|
-
if (!this._asyncAttributesPending) {
|
|
1514
|
-
this._memoizedAttributes = attrs;
|
|
1515
|
-
}
|
|
1516
|
-
return attrs;
|
|
1517
|
-
}
|
|
1518
|
-
getRawAttributes() {
|
|
1519
|
-
return this._rawAttributes;
|
|
1520
|
-
}
|
|
1521
|
-
get schemaUrl() {
|
|
1522
|
-
return this._schemaUrl;
|
|
1523
|
-
}
|
|
1524
|
-
merge(resource) {
|
|
1525
|
-
if (resource == null)
|
|
1526
|
-
return this;
|
|
1527
|
-
const mergedSchemaUrl = mergeSchemaUrl(this, resource);
|
|
1528
|
-
const mergedOptions = mergedSchemaUrl ? { schemaUrl: mergedSchemaUrl } : void 0;
|
|
1529
|
-
return _ResourceImpl.FromAttributeList([...resource.getRawAttributes(), ...this.getRawAttributes()], mergedOptions);
|
|
1530
|
-
}
|
|
1531
|
-
};
|
|
1532
|
-
function resourceFromAttributes(attributes, options) {
|
|
1533
|
-
return ResourceImpl.FromAttributeList(Object.entries(attributes), options);
|
|
1534
|
-
}
|
|
1535
|
-
function defaultResource() {
|
|
1536
|
-
return resourceFromAttributes({
|
|
1537
|
-
[ATTR_SERVICE_NAME]: defaultServiceName(),
|
|
1538
|
-
[ATTR_TELEMETRY_SDK_LANGUAGE]: SDK_INFO[ATTR_TELEMETRY_SDK_LANGUAGE],
|
|
1539
|
-
[ATTR_TELEMETRY_SDK_NAME]: SDK_INFO[ATTR_TELEMETRY_SDK_NAME],
|
|
1540
|
-
[ATTR_TELEMETRY_SDK_VERSION]: SDK_INFO[ATTR_TELEMETRY_SDK_VERSION]
|
|
1541
|
-
});
|
|
1542
|
-
}
|
|
1543
|
-
function guardedRawAttributes(attributes) {
|
|
1544
|
-
return attributes.map(([k, v]) => {
|
|
1545
|
-
if (isPromiseLike(v)) {
|
|
1546
|
-
return [
|
|
1547
|
-
k,
|
|
1548
|
-
v.catch((err) => {
|
|
1549
|
-
diag.debug("promise rejection for resource attribute: %s - %s", k, err);
|
|
1550
|
-
return void 0;
|
|
1551
|
-
})
|
|
1552
|
-
];
|
|
1553
|
-
}
|
|
1554
|
-
return [k, v];
|
|
1555
|
-
});
|
|
1556
|
-
}
|
|
1557
|
-
function validateSchemaUrl(schemaUrl) {
|
|
1558
|
-
if (typeof schemaUrl === "string" || schemaUrl === void 0) {
|
|
1559
|
-
return schemaUrl;
|
|
1560
|
-
}
|
|
1561
|
-
diag.warn("Schema URL must be string or undefined, got %s. Schema URL will be ignored.", schemaUrl);
|
|
1562
|
-
return void 0;
|
|
1563
|
-
}
|
|
1564
|
-
function mergeSchemaUrl(old, updating) {
|
|
1565
|
-
const oldSchemaUrl = old?.schemaUrl;
|
|
1566
|
-
const updatingSchemaUrl = updating?.schemaUrl;
|
|
1567
|
-
const isOldEmpty = oldSchemaUrl === void 0 || oldSchemaUrl === "";
|
|
1568
|
-
const isUpdatingEmpty = updatingSchemaUrl === void 0 || updatingSchemaUrl === "";
|
|
1569
|
-
if (isOldEmpty) {
|
|
1570
|
-
return updatingSchemaUrl;
|
|
1571
|
-
}
|
|
1572
|
-
if (isUpdatingEmpty) {
|
|
1573
|
-
return oldSchemaUrl;
|
|
1574
|
-
}
|
|
1575
|
-
if (oldSchemaUrl === updatingSchemaUrl) {
|
|
1576
|
-
return oldSchemaUrl;
|
|
1577
|
-
}
|
|
1578
|
-
diag.warn('Schema URL merge conflict: old resource has "%s", updating resource has "%s". Resulting resource will have undefined Schema URL.', oldSchemaUrl, updatingSchemaUrl);
|
|
1579
|
-
return void 0;
|
|
1580
|
-
}
|
|
1581
|
-
|
|
1582
|
-
// ../../node_modules/@opentelemetry/otlp-transformer/build/esm/trace/internal.js
|
|
1583
|
-
var SPAN_FLAGS_CONTEXT_HAS_IS_REMOTE_MASK = 256;
|
|
1584
|
-
var SPAN_FLAGS_CONTEXT_IS_REMOTE_MASK = 512;
|
|
1585
|
-
function buildSpanFlagsFrom(traceFlags, isRemote) {
|
|
1586
|
-
let flags = traceFlags & 255 | SPAN_FLAGS_CONTEXT_HAS_IS_REMOTE_MASK;
|
|
1587
|
-
if (isRemote) {
|
|
1588
|
-
flags |= SPAN_FLAGS_CONTEXT_IS_REMOTE_MASK;
|
|
1589
|
-
}
|
|
1590
|
-
return flags;
|
|
1591
|
-
}
|
|
1592
|
-
function sdkSpanToOtlpSpan(span, encoder) {
|
|
1593
|
-
const ctx = span.spanContext();
|
|
1594
|
-
const status = span.status;
|
|
1595
|
-
const parentSpanId = span.parentSpanContext?.spanId ? encoder.encodeSpanContext(span.parentSpanContext?.spanId) : void 0;
|
|
1596
|
-
return {
|
|
1597
|
-
traceId: encoder.encodeSpanContext(ctx.traceId),
|
|
1598
|
-
spanId: encoder.encodeSpanContext(ctx.spanId),
|
|
1599
|
-
parentSpanId,
|
|
1600
|
-
traceState: ctx.traceState?.serialize(),
|
|
1601
|
-
name: span.name,
|
|
1602
|
-
// Span kind is offset by 1 because the API does not define a value for unset
|
|
1603
|
-
kind: span.kind == null ? 0 : span.kind + 1,
|
|
1604
|
-
startTimeUnixNano: encoder.encodeHrTime(span.startTime),
|
|
1605
|
-
endTimeUnixNano: encoder.encodeHrTime(span.endTime),
|
|
1606
|
-
attributes: toAttributes(span.attributes, encoder),
|
|
1607
|
-
droppedAttributesCount: span.droppedAttributesCount,
|
|
1608
|
-
events: span.events.map((event) => toOtlpSpanEvent(event, encoder)),
|
|
1609
|
-
droppedEventsCount: span.droppedEventsCount,
|
|
1610
|
-
status: {
|
|
1611
|
-
// API and proto enums share the same values
|
|
1612
|
-
code: status.code,
|
|
1613
|
-
message: status.message
|
|
1614
|
-
},
|
|
1615
|
-
links: span.links.map((link) => toOtlpLink(link, encoder)),
|
|
1616
|
-
droppedLinksCount: span.droppedLinksCount,
|
|
1617
|
-
flags: buildSpanFlagsFrom(ctx.traceFlags, span.parentSpanContext?.isRemote)
|
|
1618
|
-
};
|
|
1619
|
-
}
|
|
1620
|
-
function toOtlpLink(link, encoder) {
|
|
1621
|
-
return {
|
|
1622
|
-
attributes: link.attributes ? toAttributes(link.attributes, encoder) : [],
|
|
1623
|
-
spanId: encoder.encodeSpanContext(link.context.spanId),
|
|
1624
|
-
traceId: encoder.encodeSpanContext(link.context.traceId),
|
|
1625
|
-
traceState: link.context.traceState?.serialize(),
|
|
1626
|
-
droppedAttributesCount: link.droppedAttributesCount || 0,
|
|
1627
|
-
flags: buildSpanFlagsFrom(link.context.traceFlags, link.context.isRemote)
|
|
1628
|
-
};
|
|
1629
|
-
}
|
|
1630
|
-
function toOtlpSpanEvent(timedEvent, encoder) {
|
|
1631
|
-
return {
|
|
1632
|
-
attributes: timedEvent.attributes ? toAttributes(timedEvent.attributes, encoder) : [],
|
|
1633
|
-
name: timedEvent.name,
|
|
1634
|
-
timeUnixNano: encoder.encodeHrTime(timedEvent.time),
|
|
1635
|
-
droppedAttributesCount: timedEvent.droppedAttributesCount || 0
|
|
1636
|
-
};
|
|
1637
|
-
}
|
|
1638
|
-
function createExportTraceServiceRequest(spans, encoder) {
|
|
1639
|
-
return {
|
|
1640
|
-
resourceSpans: spanRecordsToResourceSpans(spans, encoder)
|
|
1641
|
-
};
|
|
1642
|
-
}
|
|
1643
|
-
function createResourceMap(readableSpans) {
|
|
1644
|
-
const resourceMap = /* @__PURE__ */ new Map();
|
|
1645
|
-
for (const record of readableSpans) {
|
|
1646
|
-
let ilsMap = resourceMap.get(record.resource);
|
|
1647
|
-
if (!ilsMap) {
|
|
1648
|
-
ilsMap = /* @__PURE__ */ new Map();
|
|
1649
|
-
resourceMap.set(record.resource, ilsMap);
|
|
1650
|
-
}
|
|
1651
|
-
const instrumentationScopeKey = `${record.instrumentationScope.name}@${record.instrumentationScope.version || ""}:${record.instrumentationScope.schemaUrl || ""}`;
|
|
1652
|
-
let records = ilsMap.get(instrumentationScopeKey);
|
|
1653
|
-
if (!records) {
|
|
1654
|
-
records = [];
|
|
1655
|
-
ilsMap.set(instrumentationScopeKey, records);
|
|
1656
|
-
}
|
|
1657
|
-
records.push(record);
|
|
1658
|
-
}
|
|
1659
|
-
return resourceMap;
|
|
1660
|
-
}
|
|
1661
|
-
function spanRecordsToResourceSpans(readableSpans, encoder) {
|
|
1662
|
-
const resourceMap = createResourceMap(readableSpans);
|
|
1663
|
-
const out = [];
|
|
1664
|
-
const entryIterator = resourceMap.entries();
|
|
1665
|
-
let entry = entryIterator.next();
|
|
1666
|
-
while (!entry.done) {
|
|
1667
|
-
const [resource, ilmMap] = entry.value;
|
|
1668
|
-
const scopeResourceSpans = [];
|
|
1669
|
-
const ilmIterator = ilmMap.values();
|
|
1670
|
-
let ilmEntry = ilmIterator.next();
|
|
1671
|
-
while (!ilmEntry.done) {
|
|
1672
|
-
const scopeSpans = ilmEntry.value;
|
|
1673
|
-
if (scopeSpans.length > 0) {
|
|
1674
|
-
const spans = scopeSpans.map((readableSpan) => sdkSpanToOtlpSpan(readableSpan, encoder));
|
|
1675
|
-
scopeResourceSpans.push({
|
|
1676
|
-
scope: createInstrumentationScope(scopeSpans[0].instrumentationScope),
|
|
1677
|
-
spans,
|
|
1678
|
-
schemaUrl: scopeSpans[0].instrumentationScope.schemaUrl
|
|
1679
|
-
});
|
|
1680
|
-
}
|
|
1681
|
-
ilmEntry = ilmIterator.next();
|
|
1682
|
-
}
|
|
1683
|
-
const processedResource = createResource(resource, encoder);
|
|
1684
|
-
const transformedSpans = {
|
|
1685
|
-
resource: processedResource,
|
|
1686
|
-
scopeSpans: scopeResourceSpans,
|
|
1687
|
-
schemaUrl: processedResource.schemaUrl
|
|
1688
|
-
};
|
|
1689
|
-
out.push(transformedSpans);
|
|
1690
|
-
entry = entryIterator.next();
|
|
1691
|
-
}
|
|
1692
|
-
return out;
|
|
1693
|
-
}
|
|
1694
|
-
|
|
1695
|
-
// ../../node_modules/@opentelemetry/otlp-transformer/build/esm/trace/json/trace.js
|
|
1696
|
-
var JsonTraceSerializer = {
|
|
1697
|
-
serializeRequest: (arg) => {
|
|
1698
|
-
const request = createExportTraceServiceRequest(arg, JSON_ENCODER);
|
|
1699
|
-
const encoder = new TextEncoder();
|
|
1700
|
-
return encoder.encode(JSON.stringify(request));
|
|
1701
|
-
},
|
|
1702
|
-
deserializeResponse: (arg) => {
|
|
1703
|
-
if (arg.length === 0) {
|
|
1704
|
-
return {};
|
|
1705
|
-
}
|
|
1706
|
-
const decoder = new TextDecoder();
|
|
1707
|
-
return JSON.parse(decoder.decode(arg));
|
|
1708
|
-
}
|
|
1709
|
-
};
|
|
1710
|
-
|
|
1711
|
-
// ../../node_modules/@opentelemetry/otlp-exporter-base/build/esm/util.js
|
|
1712
|
-
function validateAndNormalizeHeaders(partialHeaders) {
|
|
1713
|
-
const headers = {};
|
|
1714
|
-
Object.entries(partialHeaders ?? {}).forEach(([key, value]) => {
|
|
1715
|
-
if (typeof value !== "undefined") {
|
|
1716
|
-
headers[key] = String(value);
|
|
1717
|
-
} else {
|
|
1718
|
-
diag.warn(`Header "${key}" has invalid value (${value}) and will be ignored`);
|
|
1719
|
-
}
|
|
1720
|
-
});
|
|
1721
|
-
return headers;
|
|
1722
|
-
}
|
|
1723
|
-
|
|
1724
|
-
// ../../node_modules/@opentelemetry/otlp-exporter-base/build/esm/configuration/otlp-http-configuration.js
|
|
1725
|
-
function mergeHeaders(userProvidedHeaders, fallbackHeaders, defaultHeaders) {
|
|
1726
|
-
return async () => {
|
|
1727
|
-
const requiredHeaders = {
|
|
1728
|
-
...await defaultHeaders()
|
|
1729
|
-
};
|
|
1730
|
-
const headers = {};
|
|
1731
|
-
if (fallbackHeaders != null) {
|
|
1732
|
-
Object.assign(headers, await fallbackHeaders());
|
|
1733
|
-
}
|
|
1734
|
-
if (userProvidedHeaders != null) {
|
|
1735
|
-
Object.assign(headers, validateAndNormalizeHeaders(await userProvidedHeaders()));
|
|
1736
|
-
}
|
|
1737
|
-
return Object.assign(headers, requiredHeaders);
|
|
1738
|
-
};
|
|
1739
|
-
}
|
|
1740
|
-
function validateUserProvidedUrl(url) {
|
|
1741
|
-
if (url == null) {
|
|
1742
|
-
return void 0;
|
|
1743
|
-
}
|
|
1744
|
-
try {
|
|
1745
|
-
const base = globalThis.location?.href;
|
|
1746
|
-
return new URL(url, base).href;
|
|
1747
|
-
} catch {
|
|
1748
|
-
throw new Error(`Configuration: Could not parse user-provided export URL: '${url}'`);
|
|
1749
|
-
}
|
|
1750
|
-
}
|
|
1751
|
-
function mergeOtlpHttpConfigurationWithDefaults(userProvidedConfiguration, fallbackConfiguration, defaultConfiguration) {
|
|
1752
|
-
return {
|
|
1753
|
-
...mergeOtlpSharedConfigurationWithDefaults(userProvidedConfiguration, fallbackConfiguration, defaultConfiguration),
|
|
1754
|
-
headers: mergeHeaders(userProvidedConfiguration.headers, fallbackConfiguration.headers, defaultConfiguration.headers),
|
|
1755
|
-
url: validateUserProvidedUrl(userProvidedConfiguration.url) ?? fallbackConfiguration.url ?? defaultConfiguration.url
|
|
1756
|
-
};
|
|
1757
|
-
}
|
|
1758
|
-
function getHttpConfigurationDefaults(requiredHeaders, signalResourcePath) {
|
|
1759
|
-
return {
|
|
1760
|
-
...getSharedConfigurationDefaults(),
|
|
1761
|
-
headers: async () => requiredHeaders,
|
|
1762
|
-
url: "http://localhost:4318/" + signalResourcePath
|
|
1763
|
-
};
|
|
1764
|
-
}
|
|
1765
|
-
|
|
1766
|
-
// ../../node_modules/@opentelemetry/otlp-exporter-base/build/esm/configuration/otlp-node-http-configuration.js
|
|
1767
|
-
function httpAgentFactoryFromOptions(options) {
|
|
1768
|
-
return async (protocol) => {
|
|
1769
|
-
const isInsecure = protocol === "http:";
|
|
1770
|
-
const module = isInsecure ? import("http") : import("https");
|
|
1771
|
-
const { Agent } = await module;
|
|
1772
|
-
if (isInsecure) {
|
|
1773
|
-
const { ca, cert, key, ...insecureOptions } = options;
|
|
1774
|
-
return new Agent(insecureOptions);
|
|
1775
|
-
}
|
|
1776
|
-
return new Agent(options);
|
|
1777
|
-
};
|
|
1778
|
-
}
|
|
1779
|
-
function mergeOtlpNodeHttpConfigurationWithDefaults(userProvidedConfiguration, fallbackConfiguration, defaultConfiguration) {
|
|
1780
|
-
return {
|
|
1781
|
-
...mergeOtlpHttpConfigurationWithDefaults(userProvidedConfiguration, fallbackConfiguration, defaultConfiguration),
|
|
1782
|
-
agentFactory: userProvidedConfiguration.agentFactory ?? fallbackConfiguration.agentFactory ?? defaultConfiguration.agentFactory,
|
|
1783
|
-
userAgent: userProvidedConfiguration.userAgent
|
|
1784
|
-
};
|
|
1785
|
-
}
|
|
1786
|
-
function getNodeHttpConfigurationDefaults(requiredHeaders, signalResourcePath) {
|
|
1787
|
-
return {
|
|
1788
|
-
...getHttpConfigurationDefaults(requiredHeaders, signalResourcePath),
|
|
1789
|
-
agentFactory: httpAgentFactoryFromOptions({ keepAlive: true })
|
|
1790
|
-
};
|
|
1791
|
-
}
|
|
1792
|
-
|
|
1793
|
-
// ../../node_modules/@opentelemetry/otlp-exporter-base/build/esm/transport/http-transport-utils.js
|
|
1794
|
-
import * as zlib from "zlib";
|
|
1795
|
-
import { Readable } from "stream";
|
|
1796
|
-
|
|
1797
|
-
// ../../node_modules/@opentelemetry/otlp-exporter-base/build/esm/is-export-retryable.js
|
|
1798
|
-
function isExportHTTPErrorRetryable(statusCode) {
|
|
1799
|
-
return statusCode === 429 || statusCode === 502 || statusCode === 503 || statusCode === 504;
|
|
1800
|
-
}
|
|
1801
|
-
function parseRetryAfterToMills(retryAfter) {
|
|
1802
|
-
if (retryAfter == null) {
|
|
1803
|
-
return void 0;
|
|
1804
|
-
}
|
|
1805
|
-
const seconds = Number.parseInt(retryAfter, 10);
|
|
1806
|
-
if (Number.isInteger(seconds)) {
|
|
1807
|
-
return seconds > 0 ? seconds * 1e3 : -1;
|
|
1808
|
-
}
|
|
1809
|
-
const delay = new Date(retryAfter).getTime() - Date.now();
|
|
1810
|
-
if (delay >= 0) {
|
|
1811
|
-
return delay;
|
|
1812
|
-
}
|
|
1813
|
-
return 0;
|
|
1814
|
-
}
|
|
1815
|
-
|
|
1816
|
-
// ../../node_modules/@opentelemetry/otlp-exporter-base/build/esm/version.js
|
|
1817
|
-
var VERSION2 = "0.214.0";
|
|
1818
|
-
|
|
1819
|
-
// ../../node_modules/@opentelemetry/otlp-exporter-base/build/esm/transport/http-transport-utils.js
|
|
1820
|
-
var DEFAULT_USER_AGENT = `OTel-OTLP-Exporter-JavaScript/${VERSION2}`;
|
|
1821
|
-
function sendWithHttp(request, url, headers, compression, userAgent, agent, data, timeoutMillis) {
|
|
1822
|
-
return new Promise((resolve2) => {
|
|
1823
|
-
const parsedUrl = new URL(url);
|
|
1824
|
-
if (userAgent) {
|
|
1825
|
-
headers["User-Agent"] = `${userAgent} ${DEFAULT_USER_AGENT}`;
|
|
1826
|
-
} else {
|
|
1827
|
-
headers["User-Agent"] = DEFAULT_USER_AGENT;
|
|
1828
|
-
}
|
|
1829
|
-
const options = {
|
|
1830
|
-
hostname: parsedUrl.hostname,
|
|
1831
|
-
port: parsedUrl.port,
|
|
1832
|
-
path: parsedUrl.pathname,
|
|
1833
|
-
method: "POST",
|
|
1834
|
-
headers,
|
|
1835
|
-
agent
|
|
1836
|
-
};
|
|
1837
|
-
const req = request(options, (res) => {
|
|
1838
|
-
const responseData = [];
|
|
1839
|
-
res.on("data", (chunk) => responseData.push(chunk));
|
|
1840
|
-
res.on("end", () => {
|
|
1841
|
-
if (res.statusCode && res.statusCode <= 299) {
|
|
1842
|
-
resolve2({
|
|
1843
|
-
status: "success",
|
|
1844
|
-
data: Buffer.concat(responseData)
|
|
1845
|
-
});
|
|
1846
|
-
} else if (res.statusCode && isExportHTTPErrorRetryable(res.statusCode)) {
|
|
1847
|
-
resolve2({
|
|
1848
|
-
status: "retryable",
|
|
1849
|
-
retryInMillis: parseRetryAfterToMills(res.headers["retry-after"])
|
|
1850
|
-
});
|
|
1851
|
-
} else {
|
|
1852
|
-
const error = new OTLPExporterError(res.statusMessage, res.statusCode, Buffer.concat(responseData).toString());
|
|
1853
|
-
resolve2({
|
|
1854
|
-
status: "failure",
|
|
1855
|
-
error
|
|
1856
|
-
});
|
|
1857
|
-
}
|
|
1858
|
-
});
|
|
1859
|
-
res.on("error", (error) => {
|
|
1860
|
-
if (res.statusCode && res.statusCode <= 299) {
|
|
1861
|
-
resolve2({
|
|
1862
|
-
status: "success"
|
|
1863
|
-
});
|
|
1864
|
-
} else if (res.statusCode && isExportHTTPErrorRetryable(res.statusCode)) {
|
|
1865
|
-
resolve2({
|
|
1866
|
-
status: "retryable",
|
|
1867
|
-
error,
|
|
1868
|
-
retryInMillis: parseRetryAfterToMills(res.headers["retry-after"])
|
|
1869
|
-
});
|
|
1870
|
-
} else {
|
|
1871
|
-
resolve2({
|
|
1872
|
-
status: "failure",
|
|
1873
|
-
error
|
|
1874
|
-
});
|
|
1875
|
-
}
|
|
1876
|
-
});
|
|
1877
|
-
});
|
|
1878
|
-
req.setTimeout(timeoutMillis, () => {
|
|
1879
|
-
req.destroy();
|
|
1880
|
-
resolve2({
|
|
1881
|
-
status: "retryable",
|
|
1882
|
-
error: new Error("Request timed out")
|
|
1883
|
-
});
|
|
1884
|
-
});
|
|
1885
|
-
req.on("error", (error) => {
|
|
1886
|
-
if (isHttpTransportNetworkErrorRetryable(error)) {
|
|
1887
|
-
resolve2({
|
|
1888
|
-
status: "retryable",
|
|
1889
|
-
error
|
|
1890
|
-
});
|
|
1891
|
-
} else {
|
|
1892
|
-
resolve2({
|
|
1893
|
-
status: "failure",
|
|
1894
|
-
error
|
|
1895
|
-
});
|
|
1896
|
-
}
|
|
1897
|
-
});
|
|
1898
|
-
compressAndSend(req, compression, data, (error) => {
|
|
1899
|
-
resolve2({
|
|
1900
|
-
status: "failure",
|
|
1901
|
-
error
|
|
1902
|
-
});
|
|
1903
|
-
});
|
|
1904
|
-
});
|
|
1905
|
-
}
|
|
1906
|
-
function compressAndSend(req, compression, data, onError) {
|
|
1907
|
-
let dataStream = readableFromUint8Array(data);
|
|
1908
|
-
if (compression === "gzip") {
|
|
1909
|
-
req.setHeader("Content-Encoding", "gzip");
|
|
1910
|
-
dataStream = dataStream.on("error", onError).pipe(zlib.createGzip()).on("error", onError);
|
|
1911
|
-
}
|
|
1912
|
-
dataStream.pipe(req).on("error", onError);
|
|
1913
|
-
}
|
|
1914
|
-
function readableFromUint8Array(buff) {
|
|
1915
|
-
const readable = new Readable();
|
|
1916
|
-
readable.push(buff);
|
|
1917
|
-
readable.push(null);
|
|
1918
|
-
return readable;
|
|
1919
|
-
}
|
|
1920
|
-
function isHttpTransportNetworkErrorRetryable(error) {
|
|
1921
|
-
const RETRYABLE_NETWORK_ERROR_CODES = /* @__PURE__ */ new Set([
|
|
1922
|
-
"ECONNRESET",
|
|
1923
|
-
"ECONNREFUSED",
|
|
1924
|
-
"EPIPE",
|
|
1925
|
-
"ETIMEDOUT",
|
|
1926
|
-
"EAI_AGAIN",
|
|
1927
|
-
"ENOTFOUND",
|
|
1928
|
-
"ENETUNREACH",
|
|
1929
|
-
"EHOSTUNREACH"
|
|
1930
|
-
]);
|
|
1931
|
-
if ("code" in error && typeof error.code === "string") {
|
|
1932
|
-
return RETRYABLE_NETWORK_ERROR_CODES.has(error.code);
|
|
1933
|
-
}
|
|
1934
|
-
return false;
|
|
1935
|
-
}
|
|
1936
|
-
|
|
1937
|
-
// ../../node_modules/@opentelemetry/otlp-exporter-base/build/esm/transport/http-exporter-transport.js
|
|
1938
|
-
var HttpExporterTransport = class {
|
|
1939
|
-
_utils = null;
|
|
1940
|
-
_parameters;
|
|
1941
|
-
constructor(parameters) {
|
|
1942
|
-
this._parameters = parameters;
|
|
1943
|
-
}
|
|
1944
|
-
async send(data, timeoutMillis) {
|
|
1945
|
-
const { agent, request } = await this._loadUtils();
|
|
1946
|
-
const headers = await this._parameters.headers();
|
|
1947
|
-
return sendWithHttp(request, this._parameters.url, headers, this._parameters.compression, this._parameters.userAgent, agent, data, timeoutMillis);
|
|
1948
|
-
}
|
|
1949
|
-
shutdown() {
|
|
1950
|
-
}
|
|
1951
|
-
async _loadUtils() {
|
|
1952
|
-
let utils = this._utils;
|
|
1953
|
-
if (utils === null) {
|
|
1954
|
-
const protocol = new URL(this._parameters.url).protocol;
|
|
1955
|
-
const [agent, request] = await Promise.all([
|
|
1956
|
-
this._parameters.agentFactory(protocol),
|
|
1957
|
-
requestFunctionFactory(protocol)
|
|
1958
|
-
]);
|
|
1959
|
-
utils = this._utils = { agent, request };
|
|
1960
|
-
}
|
|
1961
|
-
return utils;
|
|
1962
|
-
}
|
|
1963
|
-
};
|
|
1964
|
-
async function requestFunctionFactory(protocol) {
|
|
1965
|
-
const module = protocol === "http:" ? import("http") : import("https");
|
|
1966
|
-
const { request } = await module;
|
|
1967
|
-
return request;
|
|
1968
|
-
}
|
|
1969
|
-
function createHttpExporterTransport(parameters) {
|
|
1970
|
-
return new HttpExporterTransport(parameters);
|
|
1971
|
-
}
|
|
1972
|
-
|
|
1973
|
-
// ../../node_modules/@opentelemetry/otlp-exporter-base/build/esm/retrying-transport.js
|
|
1974
|
-
var MAX_ATTEMPTS = 5;
|
|
1975
|
-
var INITIAL_BACKOFF = 1e3;
|
|
1976
|
-
var MAX_BACKOFF = 5e3;
|
|
1977
|
-
var BACKOFF_MULTIPLIER = 1.5;
|
|
1978
|
-
var JITTER = 0.2;
|
|
1979
|
-
function getJitter() {
|
|
1980
|
-
return Math.random() * (2 * JITTER) - JITTER;
|
|
1981
|
-
}
|
|
1982
|
-
var RetryingTransport = class {
|
|
1983
|
-
_transport;
|
|
1984
|
-
constructor(transport) {
|
|
1985
|
-
this._transport = transport;
|
|
1986
|
-
}
|
|
1987
|
-
retry(data, timeoutMillis, inMillis) {
|
|
1988
|
-
return new Promise((resolve2, reject) => {
|
|
1989
|
-
setTimeout(() => {
|
|
1990
|
-
this._transport.send(data, timeoutMillis).then(resolve2, reject);
|
|
1991
|
-
}, inMillis);
|
|
1992
|
-
});
|
|
1993
|
-
}
|
|
1994
|
-
async send(data, timeoutMillis) {
|
|
1995
|
-
let attempts = MAX_ATTEMPTS;
|
|
1996
|
-
let nextBackoff = INITIAL_BACKOFF;
|
|
1997
|
-
const deadline = Date.now() + timeoutMillis;
|
|
1998
|
-
let result = await this._transport.send(data, timeoutMillis);
|
|
1999
|
-
while (result.status === "retryable" && attempts > 0) {
|
|
2000
|
-
attempts--;
|
|
2001
|
-
const backoff = Math.max(Math.min(nextBackoff * (1 + getJitter()), MAX_BACKOFF), 0);
|
|
2002
|
-
nextBackoff = nextBackoff * BACKOFF_MULTIPLIER;
|
|
2003
|
-
const retryInMillis = result.retryInMillis ?? backoff;
|
|
2004
|
-
const remainingTimeoutMillis = deadline - Date.now();
|
|
2005
|
-
if (retryInMillis > remainingTimeoutMillis) {
|
|
2006
|
-
diag.info(`Export retry time ${Math.round(retryInMillis)}ms exceeds remaining timeout ${Math.round(remainingTimeoutMillis)}ms, not retrying further.`);
|
|
2007
|
-
return result;
|
|
2008
|
-
}
|
|
2009
|
-
diag.verbose(`Scheduling export retry in ${Math.round(retryInMillis)}ms`);
|
|
2010
|
-
result = await this.retry(data, remainingTimeoutMillis, retryInMillis);
|
|
2011
|
-
}
|
|
2012
|
-
if (result.status === "success") {
|
|
2013
|
-
diag.verbose(`Export succeeded after ${MAX_ATTEMPTS - attempts} retry attempts.`);
|
|
2014
|
-
} else if (result.status === "retryable") {
|
|
2015
|
-
diag.info(`Export failed after maximum retry attempts (${MAX_ATTEMPTS}).`);
|
|
2016
|
-
} else {
|
|
2017
|
-
diag.info(`Export failed with non-retryable error: ${result.error}`);
|
|
2018
|
-
}
|
|
2019
|
-
return result;
|
|
2020
|
-
}
|
|
2021
|
-
shutdown() {
|
|
2022
|
-
return this._transport.shutdown();
|
|
2023
|
-
}
|
|
2024
|
-
};
|
|
2025
|
-
function createRetryingTransport(options) {
|
|
2026
|
-
return new RetryingTransport(options.transport);
|
|
2027
|
-
}
|
|
2028
|
-
|
|
2029
|
-
// ../../node_modules/@opentelemetry/otlp-exporter-base/build/esm/otlp-http-export-delegate.js
|
|
2030
|
-
function createOtlpHttpExportDelegate(options, serializer) {
|
|
2031
|
-
return createOtlpExportDelegate({
|
|
2032
|
-
transport: createRetryingTransport({
|
|
2033
|
-
transport: createHttpExporterTransport(options)
|
|
2034
|
-
}),
|
|
2035
|
-
serializer,
|
|
2036
|
-
promiseHandler: createBoundedQueueExportPromiseHandler(options)
|
|
2037
|
-
}, { timeout: options.timeoutMillis });
|
|
2038
|
-
}
|
|
2039
|
-
|
|
2040
|
-
// ../../node_modules/@opentelemetry/otlp-exporter-base/build/esm/configuration/shared-env-configuration.js
|
|
2041
|
-
function parseAndValidateTimeoutFromEnv(timeoutEnvVar) {
|
|
2042
|
-
const envTimeout = getNumberFromEnv(timeoutEnvVar);
|
|
2043
|
-
if (envTimeout != null) {
|
|
2044
|
-
if (Number.isFinite(envTimeout) && envTimeout > 0) {
|
|
2045
|
-
return envTimeout;
|
|
2046
|
-
}
|
|
2047
|
-
diag.warn(`Configuration: ${timeoutEnvVar} is invalid, expected number greater than 0 (actual: ${envTimeout})`);
|
|
2048
|
-
}
|
|
2049
|
-
return void 0;
|
|
2050
|
-
}
|
|
2051
|
-
function getTimeoutFromEnv(signalIdentifier) {
|
|
2052
|
-
const specificTimeout = parseAndValidateTimeoutFromEnv(`OTEL_EXPORTER_OTLP_${signalIdentifier}_TIMEOUT`);
|
|
2053
|
-
const nonSpecificTimeout = parseAndValidateTimeoutFromEnv("OTEL_EXPORTER_OTLP_TIMEOUT");
|
|
2054
|
-
return specificTimeout ?? nonSpecificTimeout;
|
|
2055
|
-
}
|
|
2056
|
-
function parseAndValidateCompressionFromEnv(compressionEnvVar) {
|
|
2057
|
-
const compression = getStringFromEnv(compressionEnvVar)?.trim();
|
|
2058
|
-
if (compression == null || compression === "none" || compression === "gzip") {
|
|
2059
|
-
return compression;
|
|
2060
|
-
}
|
|
2061
|
-
diag.warn(`Configuration: ${compressionEnvVar} is invalid, expected 'none' or 'gzip' (actual: '${compression}')`);
|
|
2062
|
-
return void 0;
|
|
2063
|
-
}
|
|
2064
|
-
function getCompressionFromEnv(signalIdentifier) {
|
|
2065
|
-
const specificCompression = parseAndValidateCompressionFromEnv(`OTEL_EXPORTER_OTLP_${signalIdentifier}_COMPRESSION`);
|
|
2066
|
-
const nonSpecificCompression = parseAndValidateCompressionFromEnv("OTEL_EXPORTER_OTLP_COMPRESSION");
|
|
2067
|
-
return specificCompression ?? nonSpecificCompression;
|
|
2068
|
-
}
|
|
2069
|
-
function getSharedConfigurationFromEnvironment(signalIdentifier) {
|
|
2070
|
-
return {
|
|
2071
|
-
timeoutMillis: getTimeoutFromEnv(signalIdentifier),
|
|
2072
|
-
compression: getCompressionFromEnv(signalIdentifier)
|
|
2073
|
-
};
|
|
2074
|
-
}
|
|
2075
|
-
|
|
2076
|
-
// ../../node_modules/@opentelemetry/otlp-exporter-base/build/esm/configuration/otlp-node-http-env-configuration.js
|
|
2077
|
-
import * as fs from "fs";
|
|
2078
|
-
import * as path from "path";
|
|
2079
|
-
function getStaticHeadersFromEnv(signalIdentifier) {
|
|
2080
|
-
const signalSpecificRawHeaders = getStringFromEnv(`OTEL_EXPORTER_OTLP_${signalIdentifier}_HEADERS`);
|
|
2081
|
-
const nonSignalSpecificRawHeaders = getStringFromEnv("OTEL_EXPORTER_OTLP_HEADERS");
|
|
2082
|
-
const signalSpecificHeaders = parseKeyPairsIntoRecord(signalSpecificRawHeaders);
|
|
2083
|
-
const nonSignalSpecificHeaders = parseKeyPairsIntoRecord(nonSignalSpecificRawHeaders);
|
|
2084
|
-
if (Object.keys(signalSpecificHeaders).length === 0 && Object.keys(nonSignalSpecificHeaders).length === 0) {
|
|
2085
|
-
return void 0;
|
|
2086
|
-
}
|
|
2087
|
-
return Object.assign({}, parseKeyPairsIntoRecord(nonSignalSpecificRawHeaders), parseKeyPairsIntoRecord(signalSpecificRawHeaders));
|
|
2088
|
-
}
|
|
2089
|
-
function appendRootPathToUrlIfNeeded(url) {
|
|
2090
|
-
try {
|
|
2091
|
-
const parsedUrl = new URL(url);
|
|
2092
|
-
return parsedUrl.toString();
|
|
2093
|
-
} catch {
|
|
2094
|
-
diag.warn(`Configuration: Could not parse environment-provided export URL: '${url}', falling back to undefined`);
|
|
2095
|
-
return void 0;
|
|
2096
|
-
}
|
|
2097
|
-
}
|
|
2098
|
-
function appendResourcePathToUrl(url, path2) {
|
|
2099
|
-
try {
|
|
2100
|
-
new URL(url);
|
|
2101
|
-
} catch {
|
|
2102
|
-
diag.warn(`Configuration: Could not parse environment-provided export URL: '${url}', falling back to undefined`);
|
|
2103
|
-
return void 0;
|
|
2104
|
-
}
|
|
2105
|
-
if (!url.endsWith("/")) {
|
|
2106
|
-
url = url + "/";
|
|
2107
|
-
}
|
|
2108
|
-
url += path2;
|
|
2109
|
-
try {
|
|
2110
|
-
new URL(url);
|
|
2111
|
-
} catch {
|
|
2112
|
-
diag.warn(`Configuration: Provided URL appended with '${path2}' is not a valid URL, using 'undefined' instead of '${url}'`);
|
|
2113
|
-
return void 0;
|
|
2114
|
-
}
|
|
2115
|
-
return url;
|
|
2116
|
-
}
|
|
2117
|
-
function getNonSpecificUrlFromEnv(signalResourcePath) {
|
|
2118
|
-
const envUrl = getStringFromEnv("OTEL_EXPORTER_OTLP_ENDPOINT");
|
|
2119
|
-
if (envUrl === void 0) {
|
|
2120
|
-
return void 0;
|
|
2121
|
-
}
|
|
2122
|
-
return appendResourcePathToUrl(envUrl, signalResourcePath);
|
|
2123
|
-
}
|
|
2124
|
-
function getSpecificUrlFromEnv(signalIdentifier) {
|
|
2125
|
-
const envUrl = getStringFromEnv(`OTEL_EXPORTER_OTLP_${signalIdentifier}_ENDPOINT`);
|
|
2126
|
-
if (envUrl === void 0) {
|
|
2127
|
-
return void 0;
|
|
2128
|
-
}
|
|
2129
|
-
return appendRootPathToUrlIfNeeded(envUrl);
|
|
2130
|
-
}
|
|
2131
|
-
function readFileFromEnv(signalSpecificEnvVar, nonSignalSpecificEnvVar, warningMessage) {
|
|
2132
|
-
const signalSpecificPath = getStringFromEnv(signalSpecificEnvVar);
|
|
2133
|
-
const nonSignalSpecificPath = getStringFromEnv(nonSignalSpecificEnvVar);
|
|
2134
|
-
const filePath = signalSpecificPath ?? nonSignalSpecificPath;
|
|
2135
|
-
if (filePath != null) {
|
|
2136
|
-
try {
|
|
2137
|
-
return fs.readFileSync(path.resolve(process.cwd(), filePath));
|
|
2138
|
-
} catch {
|
|
2139
|
-
diag.warn(warningMessage);
|
|
2140
|
-
return void 0;
|
|
2141
|
-
}
|
|
2142
|
-
} else {
|
|
2143
|
-
return void 0;
|
|
2144
|
-
}
|
|
2145
|
-
}
|
|
2146
|
-
function getClientCertificateFromEnv(signalIdentifier) {
|
|
2147
|
-
return readFileFromEnv(`OTEL_EXPORTER_OTLP_${signalIdentifier}_CLIENT_CERTIFICATE`, "OTEL_EXPORTER_OTLP_CLIENT_CERTIFICATE", "Failed to read client certificate chain file");
|
|
2148
|
-
}
|
|
2149
|
-
function getClientKeyFromEnv(signalIdentifier) {
|
|
2150
|
-
return readFileFromEnv(`OTEL_EXPORTER_OTLP_${signalIdentifier}_CLIENT_KEY`, "OTEL_EXPORTER_OTLP_CLIENT_KEY", "Failed to read client certificate private key file");
|
|
2151
|
-
}
|
|
2152
|
-
function getRootCertificateFromEnv(signalIdentifier) {
|
|
2153
|
-
return readFileFromEnv(`OTEL_EXPORTER_OTLP_${signalIdentifier}_CERTIFICATE`, "OTEL_EXPORTER_OTLP_CERTIFICATE", "Failed to read root certificate file");
|
|
2154
|
-
}
|
|
2155
|
-
function getNodeHttpConfigurationFromEnvironment(signalIdentifier, signalResourcePath) {
|
|
2156
|
-
return {
|
|
2157
|
-
...getSharedConfigurationFromEnvironment(signalIdentifier),
|
|
2158
|
-
url: getSpecificUrlFromEnv(signalIdentifier) ?? getNonSpecificUrlFromEnv(signalResourcePath),
|
|
2159
|
-
headers: wrapStaticHeadersInFunction(getStaticHeadersFromEnv(signalIdentifier)),
|
|
2160
|
-
agentFactory: httpAgentFactoryFromOptions({
|
|
2161
|
-
keepAlive: true,
|
|
2162
|
-
ca: getRootCertificateFromEnv(signalIdentifier),
|
|
2163
|
-
cert: getClientCertificateFromEnv(signalIdentifier),
|
|
2164
|
-
key: getClientKeyFromEnv(signalIdentifier)
|
|
2165
|
-
})
|
|
2166
|
-
};
|
|
2167
|
-
}
|
|
2168
|
-
|
|
2169
|
-
// ../../node_modules/@opentelemetry/otlp-exporter-base/build/esm/configuration/convert-legacy-http-options.js
|
|
2170
|
-
function convertLegacyHeaders(config) {
|
|
2171
|
-
if (typeof config.headers === "function") {
|
|
2172
|
-
return config.headers;
|
|
2173
|
-
}
|
|
2174
|
-
return wrapStaticHeadersInFunction(config.headers);
|
|
2175
|
-
}
|
|
2176
|
-
|
|
2177
|
-
// ../../node_modules/@opentelemetry/otlp-exporter-base/build/esm/configuration/convert-legacy-node-http-options.js
|
|
2178
|
-
function convertLegacyAgentOptions(config) {
|
|
2179
|
-
if (typeof config.httpAgentOptions === "function") {
|
|
2180
|
-
return config.httpAgentOptions;
|
|
2181
|
-
}
|
|
2182
|
-
let legacy = config.httpAgentOptions;
|
|
2183
|
-
if (config.keepAlive != null) {
|
|
2184
|
-
legacy = { keepAlive: config.keepAlive, ...legacy };
|
|
2185
|
-
}
|
|
2186
|
-
if (legacy != null) {
|
|
2187
|
-
return httpAgentFactoryFromOptions(legacy);
|
|
2188
|
-
} else {
|
|
2189
|
-
return void 0;
|
|
2190
|
-
}
|
|
2191
|
-
}
|
|
2192
|
-
function convertLegacyHttpOptions(config, signalIdentifier, signalResourcePath, requiredHeaders) {
|
|
2193
|
-
if (config.metadata) {
|
|
2194
|
-
diag.warn("Metadata cannot be set when using http");
|
|
2195
|
-
}
|
|
2196
|
-
return mergeOtlpNodeHttpConfigurationWithDefaults({
|
|
2197
|
-
url: config.url,
|
|
2198
|
-
headers: convertLegacyHeaders(config),
|
|
2199
|
-
concurrencyLimit: config.concurrencyLimit,
|
|
2200
|
-
timeoutMillis: config.timeoutMillis,
|
|
2201
|
-
compression: config.compression,
|
|
2202
|
-
agentFactory: convertLegacyAgentOptions(config),
|
|
2203
|
-
userAgent: config.userAgent
|
|
2204
|
-
}, getNodeHttpConfigurationFromEnvironment(signalIdentifier, signalResourcePath), getNodeHttpConfigurationDefaults(requiredHeaders, signalResourcePath));
|
|
2205
|
-
}
|
|
2206
|
-
|
|
2207
|
-
// ../../node_modules/@opentelemetry/exporter-trace-otlp-http/build/esm/platform/node/OTLPTraceExporter.js
|
|
2208
|
-
var OTLPTraceExporter = class extends OTLPExporterBase {
|
|
2209
|
-
constructor(config = {}) {
|
|
2210
|
-
super(createOtlpHttpExportDelegate(convertLegacyHttpOptions(config, "TRACES", "v1/traces", {
|
|
2211
|
-
"Content-Type": "application/json"
|
|
2212
|
-
}), JsonTraceSerializer));
|
|
2213
|
-
}
|
|
2214
|
-
};
|
|
2215
|
-
|
|
2216
|
-
// ../../node_modules/@opentelemetry/sdk-trace-base/build/esm/enums.js
|
|
2217
|
-
var ExceptionEventName = "exception";
|
|
2218
|
-
|
|
2219
|
-
// ../../node_modules/@opentelemetry/sdk-trace-base/build/esm/Span.js
|
|
2220
|
-
var SpanImpl = class {
|
|
2221
|
-
// Below properties are included to implement ReadableSpan for export
|
|
2222
|
-
// purposes but are not intended to be written-to directly.
|
|
2223
|
-
_spanContext;
|
|
2224
|
-
kind;
|
|
2225
|
-
parentSpanContext;
|
|
2226
|
-
attributes = {};
|
|
2227
|
-
links = [];
|
|
2228
|
-
events = [];
|
|
2229
|
-
startTime;
|
|
2230
|
-
resource;
|
|
2231
|
-
instrumentationScope;
|
|
2232
|
-
_droppedAttributesCount = 0;
|
|
2233
|
-
_droppedEventsCount = 0;
|
|
2234
|
-
_droppedLinksCount = 0;
|
|
2235
|
-
_attributesCount = 0;
|
|
2236
|
-
name;
|
|
2237
|
-
status = {
|
|
2238
|
-
code: SpanStatusCode.UNSET
|
|
2239
|
-
};
|
|
2240
|
-
endTime = [0, 0];
|
|
2241
|
-
_ended = false;
|
|
2242
|
-
_duration = [-1, -1];
|
|
2243
|
-
_spanProcessor;
|
|
2244
|
-
_spanLimits;
|
|
2245
|
-
_attributeValueLengthLimit;
|
|
2246
|
-
_recordEndMetrics;
|
|
2247
|
-
_performanceStartTime;
|
|
2248
|
-
_performanceOffset;
|
|
2249
|
-
_startTimeProvided;
|
|
2250
|
-
/**
|
|
2251
|
-
* Constructs a new SpanImpl instance.
|
|
2252
|
-
*/
|
|
2253
|
-
constructor(opts) {
|
|
2254
|
-
const now = Date.now();
|
|
2255
|
-
this._spanContext = opts.spanContext;
|
|
2256
|
-
this._performanceStartTime = otperformance.now();
|
|
2257
|
-
this._performanceOffset = now - (this._performanceStartTime + otperformance.timeOrigin);
|
|
2258
|
-
this._startTimeProvided = opts.startTime != null;
|
|
2259
|
-
this._spanLimits = opts.spanLimits;
|
|
2260
|
-
this._attributeValueLengthLimit = this._spanLimits.attributeValueLengthLimit ?? 0;
|
|
2261
|
-
this._spanProcessor = opts.spanProcessor;
|
|
2262
|
-
this.name = opts.name;
|
|
2263
|
-
this.parentSpanContext = opts.parentSpanContext;
|
|
2264
|
-
this.kind = opts.kind;
|
|
2265
|
-
if (opts.links) {
|
|
2266
|
-
for (const link of opts.links) {
|
|
2267
|
-
this.addLink(link);
|
|
2268
|
-
}
|
|
2269
|
-
}
|
|
2270
|
-
this.startTime = this._getTime(opts.startTime ?? now);
|
|
2271
|
-
this.resource = opts.resource;
|
|
2272
|
-
this.instrumentationScope = opts.scope;
|
|
2273
|
-
this._recordEndMetrics = opts.recordEndMetrics;
|
|
2274
|
-
if (opts.attributes != null) {
|
|
2275
|
-
this.setAttributes(opts.attributes);
|
|
2276
|
-
}
|
|
2277
|
-
this._spanProcessor.onStart(this, opts.context);
|
|
2278
|
-
}
|
|
2279
|
-
spanContext() {
|
|
2280
|
-
return this._spanContext;
|
|
2281
|
-
}
|
|
2282
|
-
setAttribute(key, value) {
|
|
2283
|
-
if (value == null || this._isSpanEnded())
|
|
2284
|
-
return this;
|
|
2285
|
-
if (key.length === 0) {
|
|
2286
|
-
diag.warn(`Invalid attribute key: ${key}`);
|
|
2287
|
-
return this;
|
|
2288
|
-
}
|
|
2289
|
-
if (!isAttributeValue(value)) {
|
|
2290
|
-
diag.warn(`Invalid attribute value set for key: ${key}`);
|
|
2291
|
-
return this;
|
|
2292
|
-
}
|
|
2293
|
-
const { attributeCountLimit } = this._spanLimits;
|
|
2294
|
-
const isNewKey = !Object.prototype.hasOwnProperty.call(this.attributes, key);
|
|
2295
|
-
if (attributeCountLimit !== void 0 && this._attributesCount >= attributeCountLimit && isNewKey) {
|
|
2296
|
-
this._droppedAttributesCount++;
|
|
2297
|
-
return this;
|
|
2298
|
-
}
|
|
2299
|
-
this.attributes[key] = this._truncateToSize(value);
|
|
2300
|
-
if (isNewKey) {
|
|
2301
|
-
this._attributesCount++;
|
|
2302
|
-
}
|
|
2303
|
-
return this;
|
|
2304
|
-
}
|
|
2305
|
-
setAttributes(attributes) {
|
|
2306
|
-
for (const key in attributes) {
|
|
2307
|
-
if (Object.prototype.hasOwnProperty.call(attributes, key)) {
|
|
2308
|
-
this.setAttribute(key, attributes[key]);
|
|
2309
|
-
}
|
|
2310
|
-
}
|
|
2311
|
-
return this;
|
|
2312
|
-
}
|
|
2313
|
-
/**
|
|
2314
|
-
*
|
|
2315
|
-
* @param name Span Name
|
|
2316
|
-
* @param [attributesOrStartTime] Span attributes or start time
|
|
2317
|
-
* if type is {@type TimeInput} and 3rd param is undefined
|
|
2318
|
-
* @param [timeStamp] Specified time stamp for the event
|
|
2319
|
-
*/
|
|
2320
|
-
addEvent(name, attributesOrStartTime, timeStamp) {
|
|
2321
|
-
if (this._isSpanEnded())
|
|
2322
|
-
return this;
|
|
2323
|
-
const { eventCountLimit } = this._spanLimits;
|
|
2324
|
-
if (eventCountLimit === 0) {
|
|
2325
|
-
diag.warn("No events allowed.");
|
|
2326
|
-
this._droppedEventsCount++;
|
|
2327
|
-
return this;
|
|
2328
|
-
}
|
|
2329
|
-
if (eventCountLimit !== void 0 && this.events.length >= eventCountLimit) {
|
|
2330
|
-
if (this._droppedEventsCount === 0) {
|
|
2331
|
-
diag.debug("Dropping extra events.");
|
|
2332
|
-
}
|
|
2333
|
-
this.events.shift();
|
|
2334
|
-
this._droppedEventsCount++;
|
|
2335
|
-
}
|
|
2336
|
-
if (isTimeInput(attributesOrStartTime)) {
|
|
2337
|
-
if (!isTimeInput(timeStamp)) {
|
|
2338
|
-
timeStamp = attributesOrStartTime;
|
|
2339
|
-
}
|
|
2340
|
-
attributesOrStartTime = void 0;
|
|
2341
|
-
}
|
|
2342
|
-
const sanitized = sanitizeAttributes(attributesOrStartTime);
|
|
2343
|
-
const { attributePerEventCountLimit } = this._spanLimits;
|
|
2344
|
-
const attributes = {};
|
|
2345
|
-
let droppedAttributesCount = 0;
|
|
2346
|
-
let eventAttributesCount = 0;
|
|
2347
|
-
for (const attr in sanitized) {
|
|
2348
|
-
if (!Object.prototype.hasOwnProperty.call(sanitized, attr)) {
|
|
2349
|
-
continue;
|
|
2350
|
-
}
|
|
2351
|
-
const attrVal = sanitized[attr];
|
|
2352
|
-
if (attributePerEventCountLimit !== void 0 && eventAttributesCount >= attributePerEventCountLimit) {
|
|
2353
|
-
droppedAttributesCount++;
|
|
2354
|
-
continue;
|
|
2355
|
-
}
|
|
2356
|
-
attributes[attr] = this._truncateToSize(attrVal);
|
|
2357
|
-
eventAttributesCount++;
|
|
2358
|
-
}
|
|
2359
|
-
this.events.push({
|
|
2360
|
-
name,
|
|
2361
|
-
attributes,
|
|
2362
|
-
time: this._getTime(timeStamp),
|
|
2363
|
-
droppedAttributesCount
|
|
2364
|
-
});
|
|
2365
|
-
return this;
|
|
2366
|
-
}
|
|
2367
|
-
addLink(link) {
|
|
2368
|
-
if (this._isSpanEnded())
|
|
2369
|
-
return this;
|
|
2370
|
-
const { linkCountLimit } = this._spanLimits;
|
|
2371
|
-
if (linkCountLimit === 0) {
|
|
2372
|
-
this._droppedLinksCount++;
|
|
2373
|
-
return this;
|
|
2374
|
-
}
|
|
2375
|
-
if (linkCountLimit !== void 0 && this.links.length >= linkCountLimit) {
|
|
2376
|
-
if (this._droppedLinksCount === 0) {
|
|
2377
|
-
diag.debug("Dropping extra links.");
|
|
2378
|
-
}
|
|
2379
|
-
this.links.shift();
|
|
2380
|
-
this._droppedLinksCount++;
|
|
2381
|
-
}
|
|
2382
|
-
const { attributePerLinkCountLimit } = this._spanLimits;
|
|
2383
|
-
const sanitized = sanitizeAttributes(link.attributes);
|
|
2384
|
-
const attributes = {};
|
|
2385
|
-
let droppedAttributesCount = 0;
|
|
2386
|
-
let linkAttributesCount = 0;
|
|
2387
|
-
for (const attr in sanitized) {
|
|
2388
|
-
if (!Object.prototype.hasOwnProperty.call(sanitized, attr)) {
|
|
2389
|
-
continue;
|
|
2390
|
-
}
|
|
2391
|
-
const attrVal = sanitized[attr];
|
|
2392
|
-
if (attributePerLinkCountLimit !== void 0 && linkAttributesCount >= attributePerLinkCountLimit) {
|
|
2393
|
-
droppedAttributesCount++;
|
|
2394
|
-
continue;
|
|
2395
|
-
}
|
|
2396
|
-
attributes[attr] = this._truncateToSize(attrVal);
|
|
2397
|
-
linkAttributesCount++;
|
|
2398
|
-
}
|
|
2399
|
-
const processedLink = { context: link.context };
|
|
2400
|
-
if (linkAttributesCount > 0) {
|
|
2401
|
-
processedLink.attributes = attributes;
|
|
2402
|
-
}
|
|
2403
|
-
if (droppedAttributesCount > 0) {
|
|
2404
|
-
processedLink.droppedAttributesCount = droppedAttributesCount;
|
|
2405
|
-
}
|
|
2406
|
-
this.links.push(processedLink);
|
|
2407
|
-
return this;
|
|
2408
|
-
}
|
|
2409
|
-
addLinks(links) {
|
|
2410
|
-
for (const link of links) {
|
|
2411
|
-
this.addLink(link);
|
|
2412
|
-
}
|
|
2413
|
-
return this;
|
|
2414
|
-
}
|
|
2415
|
-
setStatus(status) {
|
|
2416
|
-
if (this._isSpanEnded())
|
|
2417
|
-
return this;
|
|
2418
|
-
if (status.code === SpanStatusCode.UNSET)
|
|
2419
|
-
return this;
|
|
2420
|
-
if (this.status.code === SpanStatusCode.OK)
|
|
2421
|
-
return this;
|
|
2422
|
-
const newStatus = { code: status.code };
|
|
2423
|
-
if (status.code === SpanStatusCode.ERROR) {
|
|
2424
|
-
if (typeof status.message === "string") {
|
|
2425
|
-
newStatus.message = status.message;
|
|
2426
|
-
} else if (status.message != null) {
|
|
2427
|
-
diag.warn(`Dropping invalid status.message of type '${typeof status.message}', expected 'string'`);
|
|
2428
|
-
}
|
|
2429
|
-
}
|
|
2430
|
-
this.status = newStatus;
|
|
2431
|
-
return this;
|
|
2432
|
-
}
|
|
2433
|
-
updateName(name) {
|
|
2434
|
-
if (this._isSpanEnded())
|
|
2435
|
-
return this;
|
|
2436
|
-
this.name = name;
|
|
2437
|
-
return this;
|
|
2438
|
-
}
|
|
2439
|
-
end(endTime) {
|
|
2440
|
-
if (this._isSpanEnded()) {
|
|
2441
|
-
diag.error(`${this.name} ${this._spanContext.traceId}-${this._spanContext.spanId} - You can only call end() on a span once.`);
|
|
2442
|
-
return;
|
|
2443
|
-
}
|
|
2444
|
-
this.endTime = this._getTime(endTime);
|
|
2445
|
-
this._duration = hrTimeDuration(this.startTime, this.endTime);
|
|
2446
|
-
if (this._duration[0] < 0) {
|
|
2447
|
-
diag.warn("Inconsistent start and end time, startTime > endTime. Setting span duration to 0ms.", this.startTime, this.endTime);
|
|
2448
|
-
this.endTime = this.startTime.slice();
|
|
2449
|
-
this._duration = [0, 0];
|
|
2450
|
-
}
|
|
2451
|
-
if (this._droppedEventsCount > 0) {
|
|
2452
|
-
diag.warn(`Dropped ${this._droppedEventsCount} events because eventCountLimit reached`);
|
|
2453
|
-
}
|
|
2454
|
-
if (this._droppedLinksCount > 0) {
|
|
2455
|
-
diag.warn(`Dropped ${this._droppedLinksCount} links because linkCountLimit reached`);
|
|
2456
|
-
}
|
|
2457
|
-
if (this._spanProcessor.onEnding) {
|
|
2458
|
-
this._spanProcessor.onEnding(this);
|
|
2459
|
-
}
|
|
2460
|
-
this._recordEndMetrics?.();
|
|
2461
|
-
this._ended = true;
|
|
2462
|
-
this._spanProcessor.onEnd(this);
|
|
2463
|
-
}
|
|
2464
|
-
_getTime(inp) {
|
|
2465
|
-
if (typeof inp === "number" && inp <= otperformance.now()) {
|
|
2466
|
-
return hrTime(inp + this._performanceOffset);
|
|
2467
|
-
}
|
|
2468
|
-
if (typeof inp === "number") {
|
|
2469
|
-
return millisToHrTime(inp);
|
|
2470
|
-
}
|
|
2471
|
-
if (inp instanceof Date) {
|
|
2472
|
-
return millisToHrTime(inp.getTime());
|
|
2473
|
-
}
|
|
2474
|
-
if (isTimeInputHrTime(inp)) {
|
|
2475
|
-
return inp;
|
|
2476
|
-
}
|
|
2477
|
-
if (this._startTimeProvided) {
|
|
2478
|
-
return millisToHrTime(Date.now());
|
|
2479
|
-
}
|
|
2480
|
-
const msDuration = otperformance.now() - this._performanceStartTime;
|
|
2481
|
-
return addHrTimes(this.startTime, millisToHrTime(msDuration));
|
|
2482
|
-
}
|
|
2483
|
-
isRecording() {
|
|
2484
|
-
return this._ended === false;
|
|
2485
|
-
}
|
|
2486
|
-
recordException(exception, time) {
|
|
2487
|
-
const attributes = {};
|
|
2488
|
-
if (typeof exception === "string") {
|
|
2489
|
-
attributes[ATTR_EXCEPTION_MESSAGE] = exception;
|
|
2490
|
-
} else if (exception) {
|
|
2491
|
-
if (exception.code) {
|
|
2492
|
-
attributes[ATTR_EXCEPTION_TYPE] = exception.code.toString();
|
|
2493
|
-
} else if (exception.name) {
|
|
2494
|
-
attributes[ATTR_EXCEPTION_TYPE] = exception.name;
|
|
2495
|
-
}
|
|
2496
|
-
if (exception.message) {
|
|
2497
|
-
attributes[ATTR_EXCEPTION_MESSAGE] = exception.message;
|
|
2498
|
-
}
|
|
2499
|
-
if (exception.stack) {
|
|
2500
|
-
attributes[ATTR_EXCEPTION_STACKTRACE] = exception.stack;
|
|
2501
|
-
}
|
|
2502
|
-
}
|
|
2503
|
-
if (attributes[ATTR_EXCEPTION_TYPE] || attributes[ATTR_EXCEPTION_MESSAGE]) {
|
|
2504
|
-
this.addEvent(ExceptionEventName, attributes, time);
|
|
2505
|
-
} else {
|
|
2506
|
-
diag.warn(`Failed to record an exception ${exception}`);
|
|
2507
|
-
}
|
|
2508
|
-
}
|
|
2509
|
-
get duration() {
|
|
2510
|
-
return this._duration;
|
|
2511
|
-
}
|
|
2512
|
-
get ended() {
|
|
2513
|
-
return this._ended;
|
|
2514
|
-
}
|
|
2515
|
-
get droppedAttributesCount() {
|
|
2516
|
-
return this._droppedAttributesCount;
|
|
2517
|
-
}
|
|
2518
|
-
get droppedEventsCount() {
|
|
2519
|
-
return this._droppedEventsCount;
|
|
2520
|
-
}
|
|
2521
|
-
get droppedLinksCount() {
|
|
2522
|
-
return this._droppedLinksCount;
|
|
2523
|
-
}
|
|
2524
|
-
_isSpanEnded() {
|
|
2525
|
-
if (this._ended) {
|
|
2526
|
-
const error = new Error(`Operation attempted on ended Span {traceId: ${this._spanContext.traceId}, spanId: ${this._spanContext.spanId}}`);
|
|
2527
|
-
diag.warn(`Cannot execute the operation on ended Span {traceId: ${this._spanContext.traceId}, spanId: ${this._spanContext.spanId}}`, error);
|
|
2528
|
-
}
|
|
2529
|
-
return this._ended;
|
|
2530
|
-
}
|
|
2531
|
-
// Utility function to truncate given value within size
|
|
2532
|
-
// for value type of string, will truncate to given limit
|
|
2533
|
-
// for type of non-string, will return same value
|
|
2534
|
-
_truncateToLimitUtil(value, limit) {
|
|
2535
|
-
if (value.length <= limit) {
|
|
2536
|
-
return value;
|
|
2537
|
-
}
|
|
2538
|
-
return value.substring(0, limit);
|
|
2539
|
-
}
|
|
2540
|
-
/**
|
|
2541
|
-
* If the given attribute value is of type string and has more characters than given {@code attributeValueLengthLimit} then
|
|
2542
|
-
* return string with truncated to {@code attributeValueLengthLimit} characters
|
|
2543
|
-
*
|
|
2544
|
-
* If the given attribute value is array of strings then
|
|
2545
|
-
* return new array of strings with each element truncated to {@code attributeValueLengthLimit} characters
|
|
2546
|
-
*
|
|
2547
|
-
* Otherwise return same Attribute {@code value}
|
|
2548
|
-
*
|
|
2549
|
-
* @param value Attribute value
|
|
2550
|
-
* @returns truncated attribute value if required, otherwise same value
|
|
2551
|
-
*/
|
|
2552
|
-
_truncateToSize(value) {
|
|
2553
|
-
const limit = this._attributeValueLengthLimit;
|
|
2554
|
-
if (limit <= 0) {
|
|
2555
|
-
diag.warn(`Attribute value limit must be positive, got ${limit}`);
|
|
2556
|
-
return value;
|
|
2557
|
-
}
|
|
2558
|
-
if (typeof value === "string") {
|
|
2559
|
-
return this._truncateToLimitUtil(value, limit);
|
|
2560
|
-
}
|
|
2561
|
-
if (Array.isArray(value)) {
|
|
2562
|
-
return value.map((val) => typeof val === "string" ? this._truncateToLimitUtil(val, limit) : val);
|
|
2563
|
-
}
|
|
2564
|
-
return value;
|
|
2565
|
-
}
|
|
2566
|
-
};
|
|
2567
|
-
|
|
2568
|
-
// ../../node_modules/@opentelemetry/sdk-trace-base/build/esm/Sampler.js
|
|
2569
|
-
var SamplingDecision2;
|
|
2570
|
-
(function(SamplingDecision3) {
|
|
2571
|
-
SamplingDecision3[SamplingDecision3["NOT_RECORD"] = 0] = "NOT_RECORD";
|
|
2572
|
-
SamplingDecision3[SamplingDecision3["RECORD"] = 1] = "RECORD";
|
|
2573
|
-
SamplingDecision3[SamplingDecision3["RECORD_AND_SAMPLED"] = 2] = "RECORD_AND_SAMPLED";
|
|
2574
|
-
})(SamplingDecision2 || (SamplingDecision2 = {}));
|
|
2575
|
-
|
|
2576
|
-
// ../../node_modules/@opentelemetry/sdk-trace-base/build/esm/sampler/AlwaysOffSampler.js
|
|
2577
|
-
var AlwaysOffSampler = class {
|
|
2578
|
-
shouldSample() {
|
|
2579
|
-
return {
|
|
2580
|
-
decision: SamplingDecision2.NOT_RECORD
|
|
2581
|
-
};
|
|
2582
|
-
}
|
|
2583
|
-
toString() {
|
|
2584
|
-
return "AlwaysOffSampler";
|
|
2585
|
-
}
|
|
2586
|
-
};
|
|
2587
|
-
|
|
2588
|
-
// ../../node_modules/@opentelemetry/sdk-trace-base/build/esm/sampler/AlwaysOnSampler.js
|
|
2589
|
-
var AlwaysOnSampler = class {
|
|
2590
|
-
shouldSample() {
|
|
2591
|
-
return {
|
|
2592
|
-
decision: SamplingDecision2.RECORD_AND_SAMPLED
|
|
2593
|
-
};
|
|
2594
|
-
}
|
|
2595
|
-
toString() {
|
|
2596
|
-
return "AlwaysOnSampler";
|
|
2597
|
-
}
|
|
2598
|
-
};
|
|
2599
|
-
|
|
2600
|
-
// ../../node_modules/@opentelemetry/sdk-trace-base/build/esm/sampler/ParentBasedSampler.js
|
|
2601
|
-
var ParentBasedSampler = class {
|
|
2602
|
-
_root;
|
|
2603
|
-
_remoteParentSampled;
|
|
2604
|
-
_remoteParentNotSampled;
|
|
2605
|
-
_localParentSampled;
|
|
2606
|
-
_localParentNotSampled;
|
|
2607
|
-
constructor(config) {
|
|
2608
|
-
this._root = config.root;
|
|
2609
|
-
if (!this._root) {
|
|
2610
|
-
globalErrorHandler(new Error("ParentBasedSampler must have a root sampler configured"));
|
|
2611
|
-
this._root = new AlwaysOnSampler();
|
|
2612
|
-
}
|
|
2613
|
-
this._remoteParentSampled = config.remoteParentSampled ?? new AlwaysOnSampler();
|
|
2614
|
-
this._remoteParentNotSampled = config.remoteParentNotSampled ?? new AlwaysOffSampler();
|
|
2615
|
-
this._localParentSampled = config.localParentSampled ?? new AlwaysOnSampler();
|
|
2616
|
-
this._localParentNotSampled = config.localParentNotSampled ?? new AlwaysOffSampler();
|
|
2617
|
-
}
|
|
2618
|
-
shouldSample(context2, traceId, spanName, spanKind, attributes, links) {
|
|
2619
|
-
const parentContext = trace.getSpanContext(context2);
|
|
2620
|
-
if (!parentContext || !isSpanContextValid(parentContext)) {
|
|
2621
|
-
return this._root.shouldSample(context2, traceId, spanName, spanKind, attributes, links);
|
|
2622
|
-
}
|
|
2623
|
-
if (parentContext.isRemote) {
|
|
2624
|
-
if (parentContext.traceFlags & TraceFlags.SAMPLED) {
|
|
2625
|
-
return this._remoteParentSampled.shouldSample(context2, traceId, spanName, spanKind, attributes, links);
|
|
2626
|
-
}
|
|
2627
|
-
return this._remoteParentNotSampled.shouldSample(context2, traceId, spanName, spanKind, attributes, links);
|
|
2628
|
-
}
|
|
2629
|
-
if (parentContext.traceFlags & TraceFlags.SAMPLED) {
|
|
2630
|
-
return this._localParentSampled.shouldSample(context2, traceId, spanName, spanKind, attributes, links);
|
|
2631
|
-
}
|
|
2632
|
-
return this._localParentNotSampled.shouldSample(context2, traceId, spanName, spanKind, attributes, links);
|
|
2633
|
-
}
|
|
2634
|
-
toString() {
|
|
2635
|
-
return `ParentBased{root=${this._root.toString()}, remoteParentSampled=${this._remoteParentSampled.toString()}, remoteParentNotSampled=${this._remoteParentNotSampled.toString()}, localParentSampled=${this._localParentSampled.toString()}, localParentNotSampled=${this._localParentNotSampled.toString()}}`;
|
|
2636
|
-
}
|
|
2637
|
-
};
|
|
2638
|
-
|
|
2639
|
-
// ../../node_modules/@opentelemetry/sdk-trace-base/build/esm/sampler/TraceIdRatioBasedSampler.js
|
|
2640
|
-
var TraceIdRatioBasedSampler = class {
|
|
2641
|
-
_ratio;
|
|
2642
|
-
_upperBound;
|
|
2643
|
-
constructor(ratio = 0) {
|
|
2644
|
-
this._ratio = this._normalize(ratio);
|
|
2645
|
-
this._upperBound = Math.floor(this._ratio * 4294967295);
|
|
2646
|
-
}
|
|
2647
|
-
shouldSample(context2, traceId) {
|
|
2648
|
-
return {
|
|
2649
|
-
decision: isValidTraceId(traceId) && this._accumulate(traceId) < this._upperBound ? SamplingDecision2.RECORD_AND_SAMPLED : SamplingDecision2.NOT_RECORD
|
|
2650
|
-
};
|
|
2651
|
-
}
|
|
2652
|
-
toString() {
|
|
2653
|
-
return `TraceIdRatioBased{${this._ratio}}`;
|
|
2654
|
-
}
|
|
2655
|
-
_normalize(ratio) {
|
|
2656
|
-
if (typeof ratio !== "number" || isNaN(ratio))
|
|
2657
|
-
return 0;
|
|
2658
|
-
return ratio >= 1 ? 1 : ratio <= 0 ? 0 : ratio;
|
|
2659
|
-
}
|
|
2660
|
-
_accumulate(traceId) {
|
|
2661
|
-
let accumulation = 0;
|
|
2662
|
-
for (let i = 0; i < traceId.length / 8; i++) {
|
|
2663
|
-
const pos = i * 8;
|
|
2664
|
-
const part = parseInt(traceId.slice(pos, pos + 8), 16);
|
|
2665
|
-
accumulation = (accumulation ^ part) >>> 0;
|
|
2666
|
-
}
|
|
2667
|
-
return accumulation;
|
|
2668
|
-
}
|
|
2669
|
-
};
|
|
2670
|
-
|
|
2671
|
-
// ../../node_modules/@opentelemetry/sdk-trace-base/build/esm/config.js
|
|
2672
|
-
var TracesSamplerValues;
|
|
2673
|
-
(function(TracesSamplerValues2) {
|
|
2674
|
-
TracesSamplerValues2["AlwaysOff"] = "always_off";
|
|
2675
|
-
TracesSamplerValues2["AlwaysOn"] = "always_on";
|
|
2676
|
-
TracesSamplerValues2["ParentBasedAlwaysOff"] = "parentbased_always_off";
|
|
2677
|
-
TracesSamplerValues2["ParentBasedAlwaysOn"] = "parentbased_always_on";
|
|
2678
|
-
TracesSamplerValues2["ParentBasedTraceIdRatio"] = "parentbased_traceidratio";
|
|
2679
|
-
TracesSamplerValues2["TraceIdRatio"] = "traceidratio";
|
|
2680
|
-
})(TracesSamplerValues || (TracesSamplerValues = {}));
|
|
2681
|
-
var DEFAULT_RATIO = 1;
|
|
2682
|
-
function loadDefaultConfig() {
|
|
2683
|
-
return {
|
|
2684
|
-
sampler: buildSamplerFromEnv(),
|
|
2685
|
-
forceFlushTimeoutMillis: 3e4,
|
|
2686
|
-
generalLimits: {
|
|
2687
|
-
attributeValueLengthLimit: getNumberFromEnv("OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT") ?? Infinity,
|
|
2688
|
-
attributeCountLimit: getNumberFromEnv("OTEL_ATTRIBUTE_COUNT_LIMIT") ?? 128
|
|
2689
|
-
},
|
|
2690
|
-
spanLimits: {
|
|
2691
|
-
attributeValueLengthLimit: getNumberFromEnv("OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT") ?? Infinity,
|
|
2692
|
-
attributeCountLimit: getNumberFromEnv("OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT") ?? 128,
|
|
2693
|
-
linkCountLimit: getNumberFromEnv("OTEL_SPAN_LINK_COUNT_LIMIT") ?? 128,
|
|
2694
|
-
eventCountLimit: getNumberFromEnv("OTEL_SPAN_EVENT_COUNT_LIMIT") ?? 128,
|
|
2695
|
-
attributePerEventCountLimit: getNumberFromEnv("OTEL_SPAN_ATTRIBUTE_PER_EVENT_COUNT_LIMIT") ?? 128,
|
|
2696
|
-
attributePerLinkCountLimit: getNumberFromEnv("OTEL_SPAN_ATTRIBUTE_PER_LINK_COUNT_LIMIT") ?? 128
|
|
2697
|
-
}
|
|
2698
|
-
};
|
|
2699
|
-
}
|
|
2700
|
-
function buildSamplerFromEnv() {
|
|
2701
|
-
const sampler = getStringFromEnv("OTEL_TRACES_SAMPLER") ?? TracesSamplerValues.ParentBasedAlwaysOn;
|
|
2702
|
-
switch (sampler) {
|
|
2703
|
-
case TracesSamplerValues.AlwaysOn:
|
|
2704
|
-
return new AlwaysOnSampler();
|
|
2705
|
-
case TracesSamplerValues.AlwaysOff:
|
|
2706
|
-
return new AlwaysOffSampler();
|
|
2707
|
-
case TracesSamplerValues.ParentBasedAlwaysOn:
|
|
2708
|
-
return new ParentBasedSampler({
|
|
2709
|
-
root: new AlwaysOnSampler()
|
|
2710
|
-
});
|
|
2711
|
-
case TracesSamplerValues.ParentBasedAlwaysOff:
|
|
2712
|
-
return new ParentBasedSampler({
|
|
2713
|
-
root: new AlwaysOffSampler()
|
|
2714
|
-
});
|
|
2715
|
-
case TracesSamplerValues.TraceIdRatio:
|
|
2716
|
-
return new TraceIdRatioBasedSampler(getSamplerProbabilityFromEnv());
|
|
2717
|
-
case TracesSamplerValues.ParentBasedTraceIdRatio:
|
|
2718
|
-
return new ParentBasedSampler({
|
|
2719
|
-
root: new TraceIdRatioBasedSampler(getSamplerProbabilityFromEnv())
|
|
2720
|
-
});
|
|
2721
|
-
default:
|
|
2722
|
-
diag.error(`OTEL_TRACES_SAMPLER value "${sampler}" invalid, defaulting to "${TracesSamplerValues.ParentBasedAlwaysOn}".`);
|
|
2723
|
-
return new ParentBasedSampler({
|
|
2724
|
-
root: new AlwaysOnSampler()
|
|
2725
|
-
});
|
|
2726
|
-
}
|
|
2727
|
-
}
|
|
2728
|
-
function getSamplerProbabilityFromEnv() {
|
|
2729
|
-
const probability = getNumberFromEnv("OTEL_TRACES_SAMPLER_ARG");
|
|
2730
|
-
if (probability == null) {
|
|
2731
|
-
diag.error(`OTEL_TRACES_SAMPLER_ARG is blank, defaulting to ${DEFAULT_RATIO}.`);
|
|
2732
|
-
return DEFAULT_RATIO;
|
|
2733
|
-
}
|
|
2734
|
-
if (probability < 0 || probability > 1) {
|
|
2735
|
-
diag.error(`OTEL_TRACES_SAMPLER_ARG=${probability} was given, but it is out of range ([0..1]), defaulting to ${DEFAULT_RATIO}.`);
|
|
2736
|
-
return DEFAULT_RATIO;
|
|
2737
|
-
}
|
|
2738
|
-
return probability;
|
|
2739
|
-
}
|
|
2740
|
-
|
|
2741
|
-
// ../../node_modules/@opentelemetry/sdk-trace-base/build/esm/utility.js
|
|
2742
|
-
var DEFAULT_ATTRIBUTE_COUNT_LIMIT = 128;
|
|
2743
|
-
var DEFAULT_ATTRIBUTE_VALUE_LENGTH_LIMIT = Infinity;
|
|
2744
|
-
function mergeConfig(userConfig) {
|
|
2745
|
-
const perInstanceDefaults = {
|
|
2746
|
-
sampler: buildSamplerFromEnv()
|
|
2747
|
-
};
|
|
2748
|
-
const DEFAULT_CONFIG = loadDefaultConfig();
|
|
2749
|
-
const target = Object.assign({}, DEFAULT_CONFIG, perInstanceDefaults, userConfig);
|
|
2750
|
-
target.generalLimits = Object.assign({}, DEFAULT_CONFIG.generalLimits, userConfig.generalLimits || {});
|
|
2751
|
-
target.spanLimits = Object.assign({}, DEFAULT_CONFIG.spanLimits, userConfig.spanLimits || {});
|
|
2752
|
-
return target;
|
|
2753
|
-
}
|
|
2754
|
-
function reconfigureLimits(userConfig) {
|
|
2755
|
-
const spanLimits = Object.assign({}, userConfig.spanLimits);
|
|
2756
|
-
spanLimits.attributeCountLimit = userConfig.spanLimits?.attributeCountLimit ?? userConfig.generalLimits?.attributeCountLimit ?? getNumberFromEnv("OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT") ?? getNumberFromEnv("OTEL_ATTRIBUTE_COUNT_LIMIT") ?? DEFAULT_ATTRIBUTE_COUNT_LIMIT;
|
|
2757
|
-
spanLimits.attributeValueLengthLimit = userConfig.spanLimits?.attributeValueLengthLimit ?? userConfig.generalLimits?.attributeValueLengthLimit ?? getNumberFromEnv("OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT") ?? getNumberFromEnv("OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT") ?? DEFAULT_ATTRIBUTE_VALUE_LENGTH_LIMIT;
|
|
2758
|
-
return Object.assign({}, userConfig, { spanLimits });
|
|
2759
|
-
}
|
|
2760
|
-
|
|
2761
|
-
// ../../node_modules/@opentelemetry/sdk-trace-base/build/esm/export/BatchSpanProcessorBase.js
|
|
2762
|
-
var BatchSpanProcessorBase = class {
|
|
2763
|
-
_maxExportBatchSize;
|
|
2764
|
-
_maxQueueSize;
|
|
2765
|
-
_scheduledDelayMillis;
|
|
2766
|
-
_exportTimeoutMillis;
|
|
2767
|
-
_exporter;
|
|
2768
|
-
_isExporting = false;
|
|
2769
|
-
_finishedSpans = [];
|
|
2770
|
-
_timer;
|
|
2771
|
-
_shutdownOnce;
|
|
2772
|
-
_droppedSpansCount = 0;
|
|
2773
|
-
constructor(exporter, config) {
|
|
2774
|
-
this._exporter = exporter;
|
|
2775
|
-
this._maxExportBatchSize = typeof config?.maxExportBatchSize === "number" ? config.maxExportBatchSize : getNumberFromEnv("OTEL_BSP_MAX_EXPORT_BATCH_SIZE") ?? 512;
|
|
2776
|
-
this._maxQueueSize = typeof config?.maxQueueSize === "number" ? config.maxQueueSize : getNumberFromEnv("OTEL_BSP_MAX_QUEUE_SIZE") ?? 2048;
|
|
2777
|
-
this._scheduledDelayMillis = typeof config?.scheduledDelayMillis === "number" ? config.scheduledDelayMillis : getNumberFromEnv("OTEL_BSP_SCHEDULE_DELAY") ?? 5e3;
|
|
2778
|
-
this._exportTimeoutMillis = typeof config?.exportTimeoutMillis === "number" ? config.exportTimeoutMillis : getNumberFromEnv("OTEL_BSP_EXPORT_TIMEOUT") ?? 3e4;
|
|
2779
|
-
this._shutdownOnce = new BindOnceFuture(this._shutdown, this);
|
|
2780
|
-
if (this._maxExportBatchSize > this._maxQueueSize) {
|
|
2781
|
-
diag.warn("BatchSpanProcessor: maxExportBatchSize must be smaller or equal to maxQueueSize, setting maxExportBatchSize to match maxQueueSize");
|
|
2782
|
-
this._maxExportBatchSize = this._maxQueueSize;
|
|
2783
|
-
}
|
|
2784
|
-
}
|
|
2785
|
-
forceFlush() {
|
|
2786
|
-
if (this._shutdownOnce.isCalled) {
|
|
2787
|
-
return this._shutdownOnce.promise;
|
|
2788
|
-
}
|
|
2789
|
-
return this._flushAll();
|
|
2790
|
-
}
|
|
2791
|
-
// does nothing.
|
|
2792
|
-
onStart(_span, _parentContext) {
|
|
2793
|
-
}
|
|
2794
|
-
onEnd(span) {
|
|
2795
|
-
if (this._shutdownOnce.isCalled) {
|
|
2796
|
-
return;
|
|
2797
|
-
}
|
|
2798
|
-
if ((span.spanContext().traceFlags & TraceFlags.SAMPLED) === 0) {
|
|
2799
|
-
return;
|
|
2800
|
-
}
|
|
2801
|
-
this._addToBuffer(span);
|
|
2802
|
-
}
|
|
2803
|
-
shutdown() {
|
|
2804
|
-
return this._shutdownOnce.call();
|
|
2805
|
-
}
|
|
2806
|
-
_shutdown() {
|
|
2807
|
-
return Promise.resolve().then(() => {
|
|
2808
|
-
return this.onShutdown();
|
|
2809
|
-
}).then(() => {
|
|
2810
|
-
return this._flushAll();
|
|
2811
|
-
}).then(() => {
|
|
2812
|
-
return this._exporter.shutdown();
|
|
2813
|
-
});
|
|
2814
|
-
}
|
|
2815
|
-
/** Add a span in the buffer. */
|
|
2816
|
-
_addToBuffer(span) {
|
|
2817
|
-
if (this._finishedSpans.length >= this._maxQueueSize) {
|
|
2818
|
-
if (this._droppedSpansCount === 0) {
|
|
2819
|
-
diag.debug("maxQueueSize reached, dropping spans");
|
|
2820
|
-
}
|
|
2821
|
-
this._droppedSpansCount++;
|
|
2822
|
-
return;
|
|
2823
|
-
}
|
|
2824
|
-
if (this._droppedSpansCount > 0) {
|
|
2825
|
-
diag.warn(`Dropped ${this._droppedSpansCount} spans because maxQueueSize reached`);
|
|
2826
|
-
this._droppedSpansCount = 0;
|
|
2827
|
-
}
|
|
2828
|
-
this._finishedSpans.push(span);
|
|
2829
|
-
this._maybeStartTimer();
|
|
2830
|
-
}
|
|
2831
|
-
/**
|
|
2832
|
-
* Send all spans to the exporter respecting the batch size limit
|
|
2833
|
-
* This function is used only on forceFlush or shutdown,
|
|
2834
|
-
* for all other cases _flush should be used
|
|
2835
|
-
* */
|
|
2836
|
-
_flushAll() {
|
|
2837
|
-
return new Promise((resolve2, reject) => {
|
|
2838
|
-
const promises = [];
|
|
2839
|
-
const count = Math.ceil(this._finishedSpans.length / this._maxExportBatchSize);
|
|
2840
|
-
for (let i = 0, j = count; i < j; i++) {
|
|
2841
|
-
promises.push(this._flushOneBatch());
|
|
2842
|
-
}
|
|
2843
|
-
Promise.all(promises).then(() => {
|
|
2844
|
-
resolve2();
|
|
2845
|
-
}).catch(reject);
|
|
2846
|
-
});
|
|
2847
|
-
}
|
|
2848
|
-
_flushOneBatch() {
|
|
2849
|
-
this._clearTimer();
|
|
2850
|
-
if (this._finishedSpans.length === 0) {
|
|
2851
|
-
return Promise.resolve();
|
|
2852
|
-
}
|
|
2853
|
-
return new Promise((resolve2, reject) => {
|
|
2854
|
-
const timer = setTimeout(() => {
|
|
2855
|
-
reject(new Error("Timeout"));
|
|
2856
|
-
}, this._exportTimeoutMillis);
|
|
2857
|
-
context.with(suppressTracing(context.active()), () => {
|
|
2858
|
-
let spans;
|
|
2859
|
-
if (this._finishedSpans.length <= this._maxExportBatchSize) {
|
|
2860
|
-
spans = this._finishedSpans;
|
|
2861
|
-
this._finishedSpans = [];
|
|
2862
|
-
} else {
|
|
2863
|
-
spans = this._finishedSpans.splice(0, this._maxExportBatchSize);
|
|
2864
|
-
}
|
|
2865
|
-
const doExport = () => this._exporter.export(spans, (result) => {
|
|
2866
|
-
clearTimeout(timer);
|
|
2867
|
-
if (result.code === ExportResultCode.SUCCESS) {
|
|
2868
|
-
resolve2();
|
|
2869
|
-
} else {
|
|
2870
|
-
reject(result.error ?? new Error("BatchSpanProcessor: span export failed"));
|
|
2871
|
-
}
|
|
2872
|
-
});
|
|
2873
|
-
let pendingResources = null;
|
|
2874
|
-
for (let i = 0, len = spans.length; i < len; i++) {
|
|
2875
|
-
const span = spans[i];
|
|
2876
|
-
if (span.resource.asyncAttributesPending && span.resource.waitForAsyncAttributes) {
|
|
2877
|
-
pendingResources ??= [];
|
|
2878
|
-
pendingResources.push(span.resource.waitForAsyncAttributes());
|
|
2879
|
-
}
|
|
2880
|
-
}
|
|
2881
|
-
if (pendingResources === null) {
|
|
2882
|
-
doExport();
|
|
2883
|
-
} else {
|
|
2884
|
-
Promise.all(pendingResources).then(doExport, (err) => {
|
|
2885
|
-
globalErrorHandler(err);
|
|
2886
|
-
reject(err);
|
|
2887
|
-
});
|
|
2888
|
-
}
|
|
2889
|
-
});
|
|
2890
|
-
});
|
|
2891
|
-
}
|
|
2892
|
-
_maybeStartTimer() {
|
|
2893
|
-
if (this._isExporting)
|
|
2894
|
-
return;
|
|
2895
|
-
const flush = () => {
|
|
2896
|
-
this._isExporting = true;
|
|
2897
|
-
this._flushOneBatch().finally(() => {
|
|
2898
|
-
this._isExporting = false;
|
|
2899
|
-
if (this._finishedSpans.length > 0) {
|
|
2900
|
-
this._clearTimer();
|
|
2901
|
-
this._maybeStartTimer();
|
|
2902
|
-
}
|
|
2903
|
-
}).catch((e) => {
|
|
2904
|
-
this._isExporting = false;
|
|
2905
|
-
globalErrorHandler(e);
|
|
2906
|
-
});
|
|
2907
|
-
};
|
|
2908
|
-
if (this._finishedSpans.length >= this._maxExportBatchSize) {
|
|
2909
|
-
return flush();
|
|
2910
|
-
}
|
|
2911
|
-
if (this._timer !== void 0)
|
|
2912
|
-
return;
|
|
2913
|
-
this._timer = setTimeout(() => flush(), this._scheduledDelayMillis);
|
|
2914
|
-
if (typeof this._timer !== "number") {
|
|
2915
|
-
this._timer.unref();
|
|
2916
|
-
}
|
|
2917
|
-
}
|
|
2918
|
-
_clearTimer() {
|
|
2919
|
-
if (this._timer !== void 0) {
|
|
2920
|
-
clearTimeout(this._timer);
|
|
2921
|
-
this._timer = void 0;
|
|
2922
|
-
}
|
|
2923
|
-
}
|
|
2924
|
-
};
|
|
2925
|
-
|
|
2926
|
-
// ../../node_modules/@opentelemetry/sdk-trace-base/build/esm/platform/node/export/BatchSpanProcessor.js
|
|
2927
|
-
var BatchSpanProcessor = class extends BatchSpanProcessorBase {
|
|
2928
|
-
onShutdown() {
|
|
2929
|
-
}
|
|
2930
|
-
};
|
|
2931
|
-
|
|
2932
|
-
// ../../node_modules/@opentelemetry/sdk-trace-base/build/esm/platform/node/RandomIdGenerator.js
|
|
2933
|
-
var SPAN_ID_BYTES = 8;
|
|
2934
|
-
var TRACE_ID_BYTES = 16;
|
|
2935
|
-
var RandomIdGenerator = class {
|
|
2936
|
-
/**
|
|
2937
|
-
* Returns a random 16-byte trace ID formatted/encoded as a 32 lowercase hex
|
|
2938
|
-
* characters corresponding to 128 bits.
|
|
2939
|
-
*/
|
|
2940
|
-
generateTraceId = getIdGenerator(TRACE_ID_BYTES);
|
|
2941
|
-
/**
|
|
2942
|
-
* Returns a random 8-byte span ID formatted/encoded as a 16 lowercase hex
|
|
2943
|
-
* characters corresponding to 64 bits.
|
|
2944
|
-
*/
|
|
2945
|
-
generateSpanId = getIdGenerator(SPAN_ID_BYTES);
|
|
2946
|
-
};
|
|
2947
|
-
var SHARED_BUFFER = Buffer.allocUnsafe(TRACE_ID_BYTES);
|
|
2948
|
-
function getIdGenerator(bytes) {
|
|
2949
|
-
return function generateId() {
|
|
2950
|
-
for (let i = 0; i < bytes / 4; i++) {
|
|
2951
|
-
SHARED_BUFFER.writeUInt32BE(Math.random() * 2 ** 32 >>> 0, i * 4);
|
|
2952
|
-
}
|
|
2953
|
-
for (let i = 0; i < bytes; i++) {
|
|
2954
|
-
if (SHARED_BUFFER[i] > 0) {
|
|
2955
|
-
break;
|
|
2956
|
-
} else if (i === bytes - 1) {
|
|
2957
|
-
SHARED_BUFFER[bytes - 1] = 1;
|
|
2958
|
-
}
|
|
2959
|
-
}
|
|
2960
|
-
return SHARED_BUFFER.toString("hex", 0, bytes);
|
|
2961
|
-
};
|
|
2962
|
-
}
|
|
2963
|
-
|
|
2964
|
-
// ../../node_modules/@opentelemetry/sdk-trace-base/build/esm/semconv.js
|
|
2965
|
-
var ATTR_OTEL_SPAN_PARENT_ORIGIN = "otel.span.parent.origin";
|
|
2966
|
-
var ATTR_OTEL_SPAN_SAMPLING_RESULT = "otel.span.sampling_result";
|
|
2967
|
-
var METRIC_OTEL_SDK_SPAN_LIVE = "otel.sdk.span.live";
|
|
2968
|
-
var METRIC_OTEL_SDK_SPAN_STARTED = "otel.sdk.span.started";
|
|
2969
|
-
|
|
2970
|
-
// ../../node_modules/@opentelemetry/sdk-trace-base/build/esm/TracerMetrics.js
|
|
2971
|
-
var TracerMetrics = class {
|
|
2972
|
-
startedSpans;
|
|
2973
|
-
liveSpans;
|
|
2974
|
-
constructor(meter) {
|
|
2975
|
-
this.startedSpans = meter.createCounter(METRIC_OTEL_SDK_SPAN_STARTED, {
|
|
2976
|
-
unit: "{span}",
|
|
2977
|
-
description: "The number of created spans."
|
|
2978
|
-
});
|
|
2979
|
-
this.liveSpans = meter.createUpDownCounter(METRIC_OTEL_SDK_SPAN_LIVE, {
|
|
2980
|
-
unit: "{span}",
|
|
2981
|
-
description: "The number of currently live spans."
|
|
2982
|
-
});
|
|
2983
|
-
}
|
|
2984
|
-
startSpan(parentSpanCtx, samplingDecision) {
|
|
2985
|
-
const samplingDecisionStr = samplingDecisionToString(samplingDecision);
|
|
2986
|
-
this.startedSpans.add(1, {
|
|
2987
|
-
[ATTR_OTEL_SPAN_PARENT_ORIGIN]: parentOrigin(parentSpanCtx),
|
|
2988
|
-
[ATTR_OTEL_SPAN_SAMPLING_RESULT]: samplingDecisionStr
|
|
2989
|
-
});
|
|
2990
|
-
if (samplingDecision === SamplingDecision2.NOT_RECORD) {
|
|
2991
|
-
return () => {
|
|
2992
|
-
};
|
|
2993
|
-
}
|
|
2994
|
-
const liveSpanAttributes = {
|
|
2995
|
-
[ATTR_OTEL_SPAN_SAMPLING_RESULT]: samplingDecisionStr
|
|
2996
|
-
};
|
|
2997
|
-
this.liveSpans.add(1, liveSpanAttributes);
|
|
2998
|
-
return () => {
|
|
2999
|
-
this.liveSpans.add(-1, liveSpanAttributes);
|
|
3000
|
-
};
|
|
3001
|
-
}
|
|
3002
|
-
};
|
|
3003
|
-
function parentOrigin(parentSpanContext) {
|
|
3004
|
-
if (!parentSpanContext) {
|
|
3005
|
-
return "none";
|
|
3006
|
-
}
|
|
3007
|
-
if (parentSpanContext.isRemote) {
|
|
3008
|
-
return "remote";
|
|
3009
|
-
}
|
|
3010
|
-
return "local";
|
|
3011
|
-
}
|
|
3012
|
-
function samplingDecisionToString(decision) {
|
|
3013
|
-
switch (decision) {
|
|
3014
|
-
case SamplingDecision2.RECORD_AND_SAMPLED:
|
|
3015
|
-
return "RECORD_AND_SAMPLE";
|
|
3016
|
-
case SamplingDecision2.RECORD:
|
|
3017
|
-
return "RECORD_ONLY";
|
|
3018
|
-
case SamplingDecision2.NOT_RECORD:
|
|
3019
|
-
return "DROP";
|
|
3020
|
-
}
|
|
3021
|
-
}
|
|
3022
|
-
|
|
3023
|
-
// ../../node_modules/@opentelemetry/sdk-trace-base/build/esm/version.js
|
|
3024
|
-
var VERSION3 = "2.6.1";
|
|
3025
|
-
|
|
3026
|
-
// ../../node_modules/@opentelemetry/sdk-trace-base/build/esm/Tracer.js
|
|
3027
|
-
var Tracer = class {
|
|
3028
|
-
_sampler;
|
|
3029
|
-
_generalLimits;
|
|
3030
|
-
_spanLimits;
|
|
3031
|
-
_idGenerator;
|
|
3032
|
-
instrumentationScope;
|
|
3033
|
-
_resource;
|
|
3034
|
-
_spanProcessor;
|
|
3035
|
-
_tracerMetrics;
|
|
3036
|
-
/**
|
|
3037
|
-
* Constructs a new Tracer instance.
|
|
3038
|
-
*/
|
|
3039
|
-
constructor(instrumentationScope, config, resource, spanProcessor) {
|
|
3040
|
-
const localConfig = mergeConfig(config);
|
|
3041
|
-
this._sampler = localConfig.sampler;
|
|
3042
|
-
this._generalLimits = localConfig.generalLimits;
|
|
3043
|
-
this._spanLimits = localConfig.spanLimits;
|
|
3044
|
-
this._idGenerator = config.idGenerator || new RandomIdGenerator();
|
|
3045
|
-
this._resource = resource;
|
|
3046
|
-
this._spanProcessor = spanProcessor;
|
|
3047
|
-
this.instrumentationScope = instrumentationScope;
|
|
3048
|
-
const meter = localConfig.meterProvider ? localConfig.meterProvider.getMeter("@opentelemetry/sdk-trace", VERSION3) : createNoopMeter();
|
|
3049
|
-
this._tracerMetrics = new TracerMetrics(meter);
|
|
3050
|
-
}
|
|
3051
|
-
/**
|
|
3052
|
-
* Starts a new Span or returns the default NoopSpan based on the sampling
|
|
3053
|
-
* decision.
|
|
3054
|
-
*/
|
|
3055
|
-
startSpan(name, options = {}, context2 = context.active()) {
|
|
3056
|
-
if (options.root) {
|
|
3057
|
-
context2 = trace.deleteSpan(context2);
|
|
3058
|
-
}
|
|
3059
|
-
const parentSpan = trace.getSpan(context2);
|
|
3060
|
-
if (isTracingSuppressed(context2)) {
|
|
3061
|
-
diag.debug("Instrumentation suppressed, returning Noop Span");
|
|
3062
|
-
const nonRecordingSpan = trace.wrapSpanContext(INVALID_SPAN_CONTEXT);
|
|
3063
|
-
return nonRecordingSpan;
|
|
3064
|
-
}
|
|
3065
|
-
const parentSpanContext = parentSpan?.spanContext();
|
|
3066
|
-
const spanId = this._idGenerator.generateSpanId();
|
|
3067
|
-
let validParentSpanContext;
|
|
3068
|
-
let traceId;
|
|
3069
|
-
let traceState;
|
|
3070
|
-
if (!parentSpanContext || !trace.isSpanContextValid(parentSpanContext)) {
|
|
3071
|
-
traceId = this._idGenerator.generateTraceId();
|
|
3072
|
-
} else {
|
|
3073
|
-
traceId = parentSpanContext.traceId;
|
|
3074
|
-
traceState = parentSpanContext.traceState;
|
|
3075
|
-
validParentSpanContext = parentSpanContext;
|
|
3076
|
-
}
|
|
3077
|
-
const spanKind = options.kind ?? SpanKind.INTERNAL;
|
|
3078
|
-
const links = (options.links ?? []).map((link) => {
|
|
3079
|
-
return {
|
|
3080
|
-
context: link.context,
|
|
3081
|
-
attributes: sanitizeAttributes(link.attributes)
|
|
3082
|
-
};
|
|
3083
|
-
});
|
|
3084
|
-
const attributes = sanitizeAttributes(options.attributes);
|
|
3085
|
-
const samplingResult = this._sampler.shouldSample(context2, traceId, name, spanKind, attributes, links);
|
|
3086
|
-
const recordEndMetrics = this._tracerMetrics.startSpan(parentSpanContext, samplingResult.decision);
|
|
3087
|
-
traceState = samplingResult.traceState ?? traceState;
|
|
3088
|
-
const traceFlags = samplingResult.decision === SamplingDecision.RECORD_AND_SAMPLED ? TraceFlags.SAMPLED : TraceFlags.NONE;
|
|
3089
|
-
const spanContext = { traceId, spanId, traceFlags, traceState };
|
|
3090
|
-
if (samplingResult.decision === SamplingDecision.NOT_RECORD) {
|
|
3091
|
-
diag.debug("Recording is off, propagating context in a non-recording span");
|
|
3092
|
-
const nonRecordingSpan = trace.wrapSpanContext(spanContext);
|
|
3093
|
-
return nonRecordingSpan;
|
|
3094
|
-
}
|
|
3095
|
-
const initAttributes = sanitizeAttributes(Object.assign(attributes, samplingResult.attributes));
|
|
3096
|
-
const span = new SpanImpl({
|
|
3097
|
-
resource: this._resource,
|
|
3098
|
-
scope: this.instrumentationScope,
|
|
3099
|
-
context: context2,
|
|
3100
|
-
spanContext,
|
|
3101
|
-
name,
|
|
3102
|
-
kind: spanKind,
|
|
3103
|
-
links,
|
|
3104
|
-
parentSpanContext: validParentSpanContext,
|
|
3105
|
-
attributes: initAttributes,
|
|
3106
|
-
startTime: options.startTime,
|
|
3107
|
-
spanProcessor: this._spanProcessor,
|
|
3108
|
-
spanLimits: this._spanLimits,
|
|
3109
|
-
recordEndMetrics
|
|
3110
|
-
});
|
|
3111
|
-
return span;
|
|
3112
|
-
}
|
|
3113
|
-
startActiveSpan(name, arg2, arg3, arg4) {
|
|
3114
|
-
let opts;
|
|
3115
|
-
let ctx;
|
|
3116
|
-
let fn;
|
|
3117
|
-
if (arguments.length < 2) {
|
|
3118
|
-
return;
|
|
3119
|
-
} else if (arguments.length === 2) {
|
|
3120
|
-
fn = arg2;
|
|
3121
|
-
} else if (arguments.length === 3) {
|
|
3122
|
-
opts = arg2;
|
|
3123
|
-
fn = arg3;
|
|
3124
|
-
} else {
|
|
3125
|
-
opts = arg2;
|
|
3126
|
-
ctx = arg3;
|
|
3127
|
-
fn = arg4;
|
|
3128
|
-
}
|
|
3129
|
-
const parentContext = ctx ?? context.active();
|
|
3130
|
-
const span = this.startSpan(name, opts, parentContext);
|
|
3131
|
-
const contextWithSpanSet = trace.setSpan(parentContext, span);
|
|
3132
|
-
return context.with(contextWithSpanSet, fn, void 0, span);
|
|
3133
|
-
}
|
|
3134
|
-
/** Returns the active {@link GeneralLimits}. */
|
|
3135
|
-
getGeneralLimits() {
|
|
3136
|
-
return this._generalLimits;
|
|
3137
|
-
}
|
|
3138
|
-
/** Returns the active {@link SpanLimits}. */
|
|
3139
|
-
getSpanLimits() {
|
|
3140
|
-
return this._spanLimits;
|
|
3141
|
-
}
|
|
3142
|
-
};
|
|
3143
|
-
|
|
3144
|
-
// ../../node_modules/@opentelemetry/sdk-trace-base/build/esm/MultiSpanProcessor.js
|
|
3145
|
-
var MultiSpanProcessor = class {
|
|
3146
|
-
_spanProcessors;
|
|
3147
|
-
constructor(spanProcessors) {
|
|
3148
|
-
this._spanProcessors = spanProcessors;
|
|
3149
|
-
}
|
|
3150
|
-
forceFlush() {
|
|
3151
|
-
const promises = [];
|
|
3152
|
-
for (const spanProcessor of this._spanProcessors) {
|
|
3153
|
-
promises.push(spanProcessor.forceFlush());
|
|
3154
|
-
}
|
|
3155
|
-
return new Promise((resolve2) => {
|
|
3156
|
-
Promise.all(promises).then(() => {
|
|
3157
|
-
resolve2();
|
|
3158
|
-
}).catch((error) => {
|
|
3159
|
-
globalErrorHandler(error || new Error("MultiSpanProcessor: forceFlush failed"));
|
|
3160
|
-
resolve2();
|
|
3161
|
-
});
|
|
3162
|
-
});
|
|
3163
|
-
}
|
|
3164
|
-
onStart(span, context2) {
|
|
3165
|
-
for (const spanProcessor of this._spanProcessors) {
|
|
3166
|
-
spanProcessor.onStart(span, context2);
|
|
3167
|
-
}
|
|
3168
|
-
}
|
|
3169
|
-
onEnding(span) {
|
|
3170
|
-
for (const spanProcessor of this._spanProcessors) {
|
|
3171
|
-
if (spanProcessor.onEnding) {
|
|
3172
|
-
spanProcessor.onEnding(span);
|
|
3173
|
-
}
|
|
3174
|
-
}
|
|
3175
|
-
}
|
|
3176
|
-
onEnd(span) {
|
|
3177
|
-
for (const spanProcessor of this._spanProcessors) {
|
|
3178
|
-
spanProcessor.onEnd(span);
|
|
3179
|
-
}
|
|
3180
|
-
}
|
|
3181
|
-
shutdown() {
|
|
3182
|
-
const promises = [];
|
|
3183
|
-
for (const spanProcessor of this._spanProcessors) {
|
|
3184
|
-
promises.push(spanProcessor.shutdown());
|
|
3185
|
-
}
|
|
3186
|
-
return new Promise((resolve2, reject) => {
|
|
3187
|
-
Promise.all(promises).then(() => {
|
|
3188
|
-
resolve2();
|
|
3189
|
-
}, reject);
|
|
3190
|
-
});
|
|
3191
|
-
}
|
|
3192
|
-
};
|
|
3193
|
-
|
|
3194
|
-
// ../../node_modules/@opentelemetry/sdk-trace-base/build/esm/BasicTracerProvider.js
|
|
3195
|
-
var ForceFlushState;
|
|
3196
|
-
(function(ForceFlushState2) {
|
|
3197
|
-
ForceFlushState2[ForceFlushState2["resolved"] = 0] = "resolved";
|
|
3198
|
-
ForceFlushState2[ForceFlushState2["timeout"] = 1] = "timeout";
|
|
3199
|
-
ForceFlushState2[ForceFlushState2["error"] = 2] = "error";
|
|
3200
|
-
ForceFlushState2[ForceFlushState2["unresolved"] = 3] = "unresolved";
|
|
3201
|
-
})(ForceFlushState || (ForceFlushState = {}));
|
|
3202
|
-
var BasicTracerProvider = class {
|
|
3203
|
-
_config;
|
|
3204
|
-
_tracers = /* @__PURE__ */ new Map();
|
|
3205
|
-
_resource;
|
|
3206
|
-
_activeSpanProcessor;
|
|
3207
|
-
constructor(config = {}) {
|
|
3208
|
-
const mergedConfig = merge({}, loadDefaultConfig(), reconfigureLimits(config));
|
|
3209
|
-
this._resource = mergedConfig.resource ?? defaultResource();
|
|
3210
|
-
this._config = Object.assign({}, mergedConfig, {
|
|
3211
|
-
resource: this._resource
|
|
3212
|
-
});
|
|
3213
|
-
const spanProcessors = [];
|
|
3214
|
-
if (config.spanProcessors?.length) {
|
|
3215
|
-
spanProcessors.push(...config.spanProcessors);
|
|
3216
|
-
}
|
|
3217
|
-
this._activeSpanProcessor = new MultiSpanProcessor(spanProcessors);
|
|
3218
|
-
}
|
|
3219
|
-
getTracer(name, version, options) {
|
|
3220
|
-
const key = `${name}@${version || ""}:${options?.schemaUrl || ""}`;
|
|
3221
|
-
if (!this._tracers.has(key)) {
|
|
3222
|
-
this._tracers.set(key, new Tracer({ name, version, schemaUrl: options?.schemaUrl }, this._config, this._resource, this._activeSpanProcessor));
|
|
3223
|
-
}
|
|
3224
|
-
return this._tracers.get(key);
|
|
3225
|
-
}
|
|
3226
|
-
forceFlush() {
|
|
3227
|
-
const timeout = this._config.forceFlushTimeoutMillis;
|
|
3228
|
-
const promises = this._activeSpanProcessor["_spanProcessors"].map((spanProcessor) => {
|
|
3229
|
-
return new Promise((resolve2) => {
|
|
3230
|
-
let state;
|
|
3231
|
-
const timeoutInterval = setTimeout(() => {
|
|
3232
|
-
resolve2(new Error(`Span processor did not completed within timeout period of ${timeout} ms`));
|
|
3233
|
-
state = ForceFlushState.timeout;
|
|
3234
|
-
}, timeout);
|
|
3235
|
-
spanProcessor.forceFlush().then(() => {
|
|
3236
|
-
clearTimeout(timeoutInterval);
|
|
3237
|
-
if (state !== ForceFlushState.timeout) {
|
|
3238
|
-
state = ForceFlushState.resolved;
|
|
3239
|
-
resolve2(state);
|
|
3240
|
-
}
|
|
3241
|
-
}).catch((error) => {
|
|
3242
|
-
clearTimeout(timeoutInterval);
|
|
3243
|
-
state = ForceFlushState.error;
|
|
3244
|
-
resolve2(error);
|
|
3245
|
-
});
|
|
3246
|
-
});
|
|
3247
|
-
});
|
|
3248
|
-
return new Promise((resolve2, reject) => {
|
|
3249
|
-
Promise.all(promises).then((results) => {
|
|
3250
|
-
const errors = results.filter((result) => result !== ForceFlushState.resolved);
|
|
3251
|
-
if (errors.length > 0) {
|
|
3252
|
-
reject(errors);
|
|
3253
|
-
} else {
|
|
3254
|
-
resolve2();
|
|
3255
|
-
}
|
|
3256
|
-
}).catch((error) => reject([error]));
|
|
3257
|
-
});
|
|
3258
|
-
}
|
|
3259
|
-
shutdown() {
|
|
3260
|
-
return this._activeSpanProcessor.shutdown();
|
|
3261
|
-
}
|
|
3262
|
-
};
|
|
3263
|
-
|
|
3264
|
-
// src/lifecycle.ts
|
|
3265
|
-
import { EventEmitter } from "node:events";
|
|
3266
|
-
|
|
3267
|
-
// src/signal-handler.ts
|
|
3268
|
-
var coexistenceState = "unknown";
|
|
3269
|
-
function setCoexistenceState(s) {
|
|
3270
|
-
coexistenceState = s;
|
|
3271
|
-
}
|
|
3272
|
-
function getCoexistenceState() {
|
|
3273
|
-
return coexistenceState;
|
|
3274
|
-
}
|
|
3275
|
-
|
|
3276
|
-
// src/lifecycle.ts
|
|
3277
|
-
var CoreState = {
|
|
3278
|
-
IDLE: "IDLE",
|
|
3279
|
-
REGISTERING: "REGISTERING",
|
|
3280
|
-
KEY_PENDING: "KEY_PENDING",
|
|
3281
|
-
KEY_RESOLVED: "KEY_RESOLVED",
|
|
3282
|
-
ACTIVE: "ACTIVE",
|
|
3283
|
-
ACTIVE_DEGRADED: "ACTIVE_DEGRADED",
|
|
3284
|
-
SHUTTING_DOWN: "SHUTTING_DOWN",
|
|
3285
|
-
SHUTDOWN: "SHUTDOWN",
|
|
3286
|
-
PRODUCTION_DISABLED: "PRODUCTION_DISABLED",
|
|
3287
|
-
REGISTRATION_FAILED: "REGISTRATION_FAILED"
|
|
3288
|
-
};
|
|
3289
|
-
var AuthState = {
|
|
3290
|
-
ANONYMOUS: "ANONYMOUS",
|
|
3291
|
-
AUTHENTICATED: "AUTHENTICATED",
|
|
3292
|
-
CLAIMING: "CLAIMING",
|
|
3293
|
-
CLAIMED: "CLAIMED"
|
|
3294
|
-
};
|
|
3295
|
-
var OtelState = {
|
|
3296
|
-
UNCONFIGURED: "UNCONFIGURED",
|
|
3297
|
-
CONFIGURING: "CONFIGURING",
|
|
3298
|
-
OWNS_PROVIDER: "OWNS_PROVIDER",
|
|
3299
|
-
AUTO_ATTACHED: "AUTO_ATTACHED",
|
|
3300
|
-
PROCESSOR_PRESENT: "PROCESSOR_PRESENT",
|
|
3301
|
-
COEXISTENCE_FAILED: "COEXISTENCE_FAILED"
|
|
3302
|
-
};
|
|
3303
|
-
var VALID_CORE_TRANSITIONS = {
|
|
3304
|
-
[CoreState.IDLE]: [CoreState.REGISTERING, CoreState.REGISTRATION_FAILED, CoreState.SHUTTING_DOWN],
|
|
3305
|
-
[CoreState.REGISTERING]: [
|
|
3306
|
-
CoreState.KEY_PENDING,
|
|
3307
|
-
CoreState.PRODUCTION_DISABLED,
|
|
3308
|
-
CoreState.REGISTRATION_FAILED,
|
|
3309
|
-
CoreState.SHUTTING_DOWN
|
|
3310
|
-
],
|
|
3311
|
-
[CoreState.KEY_PENDING]: [
|
|
3312
|
-
CoreState.KEY_RESOLVED,
|
|
3313
|
-
CoreState.REGISTRATION_FAILED,
|
|
3314
|
-
CoreState.SHUTTING_DOWN
|
|
3315
|
-
],
|
|
3316
|
-
[CoreState.KEY_RESOLVED]: [
|
|
3317
|
-
CoreState.ACTIVE,
|
|
3318
|
-
CoreState.ACTIVE_DEGRADED,
|
|
3319
|
-
CoreState.SHUTTING_DOWN
|
|
3320
|
-
],
|
|
3321
|
-
[CoreState.ACTIVE]: [
|
|
3322
|
-
CoreState.ACTIVE_DEGRADED,
|
|
3323
|
-
CoreState.SHUTTING_DOWN
|
|
3324
|
-
],
|
|
3325
|
-
[CoreState.ACTIVE_DEGRADED]: [
|
|
3326
|
-
CoreState.ACTIVE,
|
|
3327
|
-
CoreState.SHUTTING_DOWN
|
|
3328
|
-
],
|
|
3329
|
-
[CoreState.SHUTTING_DOWN]: [CoreState.SHUTDOWN],
|
|
3330
|
-
[CoreState.SHUTDOWN]: [],
|
|
3331
|
-
[CoreState.PRODUCTION_DISABLED]: [],
|
|
3332
|
-
[CoreState.REGISTRATION_FAILED]: []
|
|
3333
|
-
};
|
|
3334
|
-
var VALID_AUTH_TRANSITIONS = {
|
|
3335
|
-
[AuthState.ANONYMOUS]: [AuthState.CLAIMING],
|
|
3336
|
-
[AuthState.AUTHENTICATED]: [AuthState.CLAIMING],
|
|
3337
|
-
[AuthState.CLAIMING]: [AuthState.CLAIMED],
|
|
3338
|
-
[AuthState.CLAIMED]: [AuthState.CLAIMING]
|
|
3339
|
-
};
|
|
3340
|
-
var VALID_OTEL_TRANSITIONS = {
|
|
3341
|
-
[OtelState.UNCONFIGURED]: [OtelState.CONFIGURING],
|
|
3342
|
-
[OtelState.CONFIGURING]: [
|
|
3343
|
-
OtelState.OWNS_PROVIDER,
|
|
3344
|
-
OtelState.AUTO_ATTACHED,
|
|
3345
|
-
OtelState.PROCESSOR_PRESENT,
|
|
3346
|
-
OtelState.COEXISTENCE_FAILED
|
|
3347
|
-
],
|
|
3348
|
-
[OtelState.OWNS_PROVIDER]: [],
|
|
3349
|
-
[OtelState.AUTO_ATTACHED]: [],
|
|
3350
|
-
[OtelState.PROCESSOR_PRESENT]: [],
|
|
3351
|
-
[OtelState.COEXISTENCE_FAILED]: []
|
|
3352
|
-
};
|
|
3353
|
-
var _coreState = CoreState.IDLE;
|
|
3354
|
-
var _authState = AuthState.ANONYMOUS;
|
|
3355
|
-
var _otelState = OtelState.UNCONFIGURED;
|
|
3356
|
-
var _emitter = new EventEmitter();
|
|
3357
|
-
var _logger = null;
|
|
3358
|
-
var _initialized = false;
|
|
3359
|
-
var _initWarned = false;
|
|
3360
|
-
var _coreReadyEmitted = false;
|
|
3361
|
-
var _authInitialized = false;
|
|
3362
|
-
var _emitting = false;
|
|
3363
|
-
function initLifecycle(options) {
|
|
3364
|
-
if (_initialized) {
|
|
3365
|
-
options.logger("warn", "[glasstrace] initLifecycle() called twice \u2014 ignored.");
|
|
3366
|
-
return;
|
|
3367
|
-
}
|
|
3368
|
-
_logger = options.logger;
|
|
3369
|
-
_initialized = true;
|
|
3370
|
-
}
|
|
3371
|
-
function warnIfNotInitialized() {
|
|
3372
|
-
if (!_initialized && !_initWarned) {
|
|
3373
|
-
_initWarned = true;
|
|
3374
|
-
console.warn(
|
|
3375
|
-
"[glasstrace] Lifecycle state changed before initLifecycle() was called. Logger not available \u2014 errors will be silent."
|
|
3376
|
-
);
|
|
3377
|
-
}
|
|
3378
|
-
}
|
|
3379
|
-
function setCoreState(to) {
|
|
3380
|
-
warnIfNotInitialized();
|
|
3381
|
-
const from = _coreState;
|
|
3382
|
-
if (from === to) return;
|
|
3383
|
-
const valid = VALID_CORE_TRANSITIONS[from];
|
|
3384
|
-
if (!valid.includes(to)) {
|
|
3385
|
-
_logger?.(
|
|
3386
|
-
"warn",
|
|
3387
|
-
`[glasstrace] Invalid core state transition: ${from} \u2192 ${to}. Ignored.`
|
|
3388
|
-
);
|
|
3389
|
-
return;
|
|
3390
|
-
}
|
|
3391
|
-
_coreState = to;
|
|
3392
|
-
if (_emitting) return;
|
|
3393
|
-
_emitting = true;
|
|
3394
|
-
try {
|
|
3395
|
-
emitSafe("core:state_changed", { from, to });
|
|
3396
|
-
const current = _coreState;
|
|
3397
|
-
if (!_coreReadyEmitted && (current === CoreState.ACTIVE || current === CoreState.ACTIVE_DEGRADED)) {
|
|
3398
|
-
_coreReadyEmitted = true;
|
|
3399
|
-
emitSafe("core:ready", {});
|
|
3400
|
-
}
|
|
3401
|
-
if (current === CoreState.SHUTTING_DOWN) {
|
|
3402
|
-
emitSafe("core:shutdown_started", {});
|
|
3403
|
-
}
|
|
3404
|
-
if (current === CoreState.SHUTDOWN) {
|
|
3405
|
-
emitSafe("core:shutdown_completed", {});
|
|
3406
|
-
}
|
|
3407
|
-
} finally {
|
|
3408
|
-
_emitting = false;
|
|
3409
|
-
}
|
|
3410
|
-
}
|
|
3411
|
-
function initAuthState(state) {
|
|
3412
|
-
if (_authInitialized) {
|
|
3413
|
-
_logger?.(
|
|
3414
|
-
"warn",
|
|
3415
|
-
"[glasstrace] initAuthState() called after auth state already initialized. Ignored."
|
|
3416
|
-
);
|
|
3417
|
-
return;
|
|
3418
|
-
}
|
|
3419
|
-
_authInitialized = true;
|
|
3420
|
-
_authState = state;
|
|
3421
|
-
}
|
|
3422
|
-
function setAuthState(to) {
|
|
3423
|
-
warnIfNotInitialized();
|
|
3424
|
-
const from = _authState;
|
|
3425
|
-
if (from === to) return;
|
|
3426
|
-
const valid = VALID_AUTH_TRANSITIONS[from];
|
|
3427
|
-
if (!valid.includes(to)) {
|
|
3428
|
-
_logger?.(
|
|
3429
|
-
"warn",
|
|
3430
|
-
`[glasstrace] Invalid auth state transition: ${from} \u2192 ${to}. Ignored.`
|
|
3431
|
-
);
|
|
3432
|
-
return;
|
|
3433
|
-
}
|
|
3434
|
-
_authState = to;
|
|
3435
|
-
}
|
|
3436
|
-
function setOtelState(to) {
|
|
3437
|
-
warnIfNotInitialized();
|
|
3438
|
-
const from = _otelState;
|
|
3439
|
-
if (from === to) return;
|
|
3440
|
-
const valid = VALID_OTEL_TRANSITIONS[from];
|
|
3441
|
-
if (!valid.includes(to)) {
|
|
3442
|
-
_logger?.(
|
|
3443
|
-
"warn",
|
|
3444
|
-
`[glasstrace] Invalid OTel state transition: ${from} \u2192 ${to}. Ignored.`
|
|
3445
|
-
);
|
|
3446
|
-
return;
|
|
3447
|
-
}
|
|
3448
|
-
_otelState = to;
|
|
3449
|
-
}
|
|
3450
|
-
function getCoreState() {
|
|
3451
|
-
return _coreState;
|
|
3452
|
-
}
|
|
3453
|
-
function getSdkState() {
|
|
3454
|
-
return {
|
|
3455
|
-
core: _coreState,
|
|
3456
|
-
auth: _authState,
|
|
3457
|
-
otel: _otelState
|
|
3458
|
-
};
|
|
3459
|
-
}
|
|
3460
|
-
function onLifecycleEvent(event, listener) {
|
|
3461
|
-
_emitter.on(event, listener);
|
|
3462
|
-
}
|
|
3463
|
-
function emitLifecycleEvent(event, payload) {
|
|
3464
|
-
emitSafe(event, payload);
|
|
3465
|
-
}
|
|
3466
|
-
function offLifecycleEvent(event, listener) {
|
|
3467
|
-
_emitter.off(event, listener);
|
|
3468
|
-
}
|
|
3469
|
-
function emitSafe(event, payload) {
|
|
3470
|
-
const listeners = _emitter.listeners(event);
|
|
3471
|
-
for (const listener of listeners) {
|
|
3472
|
-
try {
|
|
3473
|
-
const result = listener(payload);
|
|
3474
|
-
if (result && typeof result.catch === "function") {
|
|
3475
|
-
result.catch((err) => {
|
|
3476
|
-
_logger?.(
|
|
3477
|
-
"error",
|
|
3478
|
-
`[glasstrace] Async error in lifecycle event listener for "${event}": ${err instanceof Error ? err.message : String(err)}`
|
|
3479
|
-
);
|
|
3480
|
-
});
|
|
3481
|
-
}
|
|
3482
|
-
} catch (err) {
|
|
3483
|
-
_logger?.(
|
|
3484
|
-
"error",
|
|
3485
|
-
`[glasstrace] Error in lifecycle event listener for "${event}": ${err instanceof Error ? err.message : String(err)}`
|
|
3486
|
-
);
|
|
3487
|
-
}
|
|
3488
|
-
}
|
|
3489
|
-
}
|
|
3490
|
-
function isReady() {
|
|
3491
|
-
return _coreState === CoreState.ACTIVE || _coreState === CoreState.ACTIVE_DEGRADED;
|
|
3492
|
-
}
|
|
3493
|
-
function waitForReady(timeoutMs = 3e4) {
|
|
3494
|
-
if (isReady()) {
|
|
3495
|
-
return Promise.resolve();
|
|
3496
|
-
}
|
|
3497
|
-
if (_coreState === CoreState.PRODUCTION_DISABLED || _coreState === CoreState.REGISTRATION_FAILED || _coreState === CoreState.SHUTTING_DOWN || _coreState === CoreState.SHUTDOWN) {
|
|
3498
|
-
return Promise.reject(new Error(`SDK is in terminal state: ${_coreState}`));
|
|
3499
|
-
}
|
|
3500
|
-
return new Promise((resolve2, reject) => {
|
|
3501
|
-
let settled = false;
|
|
3502
|
-
const listener = ({ to }) => {
|
|
3503
|
-
if (settled) return;
|
|
3504
|
-
if (to === CoreState.ACTIVE || to === CoreState.ACTIVE_DEGRADED) {
|
|
3505
|
-
settled = true;
|
|
3506
|
-
offLifecycleEvent("core:state_changed", listener);
|
|
3507
|
-
resolve2();
|
|
3508
|
-
} else if (to === CoreState.PRODUCTION_DISABLED || to === CoreState.REGISTRATION_FAILED || to === CoreState.SHUTTING_DOWN || to === CoreState.SHUTDOWN) {
|
|
3509
|
-
settled = true;
|
|
3510
|
-
offLifecycleEvent("core:state_changed", listener);
|
|
3511
|
-
reject(new Error(`SDK reached terminal state: ${to}`));
|
|
3512
|
-
}
|
|
3513
|
-
};
|
|
3514
|
-
onLifecycleEvent("core:state_changed", listener);
|
|
3515
|
-
if (timeoutMs > 0) {
|
|
3516
|
-
const timer = setTimeout(() => {
|
|
3517
|
-
if (settled) return;
|
|
3518
|
-
settled = true;
|
|
3519
|
-
offLifecycleEvent("core:state_changed", listener);
|
|
3520
|
-
reject(new Error(`waitForReady timed out after ${timeoutMs}ms (state: ${_coreState})`));
|
|
3521
|
-
}, timeoutMs);
|
|
3522
|
-
if (typeof timer === "object" && "unref" in timer) {
|
|
3523
|
-
timer.unref();
|
|
3524
|
-
}
|
|
3525
|
-
}
|
|
3526
|
-
});
|
|
3527
|
-
}
|
|
3528
|
-
function getStatus() {
|
|
3529
|
-
let mode;
|
|
3530
|
-
if (_coreState === CoreState.PRODUCTION_DISABLED) {
|
|
3531
|
-
mode = "disabled";
|
|
3532
|
-
} else if (_authState === AuthState.CLAIMING || _authState === AuthState.CLAIMED) {
|
|
3533
|
-
mode = "claiming";
|
|
3534
|
-
} else if (_authState === AuthState.AUTHENTICATED) {
|
|
3535
|
-
mode = "authenticated";
|
|
3536
|
-
} else {
|
|
3537
|
-
mode = "anonymous";
|
|
3538
|
-
}
|
|
3539
|
-
let tracing;
|
|
3540
|
-
if (_otelState === OtelState.COEXISTENCE_FAILED || _otelState === OtelState.UNCONFIGURED || _otelState === OtelState.CONFIGURING) {
|
|
3541
|
-
tracing = "not-configured";
|
|
3542
|
-
} else if (_coreState === CoreState.ACTIVE_DEGRADED) {
|
|
3543
|
-
tracing = "degraded";
|
|
3544
|
-
} else if (_otelState === OtelState.AUTO_ATTACHED || _otelState === OtelState.PROCESSOR_PRESENT) {
|
|
3545
|
-
tracing = "coexistence";
|
|
3546
|
-
} else {
|
|
3547
|
-
tracing = "active";
|
|
3548
|
-
}
|
|
3549
|
-
return {
|
|
3550
|
-
ready: isReady(),
|
|
3551
|
-
mode,
|
|
3552
|
-
tracing
|
|
3553
|
-
};
|
|
3554
|
-
}
|
|
3555
|
-
var _shutdownHooks = [];
|
|
3556
|
-
var _signalHandlersRegistered = false;
|
|
3557
|
-
var _signalHandler = null;
|
|
3558
|
-
var _beforeExitRegistered = false;
|
|
3559
|
-
var _beforeExitHandler = null;
|
|
3560
|
-
var _shutdownExecuted = false;
|
|
3561
|
-
function registerShutdownHook(hook) {
|
|
3562
|
-
_shutdownHooks.push(hook);
|
|
3563
|
-
_shutdownHooks.sort((a, b) => a.priority - b.priority);
|
|
3564
|
-
}
|
|
3565
|
-
async function executeShutdown(timeoutMs = 5e3) {
|
|
3566
|
-
if (_shutdownExecuted) return;
|
|
3567
|
-
_shutdownExecuted = true;
|
|
3568
|
-
setCoreState(CoreState.SHUTTING_DOWN);
|
|
3569
|
-
for (const hook of _shutdownHooks) {
|
|
3570
|
-
try {
|
|
3571
|
-
const hookPromise = hook.fn();
|
|
3572
|
-
hookPromise.catch(() => {
|
|
3573
|
-
});
|
|
3574
|
-
await Promise.race([
|
|
3575
|
-
hookPromise,
|
|
3576
|
-
new Promise((_, reject) => {
|
|
3577
|
-
const timer = setTimeout(() => reject(new Error(`Shutdown hook "${hook.name}" timed out`)), timeoutMs);
|
|
3578
|
-
if (typeof timer === "object" && "unref" in timer) {
|
|
3579
|
-
timer.unref();
|
|
3580
|
-
}
|
|
3581
|
-
})
|
|
3582
|
-
]);
|
|
3583
|
-
} catch (err) {
|
|
3584
|
-
_logger?.(
|
|
3585
|
-
"warn",
|
|
3586
|
-
`[glasstrace] Shutdown hook "${hook.name}" failed: ${err instanceof Error ? err.message : String(err)}`
|
|
3587
|
-
);
|
|
3588
|
-
}
|
|
3589
|
-
}
|
|
3590
|
-
setCoreState(CoreState.SHUTDOWN);
|
|
3591
|
-
}
|
|
3592
|
-
function registerSignalHandlers() {
|
|
3593
|
-
if (_signalHandlersRegistered) return;
|
|
3594
|
-
if (typeof process === "undefined" || typeof process.once !== "function") return;
|
|
3595
|
-
_signalHandlersRegistered = true;
|
|
3596
|
-
const otherSigtermListeners = process.listenerCount("SIGTERM");
|
|
3597
|
-
const otherSigintListeners = process.listenerCount("SIGINT");
|
|
3598
|
-
const handler = (signal) => {
|
|
3599
|
-
void executeShutdown().finally(() => {
|
|
3600
|
-
if (_signalHandler) {
|
|
3601
|
-
process.removeListener("SIGTERM", _signalHandler);
|
|
3602
|
-
process.removeListener("SIGINT", _signalHandler);
|
|
3603
|
-
}
|
|
3604
|
-
const otherListeners = signal === "SIGTERM" ? otherSigtermListeners : otherSigintListeners;
|
|
3605
|
-
const otherProviderOwnsSignal = getCoexistenceState() === "coexisting" && otherListeners > 0;
|
|
3606
|
-
if (!otherProviderOwnsSignal) {
|
|
3607
|
-
process.kill(process.pid, signal);
|
|
3608
|
-
}
|
|
3609
|
-
});
|
|
3610
|
-
};
|
|
3611
|
-
_signalHandler = handler;
|
|
3612
|
-
process.once("SIGTERM", handler);
|
|
3613
|
-
process.once("SIGINT", handler);
|
|
3614
|
-
}
|
|
3615
|
-
function registerBeforeExitTrigger() {
|
|
3616
|
-
if (_beforeExitRegistered) return;
|
|
3617
|
-
if (typeof process === "undefined" || typeof process.once !== "function") return;
|
|
3618
|
-
_beforeExitRegistered = true;
|
|
3619
|
-
const handler = () => {
|
|
3620
|
-
void executeShutdown();
|
|
3621
|
-
};
|
|
3622
|
-
_beforeExitHandler = handler;
|
|
3623
|
-
process.once("beforeExit", handler);
|
|
3624
|
-
}
|
|
3625
|
-
|
|
3626
|
-
// src/coexistence.ts
|
|
3627
|
-
var GLASSTRACE_EXPORTER_BRAND = /* @__PURE__ */ Symbol.for("glasstrace.exporter");
|
|
3628
|
-
function createGlasstraceSpanProcessor(options) {
|
|
3629
|
-
const config = resolveConfig(options);
|
|
3630
|
-
const exporterUrl = `${config.endpoint}/v1/traces`;
|
|
3631
|
-
const createOtlpExporter = (url, headers) => new OTLPTraceExporter({ url, headers });
|
|
3632
|
-
const exporter = new GlasstraceExporter({
|
|
3633
|
-
getApiKey: getResolvedApiKey,
|
|
3634
|
-
sessionManager: getSessionManager(),
|
|
3635
|
-
getConfig: () => getActiveConfig(),
|
|
3636
|
-
environment: config.environment,
|
|
3637
|
-
endpointUrl: exporterUrl,
|
|
3638
|
-
createDelegate: createOtlpExporter,
|
|
3639
|
-
// Propagate verbose so exporter-level enrichment and export logs
|
|
3640
|
-
// stay observable whether the processor is built automatically by
|
|
3641
|
-
// the coexistence path or wired manually by the developer.
|
|
3642
|
-
verbose: config.verbose
|
|
3643
|
-
});
|
|
3644
|
-
registerExporterForKeyNotification(exporter);
|
|
3645
|
-
return new BatchSpanProcessor(exporter, {
|
|
3646
|
-
scheduledDelayMillis: 1e3
|
|
3647
|
-
});
|
|
3648
|
-
}
|
|
3649
|
-
function isGlasstraceProcessorPresent(tracerProvider) {
|
|
3650
|
-
try {
|
|
3651
|
-
const proxy = tracerProvider;
|
|
3652
|
-
const delegate = typeof proxy.getDelegate === "function" ? proxy.getDelegate() : tracerProvider;
|
|
3653
|
-
const v2 = delegate;
|
|
3654
|
-
const v2Processors = v2._activeSpanProcessor?._spanProcessors;
|
|
3655
|
-
if (Array.isArray(v2Processors) && hasBrandedProcessor(v2Processors)) {
|
|
3656
|
-
return true;
|
|
3657
|
-
}
|
|
3658
|
-
const v1 = delegate;
|
|
3659
|
-
if (typeof v1.getActiveSpanProcessor === "function") {
|
|
3660
|
-
const active = v1.getActiveSpanProcessor();
|
|
3661
|
-
const processors = active?._spanProcessors;
|
|
3662
|
-
if (Array.isArray(processors) && hasBrandedProcessor(processors)) {
|
|
3663
|
-
return true;
|
|
3664
|
-
}
|
|
3665
|
-
}
|
|
3666
|
-
return false;
|
|
3667
|
-
} catch {
|
|
3668
|
-
return false;
|
|
3669
|
-
}
|
|
3670
|
-
}
|
|
3671
|
-
function tryAutoAttachGlasstraceProcessor(tracerProvider, options) {
|
|
3672
|
-
try {
|
|
3673
|
-
if (isGlasstraceProcessorPresent(tracerProvider)) {
|
|
3674
|
-
return "already_present";
|
|
3675
|
-
}
|
|
3676
|
-
const proxy = tracerProvider;
|
|
3677
|
-
const delegate = typeof proxy.getDelegate === "function" ? proxy.getDelegate() : tracerProvider;
|
|
3678
|
-
const withAdd = delegate;
|
|
3679
|
-
if (typeof withAdd.addSpanProcessor === "function") {
|
|
3680
|
-
const processor2 = createGlasstraceSpanProcessor(options);
|
|
3681
|
-
withAdd.addSpanProcessor(processor2);
|
|
3682
|
-
return { method: "v1_public", processor: processor2 };
|
|
3683
|
-
}
|
|
3684
|
-
const v2 = delegate;
|
|
3685
|
-
const multiProcessor = v2._activeSpanProcessor;
|
|
3686
|
-
if (!multiProcessor || !Array.isArray(multiProcessor._spanProcessors)) {
|
|
3687
|
-
return null;
|
|
3688
|
-
}
|
|
3689
|
-
const processor = createGlasstraceSpanProcessor(options);
|
|
3690
|
-
multiProcessor._spanProcessors.push(processor);
|
|
3691
|
-
return { method: "v2_private", processor };
|
|
3692
|
-
} catch {
|
|
3693
|
-
return null;
|
|
3694
|
-
}
|
|
3695
|
-
}
|
|
3696
|
-
function emitNudgeMessage() {
|
|
3697
|
-
const isSentry = detectSentry();
|
|
3698
|
-
if (isSentry) {
|
|
3699
|
-
sdkLog(
|
|
3700
|
-
"info",
|
|
3701
|
-
`[glasstrace] Detected existing OTel provider \u2014 auto-attached Glasstrace span processor.
|
|
3702
|
-
For a cleaner setup, add Glasstrace to your Sentry config:
|
|
3703
|
-
|
|
3704
|
-
import { createGlasstraceSpanProcessor } from '@glasstrace/sdk';
|
|
3705
|
-
|
|
3706
|
-
Sentry.init({
|
|
3707
|
-
dsn: '...',
|
|
3708
|
-
openTelemetrySpanProcessors: [createGlasstraceSpanProcessor()],
|
|
3709
|
-
});
|
|
3710
|
-
|
|
3711
|
-
This message will not appear once Glasstrace is added to your provider config.`
|
|
3712
|
-
);
|
|
3713
|
-
} else {
|
|
3714
|
-
sdkLog(
|
|
3715
|
-
"info",
|
|
3716
|
-
`[glasstrace] Detected existing OTel provider \u2014 auto-attached Glasstrace span processor.
|
|
3717
|
-
For a cleaner setup, add Glasstrace to your provider config:
|
|
3718
|
-
|
|
3719
|
-
import { createGlasstraceSpanProcessor } from '@glasstrace/sdk';
|
|
3720
|
-
|
|
3721
|
-
const provider = new BasicTracerProvider({
|
|
3722
|
-
spanProcessors: [
|
|
3723
|
-
// ... your existing processors,
|
|
3724
|
-
createGlasstraceSpanProcessor(),
|
|
3725
|
-
],
|
|
3726
|
-
});
|
|
3727
|
-
|
|
3728
|
-
This message will not appear once Glasstrace is added to your provider config.`
|
|
3729
|
-
);
|
|
3730
|
-
}
|
|
3731
|
-
}
|
|
3732
|
-
function emitGuidanceMessage() {
|
|
3733
|
-
const isSentry = detectSentry();
|
|
3734
|
-
if (isSentry) {
|
|
3735
|
-
sdkLog(
|
|
3736
|
-
"warn",
|
|
3737
|
-
`[glasstrace] An existing OTel TracerProvider is registered but Glasstrace could not auto-attach its span processor.
|
|
3738
|
-
Add Glasstrace to your Sentry config:
|
|
3739
|
-
|
|
3740
|
-
import { createGlasstraceSpanProcessor } from '@glasstrace/sdk';
|
|
3741
|
-
|
|
3742
|
-
Sentry.init({
|
|
3743
|
-
dsn: '...',
|
|
3744
|
-
openTelemetrySpanProcessors: [createGlasstraceSpanProcessor()],
|
|
3745
|
-
});`
|
|
3746
|
-
);
|
|
3747
|
-
} else {
|
|
3748
|
-
sdkLog(
|
|
3749
|
-
"warn",
|
|
3750
|
-
`[glasstrace] An existing OTel TracerProvider is registered but Glasstrace could not auto-attach its span processor.
|
|
3751
|
-
Add Glasstrace to your provider configuration:
|
|
3752
|
-
|
|
3753
|
-
import { createGlasstraceSpanProcessor } from '@glasstrace/sdk';
|
|
3754
|
-
|
|
3755
|
-
const provider = new BasicTracerProvider({
|
|
3756
|
-
spanProcessors: [
|
|
3757
|
-
// ... your existing processors,
|
|
3758
|
-
createGlasstraceSpanProcessor(),
|
|
3759
|
-
],
|
|
3760
|
-
});`
|
|
3761
|
-
);
|
|
3762
|
-
}
|
|
3763
|
-
}
|
|
3764
|
-
function hasBrandedProcessor(processors) {
|
|
3765
|
-
return processors.some((p) => {
|
|
3766
|
-
const exporter = p._exporter;
|
|
3767
|
-
return exporter?.[GLASSTRACE_EXPORTER_BRAND] === true;
|
|
3768
|
-
});
|
|
3769
|
-
}
|
|
3770
|
-
function detectSentry() {
|
|
3771
|
-
try {
|
|
3772
|
-
__require.resolve("@sentry/node");
|
|
3773
|
-
return true;
|
|
3774
|
-
} catch {
|
|
3775
|
-
try {
|
|
3776
|
-
__require.resolve("@sentry/nextjs");
|
|
3777
|
-
return true;
|
|
3778
|
-
} catch {
|
|
3779
|
-
return false;
|
|
3780
|
-
}
|
|
3781
|
-
}
|
|
3782
|
-
}
|
|
3783
|
-
|
|
3784
|
-
// src/otel-config.ts
|
|
3785
|
-
var _resolvedApiKey = API_KEY_PENDING;
|
|
3786
|
-
var _activeExporter = null;
|
|
3787
|
-
var _additionalExporters = [];
|
|
3788
|
-
var _injectedProcessor = null;
|
|
3789
|
-
function setResolvedApiKey(key) {
|
|
3790
|
-
_resolvedApiKey = key;
|
|
3791
|
-
}
|
|
3792
|
-
function getResolvedApiKey() {
|
|
3793
|
-
return _resolvedApiKey;
|
|
3794
|
-
}
|
|
3795
|
-
function notifyApiKeyResolved() {
|
|
3796
|
-
_activeExporter?.notifyKeyResolved();
|
|
3797
|
-
for (const exporter of _additionalExporters) {
|
|
3798
|
-
exporter.notifyKeyResolved();
|
|
3799
|
-
}
|
|
3800
|
-
}
|
|
3801
|
-
function registerExporterForKeyNotification(exporter) {
|
|
3802
|
-
_additionalExporters.push(exporter);
|
|
3803
|
-
}
|
|
3804
|
-
async function tryImport(moduleId) {
|
|
3805
|
-
try {
|
|
3806
|
-
return await Function("id", "return import(id)")(moduleId);
|
|
3807
|
-
} catch {
|
|
3808
|
-
return null;
|
|
3809
|
-
}
|
|
3810
|
-
}
|
|
3811
|
-
async function configureOtel(config, sessionManager) {
|
|
3812
|
-
setOtelState(OtelState.CONFIGURING);
|
|
3813
|
-
await new Promise((resolve2) => {
|
|
3814
|
-
if (typeof setImmediate === "function") {
|
|
3815
|
-
setImmediate(resolve2);
|
|
3816
|
-
} else {
|
|
3817
|
-
setTimeout(resolve2, 0);
|
|
3818
|
-
}
|
|
3819
|
-
});
|
|
3820
|
-
const existingProvider = trace.getTracerProvider();
|
|
3821
|
-
const probeTracer = existingProvider.getTracer("glasstrace-probe");
|
|
3822
|
-
const anotherProviderRegistered = probeTracer.constructor.name !== "ProxyTracer";
|
|
3823
|
-
if (anotherProviderRegistered) {
|
|
3824
|
-
setCoexistenceState("coexisting");
|
|
3825
|
-
await runCoexistencePath(existingProvider, config);
|
|
3826
|
-
return;
|
|
3827
|
-
}
|
|
3828
|
-
setCoexistenceState("sole-owner");
|
|
3829
|
-
await runRegistrationPath(config, sessionManager);
|
|
3830
|
-
}
|
|
3831
|
-
async function runCoexistencePath(existingProvider, config) {
|
|
3832
|
-
const result = tryAutoAttachGlasstraceProcessor(existingProvider, {
|
|
3833
|
-
endpoint: config.endpoint,
|
|
3834
|
-
verbose: config.verbose
|
|
3835
|
-
});
|
|
3836
|
-
if (result === "already_present") {
|
|
3837
|
-
if (config.verbose) {
|
|
3838
|
-
sdkLog("info", "[glasstrace] Existing provider detected \u2014 Glasstrace processor already present.");
|
|
3839
|
-
}
|
|
3840
|
-
setOtelState(OtelState.PROCESSOR_PRESENT);
|
|
3841
|
-
emitLifecycleEvent("otel:configured", { state: OtelState.PROCESSOR_PRESENT, scenario: "B-clean" });
|
|
3842
|
-
return;
|
|
3843
|
-
}
|
|
3844
|
-
if (result !== null) {
|
|
3845
|
-
_injectedProcessor = result.processor;
|
|
3846
|
-
if (config.verbose) {
|
|
3847
|
-
sdkLog(
|
|
3848
|
-
"info",
|
|
3849
|
-
"[glasstrace] Existing provider detected \u2014 auto-attached Glasstrace span processor."
|
|
3850
|
-
);
|
|
3851
|
-
}
|
|
3852
|
-
registerShutdownHook({
|
|
3853
|
-
name: "coexistence-flush",
|
|
3854
|
-
priority: 5,
|
|
3855
|
-
fn: async () => {
|
|
3856
|
-
if (_injectedProcessor) {
|
|
3857
|
-
await _injectedProcessor.forceFlush();
|
|
3858
|
-
}
|
|
3859
|
-
}
|
|
3860
|
-
});
|
|
3861
|
-
registerBeforeExitTrigger();
|
|
3862
|
-
const scenario = result.method === "v1_public" ? "D1" : "B-auto";
|
|
3863
|
-
setOtelState(OtelState.AUTO_ATTACHED);
|
|
3864
|
-
emitLifecycleEvent("otel:configured", { state: OtelState.AUTO_ATTACHED, scenario });
|
|
3865
|
-
emitLifecycleEvent("otel:injection_succeeded", { method: result.method });
|
|
3866
|
-
emitNudgeMessage();
|
|
3867
|
-
return;
|
|
3868
|
-
}
|
|
3869
|
-
if (config.verbose) {
|
|
3870
|
-
sdkLog("info", "[glasstrace] Existing provider detected \u2014 could not auto-attach.");
|
|
3871
|
-
}
|
|
3872
|
-
emitGuidanceMessage();
|
|
3873
|
-
setOtelState(OtelState.COEXISTENCE_FAILED);
|
|
3874
|
-
emitLifecycleEvent("otel:configured", { state: OtelState.COEXISTENCE_FAILED, scenario: "C/F" });
|
|
3875
|
-
emitLifecycleEvent("otel:injection_failed", { reason: "provider internals inaccessible" });
|
|
3876
|
-
const coreState = getCoreState();
|
|
3877
|
-
if (coreState === CoreState.ACTIVE || coreState === CoreState.KEY_RESOLVED) {
|
|
3878
|
-
setCoreState(CoreState.ACTIVE_DEGRADED);
|
|
3879
|
-
}
|
|
3880
|
-
}
|
|
3881
|
-
async function runRegistrationPath(config, sessionManager) {
|
|
3882
|
-
const exporterUrl = `${config.endpoint}/v1/traces`;
|
|
3883
|
-
const createOtlpExporter = (url, headers) => new OTLPTraceExporter({ url, headers });
|
|
3884
|
-
const glasstraceExporter = new GlasstraceExporter({
|
|
3885
|
-
getApiKey: getResolvedApiKey,
|
|
3886
|
-
sessionManager,
|
|
3887
|
-
getConfig: () => getActiveConfig(),
|
|
3888
|
-
environment: config.environment,
|
|
3889
|
-
endpointUrl: exporterUrl,
|
|
3890
|
-
createDelegate: createOtlpExporter,
|
|
3891
|
-
verbose: config.verbose
|
|
3892
|
-
});
|
|
3893
|
-
_activeExporter = glasstraceExporter;
|
|
3894
|
-
const vercelOtel = await tryImport("@vercel/otel");
|
|
3895
|
-
if (vercelOtel && typeof vercelOtel.registerOTel === "function") {
|
|
3896
|
-
const otelConfig = {
|
|
3897
|
-
serviceName: "glasstrace-sdk",
|
|
3898
|
-
traceExporter: glasstraceExporter
|
|
3899
|
-
};
|
|
3900
|
-
const prismaModule2 = await tryImport("@prisma/instrumentation");
|
|
3901
|
-
if (prismaModule2) {
|
|
3902
|
-
const PrismaInstrumentation = prismaModule2.PrismaInstrumentation;
|
|
3903
|
-
if (PrismaInstrumentation) {
|
|
3904
|
-
otelConfig.instrumentations = [new PrismaInstrumentation()];
|
|
3905
|
-
}
|
|
3906
|
-
}
|
|
3907
|
-
vercelOtel.registerOTel(otelConfig);
|
|
3908
|
-
const vercelProxy = trace.getTracerProvider();
|
|
3909
|
-
const vercelConcreteProvider = typeof vercelProxy.getDelegate === "function" ? vercelProxy.getDelegate() : vercelProxy;
|
|
3910
|
-
registerShutdownHook({
|
|
3911
|
-
name: "vercel-otel-shutdown",
|
|
3912
|
-
priority: 0,
|
|
3913
|
-
fn: async () => {
|
|
3914
|
-
try {
|
|
3915
|
-
await vercelConcreteProvider.shutdown?.();
|
|
3916
|
-
} catch {
|
|
3917
|
-
}
|
|
3918
|
-
}
|
|
3919
|
-
});
|
|
3920
|
-
registerBeforeExitTrigger();
|
|
3921
|
-
setOtelState(OtelState.OWNS_PROVIDER);
|
|
3922
|
-
emitLifecycleEvent("otel:configured", { state: OtelState.OWNS_PROVIDER, scenario: "E" });
|
|
3923
|
-
return;
|
|
3924
|
-
}
|
|
3925
|
-
if (config.verbose) {
|
|
3926
|
-
diag.setLogger(
|
|
3927
|
-
{
|
|
3928
|
-
verbose: (msg) => sdkLog("info", `[otel] ${msg}`),
|
|
3929
|
-
debug: (msg) => sdkLog("info", `[otel] ${msg}`),
|
|
3930
|
-
info: (msg) => sdkLog("info", `[otel] ${msg}`),
|
|
3931
|
-
warn: (msg) => sdkLog("warn", `[otel] ${msg}`),
|
|
3932
|
-
error: (msg) => sdkLog("error", `[otel] ${msg}`)
|
|
3933
|
-
},
|
|
3934
|
-
DiagLogLevel.WARN
|
|
3935
|
-
);
|
|
3936
|
-
}
|
|
3937
|
-
const processor = new BatchSpanProcessor(glasstraceExporter, {
|
|
3938
|
-
scheduledDelayMillis: 1e3
|
|
3939
|
-
});
|
|
3940
|
-
const provider = new BasicTracerProvider({
|
|
3941
|
-
spanProcessors: [processor]
|
|
3942
|
-
});
|
|
3943
|
-
trace.setGlobalTracerProvider(provider);
|
|
3944
|
-
registerShutdownHook({
|
|
3945
|
-
name: "otel-provider-shutdown",
|
|
3946
|
-
priority: 0,
|
|
3947
|
-
fn: async () => {
|
|
3948
|
-
await provider.shutdown();
|
|
3949
|
-
}
|
|
3950
|
-
});
|
|
3951
|
-
registerBeforeExitTrigger();
|
|
3952
|
-
const prismaModule = await tryImport("@prisma/instrumentation");
|
|
3953
|
-
if (prismaModule) {
|
|
3954
|
-
const PrismaInstrumentation = prismaModule.PrismaInstrumentation;
|
|
3955
|
-
if (PrismaInstrumentation) {
|
|
3956
|
-
try {
|
|
3957
|
-
const inst = new PrismaInstrumentation();
|
|
3958
|
-
inst.setTracerProvider(provider);
|
|
3959
|
-
inst.enable();
|
|
3960
|
-
} catch {
|
|
3961
|
-
}
|
|
3962
|
-
}
|
|
3963
|
-
}
|
|
3964
|
-
setOtelState(OtelState.OWNS_PROVIDER);
|
|
3965
|
-
emitLifecycleEvent("otel:configured", { state: OtelState.OWNS_PROVIDER, scenario: "A" });
|
|
3966
|
-
}
|
|
3967
|
-
|
|
3968
|
-
// src/context-manager.ts
|
|
3969
|
-
import { AsyncLocalStorage } from "node:async_hooks";
|
|
3970
|
-
function installContextManager() {
|
|
3971
|
-
try {
|
|
3972
|
-
const als = new AsyncLocalStorage();
|
|
3973
|
-
const contextManager = {
|
|
3974
|
-
active: () => als.getStore() ?? ROOT_CONTEXT,
|
|
3975
|
-
with: (context2, fn, thisArg, ...args) => als.run(context2, () => fn.apply(thisArg, args)),
|
|
3976
|
-
bind: (context2, target) => {
|
|
3977
|
-
if (typeof target === "function") {
|
|
3978
|
-
const bound = (...fnArgs) => als.run(context2, () => target(...fnArgs));
|
|
3979
|
-
return bound;
|
|
3980
|
-
}
|
|
3981
|
-
return target;
|
|
3982
|
-
},
|
|
3983
|
-
enable: () => contextManager,
|
|
3984
|
-
disable: () => contextManager
|
|
3985
|
-
};
|
|
3986
|
-
const success = context.setGlobalContextManager(contextManager);
|
|
3987
|
-
if (!success) {
|
|
3988
|
-
console.warn(
|
|
3989
|
-
"[glasstrace] Another context manager is already registered. Trace context propagation may not work as expected."
|
|
3990
|
-
);
|
|
3991
|
-
}
|
|
3992
|
-
return success;
|
|
3993
|
-
} catch {
|
|
3994
|
-
return false;
|
|
3995
|
-
}
|
|
3996
|
-
}
|
|
3997
|
-
|
|
3998
|
-
// src/heartbeat.ts
|
|
3999
|
-
var HEARTBEAT_INTERVAL_MS = 5 * 60 * 1e3;
|
|
4000
|
-
var BACKOFF_BASE_MS = HEARTBEAT_INTERVAL_MS;
|
|
4001
|
-
var BACKOFF_MAX_MS = 30 * 60 * 1e3;
|
|
4002
|
-
var BACKOFF_JITTER = 0.2;
|
|
4003
|
-
var HEARTBEAT_SHUTDOWN_PRIORITY = 10;
|
|
4004
|
-
var SHUTDOWN_MARKER_RELPATH = ".glasstrace/shutdown-requested";
|
|
4005
|
-
var heartbeatTimer = null;
|
|
4006
|
-
var heartbeatGeneration = 0;
|
|
4007
|
-
var backoffAttempts = 0;
|
|
4008
|
-
var backoffUntil = 0;
|
|
4009
|
-
var tickInProgress = false;
|
|
4010
|
-
var shutdownHookRegistered = false;
|
|
4011
|
-
var shutdownFired = false;
|
|
4012
|
-
function startHeartbeat(config, anonKey, sdkVersion, generation, onClaimTransition) {
|
|
4013
|
-
if (heartbeatTimer !== null) return;
|
|
4014
|
-
heartbeatGeneration = generation;
|
|
4015
|
-
heartbeatTimer = setInterval(() => {
|
|
4016
|
-
void heartbeatTick(config, anonKey, sdkVersion, generation, onClaimTransition);
|
|
4017
|
-
}, HEARTBEAT_INTERVAL_MS);
|
|
4018
|
-
heartbeatTimer.unref();
|
|
4019
|
-
registerHeartbeatShutdownHook(config, anonKey, sdkVersion);
|
|
4020
|
-
if (config.verbose) {
|
|
4021
|
-
sdkLog("info", "[glasstrace] Heartbeat started (5-minute interval).");
|
|
4022
|
-
}
|
|
4023
|
-
}
|
|
4024
|
-
function stopHeartbeat() {
|
|
4025
|
-
if (heartbeatTimer !== null) {
|
|
4026
|
-
clearInterval(heartbeatTimer);
|
|
4027
|
-
heartbeatTimer = null;
|
|
4028
|
-
}
|
|
4029
|
-
}
|
|
4030
|
-
function checkShutdownMarker(projectRoot) {
|
|
4031
|
-
let fsSync = null;
|
|
4032
|
-
let pathSync = null;
|
|
4033
|
-
try {
|
|
4034
|
-
fsSync = __require("node:fs");
|
|
4035
|
-
pathSync = __require("node:path");
|
|
4036
|
-
} catch {
|
|
4037
|
-
return { triggered: false };
|
|
4038
|
-
}
|
|
4039
|
-
const root = projectRoot ?? (typeof process !== "undefined" ? process.cwd() : ".");
|
|
4040
|
-
const markerPath = pathSync.join(root, SHUTDOWN_MARKER_RELPATH);
|
|
4041
|
-
if (!fsSync.existsSync(markerPath)) return { triggered: false };
|
|
4042
|
-
try {
|
|
4043
|
-
fsSync.unlinkSync(markerPath);
|
|
4044
|
-
} catch {
|
|
4045
|
-
}
|
|
4046
|
-
const shutdown = executeShutdown().catch(() => {
|
|
4047
|
-
});
|
|
4048
|
-
return { triggered: true, shutdown };
|
|
4049
|
-
}
|
|
4050
|
-
async function heartbeatTick(config, anonKey, sdkVersion, generation, onClaimTransition) {
|
|
4051
|
-
if (tickInProgress) return;
|
|
4052
|
-
tickInProgress = true;
|
|
4053
|
-
try {
|
|
4054
|
-
if (generation !== heartbeatGeneration) {
|
|
4055
|
-
stopHeartbeat();
|
|
4056
|
-
return;
|
|
4057
|
-
}
|
|
4058
|
-
const markerResult = checkShutdownMarker();
|
|
4059
|
-
if (markerResult.triggered) {
|
|
4060
|
-
stopHeartbeat();
|
|
4061
|
-
if (markerResult.shutdown) {
|
|
4062
|
-
await markerResult.shutdown;
|
|
4063
|
-
}
|
|
4064
|
-
return;
|
|
4065
|
-
}
|
|
4066
|
-
if (Date.now() < backoffUntil) {
|
|
4067
|
-
if (config.verbose) {
|
|
4068
|
-
sdkLog("info", "[glasstrace] Heartbeat skipped (rate-limit backoff).");
|
|
4069
|
-
}
|
|
4070
|
-
return;
|
|
4071
|
-
}
|
|
4072
|
-
const healthReport = collectHealthReport(sdkVersion);
|
|
4073
|
-
const initResult = await performInit(config, anonKey, sdkVersion, healthReport);
|
|
4074
|
-
if (generation !== heartbeatGeneration) return;
|
|
4075
|
-
if (initResult === null && consumeRateLimitFlag()) {
|
|
4076
|
-
backoffAttempts++;
|
|
4077
|
-
const delay = Math.min(
|
|
4078
|
-
BACKOFF_BASE_MS * Math.pow(2, backoffAttempts - 1),
|
|
4079
|
-
BACKOFF_MAX_MS
|
|
4080
|
-
);
|
|
4081
|
-
const jitter = delay * BACKOFF_JITTER * (Math.random() * 2 - 1);
|
|
4082
|
-
backoffUntil = Date.now() + delay + jitter;
|
|
4083
|
-
if (config.verbose) {
|
|
4084
|
-
sdkLog("info", `[glasstrace] Heartbeat backing off for ${Math.round((delay + jitter) / 1e3)}s.`);
|
|
4085
|
-
}
|
|
4086
|
-
} else {
|
|
4087
|
-
backoffAttempts = 0;
|
|
4088
|
-
backoffUntil = 0;
|
|
4089
|
-
}
|
|
4090
|
-
if (initResult?.claimResult) {
|
|
4091
|
-
onClaimTransition(initResult.claimResult.newApiKey, initResult.claimResult.accountId);
|
|
4092
|
-
}
|
|
4093
|
-
if (config.verbose) {
|
|
4094
|
-
sdkLog("info", "[glasstrace] Heartbeat completed.");
|
|
4095
|
-
}
|
|
4096
|
-
} finally {
|
|
4097
|
-
tickInProgress = false;
|
|
4098
|
-
}
|
|
4099
|
-
}
|
|
4100
|
-
function registerHeartbeatShutdownHook(config, anonKey, sdkVersion) {
|
|
4101
|
-
if (shutdownHookRegistered) return;
|
|
4102
|
-
shutdownHookRegistered = true;
|
|
4103
|
-
registerShutdownHook({
|
|
4104
|
-
name: "heartbeat-final-report",
|
|
4105
|
-
priority: HEARTBEAT_SHUTDOWN_PRIORITY,
|
|
4106
|
-
fn: async () => {
|
|
4107
|
-
if (shutdownFired) return;
|
|
4108
|
-
shutdownFired = true;
|
|
4109
|
-
if (heartbeatTimer !== null) {
|
|
4110
|
-
clearInterval(heartbeatTimer);
|
|
4111
|
-
heartbeatTimer = null;
|
|
4112
|
-
}
|
|
4113
|
-
try {
|
|
4114
|
-
const healthReport = collectHealthReport(sdkVersion);
|
|
4115
|
-
await performInit(config, anonKey, sdkVersion, healthReport);
|
|
4116
|
-
} catch {
|
|
4117
|
-
}
|
|
4118
|
-
}
|
|
4119
|
-
});
|
|
4120
|
-
}
|
|
4121
|
-
|
|
4122
|
-
// src/runtime-state.ts
|
|
4123
|
-
import { writeFileSync, renameSync, mkdirSync } from "node:fs";
|
|
4124
|
-
import { join } from "node:path";
|
|
4125
|
-
var _projectRoot = null;
|
|
4126
|
-
var _sdkVersion = "unknown";
|
|
4127
|
-
var _lastScenario;
|
|
4128
|
-
var _debounceTimer = null;
|
|
4129
|
-
var _started = false;
|
|
4130
|
-
function startRuntimeStateWriter(options) {
|
|
4131
|
-
if (_started) return;
|
|
4132
|
-
_started = true;
|
|
4133
|
-
_projectRoot = options.projectRoot;
|
|
4134
|
-
_sdkVersion = options.sdkVersion;
|
|
4135
|
-
onLifecycleEvent("core:state_changed", ({ to }) => {
|
|
4136
|
-
if (to === CoreState.SHUTDOWN) {
|
|
4137
|
-
writeStateNow();
|
|
4138
|
-
} else {
|
|
4139
|
-
debouncedWrite();
|
|
4140
|
-
}
|
|
4141
|
-
});
|
|
4142
|
-
onLifecycleEvent("otel:configured", ({ scenario }) => {
|
|
4143
|
-
_lastScenario = scenario;
|
|
4144
|
-
debouncedWrite();
|
|
4145
|
-
});
|
|
4146
|
-
onLifecycleEvent("auth:key_resolved", () => debouncedWrite());
|
|
4147
|
-
onLifecycleEvent("auth:claim_started", () => debouncedWrite());
|
|
4148
|
-
onLifecycleEvent("auth:claim_completed", () => debouncedWrite());
|
|
4149
|
-
writeStateNow();
|
|
4150
|
-
}
|
|
4151
|
-
function debouncedWrite() {
|
|
4152
|
-
if (_debounceTimer) return;
|
|
4153
|
-
_debounceTimer = setTimeout(() => {
|
|
4154
|
-
_debounceTimer = null;
|
|
4155
|
-
writeStateNow();
|
|
4156
|
-
}, 1e3);
|
|
4157
|
-
if (typeof _debounceTimer === "object" && "unref" in _debounceTimer) {
|
|
4158
|
-
_debounceTimer.unref();
|
|
4159
|
-
}
|
|
4160
|
-
}
|
|
4161
|
-
function writeStateNow() {
|
|
4162
|
-
if (!_projectRoot) return;
|
|
4163
|
-
try {
|
|
4164
|
-
const state = getSdkState();
|
|
4165
|
-
const runtimeState = {
|
|
4166
|
-
updatedAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
4167
|
-
pid: process.pid,
|
|
4168
|
-
sdkVersion: _sdkVersion,
|
|
4169
|
-
core: { state: state.core },
|
|
4170
|
-
auth: { state: state.auth },
|
|
4171
|
-
otel: { state: state.otel, scenario: _lastScenario }
|
|
4172
|
-
};
|
|
4173
|
-
const dir = join(_projectRoot, ".glasstrace");
|
|
4174
|
-
const filePath = join(dir, "runtime-state.json");
|
|
4175
|
-
const tmpPath = join(dir, "runtime-state.json.tmp");
|
|
4176
|
-
mkdirSync(dir, { recursive: true, mode: 448 });
|
|
4177
|
-
writeFileSync(tmpPath, JSON.stringify(runtimeState, null, 2) + "\n", {
|
|
4178
|
-
mode: 384
|
|
4179
|
-
});
|
|
4180
|
-
renameSync(tmpPath, filePath);
|
|
4181
|
-
} catch (err) {
|
|
4182
|
-
sdkLog(
|
|
4183
|
-
"warn",
|
|
4184
|
-
`[glasstrace] Failed to write runtime state: ${err instanceof Error ? err.message : String(err)}`
|
|
4185
|
-
);
|
|
4186
|
-
}
|
|
4187
|
-
}
|
|
4188
|
-
|
|
4189
|
-
// src/register.ts
|
|
4190
|
-
function maskKey(key) {
|
|
4191
|
-
if (key.length <= 12) return key.slice(0, 4) + "...";
|
|
4192
|
-
return key.slice(0, 8) + "..." + key.slice(-4);
|
|
4193
|
-
}
|
|
4194
|
-
var consoleCaptureInstalled = false;
|
|
4195
|
-
var discoveryHandler = null;
|
|
4196
|
-
var registrationGeneration = 0;
|
|
4197
|
-
var _sessionManager = null;
|
|
4198
|
-
function getSessionManager() {
|
|
4199
|
-
if (!_sessionManager) {
|
|
4200
|
-
_sessionManager = new SessionManager();
|
|
4201
|
-
}
|
|
4202
|
-
return _sessionManager;
|
|
4203
|
-
}
|
|
4204
|
-
function registerGlasstrace(options) {
|
|
4205
|
-
try {
|
|
4206
|
-
if (getCoreState() !== CoreState.IDLE) {
|
|
4207
|
-
return;
|
|
4208
|
-
}
|
|
4209
|
-
initLifecycle({ logger: sdkLog });
|
|
4210
|
-
if (typeof process === "undefined" || typeof process.versions?.node !== "string") {
|
|
4211
|
-
console.warn(
|
|
4212
|
-
"[glasstrace] SDK requires a Node.js runtime. Edge Runtime, browser, and Deno without Node compat are not supported. Glasstrace is disabled in this environment."
|
|
4213
|
-
);
|
|
4214
|
-
return;
|
|
4215
|
-
}
|
|
4216
|
-
setCoreState(CoreState.REGISTERING);
|
|
4217
|
-
startRuntimeStateWriter({
|
|
4218
|
-
projectRoot: process.cwd(),
|
|
4219
|
-
sdkVersion: "0.20.0"
|
|
4220
|
-
});
|
|
4221
|
-
const config = resolveConfig(options);
|
|
4222
|
-
if (config.verbose) {
|
|
4223
|
-
console.info("[glasstrace] Config resolved.");
|
|
4224
|
-
}
|
|
4225
|
-
if (isProductionDisabled(config)) {
|
|
4226
|
-
setCoreState(CoreState.PRODUCTION_DISABLED);
|
|
4227
|
-
console.warn(
|
|
4228
|
-
"[glasstrace] Disabled in production. Set GLASSTRACE_FORCE_ENABLE=true to override."
|
|
4229
|
-
);
|
|
4230
|
-
return;
|
|
4231
|
-
}
|
|
4232
|
-
if (config.verbose) {
|
|
4233
|
-
console.info("[glasstrace] Not production-disabled.");
|
|
4234
|
-
}
|
|
4235
|
-
const existingProbe = trace.getTracerProvider().getTracer("glasstrace-probe");
|
|
4236
|
-
const anotherProviderRegistered = existingProbe.constructor.name !== "ProxyTracer";
|
|
4237
|
-
if (anotherProviderRegistered) {
|
|
4238
|
-
setCoexistenceState("coexisting");
|
|
4239
|
-
}
|
|
4240
|
-
registerSignalHandlers();
|
|
4241
|
-
const anonymous = isAnonymousMode(config);
|
|
4242
|
-
let effectiveKey = config.apiKey;
|
|
4243
|
-
initAuthState(anonymous ? AuthState.ANONYMOUS : AuthState.AUTHENTICATED);
|
|
4244
|
-
if (effectiveKey) {
|
|
4245
|
-
setResolvedApiKey(effectiveKey);
|
|
4246
|
-
emitLifecycleEvent("auth:key_resolved", {
|
|
4247
|
-
key: maskKey(effectiveKey),
|
|
4248
|
-
mode: anonymous ? "anonymous" : "dev"
|
|
4249
|
-
});
|
|
4250
|
-
}
|
|
4251
|
-
if (config.verbose) {
|
|
4252
|
-
console.info(
|
|
4253
|
-
`[glasstrace] Auth mode = ${anonymous ? "anonymous" : "dev-key"}.`
|
|
4254
|
-
);
|
|
4255
|
-
}
|
|
4256
|
-
const cachedInitResponse = loadCachedConfig();
|
|
4257
|
-
if (cachedInitResponse) {
|
|
4258
|
-
_setCurrentConfig(cachedInitResponse);
|
|
4259
|
-
}
|
|
4260
|
-
if (config.verbose) {
|
|
4261
|
-
console.info(
|
|
4262
|
-
`[glasstrace] Cached config ${cachedInitResponse ? "loaded and applied" : "not found"}.`
|
|
4263
|
-
);
|
|
4264
|
-
}
|
|
4265
|
-
const sessionManager = getSessionManager();
|
|
4266
|
-
if (config.verbose) {
|
|
4267
|
-
console.info("[glasstrace] SessionManager created.");
|
|
4268
|
-
}
|
|
4269
|
-
setCoreState(CoreState.KEY_PENDING);
|
|
4270
|
-
const currentGeneration = registrationGeneration;
|
|
4271
|
-
if (anotherProviderRegistered) {
|
|
4272
|
-
if (config.verbose) {
|
|
4273
|
-
console.info("[glasstrace] Another OTel provider detected \u2014 using existing context manager.");
|
|
4274
|
-
}
|
|
4275
|
-
} else {
|
|
4276
|
-
const contextManagerInstalled = installContextManager();
|
|
4277
|
-
if (config.verbose) {
|
|
4278
|
-
console.info(
|
|
4279
|
-
contextManagerInstalled ? "[glasstrace] Context manager installed." : "[glasstrace] Context manager not available \u2014 trace context propagation disabled."
|
|
4280
|
-
);
|
|
4281
|
-
}
|
|
4282
|
-
}
|
|
4283
|
-
void configureOtel(config, sessionManager).then(
|
|
4284
|
-
() => {
|
|
4285
|
-
maybeInstallConsoleCapture();
|
|
4286
|
-
if (config.verbose) {
|
|
4287
|
-
console.info("[glasstrace] OTel configured.");
|
|
4288
|
-
}
|
|
4289
|
-
},
|
|
4290
|
-
(err) => {
|
|
4291
|
-
console.warn(
|
|
4292
|
-
`[glasstrace] Failed to configure OTel: ${err instanceof Error ? err.message : String(err)}`
|
|
4293
|
-
);
|
|
4294
|
-
}
|
|
4295
|
-
);
|
|
4296
|
-
if (anonymous) {
|
|
4297
|
-
if (isDiscoveryEnabled(config)) {
|
|
4298
|
-
let resolvedAnonKey = null;
|
|
4299
|
-
const anonKeyPromise = getOrCreateAnonKey();
|
|
4300
|
-
const getClaimState = () => {
|
|
4301
|
-
if (getLinkedAccountId()) return { claimed: true };
|
|
4302
|
-
if (getClaimResult()) return { claimed: true };
|
|
4303
|
-
return null;
|
|
4304
|
-
};
|
|
4305
|
-
discoveryHandler = createDiscoveryHandler(
|
|
4306
|
-
async () => resolvedAnonKey,
|
|
4307
|
-
() => sessionManager.getSessionId(getResolvedApiKey()),
|
|
4308
|
-
getClaimState
|
|
4309
|
-
);
|
|
4310
|
-
if (config.verbose) {
|
|
4311
|
-
console.info("[glasstrace] Discovery endpoint registered (key pending).");
|
|
4312
|
-
}
|
|
4313
|
-
void (async () => {
|
|
4314
|
-
try {
|
|
4315
|
-
if (currentGeneration !== registrationGeneration) return;
|
|
4316
|
-
const anonKey = await anonKeyPromise;
|
|
4317
|
-
resolvedAnonKey = anonKey;
|
|
4318
|
-
setResolvedApiKey(anonKey);
|
|
4319
|
-
notifyApiKeyResolved();
|
|
4320
|
-
emitLifecycleEvent("auth:key_resolved", { key: maskKey(anonKey), mode: "anonymous" });
|
|
4321
|
-
effectiveKey = anonKey;
|
|
4322
|
-
if (currentGeneration !== registrationGeneration) return;
|
|
4323
|
-
discoveryHandler = createDiscoveryHandler(
|
|
4324
|
-
() => Promise.resolve(anonKey),
|
|
4325
|
-
() => sessionManager.getSessionId(getResolvedApiKey()),
|
|
4326
|
-
getClaimState
|
|
4327
|
-
);
|
|
4328
|
-
await backgroundInit(config, anonKey, currentGeneration);
|
|
4329
|
-
} catch (err) {
|
|
4330
|
-
console.warn(
|
|
4331
|
-
`[glasstrace] Background init failed: ${err instanceof Error ? err.message : String(err)}`
|
|
4332
|
-
);
|
|
4333
|
-
}
|
|
4334
|
-
})();
|
|
4335
|
-
} else {
|
|
4336
|
-
void (async () => {
|
|
4337
|
-
try {
|
|
4338
|
-
if (currentGeneration !== registrationGeneration) return;
|
|
4339
|
-
const anonKey = await getOrCreateAnonKey();
|
|
4340
|
-
setResolvedApiKey(anonKey);
|
|
4341
|
-
notifyApiKeyResolved();
|
|
4342
|
-
emitLifecycleEvent("auth:key_resolved", { key: maskKey(anonKey), mode: "anonymous" });
|
|
4343
|
-
effectiveKey = anonKey;
|
|
4344
|
-
if (currentGeneration !== registrationGeneration) return;
|
|
4345
|
-
await backgroundInit(config, anonKey, currentGeneration);
|
|
4346
|
-
} catch (err) {
|
|
4347
|
-
console.warn(
|
|
4348
|
-
`[glasstrace] Background init failed: ${err instanceof Error ? err.message : String(err)}`
|
|
4349
|
-
);
|
|
4350
|
-
}
|
|
4351
|
-
})();
|
|
4352
|
-
}
|
|
4353
|
-
} else {
|
|
4354
|
-
void (async () => {
|
|
4355
|
-
try {
|
|
4356
|
-
if (currentGeneration !== registrationGeneration) return;
|
|
4357
|
-
let anonKeyForInit = null;
|
|
4358
|
-
try {
|
|
4359
|
-
anonKeyForInit = await readAnonKey();
|
|
4360
|
-
} catch {
|
|
4361
|
-
}
|
|
4362
|
-
if (currentGeneration !== registrationGeneration) return;
|
|
4363
|
-
await backgroundInit(config, anonKeyForInit, currentGeneration);
|
|
4364
|
-
} catch (err) {
|
|
4365
|
-
console.warn(
|
|
4366
|
-
`[glasstrace] Background init failed: ${err instanceof Error ? err.message : String(err)}`
|
|
4367
|
-
);
|
|
4368
|
-
}
|
|
4369
|
-
})();
|
|
4370
|
-
}
|
|
4371
|
-
if (config.coverageMapEnabled && config.verbose) {
|
|
4372
|
-
console.info("[glasstrace] Import graph building skipped.");
|
|
4373
|
-
}
|
|
4374
|
-
} catch (err) {
|
|
4375
|
-
setCoreState(CoreState.REGISTRATION_FAILED);
|
|
4376
|
-
console.warn(
|
|
4377
|
-
`[glasstrace] Registration failed: ${err instanceof Error ? err.message : String(err)}`
|
|
4378
|
-
);
|
|
4379
|
-
}
|
|
4380
|
-
}
|
|
4381
|
-
async function backgroundInit(config, anonKeyForInit, generation) {
|
|
4382
|
-
if (config.verbose) {
|
|
4383
|
-
console.info("[glasstrace] Background init firing.");
|
|
4384
|
-
}
|
|
4385
|
-
const healthReport = collectHealthReport("0.20.0");
|
|
4386
|
-
const initResult = await performInit(config, anonKeyForInit, "0.20.0", healthReport);
|
|
4387
|
-
if (generation !== registrationGeneration) return;
|
|
4388
|
-
const currentState = getCoreState();
|
|
4389
|
-
if (currentState === CoreState.SHUTTING_DOWN || currentState === CoreState.SHUTDOWN) {
|
|
4390
|
-
return;
|
|
4391
|
-
}
|
|
4392
|
-
if (currentState === CoreState.KEY_PENDING) {
|
|
4393
|
-
setCoreState(CoreState.KEY_RESOLVED);
|
|
4394
|
-
}
|
|
4395
|
-
if (getCoreState() === CoreState.KEY_RESOLVED) {
|
|
4396
|
-
setCoreState(didLastInitSucceed() ? CoreState.ACTIVE : CoreState.ACTIVE_DEGRADED);
|
|
4397
|
-
}
|
|
4398
|
-
if (initResult?.claimResult) {
|
|
4399
|
-
const { newApiKey, accountId } = initResult.claimResult;
|
|
4400
|
-
setAuthState(AuthState.CLAIMING);
|
|
4401
|
-
emitLifecycleEvent("auth:claim_started", { accountId });
|
|
4402
|
-
setResolvedApiKey(newApiKey);
|
|
4403
|
-
notifyApiKeyResolved();
|
|
4404
|
-
setAuthState(AuthState.CLAIMED);
|
|
4405
|
-
emitLifecycleEvent("auth:claim_completed", { newKey: maskKey(newApiKey), accountId });
|
|
4406
|
-
}
|
|
4407
|
-
maybeInstallConsoleCapture();
|
|
4408
|
-
if (didLastInitSucceed()) {
|
|
4409
|
-
startHeartbeat(config, anonKeyForInit, "0.20.0", generation, (newApiKey, accountId) => {
|
|
4410
|
-
setAuthState(AuthState.CLAIMING);
|
|
4411
|
-
emitLifecycleEvent("auth:claim_started", { accountId });
|
|
4412
|
-
setResolvedApiKey(newApiKey);
|
|
4413
|
-
notifyApiKeyResolved();
|
|
4414
|
-
setAuthState(AuthState.CLAIMED);
|
|
4415
|
-
emitLifecycleEvent("auth:claim_completed", { newKey: maskKey(newApiKey), accountId });
|
|
4416
|
-
});
|
|
4417
|
-
}
|
|
4418
|
-
}
|
|
4419
|
-
function getDiscoveryHandler() {
|
|
4420
|
-
return discoveryHandler;
|
|
4421
|
-
}
|
|
4422
|
-
function maybeInstallConsoleCapture() {
|
|
4423
|
-
if (consoleCaptureInstalled) return;
|
|
4424
|
-
if (getActiveConfig().consoleErrors) {
|
|
4425
|
-
consoleCaptureInstalled = true;
|
|
4426
|
-
void installConsoleCapture();
|
|
4427
|
-
}
|
|
4428
|
-
}
|
|
4429
|
-
function isDiscoveryEnabled(config) {
|
|
4430
|
-
if (process.env.GLASSTRACE_DISCOVERY_ENABLED === "true") return true;
|
|
4431
|
-
if (process.env.GLASSTRACE_DISCOVERY_ENABLED === "false") return false;
|
|
4432
|
-
if (config.nodeEnv === "production") return false;
|
|
4433
|
-
if (config.vercelEnv === "production") return false;
|
|
4434
|
-
if (config.nodeEnv === "development" || config.nodeEnv === void 0) return true;
|
|
4435
|
-
return false;
|
|
4436
|
-
}
|
|
4437
|
-
|
|
4438
|
-
// src/config-wrapper.ts
|
|
4439
|
-
import { isBuiltin as isNodeBuiltin } from "node:module";
|
|
4440
|
-
function isTurbopackBuild() {
|
|
4441
|
-
if (typeof process === "undefined") return false;
|
|
4442
|
-
const argv = Array.isArray(process.argv) ? process.argv : [];
|
|
4443
|
-
if (argv.includes("--webpack")) return false;
|
|
4444
|
-
if (argv.includes("--turbopack")) return true;
|
|
4445
|
-
if (process.env?.TURBOPACK === "1") return true;
|
|
4446
|
-
return false;
|
|
4447
|
-
}
|
|
4448
|
-
var SDK_PACKAGE_NAME = "@glasstrace/sdk";
|
|
4449
|
-
function appendNodeSchemeExternal(webpackConfig) {
|
|
4450
|
-
const nodeBuiltinExternal = (data, callback) => {
|
|
4451
|
-
const request = data.request;
|
|
4452
|
-
if (typeof request === "string" && isNodeBuiltin(request)) {
|
|
4453
|
-
callback(null, "commonjs " + request);
|
|
4454
|
-
return;
|
|
4455
|
-
}
|
|
4456
|
-
callback(null);
|
|
4457
|
-
};
|
|
4458
|
-
const existing = webpackConfig.externals;
|
|
4459
|
-
if (Array.isArray(existing)) {
|
|
4460
|
-
webpackConfig.externals = [...existing, nodeBuiltinExternal];
|
|
4461
|
-
} else if (existing == null) {
|
|
4462
|
-
webpackConfig.externals = [nodeBuiltinExternal];
|
|
4463
|
-
} else {
|
|
4464
|
-
webpackConfig.externals = [existing, nodeBuiltinExternal];
|
|
4465
|
-
}
|
|
4466
|
-
}
|
|
4467
|
-
function ensureServerExternal(config) {
|
|
4468
|
-
const existingStable = config.serverExternalPackages;
|
|
4469
|
-
const stable = Array.isArray(existingStable) ? (
|
|
4470
|
-
// Clone so we never mutate a caller-owned array in place.
|
|
4471
|
-
existingStable.filter((entry) => typeof entry === "string")
|
|
4472
|
-
) : [];
|
|
4473
|
-
if (!stable.includes(SDK_PACKAGE_NAME)) {
|
|
4474
|
-
stable.push(SDK_PACKAGE_NAME);
|
|
4475
|
-
}
|
|
4476
|
-
config.serverExternalPackages = stable;
|
|
4477
|
-
}
|
|
4478
|
-
function withGlasstraceConfig(nextConfig) {
|
|
4479
|
-
if (typeof process === "undefined" || typeof process.versions?.node !== "string") {
|
|
4480
|
-
return nextConfig != null ? { ...nextConfig } : {};
|
|
4481
|
-
}
|
|
4482
|
-
const config = nextConfig != null ? { ...nextConfig } : {};
|
|
4483
|
-
const bag = config;
|
|
4484
|
-
const existingExperimental = bag.experimental ?? {};
|
|
4485
|
-
bag.experimental = {
|
|
4486
|
-
...existingExperimental,
|
|
4487
|
-
serverSourceMaps: true
|
|
4488
|
-
};
|
|
4489
|
-
ensureServerExternal(bag);
|
|
4490
|
-
if (bag.turbopack == null) {
|
|
4491
|
-
bag.turbopack = {};
|
|
4492
|
-
}
|
|
4493
|
-
if (isTurbopackBuild()) {
|
|
4494
|
-
warnTurbopackLimitationOnce();
|
|
4495
|
-
}
|
|
4496
|
-
const distDir = typeof bag.distDir === "string" ? bag.distDir : ".next";
|
|
4497
|
-
const existingWebpack = bag.webpack;
|
|
4498
|
-
bag.webpack = (webpackConfig, context2) => {
|
|
4499
|
-
let result = webpackConfig;
|
|
4500
|
-
if (typeof existingWebpack === "function") {
|
|
4501
|
-
result = existingWebpack(webpackConfig, context2);
|
|
4502
|
-
}
|
|
4503
|
-
const webpackContext = context2;
|
|
4504
|
-
if (webpackContext.isServer) {
|
|
4505
|
-
appendNodeSchemeExternal(result);
|
|
4506
|
-
}
|
|
4507
|
-
if (!webpackContext.isServer && webpackContext.dev === false) {
|
|
4508
|
-
const plugins = result.plugins ?? [];
|
|
4509
|
-
plugins.push({
|
|
4510
|
-
apply(compiler) {
|
|
4511
|
-
const typedCompiler = compiler;
|
|
4512
|
-
if (typedCompiler.hooks?.afterEmit?.tapPromise) {
|
|
4513
|
-
typedCompiler.hooks.afterEmit.tapPromise(
|
|
4514
|
-
"GlasstraceSourceMapUpload",
|
|
4515
|
-
async () => {
|
|
4516
|
-
await handleSourceMapUpload(distDir);
|
|
4517
|
-
}
|
|
4518
|
-
);
|
|
4519
|
-
}
|
|
4520
|
-
}
|
|
4521
|
-
});
|
|
4522
|
-
result.plugins = plugins;
|
|
4523
|
-
}
|
|
4524
|
-
return result;
|
|
4525
|
-
};
|
|
4526
|
-
return config;
|
|
4527
|
-
}
|
|
4528
|
-
var _turbopackWarningEmitted = false;
|
|
4529
|
-
function warnTurbopackLimitationOnce() {
|
|
4530
|
-
if (_turbopackWarningEmitted) return;
|
|
4531
|
-
_turbopackWarningEmitted = true;
|
|
4532
|
-
console.warn(
|
|
4533
|
-
"[glasstrace] Turbopack detected. Source-map upload currently runs only under webpack \u2014 run `next build --webpack` to upload source maps, or wait for the Turbopack port in a future SDK release."
|
|
4534
|
-
);
|
|
4535
|
-
}
|
|
4536
|
-
async function handleSourceMapUpload(distDir) {
|
|
4537
|
-
try {
|
|
4538
|
-
const apiKey = process.env.GLASSTRACE_API_KEY;
|
|
4539
|
-
const endpoint = process.env.GLASSTRACE_ENDPOINT ?? "https://api.glasstrace.dev";
|
|
4540
|
-
if (!apiKey || apiKey.trim() === "") {
|
|
4541
|
-
console.info(
|
|
4542
|
-
"[glasstrace] Source map upload skipped (no API key). Stack traces will show compiled locations."
|
|
4543
|
-
);
|
|
4544
|
-
return;
|
|
4545
|
-
}
|
|
4546
|
-
const { discoverSourceMapFiles: discoverSourceMapFiles2, computeBuildHash: computeBuildHash2, uploadSourceMaps: uploadSourceMaps2 } = await import("./source-map-uploader-VPDZWWM2.js");
|
|
4547
|
-
const files = await discoverSourceMapFiles2(distDir);
|
|
4548
|
-
if (files.length === 0) {
|
|
4549
|
-
console.info("[glasstrace] No source map files found. Skipping upload.");
|
|
4550
|
-
return;
|
|
4551
|
-
}
|
|
4552
|
-
const buildHash = await computeBuildHash2(files);
|
|
4553
|
-
await uploadSourceMaps2(apiKey, endpoint, buildHash, files);
|
|
4554
|
-
console.info(
|
|
4555
|
-
`[glasstrace] Uploaded ${String(files.length)} source map(s) for build ${buildHash}.`
|
|
4556
|
-
);
|
|
4557
|
-
} catch (error) {
|
|
4558
|
-
const message = error instanceof Error ? error.message : "Unknown error";
|
|
4559
|
-
console.warn(
|
|
4560
|
-
`[glasstrace] Source map upload failed: ${message}. Build continues normally.`
|
|
4561
|
-
);
|
|
4562
|
-
}
|
|
4563
|
-
}
|
|
4564
|
-
|
|
4565
|
-
// src/capture-error.ts
|
|
4566
|
-
function captureError(error) {
|
|
4567
|
-
try {
|
|
4568
|
-
const span = trace.getSpan(context.active());
|
|
4569
|
-
if (!span) return;
|
|
4570
|
-
const attributes = {
|
|
4571
|
-
"error.message": String(error)
|
|
4572
|
-
};
|
|
4573
|
-
if (error instanceof Error) {
|
|
4574
|
-
attributes["error.type"] = error.constructor.name;
|
|
4575
|
-
if (error.stack) {
|
|
4576
|
-
attributes["error.stack"] = error.stack;
|
|
4577
|
-
}
|
|
4578
|
-
}
|
|
4579
|
-
span.addEvent("glasstrace.error", attributes);
|
|
4580
|
-
maybeShowMcpNudge(String(error));
|
|
4581
|
-
} catch {
|
|
4582
|
-
}
|
|
4583
|
-
}
|
|
4584
|
-
|
|
4585
|
-
// src/correlation-id.ts
|
|
4586
|
-
var ATTR2 = GLASSTRACE_ATTRIBUTE_NAMES;
|
|
4587
|
-
var HEADER_NAME = "x-gt-cid";
|
|
4588
|
-
var MAX_CID_LENGTH = 128;
|
|
4589
|
-
function captureCorrelationId(req) {
|
|
4590
|
-
try {
|
|
4591
|
-
if (!req || !req.headers) {
|
|
4592
|
-
return;
|
|
4593
|
-
}
|
|
4594
|
-
const value = readHeader(req.headers);
|
|
4595
|
-
if (!value) {
|
|
4596
|
-
return;
|
|
4597
|
-
}
|
|
4598
|
-
const span = trace.getActiveSpan();
|
|
4599
|
-
if (!span) {
|
|
4600
|
-
return;
|
|
4601
|
-
}
|
|
4602
|
-
span.setAttribute(ATTR2.CORRELATION_ID, value);
|
|
4603
|
-
} catch {
|
|
4604
|
-
}
|
|
4605
|
-
}
|
|
4606
|
-
function readHeader(headers) {
|
|
4607
|
-
const asFetch = headers;
|
|
4608
|
-
if (typeof asFetch.get === "function") {
|
|
4609
|
-
const raw = asFetch.get(HEADER_NAME);
|
|
4610
|
-
return firstToken(raw);
|
|
4611
|
-
}
|
|
4612
|
-
const dict = headers;
|
|
4613
|
-
const direct = dict[HEADER_NAME];
|
|
4614
|
-
if (direct !== void 0) {
|
|
4615
|
-
return firstValue(direct);
|
|
4616
|
-
}
|
|
4617
|
-
for (const key of Object.keys(dict)) {
|
|
4618
|
-
if (key.toLowerCase() === HEADER_NAME) {
|
|
4619
|
-
return firstValue(dict[key]);
|
|
4620
|
-
}
|
|
4621
|
-
}
|
|
4622
|
-
return void 0;
|
|
4623
|
-
}
|
|
4624
|
-
function firstValue(value) {
|
|
4625
|
-
if (Array.isArray(value)) {
|
|
4626
|
-
for (const entry of value) {
|
|
4627
|
-
const token = firstToken(entry);
|
|
4628
|
-
if (token) return token;
|
|
4629
|
-
}
|
|
4630
|
-
return void 0;
|
|
4631
|
-
}
|
|
4632
|
-
return firstToken(value);
|
|
4633
|
-
}
|
|
4634
|
-
function firstToken(value) {
|
|
4635
|
-
if (typeof value !== "string") return void 0;
|
|
4636
|
-
const parts = value.split(",");
|
|
4637
|
-
for (const part of parts) {
|
|
4638
|
-
const trimmed = part.trim();
|
|
4639
|
-
if (trimmed.length === 0) continue;
|
|
4640
|
-
if (trimmed.length > MAX_CID_LENGTH) return void 0;
|
|
4641
|
-
return trimmed;
|
|
4642
|
-
}
|
|
4643
|
-
return void 0;
|
|
4644
|
-
}
|
|
57
|
+
} from "./chunk-TQ54WLCZ.js";
|
|
58
|
+
import "./chunk-NSBPE2FW.js";
|
|
4645
59
|
export {
|
|
4646
60
|
GlasstraceExporter,
|
|
4647
61
|
GlasstraceSpanProcessor,
|