Skip to content

A free and open source instant messaging and VoIP chat app built for friends, groups, and communities.

TypeScript fluxerfluxerapp
46.9 KB
Raw Blame
// SPDX-License-Identifier: AGPL-3.0-or-later

import Authentication from '@app/features/auth/state/Authentication';
import Channels from '@app/features/channel/state/Channels';
import GatewaySessions from '@app/features/gateway/transport/GatewaySessionPool';
import Guilds from '@app/features/guild/state/Guilds';
import {GuildMember} from '@app/features/member/models/GuildMember';
import GuildMembers from '@app/features/member/state/GuildMembers';
import {getHydratedMemberListRangesFromNormalized} from '@app/features/member/utils/MemberListHydration';
import {deriveMemberListIdentity} from '@app/features/member/utils/MemberListIdentity';
import {
	buildMemberListLayout,
	getTotalMemberCount,
	getTotalRowsFromLayout,
	type MemberListGroupLayout,
} from '@app/features/member/utils/MemberListLayout';
import {
	areNormalizedMemberListRangesCovered,
	isIndexInMemberListRanges,
	type MemberListRanges,
	type NormalizedMemberListRanges,
	normalizeMemberListRanges,
} from '@app/features/member/utils/MemberListRangeUtils';
import {Logger} from '@app/features/platform/utils/AppLogger';
import type {CustomStatus, GatewayCustomStatusPayload} from '@app/features/user/state/CustomStatus';
import {fromGatewayCustomStatus} from '@app/features/user/state/CustomStatus';
import {CustomStatusEmitter} from '@app/features/user/state/CustomStatusEmitter';
import {GuildOperations} from '@fluxer/constants/src/GuildConstants';
import type {StatusType} from '@fluxer/constants/src/StatusConstants';
import {StatusTypes} from '@fluxer/constants/src/StatusConstants';
import type {GuildMemberData} from '@fluxer/schema/src/domains/guild/GuildMemberSchemas';
import type {UserPartialResponse} from '@fluxer/schema/src/domains/user/UserResponseSchemas';
import {makeAutoObservable, observableRef} from 'mobx';

interface MemberListGroup {
	id: string;
	count: number;
}

interface MemberListMember {
	userId: string;
	member: GuildMemberData;
}

interface MemberListItem {
	type: 'member';
	data: MemberListMember;
}

interface MemberListState {
	hasReceivedInitialPayload: boolean;
	memberCount: number;
	onlineCount: number;
	groups: Array<MemberListGroup>;
	rows: Map<number, MemberListRow>;
	items: Map<number, MemberListItem>;
	membersByUserId: Map<string, GuildMemberData>;
	requestedRanges: NormalizedMemberListRanges;
	subscribedRanges: NormalizedMemberListRanges;
	presences: Map<string, StatusType>;
	mobileUserIds: Set<string>;
	customStatuses: Map<string, CustomStatus | null>;
	knownCustomStatuses: Map<string, CustomStatus | null>;
}

interface MemberListRow {
	type: 'group' | 'member';
	group?: MemberListGroup;
	userId?: string;
	member?: GuildMemberData;
	presence?: {
		status?: string;
		mobile?: boolean;
		custom_status?: GatewayCustomStatusPayload | null;
	} | null;
}

type MemberListOperationMember = GuildMemberData & {
	presence?: {
		status?: string;
		mobile?: boolean;
		custom_status?: GatewayCustomStatusPayload | null;
	} | null;
};

type MemberListOperationItem = {
	member?: MemberListOperationMember;
	group?: MemberListGroup;
};

interface MemberListOperation {
	op: 'SYNC';
	range: [number, number];
	items: ReadonlyArray<MemberListOperationItem>;
}

interface MemberListUpdateParams {
	guildId: string;
	listId: string;
	channelId?: string;
	memberCount: number;
	onlineCount: number;
	groups: ReadonlyArray<MemberListGroup>;
	ops: ReadonlyArray<MemberListOperation>;
}

interface PendingMemberListUpdateBatch {
	guildId: string;
	listId: string;
	timeoutId: number;
	demand: MemberListUpdateDemand;
	updates: Array<MemberListUpdateParams>;
}

interface MemberListUpdateDemand {
	generation: number;
	guildId: string;
	channelId: string;
	ownerId: string | null;
}

const MEMBER_LIST_UPDATE_BATCH_MS = 1000;
const EMPTY_MEMBER_LIST_RANGES = normalizeMemberListRanges([]);

interface MemberListSubscription {
	guildId: string;
	channelId: string;
	ownerId: string | null;
}

function areCustomStatusesEqual(
	left: CustomStatus | null | undefined,
	right: CustomStatus | null | undefined,
): boolean {
	if (left == null || right == null) {
		return left == null && right == null;
	}
	return (
		left.text === right.text &&
		left.expiresAt === right.expiresAt &&
		left.emojiId === right.emojiId &&
		left.emojiName === right.emojiName &&
		(left.emojiAnimated ?? null) === (right.emojiAnimated ?? null)
	);
}

function areMemberUsersEqual(left: UserPartialResponse, right: UserPartialResponse): boolean {
	return (
		left === right ||
		(left.id === right.id &&
			left.username === right.username &&
			left.discriminator === right.discriminator &&
			left.global_name === right.global_name &&
			left.avatar === right.avatar &&
			left.avatar_color === right.avatar_color &&
			left.bot === right.bot &&
			left.system === right.system &&
			left.flags === right.flags &&
			left.mention_flags === right.mention_flags)
	);
}

function areMemberRolesEqual(left: ReadonlyArray<string>, right: ReadonlyArray<string>): boolean {
	if (left === right) {
		return true;
	}
	if (left.length !== right.length) {
		return false;
	}
	for (let index = 0; index < left.length; index += 1) {
		if (left[index] !== right[index]) {
			return false;
		}
	}
	return true;
}

function areMemberIdentitiesEqual(left: GuildMemberData, right: GuildMemberData): boolean {
	return (
		left === right ||
		(left.nick === right.nick &&
			left.avatar === right.avatar &&
			left.banner === right.banner &&
			left.accent_color === right.accent_color &&
			left.joined_at === right.joined_at &&
			left.mute === right.mute &&
			left.deaf === right.deaf &&
			left.communication_disabled_until === right.communication_disabled_until &&
			left.profile_flags === right.profile_flags &&
			left.mention_flags === right.mention_flags &&
			areMemberRolesEqual(left.roles, right.roles) &&
			areMemberUsersEqual(left.user, right.user))
	);
}

