@facilis.dev/rum 0.0.0-stage → 0.1.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/LICENSE +21 -0
- package/README.md +50 -2
- package/dist/config.d.ts +17 -0
- package/dist/config.js +40 -0
- package/dist/errors.d.ts +12 -0
- package/dist/errors.js +29 -0
- package/dist/exporter.d.ts +3 -0
- package/dist/exporter.js +55 -0
- package/dist/index.d.ts +5 -0
- package/dist/index.js +39 -0
- package/dist/instrumentations.d.ts +13 -0
- package/dist/instrumentations.js +39 -0
- package/dist/provider.d.ts +3 -0
- package/dist/provider.js +37 -0
- package/dist/react.d.ts +21 -0
- package/dist/react.js +20 -0
- package/dist/scrub.d.ts +27 -0
- package/dist/scrub.js +123 -0
- package/dist/vitals.d.ts +13 -0
- package/dist/vitals.js +22 -0
- package/package.json +65 -4
- package/src/config.ts +49 -0
- package/src/errors.ts +41 -0
- package/src/exporter.ts +58 -0
- package/src/index.ts +43 -0
- package/src/instrumentations.ts +60 -0
- package/src/provider.ts +44 -0
- package/src/react.tsx +34 -0
- package/src/scrub.ts +135 -0
- package/src/vitals.ts +34 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 facilis-dev
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,51 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @facilis.dev/rum
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Framework-owned browser RUM for Facilis apps (issue #138, D-203 §2, D-209).
|
|
4
|
+
|
|
5
|
+
- Emits Core Web Vitals (LCP/INP/CLS/FCP/TTFB) as `browser.web_vital` spans, window and
|
|
6
|
+
React-boundary errors as `browser.error` spans (type + source only, never message/stack),
|
|
7
|
+
plus document-load and fetch/XHR spans.
|
|
8
|
+
- Exports OTLP/JSON to the app's own ingestion route
|
|
9
|
+
(`POST /__facilis/telemetry/v1/traces`) with the public write-only tenant key header.
|
|
10
|
+
- `traceparent` propagates to the app's own origin only, never third parties.
|
|
11
|
+
- URLs are scrubbed client-side (defense in depth; the server allowlist is the gate).
|
|
12
|
+
- Operator collector guidance, privacy hardening and consent: `docs/TELEMETRY.md` (D-210).
|
|
13
|
+
- Production-only and opt-in: the `facilisRum()` Vite companion injects the
|
|
14
|
+
`__FACILIS_RUM_CONFIG__` literal at build time. Dev/disabled builds are completely silent.
|
|
15
|
+
|
|
16
|
+
`bootRum()` is called first in the framework template entry. The optional `./react`
|
|
17
|
+
subpath ships `RumErrorBoundary` (report-only; the fallback is caller-provided).
|
|
18
|
+
|
|
19
|
+
The web OTel line (sdk-trace-web 2.x, api 1.9.0) is deliberately separate from the server
|
|
20
|
+
line (SDK 3.x, api 1.10.0): the two cannot share one dependency tree (spike finding F1).
|
|
21
|
+
|
|
22
|
+
## Trace correlation, orphan spans, cross-origin (D-203 §4)
|
|
23
|
+
|
|
24
|
+
Every API fetch to the app's own origin carries a W3C `traceparent` header; Nitro continues
|
|
25
|
+
that trace and the DB query spans parent off the request, so one trace-id spans
|
|
26
|
+
browser fetch → Nitro request → DB query. The sampled bit (trace-flags) travels with the
|
|
27
|
+
header and both sides honor it (parent-based sampling). The integration gate is
|
|
28
|
+
`packages/nitro/src/runtime/telemetry/trace-correlation.test.ts`.
|
|
29
|
+
|
|
30
|
+
**Orphan spans.** The browser and the server export independently, and the RUM export never
|
|
31
|
+
retries (D-209). When an ad-blocker blocks the ingestion endpoint
|
|
32
|
+
(`POST /__facilis/telemetry/v1/traces`) or the backend is unreachable, traces arrive partial:
|
|
33
|
+
|
|
34
|
+
- The browser span still carries its client-generated trace-id even when the request failed or
|
|
35
|
+
its export was blocked; there is simply no backend counterpart at the collector.
|
|
36
|
+
- Conversely, backend spans can arrive without the browser half when only the export path is
|
|
37
|
+
blocked. The API request itself is never affected by a blocked export.
|
|
38
|
+
|
|
39
|
+
This is expected behavior, not data loss: read a missing half as a blocked export path. The
|
|
40
|
+
trace-id and the sampling decision stay consistent on whichever half survives, and the export
|
|
41
|
+
request itself is never instrumented (it cannot feed itself).
|
|
42
|
+
|
|
43
|
+
**Cross-origin deployments.** Same-origin (the default: one Nitro deployment serves SPA and
|
|
44
|
+
API) needs no CORS setup. When the API lives on a different origin, two things must hold:
|
|
45
|
+
|
|
46
|
+
1. The API's `Access-Control-Allow-Headers` must include `traceparent`, or the browser
|
|
47
|
+
strips the header on the cross-origin request and the trace splits. The framework's CORS
|
|
48
|
+
preflight echoes the requested headers for allowed routes; an operator proxy in front of
|
|
49
|
+
the app must allow the header as well.
|
|
50
|
+
2. The propagation allow-list must cover the API origin: `traceparent` is injected only into
|
|
51
|
+
requests matching it (never third parties).
|
package/dist/config.d.ts
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Build-time RUM configuration (D-209). The literal is injected by the facilisRum() Vite
|
|
3
|
+
* companion at `vite build` time only; dev builds define it as null, so the client is
|
|
4
|
+
* completely silent there (D-200). Nothing reads env at runtime: a browser has none.
|
|
5
|
+
*/
|
|
6
|
+
export interface RumConfig {
|
|
7
|
+
readonly tenantKey: string;
|
|
8
|
+
readonly endpoint: string;
|
|
9
|
+
readonly sampling: number;
|
|
10
|
+
readonly serviceName: string;
|
|
11
|
+
readonly deploymentId: string | null;
|
|
12
|
+
}
|
|
13
|
+
declare global {
|
|
14
|
+
const __FACILIS_RUM_CONFIG__: RumConfig | null | undefined;
|
|
15
|
+
}
|
|
16
|
+
/** Read the injected literal; anything missing or malformed is null (a no-op boot). */
|
|
17
|
+
export declare function readRumConfig(): RumConfig | null;
|
package/dist/config.js
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Build-time RUM configuration (D-209). The literal is injected by the facilisRum() Vite
|
|
3
|
+
* companion at `vite build` time only; dev builds define it as null, so the client is
|
|
4
|
+
* completely silent there (D-200). Nothing reads env at runtime: a browser has none.
|
|
5
|
+
*/
|
|
6
|
+
/** Read the injected literal; anything missing or malformed is null (a no-op boot). */
|
|
7
|
+
export function readRumConfig() {
|
|
8
|
+
// typeof guard: an unbundled import (tests, SSR/prerender) has no define at all.
|
|
9
|
+
if (typeof __FACILIS_RUM_CONFIG__ === "undefined" || __FACILIS_RUM_CONFIG__ === null)
|
|
10
|
+
return null;
|
|
11
|
+
const raw = __FACILIS_RUM_CONFIG__;
|
|
12
|
+
if (typeof raw !== "object")
|
|
13
|
+
return null;
|
|
14
|
+
const record = raw;
|
|
15
|
+
const tenantKey = record["tenantKey"];
|
|
16
|
+
const endpoint = record["endpoint"];
|
|
17
|
+
const serviceName = record["serviceName"];
|
|
18
|
+
// Fail-closed like the ingestion gates: a key with whitespace could never survive header
|
|
19
|
+
// handling, and an export without a target or a service identity is pointless.
|
|
20
|
+
if (typeof tenantKey !== "string" || tenantKey === "" || /\s/.test(tenantKey))
|
|
21
|
+
return null;
|
|
22
|
+
if (typeof endpoint !== "string" || endpoint === "")
|
|
23
|
+
return null;
|
|
24
|
+
if (typeof serviceName !== "string" || serviceName === "")
|
|
25
|
+
return null;
|
|
26
|
+
const deploymentId = typeof record["deploymentId"] === "string" ? record["deploymentId"] : null;
|
|
27
|
+
return {
|
|
28
|
+
tenantKey,
|
|
29
|
+
endpoint,
|
|
30
|
+
sampling: readSampling(record["sampling"]),
|
|
31
|
+
serviceName,
|
|
32
|
+
deploymentId,
|
|
33
|
+
};
|
|
34
|
+
}
|
|
35
|
+
/** Mirrors the backend's readSampling: an invalid ratio keeps everything, never nothing. */
|
|
36
|
+
function readSampling(value) {
|
|
37
|
+
return typeof value === "number" && Number.isFinite(value) && value >= 0 && value <= 1
|
|
38
|
+
? value
|
|
39
|
+
: 1;
|
|
40
|
+
}
|
package/dist/errors.d.ts
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Window-level error capture (D-203 §2): type + source only. Message, stack, filename and
|
|
3
|
+
* reason values are PII carriers and are never recorded — the server allowlist would drop
|
|
4
|
+
* them anyway; the client never sends them.
|
|
5
|
+
*/
|
|
6
|
+
import type { Tracer } from "@opentelemetry/api";
|
|
7
|
+
export type RumErrorSource = "window.onerror" | "unhandledrejection" | "react-boundary";
|
|
8
|
+
export declare const ERROR_SPAN_NAME = "browser.error";
|
|
9
|
+
/** Sanitized constructor name for Error values; every non-Error reason is "NonError". */
|
|
10
|
+
export declare function sanitizeErrorType(error: unknown): string;
|
|
11
|
+
export declare function captureRumError(error: unknown, source: RumErrorSource): void;
|
|
12
|
+
export declare function wireWindowErrors(tracer: Tracer): void;
|
package/dist/errors.js
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
export const ERROR_SPAN_NAME = "browser.error";
|
|
2
|
+
// Constructor names are low-cardinality identifiers; anything else collapses to a constant.
|
|
3
|
+
const ERROR_TYPE_PATTERN = /^[A-Za-z][A-Za-z0-9]{0,63}$/;
|
|
4
|
+
/** Sanitized constructor name for Error values; every non-Error reason is "NonError". */
|
|
5
|
+
export function sanitizeErrorType(error) {
|
|
6
|
+
if (!(error instanceof Error))
|
|
7
|
+
return "NonError";
|
|
8
|
+
const name = error.constructor.name;
|
|
9
|
+
return ERROR_TYPE_PATTERN.test(name) ? name : "Error";
|
|
10
|
+
}
|
|
11
|
+
// Null until an enabled boot wires a tracer: disabled/dev builds never emit (D-200).
|
|
12
|
+
let errorTracer = null;
|
|
13
|
+
export function captureRumError(error, source) {
|
|
14
|
+
if (errorTracer === null)
|
|
15
|
+
return;
|
|
16
|
+
const span = errorTracer.startSpan(ERROR_SPAN_NAME, {
|
|
17
|
+
attributes: { "error.type": sanitizeErrorType(error), "facilis.rum.source": source },
|
|
18
|
+
});
|
|
19
|
+
span.end();
|
|
20
|
+
}
|
|
21
|
+
export function wireWindowErrors(tracer) {
|
|
22
|
+
errorTracer = tracer;
|
|
23
|
+
window.addEventListener("error", (event) => {
|
|
24
|
+
captureRumError(event.error, "window.onerror");
|
|
25
|
+
});
|
|
26
|
+
window.addEventListener("unhandledrejection", (event) => {
|
|
27
|
+
captureRumError(event.reason, "unhandledrejection");
|
|
28
|
+
});
|
|
29
|
+
}
|
package/dist/exporter.js
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* OTLP/JSON export to the app's own ingestion route (D-203 §3). The browser carries only
|
|
3
|
+
* the public write-only tenant key; the collector credential stays server-side.
|
|
4
|
+
*/
|
|
5
|
+
import { context } from "@opentelemetry/api";
|
|
6
|
+
import { suppressTracing } from "@opentelemetry/core";
|
|
7
|
+
import { JsonTraceSerializer } from "@opentelemetry/otlp-transformer";
|
|
8
|
+
const EXPORT_TIMEOUT_MS = 3000;
|
|
9
|
+
export function createRumExporter(config) {
|
|
10
|
+
return {
|
|
11
|
+
export(spans, callback) {
|
|
12
|
+
try {
|
|
13
|
+
const body = JsonTraceSerializer.serializeRequest(spans);
|
|
14
|
+
if (body === undefined) {
|
|
15
|
+
callback({ code: 0 });
|
|
16
|
+
return;
|
|
17
|
+
}
|
|
18
|
+
const controller = new AbortController();
|
|
19
|
+
const timer = setTimeout(() => controller.abort(), EXPORT_TIMEOUT_MS);
|
|
20
|
+
const settle = () => {
|
|
21
|
+
clearTimeout(timer);
|
|
22
|
+
// Always report success: RUM must never break the app, and the server's span-id
|
|
23
|
+
// dedup rejects replays, so there are no retries (D-209).
|
|
24
|
+
callback({ code: 0 });
|
|
25
|
+
};
|
|
26
|
+
// suppressTracing: the export request must never be traced by the fetch
|
|
27
|
+
// instrumentation (it would feed itself). keepalive lets a page-unload export finish.
|
|
28
|
+
void context.with(suppressTracing(context.active()), () => {
|
|
29
|
+
void fetch(config.endpoint, {
|
|
30
|
+
method: "POST",
|
|
31
|
+
headers: {
|
|
32
|
+
"content-type": "application/json",
|
|
33
|
+
"x-facilis-telemetry-key": config.tenantKey,
|
|
34
|
+
},
|
|
35
|
+
// Copy into an ArrayBuffer-backed view: the serializer's Uint8Array is
|
|
36
|
+
// ArrayBufferLike-generic, which the DOM BodyInit type does not accept.
|
|
37
|
+
body: new Uint8Array(body),
|
|
38
|
+
keepalive: true,
|
|
39
|
+
signal: controller.signal,
|
|
40
|
+
}).then(settle, settle);
|
|
41
|
+
});
|
|
42
|
+
}
|
|
43
|
+
catch {
|
|
44
|
+
// export() must never throw into the SDK's flush path.
|
|
45
|
+
callback({ code: 0 });
|
|
46
|
+
}
|
|
47
|
+
},
|
|
48
|
+
shutdown() {
|
|
49
|
+
return Promise.resolve();
|
|
50
|
+
},
|
|
51
|
+
forceFlush() {
|
|
52
|
+
return Promise.resolve();
|
|
53
|
+
},
|
|
54
|
+
};
|
|
55
|
+
}
|
package/dist/index.d.ts
ADDED
package/dist/index.js
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Framework-owned browser RUM (issue #138, D-203 §2, D-209). bootRum() is called first in
|
|
3
|
+
* the framework template entry; it is a no-op unless the build injected a config literal
|
|
4
|
+
* (production + deploy telemetry options) and a window exists. Disabled/dev is completely
|
|
5
|
+
* silent: no zone patching, no provider, no instrumentation, no export (D-200).
|
|
6
|
+
*/
|
|
7
|
+
import { readRumConfig } from "./config.js";
|
|
8
|
+
export { readRumConfig } from "./config.js";
|
|
9
|
+
export { captureRumError, sanitizeErrorType } from "./errors.js";
|
|
10
|
+
let booted = false;
|
|
11
|
+
export function bootRum() {
|
|
12
|
+
// SSR/prerender has no window; a second call must not double-register the instrumentations.
|
|
13
|
+
if (booted || typeof window === "undefined")
|
|
14
|
+
return;
|
|
15
|
+
const config = readRumConfig();
|
|
16
|
+
if (config === null)
|
|
17
|
+
return;
|
|
18
|
+
booted = true;
|
|
19
|
+
void start(config);
|
|
20
|
+
}
|
|
21
|
+
async function start(config) {
|
|
22
|
+
try {
|
|
23
|
+
// zone.js loads only on an enabled boot: a disabled build never patches globals. The
|
|
24
|
+
// dynamic imports keep the whole SDK off the disabled path (and out of its chunk).
|
|
25
|
+
await import("zone.js");
|
|
26
|
+
const { createRumProvider } = await import("./provider.js");
|
|
27
|
+
const { registerRumInstrumentations } = await import("./instrumentations.js");
|
|
28
|
+
const { wireVitals } = await import("./vitals.js");
|
|
29
|
+
const { wireWindowErrors } = await import("./errors.js");
|
|
30
|
+
const provider = createRumProvider(config);
|
|
31
|
+
registerRumInstrumentations(config, window.location.origin, provider);
|
|
32
|
+
const tracer = provider.getTracer("@facilis.dev/rum");
|
|
33
|
+
wireVitals(tracer);
|
|
34
|
+
wireWindowErrors(tracer);
|
|
35
|
+
}
|
|
36
|
+
catch {
|
|
37
|
+
// RUM must never break the app: a failed boot stays silent.
|
|
38
|
+
}
|
|
39
|
+
}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import type { DocumentLoadInstrumentationConfig } from "@opentelemetry/instrumentation-document-load";
|
|
2
|
+
import type { FetchInstrumentationConfig } from "@opentelemetry/instrumentation-fetch";
|
|
3
|
+
import type { XMLHttpRequestInstrumentationConfig } from "@opentelemetry/instrumentation-xml-http-request";
|
|
4
|
+
import type { WebTracerProvider } from "@opentelemetry/sdk-trace-web";
|
|
5
|
+
import type { RumConfig } from "./config.js";
|
|
6
|
+
export interface RumInstrumentationConfigs {
|
|
7
|
+
readonly fetch: FetchInstrumentationConfig;
|
|
8
|
+
readonly xhr: XMLHttpRequestInstrumentationConfig;
|
|
9
|
+
readonly documentLoad: DocumentLoadInstrumentationConfig;
|
|
10
|
+
}
|
|
11
|
+
/** Pure factory: tests assert the origin restriction and export ignore without a browser. */
|
|
12
|
+
export declare function buildInstrumentations(config: RumConfig, origin: string): RumInstrumentationConfigs;
|
|
13
|
+
export declare function registerRumInstrumentations(config: RumConfig, origin: string, tracerProvider: WebTracerProvider): void;
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Fetch/XHR/document-load instrumentation (D-203 §2). traceparent propagates to the app's
|
|
3
|
+
* own origin only — never third parties — and the export endpoint itself is ignored so the
|
|
4
|
+
* RUM export is not instrumented (the exporter also runs under suppressTracing).
|
|
5
|
+
*/
|
|
6
|
+
import { registerInstrumentations } from "@opentelemetry/instrumentation";
|
|
7
|
+
import { DocumentLoadInstrumentation } from "@opentelemetry/instrumentation-document-load";
|
|
8
|
+
import { FetchInstrumentation } from "@opentelemetry/instrumentation-fetch";
|
|
9
|
+
import { XMLHttpRequestInstrumentation } from "@opentelemetry/instrumentation-xml-http-request";
|
|
10
|
+
function escapeRegExp(value) {
|
|
11
|
+
return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
12
|
+
}
|
|
13
|
+
/** Pure factory: tests assert the origin restriction and export ignore without a browser. */
|
|
14
|
+
export function buildInstrumentations(config, origin) {
|
|
15
|
+
// Anchored, escaped and boundary-checked: "https://app.example" must not match
|
|
16
|
+
// "https://app.example.evil.com" — a lookalike origin is a third party (D-203 §2).
|
|
17
|
+
const ownOrigin = new RegExp("^" + escapeRegExp(origin) + "(?=/|$)");
|
|
18
|
+
// Both the path and its absolute form: fetch resolves URLs before matching ignoreUrls.
|
|
19
|
+
const ignoreUrls = [
|
|
20
|
+
new RegExp(escapeRegExp(config.endpoint)),
|
|
21
|
+
new RegExp("^" + escapeRegExp(origin + config.endpoint)),
|
|
22
|
+
];
|
|
23
|
+
return {
|
|
24
|
+
fetch: { propagateTraceHeaderCorsUrls: [ownOrigin], ignoreUrls },
|
|
25
|
+
xhr: { propagateTraceHeaderCorsUrls: [ownOrigin], ignoreUrls },
|
|
26
|
+
documentLoad: {},
|
|
27
|
+
};
|
|
28
|
+
}
|
|
29
|
+
export function registerRumInstrumentations(config, origin, tracerProvider) {
|
|
30
|
+
const configs = buildInstrumentations(config, origin);
|
|
31
|
+
registerInstrumentations({
|
|
32
|
+
tracerProvider,
|
|
33
|
+
instrumentations: [
|
|
34
|
+
new FetchInstrumentation(configs.fetch),
|
|
35
|
+
new XMLHttpRequestInstrumentation(configs.xhr),
|
|
36
|
+
new DocumentLoadInstrumentation(configs.documentLoad),
|
|
37
|
+
],
|
|
38
|
+
});
|
|
39
|
+
}
|
package/dist/provider.js
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The web tracer provider on the spike-proven 2.x line (findings F1/F2/F3): the web SDK
|
|
3
|
+
* has no 3.x release, so this package keeps its own dependency surface away from the
|
|
4
|
+
* server's SDK 3.x / api 1.10.0 tree.
|
|
5
|
+
*/
|
|
6
|
+
import { ZoneContextManager } from "@opentelemetry/context-zone";
|
|
7
|
+
import { resourceFromAttributes } from "@opentelemetry/resources";
|
|
8
|
+
import { BatchSpanProcessor, ParentBasedSampler, TraceIdRatioBasedSampler, WebTracerProvider, } from "@opentelemetry/sdk-trace-web";
|
|
9
|
+
import { createRumExporter } from "./exporter.js";
|
|
10
|
+
import { ScrubProcessor } from "./scrub.js";
|
|
11
|
+
export function createRumProvider(config) {
|
|
12
|
+
const provider = new WebTracerProvider({
|
|
13
|
+
resource: resourceFromAttributes({
|
|
14
|
+
"service.name": config.serviceName,
|
|
15
|
+
// RUM only boots in production builds (D-209), so the environment is a constant.
|
|
16
|
+
"deployment.environment.name": "production",
|
|
17
|
+
...(config.deploymentId === null ? {} : { "deployment.id": config.deploymentId }),
|
|
18
|
+
}),
|
|
19
|
+
sampler: new ParentBasedSampler({ root: new TraceIdRatioBasedSampler(config.sampling) }),
|
|
20
|
+
spanProcessors: [
|
|
21
|
+
// Scrub first: the batch processor queues the same span object the scrub rewrote.
|
|
22
|
+
new ScrubProcessor(),
|
|
23
|
+
// 2.x constructor form (exporter, config) — the spike's proven shape. The options
|
|
24
|
+
// object is the 3.x API; on 2.x it would leave the exporter unset and silently drop
|
|
25
|
+
// every span (the failure spike F3 warns about, mirrored across the two lines).
|
|
26
|
+
new BatchSpanProcessor(createRumExporter(config), {
|
|
27
|
+
maxQueueSize: 256,
|
|
28
|
+
maxExportBatchSize: 64,
|
|
29
|
+
scheduledDelayMillis: 5000,
|
|
30
|
+
}),
|
|
31
|
+
],
|
|
32
|
+
});
|
|
33
|
+
// 2.x convenience registration (spike F2): 3.x removed register(); we are on the web 2.x
|
|
34
|
+
// line, and ZoneContextManager keeps the context across the fetch/XHR async boundaries.
|
|
35
|
+
provider.register({ contextManager: new ZoneContextManager() });
|
|
36
|
+
return provider;
|
|
37
|
+
}
|
package/dist/react.d.ts
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Report-only React error boundary (D-203 §2). The fallback is caller-provided: the
|
|
3
|
+
* framework ships no user-facing strings here (the app owns its UI and its t() keys).
|
|
4
|
+
* Without a fallback prop the boundary renders null and only reports.
|
|
5
|
+
*/
|
|
6
|
+
import { Component } from "react";
|
|
7
|
+
import type { ReactNode } from "react";
|
|
8
|
+
export interface RumErrorBoundaryProps {
|
|
9
|
+
readonly children?: ReactNode;
|
|
10
|
+
readonly fallback?: ReactNode;
|
|
11
|
+
}
|
|
12
|
+
interface RumErrorBoundaryState {
|
|
13
|
+
readonly hasError: boolean;
|
|
14
|
+
}
|
|
15
|
+
export declare class RumErrorBoundary extends Component<RumErrorBoundaryProps, RumErrorBoundaryState> {
|
|
16
|
+
state: RumErrorBoundaryState;
|
|
17
|
+
static getDerivedStateFromError(): RumErrorBoundaryState;
|
|
18
|
+
componentDidCatch(error: unknown): void;
|
|
19
|
+
render(): ReactNode;
|
|
20
|
+
}
|
|
21
|
+
export {};
|
package/dist/react.js
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Report-only React error boundary (D-203 §2). The fallback is caller-provided: the
|
|
3
|
+
* framework ships no user-facing strings here (the app owns its UI and its t() keys).
|
|
4
|
+
* Without a fallback prop the boundary renders null and only reports.
|
|
5
|
+
*/
|
|
6
|
+
import { Component } from "react";
|
|
7
|
+
import { captureRumError } from "./errors.js";
|
|
8
|
+
export class RumErrorBoundary extends Component {
|
|
9
|
+
state = { hasError: false };
|
|
10
|
+
static getDerivedStateFromError() {
|
|
11
|
+
return { hasError: true };
|
|
12
|
+
}
|
|
13
|
+
// React's errorInfo.componentStack is deliberately ignored: a PII carrier, never recorded.
|
|
14
|
+
componentDidCatch(error) {
|
|
15
|
+
captureRumError(error, "react-boundary");
|
|
16
|
+
}
|
|
17
|
+
render() {
|
|
18
|
+
return this.state.hasError ? (this.props.fallback ?? null) : this.props.children;
|
|
19
|
+
}
|
|
20
|
+
}
|
package/dist/scrub.d.ts
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Client-side value-free scrub (D-203 §2, D-209): defense in depth. The server allowlist
|
|
3
|
+
* (packages/nitro/src/runtime/telemetry/ingest/scrub.ts) is the final gate; this processor
|
|
4
|
+
* keeps the payload that leaves the browser already minimal, so no export path can carry
|
|
5
|
+
* what the client never sends.
|
|
6
|
+
*/
|
|
7
|
+
import type { Attributes } from "@opentelemetry/api";
|
|
8
|
+
import type { ReadableSpan, SpanProcessor } from "@opentelemetry/sdk-trace-web";
|
|
9
|
+
/** Replace UUID, numeric and email-shaped path segments with ":id" (the server's templating). */
|
|
10
|
+
export declare function templateSegments(path: string): string;
|
|
11
|
+
/** Keep only the pathname: query, fragment, scheme, host and userinfo never leave. */
|
|
12
|
+
export declare function scrubUrl(raw: string): string;
|
|
13
|
+
/** Allowlisted keys, scalars only, URL-bearing keys reduced to templated pathnames. */
|
|
14
|
+
export declare function scrubSpanAttributes(attributes: Attributes): Attributes;
|
|
15
|
+
/** Span names get the same query/fragment strip and id templating, capped like the server. */
|
|
16
|
+
export declare function scrubSpanName(name: string): string;
|
|
17
|
+
/**
|
|
18
|
+
* Scrubs each span before the batch processor queues it. The SDK hands onEnd the live Span
|
|
19
|
+
* object; ReadableSpan is its read-only view, so narrow to the mutable shape (no `any`)
|
|
20
|
+
* and rewrite in place — every exporter downstream then sees scrubbed data.
|
|
21
|
+
*/
|
|
22
|
+
export declare class ScrubProcessor implements SpanProcessor {
|
|
23
|
+
onStart(): void;
|
|
24
|
+
onEnd(span: ReadableSpan): void;
|
|
25
|
+
shutdown(): Promise<void>;
|
|
26
|
+
forceFlush(): Promise<void>;
|
|
27
|
+
}
|
package/dist/scrub.js
ADDED
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The server vocabulary names plus the RUM triple and the legacy keys the 0.217
|
|
3
|
+
* instrumentations emit (spike F6). The server maps the legacy method/status keys itself
|
|
4
|
+
* and drops the rest; keeping them here lets the client scrub URL-bearing legacy keys
|
|
5
|
+
* instead of passing raw URLs through.
|
|
6
|
+
*/
|
|
7
|
+
const ALLOWED = new Set([
|
|
8
|
+
"http.request.method",
|
|
9
|
+
"http.route",
|
|
10
|
+
"http.response.status_code",
|
|
11
|
+
"db.system.name",
|
|
12
|
+
"db.operation.name",
|
|
13
|
+
"db.collection.name",
|
|
14
|
+
"facilis.job.name",
|
|
15
|
+
"facilis.job.attempt",
|
|
16
|
+
"facilis.workflow.name",
|
|
17
|
+
"facilis.workflow.step",
|
|
18
|
+
"facilis.workflow.step.kind",
|
|
19
|
+
"browser.web_vital.name",
|
|
20
|
+
"browser.web_vital.value",
|
|
21
|
+
"browser.web_vital.rating",
|
|
22
|
+
"error.type",
|
|
23
|
+
"facilis.rum.source",
|
|
24
|
+
"http.method",
|
|
25
|
+
"http.status_code",
|
|
26
|
+
"http.url",
|
|
27
|
+
"http.target",
|
|
28
|
+
"http.scheme",
|
|
29
|
+
"http.host",
|
|
30
|
+
"net.peer.name",
|
|
31
|
+
"net.peer.port",
|
|
32
|
+
]);
|
|
33
|
+
/** Keys whose value is a URL: only the templated pathname may survive. */
|
|
34
|
+
const URL_BEARING = new Set([
|
|
35
|
+
"http.url",
|
|
36
|
+
"http.target",
|
|
37
|
+
"url.full",
|
|
38
|
+
"url.path",
|
|
39
|
+
"http.route",
|
|
40
|
+
]);
|
|
41
|
+
// Mirrors the server's sanitizeSpanName patterns (ingest/scrub.ts): concrete ids collapse
|
|
42
|
+
// to ":id" so span names and paths stay low-cardinality route templates.
|
|
43
|
+
const UUID = /\/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}(?=\/|$)/gi;
|
|
44
|
+
const NUMERIC_SEGMENT = /\/\d+(?=\/|$)/g;
|
|
45
|
+
// An email-shaped segment is an identifier, not a route (mirrors the server's pattern).
|
|
46
|
+
const EMAIL_SEGMENT = /\/[^/?#\s]*@[^/?#\s]*(?=\/|$)/g;
|
|
47
|
+
const MAX_SPAN_NAME = 120;
|
|
48
|
+
const MAX_ATTRIBUTE_STRING = 128;
|
|
49
|
+
/** Replace UUID, numeric and email-shaped path segments with ":id" (the server's templating). */
|
|
50
|
+
export function templateSegments(path) {
|
|
51
|
+
return path.replace(UUID, "/:id").replace(NUMERIC_SEGMENT, "/:id").replace(EMAIL_SEGMENT, "/:id");
|
|
52
|
+
}
|
|
53
|
+
/** Keep only the pathname: query, fragment, scheme, host and userinfo never leave. */
|
|
54
|
+
export function scrubUrl(raw) {
|
|
55
|
+
const withoutQuery = raw.split(/[?#]/)[0] ?? "";
|
|
56
|
+
let pathname = withoutQuery;
|
|
57
|
+
try {
|
|
58
|
+
// A dummy base parses relative targets too; only the pathname is kept.
|
|
59
|
+
pathname = new URL(withoutQuery, "http://rum.invalid").pathname;
|
|
60
|
+
}
|
|
61
|
+
catch {
|
|
62
|
+
// Not a URL: keep the query-free string; id templating below still applies.
|
|
63
|
+
}
|
|
64
|
+
return templateSegments(pathname).slice(0, MAX_ATTRIBUTE_STRING);
|
|
65
|
+
}
|
|
66
|
+
/** Allowlisted keys, scalars only, URL-bearing keys reduced to templated pathnames. */
|
|
67
|
+
export function scrubSpanAttributes(attributes) {
|
|
68
|
+
const kept = {};
|
|
69
|
+
for (const [key, value] of Object.entries(attributes)) {
|
|
70
|
+
if (!ALLOWED.has(key))
|
|
71
|
+
continue;
|
|
72
|
+
if (URL_BEARING.has(key)) {
|
|
73
|
+
if (typeof value === "string")
|
|
74
|
+
kept[key] = scrubUrl(value);
|
|
75
|
+
continue;
|
|
76
|
+
}
|
|
77
|
+
// An allowed key must not smuggle a structure (mirrors the server's scalar filter).
|
|
78
|
+
// Non-finite numbers are dropped: they serialize to JSON null and are never a metric.
|
|
79
|
+
if (typeof value === "string")
|
|
80
|
+
kept[key] = value.slice(0, MAX_ATTRIBUTE_STRING);
|
|
81
|
+
else if (typeof value === "number" && Number.isFinite(value))
|
|
82
|
+
kept[key] = value;
|
|
83
|
+
else if (typeof value === "boolean")
|
|
84
|
+
kept[key] = value;
|
|
85
|
+
}
|
|
86
|
+
return kept;
|
|
87
|
+
}
|
|
88
|
+
/** Absolute http(s) URLs must not leak scheme/host into span names (mirrors the server). */
|
|
89
|
+
function pathnameOf(raw) {
|
|
90
|
+
try {
|
|
91
|
+
const url = new URL(raw);
|
|
92
|
+
if (url.protocol === "http:" || url.protocol === "https:")
|
|
93
|
+
return url.pathname;
|
|
94
|
+
}
|
|
95
|
+
catch {
|
|
96
|
+
// Not an absolute URL: a route template or a fixed span name, kept as-is.
|
|
97
|
+
}
|
|
98
|
+
return raw;
|
|
99
|
+
}
|
|
100
|
+
/** Span names get the same query/fragment strip and id templating, capped like the server. */
|
|
101
|
+
export function scrubSpanName(name) {
|
|
102
|
+
const withoutQuery = pathnameOf(name).split(/[?#]/)[0] ?? "";
|
|
103
|
+
return templateSegments(withoutQuery).slice(0, MAX_SPAN_NAME);
|
|
104
|
+
}
|
|
105
|
+
/**
|
|
106
|
+
* Scrubs each span before the batch processor queues it. The SDK hands onEnd the live Span
|
|
107
|
+
* object; ReadableSpan is its read-only view, so narrow to the mutable shape (no `any`)
|
|
108
|
+
* and rewrite in place — every exporter downstream then sees scrubbed data.
|
|
109
|
+
*/
|
|
110
|
+
export class ScrubProcessor {
|
|
111
|
+
onStart() { }
|
|
112
|
+
onEnd(span) {
|
|
113
|
+
const mutable = span;
|
|
114
|
+
mutable.name = scrubSpanName(span.name);
|
|
115
|
+
mutable.attributes = scrubSpanAttributes(span.attributes);
|
|
116
|
+
}
|
|
117
|
+
shutdown() {
|
|
118
|
+
return Promise.resolve();
|
|
119
|
+
}
|
|
120
|
+
forceFlush() {
|
|
121
|
+
return Promise.resolve();
|
|
122
|
+
}
|
|
123
|
+
}
|
package/dist/vitals.d.ts
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Core Web Vitals as spans (D-203 §2, D-209). The browser.web_vital semantic convention is
|
|
3
|
+
* still Development status: this pins its name/value/rating triple and adapts it to spans,
|
|
4
|
+
* because the ingestion class accepts spans only (there is no metric surface). The
|
|
5
|
+
* standard web-vitals build is used, never attribution: attribution entries carry element
|
|
6
|
+
* selectors and other PII.
|
|
7
|
+
*/
|
|
8
|
+
import type { Attributes, Tracer } from "@opentelemetry/api";
|
|
9
|
+
import type { Metric } from "web-vitals";
|
|
10
|
+
export declare const WEB_VITAL_SPAN_NAME = "browser.web_vital";
|
|
11
|
+
/** Pure mapping for tests: the pinned semconv triple, nothing else. */
|
|
12
|
+
export declare function mapVital(metric: Metric): Attributes;
|
|
13
|
+
export declare function wireVitals(tracer: Tracer): void;
|
package/dist/vitals.js
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import { onCLS, onFCP, onINP, onLCP, onTTFB } from "web-vitals";
|
|
2
|
+
export const WEB_VITAL_SPAN_NAME = "browser.web_vital";
|
|
3
|
+
/** Pure mapping for tests: the pinned semconv triple, nothing else. */
|
|
4
|
+
export function mapVital(metric) {
|
|
5
|
+
return {
|
|
6
|
+
"browser.web_vital.name": metric.name,
|
|
7
|
+
"browser.web_vital.value": metric.value,
|
|
8
|
+
"browser.web_vital.rating": metric.rating,
|
|
9
|
+
};
|
|
10
|
+
}
|
|
11
|
+
export function wireVitals(tracer) {
|
|
12
|
+
const report = (metric) => {
|
|
13
|
+
// One span per metric report, ended immediately so the batch processor picks it up.
|
|
14
|
+
const span = tracer.startSpan(WEB_VITAL_SPAN_NAME, { attributes: mapVital(metric) });
|
|
15
|
+
span.end();
|
|
16
|
+
};
|
|
17
|
+
onLCP(report);
|
|
18
|
+
onINP(report);
|
|
19
|
+
onCLS(report);
|
|
20
|
+
onFCP(report);
|
|
21
|
+
onTTFB(report);
|
|
22
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,67 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@facilis.dev/rum",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"description": "
|
|
6
|
-
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"type": "module",
|
|
5
|
+
"description": "Facilis framework-owned browser RUM: web vitals, errors and document/fetch spans exported as OTLP/JSON to the app's own ingestion route (D-203/D-209).",
|
|
6
|
+
"license": "MIT",
|
|
7
|
+
"exports": {
|
|
8
|
+
".": "./dist/index.js",
|
|
9
|
+
"./react": "./dist/react.js",
|
|
10
|
+
"./config": "./dist/config.js",
|
|
11
|
+
"./instrumentations": "./dist/instrumentations.js",
|
|
12
|
+
"./scrub": "./dist/scrub.js",
|
|
13
|
+
"./package.json": "./package.json"
|
|
14
|
+
},
|
|
15
|
+
"files": [
|
|
16
|
+
"dist",
|
|
17
|
+
"src",
|
|
18
|
+
"README.md",
|
|
19
|
+
"LICENSE"
|
|
20
|
+
],
|
|
21
|
+
"engines": {
|
|
22
|
+
"node": ">=22.15.0"
|
|
23
|
+
},
|
|
24
|
+
"dependencies": {
|
|
25
|
+
"@opentelemetry/api": "1.9.0",
|
|
26
|
+
"@opentelemetry/context-zone": "2.12.1",
|
|
27
|
+
"@opentelemetry/core": "2.12.1",
|
|
28
|
+
"@opentelemetry/instrumentation": "0.217.0",
|
|
29
|
+
"@opentelemetry/instrumentation-document-load": "0.62.0",
|
|
30
|
+
"@opentelemetry/instrumentation-fetch": "0.217.0",
|
|
31
|
+
"@opentelemetry/instrumentation-xml-http-request": "0.217.0",
|
|
32
|
+
"@opentelemetry/otlp-transformer": "0.217.0",
|
|
33
|
+
"@opentelemetry/resources": "2.12.1",
|
|
34
|
+
"@opentelemetry/sdk-trace-web": "2.12.1",
|
|
35
|
+
"web-vitals": "5.3.0",
|
|
36
|
+
"zone.js": "0.16.3"
|
|
37
|
+
},
|
|
38
|
+
"peerDependencies": {
|
|
39
|
+
"react": "^18.0.0 || ^19.0.0"
|
|
40
|
+
},
|
|
41
|
+
"peerDependenciesMeta": {
|
|
42
|
+
"react": {
|
|
43
|
+
"optional": true
|
|
44
|
+
}
|
|
45
|
+
},
|
|
46
|
+
"publishConfig": {
|
|
47
|
+
"access": "public"
|
|
48
|
+
},
|
|
49
|
+
"repository": {
|
|
50
|
+
"type": "git",
|
|
51
|
+
"url": "git+https://github.com/facilis-dev/facilis.git",
|
|
52
|
+
"directory": "packages/rum"
|
|
53
|
+
},
|
|
54
|
+
"homepage": "https://github.com/facilis-dev/facilis/tree/main/packages/rum#readme",
|
|
55
|
+
"bugs": {
|
|
56
|
+
"url": "https://github.com/facilis-dev/facilis/issues"
|
|
57
|
+
},
|
|
58
|
+
"keywords": [
|
|
59
|
+
"facilis",
|
|
60
|
+
"framework",
|
|
61
|
+
"vite",
|
|
62
|
+
"nitro",
|
|
63
|
+
"low-code"
|
|
64
|
+
],
|
|
65
|
+
"main": "./dist/index.js",
|
|
66
|
+
"types": "./dist/index.d.ts"
|
|
67
|
+
}
|
package/src/config.ts
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Build-time RUM configuration (D-209). The literal is injected by the facilisRum() Vite
|
|
3
|
+
* companion at `vite build` time only; dev builds define it as null, so the client is
|
|
4
|
+
* completely silent there (D-200). Nothing reads env at runtime: a browser has none.
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
export interface RumConfig {
|
|
8
|
+
readonly tenantKey: string;
|
|
9
|
+
readonly endpoint: string;
|
|
10
|
+
readonly sampling: number;
|
|
11
|
+
readonly serviceName: string;
|
|
12
|
+
readonly deploymentId: string | null;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
declare global {
|
|
16
|
+
const __FACILIS_RUM_CONFIG__: RumConfig | null | undefined;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/** Read the injected literal; anything missing or malformed is null (a no-op boot). */
|
|
20
|
+
export function readRumConfig(): RumConfig | null {
|
|
21
|
+
// typeof guard: an unbundled import (tests, SSR/prerender) has no define at all.
|
|
22
|
+
if (typeof __FACILIS_RUM_CONFIG__ === "undefined" || __FACILIS_RUM_CONFIG__ === null) return null;
|
|
23
|
+
const raw: unknown = __FACILIS_RUM_CONFIG__;
|
|
24
|
+
if (typeof raw !== "object") return null;
|
|
25
|
+
const record = raw as Record<string, unknown>;
|
|
26
|
+
const tenantKey = record["tenantKey"];
|
|
27
|
+
const endpoint = record["endpoint"];
|
|
28
|
+
const serviceName = record["serviceName"];
|
|
29
|
+
// Fail-closed like the ingestion gates: a key with whitespace could never survive header
|
|
30
|
+
// handling, and an export without a target or a service identity is pointless.
|
|
31
|
+
if (typeof tenantKey !== "string" || tenantKey === "" || /\s/.test(tenantKey)) return null;
|
|
32
|
+
if (typeof endpoint !== "string" || endpoint === "") return null;
|
|
33
|
+
if (typeof serviceName !== "string" || serviceName === "") return null;
|
|
34
|
+
const deploymentId = typeof record["deploymentId"] === "string" ? record["deploymentId"] : null;
|
|
35
|
+
return {
|
|
36
|
+
tenantKey,
|
|
37
|
+
endpoint,
|
|
38
|
+
sampling: readSampling(record["sampling"]),
|
|
39
|
+
serviceName,
|
|
40
|
+
deploymentId,
|
|
41
|
+
};
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** Mirrors the backend's readSampling: an invalid ratio keeps everything, never nothing. */
|
|
45
|
+
function readSampling(value: unknown): number {
|
|
46
|
+
return typeof value === "number" && Number.isFinite(value) && value >= 0 && value <= 1
|
|
47
|
+
? value
|
|
48
|
+
: 1;
|
|
49
|
+
}
|
package/src/errors.ts
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Window-level error capture (D-203 §2): type + source only. Message, stack, filename and
|
|
3
|
+
* reason values are PII carriers and are never recorded — the server allowlist would drop
|
|
4
|
+
* them anyway; the client never sends them.
|
|
5
|
+
*/
|
|
6
|
+
import type { Tracer } from "@opentelemetry/api";
|
|
7
|
+
|
|
8
|
+
export type RumErrorSource = "window.onerror" | "unhandledrejection" | "react-boundary";
|
|
9
|
+
|
|
10
|
+
export const ERROR_SPAN_NAME = "browser.error";
|
|
11
|
+
|
|
12
|
+
// Constructor names are low-cardinality identifiers; anything else collapses to a constant.
|
|
13
|
+
const ERROR_TYPE_PATTERN = /^[A-Za-z][A-Za-z0-9]{0,63}$/;
|
|
14
|
+
|
|
15
|
+
/** Sanitized constructor name for Error values; every non-Error reason is "NonError". */
|
|
16
|
+
export function sanitizeErrorType(error: unknown): string {
|
|
17
|
+
if (!(error instanceof Error)) return "NonError";
|
|
18
|
+
const name = error.constructor.name;
|
|
19
|
+
return ERROR_TYPE_PATTERN.test(name) ? name : "Error";
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
// Null until an enabled boot wires a tracer: disabled/dev builds never emit (D-200).
|
|
23
|
+
let errorTracer: Tracer | null = null;
|
|
24
|
+
|
|
25
|
+
export function captureRumError(error: unknown, source: RumErrorSource): void {
|
|
26
|
+
if (errorTracer === null) return;
|
|
27
|
+
const span = errorTracer.startSpan(ERROR_SPAN_NAME, {
|
|
28
|
+
attributes: { "error.type": sanitizeErrorType(error), "facilis.rum.source": source },
|
|
29
|
+
});
|
|
30
|
+
span.end();
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export function wireWindowErrors(tracer: Tracer): void {
|
|
34
|
+
errorTracer = tracer;
|
|
35
|
+
window.addEventListener("error", (event: Event) => {
|
|
36
|
+
captureRumError((event as ErrorEvent).error, "window.onerror");
|
|
37
|
+
});
|
|
38
|
+
window.addEventListener("unhandledrejection", (event: Event) => {
|
|
39
|
+
captureRumError((event as PromiseRejectionEvent).reason, "unhandledrejection");
|
|
40
|
+
});
|
|
41
|
+
}
|
package/src/exporter.ts
ADDED
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* OTLP/JSON export to the app's own ingestion route (D-203 §3). The browser carries only
|
|
3
|
+
* the public write-only tenant key; the collector credential stays server-side.
|
|
4
|
+
*/
|
|
5
|
+
import { context } from "@opentelemetry/api";
|
|
6
|
+
import { suppressTracing } from "@opentelemetry/core";
|
|
7
|
+
import { JsonTraceSerializer } from "@opentelemetry/otlp-transformer";
|
|
8
|
+
import type { SpanExporter } from "@opentelemetry/sdk-trace-web";
|
|
9
|
+
import type { RumConfig } from "./config.ts";
|
|
10
|
+
|
|
11
|
+
const EXPORT_TIMEOUT_MS = 3000;
|
|
12
|
+
|
|
13
|
+
export function createRumExporter(config: RumConfig): SpanExporter {
|
|
14
|
+
return {
|
|
15
|
+
export(spans, callback): void {
|
|
16
|
+
try {
|
|
17
|
+
const body = JsonTraceSerializer.serializeRequest(spans);
|
|
18
|
+
if (body === undefined) {
|
|
19
|
+
callback({ code: 0 });
|
|
20
|
+
return;
|
|
21
|
+
}
|
|
22
|
+
const controller = new AbortController();
|
|
23
|
+
const timer = setTimeout(() => controller.abort(), EXPORT_TIMEOUT_MS);
|
|
24
|
+
const settle = (): void => {
|
|
25
|
+
clearTimeout(timer);
|
|
26
|
+
// Always report success: RUM must never break the app, and the server's span-id
|
|
27
|
+
// dedup rejects replays, so there are no retries (D-209).
|
|
28
|
+
callback({ code: 0 });
|
|
29
|
+
};
|
|
30
|
+
// suppressTracing: the export request must never be traced by the fetch
|
|
31
|
+
// instrumentation (it would feed itself). keepalive lets a page-unload export finish.
|
|
32
|
+
void context.with(suppressTracing(context.active()), () => {
|
|
33
|
+
void fetch(config.endpoint, {
|
|
34
|
+
method: "POST",
|
|
35
|
+
headers: {
|
|
36
|
+
"content-type": "application/json",
|
|
37
|
+
"x-facilis-telemetry-key": config.tenantKey,
|
|
38
|
+
},
|
|
39
|
+
// Copy into an ArrayBuffer-backed view: the serializer's Uint8Array is
|
|
40
|
+
// ArrayBufferLike-generic, which the DOM BodyInit type does not accept.
|
|
41
|
+
body: new Uint8Array(body),
|
|
42
|
+
keepalive: true,
|
|
43
|
+
signal: controller.signal,
|
|
44
|
+
}).then(settle, settle);
|
|
45
|
+
});
|
|
46
|
+
} catch {
|
|
47
|
+
// export() must never throw into the SDK's flush path.
|
|
48
|
+
callback({ code: 0 });
|
|
49
|
+
}
|
|
50
|
+
},
|
|
51
|
+
shutdown(): Promise<void> {
|
|
52
|
+
return Promise.resolve();
|
|
53
|
+
},
|
|
54
|
+
forceFlush(): Promise<void> {
|
|
55
|
+
return Promise.resolve();
|
|
56
|
+
},
|
|
57
|
+
};
|
|
58
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Framework-owned browser RUM (issue #138, D-203 §2, D-209). bootRum() is called first in
|
|
3
|
+
* the framework template entry; it is a no-op unless the build injected a config literal
|
|
4
|
+
* (production + deploy telemetry options) and a window exists. Disabled/dev is completely
|
|
5
|
+
* silent: no zone patching, no provider, no instrumentation, no export (D-200).
|
|
6
|
+
*/
|
|
7
|
+
import { readRumConfig } from "./config.ts";
|
|
8
|
+
import type { RumConfig } from "./config.ts";
|
|
9
|
+
|
|
10
|
+
export { readRumConfig } from "./config.ts";
|
|
11
|
+
export type { RumConfig } from "./config.ts";
|
|
12
|
+
export { captureRumError, sanitizeErrorType } from "./errors.ts";
|
|
13
|
+
export type { RumErrorSource } from "./errors.ts";
|
|
14
|
+
|
|
15
|
+
let booted = false;
|
|
16
|
+
|
|
17
|
+
export function bootRum(): void {
|
|
18
|
+
// SSR/prerender has no window; a second call must not double-register the instrumentations.
|
|
19
|
+
if (booted || typeof window === "undefined") return;
|
|
20
|
+
const config = readRumConfig();
|
|
21
|
+
if (config === null) return;
|
|
22
|
+
booted = true;
|
|
23
|
+
void start(config);
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
async function start(config: RumConfig): Promise<void> {
|
|
27
|
+
try {
|
|
28
|
+
// zone.js loads only on an enabled boot: a disabled build never patches globals. The
|
|
29
|
+
// dynamic imports keep the whole SDK off the disabled path (and out of its chunk).
|
|
30
|
+
await import("zone.js");
|
|
31
|
+
const { createRumProvider } = await import("./provider.ts");
|
|
32
|
+
const { registerRumInstrumentations } = await import("./instrumentations.ts");
|
|
33
|
+
const { wireVitals } = await import("./vitals.ts");
|
|
34
|
+
const { wireWindowErrors } = await import("./errors.ts");
|
|
35
|
+
const provider = createRumProvider(config);
|
|
36
|
+
registerRumInstrumentations(config, window.location.origin, provider);
|
|
37
|
+
const tracer = provider.getTracer("@facilis.dev/rum");
|
|
38
|
+
wireVitals(tracer);
|
|
39
|
+
wireWindowErrors(tracer);
|
|
40
|
+
} catch {
|
|
41
|
+
// RUM must never break the app: a failed boot stays silent.
|
|
42
|
+
}
|
|
43
|
+
}
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Fetch/XHR/document-load instrumentation (D-203 §2). traceparent propagates to the app's
|
|
3
|
+
* own origin only — never third parties — and the export endpoint itself is ignored so the
|
|
4
|
+
* RUM export is not instrumented (the exporter also runs under suppressTracing).
|
|
5
|
+
*/
|
|
6
|
+
import { registerInstrumentations } from "@opentelemetry/instrumentation";
|
|
7
|
+
import { DocumentLoadInstrumentation } from "@opentelemetry/instrumentation-document-load";
|
|
8
|
+
import type { DocumentLoadInstrumentationConfig } from "@opentelemetry/instrumentation-document-load";
|
|
9
|
+
import { FetchInstrumentation } from "@opentelemetry/instrumentation-fetch";
|
|
10
|
+
import type { FetchInstrumentationConfig } from "@opentelemetry/instrumentation-fetch";
|
|
11
|
+
import { XMLHttpRequestInstrumentation } from "@opentelemetry/instrumentation-xml-http-request";
|
|
12
|
+
import type { XMLHttpRequestInstrumentationConfig } from "@opentelemetry/instrumentation-xml-http-request";
|
|
13
|
+
import type { WebTracerProvider } from "@opentelemetry/sdk-trace-web";
|
|
14
|
+
import type { RumConfig } from "./config.ts";
|
|
15
|
+
|
|
16
|
+
export interface RumInstrumentationConfigs {
|
|
17
|
+
readonly fetch: FetchInstrumentationConfig;
|
|
18
|
+
readonly xhr: XMLHttpRequestInstrumentationConfig;
|
|
19
|
+
readonly documentLoad: DocumentLoadInstrumentationConfig;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
function escapeRegExp(value: string): string {
|
|
23
|
+
return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/** Pure factory: tests assert the origin restriction and export ignore without a browser. */
|
|
27
|
+
export function buildInstrumentations(
|
|
28
|
+
config: RumConfig,
|
|
29
|
+
origin: string,
|
|
30
|
+
): RumInstrumentationConfigs {
|
|
31
|
+
// Anchored, escaped and boundary-checked: "https://app.example" must not match
|
|
32
|
+
// "https://app.example.evil.com" — a lookalike origin is a third party (D-203 §2).
|
|
33
|
+
const ownOrigin = new RegExp("^" + escapeRegExp(origin) + "(?=/|$)");
|
|
34
|
+
// Both the path and its absolute form: fetch resolves URLs before matching ignoreUrls.
|
|
35
|
+
const ignoreUrls = [
|
|
36
|
+
new RegExp(escapeRegExp(config.endpoint)),
|
|
37
|
+
new RegExp("^" + escapeRegExp(origin + config.endpoint)),
|
|
38
|
+
];
|
|
39
|
+
return {
|
|
40
|
+
fetch: { propagateTraceHeaderCorsUrls: [ownOrigin], ignoreUrls },
|
|
41
|
+
xhr: { propagateTraceHeaderCorsUrls: [ownOrigin], ignoreUrls },
|
|
42
|
+
documentLoad: {},
|
|
43
|
+
};
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
export function registerRumInstrumentations(
|
|
47
|
+
config: RumConfig,
|
|
48
|
+
origin: string,
|
|
49
|
+
tracerProvider: WebTracerProvider,
|
|
50
|
+
): void {
|
|
51
|
+
const configs = buildInstrumentations(config, origin);
|
|
52
|
+
registerInstrumentations({
|
|
53
|
+
tracerProvider,
|
|
54
|
+
instrumentations: [
|
|
55
|
+
new FetchInstrumentation(configs.fetch),
|
|
56
|
+
new XMLHttpRequestInstrumentation(configs.xhr),
|
|
57
|
+
new DocumentLoadInstrumentation(configs.documentLoad),
|
|
58
|
+
],
|
|
59
|
+
});
|
|
60
|
+
}
|
package/src/provider.ts
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The web tracer provider on the spike-proven 2.x line (findings F1/F2/F3): the web SDK
|
|
3
|
+
* has no 3.x release, so this package keeps its own dependency surface away from the
|
|
4
|
+
* server's SDK 3.x / api 1.10.0 tree.
|
|
5
|
+
*/
|
|
6
|
+
import { ZoneContextManager } from "@opentelemetry/context-zone";
|
|
7
|
+
import { resourceFromAttributes } from "@opentelemetry/resources";
|
|
8
|
+
import {
|
|
9
|
+
BatchSpanProcessor,
|
|
10
|
+
ParentBasedSampler,
|
|
11
|
+
TraceIdRatioBasedSampler,
|
|
12
|
+
WebTracerProvider,
|
|
13
|
+
} from "@opentelemetry/sdk-trace-web";
|
|
14
|
+
import type { RumConfig } from "./config.ts";
|
|
15
|
+
import { createRumExporter } from "./exporter.ts";
|
|
16
|
+
import { ScrubProcessor } from "./scrub.ts";
|
|
17
|
+
|
|
18
|
+
export function createRumProvider(config: RumConfig): WebTracerProvider {
|
|
19
|
+
const provider = new WebTracerProvider({
|
|
20
|
+
resource: resourceFromAttributes({
|
|
21
|
+
"service.name": config.serviceName,
|
|
22
|
+
// RUM only boots in production builds (D-209), so the environment is a constant.
|
|
23
|
+
"deployment.environment.name": "production",
|
|
24
|
+
...(config.deploymentId === null ? {} : { "deployment.id": config.deploymentId }),
|
|
25
|
+
}),
|
|
26
|
+
sampler: new ParentBasedSampler({ root: new TraceIdRatioBasedSampler(config.sampling) }),
|
|
27
|
+
spanProcessors: [
|
|
28
|
+
// Scrub first: the batch processor queues the same span object the scrub rewrote.
|
|
29
|
+
new ScrubProcessor(),
|
|
30
|
+
// 2.x constructor form (exporter, config) — the spike's proven shape. The options
|
|
31
|
+
// object is the 3.x API; on 2.x it would leave the exporter unset and silently drop
|
|
32
|
+
// every span (the failure spike F3 warns about, mirrored across the two lines).
|
|
33
|
+
new BatchSpanProcessor(createRumExporter(config), {
|
|
34
|
+
maxQueueSize: 256,
|
|
35
|
+
maxExportBatchSize: 64,
|
|
36
|
+
scheduledDelayMillis: 5000,
|
|
37
|
+
}),
|
|
38
|
+
],
|
|
39
|
+
});
|
|
40
|
+
// 2.x convenience registration (spike F2): 3.x removed register(); we are on the web 2.x
|
|
41
|
+
// line, and ZoneContextManager keeps the context across the fetch/XHR async boundaries.
|
|
42
|
+
provider.register({ contextManager: new ZoneContextManager() });
|
|
43
|
+
return provider;
|
|
44
|
+
}
|
package/src/react.tsx
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Report-only React error boundary (D-203 §2). The fallback is caller-provided: the
|
|
3
|
+
* framework ships no user-facing strings here (the app owns its UI and its t() keys).
|
|
4
|
+
* Without a fallback prop the boundary renders null and only reports.
|
|
5
|
+
*/
|
|
6
|
+
import { Component } from "react";
|
|
7
|
+
import type { ReactNode } from "react";
|
|
8
|
+
import { captureRumError } from "./errors.ts";
|
|
9
|
+
|
|
10
|
+
export interface RumErrorBoundaryProps {
|
|
11
|
+
readonly children?: ReactNode;
|
|
12
|
+
readonly fallback?: ReactNode;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
interface RumErrorBoundaryState {
|
|
16
|
+
readonly hasError: boolean;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export class RumErrorBoundary extends Component<RumErrorBoundaryProps, RumErrorBoundaryState> {
|
|
20
|
+
override state: RumErrorBoundaryState = { hasError: false };
|
|
21
|
+
|
|
22
|
+
static getDerivedStateFromError(): RumErrorBoundaryState {
|
|
23
|
+
return { hasError: true };
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
// React's errorInfo.componentStack is deliberately ignored: a PII carrier, never recorded.
|
|
27
|
+
override componentDidCatch(error: unknown): void {
|
|
28
|
+
captureRumError(error, "react-boundary");
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
override render(): ReactNode {
|
|
32
|
+
return this.state.hasError ? (this.props.fallback ?? null) : this.props.children;
|
|
33
|
+
}
|
|
34
|
+
}
|
package/src/scrub.ts
ADDED
|
@@ -0,0 +1,135 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Client-side value-free scrub (D-203 §2, D-209): defense in depth. The server allowlist
|
|
3
|
+
* (packages/nitro/src/runtime/telemetry/ingest/scrub.ts) is the final gate; this processor
|
|
4
|
+
* keeps the payload that leaves the browser already minimal, so no export path can carry
|
|
5
|
+
* what the client never sends.
|
|
6
|
+
*/
|
|
7
|
+
import type { Attributes } from "@opentelemetry/api";
|
|
8
|
+
import type { ReadableSpan, SpanProcessor } from "@opentelemetry/sdk-trace-web";
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* The server vocabulary names plus the RUM triple and the legacy keys the 0.217
|
|
12
|
+
* instrumentations emit (spike F6). The server maps the legacy method/status keys itself
|
|
13
|
+
* and drops the rest; keeping them here lets the client scrub URL-bearing legacy keys
|
|
14
|
+
* instead of passing raw URLs through.
|
|
15
|
+
*/
|
|
16
|
+
const ALLOWED: ReadonlySet<string> = new Set([
|
|
17
|
+
"http.request.method",
|
|
18
|
+
"http.route",
|
|
19
|
+
"http.response.status_code",
|
|
20
|
+
"db.system.name",
|
|
21
|
+
"db.operation.name",
|
|
22
|
+
"db.collection.name",
|
|
23
|
+
"facilis.job.name",
|
|
24
|
+
"facilis.job.attempt",
|
|
25
|
+
"facilis.workflow.name",
|
|
26
|
+
"facilis.workflow.step",
|
|
27
|
+
"facilis.workflow.step.kind",
|
|
28
|
+
"browser.web_vital.name",
|
|
29
|
+
"browser.web_vital.value",
|
|
30
|
+
"browser.web_vital.rating",
|
|
31
|
+
"error.type",
|
|
32
|
+
"facilis.rum.source",
|
|
33
|
+
"http.method",
|
|
34
|
+
"http.status_code",
|
|
35
|
+
"http.url",
|
|
36
|
+
"http.target",
|
|
37
|
+
"http.scheme",
|
|
38
|
+
"http.host",
|
|
39
|
+
"net.peer.name",
|
|
40
|
+
"net.peer.port",
|
|
41
|
+
]);
|
|
42
|
+
|
|
43
|
+
/** Keys whose value is a URL: only the templated pathname may survive. */
|
|
44
|
+
const URL_BEARING: ReadonlySet<string> = new Set([
|
|
45
|
+
"http.url",
|
|
46
|
+
"http.target",
|
|
47
|
+
"url.full",
|
|
48
|
+
"url.path",
|
|
49
|
+
"http.route",
|
|
50
|
+
]);
|
|
51
|
+
|
|
52
|
+
// Mirrors the server's sanitizeSpanName patterns (ingest/scrub.ts): concrete ids collapse
|
|
53
|
+
// to ":id" so span names and paths stay low-cardinality route templates.
|
|
54
|
+
const UUID = /\/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}(?=\/|$)/gi;
|
|
55
|
+
const NUMERIC_SEGMENT = /\/\d+(?=\/|$)/g;
|
|
56
|
+
// An email-shaped segment is an identifier, not a route (mirrors the server's pattern).
|
|
57
|
+
const EMAIL_SEGMENT = /\/[^/?#\s]*@[^/?#\s]*(?=\/|$)/g;
|
|
58
|
+
const MAX_SPAN_NAME = 120;
|
|
59
|
+
const MAX_ATTRIBUTE_STRING = 128;
|
|
60
|
+
|
|
61
|
+
/** Replace UUID, numeric and email-shaped path segments with ":id" (the server's templating). */
|
|
62
|
+
export function templateSegments(path: string): string {
|
|
63
|
+
return path.replace(UUID, "/:id").replace(NUMERIC_SEGMENT, "/:id").replace(EMAIL_SEGMENT, "/:id");
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/** Keep only the pathname: query, fragment, scheme, host and userinfo never leave. */
|
|
67
|
+
export function scrubUrl(raw: string): string {
|
|
68
|
+
const withoutQuery = raw.split(/[?#]/)[0] ?? "";
|
|
69
|
+
let pathname = withoutQuery;
|
|
70
|
+
try {
|
|
71
|
+
// A dummy base parses relative targets too; only the pathname is kept.
|
|
72
|
+
pathname = new URL(withoutQuery, "http://rum.invalid").pathname;
|
|
73
|
+
} catch {
|
|
74
|
+
// Not a URL: keep the query-free string; id templating below still applies.
|
|
75
|
+
}
|
|
76
|
+
return templateSegments(pathname).slice(0, MAX_ATTRIBUTE_STRING);
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/** Allowlisted keys, scalars only, URL-bearing keys reduced to templated pathnames. */
|
|
80
|
+
export function scrubSpanAttributes(attributes: Attributes): Attributes {
|
|
81
|
+
const kept: Attributes = {};
|
|
82
|
+
for (const [key, value] of Object.entries(attributes)) {
|
|
83
|
+
if (!ALLOWED.has(key)) continue;
|
|
84
|
+
if (URL_BEARING.has(key)) {
|
|
85
|
+
if (typeof value === "string") kept[key] = scrubUrl(value);
|
|
86
|
+
continue;
|
|
87
|
+
}
|
|
88
|
+
// An allowed key must not smuggle a structure (mirrors the server's scalar filter).
|
|
89
|
+
// Non-finite numbers are dropped: they serialize to JSON null and are never a metric.
|
|
90
|
+
if (typeof value === "string") kept[key] = value.slice(0, MAX_ATTRIBUTE_STRING);
|
|
91
|
+
else if (typeof value === "number" && Number.isFinite(value)) kept[key] = value;
|
|
92
|
+
else if (typeof value === "boolean") kept[key] = value;
|
|
93
|
+
}
|
|
94
|
+
return kept;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/** Absolute http(s) URLs must not leak scheme/host into span names (mirrors the server). */
|
|
98
|
+
function pathnameOf(raw: string): string {
|
|
99
|
+
try {
|
|
100
|
+
const url = new URL(raw);
|
|
101
|
+
if (url.protocol === "http:" || url.protocol === "https:") return url.pathname;
|
|
102
|
+
} catch {
|
|
103
|
+
// Not an absolute URL: a route template or a fixed span name, kept as-is.
|
|
104
|
+
}
|
|
105
|
+
return raw;
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/** Span names get the same query/fragment strip and id templating, capped like the server. */
|
|
109
|
+
export function scrubSpanName(name: string): string {
|
|
110
|
+
const withoutQuery = pathnameOf(name).split(/[?#]/)[0] ?? "";
|
|
111
|
+
return templateSegments(withoutQuery).slice(0, MAX_SPAN_NAME);
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/**
|
|
115
|
+
* Scrubs each span before the batch processor queues it. The SDK hands onEnd the live Span
|
|
116
|
+
* object; ReadableSpan is its read-only view, so narrow to the mutable shape (no `any`)
|
|
117
|
+
* and rewrite in place — every exporter downstream then sees scrubbed data.
|
|
118
|
+
*/
|
|
119
|
+
export class ScrubProcessor implements SpanProcessor {
|
|
120
|
+
onStart(): void {}
|
|
121
|
+
|
|
122
|
+
onEnd(span: ReadableSpan): void {
|
|
123
|
+
const mutable = span as unknown as { name: string; attributes: Attributes };
|
|
124
|
+
mutable.name = scrubSpanName(span.name);
|
|
125
|
+
mutable.attributes = scrubSpanAttributes(span.attributes);
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
shutdown(): Promise<void> {
|
|
129
|
+
return Promise.resolve();
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
forceFlush(): Promise<void> {
|
|
133
|
+
return Promise.resolve();
|
|
134
|
+
}
|
|
135
|
+
}
|
package/src/vitals.ts
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Core Web Vitals as spans (D-203 §2, D-209). The browser.web_vital semantic convention is
|
|
3
|
+
* still Development status: this pins its name/value/rating triple and adapts it to spans,
|
|
4
|
+
* because the ingestion class accepts spans only (there is no metric surface). The
|
|
5
|
+
* standard web-vitals build is used, never attribution: attribution entries carry element
|
|
6
|
+
* selectors and other PII.
|
|
7
|
+
*/
|
|
8
|
+
import type { Attributes, Tracer } from "@opentelemetry/api";
|
|
9
|
+
import { onCLS, onFCP, onINP, onLCP, onTTFB } from "web-vitals";
|
|
10
|
+
import type { Metric } from "web-vitals";
|
|
11
|
+
|
|
12
|
+
export const WEB_VITAL_SPAN_NAME = "browser.web_vital";
|
|
13
|
+
|
|
14
|
+
/** Pure mapping for tests: the pinned semconv triple, nothing else. */
|
|
15
|
+
export function mapVital(metric: Metric): Attributes {
|
|
16
|
+
return {
|
|
17
|
+
"browser.web_vital.name": metric.name,
|
|
18
|
+
"browser.web_vital.value": metric.value,
|
|
19
|
+
"browser.web_vital.rating": metric.rating,
|
|
20
|
+
};
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export function wireVitals(tracer: Tracer): void {
|
|
24
|
+
const report = (metric: Metric): void => {
|
|
25
|
+
// One span per metric report, ended immediately so the batch processor picks it up.
|
|
26
|
+
const span = tracer.startSpan(WEB_VITAL_SPAN_NAME, { attributes: mapVital(metric) });
|
|
27
|
+
span.end();
|
|
28
|
+
};
|
|
29
|
+
onLCP(report);
|
|
30
|
+
onINP(report);
|
|
31
|
+
onCLS(report);
|
|
32
|
+
onFCP(report);
|
|
33
|
+
onTTFB(report);
|
|
34
|
+
}
|