import ValTown from 'npm:@valtown/sdk';
import "jsr:@std/dotenv/load";
import { Sema } from 'npm:async-sema';
const client = new ValTown();
export async function getUser(username) {
const user = await client.alias.username.retrieve(username);
return user;
}
export async function getVals(username) {
const user = await getUser(username);
const valsArray = [];
if (user && user.id) {
for await (const basicVal of client.users.vals.list(user.id, {
limit: 100,
offset: 0,
})) {
valsArray.push(basicVal);
}
} else {
console.error('User not found or invalid user ID');
}
return valsArray;
}
export async function getValVersions(valOrId) {
const versionsArray = [];
const valId = typeof valOrId === 'string' ? valOrId : valOrId.id;
for await (const versionListResponse of client.vals.versions.list(valId, {
limit: 20,
offset: 0,
})) {
versionsArray.push(versionListResponse);
}
return versionsArray;
}
export async function getValsWithVersions(username, concurrency = 40) {
const user = await getUser(username);
const valsArray = [];
if (user && user.id) {
const semaphore = new Sema(concurrency);
const processVal = async (basicVal) => {
await semaphore.acquire();
const versions = await getValVersions(basicVal.id);
valsArray.push({ ...basicVal, versions });
semaphore.release();
};
const valPromises = [];
for await (const basicVal of client.users.vals.list(user.id, {
limit: 100,
offset: 0,
})) {
valPromises.push(processVal(basicVal));
}
await Promise.all(valPromises);
} else {
console.error('User not found or invalid user ID');
}
return valsArray;
}