lazysusan 0.0.0-stage → 0.1.0

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 LazySusan
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,164 @@
1
- # Temporary Holding Version
1
+ # LazySusan SDK for JavaScript and TypeScript
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ The official SDK for the [LazySusan API](https://www.lazysusan.ai/developers): chat, image and video models from every major AI lab through one API key and one prepaid balance. Switch models by changing one string.
4
+
5
+ - Zero dependencies. Node 18+, Bun, Deno, edge runtimes.
6
+ - Typed end to end.
7
+ - Streaming, tool calling, images, async video, usage and cost on every response.
8
+
9
+ Full reference: https://www.lazysusan.ai/developers/docs
10
+
11
+ ## Install
12
+
13
+ ```bash
14
+ npm install https://www.lazysusan.ai/sdk/lazysusan-0.1.0.tgz
15
+ ```
16
+
17
+ Get an API key in the [developer console](https://www.lazysusan.ai/developers/console) and set it as an environment variable:
18
+
19
+ ```bash
20
+ export LAZYSUSAN_API_KEY=lsk_live_...
21
+ ```
22
+
23
+ Keep keys on the server. Never ship them in browser or mobile code.
24
+
25
+ ## Chat
26
+
27
+ ```ts
28
+ import LazySusan from 'lazysusan'
29
+
30
+ const ls = new LazySusan() // reads LAZYSUSAN_API_KEY
31
+
32
+ const reply = await ls.chat.create({
33
+ model: 'anthropic/claude-sonnet-5-5',
34
+ messages: [{ role: 'user', content: 'Summarise this in two lines: ...' }],
35
+ })
36
+
37
+ console.log(reply.text)
38
+ console.log(reply.usage) // { inputTokens, outputTokens, totalTokens, costCredits }
39
+ ```
40
+
41
+ ### Switch models
42
+
43
+ Every model takes the same request. Change the string and nothing else:
44
+
45
+ ```ts
46
+ for (const model of ['anthropic/claude-opus-5-5', 'deepseek/deepseek-v4-pro', 'google/gemini-3.8-flash', 'xai/grok-4.7']) {
47
+ const r = await ls.chat.create({ model, messages: [{ role: 'user', content: 'One-line tagline for a coffee shop.' }] })
48
+ console.log(model, r.text, r.usage.costCredits)
49
+ }
50
+ ```
51
+
52
+ `await ls.models.list({ type: 'chat' })` returns every model with its price.
53
+
54
+ ### Stream
55
+
56
+ ```ts
57
+ const stream = ls.chat.stream({
58
+ model: 'google/gemini-3.8-flash',
59
+ messages: [{ role: 'user', content: 'Write a haiku about deployments.' }],
60
+ })
61
+
62
+ for await (const event of stream) {
63
+ if (event.type === 'delta') process.stdout.write(event.text)
64
+ if (event.type === 'done') console.log('\ncredits:', event.usage?.costCredits)
65
+ }
66
+ ```
67
+
68
+ Or just `await stream.text()`. Call `stream.controller.abort()` to stop early.
69
+
70
+ ### Tools and JSON
71
+
72
+ ```ts
73
+ const r = await ls.chat.create({
74
+ model: 'anthropic/claude-sonnet-5-5',
75
+ messages: [{ role: 'user', content: 'Weather in Paris?' }],
76
+ tools: [{ type: 'function', function: { name: 'get_weather', parameters: { type: 'object', properties: { city: { type: 'string' } } } } }],
77
+ })
78
+ console.log(r.toolCalls)
79
+ ```
80
+
81
+ Pass `responseFormat: { type: 'json_object' }` for JSON output.
82
+
83
+ ## Images
84
+
85
+ ```ts
86
+ const img = await ls.images.generate({
87
+ model: 'google/nano-banana-2.1',
88
+ prompt: 'A product photo of a ceramic mug on oak, soft daylight',
89
+ size: '1024x1024',
90
+ })
91
+ console.log(img.images[0].url)
92
+ ```
93
+
94
+ ## Video
95
+
96
+ Videos run in the background. Start one, then wait for it:
97
+
98
+ ```ts
99
+ const job = await ls.videos.create({ model: 'google/veo-3.1-fast', prompt: 'Slow pan across a misty lake at dawn', seconds: 8 })
100
+ const video = await ls.videos.wait(job.id, { onProgress: (v) => console.log(v.status) })
101
+ console.log(video.videoUrl)
102
+ ```
103
+
104
+ Credits for a video are held when it starts and charged only if it succeeds. Failed videos are refunded.
105
+
106
+ ## Track usage by project
107
+
108
+ Tag any request with `metadata` (up to 16 string pairs). Filter and group by these tags, by key, by team member, by model and by environment in the console.
109
+
110
+ ```ts
111
+ await ls.chat.create({
112
+ model: 'anthropic/claude-haiku-5-5',
113
+ messages: [{ role: 'user', content: '...' }],
114
+ metadata: { project: 'support-bot', feature: 'triage', customer: 'acme' },
115
+ })
116
+ ```
117
+
118
+ Give each developer, service and environment its own key from the console for per-key budgets, model allowlists and expiry dates.
119
+
120
+ ## Errors
121
+
122
+ Every failure throws a `LazySusanError` with `status`, `type`, `code`, `param` and `requestId`:
123
+
124
+ ```ts
125
+ import LazySusan, { LazySusanError } from 'lazysusan'
126
+
127
+ try {
128
+ await ls.chat.create({ model: 'anthropic/claude-fable-5-1', messages })
129
+ } catch (e) {
130
+ if (LazySusanError.isInsufficientBalance(e)) {
131
+ // 402: the balance or a budget can't cover this request. Nothing was charged.
132
+ if (LazySusanError.isBudgetReached(e)) console.log('budget reached:', e.code)
133
+ } else if (LazySusanError.isPermission(e)) {
134
+ // 403: e.g. this key isn't allowed to use that model
135
+ } else if (LazySusanError.isRateLimit(e)) {
136
+ // 429 after automatic retries
137
+ }
138
+ console.error(e.requestId, e.message)
139
+ }
140
+ ```
141
+
142
+ The SDK retries automatically, with backoff, only where a retry can't cause a second charge:
143
+
144
+ - `429` and `503` responses. These are never charged.
145
+ - Network errors on `GET` requests.
146
+
147
+ Other failures on `POST` requests are never retried. Configure retries with `new LazySusan({ maxRetries: 2, timeoutMs: 300000 })`.
148
+
149
+ ## Balance
150
+
151
+ ```ts
152
+ const { balance } = await ls.credits.get() // credits; 1 credit = $0.001
153
+ ```
154
+
155
+ ## CommonJS
156
+
157
+ ```js
158
+ const LazySusan = require('lazysusan')
159
+ const ls = new LazySusan()
160
+ ```
161
+
162
+ ## License
163
+
164
+ MIT
@@ -0,0 +1,474 @@
1
+ "use strict";
2
+ /**
3
+ * LazySusan SDK — every leading AI model for chat, images and video through one API key.
4
+ * Docs: https://www.lazysusan.ai/developers/docs
5
+ *
6
+ * Zero dependencies. Runs on Node 18+, Deno, Bun, edge runtimes and modern browsers
7
+ * (anything with a global fetch). Never put an API key in code that ships to browsers.
8
+ */
9
+ Object.defineProperty(exports, "__esModule", { value: true });
10
+ exports.LazySusan = exports.LazySusanError = exports.DEFAULT_BASE_URL = exports.VERSION = void 0;
11
+ exports.VERSION = '0.1.0';
12
+ exports.DEFAULT_BASE_URL = 'https://www.lazysusan.ai/api/v1';
13
+ // ---------------------------------------------------------------------------------
14
+ // Errors
15
+ class LazySusanError extends Error {
16
+ constructor(message, opts = {}) {
17
+ super(message);
18
+ this.name = 'LazySusanError';
19
+ this.status = opts.status ?? 0;
20
+ this.type = opts.type ?? 'error';
21
+ this.code = opts.code ?? null;
22
+ this.param = opts.param ?? null;
23
+ this.requestId = opts.requestId ?? null;
24
+ }
25
+ /** The balance (or a monthly budget) can't cover the request. Nothing was charged. */
26
+ static isInsufficientBalance(e) {
27
+ return e instanceof LazySusanError && e.status === 402;
28
+ }
29
+ /** A key, team member or account budget was reached */
30
+ static isBudgetReached(e) {
31
+ return e instanceof LazySusanError && ['key_budget_reached', 'member_budget_reached', 'monthly_limit_reached'].includes(e.code ?? '');
32
+ }
33
+ static isAuthentication(e) {
34
+ return e instanceof LazySusanError && e.status === 401;
35
+ }
36
+ /** The key isn't allowed to do this (model allowlist, suspended member or account) */
37
+ static isPermission(e) {
38
+ return e instanceof LazySusanError && e.status === 403;
39
+ }
40
+ static isRateLimit(e) {
41
+ return e instanceof LazySusanError && e.status === 429;
42
+ }
43
+ static isInvalidRequest(e) {
44
+ return e instanceof LazySusanError && (e.status === 400 || e.status === 404 || e.status === 413);
45
+ }
46
+ static isTimeout(e) {
47
+ return e instanceof LazySusanError && e.code === 'timeout';
48
+ }
49
+ }
50
+ exports.LazySusanError = LazySusanError;
51
+ // ---------------------------------------------------------------------------------
52
+ // Helpers
53
+ const sleep = (ms, signal) => new Promise((resolve, reject) => {
54
+ if (signal?.aborted)
55
+ return reject(abortError());
56
+ const t = setTimeout(resolve, ms);
57
+ signal?.addEventListener('abort', () => {
58
+ clearTimeout(t);
59
+ reject(abortError());
60
+ }, { once: true });
61
+ });
62
+ const abortError = () => new LazySusanError('The request was aborted.', { code: 'aborted', type: 'aborted' });
63
+ /** Drop undefined values */
64
+ function clean(o) {
65
+ const out = {};
66
+ for (const [k, v] of Object.entries(o))
67
+ if (v !== undefined)
68
+ out[k] = v;
69
+ return out;
70
+ }
71
+ function toUsage(u) {
72
+ return {
73
+ inputTokens: u?.prompt_tokens ?? 0,
74
+ outputTokens: u?.completion_tokens ?? 0,
75
+ totalTokens: u?.total_tokens ?? (u?.prompt_tokens ?? 0) + (u?.completion_tokens ?? 0),
76
+ ...(u?.prompt_tokens_details?.cached_tokens ? { cachedTokens: u.prompt_tokens_details.cached_tokens } : {}),
77
+ costCredits: u?.cost_credits ?? 0,
78
+ };
79
+ }
80
+ function toVideo(v, requestId) {
81
+ return clean({
82
+ id: v.id,
83
+ model: v.model,
84
+ status: v.status,
85
+ created: v.created,
86
+ completed: v.completed,
87
+ seconds: v.seconds,
88
+ resolution: v.resolution,
89
+ aspectRatio: v.aspect_ratio,
90
+ videoUrl: v.video_url,
91
+ error: v.error,
92
+ costCreditsHeld: v.cost_credits_held,
93
+ costCredits: v.cost_credits,
94
+ requestId,
95
+ raw: v,
96
+ });
97
+ }
98
+ function chatBody(p, stream) {
99
+ if (!p || typeof p.model !== 'string')
100
+ throw new LazySusanError('Set "model", e.g. "anthropic/claude-sonnet-5-5".', { type: 'invalid_request_error', param: 'model' });
101
+ if (!Array.isArray(p.messages) || p.messages.length === 0)
102
+ throw new LazySusanError('"messages" must be a non-empty array.', { type: 'invalid_request_error', param: 'messages' });
103
+ return clean({
104
+ model: p.model,
105
+ messages: p.messages,
106
+ max_tokens: p.maxTokens,
107
+ temperature: p.temperature,
108
+ top_p: p.topP,
109
+ presence_penalty: p.presencePenalty,
110
+ frequency_penalty: p.frequencyPenalty,
111
+ stop: p.stop,
112
+ seed: p.seed,
113
+ tools: p.tools,
114
+ tool_choice: p.toolChoice,
115
+ parallel_tool_calls: p.parallelToolCalls,
116
+ response_format: p.responseFormat,
117
+ metadata: p.metadata,
118
+ ...(stream ? { stream: true, stream_options: { include_usage: true } } : {}),
119
+ });
120
+ }
121
+ /** Status codes that are never charged and safe to retry on any method */
122
+ const RETRYABLE_STATUS = new Set([429, 503]);
123
+ // ---------------------------------------------------------------------------------
124
+ // Client
125
+ class LazySusan {
126
+ constructor(options = {}) {
127
+ const envKey = globalThis.process?.env?.LAZYSUSAN_API_KEY;
128
+ const apiKey = options.apiKey ?? envKey;
129
+ if (!apiKey) {
130
+ throw new LazySusanError('Missing API key. Pass { apiKey } or set LAZYSUSAN_API_KEY. Create a key at https://www.lazysusan.ai/developers/console.', { type: 'authentication_error', code: 'missing_api_key' });
131
+ }
132
+ this.apiKey = apiKey;
133
+ this.baseURL = (options.baseURL ?? exports.DEFAULT_BASE_URL).replace(/\/+$/, '');
134
+ this.timeoutMs = options.timeoutMs ?? 300000;
135
+ this.maxRetries = Math.max(0, options.maxRetries ?? 2);
136
+ const f = options.fetch ?? (typeof fetch !== 'undefined' ? fetch : undefined);
137
+ if (!f)
138
+ throw new LazySusanError('No fetch implementation available. Use Node 18+ or pass { fetch }.');
139
+ this.fetchImpl = f;
140
+ this.defaultHeaders = options.defaultHeaders ?? {};
141
+ this.chat = new Chat(this);
142
+ this.images = new Images(this);
143
+ this.videos = new Videos(this);
144
+ this.models = new Models(this);
145
+ this.credits = new Credits(this);
146
+ }
147
+ /** @internal Send a request with timeout and safe retries; returns the raw Response (ok) */
148
+ async _request(method, path, body, signal) {
149
+ let attempt = 0;
150
+ for (;;) {
151
+ const controller = new AbortController();
152
+ const onAbort = () => controller.abort();
153
+ signal?.addEventListener('abort', onAbort, { once: true });
154
+ const timer = setTimeout(() => controller.abort(), this.timeoutMs);
155
+ let res;
156
+ try {
157
+ if (signal?.aborted)
158
+ throw abortError();
159
+ res = await this.fetchImpl(`${this.baseURL}${path}`, {
160
+ method,
161
+ headers: {
162
+ Authorization: `Bearer ${this.apiKey}`,
163
+ Accept: 'application/json',
164
+ 'User-Agent': `lazysusan-js/${exports.VERSION}`,
165
+ ...(body !== undefined ? { 'Content-Type': 'application/json' } : {}),
166
+ ...this.defaultHeaders,
167
+ },
168
+ body: body !== undefined ? JSON.stringify(body) : undefined,
169
+ signal: controller.signal,
170
+ });
171
+ }
172
+ catch (e) {
173
+ clearTimeout(timer);
174
+ signal?.removeEventListener('abort', onAbort);
175
+ if (signal?.aborted)
176
+ throw abortError();
177
+ const timedOut = controller.signal.aborted;
178
+ // A network failure on a POST may have reached the server: never retry it (could double-charge)
179
+ if (method === 'GET' && attempt < this.maxRetries) {
180
+ await sleep(backoff(attempt++), signal);
181
+ continue;
182
+ }
183
+ throw new LazySusanError(timedOut ? `The request timed out after ${this.timeoutMs} ms.` : `Network error: ${e?.message ?? e}`, { code: timedOut ? 'timeout' : 'network_error', type: 'connection_error' });
184
+ }
185
+ clearTimeout(timer);
186
+ signal?.removeEventListener('abort', onAbort);
187
+ if (res.ok)
188
+ return res;
189
+ if (RETRYABLE_STATUS.has(res.status) && attempt < this.maxRetries) {
190
+ const retryAfter = Number(res.headers.get('retry-after'));
191
+ try {
192
+ await res.body?.cancel();
193
+ }
194
+ catch { }
195
+ await sleep(Number.isFinite(retryAfter) && retryAfter > 0 ? Math.min(retryAfter * 1000, 60000) : backoff(attempt), signal);
196
+ attempt++;
197
+ continue;
198
+ }
199
+ throw await toError(res);
200
+ }
201
+ }
202
+ /** @internal */
203
+ async _json(method, path, body, signal) {
204
+ const res = await this._request(method, path, body, signal);
205
+ const requestId = res.headers.get('x-request-id');
206
+ const text = await res.text();
207
+ try {
208
+ return { data: text ? JSON.parse(text) : {}, requestId };
209
+ }
210
+ catch {
211
+ throw new LazySusanError('The API returned a response that is not JSON.', { status: res.status, requestId });
212
+ }
213
+ }
214
+ }
215
+ exports.LazySusan = LazySusan;
216
+ function backoff(attempt) {
217
+ const base = Math.min(500 * 2 ** attempt, 8000);
218
+ return base / 2 + Math.random() * (base / 2);
219
+ }
220
+ async function toError(res) {
221
+ const requestId = res.headers.get('x-request-id');
222
+ let body = null;
223
+ try {
224
+ body = await res.json();
225
+ }
226
+ catch { }
227
+ const e = body?.error ?? {};
228
+ return new LazySusanError(e.message || `Request failed with status ${res.status}.`, {
229
+ status: res.status,
230
+ type: e.type || 'api_error',
231
+ code: e.code ?? null,
232
+ param: e.param ?? null,
233
+ requestId,
234
+ });
235
+ }
236
+ // ---------------------------------------------------------------------------------
237
+ // Chat
238
+ class ChatStream {
239
+ constructor(client, params) {
240
+ this.client = client;
241
+ this.params = params;
242
+ this.consumed = false;
243
+ this.controller = new AbortController();
244
+ if (params.signal)
245
+ params.signal.addEventListener('abort', () => this.controller.abort(), { once: true });
246
+ this.iterator = this.run();
247
+ }
248
+ [Symbol.asyncIterator]() {
249
+ if (this.consumed)
250
+ throw new LazySusanError('A stream can only be read once.');
251
+ this.consumed = true;
252
+ return this.iterator;
253
+ }
254
+ /** Read the whole stream and return the full text */
255
+ async text() {
256
+ let final = '';
257
+ for await (const ev of this)
258
+ if (ev.type === 'done')
259
+ final = ev.text;
260
+ return final;
261
+ }
262
+ /** Read the whole stream and return the final event (text, usage, finish reason) */
263
+ async final() {
264
+ let last = null;
265
+ for await (const ev of this)
266
+ if (ev.type === 'done')
267
+ last = ev;
268
+ if (!last)
269
+ throw new LazySusanError('The stream ended without a final event.');
270
+ return last;
271
+ }
272
+ async *run() {
273
+ const res = await this.client._request('POST', '/chat/completions', chatBody(this.params, true), this.controller.signal);
274
+ const reader = res.body?.getReader();
275
+ if (!reader)
276
+ throw new LazySusanError('The API returned an empty stream.');
277
+ const decoder = new TextDecoder();
278
+ let buffer = '';
279
+ let text = '';
280
+ let usage = null;
281
+ let finishReason = null;
282
+ try {
283
+ for (;;) {
284
+ const { done, value } = await reader.read();
285
+ if (done)
286
+ break;
287
+ buffer += decoder.decode(value, { stream: true });
288
+ let nl;
289
+ while ((nl = buffer.indexOf('\n')) >= 0) {
290
+ const line = buffer.slice(0, nl).trim();
291
+ buffer = buffer.slice(nl + 1);
292
+ if (!line.startsWith('data:'))
293
+ continue;
294
+ const payload = line.slice(5).trim();
295
+ if (!payload)
296
+ continue;
297
+ if (payload === '[DONE]') {
298
+ yield { type: 'done', text, usage, finishReason };
299
+ return;
300
+ }
301
+ let chunk;
302
+ try {
303
+ chunk = JSON.parse(payload);
304
+ }
305
+ catch {
306
+ continue;
307
+ }
308
+ if (chunk?.error) {
309
+ throw new LazySusanError(chunk.error.message || 'The stream was interrupted.', { type: chunk.error.type || 'api_error', code: chunk.error.code ?? null, requestId: res.headers.get('x-request-id') });
310
+ }
311
+ if (chunk?.usage)
312
+ usage = toUsage(chunk.usage);
313
+ const choice = chunk?.choices?.[0];
314
+ if (!choice)
315
+ continue;
316
+ if (choice.finish_reason)
317
+ finishReason = choice.finish_reason;
318
+ const delta = choice.delta ?? {};
319
+ const piece = typeof delta.content === 'string' ? delta.content : '';
320
+ if (piece || delta.tool_calls) {
321
+ text += piece;
322
+ yield { type: 'delta', text: piece, ...(delta.tool_calls ? { toolCalls: delta.tool_calls } : {}), raw: chunk };
323
+ }
324
+ }
325
+ }
326
+ // Stream closed without [DONE]
327
+ yield { type: 'done', text, usage, finishReason };
328
+ }
329
+ finally {
330
+ try {
331
+ reader.releaseLock();
332
+ }
333
+ catch { }
334
+ }
335
+ }
336
+ }
337
+ class Chat {
338
+ constructor(client) {
339
+ this.client = client;
340
+ }
341
+ /** Send a chat request and wait for the full reply */
342
+ async create(params) {
343
+ const { data, requestId } = await this.client._json('POST', '/chat/completions', chatBody(params, false), params.signal);
344
+ const choice = data?.choices?.[0] ?? {};
345
+ const message = choice.message ?? { role: 'assistant', content: '' };
346
+ const text = typeof message.content === 'string' ? message.content : Array.isArray(message.content) ? message.content.map((p) => p?.text ?? '').join('') : '';
347
+ return {
348
+ id: data.id,
349
+ model: data.model,
350
+ text,
351
+ message,
352
+ finishReason: choice.finish_reason ?? null,
353
+ toolCalls: message.tool_calls ?? [],
354
+ usage: toUsage(data.usage),
355
+ ...(data.citations ? { citations: data.citations } : {}),
356
+ requestId,
357
+ raw: data,
358
+ };
359
+ }
360
+ /** Stream the reply as it's generated: `for await (const ev of ls.chat.stream({...}))` */
361
+ stream(params) {
362
+ return new ChatStream(this.client, params);
363
+ }
364
+ }
365
+ // ---------------------------------------------------------------------------------
366
+ // Images
367
+ class Images {
368
+ constructor(client) {
369
+ this.client = client;
370
+ }
371
+ async generate(params) {
372
+ const body = clean({
373
+ model: params.model,
374
+ prompt: params.prompt,
375
+ size: params.size,
376
+ quality: params.quality,
377
+ n: params.n,
378
+ image: params.image,
379
+ images: params.images,
380
+ response_format: params.format,
381
+ metadata: params.metadata,
382
+ });
383
+ const { data, requestId } = await this.client._json('POST', '/images/generations', body, params.signal);
384
+ return {
385
+ id: data.id,
386
+ model: data.model,
387
+ images: (data.data ?? []).map((d) => clean({ url: d.url, b64: d.b64_json, revisedPrompt: d.revised_prompt })),
388
+ usage: { images: data.usage?.images ?? 0, costCredits: data.usage?.cost_credits ?? 0 },
389
+ requestId,
390
+ raw: data,
391
+ };
392
+ }
393
+ }
394
+ // ---------------------------------------------------------------------------------
395
+ // Videos
396
+ class Videos {
397
+ constructor(client) {
398
+ this.client = client;
399
+ }
400
+ /** Start a video. It runs in the background; poll with get() or use wait(). */
401
+ async create(params) {
402
+ const body = clean({
403
+ model: params.model,
404
+ prompt: params.prompt,
405
+ seconds: params.seconds,
406
+ resolution: params.resolution,
407
+ aspect_ratio: params.aspectRatio,
408
+ image: params.image,
409
+ negative_prompt: params.negativePrompt,
410
+ metadata: params.metadata,
411
+ });
412
+ const { data, requestId } = await this.client._json('POST', '/videos', body, params.signal);
413
+ return toVideo(data, requestId);
414
+ }
415
+ async get(id, options = {}) {
416
+ const { data, requestId } = await this.client._json('GET', `/videos/${encodeURIComponent(id)}`, undefined, options.signal);
417
+ return toVideo(data, requestId);
418
+ }
419
+ /** Your 50 most recent videos */
420
+ async list(options = {}) {
421
+ const { data, requestId } = await this.client._json('GET', '/videos', undefined, options.signal);
422
+ return (data.data ?? []).map((v) => toVideo(v, requestId));
423
+ }
424
+ /** Poll until the video is ready. Throws if it fails (failed videos are refunded) or the wait times out. */
425
+ async wait(id, options = {}) {
426
+ const interval = Math.max(2000, options.pollIntervalMs ?? 10000);
427
+ const deadline = Date.now() + (options.timeoutMs ?? 20 * 60000);
428
+ for (;;) {
429
+ const video = await this.get(id, { signal: options.signal });
430
+ options.onProgress?.(video);
431
+ if (video.status === 'succeeded')
432
+ return video;
433
+ if (video.status === 'failed') {
434
+ throw new LazySusanError(video.error?.message ?? 'The video could not be generated. You were not charged.', { type: 'video_failed', code: 'video_failed', requestId: video.requestId });
435
+ }
436
+ if (Date.now() + interval > deadline) {
437
+ throw new LazySusanError(`Still ${video.status} after waiting. Call videos.get("${id}") later; it keeps running.`, { code: 'timeout', type: 'timeout' });
438
+ }
439
+ await sleep(interval, options.signal);
440
+ }
441
+ }
442
+ }
443
+ // ---------------------------------------------------------------------------------
444
+ // Models and credits
445
+ class Models {
446
+ constructor(client) {
447
+ this.client = client;
448
+ }
449
+ async list(options = {}) {
450
+ const { data } = await this.client._json('GET', '/models', undefined, options.signal);
451
+ return (data.data ?? []).filter((m) => !options.type || m.type === options.type).map(toModel);
452
+ }
453
+ async get(id, options = {}) {
454
+ const path = id.split('/').map(encodeURIComponent).join('/');
455
+ const { data } = await this.client._json('GET', `/models/${path}`, undefined, options.signal);
456
+ return toModel(data);
457
+ }
458
+ }
459
+ function toModel(m) {
460
+ return { id: m.id, name: m.name, type: m.type, ownedBy: m.owned_by, description: m.description, pricing: m.pricing, raw: m };
461
+ }
462
+ class Credits {
463
+ constructor(client) {
464
+ this.client = client;
465
+ }
466
+ /** Remaining balance in credits (1 credit = $0.001) */
467
+ async get(options = {}) {
468
+ const { data } = await this.client._json('GET', '/credits', undefined, options.signal);
469
+ return { balance: data.balance, autoTopUp: !!data.auto_top_up };
470
+ }
471
+ }
472
+ exports.default = LazySusan;
473
+
474
+ module.exports = Object.assign(exports.default, exports);