diff --git a/README.md b/README.md index fdb010a..2f97658 100644 --- a/README.md +++ b/README.md @@ -94,6 +94,11 @@ pixelvault keys list KEY=$(pixelvault keys create --label ci) # raw key on stdout, shown once pixelvault keys revoke key_abc123 +# Attach a custom domain to the active project +pixelvault domains add media.example.com +pixelvault domains refresh dom_abc123 +pixelvault upload photo.jpg --branded + # Export everything — manifest plus all project media and derived artifacts (no lock-in) pixelvault export -o pixelvault-export.tar ``` @@ -103,6 +108,7 @@ pixelvault export -o pixelvault-export.tar The CLI is designed for AI coding agents. Output contract: - `upload` prints **only the URL** to stdout for images, PDFs, and MP4 videos. PDFs are served as forced downloads and do not support image transforms. Add `--optimized` for the smaller WebP/AVIF image variant; it falls back to the original URL for SVG, GIF, PDF, and private images +- Media JSON keeps the canonical `url` and includes optional `branded_url` when the active project has a ready custom domain. Add `--branded` to `upload`, `list`, `get`, or `audio upload|list|get|update|sign` to print it, with canonical fallback - `upload` streams local MP4 files and automatically switches to multipart upload above 100 MB. It also accepts public MP4 URLs and has PixelVault import them directly. `--private [--expires 12h]` returns signed video and poster URLs. `--social` requests a separate H.264/AAC fast-start copy, waits for it, and prints the post-ready URL while preserving the original; `--json` returns both `original_url` and `social_ready_url`. Every video response includes duration, dimensions, codecs, fast-start status, and social-compatibility warnings. Video limits: Free 25 MB, Starter 100 MB, Pro 250 MB - `optimize-video` converts an existing upload, waits for the derived social-ready URL, and prints only that URL; `--no-wait` enqueues and returns, while `--json` returns the full state - `enrich-video` uploads a local MP4 or reuses an existing `vid_` asset, starts or resumes transcript + storyboard enrichment, and reports the stable asset/job IDs before bounded polling @@ -154,6 +160,7 @@ npx pixelvault-cli upload build-output.png | `export` | Export all project media and derived artifacts with a manifest | | `usage` | Show plan, period, storage/upload/bandwidth usage and limits, and AI generation credits | | `keys list\|create\|revoke` | List, create, and revoke the project's secret API keys | +| `domains list\|add\|refresh\|delete` | Manage the active project's custom domain and inspect account plan capacity | | `upgrade ` | Print a Stripe Checkout URL to subscribe (live key; you pay in the browser) | | `billing` | Print a Stripe billing-portal URL to change plan, update payment details or cancel (live key) | | `whoami` | Show current auth state | @@ -165,6 +172,7 @@ npx pixelvault-cli upload build-output.png pixelvault upload photo.jpg # Single file pixelvault upload *.png --folder icons # Bulk with folder pixelvault upload shot.png --json # Full JSON response +pixelvault upload shot.png --branded # Ready custom-domain URL; canonical fallback pixelvault upload demo.mp4 --social # Upload + wait; prints the post-ready URL pixelvault upload demo.mp4 --social --json # Includes original_url and social_ready_url pixelvault upload "https://media.example.com/demo.mp4" --private --expires 12h --social --json @@ -244,6 +252,7 @@ pixelvault audio enrich private.ogg --private --link-expires 12h --delete-after pixelvault audio enrich aud_xyz --no-wait --json pixelvault audio enrich aud_xyz --timeout 1200 --json pixelvault audio list --folder podcasts --json +pixelvault audio get aud_xyz --branded pixelvault audio get aud_xyz --json pixelvault audio update aud_xyz --folder archive --meta episode=7 --json pixelvault audio sign aud_xyz --expires 1h --json @@ -349,6 +358,7 @@ progress to **stderr**. ```bash pixelvault list # One URL per line +pixelvault list --branded # Ready custom-domain URLs; canonical fallback pixelvault list --json # Full JSON with metadata pixelvault list --page 2 --per-page 50 # Pagination pixelvault list --meta env=prod # Only images tagged env=prod (repeatable; all must match) @@ -417,6 +427,24 @@ pixelvault keys revoke key_abc123 `PIXELVAULT_API_KEY` to `$NEW`, then `pixelvault keys revoke ` using the new key. If you get locked out, use the dashboard's Regenerate. +### Custom Domains + +Custom domains attach to the active project; plan capacity is account-wide +(Starter 1, Pro 3). A verified email and live secret key are required. + +```bash +pixelvault domains list +pixelvault domains add media.example.com +# Add the returned CNAME and optional TXT record, then: +pixelvault domains refresh dom_abc123 +pixelvault domains delete dom_abc123 +``` + +The hostname is ready only when both hostname and certificate status are active. +Once ready, API JSON includes `branded_url` while preserving canonical `url`. +`--branded` selects that API-provided URL and never reconstructs a signed link. +Deleting the domain does not invalidate canonical PixelVault URLs. + ### Upgrade and billing Both need a **live** secret key (`pv_live_...`); test and publishable keys get a 403. They print a Stripe URL for **you** to open — nothing is charged by the command, and the plan changes only after Stripe confirms payment. diff --git a/package-lock.json b/package-lock.json index 1d36d4f..c742471 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "pixelvault-cli", - "version": "0.25.0", + "version": "0.26.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "pixelvault-cli", - "version": "0.25.0", + "version": "0.26.0", "license": "MIT", "dependencies": { "citty": "^0.1.6" diff --git a/package.json b/package.json index b7896f0..02fb393 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "pixelvault-cli", - "version": "0.25.0", + "version": "0.26.0", "description": "CLI for PixelVault — agent-first media hosting for images, PDFs, video, and audio", "type": "module", "bin": { diff --git a/src/commands/audio.ts b/src/commands/audio.ts index 2df7b03..7d5697c 100644 --- a/src/commands/audio.ts +++ b/src/commands/audio.ts @@ -168,6 +168,7 @@ const upload = defineCommand({ args: { source: { type: "positional", description: "MP3, WAV, M4A, or OGG path or public HTTP(S) URL", required: true }, ...lifecycleOptions, + branded: { type: "boolean", description: "Print the active custom-domain URL when available", default: false }, }, async run({ args }) { const audio = await uploadAudioSource( @@ -178,7 +179,7 @@ const upload = defineCommand({ if (args.json) jsonOut(audio); else { - stdout(audio.url); + stdout(args.branded ? (audio.branded_url ?? audio.url) : audio.url); stderr(`${audio.replayed ? "Replayed" : "Hosted"} ${audio.id}: ${audio.codec}, ${audio.duration_seconds}s, ${audio.visibility}.`); } }, @@ -195,6 +196,7 @@ const list = defineCommand({ meta: { type: "string", description: "Filter metadata key=value (repeatable)" }, metadata: { type: "string", description: "Filter by metadata JSON containment" }, json: { type: "boolean", description: "Output complete JSON", default: false }, + branded: { type: "boolean", description: "Print active custom-domain URLs when available", default: false }, }, async run({ args }) { const params = new URLSearchParams({ page: args.page, per_page: args["per-page"] }); @@ -207,7 +209,7 @@ const list = defineCommand({ auth: requireApiKey(), }); if (args.json) jsonOut(response); - else for (const audio of response.data) stdout(audio.url); + else for (const audio of response.data) stdout(args.branded ? (audio.branded_url ?? audio.url) : audio.url); }, }); @@ -216,6 +218,7 @@ const get = defineCommand({ args: { id: { type: "positional", description: "Stable aud_ asset ID", required: true }, json: { type: "boolean", description: "Output complete JSON", default: false }, + branded: { type: "boolean", description: "Print the active custom-domain URL when available", default: false }, }, async run({ args }) { const response = await apiRequest>({ @@ -223,7 +226,7 @@ const get = defineCommand({ auth: requireApiKey(), }); if (args.json) jsonOut(response.data); - else stdout(response.data.url); + else stdout(args.branded ? (response.data.branded_url ?? response.data.url) : response.data.url); }, }); @@ -239,6 +242,7 @@ const update = defineCommand({ metadata: { type: "string", description: "Replacement metadata JSON object" }, "clear-metadata": { type: "boolean", description: "Replace metadata with an empty object", default: false }, json: { type: "boolean", description: "Output complete JSON", default: false }, + branded: { type: "boolean", description: "Print the active custom-domain URL when available", default: false }, }, async run({ args }) { if (args.folder && args["clear-folder"]) throw new CliError("Use --folder or --clear-folder, not both."); @@ -264,7 +268,7 @@ const update = defineCommand({ body, }); if (args.json) jsonOut(response.data); - else stdout(response.data.url); + else stdout(args.branded ? (response.data.branded_url ?? response.data.url) : response.data.url); }, }); @@ -274,16 +278,17 @@ const sign = defineCommand({ id: { type: "positional", description: "Stable aud_ asset ID", required: true }, expires: { type: "string", description: "Signed-link lifetime, e.g. 1h or 7d", default: "1h" }, json: { type: "boolean", description: "Output complete JSON", default: false }, + branded: { type: "boolean", description: "Print the active custom-domain signed URL when available", default: false }, }, async run({ args }) { - const response = await apiRequest>({ + const response = await apiRequest>({ method: "POST", path: `${AUDIO_PATH}/${encodeURIComponent(args.id)}/sign-url`, auth: requireApiKey(), body: { expires_in: parseExpires(args.expires) }, }); if (args.json) jsonOut(response.data); - else stdout(response.data.url); + else stdout(args.branded ? (response.data.branded_url ?? response.data.url) : response.data.url); }, }); diff --git a/src/commands/domains.ts b/src/commands/domains.ts new file mode 100644 index 0000000..3411938 --- /dev/null +++ b/src/commands/domains.ts @@ -0,0 +1,162 @@ +import { defineCommand } from "citty"; +import { apiRequest, ApiRequestError } from "../lib/client.js"; +import { requireApiKey } from "../lib/config.js"; +import { CliError } from "../lib/errors.js"; +import { jsonOut, stderr, stdout } from "../lib/output.js"; + +export interface CustomDomain { + id: string; + project_id: string; + hostname: string; + status: string; + hostname_status: string; + certificate_status: string; + ready: boolean; + cname_target: string; + ownership_verification: { type: "TXT"; name: string; value: string } | null; + created_at: string; + updated_at: string; +} + +type DomainListResponse = { + data: CustomDomain[]; + meta: { limit: number; total: number; project_total: number; cname_target: string }; +}; + +function explainDomainError(error: unknown): never { + if (error instanceof ApiRequestError) { + switch (error.code) { + case "custom_domains_require_paid_plan": + throw new CliError( + "Custom domains require a Starter or Pro plan. Run `pixelvault upgrade starter` to get a checkout URL.", + 1, + ); + case "custom_domain_limit_reached": + throw new CliError(`${error.message} Remove an unused hostname with \`pixelvault domains delete \`.`, 1); + case "custom_domain_exists": + case "custom_domain_conflict": + throw new CliError(`${error.message} List configured hostnames with \`pixelvault domains list\`.`, 1); + case "email_verification_required": + throw new CliError("Verify the account email before adding a custom domain.", 1); + case "custom_domain_not_found": + throw new CliError("Custom domain not found. Run `pixelvault domains list` to get its id.", 1); + case "custom_domains_unavailable": + case "custom_domain_provisioning_failed": + throw new CliError(`Custom-domain provisioning is unavailable: ${error.message}`, 1); + case "validation_error": + throw new CliError(`Invalid hostname: ${error.message}`, 1); + } + } + throw error; +} + +function printDomain(domain: CustomDomain): void { + stdout([ + domain.id, + domain.ready ? "active" : domain.status, + domain.hostname, + `CNAME ${domain.cname_target}`, + ].join(" ")); + if (domain.ownership_verification) { + stderr( + `Add ${domain.ownership_verification.type} ${domain.ownership_verification.name} = ${domain.ownership_verification.value}`, + ); + } +} + +const list = defineCommand({ + meta: { name: "list", description: "List custom domains for the active project" }, + args: { json: { type: "boolean", description: "Output as JSON", default: false } }, + async run({ args }) { + let response: DomainListResponse; + try { + response = await apiRequest({ + path: "/v1/custom-domains", + auth: requireApiKey(), + }); + } catch (error) { + explainDomainError(error); + } + if (args.json) { + jsonOut(response); + return; + } + stderr(`${response.meta.total}/${response.meta.limit} account custom domains used; ${response.meta.project_total} on this project.`); + for (const domain of response.data) printDomain(domain); + }, +}); + +const add = defineCommand({ + meta: { name: "add", description: "Attach a hostname to the active project" }, + args: { + hostname: { type: "positional", description: "Customer hostname, e.g. media.example.com", required: true }, + json: { type: "boolean", description: "Output as JSON", default: false }, + }, + async run({ args }) { + let response: { data: CustomDomain; meta: { limit: number } }; + try { + response = await apiRequest({ + method: "POST", + path: "/v1/custom-domains", + auth: requireApiKey(), + body: { hostname: args.hostname }, + }); + } catch (error) { + explainDomainError(error); + } + if (args.json) jsonOut(response); + else { + printDomain(response.data); + stderr(`Point ${response.data.hostname} to ${response.data.cname_target}, then run pixelvault domains refresh ${response.data.id}.`); + } + }, +}); + +const refresh = defineCommand({ + meta: { name: "refresh", description: "Refresh DNS and certificate status" }, + args: { + id: { type: "positional", description: "Custom-domain id", required: true }, + json: { type: "boolean", description: "Output as JSON", default: false }, + }, + async run({ args }) { + let response: { data: CustomDomain }; + try { + response = await apiRequest({ + method: "POST", + path: `/v1/custom-domains/${encodeURIComponent(args.id)}/refresh`, + auth: requireApiKey(), + }); + } catch (error) { + explainDomainError(error); + } + if (args.json) jsonOut(response.data); + else printDomain(response.data); + }, +}); + +const remove = defineCommand({ + meta: { name: "delete", description: "Remove a custom domain" }, + args: { + id: { type: "positional", description: "Custom-domain id", required: true }, + json: { type: "boolean", description: "Output as JSON", default: false }, + }, + async run({ args }) { + let response: { data: { deleted: boolean; id: string } }; + try { + response = await apiRequest({ + method: "DELETE", + path: `/v1/custom-domains/${encodeURIComponent(args.id)}`, + auth: requireApiKey(), + }); + } catch (error) { + explainDomainError(error); + } + if (args.json) jsonOut(response.data); + else stderr(`Deleted custom domain ${response.data.id}.`); + }, +}); + +export default defineCommand({ + meta: { name: "domains", description: "Manage project custom domains" }, + subCommands: { list, add, refresh, delete: remove }, +}); diff --git a/src/commands/get.ts b/src/commands/get.ts index 83da17c..7c8c683 100644 --- a/src/commands/get.ts +++ b/src/commands/get.ts @@ -9,6 +9,7 @@ interface GetResponse { data: { id: string; url: string; + branded_url?: string; mime_type: string; size: number; filename: string; @@ -60,6 +61,11 @@ export default defineCommand({ 'Transform params to apply, e.g. "w=400&fmt=webp", "segment=foreground", "tile=img_logo.png"', alias: "t", }, + branded: { + type: "boolean", + description: "Use the active custom-domain URL when available", + default: false, + }, json: { type: "boolean", description: "Output full JSON metadata", @@ -74,7 +80,8 @@ export default defineCommand({ auth: apiKey, }); - const url = applyTransform(res.data.url, args.transform as string | undefined); + const baseUrl = args.branded ? (res.data.branded_url ?? res.data.url) : res.data.url; + const url = applyTransform(baseUrl, args.transform as string | undefined); // Download mode: fetch the (possibly transformed) bytes to disk. if (args.output) { diff --git a/src/commands/list.ts b/src/commands/list.ts index de02f8f..a7c0ac5 100644 --- a/src/commands/list.ts +++ b/src/commands/list.ts @@ -8,6 +8,7 @@ interface ListResponse { data: Array<{ id: string; url: string; + branded_url?: string; mime_type: string; size: number; filename: string; @@ -59,6 +60,11 @@ export default defineCommand({ description: 'Only images whose metadata contains this JSON object (typed match), e.g. --metadata \'{"n":3}\'', }, + branded: { + type: "boolean", + description: "Print active custom-domain URLs when available", + default: false, + }, json: { type: "boolean", description: "Output full JSON response", @@ -88,7 +94,7 @@ export default defineCommand({ jsonOut(res); } else { for (const img of res.data) { - stdout(img.url); + stdout(args.branded ? (img.branded_url ?? img.url) : img.url); } } }, diff --git a/src/commands/upload.ts b/src/commands/upload.ts index df3da53..c90bd31 100644 --- a/src/commands/upload.ts +++ b/src/commands/upload.ts @@ -16,6 +16,7 @@ interface UploadResponse { id: string; kind?: "image" | "document" | "video"; url: string; + branded_url?: string; optimized_url?: string; poster_url?: string; visibility?: "public" | "private"; @@ -69,6 +70,12 @@ export default defineCommand({ "Print the optimized URL (WebP/AVIF, usually much smaller) instead of the original; falls back to the original URL when none is returned (SVG, GIF, private)", default: false, }, + branded: { + type: "boolean", + description: + "Print the active custom-domain URL when available; falls back to the canonical CDN URL", + default: false, + }, social: { type: "boolean", description: @@ -145,6 +152,10 @@ export default defineCommand({ stderr("--social only applies to MP4 file or URL uploads."); process.exit(1); } + if (args.branded && (args.optimized || args.social)) { + stderr("--branded cannot be combined with --optimized or --social; each selects a different output URL."); + process.exit(1); + } const imageOnlyOption = args.folder || args.optimized || @@ -228,7 +239,11 @@ export default defineCommand({ if (args.json) { results.push(video); } else { - stdout(args.social ? video.social_optimization.url! : video.url); + stdout(args.social + ? video.social_optimization.url! + : args.branded + ? (video.branded_url ?? video.url) + : video.url); } continue; } @@ -308,7 +323,11 @@ export default defineCommand({ if (args.json) { results.push(res.data); } else { - stdout(args.optimized ? (res.data.optimized_url ?? res.data.url) : res.data.url); + stdout(args.branded + ? (res.data.branded_url ?? res.data.url) + : args.optimized + ? (res.data.optimized_url ?? res.data.url) + : res.data.url); } } catch (err) { hadError = true; diff --git a/src/index.ts b/src/index.ts index b319d6f..9f67d56 100644 --- a/src/index.ts +++ b/src/index.ts @@ -27,6 +27,7 @@ const main = defineCommand({ usage: () => import("./commands/usage.js").then((m) => m.default), keys: () => import("./commands/keys.js").then((m) => m.default), webhooks: () => import("./commands/webhooks.js").then((m) => m.default), + domains: () => import("./commands/domains.js").then((m) => m.default), upgrade: () => import("./commands/upgrade.js").then((m) => m.default), billing: () => import("./commands/billing.js").then((m) => m.default), whoami: () => import("./commands/whoami.js").then((m) => m.default), diff --git a/src/lib/audio-enrichment.ts b/src/lib/audio-enrichment.ts index 7927fa6..6008bac 100644 --- a/src/lib/audio-enrichment.ts +++ b/src/lib/audio-enrichment.ts @@ -30,6 +30,7 @@ export interface AudioAsset { kind: "audio"; url: string; original_url: string; + branded_url?: string; visibility: "public" | "private"; mime_type: string; size: number; diff --git a/src/lib/client.ts b/src/lib/client.ts index fa5ee5f..1b5c70a 100644 --- a/src/lib/client.ts +++ b/src/lib/client.ts @@ -18,7 +18,7 @@ interface ApiError { // this channel (server reads X-PixelVault-Client at register/device-login — see // pixelvault docs/specs/lead-attribution.md). Keep the version in sync with // package.json on release (tests/lib/version.test.ts fails if they drift). -export const VERSION = "0.25.0"; +export const VERSION = "0.26.0"; const CLIENT_ID = `pixelvault-cli/${VERSION}`; /** CliError carrying the API's machine-readable error details. */ diff --git a/src/lib/video-upload.ts b/src/lib/video-upload.ts index 79f82e4..d9caae4 100644 --- a/src/lib/video-upload.ts +++ b/src/lib/video-upload.ts @@ -57,6 +57,7 @@ export interface VideoData { kind: "video"; url: string; original_url: string; + branded_url?: string; social_ready_url?: string; poster_url?: string; visibility: "public" | "private"; diff --git a/tests/commands/domains.test.ts b/tests/commands/domains.test.ts new file mode 100644 index 0000000..b0a4cd1 --- /dev/null +++ b/tests/commands/domains.test.ts @@ -0,0 +1,104 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; + +vi.mock("../../src/lib/config.js", () => ({ + requireApiKey: () => "pv_live_test", + getApiUrl: () => "https://api.test.pixelvault.dev", +})); + +const { default: domains } = await import("../../src/commands/domains.js"); +type Cmd = { run?: (ctx: any) => unknown; subCommands?: Record }; +const sub = (name: string) => (domains as Cmd).subCommands?.[name] as Cmd; + +const DOMAIN = { + id: "dom_one", + project_id: "proj_one", + hostname: "media.example.com", + status: "pending", + hostname_status: "pending", + certificate_status: "pending_validation", + ready: false, + cname_target: "custom.pvcdn.dev", + ownership_verification: null, + created_at: "2026-11-18T00:00:00Z", + updated_at: "2026-11-18T00:00:00Z", +}; + +function mockFetch(status: number, body: unknown) { + const fetchMock = vi.fn().mockResolvedValue({ + ok: status < 400, + status, + statusText: "x", + headers: new Headers(), + json: () => Promise.resolve(body), + }); + globalThis.fetch = fetchMock as typeof fetch; + return fetchMock; +} + +describe("domains commands", () => { + const originalFetch = globalThis.fetch; + let out = ""; + let err = ""; + + beforeEach(() => { + out = ""; + err = ""; + vi.spyOn(process.stdout, "write").mockImplementation((value) => { + out += value; + return true; + }); + vi.spyOn(process.stderr, "write").mockImplementation((value) => { + err += value; + return true; + }); + }); + + afterEach(() => { + globalThis.fetch = originalFetch; + vi.restoreAllMocks(); + }); + + it("lists account capacity and project domains", async () => { + mockFetch(200, { + data: [{ ...DOMAIN, ready: true, status: "active", hostname_status: "active", certificate_status: "active" }], + meta: { limit: 1, total: 1, project_total: 1, cname_target: "custom.pvcdn.dev" }, + }); + await sub("list").run?.({ args: { json: false } }); + expect(out).toContain("dom_one active media.example.com CNAME custom.pvcdn.dev"); + expect(err).toContain("1/1 account custom domains used; 1 on this project"); + }); + + it("adds a hostname and prints its DNS target", async () => { + const fetchMock = mockFetch(201, { data: DOMAIN, meta: { limit: 1 } }); + await sub("add").run?.({ args: { hostname: "media.example.com", json: false } }); + expect(fetchMock).toHaveBeenCalledWith( + "https://api.test.pixelvault.dev/v1/custom-domains", + expect.objectContaining({ method: "POST", body: JSON.stringify({ hostname: "media.example.com" }) }), + ); + expect(out).toContain("media.example.com CNAME custom.pvcdn.dev"); + expect(err).toContain("pixelvault domains refresh dom_one"); + }); + + it("refreshes and deletes by encoded id", async () => { + const refreshFetch = mockFetch(200, { data: { ...DOMAIN, ready: true, status: "active" } }); + await sub("refresh").run?.({ args: { id: "dom/one", json: true } }); + expect(refreshFetch.mock.calls[0]?.[0]).toBe( + "https://api.test.pixelvault.dev/v1/custom-domains/dom%2Fone/refresh", + ); + + const deleteFetch = mockFetch(200, { data: { deleted: true, id: "dom_one" } }); + await sub("delete").run?.({ args: { id: "dom/one", json: false } }); + expect(deleteFetch.mock.calls[0]?.[0]).toBe( + "https://api.test.pixelvault.dev/v1/custom-domains/dom%2Fone", + ); + expect(deleteFetch.mock.calls[0]?.[1]).toMatchObject({ method: "DELETE" }); + }); + + it("explains the paid-plan requirement", async () => { + mockFetch(402, { + error: { code: "custom_domains_require_paid_plan", message: "paid" }, + }); + await expect(sub("add").run?.({ args: { hostname: "media.example.com", json: false } })) + .rejects.toThrow("require a Starter or Pro plan"); + }); +}); diff --git a/tests/commands/upload.test.ts b/tests/commands/upload.test.ts index da94f73..509612d 100644 --- a/tests/commands/upload.test.ts +++ b/tests/commands/upload.test.ts @@ -263,4 +263,41 @@ describe("upload command", () => { "https://img.test/b.svg", ]); }); + it("--branded prints the custom-domain URL and falls back to the canonical URL", async () => { + const names = ["custom.png", "canonical.png"]; + const paths = names.map((name) => { + const path = join(testDir, name); + writeFileSync(path, Buffer.from(name)); + return path; + }); + globalThis.fetch = vi.fn().mockImplementation(async (_url, init) => { + const file = (init.body as FormData).get("file") as File; + const canonical = `https://img.test/proj_1/${file.name}`; + return { + ok: true, + json: () => Promise.resolve({ + data: { + id: file.name, + url: canonical, + ...(file.name === "custom.png" + ? { branded_url: `https://media.example.com/${file.name}` } + : {}), + }, + }), + }; + }); + const out = vi.spyOn(process.stdout, "write").mockImplementation(() => true); + + const { runCommand } = await import("citty"); + const { default: upload } = await import("../../src/commands/upload.js"); + await runCommand(upload, { rawArgs: [...paths, "--branded"] }); + const printed = out.mock.calls.map((call) => String(call[0]).trim()); + out.mockRestore(); + + expect(printed).toEqual([ + "https://media.example.com/custom.png", + "https://img.test/proj_1/canonical.png", + ]); + }); + });