Skip to content

ref: Refactor some more any types #14546

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 4 commits into from
Dec 5, 2024
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
17 changes: 7 additions & 10 deletions packages/angular/src/tracing.ts
Original file line number Diff line number Diff line change
Expand Up @@ -271,8 +271,9 @@ export class TraceDirective implements OnInit, AfterViewInit {
* @inheritdoc
*/
public ngAfterViewInit(): void {
if (this._tracingSpan) {
runOutsideAngular(() => this._tracingSpan!.end());
const span = this._tracingSpan;
if (span) {
runOutsideAngular(() => span.end());
}
}
}
Expand Down Expand Up @@ -302,8 +303,7 @@ export function TraceClass(options?: TraceClassOptions): ClassDecorator {
/* eslint-disable @typescript-eslint/no-unsafe-member-access */
return target => {
const originalOnInit = target.prototype.ngOnInit;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
target.prototype.ngOnInit = function (...args: any[]): ReturnType<typeof originalOnInit> {
target.prototype.ngOnInit = function (...args: unknown[]): ReturnType<typeof originalOnInit> {
tracingSpan = runOutsideAngular(() =>
startInactiveSpan({
onlyIfParent: true,
Expand All @@ -321,8 +321,7 @@ export function TraceClass(options?: TraceClassOptions): ClassDecorator {
};

const originalAfterViewInit = target.prototype.ngAfterViewInit;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
target.prototype.ngAfterViewInit = function (...args: any[]): ReturnType<typeof originalAfterViewInit> {
target.prototype.ngAfterViewInit = function (...args: unknown[]): ReturnType<typeof originalAfterViewInit> {
if (tracingSpan) {
runOutsideAngular(() => tracingSpan.end());
}
Expand All @@ -345,11 +344,9 @@ interface TraceMethodOptions {
* Decorator function that can be used to capture a single lifecycle methods of the component.
*/
export function TraceMethod(options?: TraceMethodOptions): MethodDecorator {
// eslint-disable-next-line @typescript-eslint/ban-types
return (target: Object, propertyKey: string | symbol, descriptor: PropertyDescriptor) => {
return (_target: unknown, propertyKey: string | symbol, descriptor: PropertyDescriptor) => {
const originalMethod = descriptor.value;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
descriptor.value = function (...args: any[]): ReturnType<typeof originalMethod> {
descriptor.value = function (...args: unknown[]): ReturnType<typeof originalMethod> {
const now = timestampInSeconds();

runOutsideAngular(() => {
Expand Down
12 changes: 8 additions & 4 deletions packages/browser/src/integrations/globalhandlers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -153,8 +153,12 @@ function _eventFromRejectionWithPrimitive(reason: Primitive): Event {
};
}

// eslint-disable-next-line @typescript-eslint/no-explicit-any
function _enhanceEventWithInitialFrame(event: Event, url: any, line: any, column: any): Event {
function _enhanceEventWithInitialFrame(
event: Event,
url: string | undefined,
line: number | undefined,
column: number | undefined,
): Event {
// event.exception
const e = (event.exception = event.exception || {});
// event.exception.values
Expand All @@ -166,8 +170,8 @@ function _enhanceEventWithInitialFrame(event: Event, url: any, line: any, column
// event.exception.values[0].stacktrace.frames
const ev0sf = (ev0s.frames = ev0s.frames || []);

const colno = isNaN(parseInt(column, 10)) ? undefined : column;
const lineno = isNaN(parseInt(line, 10)) ? undefined : line;
const colno = column;
const lineno = line;
Comment on lines +173 to +174
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

m: why are we removing the isNaN check here?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

because it should not actually be needed, I think? window.onerror = function() should be supported everywhere in all the browser we support, and is typed consistently, so these should be proper numbers (or undefined) always?

const filename = isString(url) && url.length > 0 ? url : getLocationHref();

// event.exception.values[0].stacktrace.frames
Expand Down
1 change: 1 addition & 0 deletions packages/browser/src/sdk.ts
Original file line number Diff line number Diff line change
Expand Up @@ -198,6 +198,7 @@ export function init(browserOptions: BrowserOptions = {}): Client | undefined {
* All properties the report dialog supports
*/
export interface ReportDialogOptions {
// TODO(v9): Change this to [key: string]: unknkown;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
[key: string]: any;
eventId?: string;
Expand Down
1 change: 1 addition & 0 deletions packages/core/src/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@ export function getEnvelopeEndpointWithUrlEncodedAuth(dsn: DsnComponents, tunnel
export function getReportDialogEndpoint(
dsnLike: DsnLike,
dialogOptions: {
// TODO(v9): Change this to [key: string]: unknown;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
[key: string]: any;
user?: { name?: string; email?: string };
Expand Down
6 changes: 2 additions & 4 deletions packages/core/src/baseclient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -158,8 +158,7 @@ export abstract class BaseClient<O extends ClientOptions> implements Client<O> {
/**
* @inheritDoc
*/
// eslint-disable-next-line @typescript-eslint/no-explicit-any
public captureException(exception: any, hint?: EventHint, scope?: Scope): string {
public captureException(exception: unknown, hint?: EventHint, scope?: Scope): string {
const eventId = uuid4();

// ensure we haven't captured this very object before
Expand Down Expand Up @@ -915,8 +914,7 @@ export abstract class BaseClient<O extends ClientOptions> implements Client<O> {
/**
* @inheritDoc
*/
// eslint-disable-next-line @typescript-eslint/no-explicit-any
public abstract eventFromException(_exception: any, _hint?: EventHint): PromiseLike<Event>;
public abstract eventFromException(_exception: unknown, _hint?: EventHint): PromiseLike<Event>;

/**
* @inheritDoc
Expand Down
9 changes: 2 additions & 7 deletions packages/core/src/exports.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,11 +34,7 @@ import { parseEventHintOrCaptureContext } from './utils/prepareEvent';
* @param hint Optional additional data to attach to the Sentry event.
* @returns the id of the captured Sentry event.
*/
export function captureException(
// eslint-disable-next-line @typescript-eslint/no-explicit-any
exception: any,
hint?: ExclusiveEventHintOrCaptureContext,
): string {
export function captureException(exception: unknown, hint?: ExclusiveEventHintOrCaptureContext): string {
return getCurrentScope().captureException(exception, parseEventHintOrCaptureContext(hint));
}

Expand Down Expand Up @@ -73,8 +69,7 @@ export function captureEvent(event: Event, hint?: EventHint): string {
* @param name of the context
* @param context Any kind of data. This data will be normalized.
*/
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export function setContext(name: string, context: { [key: string]: any } | null): void {
export function setContext(name: string, context: { [key: string]: unknown } | null): void {
getIsolationScope().setContext(name, context);
}

Expand Down
2 changes: 0 additions & 2 deletions packages/core/src/fetch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,6 @@ type PolymorphicRequestHeaders =
| Array<[string, string]>
// the below is not precisely the Header type used in Request, but it'll pass duck-typing
| {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
[key: string]: any;
append: (key: string, value: string) => void;
get: (key: string) => string | null | undefined;
};
Expand Down
3 changes: 1 addition & 2 deletions packages/core/src/integrations/functiontostring.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,7 @@ const _functionToStringIntegration = (() => {
// intrinsics (like Function.prototype) might be immutable in some environments
// e.g. Node with --frozen-intrinsics, XS (an embedded JavaScript engine) or SES (a JavaScript proposal)
try {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
Function.prototype.toString = function (this: WrappedFunction, ...args: any[]): string {
Function.prototype.toString = function (this: WrappedFunction, ...args: unknown[]): string {
const originalFunction = getOriginalFunction(this);
const context =
SETUP_CLIENTS.has(getClient() as Client) && originalFunction !== undefined ? originalFunction : this;
Expand Down
2 changes: 1 addition & 1 deletion packages/core/src/metrics/aggregator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ export class MetricsAggregator implements MetricsAggregatorBase {
// that we store in memory.
private _bucketsTotalWeight;

// We adjust the type here to add the `unref()` part, as setInterval can technically return a number of a NodeJS.Timer.
// We adjust the type here to add the `unref()` part, as setInterval can technically return a number or a NodeJS.Timer
private readonly _interval: ReturnType<typeof setInterval> & { unref?: () => void };

// SDKs are required to shift the flush interval by random() * rollup_in_seconds.
Expand Down
3 changes: 1 addition & 2 deletions packages/core/src/server-runtime-client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -79,8 +79,7 @@ export class ServerRuntimeClient<
/**
* @inheritDoc
*/
// eslint-disable-next-line @typescript-eslint/no-explicit-any
public captureException(exception: any, hint?: EventHint, scope?: Scope): string {
public captureException(exception: unknown, hint?: EventHint, scope?: Scope): string {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think this might be breaking in a weird way but I can't think of an example right now.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this should be fine as accepting stuff as unknown like this will generally work for anything. The problematic part is replacing a return value of any with unknown, or with function args taking ...args: unknown[] vs ...args: any[].

// Check if `_sessionFlusher` exists because it is initialized (defined) only when the `autoSessionTracking` is enabled.
// The expectation is that session aggregates are only sent when `autoSessionTracking` is enabled.
// TODO(v9): Our goal in the future is to not have the `autoSessionTracking` option and instead rely on integrations doing the creation and sending of sessions. We will not have a central kill-switch for sessions.
Expand Down
7 changes: 2 additions & 5 deletions packages/core/src/sessionflusher.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,9 +22,8 @@ export class SessionFlusher implements SessionFlusherLike {
public readonly flushTimeout: number;
private _pendingAggregates: Map<number, AggregationCounts>;
private _sessionAttrs: ReleaseHealthAttributes;
// Cast to any so that it can use Node.js timeout
// eslint-disable-next-line @typescript-eslint/no-explicit-any
private _intervalId: any;
// We adjust the type here to add the `unref()` part, as setInterval can technically return a number or a NodeJS.Timer
private readonly _intervalId: ReturnType<typeof setInterval> & { unref?: () => void };
private _isEnabled: boolean;
private _client: Client;

Expand All @@ -36,9 +35,7 @@ export class SessionFlusher implements SessionFlusherLike {

// Call to setInterval, so that flush is called every 60 seconds.
this._intervalId = setInterval(() => this.flush(), this.flushTimeout * 1000);
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
if (this._intervalId.unref) {
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
this._intervalId.unref();
}
this._sessionAttrs = attrs;
Expand Down
2 changes: 1 addition & 1 deletion packages/core/src/utils-hoist/instrument/globalError.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ export function addGlobalErrorInstrumentationHandler(handler: (data: HandlerData
function instrumentError(): void {
_oldOnErrorHandler = GLOBAL_OBJ.onerror;

// Note: The reason we are doing window.onerror instead of window.addEventListener('error') is
// Note: The reason we are doing window.onerror instead of window.addEventListener('error')
// is that we are using this handler in the Loader Script, to handle buffered errors consistently
GLOBAL_OBJ.onerror = function (
msg: string | object,
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import type { HandlerDataUnhandledRejection } from '../../types-hoist';

import { GLOBAL_OBJ } from '../worldwide';
import { addHandler, maybeInstrument, triggerHandlers } from './handlers';

Expand All @@ -22,7 +21,7 @@ export function addGlobalUnhandledRejectionInstrumentationHandler(
function instrumentUnhandledRejection(): void {
_oldOnUnhandledRejectionHandler = GLOBAL_OBJ.onunhandledrejection;

// Note: The reason we are doing window.onerror instead of window.addEventListener('unhandledrejection') is
// Note: The reason we are doing window.onunhandledrejection instead of window.addEventListener('unhandledrejection')
// is that we are using this handler in the Loader Script, to handle buffered rejections consistently
GLOBAL_OBJ.onunhandledrejection = function (e: unknown): boolean {
const handlerData: HandlerDataUnhandledRejection = e;
Expand Down
6 changes: 2 additions & 4 deletions packages/core/src/utils-hoist/logger.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,7 @@ type LoggerConsoleMethods = Record<ConsoleLevel, LoggerMethod>;

/** This may be mutated by the console instrumentation. */
export const originalConsoleMethods: {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
[key in ConsoleLevel]?: (...args: any[]) => void;
[key in ConsoleLevel]?: (...args: unknown[]) => void;
} = {};

/** JSDoc */
Expand Down Expand Up @@ -79,8 +78,7 @@ function makeLogger(): Logger {

if (DEBUG_BUILD) {
CONSOLE_LEVELS.forEach(name => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
logger[name] = (...args: any[]) => {
logger[name] = (...args: Parameters<(typeof GLOBAL_OBJ.console)[typeof name]>) => {
if (enabled) {
consoleSandbox(() => {
GLOBAL_OBJ.console[name](`${PREFIX}[${name}]:`, ...args);
Expand Down
1 change: 0 additions & 1 deletion packages/core/src/utils-hoist/misc.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
import type { Event, Exception, Mechanism, StackFrame } from '../types-hoist';

import { addNonEnumerableProperty } from './object';
Expand Down
7 changes: 4 additions & 3 deletions packages/core/src/utils-hoist/object.ts
Original file line number Diff line number Diff line change
Expand Up @@ -94,9 +94,10 @@ export function getOriginalFunction<T extends Function>(func: WrappedFunction<T>
*
* @deprecated This function is deprecated and will be removed in the next major version of the SDK.
*/
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export function urlEncode(object: { [key: string]: any }): string {
return Object.keys(object)
.map(key => `${encodeURIComponent(key)}=${encodeURIComponent(object[key])}`)
return Object.entries(object)
.map(([key, value]) => `${encodeURIComponent(key)}=${encodeURIComponent(value)}`)
.join('&');
}

Expand Down Expand Up @@ -237,7 +238,7 @@ function _dropUndefinedKeys<T>(inputValue: T, memoizationMap: Map<unknown, unkno
return memoVal as T;
}

const returnValue: { [key: string]: any } = {};
const returnValue: { [key: string]: unknown } = {};
// Store the mapping of this value in case we visit it again, in case of circular data
memoizationMap.set(inputValue, returnValue);

Expand Down
3 changes: 1 addition & 2 deletions packages/core/src/utils-hoist/string.ts
Original file line number Diff line number Diff line change
Expand Up @@ -65,8 +65,7 @@ export function snipLine(line: string, colno: number): string {
* @param delimiter string to be placed in-between values
* @returns Joined values
*/
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export function safeJoin(input: any[], delimiter?: string): string {
export function safeJoin(input: unknown[], delimiter?: string): string {
if (!Array.isArray(input)) {
return '';
}
Expand Down
6 changes: 2 additions & 4 deletions packages/core/src/utils-hoist/vendor/supportsHistory.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,11 +35,9 @@ export function supportsHistory(): boolean {
// NOTE: in Chrome App environment, touching history.pushState, *even inside
// a try/catch block*, will cause Chrome to output an error to console.error
// borrowed from: https://github.com/angular/angular.js/pull/13945/files
/* eslint-disable @typescript-eslint/no-unsafe-member-access */
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const chromeVar = (WINDOW as any).chrome;
// TODO(v9): Remove this custom check, it is pretty old and likely not needed anymore
const chromeVar = (WINDOW as { chrome?: { app?: { runtime?: unknown } } }).chrome;
const isChromePackagedApp = chromeVar && chromeVar.app && chromeVar.app.runtime;
/* eslint-enable @typescript-eslint/no-unsafe-member-access */
const hasHistoryApi = 'history' in WINDOW && !!WINDOW.history.pushState && !!WINDOW.history.replaceState;

return !isChromePackagedApp && hasHistoryApi;
Expand Down
18 changes: 6 additions & 12 deletions packages/nestjs/src/decorators.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,9 @@ import { isExpectedError } from './helpers';
*/
export const SentryCron = (monitorSlug: string, monitorConfig?: MonitorConfig): MethodDecorator => {
return (target: unknown, propertyKey, descriptor: PropertyDescriptor) => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const originalMethod = descriptor.value as (...args: any[]) => Promise<any>;
const originalMethod = descriptor.value as (...args: unknown[]) => Promise<unknown>;

// eslint-disable-next-line @typescript-eslint/no-explicit-any
descriptor.value = function (...args: any[]) {
descriptor.value = function (...args: unknown[]) {
return Sentry.withMonitor(
monitorSlug,
() => {
Expand All @@ -31,11 +29,9 @@ export const SentryCron = (monitorSlug: string, monitorConfig?: MonitorConfig):
*/
export function SentryTraced(op: string = 'function') {
return function (target: unknown, propertyKey: string, descriptor: PropertyDescriptor) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const originalMethod = descriptor.value as (...args: any[]) => Promise<any> | any; // function can be sync or async
const originalMethod = descriptor.value as (...args: unknown[]) => Promise<unknown> | unknown; // function can be sync or async

// eslint-disable-next-line @typescript-eslint/no-explicit-any
descriptor.value = function (...args: any[]) {
descriptor.value = function (...args: unknown[]) {
return startSpan(
{
op: op,
Expand Down Expand Up @@ -64,11 +60,9 @@ export function SentryTraced(op: string = 'function') {
*/
export function SentryExceptionCaptured() {
return function (target: unknown, propertyKey: string, descriptor: PropertyDescriptor) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const originalCatch = descriptor.value as (exception: unknown, host: unknown, ...args: any[]) => void;
const originalCatch = descriptor.value as (exception: unknown, host: unknown, ...args: unknown[]) => void;

// eslint-disable-next-line @typescript-eslint/no-explicit-any
descriptor.value = function (exception: unknown, host: unknown, ...args: any[]) {
descriptor.value = function (exception: unknown, host: unknown, ...args: unknown[]) {
if (isExpectedError(exception)) {
return originalCatch.apply(this, [exception, host, ...args]);
}
Expand Down
10 changes: 2 additions & 8 deletions packages/node/src/integrations/onunhandledrejection.ts
Original file line number Diff line number Diff line change
Expand Up @@ -63,13 +63,8 @@ export function makeUnhandledPromiseHandler(

/**
* Handler for `mode` option

*/
function handleRejection(
// eslint-disable-next-line @typescript-eslint/no-explicit-any
reason: any,
options: OnUnhandledRejectionOptions,
): void {
function handleRejection(reason: unknown, options: OnUnhandledRejectionOptions): void {
// https://github.com/nodejs/node/blob/7cf6f9e964aa00772965391c23acda6d71972a9a/lib/internal/process/promises.js#L234-L240
const rejectionWarning =
'This error originated either by ' +
Expand All @@ -81,8 +76,7 @@ function handleRejection(
if (options.mode === 'warn') {
consoleSandbox(() => {
console.warn(rejectionWarning);
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
console.error(reason && reason.stack ? reason.stack : reason);
console.error(reason && typeof reason === 'object' && 'stack' in reason ? reason.stack : reason);
});
} else if (options.mode === 'strict') {
consoleSandbox(() => {
Expand Down
2 changes: 1 addition & 1 deletion packages/node/src/utils/errorhandling.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ const DEFAULT_SHUTDOWN_TIMEOUT = 2000;
/**
* @hidden
*/
export function logAndExitProcess(error: Error): void {
export function logAndExitProcess(error: unknown): void {
consoleSandbox(() => {
// eslint-disable-next-line no-console
console.error(error);
Expand Down
3 changes: 1 addition & 2 deletions packages/solid/src/errorboundary.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,7 @@ export function withSentryErrorBoundary(ErrorBoundary: Component<ErrorBoundaryPr
const SentryErrorBoundary = (props: ErrorBoundaryProps): JSX.Element => {
const [local, others] = splitProps(props, ['fallback']);

// eslint-disable-next-line @typescript-eslint/no-explicit-any
const fallback = (error: any, reset: () => void): JSX.Element => {
const fallback = (error: unknown, reset: () => void): JSX.Element => {
captureException(error);

const f = local.fallback;
Expand Down
Loading