diff --git a/README.md b/README.md index 2a01440..d9e2ee2 100644 --- a/README.md +++ b/README.md @@ -60,6 +60,19 @@ pixelvault enrich-video demo.mp4 # Resume the same server job without uploading again pixelvault enrich-video vid_xyz +# Host original MP3/WAV/M4A/OGG audio; prints the original-byte CDN URL +pixelvault audio upload episode.mp3 + +# Private audio with a 12-hour signed link and 7-day asset deletion TTL +pixelvault audio upload episode.m4a --private --link-expires 12h --delete-after 7d --json + +# Import, discover, update, re-sign, or delete by stable aud_ ID +pixelvault audio upload "https://media.example.com/episode.ogg" --json +pixelvault audio list --folder podcasts --json +pixelvault audio get aud_xyz --json +pixelvault audio sign aud_xyz --expires 1h +pixelvault audio delete aud_xyz + # List your images pixelvault list @@ -79,8 +92,8 @@ pixelvault keys list KEY=$(pixelvault keys create --label ci) # raw key on stdout, shown once pixelvault keys revoke key_abc123 -# Export everything — all your images as a tar archive (no lock-in) -pixelvault export -o my-images.tar +# Export everything — manifest plus all project media and derived artifacts (no lock-in) +pixelvault export -o pixelvault-export.tar ``` ## Agent Integration @@ -91,6 +104,8 @@ The CLI is designed for AI coding agents. Output contract: - `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 +- `audio upload` hosts original MP3, PCM/float WAV, AAC M4A, or Opus/Vorbis OGG from a local path or public URL; actual bytes are validated. The approved global maximum is 25,000,000 bytes (not a plan allowance). `--json` returns the stable `aud_` ID, detected codec/duration/sample rate/channels, privacy, and expiry +- `audio list|get|update|sign|delete` cover discovery, organization, fresh private links, and deletion without public fallbacks - Image and PDF uploads support `--idempotency-key` and `--dedupe`; folder, image optimization, reuse, metadata, and AI-description options are rejected for MP4 files and URLs - `list` outputs one URL per line - `meta` prints the stored metadata as JSON @@ -127,10 +142,12 @@ npx pixelvault-cli upload build-output.png | `optimize ` | Compress images locally — no account needed (resize, convert, strip metadata; never writes a bigger file) | | `optimize-video ` | Preserve a hosted MP4 and create a social-ready H.264/AAC fast-start copy | | `enrich-video ` | Upload or resume transcript + storyboard enrichment, with bounded polling and structured artifact access data | +| `audio upload ` | Host original MP3/WAV/M4A/OGG bytes with privacy, TTL, metadata, organization, and retry safety | +| `audio list\|get\|update\|sign\|delete` | Discover and manage audio by stable `aud_` asset ID | | `get ` | Get an image's URL/metadata, or download it (optionally transformed) | | `meta ` | Replace an image's custom metadata (`--meta k=v`, `--metadata ''`, or `--clear`) | | `delete ` | Delete an image | -| `export` | Export all project images as a tar archive | +| `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 | | `upgrade ` | Print a Stripe Checkout URL to subscribe (live key; you pay in the browser) | @@ -213,6 +230,34 @@ Quota, duration, size, unavailable-metadata, failed-job, and local-timeout state exit explicitly. Monthly source minutes are Free 2, Starter 30, and Pro 120; check `pixelvault usage` for the current allowance and reset. +### Audio Hosting + +```bash +pixelvault audio upload episode.mp3 +pixelvault audio upload episode.wav --idempotency-key episode-v1 --json +pixelvault audio upload "https://media.example.com/episode.m4a" --folder podcasts --json +pixelvault audio upload private.ogg --private --link-expires 12h --delete-after 7d --json +pixelvault audio list --folder podcasts --json +pixelvault audio get aud_xyz --json +pixelvault audio update aud_xyz --folder archive --meta episode=7 --json +pixelvault audio sign aud_xyz --expires 1h +pixelvault audio delete aud_xyz +``` + +Audio hosting preserves original bytes and accepts MP3, PCM integer/IEEE-float +WAV, AAC in M4A, and Opus or Vorbis in OGG. PixelVault validates the actual +container and codec, not only the extension or supplied MIME type. The approved +global original-file maximum is 25,000,000 bytes; it is not a plan allowance or +capacity reservation. Existing storage, upload, bandwidth, private-asset, and +retention rules apply. + +`--link-expires` controls only the private bearer URL. `--delete-after` deletes +the asset. Local uploads with `--idempotency-key` send a byte checksum; exact +retries return the original asset, while conflicting inputs fail. URL import is +server-side and keeps the same product limit. Private assets never fall back to +a public URL; use `audio sign` to mint a fresh link. Audio editing, conversion, +HLS/DASH, and transcription are intentionally unsupported. + ### Generate Options ```bash diff --git a/package-lock.json b/package-lock.json index 25b96fc..ba22371 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "pixelvault-cli", - "version": "0.23.2", + "version": "0.24.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "pixelvault-cli", - "version": "0.23.2", + "version": "0.24.0", "license": "MIT", "dependencies": { "citty": "^0.1.6" diff --git a/package.json b/package.json index ab80ac6..3d02499 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "pixelvault-cli", - "version": "0.23.2", - "description": "CLI for PixelVault — agent-first media hosting for images, PDFs, and video", + "version": "0.24.0", + "description": "CLI for PixelVault — agent-first media hosting for images, PDFs, video, and audio", "type": "module", "bin": { "pixelvault": "bin/pixelvault.mjs" diff --git a/src/commands/audio.ts b/src/commands/audio.ts new file mode 100644 index 0000000..bee13cf --- /dev/null +++ b/src/commands/audio.ts @@ -0,0 +1,306 @@ +import { createHash } from "node:crypto"; +import { basename, extname } from "node:path"; +import { readFile, stat } from "node:fs/promises"; +import { defineCommand } from "citty"; +import { apiRequest, ApiRequestError } from "../lib/client.js"; +import { requireApiKey } from "../lib/config.js"; +import { parseExpires } from "../lib/duration.js"; +import { CliError } from "../lib/errors.js"; +import { parseMetadataFlags } from "../lib/metadata.js"; +import { jsonOut, stderr, stdout } from "../lib/output.js"; + +const AUDIO_PATH = "/v1/audio"; +const AUDIO_MAX_BYTES = 25_000_000; +const CONTENT_TYPES: Readonly> = { + ".mp3": "audio/mpeg", + ".wav": "audio/wav", + ".m4a": "audio/mp4", + ".ogg": "audio/ogg", +}; + +interface AudioAsset { + id: string; + kind: "audio"; + url: string; + original_url: string; + visibility: "public" | "private"; + mime_type: string; + size: number; + container: "mp3" | "wav" | "m4a" | "ogg"; + codec: "mp3" | "pcm" | "pcm_float" | "aac" | "opus" | "vorbis"; + duration_seconds: number; + sample_rate: number; + channels: number; + filename: string; + folder: string | null; + collection_id: string | null; + metadata: Record | null; + created_at: string; + expires_at?: string; + signed_expires?: number; + replayed?: true; +} + +interface DataResponse { + data: T; +} + +function isRemoteSource(source: string): boolean { + try { + const url = new URL(source); + return url.protocol === "https:" || url.protocol === "http:"; + } catch { + return false; + } +} + +function lifecycleArgs(args: Record): { + visibility: "public" | "private"; + signExpiresIn?: number; + expiresIn?: number; + folder?: string; + collectionId?: string; + metadata: Record | null; + idempotencyKey?: string; +} { + const privateAsset = args.private === true; + const signExpiresIn = args["link-expires"] === undefined + ? undefined + : parseExpires(String(args["link-expires"]), "--link-expires"); + if (signExpiresIn !== undefined && !privateAsset) { + throw new CliError("--link-expires only applies with --private."); + } + const expiresIn = args["delete-after"] === undefined + ? undefined + : parseExpires(String(args["delete-after"]), "--delete-after"); + return { + visibility: privateAsset ? "private" : "public", + signExpiresIn, + expiresIn, + folder: typeof args.folder === "string" && args.folder ? args.folder : undefined, + collectionId: typeof args.collection === "string" && args.collection ? args.collection : undefined, + metadata: parseMetadataFlags({ meta: args.meta, metadata: args.metadata }), + idempotencyKey: typeof args["idempotency-key"] === "string" && args["idempotency-key"] + ? args["idempotency-key"] + : undefined, + }; +} + +function explainAudioError(error: unknown): never { + if (error instanceof ApiRequestError) { + if (error.code === "audio_policy_pending") { + throw new CliError("Audio hosting is temporarily unavailable because the deployment is missing its approved 25,000,000-byte ceiling."); + } + if (error.code === "file_too_large") { + throw new CliError(`${error.message} The server's audio policy is authoritative; the CLI does not invent a plan limit.`); + } + if (error.code === "invalid_audio" || error.code === "unsupported_audio_codec" || error.code === "unsupported_media_type") { + throw new CliError(`${error.message} Supported original containers/codecs: MP3, PCM/float WAV, AAC M4A, and Opus/Vorbis OGG.`); + } + if (error.code === "idempotency_key_reuse") { + throw new CliError(`${error.message} Reuse a key only for an identical source and lifecycle settings.`); + } + } + throw error; +} + +const lifecycleOptions = { + private: { type: "boolean" as const, description: "Store privately and return a signed URL", default: false }, + "link-expires": { type: "string" as const, description: "Private link lifetime, e.g. 1h or 7d (requires --private)" }, + "delete-after": { type: "string" as const, description: "Delete the asset after this TTL, e.g. 1h or 7d; omit to keep it" }, + folder: { type: "string" as const, description: "Folder name" }, + collection: { type: "string" as const, description: "Existing collection ID with matching visibility" }, + meta: { type: "string" as const, description: "Custom metadata key=value (repeatable)" }, + metadata: { type: "string" as const, description: "Custom metadata JSON object" }, + "idempotency-key": { type: "string" as const, description: "Replay-safe key for this exact upload/import" }, + json: { type: "boolean" as const, description: "Output complete JSON", default: false }, +}; + +const upload = defineCommand({ + meta: { name: "upload", description: "Upload local audio or securely import a public audio URL" }, + args: { + source: { type: "positional", description: "MP3, WAV, M4A, or OGG path or public HTTP(S) URL", required: true }, + ...lifecycleOptions, + }, + async run({ args }) { + const auth = requireApiKey(); + const options = lifecycleArgs(args as Record); + let response: DataResponse; + try { + if (isRemoteSource(args.source)) { + response = await apiRequest({ + method: "POST", + path: AUDIO_PATH, + auth, + headers: options.idempotencyKey ? { "Idempotency-Key": options.idempotencyKey } : undefined, + body: { + url: args.source, + visibility: options.visibility, + ...(options.signExpiresIn !== undefined ? { sign_expires_in: options.signExpiresIn } : {}), + ...(options.expiresIn !== undefined ? { expires_in: options.expiresIn } : {}), + ...(options.folder ? { folder: options.folder } : {}), + ...(options.collectionId ? { collection_id: options.collectionId } : {}), + ...(options.metadata ? { metadata: options.metadata } : {}), + }, + }); + } else { + const info = await stat(args.source).catch((error: unknown) => { + throw new CliError(`Cannot read audio path ${args.source}: ${error instanceof Error ? error.message : String(error)}`); + }); + if (!info.isFile()) throw new CliError(`Audio path is not a regular file: ${args.source}`); + if (info.size > AUDIO_MAX_BYTES) { + throw new CliError( + `Local audio is ${info.size.toLocaleString("en-US")} bytes. Audio originals are limited to the approved global maximum of 25,000,000 bytes; this is not a plan allowance.`, + ); + } + const filename = basename(args.source); + const contentType = CONTENT_TYPES[extname(filename).toLowerCase()]; + if (!contentType) throw new CliError("Audio filename must end in .mp3, .wav, .m4a, or .ogg."); + const bytes = await readFile(args.source); + const headers: Record = { + "Content-Type": contentType, + "Content-Length": String(bytes.byteLength), + "X-PixelVault-Filename": encodeURIComponent(filename), + "X-PixelVault-Visibility": options.visibility, + }; + if (options.signExpiresIn !== undefined) headers["X-PixelVault-Sign-Expires-In"] = String(options.signExpiresIn); + if (options.expiresIn !== undefined) headers["X-PixelVault-Expires-In"] = String(options.expiresIn); + if (options.folder) headers["X-PixelVault-Folder"] = options.folder; + if (options.collectionId) headers["X-PixelVault-Collection-Id"] = options.collectionId; + if (options.metadata) headers["X-PixelVault-Metadata"] = JSON.stringify(options.metadata); + if (options.idempotencyKey) { + headers["Idempotency-Key"] = options.idempotencyKey; + headers["X-PixelVault-Content-SHA256"] = createHash("sha256").update(bytes).digest("hex"); + } + response = await apiRequest({ method: "POST", path: AUDIO_PATH, auth, headers, rawBody: bytes }); + } + } catch (error) { + explainAudioError(error); + } + + if (args.json) jsonOut(response.data); + else { + stdout(response.data.url); + stderr(`${response.data.replayed ? "Replayed" : "Hosted"} ${response.data.id}: ${response.data.codec}, ${response.data.duration_seconds}s, ${response.data.visibility}.`); + } + }, +}); + +const list = defineCommand({ + meta: { name: "list", description: "List hosted audio" }, + args: { + page: { type: "string", description: "Page number", default: "1" }, + "per-page": { type: "string", description: "Items per page (max 100)", default: "20" }, + folder: { type: "string", description: "Filter by folder" }, + collection: { type: "string", description: "Filter by collection ID" }, + 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 }, + }, + async run({ args }) { + const params = new URLSearchParams({ page: args.page, per_page: args["per-page"] }); + if (args.folder) params.set("folder", args.folder); + if (args.collection) params.set("collection_id", args.collection); + const metadata = parseMetadataFlags({ meta: args.meta, metadata: args.metadata }); + if (metadata) params.set("metadata", JSON.stringify(metadata)); + const response = await apiRequest<{ data: AudioAsset[]; meta: Record }>({ + path: `${AUDIO_PATH}?${params}`, + auth: requireApiKey(), + }); + if (args.json) jsonOut(response); + else for (const audio of response.data) stdout(audio.url); + }, +}); + +const get = defineCommand({ + meta: { name: "get", description: "Get audio metadata and its current original URL" }, + args: { + id: { type: "positional", description: "Stable aud_ asset ID", required: true }, + json: { type: "boolean", description: "Output complete JSON", default: false }, + }, + async run({ args }) { + const response = await apiRequest>({ + path: `${AUDIO_PATH}/${encodeURIComponent(args.id)}`, + auth: requireApiKey(), + }); + if (args.json) jsonOut(response.data); + else stdout(response.data.url); + }, +}); + +const update = defineCommand({ + meta: { name: "update", description: "Replace audio metadata, folder, or collection membership" }, + args: { + id: { type: "positional", description: "Stable aud_ asset ID", required: true }, + folder: { type: "string", description: "Replacement folder" }, + "clear-folder": { type: "boolean", description: "Remove folder membership", default: false }, + collection: { type: "string", description: "Replacement existing collection ID" }, + "clear-collection": { type: "boolean", description: "Remove collection membership", default: false }, + meta: { type: "string", description: "Replacement metadata key=value (repeatable)" }, + 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 }, + }, + async run({ args }) { + if (args.folder && args["clear-folder"]) throw new CliError("Use --folder or --clear-folder, not both."); + if (args.collection && args["clear-collection"]) throw new CliError("Use --collection or --clear-collection, not both."); + if ((args.meta || args.metadata) && args["clear-metadata"]) { + throw new CliError("Use metadata flags or --clear-metadata, not both."); + } + const body: Record = {}; + if (args.folder) body.folder = args.folder; + else if (args["clear-folder"]) body.folder = null; + if (args.collection) body.collection_id = args.collection; + else if (args["clear-collection"]) body.collection_id = null; + const metadata = parseMetadataFlags({ meta: args.meta, metadata: args.metadata }); + if (metadata) body.metadata = metadata; + else if (args["clear-metadata"]) body.metadata = {}; + if (Object.keys(body).length === 0) { + throw new CliError("Provide --folder, --clear-folder, --collection, --clear-collection, metadata, or --clear-metadata."); + } + const response = await apiRequest>({ + method: "PATCH", + path: `${AUDIO_PATH}/${encodeURIComponent(args.id)}`, + auth: requireApiKey(), + body, + }); + if (args.json) jsonOut(response.data); + else stdout(response.data.url); + }, +}); + +const sign = defineCommand({ + meta: { name: "sign", description: "Mint a fresh signed URL for a private audio original" }, + args: { + 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 }, + }, + async run({ args }) { + 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); + }, +}); + +const remove = defineCommand({ + meta: { name: "delete", description: "Permanently delete an audio original" }, + args: { id: { type: "positional", description: "Stable aud_ asset ID", required: true } }, + async run({ args }) { + await apiRequest({ + method: "DELETE", + path: `${AUDIO_PATH}/${encodeURIComponent(args.id)}`, + auth: requireApiKey(), + }); + }, +}); + +export default defineCommand({ + meta: { name: "audio", description: "Host and manage original audio files" }, + subCommands: { upload, list, get, update, sign, delete: remove }, +}); diff --git a/src/index.ts b/src/index.ts index 66a13f9..b319d6f 100644 --- a/src/index.ts +++ b/src/index.ts @@ -19,6 +19,7 @@ const main = defineCommand({ optimize: () => import("./commands/optimize.js").then((m) => m.default), "optimize-video": () => import("./commands/optimize-video.js").then((m) => m.default), "enrich-video": () => import("./commands/enrich-video.js").then((m) => m.default), + audio: () => import("./commands/audio.js").then((m) => m.default), get: () => import("./commands/get.js").then((m) => m.default), meta: () => import("./commands/meta.js").then((m) => m.default), delete: () => import("./commands/delete.js").then((m) => m.default), diff --git a/src/lib/client.ts b/src/lib/client.ts index e26845a..dad7fc6 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.23.2"; +export const VERSION = "0.24.0"; const CLIENT_ID = `pixelvault-cli/${VERSION}`; /** CliError carrying the API's machine-readable error details. */ diff --git a/tests/commands/audio.test.ts b/tests/commands/audio.test.ts new file mode 100644 index 0000000..5889433 --- /dev/null +++ b/tests/commands/audio.test.ts @@ -0,0 +1,193 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { mkdtemp, rm, truncate, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; + +vi.mock("../../src/lib/config.js", () => ({ + requireApiKey: () => "pv_live_test", + getApiUrl: () => "https://api.test.pixelvault.dev", +})); + +const { default: audio } = await import("../../src/commands/audio.js"); +type Cmd = { run?: (ctx: { args: Record }) => unknown; subCommands?: Record }; +const sub = (name: string) => (audio as Cmd).subCommands?.[name] as Cmd; + +const ASSET = { + id: "aud_1", + kind: "audio", + url: "https://img.example/aud_1.ogg", + original_url: "https://img.example/aud_1.ogg", + visibility: "private", + mime_type: "audio/ogg", + size: 3, + container: "ogg", + codec: "opus", + duration_seconds: 1, + sample_rate: 48_000, + channels: 2, + filename: "episode.ogg", + folder: "episodes", + collection_id: null, + metadata: { season: 1 }, + created_at: "2026-11-16T00: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("audio commands", () => { + const originalFetch = globalThis.fetch; + let out = ""; + + beforeEach(() => { + out = ""; + vi.spyOn(process.stdout, "write").mockImplementation((value) => { + out += value; + return true; + }); + vi.spyOn(process.stderr, "write").mockImplementation(() => true); + }); + + afterEach(() => { + globalThis.fetch = originalFetch; + vi.restoreAllMocks(); + }); + + it("uploads local audio with privacy, TTL, organization, and retry headers", async () => { + const dir = await mkdtemp(join(tmpdir(), "pv-cli-audio-")); + const path = join(dir, "episode.ogg"); + await writeFile(path, Buffer.from("ogg")); + const fetchMock = mockFetch(201, { data: ASSET }); + try { + await sub("upload").run?.({ + args: { + source: path, + private: true, + "link-expires": "1h", + "delete-after": "1d", + folder: "episodes", + collection: "col_1", + meta: "season=1", + "idempotency-key": "audio-retry-1", + json: false, + }, + }); + } finally { + await rm(dir, { recursive: true, force: true }); + } + + expect(out).toBe(`${ASSET.url}\n`); + const [, init] = fetchMock.mock.calls[0] as [string, RequestInit]; + expect(init.headers).toMatchObject({ + "Content-Type": "audio/ogg", + "Content-Length": "3", + "X-PixelVault-Filename": "episode.ogg", + "X-PixelVault-Visibility": "private", + "X-PixelVault-Sign-Expires-In": "3600", + "X-PixelVault-Expires-In": "86400", + "X-PixelVault-Folder": "episodes", + "X-PixelVault-Collection-Id": "col_1", + "X-PixelVault-Metadata": '{"season":"1"}', + "Idempotency-Key": "audio-retry-1", + "X-PixelVault-Content-SHA256": "90308fe99871113bf5490ec73a8813b667adc60fe01530102a6c7bfb73c66481", + }); + expect(Buffer.from(init.body as Uint8Array).toString()).toBe("ogg"); + }); + + it("securely imports a URL and emits complete JSON", async () => { + const fetchMock = mockFetch(201, { data: ASSET }); + await sub("upload").run?.({ + args: { + source: "https://example.com/episode.m4a", + private: false, + "delete-after": "1h", + metadata: '{"source":"demo"}', + "idempotency-key": "audio-import-1", + json: true, + }, + }); + expect(JSON.parse(out)).toMatchObject({ id: "aud_1", codec: "opus" }); + const [, init] = fetchMock.mock.calls[0] as [string, RequestInit]; + expect(init.headers).toMatchObject({ "Idempotency-Key": "audio-import-1" }); + expect(JSON.parse(init.body as string)).toMatchObject({ + url: "https://example.com/episode.m4a", + visibility: "public", + expires_in: 3600, + metadata: { source: "demo" }, + }); + }); + + it("lists, gets, updates, signs, and deletes by stable audio ID", async () => { + const fetchMock = mockFetch(200, { data: [ASSET], meta: { total: 1, page: 1, per_page: 20 } }); + await sub("list").run?.({ + args: { page: "1", "per-page": "20", collection: "col_1", meta: "season=1", json: false }, + }); + expect(out).toBe(`${ASSET.url}\n`); + expect(fetchMock.mock.calls[0]?.[0]).toContain("collection_id=col_1"); + + out = ""; + mockFetch(200, { data: ASSET }); + await sub("get").run?.({ args: { id: "aud/1", json: false } }); + expect(globalThis.fetch).toHaveBeenCalledWith( + "https://api.test.pixelvault.dev/v1/audio/aud%2F1", + expect.any(Object), + ); + + const updateFetch = mockFetch(200, { data: ASSET }); + await sub("update").run?.({ + args: { + id: "aud_1", + folder: "archive", + "clear-folder": false, + "clear-collection": true, + "clear-metadata": true, + json: true, + }, + }); + expect(JSON.parse((updateFetch.mock.calls[0]?.[1] as RequestInit).body as string)).toEqual({ + folder: "archive", + collection_id: null, + metadata: {}, + }); + + const signFetch = mockFetch(200, { data: { url: "https://signed", expires: 123, visibility: "private" } }); + await sub("sign").run?.({ args: { id: "aud_1", expires: "5m", json: false } }); + expect(JSON.parse((signFetch.mock.calls[0]?.[1] as RequestInit).body as string)).toEqual({ expires_in: 300 }); + + const deleteFetch = mockFetch(200, { success: true }); + await sub("delete").run?.({ args: { id: "aud_1" } }); + expect(deleteFetch.mock.calls[0]?.[1]).toMatchObject({ method: "DELETE" }); + }); + + it("turns the backend policy gate into an explicit CLI error", async () => { + mockFetch(503, { + error: { code: "audio_policy_pending", message: "not configured" }, + }); + await expect(sub("upload").run?.({ + args: { source: "https://example.com/episode.mp3", private: false, json: false }, + })).rejects.toThrow("approved 25,000,000-byte ceiling"); + }); + + it("rejects a local original above the approved global ceiling before reading it", async () => { + const dir = await mkdtemp(join(tmpdir(), "pv-cli-audio-limit-")); + const path = join(dir, "oversized.mp3"); + await writeFile(path, ""); + await truncate(path, 25_000_001); + try { + await expect(sub("upload").run?.({ + args: { source: path, private: false, json: false }, + })).rejects.toThrow("25,000,000 bytes"); + } finally { + await rm(dir, { recursive: true, force: true }); + } + }); +});