Skip to content

Commit

Permalink
Make lex-gen type more precise
Browse files Browse the repository at this point in the history
  • Loading branch information
matthieusieben committed Nov 15, 2024
1 parent 02ddb9a commit 77c134f
Show file tree
Hide file tree
Showing 61 changed files with 782 additions and 430 deletions.
42 changes: 18 additions & 24 deletions packages/api/src/agent.ts
Original file line number Diff line number Diff line change
Expand Up @@ -61,15 +61,6 @@ const THREAD_VIEW_PREF_DEFAULTS = {
prioritizeFollowedUsers: true,
}

declare global {
interface Array<T> {
findLast(
predicate: (value: T, index: number, obj: T[]) => unknown,
thisArg?: any,
): T
}
}

export type { FetchHandler }

/**
Expand Down Expand Up @@ -895,7 +886,7 @@ export class Agent extends XrpcClient {
async setAdultContentEnabled(v: boolean) {
await this.updatePreferences((prefs: AppBskyActorDefs.Preferences) => {
let adultContentPref = prefs.findLast(
(pref) =>
(pref): pref is AppBskyActorDefs.AdultContentPref =>
AppBskyActorDefs.isAdultContentPref(pref) &&
AppBskyActorDefs.validateAdultContentPref(pref).success,
)
Expand Down Expand Up @@ -923,7 +914,7 @@ export class Agent extends XrpcClient {
}
await this.updatePreferences((prefs: AppBskyActorDefs.Preferences) => {
let labelPref = prefs.findLast(
(pref) =>
(pref): pref is AppBskyActorDefs.ContentLabelPref =>
AppBskyActorDefs.isContentLabelPref(pref) &&
AppBskyActorDefs.validateContentLabelPref(pref).success &&
pref.label === key &&
Expand Down Expand Up @@ -1066,7 +1057,7 @@ export class Agent extends XrpcClient {
birthDate = birthDate instanceof Date ? birthDate.toISOString() : birthDate
await this.updatePreferences((prefs: AppBskyActorDefs.Preferences) => {
let personalDetailsPref = prefs.findLast(
(pref) =>
(pref): pref is AppBskyActorDefs.PersonalDetailsPref =>
AppBskyActorDefs.isPersonalDetailsPref(pref) &&
AppBskyActorDefs.validatePersonalDetailsPref(pref).success,
)
Expand All @@ -1087,7 +1078,7 @@ export class Agent extends XrpcClient {
async setFeedViewPrefs(feed: string, pref: Partial<BskyFeedViewPreference>) {
await this.updatePreferences((prefs: AppBskyActorDefs.Preferences) => {
const existing = prefs.findLast(
(pref) =>
(pref): pref is AppBskyActorDefs.FeedViewPref =>
AppBskyActorDefs.isFeedViewPref(pref) &&
AppBskyActorDefs.validateFeedViewPref(pref).success &&
pref.feed === feed,
Expand All @@ -1097,7 +1088,10 @@ export class Agent extends XrpcClient {
}
return prefs
.filter(
(p) => !AppBskyActorDefs.isFeedViewPref(pref) || p.feed !== feed,
(p) =>
!AppBskyActorDefs.isFeedViewPref(pref) ||
!('feed' in p) ||
p.feed !== feed,
)
.concat([{ ...pref, $type: 'app.bsky.actor.defs#feedViewPref', feed }])
})
Expand Down Expand Up @@ -1313,8 +1307,8 @@ export class Agent extends XrpcClient {

async bskyAppQueueNudges(nudges: string | string[]) {
await this.updatePreferences((prefs: AppBskyActorDefs.Preferences) => {
let bskyAppStatePref: AppBskyActorDefs.BskyAppStatePref = prefs.findLast(
(pref) =>
let bskyAppStatePref = prefs.findLast(
(pref): pref is AppBskyActorDefs.BskyAppStatePref =>
AppBskyActorDefs.isBskyAppStatePref(pref) &&
AppBskyActorDefs.validateBskyAppStatePref(pref).success,
)
Expand All @@ -1338,8 +1332,8 @@ export class Agent extends XrpcClient {

async bskyAppDismissNudges(nudges: string | string[]) {
await this.updatePreferences((prefs: AppBskyActorDefs.Preferences) => {
let bskyAppStatePref: AppBskyActorDefs.BskyAppStatePref = prefs.findLast(
(pref) =>
let bskyAppStatePref = prefs.findLast(
(pref): pref is AppBskyActorDefs.BskyAppStatePref =>
AppBskyActorDefs.isBskyAppStatePref(pref) &&
AppBskyActorDefs.validateBskyAppStatePref(pref).success,
)
Expand Down Expand Up @@ -1372,8 +1366,8 @@ export class Agent extends XrpcClient {
}

await this.updatePreferences((prefs: AppBskyActorDefs.Preferences) => {
let bskyAppStatePref: AppBskyActorDefs.BskyAppStatePref = prefs.findLast(
(pref) =>
let bskyAppStatePref = prefs.findLast(
(pref): pref is AppBskyActorDefs.BskyAppStatePref =>
AppBskyActorDefs.isBskyAppStatePref(pref) &&
AppBskyActorDefs.validateBskyAppStatePref(pref).success,
)
Expand All @@ -1399,8 +1393,8 @@ export class Agent extends XrpcClient {
validateNux(nux)

await this.updatePreferences((prefs: AppBskyActorDefs.Preferences) => {
let bskyAppStatePref: AppBskyActorDefs.BskyAppStatePref = prefs.findLast(
(pref) =>
let bskyAppStatePref = prefs.findLast(
(pref): pref is AppBskyActorDefs.BskyAppStatePref =>
AppBskyActorDefs.isBskyAppStatePref(pref) &&
AppBskyActorDefs.validateBskyAppStatePref(pref).success,
)
Expand Down Expand Up @@ -1446,8 +1440,8 @@ export class Agent extends XrpcClient {
*/
async bskyAppRemoveNuxs(ids: string[]) {
await this.updatePreferences((prefs: AppBskyActorDefs.Preferences) => {
let bskyAppStatePref: AppBskyActorDefs.BskyAppStatePref = prefs.findLast(
(pref) =>
let bskyAppStatePref = prefs.findLast(
(pref): pref is AppBskyActorDefs.BskyAppStatePref =>
AppBskyActorDefs.isBskyAppStatePref(pref) &&
AppBskyActorDefs.validateBskyAppStatePref(pref).success,
)
Expand Down
7 changes: 4 additions & 3 deletions packages/api/src/mocker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -108,7 +108,8 @@ export const mock = {
did: `did:web:${handle}`,
handle,
displayName,
description, // technically not in ProfileViewBasic but useful in some cases
// @ts-expect-error technically not in ProfileViewBasic but useful in some cases
description,
viewer,
labels,
}
Expand Down Expand Up @@ -158,7 +159,7 @@ export const mock = {
labels,
}: {
record: AppBskyFeedPost.Record
author: AppBskyActorDefs.ProfileViewBasic
author: Omit<AppBskyActorDefs.ProfileViewBasic, '$type'>
labels?: ComAtprotoLabelDefs.Label[]
}): AppBskyNotificationListNotifications.Notification {
return {
Expand All @@ -179,7 +180,7 @@ export const mock = {
subjectDid,
labels,
}: {
author: AppBskyActorDefs.ProfileViewBasic
author: Omit<AppBskyActorDefs.ProfileViewBasic, '$type'>
subjectDid: string
labels?: ComAtprotoLabelDefs.Label[]
}): AppBskyNotificationListNotifications.Notification {
Expand Down
2 changes: 1 addition & 1 deletion packages/api/src/moderation/mutewords.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ export function hasMutedWord({
facets?: AppBskyRichtextFacet.Main[]
outlineTags?: string[]
languages?: string[]
actor?: AppBskyActorDefs.ProfileView
actor?: AppBskyActorDefs.ProfileView | AppBskyActorDefs.ProfileViewBasic
}) {
const exception = LANGUAGE_EXCEPTIONS.includes(languages?.[0] || '')
const tags = ([] as string[])
Expand Down
23 changes: 19 additions & 4 deletions packages/api/src/moderation/subjects/post.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,11 @@ export function decidePost(

let embedAcc
if (subject.embed) {
if (AppBskyEmbedRecord.isViewRecord(subject.embed.record)) {
if (
(AppBskyEmbedRecord.isView(subject.embed) ||
AppBskyEmbedRecordWithMedia.isView(subject.embed)) &&
AppBskyEmbedRecord.isViewRecord(subject.embed.record)
) {
// quote post
embedAcc = decideQuotedPost(subject.embed.record, opts)
} else if (
Expand All @@ -41,7 +45,11 @@ export function decidePost(
) {
// quoted post with media
embedAcc = decideQuotedPost(subject.embed.record.record, opts)
} else if (AppBskyEmbedRecord.isViewBlocked(subject.embed.record)) {
} else if (
(AppBskyEmbedRecord.isView(subject.embed) ||
AppBskyEmbedRecordWithMedia.isView(subject.embed)) &&
AppBskyEmbedRecord.isViewBlocked(subject.embed.record)
) {
// blocked quote post
embedAcc = decideBlockedQuotedPost(subject.embed.record, opts)
} else if (
Expand Down Expand Up @@ -115,7 +123,10 @@ function checkHiddenPost(
if (hiddenPosts.includes(subject.uri)) {
return true
}
if (subject.embed) {
if (
AppBskyEmbedRecord.isView(subject.embed) ||
AppBskyEmbedRecordWithMedia.isView(subject.embed)
) {
if (
AppBskyEmbedRecord.isViewRecord(subject.embed.record) &&
hiddenPosts.includes(subject.embed.record.uri)
Expand Down Expand Up @@ -180,7 +191,11 @@ function checkMutedWords(

if (subject.embed) {
// quote post
if (AppBskyEmbedRecord.isViewRecord(subject.embed.record)) {
if (
(AppBskyEmbedRecord.isView(subject.embed) ||
AppBskyEmbedRecordWithMedia.isView(subject.embed)) &&
AppBskyEmbedRecord.isViewRecord(subject.embed.record)
) {
if (AppBskyFeedPost.isRecord(subject.embed.record.value)) {
const embeddedPost = subject.embed.record.value
const embedAuthor = subject.embed.record.author
Expand Down
5 changes: 4 additions & 1 deletion packages/api/src/moderation/subjects/user-list.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,10 @@ export function decideUserList(
): ModerationDecision {
const acc = new ModerationDecision()

const creator = isProfile(subject.creator) ? subject.creator : undefined
const creator =
'creator' in subject && isProfile(subject.creator)
? subject.creator
: undefined

if (creator) {
acc.setDid(creator.did)
Expand Down
5 changes: 4 additions & 1 deletion packages/api/tests/atp-agent.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2217,7 +2217,7 @@ describe('agent', () => {
async function addLegacyMutedWord(mutedWord: AppBskyActorDefs.MutedWord) {
await updatePreferences(agent, (prefs) => {
let mutedWordsPref = prefs.findLast(
(pref) =>
(pref): pref is AppBskyActorDefs.MutedWordsPref =>
AppBskyActorDefs.isMutedWordsPref(pref) &&
AppBskyActorDefs.validateMutedWordsPref(pref).success,
)
Expand Down Expand Up @@ -3246,6 +3246,7 @@ describe('agent', () => {

await agent.bskyAppSetActiveProgressGuide({
guide: 'test-guide',
// @ts-expect-error unspecced field
numThings: 0,
})
await expect(agent.getPreferences()).resolves.toHaveProperty(
Expand All @@ -3254,6 +3255,7 @@ describe('agent', () => {
)
await agent.bskyAppSetActiveProgressGuide({
guide: 'test-guide',
// @ts-expect-error unspecced field
numThings: 1,
})
await expect(agent.getPreferences()).resolves.toHaveProperty(
Expand Down Expand Up @@ -3332,6 +3334,7 @@ describe('agent', () => {
// @ts-expect-error
expect(() => agent.bskyAppUpsertNux({ name: 'a' })).rejects.toThrow()
expect(() =>
// @ts-expect-error
agent.bskyAppUpsertNux({ id: 'a', completed: false, foo: 'bar' }),
).rejects.toThrow()
})
Expand Down
3 changes: 2 additions & 1 deletion packages/api/tests/moderation-prefs.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { TestNetworkNoAppView } from '@atproto/dev-env'
import { DEFAULT_LABEL_SETTINGS } from '../src'
import { isContentLabelPref } from '../src/client/types/app/bsky/actor/defs'
import './util/moderation-behavior'

describe('agent', () => {
Expand Down Expand Up @@ -335,7 +336,7 @@ describe('agent', () => {
const a = await agent.app.bsky.actor.getPreferences({})

const nsfwSettings = a.data.preferences.filter(
(pref) => pref.label === 'nsfw',
(pref) => isContentLabelPref(pref) && pref.label === 'nsfw',
)
expect(nsfwSettings.length).toEqual(1)
})
Expand Down
10 changes: 7 additions & 3 deletions packages/api/tests/rich-text-detection.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
import { AtpAgent, RichText, RichTextSegment } from '../src'
import { isTag } from '../src/client/types/app/bsky/richtext/facet'
import {
isLink,
isMention,
isTag,
} from '../src/client/types/app/bsky/richtext/facet'

describe('detectFacets', () => {
const agent = new AtpAgent({ service: 'http://localhost' })
Expand Down Expand Up @@ -374,10 +378,10 @@ function segmentToOutput(segment: RichTextSegment): string[] {
return [
segment.text,
segment.facet?.features.map((f) => {
if (f.did) {
if (isMention(f)) {
return String(f.did)
}
if (f.uri) {
if (isLink(f)) {
return String(f.uri)
}
return undefined
Expand Down
2 changes: 1 addition & 1 deletion packages/bsky/src/api/app/bsky/actor/getSuggestions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -148,5 +148,5 @@ type Params = QueryParams & {
type Skeleton = {
dids: string[]
cursor?: string
resHeaders?: Record<string, string>
resHeaders?: Record<string, undefined | string>
}
14 changes: 6 additions & 8 deletions packages/bsky/src/api/app/bsky/feed/getFeed.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import {
import { ResponseType, XRPCError } from '@atproto/xrpc'
import { AtpAgent, AppBskyFeedGetFeedSkeleton } from '@atproto/api'
import { noUndefinedVals } from '@atproto/common'
import { isSkeletonReasonRepost } from '../../../../lexicon/types/app/bsky/feed/defs'
import { QueryParams as GetFeedParams } from '../../../../lexicon/types/app/bsky/feed/getFeed'
import { OutputSchema as SkeletonOutput } from '../../../../lexicon/types/app/bsky/feed/getFeedSkeleton'
import { Server } from '../../../../lexicon'
Expand Down Expand Up @@ -42,10 +43,8 @@ export default function (server: Server, ctx: AppContext) {
auth: ctx.authVerifier.standardOptionalParameterized({
lxmCheck: (method) => {
return (
method !== undefined &&
[ids.AppBskyFeedGetFeedSkeleton, ids.AppBskyFeedGetFeed].includes(
method,
)
method === ids.AppBskyFeedGetFeedSkeleton ||
method === ids.AppBskyFeedGetFeed
)
},
skipAudCheck: true,
Expand Down Expand Up @@ -247,10 +246,9 @@ const skeletonFromFeedGen = async (
const { feed: feedSkele, ...skele } = skeleton
const feedItems = feedSkele.slice(0, params.limit).map((item) => ({
post: { uri: item.post },
repost:
typeof item.reason?.repost === 'string'
? { uri: item.reason.repost }
: undefined,
repost: isSkeletonReasonRepost(item.reason)
? { uri: item.reason.repost }
: undefined,
feedContext: item.feedContext,
}))

Expand Down
4 changes: 2 additions & 2 deletions packages/bsky/src/api/app/bsky/labeler/getServices.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,15 +21,15 @@ export default function (server: Server, ctx: AppContext) {
const view = ctx.views.labelerDetailed(did, hydration)
if (!view) return
return {
$type: 'app.bsky.labeler.defs#labelerViewDetailed',
...view,
$type: 'app.bsky.labeler.defs#labelerViewDetailed',
}
} else {
const view = ctx.views.labeler(did, hydration)
if (!view) return
return {
$type: 'app.bsky.labeler.defs#labelerView',
...view,
$type: 'app.bsky.labeler.defs#labelerView',
}
}
})
Expand Down
5 changes: 4 additions & 1 deletion packages/bsky/src/hydration/graph.ts
Original file line number Diff line number Diff line change
Expand Up @@ -176,7 +176,10 @@ export class GraphHydrator {
}, new HydrationMap<Follow>())
}

async getBlocks(uris: string[], includeTakedowns = false): Promise<Follows> {
async getBlocks(
uris: string[],
includeTakedowns = false,
): Promise<HydrationMap<Block>> {
if (!uris.length) return new HydrationMap<Block>()
const res = await this.dataplane.getBlockRecords({ uris })
return uris.reduce((acc, uri, i) => {
Expand Down
6 changes: 4 additions & 2 deletions packages/bsky/src/hydration/util.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,9 @@ export interface Merges {
merge<T extends this>(map: T): this
}

export type RecordInfo<T> = {
export type UnknownRecord = { $type?: string; [x: string]: unknown }

export type RecordInfo<T extends UnknownRecord> = {
record: T
cid: string
sortedAt: Date
Expand Down Expand Up @@ -56,7 +58,7 @@ export const mergeManyMaps = <T>(...maps: HydrationMap<T>[]) => {

export type ItemRef = { uri: string; cid?: string }

export const parseRecord = <T>(
export const parseRecord = <T extends UnknownRecord>(
entry: Record,
includeTakedowns: boolean,
): RecordInfo<T> | undefined => {
Expand Down
Loading

0 comments on commit 77c134f

Please sign in to comment.