Skip to content

ref: Use optional chaining where possible #14954

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Jan 9, 2025
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
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ const oldOnError = window.onerror;

window.onerror = function () {
console.log('custom error');
oldOnError && oldOnError.apply(this, arguments);
oldOnError?.apply(this, arguments);
};

window.doSomethingWrong();
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ Sentry.init({
// Also, no SDK has mock utils for FlagUsedHandler's.
const MockLaunchDarkly = {
initialize(_clientId, context, options) {
const flagUsedHandler = options && options.inspectors ? options.inspectors[0].method : undefined;
const flagUsedHandler = options.inspectors ? options.inspectors[0].method : undefined;

return {
variation(key, defaultValue) {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
const sentryCarrier = window && window.__SENTRY__;
const sentryCarrier = window?.__SENTRY__;

/**
* Simulate an old pre v8 SDK obtaining the hub from the global sentry carrier
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
const sentryCarrier = window && window.__SENTRY__;
const sentryCarrier = window?.__SENTRY__;

/**
* Simulate an old pre v8 SDK obtaining the hub from the global sentry carrier
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ export default function LoaderError() {

return (
<div>
<h1>{data && data.test ? data.test : 'Not Found'}</h1>
<h1>{data?.test ? data.test : 'Not Found'}</h1>
</div>
);
}
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ export default function LoaderError() {

return (
<div>
<h1>{data && data.test ? data.test : 'Not Found'}</h1>
<h1>{data?.test ? data.test : 'Not Found'}</h1>
</div>
);
}
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ export default function LoaderError() {

return (
<div>
<h1>{data && data.test ? data.test : 'Not Found'}</h1>
<h1>{data?.test ? data.test : 'Not Found'}</h1>
</div>
);
}
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ export default function LoaderError() {

return (
<div>
<h1>{data && data.test ? data.test : 'Not Found'}</h1>
<h1>{data?.test ? data.test : 'Not Found'}</h1>
</div>
);
}
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ export default function LoaderError() {

return (
<div>
<h1>{data && data.test ? data.test : 'Not Found'}</h1>
<h1>{data?.test ? data.test : 'Not Found'}</h1>
</div>
);
}
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ export default function LoaderError() {

return (
<div>
<h1>{data && data.test ? data.test : 'Not Found'}</h1>
<h1>{data?.test ? data.test : 'Not Found'}</h1>
</div>
);
}
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ export default function LoaderError() {

return (
<div>
<h1>{data && data.test ? data.test : 'Not Found'}</h1>
<h1>{data?.test ? data.test : 'Not Found'}</h1>
</div>
);
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { registerDeprecationHandler } from '@ember/debug';

export function initialize(): void {
registerDeprecationHandler((message, options, next) => {
if (options && options.until && options.until !== '3.0.0') {
if (options?.until && options.until !== '3.0.0') {
return;
} else {
next(message, options);
Expand Down
8 changes: 3 additions & 5 deletions packages/angular/patch-vitest.ts
Original file line number Diff line number Diff line change
Expand Up @@ -182,22 +182,20 @@ function isAngularFixture(val: any): boolean {
*/
function fixtureVitestSerializer(fixture: any) {
// * Get Component meta data
const componentType = (
fixture && fixture.componentType ? fixture.componentType : fixture.componentRef.componentType
) as any;
const componentType = (fixture?.componentType ? fixture.componentType : fixture.componentRef.componentType) as any;

let inputsData: string = '';

const selector = Reflect.getOwnPropertyDescriptor(componentType, '__annotations__')?.value[0].selector;

if (componentType && componentType.propDecorators) {
if (componentType?.propDecorators) {
inputsData = Object.entries(componentType.propDecorators)
.map(([key, value]) => `${key}="${value}"`)
.join('');
}

// * Get DOM Elements
const divElement = fixture && fixture.nativeElement ? fixture.nativeElement : fixture.location.nativeElement;
const divElement = fixture?.nativeElement ? fixture.nativeElement : fixture.location.nativeElement;

// * Convert string data to HTML data
const doc = new DOMParser().parseFromString(
Expand Down
2 changes: 1 addition & 1 deletion packages/angular/src/sdk.ts
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ export function init(options: BrowserOptions): Client | undefined {
function checkAndSetAngularVersion(): void {
const ANGULAR_MINIMUM_VERSION = 14;

const angularVersion = VERSION && VERSION.major ? parseInt(VERSION.major, 10) : undefined;
const angularVersion = VERSION?.major && parseInt(VERSION.major, 10);

if (angularVersion) {
if (angularVersion < ANGULAR_MINIMUM_VERSION) {
Expand Down
8 changes: 4 additions & 4 deletions packages/angular/src/tracing.ts
Original file line number Diff line number Diff line change
Expand Up @@ -322,7 +322,7 @@ export function TraceClass(options?: TraceClassOptions): ClassDecorator {
tracingSpan = runOutsideAngular(() =>
startInactiveSpan({
onlyIfParent: true,
name: `<${options && options.name ? options.name : 'unnamed'}>`,
name: `<${options?.name || 'unnamed'}>`,
op: ANGULAR_INIT_OP,
attributes: {
[SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.ui.angular.trace_class_decorator',
Expand Down Expand Up @@ -367,7 +367,7 @@ export function TraceMethod(options?: TraceMethodOptions): MethodDecorator {
runOutsideAngular(() => {
startInactiveSpan({
onlyIfParent: true,
name: `<${options && options.name ? options.name : 'unnamed'}>`,
name: `<${options?.name ? options.name : 'unnamed'}>`,
op: `${ANGULAR_OP}.${String(propertyKey)}`,
startTime: now,
attributes: {
Expand Down Expand Up @@ -397,9 +397,9 @@ export function TraceMethod(options?: TraceMethodOptions): MethodDecorator {
export function getParameterizedRouteFromSnapshot(route?: ActivatedRouteSnapshot | null): string {
const parts: string[] = [];

let currentRoute = route && route.firstChild;
let currentRoute = route?.firstChild;
while (currentRoute) {
const path = currentRoute && currentRoute.routeConfig && currentRoute.routeConfig.path;
const path = currentRoute?.routeConfig && currentRoute.routeConfig.path;
if (path === null || path === undefined) {
break;
}
Expand Down
10 changes: 6 additions & 4 deletions packages/astro/src/server/middleware.ts
Original file line number Diff line number Diff line change
Expand Up @@ -87,11 +87,13 @@ async function instrumentRequest(
isolationScope?: Scope,
): Promise<Response> {
// Make sure we don't accidentally double wrap (e.g. user added middleware and integration auto added it)
const locals = ctx.locals as AstroLocalsWithSentry;
if (locals && locals.__sentry_wrapped__) {
const locals = ctx.locals as AstroLocalsWithSentry | undefined;
if (locals?.__sentry_wrapped__) {
return next();
}
addNonEnumerableProperty(locals, '__sentry_wrapped__', true);
if (locals) {
addNonEnumerableProperty(locals, '__sentry_wrapped__', true);
}

const isDynamicPageRequest = checkIsDynamicPageRequest(ctx);

Expand Down Expand Up @@ -164,7 +166,7 @@ async function instrumentRequest(
const client = getClient();
const contentType = originalResponse.headers.get('content-type');

const isPageloadRequest = contentType && contentType.startsWith('text/html');
const isPageloadRequest = contentType?.startsWith('text/html');
if (!isPageloadRequest || !client) {
return originalResponse;
}
Expand Down
2 changes: 1 addition & 1 deletion packages/aws-serverless/src/sdk.ts
Original file line number Diff line number Diff line change
Expand Up @@ -323,7 +323,7 @@ export function wrapHandler<TEvent, TResult>(
throw e;
} finally {
clearTimeout(timeoutWarningTimer);
if (span && span.isRecording()) {
if (span?.isRecording()) {
span.end();
}
await flush(options.flushTimeout).catch(e => {
Expand Down
2 changes: 1 addition & 1 deletion packages/aws-serverless/src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ export function getAwsTraceData(event: HandlerEvent, context?: HandlerContext):
baggage: headers.baggage,
};

if (context && context.clientContext && context.clientContext.Custom) {
if (context?.clientContext?.Custom) {
const customContext: Record<string, unknown> = context.clientContext.Custom;
const sentryTrace = isString(customContext['sentry-trace']) ? customContext['sentry-trace'] : undefined;

Expand Down
3 changes: 1 addition & 2 deletions packages/browser-utils/src/instrument/dom.ts
Original file line number Diff line number Diff line change
Expand Up @@ -64,8 +64,7 @@ export function instrumentDOM(): void {
// guaranteed to fire at least once.)
['EventTarget', 'Node'].forEach((target: string) => {
const globalObject = WINDOW as unknown as Record<string, { prototype?: object }>;
const targetObj = globalObject[target];
const proto = targetObj && targetObj.prototype;
const proto = globalObject[target]?.prototype;

// eslint-disable-next-line no-prototype-builtins
if (!proto || !proto.hasOwnProperty || !proto.hasOwnProperty('addEventListener')) {
Expand Down
2 changes: 1 addition & 1 deletion packages/browser-utils/src/metrics/browserMetrics.ts
Original file line number Diff line number Diff line change
Expand Up @@ -674,7 +674,7 @@ function _setWebVitalAttributes(span: Span): void {
}

// See: https://developer.mozilla.org/en-US/docs/Web/API/LayoutShift
if (_clsEntry && _clsEntry.sources) {
if (_clsEntry?.sources) {
_clsEntry.sources.forEach((source, index) =>
span.setAttribute(`cls.source.${index + 1}`, htmlTreeAsString(source.node)),
);
Expand Down
14 changes: 8 additions & 6 deletions packages/browser-utils/src/metrics/cls.ts
Original file line number Diff line number Diff line change
Expand Up @@ -77,26 +77,28 @@ export function trackClsAsStandaloneSpan(): void {
});

const activeSpan = getActiveSpan();
const rootSpan = activeSpan && getRootSpan(activeSpan);
const spanJSON = rootSpan && spanToJSON(rootSpan);
if (spanJSON && spanJSON.op === 'pageload') {
pageloadSpanId = rootSpan.spanContext().spanId;
if (activeSpan) {
const rootSpan = getRootSpan(activeSpan);
const spanJSON = spanToJSON(rootSpan);
if (spanJSON.op === 'pageload') {
pageloadSpanId = rootSpan.spanContext().spanId;
}
}
}, 0);
}

function sendStandaloneClsSpan(clsValue: number, entry: LayoutShift | undefined, pageloadSpanId: string) {
DEBUG_BUILD && logger.log(`Sending CLS span (${clsValue})`);

const startTime = msToSec((browserPerformanceTimeOrigin || 0) + ((entry && entry.startTime) || 0));
const startTime = msToSec((browserPerformanceTimeOrigin || 0) + (entry?.startTime || 0));
const routeName = getCurrentScope().getScopeData().transactionName;

const name = entry ? htmlTreeAsString(entry.sources[0] && entry.sources[0].node) : 'Layout shift';

const attributes: SpanAttributes = dropUndefinedKeys({
[SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.http.browser.cls',
[SEMANTIC_ATTRIBUTE_SENTRY_OP]: 'ui.webvital.cls',
[SEMANTIC_ATTRIBUTE_EXCLUSIVE_TIME]: (entry && entry.duration) || 0,
[SEMANTIC_ATTRIBUTE_EXCLUSIVE_TIME]: entry?.duration || 0,
// attach the pageload span id to the CLS span so that we can link them in the UI
'sentry.pageload.span_id': pageloadSpanId,
});
Expand Down
4 changes: 2 additions & 2 deletions packages/browser-utils/src/metrics/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@ export function startStandaloneWebVitalSpan(options: StandaloneWebVitalSpanOptio
// We need to get the replay, user, and activeTransaction from the current scope
// so that we can associate replay id, profile id, and a user display to the span
const replay = client.getIntegrationByName<Integration & { getReplayId: () => string }>('Replay');
const replayId = replay && replay.getReplayId();
const replayId = replay?.getReplayId();

const scope = getCurrentScope();

Expand Down Expand Up @@ -124,7 +124,7 @@ export function startStandaloneWebVitalSpan(options: StandaloneWebVitalSpanOptio
/** Get the browser performance API. */
export function getBrowserPerformanceAPI(): Performance | undefined {
// @ts-expect-error we want to make sure all of these are available, even if TS is sure they are
return WINDOW && WINDOW.addEventListener && WINDOW.performance;
return WINDOW.addEventListener && WINDOW.performance;
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,5 +18,5 @@ import { getNavigationEntry } from './getNavigationEntry';

export const getActivationStart = (): number => {
const navEntry = getNavigationEntry();
return (navEntry && navEntry.activationStart) || 0;
return navEntry?.activationStart || 0;
};
14 changes: 7 additions & 7 deletions packages/browser/src/eventbuilder.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ function eventFromPlainObject(
isUnhandledRejection?: boolean,
): Event {
const client = getClient();
const normalizeDepth = client && client.getOptions().normalizeDepth;
const normalizeDepth = client?.getOptions().normalizeDepth;

// If we can, we extract an exception from the object properties
const errorFromProp = getErrorPropertyFromObject(exception);
Expand Down Expand Up @@ -178,7 +178,7 @@ function isWebAssemblyException(exception: unknown): exception is WebAssembly.Ex
* Usually, this is the `name` property on Error objects but WASM errors need to be treated differently.
*/
export function extractType(ex: Error & { message: { error?: Error } }): string | undefined {
const name = ex && ex.name;
const name = ex?.name;

// The name for WebAssembly.Exception Errors needs to be extracted differently.
// Context: https://github.com/getsentry/sentry-javascript/issues/13787
Expand All @@ -197,7 +197,7 @@ export function extractType(ex: Error & { message: { error?: Error } }): string
* In this specific case we try to extract stacktrace.message.error.message
*/
export function extractMessage(ex: Error & { message: { error?: Error } }): string {
const message = ex && ex.message;
const message = ex?.message;

if (!message) {
return 'No error message';
Expand Down Expand Up @@ -225,11 +225,11 @@ export function eventFromException(
hint?: EventHint,
attachStacktrace?: boolean,
): PromiseLike<Event> {
const syntheticException = (hint && hint.syntheticException) || undefined;
const syntheticException = hint?.syntheticException || undefined;
const event = eventFromUnknownInput(stackParser, exception, syntheticException, attachStacktrace);
addExceptionMechanism(event); // defaults to { type: 'generic', handled: true }
event.level = 'error';
if (hint && hint.event_id) {
if (hint?.event_id) {
event.event_id = hint.event_id;
}
return resolvedSyncPromise(event);
Expand All @@ -246,10 +246,10 @@ export function eventFromMessage(
hint?: EventHint,
attachStacktrace?: boolean,
): PromiseLike<Event> {
const syntheticException = (hint && hint.syntheticException) || undefined;
const syntheticException = hint?.syntheticException || undefined;
const event = eventFromString(stackParser, message, syntheticException, attachStacktrace);
event.level = level;
if (hint && hint.event_id) {
if (hint?.event_id) {
event.event_id = hint.event_id;
}
return resolvedSyncPromise(event);
Expand Down
2 changes: 1 addition & 1 deletion packages/browser/src/integrations/breadcrumbs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -313,7 +313,7 @@ function _getFetchBreadcrumbHandler(client: Client): (handlerData: HandlerDataFe

breadcrumbData.request_body_size = handlerData.fetchData.request_body_size;
breadcrumbData.response_body_size = handlerData.fetchData.response_body_size;
breadcrumbData.status_code = response && response.status;
breadcrumbData.status_code = response?.status;

const hint: FetchBreadcrumbHint = {
input: handlerData.args,
Expand Down
3 changes: 1 addition & 2 deletions packages/browser/src/integrations/browserapierrors.ts
Original file line number Diff line number Diff line change
Expand Up @@ -163,8 +163,7 @@ function _wrapXHR(originalSend: () => void): () => void {

function _wrapEventTarget(target: string): void {
const globalObject = WINDOW as unknown as Record<string, { prototype?: object }>;
const targetObj = globalObject[target];
const proto = targetObj && targetObj.prototype;
const proto = globalObject[target]?.prototype;

// eslint-disable-next-line no-prototype-builtins
if (!proto || !proto.hasOwnProperty || !proto.hasOwnProperty('addEventListener')) {
Expand Down
2 changes: 1 addition & 1 deletion packages/browser/src/integrations/contextlines.ts
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ function addSourceContext(event: Event, contextLines: number): Event {

exceptions.forEach(exception => {
const stacktrace = exception.stacktrace;
if (stacktrace && stacktrace.frames) {
if (stacktrace?.frames) {
stacktrace.frames = stacktrace.frames.map(frame =>
applySourceContextToFrame(frame, htmlLines, htmlFilename, contextLines),
);
Expand Down
2 changes: 1 addition & 1 deletion packages/browser/src/integrations/globalhandlers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -194,7 +194,7 @@ function globalHandlerLog(type: string): void {

function getOptions(): { stackParser: StackParser; attachStacktrace?: boolean } {
const client = getClient<BrowserClient>();
const options = (client && client.getOptions()) || {
const options = client?.getOptions() || {
stackParser: () => [],
attachStacktrace: false,
};
Expand Down
2 changes: 1 addition & 1 deletion packages/browser/src/integrations/spotlight.ts
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,6 @@ export function isSpotlightInteraction(event: Event): boolean {
event.contexts &&
event.contexts.trace &&
event.contexts.trace.op === 'ui.action.click' &&
event.spans.some(({ description }) => description && description.includes('#sentry-spotlight')),
event.spans.some(({ description }) => description?.includes('#sentry-spotlight')),
);
}
2 changes: 1 addition & 1 deletion packages/browser/src/profiling/integration.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ const _browserProfilingIntegration = (() => {
const profilesToAddToEnvelope: Profile[] = [];

for (const profiledTransaction of profiledTransactionEvents) {
const context = profiledTransaction && profiledTransaction.contexts;
const context = profiledTransaction?.contexts;
const profile_id = context && context['profile'] && context['profile']['profile_id'];
const start_timestamp = context && context['profile'] && context['profile']['start_timestamp'];

Expand Down
Loading
Loading