ronantakizawa/codereview-bench huggingface dataset:
Repository: withastro/astro
File: packages/db/src/core/db-client/utils.ts (TypeScript)

Code before:
import type { Config as LibSQLConfig } from '@libsql/client';
import z from 'zod';

const rawLibSQLOptions = z.record(z.string());

const parseNumber = (value: string) => z.coerce.number().parse(value);
const parseBoolean = (value: string) => z.coerce.boolean().parse(value);

const booleanValues = ['true', 'false'];

// parse a value that should be a boolean, but could be a valueless variable)
// e.g. 'file://local-copy.db?readYourWrites' & 'file://local-copy.db?readYourWrites=true' should be parsed as true
const parseOptionalBoolean = (value: string) => {
	if (booleanValues.includes(value)) {
		return parseBoolean(value);
	}
	return true; // If the value is not explicitly 'true' or 'false', assume it's true (valueless variable)
};

const libSQLConfigTransformed = rawLibSQLOptions.transform((raw) => {
	// Ensure the URL is always present
	const parsed: Partial<LibSQLConfig> = {};

	// Optional fields
	for (const [key, value] of Object.entries(raw)) {
		switch (key) {
			case 'syncInterval':
			case 'concurrency':
				parsed[key] = parseNumber(value);
				break;
			case 'readYourWrites':
			case 'offline':
			case 'tls':
				parsed[key] = parseOptionalBoolean(value);
				break;
			case 'authToken':

Review comment (suggestion):
```suggestion
// parse a value that should be a boolean, but could be a valueless variable:
```

Code after:
import type { Config as LibSQLConfig } from '@libsql/client';
import z from 'zod';

const rawLibSQLOptions = z.record(z.string());

const parseNumber = (value: string) => z.coerce.number().parse(value);
const parseBoolean = (value: string) => z.coerce.boolean().parse(value);

const booleanValues = ['true', 'false'];

// parse a value that should be a boolean, but could be a valueless variable:
// e.g. 'file://local-copy.db?readYourWrites' & 'file://local-copy.db?readYourWrites=true' should be parsed as true
const parseOptionalBoolean = (value: string) => {
	if (booleanValues.includes(value)) {
		return parseBoolean(value);
	}
	return true; // If the value is not explicitly 'true' or 'false', assume it's true (valueless variable)
};

const libSQLConfigTransformed = rawLibSQLOptions.transform((raw) => {
	// Ensure the URL is always present
	const parsed: Partial<LibSQLConfig> = {};

	// Optional fields
	for (const [key, value] of Object.entries(raw)) {
		switch (key) {
			case 'syncInterval':
			case 'concurrency':
				parsed[key] = parseNumber(value);
				break;
			case 'readYourWrites':
			case 'offline':
			case 'tls':
				parsed[key] = parseOptionalBoolean(value);
				break;
			case 'authToken':
Repository: withastro/astro
File: packages/astro/src/assets/endpoint/node.ts (TypeScript)

Code before:
			buffer = await loadRemoteImage(sourceUrl);
		} catch (err: unknown) {
			console.error('Could not process image request:', err);
			return undefined;
		}
	}

	return buffer;
}

async function loadRemoteImage(src: URL) {
	try {
		const res = await fetch(src);

		if (!res.ok) {
			return undefined;
		}

		return Buffer.from(await res.arrayBuffer());
	} catch {
		return undefined;
	}
}

const URL_PROTOCOL_REGEX = /^(?:(?:http|ftp|https|ws):?\/\/|\/\/)/;

/**
 * Endpoint used in dev and SSR to serve optimized images by the base image services
 */
export const GET: APIRoute = async ({ request }) => {
	try {
		const imageService = await getConfiguredImageService();

		if (!('transform' in imageService)) {
			throw new Error('Configured image service is not a local service');
		}

		const url = new URL(request.url);
		const transform = await imageService.parseURL(url, imageConfig);

		if (!transform?.src) {
			const err = new Error(
				'Incorrect transform returned by `parseURL`. Expected a transform with a `src` property.',
			);
			console.error('Could not parse image transform from URL:', err);
			return new Response('Internal Server Error', { status: 500 });
		}

		let inputBuffer: Buffer | undefined = undefined;

		if (isCoreRemotePath(transform.src)) {

Review comment (suggestion):
Linter says this can be removed as it’s unused now:

```suggestion
```

Code after:
			buffer = await loadRemoteImage(sourceUrl);
		} catch (err: unknown) {
			console.error('Could not process image request:', err);
			return undefined;
		}
	}

	return buffer;
}

async function loadRemoteImage(src: URL) {
	try {
		const res = await fetch(src);

		if (!res.ok) {
			return undefined;
		}

		return Buffer.from(await res.arrayBuffer());
	} catch {
		return undefined;
	}
}

/**
 * Endpoint used in dev and SSR to serve optimized images by the base image services
 */
export const GET: APIRoute = async ({ request }) => {
	try {
		const imageService = await getConfiguredImageService();

		if (!('transform' in imageService)) {
			throw new Error('Configured image service is not a local service');
		}

		const url = new URL(request.url);
		const transform = await imageService.parseURL(url, imageConfig);

		if (!transform?.src) {
			const err = new Error(
				'Incorrect transform returned by `parseURL`. Expected a transform with a `src` property.',
			);
			console.error('Could not parse image transform from URL:', err);
			return new Response('Internal Server Error', { status: 500 });
		}

		let inputBuffer: Buffer | undefined = undefined;

		if (isCoreRemotePath(transform.src)) {
			if (isRemoteAllowed(transform.src, imageConfig) === false) {
				return new Response('Forbidden', { status: 403 });
Repository: withastro/astro
File: packages/astro/src/core/middleware/sequence.ts (TypeScript)

Code before:
							handleContext.request,
						);

						// This is a case where the user tries to rewrite from a SSR route to a prerendered route (SSG).
						// This case isn't valid because when building for SSR, the prerendered route disappears from the server output because it becomes an HTML file,
						// so Astro can't retrieve it from the emitted manifest.
						if (
							pipeline.serverLike === true &&
							handleContext.isPrerendered === false &&
							routeData.prerender === true
						) {
							throw new AstroError({
								...ForbiddenRewrite,
								message: ForbiddenRewrite.message(
									handleContext.url.pathname,
									pathname,
									routeData.component,
								),
								hint: ForbiddenRewrite.hint(routeData.component),
							});
						}

						carriedPayload = payload;
						handleContext.request = newRequest;
						handleContext.url = new URL(newRequest.url);
						handleContext.cookies = new AstroCookies(newRequest);
						handleContext.params = getParams(routeData, pathname);
						handleContext.routePattern = routeData.route;
						setOriginPathname(
							handleContext.request,
							oldPathname,
							pipeline.manifest.trailingSlash,
							pipeline.manifest.buildFormat,
						);
					}
					return applyHandle(i + 1, handleContext);
				} else {
					return next(payload ?? carriedPayload);
				}
			});
			return result;
		}
	});
}