function areMemberListGroupsEqual(
	left: ReadonlyArray<MemberListGroup>,
	right: ReadonlyArray<MemberListGroup>,
): boolean {
	if (left === right) {
		return true;
	}
	if (left.length !== right.length) {
		return false;
	}
	for (let index = 0; index < left.length; index += 1) {
		if (left[index].id !== right[index].id || left[index].count !== right[index].count) {
			return false;
		}
	}
	return true;
}

function areRangesEqual(left?: Array<[number, number]>, right?: Array<[number, number]>): boolean {
	const leftRanges = left ?? [];
	const rightRanges = right ?? [];
	if (leftRanges.length !== rightRanges.length) {
		return false;
	}
	for (let i = 0; i < leftRanges.length; i++) {
		const [leftStart, leftEnd] = leftRanges[i];
		const [rightStart, rightEnd] = rightRanges[i];
		if (leftStart !== rightStart || leftEnd !== rightEnd) {
			return false;
		}
	}
	return true;
}

class MemberSidebar {
	private logger = new Logger('MemberSidebar');
	lists: Record<string, Record<string, MemberListState>> = {};
	private wireListChannelIds: Record<string, Record<string, string>> = {};
	private listSubscribedChannelIds: Record<string, Record<string, string>> = {};
	private syncedMemberListGuildIds = new Set<string>();
	private sentMemberListGuildId: string | null = null;
	private sentMemberListChannelId: string | null = null;
	private sentMemberListRanges: NormalizedMemberListRanges = EMPTY_MEMBER_LIST_RANGES;
	private gatewaySessionId: string | null = null;
	private activeMemberListSubscription: MemberListSubscription | null = null;
	sessionVersion = 0;
	memberListSubscriptionGeneration = 0;
	private materializedMemberCache = new WeakMap<MemberListMember, GuildMember>();
	private memberListItemCache = new WeakMap<GuildMemberData, MemberListItem>();
	private pendingListUpdateBatches = new Map<string, PendingMemberListUpdateBatch>();

	constructor() {
		makeAutoObservable<
			this,
			| 'wireListChannelIds'
			| 'listSubscribedChannelIds'
			| 'syncedMemberListGuildIds'
			| 'sentMemberListGuildId'
			| 'sentMemberListChannelId'
			| 'sentMemberListRanges'
			| 'gatewaySessionId'
			| 'activeMemberListSubscription'
			| 'materializedMemberCache'
			| 'memberListItemCache'
			| 'pendingListUpdateBatches'
		>(
			this,
			{
				lists: observableRef,
				wireListChannelIds: false,
				listSubscribedChannelIds: false,
				syncedMemberListGuildIds: false,
				sentMemberListGuildId: false,
				sentMemberListChannelId: false,
				sentMemberListRanges: false,
				gatewaySessionId: false,
				activeMemberListSubscription: false,
				materializedMemberCache: false,
				memberListItemCache: false,
				pendingListUpdateBatches: false,
			},
			{autoBind: true},
		);
	}

	synchronizeGatewaySession(sessionId: string | null): void {
		const previousSessionId = this.gatewaySessionId;
		if (previousSessionId === sessionId) {
			return;
		}
		this.gatewaySessionId = sessionId;
		if (previousSessionId !== null || sessionId === null) {
			this.handleSessionInvalidated();
		}
	}

	handleSessionInvalidated(): void {
		this.clearPendingListUpdateBatches();
		this.lists = {};
		this.wireListChannelIds = {};
		this.listSubscribedChannelIds = {};
		this.syncedMemberListGuildIds.clear();
		this.clearSentMemberListSubscription();
		this.setActiveMemberListSubscription(null);
		this.sessionVersion += 1;
	}

	handleGuildDelete(guildId: string): void {
		this.clearPendingListUpdateBatches(guildId);
		if (this.lists[guildId]) {
			const {[guildId]: _, ...remainingLists} = this.lists;
			this.lists = remainingLists;
		}
		if (this.wireListChannelIds[guildId]) {
			const {[guildId]: _, ...remainingWireMappings} = this.wireListChannelIds;
			this.wireListChannelIds = remainingWireMappings;
		}
		if (this.listSubscribedChannelIds[guildId]) {
			const {[guildId]: _, ...remainingSubscribedChannels} = this.listSubscribedChannelIds;
			this.listSubscribedChannelIds = remainingSubscribedChannels;
		}
		this.syncedMemberListGuildIds.delete(guildId);
		if (this.sentMemberListGuildId === guildId) {
			this.clearSentMemberListSubscription();
		}
		if (this.activeMemberListSubscription?.guildId === guildId) {
			this.setActiveMemberListSubscription(null);
		}
	}

	handleGuildCreate(guildId: string): void {
		this.handleGuildDelete(guildId);
	}

	handleGuildStorageIdentityChange(guildId: string): void {
		const subscribedChannels = this.listSubscribedChannelIds[guildId];
		if (subscribedChannels == null) {
			return;
		}
		const existingGuildLists = this.lists[guildId] ?? {};
		const nextSubscribedChannels: Record<string, string> = {};
		const changedStorageKeys = new Set<string>();
		const rekeyedRequestedRanges = new Map<string, NormalizedMemberListRanges>();
		for (const [previousStorageKey, channelId] of Object.entries(subscribedChannels)) {
			const storageKey = this.resolveStorageKey(guildId, channelId);
			nextSubscribedChannels[storageKey] = channelId;
			if (storageKey === previousStorageKey) {
				continue;
			}
			changedStorageKeys.add(previousStorageKey);
			changedStorageKeys.add(storageKey);
			rekeyedRequestedRanges.set(
				storageKey,
				existingGuildLists[previousStorageKey]?.requestedRanges ?? EMPTY_MEMBER_LIST_RANGES,
			);
		}
		if (changedStorageKeys.size === 0) {
			return;
		}
		for (const storageKey of changedStorageKeys) {
			this.clearPendingListUpdateBatch(guildId, storageKey);
		}
		const guildLists: Record<string, MemberListState> = {...existingGuildLists};
		for (const storageKey of changedStorageKeys) {
			delete guildLists[storageKey];
		}
		for (const [storageKey, requestedRanges] of rekeyedRequestedRanges) {
			guildLists[storageKey] = this.createEmptyListState(requestedRanges);
		}
		this.lists = {...this.lists, [guildId]: guildLists};
		this.listSubscribedChannelIds = {...this.listSubscribedChannelIds, [guildId]: nextSubscribedChannels};
		this.syncedMemberListGuildIds.delete(guildId);
		if (this.sentMemberListGuildId === guildId) {
			this.clearSentMemberListSubscription();
		}
		this.memberListSubscriptionGeneration += 1;
	}

