Files
karaoke-gen/frontend/lib/api.ts
T
Andrew Beveridge ☄️andClaude Opus 5.5 a8f9618a07 feat(review): admin "perfectly synced" mark for the word-timing reference set (v0.290.0) (#1242)
## Summary
Andrew's review depth varies: Thursday live-event jobs often get only a
quick review. Treating every admin review as perfect sync truth
therefore poisons aligner training and evaluation (full-auto v2). This
adds an explicit, admin-only **"perfectly synced"** mark in the lyrics
review. Ticked jobs join the word-timing reference set; unticked means
unverified. Andrew's definition: a confident spot-check (anchors +
waveforms), not necessarily a full listen.

## Changes
- **Backend:** new `POST /api/review/{job_id}/sync-reference`
(`require_admin`).
  - Stores `state_data.sync_reference = {verified, by, at, notes}`.
- `verified: true` needs saved review output: the `file_urls` pointer,
or the direct GCS path for older jobs. Otherwise it returns 409.
Revoking is always allowed.
- **`correction-data`** returns `sync_reference`, so a re-review shows
the existing mark and can revoke it.
- **Frontend:**
- The review modal shows the checkbox plus an optional notes field, to
admins only.
- The modal passes the mark to `onSubmit`. `LyricsAnalyzer` saves it
**after** `submitCorrections` succeeds, so a mark can't sit on unsaved
timing. A failure shows a toast and never blocks the review.
- Once the box is touched, its current state is always sent, so it can
be revoked.
- **i18n:** 4 new strings × 33 locales.
- **Docs:** API.md. Version 0.290.0.

## Testing
- Backend: `test_review_sync_reference.py` (admin store, notes trim,
404, 422, 403 non-admin, 409 without review, direct-path fallback).
Related review suites pass (29).
- Frontend: `ReviewChangesModal.syncReference.test.tsx` (hidden for
non-admin, tick passes the mark, untick sends nothing, saved mark
pre-ticks and revokes, touched-then-unticked sends `false`). The modal
suites pass (29). tsc shows no new errors (21 pre-existing test-file
errors, the same on main).
- **CodeRabbit:** ran locally for 3 cycles and fixed 6 findings. One was
left by design: a pre-ticked mark on an edited re-review is visible in
the modal Andrew confirms, so submitting re-affirms it. The only user is
Andrew.

@coderabbitai ignore

