import type { Env, User } from '../env';
import { escapeHtml, newId, now } from './util';
type Mail = { to: string; subject: string; heading: string; lines: string[]; cta?: { label: string; url: string }; kind: string; userId?: string | null };
function layout(env: Env, m: Mail): string {
const body = m.lines.map((l) => `
${l}
`).join('');
const cta = m.cta
? `${escapeHtml(m.cta.label)}
`
: '';
return `
| Skillfarm |
${escapeHtml(m.heading)}
${body}${cta}
|
You are getting this because you have a Skillfarm account. Change email notices in your settings.
|
`;
}
function textVersion(m: Mail): string {
const strip = (s: string) => s.replace(/<[^>]+>/g, '').replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"').replace(/'/g, "'");
return [m.heading, '', ...m.lines.map(strip), '', m.cta ? `${m.cta.label}: ${m.cta.url}` : ''].join('\n').trim();
}
async function log(env: Env, m: Mail, status: string, detail?: string) {
try {
await env.DB.prepare('INSERT INTO email_log (id, user_id, kind, status, detail, created_at) VALUES (?,?,?,?,?,?)')
.bind(newId(), m.userId ?? null, m.kind, status, detail?.slice(0, 300) ?? null, now())
.run();
} catch {
/* logging must never break the caller */
}
}
export async function sendMail(env: Env, m: Mail): Promise {
if (!env.RESEND_API_KEY) {
await log(env, m, 'skipped', 'RESEND_API_KEY is not set');
return false;
}
try {
const res = await fetch('https://api.resend.com/emails', {
method: 'POST',
headers: { authorization: `Bearer ${env.RESEND_API_KEY}`, 'content-type': 'application/json' },
body: JSON.stringify({ from: env.EMAIL_FROM, to: [m.to], subject: m.subject, html: layout(env, m), text: textVersion(m) }),
});
if (!res.ok) {
await log(env, m, 'failed', `${res.status} ${await res.text()}`);
return false;
}
await log(env, m, 'sent');
return true;
} catch (e) {
await log(env, m, 'failed', String(e));
return false;
}
}
type Recipient = Pick;
async function toUser(env: Env, user: Recipient | null, m: Omit): Promise {
if (!user || !user.email || !user.email_notices) return false;
return sendMail(env, { ...m, to: user.email, userId: user.id });
}
const e = escapeHtml;
export const mail = {
welcome: (env: Env, user: Recipient, handle: string) =>
toUser(env, user, {
kind: 'welcome',
subject: 'Welcome to Skillfarm',
heading: `Welcome to the farm, ${user.display_name}`,
lines: [
'Your profile is ready. Share an agent skill and you earn Seeds, which raise your tier and get your portfolio more exposure.',
'Every skill is reviewed before it goes live, so the first step is to plant one.',
],
cta: { label: 'Share your first skill', url: `${env.SITE_URL}/share` },
}),
received: (env: Env, user: Recipient, title: string, url: string) =>
toUser(env, user, {
kind: 'received',
subject: `We received "${title}"`,
heading: 'Your skill is in the review queue',
lines: [`${e(title)} was submitted and is waiting for review. Nothing is public yet.`, 'You will get another email as soon as it is approved or denied.'],
cta: { label: 'View your submission', url },
}),
approved: (env: Env, user: Recipient, title: string, url: string, seeds: number) =>
toUser(env, user, {
kind: 'approved',
subject: `"${title}" is live on Skillfarm`,
heading: 'Approved. Your skill is live.',
lines: [
`${e(title)} passed review and is now public.`,
seeds > 0 ? `You earned ${seeds} Seeds for sharing it. Installs, likes and replants earn more.` : 'This update replaces the previous version.',
],
cta: { label: 'See it on Skillfarm', url },
}),
denied: (env: Env, user: Recipient, title: string, url: string, note: string) =>
toUser(env, user, {
kind: 'denied',
subject: `"${title}" was not approved`,
heading: 'Your skill was not approved',
lines: [
`${e(title)} did not pass review, so it is not public.`,
note ? `Reviewer note: ${e(note)}` : 'No reviewer note was left.',
'You can fix the issue and submit a new version from the skill page.',
],
cta: { label: 'Open your submission', url },
}),
removed: (env: Env, user: Recipient, title: string, note: string) =>
toUser(env, user, {
kind: 'removed',
subject: `"${title}" was taken down`,
heading: 'Your skill was taken down',
lines: [`${e(title)} was removed from Skillfarm by a moderator, and the Seeds it earned were reversed.`, note ? `Moderator note: ${e(note)}` : ''].filter(Boolean),
}),
tierUp: (env: Env, user: Recipient, tierName: string, perk: string, handle: string) =>
toUser(env, user, {
kind: 'tier-up',
subject: `You are now a ${tierName} on Skillfarm`,
heading: `You grew into ${tierName}`,
lines: [`Your Seeds carried you to a new tier.`, `New at this tier: ${e(perk)}.`],
cta: { label: 'See your profile', url: `${env.SITE_URL}/u/${handle}` },
}),
repoReceived: (env: Env, user: Recipient, repo: string, queued: number, skipped: number, url: string) =>
toUser(env, user, {
kind: 'repo-received',
subject: `We received ${repo}`,
heading: 'Your repo is in the review queue',
lines: [
`Skillfarm read ${e(repo)} and found ${queued === 1 ? '1 skill' : `${queued} skills`} to review.${skipped ? ` ${skipped === 1 ? '1 folder was' : `${skipped} folders were`} left out, and the page below says why.` : ''}`,
'Nothing is public yet. A person reviews the repo and each skill in it. You will get an email with the decision.',
],
cta: { label: 'See what was found', url },
}),
repoDenied: (env: Env, user: Recipient, repo: string, count: number, note: string, url: string) =>
toUser(env, user, {
kind: 'repo-denied',
subject: `${repo} was not approved`,
heading: 'Your repo was not approved',
lines: [
`${e(repo)} did not pass review, so ${count === 1 ? 'its skill is' : `its ${count} skills are`} not public.`,
note ? `Reviewer note: ${e(note)}` : 'No reviewer note was left.',
'You are welcome to improve the skills and share the repo again. In the meantime you can like and comment on other skills.',
],
cta: { label: 'Open your submission', url },
}),
repoApproved: (env: Env, user: Recipient, repo: string, titles: string[], seeds: number, url: string) =>
toUser(env, user, {
kind: 'repo-approved',
subject: `${titles.length === 1 ? '1 skill' : `${titles.length} skills`} from ${repo} ${titles.length === 1 ? 'is' : 'are'} live on Skillfarm`,
heading: 'Approved. Your skills are live.',
lines: [
`These passed review and are now on your profile: ${titles.slice(0, 25).map(e).join(', ')}.`,
seeds > 0 ? `You earned ${seeds} Seeds for sharing them. Installs, likes and replants earn more.` : '',
].filter(Boolean),
cta: { label: 'See your profile', url },
}),
adminRepo: async (env: Env, repo: string, owner: string, count: number, url: string) => {
const admins = await env.DB.prepare("SELECT id, email, email_notices, display_name, status FROM users WHERE is_admin = 1 AND status = 'active'").all();
for (const a of admins.results) {
await toUser(env, a, {
kind: 'admin-repo',
subject: `Review needed: ${repo} by @${owner} (${count === 1 ? '1 skill' : `${count} skills`})`,
heading: 'A shared repo is ready for your review',
lines: [`${e(repo)} by @${e(owner)} holds ${count === 1 ? '1 skill' : `${count} skills`}.`, 'The AI review of each skill fills in over the next few minutes. You can deny the whole repo in one step, or approve and deny skills one by one.'],
cta: { label: 'Open the repo', url },
});
}
},
adminReview: async (env: Env, title: string, owner: string, recommendation: string, summary: string) => {
const admins = await env.DB.prepare("SELECT id, email, email_notices, display_name, status FROM users WHERE is_admin = 1 AND status = 'active'").all();
for (const a of admins.results) {
await toUser(env, a, {
kind: 'admin-review',
subject: `Review needed: "${title}" by @${owner} (AI: ${recommendation})`,
heading: 'A submission is ready for your review',
lines: [`${e(title)} by @${e(owner)}`, `AI recommendation: ${e(recommendation)}`, e(summary)],
cta: { label: 'Open the review queue', url: `${env.SITE_URL}/admin` },
});
}
},
};