	handleListUpdate(params: MemberListUpdateParams): void {
		const {guildId} = params;
		if (this.isMemberListUpdatesDisabled(guildId)) {
			return;
		}
		const demand = this.getMemberListUpdateDemand(params);
		if (demand == null) {
			return;
		}
		const storageKey = this.resolveStorageKey(guildId, demand.channelId);
		const existingList = this.lists[guildId]?.[storageKey];
		if (!existingList?.hasReceivedInitialPayload || typeof window === 'undefined') {
			this.applyListUpdate(params, demand);
			return;
		}
		if (this.shouldBypassListUpdateBatchForCurrentUserPresence(params, existingList)) {
			this.flushPendingListUpdateBatch(this.getListUpdateBatchKey(guildId, storageKey));
			this.applyListUpdate(params, demand);
			return;
		}
		this.queueListUpdate(params, demand);
	}

	private queueListUpdate(params: MemberListUpdateParams, demand: MemberListUpdateDemand): void {
		if (!this.isMemberListUpdateAccepted(demand, params)) {
			return;
		}
		const {guildId} = params;
		const storageKey = this.resolveStorageKey(guildId, demand.channelId);
		const batchKey = this.getListUpdateBatchKey(guildId, storageKey);
		let batch = this.pendingListUpdateBatches.get(batchKey);
		if (
			batch != null &&
			(!this.isMemberListUpdateDemandCurrent(batch.demand) ||
				!this.areMemberListUpdateDemandsEqual(batch.demand, demand))
		) {
			window.clearTimeout(batch.timeoutId);
			this.pendingListUpdateBatches.delete(batchKey);
			batch = undefined;
		}
		if (!batch) {
			batch = {
				guildId,
				listId: storageKey,
				timeoutId: window.setTimeout(() => this.flushPendingListUpdateBatch(batchKey), MEMBER_LIST_UPDATE_BATCH_MS),
				demand,
				updates: [],
			};
			this.pendingListUpdateBatches.set(batchKey, batch);
		}
		if (batch.updates.length === 0) {
			batch.updates.push(params);
		} else {
			batch.updates[0] = this.mergeQueuedListUpdate(batch.updates[0], params);
		}
	}

	private flushPendingListUpdateBatch(batchKey: string): void {
		const batch = this.pendingListUpdateBatches.get(batchKey);
		if (!batch) {
			return;
		}
		this.pendingListUpdateBatches.delete(batchKey);
		window.clearTimeout(batch.timeoutId);
		for (const update of batch.updates) {
			this.applyListUpdate(update, batch.demand);
		}
	}

	private clearPendingListUpdateBatches(guildId?: string): void {
		for (const [batchKey, batch] of Array.from(this.pendingListUpdateBatches.entries())) {
			if (guildId !== undefined && batch.guildId !== guildId) {
				continue;
			}
			window.clearTimeout(batch.timeoutId);
			this.pendingListUpdateBatches.delete(batchKey);
		}
	}

	private clearPendingListUpdateBatch(guildId: string, storageKey: string): void {
		const batchKey = this.getListUpdateBatchKey(guildId, storageKey);
		const batch = this.pendingListUpdateBatches.get(batchKey);
		if (!batch) {
			return;
		}
		window.clearTimeout(batch.timeoutId);
		this.pendingListUpdateBatches.delete(batchKey);
	}

	private getListUpdateBatchKey(guildId: string, listId: string): string {
		return `${guildId}\u0000${listId}`;
	}

	private mergeQueuedListUpdate(
		existing: MemberListUpdateParams,
		next: MemberListUpdateParams,
	): MemberListUpdateParams {
		return {
			...next,
			channelId: next.channelId ?? existing.channelId,
			ops: this.mergeMemberListSyncOps([...existing.ops, ...next.ops]),
		};
	}

	private mergeMemberListSyncOps(ops: Array<MemberListOperation>): Array<MemberListOperation> {
		const mergedOps: Array<MemberListOperation> = [];
		for (const op of ops) {
			let mergedOp = op;
			for (let index = 0; index < mergedOps.length; ) {
				const existing = mergedOps[index];
				if (!this.doMemberListSyncRangesOverlap(existing.range, mergedOp.range)) {
					index += 1;
					continue;
				}
				mergedOp = this.mergeMemberListSyncOp(existing, mergedOp);
				mergedOps.splice(index, 1);
			}
			mergedOps.push(mergedOp);
		}
		mergedOps.sort((left, right) => left.range[0] - right.range[0]);
		return mergedOps;
	}

	private doMemberListSyncRangesOverlap(left: [number, number], right: [number, number]): boolean {
		return left[0] <= right[1] && right[0] <= left[1];
	}

	private mergeMemberListSyncOp(existing: MemberListOperation, next: MemberListOperation): MemberListOperation {
		const start = Math.min(existing.range[0], next.range[0]);
		const end = Math.max(existing.range[1], next.range[1]);
		const rows = new Map<number, MemberListOperationItem>();
		this.applyMemberListSyncOpToRows(rows, existing);
		this.applyMemberListSyncOpToRows(rows, next);
		const items: Array<MemberListOperationItem> = [];
		for (let index = start; index <= end; index += 1) {
			items.push(rows.get(index) ?? {});
		}
		return {
			op: 'SYNC',
			range: [start, end],
			items,
		};
	}

	private applyMemberListSyncOpToRows(rows: Map<number, MemberListOperationItem>, op: MemberListOperation): void {
		const [start, end] = op.range;
		for (let index = start; index <= end; index += 1) {
			rows.delete(index);
		}
		let nextIndex = start;
		for (const item of op.items) {
			if (this.isEmptyGroupItem(item)) {
				continue;
			}
			if (item.member?.user?.id || item.group) {
				rows.set(nextIndex, item);
			} else {
				rows.delete(nextIndex);
			}
			nextIndex += 1;
		}
	}

	private shouldBypassListUpdateBatchForCurrentUserPresence(
		params: MemberListUpdateParams,
		listState: MemberListState,
	): boolean {
		const currentUserId = Authentication.currentUserId;
		if (!currentUserId || listState.requestedRanges.length === 0) {
			return false;
		}
		let currentUserVisible = false;
		for (const item of listState.items.values()) {
			if (item.data.userId === currentUserId) {
				currentUserVisible = true;
				break;
			}
		}
		if (!currentUserVisible) {
			return false;
		}
		for (const op of params.ops) {
			for (const item of op.items) {
				const member = item.member;
				if (member?.user?.id !== currentUserId) {
					continue;
				}
				if (this.memberPresencePayloadChanged(listState, currentUserId, member.presence ?? null)) {
					return true;
				}
			}
		}
		return false;
	}

