ronantakizawa/codereview-bench huggingface dataset:
Repository: discordjs/discord.js
File: packages/ws/src/ws/WebSocketShard.ts (TypeScript)

Code before:
import { Buffer } from 'node:buffer';
import { once } from 'node:events';
import { clearInterval, clearTimeout, setInterval, setTimeout } from 'node:timers';
import { setTimeout as sleep } from 'node:timers/promises';
import type * as nativeZlib from 'node:zlib';
import { Collection } from '@discordjs/collection';
import { lazy, shouldUseGlobalFetchAndWebSocket } from '@discordjs/util';
import { AsyncQueue } from '@sapphire/async-queue';
import { AsyncEventEmitter } from '@vladfrangu/async_event_emitter';
import {
	GatewayCloseCodes,
	GatewayDispatchEvents,
	GatewayOpcodes,
	type GatewayDispatchPayload,
	type GatewayIdentifyData,
	type GatewayReadyDispatchData,
	type GatewayReceivePayload,
	type GatewaySendPayload,
} from 'discord-api-types/v10';
import { WebSocket, type Data } from 'ws';
import type * as ZlibSync from 'zlib-sync';
import type { IContextFetchingStrategy } from '../strategies/context/IContextFetchingStrategy';
import {
	CompressionMethod,
	CompressionParameterMap,
	ImportantGatewayOpcodes,
	getInitialSendRateLimitState,
} from '../utils/constants.js';

Review comment (suggestion):
Let's remove these too. The exception being imports from `node:timers/promises`

Code after:
import { Buffer } from 'node:buffer';
import { once } from 'node:events';
import { setTimeout as sleep } from 'node:timers/promises';
import type * as nativeZlib from 'node:zlib';
import { Collection } from '@discordjs/collection';
import { lazy, shouldUseGlobalFetchAndWebSocket } from '@discordjs/util';
import { AsyncQueue } from '@sapphire/async-queue';
import { AsyncEventEmitter } from '@vladfrangu/async_event_emitter';
import {
	GatewayCloseCodes,
	GatewayDispatchEvents,
	GatewayOpcodes,
	type GatewayDispatchPayload,
	type GatewayIdentifyData,
	type GatewayReadyDispatchData,
	type GatewayReceivePayload,
	type GatewaySendPayload,
} from 'discord-api-types/v10';
import { WebSocket, type Data } from 'ws';
import type * as ZlibSync from 'zlib-sync';
import type { IContextFetchingStrategy } from '../strategies/context/IContextFetchingStrategy';
import {
	CompressionMethod,
	CompressionParameterMap,
	ImportantGatewayOpcodes,
	getInitialSendRateLimitState,
} from '../utils/constants.js';
import type { SessionInfo } from './WebSocketManager.js';
Repository: discordjs/discord.js
File: packages/builders/src/Assertions.ts (TypeScript)

Code before:
import { Locale } from 'discord-api-types/v10';
import { z } from 'zod';

export const idPredicate = z.int().min(0).max(2_147_483_647).optional();
export const customIdPredicate = z.string().min(1).max(100);
export const snowflakePredicate = z.string().regex(/^\d{17,20}$/);

export const memberPermissionsPredicate = z.coerce.bigint();

export const localeMapPredicate = z.strictObject(
	Object.fromEntries(Object.values(Locale).map((loc) => [loc, z.string().optional()])) as Record<
		Locale,
		z.ZodOptional<z.ZodString>
	>,
);


Review comment (suggestion):
```suggestion
export const snowflakePredicate = z.string().regex(/^[1-9]\d{16,18}$/);
```

Code after:
import { Locale } from 'discord-api-types/v10';
import { z } from 'zod';

export const idPredicate = z.int().min(0).max(2_147_483_647).optional();
export const customIdPredicate = z.string().min(1).max(100);
export const snowflakePredicate = z.string().regex(/^(?:0|[1-9]\d*)$/);

export const memberPermissionsPredicate = z.coerce.bigint();

