Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,10 @@

## Unreleased

### Features

- Automatically detect Release name and version for Expo Web ([#4967](https://github.com/getsentry/sentry-react-native/pull/4967))

### Fixes

- ignoreError now filters Native errors ([#4948](https://github.com/getsentry/sentry-react-native/pull/4948))
Expand Down
2 changes: 2 additions & 0 deletions packages/core/src/js/sdk.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ import { ReactNativeProfiler } from './tracing';
import { useEncodePolyfill } from './transports/encodePolyfill';
import { DEFAULT_BUFFER_SIZE, makeNativeTransportFactory } from './transports/native';
import { getDefaultEnvironment, isExpoGo, isRunningInMetroDevServer, isWeb } from './utils/environment';
import { getDefaultRelease } from './utils/release';
import { safeFactory, safeTracesSampler } from './utils/safe';
import { NATIVE } from './wrapper';

Expand Down Expand Up @@ -111,6 +112,7 @@ export function init(passedOptions: ReactNativeOptions): void {
const options: ReactNativeClientOptions = {
...DEFAULT_OPTIONS,
...passedOptions,
release: passedOptions.release ?? getDefaultRelease(),
enableNative,
enableNativeNagger: shouldEnableNativeNagger(passedOptions.enableNativeNagger),
// If custom transport factory fails the SDK won't initialize
Expand Down
13 changes: 11 additions & 2 deletions packages/core/src/js/tools/metroconfig.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,8 @@ import {
setSentryBabelTransformerOptions,
setSentryDefaultBabelTransformerPathEnv,
} from './sentryBabelTransformerUtils';
import { createSentryMetroSerializer, unstable_beforeAssetSerializationPlugin } from './sentryMetroSerializer';
import { createSentryMetroSerializer, unstableBeforeAssetSerializationDebugIdPlugin } from './sentryMetroSerializer';
import { unstableReleaseConstantsPlugin } from './sentryReleaseInjector';
import type { DefaultConfigOptions } from './vendor/expo/expoconfig';

export * from './sentryMetroSerializer';
Expand Down Expand Up @@ -44,6 +45,13 @@ export interface SentryExpoConfigOptions {
* Pass a custom `getDefaultConfig` function to override the default Expo configuration getter.
*/
getDefaultConfig?: typeof getSentryExpoConfig;

/**
* For Expo Web, inject `release` and `version` options from `app.json`, the Expo Application Config.
*
* @default true
*/
injectReleaseForWeb?: boolean;
}

/**
Expand Down Expand Up @@ -93,7 +101,8 @@ export function getSentryExpoConfig(
...options,
unstable_beforeAssetSerializationPlugins: [
...(options.unstable_beforeAssetSerializationPlugins || []),
unstable_beforeAssetSerializationPlugin,
...(options.injectReleaseForWeb ?? true ? [unstableReleaseConstantsPlugin(projectRoot)] : []),
unstableBeforeAssetSerializationDebugIdPlugin,
],
});

Expand Down
59 changes: 12 additions & 47 deletions packages/core/src/js/tools/sentryMetroSerializer.ts
Original file line number Diff line number Diff line change
@@ -1,24 +1,28 @@
import * as crypto from 'crypto';
// eslint-disable-next-line import/no-extraneous-dependencies
import type { MixedOutput, Module, ReadOnlyGraph } from 'metro';
// eslint-disable-next-line import/no-extraneous-dependencies
import * as countLines from 'metro/src/lib/countLines';
import type { Bundle, MetroSerializer, MetroSerializerOutput, SerializedBundle, VirtualJSOutput } from './utils';
import { createDebugIdSnippet, createSet, determineDebugIdFromBundleSource, stringToUUID } from './utils';
import {
createDebugIdSnippet,
createVirtualJSModule,
determineDebugIdFromBundleSource,
prependModule,
stringToUUID,
} from './utils';
import { createDefaultMetroSerializer } from './vendor/metro/utils';

type SourceMap = Record<string, unknown>;

const DEBUG_ID_PLACE_HOLDER = '__debug_id_place_holder__';
const DEBUG_ID_MODULE_PATH = '__debugid__';
const PRELUDE_MODULE_PATH = '__prelude__';

const SOURCE_MAP_COMMENT = '//# sourceMappingURL=';
const DEBUG_ID_COMMENT = '//# debugId=';

/**
* Adds Sentry Debug ID polyfill module to the bundle.
*/
export function unstable_beforeAssetSerializationPlugin({
export function unstableBeforeAssetSerializationDebugIdPlugin({
premodules,
debugId,
}: {
Expand All @@ -38,7 +42,7 @@ export function unstable_beforeAssetSerializationPlugin({
}

const debugIdModule = createDebugIdModule(debugId);
return [...addDebugIdModule(premodules, debugIdModule)];
return prependModule(premodules, debugIdModule);
}

/**
Expand All @@ -63,7 +67,7 @@ export const createSentryMetroSerializer = (customSerializer?: MetroSerializer):

const debugIdModule = createDebugIdModule(DEBUG_ID_PLACE_HOLDER);
options.sentryBundleCallback = createSentryBundleCallback(debugIdModule);
const modifiedPreModules = addDebugIdModule(preModules, debugIdModule);
const modifiedPreModules = prependModule(preModules, debugIdModule);

// Run wrapped serializer
const serializerResult = serializer(entryPoint, modifiedPreModules, graph, options);
Expand Down Expand Up @@ -120,25 +124,6 @@ function createSentryBundleCallback(debugIdModule: Module<VirtualJSOutput> & { s
};
}

function addDebugIdModule(
preModules: readonly Module<MixedOutput>[],
debugIdModule: Module<VirtualJSOutput>,
): readonly Module<MixedOutput>[] {
const modifiedPreModules = [...preModules];
if (
modifiedPreModules.length > 0 &&
modifiedPreModules[0] !== undefined &&
modifiedPreModules[0].path === PRELUDE_MODULE_PATH
) {
// prelude module must be first as it measures the bundle startup time
modifiedPreModules.unshift(preModules[0] as Module<VirtualJSOutput>);
modifiedPreModules[1] = debugIdModule;
} else {
modifiedPreModules.unshift(debugIdModule);
}
return modifiedPreModules;
}

async function extractSerializerResult(serializerResult: MetroSerializerOutput): Promise<SerializedBundle> {
if (typeof serializerResult === 'string') {
return { code: serializerResult, map: '{}' };
Expand All @@ -157,27 +142,7 @@ async function extractSerializerResult(serializerResult: MetroSerializerOutput):
}

function createDebugIdModule(debugId: string): Module<VirtualJSOutput> & { setSource: (code: string) => void } {
let debugIdCode = createDebugIdSnippet(debugId);

return {
setSource: (code: string) => {
debugIdCode = code;
},
dependencies: new Map(),
getSource: () => Buffer.from(debugIdCode),
inverseDependencies: createSet(),
path: DEBUG_ID_MODULE_PATH,
output: [
{
type: 'js/script/virtual',
data: {
code: debugIdCode,
lineCount: countLines(debugIdCode),
map: [],
},
},
],
};
return createVirtualJSModule(DEBUG_ID_MODULE_PATH, createDebugIdSnippet(debugId));
}

function calculateDebugId(bundle: Bundle): string {
Expand Down
46 changes: 46 additions & 0 deletions packages/core/src/js/tools/sentryReleaseInjector.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
// eslint-disable-next-line import/no-extraneous-dependencies
import type { MixedOutput, Module, ReadOnlyGraph } from 'metro';
import type { VirtualJSOutput } from './utils';
import { createVirtualJSModule, getExpoConfig, prependModule } from './utils';

const RELEASE_CONSTANTS_MODULE_PATH = '__sentryReleaseConstants__';

/**
* Adds Sentry Release constants to the bundle.
*/
export const unstableReleaseConstantsPlugin =
(projectRoot: string) =>
({ graph, premodules }: { graph: ReadOnlyGraph<MixedOutput>; premodules: Module[]; debugId?: string }): Module[] => {
const notWeb = graph.transformOptions.platform !== 'web';
if (notWeb) {
return premodules;
}

const { name, version } = getExpoConfig(projectRoot);

if (!name || !version) {
return premodules;
}

return prependModule(
premodules,
createSentryReleaseModule({
name,
version,
}),
);
};

function createSentryReleaseModule({
name,
version,
}: {
name: string;
version: string;
}): Module<VirtualJSOutput> & { setSource: (code: string) => void } {
return createVirtualJSModule(RELEASE_CONSTANTS_MODULE_PATH, createReleaseConstantsSnippet({ name, version }));
}

function createReleaseConstantsSnippet({ name, version }: { name: string; version: string }): string {
return `var SENTRY_RELEASE;SENTRY_RELEASE={name: "${name}", version: "${version}"};`;
}
84 changes: 83 additions & 1 deletion packages/core/src/js/tools/utils.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
import * as crypto from 'crypto';
// eslint-disable-next-line import/no-extraneous-dependencies
import type { Module, ReadOnlyGraph, SerializerOptions } from 'metro';
import type { MixedOutput, Module, ReadOnlyGraph, SerializerOptions } from 'metro';
// eslint-disable-next-line import/no-extraneous-dependencies
import type CountingSet from 'metro/src/lib/CountingSet';
// eslint-disable-next-line import/no-extraneous-dependencies
import * as countLines from 'metro/src/lib/countLines';

// Variant of MixedOutput
// https://github.com/facebook/metro/blob/9b85f83c9cc837d8cd897aa7723be7da5b296067/packages/metro/src/DeltaBundler/types.flow.js#L21
Expand Down Expand Up @@ -98,3 +100,83 @@ function resolveSetCreator(): () => CountingSet<string> {
}

export const createSet = resolveSetCreator();

const PRELUDE_MODULE_PATH = '__prelude__';

/**
* Prepends the module after default required prelude modules.
*/
export function prependModule(
modules: readonly Module<MixedOutput>[],
module: Module<VirtualJSOutput>,
): Module<MixedOutput>[] {
const modifiedPreModules = [...modules];
if (
modifiedPreModules.length > 0 &&
modifiedPreModules[0] !== undefined &&
modifiedPreModules[0].path === PRELUDE_MODULE_PATH
) {
// prelude module must be first as it measures the bundle startup time
modifiedPreModules.unshift(modules[0] as Module<VirtualJSOutput>);
modifiedPreModules[1] = module;
} else {
modifiedPreModules.unshift(module);
}
return modifiedPreModules;
}

/**
* Creates a virtual JS module with the given path and code.
*/
export function createVirtualJSModule(
modulePath: string,
moduleCode: string,
): Module<VirtualJSOutput> & { setSource: (code: string) => void } {
let sourceCode = moduleCode;

return {
setSource: (code: string) => {
sourceCode = code;
},
dependencies: new Map(),
getSource: () => Buffer.from(sourceCode),
inverseDependencies: createSet(),
path: modulePath,
output: [
{
type: 'js/script/virtual',
data: {
code: sourceCode,
lineCount: countLines(sourceCode),
map: [],
},
},
],
};
}

/**
* Tries to load Expo config using `@expo/config` package.
*/
export function getExpoConfig(projectRoot: string): Partial<{
name: string;
version: string;
}> {
try {
// eslint-disable-next-line @typescript-eslint/no-var-requires, import/no-extraneous-dependencies
const expoConfig = require('@expo/config') as {
getConfig?: (projectRoot: string) => { exp: Record<string, unknown> };
};
if (expoConfig.getConfig) {
const { exp } = expoConfig.getConfig(projectRoot);
return {
name: typeof exp.name === 'string' && exp.name ? exp.name : undefined,
version: typeof exp.version === 'string' && exp.version ? exp.version : undefined,
};
}
} catch {
// @expo/config not available, do nothing
}

return {};
}
33 changes: 33 additions & 0 deletions packages/core/src/js/utils/release.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import { notWeb } from './environment';
import { RN_GLOBAL_OBJ } from './worldwide';

/**
*
*/
export function createReleaseFromGlobalReleaseConstants(): string | undefined {
const globalRelease = RN_GLOBAL_OBJ.SENTRY_RELEASE;
if (!globalRelease) {
return undefined;
}

const { name, version } = globalRelease;
if (!name || !version) {
return undefined;
}

return `${name}@${version}`;
}

/**
*
*/
export function getDefaultRelease(): string | undefined {
if (notWeb()) {
// Mobile platforms use native release from the Release integration.
return undefined;
}

// Web platforms (Expo Web) use the global release constants.
// Release set in the options is need for Session and Replay integrations.
return createReleaseFromGlobalReleaseConstants();
}
6 changes: 6 additions & 0 deletions packages/core/src/js/utils/worldwide.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,12 @@ export interface ReactNativeInternalGlobal extends InternalGlobal {
nativePerformanceNow?: () => number;
TextEncoder?: TextEncoder;
alert?: (message: string) => void;
SENTRY_RELEASE?: {
/** Used by Sentry Webpack Plugin, not used by RN, only to silence TS */
id?: string;
name?: string;
version?: string;
};
}

type TextEncoder = {
Expand Down
Loading