1 import { randomBytes } from "node:crypto"
2
3 /** Bytes of randomness in the suffix — 3 gives 6 hex characters. */
4 const SUFFIX_BYTES = 3
5
6 /**
7 * A random, URL-safe suffix.
8 *
9 * Drawn from `crypto` rather than `Math.random` so two runs starting in the same
10 * millisecond cannot land on the same value.
11 */
12 export function randomSuffix(): string {
13 return randomBytes(SUFFIX_BYTES).toString("hex")
14 }
15
16 /**
17 * Appends a random suffix to a public ID, so every upload gets its own URL.
18 *
19 * A stable ID would let a re-upload replace the image behind a URL that is
20 * already published; a fresh one per upload means an image, once linked, keeps
21 * showing what it showed when it was linked.
22 *
23 * The trade-off is that re-running for the same version no longer updates the
24 * asset in place — it adds another one, and the previous one is left behind.
25 */
26 export function withRandomSuffix(publicId: string): string {
27 return `${publicId}-${randomSuffix()}`
28 }
29
30 /**
31 * Turns a label into a Cloudinary public ID.
32 *
33 * Dots are replaced because Cloudinary reads the segment after the last dot in
34 * a public ID as the format, which would make `v2.19.0` deliver as a file named
35 * `v2.19` in a `0` format. Dashes also keep these consistent with the banners
36 * that were uploaded by hand before this was automated.
37 */
38 export function toPublicId(label: string): string {
39 return label
40 .trim()
41 .toLowerCase()
42 .replace(/[^a-z0-9]+/g, "-")
43 .replace(/^-+|-+$/g, "")
44 }