export const localeMapPredicate = z.strictObject(
	Object.fromEntries(Object.values(Locale).map((loc) => [loc, z.string().optional()])) as Record<
		Locale,
		z.ZodOptional<z.ZodString>
	>,
);
Repository: discordjs/discord.js
File: packages/builders/src/Assertions.ts (TypeScript)

Code before:
import { Locale } from 'discord-api-types/v10';
import { z } from 'zod';

export const idPredicate = z.int().min(0).max(2_147_483_647).optional();
export const customIdPredicate = z.string().min(1).max(100);
export const snowflakePredicate = z.string().regex(/^[1-9]\d{16,18}$/);

export const memberPermissionsPredicate = z.coerce.bigint();

export const localeMapPredicate = z.strictObject(
	Object.fromEntries(Object.values(Locale).map((loc) => [loc, z.string().optional()])) as Record<
		Locale,
		z.ZodOptional<z.ZodString>
	>,
);


Review comment (suggestion):
```suggestion
export const snowflakePredicate = z.string().regex(/^[0-9]\d{16,19}$/);
```

Code after:
import { Locale } from 'discord-api-types/v10';
import { z } from 'zod';

export const idPredicate = z.int().min(0).max(2_147_483_647).optional();
export const customIdPredicate = z.string().min(1).max(100);
export const snowflakePredicate = z.string().regex(/^(?:0|[1-9]\d*)$/);

export const memberPermissionsPredicate = z.coerce.bigint();

export const localeMapPredicate = z.strictObject(
	Object.fromEntries(Object.values(Locale).map((loc) => [loc, z.string().optional()])) as Record<
		Locale,
		z.ZodOptional<z.ZodString>
	>,
);
Repository: discordjs/discord.js
File: packages/builders/__tests__/messages/fileBody.test.ts (TypeScript)

Code before:
import type { RawFile } from '@discordjs/util';
import { test, expect } from 'vitest';
import { AttachmentBuilder, MessageBuilder } from '../../src/index.js';

test('AttachmentBuilder stores and exposes file data', () => {
	const data = Buffer.from('hello world');
	const attachment = new AttachmentBuilder()
		.setId(1)
		.setFilename('greeting.txt')
		.setFileData(data)
		.setFileContentType('text/plain');

	expect(attachment.getRawFile()).toStrictEqual({
		contentType: 'text/plain',
		data,
		key: 'files[1]',
		name: 'greeting.txt',
	});

	attachment.clearFileData();
	attachment.clearFileContentType();
	attachment.clearFilename();
	expect(attachment.getRawFile()).toBe(undefined);
});

test('AttachmentBuilder handles 0 as a valid ID', () => {
	const data = Buffer.from('test data');
	const attachment = new AttachmentBuilder().setId(0).setFilename('test.txt').setFileData(data);

	expect(attachment.getRawFile()).toStrictEqual({
		data,
		key: 'files[0]',
		name: 'test.txt',
	});
});