	private memberPresencePayloadChanged(
		listState: MemberListState,
		userId: string,
		presence: MemberListOperationMember['presence'],
	): boolean {
		if (!presence) {
			return false;
		}
		if (presence.status != null) {
			const nextStatus = this.normalizeStatus(presence.status);
			const currentStatus = listState.presences.get(userId) ?? StatusTypes.OFFLINE;
			if (nextStatus !== currentStatus) {
				return true;
			}
		}
		if (Object.hasOwn(presence, 'custom_status')) {
			const nextCustomStatus = fromGatewayCustomStatus(presence.custom_status ?? null);
			const currentCustomStatus = listState.customStatuses.has(userId)
				? (listState.customStatuses.get(userId) ?? null)
				: (listState.knownCustomStatuses.get(userId) ?? null);
			if (!areCustomStatusesEqual(currentCustomStatus, nextCustomStatus)) {
				return true;
			}
		}
		return false;
	}

	private applyListUpdate(params: MemberListUpdateParams, demand: MemberListUpdateDemand): void {
		if (!this.isMemberListUpdateAccepted(demand, params)) {
			return;
		}
		const {guildId, listId, channelId, memberCount, onlineCount, groups, ops} = params;
		if (this.isMemberListUpdatesDisabled(guildId)) {
			return;
		}
		if (channelId != null) {
			this.registerWireListChannel(guildId, listId, channelId);
		}
		const storageKey = this.resolveStorageKey(guildId, demand.channelId);
		const existingGuildLists = this.lists[guildId] ?? {};
		const guildLists: Record<string, MemberListState> = {...existingGuildLists};
		if (!guildLists[storageKey]) {
			guildLists[storageKey] = this.createEmptyListState();
		}
		const listState = guildLists[storageKey];
		const retainedMembers = listState.membersByUserId;
		const opRows = new Map<number, MemberListRow | null>();
		const changedCustomStatusUserIds = new Set<string>();
		for (const op of ops) {
			const [start, end] = op.range;
			for (let i = start; i <= end; i++) {
				opRows.set(i, null);
			}
			let nextIndex = start;
			for (const rawItem of op.items) {
				const row = this.convertRow(rawItem, retainedMembers);
				if (row) {
					opRows.set(nextIndex, row);
					nextIndex += 1;
				} else if (!this.isEmptyGroupItem(rawItem)) {
					nextIndex += 1;
				}
			}
		}
		const visibleGroups = this.visibleGroups(listState.groups, groups);
		const groupLayouts = buildMemberListLayout(visibleGroups);
		const totalMembers = Math.max(memberCount, getTotalMemberCount(visibleGroups));
		const totalRows = groupLayouts.length > 0 ? getTotalRowsFromLayout(groupLayouts) : totalMembers;
		const requestedRanges = listState.requestedRanges;
		const previousRows = listState.rows;
		const newRows = new Map<number, MemberListRow>();
		const newItems = new Map<number, MemberListItem>();
		const newPresences = new Map<string, StatusType>();
		const newMobileUserIds = new Set<string>();
		const newCustomStatuses = new Map<string, CustomStatus | null>();
		const newMembersByUserId = new Map<string, GuildMemberData>();
		const nextKnownCustomStatuses = new Map(listState.knownCustomStatuses);
		const userIdRowCounts = new Map<string, number>();
		const recordCustomStatus = (userId: string, customStatus: CustomStatus | null) => {
			newCustomStatuses.set(userId, customStatus);
			const hadKnownCustomStatus = nextKnownCustomStatuses.has(userId);
			const previousKnownCustomStatus = hadKnownCustomStatus
				? (nextKnownCustomStatuses.get(userId) ?? null)
				: undefined;
			if (!hadKnownCustomStatus || !areCustomStatusesEqual(previousKnownCustomStatus ?? null, customStatus)) {
				changedCustomStatusUserIds.add(userId);
			}
			nextKnownCustomStatuses.set(userId, customStatus);
		};
		const clearKnownCustomStatus = (userId: string) => {
			if ((nextKnownCustomStatuses.get(userId) ?? null) == null) {
				return;
			}
			recordCustomStatus(userId, null);
		};
		let layoutCursor = 0;
		const visitRow = (rowIndex: number, row: MemberListRow) => {
			newRows.set(rowIndex, row);
			const {userId, member} = row;
			if (row.type !== 'member' || !userId || !member) {
				return;
			}
			let rowGroupId: string | null = null;
			if (groupLayouts.length > 0) {
				while (layoutCursor < groupLayouts.length && groupLayouts[layoutCursor]!.rowEndIndex < rowIndex) {
					layoutCursor += 1;
				}
				const layout: MemberListGroupLayout | undefined = groupLayouts[layoutCursor];
				if (layout == null || rowIndex <= layout.headerRowIndex) {
					return;
				}
				rowGroupId = layout.id;
			}
			userIdRowCounts.set(userId, (userIdRowCounts.get(userId) ?? 0) + 1);
			newMembersByUserId.set(userId, member);
			GuildMembers.hydrateIfMissing(guildId, member);
			const memberItem = this.convertItem(guildId, row);
			if (memberItem) {
				newItems.set(rowIndex, memberItem);
			}
			const presenceStatus = this.extractPresenceFromRow(row);
			if (presenceStatus) {
				newPresences.set(userId, presenceStatus);
				if (presenceStatus !== StatusTypes.OFFLINE && row.presence?.mobile === true) {
					newMobileUserIds.add(userId);
				}
			}
			if (row.presence && Object.hasOwn(row.presence, 'custom_status')) {
				const customStatus = fromGatewayCustomStatus(row.presence.custom_status ?? null);
				recordCustomStatus(userId, customStatus);
			} else if (presenceStatus === StatusTypes.OFFLINE || (row.presence == null && rowGroupId === 'offline')) {
				clearKnownCustomStatus(userId);
			}
		};
		const resolveRow = (rowIndex: number): MemberListRow | null => {
			if (rowIndex < 0 || rowIndex >= totalRows) {
				return null;
			}
			const patchedRow = opRows.get(rowIndex);
			if (patchedRow !== undefined) {
				return patchedRow;
			}
			return previousRows.get(rowIndex) ?? null;
		};
		if (requestedRanges.length > 0) {
			for (const [start, end] of requestedRanges) {
				const lastRowIndex = Math.min(end, totalRows - 1);
				for (let rowIndex = Math.max(0, start); rowIndex <= lastRowIndex; rowIndex += 1) {
					const row = resolveRow(rowIndex);
					if (row) {
						visitRow(rowIndex, row);
					}
				}
			}
		} else {
			const candidateRowIndexes = new Set<number>(previousRows.keys());
			for (const rowIndex of opRows.keys()) {
				candidateRowIndexes.add(rowIndex);
			}
			for (const rowIndex of Array.from(candidateRowIndexes).sort((left, right) => left - right)) {
				const row = resolveRow(rowIndex);
				if (row) {
					visitRow(rowIndex, row);
				}
			}
		}
		const duplicateUserIds: Array<string> = [];
		for (const [userId, count] of userIdRowCounts) {
			if (count > 1) {
				duplicateUserIds.push(userId);
			}
		}
		listState.memberCount = memberCount;
		listState.onlineCount = onlineCount;
		listState.groups = visibleGroups;
		listState.rows = newRows;
		listState.items = newItems;
		listState.membersByUserId = newMembersByUserId;
		listState.presences = newPresences;
		listState.mobileUserIds = newMobileUserIds;
		listState.customStatuses = newCustomStatuses;
		listState.knownCustomStatuses = nextKnownCustomStatuses;
		listState.subscribedRanges = getHydratedMemberListRangesFromNormalized(
			{
				memberCount: totalMembers,
				groups: visibleGroups,
				layouts: groupLayouts,
				itemIndexes: newItems,
			},
			requestedRanges,
		);
		listState.hasReceivedInitialPayload = true;
		this.lists = {...this.lists, [guildId]: {...guildLists, [storageKey]: listState}};
		if (duplicateUserIds.length > 0) {
			const uniqueDuplicateUserIds = Array.from(new Set(duplicateUserIds));
			this.logger.warn('Duplicate member rows received in list update:', {
				guildId,
				listId: storageKey,
				duplicateCount: uniqueDuplicateUserIds.length,
				userIds: uniqueDuplicateUserIds.slice(0, 25),
			});
		}
		if (changedCustomStatusUserIds.size > 0) {
			queueMicrotask(() => {
				for (const userId of changedCustomStatusUserIds) {
					CustomStatusEmitter.emitMemberListChange(guildId, storageKey, userId);
				}
			});
		}
	}

