Skip to content

ref: Refactor some any #14477

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
Nov 29, 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
3 changes: 3 additions & 0 deletions biome.json
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,9 @@
"angular.json",
"ember/instance-initializers/**",
"ember/types.d.ts",
"solidstart/*.d.ts",
"solidstart/client/",
"solidstart/server/",
".output",
".vinxi"
]
Expand Down
31 changes: 11 additions & 20 deletions packages/browser-utils/src/instrument/dom.ts
Original file line number Diff line number Diff line change
Expand Up @@ -64,24 +64,21 @@ export function instrumentDOM(): void {
// could potentially prevent the event from bubbling up to our global listeners. This way, our handler are still
// guaranteed to fire at least once.)
['EventTarget', 'Node'].forEach((target: string) => {
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-explicit-any
const proto = (WINDOW as any)[target] && (WINDOW as any)[target].prototype;
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, no-prototype-builtins
const globalObject = WINDOW as unknown as Record<string, { prototype?: object }>;
const targetObj = globalObject[target];
const proto = targetObj && targetObj.prototype;

// eslint-disable-next-line no-prototype-builtins
if (!proto || !proto.hasOwnProperty || !proto.hasOwnProperty('addEventListener')) {
return;
}

fill(proto, 'addEventListener', function (originalAddEventListener: AddEventListener): AddEventListener {
return function (
this: Element,
type: string,
listener: EventListenerOrEventListenerObject,
options?: boolean | AddEventListenerOptions,
): AddEventListener {
return function (this: InstrumentedElement, type, listener, options): AddEventListener {
if (type === 'click' || type == 'keypress') {
try {
const el = this as InstrumentedElement;
const handlers = (el.__sentry_instrumentation_handlers__ = el.__sentry_instrumentation_handlers__ || {});
const handlers = (this.__sentry_instrumentation_handlers__ =
this.__sentry_instrumentation_handlers__ || {});
const handlerForType = (handlers[type] = handlers[type] || { refCount: 0 });

if (!handlerForType.handler) {
Expand All @@ -105,16 +102,10 @@ export function instrumentDOM(): void {
proto,
'removeEventListener',
function (originalRemoveEventListener: RemoveEventListener): RemoveEventListener {
return function (
this: Element,
type: string,
listener: EventListenerOrEventListenerObject,
options?: boolean | EventListenerOptions,
): () => void {
return function (this: InstrumentedElement, type, listener, options): () => void {
if (type === 'click' || type == 'keypress') {
try {
const el = this as InstrumentedElement;
const handlers = el.__sentry_instrumentation_handlers__ || {};
const handlers = this.__sentry_instrumentation_handlers__ || {};
const handlerForType = handlers[type];

if (handlerForType) {
Expand All @@ -128,7 +119,7 @@ export function instrumentDOM(): void {

// If there are no longer any custom handlers of any type on this element, cleanup everything.
if (Object.keys(handlers).length === 0) {
delete el.__sentry_instrumentation_handlers__;
delete this.__sentry_instrumentation_handlers__;
}
}
} catch (e) {
Expand Down
20 changes: 14 additions & 6 deletions packages/browser/src/integrations/reportingobserver.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,13 @@ interface ReportingObserverOptions {
types?: ReportTypes[];
}

/** This is experimental and the types are not included with TypeScript, sadly. */
interface ReportingObserverClass {
new (handler: (reports: Report[]) => void, options: { buffered?: boolean; types?: ReportTypes[] }): {
observe: () => void;
};
}

const SETUP_CLIENTS = new WeakMap<Client, boolean>();

const _reportingObserverIntegration = ((options: ReportingObserverOptions = {}) => {
Expand Down Expand Up @@ -99,13 +106,14 @@ const _reportingObserverIntegration = ((options: ReportingObserverOptions = {})
return;
}

// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-explicit-any
const observer = new (WINDOW as any).ReportingObserver(handler, {
buffered: true,
types,
});
const observer = new (WINDOW as typeof WINDOW & { ReportingObserver: ReportingObserverClass }).ReportingObserver(
handler,
{
buffered: true,
types,
},
);

// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
observer.observe();
},

Expand Down
36 changes: 24 additions & 12 deletions packages/cloudflare/src/handler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,8 +40,7 @@ export function withSentry<E extends ExportedHandler<any>>(
): E {
setAsyncLocalStorageAsyncContextStrategy();

// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-explicit-any
if ('fetch' in handler && typeof handler.fetch === 'function' && !(handler.fetch as any).__SENTRY_INSTRUMENTED__) {
if ('fetch' in handler && typeof handler.fetch === 'function' && !isInstrumented(handler.fetch)) {
handler.fetch = new Proxy(handler.fetch, {
apply(target, thisArg, args: Parameters<ExportedHandlerFetchHandler<ExtractEnv<E>>>) {
const [request, env, context] = args;
Expand All @@ -50,16 +49,10 @@ export function withSentry<E extends ExportedHandler<any>>(
},
});

// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-explicit-any
(handler.fetch as any).__SENTRY_INSTRUMENTED__ = true;
markAsInstrumented(handler.fetch);
}

if (
'scheduled' in handler &&
typeof handler.scheduled === 'function' &&
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-explicit-any
!(handler.scheduled as any).__SENTRY_INSTRUMENTED__
) {
if ('scheduled' in handler && typeof handler.scheduled === 'function' && !isInstrumented(handler.scheduled)) {
handler.scheduled = new Proxy(handler.scheduled, {
apply(target, thisArg, args: Parameters<ExportedHandlerScheduledHandler<ExtractEnv<E>>>) {
const [event, env, context] = args;
Expand Down Expand Up @@ -97,9 +90,28 @@ export function withSentry<E extends ExportedHandler<any>>(
},
});

// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-explicit-any
(handler.scheduled as any).__SENTRY_INSTRUMENTED__ = true;
markAsInstrumented(handler.scheduled);
}

return handler;
}

type SentryInstrumented<T> = T & {
__SENTRY_INSTRUMENTED__?: boolean;
};

function markAsInstrumented<T>(handler: T): void {
try {
(handler as SentryInstrumented<T>).__SENTRY_INSTRUMENTED__ = true;
} catch {
// ignore errors here
}
}

function isInstrumented<T>(handler: T): boolean | undefined {
try {
return (handler as SentryInstrumented<T>).__SENTRY_INSTRUMENTED__;
} catch {
return false;
}
}
10 changes: 3 additions & 7 deletions packages/core/src/metrics/aggregator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,9 +20,8 @@ export class MetricsAggregator implements MetricsAggregatorBase {
// that we store in memory.
private _bucketsTotalWeight;

// Cast to any so that it can use Node.js timeout
// eslint-disable-next-line @typescript-eslint/no-explicit-any
private readonly _interval: any;
// We adjust the type here to add the `unref()` part, as setInterval can technically return a number of a NodeJS.Timer.
private readonly _interval: ReturnType<typeof setInterval> & { unref?: () => void };

// SDKs are required to shift the flush interval by random() * rollup_in_seconds.
// That shift is determined once per startup to create jittering.
Expand All @@ -40,11 +39,8 @@ export class MetricsAggregator implements MetricsAggregatorBase {
this._buckets = new Map();
this._bucketsTotalWeight = 0;

// eslint-disable-next-line @typescript-eslint/no-explicit-any
this._interval = setInterval(() => this._flush(), DEFAULT_FLUSH_INTERVAL) as any;
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
this._interval = setInterval(() => this._flush(), DEFAULT_FLUSH_INTERVAL);
if (this._interval.unref) {
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
this._interval.unref();
}

Expand Down
3 changes: 1 addition & 2 deletions packages/core/src/transports/base.ts
Original file line number Diff line number Diff line change
Expand Up @@ -61,8 +61,7 @@ export function createTransport(
return resolvedSyncPromise({});
}

// eslint-disable-next-line @typescript-eslint/no-explicit-any
const filteredEnvelope: Envelope = createEnvelope(envelope[0], filteredEnvelopeItems as any);
const filteredEnvelope: Envelope = createEnvelope(envelope[0], filteredEnvelopeItems as (typeof envelope)[1]);

// Creates client report for each item in an envelope
const recordEnvelopeLoss = (reason: EventDropReason): void => {
Expand Down
6 changes: 2 additions & 4 deletions packages/core/src/utils-hoist/isBrowser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,6 @@ type ElectronProcess = { type?: string };

// Electron renderers with nodeIntegration enabled are detected as Node.js so we specifically test for them
function isElectronNodeRenderer(): boolean {
return (
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-explicit-any
(GLOBAL_OBJ as any).process !== undefined && ((GLOBAL_OBJ as any).process as ElectronProcess).type === 'renderer'
);
const process = (GLOBAL_OBJ as typeof GLOBAL_OBJ & { process?: ElectronProcess }).process;
return !!process && process.type === 'renderer';
}
9 changes: 7 additions & 2 deletions packages/core/src/utils-hoist/misc.ts
Original file line number Diff line number Diff line change
Expand Up @@ -211,8 +211,7 @@ export function addContextToFrame(lines: string[], frame: StackFrame, linesOfCon
* @returns `true` if the exception has already been captured, `false` if not (with the side effect of marking it seen)
*/
export function checkOrSetAlreadyCaught(exception: unknown): boolean {
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
if (exception && (exception as any).__sentry_captured__) {
if (isAlreadyCaptured(exception)) {
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 was unsafe because you could pass e.g. undefined here which would throw.

return true;
}

Expand All @@ -227,6 +226,12 @@ export function checkOrSetAlreadyCaught(exception: unknown): boolean {
return false;
}

function isAlreadyCaptured(exception: unknown): boolean | void {
try {
return (exception as { __sentry_captured__?: boolean }).__sentry_captured__;
} catch {} // eslint-disable-line no-empty
}

/**
* Checks whether the given input is already an array, and if it isn't, wraps it in one.
*
Expand Down
3 changes: 2 additions & 1 deletion packages/core/src/utils-hoist/object.ts
Original file line number Diff line number Diff line change
Expand Up @@ -296,7 +296,8 @@ function isPojo(input: unknown): input is Record<string, unknown> {
export function objectify(wat: unknown): typeof Object {
let objectified;
switch (true) {
case wat === undefined || wat === null:
// this will catch both undefined and null
case wat == undefined:
objectified = new String(wat);
break;

Expand Down
3 changes: 1 addition & 2 deletions packages/google-cloud-serverless/src/gcpfunction/http.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,8 +27,7 @@ export function wrapHttpFunction(fn: HttpFunction, wrapOptions: Partial<WrapperO

// Functions emulator from firebase-tools has a hack-ish workaround that saves the actual function
// passed to `onRequest(...)` and in fact runs it so we need to wrap it too.
// eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-member-access
const emulatorFunc = (fn as any).__emulator_func as HttpFunction | undefined;
const emulatorFunc = (fn as HttpFunction & { __emulator_func?: HttpFunction }).__emulator_func;
if (emulatorFunc) {
overrides = { __emulator_func: proxyFunction(emulatorFunc, wrap) };
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,9 @@ import RouterImport from 'next/router';
// next/router v10 is CJS
//
// For ESM/CJS interoperability 'reasons', depending on how this file is loaded, Router might be on the default export
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-explicit-any
const Router: typeof RouterImport = RouterImport.events ? RouterImport : (RouterImport as any).default;
const Router: typeof RouterImport = RouterImport.events
? RouterImport
: (RouterImport as unknown as { default: typeof RouterImport }).default;

import { DEBUG_BUILD } from '../../common/debug-build';

Expand Down
4 changes: 2 additions & 2 deletions packages/nextjs/src/common/utils/tracingUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -68,8 +68,8 @@ let nextjsEscapedAsyncStorage: AsyncLocalStorage<true>;
* first time.
*/
export function escapeNextjsTracing<T>(cb: () => T): T {
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-explicit-any
const MaybeGlobalAsyncLocalStorage = (GLOBAL_OBJ as any).AsyncLocalStorage;
const MaybeGlobalAsyncLocalStorage = (GLOBAL_OBJ as { AsyncLocalStorage?: new () => AsyncLocalStorage<true> })
.AsyncLocalStorage;

if (!MaybeGlobalAsyncLocalStorage) {
DEBUG_BUILD &&
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -41,14 +41,13 @@ if (typeof serverComponent === 'function') {
// Current assumption is that Next.js applies some loader magic to userfiles, but not files in node_modules. This file
// is technically a userfile so it gets the loader magic applied.
wrappedServerComponent = new Proxy(serverComponent, {
apply: (originalFunction, thisArg, args) => {
apply: (originalFunction: (...args: unknown[]) => unknown, thisArg, args) => {
let sentryTraceHeader: string | undefined | null = undefined;
let baggageHeader: string | undefined | null = undefined;
let headers: WebFetchHeaders | undefined = undefined;

// We try-catch here just in `requestAsyncStorage` is undefined since it may not be defined
try {
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
const requestAsyncStore = requestAsyncStorage?.getStore() as ReturnType<RequestAsyncStorage['getStore']>;
sentryTraceHeader = requestAsyncStore?.headers.get('sentry-trace') ?? undefined;
baggageHeader = requestAsyncStore?.headers.get('baggage') ?? undefined;
Expand All @@ -57,8 +56,7 @@ if (typeof serverComponent === 'function') {
/** empty */
}

// eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-member-access
return Sentry.wrapServerComponentWithSentry(originalFunction as any, {
return Sentry.wrapServerComponentWithSentry(originalFunction, {
componentRoute: '__ROUTE__',
componentType: '__COMPONENT_TYPE__',
sentryTraceHeader,
Expand Down
3 changes: 1 addition & 2 deletions packages/node/src/integrations/context.ts
Original file line number Diff line number Diff line change
Expand Up @@ -171,8 +171,7 @@ async function getOsContext(): Promise<OsContext> {

function getCultureContext(): CultureContext | undefined {
try {
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-explicit-any
if (typeof (process.versions as unknown as any).icu !== 'string') {
if (typeof process.versions.icu !== 'string') {
// Node was built without ICU support
return;
}
Expand Down
3 changes: 1 addition & 2 deletions packages/node/src/proxy/base.ts
Original file line number Diff line number Diff line change
Expand Up @@ -81,8 +81,7 @@ export abstract class Agent extends http.Agent {
if (options) {
// First check the `secureEndpoint` property explicitly, since this
// means that a parent `Agent` is "passing through" to this instance.
// eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-member-access
if (typeof (options as any).secureEndpoint === 'boolean') {
if (typeof (options as Partial<typeof options>).secureEndpoint === 'boolean') {
return options.secureEndpoint;
}

Expand Down
2 changes: 1 addition & 1 deletion packages/react/src/reactrouter.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -223,7 +223,7 @@ function computeRootMatch(pathname: string): Match {

/* eslint-disable @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-member-access */
export function withSentryRouting<P extends Record<string, any>, R extends React.ComponentType<P>>(Route: R): R {
const componentDisplayName = (Route as any).displayName || (Route as any).name;
const componentDisplayName = Route.displayName || Route.name;

const WrappedRoute: React.FC<P> = (props: P) => {
if (props && props.computedMatch && props.computedMatch.isExact) {
Expand Down
Loading