import {
array,
boolean,
object,
parse,
string,
toCustom,
transform,
url,
} from "https://deno.land/x/valibot@v0.22.0/mod.ts";
import ky, { HTTPError } from "npm:ky@1.1.3";
import { joinURL } from "npm:ufo@1.3.2";
const API_URL = "https://crates.io/api/v1/";
const VersionSchema = transform(
object({
num: string(),
dl_path: string([toCustom(input => (new URL(input, API_URL)).href)]),
yanked: boolean(),
}),
({ num: version, dl_path: downloadUrl, ...other }) => ({ version, downloadUrl, ...other }),
);
const CrateInfoSchema = object({
versions: array(VersionSchema),
});
export async function getCrateInfo(crateName: string, version?: string) {
const createURL = joinURL(API_URL, `/crates/${crateName}`);
const crateInfo = parse(CrateInfoSchema, await ky.get(createURL).json());
const versions = crateInfo.versions.filter(it => !it.yanked);
if (!version) return versions.at(0);
return versions.find(it => it.version === version);
}
export { HTTPError };