Review comment (bug):
This assignment wasn't the cause of the bug, but when the bug was fixed, this broke sequences *without* rewrites. It's not needed, because the new request won't have any cookies to read as it has no headers. Instead we preserve the cookies from the original request.

Code after:
						);

						// This is a case where the user tries to rewrite from a SSR route to a prerendered route (SSG).
						// This case isn't valid because when building for SSR, the prerendered route disappears from the server output because it becomes an HTML file,
						// so Astro can't retrieve it from the emitted manifest.
						if (
							pipeline.serverLike === true &&
							handleContext.isPrerendered === false &&
							routeData.prerender === true
						) {
							throw new AstroError({
								...ForbiddenRewrite,
								message: ForbiddenRewrite.message(
									handleContext.url.pathname,
									pathname,
									routeData.component,
								),
								hint: ForbiddenRewrite.hint(routeData.component),
							});
						}

						carriedPayload = payload;
						handleContext.request = newRequest;
						handleContext.url = new URL(newRequest.url);
						handleContext.params = getParams(routeData, pathname);
						handleContext.routePattern = routeData.route;
						setOriginPathname(
							handleContext.request,
							oldPathname,
							pipeline.manifest.trailingSlash,
							pipeline.manifest.buildFormat,
						);
					}
					return applyHandle(i + 1, handleContext);
				} else {
					return next(payload ?? carriedPayload);
				}
			});
			return result;
		}
	});
}
Repository: withastro/astro
File: packages/astro/src/core/render-context.ts (TypeScript)

