Skip to content

Commit

Permalink
Forbid use of implicit any
Browse files Browse the repository at this point in the history
  • Loading branch information
matthieusieben committed Nov 15, 2024
1 parent 3764dfd commit 8b0fbb0
Show file tree
Hide file tree
Showing 45 changed files with 244 additions and 109 deletions.
4 changes: 2 additions & 2 deletions packages/api/src/agent.ts
Original file line number Diff line number Diff line change
Expand Up @@ -351,7 +351,7 @@ export class Agent extends XrpcClient {
})

// assemble a map of labeler dids to the interpreted label value definitions
const labelDefs = {}
const labelDefs: Record<string, InterpretedLabelValueDefinition[]> = {}
if (labelers.data) {
for (const labeler of labelers.data
.views as AppBskyLabelerDefs.LabelerViewDetailed[]) {
Expand Down Expand Up @@ -1553,7 +1553,7 @@ export class Agent extends XrpcClient {
.filter((pref) => !AppBskyActorDefs.isSavedFeedsPref(pref))
.concat([feedsPref])
})
return res
return res!
}

private async updateSavedFeedsV2Preferences(
Expand Down
6 changes: 6 additions & 0 deletions packages/api/src/moderation/const/labels.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ export const DEFAULT_LABEL_SETTINGS: Record<string, LabelPreference> = {
'graphic-media': 'warn',
}

/** @deprecated use {@link KNOWN_LABEL_DEFINITIONS} instead */
export const LABELS: Record<KnownLabelValue, InterpretedLabelValueDefinition> =
{
'!hide': {
Expand Down Expand Up @@ -194,3 +195,8 @@ export const LABELS: Record<KnownLabelValue, InterpretedLabelValueDefinition> =
locales: [],
},
}

export const KNOWN_LABEL_DEFINITIONS = new Map<
string,
InterpretedLabelValueDefinition
>(Object.entries(LABELS))
6 changes: 3 additions & 3 deletions packages/api/src/moderation/decision.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ import {
CUSTOM_LABEL_VALUE_RE,
} from './types'
import { ModerationUI } from './ui'
import { LABELS } from './const/labels'
import { KNOWN_LABEL_DEFINITIONS } from './const/labels'

enum ModerationBehaviorSeverity {
High,
Expand Down Expand Up @@ -254,8 +254,8 @@ export class ModerationDecision {
const labelDef = CUSTOM_LABEL_VALUE_RE.test(label.val)
? opts.labelDefs?.[label.src]?.find(
(def) => def.identifier === label.val,
) || LABELS[label.val]
: LABELS[label.val]
) || KNOWN_LABEL_DEFINITIONS.get(label.val)
: KNOWN_LABEL_DEFINITIONS.get(label.val)
if (!labelDef) {
// ignore labels we don't understand
return
Expand Down
1 change: 1 addition & 0 deletions packages/api/tsconfig.build.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
"compilerOptions": {
"rootDir": "./src",
"outDir": "./dist",
"noPropertyAccessFromIndexSignature": false,
"noUnusedLocals": false
},
"include": ["./src"]
Expand Down
2 changes: 1 addition & 1 deletion packages/bsky/src/logger.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ export const httpLogger: ReturnType<typeof subsystemLogger> =
export const loggerMiddleware = pinoHttp({
logger: httpLogger,
serializers: {
err: (err: unknown) => ({
err: (err: any) => ({
code: err?.['code'],
message: err?.['message'],
}),
Expand Down
2 changes: 1 addition & 1 deletion packages/bsync/src/logger.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ export const loggerMiddleware = pinoHttp({
paths: ['req.headers.authorization'],
},
serializers: {
err: (err: unknown) => ({
err: (err: any) => ({
code: err?.['code'],
message: err?.['message'],
}),
Expand Down
5 changes: 4 additions & 1 deletion packages/common-web/src/arrays.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
export const keyBy = <T>(arr: T[], key: string): Record<string, T> => {
export function keyBy<
T extends { [_ in K]: string },
K extends string = string,
>(arr: T[], key: K): Record<string, T> {
return arr.reduce(
(acc, cur) => {
acc[cur[key]] = cur
Expand Down
6 changes: 3 additions & 3 deletions packages/common-web/src/async.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,11 +49,11 @@ export type Deferrable = {
}

export const createDeferrable = (): Deferrable => {
let resolve
const promise: Promise<void> = new Promise((res) => {
let resolve: () => void
const promise = new Promise<void>((res) => {
resolve = () => res()
})
return { resolve, complete: promise }
return { resolve: resolve!, complete: promise }
}

export const createDeferrables = (count: number): Deferrable[] => {
Expand Down
19 changes: 14 additions & 5 deletions packages/common-web/src/ipld.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,9 @@ export type IpldValue =
| Array<IpldValue>
| { [key: string]: IpldValue }

const isJsonObject = (val: JsonValue): val is { [key: string]: JsonValue } =>
val != null && typeof val === 'object' && !Array.isArray(val)

// @NOTE avoiding use of check.is() here only because it makes
// these implementations slow, and they often live in hot paths.

Expand All @@ -27,7 +30,7 @@ export const jsonToIpld = (val: JsonValue): IpldValue => {
return val.map((item) => jsonToIpld(item))
}
// objects
if (val && typeof val === 'object') {
if (isJsonObject(val)) {
// check for dag json values
if (typeof val['$link'] === 'string' && Object.keys(val).length === 1) {
return CID.parse(val['$link'])
Expand All @@ -36,7 +39,7 @@ export const jsonToIpld = (val: JsonValue): IpldValue => {
return ui8.fromString(val['$bytes'], 'base64')
}
// walk plain objects
const toReturn = {}
const toReturn: Record<string, unknown> = {}
for (const key of Object.keys(val)) {
toReturn[key] = jsonToIpld(val[key])
}
Expand Down Expand Up @@ -66,9 +69,9 @@ export const ipldToJson = (val: IpldValue): JsonValue => {
}
}
// walk plain objects
const toReturn = {}
const toReturn: Record<string, unknown> = {}
for (const key of Object.keys(val)) {
toReturn[key] = ipldToJson(val[key])
toReturn[key] = ipldToJson((val as Record<string, unknown>)[key])
}
return toReturn
}
Expand Down Expand Up @@ -98,7 +101,13 @@ export const ipldEquals = (a: IpldValue, b: IpldValue): boolean => {
// walk plain objects
if (Object.keys(a).length !== Object.keys(b).length) return false
for (const key of Object.keys(a)) {
if (!ipldEquals(a[key], b[key])) return false
if (
!ipldEquals(
(a as Record<string, unknown>)[key],
(b as Record<string, unknown>)[key],
)
)
return false
}
return true
}
Expand Down
16 changes: 8 additions & 8 deletions packages/common-web/src/strings.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,14 +25,14 @@ export const parseLanguage = (langTag: string): LanguageTag | null => {
if (!parsed?.groups) return null
const parts = parsed.groups
return {
grandfathered: parts.grandfathered,
language: parts.language,
extlang: parts.extlang,
script: parts.script,
region: parts.region,
variant: parts.variant,
extension: parts.extension,
privateUse: parts.privateUseA || parts.privateUseB,
grandfathered: parts['grandfathered'],
language: parts['language'],
extlang: parts['extlang'],
script: parts['script'],
region: parts['region'],
variant: parts['variant'],
extension: parts['extension'],
privateUse: parts['privateUseA'] || parts['privateUseB'],
}
}

Expand Down
17 changes: 12 additions & 5 deletions packages/common-web/src/util.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ export function omit(

if (!src) return src

const dst = {}
const dst: Record<string, unknown> = {}
const srcKeys = Object.keys(src)
for (let i = 0; i < srcKeys.length; i++) {
const key = srcKeys[i]
Expand All @@ -53,15 +53,15 @@ export type BailableWait = {
}

export const bailableWait = (ms: number): BailableWait => {
let bail
let bail: () => void
const waitPromise = new Promise<void>((res) => {
const timeout = setTimeout(res, ms)
bail = () => {
clearTimeout(timeout)
res()
}
})
return { bail, wait: () => waitPromise }
return { bail: bail!, wait: () => waitPromise }
}

export const flattenUint8Arrays = (arrs: Uint8Array[]): Uint8Array => {
Expand Down Expand Up @@ -118,11 +118,18 @@ export const asyncFilter = async <T>(
export const isErrnoException = (
err: unknown,
): err is NodeJS.ErrnoException => {
return !!err && err['code']
return (
err instanceof Error && 'code' in err && typeof err['code'] === 'string'
)
}

export const errHasMsg = (err: unknown, msg: string): boolean => {
return !!err && typeof err === 'object' && err['message'] === msg
return (
!!err &&
typeof err === 'object' &&
'message' in err &&
err['message'] === msg
)
}

export const chunkArray = <T>(arr: T[], chunkSize: number): T[][] => {
Expand Down
12 changes: 6 additions & 6 deletions packages/common/src/logger.ts
Original file line number Diff line number Diff line change
@@ -1,23 +1,23 @@
import pino from 'pino'

const allSystemsEnabled = !process.env.LOG_SYSTEMS
const enabledSystems = (process.env.LOG_SYSTEMS || '')
const allSystemsEnabled = !process.env['LOG_SYSTEMS']
const enabledSystems = (process.env['LOG_SYSTEMS'] || '')
.replace(',', ' ')
.split(' ')

const enabledEnv = process.env.LOG_ENABLED
const enabledEnv = process.env['LOG_ENABLED']
const enabled =
enabledEnv === 'true' || enabledEnv === 't' || enabledEnv === '1'

const level = process.env.LOG_LEVEL || 'info'
const level = process.env['LOG_LEVEL'] || 'info'

const config = {
enabled,
level,
}

const rootLogger = process.env.LOG_DESTINATION
? pino(config, pino.destination(process.env.LOG_DESTINATION))
const rootLogger = process.env['LOG_DESTINATION']
? pino(config, pino.destination(process.env['LOG_DESTINATION']))
: pino(config)

const subsystems: Record<string, pino.Logger> = {}
Expand Down
12 changes: 8 additions & 4 deletions packages/did/src/did-error.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,10 +33,14 @@ export class DidError extends Error {
: 'An unknown error occurred'

const status =
(typeof cause?.['statusCode'] === 'number'
? cause['statusCode']
: undefined) ??
(typeof cause?.['status'] === 'number' ? cause['status'] : undefined)
cause != null && typeof cause === 'object'
? ('statusCode' in cause && typeof cause['statusCode'] === 'number'
? cause['statusCode']
: undefined) ??
('status' in cause && typeof cause['status'] === 'number'
? cause['status']
: undefined)
: undefined

return new DidError(did, message, 'did-unknown-error', status, cause)
}
Expand Down
15 changes: 13 additions & 2 deletions packages/internal/fetch-node/src/safe.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ export type SafeFetchWrapOptions = NonNullable<
* @see {@link https://cheatsheetseries.owasp.org/cheatsheets/Server_Side_Request_Forgery_Prevention_Cheat_Sheet.html}
*/
export function safeFetchWrap({
fetch = globalThis.fetch as Fetch,
fetch = globalThis.fetch,
responseMaxSize = 512 * 1024, // 512kB
ssrfProtection = true,
allowCustomPort = !ssrfProtection,
Expand All @@ -34,7 +34,18 @@ export function safeFetchWrap({
allowIpHost = true,
allowPrivateIps = !ssrfProtection,
timeout = 10e3,
forbiddenDomainNames = DEFAULT_FORBIDDEN_DOMAIN_NAMES as Iterable<string>,
forbiddenDomainNames = DEFAULT_FORBIDDEN_DOMAIN_NAMES,
}: {
fetch?: Fetch
responseMaxSize?: number
ssrfProtection?: boolean
allowCustomPort?: boolean
allowData?: boolean
allowHttp?: boolean
allowIpHost?: boolean
allowPrivateIps?: boolean
timeout?: number
forbiddenDomainNames?: Iterable<string>
} = {}): Fetch<unknown> {
return toRequestTransformer(
pipe(
Expand Down
3 changes: 2 additions & 1 deletion packages/internal/fetch/src/fetch-error.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,8 @@ function extractInfo(err: unknown): [statusCode: number, message: string] {
return [500, 'Failed to fetch']
}

const code = err['code']
const code =
err != null && typeof err === 'object' && 'code' in err && err['code']
if (typeof code === 'string') {
switch (true) {
case code === 'ENOTFOUND':
Expand Down
4 changes: 3 additions & 1 deletion packages/internal/fetch/src/fetch-request.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,9 @@ export function protocolCheckRequestTransform(protocols: {
const request = asRequest(input, init)

const config: undefined | boolean | { allowCustomPort?: boolean } =
Object.hasOwn(protocols, protocol) ? protocols[protocol] : undefined
Object.hasOwn(protocols, protocol)
? protocols[protocol as keyof typeof protocols]
: undefined

if (!config) {
throw new FetchRequestError(
Expand Down
6 changes: 3 additions & 3 deletions packages/internal/fetch/src/fetch-wrap.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ export function loggedFetch<C = FetchContext>({
}) {
const onRequest =
logRequest === true
? async (request) => {
? async (request: Request) => {
const requestMessage = await stringifyMessage(request)
console.info(
`> ${request.method} ${request.url}\n${padLines(requestMessage, ' ')}`,
Expand All @@ -23,7 +23,7 @@ export function loggedFetch<C = FetchContext>({

const onResponse =
logResponse === true
? async (response) => {
? async (response: Response) => {
const responseMessage = await stringifyMessage(response.clone())
console.info(
`< HTTP/1.1 ${response.status} ${response.statusText}\n${padLines(responseMessage, ' ')}`,
Expand All @@ -33,7 +33,7 @@ export function loggedFetch<C = FetchContext>({

const onError =
logError === true
? async (error) => {
? async (error: unknown) => {
console.error(`< Error:`, error)
}
: logError || undefined
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -68,10 +68,10 @@ function handleError(err: unknown) {

// If the hostname does not resolve, return null
if (err instanceof Error) {
if (err['code'] === 'ENOTFOUND') return null
if ('code' in err && err.code === 'ENOTFOUND') return null

// Hostname is not a valid domain name
if (err['code'] === 'EBADNAME') throw err
if ('code' in err && err.code === 'EBADNAME') throw err

// DNS server unreachable
// if (err['code'] === 'ETIMEOUT') throw err
Expand Down
2 changes: 1 addition & 1 deletion packages/internal/simple-store-memory/src/util.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ export function roughSizeOfObject(value: unknown): number {
for (let i = 0; i < keys.length; i++) {
bytes += 4
const key = keys[i]
const val = value[key]
const val: unknown = value[key as keyof typeof value]
if (val !== undefined) stack.push(val)
stack.push(key)
}
Expand Down
8 changes: 6 additions & 2 deletions packages/lex-cli/src/codegen/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -429,14 +429,18 @@ function genRecordCls(file: SourceFile, nsid: string, lexRecord: LexRecord) {
}
}

const lexiconTs = (project, lexicons: Lexicons, lexiconDoc: LexiconDoc) =>
const lexiconTs = (
project: Project,
lexicons: Lexicons,
lexiconDoc: LexiconDoc,
) =>
gen(
project,
`/types/${lexiconDoc.id.split('.').join('/')}.ts`,
async (file) => {
const imports: Set<string> = new Set()

const main = lexiconDoc.defs.main
const main = lexiconDoc.defs['main']
if (
main?.type === 'query' ||
main?.type === 'subscription' ||
Expand Down
Loading

0 comments on commit 8b0fbb0

Please sign in to comment.