@nitida/sdk 0.24.0 → 0.24.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts"],"sourcesContent":["/**\n * @nitida/sdk — universal client for the aquienpz multi-tenant asset\n * platform.\n *\n * One ergonomic facade over the underlying packages\n * (`@nitida/asset-client` URL builders + `@aquienpz/asset-uploader-web`\n * + the slot resolver). Auth is a Better Auth API key (`amk_rt_*`)\n * issued by aquienpz `bootstrap-project.ts`; tenant scope comes from\n * the key's metadata (`X-Tenant-Code` is log-only).\n *\n * Usage:\n *\n * import { NitidaClient } from \"@nitida/sdk\";\n *\n * const aq = new NitidaClient({\n * endpoint: \"https://api.nitida.gofuture.space\",\n * apiKey: process.env.ASSET_MANAGER_RUNTIME_KEY!,\n * tenantCode: \"realtyone-cr\",\n * cdnBase: \"https://8ok.uk\", // optional override\n * tenantId: 4, // required for tenant-prefixed URLs\n * });\n *\n * // Slot system (recommended — admin can rebind without redeploys).\n * const hero = await aq.slots.resolve(\"storefront.cr.hero\");\n * const set = await aq.slots.resolveMany([\"a\", \"b\", \"c\"]);\n *\n * // Lower-level asset operations.\n * const asset = await aq.assets.byHash(sha);\n * const list = await aq.assets.list({ limit: 50 });\n *\n * // Upload bytes / files.\n * const up = await aq.upload(file, { fileName: \"cover.jpg\" });\n *\n * For React, see `@nitida/sdk/react` (useSlot, useSlots, useAsset).\n * @module @nitida/sdk\n */\n\nimport {\n type AssetDTO,\n type AssetVariant,\n configureSlotResolver,\n getAssetSrcSet,\n getAssetUrl,\n getHlsStreamingUrl,\n getSignedTransformUrl,\n getTransformSrcSet,\n getTransformUrl,\n getVideoTransformUrl,\n hasPreset,\n invalidateSlotCache,\n type ResolveSlotOptions,\n resolveSlot,\n resolveSlots,\n type SignedTransformOptions,\n type SlotDTO,\n type SlotResolution,\n setCdnBase,\n setTenantId,\n type TransformOptions,\n type VariantPreset,\n} from \"@nitida/asset-client\";\n\n// ---------------------------------------------------------------------------\n// Config\n// ---------------------------------------------------------------------------\n\n/**\n * Permissive constructor options for the root `NitidaClient`.\n *\n * App code should NOT import this type directly — prefer the strict\n * variants from the subpaths:\n *\n * - `WebClientOptions` from `@nitida/sdk/web` (no `apiKey`)\n * - `ServerClientOptions` from `@nitida/sdk/server` (`apiKey` required)\n *\n * This root type is the union both modes resolve to; the underlying class\n * accepts both shapes so subpath wrappers can extend without duplication.\n */\nexport type NitidaClientOptions = {\n /**\n * Base URL of the aquienpz asset-manager (Cloud Run service URL).\n *\n * May be relative (e.g. `/api/am`) ONLY in browser contexts where the\n * SDK resolves it against `window.location.origin`. Node/Bun consumers\n * must always pass an absolute URL.\n */\n endpoint: string;\n /**\n * Better Auth API key with the `amk_rt_*` prefix.\n *\n * **Server-only.** Omit when constructing from `@nitida/sdk/web` —\n * your BFF / route handler injects the bearer header in proxy mode.\n */\n apiKey?: string;\n /**\n * Extra headers merged into every request. The documented way for\n * mobile/Expo clients to authenticate a BFF that gates on the Better Auth\n * session: they can't send cookies automatically, so they pass\n * `{ Cookie: authClient.getCookie() }` here (see Better Auth Expo docs,\n * \"Making Authenticated Requests to Your Server\"). Web/server consumers omit\n * this — browsers attach the same-origin cookie and servers pass `apiKey`.\n */\n headers?: Record<string, string>;\n /** Tenant code — sent as `X-Tenant-Code` (log-only). Authoritative scope is the key's metadata.tenantId. */\n tenantCode: string;\n /** Numeric tenant id — used to build tenant-prefixed CDN URLs `<cdn>/<tenantId b36>/v/<sha>-<preset>.<ext>`. */\n tenantId: number;\n /** Override the public CDN base. Defaults to `https://8ok.uk`. */\n cdnBase?: string;\n /**\n * Tenant's HMAC signing key for transform URLs (Phase 3). Required\n * only when calling `aq.transform(asset, opts, { sign: true })`.\n *\n * Generated server-side per tenant (see `infra/sql/tenants_signed_transforms.sql`);\n * fetch via `GET /admin/tenants/:id` with an admin key. **Keep it\n * server-side only** — do not ship in `NEXT_PUBLIC_*` env vars. Sign\n * URLs from a BFF route handler, or pre-sign at build time.\n */\n signingKey?: string;\n};\n\n// ---------------------------------------------------------------------------\n// URL construction\n// ---------------------------------------------------------------------------\n\n/**\n * Build a fully-qualified URL for an aquienpz endpoint path.\n *\n * Accepts both absolute endpoints (`https://api.nitida.gofuture.space`) and\n * relative ones (`/api/am`) — the latter only works in browser contexts\n * (resolved against `window.location.origin`). Node/Bun throws a clear\n * error if a relative endpoint is configured.\n *\n * The native `URL` constructor throws on relative inputs, so every fetch\n * site in the SDK must go through this helper instead of `new URL(...)`.\n */\nfunction endpointUrl(\n opts: Pick<NitidaClientOptions, \"endpoint\">,\n path: string,\n searchParams?: Record<string, string | number | boolean | undefined>,\n): URL {\n const endpoint = opts.endpoint.replace(/\\/+$/, \"\");\n const isAbsolute = /^https?:\\/\\//i.test(endpoint);\n let base: string;\n if (isAbsolute) {\n base = `${endpoint}${path}`;\n } else if (typeof window !== \"undefined\" && window.location?.origin) {\n base = `${window.location.origin}${endpoint}${path}`;\n } else {\n throw new Error(\n `[@nitida/sdk] relative endpoint \"${endpoint}\" requires a browser; ` +\n \"pass an absolute URL when using the SDK from Node/Bun.\",\n );\n }\n const u = new URL(base);\n if (searchParams) {\n for (const [k, v] of Object.entries(searchParams)) {\n if (v !== undefined && v !== null && v !== \"\") {\n u.searchParams.set(k, String(v));\n }\n }\n }\n return u;\n}\n\n/** Build a request URL as a plain string (no search params). */\nfunction endpointHref(\n opts: Pick<NitidaClientOptions, \"endpoint\">,\n path: string,\n): string {\n return endpointUrl(opts, path).toString();\n}\n\n/**\n * Auth headers — conditionally includes `Authorization` only when an\n * `apiKey` is present. In BFF-proxy mode (browser via `/web`) the\n * proxy injects the real bearer header, so we omit it here.\n */\nfunction authHeaders(opts: NitidaClientOptions): Record<string, string> {\n const h: Record<string, string> = {\n // Caller-supplied headers first; `X-Tenant-Code` stays authoritative below.\n ...opts.headers,\n \"X-Tenant-Code\": opts.tenantCode,\n };\n if (opts.apiKey) h.Authorization = `Bearer ${opts.apiKey}`;\n return h;\n}\n\n// ---------------------------------------------------------------------------\n// Re-exports (so consumers don't double-import from asset-client)\n// ---------------------------------------------------------------------------\n\nexport type {\n AssetDTO,\n AssetVariant,\n ResolveSlotOptions,\n SignedTransformOptions,\n SlotDTO,\n SlotResolution,\n TransformEffect,\n TransformFit,\n TransformFormat,\n TransformGravity,\n TransformOptions,\n VariantPreset,\n} from \"@nitida/asset-client\";\nexport {\n computeVariantDimensions,\n extractAssetSha,\n getAssetDimensions,\n getAssetSrcSet,\n getAssetUrl,\n getHlsStreamingUrl,\n getSignedTransformUrl,\n getTenantId,\n getTransformSrcSet,\n getTransformUrl,\n getVideoTransformUrl,\n hasPreset,\n serializeTransform,\n setTenantId,\n signTransformUrl,\n} from \"@nitida/asset-client\";\n\n// ---------------------------------------------------------------------------\n// Sub-namespaces\n// ---------------------------------------------------------------------------\n\nclass SlotsApi {\n constructor(private readonly opts: NitidaClientOptions) {}\n\n /** Resolve one slot — returns `{slot, preset, url}` or `{slot: null, url: null}` when unbound. */\n resolve(\n slotKey: string,\n options: ResolveSlotOptions = {},\n ): Promise<SlotResolution> {\n return resolveSlot(slotKey, options);\n }\n\n /** Bulk-resolve N slots in one HTTP round-trip. */\n resolveMany(\n slotKeys: string[],\n options: ResolveSlotOptions = {},\n ): Promise<Record<string, SlotResolution>> {\n return resolveSlots(slotKeys, options);\n }\n\n /** List slots for the tenant (admin). Optional prefix filter for tree views. */\n async list(\n opts: { prefix?: string; limit?: number } = {},\n ): Promise<SlotDTO[]> {\n const u = endpointUrl(this.opts, \"/slots\", {\n prefix: opts.prefix,\n limit: opts.limit,\n });\n const r = await fetch(u, { headers: this.headers() });\n if (!r.ok) throw new Error(`slots list ${r.status}: ${await r.text()}`);\n const body = (await r.json()) as { slots: SlotDTO[] };\n return body.slots;\n }\n\n /** Bind / rebind a slot to an asset. Admin-only operation. */\n async bind(\n slotKey: string,\n body: {\n assetId: string;\n preset?: VariantPreset;\n description?: string;\n updatedBy?: string;\n },\n ): Promise<{ ok: true; slotKey: string; assetId: string }> {\n const r = await fetch(\n endpointHref(this.opts, `/slots/${encodeURIComponent(slotKey)}`),\n {\n method: \"PUT\",\n headers: { ...this.headers(), \"Content-Type\": \"application/json\" },\n body: JSON.stringify(body),\n },\n );\n if (!r.ok) throw new Error(`slot bind ${r.status}: ${await r.text()}`);\n return (await r.json()) as { ok: true; slotKey: string; assetId: string };\n }\n\n /**\n * Recent bindings for a slot. Lets the admin audit who changed\n * what and restore a previous binding without remembering the\n * asset id. Default limit 20, max 100.\n */\n async history(\n slotKey: string,\n opts: { limit?: number } = {},\n ): Promise<SlotHistoryEntry[]> {\n const u = endpointUrl(\n this.opts,\n `/slots/${encodeURIComponent(slotKey)}/history`,\n { limit: opts.limit },\n );\n const r = await fetch(u, { headers: this.headers() });\n if (!r.ok) throw new Error(`slots history ${r.status}: ${await r.text()}`);\n const body = (await r.json()) as { history: SlotHistoryEntry[] };\n return body.history;\n }\n\n /**\n * Restore the slot to a previous binding. Equivalent to\n * `bind(key, { assetId: previous.assetId, action: \"restore\" })`\n * — the audit row is tagged `restore` instead of `bind`.\n */\n async restore(\n slotKey: string,\n args: { assetId: string; preset?: VariantPreset; updatedBy?: string },\n ): Promise<{ ok: true; slotKey: string; assetId: string }> {\n const r = await fetch(\n endpointHref(this.opts, `/slots/${encodeURIComponent(slotKey)}`),\n {\n method: \"PUT\",\n headers: { ...this.headers(), \"Content-Type\": \"application/json\" },\n body: JSON.stringify({ ...args, action: \"restore\" }),\n },\n );\n if (!r.ok) throw new Error(`slot restore ${r.status}: ${await r.text()}`);\n return (await r.json()) as { ok: true; slotKey: string; assetId: string };\n }\n\n /** Remove a slot binding. The asset itself is left alone. */\n async unbind(slotKey: string): Promise<{ ok: true; removed: number }> {\n const r = await fetch(\n endpointHref(this.opts, `/slots/${encodeURIComponent(slotKey)}`),\n {\n method: \"DELETE\",\n headers: this.headers(),\n },\n );\n if (!r.ok) throw new Error(`slot unbind ${r.status}: ${await r.text()}`);\n return (await r.json()) as { ok: true; removed: number };\n }\n\n /** Invalidate the in-process cache after a slot rebind. */\n invalidateCache(slotKey?: string): void {\n invalidateSlotCache(slotKey);\n }\n\n private headers(): Record<string, string> {\n return authHeaders(this.opts);\n }\n}\n\n/**\n * Returned by `aq.assets.regenerate(...)`. The shape varies by kind —\n * images return immediately with the merged variant list; videos\n * return a dispatch handle (the actual transcode runs in a Cloud Run\n * Job and finishes async).\n */\nexport type RegenerateResult =\n | {\n ok: true;\n kind: \"image\";\n /** Full variant set after the merge. */\n variants: AssetVariant[];\n /** Presets newly written this run. Useful for showing \"added X\". */\n newVariants: VariantPreset[];\n /**\n * Which source the server read to derive the new variants:\n * - `\"original\"` / `\"raw\"` → lossless source bytes (best)\n * - `\"xl\"` / `\"lg\"` / `\"md\"` / `\"sm\"` / `\"thumb\"` → a previously\n * encoded WebP variant was used as the source. Output is\n * re-encoded WebP — fine for thumb/sm from lg, lossier when\n * working from already-small sources.\n *\n * The no-upscale clamp still applies: deriving `lg` (1920) from\n * a 640 `sm` source produces a 640-side `lg` variant, not a\n * stretched 1920.\n */\n sourceUsed: VariantPreset | \"raw\";\n }\n | {\n ok: true;\n kind: \"video\";\n dispatch: unknown;\n regenerated: string[] | \"default\";\n };\n\n/**\n * Wire shape returned by `POST /assets/upload-url`. Either the server\n * resolves the upload synchronously via dedup (`deduped: true` + existing\n * asset DTO) or it returns a presigned R2 PUT URL plus a `process` payload\n * the caller must POST to `/assets/process` after the PUT lands.\n */\nexport type UploadUrlResult =\n | { deduped: true; asset: AssetDTO }\n | {\n deduped: false;\n upload: { url: string; headers?: Record<string, string> };\n process: { url: string; body: Record<string, unknown> };\n };\n\n/**\n * VIDEO-only delivery knobs threaded into `/assets/process`. Ignored for\n * image / audio / other uploads. Both fields default to today's behavior when\n * omitted, so existing callers are unaffected.\n */\nexport type UploadVideoOptions = {\n /**\n * `false` → skip the auto-dispatched HLS adaptive ladder (240p–2160p). Use\n * for download-only assets served as a progressive `-v.mp4` and never\n * streamed (e.g. share-video reels) — it avoids a second Cloud Run Job no\n * one watches. Default/absent → the ladder is generated as before.\n */\n hls?: boolean;\n /**\n * `true` → when the uploaded MP4 is ALREADY web-safe (H.264 + yuv420p),\n * re-mux the `video` variant with `-c copy` instead of re-encoding. Use for\n * delivery-ready uploads (the bytes are already H.264 High / yuv420p /\n * +faststart / capped bitrate) to skip a wasteful re-encode + generational\n * quality loss. Falls back to a full re-encode automatically when the source\n * is not web-safe. Default/absent → unconditional re-encode (today's path).\n */\n passthrough?: boolean;\n};\n\n/** Input shape accepted by `aq.assets.presignUploadUrl(...)`. */\nexport type PresignUploadUrlOptions = {\n /** Full sha256 (64 hex) of the bytes that will be PUT to R2. */\n sha256: string;\n /** MIME type of the bytes (e.g. `image/jpeg`, `video/mp4`). */\n mime: string;\n /** Byte length of the upload payload. */\n bytes: number;\n /** Suggested file name; surfaces in admin dashboards + extension fallback. */\n fileName: string;\n /**\n * Variant ladder to generate after `/assets/process`. Defaults to\n * `[\"original\"]` server-side when omitted — same contract as `aq.upload`.\n */\n presets?: VariantPreset[];\n /**\n * Pre-compression size of the source (useful when the browser ran\n * compressorjs / heic2any before computing `bytes`). Surfaces in admin\n * dashboards under `assets.client_original_bytes`.\n */\n clientOriginalBytes?: number;\n /** VIDEO-only delivery knobs forwarded into `/assets/process`. See {@link UploadVideoOptions}. */\n video?: UploadVideoOptions;\n};\n\n/** Input shape accepted by `aq.assets.composeMarketing(...)`. */\nexport type ComposeMarketingSegment = {\n /** Public URL of the source clip (typically a `/t/.../video.mp4` transform). */\n sourceUrl: string;\n /** Optional clip duration in seconds (cap for that segment). */\n durationSec?: number;\n};\n\nexport type ComposeMarketingComposition = {\n /** Transition between consecutive segments. Default `\"cut\"`. */\n transition?: \"cut\" | \"fade\";\n /** Optional audio track to mix on top of the final composition. */\n audioTrack?: { url: string };\n /** Final composition length in seconds (server may clamp). */\n finalDurationSec?: number;\n};\n\nexport type ComposeMarketingOptions = {\n /** Marketing-kit id this composition belongs to (server uses it for naming + dedup). */\n marketingKitId: string;\n /** Ordered clip segments to stitch. */\n segments: ComposeMarketingSegment[];\n /** Optional composition-level knobs (transitions, audio, duration). */\n composition?: ComposeMarketingComposition;\n};\n\nexport type ComposeMarketingResult = {\n /** Aquienpz asset id of the in-flight composition. Poll `aq.assets.waitReady(id)`. */\n assetId: string;\n /** Asset status at dispatch time — usually `\"processing\"`. */\n status: \"processing\" | \"ready\" | \"failed\";\n};\n\nclass AssetsApi {\n constructor(private readonly opts: NitidaClientOptions) {}\n\n /** Look up an asset by full sha256 (64 hex). Returns null on 404. */\n async byHash(sha256: string): Promise<AssetDTO | null> {\n const r = await fetch(\n endpointHref(this.opts, `/assets/by-hash/${sha256}`),\n { headers: this.headers() },\n );\n if (r.status === 404) return null;\n if (!r.ok) throw new Error(`assets byHash ${r.status}: ${await r.text()}`);\n return (await r.json()) as AssetDTO;\n }\n\n /** Bulk lookup by sha256s. */\n async byHashes(\n hashes: string[],\n ): Promise<{ existing: AssetDTO[]; missing: string[] }> {\n const r = await fetch(endpointHref(this.opts, \"/assets/by-hashes\"), {\n method: \"POST\",\n headers: { ...this.headers(), \"Content-Type\": \"application/json\" },\n body: JSON.stringify({ hashes }),\n });\n if (!r.ok)\n throw new Error(`assets byHashes ${r.status}: ${await r.text()}`);\n return (await r.json()) as { existing: AssetDTO[]; missing: string[] };\n }\n\n /** Paginated list of recent assets for the tenant. */\n async list(\n opts: { limit?: number; cursor?: string; includeDeleted?: boolean } = {},\n ): Promise<{\n assets: AssetDTO[];\n nextCursor: string | null;\n }> {\n const u = endpointUrl(this.opts, \"/assets\", {\n limit: opts.limit,\n cursor: opts.cursor,\n include_deleted: opts.includeDeleted ? \"true\" : undefined,\n });\n const r = await fetch(u, { headers: this.headers() });\n if (!r.ok) throw new Error(`assets list ${r.status}: ${await r.text()}`);\n return (await r.json()) as {\n assets: AssetDTO[];\n nextCursor: string | null;\n };\n }\n\n /** Full DTO for an asset (admin view — includes audit-only fields). */\n async get(assetId: string): Promise<AssetDTO & Record<string, unknown>> {\n const r = await fetch(endpointHref(this.opts, `/assets/${assetId}`), {\n headers: this.headers(),\n });\n if (!r.ok) throw new Error(`asset get ${r.status}: ${await r.text()}`);\n return (await r.json()) as AssetDTO & Record<string, unknown>;\n }\n\n /**\n * Slot bindings pointing at an asset. Use this before deleting an\n * asset so the admin sees which storefront slots would suddenly\n * resolve to nothing.\n */\n async bindings(assetId: string): Promise<\n Array<{\n slotKey: string;\n preset: VariantPreset | null;\n description: string | null;\n updatedAt: string;\n updatedBy: string | null;\n }>\n > {\n const r = await fetch(endpointHref(this.opts, `/assets/${assetId}/slots`), {\n headers: this.headers(),\n });\n if (!r.ok) throw new Error(`asset bindings ${r.status}: ${await r.text()}`);\n const body = (await r.json()) as {\n slots: Array<{\n slotKey: string;\n preset: VariantPreset | null;\n description: string | null;\n updatedAt: string;\n updatedBy: string | null;\n }>;\n };\n return body.slots;\n }\n\n /**\n * Full variant list for an asset — preset, URL, dimensions, bytes.\n * Stronger-typed wrapper around `get()` that exposes only the\n * `variants` field with the proper `AssetVariant[]` shape.\n *\n * const v = await aq.assets.variants(logoId);\n * v.map((x) => x.preset); // → (\"thumb\" | \"sm\" | … | \"original\")[]\n *\n * ⚠️ Returns `[]` — not an error — against an `asset-manager` older than the\n * 2026-08-17 deploy, which never sent the field (doc 240 §4.3). An empty\n * array is therefore \"no variants OR old server\". For a plain existence\n * check prefer `hasPreset(dto, preset)` on `dto.presets`, which every server\n * version sends; use this when you need the URLs and sizes.\n */\n async variants(assetId: string): Promise<AssetVariant[]> {\n const dto = await this.get(assetId);\n return Array.isArray((dto as { variants?: unknown }).variants)\n ? (dto as { variants: AssetVariant[] }).variants\n : [];\n }\n\n /**\n * Add or rebuild variants on an existing asset. Image presets are\n * MERGED with what's there — passing `{ presets: [\"thumb\"] }` adds\n * the thumb variant without touching `lg`, `sm`, `original`, etc.\n *\n * // Day 0: upload original-only logo\n * const { assetId } = await aq.upload(logoFile); // defaults to [\"original\"]\n *\n * // Day 7: need a thumb without re-uploading\n * await aq.assets.regenerate(assetId, { presets: [\"thumb\"] });\n *\n * const after = await aq.assets.variants(assetId);\n * after.map((v) => v.preset); // → [\"original\", \"thumb\"]\n *\n * Passing no presets re-runs the FULL default pipeline for that\n * asset's kind (thumb+sm+md+lg for images, poster+video for video).\n *\n * If the asset was uploaded original-only and the cleanup job has\n * already reaped `raw/`, the route falls back to reading the source\n * bytes from `variants/o.<ext>` — no need to re-upload.\n *\n * Video presets are filtered to `[\"poster\",\"video\",\"aiproxy\"]` and\n * dispatched to the Cloud Run Job (the call returns immediately\n * with a dispatch handle; poll `aq.assets.get(id).status` for\n * completion).\n */\n async regenerate(\n assetId: string,\n opts: { presets?: VariantPreset[] } = {},\n ): Promise<RegenerateResult> {\n const r = await fetch(\n endpointHref(this.opts, `/assets/${assetId}/regenerate`),\n {\n method: \"POST\",\n headers: { ...this.headers(), \"Content-Type\": \"application/json\" },\n body: JSON.stringify(opts.presets ? { presets: opts.presets } : {}),\n },\n );\n if (!r.ok)\n throw new Error(`asset regenerate ${r.status}: ${await r.text()}`);\n return (await r.json()) as RegenerateResult;\n }\n\n /** Merge metadata into an asset (role / slot / description / tags). */\n async patchMetadata(\n assetId: string,\n metadata: Record<string, unknown>,\n ): Promise<{ ok: true; metadata: Record<string, unknown> }> {\n const r = await fetch(endpointHref(this.opts, `/assets/${assetId}`), {\n method: \"PATCH\",\n headers: { ...this.headers(), \"Content-Type\": \"application/json\" },\n body: JSON.stringify({ metadata }),\n });\n if (!r.ok) throw new Error(`asset patch ${r.status}: ${await r.text()}`);\n return (await r.json()) as { ok: true; metadata: Record<string, unknown> };\n }\n\n /**\n * Request a presigned R2 PUT URL for direct browser-side uploads.\n *\n * Mirrors the first half of `aq.upload()` — the caller (typically a\n * BFF / share-link dropzone) computes sha256 in the browser, then\n * uploads bytes straight to R2 with the returned `upload.url`, then\n * POSTs `process.body` to `/assets/process` (see {@link processAndWait})\n * once R2 has the bytes.\n *\n * If the sha is already known to the tenant the server short-circuits\n * with `{ deduped: true, asset }` — no PUT needed.\n *\n * @example The browser-direct flow, in full\n * ```ts\n * // SERVER (holds the amk_rt_* key — never the browser):\n * const presign = await aq.assets.presignUploadUrl({ sha256, mime, bytes, fileName, presets });\n * if (presign.deduped) return presign.asset; // those bytes already exist; none fly\n *\n * // BROWSER: PUT straight to presign.upload.url — the bytes never touch your server.\n * // ⚠️ R2 answers that preflight ITSELF, so your origin must be in the BUCKET's CORS policy.\n * // Symptom when it is not: \"PUT failed: network error\" with every earlier step green —\n * // and it cannot be fixed in this SDK, in your app, or in `storefront_origins`.\n *\n * // SERVER again, forwarding presign.process.body VERBATIM:\n * const asset = await aq.assets.processAndWait(presign.process.body, { timeoutMs: 300_000 });\n * ```\n *\n * Works for images AND video. A video answers immediately with\n * `{ assetId, status: \"processing\" }` while a Cloud Run Job transcodes, so\n * give `processAndWait` a bigger `timeoutMs` (a transcode + HLS ladder runs\n * 1–2 min; 300_000 is a sane floor).\n */\n async presignUploadUrl(\n opts: PresignUploadUrlOptions,\n ): Promise<UploadUrlResult> {\n const body: Record<string, unknown> = {\n sha256: opts.sha256,\n mime: opts.mime,\n bytes: opts.bytes,\n fileName: opts.fileName,\n };\n if (opts.presets && opts.presets.length > 0) body.presets = opts.presets;\n if (opts.clientOriginalBytes != null)\n body.clientOriginalBytes = opts.clientOriginalBytes;\n if (opts.video != null) body.video = opts.video;\n\n const r = await fetch(endpointHref(this.opts, \"/assets/upload-url\"), {\n method: \"POST\",\n headers: { ...this.headers(), \"Content-Type\": \"application/json\" },\n body: JSON.stringify(body),\n });\n if (!r.ok) throw new Error(`upload-url ${r.status}: ${await r.text()}`);\n return (await r.json()) as UploadUrlResult;\n }\n\n /**\n * Dispatch `/assets/process` with the body returned by a prior\n * {@link presignUploadUrl} call, then poll until the asset transitions\n * to `ready` or `failed`. Throws on `failed` or timeout.\n *\n * Use this when bytes were uploaded directly from the browser to R2 —\n * `aq.upload()` already does presign + PUT + process + wait in one\n * step when the server holds the bytes.\n */\n async processAndWait(\n processBody: Record<string, unknown>,\n opts: { timeoutMs?: number } = {},\n ): Promise<AssetDTO> {\n const r = await fetch(endpointHref(this.opts, \"/assets/process\"), {\n method: \"POST\",\n headers: { ...this.headers(), \"Content-Type\": \"application/json\" },\n body: JSON.stringify(processBody),\n });\n if (!r.ok) throw new Error(`process ${r.status}: ${await r.text()}`);\n const proc = (await r.json()) as { assetId?: string };\n if (!proc.assetId) throw new Error(\"process returned no assetId\");\n const final = await this.waitReady(proc.assetId, opts.timeoutMs);\n if (final.status === \"failed\") {\n throw new Error(\n `processAndWait: asset ${proc.assetId} ended status=failed`,\n );\n }\n return final;\n }\n\n /**\n * Poll `GET /assets/:id` until the asset transitions to `ready` or\n * `failed`. Returns the final DTO (whether ready OR failed — callers\n * decide whether to throw on `failed`). Throws on timeout.\n *\n * Default timeout is 5 minutes; videos / HLS ladders may need a\n * higher cap (pass `10 * 60_000` for compositions, transcodes).\n */\n async waitReady(assetId: string, timeoutMs = 5 * 60_000): Promise<AssetDTO> {\n const start = Date.now();\n let delay = 500;\n let last: AssetDTO | null = null;\n while (Date.now() - start < timeoutMs) {\n last = (await this.get(assetId)) as AssetDTO;\n if (last.status === \"ready\" || last.status === \"failed\") return last;\n await new Promise((r) => setTimeout(r, delay));\n delay = Math.min(delay * 1.5, 5_000);\n }\n if (!last) throw new Error(`waitReady: no asset ${assetId}`);\n throw new Error(`waitReady timeout for ${assetId}`);\n }\n\n /**\n * Dispatch `POST /assets/compose-marketing` to stitch pre-uploaded clip\n * segments into a single MP4 composition. Returns the processing asset\n * id immediately — does NOT block on completion. Callers poll via\n * {@link waitReady} (typical timeout: 10 min for multi-segment kits).\n *\n * Tenant scope is inherited from the SDK client; `tenantCode` is added\n * to the request body so the Cloud Run Job can resolve it without\n * re-reading the header.\n */\n async composeMarketing(\n opts: ComposeMarketingOptions,\n ): Promise<ComposeMarketingResult> {\n const r = await fetch(\n endpointHref(this.opts, \"/assets/compose-marketing\"),\n {\n method: \"POST\",\n headers: { ...this.headers(), \"Content-Type\": \"application/json\" },\n body: JSON.stringify({\n tenantCode: this.opts.tenantCode,\n marketingKitId: opts.marketingKitId,\n segments: opts.segments,\n composition: opts.composition ?? {},\n }),\n },\n );\n if (!r.ok) {\n throw new Error(`compose-marketing ${r.status}: ${await r.text()}`);\n }\n const body = (await r.json()) as {\n asset?: { id: string; status: \"processing\" | \"ready\" | \"failed\" };\n assetId?: string;\n status?: \"processing\" | \"ready\" | \"failed\";\n };\n // Server returns `{ asset: { id, status }, dispatch? }`; some older\n // builds returned `{ assetId, status }` directly. Normalize both.\n const assetId = body.asset?.id ?? body.assetId;\n const status = body.asset?.status ?? body.status ?? \"processing\";\n if (!assetId) {\n throw new Error(\"compose-marketing: response missing assetId\");\n }\n return { assetId, status };\n }\n\n private headers(): Record<string, string> {\n return authHeaders(this.opts);\n }\n}\n\n// ---------------------------------------------------------------------------\n// Upload helpers\n// ---------------------------------------------------------------------------\n\n/**\n * Best-effort MIME from a file name's extension. Used as a fallback for `Uint8Array`\n * uploads (which carry no inherent type) so they still get classified correctly instead\n * of silently becoming `application/octet-stream` → `kind:\"other\"`. Returns `null` when\n * the extension is unknown.\n */\nconst MIME_BY_EXT: Record<string, string> = {\n webp: \"image/webp\",\n jpg: \"image/jpeg\",\n jpeg: \"image/jpeg\",\n png: \"image/png\",\n gif: \"image/gif\",\n avif: \"image/avif\",\n heic: \"image/heic\",\n heif: \"image/heif\",\n svg: \"image/svg+xml\",\n bmp: \"image/bmp\",\n tiff: \"image/tiff\",\n mp4: \"video/mp4\",\n webm: \"video/webm\",\n mov: \"video/quicktime\",\n m4v: \"video/x-m4v\",\n pdf: \"application/pdf\",\n};\nexport function mimeFromFileName(fileName: string | undefined): string | null {\n if (!fileName) return null;\n const ext = fileName.split(\".\").pop()?.toLowerCase();\n return ext ? (MIME_BY_EXT[ext] ?? null) : null;\n}\n\n/**\n * Subset of compressorjs options exposed through the SDK. Re-imported here\n * to avoid a hard import dependency on `./web` from this top-level module\n * (the /web subpath uses browser-only APIs). The runtime `compress`\n * implementation is lazy-loaded so Node/Bun callers don't pay the bundle\n * cost — see `aq.upload` below.\n */\nexport type CompressOptions = {\n quality?: number;\n mimeType?: \"image/jpeg\" | \"image/webp\";\n maxWidth?: number;\n maxHeight?: number;\n convertSize?: number;\n strict?: boolean;\n keepOriginalDimensions?: boolean;\n convertHeic?: boolean;\n onProgress?: (\n stage: \"convertingHeic\" | \"compressing\" | \"compressingKeepingDimensions\",\n ) => void;\n};\n\nexport type UploadOptions = {\n fileName?: string;\n /**\n * MIME type of the bytes. **Only needed for a `Uint8Array` input** — a `File`/`Blob`\n * already carries its `.type`. Raw bytes have no inherent MIME, so without this (and\n * without an extension on `fileName` to infer from) they upload as\n * `application/octet-stream`, which the asset-manager classifies as `kind:\"other\"` —\n * meaning NO image/video variants are generated and `regenerate()` is unsupported.\n * Resolution order for the effective MIME: `Blob.type` → `contentType` →\n * inferred from `fileName`'s extension → `application/octet-stream`.\n *\n * aq.upload(bytes, { fileName: \"cover.webp\" }) // inferred → image/webp ✓\n * aq.upload(bytes, { contentType: \"image/webp\" }) // explicit ✓\n * aq.upload(bytes) // octet-stream → kind:\"other\" ⚠\n */\n contentType?: string;\n /** Computed sha256 of bytes. Skip to compute locally with WebCrypto (browser only). */\n sha256?: string;\n /**\n * Client-side compression before upload. Saves user bandwidth — typical\n * 5–10× reduction for raw phone photos. Browser-only; in Node/Bun this\n * silently no-ops with a console.warn and the raw bytes upload as-is.\n *\n * - `true` → use SDK `DEFAULT_COMPRESSION_OPTIONS` (webapp-tuned)\n * - `CompressOptions` → merge over defaults\n * - `false` / omit → no compression (current default behavior)\n *\n * Implementation is lazy-imported from `@nitida/sdk/web` so callers\n * that never set `compress` don't pay the compressorjs + heic2any\n * bundle cost. Skipped for non-image MIMEs (video, PDF) regardless of\n * this option — those go to the upload pipeline raw.\n *\n * @see {@link CompressOptions}\n * @see https://github.com/espaciofuturoio/aquienpz/tree/main/packages/sdk#client-side-compression-browsers\n */\n compress?: boolean | CompressOptions;\n /**\n * Variant set to generate. **Defaults to `[\"original\"]`** —\n * if you omit this option, only the raw bytes land on the CDN\n * under the `o` path. Pass an explicit array to request more.\n *\n * Image presets (`thumb` 256 · `sm` 640 · `md` 1280 · `lg` 1920 ·\n * `xl` 3840 · `original`):\n * - `[\"original\"]` (default) → just the raw bytes. Right call for\n * logos / SVGs / anything you'll resize browser-side or via\n * `aq.assets.regenerate(id, { presets: [\"thumb\"] })` later.\n * - `[\"thumb\",\"sm\",\"md\",\"lg\"]` → the classic responsive ladder.\n * - `[\"thumb\",\"sm\",\"md\",\"lg\",\"xl\"]` → add 4K.\n *\n * Video presets (`poster`, `video`, `aiproxy`): omit `aiproxy` if\n * the tenant doesn't need the low-res transcode for AI captioning.\n *\n * No upscaling. Each size preset is a **ceiling**; a 1080×720 source\n * asked for `xl` (3840) yields a 1080×720 xl variant, not a stretched\n * 3840-wide image.\n *\n * Idempotent: you can always add missing variants later via\n * `aq.assets.regenerate(id, { presets: [...] })`. The platform\n * stores the source so regeneration doesn't require re-uploading.\n */\n presets?: VariantPreset[];\n /**\n * Max time to wait for the asset to transition to `ready` (or `failed`)\n * after dispatch. Default `5 * 60_000` (5 min). Bump higher for large\n * videos / HLS transcodes — aquienpz processing time scales with input\n * size and per-instance CPU.\n *\n * Throws `Error(\"waitReady timeout for <id>\")` if the deadline passes\n * without the asset transitioning. The asset row stays in aquienpz\n * (status=\"processing\") and the next byHash lookup will return it once\n * processing completes; the caller can resume with their own poll.\n */\n timeoutMs?: number;\n /**\n * VIDEO-only delivery knobs forwarded into `/assets/process`. See\n * {@link UploadVideoOptions}. Ignored for non-video uploads.\n *\n * // A delivery-ready reel: skip the unused HLS ladder + skip re-encode.\n * await aq.upload(mp4Bytes, {\n * fileName: \"reel.mp4\",\n * presets: [\"poster\", \"video\"],\n * video: { hls: false, passthrough: true },\n * });\n */\n video?: UploadVideoOptions;\n};\n\n/** Default preset set the SDK sends to `/assets/upload-url` when the caller omits `presets`. */\nconst DEFAULT_UPLOAD_PRESETS: VariantPreset[] = [\"original\"];\n\nexport type UploadResult = {\n assetId: string;\n sha256: string;\n cdnUrl: string;\n};\n\nasync function computeSha256(\n bytes: ArrayBuffer | Uint8Array | Blob,\n): Promise<string> {\n const buf =\n bytes instanceof Blob\n ? await bytes.arrayBuffer()\n : bytes instanceof Uint8Array\n ? (bytes.buffer as ArrayBuffer)\n : bytes;\n const digest = await crypto.subtle.digest(\"SHA-256\", buf);\n return [...new Uint8Array(digest)]\n .map((b) => b.toString(16).padStart(2, \"0\"))\n .join(\"\");\n}\n\n// ---------------------------------------------------------------------------\n// Main facade\n// ---------------------------------------------------------------------------\n\n// ---------------------------------------------------------------------------\n// Usage (Cloudinary-style consumption dashboard data)\n// ---------------------------------------------------------------------------\n\n// ---------------------------------------------------------------------------\n// Slot history\n// ---------------------------------------------------------------------------\n\nexport type SlotHistoryEntry = {\n id: string;\n action: \"bind\" | \"unbind\" | \"restore\";\n preset: VariantPreset | null;\n description: string | null;\n updatedAt: string;\n updatedBy: string | null;\n assetId: string | null;\n /** Resolved DTO when the asset still exists; `null` after delete / 404. */\n asset: AssetDTO | null;\n};\n\nexport type UsageSnapshot = {\n tenant: { id: number; code: string };\n storage: { totalBytes: number; assetCount: number };\n today: UsageWindow;\n last30Days: UsageWindow;\n};\n\nexport type UsageWindow = {\n reads: number;\n writes: number;\n lists: number;\n deletes: number;\n admins: number;\n upscales: number;\n processes: number;\n bytesIn: number;\n};\n\nexport type UsageDailyPoint = {\n date: string;\n reads: number;\n writes: number;\n lists: number;\n deletes: number;\n processes: number;\n bytesIn: number;\n bytesStored: number;\n};\n\nexport type UsagePerKey = {\n apiKeyId: string;\n prefix: string | null;\n name: string | null;\n opsTotal: number;\n bytesTotal: number;\n lastSeen: string;\n};\n\nclass UsageApi {\n constructor(private readonly opts: NitidaClientOptions) {}\n\n /** Snapshot for the active tenant — storage + today + last 30 days totals. */\n async snapshot(): Promise<UsageSnapshot> {\n const r = await fetch(endpointHref(this.opts, \"/usage\"), {\n headers: this.headers(),\n });\n if (!r.ok) throw new Error(`usage snapshot ${r.status}: ${await r.text()}`);\n return (await r.json()) as UsageSnapshot;\n }\n\n /** Daily rollup for charts — 1..365 days, default 30. */\n async timeseries(days = 30): Promise<{\n tenant: { id: number; code: string };\n days: UsageDailyPoint[];\n }> {\n const r = await fetch(\n endpointUrl(this.opts, \"/usage/timeseries\", { days }),\n { headers: this.headers() },\n );\n if (!r.ok)\n throw new Error(`usage timeseries ${r.status}: ${await r.text()}`);\n return (await r.json()) as {\n tenant: { id: number; code: string };\n days: UsageDailyPoint[];\n };\n }\n\n /** Per-API-key breakdown for the current month. */\n async keys(): Promise<{\n tenant: { id: number; code: string };\n monthStart: string;\n keys: UsagePerKey[];\n }> {\n const r = await fetch(endpointHref(this.opts, \"/usage/keys\"), {\n headers: this.headers(),\n });\n if (!r.ok) throw new Error(`usage keys ${r.status}: ${await r.text()}`);\n return (await r.json()) as {\n tenant: { id: number; code: string };\n monthStart: string;\n keys: UsagePerKey[];\n };\n }\n\n private headers(): Record<string, string> {\n return authHeaders(this.opts);\n }\n}\n\nexport class NitidaClient {\n readonly slots: SlotsApi;\n readonly assets: AssetsApi;\n readonly usage: UsageApi;\n /**\n * Effective options — read-only. Exposed so the `/web` and `/expo`\n * subpaths can inherit endpoint / apiKey / tenant scope from the\n * configured client without re-passing them per call site.\n */\n readonly opts: NitidaClientOptions;\n\n constructor(opts: NitidaClientOptions) {\n this.opts = opts;\n const cdn = opts.cdnBase ?? \"https://8ok.uk\";\n setCdnBase(cdn);\n // Configure the process-global tenant so every variant URL builder\n // (`getAssetUrl`, `urlFor`, `srcSetFor`, upload `cdnUrl`) emits the\n // tenant-prefixed path `<cdn>/<tid b36>/v/<sha>-<preset>.<ext>`.\n setTenantId(opts.tenantId);\n configureSlotResolver({\n endpoint: opts.endpoint,\n apiKey: opts.apiKey,\n tenantCode: opts.tenantCode,\n });\n this.slots = new SlotsApi(opts);\n this.assets = new AssetsApi(opts);\n this.usage = new UsageApi(opts);\n }\n\n /** Tenant id as base36 path segment (e.g. tenantId=4 → \"4/v/\"). */\n get tenantSegment(): string {\n return `${this.opts.tenantId.toString(36)}/v/`;\n }\n\n /** Build the canonical CDN URL deterministically from sha + preset. */\n urlFor(asset: Pick<AssetDTO, \"sha\">, preset: VariantPreset = \"lg\"): string {\n return getAssetUrl(asset, preset);\n }\n\n /** Build a responsive srcSet across the available image presets. */\n srcSetFor(asset: Pick<AssetDTO, \"sha\" | \"presets\">): string {\n return getAssetSrcSet(asset);\n }\n\n /**\n * Build an on-the-fly transform URL — `<cdn>/t/<dsl>/<sha>.<ext>`.\n *\n * ## URL CONVENTION — transforms are NOT tenant-prefixed (variants are)\n * Two distinct delivery paths, by design:\n * - **Variants / presets** (`urlFor`, `srcSetFor`, upload `cdnUrl`):\n * `<cdn>/<tenantId b36>/v/<sha>-<preset>.<ext>` ← tenant-scoped (e.g. `/4/v/<sha>-lg.webp`)\n * - **On-the-fly transforms** (`transform`, `transformSrcSet`):\n * `<cdn>/t/<dsl>/<sha>.<ext>` ← GLOBAL, no tenant segment (`/t/...`)\n * The transform service is content-addressed by sha + resizes from the source on demand,\n * so it needs no tenant in the path. Prefixing a transform URL with `/<tenant>/t/...` 404s.\n * Consumers that build URLs by hand must NOT add the tenant segment to `/t/` URLs.\n *\n * Returns the canonical `lg` variant URL when called with empty options,\n * so callers can swap `urlFor()` for `transform()` without thinking.\n *\n * URLs with the same params in different order produce the same R2\n * cache entry (the server canonicalizes both sides). Safe to use as\n * stable cache keys.\n *\n * <Image\n * src={aq.transform(asset, { width: 1280 })}\n * srcSet={aq.transformSrcSet(asset, [640, 960, 1280, 1920])}\n * sizes=\"(max-width: 768px) 100vw, 50vw\"\n * />\n *\n * @see {@link TransformOptions} for the full param matrix.\n */\n // Overload 1: no signing — synchronous, on-ladder width only (strict).\n transform(asset: Pick<AssetDTO, \"sha\">, opts?: TransformOptions): string;\n // Overload 2: with { sign: true } — async; returns `?sig=<hmac>` URL.\n // Accepts SignedTransformOptions so a signed URL may carry an off-ladder\n // custom width (the signature earns the edge whitelist bypass).\n transform(\n asset: Pick<AssetDTO, \"sha\">,\n opts: SignedTransformOptions,\n signOpts: { sign: true },\n ): Promise<string>;\n transform(\n asset: Pick<AssetDTO, \"sha\">,\n opts: SignedTransformOptions = {},\n signOpts?: { sign: true },\n ): string | Promise<string> {\n if (!signOpts?.sign) {\n // Unsigned path. Overload 1 constrains `width` to the ladder at every\n // public call site, so an off-ladder width can't reach here through the\n // typed API — narrow back to TransformOptions for the strict builder.\n return (\n getTransformUrl(asset, opts as TransformOptions) ??\n this.urlFor(asset, \"lg\")\n );\n }\n if (!this.opts.signingKey) {\n throw new Error(\n \"aq.transform({ sign: true }) requires `signingKey` in NitidaClientOptions. \" +\n \"Pull the tenant's signing key from /admin/tenants/:id and pass it to the SDK constructor on a SERVER-side instance only.\",\n );\n }\n // Signed path — custom (off-ladder) widths allowed. Empty opts → no\n // transform DSL, fall back to the unsigned `lg` variant URL.\n return (\n getSignedTransformUrl(asset, opts, this.opts.signingKey) ??\n Promise.resolve(this.urlFor(asset, \"lg\"))\n );\n }\n\n /**\n * Build a responsive `srcSet` string. One transform URL per width; all\n * other options apply to every URL.\n *\n * Pass `{ sign: true }` to return signed URLs (async). Without it, the\n * call stays synchronous as before.\n */\n transformSrcSet(\n asset: Pick<AssetDTO, \"sha\">,\n widths: number[],\n extraOpts?: Omit<TransformOptions, \"width\">,\n ): string;\n transformSrcSet(\n asset: Pick<AssetDTO, \"sha\">,\n widths: number[],\n extraOpts: Omit<TransformOptions, \"width\">,\n signOpts: { sign: true },\n ): Promise<string>;\n transformSrcSet(\n asset: Pick<AssetDTO, \"sha\">,\n widths: number[],\n extraOpts: Omit<TransformOptions, \"width\"> = {},\n signOpts?: { sign: true },\n ): string | Promise<string> {\n if (!signOpts?.sign) return getTransformSrcSet(asset, widths, extraOpts);\n if (!this.opts.signingKey) {\n throw new Error(\n \"aq.transformSrcSet({ sign: true }) requires `signingKey` in NitidaClientOptions.\",\n );\n }\n const key = this.opts.signingKey;\n return Promise.all(\n widths.map(async (w) => {\n // Signed path → off-ladder widths allowed; build+sign via the\n // custom-width helper (the strict `getTransformUrl` would reject a\n // raw `number` width).\n const signed = await getSignedTransformUrl(\n asset,\n { ...extraOpts, width: w },\n key,\n );\n return signed ? `${signed} ${w}w` : null;\n }),\n ).then((parts) => parts.filter((s): s is string => s != null).join(\", \"));\n }\n\n /**\n * Build an on-the-fly VIDEO transform URL — Phase 4.\n *\n * Same DSL shape as `transform()` but the URL has a `.mp4` (default)\n * or `.webm` extension and the server routes the request to a Cloud\n * Run Job for ffmpeg encoding (vs the inline sharp pipeline for\n * images).\n *\n * On the first request the route returns **202 Accepted** with\n * `Retry-After: 10` while the Job runs (typically 5-30 s for a\n * short clip). The response body includes `outputUrl` which is the\n * eventual CDN URL — poll the same transform URL after the\n * retry-after window to get a 302 redirect to it.\n *\n * const url = aq.transformVideo(asset, {\n * width: 1080, height: 1920, fit: \"cover\",\n * start: 0, duration: 15,\n * });\n * // Pass to Video.js / <video src={url}>; on the first load it\n * // gets 202 + body.outputUrl; subsequent loads hit cache → 302.\n *\n * Video-specific DSL params:\n * - `start` (seconds, decimal OK)\n * - `duration` (seconds, 1..300)\n * - `format`: \"mp4\" (default) or \"webm\"\n *\n * The other params (`width`, `height`, `fit`) work identically to\n * image transforms. `gravity`, `quality`, `effect`, `dpr` are\n * accepted by the DSL but currently ignored on the video path.\n */\n transformVideo(\n asset: Pick<AssetDTO, \"sha\">,\n opts: TransformOptions = {},\n ): string {\n return getVideoTransformUrl(asset, opts) ?? this.urlFor(asset, \"lg\");\n }\n\n /**\n * Build the HLS master playlist URL for a VIDEO asset (Phase 5).\n *\n * Returns `<cdn>/t/format=hls(,start=…,duration=…)/<sha>.m3u8`. Pass\n * to an HLS-aware player:\n *\n * <video\n * src={aq.streamingUrl(asset)}\n * controls playsInline\n * // Video.js v10's @videojs/http-streaming ships native HLS —\n * // no plugin needed.\n * />\n *\n * On the first request the server returns **202 Accepted** while a\n * Cloud Run Job builds the multi-rung ladder (typically 1-3 min for\n * a 90 s source — five rungs of 240p/360p/480p/720p/1080p @ AAC).\n * Subsequent requests hit the cache → **302** to the master.m3u8.\n *\n * Supports `start` + `duration` to ladder a sub-clip. Other DSL\n * params (width, height, fit) are ignored on the HLS path because\n * the rungs determine resolution.\n */\n streamingUrl(\n asset: Pick<AssetDTO, \"sha\">,\n opts: Omit<TransformOptions, \"format\"> = {},\n ): string {\n return getHlsStreamingUrl(asset, opts);\n }\n\n /**\n * Upload a file or raw bytes. Returns the new asset id + canonical\n * URL. Hash-deduped — uploading the same bytes twice returns the\n * existing asset.\n *\n * Browser-first: uses `Blob` + WebCrypto. For Node 20+, pass a\n * Uint8Array and a precomputed `sha256` (since `crypto.subtle` works\n * but isn't always available depending on the runtime).\n */\n /**\n * Upload bytes end to end: optional client compression → sha256 → presign → **direct-to-R2 PUT**\n * → `/assets/process` → wait until the asset is ready.\n *\n * ⚠️ `presets` decides what exists FOREVER. Omit it and only `original` is written; ask for\n * `[\"thumb\"]` and the bytes you just uploaded are **not retrievable**. A variant not requested in\n * this first ingest cannot be added later once the cleanup job reaps `raw/` — measured once as\n * \"97 files archived successfully, zero recoverable\".\n *\n * @example Deliver an image on a site (the responsive ladder)\n * ```ts\n * import { NitidaClient } from \"@nitida/sdk/server\";\n *\n * const aq = new NitidaClient({ endpoint, apiKey, tenantCode, tenantId });\n * const { assetId, sha256 } = await aq.upload(file, {\n * fileName: file.name,\n * presets: [\"thumb\", \"sm\", \"md\", \"lg\"],\n * });\n * ```\n *\n * @example ARCHIVE a file — you must ask for `original`\n * ```ts\n * await aq.upload(bytes, {\n * fileName: \"contrato.pdf\",\n * contentType: \"application/pdf\",\n * presets: [\"original\"], // without this the bytes are unrecoverable\n * });\n * ```\n *\n * @example Raw bytes need an explicit MIME\n * ```ts\n * await aq.upload(bytes, { fileName: \"track.mp3\", contentType: \"audio/mpeg\" });\n * // Without either, it stores as kind:\"other\" — no variants, and regenerate() is unsupported.\n * ```\n *\n * @example Video — and what does NOT work there\n * ```ts\n * // `original` is accepted and then silently DROPPED: /assets/process filters video presets to\n * // {poster, video, aiproxy, probe} before dispatching the transcode Job.\n * await aq.upload(clip, { fileName: \"tour.mp4\", presets: [\"poster\", \"video\"] });\n *\n * // Omit `aiproxy`/`probe` unless the asset really goes to a vision model — they cost Job time\n * // and permanent R2 objects that nothing else reads.\n * ```\n */\n async upload(\n input: File | Blob | Uint8Array,\n opts: UploadOptions = {},\n ): Promise<UploadResult> {\n // 1. Resolve incoming bytes + mime first (the source of truth for\n // \"should we compress this?\")\n const sourceIsBlob = input instanceof File || input instanceof Blob;\n // A Uint8Array has no inherent MIME. Fall back to an explicit `contentType`, then to\n // the file extension, before octet-stream (which the asset-manager files as\n // `kind:\"other\"` — no variants). A File/Blob's own `.type` always wins when present.\n const sourceMime =\n (sourceIsBlob ? input.type : \"\") ||\n opts.contentType ||\n mimeFromFileName(opts.fileName) ||\n \"application/octet-stream\";\n if (!sourceIsBlob && sourceMime === \"application/octet-stream\") {\n console.warn(\n \"[@nitida/sdk] upload(Uint8Array): no MIME resolved (no `contentType`, no recognizable \" +\n '`fileName` extension) — the asset will be stored as kind:\"other\" with NO image/video ' +\n \"variants and regenerate() unsupported. Pass `contentType` or a `fileName` with an extension.\",\n );\n }\n\n // 2. Optional client-side compression. Image MIMEs only; non-image\n // sources pass through unchanged so a video or PDF upload still\n // works when the caller sets `compress: true` blanket-fashion.\n let bytes: Uint8Array;\n let effectiveMime: string;\n let clientOriginalBytes: number | undefined;\n\n const wantCompression =\n !!opts.compress &&\n sourceIsBlob &&\n typeof window !== \"undefined\" &&\n sourceMime.startsWith(\"image/\");\n\n if (wantCompression) {\n const compressOpts =\n opts.compress === true ? {} : (opts.compress as CompressOptions);\n // Lazy: keeps compressorjs/heic2any out of bundles that don't use it.\n //\n // Resolve `./web` against `import.meta.url` at runtime so no static\n // analyzer — esbuild, tsup, `bun build --compile`, vite, rollup —\n // can follow the specifier. Holding the path in a plain `const`\n // was not enough: `bun build --compile` constant-folds simple\n // strings and still eagerly bundled `./web.js`, which\n // top-level-imports the browser-only peer deps\n // `@aquienpz/asset-uploader-web` / `@nitida/asset-compressor-web`\n // — neither installed on server consumers — crashing the\n // single-binary on boot with `Cannot find module\n // '@aquienpz/asset-uploader-web'`.\n //\n // The earlier `new URL(\"./web.js\", import.meta.url)` + `await import(URL)`\n // dance survived bun-compile but Turbopack still tracks the URL literal\n // and tries to resolve `./web.js` at build time (no such file exists in\n // src/, only src/web/index.ts), failing with \"Module not found\".\n //\n // Indirect-eval via the Function constructor is opaque to BOTH static\n // analyzers — neither bun-compile nor Turbopack can follow the string\n // back to a module specifier. The browser `typeof window` guard above\n // ensures the branch never runs on the server, so the indirection is\n // safe at runtime.\n // Build the URL inside the Function body too — Turbopack still tracks\n // `new URL(<any expr>, import.meta.url)` as a resolution pattern even\n // when the first arg isn't a literal, so we have to hide both the URL\n // construction AND the import() behind indirect eval.\n const dynImport = new Function(\n \"base\",\n \"return import(new URL('./' + 'web' + '.js', base).href)\",\n ) as (base: string) => Promise<typeof import(\"./web\")>;\n const { compressImage } = await dynImport(import.meta.url);\n const result = await compressImage(input as File | Blob, compressOpts);\n bytes = new Uint8Array(await result.blob.arrayBuffer());\n clientOriginalBytes = result.originalBytes;\n effectiveMime = result.blob.type || sourceMime;\n } else {\n if (opts.compress && !sourceIsBlob) {\n console.warn(\n \"[@nitida/sdk] compress: true requires a File or Blob input; got Uint8Array — uploading raw bytes.\",\n );\n } else if (opts.compress && typeof window === \"undefined\") {\n console.warn(\n \"[@nitida/sdk] compress: true is browser-only — uploading raw bytes.\",\n );\n } else if (opts.compress && !sourceMime.startsWith(\"image/\")) {\n // Silent: callers can set `compress: true` for batched mixed\n // media and not have to special-case images vs videos.\n }\n bytes =\n input instanceof Uint8Array\n ? input\n : new Uint8Array(await input.arrayBuffer());\n effectiveMime = sourceMime;\n }\n\n const sha = opts.sha256 ?? (await computeSha256(bytes));\n const mime = effectiveMime;\n const fileName =\n opts.fileName ??\n (input instanceof File ? input.name : `upload-${sha.slice(0, 8)}.bin`);\n\n // Dedup probe.\n const existing = await this.assets.byHash(sha);\n if (existing && existing.status === \"ready\") {\n return {\n assetId: existing.id,\n sha256: sha,\n cdnUrl: this.urlFor(existing, this.bestPresetForAsset(existing, mime)),\n };\n }\n\n // Presign + PUT + process. Delegates to `assets.presignUploadUrl()` so\n // the public method and `aq.upload()` share one code path; always\n // threads an explicit preset list so the default matches the SDK\n // contract (`[\"original\"]`) instead of inheriting the server's older\n // default (`thumb+sm+md+lg`).\n const presign = await this.assets.presignUploadUrl({\n sha256: sha,\n mime,\n bytes: bytes.byteLength,\n fileName,\n presets:\n opts.presets && opts.presets.length > 0\n ? opts.presets\n : DEFAULT_UPLOAD_PRESETS,\n ...(clientOriginalBytes != null && { clientOriginalBytes }),\n ...(opts.video != null && { video: opts.video }),\n });\n if (presign.deduped) {\n return {\n assetId: presign.asset.id,\n sha256: sha,\n cdnUrl: this.urlFor(presign.asset, this.defaultPresetForMime(mime)),\n };\n }\n\n const putR = await fetch(presign.upload.url, {\n method: \"PUT\",\n headers: { \"Content-Type\": mime, ...(presign.upload.headers ?? {}) },\n body: new Blob([bytes as unknown as ArrayBuffer], { type: mime }),\n });\n if (!putR.ok)\n throw new Error(`R2 PUT ${putR.status}: ${await putR.text()}`);\n\n const procR = await fetch(endpointHref(this.opts, presign.process.url), {\n method: \"POST\",\n headers: {\n ...authHeaders(this.opts),\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify(presign.process.body),\n });\n if (!procR.ok)\n throw new Error(`process ${procR.status}: ${await procR.text()}`);\n const proc = (await procR.json()) as { assetId?: string; kind?: string };\n\n let assetId = proc.assetId;\n if (!assetId && proc.kind === \"video\") {\n // Videos are async — poll by-hash until the row lands.\n const start = Date.now();\n let delay = 1000;\n while (Date.now() - start < 60_000) {\n const dto = await this.assets.byHash(sha);\n if (dto?.id) {\n assetId = dto.id;\n break;\n }\n await new Promise((r) => setTimeout(r, delay));\n delay = Math.min(delay * 1.5, 5_000);\n }\n }\n if (!assetId) throw new Error(\"upload: process returned no assetId\");\n\n // Wait until variants are ready so the URL works immediately.\n // Passing `undefined` keeps waitReady's own default (5 min). Callers\n // uploading large videos can opt in to a longer deadline via opts.timeoutMs.\n const final = await this.assets.waitReady(assetId, opts.timeoutMs);\n if (final.status !== \"ready\")\n throw new Error(`upload: asset ended status=${final.status}`);\n return {\n assetId,\n sha256: sha,\n cdnUrl: this.urlFor(final, this.bestPresetForAsset(final, mime)),\n };\n }\n\n private defaultPresetForMime(mime: string): VariantPreset {\n if (mime.startsWith(\"video/\")) return \"video\";\n // The `mp3` variant only exists AFTER /process transcodes it; at presign\n // time only the original is guaranteed to be playable, so bind to it.\n if (mime.startsWith(\"audio/\")) return \"original\";\n return \"lg\";\n }\n\n /**\n * Pick a sensible preset to build a URL for, given the asset's actual\n * `presets` string. Falls back through the preference order\n * lg → md → sm → thumb → original (for images)\n * video → poster (for videos)\n * mp3 → original (for audio)\n * so an upload that was processed with e.g. `[\"original\"]` still\n * returns a non-404 URL in `aq.upload`'s result.\n */\n private bestPresetForAsset(asset: AssetDTO, mime: string): VariantPreset {\n const order: VariantPreset[] = mime.startsWith(\"video/\")\n ? [\"video\", \"poster\"]\n : mime.startsWith(\"audio/\")\n ? [\"mp3\", \"original\"] // prefer the cross-browser mp3, else the playable original; never image presets\n : [\"lg\", \"md\", \"sm\", \"thumb\", \"xl\", \"original\"];\n return (\n order.find((p) => hasPreset(asset, p)) ?? this.defaultPresetForMime(mime)\n );\n }\n}\n"],"mappings":";AAqCA;AAAA,EAGE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EAEA;AAAA,EACA;AAAA,EAIA;AAAA,EACA;AAAA,OAGK;AAkJP;AAAA,EACE;AAAA,EACA;AAAA,EACA;A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AS;AACjE,QAAI,MAAM,WAAW;AACnB,YAAM,IAAI,MAAM,8BAA8B,MAAM,MAAM,EAAE;AAC9D,WAAO;AAAA,MACL;AAAA,MACA,QAAQ;AAAA,MACR,QAAQ,KAAK,OAAO,OAAO,KAAK,mBAAmB,OAAO,IAAI,CAAC;AAAA,IACjE;AAAA,EACF;AAAA,EAEQ,qBAAqB,MAA6B;AACxD,QAAI,KAAK,WAAW,QAAQ,EAAG,QAAO;AAGtC,QAAI,KAAK,WAAW,QAAQ,EAAG,QAAO;AACtC,WAAO;AAAA,EACT;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAWQ,mBAAmB,OAAiB,MAA6B;AACvE,UAAM,QAAyB,KAAK,WAAW,QAAQ,IACnD,CAAC,SAAS,QAAQ,IAClB,KAAK,WAAW,QAAQ,IACtB,CAAC,OAAO,UAAU,IAClB,CAAC,MAAM,MAAM,MAAM,SAAS,MAAM,UAAU;AAClD,WACE,MAAM,KAAK,CAAC,MAAM,UAAU,OAAO,CAAC,CAAC,KAAK,KAAK,qBAAqB,IAAI;AAAA,EAE5E;AACF;","names":["getAssetSrcSet","getAssetUrl","getHlsStreamingUrl","getSignedTransformUrl","getTransformSrcSet","getTransformUrl","getVideoTransformUrl","hasPreset","setTenantId"]}
1
+ {"version":3,"sources":["../src/index.ts"],"sourcesContent":["/**\n * @nitida/sdk — universal client for the aquienpz multi-tenant asset\n * platform.\n *\n * One ergonomic facade over the underlying packages\n * (`@nitida/asset-client` URL builders + `@aquienpz/asset-uploader-web`\n * + the slot resolver). Auth is a Better Auth API key (`amk_rt_*`)\n * issued by aquienpz `bootstrap-project.ts`; tenant scope comes from\n * the key's metadata (`X-Tenant-Code` is log-only).\n *\n * Usage:\n *\n * import { NitidaClient } from \"@nitida/sdk\";\n *\n * const aq = new NitidaClient({\n * endpoint: \"https://api.nitida.gofuture.space\",\n * apiKey: process.env.ASSET_MANAGER_RUNTIME_KEY!,\n * tenantCode: \"realtyone-cr\",\n * cdnBase: \"https://8ok.uk\", // optional override\n * tenantId: 4, // required for tenant-prefixed URLs\n * });\n *\n * // Slot system (recommended — admin can rebind without redeploys).\n * const hero = await aq.slots.resolve(\"storefront.cr.hero\");\n * const set = await aq.slots.resolveMany([\"a\", \"b\", \"c\"]);\n *\n * // Lower-level asset operations.\n * const asset = await aq.assets.byHash(sha);\n * const list = await aq.assets.list({ limit: 50 });\n *\n * // Upload bytes / files.\n * const up = await aq.upload(file, { fileName: \"cover.jpg\" });\n *\n * For React, see `@nitida/sdk/react` (useSlot, useSlots, useAsset).\n * @module @nitida/sdk\n */\n\nimport {\n type AssetDTO,\n type AssetVariant,\n configureSlotResolver,\n getAssetSrcSet,\n getAssetUrl,\n getHlsStreamingUrl,\n getSignedTransformUrl,\n getTransformSrcSet,\n getTransformUrl,\n getVideoTransformUrl,\n hasPreset,\n invalidateSlotCache,\n type ResolveSlotOptions,\n resolveSlot,\n resolveSlots,\n type SignedTransformOptions,\n type SlotDTO,\n type SlotResolution,\n setCdnBase,\n setTenantId,\n type TransformOptions,\n type VariantPreset,\n} from \"@nitida/asset-client\";\n\n// ---------------------------------------------------------------------------\n// Config\n// ---------------------------------------------------------------------------\n\n/**\n * Permissive constructor options for the root `NitidaClient`.\n *\n * App code should NOT import this type directly — prefer the strict\n * variants from the subpaths:\n *\n * - `WebClientOptions` from `@nitida/sdk/web` (no `apiKey`)\n * - `ServerClientOptions` from `@nitida/sdk/server` (`apiKey` required)\n *\n * This root type is the union both modes resolve to; the underlying class\n * accepts both shapes so subpath wrappers can extend without duplication.\n */\nexport type NitidaClientOptions = {\n /**\n * Base URL of the nitida API (e.g. `https://api.nitida.gofuture.space`).\n *\n * May be relative (e.g. `/api/am`) ONLY in browser contexts where the\n * SDK resolves it against `window.location.origin`. Node/Bun consumers\n * must always pass an absolute URL.\n */\n endpoint: string;\n /**\n * Better Auth API key with the `amk_rt_*` prefix.\n *\n * **Server-only.** Omit when constructing from `@nitida/sdk/web` —\n * your BFF / route handler injects the bearer header in proxy mode.\n */\n apiKey?: string;\n /**\n * Extra headers merged into every request. The documented way for\n * mobile/Expo clients to authenticate a BFF that gates on the Better Auth\n * session: they can't send cookies automatically, so they pass\n * `{ Cookie: authClient.getCookie() }` here (see Better Auth Expo docs,\n * \"Making Authenticated Requests to Your Server\"). Web/server consumers omit\n * this — browsers attach the same-origin cookie and servers pass `apiKey`.\n */\n headers?: Record<string, string>;\n /** Tenant code — sent as `X-Tenant-Code` (log-only). Authoritative scope is the key's metadata.tenantId. */\n tenantCode: string;\n /** Numeric tenant id — used to build tenant-prefixed CDN URLs `<cdn>/<tenantId b36>/v/<sha>-<preset>.<ext>`. */\n tenantId: number;\n /** Override the public CDN base. Defaults to `https://8ok.uk`. */\n cdnBase?: string;\n /**\n * Tenant's HMAC signing key for transform URLs (Phase 3). Required\n * only when calling `aq.transform(asset, opts, { sign: true })`.\n *\n * Generated server-side per tenant (see `infra/sql/tenants_signed_transforms.sql`);\n * fetch via `GET /admin/tenants/:id` with an admin key. **Keep it\n * server-side only** — do not ship in `NEXT_PUBLIC_*` env vars. Sign\n * URLs from a BFF route handler, or pre-sign at build time.\n */\n signingKey?: string;\n};\n\n// ---------------------------------------------------------------------------\n// URL construction\n// ---------------------------------------------------------------------------\n\n/**\n * Build a fully-qualified URL for an aquienpz endpoint path.\n *\n * Accepts both absolute endpoints (`https://api.nitida.gofuture.space`) and\n * relative ones (`/api/am`) — the latter only works in browser contexts\n * (resolved against `window.location.origin`). Node/Bun throws a clear\n * error if a relative endpoint is configured.\n *\n * The native `URL` constructor throws on relative inputs, so every fetch\n * site in the SDK must go through this helper instead of `new URL(...)`.\n */\nfunction endpointUrl(\n opts: Pick<NitidaClientOptions, \"endpoint\">,\n path: string,\n searchParams?: Record<string, string | number | boolean | undefined>,\n): URL {\n const endpoint = opts.endpoint.replace(/\\/+$/, \"\");\n const isAbsolute = /^https?:\\/\\//i.test(endpoint);\n let base: string;\n if (isAbsolute) {\n base = `${endpoint}${path}`;\n } else if (typeof window !== \"undefined\" && window.location?.origin) {\n base = `${window.location.origin}${endpoint}${path}`;\n } else {\n throw new Error(\n `[@nitida/sdk] relative endpoint \"${endpoint}\" requires a browser; ` +\n \"pass an absolute URL when using the SDK from Node/Bun.\",\n );\n }\n const u = new URL(base);\n if (searchParams) {\n for (const [k, v] of Object.entries(searchParams)) {\n if (v !== undefined && v !== null && v !== \"\") {\n u.searchParams.set(k, String(v));\n }\n }\n }\n return u;\n}\n\n/** Build a request URL as a plain string (no search params). */\nfunction endpointHref(\n opts: Pick<NitidaClientOptions, \"endpoint\">,\n path: string,\n): string {\n return endpointUrl(opts, path).toString();\n}\n\n/**\n * Auth headers — conditionally includes `Authorization` only when an\n * `apiKey` is present. In BFF-proxy mode (browser via `/web`) the\n * proxy injects the real bearer header, so we omit it here.\n */\nfunction authHeaders(opts: NitidaClientOptions): Record<string, string> {\n const h: Record<string, string> = {\n // Caller-supplied headers first; `X-Tenant-Code` stays authoritative below.\n ...opts.headers,\n \"X-Tenant-Code\": opts.tenantCode,\n };\n if (opts.apiKey) h.Authorization = `Bearer ${opts.apiKey}`;\n return h;\n}\n\n// ---------------------------------------------------------------------------\n// Re-exports (so consumers don't double-import from asset-client)\n// ---------------------------------------------------------------------------\n\nexport type {\n AssetDTO,\n AssetVariant,\n ResolveSlotOptions,\n SignedTransformOptions,\n SlotDTO,\n SlotResolution,\n TransformEffect,\n TransformFit,\n TransformFormat,\n TransformGravity,\n TransformOptions,\n VariantPreset,\n} from \"@nitida/asset-client\";\nexport {\n computeVariantDimensions,\n extractAssetSha,\n getAssetDimensions,\n getAssetSrcSet,\n getAssetUrl,\n getHlsStreamingUrl,\n getSignedTransformUrl,\n getTenantId,\n getTransformSrcSet,\n getTransformUrl,\n getVideoTransformUrl,\n hasPreset,\n serializeTransform,\n setTenantId,\n signTransformUrl,\n} from \"@nitida/asset-client\";\n\n// ---------------------------------------------------------------------------\n// Sub-namespaces\n// ---------------------------------------------------------------------------\n\nclass SlotsApi {\n constructor(private readonly opts: NitidaClientOptions) {}\n\n /** Resolve one slot — returns `{slot, preset, url}` or `{slot: null, url: null}` when unbound. */\n resolve(\n slotKey: string,\n options: ResolveSlotOptions = {},\n ): Promise<SlotResolution> {\n return resolveSlot(slotKey, options);\n }\n\n /** Bulk-resolve N slots in one HTTP round-trip. */\n resolveMany(\n slotKeys: string[],\n options: ResolveSlotOptions = {},\n ): Promise<Record<string, SlotResolution>> {\n return resolveSlots(slotKeys, options);\n }\n\n /** List slots for the tenant (admin). Optional prefix filter for tree views. */\n async list(\n opts: { prefix?: string; limit?: number } = {},\n ): Promise<SlotDTO[]> {\n const u = endpointUrl(this.opts, \"/slots\", {\n prefix: opts.prefix,\n limit: opts.limit,\n });\n const r = await fetch(u, { headers: this.headers() });\n if (!r.ok) throw new Error(`slots list ${r.status}: ${await r.text()}`);\n const body = (await r.json()) as { slots: SlotDTO[] };\n return body.slots;\n }\n\n /** Bind / rebind a slot to an asset. Admin-only operation. */\n async bind(\n slotKey: string,\n body: {\n assetId: string;\n preset?: VariantPreset;\n description?: string;\n updatedBy?: string;\n },\n ): Promise<{ ok: true; slotKey: string; assetId: string }> {\n const r = await fetch(\n endpointHref(this.opts, `/slots/${encodeURIComponent(slotKey)}`),\n {\n method: \"PUT\",\n headers: { ...this.headers(), \"Content-Type\": \"application/json\" },\n body: JSON.stringify(body),\n },\n );\n if (!r.ok) throw new Error(`slot bind ${r.status}: ${await r.text()}`);\n return (await r.json()) as { ok: true; slotKey: string; assetId: string };\n }\n\n /**\n * Recent bindings for a slot. Lets the admin audit who changed\n * what and restore a previous binding without remembering the\n * asset id. Default limit 20, max 100.\n */\n async history(\n slotKey: string,\n opts: { limit?: number } = {},\n ): Promise<SlotHistoryEntry[]> {\n const u = endpointUrl(\n this.opts,\n `/slots/${encodeURIComponent(slotKey)}/history`,\n { limit: opts.limit },\n );\n const r = await fetch(u, { headers: this.headers() });\n if (!r.ok) throw new Error(`slots history ${r.status}: ${await r.text()}`);\n const body = (await r.json()) as { history: SlotHistoryEntry[] };\n return body.history;\n }\n\n /**\n * Restore the slot to a previous binding. Equivalent to\n * `bind(key, { assetId: previous.assetId, action: \"restore\" })`\n * — the audit row is tagged `restore` instead of `bind`.\n */\n async restore(\n slotKey: string,\n args: { assetId: string; preset?: VariantPreset; updatedBy?: string },\n ): Promise<{ ok: true; slotKey: string; assetId: string }> {\n const r = await fetch(\n endpointHref(this.opts, `/slots/${encodeURIComponent(slotKey)}`),\n {\n method: \"PUT\",\n headers: { ...this.headers(), \"Content-Type\": \"application/json\" },\n body: JSON.stringify({ ...args, action: \"restore\" }),\n },\n );\n if (!r.ok) throw new Error(`slot restore ${r.status}: ${await r.text()}`);\n return (await r.json()) as { ok: true; slotKey: string; assetId: string };\n }\n\n /** Remove a slot binding. The asset itself is left alone. */\n async unbind(slotKey: string): Promise<{ ok: true; removed: number }> {\n const r = await fetch(\n endpointHref(this.opts, `/slots/${encodeURIComponent(slotKey)}`),\n {\n method: \"DELETE\",\n headers: this.headers(),\n },\n );\n if (!r.ok) throw new Error(`slot unbind ${r.status}: ${await r.text()}`);\n return (await r.json()) as { ok: true; removed: number };\n }\n\n /** Invalidate the in-process cache after a slot rebind. */\n invalidateCache(slotKey?: string): void {\n invalidateSlotCache(slotKey);\n }\n\n private headers(): Record<string, string> {\n return authHeaders(this.opts);\n }\n}\n\n/**\n * Returned by `aq.assets.regenerate(...)`. The shape varies by kind —\n * images return immediately with the merged variant list; videos\n * return a dispatch handle (the actual transcode runs in a background\n * job and finishes async).\n */\nexport type RegenerateResult =\n | {\n ok: true;\n kind: \"image\";\n /** Full variant set after the merge. */\n variants: AssetVariant[];\n /** Presets newly written this run. Useful for showing \"added X\". */\n newVariants: VariantPreset[];\n /**\n * Which source the server read to derive the new variants:\n * - `\"original\"` / `\"raw\"` → lossless source bytes (best)\n * - `\"xl\"` / `\"lg\"` / `\"md\"` / `\"sm\"` / `\"thumb\"` → a previously\n * encoded WebP variant was used as the source. Output is\n * re-encoded WebP — fine for thumb/sm from lg, lossier when\n * working from already-small sources.\n *\n * The no-upscale clamp still applies: deriving `lg` (1920) from\n * a 640 `sm` source produces a 640-side `lg` variant, not a\n * stretched 1920.\n */\n sourceUsed: VariantPreset | \"raw\";\n }\n | {\n ok: true;\n kind: \"video\";\n dispatch: unknown;\n regenerated: string[] | \"default\";\n };\n\n/**\n * Wire shape returned by `POST /assets/upload-url`. Either the server\n * resolves the upload synchronously via dedup (`deduped: true` + existing\n * asset DTO) or it returns a presigned storage PUT URL plus a `process` payload\n * the caller must POST to `/assets/process` after the PUT lands.\n */\nexport type UploadUrlResult =\n | { deduped: true; asset: AssetDTO }\n | {\n deduped: false;\n upload: { url: string; headers?: Record<string, string> };\n process: { url: string; body: Record<string, unknown> };\n };\n\n/**\n * VIDEO-only delivery knobs threaded into `/assets/process`. Ignored for\n * image / audio / other uploads. Both fields default to today's behavior when\n * omitted, so existing callers are unaffected.\n */\nexport type UploadVideoOptions = {\n /**\n * `false` → skip the auto-dispatched HLS adaptive ladder (240p–2160p). Use\n * for download-only assets served as a progressive `-v.mp4` and never\n * streamed (e.g. share-video reels) — it avoids a second background job no\n * one watches. Default/absent → the ladder is generated as before.\n */\n hls?: boolean;\n /**\n * `true` → when the uploaded MP4 is ALREADY web-safe (H.264 + yuv420p),\n * re-mux the `video` variant with `-c copy` instead of re-encoding. Use for\n * delivery-ready uploads (the bytes are already H.264 High / yuv420p /\n * +faststart / capped bitrate) to skip a wasteful re-encode + generational\n * quality loss. Falls back to a full re-encode automatically when the source\n * is not web-safe. Default/absent → unconditional re-encode (today's path).\n */\n passthrough?: boolean;\n};\n\n/** Input shape accepted by `aq.assets.presignUploadUrl(...)`. */\nexport type PresignUploadUrlOptions = {\n /** Full sha256 (64 hex) of the bytes that will be PUT to storage. */\n sha256: string;\n /** MIME type of the bytes (e.g. `image/jpeg`, `video/mp4`). */\n mime: string;\n /** Byte length of the upload payload. */\n bytes: number;\n /** Suggested file name; surfaces in admin dashboards + extension fallback. */\n fileName: string;\n /**\n * Variant ladder to generate after `/assets/process`. Defaults to\n * `[\"original\"]` server-side when omitted — same contract as `aq.upload`.\n */\n presets?: VariantPreset[];\n /**\n * Pre-compression size of the source (useful when the browser ran\n * compressorjs / heic2any before computing `bytes`). Surfaces in admin\n * dashboards under `assets.client_original_bytes`.\n */\n clientOriginalBytes?: number;\n /** VIDEO-only delivery knobs forwarded into `/assets/process`. See {@link UploadVideoOptions}. */\n video?: UploadVideoOptions;\n};\n\n/** Input shape accepted by `aq.assets.composeMarketing(...)`. */\nexport type ComposeMarketingSegment = {\n /** Public URL of the source clip (typically a `/t/.../video.mp4` transform). */\n sourceUrl: string;\n /** Optional clip duration in seconds (cap for that segment). */\n durationSec?: number;\n};\n\nexport type ComposeMarketingComposition = {\n /** Transition between consecutive segments. Default `\"cut\"`. */\n transition?: \"cut\" | \"fade\";\n /** Optional audio track to mix on top of the final composition. */\n audioTrack?: { url: string };\n /** Final composition length in seconds (server may clamp). */\n finalDurationSec?: number;\n};\n\nexport type ComposeMarketingOptions = {\n /** Marketing-kit id this composition belongs to (server uses it for naming + dedup). */\n marketingKitId: string;\n /** Ordered clip segments to stitch. */\n segments: ComposeMarketingSegment[];\n /** Optional composition-level knobs (transitions, audio, duration). */\n composition?: ComposeMarketingComposition;\n};\n\nexport type ComposeMarketingResult = {\n /** Aquienpz asset id of the in-flight composition. Poll `aq.assets.waitReady(id)`. */\n assetId: string;\n /** Asset status at dispatch time — usually `\"processing\"`. */\n status: \"processing\" | \"ready\" | \"failed\";\n};\n\nclass AssetsApi {\n constructor(private readonly opts: NitidaClientOptions) {}\n\n /** Look up an asset by full sha256 (64 hex). Returns null on 404. */\n async byHash(sha256: string): Promise<AssetDTO | null> {\n const r = await fetch(\n endpointHref(this.opts, `/assets/by-hash/${sha256}`),\n { headers: this.headers() },\n );\n if (r.status === 404) return null;\n if (!r.ok) throw new Error(`assets byHash ${r.status}: ${await r.text()}`);\n return (await r.json()) as AssetDTO;\n }\n\n /** Bulk lookup by sha256s. */\n async byHashes(\n hashes: string[],\n ): Promise<{ existing: AssetDTO[]; missing: string[] }> {\n const r = await fetch(endpointHref(this.opts, \"/assets/by-hashes\"), {\n method: \"POST\",\n headers: { ...this.headers(), \"Content-Type\": \"application/json\" },\n body: JSON.stringify({ hashes }),\n });\n if (!r.ok)\n throw new Error(`assets byHashes ${r.status}: ${await r.text()}`);\n return (await r.json()) as { existing: AssetDTO[]; missing: string[] };\n }\n\n /** Paginated list of recent assets for the tenant. */\n async list(\n opts: { limit?: number; cursor?: string; includeDeleted?: boolean } = {},\n ): Promise<{\n assets: AssetDTO[];\n nextCursor: string | null;\n }> {\n const u = endpointUrl(this.opts, \"/assets\", {\n limit: opts.limit,\n cursor: opts.cursor,\n include_deleted: opts.includeDeleted ? \"true\" : undefined,\n });\n const r = await fetch(u, { headers: this.headers() });\n if (!r.ok) throw new Error(`assets list ${r.status}: ${await r.text()}`);\n return (await r.json()) as {\n assets: AssetDTO[];\n nextCursor: string | null;\n };\n }\n\n /** Full DTO for an asset (admin view — includes audit-only fields). */\n async get(assetId: string): Promise<AssetDTO & Record<string, unknown>> {\n const r = await fetch(endpointHref(this.opts, `/assets/${assetId}`), {\n headers: this.headers(),\n });\n if (!r.ok) throw new Error(`asset get ${r.status}: ${await r.text()}`);\n return (await r.json()) as AssetDTO & Record<string, unknown>;\n }\n\n /**\n * Slot bindings pointing at an asset. Use this before deleting an\n * asset so the admin sees which storefront slots would suddenly\n * resolve to nothing.\n */\n async bindings(assetId: string): Promise<\n Array<{\n slotKey: string;\n preset: VariantPreset | null;\n description: string | null;\n updatedAt: string;\n updatedBy: string | null;\n }>\n > {\n const r = await fetch(endpointHref(this.opts, `/assets/${assetId}/slots`), {\n headers: this.headers(),\n });\n if (!r.ok) throw new Error(`asset bindings ${r.status}: ${await r.text()}`);\n const body = (await r.json()) as {\n slots: Array<{\n slotKey: string;\n preset: VariantPreset | null;\n description: string | null;\n updatedAt: string;\n updatedBy: string | null;\n }>;\n };\n return body.slots;\n }\n\n /**\n * Full variant list for an asset — preset, URL, dimensions, bytes.\n * Stronger-typed wrapper around `get()` that exposes only the\n * `variants` field with the proper `AssetVariant[]` shape.\n *\n * const v = await aq.assets.variants(logoId);\n * v.map((x) => x.preset); // → (\"thumb\" | \"sm\" | … | \"original\")[]\n *\n * ⚠️ Returns `[]` — not an error — against a server deploy older than the\n * 2026-08-17 deploy, which never sent the field (doc 240 §4.3). An empty\n * array is therefore \"no variants OR old server\". For a plain existence\n * check prefer `hasPreset(dto, preset)` on `dto.presets`, which every server\n * version sends; use this when you need the URLs and sizes.\n */\n async variants(assetId: string): Promise<AssetVariant[]> {\n const dto = await this.get(assetId);\n return Array.isArray((dto as { variants?: unknown }).variants)\n ? (dto as { variants: AssetVariant[] }).variants\n : [];\n }\n\n /**\n * Add or rebuild variants on an existing asset. Image presets are\n * MERGED with what's there — passing `{ presets: [\"thumb\"] }` adds\n * the thumb variant without touching `lg`, `sm`, `original`, etc.\n *\n * // Day 0: upload original-only logo\n * const { assetId } = await aq.upload(logoFile); // defaults to [\"original\"]\n *\n * // Day 7: need a thumb without re-uploading\n * await aq.assets.regenerate(assetId, { presets: [\"thumb\"] });\n *\n * const after = await aq.assets.variants(assetId);\n * after.map((v) => v.preset); // → [\"original\", \"thumb\"]\n *\n * Passing no presets re-runs the FULL default pipeline for that\n * asset's kind (thumb+sm+md+lg for images, poster+video for video).\n *\n * If the asset was uploaded original-only and the cleanup job has\n * already reaped `raw/`, the route falls back to reading the source\n * bytes from `variants/o.<ext>` — no need to re-upload.\n *\n * Video presets are filtered to `[\"poster\",\"video\",\"aiproxy\"]` and\n * dispatched to the background job (the call returns immediately\n * with a dispatch handle; poll `aq.assets.get(id).status` for\n * completion).\n */\n async regenerate(\n assetId: string,\n opts: { presets?: VariantPreset[] } = {},\n ): Promise<RegenerateResult> {\n const r = await fetch(\n endpointHref(this.opts, `/assets/${assetId}/regenerate`),\n {\n method: \"POST\",\n headers: { ...this.headers(), \"Content-Type\": \"application/json\" },\n body: JSON.stringify(opts.presets ? { presets: opts.presets } : {}),\n },\n );\n if (!r.ok)\n throw new Error(`asset regenerate ${r.status}: ${await r.text()}`);\n return (await r.json()) as RegenerateResult;\n }\n\n /** Merge metadata into an asset (role / slot / description / tags). */\n async patchMetadata(\n assetId: string,\n metadata: Record<string, unknown>,\n ): Promise<{ ok: true; metadata: Record<string, unknown> }> {\n const r = await fetch(endpointHref(this.opts, `/assets/${assetId}`), {\n method: \"PATCH\",\n headers: { ...this.headers(), \"Content-Type\": \"application/json\" },\n body: JSON.stringify({ metadata }),\n });\n if (!r.ok) throw new Error(`asset patch ${r.status}: ${await r.text()}`);\n return (await r.json()) as { ok: true; metadata: Record<string, unknown> };\n }\n\n /**\n * Request a presigned storage PUT URL for direct browser-side uploads.\n *\n * Mirrors the first half of `aq.upload()` — the caller (typically a\n * BFF / share-link dropzone) computes sha256 in the browser, then\n * uploads bytes straight to object storage with the returned `upload.url`,\n * then POSTs `process.body` to `/assets/process` (see {@link processAndWait})\n * once storage has the bytes.\n *\n * If the sha is already known to the tenant the server short-circuits\n * with `{ deduped: true, asset }` — no PUT needed.\n *\n * @example The browser-direct flow, in full\n * ```ts\n * // SERVER (holds the amk_rt_* key — never the browser):\n * const presign = await aq.assets.presignUploadUrl({ sha256, mime, bytes, fileName, presets });\n * if (presign.deduped) return presign.asset; // those bytes already exist; none fly\n *\n * // BROWSER: PUT straight to presign.upload.url — the bytes never touch your server.\n * // ⚠️ The STORAGE BUCKET answers that preflight itself, so your origin must be in its CORS\n * // policy. Symptom when it is not: \"PUT failed: network error\" with every earlier step\n * // green — and it cannot be fixed in this SDK, in your app, or by the API's allowed origins.\n *\n * // SERVER again, forwarding presign.process.body VERBATIM:\n * const asset = await aq.assets.processAndWait(presign.process.body, { timeoutMs: 300_000 });\n * ```\n *\n * Works for images AND video. A video answers immediately with\n * `{ assetId, status: \"processing\" }` while a background job transcodes, so\n * give `processAndWait` a bigger `timeoutMs` (a transcode + HLS ladder runs\n * 1–2 min; 300_000 is a sane floor).\n */\n async presignUploadUrl(\n opts: PresignUploadUrlOptions,\n ): Promise<UploadUrlResult> {\n const body: Record<string, unknown> = {\n sha256: opts.sha256,\n mime: opts.mime,\n bytes: opts.bytes,\n fileName: opts.fileName,\n };\n if (opts.presets && opts.presets.length > 0) body.presets = opts.presets;\n if (opts.clientOriginalBytes != null)\n body.clientOriginalBytes = opts.clientOriginalBytes;\n if (opts.video != null) body.video = opts.video;\n\n const r = await fetch(endpointHref(this.opts, \"/assets/upload-url\"), {\n method: \"POST\",\n headers: { ...this.headers(), \"Content-Type\": \"application/json\" },\n body: JSON.stringify(body),\n });\n if (!r.ok) throw new Error(`upload-url ${r.status}: ${await r.text()}`);\n return (await r.json()) as UploadUrlResult;\n }\n\n /**\n * Dispatch `/assets/process` with the body returned by a prior\n * {@link presignUploadUrl} call, then poll until the asset transitions\n * to `ready` or `failed`. Throws on `failed` or timeout.\n *\n * Use this when bytes were uploaded directly from the browser to storage —\n * `aq.upload()` already does presign + PUT + process + wait in one\n * step when the server holds the bytes.\n */\n async processAndWait(\n processBody: Record<string, unknown>,\n opts: { timeoutMs?: number } = {},\n ): Promise<AssetDTO> {\n const r = await fetch(endpointHref(this.opts, \"/assets/process\"), {\n method: \"POST\",\n headers: { ...this.headers(), \"Content-Type\": \"application/json\" },\n body: JSON.stringify(processBody),\n });\n if (!r.ok) throw new Error(`process ${r.status}: ${await r.text()}`);\n const proc = (await r.json()) as { assetId?: string };\n if (!proc.assetId) throw new Error(\"process returned no assetId\");\n const final = await this.waitReady(proc.assetId, opts.timeoutMs);\n if (final.status === \"failed\") {\n throw new Error(\n `processAndWait: asset ${proc.assetId} ended status=failed`,\n );\n }\n return final;\n }\n\n /**\n * Poll `GET /assets/:id` until the asset transitions to `ready` or\n * `failed`. Returns the final DTO (whether ready OR failed — callers\n * decide whether to throw on `failed`). Throws on timeout.\n *\n * Default timeout is 5 minutes; videos / HLS ladders may need a\n * higher cap (pass `10 * 60_000` for compositions, transcodes).\n */\n async waitReady(assetId: string, timeoutMs = 5 * 60_000): Promise<AssetDTO> {\n const start = Date.now();\n let delay = 500;\n let last: AssetDTO | null = null;\n while (Date.now() - start < timeoutMs) {\n last = (await this.get(assetId)) as AssetDTO;\n if (last.status === \"ready\" || last.status === \"failed\") return last;\n await new Promise((r) => setTimeout(r, delay));\n delay = Math.min(delay * 1.5, 5_000);\n }\n if (!last) throw new Error(`waitReady: no asset ${assetId}`);\n throw new Error(`waitReady timeout for ${assetId}`);\n }\n\n /**\n * Dispatch `POST /assets/compose-marketing` to stitch pre-uploaded clip\n * segments into a single MP4 composition. Returns the processing asset\n * id immediately — does NOT block on completion. Callers poll via\n * {@link waitReady} (typical timeout: 10 min for multi-segment kits).\n *\n * Tenant scope is inherited from the SDK client; `tenantCode` is added\n * to the request body so the background job can resolve it without\n * re-reading the header.\n */\n async composeMarketing(\n opts: ComposeMarketingOptions,\n ): Promise<ComposeMarketingResult> {\n const r = await fetch(\n endpointHref(this.opts, \"/assets/compose-marketing\"),\n {\n method: \"POST\",\n headers: { ...this.headers(), \"Content-Type\": \"application/json\" },\n body: JSON.stringify({\n tenantCode: this.opts.tenantCode,\n marketingKitId: opts.marketingKitId,\n segments: opts.segments,\n composition: opts.composition ?? {},\n }),\n },\n );\n if (!r.ok) {\n throw new Error(`compose-marketing ${r.status}: ${await r.text()}`);\n }\n const body = (await r.json()) as {\n asset?: { id: string; status: \"processing\" | \"ready\" | \"failed\" };\n assetId?: string;\n status?: \"processing\" | \"ready\" | \"failed\";\n };\n // Server returns `{ asset: { id, status }, dispatch? }`; some older\n // builds returned `{ assetId, status }` directly. Normalize both.\n const assetId = body.asset?.id ?? body.assetId;\n const status = body.asset?.status ?? body.status ?? \"processing\";\n if (!assetId) {\n throw new Error(\"compose-marketing: response missing assetId\");\n }\n return { assetId, status };\n }\n\n private headers(): Record<string, string> {\n return authHeaders(this.opts);\n }\n}\n\n// ---------------------------------------------------------------------------\n// Upload helpers\n// ---------------------------------------------------------------------------\n\n/**\n * Best-effort MIME from a file name's extension. Used as a fallback for `Uint8Array`\n * uploads (which carry no inherent type) so they still get classified correctly instead\n * of silently becoming `application/octet-stream` → `kind:\"other\"`. Returns `null` when\n * the extension is unknown.\n */\nconst MIME_BY_EXT: Record<string, string> = {\n webp: \"image/webp\",\n jpg: \"image/jpeg\",\n jpeg: \"image/jpeg\",\n png: \"image/png\",\n gif: \"image/gif\",\n avif: \"image/avif\",\n heic: \"image/heic\",\n heif: \"image/heif\",\n svg: \"image/svg+xml\",\n bmp: \"image/bmp\",\n tiff: \"image/tiff\",\n mp4: \"video/mp4\",\n webm: \"video/webm\",\n mov: \"video/quicktime\",\n m4v: \"video/x-m4v\",\n pdf: \"application/pdf\",\n};\nexport function mimeFromFileName(fileName: string | undefined): string | null {\n if (!fileName) return null;\n const ext = fileName.split(\".\").pop()?.toLowerCase();\n return ext ? (MIME_BY_EXT[ext] ?? null) : null;\n}\n\n/**\n * Subset of compressorjs options exposed through the SDK. Re-imported here\n * to avoid a hard import dependency on `./web` from this top-level module\n * (the /web subpath uses browser-only APIs). The runtime `compress`\n * implementation is lazy-loaded so Node/Bun callers don't pay the bundle\n * cost — see `aq.upload` below.\n */\nexport type CompressOptions = {\n quality?: number;\n mimeType?: \"image/jpeg\" | \"image/webp\";\n maxWidth?: number;\n maxHeight?: number;\n convertSize?: number;\n strict?: boolean;\n keepOriginalDimensions?: boolean;\n convertHeic?: boolean;\n onProgress?: (\n stage: \"convertingHeic\" | \"compressing\" | \"compressingKeepingDimensions\",\n ) => void;\n};\n\nexport type UploadOptions = {\n fileName?: string;\n /**\n * MIME type of the bytes. **Only needed for a `Uint8Array` input** — a `File`/`Blob`\n * already carries its `.type`. Raw bytes have no inherent MIME, so without this (and\n * without an extension on `fileName` to infer from) they upload as\n * `application/octet-stream`, which the server classifies as `kind:\"other\"` —\n * meaning NO image/video variants are generated and `regenerate()` is unsupported.\n * Resolution order for the effective MIME: `Blob.type` → `contentType` →\n * inferred from `fileName`'s extension → `application/octet-stream`.\n *\n * aq.upload(bytes, { fileName: \"cover.webp\" }) // inferred → image/webp ✓\n * aq.upload(bytes, { contentType: \"image/webp\" }) // explicit ✓\n * aq.upload(bytes) // octet-stream → kind:\"other\" ⚠\n */\n contentType?: string;\n /** Computed sha256 of bytes. Skip to compute locally with WebCrypto (browser only). */\n sha256?: string;\n /**\n * Client-side compression before upload. Saves user bandwidth — typical\n * 5–10× reduction for raw phone photos. Browser-only; in Node/Bun this\n * silently no-ops with a console.warn and the raw bytes upload as-is.\n *\n * - `true` → use SDK `DEFAULT_COMPRESSION_OPTIONS` (webapp-tuned)\n * - `CompressOptions` → merge over defaults\n * - `false` / omit → no compression (current default behavior)\n *\n * Implementation is lazy-imported from `@nitida/sdk/web` so callers\n * that never set `compress` don't pay the compressorjs + heic2any\n * bundle cost. Skipped for non-image MIMEs (video, PDF) regardless of\n * this option — those go to the upload pipeline raw.\n *\n * @see {@link CompressOptions}\n * @see https://github.com/espaciofuturoio/aquienpz/tree/main/packages/sdk#client-side-compression-browsers\n */\n compress?: boolean | CompressOptions;\n /**\n * Variant set to generate. **Defaults to `[\"original\"]`** —\n * if you omit this option, only the raw bytes land on the CDN\n * under the `o` path. Pass an explicit array to request more.\n *\n * Image presets (`thumb` 256 · `sm` 640 · `md` 1280 · `lg` 1920 ·\n * `xl` 3840 · `original`):\n * - `[\"original\"]` (default) → just the raw bytes. Right call for\n * logos / SVGs / anything you'll resize browser-side or via\n * `aq.assets.regenerate(id, { presets: [\"thumb\"] })` later.\n * - `[\"thumb\",\"sm\",\"md\",\"lg\"]` → the classic responsive ladder.\n * - `[\"thumb\",\"sm\",\"md\",\"lg\",\"xl\"]` → add 4K.\n *\n * Video presets (`poster`, `video`, `aiproxy`): omit `aiproxy` if\n * the tenant doesn't need the low-res transcode for AI captioning.\n *\n * No upscaling. Each size preset is a **ceiling**; a 1080×720 source\n * asked for `xl` (3840) yields a 1080×720 xl variant, not a stretched\n * 3840-wide image.\n *\n * Idempotent: you can always add missing variants later via\n * `aq.assets.regenerate(id, { presets: [...] })`. The platform\n * stores the source so regeneration doesn't require re-uploading.\n */\n presets?: VariantPreset[];\n /**\n * Max time to wait for the asset to transition to `ready` (or `failed`)\n * after dispatch. Default `5 * 60_000` (5 min). Bump higher for large\n * videos / HLS transcodes — aquienpz processing time scales with input\n * size and per-instance CPU.\n *\n * Throws `Error(\"waitReady timeout for <id>\")` if the deadline passes\n * without the asset transitioning. The asset row stays in aquienpz\n * (status=\"processing\") and the next byHash lookup will return it once\n * processing completes; the caller can resume with their own poll.\n */\n timeoutMs?: number;\n /**\n * VIDEO-only delivery knobs forwarded into `/assets/process`. See\n * {@link UploadVideoOptions}. Ignored for non-video uploads.\n *\n * // A delivery-ready reel: skip the unused HLS ladder + skip re-encode.\n * await aq.upload(mp4Bytes, {\n * fileName: \"reel.mp4\",\n * presets: [\"poster\", \"video\"],\n * video: { hls: false, passthrough: true },\n * });\n */\n video?: UploadVideoOptions;\n};\n\n/** Default preset set the SDK sends to `/assets/upload-url` when the caller omits `presets`. */\nconst DEFAULT_UPLOAD_PRESETS: VariantPreset[] = [\"original\"];\n\nexport type UploadResult = {\n assetId: string;\n sha256: string;\n cdnUrl: string;\n};\n\nasync function computeSha256(\n bytes: ArrayBuffer | Uint8Array | Blob,\n): Promise<string> {\n const buf =\n bytes instanceof Blob\n ? await bytes.arrayBuffer()\n : bytes instanceof Uint8Array\n ? (bytes.buffer as ArrayBuffer)\n : bytes;\n const digest = await crypto.subtle.digest(\"SHA-256\", buf);\n return [...new Uint8Array(digest)]\n .map((b) => b.toString(16).padStart(2, \"0\"))\n .join(\"\");\n}\n\n// ---------------------------------------------------------------------------\n// Main facade\n// ---------------------------------------------------------------------------\n\n// ---------------------------------------------------------------------------\n// Usage (Cloudinary-style consumption dashboard data)\n// ---------------------------------------------------------------------------\n\n// ---------------------------------------------------------------------------\n// Slot history\n// ---------------------------------------------------------------------------\n\nexport type SlotHistoryEntry = {\n id: string;\n action: \"bind\" | \"unbind\" | \"restore\";\n preset: VariantPreset | null;\n description: string | null;\n updatedAt: string;\n updatedBy: string | null;\n assetId: string | null;\n /** Resolved DTO when the asset still exists; `null` after delete / 404. */\n asset: AssetDTO | null;\n};\n\nexport type UsageSnapshot = {\n tenant: { id: number; code: string };\n storage: { totalBytes: number; assetCount: number };\n today: UsageWindow;\n last30Days: UsageWindow;\n};\n\nexport type UsageWindow = {\n reads: number;\n writes: number;\n lists: number;\n deletes: number;\n admins: number;\n upscales: number;\n processes: number;\n /**\n * Minutes of video actually TRANSCODED in the window — source minutes ×\n * encode passes, so a 7-rung HLS ladder over a 2-minute clip books 14.\n *\n * A re-encode of a video already ingested counts AGAIN. That is the point:\n * `assets.assets` cannot report it, because its insert is\n * `ON CONFLICT DO UPDATE` and a re-encode creates no row there.\n *\n * A stream copy (`-c copy` passthrough, an idempotent cache skip) books\n * nothing, so a tenant that ran no encoder reads `0` — and that `0` is real.\n */\n videoMinutes: number;\n /** Encode passes behind `videoMinutes`. 0 when nothing was encoded. */\n videoEncodes: number;\n};\n\n/**\n * ⚠️ REMOVED 2026-08-17: `bytesIn` on `UsageWindow`/`UsageDailyPoint` and\n * `bytesTotal` on `UsagePerKey`.\n *\n * All three were structurally zero: the field behind them was never populated,\n * on any row. They could not be instrumented in place either — uploads go to\n * object storage through presigned URLs, so the payload never passes through\n * the API, and the only figure measurable there is a JSON envelope of a few\n * hundred bytes.\n *\n * A field that always reads `0` is worse than an absent field, because absent\n * is honest — a `0` next to a real `storage.totalBytes` reads as a measurement.\n * The byte number that IS true is still served: `storage.totalBytes`.\n */\n\nexport type UsageDailyPoint = {\n date: string;\n reads: number;\n writes: number;\n lists: number;\n deletes: number;\n processes: number;\n bytesStored: number;\n /** See `UsageWindow.videoMinutes`. Minutes transcoded on this day. */\n videoMinutes: number;\n videoEncodes: number;\n};\n\nexport type UsagePerKey = {\n apiKeyId: string;\n prefix: string | null;\n name: string | null;\n opsTotal: number;\n lastSeen: string;\n};\n\nclass UsageApi {\n constructor(private readonly opts: NitidaClientOptions) {}\n\n /** Snapshot for the active tenant — storage + today + last 30 days totals. */\n async snapshot(): Promise<UsageSnapshot> {\n const r = await fetch(endpointHref(this.opts, \"/usage\"), {\n headers: this.headers(),\n });\n if (!r.ok) throw new Error(`usage snapshot ${r.status}: ${await r.text()}`);\n return (await r.json()) as UsageSnapshot;\n }\n\n /** Daily rollup for charts — 1..365 days, default 30. */\n async timeseries(days = 30): Promise<{\n tenant: { id: number; code: string };\n days: UsageDailyPoint[];\n }> {\n const r = await fetch(\n endpointUrl(this.opts, \"/usage/timeseries\", { days }),\n { headers: this.headers() },\n );\n if (!r.ok)\n throw new Error(`usage timeseries ${r.status}: ${await r.text()}`);\n return (await r.json()) as {\n tenant: { id: number; code: string };\n days: UsageDailyPoint[];\n };\n }\n\n /** Per-API-key breakdown for the current month. */\n async keys(): Promise<{\n tenant: { id: number; code: string };\n monthStart: string;\n keys: UsagePerKey[];\n }> {\n const r = await fetch(endpointHref(this.opts, \"/usage/keys\"), {\n headers: this.headers(),\n });\n if (!r.ok) throw new Error(`usage keys ${r.status}: ${await r.text()}`);\n return (await r.json()) as {\n tenant: { id: number; code: string };\n monthStart: string;\n keys: UsagePerKey[];\n };\n }\n\n private headers(): Record<string, string> {\n return authHeaders(this.opts);\n }\n}\n\nexport class NitidaClient {\n readonly slots: SlotsApi;\n readonly assets: AssetsApi;\n readonly usage: UsageApi;\n /**\n * Effective options — read-only. Exposed so the `/web` and `/expo`\n * subpaths can inherit endpoint / apiKey / tenant scope from the\n * configured client without re-passing them per call site.\n */\n readonly opts: NitidaClientOptions;\n\n constructor(opts: NitidaClientOptions) {\n this.opts = opts;\n const cdn = opts.cdnBase ?? \"https://8ok.uk\";\n setCdnBase(cdn);\n // Configure the process-global tenant so every variant URL builder\n // (`getAssetUrl`, `urlFor`, `srcSetFor`, upload `cdnUrl`) emits the\n // tenant-prefixed path `<cdn>/<tid b36>/v/<sha>-<preset>.<ext>`.\n setTenantId(opts.tenantId);\n configureSlotResolver({\n endpoint: opts.endpoint,\n apiKey: opts.apiKey,\n tenantCode: opts.tenantCode,\n });\n this.slots = new SlotsApi(opts);\n this.assets = new AssetsApi(opts);\n this.usage = new UsageApi(opts);\n }\n\n /** Tenant id as base36 path segment (e.g. tenantId=4 → \"4/v/\"). */\n get tenantSegment(): string {\n return `${this.opts.tenantId.toString(36)}/v/`;\n }\n\n /** Build the canonical CDN URL deterministically from sha + preset. */\n urlFor(asset: Pick<AssetDTO, \"sha\">, preset: VariantPreset = \"lg\"): string {\n return getAssetUrl(asset, preset);\n }\n\n /** Build a responsive srcSet across the available image presets. */\n srcSetFor(asset: Pick<AssetDTO, \"sha\" | \"presets\">): string {\n return getAssetSrcSet(asset);\n }\n\n /**\n * Build an on-the-fly transform URL — `<cdn>/t/<dsl>/<sha>.<ext>`.\n *\n * ## URL CONVENTION — transforms are NOT tenant-prefixed (variants are)\n * Two distinct delivery paths, by design:\n * - **Variants / presets** (`urlFor`, `srcSetFor`, upload `cdnUrl`):\n * `<cdn>/<tenantId b36>/v/<sha>-<preset>.<ext>` ← tenant-scoped (e.g. `/4/v/<sha>-lg.webp`)\n * - **On-the-fly transforms** (`transform`, `transformSrcSet`):\n * `<cdn>/t/<dsl>/<sha>.<ext>` ← GLOBAL, no tenant segment (`/t/...`)\n * The transform service is content-addressed by sha + resizes from the source on demand,\n * so it needs no tenant in the path. Prefixing a transform URL with `/<tenant>/t/...` 404s.\n * Consumers that build URLs by hand must NOT add the tenant segment to `/t/` URLs.\n *\n * Returns the canonical `lg` variant URL when called with empty options,\n * so callers can swap `urlFor()` for `transform()` without thinking.\n *\n * URLs with the same params in different order produce the same\n * cache entry (the server canonicalizes both sides). Safe to use as\n * stable cache keys.\n *\n * <Image\n * src={aq.transform(asset, { width: 1280 })}\n * srcSet={aq.transformSrcSet(asset, [640, 960, 1280, 1920])}\n * sizes=\"(max-width: 768px) 100vw, 50vw\"\n * />\n *\n * @see {@link TransformOptions} for the full param matrix.\n */\n // Overload 1: no signing — synchronous, on-ladder width only (strict).\n transform(asset: Pick<AssetDTO, \"sha\">, opts?: TransformOptions): string;\n // Overload 2: with { sign: true } — async; returns `?sig=<hmac>` URL.\n // Accepts SignedTransformOptions so a signed URL may carry an off-ladder\n // custom width (the signature earns the edge whitelist bypass).\n transform(\n asset: Pick<AssetDTO, \"sha\">,\n opts: SignedTransformOptions,\n signOpts: { sign: true },\n ): Promise<string>;\n transform(\n asset: Pick<AssetDTO, \"sha\">,\n opts: SignedTransformOptions = {},\n signOpts?: { sign: true },\n ): string | Promise<string> {\n if (!signOpts?.sign) {\n // Unsigned path. Overload 1 constrains `width` to the ladder at every\n // public call site, so an off-ladder width can't reach here through the\n // typed API — narrow back to TransformOptions for the strict builder.\n return (\n getTransformUrl(asset, opts as TransformOptions) ??\n this.urlFor(asset, \"lg\")\n );\n }\n if (!this.opts.signingKey) {\n throw new Error(\n \"aq.transform({ sign: true }) requires `signingKey` in NitidaClientOptions. \" +\n \"Pull the tenant's signing key from /admin/tenants/:id and pass it to the SDK constructor on a SERVER-side instance only.\",\n );\n }\n // Signed path — custom (off-ladder) widths allowed. Empty opts → no\n // transform DSL, fall back to the unsigned `lg` variant URL.\n return (\n getSignedTransformUrl(asset, opts, this.opts.signingKey) ??\n Promise.resolve(this.urlFor(asset, \"lg\"))\n );\n }\n\n /**\n * Build a responsive `srcSet` string. One transform URL per width; all\n * other options apply to every URL.\n *\n * Pass `{ sign: true }` to return signed URLs (async). Without it, the\n * call stays synchronous as before.\n */\n transformSrcSet(\n asset: Pick<AssetDTO, \"sha\">,\n widths: number[],\n extraOpts?: Omit<TransformOptions, \"width\">,\n ): string;\n transformSrcSet(\n asset: Pick<AssetDTO, \"sha\">,\n widths: number[],\n extraOpts: Omit<TransformOptions, \"width\">,\n signOpts: { sign: true },\n ): Promise<string>;\n transformSrcSet(\n asset: Pick<AssetDTO, \"sha\">,\n widths: number[],\n extraOpts: Omit<TransformOptions, \"width\"> = {},\n signOpts?: { sign: true },\n ): string | Promise<string> {\n if (!signOpts?.sign) return getTransformSrcSet(asset, widths, extraOpts);\n if (!this.opts.signingKey) {\n throw new Error(\n \"aq.transformSrcSet({ sign: true }) requires `signingKey` in NitidaClientOptions.\",\n );\n }\n const key = this.opts.signingKey;\n return Promise.all(\n widths.map(async (w) => {\n // Signed path → off-ladder widths allowed; build+sign via the\n // custom-width helper (the strict `getTransformUrl` would reject a\n // raw `number` width).\n const signed = await getSignedTransformUrl(\n asset,\n { ...extraOpts, width: w },\n key,\n );\n return signed ? `${signed} ${w}w` : null;\n }),\n ).then((parts) => parts.filter((s): s is string => s != null).join(\", \"));\n }\n\n /**\n * Build an on-the-fly VIDEO transform URL — Phase 4.\n *\n * Same DSL shape as `transform()` but the URL has a `.mp4` (default)\n * or `.webm` extension and the server routes the request to a\n * background job for video encoding (vs the inline pipeline for\n * images).\n *\n * On the first request the route returns **202 Accepted** with\n * `Retry-After: 10` while the Job runs (typically 5-30 s for a\n * short clip). The response body includes `outputUrl` which is the\n * eventual CDN URL — poll the same transform URL after the\n * retry-after window to get a 302 redirect to it.\n *\n * const url = aq.transformVideo(asset, {\n * width: 1080, height: 1920, fit: \"cover\",\n * start: 0, duration: 15,\n * });\n * // Pass to Video.js / <video src={url}>; on the first load it\n * // gets 202 + body.outputUrl; subsequent loads hit cache → 302.\n *\n * Video-specific DSL params:\n * - `start` (seconds, decimal OK)\n * - `duration` (seconds, 1..300)\n * - `format`: \"mp4\" (default) or \"webm\"\n *\n * The other params (`width`, `height`, `fit`) work identically to\n * image transforms. `gravity`, `quality`, `effect`, `dpr` are\n * accepted by the DSL but currently ignored on the video path.\n */\n transformVideo(\n asset: Pick<AssetDTO, \"sha\">,\n opts: TransformOptions = {},\n ): string {\n return getVideoTransformUrl(asset, opts) ?? this.urlFor(asset, \"lg\");\n }\n\n /**\n * Build the HLS master playlist URL for a VIDEO asset (Phase 5).\n *\n * Returns `<cdn>/t/format=hls(,start=…,duration=…)/<sha>.m3u8`. Pass\n * to an HLS-aware player:\n *\n * <video\n * src={aq.streamingUrl(asset)}\n * controls playsInline\n * // Video.js v10's @videojs/http-streaming ships native HLS —\n * // no plugin needed.\n * />\n *\n * On the first request the server returns **202 Accepted** while a\n * background job builds the multi-rung ladder (typically 1-3 min for\n * a 90 s source — five rungs of 240p/360p/480p/720p/1080p @ AAC).\n * Subsequent requests hit the cache → **302** to the master.m3u8.\n *\n * Supports `start` + `duration` to ladder a sub-clip. Other DSL\n * params (width, height, fit) are ignored on the HLS path because\n * the rungs determine resolution.\n */\n streamingUrl(\n asset: Pick<AssetDTO, \"sha\">,\n opts: Omit<TransformOptions, \"format\"> = {},\n ): string {\n return getHlsStreamingUrl(asset, opts);\n }\n\n /**\n * Upload a file or raw bytes. Returns the new asset id + canonical\n * URL. Hash-deduped — uploading the same bytes twice returns the\n * existing asset.\n *\n * Browser-first: uses `Blob` + WebCrypto. For Node 20+, pass a\n * Uint8Array and a precomputed `sha256` (since `crypto.subtle` works\n * but isn't always available depending on the runtime).\n */\n /**\n * Upload bytes end to end: optional client compression → sha256 → presign → **direct-to-storage PUT**\n * → `/assets/process` → wait until the asset is ready.\n *\n * ⚠️ `presets` decides what exists FOREVER. Omit it and only `original` is written; ask for\n * `[\"thumb\"]` and the bytes you just uploaded are **not retrievable**. A variant not requested in\n * this first ingest cannot be added later once the cleanup job reaps `raw/` — measured once as\n * \"97 files archived successfully, zero recoverable\".\n *\n * @example Deliver an image on a site (the responsive ladder)\n * ```ts\n * import { NitidaClient } from \"@nitida/sdk/server\";\n *\n * const aq = new NitidaClient({ endpoint, apiKey, tenantCode, tenantId });\n * const { assetId, sha256 } = await aq.upload(file, {\n * fileName: file.name,\n * presets: [\"thumb\", \"sm\", \"md\", \"lg\"],\n * });\n * ```\n *\n * @example ARCHIVE a file — you must ask for `original`\n * ```ts\n * await aq.upload(bytes, {\n * fileName: \"contrato.pdf\",\n * contentType: \"application/pdf\",\n * presets: [\"original\"], // without this the bytes are unrecoverable\n * });\n * ```\n *\n * @example Raw bytes need an explicit MIME\n * ```ts\n * await aq.upload(bytes, { fileName: \"track.mp3\", contentType: \"audio/mpeg\" });\n * // Without either, it stores as kind:\"other\" — no variants, and regenerate() is unsupported.\n * ```\n *\n * @example Video — and what does NOT work there\n * ```ts\n * // `original` is accepted and then silently DROPPED: /assets/process filters video presets to\n * // {poster, video, aiproxy, probe} before dispatching the transcode Job.\n * await aq.upload(clip, { fileName: \"tour.mp4\", presets: [\"poster\", \"video\"] });\n *\n * // Omit `aiproxy`/`probe` unless the asset really goes to a vision model — they cost encode\n * // time and permanent stored objects that nothing else reads.\n * ```\n */\n async upload(\n input: File | Blob | Uint8Array,\n opts: UploadOptions = {},\n ): Promise<UploadResult> {\n // 1. Resolve incoming bytes + mime first (the source of truth for\n // \"should we compress this?\")\n const sourceIsBlob = input instanceof File || input instanceof Blob;\n // A Uint8Array has no inherent MIME. Fall back to an explicit `contentType`, then to\n // the file extension, before octet-stream (which the server files as\n // `kind:\"other\"` — no variants). A File/Blob's own `.type` always wins when present.\n const sourceMime =\n (sourceIsBlob ? input.type : \"\") ||\n opts.contentType ||\n mimeFromFileName(opts.fileName) ||\n \"application/octet-stream\";\n if (!sourceIsBlob && sourceMime === \"application/octet-stream\") {\n console.warn(\n \"[@nitida/sdk] upload(Uint8Array): no MIME resolved (no `contentType`, no recognizable \" +\n '`fileName` extension) — the asset will be stored as kind:\"other\" with NO image/video ' +\n \"variants and regenerate() unsupported. Pass `contentType` or a `fileName` with an extension.\",\n );\n }\n\n // 2. Optional client-side compression. Image MIMEs only; non-image\n // sources pass through unchanged so a video or PDF upload still\n // works when the caller sets `compress: true` blanket-fashion.\n let bytes: Uint8Array;\n let effectiveMime: string;\n let clientOriginalBytes: number | undefined;\n\n const wantCompression =\n !!opts.compress &&\n sourceIsBlob &&\n typeof window !== \"undefined\" &&\n sourceMime.startsWith(\"image/\");\n\n if (wantCompression) {\n const compressOpts =\n opts.compress === true ? {} : (opts.compress as CompressOptions);\n // Lazy: keeps compressorjs/heic2any out of bundles that don't use it.\n //\n // Resolve `./web` against `import.meta.url` at runtime so no static\n // analyzer — esbuild, tsup, `bun build --compile`, vite, rollup —\n // can follow the specifier. Holding the path in a plain `const`\n // was not enough: `bun build --compile` constant-folds simple\n // strings and still eagerly bundled `./web.js`, which\n // top-level-imports the browser-only peer deps\n // `@aquienpz/asset-uploader-web` / `@nitida/asset-compressor-web`\n // — neither installed on server consumers — crashing the\n // single-binary on boot with `Cannot find module\n // '@aquienpz/asset-uploader-web'`.\n //\n // The earlier `new URL(\"./web.js\", import.meta.url)` + `await import(URL)`\n // dance survived bun-compile but Turbopack still tracks the URL literal\n // and tries to resolve `./web.js` at build time (no such file exists in\n // src/, only src/web/index.ts), failing with \"Module not found\".\n //\n // Indirect-eval via the Function constructor is opaque to BOTH static\n // analyzers — neither bun-compile nor Turbopack can follow the string\n // back to a module specifier. The browser `typeof window` guard above\n // ensures the branch never runs on the server, so the indirection is\n // safe at runtime.\n // Build the URL inside the Function body too — Turbopack still tracks\n // `new URL(<any expr>, import.meta.url)` as a resolution pattern even\n // when the first arg isn't a literal, so we have to hide both the URL\n // construction AND the import() behind indirect eval.\n const dynImport = new Function(\n \"base\",\n \"return import(new URL('./' + 'web' + '.js', base).href)\",\n ) as (base: string) => Promise<typeof import(\"./web\")>;\n const { compressImage } = await dynImport(import.meta.url);\n const result = await compressImage(input as File | Blob, compressOpts);\n bytes = new Uint8Array(await result.blob.arrayBuffer());\n clientOriginalBytes = result.originalBytes;\n effectiveMime = result.blob.type || sourceMime;\n } else {\n if (opts.compress && !sourceIsBlob) {\n console.warn(\n \"[@nitida/sdk] compress: true requires a File or Blob input; got Uint8Array — uploading raw bytes.\",\n );\n } else if (opts.compress && typeof window === \"undefined\") {\n console.warn(\n \"[@nitida/sdk] compress: true is browser-only — uploading raw bytes.\",\n );\n } else if (opts.compress && !sourceMime.startsWith(\"image/\")) {\n // Silent: callers can set `compress: true` for batched mixed\n // media and not have to special-case images vs videos.\n }\n bytes =\n input instanceof Uint8Array\n ? input\n : new Uint8Array(await input.arrayBuffer());\n effectiveMime = sourceMime;\n }\n\n const sha = opts.sha256 ?? (await computeSha256(bytes));\n const mime = effectiveMime;\n const fileName =\n opts.fileName ??\n (input instanceof File ? input.name : `upload-${sha.slice(0, 8)}.bin`);\n\n // Dedup probe.\n const existing = await this.assets.byHash(sha);\n if (existing && existing.status === \"ready\") {\n return {\n assetId: existing.id,\n sha256: sha,\n cdnUrl: this.urlFor(existing, this.bestPresetForAsset(existing, mime)),\n };\n }\n\n // Presign + PUT + process. Delegates to `assets.presignUploadUrl()` so\n // the public method and `aq.upload()` share one code path; always\n // threads an explicit preset list so the default matches the SDK\n // contract (`[\"original\"]`) instead of inheriting the server's older\n // default (`thumb+sm+md+lg`).\n const presign = await this.assets.presignUploadUrl({\n sha256: sha,\n mime,\n bytes: bytes.byteLength,\n fileName,\n presets:\n opts.presets && opts.presets.length > 0\n ? opts.presets\n : DEFAULT_UPLOAD_PRESETS,\n ...(clientOriginalBytes != null && { clientOriginalBytes }),\n ...(opts.video != null && { video: opts.video }),\n });\n if (presign.deduped) {\n return {\n assetId: presign.asset.id,\n sha256: sha,\n cdnUrl: this.urlFor(presign.asset, this.defaultPresetForMime(mime)),\n };\n }\n\n const putR = await fetch(presign.upload.url, {\n method: \"PUT\",\n headers: { \"Content-Type\": mime, ...(presign.upload.headers ?? {}) },\n body: new Blob([bytes as unknown as ArrayBuffer], { type: mime }),\n });\n if (!putR.ok)\n throw new Error(`Storage PUT ${putR.status}: ${await putR.text()}`);\n\n const procR = await fetch(endpointHref(this.opts, presign.process.url), {\n method: \"POST\",\n headers: {\n ...authHeaders(this.opts),\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify(presign.process.body),\n });\n if (!procR.ok)\n throw new Error(`process ${procR.status}: ${await procR.text()}`);\n const proc = (await procR.json()) as { assetId?: string; kind?: string };\n\n let assetId = proc.assetId;\n if (!assetId && proc.kind === \"video\") {\n // Videos are async — poll by-hash until the row lands.\n const start = Date.now();\n let delay = 1000;\n while (Date.now() - start < 60_000) {\n const dto = await this.assets.byHash(sha);\n if (dto?.id) {\n assetId = dto.id;\n break;\n }\n await new Promise((r) => setTimeout(r, delay));\n delay = Math.min(delay * 1.5, 5_000);\n }\n }\n if (!assetId) throw new Error(\"upload: process returned no assetId\");\n\n // Wait until variants are ready so the URL works immediately.\n // Passing `undefined` keeps waitReady's own default (5 min). Callers\n // uploading large videos can opt in to a longer deadline via opts.timeoutMs.\n const final = await this.assets.waitReady(assetId, opts.timeoutMs);\n if (final.status !== \"ready\")\n throw new Error(`upload: asset ended status=${final.status}`);\n return {\n assetId,\n sha256: sha,\n cdnUrl: this.urlFor(final, this.bestPresetForAsset(final, mime)),\n };\n }\n\n private defaultPresetForMime(mime: string): VariantPreset {\n if (mime.startsWith(\"video/\")) return \"video\";\n // The `mp3` variant only exists AFTER /process transcodes it; at presign\n // time only the original is guaranteed to be playable, so bind to it.\n if (mime.startsWith(\"audio/\")) return \"original\";\n return \"lg\";\n }\n\n /**\n * Pick a sensible preset to build a URL for, given the asset's actual\n * `presets` string. Falls back through the preference order\n * lg → md → sm → thumb → original (for images)\n * video → poster (for videos)\n * mp3 → original (for audio)\n * so an upload that was processed with e.g. `[\"original\"]` still\n * returns a non-404 URL in `aq.upload`'s result.\n */\n private bestPresetForAsset(asset: AssetDTO, mime: string): VariantPreset {\n const order: VariantPreset[] = mime.startsWith(\"video/\")\n ? [\"video\", \"poster\"]\n : mime.startsWith(\"audio/\")\n ? [\"mp3\", \"original\"] // prefer the cross-browser mp3, else the playable original; never image presets\n : [\"lg\", \"md\", \"sm\", \"thumb\", \"xl\", \"original\"];\n return (\n order.find((p) => hasPreset(asset, p)) ?? this.defaultPresetForMime(mime)\n );\n }\n}\n"],"mappings":";AAqCA;AAAA,EAGE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EAEA;AAAA,EACA;AAAA,EAIA;AAAA,EACA;A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UAAM,QAAQ,MAAM,KAAK,OAAO,UAAU,SAAS,KAAK,SAAS;AACjE,QAAI,MAAM,WAAW;AACnB,YAAM,IAAI,MAAM,8BAA8B,MAAM,MAAM,EAAE;AAC9D,WAAO;AAAA,MACL;AAAA,MACA,QAAQ;AAAA,MACR,QAAQ,KAAK,OAAO,OAAO,KAAK,mBAAmB,OAAO,IAAI,CAAC;AAAA,IACjE;AAAA,EACF;AAAA,EAEQ,qBAAqB,MAA6B;AACxD,QAAI,KAAK,WAAW,QAAQ,EAAG,QAAO;AAGtC,QAAI,KAAK,WAAW,QAAQ,EAAG,QAAO;AACtC,WAAO;AAAA,EACT;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAWQ,mBAAmB,OAAiB,MAA6B;AACvE,UAAM,QAAyB,KAAK,WAAW,QAAQ,IACnD,CAAC,SAAS,QAAQ,IAClB,KAAK,WAAW,QAAQ,IACtB,CAAC,OAAO,UAAU,IAClB,CAAC,MAAM,MAAM,MAAM,SAAS,MAAM,UAAU;AAClD,WACE,MAAM,KAAK,CAAC,MAAM,UAAU,OAAO,CAAC,CAAC,KAAK,KAAK,qBAAqB,IAAI;AAAA,EAE5E;AACF;","names":["getAssetSrcSet","getAssetUrl","getHlsStreamingUrl","getSignedTransformUrl","getTransformSrcSet","getTransformUrl","getVideoTransformUrl","hasPreset","setTenantId"]}
package/dist/server.js CHANGED
@@ -223,7 +223,7 @@ var AssetsApi = class {
223
223
  * const v = await aq.assets.variants(logoId);
224
224
  * v.map((x) => x.preset); // → ("thumb" | "sm" | … | "original")[]
225
225
  *
226
- * ⚠️ Returns `[]` — not an error — against an `asset-manager` older than the
226
+ * ⚠️ Returns `[]` — not an error — against a server deploy older than the
227
227
  * 2026-08-17 deploy, which never sent the field (doc 240 §4.3). An empty
228
228
  * array is therefore "no variants OR old server". For a plain existence
229
229
  * check prefer `hasPreset(dto, preset)` on `dto.presets`, which every server
@@ -255,7 +255,7 @@ var AssetsApi = class {
255
255
  * bytes from `variants/o.<ext>` — no need to re-upload.
256
256
  *
257
257
  * Video presets are filtered to `["poster","video","aiproxy"]` and
258
- * dispatched to the Cloud Run Job (the call returns immediately
258
+ * dispatched to the background job (the call returns immediately
259
259
  * with a dispatch handle; poll `aq.assets.get(id).status` for
260
260
  * completion).
261
261
  */
@@ -283,13 +283,13 @@ var AssetsApi = class {
283
283
  return await r.json();
284
284
  }
285
285
  /**
286
- * Request a presigned R2 PUT URL for direct browser-side uploads.
286
+ * Request a presigned storage PUT URL for direct browser-side uploads.
287
287
  *
288
288
  * Mirrors the first half of `aq.upload()` — the caller (typically a
289
289
  * BFF / share-link dropzone) computes sha256 in the browser, then
290
- * uploads bytes straight to R2 with the returned `upload.url`, then
291
- * POSTs `process.body` to `/assets/process` (see {@link processAndWait})
292
- * once R2 has the bytes.
290
+ * uploads bytes straight to object storage with the returned `upload.url`,
291
+ * then POSTs `process.body` to `/assets/process` (see {@link processAndWait})
292
+ * once storage has the bytes.
293
293
  *
294
294
  * If the sha is already known to the tenant the server short-circuits
295
295
  * with `{ deduped: true, asset }` — no PUT needed.
@@ -301,16 +301,16 @@ var AssetsApi = class {
301
301
  * if (presign.deduped) return presign.asset; // those bytes already exist; none fly
302
302
  *
303
303
  * // BROWSER: PUT straight to presign.upload.url — the bytes never touch your server.
304
- * // ⚠️ R2 answers that preflight ITSELF, so your origin must be in the BUCKET's CORS policy.
305
- * // Symptom when it is not: "PUT failed: network error" with every earlier step green —
306
- * // and it cannot be fixed in this SDK, in your app, or in `storefront_origins`.
304
+ * // ⚠️ The STORAGE BUCKET answers that preflight itself, so your origin must be in its CORS
305
+ * // policy. Symptom when it is not: "PUT failed: network error" with every earlier step
306
+ * // green — and it cannot be fixed in this SDK, in your app, or by the API's allowed origins.
307
307
  *
308
308
  * // SERVER again, forwarding presign.process.body VERBATIM:
309
309
  * const asset = await aq.assets.processAndWait(presign.process.body, { timeoutMs: 300_000 });
310
310
  * ```
311
311
  *
312
312
  * Works for images AND video. A video answers immediately with
313
- * `{ assetId, status: "processing" }` while a Cloud Run Job transcodes, so
313
+ * `{ assetId, status: "processing" }` while a background job transcodes, so
314
314
  * give `processAndWait` a bigger `timeoutMs` (a transcode + HLS ladder runs
315
315
  * 1–2 min; 300_000 is a sane floor).
316
316
  */
@@ -338,7 +338,7 @@ var AssetsApi = class {
338
338
  * {@link presignUploadUrl} call, then poll until the asset transitions
339
339
  * to `ready` or `failed`. Throws on `failed` or timeout.
340
340
  *
341
- * Use this when bytes were uploaded directly from the browser to R2
341
+ * Use this when bytes were uploaded directly from the browser to storage
342
342
  * `aq.upload()` already does presign + PUT + process + wait in one
343
343
  * step when the server holds the bytes.
344
344
  */
@@ -387,7 +387,7 @@ var AssetsApi = class {
387
387
  * {@link waitReady} (typical timeout: 10 min for multi-segment kits).
388
388
  *
389
389
  * Tenant scope is inherited from the SDK client; `tenantCode` is added
390
- * to the request body so the Cloud Run Job can resolve it without
390
+ * to the request body so the background job can resolve it without
391
391
  * re-reading the header.
392
392
  */
393
393
  async composeMarketing(opts) {
@@ -553,8 +553,8 @@ var NitidaClient = class {
553
553
  * Build an on-the-fly VIDEO transform URL — Phase 4.
554
554
  *
555
555
  * Same DSL shape as `transform()` but the URL has a `.mp4` (default)
556
- * or `.webm` extension and the server routes the request to a Cloud
557
- * Run Job for ffmpeg encoding (vs the inline sharp pipeline for
556
+ * or `.webm` extension and the server routes the request to a
557
+ * background job for video encoding (vs the inline pipeline for
558
558
  * images).
559
559
  *
560
560
  * On the first request the route returns **202 Accepted** with
@@ -596,7 +596,7 @@ var NitidaClient = class {
596
596
  * />
597
597
  *
598
598
  * On the first request the server returns **202 Accepted** while a
599
- * Cloud Run Job builds the multi-rung ladder (typically 1-3 min for
599
+ * background job builds the multi-rung ladder (typically 1-3 min for
600
600
  * a 90 s source — five rungs of 240p/360p/480p/720p/1080p @ AAC).
601
601
  * Subsequent requests hit the cache → **302** to the master.m3u8.
602
602
  *
@@ -617,7 +617,7 @@ var NitidaClient = class {
617
617
  * but isn't always available depending on the runtime).
618
618
  */
619
619
  /**
620
- * Upload bytes end to end: optional client compression → sha256 → presign → **direct-to-R2 PUT**
620
+ * Upload bytes end to end: optional client compression → sha256 → presign → **direct-to-storage PUT**
621
621
  * → `/assets/process` → wait until the asset is ready.
622
622
  *
623
623
  * ⚠️ `presets` decides what exists FOREVER. Omit it and only `original` is written; ask for
@@ -657,8 +657,8 @@ var NitidaClient = class {
657
657
  * // {poster, video, aiproxy, probe} before dispatching the transcode Job.
658
658
  * await aq.upload(clip, { fileName: "tour.mp4", presets: ["poster", "video"] });
659
659
  *
660
- * // Omit `aiproxy`/`probe` unless the asset really goes to a vision model — they cost Job time
661
- * // and permanent R2 objects that nothing else reads.
660
+ * // Omit `aiproxy`/`probe` unless the asset really goes to a vision model — they cost encode
661
+ * // time and permanent stored objects that nothing else reads.
662
662
  * ```
663
663
  */
664
664
  async upload(input, opts = {}) {
@@ -731,7 +731,7 @@ var NitidaClient = class {
731
731
  body: new Blob([bytes], { type: mime })
732
732
  });
733
733
  if (!putR.ok)
734
- throw new Error(`R2 PUT ${putR.status}: ${await putR.text()}`);
734
+ throw new Error(`Storage PUT ${putR.status}: ${await putR.text()}`);
735
735
  const procR = await fetch(endpointHref(this.opts, presign.process.url), {
736
736
  method: "POST",
737
737
  headers: {