test('MessageBuilder.toFileBody returns JSON body and files', () => {
	const msg = new MessageBuilder().setContent('here is a file').addAttachments(
		new AttachmentBuilder()
			.setId(0)
			.setFilename('file.bin')
			.setFileData(Buffer.from([1, 2, 3]))
			.setFileContentType('application/octet-stream'),
	);

	const { body, files } = msg.toFileBody();

	// body should match toJSON()
	expect(body).toStrictEqual(msg.toJSON());

	// files should contain the uploaded file

Review comment (suggestion):
We prefer "id":

```suggestion
test('AttachmentBuilder handles 0 as a valid id', () => {
```

Code after:
import type { RawFile } from '@discordjs/util';
import { test, expect } from 'vitest';
import { AttachmentBuilder, MessageBuilder } from '../../src/index.js';

test('AttachmentBuilder stores and exposes file data', () => {
	const data = Buffer.from('hello world');
	const attachment = new AttachmentBuilder()
		.setId(1)
		.setFilename('greeting.txt')
		.setFileData(data)
		.setFileContentType('text/plain');

	expect(attachment.getRawFile()).toStrictEqual({
		contentType: 'text/plain',
		data,
		key: 'files[1]',
		name: 'greeting.txt',
	});

	attachment.clearFileData();
	attachment.clearFileContentType();
	attachment.clearFilename();
	expect(attachment.getRawFile()).toBe(undefined);
});

test('AttachmentBuilder handles 0 as a valid id', () => {
	const data = Buffer.from('test data');
	const attachment = new AttachmentBuilder().setId(0).setFilename('test.txt').setFileData(data);

	expect(attachment.getRawFile()).toStrictEqual({
		data,
		key: 'files[0]',
		name: 'test.txt',
	});
});

test('MessageBuilder.toFileBody returns JSON body and files', () => {
	const msg = new MessageBuilder().setContent('here is a file').addAttachments(
		new AttachmentBuilder()
			.setId(0)
			.setFilename('file.bin')
			.setFileData(Buffer.from([1, 2, 3]))
			.setFileContentType('application/octet-stream'),
	);

	const { body, files } = msg.toFileBody();

	// body should match toJSON()
	expect(body).toStrictEqual(msg.toJSON());

	// files should contain the uploaded file
Repository: discordjs/discord.js
File: packages/builders/src/messages/Attachment.ts (TypeScript)

Code before:
		this.fileData.contentType = contentType;
		return this;
	}

	/**
	 * Clears the content type of the file data from this attachment.
	 */
	public clearFileContentType(): this {
		this.fileData.contentType = undefined;
		return this;
	}

	/**
	 * Converts this attachment to a {@link RawFile} for uploading.
	 *
	 * @returns A {@link RawFile} object, or `undefined` if no file data is set
	 */
	public getRawFile(): Partial<RawFile> | undefined {
		if (!this.fileData?.data) {
			return;
		}

		return {
			...this.fileData,
			name: this.data.filename,
			key: 'id' in this.data ? `files[${this.data.id}]` : undefined,
		};
	}

	/**
	 * Sets the title of this attachment.
	 *
	 * @param title - The title of the attachment
	 */
	public setTitle(title: string): this {
		this.data.title = title;
		return this;
	}

	/**
	 * Clears the title of this attachment.
	 */
	public clearTitle(): this {
		this.data.title = undefined;
		return this;
	}

	/**
	 * Sets the waveform of this attachment (audio clips).
	 *
	 * @param waveform - The waveform of the attachment

Review comment (suggestion):
```suggestion
			key: this.data.id !== undefined ? `files[${this.data.id}]` : undefined,
```

Code after:
	 * Sets the content type of the file data to upload with this attachment.
	 *
	 * @remarks Note that this data is NOT included in the {@link toJSON} output. To retrieve it, use {@link getRawFile}.
	 */
	public setFileContentType(contentType: string): this {
		this.fileData.contentType = contentType;
		return this;
	}

	/**
	 * Clears the content type of the file data from this attachment.
	 */
	public clearFileContentType(): this {
		this.fileData.contentType = undefined;
		return this;
	}

	/**
	 * Converts this attachment to a {@link RawFile} for uploading.
	 *
	 * @returns A {@link RawFile} object, or `undefined` if no file data is set
	 */
	public getRawFile(): Partial<RawFile> | undefined {
		if (!this.fileData?.data) {
			return;
		}

		return {
			...this.fileData,
			name: this.data.filename,
			key: this.data.id === undefined ? undefined : `files[${this.data.id}]`,
		};
	}

	/**
	 * Sets the title of this attachment.
	 *
	 * @param title - The title of the attachment
	 */
	public setTitle(title: string): this {
		this.data.title = title;
		return this;
	}

	/**
	 * Clears the title of this attachment.
	 */
	public clearTitle(): this {
		this.data.title = undefined;
		return this;
	}
Repository: discordjs/discord.js
File: packages/discord.js/src/structures/AuthorizingIntegrationOwners.js (JavaScript)

Code before:
    }
  }

  /**
   * The ID of the guild where the integration is installed, if applicable.
   *
   * @returns {?Snowflake}
   */
  get guildId() {
    return this.data[ApplicationIntegrationType.GuildInstall] ?? null;
  }

  /**
   * The guild where the integration is installed, if applicable.
   *
   * @returns {?Guild}
   */
  get guild() {
    return (this.guildId && this.client.guilds.cache.get(this.guildId)) ?? null;
  }

  /**
   * The ID of the user on which the integration is installed, if applicable.
   *
   * @returns {?Snowflake}
   */
  get userId() {
    return this.data[ApplicationIntegrationType.UserInstall] ?? null;
  }

  /**
   * The user on which the integration is installed, if applicable.
   *
   * @returns {?User}
   */
  get user() {
    return (this.userId && this.client.users.cache.get(this.userId)) ?? null;
  }

  toJSON() {
    return this.data;
  }
}