	private getMemberListUpdateDemand(params: MemberListUpdateParams): MemberListUpdateDemand | null {
		const active = this.activeMemberListSubscription;
		if (active == null) {
			return null;
		}
		const demand: MemberListUpdateDemand = {
			generation: this.memberListSubscriptionGeneration,
			guildId: active.guildId,
			channelId: active.channelId,
			ownerId: active.ownerId,
		};
		if (!this.isMemberListUpdateAccepted(demand, params)) {
			return null;
		}
		return demand;
	}

	private isMemberListUpdateDemandCurrent(demand: MemberListUpdateDemand): boolean {
		if (demand.generation !== this.memberListSubscriptionGeneration) {
			return false;
		}
		const active = this.activeMemberListSubscription;
		if (
			active == null ||
			active.guildId !== demand.guildId ||
			active.channelId !== demand.channelId ||
			active.ownerId !== demand.ownerId
		) {
			return false;
		}
		const storageKey = this.resolveStorageKey(demand.guildId, demand.channelId);
		const guildLists = this.lists[demand.guildId];
		const listState = guildLists == null ? undefined : guildLists[storageKey];
		return listState != null && listState.requestedRanges.length > 0;
	}

	private isMemberListUpdateAccepted(demand: MemberListUpdateDemand, params: MemberListUpdateParams): boolean {
		if (!this.isMemberListUpdateDemandCurrent(demand) || params.guildId !== demand.guildId) {
			return false;
		}
		return this.resolveUpdateChannelId(demand.guildId, params) === demand.channelId;
	}

	private resolveUpdateChannelId(guildId: string, params: MemberListUpdateParams): string | undefined {
		if (params.channelId != null) {
			return params.channelId;
		}
		return this.wireListChannelIds[guildId]?.[params.listId];
	}

	private areMemberListUpdateDemandsEqual(left: MemberListUpdateDemand, right: MemberListUpdateDemand): boolean {
		return (
			left.generation === right.generation &&
			left.guildId === right.guildId &&
			left.channelId === right.channelId &&
			left.ownerId === right.ownerId
		);
	}

	handleGatewayDisconnected(): void {
		this.listSubscribedChannelIds = {};
		this.syncedMemberListGuildIds.clear();
		this.clearSentMemberListSubscription();
	}

	private convertRow(
		rawItem: MemberListOperationItem,
		retainedMembers: Map<string, GuildMemberData>,
	): MemberListRow | null {
		if (rawItem.group) {
			if (Math.max(0, rawItem.group.count) === 0) {
				return null;
			}
			return {
				type: 'group',
				group: rawItem.group,
			};
		}
		const member = rawItem.member;
		if (!member?.user?.id) {
			return null;
		}
		const retained = retainedMembers.get(member.user.id);
		return {
			type: 'member',
			userId: member.user.id,
			member: retained != null && areMemberIdentitiesEqual(retained, member) ? retained : member,
			presence: member.presence ?? null,
		};
	}

	private visibleGroups(
		previousGroups: Array<MemberListGroup>,
		groups: ReadonlyArray<MemberListGroup>,
	): Array<MemberListGroup> {
		const nextGroups = groups.filter((group) => Math.max(0, group.count) > 0);
		return areMemberListGroupsEqual(previousGroups, nextGroups) ? previousGroups : nextGroups;
	}

	private isEmptyGroupItem(rawItem: MemberListOperationItem): boolean {
		return rawItem.group !== undefined && Math.max(0, rawItem.group.count) === 0;
	}

	private convertItem(guildId: string, row: MemberListRow): MemberListItem | null {
		const {member, userId} = row;
		if (!member || !userId) {
			this.logger.warn('Member not found in store:', {guildId, userId: row.userId});
			return null;
		}
		const cachedItem = this.memberListItemCache.get(member);
		if (cachedItem != null && cachedItem.data.userId === userId) {
			return cachedItem;
		}
		const item: MemberListItem = {type: 'member', data: {userId, member}};
		this.memberListItemCache.set(member, item);
		return item;
	}

	materializeItemMember(guildId: string, item: MemberListItem | null | undefined): GuildMember | null {
		if (!item) {
			return null;
		}
		const cachedMember = this.materializedMemberCache.get(item.data);
		if (cachedMember) {
			return cachedMember;
		}
		const member = new GuildMember(guildId, item.data.member, {cacheUser: false});
		this.materializedMemberCache.set(item.data, member);
		return member;
	}