Code before:
		const pipelineMiddleware = await pipeline.getMiddleware();
		const pipelineActions = actions ?? (await pipeline.getActions());
		setOriginPathname(
			request,
			pathname,
			pipeline.manifest.trailingSlash,
			pipeline.manifest.buildFormat,
		);
		return new RenderContext(
			pipeline,
			locals,
			sequence(...pipeline.internalMiddleware, middleware ?? pipelineMiddleware),
			pipelineActions,
			pathname,
			request,
			routeData,
			status,
			clientAddress,
			undefined,
			undefined,
			undefined,
			props,
			partial,
			typeof shouldInjectCspMetaTags !== 'undefined'
				? shouldInjectCspMetaTags
				: !!pipeline.manifest.csp,
		);
	}
	/**
	 * The main function of the RenderContext.
	 *
	 * Use this function to render any route known to Astro.
	 * It attempts to render a route. A route can be a:
	 *
	 * - page
	 * - redirect
	 * - endpoint
	 * - fallback
	 */
	async render(
		componentInstance: ComponentInstance | undefined,
		slots: Record<string, any> = {},
	): Promise<Response> {
		const { cookies, middleware, pipeline } = this;
		const { logger, serverLike, streaming, manifest } = pipeline;

		const props =
			Object.keys(this.props).length > 0
				? this.props
				: await getProps({
						mod: componentInstance,

Review comment (suggestion):
```suggestion
			shouldInjectCspMetaTags ?? !!pipeline.manifest.csp,
```

Code after:
		const pipelineMiddleware = await pipeline.getMiddleware();
		const pipelineActions = actions ?? (await pipeline.getActions());
		setOriginPathname(
			request,
			pathname,
			pipeline.manifest.trailingSlash,
			pipeline.manifest.buildFormat,
		);
		return new RenderContext(
			pipeline,
			locals,
			sequence(...pipeline.internalMiddleware, middleware ?? pipelineMiddleware),
			pipelineActions,
			pathname,
			request,
			routeData,
			status,
			clientAddress,
			undefined,
			undefined,
			undefined,
			props,
			partial,
			shouldInjectCspMetaTags ?? !!pipeline.manifest.csp,
		);
	}
	/**
	 * The main function of the RenderContext.
	 *
	 * Use this function to render any route known to Astro.
	 * It attempts to render a route. A route can be a:
	 *
	 * - page
	 * - redirect
	 * - endpoint
	 * - fallback
	 */
	async render(
		componentInstance: ComponentInstance | undefined,
		slots: Record<string, any> = {},
	): Promise<Response> {
		const { cookies, middleware, pipeline } = this;
		const { logger, serverLike, streaming, manifest } = pipeline;

		const props =
			Object.keys(this.props).length > 0
				? this.props
				: await getProps({
						mod: componentInstance,
						routeData: this.routeData,
						routeCache: this.pipeline.routeCache,
Repository: withastro/astro
File: packages/astro/test/astro-get-static-paths.test.js (JavaScript)

Code before:
	let fixture;

	before(async () => {
		fixture = await loadFixture({
			root,
			site: 'https://mysite.dev/',
		});
		await fixture.editFile(
			'/src/pages/food/[name].astro',
			(prev) => prev.replace('getStaticPaths() {', 'getStaticPaths() {\nAstro.getActionResult;'),
			false,
		);
	});

	after(async () => {
		fixture.resetAllFiles();
	});

	it('does not build', async () => {
		try {
			await fixture.build({});
			assert.fail();
		} catch (err) {
			assert.equal(err instanceof Error, true);
			// @ts-ignore
			assert.equal(err.title, 'Unavailable Astro global property in getStaticPaths');
		}
	});
});


Review comment (suggestion):
```suggestion
			assert.equal(err.title, 'Unavailable Astro global in getStaticPaths()');
```

Code after:
	let fixture;

	before(async () => {
		fixture = await loadFixture({
			root,
			site: 'https://mysite.dev/',
		});
		await fixture.editFile(
			'/src/pages/food/[name].astro',
			(prev) => prev.replace('getStaticPaths() {', 'getStaticPaths() {\nAstro.getActionResult;'),
			false,
		);
	});

	after(async () => {
		fixture.resetAllFiles();
	});

	it('does not build', async () => {
		try {
			await fixture.build({});
			assert.fail();
		} catch (err) {
			assert.equal(err instanceof Error, true);
			// @ts-ignore
			assert.equal(err.title, 'Unavailable Astro global in getStaticPaths()');
		}
	});
});
Repository: withastro/astro
File: packages/astro/src/types/public/integrations.ts (TypeScript)

Code before:
	 *
	 * NOTE: the semantics and list of headers might change until the feature
	 * is out of experimental
	 */
	experimentalStaticHeaders?: boolean;
}

