@monoscopetech/browser 0.7.2 → 0.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/README.md CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
  The **Monoscope Browser SDK** is a lightweight JavaScript library for adding **session replay**, **performance tracing**, **error tracking**, and **web vitals** to your web applications.
4
4
 
5
- When used together with the [Monoscope Server SDKs](https://apitoolkit.io/docs/sdks/), you gain **end-to-end observability** — seamlessly connecting user interactions in the browser to backend services, APIs, and databases.
5
+ When used together with the [Monoscope Server SDKs](https://monoscope.tech/docs/sdks/), you gain **end-to-end observability** — seamlessly connecting user interactions in the browser to backend services, APIs, and databases.
6
6
 
7
7
  This means you can:
8
8
 
@@ -32,14 +32,13 @@ Or include it directly in your HTML using a `<script>` tag:
32
32
 
33
33
  ## Quick Start
34
34
 
35
- Initialize Monoscope with your **project ID** and configuration:
35
+ Initialize Monoscope with your **API key** (found in your project settings):
36
36
 
37
37
  ```javascript
38
38
  import Monoscope from "@monoscopetech/browser";
39
39
 
40
40
  const monoscope = new Monoscope({
41
- projectId: "YOUR_PROJECT_ID",
42
- serviceName: "my-web-app",
41
+ apiKey: "YOUR_API_KEY",
43
42
  });
44
43
 
45
44
  // Identify the current user
@@ -49,6 +48,13 @@ monoscope.setUser({
49
48
  });
50
49
  ```
51
50
 
51
+ On `localhost`, debug mode is auto-enabled — you'll see a status overlay and console diagnostics. Call `monoscope.test()` to verify your setup:
52
+
53
+ ```javascript
54
+ const result = await monoscope.test();
55
+ console.log(result); // { success: true, message: "Test span sent successfully." }
56
+ ```
57
+
52
58
  ---
53
59
 
54
60
  ## Configuration
@@ -57,8 +63,9 @@ The `Monoscope` constructor accepts the following options:
57
63
 
58
64
  | Name | Type | Description |
59
65
  | --- | --- | --- |
60
- | `projectId` | `string` | **Required** – Your Monoscope project ID. |
61
- | `serviceName` | `string` | **Required** Name of your service or application. |
66
+ | `apiKey` | `string` | **Required** – Your Monoscope API key (found in project settings). |
67
+ | `serviceName` | `string` | Service name. Defaults to `location.hostname`. |
68
+ | `projectId` | `string` | Deprecated alias for `apiKey`. |
62
69
  | `exporterEndpoint` | `string` | Endpoint for exporting traces. Defaults to Monoscope's ingest endpoint. |
63
70
  | `propagateTraceHeaderCorsUrls` | `RegExp[]` | URL patterns where trace context headers should be propagated. Defaults to same-origin only. |
64
71
  | `resourceAttributes` | `Record<string, string>` | Additional OpenTelemetry resource attributes. |
@@ -134,6 +141,15 @@ Returns the current session ID.
134
141
 
135
142
  Returns the current tab ID (unique per browser tab).
136
143
 
144
+ ### `test(): Promise<{success: boolean, message: string}>`
145
+
146
+ Sends a test span and flushes it to verify the connection is working.
147
+
148
+ ```javascript
149
+ const result = await monoscope.test();
150
+ console.log(result.success); // true if the span was accepted
151
+ ```
152
+
137
153
  ### `enable()` / `disable()`
138
154
 
139
155
  Dynamically enable or disable all data collection.
@@ -167,7 +183,7 @@ import { MonoscopeProvider, useMonoscope, useMonoscopeUser, MonoscopeErrorBounda
167
183
  // Wrap your app with MonoscopeProvider
168
184
  function App() {
169
185
  return (
170
- <MonoscopeProvider config={{ projectId: "YOUR_PROJECT_ID", serviceName: "my-react-app" }}>
186
+ <MonoscopeProvider config={{ apiKey: "YOUR_API_KEY" }}>
171
187
  <MonoscopeErrorBoundary fallback={<div>Something went wrong</div>}>
172
188
  <MyApp />
173
189
  </MonoscopeErrorBoundary>
@@ -261,8 +277,7 @@ Pass extra OTel instrumentations via the `instrumentations` config to extend tra
261
277
  import { LongTaskInstrumentation } from "@opentelemetry/instrumentation-long-task";
262
278
 
263
279
  const monoscope = new Monoscope({
264
- projectId: "YOUR_PROJECT_ID",
265
- serviceName: "my-app",
280
+ apiKey: "YOUR_API_KEY",
266
281
  instrumentations: [new LongTaskInstrumentation()],
267
282
  });
268
283
  ```
package/dist/index.d.ts CHANGED
@@ -13,7 +13,9 @@ declare class Monoscope {
13
13
  private vitals;
14
14
  private router;
15
15
  private _enabled;
16
+ private overlay;
16
17
  constructor(config: MonoscopeConfig);
18
+ private logInitBanner;
17
19
  private resolveSessionId;
18
20
  private persistActivity;
19
21
  private rotateSession;
@@ -24,6 +26,10 @@ declare class Monoscope {
24
26
  setUser(u: MonoscopeUser): void;
25
27
  startSpan<T>(name: string, fn: (span: Span) => T): T;
26
28
  recordEvent(name: string, attributes?: Record<string, string | number | boolean>): void;
29
+ test(): Promise<{
30
+ success: boolean;
31
+ message: string;
32
+ }>;
27
33
  disable(): void;
28
34
  enable(): void;
29
35
  isEnabled(): boolean;
package/dist/index.js CHANGED
@@ -4,15 +4,25 @@ import { ErrorTracker } from "./errors";
4
4
  import { WebVitalsCollector } from "./web-vitals";
5
5
  import { SPARouter } from "./router";
6
6
  import { addBreadcrumb, clearBreadcrumbs } from "./breadcrumbs";
7
+ import { DevOverlay } from "./overlay";
7
8
  const SESSION_TIMEOUT_MS = 30 * 60 * 1000;
8
9
  const LAST_ACTIVITY_KEY = "monoscope-last-activity";
9
10
  const isBrowser = typeof window !== "undefined";
10
11
  class Monoscope {
11
12
  constructor(config) {
12
- if (!config.projectId)
13
- throw new Error("MonoscopeConfig must include projectId");
13
+ this.overlay = null;
14
+ const resolvedKey = config.apiKey || config.projectId;
15
+ if (!resolvedKey)
16
+ throw new Error("MonoscopeConfig must include apiKey (or projectId)");
17
+ if (config.projectId && !config.apiKey && config.debug) {
18
+ console.warn("[Monoscope] `projectId` is deprecated. Use `apiKey` instead.");
19
+ }
20
+ config = { ...config, apiKey: resolvedKey, projectId: resolvedKey };
21
+ const isLocalhost = isBrowser && (location.hostname === "localhost" || location.hostname === "127.0.0.1");
22
+ if (config.debug === undefined && isLocalhost)
23
+ config = { ...config, debug: true };
14
24
  if (!config.serviceName)
15
- throw new Error("MonoscopeConfig must include serviceName");
25
+ config = { ...config, serviceName: isBrowser ? location.hostname : "unknown" };
16
26
  this.config = config;
17
27
  this._enabled = config.enabled !== false;
18
28
  this.tabId = crypto.randomUUID();
@@ -36,9 +46,31 @@ class Monoscope {
36
46
  });
37
47
  this.router.start();
38
48
  }
49
+ if (this._enabled && this.config.debug) {
50
+ this.logInitBanner();
51
+ if (isBrowser) {
52
+ this.overlay = new DevOverlay();
53
+ this.otel.onExportStatus = (ok) => this.overlay?.setConnectionStatus(ok);
54
+ }
55
+ }
39
56
  if (isBrowser)
40
57
  this.setupActivityTracking();
41
58
  }
59
+ logInitBanner() {
60
+ const c = this.config;
61
+ const endpoint = c.exporterEndpoint || "https://otelcol.monoscope.tech/v1/traces";
62
+ const samplePct = Math.round((c.sampleRate ?? 1) * 100);
63
+ const replayPct = Math.round((c.replaySampleRate ?? 1) * 100);
64
+ console.groupCollapsed("%c[Monoscope] ✓ Initialized", "color: #22c55e; font-weight: bold");
65
+ console.log(` API Key: ${c.apiKey}`);
66
+ console.log(` Service: ${c.serviceName}`);
67
+ console.log(` Session: ${this.sessionId}`);
68
+ console.log(` Tracing: ✓ (sample rate: ${samplePct}%)`);
69
+ console.log(` Replay: ✓ (sample rate: ${replayPct}%)`);
70
+ console.log(` Errors: ✓`);
71
+ console.log(` Endpoint: ${endpoint}`);
72
+ console.groupEnd();
73
+ }
42
74
  resolveSessionId() {
43
75
  try {
44
76
  const storedId = sessionStorage.getItem("monoscope-session-id");
@@ -135,10 +167,28 @@ class Monoscope {
135
167
  this.replay.setUser(u);
136
168
  }
137
169
  startSpan(name, fn) {
170
+ this.overlay?.incrementEvents();
138
171
  return this.otel.startSpan(name, fn);
139
172
  }
140
173
  recordEvent(name, attributes) {
141
174
  this.otel.recordEvent(name, attributes);
175
+ this.overlay?.incrementEvents();
176
+ }
177
+ async test() {
178
+ try {
179
+ this.otel.emitSpan("monoscope.test", { "test.timestamp": Date.now() });
180
+ await this.otel.forceFlush();
181
+ const msg = "Test span sent successfully.";
182
+ if (this.config.debug)
183
+ console.log(`[Monoscope] ${msg}`);
184
+ return { success: true, message: msg };
185
+ }
186
+ catch (e) {
187
+ const msg = `Test failed: ${e}`;
188
+ if (this.config.debug)
189
+ console.error(`[Monoscope] ${msg}`);
190
+ return { success: false, message: msg };
191
+ }
142
192
  }
143
193
  disable() {
144
194
  this._enabled = false;