import { askAI } from 'https://esm.town/v/DFB/askAI'
import { blob } from 'https://esm.town/v/std/blob'
const baseMsg = (extraInfo = '') => `
Please generate me a list of 50 unique, memorable strings that I
could use as simple passwords or for unique IDs. Please use a mix
of funny words and numbers, but the entries should not be more than
12 characters in length. ${extraInfo}
Please separate the values into a marked code block
so that I can easily parse them. Please dont number them.`
const opts = {
slug: 'These values will need to work as slug values, so dont include special characters.',
password:
'These values will be used as passwords, so make sure they satisfy reasonable password requirements and include a special character.',
} as const
type FunType = keyof typeof opts
async function generate(opt: keyof typeof opts) {
try {
const msg = baseMsg(opts[opt])
const res = await askAI(msg)
const sep = '```'
const start = res.indexOf(sep)
const end = res.lastIndexOf(sep)
const data = res.substring(start, end).split('\n').slice(1, -1)
const parsed = parseFunStrings(data)
return parsed
} catch (e) {
console.error(e)
}
}
function parseFunStrings(x: unknown): string[] {
if (Array.isArray(x)) {
return x.filter(x => typeof x === 'string')
}
}
async function getMoreFun(type: FunType, existingFun: string[] = []) {
return [...existingFun, ...(await generate(type))]
}
const isFunType = (t: string): t is FunType => t in opts
export default async function (req: Request): Promise<Response> {
const searchParams = new URL(req.url).searchParams
const funType = searchParams.get('type') ?? 'slug'
if (!isFunType(funType))
return Response.json('you have passed an invalid fun type')
const storageKey = `fun_${funType}s`
const stashFun = async (fun: string[]) => await blob.setJSON(storageKey, fun)
const rawFun = await blob.getJSON(storageKey)
const realFun = parseFunStrings(rawFun)
if (!realFun?.length) {
const fresh = await getMoreFun(funType)
fresh.forEach(str => realFun.push(str))
}
const funItem = realFun.pop()
;(async () => {
if (realFun?.length < 5) {
const toppedOffFun = await getMoreFun(funType, realFun)
await stashFun(toppedOffFun)
} else {
await stashFun(realFun)
}
})()
return Response.json(funItem)
}