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

Code before:
					} else {
						console.warn('WebSocketShard: Compression is set to native zlib but node:zlib is not available.');
						params.delete('compress');
					}

					break;
				}

				case CompressionMethod.ZlibSync: {
					const zlib = await getZlibSync();
					if (zlib) {
						this.zLibSyncInflate = new zlib.Inflate({
							chunkSize: 65_535,
							to: 'string',
						});
					} else {
						console.warn('WebSocketShard: Compression is set to zlib-sync, but it is not installed.');
						params.delete('compress');
					}

					break;
				}

				case CompressionMethod.ZstdNative: {
					const zlib = await getNativeZlib();
					if (zlib && 'createZstdDecompress' in zlib) {
						this.inflateBuffer = [];

						// @ts-expect-error node 23 called, it wants its code back
						const inflate = zlib.createZstdDecompress({
							chunkSize: 65_535,
						}) as nativeZlib.Inflate;

						inflate.on('data', (chunk) => {
							this.inflateBuffer.push(chunk);
						});

						inflate.on('error', (error) => {
							this.emit(WebSocketShardEvents.Error, error);
						});

						this.nativeInflate = inflate;
					} else {
						console.warn(
							'WebSocketShard: Compression is set to native zstd but node:zlib is not available or your node version does not support zstd decompression.',
						);
						params.delete('compress');
					}

					break;
				}

Review comment (suggestion):
I believe this will need to set `flush: zlib.constants.ZSTD_e_flush`, as the default zstd behaviour is not to flush the output buffer if the received message doesn't close the current frame.

