ronantakizawa/codereview-bench huggingface dataset:
Repository: directus/directus
File: app/src/interfaces/file-image/file-image.vue (Vue)

Code before:
	if (image.value.type.includes('image')) {
		const fit = props.crop ? 'cover' : 'contain';
		const url = getAssetUrl(`${image.value.id}?key=system-large-${fit}&cache-buster=${image.value.modified_on}`);
		return url;
	}

	return null;
});

const ext = computed(() => (image.value?.type ? readableMimeType(image.value.type, true) : 'unknown'));

const meta = computed(() => {
	if (!image.value) return null;
	const { filesize, width, height, type } = image.value;

	if (width && height) {
		return `${n(width)}x${n(height)} • ${formatFilesize(filesize)} • ${type}`;
	}

	return `${formatFilesize(filesize)} • ${type}`;
});

const editImageDetails = ref(false);
const editImageEditor = ref(false);

const _disabled = computed(() => {
	return props.disabled || (props.enableCreate === false && props.enableSelect === false);
});

async function imageErrorHandler() {
	isImage.value = false;
	if (!src.value) return;

	try {
		await api.get(src.value);
	} catch (err: any) {
		imageError.value = err.response?.data?.errors[0]?.extensions?.code;

		if (!imageError.value || !te('errors.' + imageError.value)) {
			imageError.value = 'UNKNOWN';
		}
	}
}

const values = inject('values', ref<Record<string, any>>({}));