exports.AuthorizingIntegrationOwners = AuthorizingIntegrationOwners;


Review comment (performance):
```suggestion
    return this.guildId && this.client.guilds.cache.get(this.guildId);
```
That already is `null`.

Code after:

      Object.defineProperty(this, value, { value: this.data[value] });
    }

    /**
     * The id of the guild where the integration is installed, if applicable.
     *
     * @type {?Snowflake}
     */
    this.guildId = this.data[ApplicationIntegrationType.GuildInstall] ?? null;

    /**
     * The id of the user on which the integration is installed, if applicable.
     *
     * @type {?Snowflake}
     */
    this.userId = this.data[ApplicationIntegrationType.UserInstall] ?? null;
  }

  /**
   * The guild where the integration is installed, if applicable.
   *
   * @type {?Guild}
   */
  get guild() {
    return (this.guildId && this.client.guilds.cache.get(this.guildId)) ?? null;
  }

  /**
   * The user on which the integration is installed, if applicable.
   *
   * @type {?User}
   */
  get user() {
    return (this.userId && this.client.users.cache.get(this.userId)) ?? null;
  }

  toJSON() {
    return this.data;
  }
}

exports.AuthorizingIntegrationOwners = AuthorizingIntegrationOwners;
Repository: discordjs/discord.js
File: packages/discord.js/src/structures/AuthorizingIntegrationOwners.js (JavaScript)

Code before:
    return this.data[ApplicationIntegrationType.GuildInstall] ?? null;
  }

  /**
   * The guild where the integration is installed, if applicable.
   *
   * @returns {?Guild}
   */
  get guild() {
    return (this.guildId && this.client.guilds.cache.get(this.guildId)) ?? null;
  }

  /**
   * The ID of the user on which the integration is installed, if applicable.
   *
   * @returns {?Snowflake}
   */
  get userId() {
    return this.data[ApplicationIntegrationType.UserInstall] ?? null;
  }

  /**
   * The user on which the integration is installed, if applicable.
   *
   * @returns {?User}
   */
  get user() {
    return (this.userId && this.client.users.cache.get(this.userId)) ?? null;
  }

  toJSON() {
    return this.data;
  }
}

exports.AuthorizingIntegrationOwners = AuthorizingIntegrationOwners;


Review comment (performance):
```suggestion
    return this.userId && this.client.users.cache.get(this.userId);
```

Code after:
    this.guildId = this.data[ApplicationIntegrationType.GuildInstall] ?? null;

    /**
     * The id of the user on which the integration is installed, if applicable.
     *
     * @type {?Snowflake}
     */
    this.userId = this.data[ApplicationIntegrationType.UserInstall] ?? null;
  }

  /**
   * The guild where the integration is installed, if applicable.
   *
   * @type {?Guild}
   */
  get guild() {
    return (this.guildId && this.client.guilds.cache.get(this.guildId)) ?? null;
  }

  /**
   * The user on which the integration is installed, if applicable.
   *
   * @type {?User}
   */
  get user() {
    return (this.userId && this.client.users.cache.get(this.userId)) ?? null;
  }

  toJSON() {
    return this.data;
  }
}

