### Development Mode Setup Source: https://github.com/embrace-io/embrace-web-sdk/blob/main/demo/frontend/README.md Starts the demo app in development mode with hot reloading, using local SDK source code. ```bash cd ../.. npm run dev ``` -------------------------------- ### Install and Run Demo Source: https://github.com/embrace-io/embrace-web-sdk/blob/main/demo/frontend/README.md Installs project dependencies and runs the demo application. ```bash npm ci && npm run demo ``` -------------------------------- ### Clone and Install SDK Dependencies Source: https://github.com/embrace-io/embrace-web-sdk/blob/main/DEVELOPING.md Clone the SDK repository and install its dependencies to begin development. ```sh git clone git@github.com:embrace-io/embrace-web-sdk.git cd embrace-web-sdk npm install ``` -------------------------------- ### Start Local Collector Source: https://github.com/embrace-io/embrace-web-sdk/blob/main/server/README.md Run this command in the repository root to start the local collector server. ```bash npm run dev ``` -------------------------------- ### Install Embrace Web SDK using yarn Source: https://github.com/embrace-io/embrace-web-sdk/blob/main/packages/web-sdk/README.md Install the Embrace Web SDK package using yarn. ```sh yarn add @embrace-io/web-sdk ``` -------------------------------- ### Install Embrace Web SDK using npm Source: https://github.com/embrace-io/embrace-web-sdk/blob/main/packages/web-sdk/README.md Install the Embrace Web SDK package using npm. ```sh npm install @embrace-io/web-sdk ``` -------------------------------- ### Setup and Run the Demo Source: https://github.com/embrace-io/embrace-web-sdk/blob/main/demo/frontend-sdk/README.md Execute these commands in the frontend-sdk directory to set up, build, and run the demo application. The dev command listens for changes in the host SDK and rebuilds it. ```bash npm run setup npm run build npm run dev ``` -------------------------------- ### Install Embrace Web SDK CLI with npm Source: https://github.com/embrace-io/embrace-web-sdk/blob/main/packages/web-cli/README.md Install the Embrace Web SDK CLI as a development dependency using npm. ```sh npm install --save-dev @embrace-io/web-cli ``` -------------------------------- ### Install Embrace Web SDK CLI with yarn Source: https://github.com/embrace-io/embrace-web-sdk/blob/main/packages/web-cli/README.md Install the Embrace Web SDK CLI as a development dependency using yarn. ```sh yarn add -D @embrace-io/web-cli ``` -------------------------------- ### Platform Dependencies Configuration Source: https://github.com/embrace-io/embrace-web-sdk/blob/main/tests/integration/README.md Example of how individual platform directories reference workspace dependencies using file: paths in their package.json. ```json { "@embrace-io/web-sdk": "file:../../../../packages/web-sdk", "@embrace-io/web-cli": "file:../../../../packages/web-cli" } ``` -------------------------------- ### Install Workspace Dependencies Source: https://github.com/embrace-io/embrace-web-sdk/blob/main/tests/integration/README.md Ensure all workspace dependencies are installed before proceeding with platform-specific installations. This is crucial for linked platform dependencies. ```bash npm install ``` -------------------------------- ### Install Embrace Web CLI Source: https://github.com/embrace-io/embrace-web-sdk/blob/main/packages/web-sdk/README.md Install the Embrace Web CLI as a development dependency for managing sourcemap uploads and app version injection. ```bash npm install --save-dev @embrace-io/web-cli ``` ```bash yarn add -D @embrace-io/web-cli ``` -------------------------------- ### Initialize SDK in a Separate File (Pages Router) Source: https://github.com/embrace-io/embrace-web-sdk/blob/main/packages/web-sdk/NEXTJS.md Create a dedicated file to initialize the SDK once and export it. This approach is suitable for the Pages Router setup. ```typescript import { initSDK } from '@embrace-io/web-sdk'; export const embraceWebSdk = initSDK({ appID: 'xxxxx', appVersion: '1.0.0', }); ``` -------------------------------- ### Reinstall Platform Dependencies Source: https://github.com/embrace-io/embrace-web-sdk/blob/main/tests/integration/README.md After installing workspace dependencies, reinstall platform dependencies to ensure correct linking and setup for the Embrace Web SDK. ```bash npm run install-dependencies ``` -------------------------------- ### Start Long-Running Server Container for Integration Tests Source: https://github.com/embrace-io/embrace-web-sdk/blob/main/DEVELOPING.md Start the server container that will remain alive between integration test runs for faster iteration. ```bash npm run test:integration:container:serve ``` -------------------------------- ### Platform Build Smoke Test Setup Source: https://github.com/embrace-io/embrace-web-sdk/blob/main/tests/integration/README.md TypeScript code for setting up and running a platform build smoke test, specifying the platform directory and build targets. ```typescript import { dirname, resolve } from 'node:path'; import { fileURLToPath } from 'node:url'; import { runPlatformBuildSmokeTest } from '../../utils/index.ts'; const __dirname = dirname(fileURLToPath(import.meta.url)); const platformDir = resolve(__dirname, '../../platforms/'); await runPlatformBuildSmokeTest(platformDir, { targets: ['es2015'], platformName: '', }); ``` -------------------------------- ### Initialize the Embrace SDK Source: https://github.com/embrace-io/embrace-web-sdk/blob/main/packages/web-sdk/README.md Initialize the Embrace SDK with your application's appID and version. This should be done early in your app's lifecycle to start capturing telemetry. ```typescript import { initSDK } from '@embrace-io/web-sdk'; const result = initSDK({ appID: "YOUR_EMBRACE_APP_ID", appVersion: "YOUR_APP_VERSION", }); if (!!result) { console.log("Successfully initialized the Embrace SDK"); } else { console.log("Failed to initialize the Embrace SDK"); } ``` -------------------------------- ### Update trace span calls from 0.x to 1.x Source: https://github.com/embrace-io/embrace-web-sdk/blob/main/packages/web-sdk/UPGRADING.md The method for starting performance spans has been renamed from `startPerformanceSpan` to `startSpan` in version 1.x. ```typescript import { trace } from '@embrace-io/web-sdk'; const span = trace.startPerformanceSpan("span-name"); ``` ```typescript import { trace } from '@embrace-io/web-sdk'; const span = trace.startSpan("span-name"); ``` -------------------------------- ### Configure Playwright for Custom Dev Server Source: https://github.com/embrace-io/embrace-web-sdk/blob/main/tests/integration/README.md Example of adding a custom web server entry to playwright.config.ts for platforms with non-standard development servers. ```typescript { name: '', command: 'cd platforms/ && npm run build && your-serve-command -p 3020', url: 'http://localhost:3020', reuseExistingServer: false, } ``` -------------------------------- ### Generate Fetch GET Request Source: https://github.com/embrace-io/embrace-web-sdk/blob/main/tests/performance/public/performance-test.html Creates a GET request to a specified server URL using the Fetch API. It returns a promise that resolves with the response text or rejects with an error if the request fails. ```javascript function generateFetchRequest() { return fetch(SERVER_URL, { method: 'GET', }) .then(response => response.text()) .catch(error => console.error('Error fetching data:', error)); } ``` -------------------------------- ### Generate XMLHttpRequest GET Request Source: https://github.com/embrace-io/embrace-web-sdk/blob/main/tests/performance/public/performance-test.html Creates a GET request to a specified server URL using XMLHttpRequest. It returns a promise that resolves upon successful completion or rejects on network errors. ```javascript function generateXHRRequest() { return new Promise((resolve, reject) => { const xhr = new XMLHttpRequest(); xhr.open('GET', SERVER_URL, true); xhr.onload = () => { resolve(); }; xhr.onerror = () => { reject(new Error('Network error')); }; xhr.send(); }); } ``` -------------------------------- ### Add a custom trace span Source: https://github.com/embrace-io/embrace-web-sdk/blob/main/packages/web-sdk/README.md Create a custom span for operations you want to track. Start a span, perform an operation, and then end or fail the span accordingly. Only explicitly ended spans are exported. ```typescript import { trace } from '@embrace-io/web-sdk'; const span = trace.startSpan("span-name"); someAsyncOperation() .then(() => span.end()) .catch(() => span.fail()); ``` -------------------------------- ### Build and Run Production Demo Source: https://github.com/embrace-io/embrace-web-sdk/blob/main/demo/frontend/README.md Compiles the SDK, builds the demo app for production, and opens it in the browser. ```bash npm run demo ``` -------------------------------- ### Build the SDK Source: https://github.com/embrace-io/embrace-web-sdk/blob/main/demo/frontend-sdk/README.md Run this command in the root of the repository to build the SDK. This allows changes to be reflected in the demo app without rebuilding the SDK each time. ```bash npm run build ``` -------------------------------- ### Initialize SDK with Verbose Logging Source: https://github.com/embrace-io/embrace-web-sdk/blob/main/packages/web-sdk/README.md Configure the SDK to output all log levels to the console during initialization. This is useful for debugging. ```typescript import { initSDK, DiagLogLevel } from '@embrace-io/web-sdk'; initSDK({ appID: "YOUR_EMBRACE_APP_ID", appVersion: "YOUR_APP_VERSION", logLevel: DiagLogLevel.ALL, }); ``` -------------------------------- ### Async Embrace Web SDK Initialization Source: https://github.com/embrace-io/embrace-web-sdk/blob/main/tests/performance/public/performance-test.html This snippet demonstrates how to asynchronously load and initialize the Embrace Web SDK using a script tag. It ensures the SDK is ready before executing further code. ```javascript (() => { window.EmbraceWebSdkOnReady = window.EmbraceWebSdkOnReady || { q: [], onReady: (fn) => { window.EmbraceWebSdkOnReady.q.push(fn); }, }; const script = document.createElement('script'); script.async = true; script.defer = true; script.src = '/embrace-web-sdk.js'; script.onload = () => { window.EmbraceWebSdkOnReady.q.forEach(fn => { fn(); }); window.EmbraceWebSdkOnReady.q = []; // Call onReady immediately if the SDK is already loaded window.EmbraceWebSdkOnReady.onReady = (fn) => { fn(); }; }; const firstScript = document.getElementsByTagName('script')[0]; firstScript.parentNode.insertBefore(script, firstScript); })(); ``` -------------------------------- ### Initialize SDK in a Client Component (App Router) Source: https://github.com/embrace-io/embrace-web-sdk/blob/main/packages/web-sdk/NEXTJS.md Create a Client Component to initialize the SDK. Ensure the 'use client' directive is present. This component should render nothing and is intended for browser-only execution. ```typescript 'use client'; import { initSDK } from '@embrace-io/web-sdk'; export const embraceWebSdk = initSDK({ appID: 'xxxxx', appVersion: '1.0.0', }); export default function EmbraceWebSdk() { return null; } ``` -------------------------------- ### Initialize Embrace Web SDK Conditionally Source: https://github.com/embrace-io/embrace-web-sdk/blob/main/tests/performance/public/lighthouse-test.html Initializes the Embrace Web SDK if the 'use_sdk' query parameter is present in the URL. Requires appID and appVersion. ```javascript const urlParams = new URLSearchParams(window.location.search); const usesSDK = urlParams.has('use_sdk'); if (usesSDK) { window.EmbraceWebSdk.initSDK({ appID: '11111', appVersion: '0.0.1', }); } ``` -------------------------------- ### Embrace Web SDK Initialization and Event Handling Source: https://github.com/embrace-io/embrace-web-sdk/blob/main/tests/performance/public/performance-test.html Initializes the Embrace SDK with provided app details and sets up an indicator to confirm SDK loading. It also handles the 'onReady' event to ensure the SDK is fully operational before proceeding. ```javascript window.EmbraceWebSdkOnReady.onReady(() => { // Insert an element showing that the SDK is loaded const sdkLoadedIndicator = document.createElement('div'); sdkLoadedIndicator.textContent = 'Embrace Web SDK Loaded'; document.body.appendChild(sdkLoadedIndicator); client = window.EmbraceWebSdk.initSDK({ appID: '11111', appVersion: '0.0.1', }); sdkReady = true; setIdleState(); }); ``` -------------------------------- ### Add Build Tests for New Platform Source: https://github.com/embrace-io/embrace-web-sdk/blob/main/tests/integration/README.md Configuration for a new platform's package.json, including build scripts and dependencies required for build tests. ```json { "scripts": { "build": "npm run build:clean && npm run build:es2015", "build:clean": "emb-rm dist .sonda", "build:es2015": "your-build-command && npm run process-sourcemaps", "process-sourcemaps": "embrace-web-cli upload -a NOEMB -p ./dist/es2015 --no-upload" } } ``` ```json { "dependencies": { "@embrace-io/web-sdk": "file:../../../../packages/web-sdk" }, "devDependencies": { "@embrace-io/web-cli": "file:../../../../packages/web-cli" } } ``` -------------------------------- ### Upload Sourcemaps with CLI Source: https://github.com/embrace-io/embrace-web-sdk/blob/main/packages/web-sdk/README.md Use the Embrace Web CLI to upload your JavaScript bundle and sourcemap files for symbolicated stack traces. Ensure you have a Symbol Upload API token. ```bash npx embrace-web-cli upload -a "YOUR_EMBRACE_APP_ID" -t "YOUR_EMBRACE_UPLOAD_API_TOKEN" -p "JS_BUILD_PATH" ``` -------------------------------- ### Upload Sourcemaps and Inject App Version with CLI Source: https://github.com/embrace-io/embrace-web-sdk/blob/main/packages/web-sdk/README.md Upload sourcemaps and simultaneously inject your app version into the bundle using the CLI. This is useful when the app version is determined at build time. Do not set appVersion in initSDK if using this method. ```bash npx embrace-web-cli upload --app-version "APP_VERSION" -a "YOUR_EMBRACE_APP_ID" -t "YOUR_EMBRACE_UPLOAD_API_TOKEN" -p "JS_BUILD_PATH" ``` -------------------------------- ### Initialize SDK with App Version (CDN) Source: https://github.com/embrace-io/embrace-web-sdk/blob/main/packages/web-sdk/README.md When loading from CDN, you must explicitly provide the app version during SDK initialization. ```javascript initSDK({ appVersion: '0.0.1', /*...*/ }); ``` -------------------------------- ### Listen to React Router V6+ Changes in Data Mode Source: https://github.com/embrace-io/embrace-web-sdk/blob/main/packages/web-sdk/REACT.md Use `listenToRouterChanges` within a `useEffect` hook to track route changes in React Router V6+ data mode. This ensures tracking starts after the app mounts and stops when the component unmounts. ```typescript jsx import { listenToRouterChanges } from '@embrace-io/web-sdk/react-instrumentation'; import { createBrowserRouter, RouterProvider, matchRoutes, } from 'react-router-dom'; import { useEffect } from 'react'; const router = createBrowserRouter([ { path: '/home', element: , }, { path: '/about', element: , }, { path: '/contact', element: , } ]); const App = () => { useEffect(() => { // It's important that `listenToRouterChanges` is called on a useEffect so it starts tracking routes once the App is mounted. // Otherwise some early telemetry can be missed if this gets initialized too early. // Return the cleanup function to stop listening to route changes when the component unmount. return listenToRouterChanges({ router, // Use `matchRoutes` from React Router to match the current route. routesMatcher: matchRoutes, }); // Set an empty dependency array to run this effect only once. }, []); return ( ) } ``` -------------------------------- ### Initialize SDK with Console Exporters Source: https://github.com/embrace-io/embrace-web-sdk/blob/main/packages/web-sdk/README.md Set up console exporters and processors to view telemetry output as it's emitted or batched. This provides detailed insights into spans and logs. ```typescript import { initSDK, DiagLogLevel } from '@embrace-io/web-sdk'; import { ConsoleLogRecordExporter, SimpleLogRecordProcessor } from '@opentelemetry/sdk-logs'; import { ConsoleSpanExporter, SimpleSpanProcessor } from '@opentelemetry/sdk-trace-web' initSDK({ appID: "YOUR_EMBRACE_APP_ID", appVersion: "YOUR_APP_VERSION", logLevel: DiagLogLevel.INFO, // setup as exporters to output with the same batching as when exporting to a collector endpoint spanExporters: [new ConsoleSpanExporter()], logExporters: [new ConsoleLogRecordExporter()], // OR, wrap exporters with simple processors to output as soon as telemetry is emitted spanProcessors: [new SimpleSpanProcessor(new ConsoleSpanExporter())], logProcessors: [new SimpleLogRecordProcessor(new ConsoleLogRecordExporter())], }); ``` -------------------------------- ### Initialize Embrace SDK with React Router Navigation Source: https://github.com/embrace-io/embrace-web-sdk/blob/main/packages/web-sdk/REACT.md Call `initSDK` before your React App is mounted. Include `createReactRouterNavigationInstrumentation` to automatically track React Router navigation. ```typescript import { initSDK } from '@embrace-io/web-sdk'; import { createReactRouterNavigationInstrumentation } from '@embrace-io/web-sdk/react-instrumentation'; initSDK({ // ...Other configs instrumentations: [ createReactRouterNavigationInstrumentation(), ], }) ``` -------------------------------- ### Import SDK from Global Window Object Source: https://github.com/embrace-io/embrace-web-sdk/blob/main/packages/web-sdk/README.md When using the SDK from a CDN, import necessary functions from the global `window.EmbraceWebSdk` object instead of node modules. ```diff - import { initSDK, log, page, session, trace, user } from '@embrace-io/web-sdk'; + const { initSDK, log, page, session, trace, user } = window.EmbraceWebSdk; ``` -------------------------------- ### Upload Sourcemaps with Embrace CLI Source: https://github.com/embrace-io/embrace-web-sdk/blob/main/packages/web-cli/README.md Upload sourcemaps to Embrace using the CLI. Ensure this is run before files are packaged. Requires App ID, Upload API token, and build path. ```sh npx embrace-web-cli upload -a "YOUR_EMBRACE_APP_ID" -t "YOUR_EMBRACE_UPLOAD_API_TOKEN" -p "BUILD_PATH" ``` -------------------------------- ### Include SDK Initialization in Root Layout (App Router) Source: https://github.com/embrace-io/embrace-web-sdk/blob/main/packages/web-sdk/NEXTJS.md Render the SDK initialization component in your root layout to ensure the SDK initializes on every page load. This component should be placed within the body. ```typescript import EmbraceWebSdk from '../components/EmbraceWebSdk'; export default function RootLayout({ children }: { children: React.ReactNode }) { return ( {children} ); } ``` -------------------------------- ### Run SDK Tests Source: https://github.com/embrace-io/embrace-web-sdk/blob/main/DEVELOPING.md Execute the test suite for the Embrace Web SDK. ```sh npm run test ``` -------------------------------- ### Initialize Multiple SDK Instances Source: https://github.com/embrace-io/embrace-web-sdk/blob/main/packages/web-sdk/README.md To run multiple SDK instances, set `registerGlobally: false` during initialization and use the returned instance for SDK methods. ```typescript import { initSDK } from '@embrace-io/web-sdk'; const embraceSDK = initSDK({ appID: "YOUR_EMBRACE_APP_ID", appVersion: "YOUR_APP_VERSION", registerGlobally: false, // Prevents the SDK from registering itself globally }); ``` -------------------------------- ### Run Integration Tests Against Running Servers Source: https://github.com/embrace-io/embrace-web-sdk/blob/main/DEVELOPING.md Execute integration tests against the already running servers for fast, non-rebuilding test cycles. ```bash npm run test:integration:container:test ``` -------------------------------- ### Run Full Integration Test Suite Source: https://github.com/embrace-io/embrace-web-sdk/blob/main/tests/integration/README.md Execute all integration tests, including build and end-to-end tests. Ensure this is run before updating golden files. ```bash npm run test:integration ``` -------------------------------- ### Rebuild SDK and Run Integration Tests Source: https://github.com/embrace-io/embrace-web-sdk/blob/main/tests/integration/README.md Before running integration tests, rebuild the SDK to ensure the latest changes are included. This is a common step after making SDK modifications. ```bash npm run build npm run test:integration ``` -------------------------------- ### Initialize SDK with App Version from package.json Source: https://github.com/embrace-io/embrace-web-sdk/blob/main/packages/web-sdk/README.md Use this method to automatically set the appVersion for Embrace by reading it from your package.json file during SDK initialization. Ensure your bundler supports JSON imports. ```typescript import * as packageInfo from "..//package.json"; initSDK({ appID: "YOUR_EMBRACE_APP_ID", appVersion: packageInfo.version, }); ``` -------------------------------- ### Async Loading of Embrace SDK Source: https://github.com/embrace-io/embrace-web-sdk/blob/main/packages/web-sdk/README.md Load the SDK asynchronously to prevent blocking page rendering. Replace 'X.X.X' with the desired SDK version. ```html ``` -------------------------------- ### Include Embrace SDK from CDN Source: https://github.com/embrace-io/embrace-web-sdk/blob/main/packages/web-sdk/README.md Add this script tag to your HTML's head to include the SDK from a CDN. Pinning a specific version is recommended to avoid breaking changes. ```html ``` ```html ``` -------------------------------- ### Conditional SDK Initialization Source: https://github.com/embrace-io/embrace-web-sdk/blob/main/tests/performance/public/performance-test.html Conditionally initializes the Embrace Web SDK based on the 'use_sdk' URL parameter. If the SDK is not used, it provides a fallback 'onReady' function that executes immediately. ```javascript if (usesSDK) { setWorkingState(); // Snippet from cdn/asyncSnippet.js (() => { window.EmbraceWebSdkOnReady = window.EmbraceWebSdkOnReady || { q: [], onReady: (fn) => { window.EmbraceWebSdkOnReady.q.push(fn); }, }; const script = document.createElement('script'); script.async = true; script.defer = true; script.src = '/embrace-web-sdk.js'; script.onload = () => { window.EmbraceWebSdkOnReady.q.forEach(fn => { fn(); }); window.EmbraceWebSdkOnReady.q = []; // Call onReady immediately if the SDK is already loaded window.EmbraceWebSdkOnReady.onReady = (fn) => { fn(); }; }; const firstScript = document.getElementsByTagName('script')[0]; firstScript.parentNode.insertBefore(script, firstScript); })(); window.EmbraceWebSdkOnReady.onReady(() => { // Insert an element showing that the SDK is loaded const sdkLoadedIndicator = document.createElement('div'); sdkLoadedIndicator.textContent = 'Embrace Web SDK Loaded'; document.body.appendChild(sdkLoadedIndicator); client = window.EmbraceWebSdk.initSDK({ appID: '11111', appVersion: '0.0.1', }); sdkReady = true; setIdleState(); }); } else { window.EmbraceWebSdkOnReady = { onReady: (fn) => { fn(); }, }; } ``` -------------------------------- ### Wrap Early SDK Calls with onReady Source: https://github.com/embrace-io/embrace-web-sdk/blob/main/packages/web-sdk/README.md When using asynchronous loading, wrap any early SDK calls within the `onReady` method to ensure the SDK is loaded. ```javascript window.EmbraceWebSdkOnReady.onReady(() => { window.EmbraceWebSdk.initSDK({ appVersion: '0.0.1', /*...*/ }); }) ``` -------------------------------- ### Import Initialization File in _app.tsx (Pages Router) Source: https://github.com/embrace-io/embrace-web-sdk/blob/main/packages/web-sdk/NEXTJS.md Import the SDK initialization file at the top of your `_app.tsx` file. The Pages Router automatically handles client-side execution for this file. ```typescript import '../lib/embrace'; import type { AppProps } from 'next/app'; export default function App({ Component, pageProps }: AppProps) { return ; } ``` -------------------------------- ### Configure Custom Log and Trace Exporters Source: https://github.com/embrace-io/embrace-web-sdk/blob/main/packages/web-sdk/README.md Set up custom OTLP-compatible log and trace exporters with specific URLs and headers. Configure network instrumentation to ignore export URLs to prevent recursive requests. ```typescript import { OTLPLogExporter } from '@opentelemetry/exporter-logs-otlp-http'; import { OTLPTraceExporter } from '@opentelemetry/exporter-trace-otlp-http'; initSDK({ appID: "YOUR_EMBRACE_APP_ID", appVersion: "YOUR_APP_VERSION", spanExporters: [ new OTLPTraceExporter({ url: 'https://example.com/endpoint/for/traces', headers: { 'Authorization': 'Basic TOKEN' } }), ], logExporters: [ new OTLPLogExporter({ url: 'https://example.com/endpoint/for/logs', headers: { 'Authorization': 'Basic TOKEN' } }), ], defaultInstrumentationConfig: { network: { ignoreUrls: ['https://example.com/endpoint/for/traces', 'https://example.com/endpoint/for/logs'], }, }, }); ``` -------------------------------- ### Use SDK APIs in Client Components (App Router) Source: https://github.com/embrace-io/embrace-web-sdk/blob/main/packages/web-sdk/NEXTJS.md After initializing the SDK, import and use its APIs within any Client Component. Ensure the initialization component is rendered before components that call SDK APIs. ```typescript 'use client'; import { session } from '@embrace-io/web-sdk'; export default function Checkout() { const handlePurchase = () => { session.addBreadcrumb('purchase_started'); // ... }; return ; } ``` -------------------------------- ### Run Full Integration Tests in Container Source: https://github.com/embrace-io/embrace-web-sdk/blob/main/DEVELOPING.md Execute integration tests within a container, mimicking the CI environment for a full test run. ```bash npm run test:integration:container ``` -------------------------------- ### Test Source Map Upload Source: https://github.com/embrace-io/embrace-web-sdk/blob/main/demo/frontend/README.md Commands to test the source map upload functionality using the Embrace web-cli. ```bash npm run build npm run upload-sourcemaps:dry npm run upload-sourcemaps ``` -------------------------------- ### Run Only Build Tests Source: https://github.com/embrace-io/embrace-web-sdk/blob/main/tests/integration/README.md Execute only the build tests for the SDK across various platforms and bundlers. This verifies the SDK builds correctly and checks bundle sizes. ```bash npm run build-platforms ``` -------------------------------- ### Set App Version with Embrace CLI Source: https://github.com/embrace-io/embrace-web-sdk/blob/main/packages/web-cli/README.md Inject the application version into your bundle using the CLI. This command is the same as uploading sourcemaps but includes the --app-version flag. ```sh npx embrace-web-cli upload -a "YOUR_EMBRACE_APP_ID" -t "YOUR_EMBRACE_UPLOAD_API_TOKEN" -p "BUILD_PATH" --app-version "APP_VERSION" ``` -------------------------------- ### Add Custom Instrumentations Source: https://github.com/embrace-io/embrace-web-sdk/blob/main/packages/web-sdk/README.md Include additional custom instrumentations by passing them in the `instrumentations` array during SDK initialization. Ensure custom instrumentations conform to the `Instrumentation` interface. ```typescript import { initSDK } from '@embrace-io/web-sdk'; initSDK({ appID: "YOUR_EMBRACE_APP_ID", appVersion: "YOUR_APP_VERSION", instrumentations: [myCustomInstrumentation], }); ``` -------------------------------- ### Run Function When SDK is Ready Source: https://github.com/embrace-io/embrace-web-sdk/blob/main/tests/performance/public/performance-test.html Ensures a given function is executed only after the Embrace Web SDK is ready. If the SDK is not yet ready, it queues the function to run when the SDK becomes available. ```javascript function runOnReady(fn) { if (sdkReady) { fn(); } else { window.EmbraceWebSdkOnReady.onReady(fn); } } ``` -------------------------------- ### Dynamically Create and Append Buttons Source: https://github.com/embrace-io/embrace-web-sdk/blob/main/tests/performance/public/performance-test.html Generates 100 button elements, assigns them unique IDs and text content, and appends them to the document body. Each button logs a message using the Embrace SDK when clicked, if the SDK is enabled. ```javascript // Insert 100 buttons for (let i = 0; i < 100; i++) { const button = document.createElement('button'); button.textContent = `Button ${i}`; button.id = `button-${i}`; button.onclick = () => { if (usesSDK) { window.EmbraceWebSdk.log.message('Test Message', 'info'); } }; document.body.appendChild(button); } ``` -------------------------------- ### Run End-to-End Tests Source: https://github.com/embrace-io/embrace-web-sdk/blob/main/tests/integration/README.md Execute the end-to-end tests after the build tests have been completed. These tests verify the built SDK functions correctly in real applications. ```bash # Build tests must run first npm run build-platforms # Then run e2e tests npx playwright test ``` -------------------------------- ### Run SDK Tests in Watch Mode Source: https://github.com/embrace-io/embrace-web-sdk/blob/main/DEVELOPING.md Run SDK tests in watch mode with debugging options enabled. ```sh npm run test:watch ``` -------------------------------- ### Handle Router Redirection in React Demo Source: https://github.com/embrace-io/embrace-web-sdk/blob/main/demo/frontend/index.html This script ensures users are redirected to the correct demo path, especially when accessing sub-routes of different router versions. It checks the current URL against expected paths for various router configurations and redirects if a mismatch is found. ```javascript const baseUrl = import.meta.env.BASE_URL; const path = window.location.pathname; const getRouterPath = routerName => { return baseUrl !== '/' ? `${baseUrl}${routerName}/` : `/${routerName}/`; }; if ( path.startsWith(getRouterPath('soft').replace(/\/$/, '')) && path !== getRouterPath('soft') ) { window.location.assign(getRouterPath('soft')); } else if ( path.startsWith(getRouterPath('react-router-v5').replace(/\/$/, '')) && path !== getRouterPath('react-router-v5') ) { window.location.assign(getRouterPath('react-router-v5')); } else if ( path.startsWith( getRouterPath('react-router-v6-declarative').replace(/\/$/, '') ) && path !== getRouterPath('react-router-v6-declarative') ) { window.location.assign(getRouterPath('react-router-v6-declarative')); } else if ( path.startsWith( getRouterPath('react-router-v6-data').replace(/\/$/, '') ) && path !== getRouterPath('react-router-v6-data') ) { window.location.assign(getRouterPath('react-router-v6-data')); } ``` -------------------------------- ### Run SDK Tests Manually Source: https://github.com/embrace-io/embrace-web-sdk/blob/main/DEVELOPING.md Run SDK tests in manual mode for debugging purposes, allowing breakpoints and console access. ```sh npm run test:manual ``` -------------------------------- ### Update CLI upload command from 1.x to 2.x Source: https://github.com/embrace-io/embrace-web-sdk/blob/main/packages/web-sdk/UPGRADING.md The CLI command for uploading source maps has changed. Version 2.x operates on a build folder path ('-p') instead of individual file paths ('-b', '-m'). ```shell npx embrace-web-cli upload --app-version "APP_VERSION" -a "YOUR_EMBRACE_APP_ID" -t "YOUR_EMBRACE_UPLOAD_API_TOKEN" -b "BUNDLE_PATH" -m "SOURCE_MAP_PATH" ``` ```shell npx embrace-web-cli upload --app-version "APP_VERSION" -a "YOUR_EMBRACE_APP_ID" -t "YOUR_EMBRACE_UPLOAD_API_TOKEN" -p "JS_BUILD_PATH" ``` -------------------------------- ### Access SDK Methods from Instance Source: https://github.com/embrace-io/embrace-web-sdk/blob/main/packages/web-sdk/README.md When `registerGlobally` is false, use the specific SDK instance (e.g., `embraceSDK`) to call SDK methods like `log.message`. ```typescript import { initSDK } from '@embrace-io/web-sdk'; const embraceSDK = initSDK({ appID: "YOUR_EMBRACE_APP_ID", appVersion: "YOUR_APP_VERSION", registerGlobally: false, // Prevents the SDK from registering itself globally }); // Use this embraceSDK.log.message('This is a log message', 'info'); // Instead of import { log } from '@embrace-io/web-sdk'; log.message('This is a log message', 'info'); ``` -------------------------------- ### Update Golden Files in Fast Iteration Mode Source: https://github.com/embrace-io/embrace-web-sdk/blob/main/DEVELOPING.md Update golden files for integration tests while using the fast iteration mode with running servers. ```bash npm run test:integration:container:test:update-golden ``` -------------------------------- ### Configure Local Collector URL Source: https://github.com/embrace-io/embrace-web-sdk/blob/main/server/README.md Update your frontend .env file to direct data to the local collector running on port 3001. ```dotenv # demo/frontend/.env VITE_DATA_URL=http://localhost:3001 ``` -------------------------------- ### Log Exception with Embrace SDK or Create Error Source: https://github.com/embrace-io/embrace-web-sdk/blob/main/tests/performance/public/performance-test.html Logs an exception using the Embrace Web SDK if it's enabled, otherwise it just creates an Error object. This is used to simulate exception occurrences for testing purposes. ```javascript function throwException() { if (usesSDK) { // Log an exception instead of throwing it so execution continues window.EmbraceWebSdk.log.logException(new Error()); } else { // Just create the error so at least we match the number of exceptions created const error = new Error('Test exception'); } } ``` -------------------------------- ### Migrate exports from 'sdk' to top-level in 1.x to 2.x Source: https://github.com/embrace-io/embrace-web-sdk/blob/main/packages/web-sdk/UPGRADING.md In version 2.x, exports like initSDK, DiagLogLevel, and Span are moved from the 'sdk' namespace to the top-level import. ```typescript import { sdk } from '@embrace-io/web-sdk'; sdk.initSDK({ appID: "YOUR_EMBRACE_APP_ID", appVersion: "YOUR_APP_VERSION", logLevel: sdk.DiagLogLevel.INFO, }); const myMethod = (span: sdk.Span) => { /* ... */ }; ``` ```typescript import { initSDK, DiagLogLevel, Span } from '@embrace-io/web-sdk'; initSDK({ appID: "YOUR_EMBRACE_APP_ID", appVersion: "YOUR_APP_VERSION", logLevel: DiagLogLevel.INFO, }); const myMethod = (span: Span) => { /* ... */ }; ``` -------------------------------- ### Incompatible Configurations with Network Span Forwarding Source: https://github.com/embrace-io/embrace-web-sdk/blob/main/packages/web-sdk/README.md Certain SDK configurations are incompatible with Network Span Forwarding and will disable the feature. These include setting registerGlobally to false, providing a custom propagator, or omitting both network instrumentations. ```typescript import { sdk } from '@embrace-io/web-sdk'; sdk.initSDK({ appID: "YOUR_EMBRACE_APP_ID", appVersion: "YOUR_APP_VERSION", // The following are not supported alongside Network Span Forwarding and will cause that feature to turn off: // 1. Setting registerGlobally to false registerGlobally: false, // 2. Providing a custom propagator propagator: myCustomPropagator, // 3. Omitting both network instrumentations omit: new Set(['@opentelemetry/instrumentation-fetch', '@opentelemetry/instrumentation-xml-http-request']), }); ``` -------------------------------- ### Configure Default Auto-Instrumentations Source: https://github.com/embrace-io/embrace-web-sdk/blob/main/packages/web-sdk/README.md Pass a `defaultInstrumentationConfig` object during SDK initialization to modify or disable default auto-instrumentations. Use the `omit` set to exclude specific instrumentations. ```typescript import { initSDK } from '@embrace-io/web-sdk'; initSDK({ appID: "YOUR_EMBRACE_APP_ID", appVersion: "YOUR_APP_VERSION", defaultInstrumentationConfig: { omit: new Set(['@opentelemetry/instrumentation-fetch']), }, }); ``` -------------------------------- ### Reset Container Dependencies Source: https://github.com/embrace-io/embrace-web-sdk/blob/main/DEVELOPING.md Reset the container image dependencies, typically needed after changes to package.json or other core dependencies. ```bash bash scripts/e2e-reset-deps.sh ``` -------------------------------- ### Configure Next.js to Suppress Server-Side Build Warning Source: https://github.com/embrace-io/embrace-web-sdk/blob/main/packages/web-sdk/NEXTJS.md Add `serverExternalPackages` to your Next.js configuration to silence the 'Critical dependency' warning related to `@opentelemetry/instrumentation` during server builds. This config tells Next.js to use native `require()` for the package on the server. ```typescript import type { NextConfig } from 'next'; const nextConfig: NextConfig = { serverExternalPackages: ['@opentelemetry/instrumentation'], }; export default nextConfig; ``` -------------------------------- ### End Embrace SDK Session and Flush Data Source: https://github.com/embrace-io/embrace-web-sdk/blob/main/tests/performance/public/performance-test.html Ends the current Embrace SDK session and flushes any pending data. This function should only be called if the SDK is being used. ```javascript function endSession() { if (!usesSDK) { return; } runOnReady(() => { window.EmbraceWebSdk.session.endSessionSpan(); client.flush(); }); } ``` -------------------------------- ### Update Golden Files for Integration Tests Source: https://github.com/embrace-io/embrace-web-sdk/blob/main/DEVELOPING.md Update the golden files used for integration test comparisons within a containerized environment. ```bash npm run test:integration:container:update-golden ``` -------------------------------- ### Update logging arguments from 0.x to 1.x Source: https://github.com/embrace-io/embrace-web-sdk/blob/main/packages/web-sdk/UPGRADING.md The arguments for `log.message` and `log.logException` have changed. In 1.x, options like `attributes` and `includeStacktrace` are passed as an object. ```typescript import { log } from '@embrace-io/web-sdk'; log.message('Loading not finished in time.', 'error', { keyA: 'valueA', keYB: 'valueB' }, true); // ... log.logException(err, true, { keyA: 'valueA' }, ts); ``` ```typescript import { log } from '@embrace-io/web-sdk'; log.message('Loading not finished in time.', 'error', { attributes: { keyA: 'valueA', keYB: 'valueB' }, includeStacktrace: true }); // ... log.logException(err, { handled: true, attributes: { keyA: 'valueA' }, timestamp: ts, }); ``` -------------------------------- ### Stop Integration Test Server Container Source: https://github.com/embrace-io/embrace-web-sdk/blob/main/DEVELOPING.md Stop the long-running server container after completing integration testing sessions. ```bash npm run test:integration:container:stop ``` -------------------------------- ### Run Function Multiple Times with Optional Delay Source: https://github.com/embrace-io/embrace-web-sdk/blob/main/tests/performance/public/performance-test.html Repeatedly executes a given asynchronous function a specified number of times, with an optional delay between each execution. It updates the application state to 'working' and 'idle' around the execution loop. ```javascript function runNTimes(fn, n, waitTime) { return async () => { setWorkingState(); for (let i = 0; i < n; i++) { await fn(i); if (waitTime) { await new Promise(resolve => setTimeout(resolve, waitTime)); } } setIdleState(); }; } ``` -------------------------------- ### Update Golden Files for Integration Tests Source: https://github.com/embrace-io/embrace-web-sdk/blob/main/tests/integration/README.md Update the golden files used for comparison in integration tests. This should be done after intentional SDK changes that affect test results. ```bash npm run test:integration:update-golden ``` -------------------------------- ### User Session Manager Public API Source: https://github.com/embrace-io/embrace-web-sdk/blob/main/packages/web-sdk/src/managers/EmbraceUserSessionManager/README.md Methods available for direct use by SDK consumers to interact with user session and session part management. ```APIDOC ## getUserSessionId() ### Description Retrieves the unique identifier (UUID) of the current user session. ### Method `getUserSessionId()` ### Returns - `string` | `null`: The user session UUID if a session is active, otherwise `null`. ## getPreviousUserSessionId() ### Description Retrieves the unique identifier (UUID) of the previous user session. ### Method `getPreviousUserSessionId()` ### Returns - `string` | `null`: The previous user session UUID if one exists, otherwise `null`. ## getUserSessionStartTime() ### Description Retrieves the start time of the current user session. ### Method `getUserSessionStartTime()` ### Returns - `number` | `null`: The start time in milliseconds since the Unix epoch if a session is active, otherwise `null`. ## endUserSession() ### Description Ends the current user session. This action is subject to a 5-second cooldown and has no effect if no user session is currently active. ### Method `endUserSession()` ### Behavior - Ends the current user session. - No-op if no user session is active. - If no session part is active when called, the user session ends silently. ## addBreadcrumb(name) ### Description Adds an `emb-breadcrumb` event to the active session-part span. This action is ignored if no session part is currently active. ### Method `addBreadcrumb(name: string)` ### Parameters #### Path Parameters - **name** (string) - Description of the breadcrumb event. ### Behavior - Adds an `emb-breadcrumb` event to the active session-part span. - Dropped if no session part is active. ## addProperty(key, value, options?) ### Description Stores a key-value pair as a property. Properties can be configured to be permanent, surviving user-session boundaries, or to live within the current user session state. ### Method `addProperty(key: string, value: any, options?: { lifespan: 'permanent' }) ### Parameters #### Path Parameters - **key** (string) - The key for the property. - **value** (any) - The value of the property. - **options** (object, optional) - Configuration options for the property. - **lifespan** ('permanent', optional) - If set to 'permanent', the property is written to `embrace_permanent_properties` and survives user-session boundaries. Otherwise, it resides within the current user session state. ### Behavior - Safe to call before the first session part starts; it eagerly creates a user-session row. - If `lifespan` is 'permanent', writes to `embrace_permanent_properties`. - Without `lifespan`, the entry is cleared on user-session end. ## removeProperty(key) ### Description Removes a property by its key from all storage locations. If a session part is active, the corresponding span attribute is also removed. ### Method `removeProperty(key: string)` ### Parameters #### Path Parameters - **key** (string) - The key of the property to remove. ### Behavior - Removes the key from all stores. - If a session part is active, removes the corresponding span attribute. ``` -------------------------------- ### Log Exception Source: https://github.com/embrace-io/embrace-web-sdk/blob/main/packages/web-sdk/README.md Manually logs a handled exception, including optional attributes. ```APIDOC ## log.logException ### Description Manually logs a handled exception. The SDK automatically captures unhandled exceptions. ### Method Signature log.logException(error: Error, options?: { handled: boolean, attributes?: Record }) ### Parameters #### Path Parameters - **error** (Error) - Required - The error object to log. - **options** (object) - Optional - Additional options for logging the exception. - **handled** (boolean) - Required - Indicates if the exception was handled. - **attributes** (object) - Optional - Custom key-value attributes to associate with the exception. ### Request Example ```typescript import { log } from '@embrace-io/web-sdk'; try { // some operation... } catch (e) { log.logException(e as Error, { handled: true, attributes: { propertyA: 'valueA', propertyB: 'valueB' } }); } ``` ``` -------------------------------- ### End-to-End Test Configuration Source: https://github.com/embrace-io/embrace-web-sdk/blob/main/tests/integration/README.md TypeScript code for configuring and running end-to-end tests, specifying the test name, URL, and expected number of spans. ```typescript import { runE2ETests } from '../../utils/index.ts'; runE2ETests({ name: ' ES2015', url: 'http://localhost:3001/platforms//es2015/index.html', // or custom server URL numberOfExpectedSpans: 3, // Adjust based on your app's auto-instrumentation }); ```