A free and open source instant messaging and VoIP chat app built for friends, groups, and communities.
refactor(api): clarify community audit logs and role ordering
Hampus40aa574332e7
diff --git a/fluxer_api/src/api/guild/GuildAuditLogService.ts b/fluxer_api/src/api/guild/GuildAuditLogService.tsindex f77b13bb6..0fb96934a 100644--- a/fluxer_api/src/api/guild/GuildAuditLogService.ts+++ b/fluxer_api/src/api/guild/GuildAuditLogService.ts@@ -17,10 +17,13 @@ import type {ChannelPermissionOverwrite} from '@app/api/models/ChannelPermissionimport type {GuildAuditLog} from '@app/api/models/GuildAuditLog';import type {WorkerTaskName} from '@app/api/worker/WorkerLaneConfig';import {AuditLogActionType} from '@fluxer/constants/src/AuditLogActionType';+import {ChannelOverwriteTypes} from '@fluxer/constants/src/ChannelConstants';import type {IWorkerService} from '@pkgs/worker/src/contracts/IWorkerService';import {ms} from 'itty-time';const MESSAGE_DELETE_BATCH_DELAY_MS = ms('30 seconds');+const MESSAGE_DELETE_BATCH_MAX_ATTEMPTS = 3;+const RECENT_MESSAGE_DELETE_LOG_LIMIT = 250;interface MessageDeleteBatchGroup {logs: Array<GuildAuditLog>;@@ -70,12 +73,10 @@ export class GuildAuditLogService {changes?: GuildAuditLogChange | null;createdAt?: Date;}): Promise<void> {- const targetId =- params.targetId === undefined || params.targetId === null- ? null- : typeof params.targetId === 'string'- ? params.targetId- : params.targetId.toString();+ let targetId: string | null = null;+ if (params.targetId !== undefined && params.targetId !== null) {+ targetId = typeof params.targetId === 'string' ? params.targetId : params.targetId.toString();+ }try {const builder = this.createBuilder(params.guildId, params.userId).withAction(params.action, targetId)@@ -128,14 +129,14 @@ export class GuildAuditLogService {changes: params.changes ? JSON.stringify(params.changes) : null,};const log = await this.guildRepository.createAuditLog(row);- await this.dispatchAuditLogEntryCreate(log, params.threadScoped === true);+ await this.dispatchAuditLogEntryCreate(log, {threadScoped: params.threadScoped === true});if (params.actionType === AuditLogActionType.MESSAGE_DELETE) {await this.scheduleMessageDeleteBatchJob(params.guildId);}return log;}- async scheduleMessageDeleteBatchJob(guildId: GuildID): Promise<void> {+ private async scheduleMessageDeleteBatchJob(guildId: GuildID): Promise<void> {const batchWindow = Math.floor(Date.now() / MESSAGE_DELETE_BATCH_DELAY_MS);await this.workerService.addJob('batchGuildAuditLogMessageDeletes',@@ -143,7 +144,7 @@ export class GuildAuditLogService {{jobKey: `batch-audit-log-message-deletes:${guildId}:${batchWindow}`,runAt: new Date((batchWindow + 2) * MESSAGE_DELETE_BATCH_DELAY_MS),- maxAttempts: 3,+ maxAttempts: MESSAGE_DELETE_BATCH_MAX_ATTEMPTS,skipLedger: true,},);@@ -156,23 +157,27 @@ export class GuildAuditLogService {const processedLogs: Array<GuildAuditLog> = [];for (const log of logs) {const group = groups.find((g) => g.logs.includes(log));- if (group && group.logs.length >= 2) {- if (log === group.logs[0]) {- for (const groupLog of group.logs) {- deletedLogIds.push(groupLog.logId);- }- const batchedLog = await this.createBatchedMessageDeleteLog(guildId, group);- createdLogs.push(batchedLog);- processedLogs.push(batchedLog);- }- } else {+ if (!group || group.logs.length < 2) {processedLogs.push(log);+ continue;+ }+ if (log !== group.logs[0]) {+ continue;+ }+ for (const groupLog of group.logs) {+ deletedLogIds.push(groupLog.logId);}+ const batchedLog = await this.createBatchedMessageDeleteLog(guildId, group);+ createdLogs.push(batchedLog);+ processedLogs.push(batchedLog);}return {processedLogs, deletedLogIds, createdLogs};}- async batchRecentMessageDeleteLogs(guildId: GuildID, limit: number = 250): Promise<BatchResult> {+ async batchRecentMessageDeleteLogs(+ guildId: GuildID,+ limit: number = RECENT_MESSAGE_DELETE_LOG_LIMIT,+ ): Promise<BatchResult> {const logs = await this.guildRepository.listAuditLogs({guildId,limit,@@ -230,9 +235,6 @@ export class GuildAuditLogService {guildId: GuildID,group: MessageDeleteBatchGroup,): Promise<GuildAuditLog> {- // Must be a fresh id: reusing one of the replaced logs would put a delete and an insert for the same- // primary key in one batch, and Cassandra resolves that tie in favour of the tombstone, so the entry- // would silently vanish from every table whose key does not include action_type.const logId = await this.snowflakeService.generate();const threadScoped = group.logs.some((log) => log.options.has(THREAD_SCOPED_AUDIT_OPTION));const row: GuildAuditLogRow = {@@ -250,7 +252,7 @@ export class GuildAuditLogService {changes: null,};const log = await this.guildRepository.batchDeleteAndCreateAuditLogs(guildId, group.logs, row);- await this.dispatchAuditLogEntryCreate(log, threadScoped);+ await this.dispatchAuditLogEntryCreate(log, {threadScoped});return log;}@@ -275,7 +277,7 @@ export class GuildAuditLogService {if (before && after && before.type === after.type && before.allow === after.allow && before.deny === after.deny) {continue;}- const overwriteType = (after ?? before)?.type ?? 0;+ const overwriteType = (after ?? before)?.type ?? ChannelOverwriteTypes.ROLE;const previousSnapshot = before? {id: targetId.toString(),@@ -293,15 +295,17 @@ export class GuildAuditLogService {}: null;const changes = this.computeChanges(previousSnapshot, nextSnapshot);- if (changes.length === 0) continue;- const action =- !before && after- ? AuditLogActionType.CHANNEL_OVERWRITE_CREATE- : before && !after- ? AuditLogActionType.CHANNEL_OVERWRITE_DELETE- : AuditLogActionType.CHANNEL_OVERWRITE_UPDATE;+ if (changes.length === 0) {+ continue;+ }+ let action = AuditLogActionType.CHANNEL_OVERWRITE_UPDATE;+ if (!before && after) {+ action = AuditLogActionType.CHANNEL_OVERWRITE_CREATE;+ } else if (before && !after) {+ action = AuditLogActionType.CHANNEL_OVERWRITE_DELETE;+ }let roleName: string | null = null;- if (overwriteType === 0 && targetId.toString() !== params.guildId.toString()) {+ if (overwriteType === ChannelOverwriteTypes.ROLE && targetId.toString() !== params.guildId.toString()) {try {const role = await this.guildRepository.getRole(createRoleID(BigInt(targetId)), params.guildId);roleName = role?.name ?? null;@@ -388,17 +392,23 @@ export class GuildAuditLogService {}private areValuesEqual(a: unknown, b: unknown): boolean {- if (a === b) return true;- if (a == null || b == null) return false;- if (typeof a !== typeof b) return false;+ if (a === b) {+ return true;+ }+ if (a == null || b == null) {+ return false;+ }+ if (typeof a !== typeof b) {+ return false;+ }if (typeof a === 'object' && typeof b === 'object') {return JSON.stringify(a) === JSON.stringify(b);}return false;}- private async dispatchAuditLogEntryCreate(log: GuildAuditLog, threadScoped = false): Promise<void> {- const scoped = threadScoped || THREAD_AUDIT_LOG_ACTION_TYPES.has(log.actionType);+ private async dispatchAuditLogEntryCreate(log: GuildAuditLog, options: {threadScoped: boolean}): Promise<void> {+ const scoped = options.threadScoped || THREAD_AUDIT_LOG_ACTION_TYPES.has(log.actionType);try {await this.gatewayService.dispatchGuild({guildId: log.guildId,@@ -423,7 +433,7 @@ export class GuildAuditLogService {}class GuildAuditLogBuilder {- private readonly params: Partial<CreateGuildAuditLogParams>;+ private readonly params: Pick<CreateGuildAuditLogParams, 'guildId' | 'userId'> & Partial<CreateGuildAuditLogParams>;private metadataMap: Map<string, string> | null = null;constructor(@@ -473,8 +483,8 @@ class GuildAuditLogBuilder {return null;}return this.service.createLog({- guildId: this.params.guildId!,- userId: this.params.userId!,+ guildId: this.params.guildId,+ userId: this.params.userId,actionType: this.params.actionType,targetId: this.params.targetId ?? null,auditLogReason: this.params.auditLogReason ?? null,diff --git a/fluxer_api/src/api/guild/services/GuildRoleService.ts b/fluxer_api/src/api/guild/services/GuildRoleService.tsindex 8cd2a9ad3..aec3ff7a7 100644--- a/fluxer_api/src/api/guild/services/GuildRoleService.ts+++ b/fluxer_api/src/api/guild/services/GuildRoleService.ts@@ -1,5 +1,6 @@// SPDX-License-Identifier: AGPL-3.0-or-later+import assert from 'node:assert/strict';import {createRoleID, type GuildID, guildIdToRoleId, type RoleID, type UserID} from '@app/api/BrandedTypes';import type {ThreadViewer} from '@app/api/experiment/ChannelThreadsGate';import type {GuildAuditLogService} from '@app/api/guild/GuildAuditLogService';@@ -38,8 +39,11 @@ import type {} from '@fluxer/schema/src/domains/guild/GuildRequestSchemas';import type {GuildResponse} from '@fluxer/schema/src/domains/guild/GuildResponseSchemas';import type {GuildRoleResponse} from '@fluxer/schema/src/domains/guild/GuildRoleSchemas';+import {compareSnowflakes} from '@fluxer/snowflake/src/SnowflakeComparison';import type {ICacheService} from '@pkgs/cache/src/ICacheService';+const ROLE_REORDER_LOCK_TTL_SECONDS = 30;+type RoleUpdateData = Partial<{name: string;color: number;@@ -64,12 +68,20 @@ export class GuildRoleService {let myHighestRole: GuildRole | null = null;if (!isOwner) {const member = await this.guildRepository.getMember(guildId, userId);- if (member) myHighestRole = this.getUserHighestRole(member, allRoles);+ if (member) {+ myHighestRole = this.getUserHighestRole(member, allRoles);+ }}return (role: GuildRole) => {- if (isOwner) return true;- if (role.id === everyoneRoleId) return false;- if (!myHighestRole) return false;+ if (isOwner) {+ return true;+ }+ if (role.id === everyoneRoleId) {+ return false;+ }+ if (!myHighestRole) {+ return false;+ }return this.isRoleHigherThan(myHighestRole, role);};}@@ -93,7 +105,9 @@ export class GuildRoleService {const guildData = await this.gatewayService.getGuildData({guildId, userId: initiatorId, skipMembershipCheck: true});const currentRoleCount = await this.guildRepository.countRoles(guildId);const roleLimit = this.resolveGuildLimit(guildData.features, 'max_guild_roles', MAX_GUILD_ROLES);- if (currentRoleCount >= roleLimit) throw new MaxGuildRolesError(roleLimit);+ if (currentRoleCount >= roleLimit) {+ throw new MaxGuildRolesError(roleLimit);+ }const permissionMask = THREAD_AWARE_ALL_PERMISSIONS;const permissions = data.permissions !== undefined ? data.permissions & permissionMask : DEFAULT_PERMISSIONS;const roleId = createRoleID(await this.snowflakeService.generate());@@ -143,7 +157,9 @@ export class GuildRoleService {await checkPermission(Permissions.MANAGE_ROLES);const currentRoleCount = await this.guildRepository.countRoles(guildId);const roleLimit = this.resolveGuildLimit(guildData.features, 'max_guild_roles', MAX_GUILD_ROLES);- if (currentRoleCount >= roleLimit) throw new MaxGuildRolesError(roleLimit);+ if (currentRoleCount >= roleLimit) {+ throw new MaxGuildRolesError(roleLimit);+ }const permissions =data.permissions !== undefined? await this.resolveRequestedPermissions({@@ -229,7 +245,9 @@ export class GuildRoleService {viewer: ThreadViewer | undefined,): Promise<GuildRoleResponse> {const response = mapGuildRoleToResponse(role);- if (!(await shouldMaskThreadPermissionBits(guildId, viewer, [role.permissions]))) return response;+ if (!(await shouldMaskThreadPermissionBits(guildId, viewer, [role.permissions]))) {+ return response;+ }return {...response, permissions: stripThreadPermissionBits(role.permissions).toString()};}@@ -373,7 +391,7 @@ export class GuildRoleService {const {checkPermission} = await getGuildAuth(this.gatewayService, this.userRepository, {userId, guildId});await checkPermission(Permissions.MANAGE_ROLES);const lockKey = `guild:${guildId}:role-positions`;- const lockToken = await this.cacheService.acquireLock(lockKey, 30);+ const lockToken = await this.cacheService.acquireLock(lockKey, ROLE_REORDER_LOCK_TTL_SECONDS);if (!lockToken) {throw new ResourceLockedError();}@@ -393,10 +411,12 @@ export class GuildRoleService {await getGuildAuth(this.gatewayService, this.userRepository, {userId, guildId});const roles = await this.guildRepository.listRoles(guildId);const sortedRoles = [...roles].sort((a, b) => {- if (b.position !== a.position) return b.position - a.position;- return this.compareRoleIds(a, b);+ if (b.position !== a.position) {+ return b.position - a.position;+ }+ return compareSnowflakes(a.id, b.id);});- const responses = sortedRoles.map(mapGuildRoleToResponse);+ const roleResponses = sortedRoles.map((role) => ({role, response: mapGuildRoleToResponse(role)}));if (!(await shouldMaskThreadPermissionBits(guildId,@@ -404,11 +424,11 @@ export class GuildRoleService {sortedRoles.map((role) => role.permissions),))) {- return responses;+ return roleResponses.map(({response}) => response);}- return responses.map((response, index) => ({+ return roleResponses.map(({role, response}) => ({...response,- permissions: stripThreadPermissionBits(sortedRoles[index]!.permissions).toString(),+ permissions: stripThreadPermissionBits(role.permissions).toString(),}));}@@ -430,7 +450,7 @@ export class GuildRoleService {});await checkPermission(Permissions.MANAGE_ROLES);const lockKey = `guild:${guildId}:role-hoist-positions`;- const lockToken = await this.cacheService.acquireLock(lockKey, 30);+ const lockToken = await this.cacheService.acquireLock(lockKey, ROLE_REORDER_LOCK_TTL_SECONDS);if (!lockToken) {throw new ResourceLockedError();}@@ -455,8 +475,11 @@ export class GuildRoleService {}const changedRoles: Array<GuildRole> = [];for (const update of updates) {- const role = roleMap.get(update.roleId)!;- if (role.hoistPosition === update.hoistPosition) continue;+ const role = roleMap.get(update.roleId);+ assert(role !== undefined);+ if (role.hoistPosition === update.hoistPosition) {+ continue;+ }const updatedRole = await this.guildRepository.upsertRole({...role.toRow(),hoist_position: update.hoistPosition,@@ -491,7 +514,7 @@ export class GuildRoleService {const {checkPermission} = await getGuildAuth(this.gatewayService, this.userRepository, {userId, guildId});await checkPermission(Permissions.MANAGE_ROLES);const lockKey = `guild:${guildId}:role-hoist-positions`;- const lockToken = await this.cacheService.acquireLock(lockKey, 30);+ const lockToken = await this.cacheService.acquireLock(lockKey, ROLE_REORDER_LOCK_TTL_SECONDS);if (!lockToken) {throw new ResourceLockedError();}@@ -500,7 +523,9 @@ export class GuildRoleService {const roleMap = new Map(allRoles.map((r) => [r.id, r]));const changedRoles: Array<GuildRole> = [];for (const role of allRoles) {- if (role.hoistPosition === null) continue;+ if (role.hoistPosition === null) {+ continue;+ }const updatedRole = await this.guildRepository.upsertRole({...role.toRow(), hoist_position: null});changedRoles.push(updatedRole);}@@ -544,30 +569,22 @@ export class GuildRoleService {let highestRole: GuildRole | null = null;for (const roleId of member.roleIds) {const role = roleMap.get(roleId);- if (!role) continue;- if (!highestRole) {+ if (!role) {+ continue;+ }+ if (!highestRole || this.isRoleHigherThan(role, highestRole)) {highestRole = role;- } else {- if (this.isRoleHigherThan(role, highestRole)) {- highestRole = role;- }}}return highestRole;}- private compareRoleIds(a: GuildRole, b: GuildRole): number {- const idA = BigInt(a.id);- const idB = BigInt(b.id);- return idA < idB ? -1 : idA > idB ? 1 : 0;- }-private isRoleHigherThan(roleA: GuildRole, roleB: GuildRole): boolean {if (roleA.position > roleB.position) {return true;}if (roleA.position === roleB.position) {- return BigInt(roleA.id) < BigInt(roleB.id);+ return compareSnowflakes(roleA.id, roleB.id) < 0;}return false;}@@ -643,7 +660,8 @@ export class GuildRoleService {}const canManageRole = await this.buildRoleManageCheck(guildId, userId, guildData, allRoles);for (const update of updates) {- const role = roleMap.get(update.roleId)!;+ const role = roleMap.get(update.roleId);+ assert(role !== undefined);if (canManageRole(role)) {continue;}@@ -711,7 +729,7 @@ export class GuildRoleService {private getCurrentRoleOrder(allRoles: Array<GuildRole>, everyoneRoleId: RoleID): Array<GuildRole> {return allRoles.filter((role) => role.id !== everyoneRoleId)- .sort((a, b) => b.position - a.position || this.compareRoleIds(a, b));+ .sort((a, b) => b.position - a.position || compareSnowflakes(a.id, b.id));}private mergeManageableRoleOrder(params: {@@ -720,27 +738,28 @@ export class GuildRoleService {explicitPositions: Map<RoleID, number>;}): Array<GuildRole> {const {currentOrder, canManageRole, explicitPositions} = params;- const currentIndexById = new Map(currentOrder.map((role, index) => [role.id, index]));const manageableSlotIndices: Array<number> = [];- const manageableRoles: Array<GuildRole> = [];+ const manageableRoles: Array<{role: GuildRole; index: number}> = [];for (const [index, role] of currentOrder.entries()) {if (!canManageRole(role)) {continue;}manageableSlotIndices.push(index);- manageableRoles.push(role);+ manageableRoles.push({role, index});}const sortedManageableRoles = [...manageableRoles].sort((a, b) => {- const posA = explicitPositions.has(a.id) ? explicitPositions.get(a.id)! : a.position;- const posB = explicitPositions.has(b.id) ? explicitPositions.get(b.id)! : b.position;+ const posA = explicitPositions.get(a.role.id) ?? a.role.position;+ const posB = explicitPositions.get(b.role.id) ?? b.role.position;if (posA !== posB) {return posB - posA;}- return currentIndexById.get(a.id)! - currentIndexById.get(b.id)!;+ return a.index - b.index;});const targetOrder = [...currentOrder];for (const [index, slot] of manageableSlotIndices.entries()) {- targetOrder[slot] = sortedManageableRoles[index]!;+ const entry = sortedManageableRoles[index];+ assert(entry !== undefined);+ targetOrder[slot] = entry.role;}return targetOrder;}@@ -759,7 +778,7 @@ export class GuildRoleService {const reorderedRoleSet = new Set(reorderedIds);const nonReorderedRoles = allRoles.filter((role) => role.id !== guildIdToRoleId(guildId) && !reorderedRoleSet.has(role.id))- .sort((a, b) => a.position - b.position || this.compareRoleIds(a, b));+ .sort((a, b) => a.position - b.position || compareSnowflakes(a.id, b.id));const newRoles: Array<GuildRole> = [];if (everyoneRole) {newRoles.push(new GuildRole({...everyoneRole.toRow(), position: 0}));diff --git a/fluxer_api/src/api/guild/services/role/RoleOrderAuditUtils.ts b/fluxer_api/src/api/guild/services/role/RoleOrderAuditUtils.tsindex 72996a91d..cd9a659c6 100644--- a/fluxer_api/src/api/guild/services/role/RoleOrderAuditUtils.ts+++ b/fluxer_api/src/api/guild/services/role/RoleOrderAuditUtils.ts@@ -2,6 +2,7 @@import type {RoleID} from '@app/api/BrandedTypes';import type {GuildRole} from '@app/api/models/GuildRole';+import {compareSnowflakes} from '@fluxer/snowflake/src/SnowflakeComparison';export function computeMovedIds<T extends string | bigint>(before: ReadonlyArray<T>, after: ReadonlyArray<T>): Set<T> {const width = after.length + 1;@@ -39,6 +40,6 @@ export function computeMovedIds<T extends string | bigint>(before: ReadonlyArrayexport function getMemberListRoleOrderIds(roles: ReadonlyArray<GuildRole>, everyoneRoleId: RoleID): Array<RoleID> {return roles.filter((role) => role.isHoisted && role.id !== everyoneRoleId)- .sort((a, b) => b.effectiveHoistPosition - a.effectiveHoistPosition || (a.id < b.id ? -1 : a.id > b.id ? 1 : 0))+ .sort((a, b) => b.effectiveHoistPosition - a.effectiveHoistPosition || compareSnowflakes(a.id, b.id)).map((role) => role.id);}diff --git a/fluxer_api/src/api/guild/tests/GuildRoleOrdering.test.ts b/fluxer_api/src/api/guild/tests/GuildRoleOrdering.test.tsnew file mode 100644index 000000000..ca7a93705--- /dev/null+++ b/fluxer_api/src/api/guild/tests/GuildRoleOrdering.test.ts@@ -0,0 +1,162 @@+// SPDX-License-Identifier: AGPL-3.0-or-later++import {createTestAccount, type TestAccount} from '@app/api/auth/tests/AuthTestUtils';+import {createGuildID, createRoleID} from '@app/api/BrandedTypes';+import {getMemberListRoleOrderIds} from '@app/api/guild/services/role/RoleOrderAuditUtils';+import {createGuild, createRole, getRoles} from '@app/api/guild/tests/GuildTestUtils';+import {GuildRole} from '@app/api/models/GuildRole';+import {type ApiTestHarness, createApiTestHarness} from '@app/api/test/ApiTestHarness';+import {createBuilder} from '@app/api/test/TestRequestBuilder';+import {HttpStatus} from '@fluxer/constants/src/HttpConstants';+import type {GuildResponse} from '@fluxer/schema/src/domains/guild/GuildResponseSchemas';+import type {GuildRoleResponse} from '@fluxer/schema/src/domains/guild/GuildRoleSchemas';+import {afterEach, beforeEach, describe, expect, test} from 'vitest';++type RoleName = 'Alpha' | 'Bravo' | 'Charlie';++describe('Guild role ordering', () => {+ let harness: ApiTestHarness;+ let owner: TestAccount;+ let guild: GuildResponse;+ let roles: Record<RoleName, GuildRoleResponse>;++ beforeEach(async () => {+ harness = await createApiTestHarness();+ owner = await createTestAccount(harness);+ guild = await createGuild(harness, owner.token, 'Role ordering');+ roles = {+ Alpha: await createRole(harness, owner.token, guild.id, {name: 'Alpha'}),+ Bravo: await createRole(harness, owner.token, guild.id, {name: 'Bravo'}),+ Charlie: await createRole(harness, owner.token, guild.id, {name: 'Charlie'}),+ };+ });++ afterEach(async () => {+ await harness?.shutdown();+ });++ async function listedPositions(): Promise<Array<{name: string; position: number}>> {+ const listed = await getRoles(harness, owner.token, guild.id);+ return listed.filter((role) => role.id !== guild.id).map(({name, position}) => ({name, position}));+ }++ test('lists equal-position roles in snowflake order', async () => {+ expect(await listedPositions()).toEqual([+ {name: 'Alpha', position: 1},+ {name: 'Bravo', position: 1},+ {name: 'Charlie', position: 1},+ ]);+ });++ test.each([+ {+ name: 'omitted positions keep the existing tie order',+ updates: [{role: 'Charlie'}, {role: 'Bravo'}, {role: 'Alpha'}],+ expected: [+ {name: 'Alpha', position: 3},+ {name: 'Bravo', position: 2},+ {name: 'Charlie', position: 1},+ ],+ },+ {+ name: 'zero positions keep the existing tie order',+ updates: [+ {role: 'Charlie', position: 0},+ {role: 'Bravo', position: 0},+ {role: 'Alpha', position: 0},+ ],+ expected: [+ {name: 'Alpha', position: 3},+ {name: 'Bravo', position: 2},+ {name: 'Charlie', position: 1},+ ],+ },+ {+ name: 'the last duplicate position wins',+ updates: [+ {role: 'Alpha', position: 10},+ {role: 'Alpha', position: -1},+ ],+ expected: [+ {name: 'Bravo', position: 3},+ {name: 'Charlie', position: 2},+ {name: 'Alpha', position: 1},+ ],+ },+ ] satisfies Array<{+ name: string;+ updates: Array<{role: RoleName; position?: number}>;+ expected: Array<{name: string; position: number}>;+ }>)('$name', async ({updates, expected}) => {+ await createBuilder(harness, owner.token)+ .patch(`/guilds/${guild.id}/roles`)+ .body(updates.map(({role, ...update}) => ({id: roles[role].id, ...update})))+ .expect(HttpStatus.NO_CONTENT)+ .execute();+ expect(await listedPositions()).toEqual(expected);+ });++ test.each([+ {suffix: '', update: {position: 7}},+ {suffix: '/hoist-positions', update: {hoist_position: 7}},+ ])('validates all $suffix updates before writing', async ({suffix, update}) => {+ const before = await getRoles(harness, owner.token, guild.id);+ await createBuilder(harness, owner.token)+ .patch(`/guilds/${guild.id}/roles${suffix}`)+ .body([+ {id: roles.Alpha.id, ...update},+ {id: '1420000000000000999', ...update},+ ])+ .expect(HttpStatus.BAD_REQUEST)+ .execute();+ expect(await getRoles(harness, owner.token, guild.id)).toEqual(before);+ });++ test('applies duplicate hoist updates in request order', async () => {+ await createBuilder(harness, owner.token)+ .patch(`/guilds/${guild.id}/roles/hoist-positions`)+ .body([+ {id: roles.Alpha.id, hoist_position: 5},+ {id: roles.Alpha.id, hoist_position: 0},+ ])+ .expect(HttpStatus.NO_CONTENT)+ .execute();+ const listed = await getRoles(harness, owner.token, guild.id);+ expect(+ listed.filter((role) => role.id !== guild.id).map(({name, hoist_position}) => ({name, hoist_position})),+ ).toEqual([+ {name: 'Alpha', hoist_position: 0},+ {name: 'Bravo', hoist_position: null},+ {name: 'Charlie', hoist_position: null},+ ]);+ });+});++test('member-list ordering uses effective hoist position then snowflakes, excluding everyone and non-hoisted roles', () => {+ const roles = [+ {id: 30n, position: 1, hoistPosition: 2, hoist: true},+ {id: 10n, position: 1, hoistPosition: 2, hoist: true},+ {id: 20n, position: 1, hoistPosition: 2, hoist: true},+ {id: 40n, position: 3, hoistPosition: null, hoist: true},+ {id: 50n, position: 9, hoistPosition: 0, hoist: true},+ {id: 60n, position: 10, hoistPosition: 10, hoist: false},+ {id: 1n, position: 10, hoistPosition: 10, hoist: true},+ ].map(+ ({id, position, hoistPosition, hoist}) =>+ new GuildRole({+ guild_id: createGuildID(1n),+ role_id: createRoleID(id),+ name: 'Role',+ permissions: 0n,+ position,+ hoist_position: hoistPosition,+ color: 0,+ icon_hash: null,+ unicode_emoji: null,+ hoist,+ mentionable: false,+ version: 1,+ }),+ );+ expect(getMemberListRoleOrderIds(roles, createRoleID(1n))).toEqual([40n, 10n, 20n, 30n, 50n]);+});