🤖 Generated with [Claude Code](https://claude.com/claude-code)

https://claude.ai/code/session_012RYLVVVPsvPbXFhRYY5VSJ

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-02 20:17:41 +00:00

5187 lines
168 KiB
TypeScript

/**
* API client for karaoke-gen backend
*/
import type { VideoThemeSummary, VideoThemeDetail, ThemesListResponse, ThemeDetailResponse, ColorOverrides } from './video-themes';
import type { MagicLinkResponse, VerifyMagicLinkResponse, UserProfileResponse, ReferralInterstitial, ReferralDashboard, ReferralLink, VanityRequest, BoardResponse, SubmitRequestResponse, SongRequestPublic, DailyVoteStatus, ClaimWelcomeCreditResponse, DeletionPreview } from './types';
import type { CorrectionData, CorrectionAnnotation, EditLog, SearchLyricsResponse, AddLyricsResult } from './lyrics-review/types';
import {
beginRequest,
endRequest,
configureHealthProbe,
configurePrewarm,
markBackendReachable,
} from './backend-status';
import { ApiError } from './api-error';
import { isLocalPage, localApiOverride } from './local-host';
import { putFileToSignedUrl, uploadFilesToSignedUrls, type UploadProgress } from './upload';
// In development, use relative URLs to go through Next.js proxy (avoids CORS)
// In production (static export), use the full backend URL
// For local mode (localhost, 127.0.0.1, or the Android emulator's 10.0.2.2), use relative URLs.
// Every client that builds API URLs (lib/api/*) must use API_BASE_URL, so a local page never
// sends its bearer token to production.
export const API_BASE_URL = isLocalPage()
? localApiOverride(location.search) || ('' /* Relative URL - goes to the local server */)
: (process.env.NEXT_PUBLIC_API_URL || 'https://api.nomadkaraoke.com');
// Token management - stored in localStorage (client-side only)
// Always read fresh from localStorage to avoid stale cached values
// during Next.js module caching or hydration edge cases
export function setAccessToken(token: string) {
if (typeof window !== 'undefined') {
localStorage.setItem('karaoke_access_token', token);
}
}
export function getAccessToken(): string | null {
if (typeof window !== 'undefined') {
return localStorage.getItem('karaoke_access_token');
}
return null;
}
export function clearAccessToken() {
if (typeof window !== 'undefined') {
localStorage.removeItem('karaoke_access_token');
}
}
function getLocaleFromPath(): string {
if (typeof window === 'undefined') return 'en';
const match = window.location.pathname.match(/^\/([a-z]{2})\//);
if (match) {
const knownLocales = [
'en', 'es', 'de', 'pt', 'fr', 'ja', 'ko', 'zh', 'it', 'nl',
'pl', 'tr', 'ru', 'th', 'id', 'vi', 'tl', 'hi', 'ar', 'sv',
'nb', 'da', 'fi', 'cs', 'ro', 'hu', 'el', 'he', 'ms', 'uk',
'hr', 'sk', 'ca',
];
if (knownLocales.includes(match[1])) {
return match[1];
}
}
return 'en';
}
/**
* Resolve the current white-label tenant id, if any.
*
* On tenant portals the Cloudflare Pages edge function (frontend/functions/[[path]].ts)
* injects `window.__TENANT_CONFIG__` into the HTML before any app JS runs, and the
* tenant store (lib/tenant.ts) mirrors the same shape there in dev/preview. Reading it
* directly here keeps api.ts free of an import cycle with tenant.ts (which imports
* API_BASE_URL from this module).
*
* Returns null on the consumer build / consumer domain, so no tenant header is sent and
* existing consumer behavior is unchanged.
*/
export function getTenantId(): string | null {
if (typeof window === 'undefined') return null;
const injected = (window as { __TENANT_CONFIG__?: { tenant?: { id?: string } | null } }).__TENANT_CONFIG__;
const id = injected?.tenant?.id;
return typeof id === 'string' && id ? id : null;
}
/**
* Base headers attached to every API request: locale, and the X-Tenant-ID header when
* on a white-label tenant portal. The shared backend (api.nomadkaraoke.com) cannot infer
* the tenant from the Host (it's not the tenant subdomain) or from the prod-disabled
* `?tenant=` query param, so this header is the primary tenant-detection signal that lets
* the backend apply tenant config (locked theme, Dropbox path, no YouTube/GDrive).
*/
function getBaseHeaders(): Record<string, string> {
const headers: Record<string, string> = {
'Accept-Language': getLocaleFromPath(),
};
const tenantId = getTenantId();
if (tenantId) {
headers['X-Tenant-ID'] = tenantId;
}
return headers;
}
function getAuthHeaders(): HeadersInit {
const headers: Record<string, string> = getBaseHeaders();
const token = getAccessToken();
if (token) {
headers['Authorization'] = `Bearer ${token}`;
}
return headers;
}
export interface Job {
job_id: string;
status: string;
progress: number;
created_at: string;
updated_at: string;
url?: string;
artist?: string;
title?: string;
/** Audio-editor tempo change (0.9 = 90% speed); when set, title carries a "(90% Tempo)" label. */
tempo_factor?: number | null;
filename?: string;
error_message?: string;
error_details?: Record<string, any>;
file_urls?: Record<string, any>;
state_data?: Record<string, any>;
timeline?: Array<{
status: string;
timestamp: string;
progress?: number;
message?: string;
}>;
review_token?: string;
instrumental_token?: string;
audio_hash?: string;
non_interactive?: boolean;
is_private?: boolean;
user_email?: string;
outputs_deleted_at?: string;
outputs_deleted_by?: string;
/** Storage retention archived the big video files (720p + packages kept); "Regenerate video" rebuilds them. */
renders_purged_at?: string | null;
/** Storage retention archived the separated stems (re-separated on demand). */
stems_purged_at?: string | null;
finalise_only?: boolean;
prep_only?: boolean;
edit_count?: number;
existing_instrumental_gcs_path?: string;
// Audio search fields
audio_search_artist?: string;
audio_search_title?: string;
// Audio source tracking
audio_source_type?: string;
source_name?: string;
source_id?: string;
target_file?: string;
download_url?: string;
// Theme and branding
theme_id?: string;
brand_prefix?: string;
// Translated lyrics: language code shown beneath the synced lyrics (null/absent = off)
translation_language?: string | null;
// Customer order fields
customer_email?: string;
made_for_you?: boolean;
// UI language the job was submitted in (admin-only signal, any of 33 locales)
locale?: string;
// IP at job creation (admin-only; used to derive country)
creation_ip?: string;
// Request tracking metadata
request_metadata?: Record<string, any>;
}
export interface UploadJobResponse {
status: string;
job_id: string;
message: string;
filename?: string;
style_assets_uploaded?: string[];
server_version?: string;
distribution_services?: Record<string, any>;
}
export interface EditTrackResponse {
status: string;
job_id: string;
message: string;
review_url: string;
review_token: string;
metadata_updated: boolean;
cleanup_results: Record<string, any>;
}
export interface InstrumentalOption {
id: string;
label: string;
audio_url: string;
duration_seconds?: number;
}
export interface InstrumentalOptionsResponse {
options: InstrumentalOption[];
status: string;
artist?: string;
title?: string;
}
/** GET /api/review/{jobId}/instrumental-urls — stems + separation status for the review page. */
export interface InstrumentalState {
instrumental_options: InstrumentalOption[];
/** Separation finished (stems, review OGGs and backing analysis all written). */
audio_complete?: boolean;
job_status?: string;
backing_vocals_analysis?: CorrectionData['backing_vocals_analysis'];
auto_approval?: CorrectionData['auto_approval'];
}
// Instrumental Review Types
export interface MuteRegion {
start_seconds: number;
end_seconds: number;
}
export interface AudibleSegment {
start_seconds: number;
end_seconds: number;
confidence?: number;
}
export interface BackingVocalAnalysis {
audible_segments: AudibleSegment[];
audible_percentage: number;
recommended_selection: 'clean' | 'with_backing';
}
export interface InstrumentalAnalysis {
job_id?: string;
artist?: string;
title?: string;
duration_seconds?: number;
analysis: BackingVocalAnalysis;
audio_urls: {
clean?: string;
with_backing?: string;
backing_vocals?: string;
original?: string;
custom?: string;
uploaded?: string;
};
has_uploaded_instrumental?: boolean;
has_original?: boolean;
}
export interface WaveformData {
amplitudes: number[];
duration_seconds?: number;
duration?: number; // Legacy field name
sample_rate?: number;
}
export interface AudioEditEntry {
edit_id: string;
operation: string;
params: Record<string, unknown>;
duration_before: number;
duration_after: number;
timestamp: string;
}
export interface AudioEditInfo {
job_id: string;
artist?: string;
title?: string;
original_duration_seconds: number;
current_duration_seconds: number;
original_audio_url: string;
current_audio_url: string;
waveform_data: { amplitudes: number[] };
original_waveform_data: { amplitudes: number[] };
edit_stack: AudioEditEntry[];
can_undo: boolean;
can_redo: boolean;
}
export interface AudioEditSessionSummary {
total_operations: number;
operations_breakdown: Record<string, number>;
duration_change_seconds: number;
net_duration_seconds: number;
}
export interface AudioEditSessionMeta {
session_id: string;
job_id: string;
user_email?: string;
edit_count: number;
trigger: string;
summary?: AudioEditSessionSummary;
created_at: string;
updated_at: string;
}
export interface AudioEditSessionWithData extends AudioEditSessionMeta {
edit_data?: {
entries: AudioEditEntry[];
[key: string]: unknown;
};
}
export interface AudioEditResponse {
status: string;
edit_id?: string;
operation?: string;
duration_before: number;
duration_after: number;
current_audio_url: string;
waveform_data: { amplitudes: number[] };
edit_stack: AudioEditEntry[];
can_undo: boolean;
can_redo: boolean;
}
// 'auto' (C1 per-screen skip): the client skipped the instrumental screen because
// the backing decision was confidently auto-resolved; the backend resolves 'auto'
// to a concrete selection from the stored verdict.
export type InstrumentalSelectionType = 'clean' | 'with_backing' | 'custom' | 'uploaded' | 'original' | 'auto';
export interface DownloadUrlsResponse {
job_id: string;
artist?: string;
title?: string;
download_urls: Record<string, any>;
}
export interface AudioSearchResult {
index: number;
title: string;
artist: string;
provider: string;
url?: string;
duration?: number;
quality?: string;
source_id?: string;
seeders?: number;
is_lossless?: boolean;
year?: number;
album?: string;
// Additional fields from CLI
category?: string;
release_type?: string;
label?: string;
size_mb?: number;
filename?: string;
views?: number;
bitrate?: number;
}
export interface AudioSearchResponse {
status: string;
job_id: string;
results: AudioSearchResult[];
total_results: number;
results_count?: number;
// Present on GET /results and POST /research — the job's current search terms.
artist?: string;
title?: string;
message?: string;
}
export interface JobLog {
timestamp: string;
level: string;
message: string;
details?: Record<string, any>;
}
export interface EncodingWorkerHealth {
available: boolean;
status: string; // 'ok' | 'offline' | 'not_configured'
version?: string | null;
active_jobs?: number;
queue_length?: number;
error?: string;
}
export interface FlacfetchHealth {
available: boolean;
status: string; // 'ok' | 'offline' | 'not_configured'
version?: string | null;
error?: string;
}
export interface AudioSeparatorHealth {
available: boolean;
status: string; // 'ok' | 'offline' | 'not_configured'
version?: string | null;
error?: string;
}
export interface ServiceStatus {
status: string; // 'ok' | 'offline'
version?: string | null;
deployed_at?: string | null;
commit_sha?: string | null;
pr_number?: string | null;
pr_title?: string | null;
active_jobs?: number;
admin_details?: {
// Encoder blue-green
primary_vm?: string;
primary_ip?: string;
primary_version?: string;
primary_deployed_at?: string;
secondary_vm?: string;
secondary_ip?: string;
secondary_version?: string;
secondary_deployed_at?: string;
last_swap_at?: string;
deploy_in_progress?: boolean;
active_jobs?: number;
queue_length?: number;
// Currently-serving worker (fallback-aware). When a capacity stockout
// routes off the c4d primary pair, these point at the live fallback VM.
active_vm?: string;
active_zone?: string;
active_machine_type?: string;
on_fallback?: boolean;
// Error details for offline services
error?: string | null;
};
}
export interface SystemStatus {
services: {
frontend: ServiceStatus;
backend: ServiceStatus;
encoder: ServiceStatus;
flacfetch: ServiceStatus;
separator: ServiceStatus;
};
}
// Signed URL upload types
export interface SignedUploadUrl {
file_type: string;
gcs_path: string;
upload_url: string;
content_type: string;
/** True when upload_url is a GCS resumable session URI (chunked, resumable). */
resumable?: boolean;
}
export interface CreateJobWithUploadUrlsResponse {
status: string;
job_id: string;
message: string;
upload_urls: SignedUploadUrl[];
server_version: string;
}
export interface BulkProposedRow {
artist: string;
title: string;
mixed_filename: string;
instrumental_filename: string;
confidence: 'high' | 'medium' | 'low' | string;
warning: string | null;
/** Tenant catalogue code parsed from the filename (e.g. "VS6588"), if any. */
track_code?: string | null;
}
export interface BulkUnpairedFile {
filename: string;
reason: string;
artist: string | null;
title: string | null;
role: 'mixed' | 'instrumental' | null;
}
export interface BulkIgnoredFile {
filename: string;
reason: string;
}
export interface BulkAnalyzeResponse {
rows: BulkProposedRow[];
unpaired: BulkUnpairedFile[];
ignored: BulkIgnoredFile[];
}
export type { UploadProgress } from './upload';
/**
* Thrown when we couldn't get any answer from our own backend — the request failed
* at the network/edge level (connection refused, timeout, or a Cloudflare 5xx),
* rather than the backend deliberately returning an error. Distinct from a normal
* ApiError (which means the backend WAS reached and replied with a 4xx/5xx). The
* app-wide <BackendStatusBanner> reacts to this via the backend-status store; pages
* can also detect it with `err instanceof BackendUnavailableError`.
*
* This is the client-side manifestation of a min-instance recycle blip — see
* lib/backend-status.ts and infrastructure/modules/monitoring.py.
*/
export class BackendUnavailableError extends ApiError {
readonly isBackendUnavailable = true;
readonly cause?: unknown;
constructor(cause?: unknown, status = 503) {
super('The server is temporarily unavailable. Please try again in a moment.', status);
this.name = 'BackendUnavailableError';
this.cause = cause;
}
}
// ===== Backend connectivity: timeout + safe retry wrapper =====
//
// Every `api.*` call goes through apiFetch instead of raw fetch so that a transient
// backend blip (e.g. Cloud Run recycling its single min-instance) degrades gracefully:
// transparent retries for idempotent reads, and — via the backend-status store — a
// single app-wide banner that only appears once a read has genuinely STALLED (been
// outstanding past the store's threshold), never merely because a request was slow.
// See lib/backend-status.ts for how the banner is derived from in-flight GETs.
/** Hard backstop: abort a request that has hung this long (Cloud Run holds requests
* during a cold start, but not forever). Generous so genuine cold-starts can ride
* out and still succeed rather than erroring the user. */
const HARD_TIMEOUT_MS = 45_000;
/** Max attempts for idempotent GETs (initial + retries). Non-GET is never retried. */
const GET_MAX_ATTEMPTS = 3;
/** Backoff between GET retries (ms), indexed by prior-attempt number. */
const RETRY_BACKOFF_MS = [600, 1500];
/** Backoff for network-level failures (fetch rejected). A cross-origin request
* blocked by Cloudflare's rate limit surfaces as an opaque network error (its
* block page has no CORS headers), and the mitigation window is 10s — quick
* 0.6/1.5s retries all land inside the block AND add fuel to the count. Space
* the retries so the last attempt can land after a block window has expired. */
const NETWORK_RETRY_BACKOFF_MS = [2_000, 9_000];
/** Edge/origin status codes that mean "backend briefly unreachable", not a real
* application error: standard 502/503/504 plus Cloudflare's origin-reachability
* 52x, and 429 (edge rate-limit block, when the response is readable). */
const TRANSIENT_STATUS = new Set([429, 502, 503, 504, 520, 521, 522, 523, 524]);
/** Wait before retrying a 429: at least the edge mitigation window. */
const RATE_LIMITED_RETRY_MS = 10_500;
const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
/** How long the reachability probe gets before we treat the backend as unreachable.
* During a recycle the origin HANGS (rather than erroring), so the probe must race
* its own timer — fetch abort support can't be relied on to settle the promise. */
const HEALTH_PROBE_TIMEOUT_MS = 4_000;
// Confirm-before-banner probe: a stalled GET only surfaces the connectivity banner
// once this probe says the backend is genuinely unreachable (see backend-status.ts).
// /api/health is unauthenticated and returns instantly, so a legitimately slow read
// (first-time instrumental-analysis / lyrics-review transcoding) never false-fires.
/** Exported so tests can re-register the real probe to reset its cached verdict. */
export function __backendHealthProbe(): Promise<boolean> {
const controller = new AbortController();
return Promise.race([
globalThis
.fetch(`${API_BASE_URL}/api/health`, { cache: 'no-store', signal: controller.signal })
.then((res) => res.ok)
.catch(() => false),
sleep(HEALTH_PROBE_TIMEOUT_MS).then(() => {
controller.abort();
return false;
}),
]);
}
configureHealthProbe(__backendHealthProbe);
// Cold-start pre-warm (see prewarmBackend in backend-status.ts): an untracked,
// fire-and-forget GET /api/health so a scaled-to-zero backend starts booting while
// the user is still reading the page. Deliberately NOT time-boxed: aborting it
// would gain nothing, and letting it complete is how we learn the backend is up.
// A plain GET with no custom headers, so it never needs a CORS preflight.
/** Exported for tests. */
export function __backendPrewarm(): Promise<boolean> {
return globalThis
.fetch(`${API_BASE_URL}/api/health`, { cache: 'no-store', keepalive: true })
.then((res) => res.ok)
.catch(() => false);
}
configurePrewarm(__backendPrewarm);
/** True only for calls to our own backend API — GCS signed-URL uploads and any other
* third-party host pass straight through apiFetch untouched (no timeout/retry/status).
* Resolves relative URLs and Request inputs (whose `.url` is always absolute) against
* the current origin, then matches on `/api/*` path + backend origin. */
function isManagedBackendUrl(input: RequestInfo | URL): boolean {
const urlStr =
typeof input === 'string' ? input : input instanceof URL ? input.toString() : input.url;
const base =
typeof window !== 'undefined' ? window.location.href : 'http://localhost';
let parsed: URL;
try {
parsed = new URL(urlStr, base);
} catch {
return false;
}
const isApiPath = parsed.pathname === '/api' || parsed.pathname.startsWith('/api/');
if (!isApiPath) return false;
if (API_BASE_URL) {
// Absolute backend URL (production): must target the configured backend origin.
try {
return parsed.origin === new URL(API_BASE_URL).origin;
} catch {
return false;
}
}
// Relative / same-origin proxy (local dev): our own origin owns /api/*.
return typeof window === 'undefined' || parsed.origin === window.location.origin;
}
export interface ApiFetchOptions {
/** Override the per-attempt hard-timeout (ms). By default only GETs get a timeout
* (a backstop for hung reads); non-GETs run untimed. Set explicitly to time-box a
* POST, or pass a larger value for a slow read. */
timeoutMs?: number;
/** Force-disable retry even for GET (e.g. a GET with side effects). */
retry?: boolean;
/** Opt a GET out of connectivity-banner tracking — for reads that are inherently
* slow (large payloads, server-side work) and should never surface the banner. */
trackConnectivity?: boolean;
}
/**
* Drop-in replacement for `fetch` for backend calls: a hard-timeout backstop, safe
* retries for GETs, and — for GETs only — connectivity tracking so the app-wide
* banner can surface when a read STALLS (see lib/backend-status.ts). Signature matches
* fetch so call sites only change the function name.
*/
export async function apiFetch(
input: RequestInfo | URL,
init?: RequestInit,
opts?: ApiFetchOptions,
): Promise<Response> {
// Not our backend (e.g. a GCS signed-URL PUT) → passthrough, no side effects.
if (!isManagedBackendUrl(input)) {
return globalThis.fetch(input, init);
}
// The method/signal can arrive either on `init` or on a `Request` input. Read
// both so a POST Request isn't mis-read as a retryable GET and its abort signal
// isn't dropped.
const request =
typeof Request !== 'undefined' && input instanceof Request ? input : undefined;
const method = (init?.method ?? request?.method ?? 'GET').toUpperCase();
const isGet = method === 'GET';
// Never auto-retry non-GET: replaying a create/submit/payment could double-charge
// or duplicate a job. Reads are idempotent and safe to retry.
const allowRetry = isGet && (opts?.retry ?? true);
// Only reads get an artificial hard-timeout backstop; long-running POSTs (preview
// video, generate, search) must run as long as they need or they'd fail mid-encode.
// A caller can still explicitly time-box any request via opts.timeoutMs.
const hardTimeout = opts?.timeoutMs ?? (isGet ? HARD_TIMEOUT_MS : undefined);
const maxAttempts = allowRetry ? GET_MAX_ATTEMPTS : 1;
const callerSignal = init?.signal ?? request?.signal ?? undefined;
// Only reads feed the connectivity banner: a page waits on GETs during a recycle,
// whereas long POSTs (search, generate, auto-correct) are legitimately slow and
// must never trip it. Tracking spans the whole call (across retries) and settles in
// `finally`, so the banner reflects how long the read has actually been stalled.
const track = isGet && (opts?.trackConnectivity ?? true);
const trackingId = track ? beginRequest() : null;
try {
let lastError: unknown;
for (let attempt = 1; attempt <= maxAttempts; attempt++) {
const controller = new AbortController();
const hardTimer =
hardTimeout != null
? setTimeout(
() => controller.abort(new DOMException('Request timed out', 'AbortError')),
hardTimeout,
)
: null;
const onCallerAbort = () =>
controller.abort((callerSignal as AbortSignal | undefined)?.reason);
if (callerSignal) {
if (callerSignal.aborted) controller.abort(callerSignal.reason);
else callerSignal.addEventListener('abort', onCallerAbort, { once: true });
}
const cleanup = () => {
if (hardTimer) clearTimeout(hardTimer);
callerSignal?.removeEventListener('abort', onCallerAbort);
};
let response: Response;
try {
response = await globalThis.fetch(input, { ...init, signal: controller.signal });
} catch (err) {
cleanup();
// The CALLER aborted (navigation, their own timeout) — not a backend problem.
if (callerSignal?.aborted) throw err;
lastError = err;
if (attempt < maxAttempts) {
await sleep(NETWORK_RETRY_BACKOFF_MS[Math.min(attempt - 1, NETWORK_RETRY_BACKOFF_MS.length - 1)]);
continue;
}
throw new BackendUnavailableError(err);
}
cleanup();
if (!TRANSIENT_STATUS.has(response.status)) {
// The backend answered (even a 4xx is proof it's up) — this is what lets
// the status store tell a later stall (recycle) from a cold start.
markBackendReachable();
}
if (TRANSIENT_STATUS.has(response.status)) {
if (allowRetry && attempt < maxAttempts) {
if (response.status === 429) {
// Rate-limited at the edge: honor Retry-After when present, else
// wait out the full mitigation window — retrying sooner both fails
// and prolongs the block.
const retryAfterS = Number(response.headers.get('retry-after'));
await sleep(
Number.isFinite(retryAfterS) && retryAfterS > 0
? retryAfterS * 1000 + 500
: RATE_LIMITED_RETRY_MS,
);
} else {
await sleep(RETRY_BACKOFF_MS[Math.min(attempt - 1, RETRY_BACKOFF_MS.length - 1)]);
}
continue;
}
if (isGet) {
throw new BackendUnavailableError(undefined, response.status);
}
// Non-GET: hand the real transient response back so the caller's handleResponse
// surfaces it.
return response;
}
return response;
}
// Unreachable (loop always returns or throws) — satisfies the compiler.
throw new BackendUnavailableError(lastError);
} finally {
if (trackingId !== null) endRequest(trackingId);
}
}
// Exported for testing
export function extractErrorMessage(data: any, fallback: string): string {
// Handle various error response formats
if (typeof data?.detail === 'string') return data.detail;
if (typeof data?.message === 'string') return data.message;
if (typeof data?.error === 'string') return data.error;
// Handle nested error objects
if (data?.detail?.message) return String(data.detail.message);
if (data?.detail?.error) return String(data.detail.error);
// If detail is an object, try to stringify it meaningfully
if (data?.detail && typeof data.detail === 'object') {
try {
return JSON.stringify(data.detail);
} catch {
return fallback;
}
}
return fallback;
}
// ===== Bulk Mode types =====
export interface BulkArtist {
mbid: string | null;
name: string;
disambiguation: string;
type?: string | null;
country?: string | null;
/** Set when only a MusicBrainz alias matched the query (e.g. "Hikaru Utada"). */
alias?: string | null;
}
export interface BulkAlbum {
release_group_mbid: string;
title: string;
primary_type?: string | null;
secondary_types: string[];
first_release_date: string;
is_studio: boolean;
}
export interface BulkEdition {
release_mbid: string;
title?: string | null;
status?: string | null;
date: string;
country?: string | null;
track_count: number;
}
/** An existing community karaoke version the user can preview on YouTube. */
export interface CommunityVersion {
brand: string;
url: string;
}
/** A distinct tracklist variant (country pressings collapsed by track count). */
export interface BulkEditionVariant {
representative_release_mbid: string;
label: string; // "Original" | "Reissue"
track_count: number;
year: string;
pressing_count: number;
delta_vs_original: number;
}
export interface BulkTrack {
position: number | null;
title: string;
recording_mbid?: string | null;
length_ms?: number | null;
is_extra: boolean;
extra_reason: string;
available: boolean;
brands: string[];
versions: CommunityVersion[];
}
/** The album an album-mode batch came from; the backend searches it once for the whole batch. */
export interface BulkAlbumRef {
artist: string;
title: string;
release_group_mbid?: string | null;
release_mbid?: string | null;
}
export interface BulkTracklist {
release_mbid: string | null;
canonical_release_mbid: string | null;
selected_variant_mbid: string | null;
title: string | null;
date: string;
tracks: BulkTrack[];
editions: BulkEdition[];
variants: BulkEditionVariant[];
}
export interface BulkAvailabilityResult {
artist: string;
title: string;
available: boolean;
brands: string[];
brand_count: number;
versions: CommunityVersion[];
}
export interface BulkSettings {
auto_select_if_lossless: boolean;
is_private: boolean;
skip_audio_edit: boolean;
skip_customization: boolean;
}
export interface BulkSubmitResponse {
batch_id: string;
job_ids: string[];
total: number;
}
export interface BulkBatchJob {
job_id: string;
artist: string;
title: string;
status: string;
auto_selected: boolean;
}
export interface BulkBatch {
batch_id: string;
total: number;
counts: Record<string, number>;
jobs: BulkBatchJob[];
}
async function handleResponse<T>(response: Response): Promise<T> {
if (!response.ok) {
let data;
try {
data = await response.json();
} catch {
data = { detail: response.statusText };
}
throw new ApiError(
extractErrorMessage(data, `Request failed with status ${response.status}`),
response.status,
data
);
}
return response.json();
}
// --- Catalog types (song/artist autocomplete + community check) ---
export interface CatalogArtistResult {
name: string;
mbid?: string;
disambiguation?: string;
artist_type?: string;
spotify_id?: string;
popularity?: number;
genres?: string[];
tags?: string[];
}
export interface CatalogTrackResult {
track_name: string;
artist_name: string;
track_id?: string;
artist_id?: string;
popularity?: number;
duration_ms?: number;
explicit?: boolean;
}
export interface CommunityTrack {
brand_name: string;
brand_code: string;
youtube_url: string;
is_community: boolean;
}
export interface CommunityCheckSong {
title: string;
artist: string;
community_tracks: CommunityTrack[];
}
export interface CommunityCheckResponse {
has_community: boolean;
songs: CommunityCheckSong[];
best_youtube_url: string | null;
}
export type MatchJudgeKind = 'cosmetic' | 'content' | 'ambiguous' | 'none';
export interface MatchJudgeVerdict {
kind: MatchJudgeKind;
confident: boolean;
canonical_artist: string;
canonical_title: string;
alternatives: { artist: string; title: string }[];
engine: 'deterministic' | 'catalog' | 'ai';
reason: string;
// Set by a "fast" (catalog-only) pass that couldn't decide — the client should
// follow up with a "full" call once the audio confidence tier is known.
needs_ai: boolean;
}
export type MatchJudgeStage = 'fast' | 'full';
export interface MatchJudgeOptions {
stage?: MatchJudgeStage;
audioConfidenceTier?: number;
}
export const api = {
/**
* List all jobs
*/
async listJobs(params?: {
status?: string;
limit?: number;
exclude_test?: boolean;
fields?: 'summary';
hide_completed?: boolean;
search?: string;
}): Promise<Job[]> {
const searchParams = new URLSearchParams();
if (params?.status) searchParams.set('status', params.status);
if (params?.limit) searchParams.set('limit', String(params.limit));
if (params?.exclude_test !== undefined) searchParams.set('exclude_test', String(params.exclude_test));
if (params?.fields) searchParams.set('fields', params.fields);
if (params?.hide_completed !== undefined) searchParams.set('hide_completed', String(params.hide_completed));
if (params?.search) searchParams.set('search', params.search);
const url = `${API_BASE_URL}/api/jobs${searchParams.toString() ? '?' + searchParams.toString() : ''}`;
const response = await apiFetch(url, {
headers: getAuthHeaders()
});
return handleResponse<Job[]>(response);
},
/**
* Get a single job by ID
*/
async getJob(jobId: string): Promise<Job> {
const response = await apiFetch(`${API_BASE_URL}/api/jobs/${jobId}`, {
headers: getAuthHeaders()
});
return handleResponse<Job>(response);
},
/**
* Upload a file and create a new job
*/
async uploadJob(
file: File,
artist: string,
title: string,
options?: {
enable_cdg?: boolean;
enable_txt?: boolean;
brand_prefix?: string;
enable_youtube_upload?: boolean;
theme_id?: string;
color_overrides?: ColorOverrides;
non_interactive?: boolean;
is_private?: boolean;
requires_audio_edit?: boolean;
review_mode?: string;
backing_preference?: string;
/** UI locale code to show an AI translation of each lyric line beneath the lyrics. Omit = off. */
translation_language?: string;
}
): Promise<UploadJobResponse> {
const formData = new FormData();
formData.append('file', file);
formData.append('artist', artist);
formData.append('title', title);
if (options?.enable_cdg !== undefined) {
formData.append('enable_cdg', String(options.enable_cdg));
}
if (options?.enable_txt !== undefined) {
formData.append('enable_txt', String(options.enable_txt));
}
if (options?.brand_prefix) {
formData.append('brand_prefix', options.brand_prefix);
}
if (options?.enable_youtube_upload !== undefined) {
formData.append('enable_youtube_upload', String(options.enable_youtube_upload));
}
if (options?.theme_id) {
formData.append('theme_id', options.theme_id);
}
if (options?.color_overrides) {
formData.append('color_overrides', JSON.stringify(options.color_overrides));
}
if (options?.non_interactive !== undefined) {
formData.append('non_interactive', String(options.non_interactive));
}
if (options?.is_private !== undefined) {
formData.append('is_private', String(options.is_private));
}
if (options?.requires_audio_edit) {
formData.append('requires_audio_edit', String(options.requires_audio_edit));
}
if (options?.review_mode) {
formData.append('review_mode', options.review_mode);
}
if (options?.backing_preference) {
formData.append('backing_preference', options.backing_preference);
}
if (options?.translation_language) {
formData.append('translation_language', options.translation_language);
}
const response = await apiFetch(`${API_BASE_URL}/api/jobs/upload`, {
method: 'POST',
headers: getAuthHeaders(),
body: formData,
});
return handleResponse<UploadJobResponse>(response);
},
/**
* Create a job and get signed URLs for direct GCS upload.
* Used for large files that exceed Cloud Run's 32MB body limit.
*/
async createJobWithUploadUrls(
artist: string,
title: string,
files: Array<{ filename: string; content_type: string; file_type: string }>,
options?: {
is_private?: boolean;
existing_instrumental?: boolean;
requires_audio_edit?: boolean;
batch_id?: string;
/** "resumable" → backend returns GCS resumable session URIs instead of signed PUT URLs. */
upload_mode?: 'signed_put' | 'resumable';
review_mode?: string;
backing_preference?: string;
/** UI locale code to show an AI translation of each lyric line beneath the lyrics. Omit = off. */
translation_language?: string;
/** Tenant portals only: the tenant's own catalogue code, used to prefix every output file. */
track_code?: string;
}
): Promise<CreateJobWithUploadUrlsResponse> {
const body: Record<string, any> = { artist, title, files };
if (options?.is_private !== undefined) body.is_private = options.is_private;
if (options?.existing_instrumental !== undefined) body.existing_instrumental = options.existing_instrumental;
if (options?.requires_audio_edit) body.requires_audio_edit = options.requires_audio_edit;
if (options?.batch_id) body.batch_id = options.batch_id;
if (options?.upload_mode) body.upload_mode = options.upload_mode;
if (options?.review_mode) body.review_mode = options.review_mode;
if (options?.backing_preference) body.backing_preference = options.backing_preference;
if (options?.translation_language) body.translation_language = options.translation_language;
if (options?.track_code) body.track_code = options.track_code;
const response = await apiFetch(`${API_BASE_URL}/api/jobs/create-with-upload-urls`, {
method: 'POST',
headers: {
...getAuthHeaders(),
'Content-Type': 'application/json',
},
body: JSON.stringify(body),
});
return handleResponse<CreateJobWithUploadUrlsResponse>(response);
},
/**
* Upload a file directly to a GCS signed URL, with progress.
*/
uploadToSignedUrl(
signedUrl: string,
file: File,
contentType: string,
onProgress?: (loaded: number, total: number) => void,
): Promise<void> {
return putFileToSignedUrl(signedUrl, file, contentType, onProgress);
},
/**
* Mark uploads as complete so the backend starts processing.
*/
async completeJobUpload(
jobId: string,
uploadedFileTypes: string[],
): Promise<{ status: string; message: string }> {
const url = `${API_BASE_URL}/api/jobs/${jobId}/uploads-complete`;
const init: RequestInit = {
method: 'POST',
headers: {
...getAuthHeaders(),
'Content-Type': 'application/json',
},
body: JSON.stringify({ uploaded_files: uploadedFileTypes }),
};
// Retry ONLY on network-level failures (fetch() rejects on DNS/TLS/connection
// reset/offline, never on an HTTP error status). This is the last step of the
// signed-URL submit flow: the files are already in GCS and the job stays
// PENDING until this call lands, so a transient blip here would otherwise
// strand a paid-for job at "Setting up" and show the user a generic error.
// Retrying lets the submit self-heal. HTTP errors (4xx/5xx) are deterministic
// and surfaced immediately via handleResponse — never retried.
const MAX_ATTEMPTS = 3;
let lastError: unknown;
for (let attempt = 1; attempt <= MAX_ATTEMPTS; attempt++) {
let response: Response;
try {
response = await apiFetch(url, init);
} catch (err) {
lastError = err;
if (attempt < MAX_ATTEMPTS) {
await new Promise((resolve) => setTimeout(resolve, 500 * attempt));
continue;
}
throw err;
}
return handleResponse<{ status: string; message: string }>(response);
}
// Unreachable: the loop either returns or throws, but satisfies the compiler.
throw lastError;
},
/**
* Tenant bulk upload: analyse a list of filenames into proposed
* Mixed/Instrumental job rows. Filenames only — no audio is uploaded here.
*/
async analyzeBulk(filenames: string[]): Promise<BulkAnalyzeResponse> {
const response = await apiFetch(`${API_BASE_URL}/api/tenant/bulk/analyze`, {
method: 'POST',
headers: {
...getAuthHeaders(),
'Content-Type': 'application/json',
},
body: JSON.stringify({ filenames }),
});
return handleResponse<BulkAnalyzeResponse>(response);
},
/**
* Create a job from the user's own audio file(s): create the job, upload the
* bytes straight to GCS (signed URLs — Cloud Run caps request bodies at 32 MiB),
* then tell the backend to start. An optional instrumental makes the job skip
* vocal separation and instrumental review entirely.
*/
async createJobFromUploadedAudio(
file: File,
artist: string,
title: string,
options?: {
is_private?: boolean;
requires_audio_edit?: boolean;
review_mode?: string;
backing_preference?: string;
/** UI locale code to show an AI translation of each lyric line beneath the lyrics. Omit = off. */
translation_language?: string;
/** Tenant portals only: the tenant's own catalogue code, used to prefix every output file. */
track_code?: string;
instrumentalFile?: File | null;
},
onProgress?: (progress: UploadProgress) => void,
): Promise<UploadJobResponse> {
const { instrumentalFile, ...createOptions } = options ?? {};
const files: Array<{ file: File; file_type: string }> = [{ file, file_type: 'audio' }];
if (instrumentalFile) files.push({ file: instrumentalFile, file_type: 'existing_instrumental' });
const totalBytes = files.reduce((sum, f) => sum + f.file.size, 0);
onProgress?.({ phase: 'creating', loaded: 0, total: totalBytes });
const createResponse = await this.createJobWithUploadUrls(
artist, title,
files.map(f => ({
filename: f.file.name,
content_type: f.file.type || 'application/octet-stream',
file_type: f.file_type,
})),
{ ...createOptions, existing_instrumental: instrumentalFile ? true : undefined },
);
try {
const targets = files.map(f => {
const entry = createResponse.upload_urls.find(u => u.file_type === f.file_type);
if (!entry) throw new ApiError(`No upload URL returned for ${f.file_type}`, 500);
return { file: f.file, url: entry.upload_url, contentType: entry.content_type };
});
await uploadFilesToSignedUrls(targets, onProgress);
} catch (err) {
// The job was created (and charged) before the bytes were sent. Cancel it
// (refunds the credit) so a retry isn't blocked and nothing is left
// stranded at "Waiting for upload". Best-effort: the stale-upload sweep
// is the backstop.
await this.cancelJob(createResponse.job_id, 'Upload did not complete').catch(() => {});
throw err;
}
onProgress?.({ phase: 'finalizing', loaded: totalBytes, total: totalBytes });
await this.completeJobUpload(createResponse.job_id, files.map(f => f.file_type));
return {
status: 'success',
job_id: createResponse.job_id,
message: 'Job created via signed URL upload',
};
},
/**
* Create a job from a URL (YouTube, etc.)
*/
async createJobFromUrl(
url: string,
artist?: string,
title?: string,
options?: {
enable_cdg?: boolean;
enable_txt?: boolean;
brand_prefix?: string;
enable_youtube_upload?: boolean;
theme_id?: string;
color_overrides?: ColorOverrides;
non_interactive?: boolean;
is_private?: boolean;
requires_audio_edit?: boolean;
review_mode?: string;
backing_preference?: string;
/** UI locale code to show an AI translation of each lyric line beneath the lyrics. Omit = off. */
translation_language?: string;
}
): Promise<{ status: string; job_id: string; message: string }> {
const body: Record<string, any> = { url };
if (artist) body.artist = artist;
if (title) body.title = title;
if (options?.enable_cdg !== undefined) body.enable_cdg = options.enable_cdg;
if (options?.enable_txt !== undefined) body.enable_txt = options.enable_txt;
if (options?.brand_prefix) body.brand_prefix = options.brand_prefix;
if (options?.enable_youtube_upload !== undefined) body.enable_youtube_upload = options.enable_youtube_upload;
if (options?.theme_id) body.theme_id = options.theme_id;
if (options?.color_overrides) body.color_overrides = options.color_overrides;
if (options?.non_interactive !== undefined) body.non_interactive = options.non_interactive;
if (options?.is_private !== undefined) body.is_private = options.is_private;
if (options?.requires_audio_edit) body.requires_audio_edit = options.requires_audio_edit;
if (options?.review_mode) body.review_mode = options.review_mode;
if (options?.backing_preference) body.backing_preference = options.backing_preference;
if (options?.translation_language) body.translation_language = options.translation_language;
const response = await apiFetch(`${API_BASE_URL}/api/jobs/create-from-url`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
...getAuthHeaders()
},
body: JSON.stringify(body),
});
return handleResponse(response);
},
/**
* Pre-validate a URL before submitting a job. Used by the guided flow so
* unsupported links (e.g. DRM streaming services) are caught at the
* "Use this URL" step instead of only at final submit.
*/
async validateJobUrl(
url: string
): Promise<{ supported: boolean; detail: string | null }> {
const response = await apiFetch(`${API_BASE_URL}/api/jobs/validate-url`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
...getAuthHeaders()
},
body: JSON.stringify({ url }),
});
return handleResponse(response);
},
/**
* Get review data for lyrics review
*/
async getReviewData(jobId: string): Promise<{
corrections_url: string;
audio_url: string;
status: string;
artist?: string;
title?: string;
}> {
const response = await apiFetch(`${API_BASE_URL}/api/jobs/${jobId}/review-data`, {
headers: getAuthHeaders()
});
return handleResponse(response);
},
/**
* Complete the lyrics review with optional instrumental selection (combined flow)
*/
async completeReview(jobId: string, instrumentalSelection?: InstrumentalSelectionType): Promise<{ status: string; job_status: string; message: string }> {
const body = instrumentalSelection ? { instrumental_selection: instrumentalSelection } : undefined;
const response = await apiFetch(`${API_BASE_URL}/api/jobs/${jobId}/complete-review`, {
method: 'POST',
headers: body ? { 'Content-Type': 'application/json', ...getAuthHeaders() } : getAuthHeaders(),
body: body ? JSON.stringify(body) : undefined
});
return handleResponse(response);
},
/**
* Get instrumental options
*/
async getInstrumentalOptions(jobId: string): Promise<InstrumentalOptionsResponse> {
const response = await apiFetch(`${API_BASE_URL}/api/jobs/${jobId}/instrumental-options`, {
headers: getAuthHeaders()
});
return handleResponse(response);
},
/**
* Select an instrumental
*/
async selectInstrumental(
jobId: string,
selection: InstrumentalSelectionType
): Promise<{ status: string; job_status: string; selection: string; message: string }> {
const response = await apiFetch(`${API_BASE_URL}/api/jobs/${jobId}/select-instrumental`, {
method: 'POST',
headers: { 'Content-Type': 'application/json', ...getAuthHeaders() },
body: JSON.stringify({ selection }),
});
return handleResponse(response);
},
/**
* Submit audio edit (finalize and continue processing).
* For auto-processor: submits with no edits to skip the audio edit phase.
*/
/**
* Get input audio info for the audio editor.
*/
async getInputAudioInfo(jobId: string): Promise<AudioEditInfo> {
const response = await apiFetch(`${API_BASE_URL}/api/review/${jobId}/input-audio-info`, {
headers: { 'Content-Type': 'application/json', ...getAuthHeaders() },
});
return handleResponse(response);
},
/**
* Apply an audio edit operation (trim, cut, mute, join).
*/
async applyAudioEdit(jobId: string, operation: string, params: Record<string, unknown>): Promise<AudioEditResponse> {
const response = await apiFetch(`${API_BASE_URL}/api/review/${jobId}/audio-edit/apply`, {
method: 'POST',
headers: { 'Content-Type': 'application/json', ...getAuthHeaders() },
body: JSON.stringify({ operation, params }),
});
return handleResponse(response);
},
/**
* Undo the last audio edit operation.
*/
async undoAudioEdit(jobId: string): Promise<AudioEditResponse> {
const response = await apiFetch(`${API_BASE_URL}/api/review/${jobId}/audio-edit/undo`, {
method: 'POST',
headers: { 'Content-Type': 'application/json', ...getAuthHeaders() },
});
return handleResponse(response);
},
/**
* Redo a previously undone audio edit.
*/
async redoAudioEdit(jobId: string): Promise<AudioEditResponse> {
const response = await apiFetch(`${API_BASE_URL}/api/review/${jobId}/audio-edit/redo`, {
method: 'POST',
headers: { 'Content-Type': 'application/json', ...getAuthHeaders() },
});
return handleResponse(response);
},
/**
* Upload an audio file for join operations.
*/
async uploadAudioForJoin(jobId: string, file: File): Promise<{ upload_id: string; duration_seconds: number; filename: string }> {
const formData = new FormData();
formData.append('file', file);
const response = await apiFetch(`${API_BASE_URL}/api/review/${jobId}/audio-edit/upload`, {
method: 'POST',
headers: getAuthHeaders(),
body: formData,
});
return handleResponse(response);
},
async submitAudioEdit(jobId: string, editLog?: unknown): Promise<{ status: string; message: string; job_id: string }> {
const body = editLog ? { edit_log: editLog } : {};
const response = await apiFetch(`${API_BASE_URL}/api/review/${jobId}/audio-edit/submit`, {
method: 'POST',
headers: { 'Content-Type': 'application/json', ...getAuthHeaders() },
body: JSON.stringify(body),
});
return handleResponse(response);
},
/**
* Save an audio edit session snapshot.
*/
async saveAudioEditSession(
jobId: string,
data: {
edit_data: unknown;
edit_count: number;
trigger: string;
summary?: AudioEditSessionSummary;
}
): Promise<{ status: string; session_id?: string; reason?: string }> {
const response = await apiFetch(`${API_BASE_URL}/api/review/${jobId}/audio-edit-sessions`, {
method: 'POST',
headers: { 'Content-Type': 'application/json', ...getAuthHeaders() },
body: JSON.stringify(data),
});
return handleResponse(response);
},
/**
* List audio edit sessions for a job.
*/
async listAudioEditSessions(
jobId: string
): Promise<{ sessions: AudioEditSessionMeta[] }> {
const response = await apiFetch(`${API_BASE_URL}/api/review/${jobId}/audio-edit-sessions`, {
headers: getAuthHeaders(),
});
return handleResponse(response);
},
/**
* Get a single audio edit session with full edit_data.
*/
async getAudioEditSession(
jobId: string,
sessionId: string
): Promise<AudioEditSessionWithData> {
const response = await apiFetch(`${API_BASE_URL}/api/review/${jobId}/audio-edit-sessions/${sessionId}`, {
headers: getAuthHeaders(),
});
return handleResponse(response);
},
/**
* Get instrumental analysis data for review
*/
async getInstrumentalAnalysis(jobId: string): Promise<InstrumentalAnalysis> {
const response = await apiFetch(`${API_BASE_URL}/api/jobs/${jobId}/instrumental-analysis`, {
headers: getAuthHeaders()
});
return handleResponse(response);
},
/**
* Get waveform data for visualization
*/
async getWaveformData(jobId: string, numPoints: number = 1000): Promise<WaveformData> {
const response = await apiFetch(
`${API_BASE_URL}/api/jobs/${jobId}/waveform-data?num_points=${numPoints}`,
{ headers: getAuthHeaders() }
);
return handleResponse(response);
},
/**
* Upload a custom instrumental file
*/
/**
* Upload the user's own instrumental during instrumental review: signed PUT
* straight to GCS (Cloud Run caps request bodies at 32 MiB), then the backend
* validates duration, converts to FLAC and stores it as the custom stem.
*/
async uploadInstrumentalForReview(
jobId: string,
file: File,
onProgress?: (progress: UploadProgress) => void,
): Promise<{ status: string; duration_seconds: number; message: string; audio_url?: string }> {
const contentType = file.type || 'application/octet-stream';
onProgress?.({ phase: 'creating', loaded: 0, total: file.size });
const urlResponse = await apiFetch(`${API_BASE_URL}/api/jobs/${jobId}/instrumental-upload-url`, {
method: 'POST',
headers: { ...getAuthHeaders(), 'Content-Type': 'application/json' },
body: JSON.stringify({ filename: file.name, content_type: contentType }),
});
const target = await handleResponse<{ upload_url: string; gcs_path: string; content_type: string }>(urlResponse);
await uploadFilesToSignedUrls(
[{ file, url: target.upload_url, contentType: target.content_type || contentType }],
onProgress,
);
onProgress?.({ phase: 'finalizing', loaded: file.size, total: file.size });
const completeResponse = await apiFetch(`${API_BASE_URL}/api/jobs/${jobId}/instrumental-upload-complete`, {
method: 'POST',
headers: { ...getAuthHeaders(), 'Content-Type': 'application/json' },
body: JSON.stringify({ gcs_path: target.gcs_path }),
});
return handleResponse(completeResponse);
},
async uploadCustomInstrumental(jobId: string, file: File): Promise<{ status: string; duration_seconds: number; message: string; audio_url?: string }> {
const formData = new FormData();
formData.append('file', file);
const response = await apiFetch(`${API_BASE_URL}/api/jobs/${jobId}/upload-instrumental`, {
method: 'POST',
headers: getAuthHeaders(),
body: formData,
});
return handleResponse(response);
},
/**
* Create a custom instrumental with mute regions
*/
async createCustomInstrumental(jobId: string, muteRegions: MuteRegion[]): Promise<{ status: string; message: string; audio_url?: string }> {
const response = await apiFetch(`${API_BASE_URL}/api/jobs/${jobId}/create-custom-instrumental`, {
method: 'POST',
headers: { 'Content-Type': 'application/json', ...getAuthHeaders() },
body: JSON.stringify({ mute_regions: muteRegions }),
});
return handleResponse(response);
},
/**
* Get audio stream URL for a specific stem type
*/
getAudioStreamUrl(jobId: string, stemType: string): string {
const token = getAccessToken();
const base = `${API_BASE_URL}/api/jobs/${jobId}/audio-stream/${stemType}`;
return token ? `${base}?token=${encodeURIComponent(token)}` : base;
},
/**
* Get download URLs for completed job
*/
async getDownloadUrls(jobId: string): Promise<DownloadUrlsResponse> {
const response = await apiFetch(`${API_BASE_URL}/api/jobs/${jobId}/download-urls`, {
headers: getAuthHeaders()
});
return handleResponse(response);
},
/**
* Cancel a job
*/
async cancelJob(jobId: string, reason?: string): Promise<{ status: string; message: string }> {
const response = await apiFetch(`${API_BASE_URL}/api/jobs/${jobId}/cancel`, {
method: 'POST',
headers: { 'Content-Type': 'application/json', ...getAuthHeaders() },
body: JSON.stringify({ reason: reason || 'Cancelled by user' }),
});
return handleResponse(response);
},
/**
* Delete a job
*/
async deleteJob(jobId: string, deleteFiles: boolean = true): Promise<{ status: string; message: string }> {
const response = await apiFetch(
`${API_BASE_URL}/api/jobs/${jobId}?delete_files=${deleteFiles}`,
{ method: 'DELETE', headers: getAuthHeaders() }
);
return handleResponse(response);
},
/**
* Get the download URL for a file, including authentication token
*/
getDownloadUrl(jobId: string, category: string, fileKey: string): string {
const baseUrl = `${API_BASE_URL}/api/jobs/${jobId}/download/${category}/${fileKey}`;
const token = getAccessToken();
if (token) {
return `${baseUrl}?token=${encodeURIComponent(token)}`;
}
return baseUrl;
},
/**
* Search for audio by artist and title
*/
async searchAudio(
artist: string,
title: string,
autoDownload: boolean = false,
options?: {
enable_cdg?: boolean;
enable_txt?: boolean;
brand_prefix?: string;
enable_youtube_upload?: boolean;
theme_id?: string;
color_overrides?: ColorOverrides;
non_interactive?: boolean;
is_private?: boolean;
// Display overrides - if provided, these appear on title screens/filenames instead of search values
display_artist?: string;
display_title?: string;
}
): Promise<AudioSearchResponse> {
const body: Record<string, any> = { artist, title, auto_download: autoDownload };
if (options?.enable_cdg !== undefined) body.enable_cdg = options.enable_cdg;
if (options?.enable_txt !== undefined) body.enable_txt = options.enable_txt;
if (options?.brand_prefix) body.brand_prefix = options.brand_prefix;
if (options?.enable_youtube_upload !== undefined) body.enable_youtube_upload = options.enable_youtube_upload;
if (options?.theme_id) body.theme_id = options.theme_id;
if (options?.color_overrides) body.color_overrides = options.color_overrides;
if (options?.non_interactive !== undefined) body.non_interactive = options.non_interactive;
if (options?.is_private !== undefined) body.is_private = options.is_private;
// Display overrides
if (options?.display_artist) body.display_artist = options.display_artist;
if (options?.display_title) body.display_title = options.display_title;
const response = await apiFetch(`${API_BASE_URL}/api/audio-search/search`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
...getAuthHeaders()
},
body: JSON.stringify(body),
});
return handleResponse(response);
},
/**
* Search for audio WITHOUT creating a job (guided flow Step 2).
* Returns a search session ID and results.
* Use createJobFromSearch() to create the actual job.
*/
async searchStandalone(
artist: string,
title: string
): Promise<{ search_session_id: string; results: AudioSearchResult[]; results_count: number }> {
const controller = new AbortController();
const timeout = setTimeout(() => controller.abort(), 45000);
try {
const response = await apiFetch(`${API_BASE_URL}/api/audio-search/search-standalone`, {
method: 'POST',
headers: { 'Content-Type': 'application/json', ...getAuthHeaders() },
body: JSON.stringify({ artist, title }),
signal: controller.signal,
});
return handleResponse(response);
} finally {
clearTimeout(timeout);
}
},
/**
* Create a job from a standalone search session (guided flow Step 3 confirm).
* Deducts a credit and starts the download + processing pipeline.
*/
async createJobFromSearch(params: {
search_session_id: string;
selection_index: number;
artist: string;
title: string;
display_artist?: string;
display_title?: string;
is_private?: boolean;
requires_audio_edit?: boolean;
review_mode?: string;
backing_preference?: string;
/** UI locale code to show an AI translation of each lyric line beneath the lyrics. Omit = off. */
translation_language?: string;
}): Promise<{ status: string; job_id: string; message: string }> {
const response = await apiFetch(`${API_BASE_URL}/api/jobs/create-from-search`, {
method: 'POST',
headers: { 'Content-Type': 'application/json', ...getAuthHeaders() },
body: JSON.stringify(params),
});
return handleResponse(response);
},
// ===== Bulk Mode =====
async searchAlbumArtists(q: string): Promise<BulkArtist[]> {
const response = await apiFetch(`${API_BASE_URL}/api/bulk/album/artists?q=${encodeURIComponent(q)}`, {
headers: { ...getAuthHeaders() },
});
return handleResponse(response);
},
async getAlbums(artistMbid: string): Promise<BulkAlbum[]> {
const response = await apiFetch(`${API_BASE_URL}/api/bulk/album/albums?artist_mbid=${encodeURIComponent(artistMbid)}`, {
headers: { ...getAuthHeaders() },
});
return handleResponse(response);
},
async getAlbumTracklist(params: {
artist: string;
releaseGroupMbid?: string;
releaseMbid?: string;
locale?: string;
}): Promise<BulkTracklist> {
const qs = new URLSearchParams({ artist: params.artist });
if (params.releaseGroupMbid) qs.set('release_group_mbid', params.releaseGroupMbid);
if (params.releaseMbid) qs.set('release_mbid', params.releaseMbid);
if (params.locale) qs.set('locale', params.locale);
const response = await apiFetch(`${API_BASE_URL}/api/bulk/album/tracklist?${qs.toString()}`, {
headers: { ...getAuthHeaders() },
});
return handleResponse(response);
},
async checkBulkAvailability(
tracks: Array<{ artist: string; title: string }>
): Promise<{ results: BulkAvailabilityResult[] }> {
const response = await apiFetch(`${API_BASE_URL}/api/bulk/availability`, {
method: 'POST',
headers: { 'Content-Type': 'application/json', ...getAuthHeaders() },
body: JSON.stringify({ tracks }),
});
return handleResponse(response);
},
async bulkSubmit(params: {
songs: Array<{
artist: string; title: string; display_artist?: string; display_title?: string; position?: number | null
}>;
settings: BulkSettings;
album?: BulkAlbumRef;
}): Promise<BulkSubmitResponse> {
const response = await apiFetch(`${API_BASE_URL}/api/bulk/submit`, {
method: 'POST',
headers: { 'Content-Type': 'application/json', ...getAuthHeaders() },
body: JSON.stringify(params),
});
return handleResponse(response);
},
async getBulkBatch(batchId: string): Promise<BulkBatch> {
const response = await apiFetch(`${API_BASE_URL}/api/bulk/${encodeURIComponent(batchId)}`, {
headers: { ...getAuthHeaders() },
});
return handleResponse(response);
},
/**
* Get signed upload URLs for style assets on an existing job.
*/
async getStyleUploadUrls(
jobId: string,
files: Array<{ filename: string; content_type: string; file_type: string }>
): Promise<{ status: string; job_id: string; upload_urls: SignedUploadUrl[] }> {
const response = await apiFetch(`${API_BASE_URL}/api/jobs/${jobId}/style-upload-urls`, {
method: 'POST',
headers: { 'Content-Type': 'application/json', ...getAuthHeaders() },
body: JSON.stringify({ files }),
});
return handleResponse(response);
},
/**
* Upload a file directly to a GCS signed URL.
*/
async uploadFileToSignedUrl(url: string, file: File, contentType: string): Promise<void> {
return putFileToSignedUrl(url, file, contentType);
},
/**
* Finalize style asset uploads on an existing job.
*/
async completeStyleUploads(
jobId: string,
uploadedFiles: string[],
colorOverrides?: { artist_color?: string; title_color?: string }
): Promise<{ status: string; job_id: string; message: string; assets_updated: string[] }> {
const response = await apiFetch(`${API_BASE_URL}/api/jobs/${jobId}/style-uploads-complete`, {
method: 'POST',
headers: { 'Content-Type': 'application/json', ...getAuthHeaders() },
body: JSON.stringify({
uploaded_files: uploadedFiles,
color_overrides: colorOverrides,
}),
});
return handleResponse(response);
},
/**
* Get audio search results for a job
*/
async getAudioSearchResults(jobId: string): Promise<AudioSearchResponse> {
const response = await apiFetch(`${API_BASE_URL}/api/audio-search/${jobId}/results`, {
headers: getAuthHeaders()
});
return handleResponse(response);
},
/**
* Select an audio search result
*/
async selectAudioResult(
jobId: string,
index: number,
overrides?: { is_private?: boolean; display_artist?: string; display_title?: string }
): Promise<{ status: string; message: string }> {
const response = await apiFetch(`${API_BASE_URL}/api/audio-search/${jobId}/select`, {
method: 'POST',
headers: { 'Content-Type': 'application/json', ...getAuthHeaders() },
body: JSON.stringify({ selection_index: index, ...overrides }),
});
return handleResponse(response);
},
/**
* Re-run the audio search for a parked job, optionally with edited
* artist/title. Empty results are a normal 200 (no sources found), not an error.
*/
async researchAudio(
jobId: string,
edits?: { artist?: string; title?: string }
): Promise<AudioSearchResponse> {
const response = await apiFetch(`${API_BASE_URL}/api/audio-search/${jobId}/research`, {
method: 'POST',
headers: { 'Content-Type': 'application/json', ...getAuthHeaders() },
body: JSON.stringify({ artist: edits?.artist, title: edits?.title }),
});
return handleResponse(response);
},
/**
* Attach a YouTube/yt-dlp URL to a parked job and start processing.
* Manual fallback when audio search finds nothing usable.
*/
async provideUrlForJob(
jobId: string,
url: string
): Promise<{ status: string; job_id: string; message: string }> {
const response = await apiFetch(`${API_BASE_URL}/api/audio-search/${jobId}/provide-url`, {
method: 'POST',
headers: { 'Content-Type': 'application/json', ...getAuthHeaders() },
body: JSON.stringify({ url }),
});
return handleResponse(response);
},
/**
* Attach an uploaded audio file to a parked job:
* 1) request a signed upload URL, 2) PUT the file, 3) mark complete.
*/
async attachUploadToJob(jobId: string, file: File): Promise<{ status: string; message: string }> {
const contentType = file.type || 'application/octet-stream';
const signed = await apiFetch(`${API_BASE_URL}/api/audio-search/${jobId}/attach-upload-url`, {
method: 'POST',
headers: { 'Content-Type': 'application/json', ...getAuthHeaders() },
body: JSON.stringify({ filename: file.name, content_type: contentType }),
});
const { upload_url, gcs_path } = await handleResponse<{ upload_url: string; gcs_path: string }>(signed);
await this.uploadFileToSignedUrl(upload_url, file, contentType);
const done = await apiFetch(`${API_BASE_URL}/api/audio-search/${jobId}/attach-upload-complete`, {
method: 'POST',
headers: { 'Content-Type': 'application/json', ...getAuthHeaders() },
body: JSON.stringify({ gcs_path }),
});
return handleResponse(done);
},
/**
* Get job logs
*/
async getJobLogs(jobId: string, limit: number = 100): Promise<JobLog[]> {
const response = await apiFetch(`${API_BASE_URL}/api/jobs/${jobId}/logs?limit=${limit}`, {
headers: getAuthHeaders()
});
const data = await handleResponse<{ logs: JobLog[] }>(response);
return data.logs || [];
},
/**
* Retry a failed job
*/
async retryJob(
jobId: string,
options?: { keepTrying?: boolean }
): Promise<{ status: string; job_id: string; message: string }> {
const response = await apiFetch(`${API_BASE_URL}/api/jobs/${jobId}/retry`, {
method: 'POST',
headers: { ...getAuthHeaders(), 'Content-Type': 'application/json' },
body: JSON.stringify({ keep_trying: !!options?.keepTrying }),
});
return handleResponse(response);
},
/**
* Reopen audio selection for a job whose audio download failed
* (e.g. a stalled torrent) so the user can pick another source.
*/
async chooseDifferentAudio(jobId: string): Promise<{ status: string; job_id: string; job_status: string }> {
const response = await apiFetch(`${API_BASE_URL}/api/jobs/${jobId}/choose-different-audio`, {
method: 'POST',
headers: getAuthHeaders()
});
return handleResponse(response);
},
// ==========================================================================
// Theme API endpoints
// ==========================================================================
/**
* List all available video themes
*/
async listThemes(): Promise<VideoThemeSummary[]> {
const response = await apiFetch(`${API_BASE_URL}/api/themes`, {
headers: getAuthHeaders()
});
const data = await handleResponse<ThemesListResponse>(response);
return data.themes;
},
/**
* Get full details for a specific theme
*/
async getTheme(themeId: string): Promise<VideoThemeDetail> {
const response = await apiFetch(`${API_BASE_URL}/api/themes/${themeId}`, {
headers: getAuthHeaders()
});
const data = await handleResponse<ThemeDetailResponse>(response);
return data.theme;
},
/**
* Get preview URL for a theme
*/
async getThemePreview(themeId: string): Promise<string | null> {
const response = await apiFetch(`${API_BASE_URL}/api/themes/${themeId}/preview`, {
headers: getAuthHeaders()
});
const data = await handleResponse<{ preview_url: string | null }>(response);
return data.preview_url;
},
/**
* Get YouTube description template for a theme
*/
async getThemeYoutubeDescription(themeId: string): Promise<string | null> {
const response = await apiFetch(`${API_BASE_URL}/api/themes/${themeId}/youtube-description`, {
headers: getAuthHeaders()
});
const data = await handleResponse<{ description: string | null }>(response);
return data.description;
},
/**
* Get a rendered sample frame of the default theme's karaoke video showing
* the translated-lyrics row in the given language. Returns a data: URL.
*/
async getTranslationPreview(language: string): Promise<{ image: string }> {
const response = await apiFetch(
`${API_BASE_URL}/api/themes/translation-preview?language=${encodeURIComponent(language)}`,
{ headers: getAuthHeaders() }
);
return handleResponse<{ image: string }>(response);
},
// ==========================================================================
// Auth API endpoints (Magic Link)
// ==========================================================================
/**
* Send a magic link email for passwordless login
*/
async sendMagicLink(
email: string,
deviceFingerprint?: string | null,
referralCode?: string | null,
purpose?: string | null,
attribution?: Record<string, string | undefined> | null,
): Promise<MagicLinkResponse> {
const body: Record<string, unknown> = { email }
if (deviceFingerprint) {
body.device_fingerprint = deviceFingerprint
}
if (referralCode) {
body.referral_code = referralCode
}
if (purpose) {
body.purpose = purpose
}
if (attribution) {
body.attribution = attribution
}
const response = await apiFetch(`${API_BASE_URL}/api/users/auth/magic-link`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
// Carry tenant context so the backend validates the email domain against the
// tenant, embeds tenant_id in the magic-link token, and uses the tenant's
// sender email + portal URL. Without this, tenant sign-in silently falls back
// to the consumer (nomad) flow.
...getBaseHeaders(),
},
body: JSON.stringify(body),
});
return handleResponse(response);
},
/**
* Verify a magic link token and get a session
*/
/**
* Read-only status check for a magic link — does NOT consume the token.
* Used by the verify page on load to show the correct UI upfront (the
* "Complete Sign-In" gate for a valid link, or an already-used/expired
* message for a dead one) without making the user click only to then fail.
*/
async getMagicLinkStatus(token: string): Promise<{ status: 'valid' | 'used' | 'expired' | 'invalid'; handoff?: boolean }> {
const response = await apiFetch(`${API_BASE_URL}/api/users/auth/link-status?token=${encodeURIComponent(token)}`, {
method: 'GET',
})
return handleResponse(response)
},
async verifyMagicLink(token: string, referralCode?: string | null): Promise<VerifyMagicLinkResponse> {
const headers: HeadersInit = {};
if (referralCode) {
headers['x-referral-code'] = referralCode;
}
const response = await apiFetch(`${API_BASE_URL}/api/users/auth/verify?token=${encodeURIComponent(token)}`, {
method: 'GET',
headers,
});
return handleResponse(response);
},
/**
* Resend a magic link to the email associated with a previously-issued
* (expired or used) token. Used by the verify failure UI to give users
* a one-click recovery path.
*/
async resendMagicLinkFromToken(token: string): Promise<{
status: 'sent' | 'no_token';
masked_email: string | null;
message: string;
}> {
const response = await apiFetch(`${API_BASE_URL}/api/users/auth/resend-from-token`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ token }),
});
return handleResponse(response);
},
// ==========================================================================
// Requests voting board (requests.nomadkaraoke.com)
// ==========================================================================
/** Public board listing (auth optional — annotates the caller's vote if signed in). */
async getRequestsBoard(): Promise<BoardResponse> {
const response = await apiFetch(`${API_BASE_URL}/api/requests-board/requests`, {
method: 'GET',
headers: getAuthHeaders(),
});
return handleResponse(response);
},
/** Submit a song request (auth required). Auto-corrects artist/title and dedupes. */
async submitSongRequest(artist: string, title: string): Promise<SubmitRequestResponse> {
const response = await apiFetch(`${API_BASE_URL}/api/requests-board/requests`, {
method: 'POST',
headers: { ...getAuthHeaders(), 'Content-Type': 'application/json' },
body: JSON.stringify({ artist, title }),
});
return handleResponse(response);
},
/**
* Cast/move/undo the caller's single daily vote (auth required). Removing a request's
* last up-vote deletes it, which the server refuses with 409 `would_delete_request`
* until the user confirms and the call is repeated with `confirmDelete`.
*/
async voteSongRequest(
requestId: string,
direction: 'up' | 'down',
confirmDelete = false,
): Promise<SongRequestPublic> {
const response = await apiFetch(`${API_BASE_URL}/api/requests-board/requests/${encodeURIComponent(requestId)}/vote`, {
method: 'POST',
headers: { ...getAuthHeaders(), 'Content-Type': 'application/json' },
body: JSON.stringify({ direction, confirm_delete: confirmDelete }),
});
return handleResponse(response);
},
/** The caller's daily-vote status (auth required). */
async getDailyVoteStatus(): Promise<DailyVoteStatus> {
const response = await apiFetch(`${API_BASE_URL}/api/requests-board/me`, {
method: 'GET',
headers: getAuthHeaders(),
});
return handleResponse(response);
},
/**
* Grant the standard one-time welcome credit to a signed-in user (auth required).
* Powers the board's "make it yourself now" conversion — board sign-in grants no
* credit, so this claims it (idempotent) before sending the user into the generator.
*/
async claimWelcomeCredit(): Promise<ClaimWelcomeCreditResponse> {
const response = await apiFetch(`${API_BASE_URL}/api/users/claim-welcome-credit`, {
method: 'POST',
headers: getAuthHeaders(),
});
return handleResponse(response);
},
/**
* Get the current user's profile
*/
async getCurrentUser(): Promise<UserProfileResponse> {
const response = await apiFetch(`${API_BASE_URL}/api/users/me`, {
headers: getAuthHeaders()
});
return handleResponse(response);
},
/**
* Logout and invalidate the current session
*/
async logout(): Promise<{ status: string; message: string }> {
const response = await apiFetch(`${API_BASE_URL}/api/users/auth/logout`, {
method: 'POST',
headers: getAuthHeaders()
});
return handleResponse(response);
},
/**
* Account deletion (Google Play web deletion path). Preview what will be lost
* and whether deletion is blocked; the DELETE itself is irreversible.
*/
async getDeletionPreview(): Promise<DeletionPreview> {
const response = await apiFetch(`${API_BASE_URL}/api/users/me/deletion-preview`, {
headers: getAuthHeaders()
});
return handleResponse(response);
},
async deleteAccount(): Promise<{ deleted: boolean; summary?: unknown }> {
const response = await apiFetch(`${API_BASE_URL}/api/users/me`, {
method: 'DELETE',
headers: getAuthHeaders()
});
return handleResponse(response);
},
// ==========================================================================
// Feedback-for-Credits API endpoints
// ==========================================================================
/**
* Submit product feedback to earn free credits
*/
async submitFeedback(data: FeedbackRequest): Promise<FeedbackResponse> {
const response = await apiFetch(`${API_BASE_URL}/api/users/feedback`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
...getAuthHeaders(),
},
body: JSON.stringify(data),
});
return handleResponse(response);
},
// ==========================================================================
// Version & Health API endpoints
// ==========================================================================
/**
* Get backend service info including version
* Note: Uses /backend-info in dev (proxied to production /) to avoid proxying all routes
*/
async getBackendInfo(): Promise<{ service: string; version: string; status: string }> {
const url = API_BASE_URL ? `${API_BASE_URL}/` : '/backend-info';
const response = await apiFetch(url, {
headers: getAuthHeaders()
});
return handleResponse(response);
},
/**
* Get encoding worker health status
*/
async getEncodingWorkerHealth(): Promise<EncodingWorkerHealth> {
const response = await apiFetch(`${API_BASE_URL}/api/health/encoding-worker`);
return handleResponse(response);
},
/**
* Get flacfetch service health status
*/
async getFlacfetchHealth(): Promise<FlacfetchHealth> {
const response = await apiFetch(`${API_BASE_URL}/api/health/flacfetch`);
return handleResponse(response);
},
/**
* Get audio separator service health status
*/
async getAudioSeparatorHealth(): Promise<AudioSeparatorHealth> {
const response = await apiFetch(`${API_BASE_URL}/api/health/audio-separator`);
return handleResponse(response);
},
/**
* Get aggregated system status for all services
*/
async getSystemStatus(): Promise<SystemStatus> {
const response = await apiFetch(`${API_BASE_URL}/api/health/system-status`, {
headers: getAuthHeaders(),
});
return handleResponse(response);
},
// ==========================================================================
// Credits/Payment API endpoints
// ==========================================================================
/**
* Get available credit packages
*/
async getCreditPackages(): Promise<CreditPackage[]> {
const response = await apiFetch(`${API_BASE_URL}/api/users/credits/packages`);
const data = await handleResponse<{ packages: CreditPackage[] }>(response);
return data.packages;
},
/**
* Create a Stripe checkout session
*/
async createCheckout(packageId: string, email: string): Promise<string> {
const response = await apiFetch(`${API_BASE_URL}/api/users/credits/checkout`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
package_id: packageId,
email: email.toLowerCase(),
}),
});
const data = await handleResponse<{ checkout_url: string }>(response);
return data.checkout_url;
},
/**
* Create a Made For You checkout session ($15 full-service)
*/
async createMadeForYouCheckout(data: {
email: string;
artist: string;
title: string;
source_type: 'search' | 'youtube' | 'upload';
youtube_url?: string;
notes?: string;
}): Promise<string> {
const response = await apiFetch(`${API_BASE_URL}/api/users/made-for-you/checkout`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
email: data.email.toLowerCase(),
artist: data.artist,
title: data.title,
source_type: data.source_type,
youtube_url: data.youtube_url,
notes: data.notes,
}),
});
const result = await handleResponse<{ checkout_url: string; status: string; message: string }>(response);
if (!result.checkout_url) {
throw new Error('No checkout URL received');
}
return result.checkout_url;
},
// ==========================================================================
// Push Notifications API endpoints
// ==========================================================================
/**
* Get VAPID public key for push subscription
* Returns whether push is enabled and the public key if so
*/
async getVapidPublicKey(): Promise<{ enabled: boolean; vapid_public_key: string | null }> {
const response = await apiFetch(`${API_BASE_URL}/api/push/vapid-public-key`);
return handleResponse(response);
},
/**
* Subscribe to push notifications
*/
async subscribePush(
endpoint: string,
keys: { p256dh: string; auth: string },
deviceName?: string,
tenantId?: string | null
): Promise<{ status: string; message: string }> {
const response = await apiFetch(`${API_BASE_URL}/api/push/subscribe`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
...getAuthHeaders()
},
body: JSON.stringify({
endpoint,
keys,
device_name: deviceName,
tenant_id: tenantId || null,
}),
});
return handleResponse(response);
},
/**
* Unsubscribe from push notifications
*/
async unsubscribePush(endpoint: string): Promise<{ status: string; message: string }> {
const response = await apiFetch(`${API_BASE_URL}/api/push/unsubscribe`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
...getAuthHeaders()
},
body: JSON.stringify({ endpoint }),
});
return handleResponse(response);
},
/**
* List user's push notification subscriptions
*/
async listPushSubscriptions(): Promise<PushSubscriptionsListResponse> {
const response = await apiFetch(`${API_BASE_URL}/api/push/subscriptions`, {
headers: getAuthHeaders()
});
return handleResponse(response);
},
// --- Catalog (song/artist autocomplete + community check) ---
async searchCatalogArtists(query: string, limit: number = 10): Promise<CatalogArtistResult[]> {
const params = new URLSearchParams({ q: query, limit: String(limit) });
const response = await apiFetch(`${API_BASE_URL}/api/catalog/artists?${params}`, {
headers: getAuthHeaders()
});
return handleResponse(response);
},
async searchCatalogTracks(query: string, artist?: string, limit: number = 10): Promise<CatalogTrackResult[]> {
const params = new URLSearchParams({ q: query, limit: String(limit) });
if (artist) params.set('artist', artist);
const response = await apiFetch(`${API_BASE_URL}/api/catalog/tracks?${params}`, {
headers: getAuthHeaders()
});
return handleResponse(response);
},
async checkCommunityVersions(artist: string, title: string): Promise<CommunityCheckResponse> {
const response = await apiFetch(`${API_BASE_URL}/api/catalog/community-check`, {
method: 'POST',
headers: {
...getAuthHeaders(),
'Content-Type': 'application/json',
},
body: JSON.stringify({ artist, title }),
});
return handleResponse(response);
},
async matchJudge(artist: string, title: string, opts?: MatchJudgeOptions): Promise<MatchJudgeVerdict> {
const body: Record<string, unknown> = { artist, title };
if (opts?.audioConfidenceTier != null) body.audio_confidence_tier = opts.audioConfidenceTier;
if (opts?.stage != null) body.stage = opts.stage;
const response = await apiFetch(`${API_BASE_URL}/api/catalog/match-judge`, {
method: 'POST',
headers: {
...getAuthHeaders(),
'Content-Type': 'application/json',
},
body: JSON.stringify(body),
});
return handleResponse(response);
},
async changeVisibility(jobId: string, targetVisibility: 'public' | 'private'): Promise<ChangeVisibilityResponse> {
const response = await apiFetch(`${API_BASE_URL}/api/jobs/${jobId}/change-visibility`, {
method: 'POST',
headers: {
...getAuthHeaders(),
'Content-Type': 'application/json',
},
body: JSON.stringify({ target_visibility: targetVisibility }),
});
return handleResponse(response);
},
/** Re-render a finished tenant track with the tenant's current theme (no review). */
async regenerateJob(jobId: string): Promise<{ status: string; job_id: string; needs_stems: boolean; message: string }> {
const response = await apiFetch(`${API_BASE_URL}/api/jobs/${jobId}/regenerate`, {
method: 'POST',
headers: getAuthHeaders(),
});
return handleResponse(response);
},
async rerenderWithCurrentTheme(jobId: string): Promise<{ status: string; job_id: string; theme_id: string }> {
const response = await apiFetch(`${API_BASE_URL}/api/jobs/${jobId}/rerender`, {
method: 'POST',
headers: getAuthHeaders(),
});
return handleResponse(response);
},
async editCompletedTrack(jobId: string, updates?: { artist?: string; title?: string }): Promise<EditTrackResponse> {
const response = await apiFetch(`${API_BASE_URL}/api/jobs/${jobId}/edit`, {
method: 'POST',
headers: {
...getAuthHeaders(),
'Content-Type': 'application/json',
},
body: JSON.stringify(updates || {}),
});
return handleResponse(response);
},
/**
* Estimate the credit cost for a URL before creating a job.
* Returns duration (may be null if unknown), credits required, whether the
* job is blocked (e.g. exceeds max duration), and the audio source.
*/
async estimateDuration(url: string): Promise<{
duration_seconds: number | null;
credits: number;
blocked: boolean;
source: string;
}> {
const response = await apiFetch(`${API_BASE_URL}/api/jobs/estimate`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
...getAuthHeaders(),
},
body: JSON.stringify({ url }),
});
return handleResponse(response);
},
/**
* Confirm a duration-priced job after the user acknowledges the credit cost.
* Possible non-2xx: 402 (insufficient credits), 409 (figure changed / wrong state).
* Both are surfaced as ApiError with a .status property so callers can branch.
*/
async confirmDuration(jobId: string, acknowledgedCredits: number): Promise<Job> {
const response = await apiFetch(`${API_BASE_URL}/api/jobs/${jobId}/confirm-duration`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
...getAuthHeaders(),
},
body: JSON.stringify({ acknowledged_credits: acknowledgedCredits }),
});
return handleResponse<Job>(response);
},
};
// Types for credits/payment
export interface CreditPackage {
id: string;
credits: number;
price_cents: number;
name: string;
description: string;
}
// Types for push notifications
export interface PushSubscriptionInfo {
endpoint: string;
device_name: string | null;
created_at: string;
last_used_at: string | null;
}
export interface PushSubscriptionsListResponse {
subscriptions: PushSubscriptionInfo[];
count: number;
}
// ==========================================================================
// Admin Types
// ==========================================================================
export interface AdminStatsOverview {
total_users: number;
active_users_7d: number;
active_users_30d: number;
total_jobs: number;
jobs_last_7d: number;
jobs_last_30d: number;
jobs_by_status: {
pending: number;
processing: number;
awaiting_review: number;
awaiting_instrumental: number;
complete: number;
failed: number;
cancelled: number;
};
total_credits_issued_30d: number;
}
export interface AdminUser {
email: string;
role: 'user' | 'admin';
credits: number;
display_name?: string;
total_jobs_created?: number;
total_jobs_completed?: number;
total_spent?: number;
created_at?: string;
last_login_at?: string;
}
export interface AdminUserListResponse {
users: AdminUser[];
total: number;
offset: number;
limit: number;
has_more: boolean;
}
export interface AdminUserDetail {
email: string;
role: 'user' | 'admin';
credits: number;
display_name?: string;
is_active: boolean;
email_verified: boolean;
// Language: locale = email locale (en/es/de); ui_locale = full UI language (33 locales)
locale?: string | null;
ui_locale?: string | null;
created_at?: string;
updated_at?: string;
last_login_at?: string;
total_jobs_created: number;
total_jobs_completed: number;
credit_transactions: Array<{
id: string;
amount: number;
reason: string;
created_at: string;
job_id?: string;
created_by?: string;
}>;
total_spent: number;
recent_jobs: Array<{
job_id: string;
status: string;
artist?: string;
title?: string;
created_at?: string;
locale?: string | null;
}>;
active_sessions_count: number;
// Anti-abuse fields
signup_ip?: string | null;
device_fingerprint?: string | null;
welcome_credits_granted?: boolean;
has_submitted_feedback?: boolean;
// Referral fields
referred_by_code?: string | null;
referral_discount_expires_at?: string | null;
referral_code?: string | null;
// Acquisition: channel label + first-touch UTM/referrer detail
signup_source?: string | null;
signup_venue?: string | null;
signup_attribution?: Record<string, string> | null;
recent_sessions?: Array<{
ip_address?: string;
user_agent?: string;
device_fingerprint?: string;
created_at?: string;
last_activity_at?: string;
}>;
}
export interface UserEmailSummary {
message_id?: string | null;
source: 'postmark' | 'log';
subject?: string | null;
to?: string | null;
from_email?: string | null;
sent_at?: string | null;
status?: string | null;
email_type?: string | null;
has_stored_html?: boolean;
doc_id?: string;
}
export interface UserEmailHistory {
email: string;
count: number;
postmark_available: boolean;
emails: UserEmailSummary[];
}
export interface EmailDetailEvent {
type?: string;
received_at?: string | null;
details?: Record<string, any>;
}
export interface EmailDetail {
message_id?: string | null;
source: 'postmark' | 'log';
subject?: string | null;
from_email?: string | null;
to?: string | null;
cc?: string | string[] | null;
bcc?: string | string[] | null;
sent_at?: string | null;
message_stream?: string | null;
html_body?: string | null;
text_body?: string | null;
status?: string | null;
delivered_at?: string | null;
open_count?: number;
click_count?: number;
bounce?: Record<string, any> | null;
email_type?: string | null;
events?: EmailDetailEvent[];
}
export interface AdminJobListParams {
status?: string;
user_email?: string;
environment?: string;
created_after?: string;
created_before?: string;
limit?: number;
}
// Audio Search Admin Types
export interface AudioSearchResultSummary {
index: number;
provider: string;
artist: string;
title: string;
is_lossless: boolean;
quality?: string;
seeders?: number;
}
export interface AudioSearchJobSummary {
job_id: string;
status: string;
user_email?: string;
audio_search_artist?: string;
audio_search_title?: string;
created_at?: string;
results_count: number;
results_summary: AudioSearchResultSummary[];
has_lossless: boolean;
providers: string[];
}
export interface AudioSearchListResponse {
jobs: AudioSearchJobSummary[];
total: number;
}
export interface ClearSearchCacheResponse {
status: string;
job_id: string;
message: string;
previous_status: string;
new_status: string;
results_cleared: number;
flacfetch_cache_cleared: boolean;
flacfetch_error?: string;
}
export interface ClearAllCacheResponse {
status: string;
message: string;
deleted_count: number;
}
export interface CacheStatsResponse {
count: number;
total_size_bytes: number;
oldest_entry?: string;
newest_entry?: string;
configured: boolean;
}
// Admin API namespace
export interface TenantSummary {
id: string;
name: string;
subdomain: string;
is_active: boolean;
locked_theme?: string | null;
dropbox_path?: string | null;
brand_prefix?: string | null;
created_at?: string | null;
}
/** Cloudflare state of a tenant's {id}.nomadkaraoke.com portal subdomain. */
export interface TenantDomainStatus {
hostname: string;
state: 'active' | 'provisioning' | 'missing';
dns_ok: boolean;
pages_status?: string | null;
}
export interface TenantCreateResult {
tenant: {
id: string;
name: string;
subdomain: string;
is_active: boolean;
};
preview_url: string;
subdomain_url: string;
domain?: TenantDomainStatus | null;
}
export interface TenantDetail {
tenant: Record<string, any>;
theme_id: string;
style_params: Record<string, any>;
assets: string[];
preview_url: string;
domain?: TenantDomainStatus | null;
}
export interface CommunityReviewItem {
id: string;
artist: string;
title: string;
submitted_by: string;
vote_count: number;
upvoter_count: number;
community_versions?: {
best_youtube_url?: string | null;
tracks?: { brand_name: string; youtube_url: string }[];
} | null;
community_checked_at?: string | null;
}
export interface CommunityRequestItem {
id: string;
artist: string;
title: string;
status: string;
submitted_by: string;
owner_email?: string | null;
vote_count: number;
job_id?: string | null;
youtube_url?: string | null;
review_state?: string | null;
created_at?: string | null;
picked_at?: string | null;
}
// --- Tenant self-service theme editor (/api/tenant/theme) -------------------
export type ThemeStyleParams = Record<string, Record<string, any>>
export interface TenantThemeData {
theme_id: string
style_params: ThemeStyleParams
images: string[]
fonts: string[]
// Images that fit the 300x216 CD+G screen (offered on the CD+G tab)
cdg_images?: string[]
// Built-in CD+G reveal transitions (the order the screen's tiles are drawn in)
cdg_transitions?: string[]
}
export interface TenantThemeSaveResult extends TenantThemeData {
refreshed_jobs: number
outdated_job_ids: string[]
}
export interface ThemePreviewSample {
artist?: string
title?: string
lyrics?: string[]
}
export interface ThemePreviewImages {
// data:image/jpeg;base64,... — null for a screen the theme leaves out of videos
title_card: string | null
karaoke_frame: string | null
end_screen: string | null
// data:image/png;base64,... — CD+G screens (only when requested)
cdg_title_card?: string | null
cdg_lyrics?: string | null
cdg_instrumental?: string | null
cdg_outro?: string | null
}
export const tenantThemeApi = {
/** The signed-in user's tenant theme + uploaded images and available fonts. */
async get(): Promise<TenantThemeData> {
const response = await apiFetch(`${API_BASE_URL}/api/tenant/theme`, { headers: getAuthHeaders() })
return handleResponse<TenantThemeData>(response)
},
/**
* Upload a background image or font; returns the stored asset name.
* `purpose: 'cdg'` fits an image to the 300x216 CD+G screen.
*/
async uploadAsset(file: File, purpose?: 'cdg'): Promise<{ name: string }> {
const fd = new FormData()
fd.append('file', file)
if (purpose) fd.append('purpose', purpose)
const response = await apiFetch(`${API_BASE_URL}/api/tenant/theme/assets`, {
method: 'POST',
headers: getAuthHeaders(),
body: fd,
})
return handleResponse<{ name: string }>(response)
},
/** Render exact previews of a draft theme (nothing is saved). */
async preview(
styleParams: ThemeStyleParams,
sample: ThemePreviewSample,
signal?: AbortSignal,
options: { includeCdg?: boolean; kinds?: Array<'title_card' | 'karaoke_frame' | 'end_screen'> } = {},
): Promise<ThemePreviewImages> {
const response = await apiFetch(`${API_BASE_URL}/api/tenant/theme/preview`, {
method: 'POST',
headers: { ...getAuthHeaders(), 'Content-Type': 'application/json' },
body: JSON.stringify({
style_params: styleParams, sample, include_cdg: !!options.includeCdg,
...(options.kinds ? { kinds: options.kinds } : {}),
}),
signal,
})
return handleResponse<ThemePreviewImages>(response)
},
/**
* Save the theme. Applies to new tracks and to tracks still in progress
* (`refreshed_jobs`); finished tracks made with the old theme are listed in
* `outdated_job_ids` (re-render to update them).
*/
async save(styleParams: ThemeStyleParams): Promise<TenantThemeSaveResult> {
const response = await apiFetch(`${API_BASE_URL}/api/tenant/theme`, {
method: 'PUT',
headers: { ...getAuthHeaders(), 'Content-Type': 'application/json' },
body: JSON.stringify({ style_params: styleParams }),
})
return handleResponse<TenantThemeSaveResult>(response)
},
/** The caller's finished tracks made with an older version of the theme. */
async outdatedJobs(): Promise<{ theme_updated_at: string | null; job_ids: string[] }> {
const response = await apiFetch(`${API_BASE_URL}/api/tenant/theme/outdated-jobs`, { headers: getAuthHeaders() })
return handleResponse<{ theme_updated_at: string | null; job_ids: string[] }>(response)
},
/** Re-render every outdated finished track with the current theme (no per-track emails). */
async rerenderOutdated(): Promise<{ started: string[]; failed: Record<string, string>; remaining?: string[] }> {
const response = await apiFetch(`${API_BASE_URL}/api/tenant/theme/rerender-outdated`, {
method: 'POST',
headers: getAuthHeaders(),
})
return handleResponse<{ started: string[]; failed: Record<string, string>; remaining?: string[] }>(response)
},
}
export const adminApi = {
/**
* Full history of requests-board submissions across every status.
*/
async listCommunityRequests(): Promise<{ requests: CommunityRequestItem[] }> {
const response = await apiFetch(`${API_BASE_URL}/api/admin/community-requests`, {
headers: getAuthHeaders(),
});
return handleResponse(response);
},
/**
* List requests-board picks flagged for existing-community-version review.
*/
async listCommunityReviews(): Promise<{ reviews: CommunityReviewItem[] }> {
const response = await apiFetch(`${API_BASE_URL}/api/admin/community-reviews`, {
headers: getAuthHeaders(),
});
return handleResponse(response);
},
/**
* Resolve a flagged pick: 'make' our version, 'reject' (notify up-voters), or 'keep'.
*/
async actionCommunityReview(
requestId: string,
action: 'make' | 'reject' | 'keep',
): Promise<{ status: string; request_id: string; message: string }> {
const response = await apiFetch(
`${API_BASE_URL}/api/admin/community-reviews/${encodeURIComponent(requestId)}`,
{
method: 'POST',
headers: { ...getAuthHeaders(), 'Content-Type': 'application/json' },
body: JSON.stringify({ action }),
},
);
return handleResponse(response);
},
/**
* List all white-label tenants
*/
async listTenants(): Promise<{ tenants: TenantSummary[] }> {
const response = await apiFetch(`${API_BASE_URL}/api/admin/tenants`, {
headers: getAuthHeaders(),
});
return handleResponse(response);
},
/**
* Create a white-label tenant (multipart: fields + optional background/logo images).
* Do NOT set Content-Type — the browser sets the multipart boundary.
*/
async createTenant(formData: FormData): Promise<TenantCreateResult> {
const response = await apiFetch(`${API_BASE_URL}/api/admin/tenants`, {
method: 'POST',
headers: getAuthHeaders(),
body: formData,
});
return handleResponse(response);
},
/**
* Get a tenant's full config, theme style_params, and asset list (for editing).
*/
async getTenant(tenantId: string): Promise<TenantDetail> {
const response = await apiFetch(`${API_BASE_URL}/api/admin/tenants/${encodeURIComponent(tenantId)}`, {
headers: getAuthHeaders(),
});
return handleResponse(response);
},
/**
* Update a tenant (multipart: optional config JSON, style_params JSON, and asset files).
*/
async updateTenant(tenantId: string, formData: FormData): Promise<{ tenant: TenantCreateResult['tenant'] }> {
const response = await apiFetch(`${API_BASE_URL}/api/admin/tenants/${encodeURIComponent(tenantId)}`, {
method: 'PUT',
headers: getAuthHeaders(),
body: formData,
});
return handleResponse(response);
},
/**
* Delete a tenant: portal subdomain (Cloudflare), theme, and config. Jobs are kept.
*/
async deleteTenant(tenantId: string): Promise<void> {
const response = await apiFetch(`${API_BASE_URL}/api/admin/tenants/${encodeURIComponent(tenantId)}`, {
method: 'DELETE',
headers: getAuthHeaders(),
});
if (!response.ok) await handleResponse(response);
},
/**
* (Re)provision a tenant's {id}.nomadkaraoke.com subdomain (idempotent).
*/
async provisionTenantDomain(tenantId: string): Promise<{ domain: TenantDomainStatus }> {
const response = await apiFetch(`${API_BASE_URL}/api/admin/tenants/${encodeURIComponent(tenantId)}/domain`, {
method: 'POST',
headers: getAuthHeaders(),
});
return handleResponse(response);
},
/**
* Get the default Nomad theme's full style_params — a starting template for a new theme.
*/
async getThemeTemplate(): Promise<{ style_params: Record<string, any> }> {
const response = await apiFetch(`${API_BASE_URL}/api/admin/tenants/_template`, {
headers: getAuthHeaders(),
});
return handleResponse(response);
},
/**
* Get admin dashboard statistics
*/
async getStats(params?: { exclude_test?: boolean }): Promise<AdminStatsOverview> {
const searchParams = new URLSearchParams();
if (params?.exclude_test !== undefined) {
searchParams.set('exclude_test', String(params.exclude_test));
}
const url = `${API_BASE_URL}/api/admin/stats/overview${searchParams.toString() ? '?' + searchParams.toString() : ''}`;
const response = await apiFetch(url, {
headers: getAuthHeaders()
});
return handleResponse(response);
},
/**
* List all users with pagination and search
*/
async listUsers(params?: {
limit?: number;
offset?: number;
search?: string;
sort_by?: 'created_at' | 'last_login_at' | 'credits' | 'email';
sort_order?: 'asc' | 'desc';
include_inactive?: boolean;
exclude_test?: boolean;
}): Promise<AdminUserListResponse> {
const searchParams = new URLSearchParams();
if (params?.limit) searchParams.set('limit', String(params.limit));
if (params?.offset) searchParams.set('offset', String(params.offset));
if (params?.search) searchParams.set('search', params.search);
if (params?.sort_by) searchParams.set('sort_by', params.sort_by);
if (params?.sort_order) searchParams.set('sort_order', params.sort_order);
if (params?.include_inactive) searchParams.set('include_inactive', 'true');
if (params?.exclude_test !== undefined) searchParams.set('exclude_test', String(params.exclude_test));
const url = `${API_BASE_URL}/api/users/admin/users${searchParams.toString() ? '?' + searchParams.toString() : ''}`;
const response = await apiFetch(url, {
headers: getAuthHeaders()
});
return handleResponse(response);
},
/**
* Get detailed user information
*/
async getUserDetail(email: string): Promise<AdminUserDetail> {
const response = await apiFetch(`${API_BASE_URL}/api/users/admin/users/${encodeURIComponent(email)}/detail`, {
headers: getAuthHeaders()
});
return handleResponse(response);
},
/**
* List every email ever sent to a user (Postmark + persisted log)
*/
async getUserEmails(email: string): Promise<UserEmailHistory> {
const response = await apiFetch(`${API_BASE_URL}/api/admin/users/${encodeURIComponent(email)}/emails`, {
headers: getAuthHeaders()
});
return handleResponse(response);
},
/**
* Full detail for one sent email — rendered HTML + delivery metadata.
* `source` is "postmark" (default) or "log" (our stored copy for older mail).
*/
async getEmailDetail(messageId: string, source: string = 'postmark'): Promise<EmailDetail> {
const response = await apiFetch(
`${API_BASE_URL}/api/admin/emails/${encodeURIComponent(messageId)}?source=${encodeURIComponent(source)}`,
{ headers: getAuthHeaders() }
);
return handleResponse(response);
},
/**
* Create a user account directly (e.g. to grant credits or impersonate
* someone who has never logged in)
*/
async createUser(data: {
email: string;
display_name?: string;
initial_credits?: number;
credit_reason?: string;
}): Promise<{
status: string;
email: string;
credits: number;
message: string;
}> {
const response = await apiFetch(`${API_BASE_URL}/api/users/admin/users`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
...getAuthHeaders()
},
body: JSON.stringify(data),
});
return handleResponse(response);
},
/**
* Add credits to a user
*/
async addCredits(email: string, amount: number, reason: string): Promise<{
status: string;
email: string;
credits_added: number;
new_balance: number;
message: string;
}> {
const response = await apiFetch(`${API_BASE_URL}/api/users/admin/credits`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
...getAuthHeaders()
},
body: JSON.stringify({ email, amount, reason }),
});
return handleResponse(response);
},
/**
* Apply a referral discount to a user (admin only)
*/
async applyDiscount(email: string, data: {
discount_percent?: number;
duration_days?: number;
referral_code?: string;
}): Promise<{ ok: boolean; message: string; discount_expires_at: string }> {
const response = await apiFetch(`${API_BASE_URL}/api/referrals/admin/apply-discount`, {
method: 'POST',
headers: { ...getAuthHeaders(), 'Content-Type': 'application/json' },
body: JSON.stringify({ email, ...data }),
});
return handleResponse(response);
},
/**
* Impersonate a user (admin only)
* Creates a session token that allows viewing the app as the target user
*/
async impersonateUser(email: string): Promise<{
session_token: string;
user_email: string;
message: string;
}> {
const response = await apiFetch(`${API_BASE_URL}/api/admin/users/${encodeURIComponent(email)}/impersonate`, {
method: 'POST',
headers: getAuthHeaders()
});
return handleResponse(response);
},
/**
* Enable a user account
*/
async enableUser(email: string): Promise<{ status: string; message: string }> {
const response = await apiFetch(`${API_BASE_URL}/api/users/admin/users/${encodeURIComponent(email)}/enable`, {
method: 'POST',
headers: getAuthHeaders()
});
return handleResponse(response);
},
/**
* Disable a user account
*/
async disableUser(email: string): Promise<{ status: string; message: string }> {
const response = await apiFetch(`${API_BASE_URL}/api/users/admin/users/${encodeURIComponent(email)}/disable`, {
method: 'POST',
headers: getAuthHeaders()
});
return handleResponse(response);
},
/**
* Permanently delete a user and all associated data
*/
async deleteUser(email: string): Promise<{ status: string; message: string }> {
const response = await apiFetch(`${API_BASE_URL}/api/users/admin/users/${encodeURIComponent(email)}`, {
method: 'DELETE',
headers: getAuthHeaders()
});
return handleResponse(response);
},
/**
* List all jobs (admin view)
*/
async listAllJobs(params?: AdminJobListParams & { exclude_test?: boolean }): Promise<Job[]> {
const searchParams = new URLSearchParams();
if (params?.status) searchParams.set('status', params.status);
if (params?.user_email) searchParams.set('user_email', params.user_email);
if (params?.environment) searchParams.set('environment', params.environment);
if (params?.created_after) searchParams.set('created_after', params.created_after);
if (params?.created_before) searchParams.set('created_before', params.created_before);
if (params?.limit) searchParams.set('limit', String(params.limit));
if (params?.exclude_test !== undefined) searchParams.set('exclude_test', String(params.exclude_test));
const url = `${API_BASE_URL}/api/jobs${searchParams.toString() ? '?' + searchParams.toString() : ''}`;
const response = await apiFetch(url, {
headers: getAuthHeaders()
});
return handleResponse<Job[]>(response);
},
/**
* Delete a job (admin)
*/
async deleteJob(jobId: string, deleteFiles: boolean = true): Promise<{ status: string; message: string }> {
const response = await apiFetch(
`${API_BASE_URL}/api/jobs/${jobId}?delete_files=${deleteFiles}`,
{ method: 'DELETE', headers: getAuthHeaders() }
);
return handleResponse(response);
},
/**
* List jobs with audio search results
*/
async listAudioSearches(params?: {
limit?: number;
status_filter?: string;
exclude_test?: boolean;
}): Promise<AudioSearchListResponse> {
const searchParams = new URLSearchParams();
if (params?.limit) searchParams.set('limit', String(params.limit));
if (params?.status_filter) searchParams.set('status_filter', params.status_filter);
if (params?.exclude_test !== undefined) searchParams.set('exclude_test', String(params.exclude_test));
const url = `${API_BASE_URL}/api/admin/audio-searches${searchParams.toString() ? '?' + searchParams.toString() : ''}`;
const response = await apiFetch(url, {
headers: getAuthHeaders()
});
return handleResponse(response);
},
/**
* Clear audio search cache for a job
*/
async clearAudioSearchCache(jobId: string): Promise<ClearSearchCacheResponse> {
const response = await apiFetch(
`${API_BASE_URL}/api/admin/audio-searches/${jobId}/clear-cache`,
{ method: 'POST', headers: getAuthHeaders() }
);
return handleResponse(response);
},
/**
* Clear all flacfetch search cache
*/
async clearAllCache(): Promise<ClearAllCacheResponse> {
const response = await apiFetch(
`${API_BASE_URL}/api/admin/cache`,
{ method: 'DELETE', headers: getAuthHeaders() }
);
return handleResponse(response);
},
/**
* Get flacfetch cache statistics
*/
async getCacheStats(): Promise<CacheStatsResponse> {
const response = await apiFetch(
`${API_BASE_URL}/api/admin/cache/stats`,
{ headers: getAuthHeaders() }
);
return handleResponse(response);
},
/**
* Get rendered completion message for a job (for copy to clipboard)
*/
async getCompletionMessage(jobId: string): Promise<CompletionMessageResponse> {
const response = await apiFetch(
`${API_BASE_URL}/api/admin/jobs/${jobId}/completion-message`,
{ headers: getAuthHeaders() }
);
return handleResponse(response);
},
/**
* Send completion email for a job
*/
async sendCompletionEmail(jobId: string, toEmail: string, ccAdmin: boolean = true): Promise<SendCompletionEmailResponse> {
const response = await apiFetch(
`${API_BASE_URL}/api/admin/jobs/${jobId}/send-completion-email`,
{
method: 'POST',
headers: {
...getAuthHeaders(),
'Content-Type': 'application/json',
},
body: JSON.stringify({ to_email: toEmail, cc_admin: ccAdmin }),
}
);
return handleResponse(response);
},
/**
* Get all files for a job with signed download URLs
*/
async getJobFiles(jobId: string): Promise<JobFilesResponse> {
const response = await apiFetch(
`${API_BASE_URL}/api/admin/jobs/${jobId}/files`,
{ headers: getAuthHeaders() }
);
return handleResponse(response);
},
/**
* Update editable fields of a job (admin only)
*/
async updateJob(jobId: string, updates: JobUpdateRequest): Promise<JobUpdateResponse> {
const response = await apiFetch(
`${API_BASE_URL}/api/admin/jobs/${jobId}`,
{
method: 'PATCH',
headers: {
'Content-Type': 'application/json',
...getAuthHeaders()
},
body: JSON.stringify(updates),
}
);
return handleResponse(response);
},
/**
* Reset a job to a specific state for re-processing (admin only)
*/
async resetJob(jobId: string, targetState: string): Promise<JobResetResponse> {
const response = await apiFetch(
`${API_BASE_URL}/api/admin/jobs/${jobId}/reset`,
{
method: 'POST',
headers: {
'Content-Type': 'application/json',
...getAuthHeaders()
},
body: JSON.stringify({ target_state: targetState }),
}
);
return handleResponse(response);
},
/**
* Delete all distributed outputs for a job (admin only).
* Deletes YouTube video, Dropbox folder, and Google Drive files.
* Job record is preserved with outputs_deleted_at timestamp.
*/
async deleteJobOutputs(jobId: string): Promise<DeleteOutputsResponse> {
const response = await apiFetch(
`${API_BASE_URL}/api/admin/jobs/${jobId}/delete-outputs`,
{
method: 'POST',
headers: getAuthHeaders()
}
);
return handleResponse(response);
},
/**
* Clear all worker progress markers for a job (admin only).
* This allows workers to re-execute without skipping due to idempotency checks.
* Does NOT change job status - use resetJob for that.
*/
async clearWorkers(jobId: string): Promise<ClearWorkersResponse> {
const response = await apiFetch(
`${API_BASE_URL}/api/admin/jobs/${jobId}/clear-workers`,
{
method: 'POST',
headers: getAuthHeaders()
}
);
return handleResponse(response);
},
/**
* Manually trigger a worker for a job (admin only).
* Use when auto-trigger fails after reset, or to re-run processing.
*/
async triggerWorker(jobId: string, workerType: string = "video"): Promise<TriggerWorkerResponse> {
const response = await apiFetch(
`${API_BASE_URL}/api/admin/jobs/${jobId}/trigger-worker`,
{
method: 'POST',
headers: {
'Content-Type': 'application/json',
...getAuthHeaders()
},
body: JSON.stringify({ worker_type: workerType }),
}
);
return handleResponse(response);
},
/**
* Re-render a completed job end to end with the current renderer, without
* review (admin only). Keeps the job's style and brand code; published
* outputs are replaced (YouTube gets a new URL). The customer is only
* notified when notifyCustomer is true.
*/
async rerenderJob(jobId: string, notifyCustomer: boolean = false): Promise<AdminRerenderResponse> {
const response = await apiFetch(
`${API_BASE_URL}/api/admin/jobs/${jobId}/rerender`,
{
method: 'POST',
headers: {
...getAuthHeaders(),
'Content-Type': 'application/json',
},
body: JSON.stringify({ notify_customer: notifyCustomer }),
}
);
return handleResponse(response);
},
/**
* Regenerate title and end screens with current artist/title metadata (admin only).
* Use when you've edited artist/title and need screens to reflect the new metadata.
*/
async regenerateScreens(jobId: string): Promise<RegenerateScreensResponse> {
const response = await apiFetch(
`${API_BASE_URL}/api/admin/jobs/${jobId}/regenerate-screens`,
{
method: 'POST',
headers: getAuthHeaders()
}
);
return handleResponse(response);
},
/**
* Fully restart a job from the beginning (admin only).
* Unlike reset (which just changes state), restart actually triggers workers.
*/
async restartJob(jobId: string, options: RestartJobRequest): Promise<RestartJobResponse> {
const response = await apiFetch(
`${API_BASE_URL}/api/admin/jobs/${jobId}/restart`,
{
method: 'POST',
headers: {
'Content-Type': 'application/json',
...getAuthHeaders()
},
body: JSON.stringify(options),
}
);
return handleResponse(response);
},
/**
* Override the audio source for a job (admin only).
* Switch from YouTube URL to audio search mode.
*/
async overrideAudioSource(jobId: string, request: OverrideAudioSourceRequest): Promise<OverrideAudioSourceResponse> {
const response = await apiFetch(
`${API_BASE_URL}/api/admin/jobs/${jobId}/override-audio-source`,
{
method: 'POST',
headers: {
'Content-Type': 'application/json',
...getAuthHeaders()
},
body: JSON.stringify(request),
}
);
return handleResponse(response);
},
// =========================================================================
// Rate Limits API
// =========================================================================
/**
* Get all blocklists
*/
async getBlocklists(): Promise<BlocklistsResponse> {
const response = await apiFetch(
`${API_BASE_URL}/api/admin/rate-limits/blocklists`,
{ headers: getAuthHeaders() }
);
return handleResponse(response);
},
/**
* Add a disposable domain
*/
async addDisposableDomain(domain: string): Promise<SuccessResponse> {
const response = await apiFetch(
`${API_BASE_URL}/api/admin/rate-limits/blocklists/disposable-domains`,
{
method: 'POST',
headers: { 'Content-Type': 'application/json', ...getAuthHeaders() },
body: JSON.stringify({ domain }),
}
);
return handleResponse(response);
},
/**
* Remove a disposable domain
*/
async removeDisposableDomain(domain: string): Promise<SuccessResponse> {
const response = await apiFetch(
`${API_BASE_URL}/api/admin/rate-limits/blocklists/disposable-domains/${encodeURIComponent(domain)}`,
{ method: 'DELETE', headers: getAuthHeaders() }
);
return handleResponse(response);
},
/**
* Add a blocked email
*/
async addBlockedEmail(email: string): Promise<SuccessResponse> {
const response = await apiFetch(
`${API_BASE_URL}/api/admin/rate-limits/blocklists/blocked-emails`,
{
method: 'POST',
headers: { 'Content-Type': 'application/json', ...getAuthHeaders() },
body: JSON.stringify({ email }),
}
);
return handleResponse(response);
},
/**
* Remove a blocked email
*/
async removeBlockedEmail(email: string): Promise<SuccessResponse> {
const response = await apiFetch(
`${API_BASE_URL}/api/admin/rate-limits/blocklists/blocked-emails/${encodeURIComponent(email)}`,
{ method: 'DELETE', headers: getAuthHeaders() }
);
return handleResponse(response);
},
/**
* Add a blocked IP
*/
async addBlockedIP(ipAddress: string): Promise<SuccessResponse> {
const response = await apiFetch(
`${API_BASE_URL}/api/admin/rate-limits/blocklists/blocked-ips`,
{
method: 'POST',
headers: { 'Content-Type': 'application/json', ...getAuthHeaders() },
body: JSON.stringify({ ip_address: ipAddress }),
}
);
return handleResponse(response);
},
/**
* Remove a blocked IP
*/
async removeBlockedIP(ipAddress: string): Promise<SuccessResponse> {
const response = await apiFetch(
`${API_BASE_URL}/api/admin/rate-limits/blocklists/blocked-ips/${encodeURIComponent(ipAddress)}`,
{ method: 'DELETE', headers: getAuthHeaders() }
);
return handleResponse(response);
},
async syncDisposableDomains(): Promise<SuccessResponse> {
const response = await apiFetch(
`${API_BASE_URL}/api/admin/rate-limits/blocklists/sync`,
{ method: 'POST', headers: getAuthHeaders() }
);
return handleResponse(response);
},
async addAllowlistedDomain(domain: string): Promise<SuccessResponse> {
const response = await apiFetch(
`${API_BASE_URL}/api/admin/rate-limits/blocklists/allowlisted-domains`,
{
method: 'POST',
headers: { 'Content-Type': 'application/json', ...getAuthHeaders() },
body: JSON.stringify({ domain }),
}
);
return handleResponse(response);
},
async removeAllowlistedDomain(domain: string): Promise<SuccessResponse> {
const response = await apiFetch(
`${API_BASE_URL}/api/admin/rate-limits/blocklists/allowlisted-domains/${encodeURIComponent(domain)}`,
{ method: 'DELETE', headers: getAuthHeaders() }
);
return handleResponse(response);
},
// YouTube Upload Queue
async getYouTubeQueue(): Promise<YouTubeQueueListResponse> {
const response = await apiFetch(
`${API_BASE_URL}/api/admin/rate-limits/youtube-queue`,
{ headers: getAuthHeaders() }
);
return handleResponse(response);
},
async retryYouTubeUpload(jobId: string): Promise<SuccessResponse> {
const response = await apiFetch(
`${API_BASE_URL}/api/admin/rate-limits/youtube-queue/${encodeURIComponent(jobId)}/retry`,
{ method: 'POST', headers: getAuthHeaders() }
);
return handleResponse(response);
},
async processYouTubeQueue(): Promise<SuccessResponse> {
const response = await apiFetch(
`${API_BASE_URL}/api/admin/rate-limits/youtube-queue/process`,
{ method: 'POST', headers: getAuthHeaders() }
);
return handleResponse(response);
},
// =========================================================================
// Payments API
// =========================================================================
async getPaymentSummary(params?: { days?: number; exclude_test?: boolean }): Promise<RevenueSummary> {
const searchParams = new URLSearchParams();
if (params?.days) searchParams.set('days', String(params.days));
if (params?.exclude_test !== undefined) searchParams.set('exclude_test', String(params.exclude_test));
const url = `${API_BASE_URL}/api/admin/payments/summary${searchParams.toString() ? '?' + searchParams.toString() : ''}`;
const response = await apiFetch(url, { headers: getAuthHeaders() });
return handleResponse(response);
},
async getRevenueChart(params?: { days?: number; group_by?: string; exclude_test?: boolean }): Promise<RevenueChartPoint[]> {
const searchParams = new URLSearchParams();
if (params?.days) searchParams.set('days', String(params.days));
if (params?.group_by) searchParams.set('group_by', params.group_by);
if (params?.exclude_test !== undefined) searchParams.set('exclude_test', String(params.exclude_test));
const url = `${API_BASE_URL}/api/admin/payments/revenue-chart${searchParams.toString() ? '?' + searchParams.toString() : ''}`;
const response = await apiFetch(url, { headers: getAuthHeaders() });
return handleResponse(response);
},
async listPayments(params?: {
limit?: number;
offset?: number;
order_type?: string;
status?: string;
email?: string;
exclude_test?: boolean;
}): Promise<PaymentListResponse> {
const searchParams = new URLSearchParams();
if (params?.limit) searchParams.set('limit', String(params.limit));
if (params?.offset) searchParams.set('offset', String(params.offset));
if (params?.order_type) searchParams.set('order_type', params.order_type);
if (params?.status) searchParams.set('status', params.status);
if (params?.email) searchParams.set('email', params.email);
if (params?.exclude_test !== undefined) searchParams.set('exclude_test', String(params.exclude_test));
const url = `${API_BASE_URL}/api/admin/payments${searchParams.toString() ? '?' + searchParams.toString() : ''}`;
const response = await apiFetch(url, { headers: getAuthHeaders() });
return handleResponse(response);
},
async getPaymentDetail(sessionId: string): Promise<PaymentRecord> {
const response = await apiFetch(
`${API_BASE_URL}/api/admin/payments/${encodeURIComponent(sessionId)}`,
{ headers: getAuthHeaders() }
);
return handleResponse(response);
},
async getStripeBalance(): Promise<StripeBalance> {
const response = await apiFetch(
`${API_BASE_URL}/api/admin/payments/balance`,
{ headers: getAuthHeaders() }
);
return handleResponse(response);
},
async getPayouts(limit: number = 20): Promise<PayoutRecord[]> {
const response = await apiFetch(
`${API_BASE_URL}/api/admin/payments/payouts?limit=${limit}`,
{ headers: getAuthHeaders() }
);
return handleResponse(response);
},
async getDisputes(): Promise<DisputeRecord[]> {
const response = await apiFetch(
`${API_BASE_URL}/api/admin/payments/disputes`,
{ headers: getAuthHeaders() }
);
return handleResponse(response);
},
async getUserPayments(email: string): Promise<UserPaymentHistory> {
const response = await apiFetch(
`${API_BASE_URL}/api/admin/payments/by-user/${encodeURIComponent(email)}`,
{ headers: getAuthHeaders() }
);
return handleResponse(response);
},
async getWebhookEvents(params?: { limit?: number; event_type?: string; status?: string }): Promise<WebhookEvent[]> {
const searchParams = new URLSearchParams();
if (params?.limit) searchParams.set('limit', String(params.limit));
if (params?.event_type) searchParams.set('event_type', params.event_type);
if (params?.status) searchParams.set('status', params.status);
const url = `${API_BASE_URL}/api/admin/payments/webhook-events${searchParams.toString() ? '?' + searchParams.toString() : ''}`;
const response = await apiFetch(url, { headers: getAuthHeaders() });
return handleResponse(response);
},
async refundPayment(sessionId: string, request: RefundRequest): Promise<RefundResponse> {
const response = await apiFetch(
`${API_BASE_URL}/api/admin/payments/${encodeURIComponent(sessionId)}/refund`,
{
method: 'POST',
headers: { 'Content-Type': 'application/json', ...getAuthHeaders() },
body: JSON.stringify(request),
}
);
return handleResponse(response);
},
async listEditReviews(params?: {
limit?: number;
offset?: number;
exclude_test?: boolean;
search?: string;
}): Promise<EditReviewListResponse> {
const searchParams = new URLSearchParams();
if (params?.limit) searchParams.set('limit', String(params.limit));
if (params?.offset) searchParams.set('offset', String(params.offset));
if (params?.exclude_test !== undefined) searchParams.set('exclude_test', String(params.exclude_test));
if (params?.search) searchParams.set('search', params.search);
const url = `${API_BASE_URL}/api/admin/edit-reviews${searchParams.toString() ? '?' + searchParams.toString() : ''}`;
const response = await apiFetch(url, { headers: getAuthHeaders() });
return handleResponse(response);
},
async getEditReview(jobId: string): Promise<EditReviewDetail> {
const response = await apiFetch(
`${API_BASE_URL}/api/admin/edit-reviews/${encodeURIComponent(jobId)}`,
{ headers: getAuthHeaders() }
);
return handleResponse(response);
},
async listAudioEditReviews(params?: {
limit?: number;
offset?: number;
exclude_test?: boolean;
search?: string;
}): Promise<AudioEditReviewListResponse> {
const searchParams = new URLSearchParams();
if (params?.limit) searchParams.set('limit', String(params.limit));
if (params?.offset) searchParams.set('offset', String(params.offset));
if (params?.exclude_test !== undefined) searchParams.set('exclude_test', String(params.exclude_test));
if (params?.search) searchParams.set('search', params.search);
const url = `${API_BASE_URL}/api/admin/audio-edit-reviews${searchParams.toString() ? '?' + searchParams.toString() : ''}`;
const response = await apiFetch(url, { headers: getAuthHeaders() });
return handleResponse(response);
},
async getAudioEditReview(jobId: string): Promise<AudioEditReviewDetail> {
const response = await apiFetch(
`${API_BASE_URL}/api/admin/audio-edit-reviews/${encodeURIComponent(jobId)}`,
{ headers: getAuthHeaders() }
);
return handleResponse(response);
},
// Anti-abuse investigation endpoints
async getAbuseCorrelations(): Promise<AbuseCorrelationsResponse> {
const response = await apiFetch(
`${API_BASE_URL}/api/admin/abuse/correlations`,
{ headers: getAuthHeaders() }
);
return handleResponse(response);
},
async getAbuseSuspicious(params?: { min_jobs?: number; max_spend?: number }): Promise<AbuseSuspiciousResponse> {
const searchParams = new URLSearchParams();
if (params?.min_jobs) searchParams.set('min_jobs', String(params.min_jobs));
if (params?.max_spend !== undefined) searchParams.set('max_spend', String(params.max_spend));
const url = `${API_BASE_URL}/api/admin/abuse/suspicious${searchParams.toString() ? '?' + searchParams.toString() : ''}`;
const response = await apiFetch(url, { headers: getAuthHeaders() });
return handleResponse(response);
},
async getAbuseRelated(email: string): Promise<AbuseRelatedResponse> {
const response = await apiFetch(
`${API_BASE_URL}/api/admin/abuse/related/${encodeURIComponent(email)}`,
{ headers: getAuthHeaders() }
);
return handleResponse(response);
},
async getAbuseByIp(ip: string): Promise<AbuseByIpResponse> {
const response = await apiFetch(
`${API_BASE_URL}/api/admin/abuse/by-ip/${encodeURIComponent(ip)}`,
{ headers: getAuthHeaders() }
);
return handleResponse(response);
},
async getAbuseByFingerprint(fingerprint: string): Promise<AbuseByFingerprintResponse> {
const response = await apiFetch(
`${API_BASE_URL}/api/admin/abuse/by-fingerprint/${encodeURIComponent(fingerprint)}`,
{ headers: getAuthHeaders() }
);
return handleResponse(response);
},
async getIpInfo(ip: string): Promise<IpGeoInfo> {
const response = await apiFetch(
`${API_BASE_URL}/api/admin/abuse/ip-info/${encodeURIComponent(ip)}`,
{ headers: getAuthHeaders() }
);
return handleResponse(response);
},
async getIpInfoBatch(ips: string[]): Promise<Record<string, IpGeoInfo>> {
const response = await apiFetch(
`${API_BASE_URL}/api/admin/abuse/ip-info/batch`,
{
method: 'POST',
headers: { 'Content-Type': 'application/json', ...getAuthHeaders() },
body: JSON.stringify({ ips }),
}
);
return handleResponse(response);
},
async listFeedback(params?: {
limit?: number;
offset?: number;
search?: string;
exclude_test?: boolean;
}): Promise<AdminFeedbackListResponse> {
const searchParams = new URLSearchParams();
if (params?.limit) searchParams.set('limit', String(params.limit));
if (params?.offset) searchParams.set('offset', String(params.offset));
if (params?.search) searchParams.set('search', params.search);
if (params?.exclude_test !== undefined) searchParams.set('exclude_test', String(params.exclude_test));
const url = `${API_BASE_URL}/api/admin/feedback${searchParams.toString() ? '?' + searchParams.toString() : ''}`;
const response = await apiFetch(url, {
headers: getAuthHeaders()
});
return handleResponse(response);
},
// Referral Management
async listReferralLinks(params?: { limit?: number; offset?: number }): Promise<{ links: ReferralLink[]; count: number }> {
const searchParams = new URLSearchParams();
if (params?.limit) searchParams.set('limit', String(params.limit));
if (params?.offset) searchParams.set('offset', String(params.offset));
const url = `${API_BASE_URL}/api/referrals/admin/links${searchParams.toString() ? '?' + searchParams.toString() : ''}`;
const response = await apiFetch(url, { headers: getAuthHeaders() });
return handleResponse(response);
},
async createVanityLink(data: {
vanity_code: string;
owner_email: string;
display_name?: string;
custom_message?: string;
discount_percent?: number;
kickback_percent?: number;
}): Promise<{ ok: boolean; code: string; message: string }> {
const response = await apiFetch(`${API_BASE_URL}/api/referrals/admin/vanity`, {
method: 'POST',
headers: { ...getAuthHeaders(), 'Content-Type': 'application/json' },
body: JSON.stringify(data),
});
return handleResponse(response);
},
async updateReferralLink(code: string, updates: Record<string, any>): Promise<{ ok: boolean; message: string }> {
const response = await apiFetch(`${API_BASE_URL}/api/referrals/admin/links/${encodeURIComponent(code)}`, {
method: 'PUT',
headers: { ...getAuthHeaders(), 'Content-Type': 'application/json' },
body: JSON.stringify(updates),
});
return handleResponse(response);
},
async listVanityRequests(status: 'pending' | 'approved' | 'denied' = 'pending'): Promise<{ requests: VanityRequest[]; count: number }> {
const response = await apiFetch(`${API_BASE_URL}/api/referrals/admin/vanity-requests?status=${status}`, {
headers: getAuthHeaders(),
});
return handleResponse(response);
},
async approveVanityRequest(requestId: string): Promise<{ ok: boolean; code: string; message: string }> {
const response = await apiFetch(`${API_BASE_URL}/api/referrals/admin/vanity-requests/${encodeURIComponent(requestId)}/approve`, {
method: 'POST',
headers: getAuthHeaders(),
});
return handleResponse(response);
},
async denyVanityRequest(requestId: string): Promise<{ ok: boolean; message: string }> {
const response = await apiFetch(`${API_BASE_URL}/api/referrals/admin/vanity-requests/${encodeURIComponent(requestId)}/deny`, {
method: 'POST',
headers: getAuthHeaders(),
});
return handleResponse(response);
},
async generateFlyer(code: string, theme: 'light' | 'dark', qrDataUrl: string): Promise<Blob> {
const response = await apiFetch(`${API_BASE_URL}/api/referrals/admin/links/${encodeURIComponent(code)}/flyer`, {
method: 'POST',
headers: { ...getAuthHeaders(), 'Content-Type': 'application/json' },
body: JSON.stringify({ theme, qr_data_url: qrDataUrl }),
});
if (!response.ok) {
const error = await response.json().catch(() => ({ detail: 'Failed to generate flyer' }));
throw new Error(error.detail || 'Failed to generate flyer');
}
return response.blob();
},
};
export interface EditReviewSummary {
job_id: string;
artist: string;
title: string;
user_email: string;
status: string;
created_at?: string;
updated_at?: string;
edit_log_session?: string;
edit_log_path?: string;
has_corrections_updated: boolean;
}
export interface EditReviewListResponse {
reviews: EditReviewSummary[];
total: number;
has_more: boolean;
}
export interface AdminEditLogEntry {
id: string;
timestamp: string;
operation: string;
segment_id?: string;
segment_index?: number;
word_ids_before?: string[];
word_ids_after?: string[];
text_before: string;
text_after: string;
details?: Record<string, unknown>;
feedback?: {
reason: string;
timestamp: string;
};
}
export interface AdminEditLog {
session_id: string;
job_id: string;
audio_hash?: string;
started_at?: string;
entries: AdminEditLogEntry[];
}
export interface EditReviewDetail {
job: {
job_id: string;
artist: string;
title: string;
user_email: string;
status: string;
created_at?: string;
updated_at?: string;
};
original_corrections: Record<string, unknown> | null;
updated_corrections: Record<string, unknown> | null;
edit_log: AdminEditLog | null;
annotations: Record<string, unknown> | null;
audio_url: string | null;
}
// Types for admin audio edit reviews
export interface AudioEditReviewSummary {
job_id: string;
artist: string;
title: string;
user_email: string;
status: string;
created_at?: string;
updated_at?: string;
session_count: number;
total_edits: number;
original_duration?: number;
current_duration?: number;
latest_trigger?: string;
}
export interface AudioEditReviewListResponse {
reviews: AudioEditReviewSummary[];
total: number;
has_more: boolean;
}
export interface AudioEditReviewDetail {
job: {
job_id: string;
artist: string;
title: string;
user_email: string;
status: string;
created_at?: string;
updated_at?: string;
};
sessions: Array<{
session_id: string;
job_id: string;
user_email: string;
created_at: string;
updated_at: string;
edit_count: number;
trigger: string;
audio_duration_seconds?: number;
original_duration_seconds?: number;
artist?: string;
title?: string;
summary: AudioEditSessionSummary;
edit_data_gcs_path: string;
data_hash: string;
}>;
edit_stack: Array<{
edit_id: string;
operation: string;
params: Record<string, unknown>;
gcs_path: string;
duration_before?: number;
duration_after?: number;
timestamp: string;
}>;
edit_log: unknown;
original_audio_url: string | null;
current_audio_url: string | null;
}
// Types for admin completion message API
export interface CompletionMessageResponse {
job_id: string;
message: string;
subject: string;
youtube_url?: string;
dropbox_url?: string;
}
export interface SendCompletionEmailResponse {
success: boolean;
job_id: string;
to_email: string;
message: string;
}
// Types for admin job files API
export interface FileInfo {
name: string;
path: string;
download_url: string;
category: string;
file_key: string;
}
export interface JobFilesResponse {
job_id: string;
artist?: string;
title?: string;
files: FileInfo[];
total_files: number;
}
export interface JobUpdateRequest {
artist?: string;
title?: string;
user_email?: string;
theme_id?: string;
brand_prefix?: string;
discord_webhook_url?: string;
youtube_description?: string;
youtube_description_template?: string;
customer_email?: string;
customer_notes?: string;
enable_cdg?: boolean;
enable_txt?: boolean;
enable_youtube_upload?: boolean;
non_interactive?: boolean;
prep_only?: boolean;
is_private?: boolean;
/** Translated lyrics language code; "" turns translated lyrics off. */
translation_language?: string;
}
export interface JobUpdateResponse {
status: string;
job_id: string;
updated_fields: string[];
message: string;
}
export interface JobResetResponse {
status: string;
job_id: string;
previous_status: string;
new_status: string;
message: string;
cleared_data: string[];
worker_triggered?: boolean; // Was worker auto-triggered? (only for instrumental_selected)
worker_trigger_error?: string; // Error message if trigger failed
}
export interface TriggerWorkerResponse {
status: string;
job_id: string;
worker_type: string;
triggered: boolean;
message: string;
error?: string;
}
export interface ClearWorkersResponse {
status: string;
job_id: string;
message: string;
cleared_keys: string[];
}
export interface AdminRerenderResponse {
status: string;
job_id: string;
message: string;
brand_code?: string | null;
notify_customer: boolean;
previous_outputs: Record<string, unknown>;
cleanup_results: Record<string, unknown>;
/** Outputs left in place (destination not re-published), e.g. YouTube now disabled. */
warnings?: string[];
}
export interface RegenerateScreensResponse {
status: string;
job_id: string;
message: string;
previous_screens_deleted: boolean;
worker_triggered: boolean;
error?: string;
}
export interface RestartJobRequest {
preserve_audio_stems: boolean;
delete_outputs: boolean;
}
export interface RestartJobResponse {
status: string;
job_id: string;
message: string;
previous_status: string;
new_status: string;
cleared_data: string[];
deleted_gcs_paths: string[];
workers_triggered: string[];
error?: string;
}
export interface OverrideAudioSourceRequest {
source_type: "audio_search";
}
export interface OverrideAudioSourceResponse {
status: string;
job_id: string;
message: string;
previous_source: string;
new_source: string;
cleared_data: string[];
new_status: string;
}
// ==========================================================================
// Lyrics Review API endpoints
// ==========================================================================
/**
* API client interface for LyricsAnalyzer component
*/
// Review Session types (backup/restore)
export interface ReviewSessionSummary {
total_segments: number
total_words: number
corrections_made: number
changed_words: Array<{ original: string; corrected: string; segment_index: number }>
}
export interface ReviewSession {
session_id: string
job_id: string
user_email: string
created_at: string | null
updated_at: string | null
edit_count: number
trigger: 'auto' | 'preview' | 'manual'
audio_duration_seconds: number | null
artist: string | null
title: string | null
summary: ReviewSessionSummary
}
export interface ReviewSessionWithData extends ReviewSession {
correction_data: CorrectionData | null
}
export interface LyricsReviewApiClient {
submitCorrections: (data: CorrectionData, isDuet?: boolean) => Promise<void>
submitAnnotations: (annotations: Omit<CorrectionAnnotation, 'annotation_id' | 'timestamp'>[]) => Promise<void>
submitEditLog: (editLog: EditLog) => Promise<void>
updateHandlers: (handlers: string[]) => Promise<CorrectionData>
addLyrics: (source: string, lyrics: string, force?: boolean) => Promise<AddLyricsResult>
searchLyrics: (artist: string, title: string, forceSources?: string[]) => Promise<SearchLyricsResponse>
getAudioUrl: (hash: string) => string
getVocalsAudioUrl: () => string
getVocalsPeaksUrl: () => string
generatePreviewVideo: (data: CorrectionData, isDuet?: boolean) => Promise<{
status: string
message?: string
preview_hash?: string
}>
getPreviewVideoStatus: (hash: string) => Promise<{
status: string
message?: string
}>
getPreviewVideoUrl: (hash: string) => string
getWaveformData: (numPoints?: number) => Promise<WaveformData>
refreshInstrumentalUrls: () => Promise<InstrumentalOption[]>
getInstrumentalState?: () => Promise<InstrumentalState>
completeReview: () => Promise<{ status: string; job_status: string; message: string }>
/** Admin only: mark the reviewed timing "perfectly synced" (word-timing reference set). */
setSyncReference?: (verified: boolean, notes?: string) => Promise<void>
// Review session methods
saveReviewSession: (data: CorrectionData, editCount: number, trigger: string, summary: ReviewSessionSummary) => Promise<{ status: string; session_id?: string; reason?: string }>
listReviewSessions: () => Promise<{ sessions: ReviewSession[] }>
getReviewSession: (sessionId: string) => Promise<ReviewSessionWithData>
deleteReviewSession: (sessionId: string) => Promise<{ status: string }>
}
/**
* Create a lyrics review API client for a specific job
*/
export function createLyricsReviewApiClient(jobId: string): LyricsReviewApiClient {
return {
/**
* Submit corrected lyrics data
*
* Backend expects: { corrections: { lines: [...], metadata: {...}, ...rest } }
* - 'lines' and 'metadata' are required by Pydantic validator
* - 'corrected_segments' and 'corrections' array are needed by render worker
*/
async submitCorrections(data: CorrectionData, isDuet?: boolean): Promise<void> {
// Wrap CorrectionData in the structure expected by CorrectionsSubmission
// - 'lines' is an alias for corrected_segments (required by validator)
// - Include full data for render worker compatibility
const payload: Record<string, unknown> = {
corrections: {
...data,
lines: data.corrected_segments,
}
}
// Only include is_duet when explicitly provided — omitting it preserves any
// previously-persisted flag rather than overwriting with false.
if (isDuet !== undefined) {
payload.is_duet = isDuet
}
const response = await apiFetch(`${API_BASE_URL}/api/jobs/${jobId}/corrections`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
...getAuthHeaders()
},
body: JSON.stringify(payload),
})
await handleResponse<{ status: string }>(response)
},
/**
* Submit human annotations/feedback on corrections
*/
async submitAnnotations(annotations: Omit<CorrectionAnnotation, 'annotation_id' | 'timestamp'>[]): Promise<void> {
const response = await apiFetch(`${API_BASE_URL}/api/review/${jobId}/v1/annotations`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
...getAuthHeaders()
},
body: JSON.stringify({ annotations }),
})
await handleResponse<{ status: string }>(response)
},
async submitEditLog(editLog: EditLog): Promise<void> {
const response = await apiFetch(`${API_BASE_URL}/api/jobs/${jobId}/edit-log`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
...getAuthHeaders()
},
body: JSON.stringify(editLog),
})
await handleResponse<{ status: string }>(response)
},
/**
* Update enabled correction handlers and get recalculated corrections
*/
async updateHandlers(handlers: string[]): Promise<CorrectionData> {
const response = await apiFetch(`${API_BASE_URL}/api/review/${jobId}/handlers`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
...getAuthHeaders()
},
body: JSON.stringify({ enabled_handlers: handlers }),
})
return handleResponse<CorrectionData>(response)
},
/**
* Add lyrics from a new source
*/
async addLyrics(source: string, lyrics: string, force: boolean = false): Promise<AddLyricsResult> {
const response = await apiFetch(`${API_BASE_URL}/api/review/${jobId}/add-lyrics`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
...getAuthHeaders()
},
// force is sent as a string because the endpoint body is typed Dict[str, str]
body: JSON.stringify({ source, lyrics, force: force ? 'true' : 'false' }),
})
// Backend returns { status: "success" | "rejected", data: CorrectionData, rejection?: {...} }
return handleResponse<AddLyricsResult>(response)
},
/**
* Search for lyrics from configured providers
*/
async searchLyrics(artist: string, title: string, forceSources: string[] = []): Promise<SearchLyricsResponse> {
const response = await apiFetch(`${API_BASE_URL}/api/review/${jobId}/search-lyrics`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
...getAuthHeaders()
},
body: JSON.stringify({
artist,
title,
force_sources: forceSources,
}),
})
return handleResponse<SearchLyricsResponse>(response)
},
/**
* Get audio URL for playback
*/
getAudioUrl(hash: string): string {
const token = getAccessToken()
const base = `${API_BASE_URL}/api/review/${jobId}/audio/${hash}`
return token ? `${base}?token=${encodeURIComponent(token)}` : base
},
/**
* Get vocals audio URL for playback
*/
getVocalsAudioUrl(): string {
const token = getAccessToken()
const base = `${API_BASE_URL}/api/review/${jobId}/audio/vocals`
return token ? `${base}?token=${encodeURIComponent(token)}` : base
},
/**
* Pre-computed vocals peak-envelope URL (Waveforms review mode).
* ~150 KB JSON instead of downloading + decoding the whole vocal stem.
*/
getVocalsPeaksUrl(): string {
const token = getAccessToken()
const base = `${API_BASE_URL}/api/review/${jobId}/vocals-peaks`
return token ? `${base}?token=${encodeURIComponent(token)}` : base
},
/**
* Generate a preview video from the current correction data.
*
* Returns status "success" when the video is immediately available
* (local render or cache hit), or "generating" when encoding continues
* in the background — poll getPreviewVideoStatus() until it's ready.
*/
async generatePreviewVideo(data: CorrectionData, isDuet?: boolean): Promise<{
status: string
message?: string
preview_hash?: string
}> {
const body: Record<string, unknown> = { ...data }
if (isDuet !== undefined) {
body.is_duet = isDuet
}
const response = await apiFetch(`${API_BASE_URL}/api/review/${jobId}/preview-video`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
...getAuthHeaders()
},
body: JSON.stringify(body),
})
return handleResponse(response)
},
/**
* Poll the state of a background preview encode ("ready" | "generating" | "error")
*/
async getPreviewVideoStatus(hash: string): Promise<{
status: string
message?: string
}> {
const response = await apiFetch(
`${API_BASE_URL}/api/review/${jobId}/preview-video/${hash}/status`,
{ headers: getAuthHeaders() }
)
return handleResponse(response)
},
/**
* Get preview video URL for playback
*/
getPreviewVideoUrl(hash: string): string {
const token = getAccessToken()
const base = `${API_BASE_URL}/api/review/${jobId}/preview-video/${hash}`
return token ? `${base}?token=${encodeURIComponent(token)}` : base
},
/**
* Get waveform amplitude data (backing-vocals stem) for client-side rendering.
*/
async getWaveformData(numPoints: number = 1000): Promise<WaveformData> {
const response = await apiFetch(
`${API_BASE_URL}/api/review/${jobId}/waveform-data?num_points=${numPoints}`,
{ headers: getAuthHeaders() }
)
return handleResponse(response)
},
/**
* Re-fetch instrumental stem URLs.
*
* Since the 2026-09-17 fast-load re-architecture these are same-origin proxy URLs
* that never expire, so a refresh is no longer strictly necessary — but the preview
* modal still calls this on an audio load error (e.g. a transient network blip), and
* it's cheap and harmless. Resolved to absolute token URLs like getCorrectionData.
*/
async setSyncReference(verified: boolean, notes?: string): Promise<void> {
const response = await apiFetch(`${API_BASE_URL}/api/review/${jobId}/sync-reference`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
...getAuthHeaders()
},
body: JSON.stringify({ verified, notes: notes || null }),
})
await handleResponse<unknown>(response)
},
async refreshInstrumentalUrls(): Promise<InstrumentalOption[]> {
const response = await apiFetch(
`${API_BASE_URL}/api/review/${jobId}/instrumental-urls`,
{ headers: getAuthHeaders() }
)
const data = await handleResponse<{ instrumental_options?: InstrumentalOption[] }>(response)
return resolveInstrumentalAudioUrls(jobId, data.instrumental_options ?? [])
},
/**
* Instrumental stems + backing analysis + separation status, for the review page's
* "stems arrived yet?" poll (review opens on lyrics completion, usually 2-3 minutes
* before audio separation finishes). Same endpoint as refreshInstrumentalUrls.
*/
async getInstrumentalState(): Promise<InstrumentalState> {
const response = await apiFetch(
`${API_BASE_URL}/api/review/${jobId}/instrumental-urls`,
{ headers: getAuthHeaders() }
)
const data = await handleResponse<InstrumentalState>(response)
return {
...data,
instrumental_options: resolveInstrumentalAudioUrls(jobId, data.instrumental_options ?? []),
}
},
/**
* Complete the review and trigger video rendering
*/
async completeReview(): Promise<{ status: string; job_status: string; message: string }> {
const response = await apiFetch(`${API_BASE_URL}/api/jobs/${jobId}/complete-review`, {
method: 'POST',
headers: getAuthHeaders()
})
return handleResponse(response)
},
// Review session methods
async saveReviewSession(data: CorrectionData, editCount: number, trigger: string, summary: ReviewSessionSummary) {
const response = await apiFetch(`${API_BASE_URL}/api/review/${jobId}/sessions`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
...getAuthHeaders()
},
body: JSON.stringify({
correction_data: data,
edit_count: editCount,
trigger,
summary,
}),
})
return handleResponse<{ status: string; session_id?: string; reason?: string }>(response)
},
async listReviewSessions() {
const response = await apiFetch(`${API_BASE_URL}/api/review/${jobId}/sessions`, {
headers: getAuthHeaders()
})
return handleResponse<{ sessions: ReviewSession[] }>(response)
},
async getReviewSession(sessionId: string) {
const response = await apiFetch(`${API_BASE_URL}/api/review/${jobId}/sessions/${sessionId}`, {
headers: getAuthHeaders()
})
return handleResponse<ReviewSessionWithData>(response)
},
async deleteReviewSession(sessionId: string) {
const response = await apiFetch(`${API_BASE_URL}/api/review/${jobId}/sessions/${sessionId}`, {
method: 'DELETE',
headers: getAuthHeaders()
})
return handleResponse<{ status: string }>(response)
},
}
}
/**
* Resolve instrumental option audio URLs for playback.
*
* The combined-review endpoints return each option's `audio_url` as a RELATIVE
* same-origin proxy path (e.g. `/api/review/{jobId}/instrumental-audio/clean`) — the
* review hot path no longer signs GCS URLs (2026-09-17 fast-load re-architecture). A raw
* <audio> src needs an ABSOLUTE URL to the API host plus auth in the query string (it
* can't send an Authorization header), so turn each relative path into
* `${API_BASE_URL}...?token=`. Already-absolute URLs (the local dev byte proxy) and null
* audio_urls are left untouched.
*/
function resolveInstrumentalAudioUrls<T extends { id?: string; audio_url?: string | null }>(
jobId: string,
options: T[],
): T[] {
const token = getAccessToken()
return options.map((o) => {
if (!o.audio_url || !o.id || /^https?:\/\//i.test(o.audio_url)) return o
const base = `${API_BASE_URL}/api/review/${jobId}/instrumental-audio/${o.id}`
return { ...o, audio_url: token ? `${base}?token=${encodeURIComponent(token)}` : base }
})
}
// Standalone lyrics review API functions (for use without jobId context)
export const lyricsReviewApi = {
/**
* Get correction data for a job
*/
async getCorrectionData(jobId: string, opts?: { replay?: boolean }): Promise<CorrectionData> {
// Replay mode (admin/owner) re-opens a COMPLETED job's review data read-only,
// without the status gate or the AWAITING_REVIEW->IN_REVIEW transition.
const qs = opts?.replay ? "?replay=true" : ""
const response = await apiFetch(`${API_BASE_URL}/api/review/${jobId}/correction-data${qs}`, {
headers: getAuthHeaders()
})
const data = await handleResponse<CorrectionData>(response)
if (data.instrumental_options) {
// Rewrite relative proxy paths into absolute, token-authenticated <audio> src URLs.
data.instrumental_options = resolveInstrumentalAudioUrls(jobId, data.instrumental_options)
}
return data
},
/**
* Get audio URL for a job by hash
*/
getAudioUrl(jobId: string, hash: string): string {
const token = getAccessToken()
const base = `${API_BASE_URL}/api/review/${jobId}/audio/${hash}`
return token ? `${base}?token=${encodeURIComponent(token)}` : base
},
/**
* Complete the review with corrections and instrumental selection
* This is the final submission endpoint for the combined review flow
*/
async completeReview(
jobId: string,
correctionData: CorrectionData,
instrumentalSelection: InstrumentalSelectionType,
isDuet?: boolean
): Promise<{ status: string; instrumental_selection: string }> {
const response = await apiFetch(`${API_BASE_URL}/api/review/${jobId}/complete`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
...getAuthHeaders()
},
body: JSON.stringify({
...correctionData,
instrumental_selection: instrumentalSelection,
is_duet: isDuet ?? false,
})
})
return handleResponse(response)
},
/**
* Get instrumental analysis data for review
* Uses the review API endpoint (for cloud mode)
*/
async getInstrumentalAnalysis(jobId: string): Promise<InstrumentalAnalysis> {
const response = await apiFetch(`${API_BASE_URL}/api/review/${jobId}/instrumental-analysis`, {
headers: getAuthHeaders()
})
return handleResponse(response)
},
/**
* Get waveform data for visualization
* Uses the review API endpoint (for cloud mode)
*/
async getWaveformData(jobId: string, numPoints: number = 1000): Promise<WaveformData> {
const response = await apiFetch(
`${API_BASE_URL}/api/review/${jobId}/waveform-data?num_points=${numPoints}`,
{ headers: getAuthHeaders() }
)
return handleResponse(response)
},
/**
* Get audio stream URL for stem playback
* Uses signed URLs from instrumental-analysis response
*/
getAudioStreamUrl(jobId: string, stemType: string): string {
const token = getAccessToken()
const base = `${API_BASE_URL}/api/review/${jobId}/audio/${stemType}`
return token ? `${base}?token=${encodeURIComponent(token)}` : base
},
}
/**
* Signal the backend to start the encoding worker VM.
* Fire-and-forget — doesn't wait for the VM to boot.
*
* Scoped to the job being reviewed: the endpoint authorizes via the same
* review access as the rest of the lyrics-review page (require_review_auth),
* so getAuthHeaders() supplies the reviewer's token. Passing an admin-only
* token was the previous behaviour and 403'd for every non-admin customer.
*/
export async function warmupEncodingWorker(jobId: string): Promise<void> {
if (!jobId) return
try {
await apiFetch(`${API_BASE_URL}/api/internal/encoding-worker/warmup/${encodeURIComponent(jobId)}`, {
method: 'POST',
headers: getAuthHeaders(),
})
} catch {
// Fire-and-forget, don't throw on failure
}
}
/**
* Send heartbeat to keep encoding worker alive during active session.
* Scoped to the job being reviewed (see warmupEncodingWorker).
*/
export async function heartbeatEncodingWorker(jobId: string): Promise<void> {
if (!jobId) return
try {
await apiFetch(`${API_BASE_URL}/api/internal/encoding-worker/heartbeat/${encodeURIComponent(jobId)}`, {
method: 'POST',
headers: getAuthHeaders(),
})
} catch {
// Fire-and-forget
}
}
export interface DeleteOutputsResponse {
status: string;
job_id: string;
message: string;
deleted_services: {
youtube: { status: string; video_id?: string; reason?: string; error?: string };
dropbox: { status: string; path?: string; reason?: string; error?: string };
gdrive: { status: string; files?: Record<string, boolean>; reason?: string; error?: string };
brand_code?: { status: string; code?: string; reason?: string; error?: string };
};
cleared_state_data: string[];
outputs_deleted_at: string;
}
// Rate Limits API Types
export interface YouTubeQueueEntry {
job_id: string;
status: string;
reason?: string;
user_email?: string;
artist?: string;
title?: string;
brand_code?: string;
queued_at?: string;
attempts: number;
max_attempts: number;
last_error?: string;
youtube_url?: string;
notification_sent: boolean;
}
export interface YouTubeQueueListResponse {
entries: YouTubeQueueEntry[];
stats: {
queued: number;
processing: number;
failed: number;
completed: number;
total: number;
};
}
export interface BlocklistsResponse {
external_domains: string[];
manual_domains: string[];
allowlisted_domains: string[];
blocked_emails: string[];
blocked_ips: string[];
last_sync_at?: string;
last_sync_count?: number;
updated_at?: string;
updated_by?: string;
}
export interface SuccessResponse {
success: boolean;
message: string;
}
// Feedback-for-Credits types
export interface FeedbackRequest {
overall_rating: number;
ease_of_use_rating: number;
lyrics_accuracy_rating: number;
correction_experience_rating: number;
what_went_well?: string;
what_could_improve?: string;
additional_comments?: string;
would_recommend: boolean;
would_use_again: boolean;
}
export interface FeedbackResponse {
status: string;
message: string;
credits_granted: number;
}
// =============================================================================
// Payment Admin Types
// =============================================================================
export interface RevenueSummary {
total_gross: number;
total_fees: number;
total_net: number;
total_refunds: number;
transaction_count: number;
average_order_value: number;
revenue_by_type: Record<string, number>;
}
export interface RevenueChartPoint {
date: string;
gross: number;
net: number;
fees: number;
count: number;
}
export interface PaymentRecord {
session_id: string;
payment_intent_id?: string;
charge_id?: string;
amount_total: number;
currency: string;
stripe_fee: number;
net_amount: number;
customer_email: string;
customer_name: string;
stripe_customer_id?: string;
payment_method_type: string;
card_brand: string;
card_last4: string;
order_type: string;
package_id?: string;
credits_granted: number;
product_description: string;
artist?: string;
title?: string;
job_id?: string;
status: string;
refund_amount: number;
refund_id?: string;
refunded_at?: string;
refund_reason?: string;
created_at?: string;
processed_at?: string;
is_test: boolean;
promotion_code?: string;
discount_amount: number;
receipt_url?: string;
stripe_dashboard_url?: string;
}
export interface PaymentListResponse {
payments: PaymentRecord[];
total: number;
has_more: boolean;
}
export interface StripeBalance {
available: number;
pending: number;
currency: string;
}
export interface PayoutRecord {
id: string;
amount: number;
currency: string;
status: string;
arrival_date?: number;
created?: number;
description?: string;
method?: string;
}
export interface DisputeRecord {
id: string;
amount: number;
currency: string;
status: string;
reason: string;
charge_id?: string;
created?: number;
evidence_due_by?: number;
payment_intent_id?: string;
}
export interface UserPaymentHistory {
email: string;
payments: PaymentRecord[];
total_spent: number;
total_refunded: number;
net_spent: number;
payment_count: number;
first_payment_at?: string;
last_payment_at?: string;
}
export interface WebhookEvent {
event_id: string;
event_type: string;
created_at?: string;
processed_at?: string;
status: string;
error_message?: string;
session_id?: string;
customer_email?: string;
summary?: string;
}
export interface RefundRequest {
amount?: number;
reason: string;
}
export interface RefundResponse {
success: boolean;
message: string;
session_id: string;
}
export interface ChangeVisibilityResponse {
status: string;
job_id: string;
message: string;
previous_visibility: string;
new_visibility: string;
reprocessing_required: boolean;
}
// Anti-abuse investigation types
export interface AbuseSuspiciousUser {
email: string;
signup_ip: string | null;
device_fingerprint: string | null;
credits: number;
total_jobs_created: number;
total_jobs_completed: number;
total_spent: number;
has_submitted_feedback: boolean;
created_at: string;
last_login_at: string | null;
}
export interface AbuseSuspiciousResponse {
count: number;
users: AbuseSuspiciousUser[];
}
export interface AbuseRelatedUser {
email: string;
credits: number;
total_jobs_created: number;
total_spent: number;
created_at: string;
signup_ip?: string | null;
device_fingerprint?: string | null;
}
export interface AbuseRelatedResponse {
user: {
email: string;
signup_ip: string | null;
device_fingerprint: string | null;
credits: number;
total_jobs_created: number;
total_spent: number;
created_at: string;
};
related_by_ip: AbuseRelatedUser[];
related_by_fingerprint: AbuseRelatedUser[];
}
export interface AbuseByIpResponse {
ip_address: string;
count: number;
users: AbuseRelatedUser[];
}
export interface AbuseByFingerprintResponse {
device_fingerprint: string;
count: number;
users: AbuseRelatedUser[];
}
// Correlation cluster types
export interface AbuseClusterUser {
email: string;
signup_ip: string | null;
device_fingerprint: string | null;
credits: number;
total_jobs_created: number;
total_jobs_completed: number;
total_spent: number;
created_at: string;
user_agent?: string | null;
}
export interface AbuseFingerprintCluster {
fingerprint: string;
count: number;
users: AbuseClusterUser[];
}
export interface AbuseIpCluster {
ip: string;
count: number;
users: AbuseClusterUser[];
}
export interface AbuseCorrelationsResponse {
fingerprint_clusters: AbuseFingerprintCluster[];
ip_clusters: AbuseIpCluster[];
}
// IP geolocation types
export interface IpGeoInfo {
status: string;
ip: string;
country?: string;
country_code?: string;
region?: string;
city?: string;
isp?: string;
org?: string;
as_number?: string;
as_name?: string;
timezone?: string;
cached_at?: string;
}
// Admin feedback types
export interface AdminFeedbackItem {
id: string;
user_email: string;
created_at: string | null;
overall_rating: number;
ease_of_use_rating: number;
lyrics_accuracy_rating: number;
correction_experience_rating: number;
what_went_well: string | null;
what_could_improve: string | null;
additional_comments: string | null;
would_recommend: boolean;
would_use_again: boolean;
}
export interface AdminFeedbackListResponse {
items: AdminFeedbackItem[];
total: number;
offset: number;
limit: number;
has_more: boolean;
avg_overall_rating: number | null;
avg_ease_of_use_rating: number | null;
avg_lyrics_accuracy_rating: number | null;
avg_correction_experience_rating: number | null;
}
export { ApiError };
// ============================================================================
// Referral API
// ============================================================================
export async function getReferralInterstitial(code: string, noTrack = false): Promise<ReferralInterstitial> {
const url = `${API_BASE_URL}/api/referrals/r/${encodeURIComponent(code)}${noTrack ? '?no_track=true' : ''}`;
const response = await apiFetch(url);
if (!response.ok) throw new Error('Failed to fetch referral info');
return response.json();
}
export async function getReferralDashboard(): Promise<ReferralDashboard> {
const response = await apiFetch(`${API_BASE_URL}/api/referrals/me`, {
headers: getAuthHeaders(),
});
if (!response.ok) throw new Error('Failed to fetch referral dashboard');
return response.json();
}
export async function updateReferralLink(updates: {
display_name?: string;
custom_message?: string;
}): Promise<void> {
const response = await apiFetch(`${API_BASE_URL}/api/referrals/me`, {
method: 'PUT',
headers: { ...getAuthHeaders(), 'Content-Type': 'application/json' },
body: JSON.stringify(updates),
});
if (!response.ok) throw new Error('Failed to update referral link');
}
export async function startConnectOnboarding(): Promise<{ account_id: string; onboarding_url: string }> {
const response = await apiFetch(`${API_BASE_URL}/api/referrals/me/connect`, {
method: 'POST',
headers: getAuthHeaders(),
});
if (!response.ok) throw new Error('Failed to start Connect onboarding');
return response.json();
}
export async function getConnectDashboardLink(): Promise<{ url: string }> {
const response = await apiFetch(`${API_BASE_URL}/api/referrals/me/connect/dashboard-link`, {
method: 'POST',
headers: getAuthHeaders(),
});
if (!response.ok) throw new Error('Failed to get dashboard link');
return response.json();
}
export async function getConnectUpdateLink(): Promise<{ url: string }> {
const response = await apiFetch(`${API_BASE_URL}/api/referrals/me/connect/update-link`, {
method: 'POST',
headers: getAuthHeaders(),
});
if (!response.ok) throw new Error('Failed to get update link');
return response.json();
}
export async function requestVanityUrl(desiredCode: string): Promise<{ ok: boolean; message: string }> {
const response = await apiFetch(`${API_BASE_URL}/api/referrals/me/vanity-request`, {
method: 'POST',
headers: { ...getAuthHeaders(), 'Content-Type': 'application/json' },
body: JSON.stringify({ desired_code: desiredCode }),
});
if (!response.ok) {
const error = await response.json().catch(() => ({ detail: 'Request failed' }));
throw new Error(error.detail || 'Request failed');
}
return response.json();
}
export async function generateFlyer(theme: 'light' | 'dark', qrDataUrl: string): Promise<Blob> {
const response = await apiFetch(`${API_BASE_URL}/api/referrals/me/flyer`, {
method: 'POST',
headers: { ...getAuthHeaders(), 'Content-Type': 'application/json' },
body: JSON.stringify({ theme, qr_data_url: qrDataUrl }),
});
if (!response.ok) {
const error = await response.json().catch(() => ({ detail: 'Failed to generate flyer' }));
throw new Error(error.detail || 'Failed to generate flyer');
}
return response.blob();
}