Code after:
					break;
				}

				case CompressionMethod.ZlibSync: {
					const zlib = await getZlibSync();
					if (zlib) {
						this.zLibSyncInflate = new zlib.Inflate({
							chunkSize: 65_535,
							to: 'string',
						});
					} else {
						console.warn('WebSocketShard: Compression is set to zlib-sync, but it is not installed.');
						params.delete('compress');
					}

					break;
				}

				case CompressionMethod.ZstdNative: {
					const zlib = await getNativeZlib();
					if (zlib && 'createZstdDecompress' in zlib) {
						this.inflateBuffer = [];

						const inflate = zlib.createZstdDecompress({
							chunkSize: 65_535,
						}) as nativeZlib.Inflate;

						inflate.on('data', (chunk) => {
							this.inflateBuffer.push(chunk);
						});

						inflate.on('error', (error) => {
							this.emit(WebSocketShardEvents.Error, error);
						});

						this.nativeInflate = inflate;
					} else {
						console.warn(
							'WebSocketShard: Compression is set to native zstd but node:zlib is not available or your node version does not support zstd decompression.',
						);
						params.delete('compress');
					}

					break;
				}
			}
		}

		if (this.identifyCompressionEnabled) {
			const zlib = await getNativeZlib();
			if (!zlib) {
Repository: discordjs/discord.js
File: apps/website/src/components/UnionMember.tsx (TypeScript)

Code before:
import { ExcerptNode } from './ExcerptNode';

export async function UnionMember({ node, version }: { readonly node: any; readonly version: string }) {
	return (
		<div className="flex flex-col gap-8">
			{node.length > 1 ? <h2 className="flex place-items-center gap-2 p-2 text-xl font-bold">Union Members</h2> : ''}

			<span className="flex flex-col gap-4 break-words font-mono text-sm">
				<ExcerptNode node={node} version={version} />
			</span>
		</div>
	);
}


Review comment (suggestion):
```suggestion
			{node.length > 1 ? <h2 className="flex place-items-center gap-2 p-2 text-xl font-bold">Union Members</h2> : null}
```

Code after:
import { ExcerptNode } from './ExcerptNode';

export async function UnionMember({ node, version }: { readonly node: any; readonly version: string }) {
	return (
		<div className="flex flex-col gap-4">
			{node.length > 1 ? <h2 className="flex place-items-center gap-2 p-2 text-xl font-bold">Union Members</h2> : null}

			<span className="flex flex-col gap-4 px-2 font-mono text-sm break-words">
				<ExcerptNode node={node} version={version} />
			</span>
		</div>
	);
}
Repository: discordjs/discord.js
File: packages/ws/src/ws/WebSocketShard.ts (TypeScript)

Code before:
	Resumed = 'resumed',
	SocketError = 'socketError',
}

export enum WebSocketShardStatus {
	Idle,
	Connecting,
	Resuming,
	Ready,
}

export enum WebSocketShardDestroyRecovery {
	Reconnect,
	Resume,
}

enum ZlibErrorCodes {
	Z_NEED_DICT = 2,
	Z_STREAM_END = 1,
	Z_ERRNO = -1,
	Z_STREAM_ERROR = -2,
	Z_DATA_ERROR = -3,
	Z_MEM_ERROR = -4,
	Z_BUF_ERROR = -5,
	Z_VERSION_ERROR = -6,
}

export interface WebSocketShardEventsMap {
	[WebSocketShardEvents.Closed]: [code: number];
	[WebSocketShardEvents.Debug]: [message: string];
	[WebSocketShardEvents.Dispatch]: [payload: GatewayDispatchPayload];
	[WebSocketShardEvents.Error]: [error: Error];
	[WebSocketShardEvents.Hello]: [];
	[WebSocketShardEvents.Ready]: [payload: GatewayReadyDispatchData];
	[WebSocketShardEvents.Resumed]: [];
	[WebSocketShardEvents.HeartbeatComplete]: [stats: { ackAt: number; heartbeatAt: number; latency: number }];
	[WebSocketShardEvents.SocketError]: [error: Error];
}

export interface WebSocketShardDestroyOptions {
	code?: number;
	reason?: string;
	recover?: WebSocketShardDestroyRecovery;
}

export enum CloseCodes {
	Normal = 1_000,
	Resuming = 4_200,
}

export interface SendRateLimitState {

Review comment (suggestion):
Having these hardcoded here is not ideal.. Especially since zlib-sync exports each of these codes as constants

We could import them and construct this object using them
https://github.com/abalabahaha/zlib-sync/blob/7f1b404ba9e1bb9af1f47ca395f33e4fdfc2299c/src/zlib_sync.cc#L220-L228

(This would imply moving this object creation into the `unpackMessage` method as that's where zlib is being imported)

Code after:
	Resumed = 'resumed',
	SocketError = 'socketError',
}

export enum WebSocketShardStatus {
	Idle,
	Connecting,
	Resuming,
	Ready,
}

export enum WebSocketShardDestroyRecovery {
	Reconnect,
	Resume,
}

export interface WebSocketShardEventsMap {
	[WebSocketShardEvents.Closed]: [code: number];
	[WebSocketShardEvents.Debug]: [message: string];
	[WebSocketShardEvents.Dispatch]: [payload: GatewayDispatchPayload];
	[WebSocketShardEvents.Error]: [error: Error];
	[WebSocketShardEvents.Hello]: [];
	[WebSocketShardEvents.Ready]: [payload: GatewayReadyDispatchData];
	[WebSocketShardEvents.Resumed]: [];
	[WebSocketShardEvents.HeartbeatComplete]: [stats: { ackAt: number; heartbeatAt: number; latency: number }];
	[WebSocketShardEvents.SocketError]: [error: Error];
}

export interface WebSocketShardDestroyOptions {
	code?: number;
	reason?: string;
	recover?: WebSocketShardDestroyRecovery;
}

export enum CloseCodes {
	Normal = 1_000,
	Resuming = 4_200,
}

export interface SendRateLimitState {
	resetAt: number;
	sent: number;
}

const WebSocketConstructor: typeof WebSocket = shouldUseGlobalFetchAndWebSocket()
	? (globalThis as any).WebSocket
	: WebSocket;

export class WebSocketShard extends AsyncEventEmitter<WebSocketShardEventsMap> {
	private connection: WebSocket | null = null;
Repository: discordjs/discord.js
File: packages/discord.js/src/structures/Poll.js (JavaScript)

Code before:
    Object.defineProperty(this, 'channel', { value: channel });

    /**
     * The id of the message that started this poll
     * @type {Snowflake}
     */
    this.messageId = data.message_id ?? message.id;

    /**
     * The message that started this poll
     * @name Poll#message
     * @type {Message}
     * @readonly
     */

    Object.defineProperty(this, 'message', { value: message });

    this._patch(data);
  }

  _patch(data) {
    /**
     * The answers of this poll
     * @type {Collection<number, PollAnswer|PartialPollAnswer>}
     */
    this.answers ??= new Collection();

    if (data.answers) {
      for (const answer of data.answers) {
        const existing = this.answers.get(answer.answer_id);
        if (existing) {
          existing._patch(answer);
        } else {
          this.answers.set(answer.answer_id, new PollAnswer(this.client, answer, this));
        }
      }
    }

    if (data.results) {
      /**
       * Whether this poll's results have been precisely counted
       * @type {boolean}
       */
      this.resultsFinalized = data.results.is_finalized;

      for (const answerResult of data.results.answer_counts) {
        const answer = this.answers.get(answerResult.id);
        answer?._patch(answerResult);
      }
    } else {
      this.resultsFinalized ??= false;

Review comment (refactor):
Why don't we move this in the constructor as `this.answers = new Collection();`? It would mean this wouldn't need to be checked, right?

Code after:
    Object.defineProperty(this, 'channel', { value: channel });

    /**
     * The id of the message that started this poll
     * @type {Snowflake}
     */
    this.messageId = data.message_id ?? message.id;

    /**
     * The message that started this poll
     * @name Poll#message
     * @type {Message}
     * @readonly
     */

    Object.defineProperty(this, 'message', { value: message });

    /**
     * The answers of this poll
     * @type {Collection<number, PollAnswer|PartialPollAnswer>}
     */
    this.answers = new Collection();

    this._patch(data);
  }

  _patch(data) {
    if (data.answers) {
      for (const answer of data.answers) {
        const existing = this.answers.get(answer.answer_id);
        if (existing) {
          existing._patch(answer);
        } else {
          this.answers.set(answer.answer_id, new PollAnswer(this.client, answer, this));
        }
      }
    }

    if (data.results) {
      /**
       * Whether this poll's results have been precisely counted
       * @type {boolean}
       */
      this.resultsFinalized = data.results.is_finalized;

      for (const answerResult of data.results.answer_counts) {
        const answer = this.answers.get(answerResult.id);
        answer?._patch(answerResult);
      }
    } else {
      this.resultsFinalized ??= false;
Repository: discordjs/discord.js
File: packages/create-discord-bot/template/TypeScript/src/events/index.ts (TypeScript)

Code before:
import type { ClientEvents } from 'discord.js';
import { z } from 'zod';
import type { StructurePredicate } from '../util/loaders.[REPLACE_IMPORT_EXT]';

/**
 * Defines the structure of an event.
 */
export type Event<T extends keyof ClientEvents = keyof ClientEvents> = {
	/**
	 * The function to execute when the event is emitted.
	 *
	 * @param parameters - The parameters of the event
	 */
	execute(this: void, ...parameters: ClientEvents[T]): Promise<void> | void;
	/**
	 * The name of the event to listen to
	 */
	name: T;
	/**
	 * Whether or not the event should only be listened to once
	 *
	 * @defaultValue false
	 */
	once?: boolean;
};

/**
 * Defines the schema for an event.
 */
export const schema = z.object({
	name: z.string(),
	once: z.boolean().optional().default(false),
	execute: z.function(),
});

/**
 * Defines the predicate to check if an object is a valid Event type.
 */
export const predicate: StructurePredicate<Event> = (structure: unknown): structure is Event =>

Review comment (suggestion):
This doesn't appear to be correct. Missing `.bind(client)` when registering the events. Also applies to the other templates

Code after:
import type { ClientEvents } from 'discord.js';
import { z } from 'zod';
import type { StructurePredicate } from '../util/loaders.[REPLACE_IMPORT_EXT]';

/**
 * Defines the structure of an event.
 */
export type Event<T extends keyof ClientEvents = keyof ClientEvents> = {
	/**
	 * The function to execute when the event is emitted.
	 *
	 * @param parameters - The parameters of the event
	 */
	execute(...parameters: ClientEvents[T]): Promise<void> | void;
	/**
	 * The name of the event to listen to
	 */
	name: T;
	/**
	 * Whether or not the event should only be listened to once
	 *
	 * @defaultValue false
	 */
	once?: boolean;
};

/**
 * Defines the schema for an event.
 */
export const schema = z.object({
	name: z.string(),
	once: z.boolean().optional().default(false),
	execute: z.function(),
});

/**
 * Defines the predicate to check if an object is a valid Event type.
 */
export const predicate: StructurePredicate<Event> = (structure: unknown): structure is Event =>
Repository: discordjs/discord.js
File: packages/discord.js/src/structures/ApplicationEmoji.js (JavaScript)

Code before:
}

/**
 * The emoji's name
 * @name name
 * @memberof ApplicationEmoji
 * @instance
 * @type {string}
 * @readonly
 */

/**
 * Whether or not the emoji is animated
 * @name animated
 * @memberof ApplicationEmoji
 * @instance
 * @type {boolean}
 * @readonly
 */

/**
 * Returns a URL for the emoji.
 * @method imageURL
 * @memberof ApplicationEmoji
 * @instance
 * @param {BaseImageURLOptions} [options] Options for the image URL
 * @returns {string}
 */

/**
 * Returns a URL for the emoji.
 * @name url
 * @memberof ApplicationEmoji
 * @instance
 * @type {string}
 * @readonly
 * @deprecated Use {@link ApplicationEmoji#imageURL} instead.
 */

/**
 * The time the emoji was created at
 * @name createdAt
 * @memberof ApplicationEmoji
 * @instance
 * @type {Date}
 * @readonly
 */

/**
 * The timestamp the emoji was created at
 * @name createdTimestamp

Review comment (suggestion):
```suggestion
 * @param {ImageURLOptions} [options] Options for the image URL
```

Code after:
}

/**
 * The emoji's name
 * @name name
 * @memberof ApplicationEmoji
 * @instance
 * @type {string}
 * @readonly
 */

/**
 * Whether the emoji is animated
 * @name animated
 * @memberof ApplicationEmoji
 * @instance
 * @type {boolean}
 * @readonly
 */

/**
 * Returns a URL for the emoji.
 * @method imageURL
 * @memberof ApplicationEmoji
 * @instance
 * @param {EmojiURLOptions} [options] Options for the image URL
 * @returns {string}
 */

/**
 * The time the emoji was created at
 * @name createdAt
 * @memberof ApplicationEmoji
 * @instance
 * @type {Date}
 * @readonly
 */

/**
 * The timestamp the emoji was created at
 * @name createdTimestamp
 * @memberof ApplicationEmoji
 * @instance
 * @type {number}
 * @readonly
 */

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

Code before:
class ApplicationEmoji extends Emoji {
  constructor(client, data, application) {
    super(client, data);

    /**
     * The application this emoji originates from
     * @type {ClientApplication}
     */
    this.application = application;

    this._patch(data);
  }

  _patch(data) {
    if ('name' in data) this.name = data.name;
    if (data.user) {
      /**
       * The user who created this emoji
       * @type {User}
       */
      this.author = this.client.users._add(data.user);
    }

    if ('managed' in data) {
      /**
       * Whether this emoji is managed by an external service. Always false for application emojis
       * @type {false}
       */
      this.managed = data.managed;
    }

    if ('require_colons' in data) {
      /**
       * Whether or not this emoji requires colons surrounding it. Always true for application emojis
       * @type {true}
       */
      this.requiresColons = data.require_colons;
    }

    if ('available' in data) {
      /**
       * Whether this emoji is available. Always true for application emojis
       * @type {true}
       */
      this.available = data.available;
    }
  }

  /**
   * Fetches the author for this emoji
   * @returns {Promise<User>}

Review comment (suggestion):
```suggestion
       * Whether this emoji is managed by an external service. Always `false` for application emojis
```

Code after:
class ApplicationEmoji extends Emoji {
  constructor(client, data, application) {
    super(client, data);

    /**
     * The application this emoji originates from
     * @type {ClientApplication}
     */
    this.application = application;

    this._patch(data);
  }

  _patch(data) {
    if ('name' in data) this.name = data.name;
    if (data.user) {
      /**
       * The user who created this emoji
       * @type {User}
       */
      this.author = this.client.users._add(data.user);
    }

    if ('managed' in data) {
      /**
       * Whether this emoji is managed by an external service. Always `false` for application emojis
       * @type {false}
       */
      this.managed = data.managed;
    }

    if ('require_colons' in data) {
      /**
       * Whether this emoji requires colons surrounding it. Always `true` for application emojis
       * @type {true}
       */
      this.requiresColons = data.require_colons;
    }

    if ('available' in data) {
      /**
       * Whether this emoji is available. Always `true` for application emojis
       * @type {true}
       */
      this.available = data.available;
    }
  }

  /**
   * Fetches the author for this emoji
   * @returns {Promise<User>}
Repository: discordjs/discord.js
File: packages/discord.js/src/structures/ApplicationEmoji.js (JavaScript)

Code before:
    this.application = application;

    this._patch(data);
  }

  _patch(data) {
    if ('name' in data) this.name = data.name;
    if (data.user) {
      /**
       * The user who created this emoji
       * @type {User}
       */
      this.author = this.client.users._add(data.user);
    }

    if ('managed' in data) {
      /**
       * Whether this emoji is managed by an external service. Always false for application emojis
       * @type {false}
       */
      this.managed = data.managed;
    }

    if ('require_colons' in data) {
      /**
       * Whether or not this emoji requires colons surrounding it. Always true for application emojis
       * @type {true}
       */
      this.requiresColons = data.require_colons;
    }

    if ('available' in data) {
      /**
       * Whether this emoji is available. Always true for application emojis
       * @type {true}
       */
      this.available = data.available;
    }
  }

  /**
   * Fetches the author for this emoji
   * @returns {Promise<User>}
   */
  fetchAuthor() {
    return this.application.emojis.fetchAuthor(this);
  }

  /**
   * Data for editing an emoji.
   * @typedef {Object} ApplicationEmojiEditOptions

Review comment (suggestion):
```suggestion
       * Whether this emoji requires colons surrounding it. Always `true` for application emojis
```

Code after:
    this.application = application;

    this._patch(data);
  }

  _patch(data) {
    if ('name' in data) this.name = data.name;
    if (data.user) {
      /**
       * The user who created this emoji
       * @type {User}
       */
      this.author = this.client.users._add(data.user);
    }

    if ('managed' in data) {
      /**
       * Whether this emoji is managed by an external service. Always `false` for application emojis
       * @type {false}
       */
      this.managed = data.managed;
    }

    if ('require_colons' in data) {
      /**
       * Whether this emoji requires colons surrounding it. Always `true` for application emojis
       * @type {true}
       */
      this.requiresColons = data.require_colons;
    }

    if ('available' in data) {
      /**
       * Whether this emoji is available. Always `true` for application emojis
       * @type {true}
       */
      this.available = data.available;
    }
  }

  /**
   * Fetches the author for this emoji
   * @returns {Promise<User>}
   */
  fetchAuthor() {
    return this.application.emojis.fetchAuthor(this);
  }

  /**
   * Data for editing an emoji.
   * @typedef {Object} ApplicationEmojiEditOptions
Repository: discordjs/discord.js
File: packages/discord.js/src/structures/ApplicationEmoji.js (JavaScript)

Code before:
      /**
       * The user who created this emoji
       * @type {User}
       */
      this.author = this.client.users._add(data.user);
    }

    if ('managed' in data) {
      /**
       * Whether this emoji is managed by an external service. Always false for application emojis
       * @type {false}
       */
      this.managed = data.managed;
    }

    if ('require_colons' in data) {
      /**
       * Whether or not this emoji requires colons surrounding it. Always true for application emojis
       * @type {true}
       */
      this.requiresColons = data.require_colons;
    }

    if ('available' in data) {
      /**
       * Whether this emoji is available. Always true for application emojis
       * @type {true}
       */
      this.available = data.available;
    }
  }

  /**
   * Fetches the author for this emoji
   * @returns {Promise<User>}
   */
  fetchAuthor() {
    return this.application.emojis.fetchAuthor(this);
  }

  /**
   * Data for editing an emoji.
   * @typedef {Object} ApplicationEmojiEditOptions
   * @property {string} [name] The name of the emoji
   */

  /**
   * Edits the emoji.
   * @param {ApplicationEmojiEditOptions} options The options to provide
   * @returns {Promise<ApplicationEmoji>}
   * @example

Review comment (suggestion):
```suggestion
       * Whether this emoji is available. Always `true` for application emojis
```

Code after:
      /**
       * The user who created this emoji
       * @type {User}
       */
      this.author = this.client.users._add(data.user);
    }

    if ('managed' in data) {
      /**
       * Whether this emoji is managed by an external service. Always `false` for application emojis
       * @type {false}
       */
      this.managed = data.managed;
    }

    if ('require_colons' in data) {
      /**
       * Whether this emoji requires colons surrounding it. Always `true` for application emojis
       * @type {true}
       */
      this.requiresColons = data.require_colons;
    }

    if ('available' in data) {
      /**
       * Whether this emoji is available. Always `true` for application emojis
       * @type {true}
       */
      this.available = data.available;
    }
  }

  /**
   * Fetches the author for this emoji
   * @returns {Promise<User>}
   */
  fetchAuthor() {
    return this.application.emojis.fetchAuthor(this);
  }

  /**
   * Data for editing an emoji.
   * @typedef {Object} ApplicationEmojiEditOptions
   * @property {string} [name] The name of the emoji
   */

  /**
   * Edits the emoji.
   * @param {ApplicationEmojiEditOptions} options The options to provide
   * @returns {Promise<ApplicationEmoji>}
   * @example