const customFilter = computed(() => {
	return parseFilter(
		deepMap(props.filter, (val: any) => {
			if (val && typeof val === 'string') {
				return render(val, values.value);

Review comment (suggestion):
```suggestion
const disabled = computed(() => {
```

Same here 😄 

Code after:
	if (image.value.type.includes('image')) {
		const fit = props.crop ? 'cover' : 'contain';
		const url = getAssetUrl(`${image.value.id}?key=system-large-${fit}&cache-buster=${image.value.modified_on}`);
		return url;
	}

	return null;
});

const ext = computed(() => (image.value?.type ? readableMimeType(image.value.type, true) : 'unknown'));

const meta = computed(() => {
	if (!image.value) return null;
	const { filesize, width, height, type } = image.value;

	if (width && height) {
		return `${n(width)}x${n(height)} • ${formatFilesize(filesize)} • ${type}`;
	}

	return `${formatFilesize(filesize)} • ${type}`;
});

const editImageDetails = ref(false);
const editImageEditor = ref(false);

const internalDisabled = computed(() => {
	return props.disabled || (props.enableCreate === false && props.enableSelect === false);
});

async function imageErrorHandler() {
	isImage.value = false;
	if (!src.value) return;

	try {
		await api.get(src.value);
	} catch (err: any) {
		imageError.value = err.response?.data?.errors[0]?.extensions?.code;

		if (!imageError.value || !te('errors.' + imageError.value)) {
			imageError.value = 'UNKNOWN';
		}
	}
}

const values = inject('values', ref<Record<string, unknown>>({}));

const customFilter = computed(() => {
	return parseFilter(
		deepMap(props.filter, (val: unknown) => {
			if (val && typeof val === 'string') {
				return render(val, values.value);
Repository: directus/directus
File: app/src/interfaces/file/file.vue (Vue)

Code before:
});

const imageThumbnail = computed(() => {
	if (file.value === null || props.value === null) return null;
	if (file.value.type.includes('svg')) return assetURL.value;
	if (file.value.type.includes('image') === false) return null;
	return addQueryToPath(assetURL.value, { key: 'system-small-cover' });
});

const imageThumbnailError = ref<any>(null);

const { url, isValidURL, loading: urlLoading, importFromURL } = useURLImport();

const editDrawerActive = ref(false);

const edits = computed(() => {
	if (!props.value || typeof props.value !== 'object') return {};

	return props.value;
});

const values = inject('values', ref<Record<string, any>>({}));

const customFilter = computed(() => {
	return parseFilter(
		deepMap(props.filter, (val: any) => {
			if (val && typeof val === 'string') {
				return render(val, values.value);
			}

			return val;
		}),
	);
});

const _disabled = computed(() => {
	return props.disabled || (props.enableCreate === false && props.enableSelect === false);
});

function setSelection(selection: (string | number)[] | null) {
	if (selection![0]) {
		update(selection![0]);
	} else {
		remove();
	}
}

function onUpload(fileInfo: FileInfo) {
	file.value = fileInfo;
	activeDialog.value = null;
	update(fileInfo.id);

Review comment (suggestion):
```suggestion
const values = inject('values', ref<Record<string, unknown>>({}));

const customFilter = computed(() => {
	return parseFilter(
		deepMap(props.filter, (val: unknown) => {
```

`unknown` would be a safer type choice here than `any` I think, `any` has the tendency to hide potential type issues.

Code after:
});

const imageThumbnail = computed(() => {
	if (file.value === null || props.value === null) return null;
	if (file.value.type.includes('svg')) return assetURL.value;
	if (file.value.type.includes('image') === false) return null;
	return addQueryToPath(assetURL.value, { key: 'system-small-cover' });
});

const imageThumbnailError = ref<any>(null);

const { url, isValidURL, loading: urlLoading, importFromURL } = useURLImport();

const editDrawerActive = ref(false);

const edits = computed(() => {
	if (!props.value || typeof props.value !== 'object') return {};

	return props.value;
});

const values = inject('values', ref<Record<string, unknown>>({}));

const customFilter = computed(() => {
	return parseFilter(
		deepMap(props.filter, (val: unknown) => {
			if (val && typeof val === 'string') {
				return render(val, values.value);
			}

			return val;
		}),
	);
});

const internalDisabled = computed(() => {
	return props.disabled || (props.enableCreate === false && props.enableSelect === false);
});

function setSelection(selection: (string | number)[] | null) {
	if (selection![0]) {
		update(selection![0]);
	} else {
		remove();
	}
}

function onUpload(fileInfo: FileInfo) {
	file.value = fileInfo;
	activeDialog.value = null;
	update(fileInfo.id);
Repository: directus/directus
File: app/src/interfaces/files/files.vue (Vue)

Code before:
	]?.filename_download;
});

const downloadUrl = computed(() => {
	if (relatedPrimaryKey.value === null || relationInfo.value?.relatedCollection.collection !== 'directus_files') return;
	return getAssetUrl(String(relatedPrimaryKey.value), true);
});

function getFilename(junctionRow: Record<string, any>) {
	const junctionField = relationInfo.value?.junctionField.field;
	if (!junctionField) return;

	const key = junctionRow[junctionField]?.id ?? junctionRow[junctionField] ?? null;
	if (!key) return null;

	return key;
}

function getDownloadName(junctionRow: Record<string, any>) {
	const junctionField = relationInfo.value?.junctionField.field;
	if (!junctionField) return;

	return junctionRow[junctionField]?.filename_download;
}

const values = inject('values', ref<Record<string, any>>({}));

const customFilter = computed(() => {
	if (!relationInfo.value) return;

	const filter: Filter = {
		_and: [],
	};

	const reverseRelation = `$FOLLOW(${relationInfo.value.junctionCollection.collection},${relationInfo.value.junctionField.field})`;

	const selectFilter: Filter = {
		[reverseRelation]: {
			_none: {
				[relationInfo.value.reverseJunctionField.field]: {
					_eq: props.primaryKey,
				},
			},
		},
	};

	if (selectedPrimaryKeys.value.length > 0) {
		filter._and.push({
			[relationInfo.value.relatedPrimaryKeyField.field]: {
				_nin: selectedPrimaryKeys.value,
			},

Review comment (suggestion):
`unknown` would be a safer type choice here than `any` I think

Code after:
	]?.filename_download;
});

const downloadUrl = computed(() => {
	if (relatedPrimaryKey.value === null || relationInfo.value?.relatedCollection.collection !== 'directus_files') return;
	return getAssetUrl(String(relatedPrimaryKey.value), true);
});

function getFilename(junctionRow: Record<string, any>) {
	const junctionField = relationInfo.value?.junctionField.field;
	if (!junctionField) return;

	const key = junctionRow[junctionField]?.id ?? junctionRow[junctionField] ?? null;
	if (!key) return null;

	return key;
}

function getDownloadName(junctionRow: Record<string, any>) {
	const junctionField = relationInfo.value?.junctionField.field;
	if (!junctionField) return;

	return junctionRow[junctionField]?.filename_download;
}

const values = inject('values', ref<Record<string, unknown>>({}));

const customFilter = computed(() => {
	if (!relationInfo.value) return;

	const filter: Filter = {
		_and: [],
	};

	const reverseRelation = `$FOLLOW(${relationInfo.value.junctionCollection.collection},${relationInfo.value.junctionField.field})`;

	const selectFilter: Filter = {
		[reverseRelation]: {
			_none: {
				[relationInfo.value.reverseJunctionField.field]: {
					_eq: props.primaryKey,
				},
			},
		},
	};

	if (selectedPrimaryKeys.value.length > 0) {
		filter._and.push({
			[relationInfo.value.relatedPrimaryKeyField.field]: {
				_nin: selectedPrimaryKeys.value,
			},
Repository: directus/directus
File: app/src/interfaces/files/files.vue (Vue)

Code before:
	const reverseRelation = `$FOLLOW(${relationInfo.value.junctionCollection.collection},${relationInfo.value.junctionField.field})`;

	const selectFilter: Filter = {
		[reverseRelation]: {
			_none: {
				[relationInfo.value.reverseJunctionField.field]: {
					_eq: props.primaryKey,
				},
			},
		},
	};

	if (selectedPrimaryKeys.value.length > 0) {
		filter._and.push({
			[relationInfo.value.relatedPrimaryKeyField.field]: {
				_nin: selectedPrimaryKeys.value,
			},
		});
	}

	if (props.primaryKey !== '+') filter._and.push(selectFilter);

	if (props.filter) {
		filter._and.push(
			parseFilter(
				deepMap(props.filter, (val: any) => {
					if (val && typeof val === 'string') {
						return render(val, values.value);
					}

					return val;
				}),
			),
		);
	}

	return filter;
});

const allowDrag = computed(
	() =>
		totalItemCount.value <= limit.value &&
		relationInfo.value?.sortField !== undefined &&
		!props.disabled &&
		updateAllowed.value,
);
</script>

<template>
	<v-notice v-if="!relationInfo" type="warning">{{ t('relationship_not_setup') }}</v-notice>
	<div v-else class="many-to-many">

Review comment (suggestion):
`unknown` would be a safer type choice here than `any` I think

Code after:
	const reverseRelation = `$FOLLOW(${relationInfo.value.junctionCollection.collection},${relationInfo.value.junctionField.field})`;

	const selectFilter: Filter = {
		[reverseRelation]: {
			_none: {
				[relationInfo.value.reverseJunctionField.field]: {
					_eq: props.primaryKey,
				},
			},
		},
	};

	if (selectedPrimaryKeys.value.length > 0) {
		filter._and.push({
			[relationInfo.value.relatedPrimaryKeyField.field]: {
				_nin: selectedPrimaryKeys.value,
			},
		});
	}

	if (props.primaryKey !== '+') filter._and.push(selectFilter);

	if (props.filter) {
		filter._and.push(
			parseFilter(
				deepMap(props.filter, (val: unknown) => {
					if (val && typeof val === 'string') {
						return render(val, values.value);
					}

					return val;
				}),
			),
		);
	}

	return filter;
});

const allowDrag = computed(
	() =>
		totalItemCount.value <= limit.value &&
		relationInfo.value?.sortField !== undefined &&
		!props.disabled &&
		updateAllowed.value,
);
</script>

<template>
	<v-notice v-if="!relationInfo" type="warning">{{ t('relationship_not_setup') }}</v-notice>
	<div v-else class="many-to-many">
Repository: directus/directus
File: app/src/modules/settings/routes/data-model/field-detail/store/alterations/global.ts (TypeScript)

Code before:
		case 'translations':
		case 'file':
		case 'files':
			set(updates, 'field.meta.special', [localType]);
			break;
		case 'presentation':
			set(updates, 'field.meta.special', ['alias', 'no-data']);
			break;
		case 'group':
			set(updates, 'field.meta.special', ['alias', 'no-data', 'group']);
			break;
	}
}

export function resetRelations(updates: StateUpdates) {
	if (!updates.relations) updates.relations = {};
	updates.relations.m2o = undefined;
	updates.relations.o2m = undefined;
}

export function resetInterfaceAndDisplay(updates: StateUpdates) {
	set(updates, 'field.meta.interface', undefined);
	set(updates, 'field.meta.options', undefined);
	set(updates, 'field.meta.display', undefined);
	set(updates, 'field.meta.display_options', undefined);
}


Review comment (bug):
So I noticed this somewhat weird behavior when attempting to select `directus_files` in an M2O field.

https://github.com/user-attachments/assets/560e1aff-050b-4f91-a98e-ccc986a9ffa3

Now I'm aware we're trying to avoid user error here, but maybe we should adapt `resetInterfaceAndDisplay` to take in the `targetType` as a prop so we can set the `undefined` value for `field.meta.interface` to "files", etc?

https://github.com/user-attachments/assets/fc3cd6b5-daa3-40b0-9207-8fb5516f1546



Code after:
		case 'translations':
		case 'file':
		case 'files':
			set(updates, 'field.meta.special', [localType]);
			break;
		case 'presentation':
			set(updates, 'field.meta.special', ['alias', 'no-data']);
			break;
		case 'group':
			set(updates, 'field.meta.special', ['alias', 'no-data', 'group']);
			break;
	}
}

export function resetRelations(updates: StateUpdates) {
	if (!updates.relations) updates.relations = {};
	updates.relations.m2o = undefined;
	updates.relations.o2m = undefined;
}

export function switchInterfaceAndDisplay(updates: StateUpdates) {
	let targetInterface = undefined;

	if (updates.localType === 'files') {
		targetInterface = 'files';
	} else if (updates.localType === 'file') {
		targetInterface = 'file';
	}

	set(updates, 'field.meta.interface', targetInterface);
	set(updates, 'field.meta.options', undefined);
	set(updates, 'field.meta.display', undefined);
	set(updates, 'field.meta.display_options', undefined);
}
Repository: directus/directus
File: app/src/interfaces/_system/system-filter/input-group.vue (Vue)

Code before:
		/>
		<div class="and">{{ t('interfaces.filter.and') }}</div>
		<input-component
			:is="interfaceType"
			:choices="choices"
			:type="fieldInfo?.type ?? 'unknown'"
			:value="(value as (string | number)[])[1] ?? ''"
			@input="setValueAt(1, $event)"
		/>
	</template>
</template>

<style lang="scss" scoped>
.value {
	display: flex;
	align-items: center;

	.v-icon {
		margin-right: 8px;
		margin-left: 12px;
		color: var(--theme--form--field--input--foreground-subdued);
		cursor: pointer;

		&:hover {
			color: var(--theme--danger);
		}
	}
}

.list {
	display: flex;

	.value:not(:last-child)::after {
		margin-right: 6px;
		content: ',';
	}
}

.and {
	margin: 0 8px;
}
</style>


Review comment (suggestion):
Any other ideas for icon?

There's already a ton of that same `{ }` icon here 🤔 

![image](https://github.com/user-attachments/assets/f89bb129-1c28-4a84-97a3-e0dd6aca1339)


Code after:
		if (newValue === null) {
			value.value = '';
			return;
		}

		newValue = String(newValue).replace(/{{/g, '').replace(/}}/g, '');
		value.value = `{{${newValue}}}`;
	}

	function inputDisplay() {
		if (isVariableInputActive.value && typeof value.value === 'string') {
			return value.value.replace(/{{/g, '').replace(/}}/g, '');
		}

		return '';
	}
}
</script>

<template>
	<v-icon
		v-if="isVariableInputComparator"
		v-tooltip="$t('toggle_variable_input')"
		class="variable-input-toggle"
		:class="{ active: isVariableInputActive }"
		name="data_object"
		small
		clickable
		@click="onToggleVariableInput"
	/>

	<template v-if="isVariableInputActive">
		<span class="variable-input-braces">{{ '\{\{' }}</span>

		<input-component
			is="interface-input"
			class="variable-input"
			type="unknown"
			:value="variableInputDisplay"
			@input="onVariableInput"
		/>

		<span class="variable-input-braces">{{ '\}\}' }}</span>
	</template>

	<template v-else>
		<template v-if="['_eq', '_neq', '_lt', '_gt', '_lte', '_gte'].includes(comparator)">
			<input-component
				:is="interfaceType"
				:choices="choices"
				:type="fieldInfo?.type ?? 'unknown'"
Repository: directus/directus
File: api/src/database/migrations/20250613A-add-project-id.ts (TypeScript)

Code before:
import type { Knex } from 'knex';
import { v7 as uuid } from 'uuid';

export async function up(knex: Knex): Promise<void> {
	await knex.schema.alterTable('directus_settings', (table) => {
		table.uuid('project_id');
	});

	const existing = await knex('directus_settings').select('id').first();

	if (existing) {
		await knex('directus_settings').update({
			project_id: uuid(),
		});
	} else {
		await knex('directus_settings').insert({
			project_id: uuid(),
		});
	}
}

export async function down(knex: Knex): Promise<void> {
	await knex.schema.alterTable('directus_settings', (table) => {
		table.dropColumn('project_id');
	});
}


Review comment (suggestion):
We should get the timestamp of the first database migration

```
const timestamp = await knex('directus_migrations').select('timestamp').first();
``` 

and use that when creating the uuid like 

```
uuid({ msecs: 12345 }) //  RFC "timestamp" field (Number of milliseconds, unix epoch)
```

Code after:
import type { Knex } from 'knex';
import { v7 as uuid } from 'uuid';

export async function up(knex: Knex): Promise<void> {
	await knex.schema.alterTable('directus_settings', (table) => {
		table.uuid('project_id');
	});

	const existing = await knex('directus_settings').select('id').first();
	const timestamp = await knex<{ timestamp: string }>('directus_migrations').select('timestamp').first();
	const msecs = timestamp ? new Date(timestamp.timestamp).getTime() : Date.now();

	if (existing) {
		await knex('directus_settings').update({
			project_id: uuid({
				msecs,
			}),
		});
	} else {
		await knex('directus_settings').insert({
			project_id: uuid(),
		});
	}
}

export async function down(knex: Knex): Promise<void> {
	await knex.schema.alterTable('directus_settings', (table) => {
		table.dropColumn('project_id');
	});
}
Repository: directus/directus
File: api/src/extensions/lib/get-extensions-settings.ts (TypeScript)

Code before:
		}

		// Add new bundle entries to the settings
		for (const entry of bundle.entries) {
			const settingsExist = bundleEntriesSettings.some(({ folder }) => folder === entry.name);

			if (settingsExist) continue;

			newSettings.push({
				id: randomUUID(),
				enabled: bundleSettings.enabled,
				source: bundleSettings.source,
				bundle: bundleSettings.id,
				folder: entry.name,
			});
		}
	};

	const generateSettingsEntry = async (
		folder: string,
		extension: Extension,
		source: 'local' | 'registry' | 'module',
	) => {
		let marketplaceId;

		if (!extension.local) {
			const marketplace = await list({ search: extension.name });
			marketplaceId = marketplace.data[0]?.id;
		}

		const id = marketplaceId ?? randomUUID();

		if (extension.type === 'bundle') {
			newSettings.push({
				id,
				enabled: true,
				source: source,
				bundle: null,
				folder: folder,
			});

			for (const entry of extension.entries) {
				newSettings.push({
					id: randomUUID(),
					enabled: true,
					source: source,
					bundle: id,
					folder: entry.name,
				});
			}
		} else {

Review comment (suggestion):
Per discussion this should be checking `source`, not `local`. `local` is used to indicate if it is an extension that is stored on disk which both local and registry are (via `.registry`)[^1][^2]
```suggestion
		if (source === 'registry') {
```

---
[^1]: https://github.com/directus/directus/blob/main/api/src/extensions/lib/get-extensions.ts
[^2]: https://github.com/directus/directus/blob/bd064fe1d2f7eeb7294e0786f8550816e09b6e82/packages/extensions/src/node/utils/get-extensions.ts#L104

Code after:
		}

		// Add new bundle entries to the settings
		for (const entry of bundle.entries) {
			const settingsExist = bundleEntriesSettings.some(({ folder }) => folder === entry.name);

			if (settingsExist) continue;

			newSettings.push({
				id: randomUUID(),
				enabled: bundleSettings.enabled,
				source: bundleSettings.source,
				bundle: bundleSettings.id,
				folder: entry.name,
			});
		}
	};

	const generateSettingsEntry = async (
		folder: string,
		extension: Extension,
		source: 'local' | 'registry' | 'module',
	) => {
		let marketplaceId;

		if (source === 'registry') {
			const marketplace = await list({ search: extension.name });
			marketplaceId = marketplace.data.find((ext) => ext.name === extension.name)?.id;
		}

		const id = marketplaceId ?? randomUUID();

		if (extension.type === 'bundle') {
			newSettings.push({
				id,
				enabled: true,
				source: source,
				bundle: null,
				folder: folder,
			});

			for (const entry of extension.entries) {
				newSettings.push({
					id: randomUUID(),
					enabled: true,
					source: source,
					bundle: id,
					folder: entry.name,
				});
			}
		} else {
Repository: directus/directus
File: api/src/websocket/authenticate.ts (TypeScript)

Code before:
		}

		if ('access_token' in message) {
			access_token = message.access_token;
		}

		if (!access_token) throw new Error();
		const expires_at = getExpiresAtForToken(access_token);

		const database = getDatabase();
		const defaultAccountability: Accountability = createDefaultAccountability(accountabilityOverrides);

		const authenticationState = {
			accountability: defaultAccountability,
			expires_at,
			refresh_token,
		} as AuthenticationState;

		const customAccountability = await emitter.emitFilter(
			'websocket.authenticate',
			defaultAccountability,
			{
				message,
			},
			{
				database,
				schema: null,
				accountability: null,
			},
		);

		if (customAccountability && isEqual(customAccountability, defaultAccountability) === false) {
			authenticationState.accountability = customAccountability;
		} else {
			authenticationState.accountability = await getAccountabilityForToken(access_token, defaultAccountability);
		}

		return authenticationState;
	} catch {
		throw new WebSocketError('auth', 'AUTH_FAILED', 'Authentication failed.', message['uid']);
	}
}