export interface AstroAdapter {
	name: string;
	serverEntrypoint?: string | URL;
	previewEntrypoint?: string | URL;
	exports?: string[];
	args?: any;
	adapterFeatures?: AstroAdapterFeatures;
	/**
	 * List of features supported by an adapter.
	 *
	 * If the adapter is not able to handle certain configurations, Astro will throw an error.
	 */
	supportedAstroFeatures: AstroAdapterFeatureMap;
	/**
	 * Runtime configuration that will be available to Astro's client-side code.
	 */
	runtimeConfig?: {
		/**
		 * Headers to inject into Astro's internal fetch calls (Actions, View Transitions, Server Islands, Prefetch).
		 * Can be an object of headers or a function that returns headers.
		 */
		internalFetchHeaders?: Record<string, string> | (() => Record<string, string>);
	};
}

export type AstroAdapterFeatureMap = {
	/**
	 * The adapter is able to serve static pages
	 */
	staticOutput?: AdapterSupport;

	/**
	 * The adapter is able to serve pages that are static or rendered via server
	 */
	hybridOutput?: AdapterSupport;

	/**
	 * The adapter is able to serve SSR pages
	 */
	serverOutput?: AdapterSupport;

	/**
	 * The adapter is able to support i18n domains
	 */

Review comment (suggestion):
We also have a fetch call for retrieving the 404 error in SSR. I believe this isn't internal.

I would put the supported features inside a list. They aren't a detail, but they define user and developer expectations 

Code after:
	 *
	 * NOTE: the semantics and list of headers might change until the feature
	 * is out of experimental
	 */
	experimentalStaticHeaders?: boolean;
}

export interface AstroAdapter {
	name: string;
	serverEntrypoint?: string | URL;
	previewEntrypoint?: string | URL;
	exports?: string[];
	args?: any;
	adapterFeatures?: AstroAdapterFeatures;
	/**
	 * List of features supported by an adapter.
	 *
	 * If the adapter is not able to handle certain configurations, Astro will throw an error.
	 */
	supportedAstroFeatures: AstroAdapterFeatureMap;
	/**
	 * Configuration for Astro's client-side code.
	 */
	client?: {
		/**
		 * Headers to inject into Astro's internal fetch calls (Actions, View Transitions, Server Islands, Prefetch).
		 * Can be an object of headers or a function that returns headers.
		 */
		internalFetchHeaders?: Record<string, string> | (() => Record<string, string>);
		/**
		 * Query parameters to append to all asset URLs (images, stylesheets, scripts, etc.).
		 * Useful for adapters that need to track deployment versions or other metadata.
		 */
		assetQueryParams?: URLSearchParams;
	};
}