	private extractPresenceFromRow(row: MemberListRow): StatusType | null {
		const status = row.presence?.status;
		if (!status) {
			return null;
		}
		return this.normalizeStatus(status);
	}

	private normalizeStatus(status: string): StatusType {
		switch (status.toLowerCase()) {
			case 'online':
				return StatusTypes.ONLINE;
			case 'idle':
				return StatusTypes.IDLE;
			case 'dnd':
				return StatusTypes.DND;
			default:
				return StatusTypes.OFFLINE;
		}
	}

	subscribeToChannel(
		guildId: string,
		channelId: string,
		ranges: Array<[number, number]>,
		ownerId: string | null = null,
	): boolean {
		if (this.isMemberListUpdatesDisabled(guildId)) {
			return false;
		}
		if (ownerId == null) {
			this.claimMemberListSubscription(guildId, channelId, null);
		} else if (!this.isActiveMemberListSubscriptionOwner(guildId, channelId, ownerId)) {
			return false;
		}
		return this.applyChannelSubscription(guildId, channelId, ranges);
	}

	retryChannelSubscription(
		guildId: string,
		channelId: string,
		ranges: Array<[number, number]>,
		ownerId: string,
		forceResend = false,
	): boolean {
		if (!this.isActiveMemberListSubscriptionOwner(guildId, channelId, ownerId)) {
			return false;
		}
		return this.applyChannelSubscription(guildId, channelId, ranges, forceResend);
	}

	updateChannelSubscriptionRangesLocally(
		guildId: string,
		channelId: string,
		ranges: MemberListRanges,
		ownerId: string,
	): boolean {
		if (!this.isActiveMemberListSubscriptionOwner(guildId, channelId, ownerId)) {
			return false;
		}
		this.applyLocalChannelSubscription(guildId, channelId, normalizeMemberListRanges(ranges));
		return true;
	}

	private applyChannelSubscription(
		guildId: string,
		channelId: string,
		ranges: Array<[number, number]>,
		forceResend = false,
	): boolean {
		if (Guilds.getGuild(guildId)?.visiting === true) {
			return false;
		}
		const normalizedRanges = normalizeMemberListRanges(ranges);
		const storageKey = this.resolveStorageKey(guildId, channelId);
		const socket = GatewaySessions.foregroundConnection.socket;
		const guildSubscriptions = this.listSubscribedChannelIds[guildId];
		const currentSubscribedChannelId = guildSubscriptions == null ? undefined : guildSubscriptions[storageKey];
		const shouldSendUpdate =
			forceResend ||
			this.sentMemberListGuildId !== guildId ||
			this.sentMemberListChannelId !== channelId ||
			currentSubscribedChannelId !== channelId ||
			!areRangesEqual(this.sentMemberListRanges, normalizedRanges);
		const shouldBootstrapGuildSync = !this.syncedMemberListGuildIds.has(guildId);
		let delivered = false;
		if (shouldSendUpdate) {
			if (socket != null && socket.isConnected() === true) {
				delivered = true;
				socket.updateGuildSubscriptions({
					subscriptions: {
						[guildId]: {
							active: true,
							...(shouldBootstrapGuildSync ? {sync: true} : {}),
							member_list_channels: {[channelId]: normalizedRanges},
						},
					},
				});
				this.setListSubscribedChannel(guildId, storageKey, channelId);
				this.sentMemberListGuildId = guildId;
				this.sentMemberListChannelId = channelId;
				this.sentMemberListRanges = normalizedRanges;
				this.syncedMemberListGuildIds.add(guildId);
			}
		}
		this.applyLocalChannelSubscription(guildId, channelId, normalizedRanges);
		return delivered;
	}

	private applyLocalChannelSubscription(
		guildId: string,
		channelId: string,
		normalizedRanges: NormalizedMemberListRanges,
	): void {
		const storageKey = this.resolveStorageKey(guildId, channelId);
		const existingGuildLists = this.lists[guildId] ?? {};
		const guildLists: Record<string, MemberListState> = {...existingGuildLists};
		const existingList = guildLists[storageKey];
		if (!existingList) {
			guildLists[storageKey] = this.createEmptyListState(normalizedRanges);
		} else {
			guildLists[storageKey] = this.pruneListStateToRanges({
				listState: existingList,
				requestedRanges: normalizedRanges,
			});
		}
		this.lists = {...this.lists, [guildId]: guildLists};
	}

	releaseMemberListSubscription(guildId: string, channelId: string, ownerId: string): void {
		this.clearChannelSubscription({
			guildId,
			channelId,
			clearLocalSubscription: true,
			ownerId,
			updateGateway: false,
		});
	}

	private clearChannelSubscription({
		guildId,
		channelId,
		clearLocalSubscription,
		ownerId,
		updateGateway,
	}: {
		guildId: string;
		channelId: string;
		clearLocalSubscription: boolean;
		ownerId?: string | null;
		updateGateway: boolean;
	}): void {
		if (ownerId !== undefined) {
			if (!this.isActiveMemberListSubscriptionOwner(guildId, channelId, ownerId)) {
				return;
			}
			this.setActiveMemberListSubscription(null);
		} else if (
			this.activeMemberListSubscription?.guildId === guildId &&
			this.activeMemberListSubscription?.channelId === channelId
		) {
			this.setActiveMemberListSubscription(null);
		}
		const storageKey = this.resolveStorageKey(guildId, channelId);
		const currentSubscribedChannelId = this.listSubscribedChannelIds[guildId]?.[storageKey];
		if (currentSubscribedChannelId && currentSubscribedChannelId !== channelId) {
			return;
		}
		if (updateGateway) {
			const socket = GatewaySessions.foregroundConnection.socket;
			if (socket != null && socket.isConnected() === true) {
				socket.updateGuildSubscriptions({
					subscriptions: {
						[guildId]: {
							member_list_channels: {[channelId]: []},
						},
					},
				});
			}
		}
		this.clearListSubscribedChannel(guildId, storageKey);
		this.clearPendingListUpdateBatch(guildId, storageKey);
		const existingGuildLists = this.lists[guildId] ?? {};
		const existingList = existingGuildLists[storageKey];
		if (existingList && clearLocalSubscription) {
			const guildLists = {...existingGuildLists};
			guildLists[storageKey] = {
				...existingList,
				requestedRanges: EMPTY_MEMBER_LIST_RANGES,
				subscribedRanges: EMPTY_MEMBER_LIST_RANGES,
			};
			this.lists = {...this.lists, [guildId]: guildLists};
		}
	}