export function authenticationSuccess(uid?: string | number, refresh_token?: string): string {
	const message: WebSocketResponse = {
		type: 'auth',
		status: 'ok',
	};

	if (uid !== undefined) {
		message.uid = uid;

Review comment (suggestion):
No need to define a `database` variable since it's only used here
```suggestion
				database: getDatabase(),
```

Code after:
		}

		if ('access_token' in message) {
			access_token = message.access_token;
		}

		if (!access_token) throw new Error();

		const defaultAccountability = createDefaultAccountability(accountabilityOverrides);

		const authenticationState = {
			accountability: defaultAccountability,
			expires_at: getExpiresAtForToken(access_token),
			refresh_token,
		} as AuthenticationState;

		const customAccountability = await emitter.emitFilter(
			'websocket.authenticate',
			defaultAccountability,
			{
				message,
			},
			{
				database: getDatabase(),
				schema: null,
				accountability: null,
			},
		);

		if (customAccountability && isEqual(customAccountability, defaultAccountability) === false) {
			authenticationState.accountability = customAccountability;
		} else {
			authenticationState.accountability = await getAccountabilityForToken(access_token, defaultAccountability);
		}

		return authenticationState;
	} catch {
		throw new WebSocketError('auth', 'AUTH_FAILED', 'Authentication failed.', message['uid']);
	}
}

export function authenticationSuccess(uid?: string | number, refresh_token?: string): string {
	const message: WebSocketResponse = {
		type: 'auth',
		status: 'ok',
	};

	if (uid !== undefined) {
		message.uid = uid;
	}