veyce 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/index.ts"],"sourcesContent":["/**\n * veyce — a tiny, dependency-free client for the avatars API.\n *\n * const avatars = createAvatars(); // uses https://veyce.vercel.app\n *\n * avatars.url({ seed: \"ada@example.com\", size: 96 }); // any string -> always an avatar\n * avatars.url({ id: \"raul\", collection: \"gta-vi\" }); // exact id -> that image, or 404\n * avatars.url({ id: user.avatarId, seed: user.email }); // exact if it exists, seed otherwise\n *\n * Works in browsers, Node 18+, Deno, Bun and edge runtimes.\n */\n\n/** The public veyce service. Used whenever no `baseUrl` is given. */\nexport const DEFAULT_BASE_URL = \"https://veyce.vercel.app\";\n\nexport const MIN_SIZE = 8;\nexport const MAX_SIZE = 2160;\nexport const DEFAULT_SIZE = 80;\n\nexport const CROPS = [\"square\", \"portrait\", \"landscape\", \"phone\", \"tablet\", \"ultrawide\"] as const;\nexport type Crop = (typeof CROPS)[number];\n\nexport const FORMATS = [\"webp\", \"png\", \"jpeg\"] as const;\nexport type Format = (typeof FORMATS)[number];\n\nexport type AvatarOptions = {\n /** Collection to draw from, e.g. `gta-vi`. Omit to use every collection. */\n collection?: string;\n /**\n * Exact image id. Unknown ids are a 404 — unless a `seed` is also given, in\n * which case the API falls back to the seed.\n */\n id?: string;\n /**\n * Anything: an email, username, uuid, number. The same seed always maps to\n * the same image (for a fixed library). Never 404s.\n */\n seed?: string | number;\n /** Pixels, 8–2160. Defaults to 80. Never upscaled past the source image. */\n size?: number;\n /** Which crop of the image to use. Defaults to `square`. */\n crop?: Crop | (string & {});\n /** `full` keeps the original aspect ratio (no mask). Defaults to `cover`. */\n fit?: \"cover\" | \"full\";\n /** Square corners instead of the default circle mask. */\n square?: boolean;\n /** Output format. Defaults to `webp`. */\n format?: Format;\n /** Hex corner fill used when a circle is encoded as JPEG, e.g. `#0b0b0f`. */\n background?: string;\n};\n\nexport type ClientConfig = {\n /** Where the avatars service is hosted. Defaults to `https://veyce.vercel.app`. A trailing `/api` is fine. */\n baseUrl?: string;\n /** Options applied to every call; per-call options win. */\n defaults?: AvatarOptions;\n /** Custom fetch (for tests, proxies or older runtimes). Defaults to `globalThis.fetch`. */\n fetch?: typeof fetch;\n};\n\n/** How the API chose the image. */\nexport type Match = \"id\" | \"seed\" | \"random\";\n\nexport type AvatarInfo = {\n collection: string;\n id: string;\n crop: string;\n /** The real pixel size served (may be smaller than requested). */\n size: number;\n match: Match;\n /** Stable URL that addresses this exact image by id — store this to \"pin\" a seeded avatar. */\n url: string;\n};\n\nexport type Photo = {\n id: string;\n label: string;\n collection: string;\n crops: string[];\n /** Path on the service, e.g. `/api/gta-vi/raul`. */\n url: string;\n};\n\nexport type PhotoIndex = {\n count: number;\n collections: string[];\n size: { min: number; max: number; default: number };\n photos: Photo[];\n};\n\nexport type AvatarImage = {\n bytes: Uint8Array;\n contentType: string;\n info: AvatarInfo;\n};\n\nexport class AvatarError extends Error {\n readonly status: number;\n readonly body: unknown;\n\n constructor(message: string, status: number, body?: unknown) {\n super(message);\n this.name = \"AvatarError\";\n this.status = status;\n this.body = body;\n }\n}\n\n/**\n * The seed hash the service uses. Exposed so you can map seeds to images\n * offline (see `pick`) and get the exact same answer as the API.\n */\nexport function hashSeed(seed: string | number): number {\n const value = String(seed);\n let hash = 0;\n for (let i = 0; i < value.length; i += 1) {\n hash = (hash << 5) - hash + value.charCodeAt(i);\n hash |= 0;\n }\n return Math.abs(hash) || 1;\n}\n\n/**\n * Offline seed -> photo, identical to the API's choice for the same library.\n * Pass `photos` from `list()` (scoped to the same collection you pass the API).\n */\nexport function pick<T>(seed: string | number, photos: readonly T[]): T | undefined {\n if (!photos.length) return undefined;\n return photos[hashSeed(seed) % photos.length];\n}\n\nexport function clampSize(size: number): number {\n if (!Number.isFinite(size)) return DEFAULT_SIZE;\n return Math.min(MAX_SIZE, Math.max(MIN_SIZE, Math.round(size)));\n}\n\n/** `https://x.com/`, `https://x.com/api` -> `https://x.com/api` */\nfunction apiRoot(baseUrl?: string): string {\n const trimmed = (baseUrl || DEFAULT_BASE_URL).replace(/\\/+$/, \"\");\n return /\\/api$/.test(trimmed) ? trimmed : `${trimmed}/api`;\n}\n\nfunction normalizeHex(value: string): string | null {\n const hex = value.replace(/^#/, \"\");\n return /^([0-9a-f]{3}|[0-9a-f]{6})$/i.test(hex) ? hex.toLowerCase() : null;\n}\n\n/**\n * Build an avatar URL. Pure string work — no network, safe to call in render.\n *\n * Ids and seeds always go in the query string, so a seed that happens to look\n * like an id, a size or a crop is never misread.\n */\nexport function avatarUrl(baseUrl: string | undefined, options: AvatarOptions = {}): string {\n const root = apiRoot(baseUrl);\n const path = options.collection ? `${root}/${encodeURIComponent(options.collection)}` : root;\n\n const query = new URLSearchParams();\n if (options.id !== undefined && options.id !== \"\") query.set(\"id\", options.id);\n if (options.seed !== undefined && options.seed !== \"\") query.set(\"seed\", String(options.seed));\n if (options.size !== undefined) query.set(\"size\", String(clampSize(options.size)));\n if (options.crop) query.set(\"crop\", options.crop);\n if (options.fit && options.fit !== \"cover\") query.set(\"fit\", options.fit);\n if (options.square) query.set(\"square\", \"true\");\n if (options.format && options.format !== \"webp\") query.set(\"format\", options.format);\n if (options.background) {\n const hex = normalizeHex(options.background);\n if (!hex) throw new TypeError(`veyce: invalid background \"${options.background}\".`);\n query.set(\"bg\", hex);\n }\n\n const qs = query.toString();\n return qs ? `${path}?${qs}` : path;\n}\n\n/** `url 1x, url 2x, url 3x` for crisp avatars on high-density screens. */\nexport function avatarSrcSet(\n baseUrl: string | undefined,\n options: AvatarOptions = {},\n densities: readonly number[] = [1, 2, 3],\n): string {\n const size = options.size ?? DEFAULT_SIZE;\n const seen = new Set<number>();\n return densities\n .map((density) => ({ density, px: clampSize(size * density) }))\n .filter(({ px }) => (seen.has(px) ? false : (seen.add(px), true)))\n .map(({ density, px }) => `${avatarUrl(baseUrl, { ...options, size: px })} ${density}x`)\n .join(\", \");\n}\n\nfunction readInfo(root: string, headers: Headers, requested: number): AvatarInfo {\n const collection = headers.get(\"x-photo-collection\") ?? \"\";\n const id = headers.get(\"x-photo-id\") ?? \"\";\n const match = (headers.get(\"x-photo-match\") as Match | null) ?? \"id\";\n return {\n collection,\n id,\n crop: headers.get(\"x-photo-crop\") ?? \"square\",\n size: Number(headers.get(\"x-photo-size\") ?? requested),\n match,\n url: avatarUrl(root, { collection, id }),\n };\n}\n\nasync function fail(response: Response): Promise<never> {\n let body: unknown;\n let message =\n response.status === 404\n ? \"veyce: no image matches (unknown id or collection) — pass a `seed` to always get one\"\n : response.status === 409\n ? \"veyce: that id exists in several collections — pass `collection`\"\n : `veyce: request failed with ${response.status}`;\n try {\n body = await response.json();\n const error = (body as { error?: unknown })?.error;\n if (typeof error === \"string\") message = `veyce: ${error}`;\n } catch {\n // not JSON — keep the generic message\n }\n throw new AvatarError(message, response.status, body);\n}\n\nfunction toBase64(bytes: Uint8Array): string {\n const B = (globalThis as { Buffer?: { from(b: Uint8Array): { toString(enc: string): string } } })\n .Buffer;\n if (B) return B.from(bytes).toString(\"base64\");\n let binary = \"\";\n for (let i = 0; i < bytes.length; i += 0x8000) {\n binary += String.fromCharCode(...bytes.subarray(i, i + 0x8000));\n }\n return btoa(binary);\n}\n\nexport type AvatarClient = {\n readonly baseUrl: string;\n /** Avatar URL for an `<img src>`. No network. */\n url(options?: AvatarOptions): string;\n /** `srcset` value with 1x/2x/3x variants. No network. */\n srcSet(options?: AvatarOptions, densities?: readonly number[]): string;\n /** Download the image bytes (plus which image it was). */\n fetch(options?: AvatarOptions): Promise<AvatarImage>;\n /** Download as a `data:` URI — handy for emails, canvases and offline storage. */\n dataUri(options?: AvatarOptions): Promise<string>;\n /** Ask which image a request lands on, without downloading it (HEAD). */\n resolve(options?: AvatarOptions): Promise<AvatarInfo>;\n /** The library index: every collection and id. */\n list(collection?: string): Promise<PhotoIndex>;\n /** Offline seed -> photo, using an index you already fetched with `list()`. */\n pick(seed: string | number, index: PhotoIndex | readonly Photo[]): Photo | undefined;\n};\n\nexport function createAvatars(config: ClientConfig = {}): AvatarClient {\n const root = apiRoot(config.baseUrl);\n const defaults = config.defaults ?? {};\n const doFetch = (input: string, init?: RequestInit) => {\n const f = config.fetch ?? globalThis.fetch;\n if (!f) throw new Error(\"veyce: no global fetch; pass `fetch` in the config.\");\n return f(input, init);\n };\n const merge = (options?: AvatarOptions): AvatarOptions => ({ ...defaults, ...options });\n\n const client: AvatarClient = {\n baseUrl: root,\n\n url: (options) => avatarUrl(root, merge(options)),\n\n srcSet: (options, densities) => avatarSrcSet(root, merge(options), densities),\n\n async fetch(options) {\n const merged = merge(options);\n const response = await doFetch(avatarUrl(root, merged));\n if (!response.ok) return fail(response);\n const bytes = new Uint8Array(await response.arrayBuffer());\n return {\n bytes,\n contentType: response.headers.get(\"content-type\") ?? `image/${merged.format ?? \"webp\"}`,\n info: readInfo(root, response.headers, merged.size ?? DEFAULT_SIZE),\n };\n },\n\n async dataUri(options) {\n const { bytes, contentType } = await client.fetch(options);\n return `data:${contentType};base64,${toBase64(bytes)}`;\n },\n\n async resolve(options) {\n const merged = merge(options);\n const response = await doFetch(avatarUrl(root, merged), { method: \"HEAD\" });\n if (!response.ok) return fail(response);\n return readInfo(root, response.headers, merged.size ?? DEFAULT_SIZE);\n },\n\n async list(collection = defaults.collection) {\n const qs = collection ? `?collection=${encodeURIComponent(collection)}` : \"\";\n const response = await doFetch(`${root}/photos${qs}`);\n if (!response.ok) return fail(response);\n return (await response.json()) as PhotoIndex;\n },\n\n pick(seed, index) {\n return pick(seed, Array.isArray(index) ? index : (index as PhotoIndex).photos);\n },\n };\n\n return client;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAaO,IAAM,mBAAmB;AAEzB,IAAM,WAA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a,SAAS,YAAY;AAC3C,YAAM,KAAK,aAAa,eAAe,mBAAmB,UAAU,CAAC,KAAK;AAC1E,YAAM,WAAW,MAAM,QAAQ,GAAG,IAAI,UAAU,EAAE,EAAE;AACpD,UAAI,CAAC,SAAS,GAAI,QAAO,KAAK,QAAQ;AACtC,aAAQ,MAAM,SAAS,KAAK;AAAA,IAC9B;AAAA,IAEA,KAAK,MAAM,OAAO;AAChB,aAAO,KAAK,MAAM,MAAM,QAAQ,KAAK,IAAI,QAAS,MAAqB,MAAM;AAAA,IAC/E;AAAA,EACF;AAEA,SAAO;AACT;","names":[]}
@@ -0,0 +1,134 @@
1
+ /**
2
+ * veyce — a tiny, dependency-free client for the avatars API.
3
+ *
4
+ * const avatars = createAvatars(); // uses https://veyce.vercel.app
5
+ *
6
+ * avatars.url({ seed: "ada@example.com", size: 96 }); // any string -> always an avatar
7
+ * avatars.url({ id: "raul", collection: "gta-vi" }); // exact id -> that image, or 404
8
+ * avatars.url({ id: user.avatarId, seed: user.email }); // exact if it exists, seed otherwise
9
+ *
10
+ * Works in browsers, Node 18+, Deno, Bun and edge runtimes.
11
+ */
12
+ /** The public veyce service. Used whenever no `baseUrl` is given. */
13
+ declare const DEFAULT_BASE_URL = "https://veyce.vercel.app";
14
+ declare const MIN_SIZE = 8;
15
+ declare const MAX_SIZE = 2160;
16
+ declare const DEFAULT_SIZE = 80;
17
+ declare const CROPS: readonly ["square", "portrait", "landscape", "phone", "tablet", "ultrawide"];
18
+ type Crop = (typeof CROPS)[number];
19
+ declare const FORMATS: readonly ["webp", "png", "jpeg"];
20
+ type Format = (typeof FORMATS)[number];
21
+ type AvatarOptions = {
22
+ /** Collection to draw from, e.g. `gta-vi`. Omit to use every collection. */
23
+ collection?: string;
24
+ /**
25
+ * Exact image id. Unknown ids are a 404 — unless a `seed` is also given, in
26
+ * which case the API falls back to the seed.
27
+ */
28
+ id?: string;
29
+ /**
30
+ * Anything: an email, username, uuid, number. The same seed always maps to
31
+ * the same image (for a fixed library). Never 404s.
32
+ */
33
+ seed?: string | number;
34
+ /** Pixels, 8–2160. Defaults to 80. Never upscaled past the source image. */
35
+ size?: number;
36
+ /** Which crop of the image to use. Defaults to `square`. */
37
+ crop?: Crop | (string & {});
38
+ /** `full` keeps the original aspect ratio (no mask). Defaults to `cover`. */
39
+ fit?: "cover" | "full";
40
+ /** Square corners instead of the default circle mask. */
41
+ square?: boolean;
42
+ /** Output format. Defaults to `webp`. */
43
+ format?: Format;
44
+ /** Hex corner fill used when a circle is encoded as JPEG, e.g. `#0b0b0f`. */
45
+ background?: string;
46
+ };
47
+ type ClientConfig = {
48
+ /** Where the avatars service is hosted. Defaults to `https://veyce.vercel.app`. A trailing `/api` is fine. */
49
+ baseUrl?: string;
50
+ /** Options applied to every call; per-call options win. */
51
+ defaults?: AvatarOptions;
52
+ /** Custom fetch (for tests, proxies or older runtimes). Defaults to `globalThis.fetch`. */
53
+ fetch?: typeof fetch;
54
+ };
55
+ /** How the API chose the image. */
56
+ type Match = "id" | "seed" | "random";
57
+ type AvatarInfo = {
58
+ collection: string;
59
+ id: string;
60
+ crop: string;
61
+ /** The real pixel size served (may be smaller than requested). */
62
+ size: number;
63
+ match: Match;
64
+ /** Stable URL that addresses this exact image by id — store this to "pin" a seeded avatar. */
65
+ url: string;
66
+ };
67
+ type Photo = {
68
+ id: string;
69
+ label: string;
70
+ collection: string;
71
+ crops: string[];
72
+ /** Path on the service, e.g. `/api/gta-vi/raul`. */
73
+ url: string;
74
+ };
75
+ type PhotoIndex = {
76
+ count: number;
77
+ collections: string[];
78
+ size: {
79
+ min: number;
80
+ max: number;
81
+ default: number;
82
+ };
83
+ photos: Photo[];
84
+ };
85
+ type AvatarImage = {
86
+ bytes: Uint8Array;
87
+ contentType: string;
88
+ info: AvatarInfo;
89
+ };
90
+ declare class AvatarError extends Error {
91
+ readonly status: number;
92
+ readonly body: unknown;
93
+ constructor(message: string, status: number, body?: unknown);
94
+ }
95
+ /**
96
+ * The seed hash the service uses. Exposed so you can map seeds to images
97
+ * offline (see `pick`) and get the exact same answer as the API.
98
+ */
99
+ declare function hashSeed(seed: string | number): number;
100
+ /**
101
+ * Offline seed -> photo, identical to the API's choice for the same library.
102
+ * Pass `photos` from `list()` (scoped to the same collection you pass the API).
103
+ */
104
+ declare function pick<T>(seed: string | number, photos: readonly T[]): T | undefined;
105
+ declare function clampSize(size: number): number;
106
+ /**
107
+ * Build an avatar URL. Pure string work — no network, safe to call in render.
108
+ *
109
+ * Ids and seeds always go in the query string, so a seed that happens to look
110
+ * like an id, a size or a crop is never misread.
111
+ */
112
+ declare function avatarUrl(baseUrl: string | undefined, options?: AvatarOptions): string;
113
+ /** `url 1x, url 2x, url 3x` for crisp avatars on high-density screens. */
114
+ declare function avatarSrcSet(baseUrl: string | undefined, options?: AvatarOptions, densities?: readonly number[]): string;
115
+ type AvatarClient = {
116
+ readonly baseUrl: string;
117
+ /** Avatar URL for an `<img src>`. No network. */
118
+ url(options?: AvatarOptions): string;
119
+ /** `srcset` value with 1x/2x/3x variants. No network. */
120
+ srcSet(options?: AvatarOptions, densities?: readonly number[]): string;
121
+ /** Download the image bytes (plus which image it was). */
122
+ fetch(options?: AvatarOptions): Promise<AvatarImage>;
123
+ /** Download as a `data:` URI — handy for emails, canvases and offline storage. */
124
+ dataUri(options?: AvatarOptions): Promise<string>;
125
+ /** Ask which image a request lands on, without downloading it (HEAD). */
126
+ resolve(options?: AvatarOptions): Promise<AvatarInfo>;
127
+ /** The library index: every collection and id. */
128
+ list(collection?: string): Promise<PhotoIndex>;
129
+ /** Offline seed -> photo, using an index you already fetched with `list()`. */
130
+ pick(seed: string | number, index: PhotoIndex | readonly Photo[]): Photo | undefined;
131
+ };
132
+ declare function createAvatars(config?: ClientConfig): AvatarClient;
133
+
134
+ export { type AvatarClient, AvatarError, type AvatarImage, type AvatarInfo, type AvatarOptions, CROPS, type ClientConfig, type Crop, DEFAULT_BASE_URL, DEFAULT_SIZE, FORMATS, type Format, MAX_SIZE, MIN_SIZE, type Match, type Photo, type PhotoIndex, avatarSrcSet, avatarUrl, clampSize, createAvatars, hashSeed, pick };
@@ -0,0 +1,134 @@
1
+ /**
2
+ * veyce — a tiny, dependency-free client for the avatars API.
3
+ *
4
+ * const avatars = createAvatars(); // uses https://veyce.vercel.app
5
+ *
6
+ * avatars.url({ seed: "ada@example.com", size: 96 }); // any string -> always an avatar
7
+ * avatars.url({ id: "raul", collection: "gta-vi" }); // exact id -> that image, or 404
8
+ * avatars.url({ id: user.avatarId, seed: user.email }); // exact if it exists, seed otherwise
9
+ *
10
+ * Works in browsers, Node 18+, Deno, Bun and edge runtimes.
11
+ */
12
+ /** The public veyce service. Used whenever no `baseUrl` is given. */
13
+ declare const DEFAULT_BASE_URL = "https://veyce.vercel.app";
14
+ declare const MIN_SIZE = 8;
15
+ declare const MAX_SIZE = 2160;
16
+ declare const DEFAULT_SIZE = 80;
17
+ declare const CROPS: readonly ["square", "portrait", "landscape", "phone", "tablet", "ultrawide"];
18
+ type Crop = (typeof CROPS)[number];
19
+ declare const FORMATS: readonly ["webp", "png", "jpeg"];
20
+ type Format = (typeof FORMATS)[number];
21
+ type AvatarOptions = {
22
+ /** Collection to draw from, e.g. `gta-vi`. Omit to use every collection. */
23
+ collection?: string;
24
+ /**
25
+ * Exact image id. Unknown ids are a 404 — unless a `seed` is also given, in
26
+ * which case the API falls back to the seed.
27
+ */
28
+ id?: string;
29
+ /**
30
+ * Anything: an email, username, uuid, number. The same seed always maps to
31
+ * the same image (for a fixed library). Never 404s.
32
+ */
33
+ seed?: string | number;
34
+ /** Pixels, 8–2160. Defaults to 80. Never upscaled past the source image. */
35
+ size?: number;
36
+ /** Which crop of the image to use. Defaults to `square`. */
37
+ crop?: Crop | (string & {});
38
+ /** `full` keeps the original aspect ratio (no mask). Defaults to `cover`. */
39
+ fit?: "cover" | "full";
40
+ /** Square corners instead of the default circle mask. */
41
+ square?: boolean;
42
+ /** Output format. Defaults to `webp`. */
43
+ format?: Format;
44
+ /** Hex corner fill used when a circle is encoded as JPEG, e.g. `#0b0b0f`. */
45
+ background?: string;
46
+ };
47
+ type ClientConfig = {
48
+ /** Where the avatars service is hosted. Defaults to `https://veyce.vercel.app`. A trailing `/api` is fine. */
49
+ baseUrl?: string;
50
+ /** Options applied to every call; per-call options win. */
51
+ defaults?: AvatarOptions;
52
+ /** Custom fetch (for tests, proxies or older runtimes). Defaults to `globalThis.fetch`. */
53
+ fetch?: typeof fetch;
54
+ };
55
+ /** How the API chose the image. */
56
+ type Match = "id" | "seed" | "random";
57
+ type AvatarInfo = {
58
+ collection: string;
59
+ id: string;
60
+ crop: string;
61
+ /** The real pixel size served (may be smaller than requested). */
62
+ size: number;
63
+ match: Match;
64
+ /** Stable URL that addresses this exact image by id — store this to "pin" a seeded avatar. */
65
+ url: string;
66
+ };
67
+ type Photo = {
68
+ id: string;
69
+ label: string;
70
+ collection: string;
71
+ crops: string[];
72
+ /** Path on the service, e.g. `/api/gta-vi/raul`. */
73
+ url: string;
74
+ };
75
+ type PhotoIndex = {
76
+ count: number;
77
+ collections: string[];
78
+ size: {
79
+ min: number;
80
+ max: number;
81
+ default: number;
82
+ };
83
+ photos: Photo[];
84
+ };
85
+ type AvatarImage = {
86
+ bytes: Uint8Array;
87
+ contentType: string;
88
+ info: AvatarInfo;
89
+ };
90
+ declare class AvatarError extends Error {
91
+ readonly status: number;
92
+ readonly body: unknown;
93
+ constructor(message: string, status: number, body?: unknown);
94
+ }
95
+ /**
96
+ * The seed hash the service uses. Exposed so you can map seeds to images
97
+ * offline (see `pick`) and get the exact same answer as the API.
98
+ */
99
+ declare function hashSeed(seed: string | number): number;
100
+ /**
101
+ * Offline seed -> photo, identical to the API's choice for the same library.
102
+ * Pass `photos` from `list()` (scoped to the same collection you pass the API).
103
+ */
104
+ declare function pick<T>(seed: string | number, photos: readonly T[]): T | undefined;
105
+ declare function clampSize(size: number): number;
106
+ /**
107
+ * Build an avatar URL. Pure string work — no network, safe to call in render.
108
+ *
109
+ * Ids and seeds always go in the query string, so a seed that happens to look
110
+ * like an id, a size or a crop is never misread.
111
+ */
112
+ declare function avatarUrl(baseUrl: string | undefined, options?: AvatarOptions): string;
113
+ /** `url 1x, url 2x, url 3x` for crisp avatars on high-density screens. */
114
+ declare function avatarSrcSet(baseUrl: string | undefined, options?: AvatarOptions, densities?: readonly number[]): string;
115
+ type AvatarClient = {
116
+ readonly baseUrl: string;
117
+ /** Avatar URL for an `<img src>`. No network. */
118
+ url(options?: AvatarOptions): string;
119
+ /** `srcset` value with 1x/2x/3x variants. No network. */
120
+ srcSet(options?: AvatarOptions, densities?: readonly number[]): string;
121
+ /** Download the image bytes (plus which image it was). */
122
+ fetch(options?: AvatarOptions): Promise<AvatarImage>;
123
+ /** Download as a `data:` URI — handy for emails, canvases and offline storage. */
124
+ dataUri(options?: AvatarOptions): Promise<string>;
125
+ /** Ask which image a request lands on, without downloading it (HEAD). */
126
+ resolve(options?: AvatarOptions): Promise<AvatarInfo>;
127
+ /** The library index: every collection and id. */
128
+ list(collection?: string): Promise<PhotoIndex>;
129
+ /** Offline seed -> photo, using an index you already fetched with `list()`. */
130
+ pick(seed: string | number, index: PhotoIndex | readonly Photo[]): Photo | undefined;
131
+ };
132
+ declare function createAvatars(config?: ClientConfig): AvatarClient;
133
+
134
+ export { type AvatarClient, AvatarError, type AvatarImage, type AvatarInfo, type AvatarOptions, CROPS, type ClientConfig, type Crop, DEFAULT_BASE_URL, DEFAULT_SIZE, FORMATS, type Format, MAX_SIZE, MIN_SIZE, type Match, type Photo, type PhotoIndex, avatarSrcSet, avatarUrl, clampSize, createAvatars, hashSeed, pick };
package/dist/index.js ADDED
@@ -0,0 +1,159 @@
1
+ // src/index.ts
2
+ var DEFAULT_BASE_URL = "https://veyce.vercel.app";
3
+ var MIN_SIZE = 8;
4
+ var MAX_SIZE = 2160;
5
+ var DEFAULT_SIZE = 80;
6
+ var CROPS = ["square", "portrait", "landscape", "phone", "tablet", "ultrawide"];
7
+ var FORMATS = ["webp", "png", "jpeg"];
8
+ var AvatarError = class extends Error {
9
+ constructor(message, status, body) {
10
+ super(message);
11
+ this.name = "AvatarError";
12
+ this.status = status;
13
+ this.body = body;
14
+ }
15
+ };
16
+ function hashSeed(seed) {
17
+ const value = String(seed);
18
+ let hash = 0;
19
+ for (let i = 0; i < value.length; i += 1) {
20
+ hash = (hash << 5) - hash + value.charCodeAt(i);
21
+ hash |= 0;
22
+ }
23
+ return Math.abs(hash) || 1;
24
+ }
25
+ function pick(seed, photos) {
26
+ if (!photos.length) return void 0;
27
+ return photos[hashSeed(seed) % photos.length];
28
+ }
29
+ function clampSize(size) {
30
+ if (!Number.isFinite(size)) return DEFAULT_SIZE;
31
+ return Math.min(MAX_SIZE, Math.max(MIN_SIZE, Math.round(size)));
32
+ }
33
+ function apiRoot(baseUrl) {
34
+ const trimmed = (baseUrl || DEFAULT_BASE_URL).replace(/\/+$/, "");
35
+ return /\/api$/.test(trimmed) ? trimmed : `${trimmed}/api`;
36
+ }
37
+ function normalizeHex(value) {
38
+ const hex = value.replace(/^#/, "");
39
+ return /^([0-9a-f]{3}|[0-9a-f]{6})$/i.test(hex) ? hex.toLowerCase() : null;
40
+ }
41
+ function avatarUrl(baseUrl, options = {}) {
42
+ const root = apiRoot(baseUrl);
43
+ const path = options.collection ? `${root}/${encodeURIComponent(options.collection)}` : root;
44
+ const query = new URLSearchParams();
45
+ if (options.id !== void 0 && options.id !== "") query.set("id", options.id);
46
+ if (options.seed !== void 0 && options.seed !== "") query.set("seed", String(options.seed));
47
+ if (options.size !== void 0) query.set("size", String(clampSize(options.size)));
48
+ if (options.crop) query.set("crop", options.crop);
49
+ if (options.fit && options.fit !== "cover") query.set("fit", options.fit);
50
+ if (options.square) query.set("square", "true");
51
+ if (options.format && options.format !== "webp") query.set("format", options.format);
52
+ if (options.background) {
53
+ const hex = normalizeHex(options.background);
54
+ if (!hex) throw new TypeError(`veyce: invalid background "${options.background}".`);
55
+ query.set("bg", hex);
56
+ }
57
+ const qs = query.toString();
58
+ return qs ? `${path}?${qs}` : path;
59
+ }
60
+ function avatarSrcSet(baseUrl, options = {}, densities = [1, 2, 3]) {
61
+ const size = options.size ?? DEFAULT_SIZE;
62
+ const seen = /* @__PURE__ */ new Set();
63
+ return densities.map((density) => ({ density, px: clampSize(size * density) })).filter(({ px }) => seen.has(px) ? false : (seen.add(px), true)).map(({ density, px }) => `${avatarUrl(baseUrl, { ...options, size: px })} ${density}x`).join(", ");
64
+ }
65
+ function readInfo(root, headers, requested) {
66
+ const collection = headers.get("x-photo-collection") ?? "";
67
+ const id = headers.get("x-photo-id") ?? "";
68
+ const match = headers.get("x-photo-match") ?? "id";
69
+ return {
70
+ collection,
71
+ id,
72
+ crop: headers.get("x-photo-crop") ?? "square",
73
+ size: Number(headers.get("x-photo-size") ?? requested),
74
+ match,
75
+ url: avatarUrl(root, { collection, id })
76
+ };
77
+ }
78
+ async function fail(response) {
79
+ let body;
80
+ let message = response.status === 404 ? "veyce: no image matches (unknown id or collection) \u2014 pass a `seed` to always get one" : response.status === 409 ? "veyce: that id exists in several collections \u2014 pass `collection`" : `veyce: request failed with ${response.status}`;
81
+ try {
82
+ body = await response.json();
83
+ const error = body?.error;
84
+ if (typeof error === "string") message = `veyce: ${error}`;
85
+ } catch {
86
+ }
87
+ throw new AvatarError(message, response.status, body);
88
+ }
89
+ function toBase64(bytes) {
90
+ const B = globalThis.Buffer;
91
+ if (B) return B.from(bytes).toString("base64");
92
+ let binary = "";
93
+ for (let i = 0; i < bytes.length; i += 32768) {
94
+ binary += String.fromCharCode(...bytes.subarray(i, i + 32768));
95
+ }
96
+ return btoa(binary);
97
+ }
98
+ function createAvatars(config = {}) {
99
+ const root = apiRoot(config.baseUrl);
100
+ const defaults = config.defaults ?? {};
101
+ const doFetch = (input, init) => {
102
+ const f = config.fetch ?? globalThis.fetch;
103
+ if (!f) throw new Error("veyce: no global fetch; pass `fetch` in the config.");
104
+ return f(input, init);
105
+ };
106
+ const merge = (options) => ({ ...defaults, ...options });
107
+ const client = {
108
+ baseUrl: root,
109
+ url: (options) => avatarUrl(root, merge(options)),
110
+ srcSet: (options, densities) => avatarSrcSet(root, merge(options), densities),
111
+ async fetch(options) {
112
+ const merged = merge(options);
113
+ const response = await doFetch(avatarUrl(root, merged));
114
+ if (!response.ok) return fail(response);
115
+ const bytes = new Uint8Array(await response.arrayBuffer());
116
+ return {
117
+ bytes,
118
+ contentType: response.headers.get("content-type") ?? `image/${merged.format ?? "webp"}`,
119
+ info: readInfo(root, response.headers, merged.size ?? DEFAULT_SIZE)
120
+ };
121
+ },
122
+ async dataUri(options) {
123
+ const { bytes, contentType } = await client.fetch(options);
124
+ return `data:${contentType};base64,${toBase64(bytes)}`;
125
+ },
126
+ async resolve(options) {
127
+ const merged = merge(options);
128
+ const response = await doFetch(avatarUrl(root, merged), { method: "HEAD" });
129
+ if (!response.ok) return fail(response);
130
+ return readInfo(root, response.headers, merged.size ?? DEFAULT_SIZE);
131
+ },
132
+ async list(collection = defaults.collection) {
133
+ const qs = collection ? `?collection=${encodeURIComponent(collection)}` : "";
134
+ const response = await doFetch(`${root}/photos${qs}`);
135
+ if (!response.ok) return fail(response);
136
+ return await response.json();
137
+ },
138
+ pick(seed, index) {
139
+ return pick(seed, Array.isArray(index) ? index : index.photos);
140
+ }
141
+ };
142
+ return client;
143
+ }
144
+ export {
145
+ AvatarError,
146
+ CROPS,
147
+ DEFAULT_BASE_URL,
148
+ DEFAULT_SIZE,
149
+ FORMATS,
150
+ MAX_SIZE,
151
+ MIN_SIZE,
152
+ avatarSrcSet,
153
+ avatarUrl,
154
+ clampSize,
155
+ createAvatars,
156
+ hashSeed,
157
+ pick
158
+ };
159
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/index.ts"],"sourcesContent":["/**\n * veyce — a tiny, dependency-free client for the avatars API.\n *\n * const avatars = createAvatars(); // uses https://veyce.vercel.app\n *\n * avatars.url({ seed: \"ada@example.com\", size: 96 }); // any string -> always an avatar\n * avatars.url({ id: \"raul\", collection: \"gta-vi\" }); // exact id -> that image, or 404\n * avatars.url({ id: user.avatarId, seed: user.email }); // exact if it exists, seed otherwise\n *\n * Works in browsers, Node 18+, Deno, Bun and edge runtimes.\n */\n\n/** The public veyce service. Used whenever no `baseUrl` is given. */\nexport const DEFAULT_BASE_URL = \"https://veyce.vercel.app\";\n\nexport const MIN_SIZE = 8;\nexport const MAX_SIZE = 2160;\nexport const DEFAULT_SIZE = 80;\n\nexport const CROPS = [\"square\", \"portrait\", \"landscape\", \"phone\", \"tablet\", \"ultrawide\"] as const;\nexport type Crop = (typeof CROPS)[number];\n\nexport const FORMATS = [\"webp\", \"png\", \"jpeg\"] as const;\nexport type Format = (typeof FORMATS)[number];\n\nexport type AvatarOptions = {\n /** Collection to draw from, e.g. `gta-vi`. Omit to use every collection. */\n collection?: string;\n /**\n * Exact image id. Unknown ids are a 404 — unless a `seed` is also given, in\n * which case the API falls back to the seed.\n */\n id?: string;\n /**\n * Anything: an email, username, uuid, number. The same seed always maps to\n * the same image (for a fixed library). Never 404s.\n */\n seed?: string | number;\n /** Pixels, 8–2160. Defaults to 80. Never upscaled past the source image. */\n size?: number;\n /** Which crop of the image to use. Defaults to `square`. */\n crop?: Crop | (string & {});\n /** `full` keeps the original aspect ratio (no mask). Defaults to `cover`. */\n fit?: \"cover\" | \"full\";\n /** Square corners instead of the default circle mask. */\n square?: boolean;\n /** Output format. Defaults to `webp`. */\n format?: Format;\n /** Hex corner fill used when a circle is encoded as JPEG, e.g. `#0b0b0f`. */\n background?: string;\n};\n\nexport type ClientConfig = {\n /** Where the avatars service is hosted. Defaults to `https://veyce.vercel.app`. A trailing `/api` is fine. */\n baseUrl?: string;\n /** Options applied to every call; per-call options win. */\n defaults?: AvatarOptions;\n /** Custom fetch (for tests, proxies or older runtimes). Defaults to `globalThis.fetch`. */\n fetch?: typeof fetch;\n};\n\n/** How the API chose the image. */\nexport type Match = \"id\" | \"seed\" | \"random\";\n\nexport type AvatarInfo = {\n collection: string;\n id: string;\n crop: string;\n /** The real pixel size served (may be smaller than requested). */\n size: number;\n match: Match;\n /** Stable URL that addresses this exact image by id — store this to \"pin\" a seeded avatar. */\n url: string;\n};\n\nexport type Photo = {\n id: string;\n label: string;\n collection: string;\n crops: string[];\n /** Path on the service, e.g. `/api/gta-vi/raul`. */\n url: string;\n};\n\nexport type PhotoIndex = {\n count: number;\n collections: string[];\n size: { min: number; max: number; default: number };\n photos: Photo[];\n};\n\nexport type AvatarImage = {\n bytes: Uint8Array;\n contentType: string;\n info: AvatarInfo;\n};\n\nexport class AvatarError extends Error {\n readonly status: number;\n readonly body: unknown;\n\n constructor(message: string, status: number, body?: unknown) {\n super(message);\n this.name = \"AvatarError\";\n this.status = status;\n this.body = body;\n }\n}\n\n/**\n * The seed hash the service uses. Exposed so you can map seeds to images\n * offline (see `pick`) and get the exact same answer as the API.\n */\nexport function hashSeed(seed: string | number): number {\n const value = String(seed);\n let hash = 0;\n for (let i = 0; i < value.length; i += 1) {\n hash = (hash << 5) - hash + value.charCodeAt(i);\n hash |= 0;\n }\n return Math.abs(hash) || 1;\n}\n\n/**\n * Offline seed -> photo, identical to the API's choice for the same library.\n * Pass `photos` from `list()` (scoped to the same collection you pass the API).\n */\nexport function pick<T>(seed: string | number, photos: readonly T[]): T | undefined {\n if (!photos.length) return undefined;\n return photos[hashSeed(seed) % photos.length];\n}\n\nexport function clampSize(size: number): number {\n if (!Number.isFinite(size)) return DEFAULT_SIZE;\n return Math.min(MAX_SIZE, Math.max(MIN_SIZE, Math.round(size)));\n}\n\n/** `https://x.com/`, `https://x.com/api` -> `https://x.com/api` */\nfunction apiRoot(baseUrl?: string): string {\n const trimmed = (baseUrl || DEFAULT_BASE_URL).replace(/\\/+$/, \"\");\n return /\\/api$/.test(trimmed) ? trimmed : `${trimmed}/api`;\n}\n\nfunction normalizeHex(value: string): string | null {\n const hex = value.replace(/^#/, \"\");\n return /^([0-9a-f]{3}|[0-9a-f]{6})$/i.test(hex) ? hex.toLowerCase() : null;\n}\n\n/**\n * Build an avatar URL. Pure string work — no network, safe to call in render.\n *\n * Ids and seeds always go in the query string, so a seed that happens to look\n * like an id, a size or a crop is never misread.\n */\nexport function avatarUrl(baseUrl: string | undefined, options: AvatarOptions = {}): string {\n const root = apiRoot(baseUrl);\n const path = options.collection ? `${root}/${encodeURIComponent(options.collection)}` : root;\n\n const query = new URLSearchParams();\n if (options.id !== undefined && options.id !== \"\") query.set(\"id\", options.id);\n if (options.seed !== undefined && options.seed !== \"\") query.set(\"seed\", String(options.seed));\n if (options.size !== undefined) query.set(\"size\", String(clampSize(options.size)));\n if (options.crop) query.set(\"crop\", options.crop);\n if (options.fit && options.fit !== \"cover\") query.set(\"fit\", options.fit);\n if (options.square) query.set(\"square\", \"true\");\n if (options.format && options.format !== \"webp\") query.set(\"format\", options.format);\n if (options.background) {\n const hex = normalizeHex(options.background);\n if (!hex) throw new TypeError(`veyce: invalid background \"${options.background}\".`);\n query.set(\"bg\", hex);\n }\n\n const qs = query.toString();\n return qs ? `${path}?${qs}` : path;\n}\n\n/** `url 1x, url 2x, url 3x` for crisp avatars on high-density screens. */\nexport function avatarSrcSet(\n baseUrl: string | undefined,\n options: AvatarOptions = {},\n densities: readonly number[] = [1, 2, 3],\n): string {\n const size = options.size ?? DEFAULT_SIZE;\n const seen = new Set<number>();\n return densities\n .map((density) => ({ density, px: clampSize(size * density) }))\n .filter(({ px }) => (seen.has(px) ? false : (seen.add(px), true)))\n .map(({ density, px }) => `${avatarUrl(baseUrl, { ...options, size: px })} ${density}x`)\n .join(\", \");\n}\n\nfunction readInfo(root: string, headers: Headers, requested: number): AvatarInfo {\n const collection = headers.get(\"x-photo-collection\") ?? \"\";\n const id = headers.get(\"x-photo-id\") ?? \"\";\n const match = (headers.get(\"x-photo-match\") as Match | null) ?? \"id\";\n return {\n collection,\n id,\n crop: headers.get(\"x-photo-crop\") ?? \"square\",\n size: Number(headers.get(\"x-photo-size\") ?? requested),\n match,\n url: avatarUrl(root, { collection, id }),\n };\n}\n\nasync function fail(response: Response): Promise<never> {\n let body: unknown;\n let message =\n response.status === 404\n ? \"veyce: no image matches (unknown id or collection) — pass a `seed` to always get one\"\n : response.status === 409\n ? \"veyce: that id exists in several collections — pass `collection`\"\n : `veyce: request failed with ${response.status}`;\n try {\n body = await response.json();\n const error = (body as { error?: unknown })?.error;\n if (typeof error === \"string\") message = `veyce: ${error}`;\n } catch {\n // not JSON — keep the generic message\n }\n throw new AvatarError(message, response.status, body);\n}\n\nfunction toBase64(bytes: Uint8Array): string {\n const B = (globalThis as { Buffer?: { from(b: Uint8Array): { toString(enc: string): string } } })\n .Buffer;\n if (B) return B.from(bytes).toString(\"base64\");\n let binary = \"\";\n for (let i = 0; i < bytes.length; i += 0x8000) {\n binary += String.fromCharCode(...bytes.subarray(i, i + 0x8000));\n }\n return btoa(binary);\n}\n\nexport type AvatarClient = {\n readonly baseUrl: string;\n /** Avatar URL for an `<img src>`. No network. */\n url(options?: AvatarOptions): string;\n /** `srcset` value with 1x/2x/3x variants. No network. */\n srcSet(options?: AvatarOptions, densities?: readonly number[]): string;\n /** Download the image bytes (plus which image it was). */\n fetch(options?: AvatarOptions): Promise<AvatarImage>;\n /** Download as a `data:` URI — handy for emails, canvases and offline storage. */\n dataUri(options?: AvatarOptions): Promise<string>;\n /** Ask which image a request lands on, without downloading it (HEAD). */\n resolve(options?: AvatarOptions): Promise<AvatarInfo>;\n /** The library index: every collection and id. */\n list(collection?: string): Promise<PhotoIndex>;\n /** Offline seed -> photo, using an index you already fetched with `list()`. */\n pick(seed: string | number, index: PhotoIndex | readonly Photo[]): Photo | undefined;\n};\n\nexport function createAvatars(config: ClientConfig = {}): AvatarClient {\n const root = apiRoot(config.baseUrl);\n const defaults = config.defaults ?? {};\n const doFetch = (input: string, init?: RequestInit) => {\n const f = config.fetch ?? globalThis.fetch;\n if (!f) throw new Error(\"veyce: no global fetch; pass `fetch` in the config.\");\n return f(input, init);\n };\n const merge = (options?: AvatarOptions): AvatarOptions => ({ ...defaults, ...options });\n\n const client: AvatarClient = {\n baseUrl: root,\n\n url: (options) => avatarUrl(root, merge(options)),\n\n srcSet: (options, densities) => avatarSrcSet(root, merge(options), densities),\n\n async fetch(options) {\n const merged = merge(options);\n const response = await doFetch(avatarUrl(root, merged));\n if (!response.ok) return fail(response);\n const bytes = new Uint8Array(await response.arrayBuffer());\n return {\n bytes,\n contentType: response.headers.get(\"content-type\") ?? `image/${merged.format ?? \"webp\"}`,\n info: readInfo(root, response.headers, merged.size ?? DEFAULT_SIZE),\n };\n },\n\n async dataUri(options) {\n const { bytes, contentType } = await client.fetch(options);\n return `data:${contentType};base64,${toBase64(bytes)}`;\n },\n\n async resolve(options) {\n const merged = merge(options);\n const response = await doFetch(avatarUrl(root, merged), { method: \"HEAD\" });\n if (!response.ok) return fail(response);\n return readInfo(root, response.headers, merged.size ?? DEFAULT_SIZE);\n },\n\n async list(collection = defaults.collection) {\n const qs = collection ? `?collection=${encodeURIComponent(collection)}` : \"\";\n const response = await doFetch(`${root}/photos${qs}`);\n if (!response.ok) return fail(response);\n return (await response.json()) as PhotoIndex;\n },\n\n pick(seed, index) {\n return pick(seed, Array.isArray(index) ? index : (index as PhotoIndex).photos);\n },\n };\n\n return client;\n}\n"],"mappings":";AAaO,IAAM,mBAAmB;AAEzB,IAAM,WAAW;AACjB,IAAM,WAAW;AACjB,IAAM,eAAe;AAErB,IAAM,QAAQ,CAAC,UAAU,YAAY,aAAa,SAAS,UAAU,WAAW;AAGhF,IAAM,UAAU,CAAC,QAAQ,OAAO,MAAM;AA2EtC,IAAM,cAAN,cAA0B,MAAM;AAAA,EAIrC,YAAY,SAAiB,QAAgB,MAAgB;AAC3D,UAAM,OAAO;AACb,SAAK,OAAO;AACZ,SAAK,SAAS;AACd,SAAK,OAAO;AAAA,EACd;AACF;AAMO,SAAS,SAAS,MAA+B;AACtD,QAAM,QAAQ,OAAO,IAAI;AACzB,MAAI,OAAO;AACX,WAAS,IAAI,GAAG,IAAI,MAAM,QAAQ,KAAK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+ "use strict";
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
7
+ var __export = (target, all) => {
8
+ for (var name in all)
9
+ __defProp(target, name, { get: all[name], enumerable: true });
10
+ };
11
+ var __copyProps = (to, from, except, desc) => {
12
+ if (from && typeof from === "object" || typeof from === "function") {
13
+ for (let key of __getOwnPropNames(from))
14
+ if (!__hasOwnProp.call(to, key) && key !== except)
15
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
16
+ }
17
+ return to;
18
+ };
19
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
20
+
21
+ // src/react.tsx
22
+ var react_exports = {};
23
+ __export(react_exports, {
24
+ Avatar: () => Avatar,
25
+ AvatarProvider: () => AvatarProvider,
26
+ useAvatarUrl: () => useAvatarUrl
27
+ });
28
+ module.exports = __toCommonJS(react_exports);
29
+ var import_react = require("react");
30
+
31
+ // src/index.ts
32
+ var DEFAULT_BASE_URL = "https://veyce.vercel.app";
33
+ var MIN_SIZE = 8;
34
+ var MAX_SIZE = 2160;
35
+ var DEFAULT_SIZE = 80;
36
+ function clampSize(size) {
37
+ if (!Number.isFinite(size)) return DEFAULT_SIZE;
38
+ return Math.min(MAX_SIZE, Math.max(MIN_SIZE, Math.round(size)));
39
+ }
40
+ function apiRoot(baseUrl) {
41
+ const trimmed = (baseUrl || DEFAULT_BASE_URL).replace(/\/+$/, "");
42
+ return /\/api$/.test(trimmed) ? trimmed : `${trimmed}/api`;
43
+ }
44
+ function normalizeHex(value) {
45
+ const hex = value.replace(/^#/, "");
46
+ return /^([0-9a-f]{3}|[0-9a-f]{6})$/i.test(hex) ? hex.toLowerCase() : null;
47
+ }
48
+ function avatarUrl(baseUrl, options = {}) {
49
+ const root = apiRoot(baseUrl);
50
+ const path = options.collection ? `${root}/${encodeURIComponent(options.collection)}` : root;
51
+ const query = new URLSearchParams();
52
+ if (options.id !== void 0 && options.id !== "") query.set("id", options.id);
53
+ if (options.seed !== void 0 && options.seed !== "") query.set("seed", String(options.seed));
54
+ if (options.size !== void 0) query.set("size", String(clampSize(options.size)));
55
+ if (options.crop) query.set("crop", options.crop);
56
+ if (options.fit && options.fit !== "cover") query.set("fit", options.fit);
57
+ if (options.square) query.set("square", "true");
58
+ if (options.format && options.format !== "webp") query.set("format", options.format);
59
+ if (options.background) {
60
+ const hex = normalizeHex(options.background);
61
+ if (!hex) throw new TypeError(`veyce: invalid background "${options.background}".`);
62
+ query.set("bg", hex);
63
+ }
64
+ const qs = query.toString();
65
+ return qs ? `${path}?${qs}` : path;
66
+ }
67
+ function avatarSrcSet(baseUrl, options = {}, densities = [1, 2, 3]) {
68
+ const size = options.size ?? DEFAULT_SIZE;
69
+ const seen = /* @__PURE__ */ new Set();
70
+ return densities.map((density) => ({ density, px: clampSize(size * density) })).filter(({ px }) => seen.has(px) ? false : (seen.add(px), true)).map(({ density, px }) => `${avatarUrl(baseUrl, { ...options, size: px })} ${density}x`).join(", ");
71
+ }
72
+
73
+ // src/react.tsx
74
+ var import_jsx_runtime = require("react/jsx-runtime");
75
+ var AvatarContext = (0, import_react.createContext)(null);
76
+ function AvatarProvider({
77
+ baseUrl,
78
+ defaults,
79
+ children
80
+ }) {
81
+ const value = (0, import_react.useMemo)(() => ({ baseUrl, defaults }), [baseUrl, defaults]);
82
+ return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(AvatarContext.Provider, { value, children });
83
+ }
84
+ function Avatar({
85
+ baseUrl,
86
+ collection,
87
+ id,
88
+ seed,
89
+ size,
90
+ crop,
91
+ fit,
92
+ square,
93
+ format,
94
+ background,
95
+ hiDpi = true,
96
+ htmlId,
97
+ alt = "",
98
+ loading = "lazy",
99
+ decoding = "async",
100
+ ...img
101
+ }) {
102
+ const context = (0, import_react.useContext)(AvatarContext);
103
+ const base = baseUrl ?? context?.baseUrl;
104
+ const own = { collection, id, seed, size, crop, fit, square, format, background };
105
+ for (const key of Object.keys(own)) {
106
+ if (own[key] === void 0) delete own[key];
107
+ }
108
+ const options = { ...context?.defaults, ...own };
109
+ const px = clampSize(options.size ?? DEFAULT_SIZE);
110
+ return (
111
+ // A plain <img> on purpose: the service already resizes and encodes.
112
+ // eslint-disable-next-line @next/next/no-img-element
113
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
114
+ "img",
115
+ {
116
+ ...img,
117
+ id: htmlId,
118
+ src: avatarUrl(base, { ...options, size: px }),
119
+ srcSet: hiDpi ? avatarSrcSet(base, { ...options, size: px }) : void 0,
120
+ width: img.width ?? px,
121
+ height: img.height ?? px,
122
+ alt,
123
+ loading,
124
+ decoding
125
+ }
126
+ )
127
+ );
128
+ }
129
+ function useAvatarUrl(options = {}) {
130
+ const context = (0, import_react.useContext)(AvatarContext);
131
+ const { baseUrl, ...rest } = options;
132
+ const base = baseUrl ?? context?.baseUrl;
133
+ return avatarUrl(base, { ...context?.defaults, ...rest });
134
+ }
135
+ // Annotate the CommonJS export names for ESM import in node:
136
+ 0 && (module.exports = {
137
+ Avatar,
138
+ AvatarProvider,
139
+ useAvatarUrl
140
+ });
141
+ //# sourceMappingURL=react.cjs.map