	claimMemberListSubscription(guildId: string, channelId: string, ownerId: string | null): void {
		if (this.isMemberListUpdatesDisabled(guildId)) {
			return;
		}
		const activeSubscription = this.activeMemberListSubscription;
		if (
			activeSubscription != null &&
			(activeSubscription.guildId !== guildId || activeSubscription.channelId !== channelId)
		) {
			this.clearChannelSubscription({
				guildId: activeSubscription.guildId,
				channelId: activeSubscription.channelId,
				clearLocalSubscription: true,
				ownerId: activeSubscription.ownerId,
				updateGateway: false,
			});
		}
		this.unsubscribeKnownMemberListSubscriptionsExcept({guildId, channelId});
		this.setActiveMemberListSubscription({guildId, channelId, ownerId});
	}

	private setActiveMemberListSubscription(subscription: MemberListSubscription | null): void {
		const current = this.activeMemberListSubscription;
		if (current === subscription) {
			return;
		}
		if (
			current != null &&
			subscription != null &&
			current.guildId === subscription.guildId &&
			current.channelId === subscription.channelId &&
			current.ownerId === subscription.ownerId
		) {
			return;
		}
		this.activeMemberListSubscription = subscription;
		this.memberListSubscriptionGeneration += 1;
	}

	isActiveMemberListSubscriptionOwner(guildId: string, channelId: string, ownerId: string | null): boolean {
		const active = this.activeMemberListSubscription;
		return active != null && active.guildId === guildId && active.channelId === channelId && active.ownerId === ownerId;
	}

	hasActiveMemberListSubscription(): boolean {
		return this.activeMemberListSubscription != null;
	}

	getList(guildId: string, channelId: string): MemberListState | undefined {
		return this.lists[guildId]?.[this.resolveStorageKey(guildId, channelId)];
	}

	getListIdentityKey(guildId: string, channelId: string): string {
		return `${guildId}:${this.resolveStorageKey(guildId, channelId)}`;
	}

	hasHydratedRanges(guildId: string, channelId: string, ranges: MemberListRanges): boolean {
		const listState = this.getList(guildId, channelId);
		if (listState == null || !listState.hasReceivedInitialPayload) {
			return false;
		}
		return areNormalizedMemberListRangesCovered(normalizeMemberListRanges(ranges), listState.subscribedRanges);
	}

	getPresence(guildId: string, listId: string, userId: string): StatusType | null {
		const listState = this.getList(guildId, listId);
		if (!listState) {
			return null;
		}
		return listState.presences.get(userId) ?? null;
	}

	isMobile(guildId: string, listId: string, userId: string): boolean | null {
		const listState = this.getList(guildId, listId);
		if (!listState?.presences.has(userId)) {
			return null;
		}
		return listState.mobileUserIds.has(userId);
	}

	getCustomStatus(guildId: string, listId: string, userId: string): CustomStatus | null | undefined {
		const listState = this.getList(guildId, listId);
		if (!listState) {
			return undefined;
		}
		if (listState.customStatuses.has(userId)) {
			return listState.customStatuses.get(userId) ?? null;
		}
		if (listState.knownCustomStatuses.has(userId)) {
			return listState.knownCustomStatuses.get(userId) ?? null;
		}
		return undefined;
	}

	handleLocalPresenceUpdate(userId: string, status: StatusType, customStatus: CustomStatus | null): void {
		const changedCustomStatusListIds: Array<{guildId: string; listId: string}> = [];
		let didUpdate = false;
		const updatedLists: Record<string, Record<string, MemberListState>> = {...this.lists};
		for (const [guildId, guildLists] of Object.entries(this.lists)) {
			let nextGuildLists: Record<string, MemberListState> | null = null;
			for (const [listId, listState] of Object.entries(guildLists)) {
				if (!this.listStateContainsUser(listState, userId)) {
					continue;
				}
				const currentStatus = listState.presences.get(userId) ?? null;
				const currentCustomStatus = listState.customStatuses.has(userId)
					? (listState.customStatuses.get(userId) ?? null)
					: (listState.knownCustomStatuses.get(userId) ?? null);
				if (currentStatus === status && areCustomStatusesEqual(currentCustomStatus, customStatus)) {
					continue;
				}
				const nextPresences = new Map(listState.presences);
				nextPresences.set(userId, status);
				const nextCustomStatuses = new Map(listState.customStatuses);
				nextCustomStatuses.set(userId, customStatus);
				const nextKnownCustomStatuses = new Map(listState.knownCustomStatuses);
				nextKnownCustomStatuses.set(userId, customStatus);
				if (!nextGuildLists) {
					nextGuildLists = {...guildLists};
				}
				nextGuildLists[listId] = {
					...listState,
					presences: nextPresences,
					customStatuses: nextCustomStatuses,
					knownCustomStatuses: nextKnownCustomStatuses,
				};
				changedCustomStatusListIds.push({guildId, listId});
				didUpdate = true;
			}
			if (nextGuildLists) {
				updatedLists[guildId] = nextGuildLists;
			}
		}
		if (!didUpdate) {
			return;
		}
		this.lists = updatedLists;
		queueMicrotask(() => {
			for (const {guildId, listId} of changedCustomStatusListIds) {
				CustomStatusEmitter.emitMemberListChange(guildId, listId, userId);
			}
		});
	}