export type AstroAdapterFeatureMap = {
	/**
	 * The adapter is able to serve static pages
	 */
	staticOutput?: AdapterSupport;

	/**
	 * The adapter is able to serve pages that are static or rendered via server
	 */
	hybridOutput?: AdapterSupport;

	/**
	 * The adapter is able to serve SSR pages
	 */
Repository: withastro/astro
File: packages/astro/src/vite-plugin-adapter-config/index.ts (TypeScript)

Code before:
import type { Plugin as VitePlugin } from 'vite';
import type { AstroSettings } from '../types/astro.js';

const VIRTUAL_CLIENT_ID = 'astro:adapter-config/client';
const RESOLVED_VIRTUAL_CLIENT_ID = '\0' + VIRTUAL_CLIENT_ID;

export function vitePluginAdapterConfig(settings: AstroSettings): VitePlugin {
	return {
		name: 'astro:adapter-config',
		resolveId(id) {
			if (id === VIRTUAL_CLIENT_ID) {
				return RESOLVED_VIRTUAL_CLIENT_ID;
			}
		},
		load(id, options) {
			if (id === RESOLVED_VIRTUAL_CLIENT_ID) {
				// During SSR, return empty headers to avoid any runtime issues
				if (options?.ssr) {
					return {
						code: `export const internalFetchHeaders = {};`,
					};
				}

				const adapter = settings.adapter;
				const runtimeConfig = adapter?.runtimeConfig || {};

				let internalFetchHeaders = {};
				if (runtimeConfig.internalFetchHeaders) {
					internalFetchHeaders =

Review comment (suggestion):
The presence of `/client` implies a possible `/server`. However, it seems that's not the case, so maybe we should just remove it or call it `/runtime`

Code after:
import type { Plugin as VitePlugin } from 'vite';
import type { AstroSettings } from '../types/astro.js';

const VIRTUAL_CLIENT_ID = 'virtual:astro:adapter-config/client';
const RESOLVED_VIRTUAL_CLIENT_ID = '\0' + VIRTUAL_CLIENT_ID;

export function vitePluginAdapterConfig(settings: AstroSettings): VitePlugin {
	return {
		name: 'astro:adapter-config',
		resolveId(id) {
			if (id === VIRTUAL_CLIENT_ID) {
				return RESOLVED_VIRTUAL_CLIENT_ID;
			}
		},
		load(id, options) {
			if (id === RESOLVED_VIRTUAL_CLIENT_ID) {
				// During SSR, return empty headers to avoid any runtime issues
				if (options?.ssr) {
					return {
						code: `export const internalFetchHeaders = {};`,
					};
				}

				const adapter = settings.adapter;
				const clientConfig = adapter?.client || {};

				let internalFetchHeaders = {};
				if (clientConfig.internalFetchHeaders) {
					internalFetchHeaders =
Repository: withastro/astro
File: packages/astro/dev-only.d.ts (TypeScript)

Code before:
// IMPORTANT: do not publish this file!
// It provides typings for internal virtual modules.
// The naming convention is: virtual:astro:<feature>/<...custom>

declare module 'virtual:astro:env/internal' {
	export const schema: import('./src/env/schema.js').EnvSchema;
}

declare module 'virtual:astro:assets/fonts/internal' {
	export const internalConsumableMap: import('./src/assets/fonts/types.js').InternalConsumableMap;
	export const consumableMap: import('./src/assets/fonts/types.js').ConsumableMap;
}

declare module 'astro:adapter-config/client' {
	export const internalFetchHeaders: Record<string, string>;
}

declare module 'virtual:astro:actions/options' {
	export const shouldAppendTrailingSlash: boolean;
}

declare module 'virtual:astro:actions/runtime' {
	export * from './src/actions/runtime/client.js';
}


Review comment (suggestion):
Since it's an internal virtual module, can we stick to the convention? In this case
```suggestion
declare module 'virtual:astro:adapter-config/client' {
```

Code after:
// IMPORTANT: do not publish this file!
// It provides typings for internal virtual modules.
// The naming convention is: virtual:astro:<feature>/<...custom>

declare module 'virtual:astro:env/internal' {
	export const schema: import('./src/env/schema.js').EnvSchema;
}

declare module 'virtual:astro:assets/fonts/internal' {
	export const internalConsumableMap: import('./src/assets/fonts/types.js').InternalConsumableMap;
	export const consumableMap: import('./src/assets/fonts/types.js').ConsumableMap;
}

declare module 'virtual:astro:adapter-config/client' {
	export const internalFetchHeaders: Record<string, string>;
}

declare module 'virtual:astro:actions/options' {
	export const shouldAppendTrailingSlash: boolean;
}

declare module 'virtual:astro:actions/runtime' {
	export * from './src/actions/runtime/client.js';
}
Repository: withastro/astro
File: packages/astro/src/cli/add/index.ts (TypeScript)

Code before:
	DB_CONFIG: `\
import { defineDb } from 'astro:db';

// https://astro.build/db/config
export default defineDb({
  tables: {}
});
`,
	DB_SEED: `\
import { db } from 'astro:db';

// https://astro.build/db/seed
export default async function seed() {
	// TODO
}
`,
	CLOUDFLARE_WRANGLER_CONFIG: (name: string) => `\
{
	"main": "dist/_worker.js/index.js",
	"name": ${JSON.stringify(name)},
	"assets": {
		"binding": "ASSETS",
		"directory": "./dist"
	}
}`,
	CLOUDFLARE_ASSETSIGNORE: `_worker.js\n_routes.json`,
};

const OFFICIAL_ADAPTER_TO_IMPORT_MAP: Record<string, string> = {
	netlify: '@astrojs/netlify',
	vercel: '@astrojs/vercel',
	cloudflare: '@astrojs/cloudflare',
	node: '@astrojs/node',
};

export async function add(names: string[], { flags }: AddOptions) {
	ensureProcessNodeEnv('production');
	applyPolyfill();
	const inlineConfig = flagsToAstroInlineConfig(flags);
	const { userConfig } = await resolveConfig(inlineConfig, 'add');
	telemetry.record(eventCliSession('add', userConfig));
	if (flags.help || names.length === 0) {
		printHelp({
			commandName: 'astro add',
			usage: '[...integrations] [...adapters]',
			tables: {
				Flags: [
					['--yes', 'Accept all prompts.'],
					['--help', 'Show this help message.'],
				],
				'UI Frameworks': [

Review comment (suggestion):
`compatibility_date` is required for publishing. What if we added 
```suggestion
  "compatibility_date": ${JSON.stringify(new Date().toISOString().slice(0,10))},
	"assets": {
```

Code after:
	DB_CONFIG: `\
import { defineDb } from 'astro:db';

// https://astro.build/db/config
export default defineDb({
  tables: {}
});
`,
	DB_SEED: `\
import { db } from 'astro:db';

// https://astro.build/db/seed
export default async function seed() {
	// TODO
}
`,
	CLOUDFLARE_WRANGLER_CONFIG: (name: string) => `\
{
	"main": "dist/_worker.js/index.js",
	"name": ${JSON.stringify(name)},
  "compatibility_date": ${JSON.stringify(new Date().toISOString().slice(0,10))},
  "compatibility_flags": [
    "nodejs_compat",
    "global_fetch_strictly_public"
  ],
	"assets": {
		"binding": "ASSETS",
		"directory": "./dist"
	},
	"observability": {
    "enabled": true
  }
}`,
	CLOUDFLARE_ASSETSIGNORE: `_worker.js\n_routes.json`,
};

const OFFICIAL_ADAPTER_TO_IMPORT_MAP: Record<string, string> = {
	netlify: '@astrojs/netlify',
	vercel: '@astrojs/vercel',
	cloudflare: '@astrojs/cloudflare',
	node: '@astrojs/node',
};

export async function add(names: string[], { flags }: AddOptions) {
	ensureProcessNodeEnv('production');
	applyPolyfill();
	const inlineConfig = flagsToAstroInlineConfig(flags);
	const { userConfig } = await resolveConfig(inlineConfig, 'add');
	telemetry.record(eventCliSession('add', userConfig));
	if (flags.help || names.length === 0) {
		printHelp({