exports.AuthorizingIntegrationOwners = AuthorizingIntegrationOwners;
Repository: discordjs/discord.js
File: packages/discord.js/src/structures/BaseInteraction.js (JavaScript)

Code before:
    /**
     * The locale of the user who invoked this interaction
     *
     * @type {Locale}
     */
    this.locale = data.locale;

    /**
     * The preferred locale from the guild this interaction was sent in
     *
     * @type {?Locale}
     */
    this.guildLocale = data.guild_locale ?? null;

    /**
     * The entitlements for the invoking user, representing access to premium SKUs
     *
     * @type {Collection<Snowflake, Entitlement>}
     */
    this.entitlements = data.entitlements.reduce(
      (coll, entitlement) => coll.set(entitlement.id, this.client.application.entitlements._add(entitlement)),
      new Collection(),
    );

    /**
     * Mapping of installation contexts that the integration was authorized for the related user or guild ids
     *
     * @type {AuthorizingIntegrationOwners}
     * @see {@link https://discord.com/developers/docs/interactions/receiving-and-responding#interaction-object-authorizing-integration-owners-object}
     */
    this.authorizingIntegrationOwners = new AuthorizingIntegrationOwners(
      this.client,
      data.authorizing_integration_owners,
    );

    /**
     * Context where the interaction was triggered from
     *
     * @type {?InteractionContextType}
     */
    this.context = data.context ?? null;

    /**
     * Attachment size limit in bytes
     *
     * @type {number}
     */
    this.attachmentSizeLimit = data.attachment_size_limit;
  }

  /**

Review comment (security):
```suggestion
     * Mapping of integration types that the application was authorized for the related user or guild ids
```

Code after:
    /**
     * The locale of the user who invoked this interaction
     *
     * @type {Locale}
     */
    this.locale = data.locale;

    /**
     * The preferred locale from the guild this interaction was sent in
     *
     * @type {?Locale}
     */
    this.guildLocale = data.guild_locale ?? null;

    /**
     * The entitlements for the invoking user, representing access to premium SKUs
     *
     * @type {Collection<Snowflake, Entitlement>}
     */
    this.entitlements = data.entitlements.reduce(
      (coll, entitlement) => coll.set(entitlement.id, this.client.application.entitlements._add(entitlement)),
      new Collection(),
    );

    /**
     * Mapping of integration types that the application was authorized for the related user or guild ids
     *
     * @type {AuthorizingIntegrationOwners}
     * @see {@link https://discord.com/developers/docs/interactions/receiving-and-responding#interaction-object-authorizing-integration-owners-object}
     */
    this.authorizingIntegrationOwners = new AuthorizingIntegrationOwners(
      this.client,
      data.authorizing_integration_owners,
    );

    /**
     * Context where the interaction was triggered from
     *
     * @type {?InteractionContextType}
     */
    this.context = data.context ?? null;

    /**
     * Attachment size limit in bytes
     *
     * @type {number}
     */
    this.attachmentSizeLimit = data.attachment_size_limit;
  }

  /**
Repository: discordjs/discord.js
File: packages/discord.js/src/structures/AuthorizingIntegrationOwners.js (JavaScript)

Code before:

      Object.defineProperty(this, value, { value: this.data[value] });
    }

    /**
     * The id of the guild where the integration is installed, if applicable.
     *
     * @type {?Snowflake}
     */
    this.guildId = this.data[ApplicationIntegrationType.GuildInstall] ?? null;

    /**
     * The id of the user on which the integration is installed, if applicable.
     *
     * @type {?Snowflake}
     */
    this.userId = this.data[ApplicationIntegrationType.UserInstall] ?? null;
  }

  /**
   * The guild where the integration is installed, if applicable.
   *
   * @type {?Guild}
   */
  get guild() {
    return this.guildId && this.client.guilds.cache.get(this.guildId);
  }

  /**
   * The user on which the integration is installed, if applicable.
   *
   * @type {?User}
   */
  get user() {
    return this.userId && this.client.users.cache.get(this.userId);
  }

  toJSON() {
    return this.data;
  }
}

