All files / packages/services/src sentryService.ts

86.73% Statements 85/98
100% Branches 81/81
60% Functions 15/25
94.31% Lines 83/88

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 3342x   2x 2x   2x   35x 34x     30x 1x     29x   29x 1x 1x     28x 28x               1x       27x 27x 27x   27x   27x   1x 1x         27x 2x   2x         1x         1x           2x         10x       108x       29x       1x                       10x 10x 1x     9x   9x   20x           9x 1x     8x 8x     8x       8x 5x     5x   5x       5x                 3x                     11x 1x       10x 10x   10x                                                                 10x                 2x 1x     1x                       9x   9x     9x             9x 2x   9x 9x 6x   9x   9x                   9x 5x               9x   9x                 9x               1x 1x 1x 1x                                                 2x         5x   2x 2x                         2x       2x  
import { Platform } from "react-native";
 
import * as Sentry from "@sentry/react-native";
import { Context, Effect, Layer } from "effect";
 
import { getPlatform } from "@repo/utils/platform";
 
export class SentryService {
  private isInitialized = false;
 
  initHostApp() {
    if (this.isInitialized) {
      return;
    }
 
    const dsn = process.env.SENTRY_DSN;
 
    if (!dsn) {
      this.isInitialized = true;
      return;
    }
 
    try {
      Sentry.init({
        dsn,
        sendDefaultPii: true,
        enableLogs: true,
        replaysSessionSampleRate: 0.1,
        replaysOnErrorSampleRate: 1,
        integrations: (integrations) => {
          // Add mobile replay for session replay on RN
          return integrations.concat([Sentry.mobileReplayIntegration()]);
        },
      });
 
      this.setTag("app", "host");
      this.setTag("platform", "react-native");
      this.setTag("mf_role", "host");
 
      this.setupModuleFederationErrorProcessor();
 
      this.isInitialized = true;
    } catch (error) {
      console.error("[Sentry] Initialization failed:", error);
      this.isInitialized = true;
    }
  }
 
  private setupModuleFederationErrorProcessor() {
    Sentry.addEventProcessor((event) => {
      const value = event.exception?.values?.[0]?.value;
 
      if (
        typeof value === "string" &&
        value.includes("[ Federation Runtime ]")
      ) {
        // Tag MF runtime errors for easier filtering/debugging
        event.tags = {
          ...(event.tags || {}),
          category: "module_federation",
          mf_error: "runtime_manifest",
        };
        event.extra = {
          ...(event.extra || {}),
          mf_raw_message: value,
        };
      }
 
      return event;
    });
  }
 
  private setUser(user: Sentry.User | null) {
    Sentry.setUser(user);
  }
 
  private setTag(key: string, value: string) {
    Sentry.setTag(key, value);
  }
 
  private setContext(name: string, context: Record<string, unknown>) {
    Sentry.setContext(name, context);
  }
 
  wrap<T>(component: T): T {
    return Sentry.wrap(
      component as unknown as Parameters<typeof Sentry.wrap>[0],
    ) as unknown as T;
  }
 