	private pruneListStateToRanges(params: {
		listState: MemberListState;
		requestedRanges: MemberListRanges;
	}): MemberListState {
		const {listState, requestedRanges} = params;
		const normalizedRequestedRanges = normalizeMemberListRanges(requestedRanges);
		if (normalizedRequestedRanges.length === 0) {
			return {
				...listState,
				requestedRanges: EMPTY_MEMBER_LIST_RANGES,
				subscribedRanges: EMPTY_MEMBER_LIST_RANGES,
				rows: new Map(),
				items: new Map(),
				membersByUserId: new Map(),
				presences: new Map(),
				mobileUserIds: new Set(),
				customStatuses: new Map(),
			};
		}
		const prunedRows = this.pruneRowsToRanges(listState.rows, normalizedRequestedRanges);
		const prunedItems = this.pruneItemsToRanges(listState.items, normalizedRequestedRanges);
		const retainedUserIds = new Set<string>();
		const prunedMembersByUserId = new Map<string, GuildMemberData>();
		for (const item of prunedItems.values()) {
			retainedUserIds.add(item.data.userId);
			prunedMembersByUserId.set(item.data.userId, item.data.member);
		}
		const prunedPresences = new Map<string, StatusType>();
		const prunedMobileUserIds = new Set<string>();
		const prunedCustomStatuses = new Map<string, CustomStatus | null>();
		for (const [userId, status] of listState.presences) {
			if (retainedUserIds.has(userId)) {
				prunedPresences.set(userId, status);
				if (listState.mobileUserIds.has(userId)) {
					prunedMobileUserIds.add(userId);
				}
			}
		}
		for (const [userId, customStatus] of listState.customStatuses) {
			if (retainedUserIds.has(userId)) {
				prunedCustomStatuses.set(userId, customStatus);
			}
		}
		return {
			...listState,
			requestedRanges: normalizedRequestedRanges,
			subscribedRanges: listState.hasReceivedInitialPayload
				? getHydratedMemberListRangesFromNormalized(
						{
							memberCount: listState.memberCount,
							groups: listState.groups,
							itemIndexes: prunedItems,
						},
						normalizedRequestedRanges,
					)
				: EMPTY_MEMBER_LIST_RANGES,
			rows: prunedRows,
			items: prunedItems,
			membersByUserId: prunedMembersByUserId,
			presences: prunedPresences,
			mobileUserIds: prunedMobileUserIds,
			customStatuses: prunedCustomStatuses,
		};
	}

	private pruneRowsToRanges(
		rows: Map<number, MemberListRow>,
		subscribedRanges: Array<[number, number]>,
	): Map<number, MemberListRow> {
		if (subscribedRanges.length === 0) {
			return new Map();
		}
		const prunedRows = new Map<number, MemberListRow>();
		for (const [index, row] of rows) {
			if (isIndexInMemberListRanges(index, subscribedRanges)) {
				prunedRows.set(index, row);
			}
		}
		return prunedRows;
	}

	private pruneItemsToRanges(
		items: Map<number, MemberListItem>,
		subscribedRanges: Array<[number, number]>,
	): Map<number, MemberListItem> {
		if (subscribedRanges.length === 0) {
			return new Map();
		}
		const prunedItems = new Map<number, MemberListItem>();
		for (const [rowIndex, item] of items) {
			if (isIndexInMemberListRanges(rowIndex, subscribedRanges)) {
				prunedItems.set(rowIndex, item);
			}
		}
		return prunedItems;
	}

	private createEmptyListState(requestedRanges: MemberListRanges = []): MemberListState {
		return {
			hasReceivedInitialPayload: false,
			memberCount: 0,
			onlineCount: 0,
			groups: [],
			rows: new Map(),
			items: new Map(),
			membersByUserId: new Map(),
			requestedRanges: normalizeMemberListRanges(requestedRanges),
			subscribedRanges: EMPTY_MEMBER_LIST_RANGES,
			presences: new Map(),
			mobileUserIds: new Set(),
			customStatuses: new Map(),
			knownCustomStatuses: new Map(),
		};
	}

	private isMemberListUpdatesDisabled(guildId: string): boolean {
		const guild = Guilds.getGuild(guildId);
		if (!guild) {
			return false;
		}
		return (guild.disabledOperations & GuildOperations.MEMBER_LIST_UPDATES) !== 0;
	}

	private resolveStorageKey(guildId: string, channelId: string): string {
		const channel = Channels.getChannel(channelId);
		if (channel != null && (channel.guildId !== guildId || channel.isPrivate())) {
			return channelId;
		}
		return deriveMemberListIdentity(Guilds.getGuild(guildId), channel);
	}

	private registerWireListChannel(guildId: string, wireListId: string, channelId: string): void {
		const guildMappings = this.wireListChannelIds[guildId];
		if (guildMappings?.[wireListId] === channelId) {
			return;
		}
		this.wireListChannelIds = {
			...this.wireListChannelIds,
			[guildId]: {...guildMappings, [wireListId]: channelId},
		};
	}

	private setListSubscribedChannel(guildId: string, listId: string, channelId: string): void {
		const guildSubscriptions = this.listSubscribedChannelIds[guildId] ?? {};
		if (guildSubscriptions[listId] === channelId) {
			if (!this.listSubscribedChannelIds[guildId]) {
				this.listSubscribedChannelIds = {...this.listSubscribedChannelIds, [guildId]: guildSubscriptions};
			}
			return;
		}
		this.listSubscribedChannelIds = {
			...this.listSubscribedChannelIds,
			[guildId]: {...guildSubscriptions, [listId]: channelId},
		};
	}

	private clearSentMemberListSubscription(): void {
		this.sentMemberListGuildId = null;
		this.sentMemberListChannelId = null;
		this.sentMemberListRanges = EMPTY_MEMBER_LIST_RANGES;
	}

	private clearListSubscribedChannel(guildId: string, listId: string): void {
		const guildSubscriptions = this.listSubscribedChannelIds[guildId];
		if (guildSubscriptions != null && guildSubscriptions[listId] != null) {
			const {[listId]: _, ...remainingGuildSubscriptions} = guildSubscriptions;
			if (Object.keys(remainingGuildSubscriptions).length === 0) {
				const {[guildId]: __, ...remainingSubscriptions} = this.listSubscribedChannelIds;
				this.listSubscribedChannelIds = remainingSubscriptions;
			} else {
				this.listSubscribedChannelIds = {...this.listSubscribedChannelIds, [guildId]: remainingGuildSubscriptions};
			}
		}
	}

	private unsubscribeKnownMemberListSubscriptionsExcept(target: {guildId: string; channelId: string} | null): void {
		const subscriptions = new Map<string, {guildId: string; channelId: string}>();
		for (const [guildId, guildSubscriptions] of Object.entries(this.listSubscribedChannelIds)) {
			for (const channelId of Object.values(guildSubscriptions)) {
				if (target && target.guildId === guildId && target.channelId === channelId) {
					continue;
				}
				subscriptions.set(`${guildId}:${channelId}`, {guildId, channelId});
			}
		}
		for (const subscription of subscriptions.values()) {
			this.clearChannelSubscription({
				guildId: subscription.guildId,
				channelId: subscription.channelId,
				clearLocalSubscription: true,
				updateGateway: false,
			});
		}
	}

	private listStateContainsUser(listState: MemberListState, userId: string): boolean {
		for (const item of listState.items.values()) {
			if (item.data.userId === userId) {
				return true;
			}
		}
		for (const row of listState.rows.values()) {
			if (row.userId === userId) {
				return true;
			}
		}
		return (
			listState.presences.has(userId) ||
			listState.customStatuses.has(userId) ||
			listState.knownCustomStatuses.has(userId)
		);
	}
}

export default new MemberSidebar();