exports.AuthorizingIntegrationOwners = AuthorizingIntegrationOwners;


Review comment (performance):
```suggestion
    return (this.guildId && this.client.guilds.cache.get(this.guildId)) ?? null;
```
Guess this is needed again, since the weird behavior with `guildId` being "0" in DMs.

Code after:

      Object.defineProperty(this, value, { value: this.data[value] });
    }

    /**
     * The id of the guild where the integration is installed, if applicable.
     *
     * @type {?Snowflake}
     */
    this.guildId = this.data[ApplicationIntegrationType.GuildInstall] ?? null;

    /**
     * The id of the user on which the integration is installed, if applicable.
     *
     * @type {?Snowflake}
     */
    this.userId = this.data[ApplicationIntegrationType.UserInstall] ?? null;
  }

  /**
   * The guild where the integration is installed, if applicable.
   *
   * @type {?Guild}
   */
  get guild() {
    return (this.guildId && this.client.guilds.cache.get(this.guildId)) ?? null;
  }

  /**
   * The user on which the integration is installed, if applicable.
   *
   * @type {?User}
   */
  get user() {
    return (this.userId && this.client.users.cache.get(this.userId)) ?? null;
  }

  toJSON() {
    return this.data;
  }
}

exports.AuthorizingIntegrationOwners = AuthorizingIntegrationOwners;
Repository: discordjs/discord.js
File: packages/discord.js/src/util/Transformers.js (JavaScript)

Code before:
'use strict';

const { isJSONEncodable } = require('@discordjs/util');
const snakeCase = require('lodash.snakecase');
const { AuthorizingIntegrationOwners } = require('../structures/AuthorizingIntegrationOwners');

/**
 * Transforms camel-cased keys into snake cased keys
 *
 * @param {*} obj The object to transform
 * @returns {*}
 */
function toSnakeCase(obj) {
  if (typeof obj !== 'object' || !obj) return obj;
  if (obj instanceof Date) return obj;
  if (isJSONEncodable(obj)) return toSnakeCase(obj.toJSON());
  if (Array.isArray(obj)) return obj.map(toSnakeCase);
  return Object.fromEntries(Object.entries(obj).map(([key, value]) => [snakeCase(key), toSnakeCase(value)]));
}

/**
 * Transforms an API auto moderation action object to a camel-cased variant.
 *
 * @param {APIAutoModerationAction} autoModerationAction The action to transform
 * @returns {AutoModerationAction}
 * @ignore
 */
function _transformAPIAutoModerationAction(autoModerationAction) {
  return {
    type: autoModerationAction.type,

Review comment (security):
```suggestion
const { AuthorizingIntegrationOwners } = require('../structures/AuthorizingIntegrationOwners.js');
```

Code after:
'use strict';

const { isJSONEncodable } = require('@discordjs/util');
const snakeCase = require('lodash.snakecase');
const { AuthorizingIntegrationOwners } = require('../structures/AuthorizingIntegrationOwners.js');

/**
 * Transforms camel-cased keys into snake cased keys
 *
 * @param {*} obj The object to transform
 * @returns {*}
 */
function toSnakeCase(obj) {
  if (typeof obj !== 'object' || !obj) return obj;
  if (obj instanceof Date) return obj;
  if (isJSONEncodable(obj)) return toSnakeCase(obj.toJSON());
  if (Array.isArray(obj)) return obj.map(toSnakeCase);
  return Object.fromEntries(Object.entries(obj).map(([key, value]) => [snakeCase(key), toSnakeCase(value)]));
}

/**
 * Transforms an API auto moderation action object to a camel-cased variant.
 *
 * @param {APIAutoModerationAction} autoModerationAction The action to transform
 * @returns {AutoModerationAction}
 * @ignore
 */
function _transformAPIAutoModerationAction(autoModerationAction) {
  return {
    type: autoModerationAction.type,