  private extractStackInfo(error: Error): {
    fileName?: string;
    lineNumber?: string;
    columnNumber?: string;
    functionName?: string;
    stackTrace?: string;
  } {
    const stack = error.stack;
    if (!stack) {
      return {};
    }
 
    const stackLines = stack.split("\n");
    // Pick first meaningful frame (skip libs/Sentry/self)
    const relevantFrame = stackLines.find(
      (line) =>
        line.includes("at ") &&
        !line.includes("node_modules") &&
        !line.includes("@sentry") &&
        !line.includes("sentryService"),
    );
 
    if (!relevantFrame) {
      return { stackTrace: stack };
    }
 
    const functionMatch = relevantFrame.match(/at\s+([^\s(]+)\s*\(/);
    const functionName = functionMatch ? functionMatch[1] : undefined;
 
    // Updated regex to require non-empty filePath (at least one character before colon)
    const fileMatch = relevantFrame.match(
      /(?:file:\/\/\/|file:\/\/)?(.+?):(\d+):(\d+)/,
    );
 
    if (fileMatch) {
      const [, filePath, line, column] = fileMatch;
 
      // Regex .+? ensures filePath is non-empty
      const srcIndex = filePath!.indexOf("/src/");
      const relativePath =
        srcIndex !== -1
          ? filePath!.substring(srcIndex + 1)
          : filePath!.split("/").slice(-3).join("/"); // fallback: last 3 segments
 
      return {
        fileName: relativePath,
        lineNumber: line,
        columnNumber: column,
        functionName: functionName !== "<anonymous>" ? functionName : undefined,
        stackTrace: stack,
      };
    }
 
    return { stackTrace: stack };
  }
 
  captureException(
    exception: unknown,
    hint?: {
      tags?: Record<string, string>;
      extra?: Record<string, unknown>;
      level?: Sentry.SeverityLevel;
    },
  ) {
    if (!this.isInitialized || !process.env.SENTRY_DSN) {
      return;
    }
 
    const error =
      exception instanceof Error ? exception : new Error(String(exception));
    const stackInfo = this.extractStackInfo(error);
 
    const enhancedHint = {
      ...hint,
      tags: {
        ...hint?.tags,
        ...(stackInfo.fileName && {
          file: stackInfo.fileName,
          ...(stackInfo.lineNumber && { line: stackInfo.lineNumber }),
        }),
        ...(stackInfo.functionName && { function: stackInfo.functionName }),
      },
      extra: {
        ...hint?.extra,
        debug: {
          fileName: stackInfo.fileName,
          lineNumber: stackInfo.lineNumber,
          columnNumber: stackInfo.columnNumber,
          functionName: stackInfo.functionName,
          ...(stackInfo.stackTrace && {
            stackTrace: stackInfo.stackTrace,
            stackPreview: stackInfo.stackTrace
              .split("\n")
              .slice(0, 5)
              .join("\n"),
          }),
        },
        ...(exception instanceof Error && {
          errorMessage: error.message,
          errorName: error.name,
        }),
      },
      level: hint?.level || ("error" as Sentry.SeverityLevel),
    };
 
    Sentry.captureException(exception, enhancedHint);
  }
 
  addBreadcrumb(breadcrumb: {
    message: string;
    level?: "debug" | "info" | "warning" | "error" | "fatal";
    category?: string;
    data?: Record<string, unknown>;
  }) {
    if (!this.isInitialized || !process.env.SENTRY_DSN) {
      return;
    }
 
    Sentry.addBreadcrumb(breadcrumb);
  }
 
  setAuthenticatedUser(params: {
    id: string;
    email?: string | null;
    username?: string | null;
    provider: string;
    feature?: string;
    additionalContext?: Record<string, unknown>;
  }) {
    const { id, email, username, provider, feature, additionalContext } =
      params;
 
    const emailDomain = email?.split("@")[1] || null;
 
    // Standard user context
    this.setUser({
      id,
      email: email ?? undefined,
      username: username ?? (email?.split("@")[0] || undefined),
      ip_address: "{{auto}}", // Sentry will auto-detect IP
    });
 
    if (feature) {
      this.setTag("feature", feature);
    }
    this.setTag("auth_provider", provider);
    if (emailDomain) {
      this.setTag("email_domain", emailDomain);
    }
    this.setTag("platform", getPlatform());
 
    const authContext: Record<string, unknown> = {
      provider,
      uid: id,
      email: email ?? null,
      name: username ?? null,
      loginMethod: provider,
      loginTimestamp: new Date().toISOString(),
      ...additionalContext,
    };
 
    if (provider === "google") {
      authContext.google = {
        emailDomain,
        hasEmail: !!email,
        hasDisplayName: !!username,
        ...(additionalContext?.google || {}),
      };
    }
 
    this.setContext("auth", authContext);
 
    this.setContext("user", {
      id,
      email: email ?? null,
      username: username ?? null,
      name: username ?? email?.split("@")[0] ?? null,
      provider,
      ...(additionalContext?.user || {}),
    });
 
    this.setContext("device", {
      platform: getPlatform(),
      platformVersion: Platform.Version,
      ...(additionalContext?.device || {}),
    });
  }
 
  clearAuthenticatedUser() {
    this.setUser(null);
    this.setTag("auth_provider", "anonymous");
    this.setContext("auth", {});
    this.setContext("user", {});
  }
}
 
// --- Effect Implementation ---
 
type CaptureExceptionHint = Parameters<SentryService["captureException"]>[1];
type Breadcrumb = Parameters<SentryService["addBreadcrumb"]>[0];
type SetAuthenticatedUserParams = Parameters<
  SentryService["setAuthenticatedUser"]
>[0];
 
export interface SentryServiceEffect {
  readonly initHostApp: () => Effect.Effect<void>;
  readonly captureException: (
    exception: unknown,
    hint?: CaptureExceptionHint,
  ) => Effect.Effect<void>;
  readonly addBreadcrumb: (breadcrumb: Breadcrumb) => Effect.Effect<void>;
  readonly setAuthenticatedUser: (
    params: SetAuthenticatedUserParams,
  ) => Effect.Effect<void>;
  readonly clearAuthenticatedUser: () => Effect.Effect<void>;
}
 
export const SentryServiceEffect = Context.GenericTag<SentryServiceEffect>(
  "@repo/services/SentryService",
);
 
// Export singleton instance for legacy usage and keep Effect layer on the same instance.
export const sentryService = new SentryService();
 
export const makeSentryService = (service: SentryService = sentryService) => {
  return SentryServiceEffect.of({
    initHostApp: () => Effect.sync(() => service.initHostApp()),
    captureException: (exception, hint) =>
      Effect.sync(() => service.captureException(exception, hint)),
    addBreadcrumb: (breadcrumb) =>
      Effect.sync(() => service.addBreadcrumb(breadcrumb)),
    setAuthenticatedUser: (params) =>
      Effect.sync(() => service.setAuthenticatedUser(params)),
    clearAuthenticatedUser: () =>
      Effect.sync(() => service.clearAuthenticatedUser()),
  });
};
 
export const SentryLive = Layer.succeed(
  SentryServiceEffect,
  makeSentryService(),
);
export default sentryService;