cloud / internal-packages / installer / worker / account-name.jsmain at aacbc74
// account-name.js — THE NAME OF A PERSON'S ACCOUNT AND ITS workers.dev ADDRESS, from their email.
// The Cloud names an account it makes `iterate-<slug>`, and gives an account with no workers.dev
// subdomain that same name, so the address is almost always free and needs no question.
//
// A workers.dev subdomain is one DNS label: 1 to 63 of a-z, 0-9 and "-", with a letter or digit
// at each end (wrangler's check: workers-sdk packages/deploy-helpers/src/triggers/subdomain.ts).
const PREFIX = "iterate-";
/** The slug's longest: `iterate-` (8), the slug, and `-` with a 6-letter hash (7) make 63. */
const SLUG_MAX = 63 - PREFIX.length - 7;
/** FNV-1a of the text, as 6 letters of base 36: the same email always gives the same letters. */
function hashOf(text) {
let h = 0x811c9dc5;
for (const byte of new TextEncoder().encode(text)) h = Math.imul(h ^ byte, 0x01000193) >>> 0;
return h.toString(36).padStart(7, "0").slice(-6);
}
/** The email as the slug sees it: lowercase, accents gone, no `+tag`. Null when it has no `@`. */
function partsOf(email) {
const text = String(email || "")
.trim()
.toLowerCase()
.normalize("NFKD")
.replace(/\p{M}/gu, "");
const at = text.lastIndexOf("@");
if (at < 1) return null;
const local = text.slice(0, at).split("+")[0];
// the domain without its last label: gmail.com → gmail, mail.example.co.uk → mail.example.co
const domain = text.slice(at + 1).replace(/\.[^.]*$/, "");
return { text, local, domain };
}
/** `iterate-<slug>` from an email: its local part (without `+tag`) and its domain without the
* last label, in a-z, 0-9 and single dashes. When nothing is left (an email in other scripts),
* the slug is a hash of the email. Null for no email. */
export function iterateNameOf(email) {
const parts = partsOf(email);
if (!parts) return null;
const slug = `${parts.local}-${parts.domain}`
.replace(/[^a-z0-9]+/g, "-")
.replace(/^-+/, "")
.slice(0, SLUG_MAX)
.replace(/-+$/, "");
return `${PREFIX}${slug || hashOf(parts.text)}`;
}
/** The workers.dev names to try in order for a person's account: `iterate-<slug>`, then the same
* with a hash of the email. Empty for no email. */
export function workersDevNamesOf(email) {
const name = iterateNameOf(email);
return name ? [name, `${name}-${hashOf(String(email).trim().toLowerCase())}`] : [];
}