@kvidai/sdk 0.0.0-stage → 0.2.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/esm/index.js +672 -0
- package/dist/esm/package.json +1 -0
- package/dist/index.d.ts +428 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +677 -0
- package/package.json +43 -4
- package/README.md +0 -3
|
@@ -0,0 +1,672 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @kvidai/sdk — kvidai TypeScript SDK
|
|
3
|
+
*
|
|
4
|
+
* Covers the 4 core external-client flows documented in docs/external-client-guide.md:
|
|
5
|
+
* 1. Auth — login + API key management (console.kvid.ai / Strapi JWT)
|
|
6
|
+
* 2. Generation — AI video/image/voice creation + status polling + result fetch (api.kvid.ai / APIM)
|
|
7
|
+
* 3. Media — presigned upload → CDN URL (api.kvid.ai / APIM)
|
|
8
|
+
* 4. Preset — CRUD (api.kvid.ai / APIM)
|
|
9
|
+
*
|
|
10
|
+
* Usage:
|
|
11
|
+
* const client = new KvidaiClient({ jwt: '<strapi-jwt>', apiKey: '<apim-32hex>' });
|
|
12
|
+
* const { requestId, model } = await client.generation.textToVideo({ prompt: '...', model: 'wan' });
|
|
13
|
+
* const result = await client.generation.waitForResult({ requestId, model });
|
|
14
|
+
*
|
|
15
|
+
* Canonical sources: docs/external-client-api-reference.md, docs/external-client-guide.md
|
|
16
|
+
*/
|
|
17
|
+
const ENV_URLS = {
|
|
18
|
+
prod: {
|
|
19
|
+
strapiBaseUrl: 'https://console.kvid.ai',
|
|
20
|
+
apimBaseUrl: 'https://api.kvid.ai',
|
|
21
|
+
webBaseUrl: 'https://kvid.ai',
|
|
22
|
+
generationPath: '/ai/generation',
|
|
23
|
+
mediaPath: '/media',
|
|
24
|
+
presetPath: '/preset',
|
|
25
|
+
agentPath: '/agent',
|
|
26
|
+
videoProjectPath: '/video-project',
|
|
27
|
+
},
|
|
28
|
+
staging: {
|
|
29
|
+
strapiBaseUrl: 'https://hometips-strapi-ts-staging1-405573518541.asia-northeast1.run.app',
|
|
30
|
+
apimBaseUrl: 'https://api.kvid.ai',
|
|
31
|
+
webBaseUrl: 'https://staging1.kvid.ai',
|
|
32
|
+
generationPath: '/ai/generation',
|
|
33
|
+
mediaPath: '/media',
|
|
34
|
+
presetPath: '/preset',
|
|
35
|
+
agentPath: '/agent',
|
|
36
|
+
videoProjectPath: '/video-project',
|
|
37
|
+
},
|
|
38
|
+
dev: {
|
|
39
|
+
strapiBaseUrl: 'http://localhost:1337',
|
|
40
|
+
apimBaseUrl: 'https://api.kvid.ai',
|
|
41
|
+
webBaseUrl: 'http://localhost:3000',
|
|
42
|
+
generationPath: '/ai/generation-clone',
|
|
43
|
+
mediaPath: '/media-dev',
|
|
44
|
+
presetPath: '/preset-dev',
|
|
45
|
+
// Agent + video-project use the same gateway paths across all envs (confirmed live 2026-10-30).
|
|
46
|
+
// No dev-clone equivalent exists for these endpoints.
|
|
47
|
+
agentPath: '/agent',
|
|
48
|
+
videoProjectPath: '/video-project',
|
|
49
|
+
},
|
|
50
|
+
};
|
|
51
|
+
export class KvidaiError extends Error {
|
|
52
|
+
constructor(code, message, status, details) {
|
|
53
|
+
super(message);
|
|
54
|
+
this.code = code;
|
|
55
|
+
this.status = status;
|
|
56
|
+
this.details = details;
|
|
57
|
+
this.name = 'KvidaiError';
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
// ─────────────────────────────────────────────────────────────────────────────
|
|
61
|
+
// Transport
|
|
62
|
+
// ─────────────────────────────────────────────────────────────────────────────
|
|
63
|
+
class Transport {
|
|
64
|
+
constructor(options, urls) {
|
|
65
|
+
this.options = options;
|
|
66
|
+
this.urls = urls;
|
|
67
|
+
}
|
|
68
|
+
buildHeaders(type) {
|
|
69
|
+
const headers = { 'Content-Type': 'application/json' };
|
|
70
|
+
if (type === 'strapi' && this.options.jwt) {
|
|
71
|
+
headers['Authorization'] = `Bearer ${this.options.jwt}`;
|
|
72
|
+
}
|
|
73
|
+
if (type === 'apim' && this.options.apiKey) {
|
|
74
|
+
headers['api-key'] = this.options.apiKey;
|
|
75
|
+
}
|
|
76
|
+
return headers;
|
|
77
|
+
}
|
|
78
|
+
async request(base, path, init = {}) {
|
|
79
|
+
const baseUrl = base === 'strapi'
|
|
80
|
+
? this.urls.strapiBaseUrl
|
|
81
|
+
: base === 'web'
|
|
82
|
+
? this.urls.webBaseUrl
|
|
83
|
+
: this.urls.apimBaseUrl;
|
|
84
|
+
const authType = base === 'strapi' ? 'strapi' : 'apim';
|
|
85
|
+
let res;
|
|
86
|
+
try {
|
|
87
|
+
res = await fetch(`${baseUrl}${path}`, {
|
|
88
|
+
...init,
|
|
89
|
+
headers: {
|
|
90
|
+
...this.buildHeaders(authType),
|
|
91
|
+
...init.headers,
|
|
92
|
+
},
|
|
93
|
+
signal: AbortSignal.timeout(this.options.timeoutMs ?? 30000),
|
|
94
|
+
});
|
|
95
|
+
}
|
|
96
|
+
catch (err) {
|
|
97
|
+
if (err instanceof Error && (err.name === 'TimeoutError' || err.name === 'AbortError')) {
|
|
98
|
+
throw new KvidaiError('TIMEOUT', `kvidai API did not respond within ${this.options.timeoutMs ?? 30000}ms`, 0);
|
|
99
|
+
}
|
|
100
|
+
throw err;
|
|
101
|
+
}
|
|
102
|
+
if (!res.ok) {
|
|
103
|
+
const body = await res.json().catch(() => ({ error: res.statusText }));
|
|
104
|
+
const msg = body?.error?.message ?? body?.message ?? body?.error ?? `HTTP ${res.status}`;
|
|
105
|
+
const code = body?.error?.name ?? body?.code ?? 'API_ERROR';
|
|
106
|
+
throw new KvidaiError(code, msg, res.status, body);
|
|
107
|
+
}
|
|
108
|
+
if (res.status === 204)
|
|
109
|
+
return undefined;
|
|
110
|
+
const text = await res.text();
|
|
111
|
+
return (text ? JSON.parse(text) : undefined);
|
|
112
|
+
}
|
|
113
|
+
/**
|
|
114
|
+
* Like request() but returns the raw text body — for SSE streams.
|
|
115
|
+
* No automatic timeout is applied since SSE streams are long-running.
|
|
116
|
+
*/
|
|
117
|
+
async requestText(base, path, init = {}) {
|
|
118
|
+
const baseUrl = base === 'strapi'
|
|
119
|
+
? this.urls.strapiBaseUrl
|
|
120
|
+
: base === 'web'
|
|
121
|
+
? this.urls.webBaseUrl
|
|
122
|
+
: this.urls.apimBaseUrl;
|
|
123
|
+
const authType = base === 'strapi' ? 'strapi' : 'apim';
|
|
124
|
+
let res;
|
|
125
|
+
try {
|
|
126
|
+
res = await fetch(`${baseUrl}${path}`, {
|
|
127
|
+
...init,
|
|
128
|
+
headers: {
|
|
129
|
+
...this.buildHeaders(authType),
|
|
130
|
+
...init.headers,
|
|
131
|
+
},
|
|
132
|
+
// No automatic timeout — SSE streams can run for minutes
|
|
133
|
+
});
|
|
134
|
+
}
|
|
135
|
+
catch (err) {
|
|
136
|
+
throw err;
|
|
137
|
+
}
|
|
138
|
+
if (!res.ok) {
|
|
139
|
+
const body = await res.json().catch(() => ({ error: res.statusText }));
|
|
140
|
+
const msg = body?.error?.message ?? body?.message ?? body?.error ?? `HTTP ${res.status}`;
|
|
141
|
+
const code = body?.error?.name ?? body?.code ?? 'API_ERROR';
|
|
142
|
+
throw new KvidaiError(code, msg, res.status, body);
|
|
143
|
+
}
|
|
144
|
+
return res.text();
|
|
145
|
+
}
|
|
146
|
+
/** Strapi JSON API envelope unwrap: `{ data: ... }` */
|
|
147
|
+
async strapiGet(path) {
|
|
148
|
+
const res = await this.request('strapi', path);
|
|
149
|
+
return res.data ?? res;
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
// ─────────────────────────────────────────────────────────────────────────────
|
|
153
|
+
// Auth module
|
|
154
|
+
// ─────────────────────────────────────────────────────────────────────────────
|
|
155
|
+
class AuthModule {
|
|
156
|
+
constructor(t, o) {
|
|
157
|
+
this.t = t;
|
|
158
|
+
this.o = o;
|
|
159
|
+
}
|
|
160
|
+
/** POST /api/auth/local — returns JWT + user. Store the jwt and pass to KvidaiClient. */
|
|
161
|
+
async login(params) {
|
|
162
|
+
return this.t.request('strapi', '/api/auth/local', {
|
|
163
|
+
method: 'POST',
|
|
164
|
+
body: JSON.stringify(params),
|
|
165
|
+
});
|
|
166
|
+
}
|
|
167
|
+
/** GET /api/users/me — verify JWT and fetch user profile. */
|
|
168
|
+
async me() {
|
|
169
|
+
return this.t.request('strapi', '/api/users/me');
|
|
170
|
+
}
|
|
171
|
+
/** GET /api/apim-management/my-keys — list active keys (masked). */
|
|
172
|
+
async listKeys() {
|
|
173
|
+
const res = await this.t.request('strapi', '/api/apim-management/my-keys');
|
|
174
|
+
return Array.isArray(res) ? res : (res.data ?? []);
|
|
175
|
+
}
|
|
176
|
+
/** GET /api/apim-management/key-detail/:subscriptionId — full 32-hex key. */
|
|
177
|
+
async keyDetail(subscriptionId) {
|
|
178
|
+
const res = await this.t.request('strapi', `/api/apim-management/key-detail/${subscriptionId}`);
|
|
179
|
+
// Controller wraps in { data: ... }
|
|
180
|
+
return res.data ?? res;
|
|
181
|
+
}
|
|
182
|
+
/** GET /api/apim-management/products — available APIM products. */
|
|
183
|
+
async products() {
|
|
184
|
+
const res = await this.t.request('strapi', '/api/apim-management/products');
|
|
185
|
+
const data = res.data ?? res;
|
|
186
|
+
return data.products ?? [];
|
|
187
|
+
}
|
|
188
|
+
/**
|
|
189
|
+
* POST /api/apim-management/generate-key — issue a new APIM key.
|
|
190
|
+
* ⚠️ primaryKey is shown only in this response — store it immediately.
|
|
191
|
+
*/
|
|
192
|
+
async generateKey(params) {
|
|
193
|
+
return this.t.request('strapi', '/api/apim-management/generate-key', {
|
|
194
|
+
method: 'POST',
|
|
195
|
+
body: JSON.stringify(params),
|
|
196
|
+
});
|
|
197
|
+
}
|
|
198
|
+
/**
|
|
199
|
+
* POST /api/apim-management/regenerate-key — rotate key; old key is immediately invalidated.
|
|
200
|
+
* ⚠️ primaryKey shown only once.
|
|
201
|
+
*/
|
|
202
|
+
async regenerateKey(params) {
|
|
203
|
+
return this.t.request('strapi', '/api/apim-management/regenerate-key', {
|
|
204
|
+
method: 'POST',
|
|
205
|
+
body: JSON.stringify(params),
|
|
206
|
+
});
|
|
207
|
+
}
|
|
208
|
+
/** DELETE /api/apim-management/subscription/:subscriptionId — revoke a key. */
|
|
209
|
+
async revokeKey(subscriptionId) {
|
|
210
|
+
return this.t.request('strapi', `/api/apim-management/subscription/${subscriptionId}`, {
|
|
211
|
+
method: 'DELETE',
|
|
212
|
+
});
|
|
213
|
+
}
|
|
214
|
+
/** GET /api/credit-management/summary/:email — credit balance. */
|
|
215
|
+
async creditSummary(email) {
|
|
216
|
+
const res = await this.t.request('strapi', `/api/credit-management/summary/${encodeURIComponent(email)}`);
|
|
217
|
+
// Controller returns { success: true, data: { totalCredit, totalUsed, ... } }
|
|
218
|
+
const raw = res.data ??
|
|
219
|
+
res;
|
|
220
|
+
const totalCredit = raw.totalCredit ?? raw.totalCredits ?? 0;
|
|
221
|
+
const totalUsed = raw.totalUsed ?? raw.usedCredits ?? 0;
|
|
222
|
+
return { totalCredit, totalUsed, remaining: totalCredit - totalUsed };
|
|
223
|
+
}
|
|
224
|
+
/**
|
|
225
|
+
* Convenience: login → fetch or generate key → return both.
|
|
226
|
+
* Implements the full ① Login→API key flow from docs/external-client-guide.md.
|
|
227
|
+
*/
|
|
228
|
+
async loginAndGetApiKey(identifier, password) {
|
|
229
|
+
const { jwt, user } = await this.login({ identifier, password });
|
|
230
|
+
// Update transport JWT
|
|
231
|
+
this.o.jwt = jwt;
|
|
232
|
+
const keys = await this.listKeys();
|
|
233
|
+
const active = keys.find((k) => k.state === 'active');
|
|
234
|
+
if (active) {
|
|
235
|
+
const detail = await this.keyDetail(active.subscriptionId);
|
|
236
|
+
return { jwt, apiKey: detail.primaryKey, user };
|
|
237
|
+
}
|
|
238
|
+
// No key — generate one
|
|
239
|
+
const products = await this.products();
|
|
240
|
+
if (!products.length)
|
|
241
|
+
throw new KvidaiError('NO_PRODUCT', 'No APIM products available', 404);
|
|
242
|
+
const { primaryKey } = await this.generateKey({ email: user.email, productId: products[0].id });
|
|
243
|
+
return { jwt, apiKey: primaryKey, user };
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
// ─────────────────────────────────────────────────────────────────────────────
|
|
247
|
+
// Generation module
|
|
248
|
+
// ─────────────────────────────────────────────────────────────────────────────
|
|
249
|
+
/** Polling constants (source: apps/web-service/src/lib/services/unified-polling.service.ts) */
|
|
250
|
+
const POLL_INTERVAL_MS = 3000;
|
|
251
|
+
const POLL_MAX_ATTEMPTS = 200;
|
|
252
|
+
const POLL_MAX_TRANSIENT_ERRORS = 5;
|
|
253
|
+
const RESULT_TIMEOUT_MS = 90000; // 90s — fal→CDN upload wait
|
|
254
|
+
class GenerationModule {
|
|
255
|
+
constructor(t, urls) {
|
|
256
|
+
this.t = t;
|
|
257
|
+
this.urls = urls;
|
|
258
|
+
}
|
|
259
|
+
async createJob(endpoint, params) {
|
|
260
|
+
const path = `${this.urls.generationPath}/${endpoint}/generate-async`;
|
|
261
|
+
const res = await this.t.request('apim', path, {
|
|
262
|
+
method: 'POST',
|
|
263
|
+
body: JSON.stringify(params),
|
|
264
|
+
});
|
|
265
|
+
// Actual APIM response: { success: true, data: { job_id, model, ... } }
|
|
266
|
+
// Some endpoints use request_id, others use job_id — accept both
|
|
267
|
+
const data = res
|
|
268
|
+
.data ?? res;
|
|
269
|
+
const requestId = data.request_id ?? data.job_id ?? '';
|
|
270
|
+
return {
|
|
271
|
+
requestId,
|
|
272
|
+
model: data.model ?? params.model,
|
|
273
|
+
jobId: data.job_id,
|
|
274
|
+
};
|
|
275
|
+
}
|
|
276
|
+
textToVideo(params) {
|
|
277
|
+
return this.createJob('text-to-video', params);
|
|
278
|
+
}
|
|
279
|
+
imageToVideo(params) {
|
|
280
|
+
return this.createJob('image-to-video', params);
|
|
281
|
+
}
|
|
282
|
+
referenceToVideo(params) {
|
|
283
|
+
return this.createJob('reference-to-video', params);
|
|
284
|
+
}
|
|
285
|
+
videoToVideo(params) {
|
|
286
|
+
return this.createJob('video-to-video', params);
|
|
287
|
+
}
|
|
288
|
+
textToImage(params) {
|
|
289
|
+
return this.createJob('text-to-image', params);
|
|
290
|
+
}
|
|
291
|
+
imageToImage(params) {
|
|
292
|
+
return this.createJob('image-to-image', params);
|
|
293
|
+
}
|
|
294
|
+
talkV2V(params) {
|
|
295
|
+
return this.createJob('talk-v2v', params);
|
|
296
|
+
}
|
|
297
|
+
voice(params) {
|
|
298
|
+
return this.createJob('voice/text-to-speech', params);
|
|
299
|
+
}
|
|
300
|
+
/** GET /generation/status */
|
|
301
|
+
/** GET /generation/status?jobId=<id> */
|
|
302
|
+
async status(requestId, _model, email) {
|
|
303
|
+
// Actual endpoint uses `jobId` query param (not `request_id` or `model`)
|
|
304
|
+
const qs = new URLSearchParams({ jobId: requestId });
|
|
305
|
+
if (email)
|
|
306
|
+
qs.set('email', email);
|
|
307
|
+
// Real live API returns the {success,data} envelope: { data: { job_id, status, progress?, result_url? } }
|
|
308
|
+
// (result_url is present once status=completed). Accept a flat body too for robustness (same as createJob).
|
|
309
|
+
const res = await this.t.request('apim', `${this.urls.generationPath}/status?${qs}`);
|
|
310
|
+
const d = res.data ??
|
|
311
|
+
res;
|
|
312
|
+
return {
|
|
313
|
+
requestId: d.job_id ?? requestId,
|
|
314
|
+
model: _model ?? '',
|
|
315
|
+
status: (d.status ?? 'queued'),
|
|
316
|
+
progress: d.progress,
|
|
317
|
+
resultUrl: d.result_url, // populated when status=completed
|
|
318
|
+
};
|
|
319
|
+
}
|
|
320
|
+
/** GET /generation/result?jobId=<id> (90s timeout for fal→CDN upload) */
|
|
321
|
+
async result(requestId, _model, email) {
|
|
322
|
+
const qs = new URLSearchParams({ jobId: requestId });
|
|
323
|
+
if (email)
|
|
324
|
+
qs.set('email', email);
|
|
325
|
+
// Real live API returns the {success,data} envelope; the result endpoint's url field is `video_url`
|
|
326
|
+
// (even for images). Accept result_url and a flat body too for robustness.
|
|
327
|
+
const res = await this.t.request('apim', `${this.urls.generationPath}/result?${qs}`, {
|
|
328
|
+
signal: AbortSignal.timeout(RESULT_TIMEOUT_MS),
|
|
329
|
+
});
|
|
330
|
+
const d = res.data ??
|
|
331
|
+
res;
|
|
332
|
+
return {
|
|
333
|
+
requestId: d.job_id ?? requestId,
|
|
334
|
+
model: _model ?? '',
|
|
335
|
+
url: d.video_url ?? d.result_url ?? '',
|
|
336
|
+
};
|
|
337
|
+
}
|
|
338
|
+
/**
|
|
339
|
+
* Polls status until terminal, then fetches result.
|
|
340
|
+
* Encapsulates the ② create→poll→result flow from docs/external-client-guide.md.
|
|
341
|
+
*
|
|
342
|
+
* - 3s interval, 200 attempts max (~10 min)
|
|
343
|
+
* - 5xx errors tolerated up to 5 consecutive times
|
|
344
|
+
* - result() uses a separate 90s timeout for fal→CDN upload
|
|
345
|
+
*/
|
|
346
|
+
async waitForResult(opts) {
|
|
347
|
+
const { requestId, model, email, pollIntervalMs = POLL_INTERVAL_MS, maxAttempts = POLL_MAX_ATTEMPTS, signal, } = opts;
|
|
348
|
+
let attempts = 0;
|
|
349
|
+
let consecutiveErrors = 0;
|
|
350
|
+
while (attempts < maxAttempts) {
|
|
351
|
+
if (signal?.aborted)
|
|
352
|
+
throw new KvidaiError('CANCELLED', 'waitForResult cancelled', 0);
|
|
353
|
+
await delay(pollIntervalMs, signal);
|
|
354
|
+
attempts++;
|
|
355
|
+
try {
|
|
356
|
+
const s = await this.status(requestId, model, email);
|
|
357
|
+
consecutiveErrors = 0;
|
|
358
|
+
if (s.status === 'completed') {
|
|
359
|
+
// result_url is often populated in the status response itself
|
|
360
|
+
const urlFromStatus = s.resultUrl;
|
|
361
|
+
if (urlFromStatus) {
|
|
362
|
+
return { requestId, model: model ?? '', url: urlFromStatus };
|
|
363
|
+
}
|
|
364
|
+
// fallback: call result() for cases where URL is only in the result endpoint
|
|
365
|
+
return this.result(requestId, model, email);
|
|
366
|
+
}
|
|
367
|
+
if (s.status === 'failed') {
|
|
368
|
+
throw new KvidaiError('GENERATION_FAILED', `Generation job failed (requestId=${requestId})`, 0);
|
|
369
|
+
}
|
|
370
|
+
if (s.status === 'cancelled') {
|
|
371
|
+
throw new KvidaiError('CANCELLED', `Generation job was cancelled (requestId=${requestId})`, 0);
|
|
372
|
+
}
|
|
373
|
+
// queued / processing — continue polling
|
|
374
|
+
}
|
|
375
|
+
catch (err) {
|
|
376
|
+
// Terminal KvidaiErrors (domain errors, not HTTP infra): bubble up immediately
|
|
377
|
+
if (err instanceof KvidaiError && err.status < 500)
|
|
378
|
+
throw err;
|
|
379
|
+
// Transient: 5xx KvidaiError or network/unknown — count consecutive occurrences
|
|
380
|
+
consecutiveErrors++;
|
|
381
|
+
if (consecutiveErrors >= POLL_MAX_TRANSIENT_ERRORS) {
|
|
382
|
+
throw new KvidaiError('POLL_ERROR', `Too many consecutive polling errors (requestId=${requestId})`, 0, err);
|
|
383
|
+
}
|
|
384
|
+
}
|
|
385
|
+
}
|
|
386
|
+
throw new KvidaiError('TIMEOUT', `waitForResult exceeded max attempts (${maxAttempts}) for requestId=${requestId}`, 0);
|
|
387
|
+
}
|
|
388
|
+
}
|
|
389
|
+
// ─────────────────────────────────────────────────────────────────────────────
|
|
390
|
+
// Media module
|
|
391
|
+
// ─────────────────────────────────────────────────────────────────────────────
|
|
392
|
+
/** Files ≥ this threshold go via browser→Spaces direct PUT (source: upload-media.ts) */
|
|
393
|
+
const LARGE_FILE_THRESHOLD_BYTES = 90 * 1024 * 1024;
|
|
394
|
+
class MediaModule {
|
|
395
|
+
constructor(t, urls) {
|
|
396
|
+
this.t = t;
|
|
397
|
+
this.urls = urls;
|
|
398
|
+
}
|
|
399
|
+
/** Presign a new upload slot. */
|
|
400
|
+
async presign(params) {
|
|
401
|
+
const res = await this.t.request('apim', `${this.urls.mediaPath}/presigned-upload-url`, {
|
|
402
|
+
method: 'POST',
|
|
403
|
+
body: JSON.stringify(params),
|
|
404
|
+
});
|
|
405
|
+
// Normalize: some responses return flat, some wrap in data
|
|
406
|
+
const flat = res;
|
|
407
|
+
const wrapped = res.data;
|
|
408
|
+
const uploadUrl = flat.uploadUrl ?? wrapped?.uploadUrl ?? '';
|
|
409
|
+
const cdnUrl = flat.cdnUrl ?? wrapped?.cdnUrl ?? '';
|
|
410
|
+
return {
|
|
411
|
+
uploadUrl,
|
|
412
|
+
cdnUrl,
|
|
413
|
+
key: flat.key ?? wrapped?.key,
|
|
414
|
+
expiresInSeconds: flat.expiresInSeconds,
|
|
415
|
+
};
|
|
416
|
+
}
|
|
417
|
+
/** Notify server that PUT to uploadUrl succeeded. */
|
|
418
|
+
async completeUpload(params) {
|
|
419
|
+
return this.t.request('apim', `${this.urls.mediaPath}/complete-upload`, {
|
|
420
|
+
method: 'POST',
|
|
421
|
+
body: JSON.stringify(params),
|
|
422
|
+
});
|
|
423
|
+
}
|
|
424
|
+
/**
|
|
425
|
+
* Full upload flow: presign → PUT → complete → cdnUrl.
|
|
426
|
+
* For files ≥ 90 MB the caller should use direct-to-Spaces PUT;
|
|
427
|
+
* this method does not handle large-file proxy routing.
|
|
428
|
+
*
|
|
429
|
+
* @param file File object (browser) or { name, type, size, stream: ReadableStream } (Node)
|
|
430
|
+
* @param email Owner email (required for server-side ownership check)
|
|
431
|
+
*/
|
|
432
|
+
async upload(file, email) {
|
|
433
|
+
if (file.size >= LARGE_FILE_THRESHOLD_BYTES) {
|
|
434
|
+
throw new KvidaiError('FILE_TOO_LARGE', `File exceeds ${LARGE_FILE_THRESHOLD_BYTES / 1024 / 1024}MB — use direct PUT for large files`, 413);
|
|
435
|
+
}
|
|
436
|
+
const filename = file.name.normalize('NFC'); // NFC normalization for S3 key (macOS NFD guard)
|
|
437
|
+
// APIM media endpoint uses `mimeType` (not `contentType`)
|
|
438
|
+
const { uploadUrl, cdnUrl, fileId } = await this.presign({
|
|
439
|
+
filename,
|
|
440
|
+
mimeType: file.type,
|
|
441
|
+
size: file.size,
|
|
442
|
+
email,
|
|
443
|
+
});
|
|
444
|
+
// PUT directly to object storage (public-read)
|
|
445
|
+
const buffer = await file.arrayBuffer();
|
|
446
|
+
const putRes = await fetch(uploadUrl, {
|
|
447
|
+
method: 'PUT',
|
|
448
|
+
headers: { 'Content-Type': file.type, 'x-amz-acl': 'public-read' },
|
|
449
|
+
body: buffer,
|
|
450
|
+
signal: AbortSignal.timeout(120000), // 2 min for large-ish files
|
|
451
|
+
});
|
|
452
|
+
if (!putRes.ok) {
|
|
453
|
+
throw new KvidaiError('UPLOAD_FAILED', `Object storage PUT failed: ${putRes.status}`, putRes.status);
|
|
454
|
+
}
|
|
455
|
+
if (fileId) {
|
|
456
|
+
await this.completeUpload({
|
|
457
|
+
fileId,
|
|
458
|
+
cdnUrl,
|
|
459
|
+
filename,
|
|
460
|
+
contentType: file.type,
|
|
461
|
+
size: file.size,
|
|
462
|
+
email,
|
|
463
|
+
});
|
|
464
|
+
}
|
|
465
|
+
return cdnUrl;
|
|
466
|
+
}
|
|
467
|
+
/** GET /media/files — list user media files. */
|
|
468
|
+
async list(email) {
|
|
469
|
+
const qs = email ? `?email=${encodeURIComponent(email)}` : '';
|
|
470
|
+
const res = await this.t.request('apim', `${this.urls.mediaPath}/files${qs}`);
|
|
471
|
+
return Array.isArray(res) ? res : (res.data ?? []);
|
|
472
|
+
}
|
|
473
|
+
/** DELETE /media/files/:id */
|
|
474
|
+
async delete(fileId) {
|
|
475
|
+
return this.t.request('apim', `${this.urls.mediaPath}/files/${fileId}`, { method: 'DELETE' });
|
|
476
|
+
}
|
|
477
|
+
}
|
|
478
|
+
// ─────────────────────────────────────────────────────────────────────────────
|
|
479
|
+
// Preset module
|
|
480
|
+
// ─────────────────────────────────────────────────────────────────────────────
|
|
481
|
+
class PresetModule {
|
|
482
|
+
constructor(t, urls) {
|
|
483
|
+
this.t = t;
|
|
484
|
+
this.urls = urls;
|
|
485
|
+
}
|
|
486
|
+
async list(email) {
|
|
487
|
+
const qs = email ? `?email=${encodeURIComponent(email)}` : '';
|
|
488
|
+
const res = await this.t.request('apim', `${this.urls.presetPath}${qs}`);
|
|
489
|
+
return Array.isArray(res) ? res : (res.data ?? []);
|
|
490
|
+
}
|
|
491
|
+
async get(id) {
|
|
492
|
+
return this.t.request('apim', `${this.urls.presetPath}/${id}`);
|
|
493
|
+
}
|
|
494
|
+
async create(params) {
|
|
495
|
+
return this.t.request('apim', this.urls.presetPath, {
|
|
496
|
+
method: 'POST',
|
|
497
|
+
body: JSON.stringify(params),
|
|
498
|
+
});
|
|
499
|
+
}
|
|
500
|
+
async update(id, params) {
|
|
501
|
+
return this.t.request('apim', `${this.urls.presetPath}/${id}`, {
|
|
502
|
+
method: 'PUT',
|
|
503
|
+
body: JSON.stringify(params),
|
|
504
|
+
});
|
|
505
|
+
}
|
|
506
|
+
async delete(id) {
|
|
507
|
+
return this.t.request('apim', `${this.urls.presetPath}/${id}`, { method: 'DELETE' });
|
|
508
|
+
}
|
|
509
|
+
async duplicate(id) {
|
|
510
|
+
return this.t.request('apim', `${this.urls.presetPath}/${id}/duplicate`, { method: 'POST' });
|
|
511
|
+
}
|
|
512
|
+
}
|
|
513
|
+
// ─────────────────────────────────────────────────────────────────────────────
|
|
514
|
+
// Agent helpers
|
|
515
|
+
// ─────────────────────────────────────────────────────────────────────────────
|
|
516
|
+
/** Extract a finished video URL from a raw project record. */
|
|
517
|
+
function extractRenderUrl(raw) {
|
|
518
|
+
for (const key of ['videoUrl', 'video_url', 'render_url', 'resultUrl', 'url']) {
|
|
519
|
+
const value = raw[key];
|
|
520
|
+
if (typeof value === 'string' && value.startsWith('https://'))
|
|
521
|
+
return value;
|
|
522
|
+
}
|
|
523
|
+
return null;
|
|
524
|
+
}
|
|
525
|
+
/**
|
|
526
|
+
* Parses a raw SSE stream text. Calls onEvent for each `event:`/`data:` pair.
|
|
527
|
+
* Returns all tool_start toolNames and the first error event payload.
|
|
528
|
+
* Mirrors apps/mobile-app/src/generation/agent-generate-client.ts parseSseEvents.
|
|
529
|
+
*/
|
|
530
|
+
function parseSseStream(text, onEvent) {
|
|
531
|
+
const tools = [];
|
|
532
|
+
let error = null;
|
|
533
|
+
let eventName = '';
|
|
534
|
+
for (const line of text.split('\n')) {
|
|
535
|
+
if (line.startsWith('event: ')) {
|
|
536
|
+
eventName = line.slice(7).trim();
|
|
537
|
+
continue;
|
|
538
|
+
}
|
|
539
|
+
if (line.startsWith('data: ')) {
|
|
540
|
+
let data = null;
|
|
541
|
+
try {
|
|
542
|
+
data = JSON.parse(line.slice(6));
|
|
543
|
+
}
|
|
544
|
+
catch {
|
|
545
|
+
continue; // non-JSON data line
|
|
546
|
+
}
|
|
547
|
+
if (onEvent)
|
|
548
|
+
onEvent({ event: eventName, data });
|
|
549
|
+
const toolName = data?.toolName;
|
|
550
|
+
if (eventName === 'tool_start' && typeof toolName === 'string')
|
|
551
|
+
tools.push(toolName);
|
|
552
|
+
if (eventName === 'error' && error === null)
|
|
553
|
+
error = data;
|
|
554
|
+
}
|
|
555
|
+
}
|
|
556
|
+
return { tools, error };
|
|
557
|
+
}
|
|
558
|
+
// ─────────────────────────────────────────────────────────────────────────────
|
|
559
|
+
// Agent module
|
|
560
|
+
// ─────────────────────────────────────────────────────────────────────────────
|
|
561
|
+
class AgentModule {
|
|
562
|
+
constructor(t, urls) {
|
|
563
|
+
this.t = t;
|
|
564
|
+
this.urls = urls;
|
|
565
|
+
}
|
|
566
|
+
/** Creates an empty project to generate into. POST /video-project/create (APIM api-key). */
|
|
567
|
+
async createProject(name) {
|
|
568
|
+
const res = await this.t.request('apim', `${this.urls.videoProjectPath}/create`, {
|
|
569
|
+
method: 'POST',
|
|
570
|
+
body: JSON.stringify({ name }),
|
|
571
|
+
});
|
|
572
|
+
const data = res.data ??
|
|
573
|
+
res;
|
|
574
|
+
const projectId = data.id ?? data.projectId;
|
|
575
|
+
if (typeof projectId !== 'number')
|
|
576
|
+
throw new KvidaiError('UNEXPECTED_RESPONSE', 'project create response has no id', 0);
|
|
577
|
+
return { projectId };
|
|
578
|
+
}
|
|
579
|
+
/**
|
|
580
|
+
* Runs one agent chat turn via SSE stream. POST /agent/generate (APIM api-key).
|
|
581
|
+
* RN-compatible: consumes full response with res.text() after stream closes.
|
|
582
|
+
* onEvent is called for each parsed SSE event as the stream is parsed.
|
|
583
|
+
*
|
|
584
|
+
* Note: the web /api/agent endpoint is origin-gated (not usable by external clients).
|
|
585
|
+
* This method uses the APIM api-key path that external clients can call.
|
|
586
|
+
*/
|
|
587
|
+
async generate(input, onEvent) {
|
|
588
|
+
const text = await this.t.requestText('apim', `${this.urls.agentPath}/generate`, {
|
|
589
|
+
method: 'POST',
|
|
590
|
+
headers: { Accept: 'text/event-stream', 'Content-Type': 'application/json' },
|
|
591
|
+
body: JSON.stringify({
|
|
592
|
+
projectId: input.projectId,
|
|
593
|
+
message: input.message,
|
|
594
|
+
chatHistory: input.chatHistory,
|
|
595
|
+
...(input.attachedFiles && input.attachedFiles.length > 0
|
|
596
|
+
? { attachedFiles: input.attachedFiles }
|
|
597
|
+
: {}),
|
|
598
|
+
}),
|
|
599
|
+
});
|
|
600
|
+
const { tools, error } = parseSseStream(text, onEvent);
|
|
601
|
+
if (error !== null)
|
|
602
|
+
throw new KvidaiError('AGENT_ERROR', 'the agent reported an error', 0, error);
|
|
603
|
+
return { tools };
|
|
604
|
+
}
|
|
605
|
+
/**
|
|
606
|
+
* Reads the result of an agent turn from the project. GET /video-project/:id (APIM api-key).
|
|
607
|
+
* Call after generate() completes — the composition is the agent's output.
|
|
608
|
+
*/
|
|
609
|
+
async getProjectResult(projectId) {
|
|
610
|
+
const res = await this.t.request('apim', `${this.urls.videoProjectPath}/${projectId}`);
|
|
611
|
+
const project = res.data ?? res;
|
|
612
|
+
const composition = project.composition;
|
|
613
|
+
const sceneCount = Object.keys(composition?.items ?? composition?.assets ?? {}).length;
|
|
614
|
+
return {
|
|
615
|
+
projectId,
|
|
616
|
+
renderUrl: extractRenderUrl(project),
|
|
617
|
+
sceneCount,
|
|
618
|
+
composition: project.composition ?? null,
|
|
619
|
+
};
|
|
620
|
+
}
|
|
621
|
+
}
|
|
622
|
+
// ─────────────────────────────────────────────────────────────────────────────
|
|
623
|
+
// KvidaiClient
|
|
624
|
+
// ─────────────────────────────────────────────────────────────────────────────
|
|
625
|
+
/**
|
|
626
|
+
* kvidai SDK client.
|
|
627
|
+
*
|
|
628
|
+
* @example
|
|
629
|
+
* // With existing credentials:
|
|
630
|
+
* const client = new KvidaiClient({ jwt: '<strapi-jwt>', apiKey: '<apim-32hex>' });
|
|
631
|
+
* const { requestId, model } = await client.generation.textToVideo({ prompt: 'Space', model: 'wan' });
|
|
632
|
+
* const result = await client.generation.waitForResult({ requestId, model });
|
|
633
|
+
*
|
|
634
|
+
* @example
|
|
635
|
+
* // Login flow (auto-obtains credentials):
|
|
636
|
+
* const client = new KvidaiClient({});
|
|
637
|
+
* const { jwt, apiKey } = await client.auth.loginAndGetApiKey('user@example.com', 'password');
|
|
638
|
+
* client.setCredentials({ jwt, apiKey });
|
|
639
|
+
*/
|
|
640
|
+
export class KvidaiClient {
|
|
641
|
+
constructor(options = {}) {
|
|
642
|
+
this.opts = { environment: 'prod', timeoutMs: 30000, ...options };
|
|
643
|
+
const urls = ENV_URLS[this.opts.environment ?? 'prod'];
|
|
644
|
+
this.transport = new Transport(this.opts, urls);
|
|
645
|
+
this.auth = new AuthModule(this.transport, this.opts);
|
|
646
|
+
this.generation = new GenerationModule(this.transport, urls);
|
|
647
|
+
this.media = new MediaModule(this.transport, urls);
|
|
648
|
+
this.preset = new PresetModule(this.transport, urls);
|
|
649
|
+
this.agent = new AgentModule(this.transport, urls);
|
|
650
|
+
}
|
|
651
|
+
/** Update JWT and/or apiKey after login. */
|
|
652
|
+
setCredentials(creds) {
|
|
653
|
+
if (creds.jwt !== undefined)
|
|
654
|
+
this.opts.jwt = creds.jwt;
|
|
655
|
+
if (creds.apiKey !== undefined)
|
|
656
|
+
this.opts.apiKey = creds.apiKey;
|
|
657
|
+
}
|
|
658
|
+
}
|
|
659
|
+
// ─────────────────────────────────────────────────────────────────────────────
|
|
660
|
+
// Utils
|
|
661
|
+
// ─────────────────────────────────────────────────────────────────────────────
|
|
662
|
+
function delay(ms, signal) {
|
|
663
|
+
return new Promise((resolve, reject) => {
|
|
664
|
+
if (signal?.aborted)
|
|
665
|
+
return reject(new KvidaiError('CANCELLED', 'Cancelled', 0));
|
|
666
|
+
const id = setTimeout(resolve, ms);
|
|
667
|
+
signal?.addEventListener('abort', () => {
|
|
668
|
+
clearTimeout(id);
|
|
669
|
+
reject(new KvidaiError('CANCELLED', 'Cancelled', 0));
|
|
670
|
+
}, { once: true });
|
|
671
|
+
});
|
|
672
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"type":"module"}
|