@flareapp/core 2.7.0 → 2.8.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.cjs +1137 -560
- package/dist/index.d.cts +188 -453
- package/dist/index.d.mts +188 -453
- package/dist/index.mjs +1097 -537
- package/dist/urlAttributes-B9BlkrfW.d.mts +452 -0
- package/dist/urlAttributes-CNGTgOJp.cjs +551 -0
- package/dist/urlAttributes-CvOw6tU3.d.cts +452 -0
- package/dist/urlAttributes-D3gCx23B.mjs +383 -0
- package/dist/util/index.cjs +24 -0
- package/dist/util/index.d.cts +2 -0
- package/dist/util/index.d.mts +2 -0
- package/dist/util/index.mjs +3 -0
- package/package.json +16 -2
package/dist/index.cjs
CHANGED
|
@@ -26,200 +26,83 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
|
|
|
26
26
|
}) : target, mod));
|
|
27
27
|
|
|
28
28
|
//#endregion
|
|
29
|
+
const require_urlAttributes = require('./urlAttributes-CNGTgOJp.cjs');
|
|
29
30
|
let error_stack_parser = require("error-stack-parser");
|
|
30
31
|
error_stack_parser = __toESM(error_stack_parser);
|
|
31
32
|
|
|
32
|
-
//#region src/
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
//#endregion
|
|
51
|
-
//#region src/util/convertToError.ts
|
|
52
|
-
function convertToError(error) {
|
|
53
|
-
if (error instanceof Error) return error;
|
|
54
|
-
if (typeof error === "string") return new Error(error);
|
|
55
|
-
if (typeof error === "object" && error !== null) {
|
|
56
|
-
const obj = error;
|
|
57
|
-
const message = typeof obj.message === "string" ? obj.message : String(error);
|
|
58
|
-
const converted = new Error(message);
|
|
59
|
-
if (typeof obj.stack === "string") converted.stack = obj.stack;
|
|
60
|
-
if (typeof obj.name === "string") converted.name = obj.name;
|
|
61
|
-
return converted;
|
|
62
|
-
}
|
|
63
|
-
return new Error(String(error));
|
|
64
|
-
}
|
|
65
|
-
|
|
66
|
-
//#endregion
|
|
67
|
-
//#region src/util/extractCode.ts
|
|
68
|
-
const MAX_CODE_LENGTH = 64;
|
|
69
|
-
function extractCode(error) {
|
|
70
|
-
const code = error.code;
|
|
71
|
-
if (typeof code !== "string" || code.length === 0) return;
|
|
72
|
-
return code.slice(0, MAX_CODE_LENGTH);
|
|
73
|
-
}
|
|
74
|
-
|
|
75
|
-
//#endregion
|
|
76
|
-
//#region src/util/flatJsonStringify.ts
|
|
77
|
-
function flatJsonStringify(json) {
|
|
78
|
-
return JSON.stringify(decycle(json));
|
|
79
|
-
}
|
|
80
|
-
function isPlainObject(value) {
|
|
81
|
-
if (typeof value !== "object" || value === null) return false;
|
|
82
|
-
const proto = Object.getPrototypeOf(value);
|
|
83
|
-
return proto === Object.prototype || proto === null;
|
|
84
|
-
}
|
|
85
|
-
function decycle(root) {
|
|
86
|
-
const inPath = /* @__PURE__ */ new WeakSet();
|
|
87
|
-
function clone(node) {
|
|
88
|
-
if (Array.isArray(node)) {
|
|
89
|
-
if (inPath.has(node)) return "[Circular]";
|
|
90
|
-
inPath.add(node);
|
|
91
|
-
const result = node.map(clone);
|
|
92
|
-
inPath.delete(node);
|
|
93
|
-
return result;
|
|
94
|
-
}
|
|
95
|
-
if (isPlainObject(node)) {
|
|
96
|
-
if (inPath.has(node)) return "[Circular]";
|
|
97
|
-
inPath.add(node);
|
|
98
|
-
const result = {};
|
|
99
|
-
for (const [k, v] of Object.entries(node)) result[k] = clone(v);
|
|
100
|
-
inPath.delete(node);
|
|
101
|
-
return result;
|
|
102
|
-
}
|
|
103
|
-
return node;
|
|
104
|
-
}
|
|
105
|
-
return clone(root);
|
|
106
|
-
}
|
|
107
|
-
|
|
108
|
-
//#endregion
|
|
109
|
-
//#region src/util/glowsToEvents.ts
|
|
110
|
-
function glowsToEvents(glows) {
|
|
111
|
-
return glows.map((glow) => ({
|
|
112
|
-
type: "php_glow",
|
|
113
|
-
startTimeUnixNano: Math.round(glow.microtime * 1e9),
|
|
114
|
-
endTimeUnixNano: null,
|
|
115
|
-
attributes: {
|
|
116
|
-
"glow.name": String(glow.name),
|
|
117
|
-
"glow.level": glow.messageLevel,
|
|
118
|
-
"glow.context": glow.metaData ?? {}
|
|
119
|
-
}
|
|
120
|
-
}));
|
|
121
|
-
}
|
|
33
|
+
//#region src/framework.ts
|
|
34
|
+
/**
|
|
35
|
+
* Framework names the Flare backend recognises. Wire format, so the values never change: they ship as
|
|
36
|
+
* `flare.framework.name` and (lowercased) as `context.custom.framework`.
|
|
37
|
+
*
|
|
38
|
+
* `Js` and `Node` are the base SDKs' fallback claim, overwritten when a framework package tags its
|
|
39
|
+
* own name. `NodeElectron` is an Electron main process; its renderers report their own.
|
|
40
|
+
*/
|
|
41
|
+
const FrameworkName = {
|
|
42
|
+
Js: "js",
|
|
43
|
+
Node: "node",
|
|
44
|
+
NodeElectron: "node-electron",
|
|
45
|
+
React: "react",
|
|
46
|
+
Vue: "vue",
|
|
47
|
+
Svelte: "svelte",
|
|
48
|
+
SvelteKit: "sveltekit",
|
|
49
|
+
ReactNative: "react-native"
|
|
50
|
+
};
|
|
122
51
|
|
|
123
52
|
//#endregion
|
|
124
|
-
//#region src/
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
53
|
+
//#region src/spanTypes.ts
|
|
54
|
+
/**
|
|
55
|
+
* Span types the Flare backend recognises. Wire format, so the values never change: they ship as the
|
|
56
|
+
* `flare.span_type` attribute and the backend groups performance data by them.
|
|
57
|
+
*
|
|
58
|
+
* These are the browser client's set. They live in core because core's `SpanOptions.spanType` needs
|
|
59
|
+
* to name them and core cannot import from `@flareapp/js`.
|
|
60
|
+
*/
|
|
61
|
+
const BrowserSpanType = {
|
|
62
|
+
Pageload: "browser_pageload",
|
|
63
|
+
Navigation: "browser_navigation",
|
|
64
|
+
Fetch: "browser_fetch",
|
|
65
|
+
Xhr: "browser_xhr",
|
|
66
|
+
Component: "browser_component",
|
|
67
|
+
WebVital: "browser_web_vital"
|
|
68
|
+
};
|
|
128
69
|
|
|
129
70
|
//#endregion
|
|
130
|
-
//#region src/
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
}
|
|
138
|
-
const flags = unionFlags(defaultDenylist.flags, custom.flags);
|
|
139
|
-
return new RegExp(`(?:${defaultDenylist.source})|(?:${custom.source})`, flags);
|
|
140
|
-
}
|
|
141
|
-
function unionFlags(a, b) {
|
|
142
|
-
const merged = /* @__PURE__ */ new Set();
|
|
143
|
-
for (const flag of a + b) {
|
|
144
|
-
if (flag === "g" || flag === "y") continue;
|
|
145
|
-
merged.add(flag);
|
|
146
|
-
}
|
|
147
|
-
return [...merged].join("");
|
|
148
|
-
}
|
|
149
|
-
function redactUrlQuery(fullPath, denylist = DEFAULT_URL_DENYLIST) {
|
|
150
|
-
const queryStart = fullPath.indexOf("?");
|
|
151
|
-
if (queryStart === -1) return fullPath;
|
|
152
|
-
const hashStart = fullPath.indexOf("#", queryStart);
|
|
153
|
-
const queryEnd = hashStart === -1 ? fullPath.length : hashStart;
|
|
154
|
-
const prefix = fullPath.slice(0, queryStart + 1);
|
|
155
|
-
const queryString = fullPath.slice(queryStart + 1, queryEnd);
|
|
156
|
-
const suffix = fullPath.slice(queryEnd);
|
|
157
|
-
return `${prefix}${queryString.split("&").map((pair) => {
|
|
158
|
-
if (pair === "") return pair;
|
|
159
|
-
const eq = pair.indexOf("=");
|
|
160
|
-
const rawKey = eq === -1 ? pair : pair.slice(0, eq);
|
|
161
|
-
const decodedKey = safeDecode(rawKey);
|
|
162
|
-
if (!denylist.test(decodedKey)) return pair;
|
|
163
|
-
return eq === -1 ? rawKey : `${rawKey}=[redacted]`;
|
|
164
|
-
}).join("&")}${suffix}`;
|
|
165
|
-
}
|
|
166
|
-
function safeDecode(value) {
|
|
167
|
-
try {
|
|
168
|
-
return decodeURIComponent(value);
|
|
169
|
-
} catch {
|
|
170
|
-
return value;
|
|
171
|
-
}
|
|
172
|
-
}
|
|
71
|
+
//#region src/types.ts
|
|
72
|
+
/** OTel status codes. Wire format: these numbers ship in the span envelope, so the values never change. */
|
|
73
|
+
const SpanStatusCode = {
|
|
74
|
+
Unset: 0,
|
|
75
|
+
Ok: 1,
|
|
76
|
+
Error: 2
|
|
77
|
+
};
|
|
173
78
|
|
|
174
79
|
//#endregion
|
|
175
|
-
//#region src/util/
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
const message = reason.message;
|
|
181
|
-
if (typeof message === "string" && message) return message;
|
|
182
|
-
try {
|
|
183
|
-
return JSON.stringify(reason);
|
|
184
|
-
} catch {
|
|
185
|
-
return "Unhandled promise rejection (non-serializable reason)";
|
|
186
|
-
}
|
|
187
|
-
}
|
|
188
|
-
return String(reason);
|
|
189
|
-
}
|
|
190
|
-
function hasStack$1(reason) {
|
|
191
|
-
return !!reason && typeof reason === "object" && typeof reason.stack === "string";
|
|
192
|
-
}
|
|
193
|
-
/**
|
|
194
|
-
* Route a rejection reason to the reporter: an Error (or any stack-bearing
|
|
195
|
-
* object) goes to `reportSilently` so the STACK survives; only a stackless
|
|
196
|
-
* reason falls back to `reportUnhandledRejection` (string message, empty-stack
|
|
197
|
-
* `UnhandledRejection` class). Any rejection from `reportUnhandledRejection`'s
|
|
198
|
-
* returned promise is swallowed so a transport failure cannot itself surface as
|
|
199
|
-
* an unhandled rejection. `reportSilently` is assumed not to throw synchronously
|
|
200
|
-
* (core's does its work asynchronously); it is intentionally not wrapped, so a
|
|
201
|
-
* synchronous throw there would propagate.
|
|
202
|
-
*/
|
|
203
|
-
function routeRejection(reporter, reason) {
|
|
204
|
-
if (reason instanceof Error) {
|
|
205
|
-
reporter.reportSilently(reason);
|
|
206
|
-
return;
|
|
207
|
-
}
|
|
208
|
-
if (hasStack$1(reason)) {
|
|
209
|
-
const error = new Error(describeRejectionReason(reason));
|
|
210
|
-
error.stack = reason.stack;
|
|
211
|
-
reporter.reportSilently(error);
|
|
212
|
-
return;
|
|
213
|
-
}
|
|
214
|
-
Promise.resolve(reporter.reportUnhandledRejection(describeRejectionReason(reason))).catch(() => {});
|
|
80
|
+
//#region src/util/utf8Bytes.ts
|
|
81
|
+
const textEncoder = new TextEncoder();
|
|
82
|
+
/** UTF-8 byte length of `value`. */
|
|
83
|
+
function utf8Bytes(value) {
|
|
84
|
+
return textEncoder.encode(value).length;
|
|
215
85
|
}
|
|
216
86
|
|
|
217
87
|
//#endregion
|
|
218
88
|
//#region src/api/Api.ts
|
|
89
|
+
const MAX_PENDING_KEEPALIVE_BYTES = 6e4;
|
|
90
|
+
const MAX_PENDING_KEEPALIVE_REQUESTS = 15;
|
|
219
91
|
var Api = class {
|
|
92
|
+
pendingKeepaliveBytes = 0;
|
|
93
|
+
pendingKeepaliveRequests = 0;
|
|
94
|
+
/**
|
|
95
|
+
* How many keepalive bytes are still available. Logs and traces share one browser allowance and both
|
|
96
|
+
* flush on page hide, so whichever goes second has to pack against what is left rather than assume the
|
|
97
|
+
* whole budget, or it exceeds the gate in send() and silently degrades to a cancellable fetch.
|
|
98
|
+
*/
|
|
99
|
+
keepaliveBudgetRemaining() {
|
|
100
|
+
if (this.pendingKeepaliveRequests >= MAX_PENDING_KEEPALIVE_REQUESTS) return 0;
|
|
101
|
+
return Math.max(0, MAX_PENDING_KEEPALIVE_BYTES - this.pendingKeepaliveBytes);
|
|
102
|
+
}
|
|
220
103
|
report(report, url, key, reportBrowserExtensionErrors, debug = false) {
|
|
221
|
-
return
|
|
222
|
-
|
|
104
|
+
return this.send({
|
|
105
|
+
url,
|
|
223
106
|
headers: {
|
|
224
107
|
"Accept": "application/json",
|
|
225
108
|
"Content-Type": "application/json",
|
|
@@ -227,34 +110,257 @@ var Api = class {
|
|
|
227
110
|
"X-Report-Browser-Extension-Errors": JSON.stringify(reportBrowserExtensionErrors),
|
|
228
111
|
"X-Flare-Client-Version": "2"
|
|
229
112
|
},
|
|
230
|
-
body: flatJsonStringify(report)
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
if (debug) console.error(error);
|
|
113
|
+
body: require_urlAttributes.flatJsonStringify(report),
|
|
114
|
+
label: "Flare",
|
|
115
|
+
debug,
|
|
116
|
+
keepalive: false
|
|
235
117
|
});
|
|
236
118
|
}
|
|
237
119
|
logs(envelope, url, key, debug = false, keepalive = false) {
|
|
120
|
+
return this.send({
|
|
121
|
+
url,
|
|
122
|
+
headers: this.ingestHeaders(key),
|
|
123
|
+
body: require_urlAttributes.flatJsonStringify(envelope),
|
|
124
|
+
label: "Flare logs",
|
|
125
|
+
debug,
|
|
126
|
+
keepalive
|
|
127
|
+
});
|
|
128
|
+
}
|
|
129
|
+
traces(envelope, url, key, debug = false, keepalive = false) {
|
|
130
|
+
let body;
|
|
131
|
+
try {
|
|
132
|
+
body = JSON.stringify(envelope);
|
|
133
|
+
} catch {
|
|
134
|
+
body = require_urlAttributes.flatJsonStringify(envelope);
|
|
135
|
+
}
|
|
136
|
+
return this.send({
|
|
137
|
+
url,
|
|
138
|
+
headers: this.ingestHeaders(key),
|
|
139
|
+
body,
|
|
140
|
+
label: "Flare traces",
|
|
141
|
+
debug,
|
|
142
|
+
keepalive
|
|
143
|
+
});
|
|
144
|
+
}
|
|
145
|
+
ingestHeaders(key) {
|
|
146
|
+
return {
|
|
147
|
+
"Accept": "application/json",
|
|
148
|
+
"Content-Type": "application/json",
|
|
149
|
+
"x-api-token": key ?? ""
|
|
150
|
+
};
|
|
151
|
+
}
|
|
152
|
+
send(request) {
|
|
153
|
+
const { url, headers, body, label, debug, keepalive: keepaliveRequested } = request;
|
|
154
|
+
const bytes = keepaliveRequested ? utf8Bytes(body) : 0;
|
|
155
|
+
const keepalive = keepaliveRequested && this.pendingKeepaliveRequests < MAX_PENDING_KEEPALIVE_REQUESTS && this.pendingKeepaliveBytes + bytes <= MAX_PENDING_KEEPALIVE_BYTES;
|
|
156
|
+
if (keepalive) {
|
|
157
|
+
this.pendingKeepaliveBytes += bytes;
|
|
158
|
+
this.pendingKeepaliveRequests += 1;
|
|
159
|
+
}
|
|
238
160
|
return fetch(url, {
|
|
239
161
|
method: "POST",
|
|
240
162
|
keepalive,
|
|
241
|
-
headers
|
|
242
|
-
|
|
243
|
-
"Content-Type": "application/json",
|
|
244
|
-
"x-api-token": key ?? ""
|
|
245
|
-
},
|
|
246
|
-
body: flatJsonStringify(envelope)
|
|
163
|
+
headers,
|
|
164
|
+
body
|
|
247
165
|
}).then((response) => {
|
|
248
|
-
if (debug && response.status !== 201) console.error(`Received response with status ${response.status} from
|
|
166
|
+
if (debug && response.status !== 201) console.error(`Received response with status ${response.status} from ${label}`);
|
|
249
167
|
}, (error) => {
|
|
250
168
|
if (debug) console.error(error);
|
|
169
|
+
}).finally(() => {
|
|
170
|
+
if (keepalive) {
|
|
171
|
+
this.pendingKeepaliveBytes -= bytes;
|
|
172
|
+
this.pendingKeepaliveRequests -= 1;
|
|
173
|
+
}
|
|
251
174
|
});
|
|
252
175
|
}
|
|
253
176
|
};
|
|
254
177
|
|
|
178
|
+
//#endregion
|
|
179
|
+
//#region src/telemetry/TelemetryBuffer.ts
|
|
180
|
+
/**
|
|
181
|
+
* The batching machine behind both telemetry signals: hold records, ship them when a size, weight or time
|
|
182
|
+
* trigger fires, and shed the oldest when nothing can drain. One instance owns one signal; what that signal
|
|
183
|
+
* is comes entirely from the policy.
|
|
184
|
+
*/
|
|
185
|
+
var TelemetryBuffer = class {
|
|
186
|
+
entries = [];
|
|
187
|
+
bufferedBytes = 0;
|
|
188
|
+
timer;
|
|
189
|
+
timerActive = false;
|
|
190
|
+
constructor(deps, policy) {
|
|
191
|
+
this.deps = deps;
|
|
192
|
+
this.policy = policy;
|
|
193
|
+
const flush = (opts) => this.flush(opts);
|
|
194
|
+
this.deps.scheduler.register(flush);
|
|
195
|
+
}
|
|
196
|
+
length() {
|
|
197
|
+
return this.entries.length;
|
|
198
|
+
}
|
|
199
|
+
add(record) {
|
|
200
|
+
const config = this.deps.getConfig();
|
|
201
|
+
const limits = this.policy.limits(config);
|
|
202
|
+
const bytes = this.policy.estimateBytes(record);
|
|
203
|
+
if (bytes > limits.maxBytes) {
|
|
204
|
+
if (config.debug) console.error(this.policy.oversizedMessage);
|
|
205
|
+
return;
|
|
206
|
+
}
|
|
207
|
+
this.entries.push({
|
|
208
|
+
record,
|
|
209
|
+
bytes
|
|
210
|
+
});
|
|
211
|
+
this.bufferedBytes += bytes;
|
|
212
|
+
this.policy.onRecordBuffered?.(record);
|
|
213
|
+
this.evaluateTriggers(config, limits);
|
|
214
|
+
this.trim(limits);
|
|
215
|
+
}
|
|
216
|
+
flush(opts) {
|
|
217
|
+
const config = this.deps.getConfig();
|
|
218
|
+
if (!this.policy.enabled(config)) return;
|
|
219
|
+
if (this.entries.length === 0) return;
|
|
220
|
+
if (!require_urlAttributes.assertKey(config.key, config.debug)) {
|
|
221
|
+
this.clearTimer();
|
|
222
|
+
return;
|
|
223
|
+
}
|
|
224
|
+
this.clearTimer();
|
|
225
|
+
const resource = this.policy.resourceForFlush();
|
|
226
|
+
let selected;
|
|
227
|
+
let sendKeepalive = !!opts?.keepalive;
|
|
228
|
+
if (opts?.keepalive) {
|
|
229
|
+
selected = this.packForKeepalive(config, resource);
|
|
230
|
+
if (selected.length === 0) {
|
|
231
|
+
selected = this.entries;
|
|
232
|
+
this.entries = [];
|
|
233
|
+
this.bufferedBytes = 0;
|
|
234
|
+
sendKeepalive = false;
|
|
235
|
+
} else {
|
|
236
|
+
this.entries = this.entries.filter((entry) => !selected.includes(entry));
|
|
237
|
+
this.bufferedBytes = this.entries.reduce((sum, entry) => sum + entry.bytes, 0);
|
|
238
|
+
if (this.entries.length > 0) this.armTimer(this.policy.limits(config));
|
|
239
|
+
}
|
|
240
|
+
} else {
|
|
241
|
+
selected = this.entries;
|
|
242
|
+
this.entries = [];
|
|
243
|
+
this.bufferedBytes = 0;
|
|
244
|
+
}
|
|
245
|
+
if (selected.length === 0) return;
|
|
246
|
+
try {
|
|
247
|
+
this.policy.send(this.policy.buildEnvelope(selected.map((entry) => entry.record), resource), config, sendKeepalive);
|
|
248
|
+
} catch (error) {
|
|
249
|
+
if (config.debug) console.error(this.policy.sendFailureMessage, error);
|
|
250
|
+
}
|
|
251
|
+
}
|
|
252
|
+
clear() {
|
|
253
|
+
this.entries = [];
|
|
254
|
+
this.bufferedBytes = 0;
|
|
255
|
+
this.clearTimer();
|
|
256
|
+
}
|
|
257
|
+
evaluateTriggers(config, limits) {
|
|
258
|
+
if (this.entries.length >= limits.maxSize) {
|
|
259
|
+
this.flush();
|
|
260
|
+
return;
|
|
261
|
+
}
|
|
262
|
+
if (this.bufferedBytes >= limits.maxBytes) {
|
|
263
|
+
this.flush();
|
|
264
|
+
return;
|
|
265
|
+
}
|
|
266
|
+
this.armTimer(limits);
|
|
267
|
+
}
|
|
268
|
+
armTimer(limits) {
|
|
269
|
+
if (this.timerActive) return;
|
|
270
|
+
this.timerActive = true;
|
|
271
|
+
this.timer = setTimeout(() => {
|
|
272
|
+
this.timerActive = false;
|
|
273
|
+
this.timer = void 0;
|
|
274
|
+
this.flush();
|
|
275
|
+
}, limits.flushIntervalMs);
|
|
276
|
+
this.timer.unref?.();
|
|
277
|
+
}
|
|
278
|
+
trim(limits) {
|
|
279
|
+
if (this.entries.length > limits.maxSize) {
|
|
280
|
+
const excess = this.entries.length - limits.maxSize;
|
|
281
|
+
for (let i = 0; i < excess; i++) this.bufferedBytes -= this.entries[i].bytes;
|
|
282
|
+
this.entries = this.entries.slice(excess);
|
|
283
|
+
}
|
|
284
|
+
while (this.entries.length > 1 && this.bufferedBytes > limits.maxBytes) {
|
|
285
|
+
const dropped = this.entries.shift();
|
|
286
|
+
if (dropped) this.bufferedBytes -= dropped.bytes;
|
|
287
|
+
}
|
|
288
|
+
}
|
|
289
|
+
/**
|
|
290
|
+
* Newest-wins. An over-budget record is skipped, not a stop signal, so a smaller older record behind a fat
|
|
291
|
+
* one still ships. Runs on visibilitychange:hidden, which fires on plain backgrounding too, so the tail this
|
|
292
|
+
* leaves behind is retained and re-armed rather than dropped (see flush).
|
|
293
|
+
*/
|
|
294
|
+
packForKeepalive(config, resource) {
|
|
295
|
+
const fixedBytes = this.policy.emptyEnvelopeBytes(resource);
|
|
296
|
+
const budget = Math.min(config.keepaliveMaxBytes, this.policy.keepaliveBudget?.(config) ?? config.keepaliveMaxBytes);
|
|
297
|
+
const selected = [];
|
|
298
|
+
let selectedBytes = 0;
|
|
299
|
+
let droppedCount = 0;
|
|
300
|
+
for (let i = this.entries.length - 1; i >= 0; i--) {
|
|
301
|
+
const entry = this.entries[i];
|
|
302
|
+
const candidateBytes = this.policy.recordBytes(entry.record);
|
|
303
|
+
if (fixedBytes + selectedBytes + candidateBytes + selected.length <= budget) {
|
|
304
|
+
selected.unshift(entry);
|
|
305
|
+
selectedBytes += candidateBytes;
|
|
306
|
+
} else if (config.debug) droppedCount++;
|
|
307
|
+
}
|
|
308
|
+
if (config.debug && droppedCount > 0) console.error(this.policy.keepaliveDropMessage(droppedCount));
|
|
309
|
+
return selected;
|
|
310
|
+
}
|
|
311
|
+
clearTimer() {
|
|
312
|
+
if (this.timer) {
|
|
313
|
+
clearTimeout(this.timer);
|
|
314
|
+
this.timer = void 0;
|
|
315
|
+
}
|
|
316
|
+
this.timerActive = false;
|
|
317
|
+
}
|
|
318
|
+
};
|
|
319
|
+
|
|
320
|
+
//#endregion
|
|
321
|
+
//#region src/telemetry/resourceIdentity.ts
|
|
322
|
+
/**
|
|
323
|
+
* Builds the attributes that go on every logs or traces envelope: the caller's own attributes in `base`, with
|
|
324
|
+
* our SDK, service and framework identity on top. Our keys win, so a user value cannot overwrite something
|
|
325
|
+
* like `telemetry.sdk.name`.
|
|
326
|
+
*/
|
|
327
|
+
function buildResourceIdentity(base, config, sdk, framework) {
|
|
328
|
+
const identity = {
|
|
329
|
+
"telemetry.sdk.language": "javascript",
|
|
330
|
+
"telemetry.sdk.name": sdk.name,
|
|
331
|
+
"telemetry.sdk.version": sdk.version,
|
|
332
|
+
"flare.language.name": "javascript"
|
|
333
|
+
};
|
|
334
|
+
if (config.serviceName) identity["service.name"] = config.serviceName;
|
|
335
|
+
if (config.version) identity["service.version"] = config.version;
|
|
336
|
+
if (config.stage) identity["service.stage"] = config.stage;
|
|
337
|
+
if (framework?.name) identity["flare.framework.name"] = framework.name;
|
|
338
|
+
if (framework?.version) identity["flare.framework.version"] = framework.version;
|
|
339
|
+
return {
|
|
340
|
+
...base,
|
|
341
|
+
...identity
|
|
342
|
+
};
|
|
343
|
+
}
|
|
344
|
+
|
|
255
345
|
//#endregion
|
|
256
346
|
//#region src/logging/otel.ts
|
|
257
|
-
|
|
347
|
+
/**
|
|
348
|
+
* Converts one attribute value into the OpenTelemetry `AnyValue` shape. Strings, numbers and booleans become
|
|
349
|
+
* leaves, arrays and objects are walked recursively. Anything OpenTelemetry cannot carry (null, undefined,
|
|
350
|
+
* NaN, functions) returns null and the caller drops that key.
|
|
351
|
+
*
|
|
352
|
+
* A value that contains itself becomes the string `[Circular]`. `inPath` only holds the parents of the value
|
|
353
|
+
* being converted right now, so the same object used twice side by side is converted twice instead of being
|
|
354
|
+
* wrongly called circular.
|
|
355
|
+
*
|
|
356
|
+
* The walk also stops at a maximum depth and a maximum number of nodes, see traversalBudget.ts. Pass `budget`
|
|
357
|
+
* to let several calls share one allowance, otherwise every call gets its own.
|
|
358
|
+
*/
|
|
359
|
+
function valueToOpenTelemetry(value, inPath = /* @__PURE__ */ new WeakSet(), budget = require_urlAttributes.createTraversalBudget()) {
|
|
360
|
+
return convert(value, inPath, 0, budget);
|
|
361
|
+
}
|
|
362
|
+
function convert(value, inPath, depth, budget) {
|
|
363
|
+
if (!require_urlAttributes.spendNode(budget)) return { stringValue: require_urlAttributes.TRUNCATED };
|
|
258
364
|
if (typeof value === "string") return { stringValue: value };
|
|
259
365
|
if (typeof value === "boolean") return { boolValue: value };
|
|
260
366
|
if (typeof value === "number") {
|
|
@@ -262,12 +368,13 @@ function valueToOpenTelemetry(value, inPath = /* @__PURE__ */ new WeakSet()) {
|
|
|
262
368
|
return Number.isInteger(value) ? { intValue: value } : { doubleValue: value };
|
|
263
369
|
}
|
|
264
370
|
if (value === null || value === void 0) return null;
|
|
371
|
+
if (depth >= require_urlAttributes.MAX_TRAVERSAL_DEPTH) return { stringValue: require_urlAttributes.TRUNCATED };
|
|
265
372
|
if (Array.isArray(value)) {
|
|
266
373
|
if (inPath.has(value)) return { stringValue: "[Circular]" };
|
|
267
374
|
inPath.add(value);
|
|
268
375
|
const values = [];
|
|
269
376
|
for (const item of value) {
|
|
270
|
-
const mapped =
|
|
377
|
+
const mapped = convert(item, inPath, depth + 1, budget);
|
|
271
378
|
if (mapped !== null) values.push(mapped);
|
|
272
379
|
}
|
|
273
380
|
inPath.delete(value);
|
|
@@ -278,7 +385,7 @@ function valueToOpenTelemetry(value, inPath = /* @__PURE__ */ new WeakSet()) {
|
|
|
278
385
|
inPath.add(value);
|
|
279
386
|
const values = [];
|
|
280
387
|
for (const [key, item] of Object.entries(value)) {
|
|
281
|
-
const mapped =
|
|
388
|
+
const mapped = convert(item, inPath, depth + 1, budget);
|
|
282
389
|
if (mapped !== null) values.push({
|
|
283
390
|
key,
|
|
284
391
|
value: mapped
|
|
@@ -290,9 +397,10 @@ function valueToOpenTelemetry(value, inPath = /* @__PURE__ */ new WeakSet()) {
|
|
|
290
397
|
return null;
|
|
291
398
|
}
|
|
292
399
|
function attributesToOpenTelemetry(attributes) {
|
|
400
|
+
const budget = require_urlAttributes.createTraversalBudget();
|
|
293
401
|
const out = [];
|
|
294
402
|
for (const [key, value] of Object.entries(attributes)) {
|
|
295
|
-
const mapped = valueToOpenTelemetry(value);
|
|
403
|
+
const mapped = valueToOpenTelemetry(value, /* @__PURE__ */ new WeakSet(), budget);
|
|
296
404
|
if (mapped !== null) out.push({
|
|
297
405
|
key,
|
|
298
406
|
value: mapped
|
|
@@ -303,6 +411,18 @@ function attributesToOpenTelemetry(attributes) {
|
|
|
303
411
|
|
|
304
412
|
//#endregion
|
|
305
413
|
//#region src/logging/envelope.ts
|
|
414
|
+
function toOtelLogRecord(record) {
|
|
415
|
+
return {
|
|
416
|
+
timeUnixNano: record.timeUnixNano,
|
|
417
|
+
observedTimeUnixNano: record.timeUnixNano,
|
|
418
|
+
severityNumber: record.severityNumber,
|
|
419
|
+
severityText: record.severityText,
|
|
420
|
+
body: { stringValue: record.message },
|
|
421
|
+
attributes: record.recordAttributes,
|
|
422
|
+
flags: 0,
|
|
423
|
+
droppedAttributesCount: 0
|
|
424
|
+
};
|
|
425
|
+
}
|
|
306
426
|
function buildLogsEnvelope(records, resourceAttributes, scopeName, scopeVersion) {
|
|
307
427
|
return { resourceLogs: [{
|
|
308
428
|
resource: {
|
|
@@ -316,19 +436,24 @@ function buildLogsEnvelope(records, resourceAttributes, scopeName, scopeVersion)
|
|
|
316
436
|
attributes: [],
|
|
317
437
|
droppedAttributesCount: 0
|
|
318
438
|
},
|
|
319
|
-
logRecords: records.map(
|
|
320
|
-
timeUnixNano: record.timeUnixNano,
|
|
321
|
-
observedTimeUnixNano: record.timeUnixNano,
|
|
322
|
-
severityNumber: record.severityNumber,
|
|
323
|
-
severityText: record.severityText,
|
|
324
|
-
body: { stringValue: record.message },
|
|
325
|
-
attributes: record.recordAttributes,
|
|
326
|
-
flags: 0,
|
|
327
|
-
droppedAttributesCount: 0
|
|
328
|
-
}))
|
|
439
|
+
logRecords: records.map(toOtelLogRecord)
|
|
329
440
|
}]
|
|
330
441
|
}] };
|
|
331
442
|
}
|
|
443
|
+
/**
|
|
444
|
+
* How many UTF-8 bytes one record adds to an envelope. We measure the real toOtelLogRecord output instead of
|
|
445
|
+
* reusing the cached BufferedLog estimate, because keepaliveMaxBytes is a hard browser limit and an estimate
|
|
446
|
+
* is not good enough.
|
|
447
|
+
*
|
|
448
|
+
* Uses flatJsonStringify to match Api.logs, which sends the envelope through the same encoder.
|
|
449
|
+
*/
|
|
450
|
+
function otelLogRecordBytes(record) {
|
|
451
|
+
return utf8Bytes(require_urlAttributes.flatJsonStringify(toOtelLogRecord(record)));
|
|
452
|
+
}
|
|
453
|
+
/** UTF-8 bytes of an empty envelope: the fixed overhead every batch has, before any records are added. */
|
|
454
|
+
function emptyLogsEnvelopeBytes(resourceAttributes, scopeName, scopeVersion) {
|
|
455
|
+
return utf8Bytes(require_urlAttributes.flatJsonStringify(buildLogsEnvelope([], resourceAttributes, scopeName, scopeVersion)));
|
|
456
|
+
}
|
|
332
457
|
|
|
333
458
|
//#endregion
|
|
334
459
|
//#region src/logging/severity.ts
|
|
@@ -355,14 +480,42 @@ function isAtOrAboveMinimum(level, minimum) {
|
|
|
355
480
|
//#endregion
|
|
356
481
|
//#region src/logging/Logger.ts
|
|
357
482
|
var Logger = class {
|
|
358
|
-
|
|
483
|
+
inner;
|
|
359
484
|
resourceAttributes = {};
|
|
360
|
-
timer;
|
|
361
|
-
timerActive = false;
|
|
362
485
|
constructor(deps) {
|
|
363
486
|
this.deps = deps;
|
|
364
|
-
|
|
365
|
-
|
|
487
|
+
this.inner = new TelemetryBuffer({
|
|
488
|
+
getConfig: deps.getConfig,
|
|
489
|
+
scheduler: deps.scheduler
|
|
490
|
+
}, {
|
|
491
|
+
limits: (config) => ({
|
|
492
|
+
maxSize: config.maxLogBufferSize,
|
|
493
|
+
maxBytes: config.logFlushMaxBytes,
|
|
494
|
+
flushIntervalMs: config.logFlushIntervalMs
|
|
495
|
+
}),
|
|
496
|
+
enabled: (config) => config.enableLogs,
|
|
497
|
+
keepaliveBudget: () => deps.api.keepaliveBudgetRemaining(),
|
|
498
|
+
estimateBytes: (record) => this.estimateBytes(record),
|
|
499
|
+
emptyEnvelopeBytes: (resource) => {
|
|
500
|
+
const sdk = deps.getSdkInfo();
|
|
501
|
+
return emptyLogsEnvelopeBytes(resource, sdk.name, sdk.version);
|
|
502
|
+
},
|
|
503
|
+
recordBytes: (record) => otelLogRecordBytes(record),
|
|
504
|
+
oversizedMessage: "Flare: dropping oversized log record",
|
|
505
|
+
keepaliveDropMessage: (count) => `Flare: dropped ${count} log record(s) from keepalive envelope (over budget)`,
|
|
506
|
+
sendFailureMessage: "Flare: failed to send buffered log records",
|
|
507
|
+
resourceForFlush: () => this.resourceForFlush(),
|
|
508
|
+
buildEnvelope: (records, resource) => {
|
|
509
|
+
const sdk = deps.getSdkInfo();
|
|
510
|
+
return buildLogsEnvelope(records, resource, sdk.name, sdk.version);
|
|
511
|
+
},
|
|
512
|
+
send: (envelope, config, keepalive) => {
|
|
513
|
+
deps.track(deps.api.logs(envelope, config.logsIngestUrl, config.key, config.debug, keepalive));
|
|
514
|
+
},
|
|
515
|
+
onRecordBuffered: (record) => {
|
|
516
|
+
this.resourceAttributes = record.resourceAttributes;
|
|
517
|
+
}
|
|
518
|
+
});
|
|
366
519
|
}
|
|
367
520
|
debug(message, context = {}, attributes = {}) {
|
|
368
521
|
this.record("debug", message, context, attributes);
|
|
@@ -389,7 +542,13 @@ var Logger = class {
|
|
|
389
542
|
this.record("emergency", message, context, attributes);
|
|
390
543
|
}
|
|
391
544
|
bufferLength() {
|
|
392
|
-
return this.
|
|
545
|
+
return this.inner.length();
|
|
546
|
+
}
|
|
547
|
+
flush(opts) {
|
|
548
|
+
this.inner.flush(opts);
|
|
549
|
+
}
|
|
550
|
+
clear() {
|
|
551
|
+
this.inner.clear();
|
|
393
552
|
}
|
|
394
553
|
record(level, message, context, attributes) {
|
|
395
554
|
const config = this.deps.getConfig();
|
|
@@ -400,114 +559,20 @@ var Logger = class {
|
|
|
400
559
|
...attributes
|
|
401
560
|
};
|
|
402
561
|
const { record, resource } = this.deps.buildLogAttributes(userAttributes);
|
|
403
|
-
|
|
562
|
+
this.inner.add({
|
|
404
563
|
timeUnixNano: String(Date.now()) + "000000",
|
|
405
564
|
severityNumber: severityNumber(level),
|
|
406
565
|
severityText: severityText(level),
|
|
407
566
|
message,
|
|
408
567
|
recordAttributes: attributesToOpenTelemetry(record),
|
|
409
568
|
resourceAttributes: resource
|
|
410
|
-
};
|
|
411
|
-
if (this.estimateBytes(buffered) > config.logFlushMaxBytes) {
|
|
412
|
-
if (config.debug) console.error("Flare: dropping oversized log record");
|
|
413
|
-
return;
|
|
414
|
-
}
|
|
415
|
-
this.buffer.push(buffered);
|
|
416
|
-
this.resourceAttributes = resource;
|
|
417
|
-
this.evaluateTriggers(config);
|
|
418
|
-
this.trim(config);
|
|
419
|
-
}
|
|
420
|
-
evaluateTriggers(config) {
|
|
421
|
-
if (this.buffer.length >= config.maxLogBufferSize) {
|
|
422
|
-
this.flush();
|
|
423
|
-
return;
|
|
424
|
-
}
|
|
425
|
-
if (this.bufferBytes() >= config.logFlushMaxBytes) {
|
|
426
|
-
this.flush();
|
|
427
|
-
return;
|
|
428
|
-
}
|
|
429
|
-
this.armTimer(config);
|
|
430
|
-
}
|
|
431
|
-
armTimer(config) {
|
|
432
|
-
if (this.timerActive) return;
|
|
433
|
-
this.timerActive = true;
|
|
434
|
-
this.timer = setTimeout(() => this.flush(), config.logFlushIntervalMs);
|
|
435
|
-
this.timer.unref?.();
|
|
436
|
-
}
|
|
437
|
-
trim(config) {
|
|
438
|
-
if (this.buffer.length > config.maxLogBufferSize) this.buffer = this.buffer.slice(this.buffer.length - config.maxLogBufferSize);
|
|
439
|
-
while (this.buffer.length > 1 && this.bufferBytes() > config.logFlushMaxBytes) this.buffer.shift();
|
|
440
|
-
}
|
|
441
|
-
flush(opts) {
|
|
442
|
-
const config = this.deps.getConfig();
|
|
443
|
-
if (!config.enableLogs) return;
|
|
444
|
-
if (this.buffer.length === 0) return;
|
|
445
|
-
if (!assertKey(config.key, config.debug)) {
|
|
446
|
-
this.clearTimer();
|
|
447
|
-
return;
|
|
448
|
-
}
|
|
449
|
-
this.clearTimer();
|
|
450
|
-
let records;
|
|
451
|
-
if (opts?.keepalive) {
|
|
452
|
-
records = this.packForKeepalive(config);
|
|
453
|
-
this.buffer = this.buffer.filter((log) => !records.includes(log));
|
|
454
|
-
if (this.buffer.length > 0) this.armTimer(config);
|
|
455
|
-
} else {
|
|
456
|
-
records = this.buffer;
|
|
457
|
-
this.buffer = [];
|
|
458
|
-
}
|
|
459
|
-
if (records.length === 0) return;
|
|
460
|
-
this.deps.track(this.deps.api.logs(this.buildEnvelope(records), config.logsIngestUrl, config.key, config.debug, !!opts?.keepalive));
|
|
461
|
-
}
|
|
462
|
-
clear() {
|
|
463
|
-
this.buffer = [];
|
|
464
|
-
this.clearTimer();
|
|
465
|
-
}
|
|
466
|
-
packForKeepalive(config) {
|
|
467
|
-
let selected = [];
|
|
468
|
-
for (let i = this.buffer.length - 1; i >= 0; i--) {
|
|
469
|
-
const trial = [this.buffer[i], ...selected];
|
|
470
|
-
if (new TextEncoder().encode(flatJsonStringify(this.buildEnvelope(trial))).length <= config.keepaliveMaxBytes) selected = trial;
|
|
471
|
-
else if (config.debug) console.error("Flare: dropping log record from keepalive envelope (over budget)");
|
|
472
|
-
}
|
|
473
|
-
return selected;
|
|
474
|
-
}
|
|
475
|
-
buildEnvelope(records) {
|
|
476
|
-
const sdk = this.deps.getSdkInfo();
|
|
477
|
-
return buildLogsEnvelope(records, this.resourceForFlush(), sdk.name, sdk.version);
|
|
569
|
+
});
|
|
478
570
|
}
|
|
479
571
|
resourceForFlush() {
|
|
480
|
-
|
|
481
|
-
const sdk = this.deps.getSdkInfo();
|
|
482
|
-
const framework = this.deps.getFramework();
|
|
483
|
-
const identity = {
|
|
484
|
-
"telemetry.sdk.language": "javascript",
|
|
485
|
-
"telemetry.sdk.name": sdk.name,
|
|
486
|
-
"telemetry.sdk.version": sdk.version,
|
|
487
|
-
"flare.language.name": "javascript"
|
|
488
|
-
};
|
|
489
|
-
if (config.serviceName) identity["service.name"] = config.serviceName;
|
|
490
|
-
if (config.version) identity["service.version"] = config.version;
|
|
491
|
-
if (config.stage) identity["service.stage"] = config.stage;
|
|
492
|
-
if (framework?.name) identity["flare.framework.name"] = framework.name;
|
|
493
|
-
if (framework?.version) identity["flare.framework.version"] = framework.version;
|
|
494
|
-
return {
|
|
495
|
-
...this.resourceAttributes,
|
|
496
|
-
...identity
|
|
497
|
-
};
|
|
498
|
-
}
|
|
499
|
-
clearTimer() {
|
|
500
|
-
if (this.timer) {
|
|
501
|
-
clearTimeout(this.timer);
|
|
502
|
-
this.timer = void 0;
|
|
503
|
-
}
|
|
504
|
-
this.timerActive = false;
|
|
572
|
+
return buildResourceIdentity(this.resourceAttributes, this.deps.getConfig(), this.deps.getSdkInfo(), this.deps.getFramework());
|
|
505
573
|
}
|
|
506
574
|
estimateBytes(log) {
|
|
507
|
-
return flatJsonStringify(log).length;
|
|
508
|
-
}
|
|
509
|
-
bufferBytes() {
|
|
510
|
-
return this.buffer.reduce((sum, log) => sum + this.estimateBytes(log), 0);
|
|
575
|
+
return require_urlAttributes.flatJsonStringify(log).length;
|
|
511
576
|
}
|
|
512
577
|
};
|
|
513
578
|
|
|
@@ -542,31 +607,17 @@ function partitionAttributes(attributes) {
|
|
|
542
607
|
|
|
543
608
|
//#endregion
|
|
544
609
|
//#region src/Scope.ts
|
|
545
|
-
/**
|
|
546
|
-
* Maps each `User` identity field to the flat report attribute key it projects to.
|
|
547
|
-
* `Flare.setUser`'s set pass writes through these so the literal key strings live in
|
|
548
|
-
* exactly one place; `USER_IDENTITY_KEYS` (the clear pass) derives from them, so adding
|
|
549
|
-
* a field here can never silently leave the clear pass out of date.
|
|
550
|
-
*/
|
|
610
|
+
/** `USER_IDENTITY_KEYS` derives from this, so adding a field here can never leave the clear pass stale. */
|
|
551
611
|
const USER_FIELD_KEYS = {
|
|
552
612
|
id: "user.id",
|
|
553
613
|
email: "user.email",
|
|
554
614
|
fullName: "user.full_name",
|
|
555
615
|
ipAddress: "client.address"
|
|
556
616
|
};
|
|
557
|
-
/**
|
|
558
|
-
*
|
|
559
|
-
* fields plus the `user.attributes` bag for extras. Single source of truth so the
|
|
560
|
-
* clear pass and the set pass in `setUser` cannot drift, and so consumers that must
|
|
561
|
-
* stamp identity outside core's report pipeline (Electron's forwarded-renderer path)
|
|
562
|
-
* pick up the exact same set instead of re-hardcoding it.
|
|
563
|
-
*/
|
|
617
|
+
/** Every key `Flare.setUser` owns. Consumers stamping identity outside core's report pipeline (Electron's
|
|
618
|
+
* forwarded-renderer path) reuse this exact set. */
|
|
564
619
|
const USER_IDENTITY_KEYS = [...Object.values(USER_FIELD_KEYS), "user.attributes"];
|
|
565
|
-
/**
|
|
566
|
-
* Pick the user-identity attributes currently set on a scope. Used where identity must
|
|
567
|
-
* be copied onto a report that does not flow through `Flare.report()` (which would
|
|
568
|
-
* otherwise spread `pendingAttributes` automatically).
|
|
569
|
-
*/
|
|
620
|
+
/** For reports that do not flow through `Flare.report()`, which would spread `pendingAttributes` itself. */
|
|
570
621
|
function userIdentityAttributes(scope) {
|
|
571
622
|
const attrs = {};
|
|
572
623
|
for (const key of USER_IDENTITY_KEYS) {
|
|
@@ -576,39 +627,15 @@ function userIdentityAttributes(scope) {
|
|
|
576
627
|
return attrs;
|
|
577
628
|
}
|
|
578
629
|
/**
|
|
579
|
-
*
|
|
580
|
-
*
|
|
581
|
-
*
|
|
582
|
-
*
|
|
583
|
-
* Why this exists as its own class: in the browser there is one `Flare` per
|
|
584
|
-
* page and one user at a time, so a single shared bag of state is fine. In
|
|
585
|
-
* Node, a single `Flare` instance serves many concurrent requests, and each
|
|
586
|
-
* request wants its own breadcrumbs and its own custom context that do NOT
|
|
587
|
-
* leak into other requests. Splitting this state out of `Flare` lets the
|
|
588
|
-
* consumer choose: one global `Scope` (browser) or one `Scope` per request
|
|
589
|
-
* via AsyncLocalStorage (Node).
|
|
590
|
-
*
|
|
591
|
-
* `Flare` reads and writes this through `scopeProvider.active()` instead of
|
|
592
|
-
* holding the state directly, so the per-request behavior comes from the
|
|
593
|
-
* provider, not from the class itself.
|
|
594
|
-
*
|
|
595
|
-
* `NodeScope` (in `@flareapp/node`) extends this with a `request` bucket
|
|
596
|
-
* (HTTP method, path, headers). User identity is written to `pendingAttributes`
|
|
597
|
-
* by `Flare.setUser`, so it needs no dedicated field. Browser does not need `request`.
|
|
630
|
+
* Per-call mutable state, split out of `Flare` so the consumer can choose one global `Scope` (browser, one
|
|
631
|
+
* user at a time) or one per request via AsyncLocalStorage (Node, where concurrent requests must not leak
|
|
632
|
+
* into each other). `@flareapp/node`'s `NodeScope` extends this with a `request` bucket.
|
|
598
633
|
*/
|
|
599
634
|
var Scope = class {
|
|
600
635
|
glows = [];
|
|
601
636
|
pendingAttributes = {};
|
|
602
637
|
entryPoint = null;
|
|
603
|
-
/**
|
|
604
|
-
* Append a breadcrumb. Caps the list at `maxGlowsPerReport` by dropping the
|
|
605
|
-
* OLDEST entries when the limit is exceeded; this keeps reports below a
|
|
606
|
-
* payload-size threshold while preserving the most recent events leading
|
|
607
|
-
* up to an error.
|
|
608
|
-
*
|
|
609
|
-
* `slice(length - max)` returns the trailing `max` items, which is the
|
|
610
|
-
* shortest way to drop from the front and keep insertion order.
|
|
611
|
-
*/
|
|
638
|
+
/** Caps at `maxGlowsPerReport` by dropping the oldest, so the payload stays bounded. */
|
|
612
639
|
addGlow(glow, maxGlowsPerReport) {
|
|
613
640
|
this.glows.push(glow);
|
|
614
641
|
if (this.glows.length > maxGlowsPerReport) this.glows = this.glows.slice(this.glows.length - maxGlowsPerReport);
|
|
@@ -616,29 +643,15 @@ var Scope = class {
|
|
|
616
643
|
clearGlows() {
|
|
617
644
|
this.glows = [];
|
|
618
645
|
}
|
|
619
|
-
/**
|
|
620
|
-
* Set a single attribute on this scope. Called from `Flare.addContext` and
|
|
621
|
-
* `Flare.addContextGroup`. Last write wins.
|
|
622
|
-
*/
|
|
623
646
|
setAttribute(key, value) {
|
|
624
647
|
this.pendingAttributes[key] = value;
|
|
625
648
|
}
|
|
626
|
-
/**
|
|
627
|
-
* Shallow-merge a bag of attributes into this scope. Used by Node's
|
|
628
|
-
* AsyncLocalStorage provider when patching the live request context via
|
|
629
|
-
* `flare.mergeContext({ ... })`. Last write wins per key; nested objects
|
|
630
|
-
* are NOT deep-merged.
|
|
631
|
-
*/
|
|
649
|
+
/** Shallow: last write wins per key, nested objects are not deep-merged. */
|
|
632
650
|
mergeAttributes(partial) {
|
|
633
651
|
Object.assign(this.pendingAttributes, partial);
|
|
634
652
|
}
|
|
635
653
|
};
|
|
636
|
-
/**
|
|
637
|
-
* The simplest provider: one `Scope` for the lifetime of the provider, shared
|
|
638
|
-
* by every caller. This is the right default for environments with a single
|
|
639
|
-
* logical context (browser tab, CLI script, etc.) and is the default that
|
|
640
|
-
* `Flare`'s constructor falls back to when no provider is supplied.
|
|
641
|
-
*/
|
|
654
|
+
/** One `Scope` for the provider's lifetime. The right default for a browser tab or a CLI script. */
|
|
642
655
|
var GlobalScopeProvider = class {
|
|
643
656
|
scope = new Scope();
|
|
644
657
|
active() {
|
|
@@ -665,11 +678,14 @@ function getCodeSnippet(fileReader, url, lineNumber, columnNumber) {
|
|
|
665
678
|
});
|
|
666
679
|
}
|
|
667
680
|
function readFile(fileReader, url) {
|
|
668
|
-
|
|
669
|
-
|
|
670
|
-
|
|
681
|
+
const cached = cachedFiles[url];
|
|
682
|
+
if (cached !== void 0) return cached;
|
|
683
|
+
const pending = fileReader.read(url).then((text) => {
|
|
684
|
+
if (text === null) delete cachedFiles[url];
|
|
671
685
|
return text;
|
|
672
686
|
});
|
|
687
|
+
cachedFiles[url] = pending;
|
|
688
|
+
return pending;
|
|
673
689
|
}
|
|
674
690
|
function readLinesFromFile(fileText, lineNumber, columnNumber, maxSnippetLineLength = 1e3, maxSnippetLines = 40) {
|
|
675
691
|
const codeSnippet = {};
|
|
@@ -709,7 +725,7 @@ function createStackTrace(error, debug, fileReader) {
|
|
|
709
725
|
try {
|
|
710
726
|
parsedFrames = error_stack_parser.default.parse(error);
|
|
711
727
|
} catch (parseError) {
|
|
712
|
-
assert(false, "Couldn't parse stacktrace of below error:", debug);
|
|
728
|
+
require_urlAttributes.assert(false, "Couldn't parse stacktrace of below error:", debug);
|
|
713
729
|
if (debug) {
|
|
714
730
|
console.error(parseError);
|
|
715
731
|
console.error(error);
|
|
@@ -761,25 +777,11 @@ function isApplicationFrame(fileName) {
|
|
|
761
777
|
//#endregion
|
|
762
778
|
//#region src/stacktrace/NullFileReader.ts
|
|
763
779
|
/**
|
|
764
|
-
* No-op `FileReader`
|
|
765
|
-
*
|
|
766
|
-
*
|
|
767
|
-
*
|
|
768
|
-
*
|
|
769
|
-
* the correct, safe behavior in an environment we know nothing about.
|
|
770
|
-
*
|
|
771
|
-
* The two real implementations live in the consumer packages and take their
|
|
772
|
-
* place once the right environment is established:
|
|
773
|
-
*
|
|
774
|
-
* - `@flareapp/js` injects `FetchFileReader`, which `fetch()`s source maps
|
|
775
|
-
* and original files over HTTP for browser stack frames.
|
|
776
|
-
* - `@flareapp/node` injects `DiskFileReader`, which reads files from disk
|
|
777
|
-
* via `node:fs/promises` for server stack frames.
|
|
778
|
-
*
|
|
779
|
-
* The interface (`read(url) -> Promise<string | null>`) lets the stack-trace
|
|
780
|
-
* builder treat all three the same way: ask for a URL, render the snippet
|
|
781
|
-
* when text comes back, gracefully skip it when `null` does. No environment
|
|
782
|
-
* checks anywhere in core.
|
|
780
|
+
* No-op `FileReader` returning `null` for every URL. Default for `Flare`'s `fileReader` param so `new Flare()` builds
|
|
781
|
+
* reports without picking an environment; stack frames just omit source snippets. Consumer packages inject the real
|
|
782
|
+
* ones: `@flareapp/js` a fetch-based reader, `@flareapp/node` a disk reader. The `read(url) -> Promise<string | null>`
|
|
783
|
+
* interface lets the stack-trace builder treat all three the same (render on text, skip on null), so core needs no
|
|
784
|
+
* environment checks.
|
|
783
785
|
*/
|
|
784
786
|
var NullFileReader = class {
|
|
785
787
|
read(_url) {
|
|
@@ -787,22 +789,634 @@ var NullFileReader = class {
|
|
|
787
789
|
}
|
|
788
790
|
};
|
|
789
791
|
|
|
792
|
+
//#endregion
|
|
793
|
+
//#region src/tracing/context.ts
|
|
794
|
+
var InMemoryActiveSpanHolder = class {
|
|
795
|
+
active;
|
|
796
|
+
root;
|
|
797
|
+
getActive() {
|
|
798
|
+
return this.active ?? this.root;
|
|
799
|
+
}
|
|
800
|
+
withActive(span, fn) {
|
|
801
|
+
const previous = this.active;
|
|
802
|
+
this.active = span;
|
|
803
|
+
try {
|
|
804
|
+
return fn();
|
|
805
|
+
} finally {
|
|
806
|
+
this.active = previous;
|
|
807
|
+
}
|
|
808
|
+
}
|
|
809
|
+
setActiveRoot(span) {
|
|
810
|
+
this.root = span;
|
|
811
|
+
}
|
|
812
|
+
};
|
|
813
|
+
|
|
814
|
+
//#endregion
|
|
815
|
+
//#region src/tracing/ids.ts
|
|
816
|
+
function randomHex(bytes) {
|
|
817
|
+
const randomBytes = new Uint8Array(bytes);
|
|
818
|
+
const cryptoApi = globalThis.crypto;
|
|
819
|
+
if (cryptoApi && typeof cryptoApi.getRandomValues === "function") cryptoApi.getRandomValues(randomBytes);
|
|
820
|
+
else for (let i = 0; i < bytes; i++) randomBytes[i] = Math.floor(Math.random() * 256);
|
|
821
|
+
if (randomBytes.every((b) => b === 0)) randomBytes[bytes - 1] = 1;
|
|
822
|
+
let out = "";
|
|
823
|
+
for (let i = 0; i < bytes; i++) out += randomBytes[i].toString(16).padStart(2, "0");
|
|
824
|
+
return out;
|
|
825
|
+
}
|
|
826
|
+
function traceId() {
|
|
827
|
+
return randomHex(16);
|
|
828
|
+
}
|
|
829
|
+
function spanId() {
|
|
830
|
+
return randomHex(8);
|
|
831
|
+
}
|
|
832
|
+
|
|
833
|
+
//#endregion
|
|
834
|
+
//#region src/tracing/sampler.ts
|
|
835
|
+
function resolveSampling(samplingContext, config, rng = Math.random) {
|
|
836
|
+
if (samplingContext.parentSampled !== void 0) return samplingContext.parentSampled;
|
|
837
|
+
let rate;
|
|
838
|
+
if (config.tracesSampler) {
|
|
839
|
+
let result;
|
|
840
|
+
try {
|
|
841
|
+
result = config.tracesSampler(samplingContext);
|
|
842
|
+
} catch (error) {
|
|
843
|
+
if (config.debug) console.error("Flare: tracesSampler threw, treating span as not sampled", error);
|
|
844
|
+
return false;
|
|
845
|
+
}
|
|
846
|
+
if (typeof result === "boolean") return result;
|
|
847
|
+
rate = result;
|
|
848
|
+
} else rate = config.tracesSampleRate;
|
|
849
|
+
rate = Math.max(0, Math.min(1, rate));
|
|
850
|
+
if (rate <= 0) return false;
|
|
851
|
+
if (rate >= 1) return true;
|
|
852
|
+
return rng() < rate;
|
|
853
|
+
}
|
|
854
|
+
|
|
855
|
+
//#endregion
|
|
856
|
+
//#region src/tracing/Span.ts
|
|
857
|
+
var SpanImpl = class {
|
|
858
|
+
traceId;
|
|
859
|
+
spanId;
|
|
860
|
+
parentSpanId;
|
|
861
|
+
name;
|
|
862
|
+
isRecording;
|
|
863
|
+
epoch;
|
|
864
|
+
stateGeneration;
|
|
865
|
+
startTimeUnixNano;
|
|
866
|
+
scopeAttributes;
|
|
867
|
+
endTimeUnixNano = 0;
|
|
868
|
+
status = { code: SpanStatusCode.Unset };
|
|
869
|
+
attributes = {};
|
|
870
|
+
droppedAttributesCount = 0;
|
|
871
|
+
events = [];
|
|
872
|
+
droppedEventsCount = 0;
|
|
873
|
+
ended = false;
|
|
874
|
+
constructor(init, deps) {
|
|
875
|
+
this.deps = deps;
|
|
876
|
+
this.traceId = init.traceId;
|
|
877
|
+
this.spanId = init.spanId;
|
|
878
|
+
this.parentSpanId = init.parentSpanId;
|
|
879
|
+
this.name = init.name;
|
|
880
|
+
this.isRecording = init.recording;
|
|
881
|
+
this.epoch = init.epoch;
|
|
882
|
+
this.stateGeneration = init.stateGeneration;
|
|
883
|
+
this.startTimeUnixNano = init.startTimeUnixNano;
|
|
884
|
+
this.scopeAttributes = init.scopeAttributes;
|
|
885
|
+
}
|
|
886
|
+
setAttribute(key, value) {
|
|
887
|
+
if (this.ended) return this;
|
|
888
|
+
if (!(key in this.attributes) && Object.keys(this.attributes).length >= this.deps.maxAttributesPerSpan) {
|
|
889
|
+
this.droppedAttributesCount++;
|
|
890
|
+
return this;
|
|
891
|
+
}
|
|
892
|
+
this.attributes[key] = value;
|
|
893
|
+
return this;
|
|
894
|
+
}
|
|
895
|
+
setStatus(status) {
|
|
896
|
+
if (!this.ended) this.status = status;
|
|
897
|
+
return this;
|
|
898
|
+
}
|
|
899
|
+
addEvent(name, attributes = {}) {
|
|
900
|
+
if (this.ended) return this;
|
|
901
|
+
if (this.events.length >= this.deps.maxEventsPerSpan) {
|
|
902
|
+
this.droppedEventsCount++;
|
|
903
|
+
return this;
|
|
904
|
+
}
|
|
905
|
+
const capped = {};
|
|
906
|
+
let dropped = 0;
|
|
907
|
+
for (const [key, value] of Object.entries(attributes)) {
|
|
908
|
+
if (Object.keys(capped).length >= this.deps.maxAttributesPerSpanEvent) {
|
|
909
|
+
dropped++;
|
|
910
|
+
continue;
|
|
911
|
+
}
|
|
912
|
+
capped[key] = value;
|
|
913
|
+
}
|
|
914
|
+
this.events.push({
|
|
915
|
+
name,
|
|
916
|
+
timeUnixNano: this.deps.now(),
|
|
917
|
+
attributes: capped,
|
|
918
|
+
droppedAttributesCount: dropped
|
|
919
|
+
});
|
|
920
|
+
return this;
|
|
921
|
+
}
|
|
922
|
+
end(endTimeUnixNano) {
|
|
923
|
+
if (this.ended) return;
|
|
924
|
+
this.ended = true;
|
|
925
|
+
this.endTimeUnixNano = endTimeUnixNano ?? this.deps.now();
|
|
926
|
+
this.deps.onEnd(this);
|
|
927
|
+
}
|
|
928
|
+
};
|
|
929
|
+
|
|
930
|
+
//#endregion
|
|
931
|
+
//#region src/tracing/envelope.ts
|
|
932
|
+
function toOtelSpan(span) {
|
|
933
|
+
const status = span.status.message !== void 0 ? {
|
|
934
|
+
code: span.status.code,
|
|
935
|
+
message: span.status.message
|
|
936
|
+
} : { code: span.status.code };
|
|
937
|
+
return {
|
|
938
|
+
traceId: span.traceId,
|
|
939
|
+
spanId: span.spanId,
|
|
940
|
+
parentSpanId: span.parentSpanId,
|
|
941
|
+
name: span.name,
|
|
942
|
+
startTimeUnixNano: span.startTimeUnixNano,
|
|
943
|
+
endTimeUnixNano: span.endTimeUnixNano,
|
|
944
|
+
status,
|
|
945
|
+
attributes: span.recordAttributes,
|
|
946
|
+
events: span.events,
|
|
947
|
+
droppedAttributesCount: span.droppedAttributesCount,
|
|
948
|
+
droppedEventsCount: span.droppedEventsCount,
|
|
949
|
+
links: [],
|
|
950
|
+
droppedLinksCount: 0
|
|
951
|
+
};
|
|
952
|
+
}
|
|
953
|
+
function buildTracesEnvelope(spans, resourceAttributes, scopeName, scopeVersion) {
|
|
954
|
+
return { resourceSpans: [{
|
|
955
|
+
resource: {
|
|
956
|
+
attributes: attributesToOpenTelemetry(resourceAttributes),
|
|
957
|
+
droppedAttributesCount: 0
|
|
958
|
+
},
|
|
959
|
+
scopeSpans: [{
|
|
960
|
+
scope: {
|
|
961
|
+
name: scopeName,
|
|
962
|
+
version: scopeVersion,
|
|
963
|
+
attributes: [],
|
|
964
|
+
droppedAttributesCount: 0
|
|
965
|
+
},
|
|
966
|
+
spans: spans.map(toOtelSpan)
|
|
967
|
+
}]
|
|
968
|
+
}] };
|
|
969
|
+
}
|
|
970
|
+
/**
|
|
971
|
+
* How many UTF-8 bytes one span adds to an envelope. We measure the real toOtelSpan output instead of reusing
|
|
972
|
+
* the cached BufferedSpan estimate, because keepaliveMaxBytes is a hard browser limit and an estimate is not
|
|
973
|
+
* good enough.
|
|
974
|
+
*
|
|
975
|
+
* We use flatJsonStringify instead of JSON.stringify because a span keeps values the caller still owns, like
|
|
976
|
+
* status.message, and those can turn unserializable after the span ended. This runs from a visibilitychange
|
|
977
|
+
* listener with no try/catch around it, so a throw here loses the flush. flatJsonStringify handles the usual
|
|
978
|
+
* suspects (circular references, BigInt, a getter that throws on a plain object) but is not bulletproof: a
|
|
979
|
+
* class instance with a throwing getter goes through untouched and can still throw.
|
|
980
|
+
*/
|
|
981
|
+
function otelSpanBytes(span) {
|
|
982
|
+
return utf8Bytes(require_urlAttributes.flatJsonStringify(toOtelSpan(span)));
|
|
983
|
+
}
|
|
984
|
+
/** UTF-8 bytes of an empty envelope: the fixed overhead every batch has, before any spans are added. */
|
|
985
|
+
function emptyTracesEnvelopeBytes(resourceAttributes, scopeName, scopeVersion) {
|
|
986
|
+
return utf8Bytes(JSON.stringify(buildTracesEnvelope([], resourceAttributes, scopeName, scopeVersion)));
|
|
987
|
+
}
|
|
988
|
+
|
|
989
|
+
//#endregion
|
|
990
|
+
//#region src/tracing/SpanBuffer.ts
|
|
991
|
+
/** The span half of the shared telemetry buffer: names the config keys, the envelope and the ingest call. */
|
|
992
|
+
var SpanBuffer = class {
|
|
993
|
+
inner;
|
|
994
|
+
constructor(deps) {
|
|
995
|
+
this.deps = deps;
|
|
996
|
+
this.inner = new TelemetryBuffer({
|
|
997
|
+
getConfig: deps.getConfig,
|
|
998
|
+
scheduler: deps.scheduler
|
|
999
|
+
}, {
|
|
1000
|
+
limits: (config) => ({
|
|
1001
|
+
maxSize: config.maxSpanBufferSize,
|
|
1002
|
+
maxBytes: config.spanFlushMaxBytes,
|
|
1003
|
+
flushIntervalMs: config.spanFlushIntervalMs
|
|
1004
|
+
}),
|
|
1005
|
+
enabled: (config) => config.enableTracing,
|
|
1006
|
+
keepaliveBudget: () => deps.api.keepaliveBudgetRemaining(),
|
|
1007
|
+
estimateBytes: (span) => this.estimateBytes(span),
|
|
1008
|
+
emptyEnvelopeBytes: (resource) => {
|
|
1009
|
+
const sdk = deps.getSdkInfo();
|
|
1010
|
+
return emptyTracesEnvelopeBytes(resource, sdk.name, sdk.version);
|
|
1011
|
+
},
|
|
1012
|
+
recordBytes: (span) => otelSpanBytes(span),
|
|
1013
|
+
oversizedMessage: "Flare: dropping oversized span",
|
|
1014
|
+
keepaliveDropMessage: (count) => `Flare: dropped ${count} span(s) from keepalive envelope (over budget)`,
|
|
1015
|
+
sendFailureMessage: "Flare: failed to send buffered spans",
|
|
1016
|
+
resourceForFlush: () => this.resourceForFlush(),
|
|
1017
|
+
buildEnvelope: (spans, resource) => {
|
|
1018
|
+
const sdk = deps.getSdkInfo();
|
|
1019
|
+
return buildTracesEnvelope(spans, resource, sdk.name, sdk.version);
|
|
1020
|
+
},
|
|
1021
|
+
send: (envelope, config, keepalive) => {
|
|
1022
|
+
deps.track(deps.api.traces(envelope, config.tracesIngestUrl, config.key, config.debug, keepalive));
|
|
1023
|
+
}
|
|
1024
|
+
});
|
|
1025
|
+
}
|
|
1026
|
+
length() {
|
|
1027
|
+
return this.inner.length();
|
|
1028
|
+
}
|
|
1029
|
+
add(span) {
|
|
1030
|
+
this.inner.add(span);
|
|
1031
|
+
}
|
|
1032
|
+
flush(opts) {
|
|
1033
|
+
this.inner.flush(opts);
|
|
1034
|
+
}
|
|
1035
|
+
clear() {
|
|
1036
|
+
this.inner.clear();
|
|
1037
|
+
}
|
|
1038
|
+
resourceForFlush() {
|
|
1039
|
+
return buildResourceIdentity(this.deps.getResourceAttributes(), this.deps.getConfig(), this.deps.getSdkInfo(), this.deps.getFramework());
|
|
1040
|
+
}
|
|
1041
|
+
estimateBytes(span) {
|
|
1042
|
+
return JSON.stringify(span).length;
|
|
1043
|
+
}
|
|
1044
|
+
};
|
|
1045
|
+
|
|
1046
|
+
//#endregion
|
|
1047
|
+
//#region src/tracing/traceparent.ts
|
|
1048
|
+
const HEX32 = /^[0-9a-f]{32}$/;
|
|
1049
|
+
const HEX16 = /^[0-9a-f]{16}$/;
|
|
1050
|
+
const HEX8 = /^[0-9a-f]{2}$/;
|
|
1051
|
+
const ZERO32 = "0".repeat(32);
|
|
1052
|
+
const ZERO16 = "0".repeat(16);
|
|
1053
|
+
function buildTraceparent(traceId, spanId, sampled) {
|
|
1054
|
+
return `00-${traceId}-${spanId}-${sampled ? "01" : "00"}`;
|
|
1055
|
+
}
|
|
1056
|
+
function parseTraceparent(header) {
|
|
1057
|
+
const parts = header.trim().split("-");
|
|
1058
|
+
if (parts.length !== 4) return null;
|
|
1059
|
+
const [version, traceId, spanId, flags] = parts;
|
|
1060
|
+
if (version !== "00") return null;
|
|
1061
|
+
if (!HEX32.test(traceId) || traceId === ZERO32) return null;
|
|
1062
|
+
if (!HEX16.test(spanId) || spanId === ZERO16) return null;
|
|
1063
|
+
if (!HEX8.test(flags)) return null;
|
|
1064
|
+
return {
|
|
1065
|
+
traceId,
|
|
1066
|
+
parentSpanId: spanId,
|
|
1067
|
+
sampled: (parseInt(flags, 16) & 1) === 1
|
|
1068
|
+
};
|
|
1069
|
+
}
|
|
1070
|
+
|
|
1071
|
+
//#endregion
|
|
1072
|
+
//#region src/tracing/Tracer.ts
|
|
1073
|
+
function isPromiseLike(value) {
|
|
1074
|
+
return (typeof value === "object" || typeof value === "function") && value !== null && typeof value.then === "function";
|
|
1075
|
+
}
|
|
1076
|
+
/** `SpanOptions.parent` is a structurally overlapping union; `isRecording` is what tells a real Span apart. */
|
|
1077
|
+
function isSpan(parent) {
|
|
1078
|
+
return "isRecording" in parent;
|
|
1079
|
+
}
|
|
1080
|
+
/** A SpanImpl carries the epoch it was created under; a hand-stitched `{traceId, spanId}` parent does not. */
|
|
1081
|
+
function hasEpoch(parent) {
|
|
1082
|
+
return "epoch" in parent && typeof parent.epoch === "number";
|
|
1083
|
+
}
|
|
1084
|
+
function defaultNowNano() {
|
|
1085
|
+
const performanceApi = globalThis.performance;
|
|
1086
|
+
const ms = performanceApi && typeof performanceApi.now === "function" && typeof performanceApi.timeOrigin === "number" ? performanceApi.timeOrigin + performanceApi.now() : Date.now();
|
|
1087
|
+
return Math.round(ms * 1e6);
|
|
1088
|
+
}
|
|
1089
|
+
/**
|
|
1090
|
+
* Both trace maps cap their size the same way: insertion order is LRU, so the first key is the one to drop.
|
|
1091
|
+
* Only evicts when `key` is not already in the map. A set() that overwrites an existing key does not grow the
|
|
1092
|
+
* map, so it must not evict an unrelated entry to make room for it.
|
|
1093
|
+
*/
|
|
1094
|
+
function evictLruIfNew(map, key, cap) {
|
|
1095
|
+
if (map.has(key) || map.size < cap) return;
|
|
1096
|
+
const lru = map.keys().next().value;
|
|
1097
|
+
if (lru !== void 0) map.delete(lru);
|
|
1098
|
+
}
|
|
1099
|
+
const MAX_CLOSED_TRACES = 100;
|
|
1100
|
+
/** Bounded backstop for the live TraceState map: an app that never ends spans must not grow it forever. */
|
|
1101
|
+
const DEFAULT_MAX_LIVE_TRACES = 1e3;
|
|
1102
|
+
var Tracer = class {
|
|
1103
|
+
buffer;
|
|
1104
|
+
holder;
|
|
1105
|
+
traceStates = /* @__PURE__ */ new Map();
|
|
1106
|
+
closedTraces = /* @__PURE__ */ new Map();
|
|
1107
|
+
stateGeneration = 0;
|
|
1108
|
+
now;
|
|
1109
|
+
rng;
|
|
1110
|
+
maxLiveTraces;
|
|
1111
|
+
epoch = 0;
|
|
1112
|
+
pendingContinuation = null;
|
|
1113
|
+
spanListeners = /* @__PURE__ */ new Set();
|
|
1114
|
+
constructor(deps) {
|
|
1115
|
+
this.deps = deps;
|
|
1116
|
+
this.buffer = new SpanBuffer({
|
|
1117
|
+
api: deps.api,
|
|
1118
|
+
getConfig: deps.getConfig,
|
|
1119
|
+
getSdkInfo: deps.getSdkInfo,
|
|
1120
|
+
getFramework: deps.getFramework,
|
|
1121
|
+
getResourceAttributes: deps.getResourceAttributes,
|
|
1122
|
+
track: deps.track,
|
|
1123
|
+
scheduler: deps.scheduler
|
|
1124
|
+
});
|
|
1125
|
+
this.holder = deps.activeSpanHolder ?? new InMemoryActiveSpanHolder();
|
|
1126
|
+
this.now = deps.now ?? defaultNowNano;
|
|
1127
|
+
this.rng = deps.rng ?? Math.random;
|
|
1128
|
+
this.maxLiveTraces = deps.maxLiveTraces ?? DEFAULT_MAX_LIVE_TRACES;
|
|
1129
|
+
}
|
|
1130
|
+
getActiveSpan() {
|
|
1131
|
+
return this.holder.getActive();
|
|
1132
|
+
}
|
|
1133
|
+
setActiveRoot(span) {
|
|
1134
|
+
this.holder.setActiveRoot?.(span);
|
|
1135
|
+
}
|
|
1136
|
+
/**
|
|
1137
|
+
* Take one span against `traceId`'s cap up front, for a caller that publishes a span id before the
|
|
1138
|
+
* span exists (the component profilers do; their descendants record first). False means the trace is
|
|
1139
|
+
* full and the caller should stay transparent instead of handing out an id the cap will refuse.
|
|
1140
|
+
* Consumed by the matching `startSpan({ claimed: true })`.
|
|
1141
|
+
*/
|
|
1142
|
+
claimSpanSlot(traceId) {
|
|
1143
|
+
const config = this.deps.getConfig();
|
|
1144
|
+
if (!config.enableTracing) return false;
|
|
1145
|
+
const state = this.traceStates.get(traceId);
|
|
1146
|
+
if (!state || !state.recording || state.startedSpanCount >= config.maxSpansPerTrace) return false;
|
|
1147
|
+
state.startedSpanCount++;
|
|
1148
|
+
return true;
|
|
1149
|
+
}
|
|
1150
|
+
addSpanListener(fn) {
|
|
1151
|
+
this.spanListeners.add(fn);
|
|
1152
|
+
return () => {
|
|
1153
|
+
this.spanListeners.delete(fn);
|
|
1154
|
+
};
|
|
1155
|
+
}
|
|
1156
|
+
emitSpanEvent(phase, span) {
|
|
1157
|
+
for (const fn of this.spanListeners) try {
|
|
1158
|
+
fn({
|
|
1159
|
+
phase,
|
|
1160
|
+
span
|
|
1161
|
+
});
|
|
1162
|
+
} catch {}
|
|
1163
|
+
}
|
|
1164
|
+
flush(opts) {
|
|
1165
|
+
this.buffer.flush(opts);
|
|
1166
|
+
}
|
|
1167
|
+
clear() {
|
|
1168
|
+
this.buffer.clear();
|
|
1169
|
+
this.traceStates.clear();
|
|
1170
|
+
this.closedTraces.clear();
|
|
1171
|
+
this.setActiveRoot(void 0);
|
|
1172
|
+
this.pendingContinuation = null;
|
|
1173
|
+
this.epoch++;
|
|
1174
|
+
}
|
|
1175
|
+
continueFromTraceparent(header) {
|
|
1176
|
+
this.pendingContinuation = parseTraceparent(header);
|
|
1177
|
+
}
|
|
1178
|
+
/**
|
|
1179
|
+
* Runs `fn` with the span active, so spans started inside auto-parent to it, then ends it.
|
|
1180
|
+
* Records an error status first if `fn` throws or its returned promise rejects.
|
|
1181
|
+
*/
|
|
1182
|
+
withSpan(name, fn, opts = {}) {
|
|
1183
|
+
const span = this.startSpan(name, opts);
|
|
1184
|
+
const finishError = (error) => {
|
|
1185
|
+
span.setStatus({
|
|
1186
|
+
code: SpanStatusCode.Error,
|
|
1187
|
+
message: error instanceof Error ? error.message : String(error)
|
|
1188
|
+
});
|
|
1189
|
+
span.end();
|
|
1190
|
+
};
|
|
1191
|
+
return this.holder.withActive(span, () => {
|
|
1192
|
+
try {
|
|
1193
|
+
const result = fn(span);
|
|
1194
|
+
if (isPromiseLike(result)) return result.then((value) => {
|
|
1195
|
+
span.end();
|
|
1196
|
+
return value;
|
|
1197
|
+
}, (error) => {
|
|
1198
|
+
finishError(error);
|
|
1199
|
+
throw error;
|
|
1200
|
+
});
|
|
1201
|
+
span.end();
|
|
1202
|
+
return result;
|
|
1203
|
+
} catch (error) {
|
|
1204
|
+
finishError(error);
|
|
1205
|
+
throw error;
|
|
1206
|
+
}
|
|
1207
|
+
});
|
|
1208
|
+
}
|
|
1209
|
+
/** Starts a span the caller must end. Unlike `withSpan`, it does not become the active span,
|
|
1210
|
+
* so spans started after it do not auto-parent to it. */
|
|
1211
|
+
startSpan(name, opts = {}) {
|
|
1212
|
+
const config = this.deps.getConfig();
|
|
1213
|
+
const spanId$1 = opts.spanId ?? spanId();
|
|
1214
|
+
const continuation = this.pendingContinuation;
|
|
1215
|
+
this.pendingContinuation = null;
|
|
1216
|
+
if (!config.enableTracing) return this.startInertSpan(name, spanId$1, opts, config);
|
|
1217
|
+
const { traceId, parentSpanId, state } = this.resolveTrace(spanId$1, name, opts, config, continuation);
|
|
1218
|
+
let recording = state.recording;
|
|
1219
|
+
if (opts.claimed) {} else if (state.startedSpanCount >= config.maxSpansPerTrace) {
|
|
1220
|
+
recording = false;
|
|
1221
|
+
if (config.debug && !state.loggedCap) {
|
|
1222
|
+
state.loggedCap = true;
|
|
1223
|
+
console.error("Flare: maxSpansPerTrace reached, dropping span");
|
|
1224
|
+
}
|
|
1225
|
+
} else state.startedSpanCount++;
|
|
1226
|
+
state.openSpanCount++;
|
|
1227
|
+
const isLocalRoot = state.localRootSpanId === spanId$1;
|
|
1228
|
+
const span = this.makeSpan({
|
|
1229
|
+
traceId,
|
|
1230
|
+
spanId: spanId$1,
|
|
1231
|
+
parentSpanId,
|
|
1232
|
+
name,
|
|
1233
|
+
recording,
|
|
1234
|
+
isLocalRoot,
|
|
1235
|
+
stateGeneration: state.generation
|
|
1236
|
+
}, opts, config);
|
|
1237
|
+
this.emitSpanEvent("start", span);
|
|
1238
|
+
return span;
|
|
1239
|
+
}
|
|
1240
|
+
/** A real Span handle that records nothing, so callers never have to branch on whether tracing is on. */
|
|
1241
|
+
startInertSpan(name, spanId, opts, config) {
|
|
1242
|
+
const span = this.makeSpan({
|
|
1243
|
+
traceId: traceId(),
|
|
1244
|
+
spanId,
|
|
1245
|
+
parentSpanId: null,
|
|
1246
|
+
name,
|
|
1247
|
+
recording: false,
|
|
1248
|
+
isLocalRoot: true,
|
|
1249
|
+
stateGeneration: 0
|
|
1250
|
+
}, opts, config);
|
|
1251
|
+
this.emitSpanEvent("start", span);
|
|
1252
|
+
return span;
|
|
1253
|
+
}
|
|
1254
|
+
resolveTrace(spanId, name, opts, config, continuation) {
|
|
1255
|
+
let parent = opts.forceRoot ? opts.parent : opts.parent ?? this.holder.getActive();
|
|
1256
|
+
if (parent && hasEpoch(parent) && parent.epoch !== this.epoch) parent = void 0;
|
|
1257
|
+
if (parent && "spanId" in parent && "traceId" in parent) {
|
|
1258
|
+
const traceId = parent.traceId;
|
|
1259
|
+
const fallbackRecording = () => isSpan(parent) ? parent.isRecording : resolveSampling({
|
|
1260
|
+
name,
|
|
1261
|
+
attributes: opts.attributes ?? {},
|
|
1262
|
+
spanType: opts.spanType
|
|
1263
|
+
}, config, this.rng);
|
|
1264
|
+
const state = this.getOrSeedState(traceId, spanId, fallbackRecording);
|
|
1265
|
+
return {
|
|
1266
|
+
traceId,
|
|
1267
|
+
parentSpanId: parent.spanId,
|
|
1268
|
+
state
|
|
1269
|
+
};
|
|
1270
|
+
}
|
|
1271
|
+
if (continuation) {
|
|
1272
|
+
const recording = resolveSampling({
|
|
1273
|
+
name,
|
|
1274
|
+
parentSampled: continuation.sampled,
|
|
1275
|
+
attributes: opts.attributes ?? {},
|
|
1276
|
+
spanType: opts.spanType
|
|
1277
|
+
}, config, this.rng);
|
|
1278
|
+
const state = this.createState(continuation.traceId, spanId, recording);
|
|
1279
|
+
return {
|
|
1280
|
+
traceId: continuation.traceId,
|
|
1281
|
+
parentSpanId: continuation.parentSpanId,
|
|
1282
|
+
state
|
|
1283
|
+
};
|
|
1284
|
+
}
|
|
1285
|
+
const traceId$1 = traceId();
|
|
1286
|
+
const recording = resolveSampling({
|
|
1287
|
+
name,
|
|
1288
|
+
attributes: opts.attributes ?? {},
|
|
1289
|
+
spanType: opts.spanType
|
|
1290
|
+
}, config, this.rng);
|
|
1291
|
+
return {
|
|
1292
|
+
traceId: traceId$1,
|
|
1293
|
+
parentSpanId: null,
|
|
1294
|
+
state: this.createState(traceId$1, spanId, recording)
|
|
1295
|
+
};
|
|
1296
|
+
}
|
|
1297
|
+
getOrSeedState(traceId, localRootSpanId, fallbackRecording) {
|
|
1298
|
+
const existing = this.traceStates.get(traceId);
|
|
1299
|
+
if (existing) {
|
|
1300
|
+
this.traceStates.delete(traceId);
|
|
1301
|
+
this.traceStates.set(traceId, existing);
|
|
1302
|
+
return existing;
|
|
1303
|
+
}
|
|
1304
|
+
const closed = this.closedTraces.get(traceId);
|
|
1305
|
+
if (closed) {
|
|
1306
|
+
this.closedTraces.delete(traceId);
|
|
1307
|
+
const state = this.createState(traceId, closed.localRootSpanId, closed.recording);
|
|
1308
|
+
state.startedSpanCount = closed.startedSpanCount;
|
|
1309
|
+
state.rootEnded = true;
|
|
1310
|
+
return state;
|
|
1311
|
+
}
|
|
1312
|
+
return this.createState(traceId, localRootSpanId, fallbackRecording());
|
|
1313
|
+
}
|
|
1314
|
+
createState(traceId, localRootSpanId, recording) {
|
|
1315
|
+
evictLruIfNew(this.traceStates, traceId, this.maxLiveTraces);
|
|
1316
|
+
const state = {
|
|
1317
|
+
traceId,
|
|
1318
|
+
recording,
|
|
1319
|
+
localRootSpanId,
|
|
1320
|
+
rootEnded: false,
|
|
1321
|
+
startedSpanCount: 0,
|
|
1322
|
+
openSpanCount: 0,
|
|
1323
|
+
generation: ++this.stateGeneration,
|
|
1324
|
+
loggedCap: false
|
|
1325
|
+
};
|
|
1326
|
+
this.traceStates.set(traceId, state);
|
|
1327
|
+
return state;
|
|
1328
|
+
}
|
|
1329
|
+
makeSpan(init, opts, config) {
|
|
1330
|
+
const scopeAttributes = init.recording && init.isLocalRoot ? this.deps.getScopeAttributes() : {};
|
|
1331
|
+
const span = new SpanImpl({
|
|
1332
|
+
...init,
|
|
1333
|
+
startTimeUnixNano: opts.startTimeUnixNano ?? this.now(),
|
|
1334
|
+
epoch: this.epoch,
|
|
1335
|
+
scopeAttributes
|
|
1336
|
+
}, {
|
|
1337
|
+
maxAttributesPerSpan: config.maxAttributesPerSpan,
|
|
1338
|
+
maxEventsPerSpan: config.maxEventsPerSpan,
|
|
1339
|
+
maxAttributesPerSpanEvent: config.maxAttributesPerSpanEvent,
|
|
1340
|
+
now: this.now,
|
|
1341
|
+
onEnd: (s) => this.onSpanEnd(s)
|
|
1342
|
+
});
|
|
1343
|
+
if (opts.spanType) span.setAttribute("flare.span_type", opts.spanType);
|
|
1344
|
+
if (opts.attributes) for (const [key, value] of Object.entries(opts.attributes)) span.setAttribute(key, value);
|
|
1345
|
+
return span;
|
|
1346
|
+
}
|
|
1347
|
+
/** Bounded, LRU by insertion order, like traceStates. Holds primitives only, never a span. */
|
|
1348
|
+
rememberClosed(state) {
|
|
1349
|
+
evictLruIfNew(this.closedTraces, state.traceId, MAX_CLOSED_TRACES);
|
|
1350
|
+
this.closedTraces.set(state.traceId, {
|
|
1351
|
+
localRootSpanId: state.localRootSpanId,
|
|
1352
|
+
recording: state.recording,
|
|
1353
|
+
startedSpanCount: state.startedSpanCount
|
|
1354
|
+
});
|
|
1355
|
+
}
|
|
1356
|
+
onSpanEnd(span) {
|
|
1357
|
+
this.emitSpanEvent("end", span);
|
|
1358
|
+
if (span.epoch !== this.epoch) return;
|
|
1359
|
+
const state = this.traceStates.get(span.traceId);
|
|
1360
|
+
if (state && state.generation === span.stateGeneration) {
|
|
1361
|
+
state.openSpanCount--;
|
|
1362
|
+
if (span.spanId === state.localRootSpanId) state.rootEnded = true;
|
|
1363
|
+
if (state.rootEnded && state.openSpanCount <= 0) {
|
|
1364
|
+
this.traceStates.delete(span.traceId);
|
|
1365
|
+
this.rememberClosed(state);
|
|
1366
|
+
}
|
|
1367
|
+
}
|
|
1368
|
+
if (!span.isRecording) return;
|
|
1369
|
+
if (!this.deps.getConfig().enableTracing) return;
|
|
1370
|
+
try {
|
|
1371
|
+
const record = {
|
|
1372
|
+
...span.scopeAttributes,
|
|
1373
|
+
...span.attributes
|
|
1374
|
+
};
|
|
1375
|
+
const buffered = {
|
|
1376
|
+
traceId: span.traceId,
|
|
1377
|
+
spanId: span.spanId,
|
|
1378
|
+
parentSpanId: span.parentSpanId,
|
|
1379
|
+
name: span.name,
|
|
1380
|
+
startTimeUnixNano: span.startTimeUnixNano,
|
|
1381
|
+
endTimeUnixNano: span.endTimeUnixNano,
|
|
1382
|
+
status: span.status,
|
|
1383
|
+
recordAttributes: attributesToOpenTelemetry(record),
|
|
1384
|
+
droppedAttributesCount: span.droppedAttributesCount,
|
|
1385
|
+
droppedEventsCount: span.droppedEventsCount,
|
|
1386
|
+
events: span.events.map((event) => ({
|
|
1387
|
+
name: event.name,
|
|
1388
|
+
timeUnixNano: event.timeUnixNano,
|
|
1389
|
+
attributes: attributesToOpenTelemetry(event.attributes),
|
|
1390
|
+
droppedAttributesCount: event.droppedAttributesCount
|
|
1391
|
+
}))
|
|
1392
|
+
};
|
|
1393
|
+
this.buffer.add(buffered);
|
|
1394
|
+
} catch (error) {
|
|
1395
|
+
if (this.deps.getConfig().debug) console.error("Flare: failed to buffer span", error);
|
|
1396
|
+
}
|
|
1397
|
+
}
|
|
1398
|
+
};
|
|
1399
|
+
|
|
790
1400
|
//#endregion
|
|
791
1401
|
//#region src/Flare.ts
|
|
1402
|
+
/** Scope attributes a span never inherits. Derived from `USER_IDENTITY_KEYS` so a future user field is
|
|
1403
|
+
* excluded automatically, without anyone needing to remember to list it here. See `getScopeAttributes`. */
|
|
1404
|
+
const SPAN_SCOPE_EXCLUDED_KEYS = USER_IDENTITY_KEYS.filter((key) => key !== USER_FIELD_KEYS.id);
|
|
792
1405
|
const DEFAULT_SDK_NAME = "@flareapp/core";
|
|
793
1406
|
var Flare = class {
|
|
794
1407
|
inflight = /* @__PURE__ */ new Set();
|
|
795
1408
|
_logger;
|
|
1409
|
+
_tracer;
|
|
796
1410
|
_config = {
|
|
797
1411
|
key: null,
|
|
798
1412
|
version: "",
|
|
799
|
-
sourcemapVersionId: SOURCEMAP_VERSION,
|
|
1413
|
+
sourcemapVersionId: require_urlAttributes.SOURCEMAP_VERSION,
|
|
800
1414
|
stage: "",
|
|
801
1415
|
maxGlowsPerReport: 30,
|
|
802
1416
|
ingestUrl: "https://ingress.flareapp.io/v1/errors",
|
|
803
1417
|
reportBrowserExtensionErrors: false,
|
|
804
1418
|
debug: false,
|
|
805
|
-
urlDenylist: DEFAULT_URL_DENYLIST,
|
|
1419
|
+
urlDenylist: require_urlAttributes.DEFAULT_URL_DENYLIST,
|
|
806
1420
|
replaceDefaultUrlDenylist: false,
|
|
807
1421
|
sampleRate: 1,
|
|
808
1422
|
beforeEvaluate: (error) => error,
|
|
@@ -812,26 +1426,37 @@ var Flare = class {
|
|
|
812
1426
|
maxLogBufferSize: 100,
|
|
813
1427
|
logFlushIntervalMs: 5e3,
|
|
814
1428
|
logFlushMaxBytes: 8e5,
|
|
815
|
-
keepaliveMaxBytes: 6e4
|
|
1429
|
+
keepaliveMaxBytes: 6e4,
|
|
1430
|
+
enableTracing: false,
|
|
1431
|
+
tracesIngestUrl: "https://ingress.flareapp.io/v1/traces",
|
|
1432
|
+
tracesSampleRate: 1,
|
|
1433
|
+
maxSpanBufferSize: 100,
|
|
1434
|
+
spanFlushIntervalMs: 5e3,
|
|
1435
|
+
spanFlushMaxBytes: 8e5,
|
|
1436
|
+
maxSpansPerTrace: 1024,
|
|
1437
|
+
maxAttributesPerSpan: 128,
|
|
1438
|
+
maxEventsPerSpan: 128,
|
|
1439
|
+
maxAttributesPerSpanEvent: 128
|
|
816
1440
|
};
|
|
817
1441
|
sdkInfo = {
|
|
818
1442
|
name: DEFAULT_SDK_NAME,
|
|
819
|
-
version: CLIENT_VERSION
|
|
1443
|
+
version: require_urlAttributes.CLIENT_VERSION
|
|
820
1444
|
};
|
|
821
1445
|
framework = null;
|
|
822
1446
|
/**
|
|
823
|
-
* @param api
|
|
824
|
-
*
|
|
825
|
-
*
|
|
826
|
-
* @param fileReader
|
|
827
|
-
*
|
|
828
|
-
*
|
|
829
|
-
*
|
|
830
|
-
*
|
|
831
|
-
*
|
|
832
|
-
*
|
|
1447
|
+
* @param api fetch transport for reports, logs and traces. Stateless: ingest url and
|
|
1448
|
+
* key are passed per call, so tests swap in a fake.
|
|
1449
|
+
* @param contextCollector per-report attributes (browser DOM, Node process). No-op by default.
|
|
1450
|
+
* @param fileReader source files for stack-trace snippets. Defaults to no snippets;
|
|
1451
|
+
* `@flareapp/js` injects a fetch reader, `@flareapp/node` a disk reader.
|
|
1452
|
+
* @param scopeProvider the current `Scope`. Browser uses one global scope; Node an
|
|
1453
|
+
* AsyncLocalStorage-backed provider so each request gets its own.
|
|
1454
|
+
* @param scheduler drains the log and span buffers when the host's lifecycle ends (browser
|
|
1455
|
+
* unload, process exit). No-op by default, leaving only size/timer flushes.
|
|
1456
|
+
* @param activeSpanHolder tracks the active span so new spans auto-parent to it. In-memory by
|
|
1457
|
+
* default; a platform can back it with AsyncLocalStorage instead.
|
|
833
1458
|
*/
|
|
834
|
-
constructor(api = new Api(), contextCollector = () => ({}), fileReader = new NullFileReader(), scopeProvider = new GlobalScopeProvider(), scheduler = new NoopFlushScheduler()) {
|
|
1459
|
+
constructor(api = new Api(), contextCollector = () => ({}), fileReader = new NullFileReader(), scopeProvider = new GlobalScopeProvider(), scheduler = new NoopFlushScheduler(), activeSpanHolder = new InMemoryActiveSpanHolder()) {
|
|
835
1460
|
this.api = api;
|
|
836
1461
|
this.contextCollector = contextCollector;
|
|
837
1462
|
this.fileReader = fileReader;
|
|
@@ -845,57 +1470,25 @@ var Flare = class {
|
|
|
845
1470
|
track: (p) => this.track(p),
|
|
846
1471
|
scheduler
|
|
847
1472
|
});
|
|
1473
|
+
this._tracer = new Tracer({
|
|
1474
|
+
api: this.api,
|
|
1475
|
+
getConfig: () => this._config,
|
|
1476
|
+
getSdkInfo: () => this.sdkInfo,
|
|
1477
|
+
getFramework: () => this.framework,
|
|
1478
|
+
getScopeAttributes: () => this.getScopeAttributes(),
|
|
1479
|
+
getResourceAttributes: () => this.spanResourceAttributes(),
|
|
1480
|
+
track: (p) => this.track(p),
|
|
1481
|
+
scheduler,
|
|
1482
|
+
activeSpanHolder
|
|
1483
|
+
});
|
|
848
1484
|
}
|
|
849
1485
|
/**
|
|
850
|
-
* Register an in-flight report so `flush()` can wait for it.
|
|
851
|
-
*
|
|
852
|
-
* `reportMessage`, `reportUnhandledRejection`, `test`); each wraps its
|
|
853
|
-
* full async pipeline (beforeEvaluate -> stack trace + source snippets ->
|
|
854
|
-
* beforeSubmit -> `api.report()`) so the entire roundtrip is what's
|
|
855
|
-
* tracked, not just the HTTP send at the end.
|
|
856
|
-
*
|
|
857
|
-
* Two problems this method solves at once.
|
|
858
|
-
*
|
|
859
|
-
* Problem 1: hold a reference to the work without leaking rejections.
|
|
860
|
-
*
|
|
861
|
-
* `p` is the real report pipeline; it can reject (network failure,
|
|
862
|
-
* `beforeSubmit` throws, etc). If we stored `p` directly in `inflight`
|
|
863
|
-
* and no caller attached a `.catch` (the global error listeners use
|
|
864
|
-
* `reportSilently` which DOES catch, but the path is still subtle), an
|
|
865
|
-
* eventual rejection would surface as an unhandled-rejection warning
|
|
866
|
-
* on Node and a console error in the browser. Bad citizen.
|
|
867
|
-
*
|
|
868
|
-
* So we build a SHADOW promise that mirrors `p`'s timing but cannot
|
|
869
|
-
* reject:
|
|
870
|
-
*
|
|
871
|
-
* p.then(
|
|
872
|
-
* () => undefined, // on fulfilment, value is undefined
|
|
873
|
-
* () => undefined, // on rejection, ALSO resolve with undefined
|
|
874
|
-
* )
|
|
875
|
-
*
|
|
876
|
-
* Providing the second argument means we have "handled" any rejection
|
|
877
|
-
* from `p`. The shadow always resolves with `undefined`, and `p`'s
|
|
878
|
-
* rejection is consumed at the boundary. From the runtime's point of
|
|
879
|
-
* view, the shadow is well-behaved.
|
|
880
|
-
*
|
|
881
|
-
* Problem 2: self-cleaning entry.
|
|
882
|
-
*
|
|
883
|
-
* `tracked.finally(() => this.inflight.delete(tracked))`. `finally`
|
|
884
|
-
* fires whether the shadow resolves or rejects, but the shadow can no
|
|
885
|
-
* longer reject (problem 1 normalized it), so this is effectively
|
|
886
|
-
* "when the underlying report has settled, remove me from the Set."
|
|
887
|
-
* No GC magic, no external cleanup, no race window.
|
|
1486
|
+
* Register an in-flight report so `flush()` can wait for it. Every entry point wraps its whole async
|
|
1487
|
+
* pipeline, from beforeEvaluate through api.report, so flush() waits on all of it.
|
|
888
1488
|
*
|
|
889
|
-
*
|
|
890
|
-
*
|
|
891
|
-
*
|
|
892
|
-
* throw so we are safe today, but anything more elaborate added here
|
|
893
|
-
* should be wrapped in try/catch.
|
|
894
|
-
*
|
|
895
|
-
* The return value is the ORIGINAL `p`. The caller awaits real success
|
|
896
|
-
* or failure; the tracking is completely invisible to them. This is why
|
|
897
|
-
* `await flare.report(err)` inside a fatal handler observes network
|
|
898
|
-
* errors the same as before tracking was added.
|
|
1489
|
+
* What goes in the Set is a shadow promise that mirrors `p`'s timing but cannot reject, so a failed
|
|
1490
|
+
* report never surfaces as an unhandled rejection warning. `p` itself is returned untouched, so the
|
|
1491
|
+
* caller still observes real success or failure.
|
|
899
1492
|
*/
|
|
900
1493
|
track(p) {
|
|
901
1494
|
const tracked = p.then(() => void 0, () => void 0);
|
|
@@ -904,86 +1497,16 @@ var Flare = class {
|
|
|
904
1497
|
return p;
|
|
905
1498
|
}
|
|
906
1499
|
/**
|
|
907
|
-
* Wait until every in-flight report settles
|
|
908
|
-
*
|
|
909
|
-
*
|
|
910
|
-
* The main consumer is `@flareapp/node`'s fatal handler:
|
|
911
|
-
*
|
|
912
|
-
* process.on('uncaughtException', async (err) => {
|
|
913
|
-
* process.exitCode = 1;
|
|
914
|
-
* try { await flare.report(err); } catch {}
|
|
915
|
-
* await flare.flush(shutdownTimeoutMs);
|
|
916
|
-
* process.exit(1);
|
|
917
|
-
* });
|
|
918
|
-
*
|
|
919
|
-
* The fatal `report` is awaited explicitly; `flush` then drains any
|
|
920
|
-
* OTHER reports that were already in flight (a request handler that
|
|
921
|
-
* fired `flare.report(...)` concurrently with the crash). The timeout
|
|
922
|
-
* caps the wait so a hung HTTP request cannot indefinitely block
|
|
923
|
-
* shutdown.
|
|
924
|
-
*
|
|
925
|
-
* Walking the implementation:
|
|
926
|
-
*
|
|
927
|
-
* const pending = [...this.inflight];
|
|
928
|
-
*
|
|
929
|
-
* Spread takes a SNAPSHOT of the Set at this instant. Reports that
|
|
930
|
-
* start AFTER this line are not included in `pending`, so they are
|
|
931
|
-
* not awaited by THIS flush call. This is intentional: it bounds
|
|
932
|
-
* the wait. Without the snapshot, a handler that kept emitting
|
|
933
|
-
* reports during shutdown could keep flush alive forever and block
|
|
934
|
-
* the process from exiting.
|
|
935
|
-
*
|
|
936
|
-
* if (pending.length === 0) return Promise.resolve();
|
|
937
|
-
*
|
|
938
|
-
* Fast path. No timer scheduled, no promise constructor needed.
|
|
939
|
-
* Resolves on the microtask queue. Cheap.
|
|
940
|
-
*
|
|
941
|
-
* return new Promise<void>((resolve) => {
|
|
942
|
-
* const timer = setTimeout(resolve, timeoutMs);
|
|
943
|
-
* Promise.allSettled(pending).then(() => {
|
|
944
|
-
* clearTimeout(timer);
|
|
945
|
-
* resolve();
|
|
946
|
-
* });
|
|
947
|
-
* });
|
|
948
|
-
*
|
|
949
|
-
* The race between two outcomes, both calling the same `resolve`:
|
|
950
|
-
*
|
|
951
|
-
* 1. `setTimeout(resolve, timeoutMs)` schedules a "give up" call.
|
|
952
|
-
* After `timeoutMs` it fires, calling `resolve()` from the
|
|
953
|
-
* timer-queue side. The outer promise resolves immediately,
|
|
954
|
-
* even if reports are still pending. Those reports are abandoned
|
|
955
|
-
* (they continue running but the process is about to die).
|
|
956
|
-
*
|
|
957
|
-
* 2. `Promise.allSettled(pending)` returns a promise that resolves
|
|
958
|
-
* when every promise in `pending` has either fulfilled or
|
|
959
|
-
* rejected. It NEVER rejects on its own. We use `allSettled`
|
|
960
|
-
* rather than `Promise.all` because `all` short-circuits on the
|
|
961
|
-
* first rejection -- we want to wait for everyone regardless of
|
|
962
|
-
* whether their HTTP calls succeed or fail. (Our shadows cannot
|
|
963
|
-
* reject anyway because `track` normalized them, but using
|
|
964
|
-
* `allSettled` documents the intent and survives future changes
|
|
965
|
-
* to shadow construction.) When it resolves, we call
|
|
966
|
-
* `clearTimeout(timer)` to cancel the pending timer (so it does
|
|
967
|
-
* not fire later and call `resolve` a second time -- a no-op,
|
|
968
|
-
* but wasted work) and then `resolve()` ourselves.
|
|
1500
|
+
* Wait until every in-flight report settles or `timeoutMs` elapses. Always resolves, never rejects.
|
|
1501
|
+
* Written for `@flareapp/node`'s fatal handler, which awaits the fatal report itself then flushes to
|
|
1502
|
+
* drain any other concurrent reports before `process.exit`.
|
|
969
1503
|
*
|
|
970
|
-
*
|
|
971
|
-
*
|
|
972
|
-
* race is safe even if for some reason both branches fired together.
|
|
973
|
-
*
|
|
974
|
-
* Things flush() deliberately does NOT do:
|
|
975
|
-
*
|
|
976
|
-
* - It does not reject. Even if every report failed, allSettled
|
|
977
|
-
* resolves. Callers do not need a `.catch`.
|
|
978
|
-
* - It does not retry. One pipeline attempt per report, then move on.
|
|
979
|
-
* - It does not stop new reports from starting. The Flare instance
|
|
980
|
-
* is still usable after flush resolves. flush is "wait for what is
|
|
981
|
-
* in flight," not "freeze the SDK."
|
|
982
|
-
* - It does not drain reports started after the snapshot. Call flush
|
|
983
|
-
* again if you need to wait for those too.
|
|
1504
|
+
* Snapshotting the Set bounds the wait: reports started after this line are not awaited, so a handler
|
|
1505
|
+
* that keeps emitting during shutdown cannot block the process forever. Call flush again for those.
|
|
984
1506
|
*/
|
|
985
1507
|
flush(timeoutMs = 2e3) {
|
|
986
1508
|
this._logger.flush();
|
|
1509
|
+
this._tracer.flush();
|
|
987
1510
|
const pending = [...this.inflight];
|
|
988
1511
|
if (pending.length === 0) return Promise.resolve();
|
|
989
1512
|
return new Promise((resolve) => {
|
|
@@ -1003,22 +1526,42 @@ var Flare = class {
|
|
|
1003
1526
|
get logger() {
|
|
1004
1527
|
return this._logger;
|
|
1005
1528
|
}
|
|
1006
|
-
|
|
1529
|
+
get tracer() {
|
|
1530
|
+
return this._tracer;
|
|
1531
|
+
}
|
|
1532
|
+
/** Starts a span the caller must end. Unlike `withSpan`, it does not become the active span,
|
|
1533
|
+
* so spans started after it do not auto-parent to it. */
|
|
1534
|
+
startSpan(name, opts) {
|
|
1535
|
+
return this._tracer.startSpan(name, opts);
|
|
1536
|
+
}
|
|
1537
|
+
/**
|
|
1538
|
+
* Runs `fn` with the span active, so spans started inside auto-parent to it, then ends it.
|
|
1539
|
+
* Records an error status first if `fn` throws or its returned promise rejects.
|
|
1540
|
+
*/
|
|
1541
|
+
withSpan(name, fn, opts) {
|
|
1542
|
+
return this._tracer.withSpan(name, fn, opts);
|
|
1543
|
+
}
|
|
1544
|
+
light(key = require_urlAttributes.KEY, debug) {
|
|
1007
1545
|
this._config.key = key;
|
|
1008
1546
|
if (debug !== void 0) this._config.debug = debug;
|
|
1009
1547
|
this._logger.flush();
|
|
1548
|
+
this._tracer.flush();
|
|
1010
1549
|
return this;
|
|
1011
1550
|
}
|
|
1012
1551
|
configure(config) {
|
|
1013
1552
|
const wasLogsEnabled = this._config.enableLogs;
|
|
1553
|
+
const wasTracingEnabled = this._config.enableTracing;
|
|
1014
1554
|
this._config = {
|
|
1015
1555
|
...this._config,
|
|
1016
1556
|
...config
|
|
1017
1557
|
};
|
|
1018
1558
|
if (config.sampleRate !== void 0) this._config.sampleRate = Math.max(0, Math.min(1, config.sampleRate));
|
|
1019
|
-
this._config.
|
|
1559
|
+
if (config.tracesSampleRate !== void 0) this._config.tracesSampleRate = Math.max(0, Math.min(1, config.tracesSampleRate));
|
|
1560
|
+
if (config.urlDenylist !== void 0 || config.replaceDefaultUrlDenylist !== void 0) this._config.urlDenylist = require_urlAttributes.resolveDenylist(config.urlDenylist, config.replaceDefaultUrlDenylist ?? this._config.replaceDefaultUrlDenylist);
|
|
1020
1561
|
if (wasLogsEnabled && this._config.enableLogs === false) this._logger.clear();
|
|
1021
1562
|
if (config.key !== void 0) this._logger.flush();
|
|
1563
|
+
if (wasTracingEnabled && this._config.enableTracing === false) this._tracer.clear();
|
|
1564
|
+
if (config.key !== void 0) this._tracer.flush();
|
|
1022
1565
|
return this;
|
|
1023
1566
|
}
|
|
1024
1567
|
test() {
|
|
@@ -1030,7 +1573,7 @@ var Flare = class {
|
|
|
1030
1573
|
return this.sendReport(report);
|
|
1031
1574
|
}
|
|
1032
1575
|
glow(name, level = "info", data = []) {
|
|
1033
|
-
const time = now();
|
|
1576
|
+
const time = require_urlAttributes.now();
|
|
1034
1577
|
this.scopeProvider.active().addGlow({
|
|
1035
1578
|
name,
|
|
1036
1579
|
messageLevel: level,
|
|
@@ -1058,11 +1601,8 @@ var Flare = class {
|
|
|
1058
1601
|
return this;
|
|
1059
1602
|
}
|
|
1060
1603
|
/**
|
|
1061
|
-
*
|
|
1062
|
-
*
|
|
1063
|
-
* and `client.address`. Any extra keys are bundled into `user.attributes`.
|
|
1064
|
-
* Pass `null` to clear the user. Scope-aware: in Node this targets the
|
|
1065
|
-
* per-request scope via the scope provider.
|
|
1604
|
+
* Maps the known fields onto the keys the Flare backend reads (see `USER_FIELD_KEYS`) and bundles
|
|
1605
|
+
* anything else into `user.attributes`. Pass `null` to clear. In Node this targets the per-request scope.
|
|
1066
1606
|
*/
|
|
1067
1607
|
setUser(user) {
|
|
1068
1608
|
const scope = this.scopeProvider.active();
|
|
@@ -1095,7 +1635,7 @@ var Flare = class {
|
|
|
1095
1635
|
async reportInternal(error, attributes = {}) {
|
|
1096
1636
|
if (this._config.sampleRate < 1 && Math.random() >= this._config.sampleRate) return;
|
|
1097
1637
|
const seenAtUnixNano = Date.now() * 1e6;
|
|
1098
|
-
const coerced = error instanceof Error ? error : new Error(
|
|
1638
|
+
const coerced = error instanceof Error ? error : new Error(String(error));
|
|
1099
1639
|
const errorToReport = await this._config.beforeEvaluate(coerced);
|
|
1100
1640
|
if (!errorToReport) return;
|
|
1101
1641
|
const report = await this.createReportFromError(errorToReport, attributes, seenAtUnixNano);
|
|
@@ -1144,9 +1684,9 @@ var Flare = class {
|
|
|
1144
1684
|
return this.sendReport(report);
|
|
1145
1685
|
}
|
|
1146
1686
|
async createReportFromError(error, attributes = {}, seenAtUnixNano = Date.now() * 1e6) {
|
|
1147
|
-
if (!assert(error, "No error provided.", this._config.debug)) return false;
|
|
1687
|
+
if (!require_urlAttributes.assert(error, "No error provided.", this._config.debug)) return false;
|
|
1148
1688
|
const stacktrace = await createStackTrace(error, this._config.debug, this.fileReader);
|
|
1149
|
-
assert(stacktrace.length, "Couldn't generate stacktrace of this error: " + error, this._config.debug);
|
|
1689
|
+
require_urlAttributes.assert(stacktrace.length, "Couldn't generate stacktrace of this error: " + error, this._config.debug);
|
|
1150
1690
|
const exceptionClass = error.constructor && error.constructor.name ? error.constructor.name : "undefined";
|
|
1151
1691
|
return this.buildReport({
|
|
1152
1692
|
exceptionClass,
|
|
@@ -1155,7 +1695,7 @@ var Flare = class {
|
|
|
1155
1695
|
isLog: false,
|
|
1156
1696
|
level: void 0,
|
|
1157
1697
|
extraAttributes: attributes,
|
|
1158
|
-
code: extractCode(error),
|
|
1698
|
+
code: require_urlAttributes.extractCode(error),
|
|
1159
1699
|
seenAtUnixNano
|
|
1160
1700
|
});
|
|
1161
1701
|
}
|
|
@@ -1177,7 +1717,10 @@ var Flare = class {
|
|
|
1177
1717
|
const baseAttributes = includeBase ? this.buildBaseAttributes() : {};
|
|
1178
1718
|
const entryPoint = activeScope.entryPoint;
|
|
1179
1719
|
const entryPointOverrides = {};
|
|
1180
|
-
if (entryPoint?.identifier !== void 0)
|
|
1720
|
+
if (entryPoint?.identifier !== void 0) {
|
|
1721
|
+
entryPointOverrides["flare.entry_point.handler.identifier"] = entryPoint.identifier;
|
|
1722
|
+
entryPointOverrides["http.route"] = entryPoint.identifier;
|
|
1723
|
+
}
|
|
1181
1724
|
if (entryPoint?.type !== void 0) entryPointOverrides["flare.entry_point.handler.type"] = entryPoint.type;
|
|
1182
1725
|
if (entryPoint?.name !== void 0) entryPointOverrides["flare.entry_point.handler.name"] = entryPoint.name;
|
|
1183
1726
|
const attributes = {
|
|
@@ -1206,6 +1749,23 @@ var Flare = class {
|
|
|
1206
1749
|
record: this.assembleAttributes(collectorRecord, userAttributes, false)
|
|
1207
1750
|
};
|
|
1208
1751
|
}
|
|
1752
|
+
/**
|
|
1753
|
+
* Local roots only, snapshotted by the Tracer at span START so a long-lived root does not drift into
|
|
1754
|
+
* the next page's scope. Children get none, and no span ever runs the DOM collector.
|
|
1755
|
+
*
|
|
1756
|
+
* Everything assembled is inherited except user identity (excluding the opaque `user.id`): a root span
|
|
1757
|
+
* goes out for every page view, so email, full name, IP and `user.attributes` would turn normal
|
|
1758
|
+
* browsing into PII traffic. The rest — `context.custom`, `addContextGroup` bags — stays in, because
|
|
1759
|
+
* the trace viewer renders any span attribute whose key does not start with `flare.`.
|
|
1760
|
+
*/
|
|
1761
|
+
getScopeAttributes() {
|
|
1762
|
+
const scoped = { ...this.assembleAttributes({}, {}, false) };
|
|
1763
|
+
for (const key of SPAN_SCOPE_EXCLUDED_KEYS) delete scoped[key];
|
|
1764
|
+
return scoped;
|
|
1765
|
+
}
|
|
1766
|
+
spanResourceAttributes() {
|
|
1767
|
+
return partitionAttributes(this.contextCollector(this._config)).resource;
|
|
1768
|
+
}
|
|
1209
1769
|
buildReport(input) {
|
|
1210
1770
|
const activeScope = this.scopeProvider.active();
|
|
1211
1771
|
const attributes = this.assembleAttributes(this.contextCollector(this._config), input.extraAttributes, true);
|
|
@@ -1214,7 +1774,7 @@ var Flare = class {
|
|
|
1214
1774
|
message: input.message,
|
|
1215
1775
|
seenAtUnixNano: input.seenAtUnixNano,
|
|
1216
1776
|
stacktrace: input.stacktrace,
|
|
1217
|
-
events: glowsToEvents(activeScope.glows),
|
|
1777
|
+
events: require_urlAttributes.glowsToEvents(activeScope.glows),
|
|
1218
1778
|
attributes
|
|
1219
1779
|
};
|
|
1220
1780
|
if (input.isLog) report.isLog = true;
|
|
@@ -1224,7 +1784,7 @@ var Flare = class {
|
|
|
1224
1784
|
return report;
|
|
1225
1785
|
}
|
|
1226
1786
|
async sendReport(report) {
|
|
1227
|
-
if (!assertKey(this._config.key, this._config.debug)) return;
|
|
1787
|
+
if (!require_urlAttributes.assertKey(this._config.key, this._config.debug)) return;
|
|
1228
1788
|
const reportToSubmit = await this._config.beforeSubmit(report);
|
|
1229
1789
|
if (!reportToSubmit) return;
|
|
1230
1790
|
return this.api.report(reportToSubmit, this._config.ingestUrl, this._config.key, this._config.reportBrowserExtensionErrors, this._config.debug);
|
|
@@ -1233,26 +1793,43 @@ var Flare = class {
|
|
|
1233
1793
|
|
|
1234
1794
|
//#endregion
|
|
1235
1795
|
exports.Api = Api;
|
|
1236
|
-
exports.
|
|
1796
|
+
exports.BrowserSpanType = BrowserSpanType;
|
|
1797
|
+
exports.DEFAULT_MAX_LIVE_TRACES = DEFAULT_MAX_LIVE_TRACES;
|
|
1798
|
+
exports.DEFAULT_URL_DENYLIST = require_urlAttributes.DEFAULT_URL_DENYLIST;
|
|
1237
1799
|
exports.Flare = Flare;
|
|
1800
|
+
exports.FrameworkName = FrameworkName;
|
|
1238
1801
|
exports.GlobalScopeProvider = GlobalScopeProvider;
|
|
1802
|
+
exports.InMemoryActiveSpanHolder = InMemoryActiveSpanHolder;
|
|
1239
1803
|
exports.Logger = Logger;
|
|
1240
1804
|
exports.NoopFlushScheduler = NoopFlushScheduler;
|
|
1241
1805
|
exports.NullFileReader = NullFileReader;
|
|
1242
1806
|
exports.Scope = Scope;
|
|
1807
|
+
exports.SpanStatusCode = SpanStatusCode;
|
|
1808
|
+
exports.Tracer = Tracer;
|
|
1243
1809
|
exports.USER_IDENTITY_KEYS = USER_IDENTITY_KEYS;
|
|
1244
|
-
exports.assert = assert;
|
|
1245
|
-
exports.assertKey = assertKey;
|
|
1246
|
-
exports.
|
|
1810
|
+
exports.assert = require_urlAttributes.assert;
|
|
1811
|
+
exports.assertKey = require_urlAttributes.assertKey;
|
|
1812
|
+
exports.buildTraceparent = buildTraceparent;
|
|
1813
|
+
exports.buildTracesEnvelope = buildTracesEnvelope;
|
|
1814
|
+
exports.convertToError = require_urlAttributes.convertToError;
|
|
1815
|
+
exports.createIdentityTagger = require_urlAttributes.createIdentityTagger;
|
|
1247
1816
|
exports.createStackTrace = createStackTrace;
|
|
1248
|
-
exports.
|
|
1249
|
-
exports.
|
|
1250
|
-
exports.
|
|
1817
|
+
exports.defaultNowNano = defaultNowNano;
|
|
1818
|
+
exports.describeRejectionReason = require_urlAttributes.describeRejectionReason;
|
|
1819
|
+
exports.extractCode = require_urlAttributes.extractCode;
|
|
1820
|
+
exports.flatJsonStringify = require_urlAttributes.flatJsonStringify;
|
|
1251
1821
|
exports.getCodeSnippet = getCodeSnippet;
|
|
1252
|
-
exports.glowsToEvents = glowsToEvents;
|
|
1253
|
-
exports.now = now;
|
|
1822
|
+
exports.glowsToEvents = require_urlAttributes.glowsToEvents;
|
|
1823
|
+
exports.now = require_urlAttributes.now;
|
|
1824
|
+
exports.parseTraceparent = parseTraceparent;
|
|
1254
1825
|
exports.readLinesFromFile = readLinesFromFile;
|
|
1255
|
-
exports.
|
|
1256
|
-
exports.
|
|
1257
|
-
exports.
|
|
1826
|
+
exports.redactObjectValues = require_urlAttributes.redactObjectValues;
|
|
1827
|
+
exports.redactUrlQuery = require_urlAttributes.redactUrlQuery;
|
|
1828
|
+
exports.resolveDenylist = require_urlAttributes.resolveDenylist;
|
|
1829
|
+
exports.routeRejection = require_urlAttributes.routeRejection;
|
|
1830
|
+
exports.safeClone = require_urlAttributes.safeClone;
|
|
1831
|
+
exports.safeDecode = require_urlAttributes.safeDecode;
|
|
1832
|
+
exports.spanId = spanId;
|
|
1833
|
+
exports.toCustomContext = require_urlAttributes.toCustomContext;
|
|
1834
|
+
exports.urlAttributes = require_urlAttributes.urlAttributes;
|
|
1258
1835
|
exports.userIdentityAttributes = userIdentityAttributes;
|