segmind 0.5.0 → 0.6.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/dist/index.cjs CHANGED
@@ -1,189 +1,25 @@
1
- "use strict";
2
- var __create = Object.create;
3
- var __defProp = Object.defineProperty;
4
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
- var __getOwnPropNames = Object.getOwnPropertyNames;
6
- var __getProtoOf = Object.getPrototypeOf;
7
- var __hasOwnProp = Object.prototype.hasOwnProperty;
8
- var __export = (target, all) => {
9
- for (var name in all)
10
- __defProp(target, name, { get: all[name], enumerable: true });
11
- };
12
- var __copyProps = (to, from, except, desc) => {
13
- if (from && typeof from === "object" || typeof from === "function") {
14
- for (let key of __getOwnPropNames(from))
15
- if (!__hasOwnProp.call(to, key) && key !== except)
16
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
- }
18
- return to;
19
- };
20
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
- // If the importer is in node compatibility mode or this is not an ESM
22
- // file that has been converted to a CommonJS file using a Babel-
23
- // compatible transform (i.e. "__esModule" has not been set), then set
24
- // "default" to the CommonJS "module.exports" for node compatibility.
25
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
- mod
27
- ));
28
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { newObj[key] = obj[key]; } } } newObj.default = obj; return newObj; } } function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } async function _asyncNullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return await rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }
2
+
3
+
29
4
 
30
- // src/index.ts
31
- var index_exports = {};
32
- __export(index_exports, {
33
- APIConnectionError: () => APIConnectionError,
34
- Accounts: () => Accounts,
35
- ChatResponse: () => ChatResponse,
36
- DEFAULT_BASE_URL: () => DEFAULT_BASE_URL,
37
- DEFAULT_CONSOLE_URL: () => DEFAULT_CONSOLE_URL,
38
- DEFAULT_SPOT_URL: () => DEFAULT_SPOT_URL,
39
- DEFAULT_WAIT_INTERVAL_MS: () => DEFAULT_WAIT_INTERVAL_MS,
40
- DEFAULT_WAIT_TIMEOUT_MS: () => DEFAULT_WAIT_TIMEOUT_MS,
41
- Files: () => Files,
42
- Generations: () => Generations,
43
- InferenceFailed: () => InferenceFailed,
44
- InferenceTimeout: () => InferenceTimeout,
45
- InsufficientCredits: () => InsufficientCredits,
46
- Job: () => Job,
47
- Models: () => Models,
48
- PixelFlows: () => PixelFlows,
49
- PixelflowJob: () => PixelflowJob,
50
- RateLimited: () => RateLimited,
51
- Segmind: () => Segmind,
52
- SegmindError: () => SegmindError,
53
- VERSION: () => VERSION,
54
- Webhooks: () => Webhooks,
55
- accounts: () => accounts,
56
- chat: () => chat,
57
- chatSync: () => chatSync,
58
- files: () => files,
59
- generations: () => generations,
60
- imageUrl: () => imageUrl,
61
- job: () => job,
62
- models: () => models,
63
- pixelflows: () => pixelflows,
64
- run: () => run,
65
- runSync: () => runSync,
66
- submit: () => submit,
67
- submitChat: () => submitChat,
68
- webhooks: () => webhooks
69
- });
70
- module.exports = __toCommonJS(index_exports);
71
5
 
72
- // src/core/errors.ts
73
- var SegmindError = class extends Error {
74
- /** HTTP status, when the error came from a response. */
75
- status;
76
- /** The server's error text (`error` in the response body), when it sent one. */
77
- detail;
78
- /** The v2 request id the error belongs to, when there is one. */
79
- requestId;
80
- /** The parsed response body, or its text when it was not JSON. */
81
- body;
82
- constructor(message, options = {}) {
83
- super(message, options.cause === void 0 ? void 0 : { cause: options.cause });
84
- this.name = new.target.name;
85
- this.status = options.status;
86
- this.detail = options.detail;
87
- this.requestId = options.requestId;
88
- this.body = options.body;
89
- }
90
- /** Reads the response body and builds the error. Consumes the body. */
91
- static fromResponse(response, requestId) {
92
- return errorFromResponse(response, requestId);
93
- }
94
- };
95
- var APIConnectionError = class extends SegmindError {
96
- };
97
- var InsufficientCredits = class extends SegmindError {
98
- };
99
- var RateLimited = class extends SegmindError {
100
- retryAfterMs;
101
- constructor(message, options = {}) {
102
- super(message, options);
103
- this.retryAfterMs = options.retryAfterMs;
104
- }
105
- };
106
- var InferenceFailed = class extends SegmindError {
107
- /** The status body that reported the failure. */
108
- statusBody;
109
- constructor(requestId, statusBody, detail) {
110
- detail ??= typeof statusBody.error === "string" ? statusBody.error : void 0;
111
- super(detail ? `request ${requestId} failed: ${detail}` : `request ${requestId} failed`, {
112
- detail,
113
- requestId,
114
- body: statusBody
115
- });
116
- this.statusBody = statusBody;
117
- }
118
- };
119
- var InferenceTimeout = class extends SegmindError {
120
- elapsedMs;
121
- constructor(requestId, elapsedMs) {
122
- super(`request ${requestId} did not finish within ${Math.round(elapsedMs)} ms`, { requestId });
123
- this.elapsedMs = elapsedMs;
124
- }
125
- };
126
- async function errorFromResponse(response, requestId) {
127
- const text = await response.text().catch(() => "");
128
- let body = text;
129
- try {
130
- body = text ? JSON.parse(text) : void 0;
131
- } catch {
132
- }
133
- const detail = errorDetail(body) ?? plainText(body);
134
- const message = detail ? `${response.status} ${detail}` : `${response.status} ${response.statusText || "request failed"}`;
135
- const options = { status: response.status, detail, requestId, body };
136
- if (response.status === 429) {
137
- return new RateLimited(message, { ...options, retryAfterMs: parseRetryAfter(response.headers.get("retry-after")) });
138
- }
139
- if (response.status === 402 || isOutOfCredits(detail)) return new InsufficientCredits(message, options);
140
- return new SegmindError(message, options);
141
- }
142
- function requestFailure(requestId, statusBody, detail) {
143
- detail ??= typeof statusBody.error === "string" ? statusBody.error : void 0;
144
- if (isOutOfCredits(detail)) {
145
- return new InsufficientCredits(`request ${requestId} failed: ${detail}`, { detail, requestId, body: statusBody });
146
- }
147
- return new InferenceFailed(requestId, statusBody, detail);
148
- }
149
- function parseRetryAfter(value, now = Date.now()) {
150
- if (!value) return void 0;
151
- const seconds = Number(value);
152
- if (Number.isFinite(seconds) && seconds >= 0) return seconds * 1e3;
153
- const date = Date.parse(value);
154
- return Number.isNaN(date) ? void 0 : Math.max(date - now, 0);
155
- }
156
- function isOutOfCredits(detail) {
157
- return detail?.startsWith("Insufficient credits.") ?? false;
158
- }
159
- function plainText(body) {
160
- if (typeof body !== "string" || !body || body.trimStart().startsWith("<")) return void 0;
161
- return body.slice(0, 500);
162
- }
163
- function errorDetail(body) {
164
- if (!body || typeof body !== "object") return void 0;
165
- const record2 = body;
166
- for (const key of ["error", "message", "detail"]) {
167
- const value = record2[key];
168
- if (typeof value === "string" && value) return value;
169
- if (value && typeof value === "object" && typeof value.message === "string") {
170
- return value.message;
171
- }
172
- }
173
- return void 0;
174
- }
6
+
7
+
8
+
9
+
10
+ var _chunk74UKKBOOcjs = require('./chunk-74UKKBOO.cjs');
175
11
 
176
12
  // src/chat.ts
177
13
  var ChatResponse = class {
178
14
  constructor(raw) {
179
15
  this.raw = raw;
180
16
  }
181
- raw;
17
+
182
18
  /** The assistant's text. Throws when the body holds none (inspect `raw`). */
183
19
  get text() {
184
20
  const text = extractText(this.raw);
185
21
  if (text === void 0) {
186
- throw new SegmindError(
22
+ throw new (0, _chunk74UKKBOOcjs.SegmindError)(
187
23
  `could not find assistant text in the response (top-level keys: ${Object.keys(this.raw).sort().join(", ")}); inspect ChatResponse.raw`,
188
24
  { body: this.raw }
189
25
  );
@@ -196,7 +32,7 @@ var ChatResponse = class {
196
32
  try {
197
33
  return JSON.parse(text);
198
34
  } catch (err) {
199
- throw new SegmindError(`ChatResponse.text is not valid JSON: ${err.message}`, {
35
+ throw new (0, _chunk74UKKBOOcjs.SegmindError)(`ChatResponse.text is not valid JSON: ${err.message}`, {
200
36
  body: text,
201
37
  cause: err
202
38
  });
@@ -204,28 +40,28 @@ var ChatResponse = class {
204
40
  }
205
41
  /** The provider's token usage (`usage` or Gemini's `usageMetadata`). */
206
42
  get usage() {
207
- return (record(this.raw.usage) ?? record(this.raw.usageMetadata)) || void 0;
43
+ return (_nullishCoalesce(record(this.raw.usage), () => ( record(this.raw.usageMetadata)))) || void 0;
208
44
  }
209
45
  /** Why generation stopped (`finish_reason`, `stop_reason` or `finishReason`). */
210
46
  get finishReason() {
211
- if (Array.isArray(this.raw.choices)) return str(record(this.raw.choices[0])?.finish_reason);
47
+ if (Array.isArray(this.raw.choices)) return str(_optionalChain([record, 'call', _ => _(this.raw.choices[0]), 'optionalAccess', _2 => _2.finish_reason]));
212
48
  if ("stop_reason" in this.raw) return str(this.raw.stop_reason);
213
- if (Array.isArray(this.raw.candidates)) return str(record(this.raw.candidates[0])?.finishReason);
49
+ if (Array.isArray(this.raw.candidates)) return str(_optionalChain([record, 'call', _3 => _3(this.raw.candidates[0]), 'optionalAccess', _4 => _4.finishReason]));
214
50
  return void 0;
215
51
  }
216
52
  /** Tool calls in the OpenAI shape, when the model made any. */
217
53
  get toolCalls() {
218
54
  if (!Array.isArray(this.raw.choices)) return [];
219
- const calls = record(record(this.raw.choices[0])?.message)?.tool_calls;
55
+ const calls = _optionalChain([record, 'call', _5 => _5(_optionalChain([record, 'call', _6 => _6(this.raw.choices[0]), 'optionalAccess', _7 => _7.message])), 'optionalAccess', _8 => _8.tool_calls]);
220
56
  return Array.isArray(calls) ? calls : [];
221
57
  }
222
58
  };
223
59
  function chatBody(params) {
224
60
  if (params.messages === void 0 && params.prompt === void 0) {
225
- throw new SegmindError('chat: pass messages: [...] or prompt: "..."');
61
+ throw new (0, _chunk74UKKBOOcjs.SegmindError)('chat: pass messages: [...] or prompt: "..."');
226
62
  }
227
63
  if (params.stream === true) {
228
- throw new SegmindError("chat: streaming is not supported yet; omit stream or set it to false");
64
+ throw new (0, _chunk74UKKBOOcjs.SegmindError)("chat: streaming is not supported yet; omit stream or set it to false");
229
65
  }
230
66
  return params;
231
67
  }
@@ -235,7 +71,7 @@ function chatFromRunResult(body) {
235
71
  try {
236
72
  const parsed = JSON.parse(output);
237
73
  if (record(parsed)) return new ChatResponse(parsed);
238
- } catch {
74
+ } catch (e2) {
239
75
  }
240
76
  return new ChatResponse({ choices: [{ message: { content: output } }] });
241
77
  }
@@ -244,21 +80,21 @@ function chatFromRunResult(body) {
244
80
  }
245
81
  function extractText(raw) {
246
82
  if ("choices" in raw) {
247
- const content = record(record(Array.isArray(raw.choices) ? raw.choices[0] : void 0)?.message)?.content;
83
+ const content = _optionalChain([record, 'call', _9 => _9(_optionalChain([record, 'call', _10 => _10(Array.isArray(raw.choices) ? raw.choices[0] : void 0), 'optionalAccess', _11 => _11.message])), 'optionalAccess', _12 => _12.content]);
248
84
  if (typeof content === "string") return content;
249
85
  if (Array.isArray(content)) {
250
- return content.map(record).filter((part) => part && (part.type === void 0 || part.type === "text")).map((part) => str(part.text) ?? "").join("");
86
+ return content.map(record).filter((part) => part && (part.type === void 0 || part.type === "text")).map((part) => _nullishCoalesce(str(part.text), () => ( ""))).join("");
251
87
  }
252
88
  return void 0;
253
89
  }
254
90
  if (Array.isArray(raw.content)) {
255
- return raw.content.map(record).filter((part) => part?.type === "text").map((part) => str(part.text) ?? "").join("");
91
+ return raw.content.map(record).filter((part) => _optionalChain([part, 'optionalAccess', _13 => _13.type]) === "text").map((part) => _nullishCoalesce(str(part.text), () => ( ""))).join("");
256
92
  }
257
93
  if ("candidates" in raw) {
258
94
  const candidate = record(Array.isArray(raw.candidates) ? raw.candidates[0] : void 0);
259
- const parts = record(candidate?.content)?.parts;
95
+ const parts = _optionalChain([record, 'call', _14 => _14(_optionalChain([candidate, 'optionalAccess', _15 => _15.content])), 'optionalAccess', _16 => _16.parts]);
260
96
  if (!Array.isArray(parts)) return candidate ? "" : void 0;
261
- return parts.map((part) => str(record(part)?.text) ?? "").join("");
97
+ return parts.map((part) => _nullishCoalesce(str(_optionalChain([record, 'call', _17 => _17(part), 'optionalAccess', _18 => _18.text])), () => ( ""))).join("");
262
98
  }
263
99
  return void 0;
264
100
  }
@@ -272,9 +108,9 @@ function str(value) {
272
108
  // src/core/env.ts
273
109
  var g = globalThis;
274
110
  function detectRuntime() {
275
- if (g.navigator?.product === "ReactNative") return "react-native";
111
+ if (_optionalChain([g, 'access', _19 => _19.navigator, 'optionalAccess', _20 => _20.product]) === "ReactNative") return "react-native";
276
112
  if (typeof g.window !== "undefined" && typeof g.document !== "undefined") return "browser";
277
- if (g.process?.versions?.node) return "node";
113
+ if (_optionalChain([g, 'access', _21 => _21.process, 'optionalAccess', _22 => _22.versions, 'optionalAccess', _23 => _23.node])) return "node";
278
114
  return "other";
279
115
  }
280
116
  function initiatorHeaders(options) {
@@ -285,17 +121,17 @@ function initiatorHeaders(options) {
285
121
  }
286
122
  function readEnv(name) {
287
123
  try {
288
- const value = g.process?.env?.[name];
289
- return value?.trim() ? value.trim() : void 0;
290
- } catch {
124
+ const value = _optionalChain([g, 'access', _24 => _24.process, 'optionalAccess', _25 => _25.env, 'optionalAccess', _26 => _26[name]]);
125
+ return _optionalChain([value, 'optionalAccess', _27 => _27.trim, 'call', _28 => _28()]) ? value.trim() : void 0;
126
+ } catch (e3) {
291
127
  return void 0;
292
128
  }
293
129
  }
294
130
  function nodeVersion() {
295
- return g.process?.versions?.node ? g.process.version : void 0;
131
+ return _optionalChain([g, 'access', _29 => _29.process, 'optionalAccess', _30 => _30.versions, 'optionalAccess', _31 => _31.node]) ? g.process.version : void 0;
296
132
  }
297
133
  function randomRequestId() {
298
- const uuid = g.crypto?.randomUUID?.();
134
+ const uuid = _optionalChain([g, 'access', _32 => _32.crypto, 'optionalAccess', _33 => _33.randomUUID, 'optionalCall', _34 => _34()]);
299
135
  if (uuid) return uuid;
300
136
  let id = "";
301
137
  for (let i = 0; i < 32; i++) id += Math.floor(Math.random() * 16).toString(16);
@@ -315,36 +151,36 @@ function toBase64(bytes) {
315
151
  var RETRYABLE_STATUS = /* @__PURE__ */ new Set([408, 429, 502, 503, 504]);
316
152
  var MAX_RETRY_DELAY_MS = 6e4;
317
153
  function retryDelay(attempt, retryAfter, now = Date.now()) {
318
- const asked = parseRetryAfter(retryAfter, now);
154
+ const asked = _chunk74UKKBOOcjs.parseRetryAfter.call(void 0, retryAfter, now);
319
155
  if (asked !== void 0) return Math.min(asked, MAX_RETRY_DELAY_MS);
320
156
  const base = Math.min(500 * 2 ** attempt, 8e3);
321
157
  return base * (0.75 + Math.random() * 0.25);
322
158
  }
323
159
  function pollDelay(interval, elapsedMs, fallback) {
324
- const delay = typeof interval === "function" ? interval(elapsedMs) : interval ?? fallback;
160
+ const delay = typeof interval === "function" ? interval(elapsedMs) : _nullishCoalesce(interval, () => ( fallback));
325
161
  return Number.isFinite(delay) && delay >= 0 ? delay : fallback;
326
162
  }
327
163
  function sleep(ms, signal) {
328
164
  return new Promise((resolve, reject) => {
329
- if (signal?.aborted) return reject(signal.reason);
165
+ if (_optionalChain([signal, 'optionalAccess', _35 => _35.aborted])) return reject(signal.reason);
330
166
  const timer = setTimeout(() => {
331
- signal?.removeEventListener("abort", onAbort);
167
+ _optionalChain([signal, 'optionalAccess', _36 => _36.removeEventListener, 'call', _37 => _37("abort", onAbort)]);
332
168
  resolve();
333
169
  }, ms);
334
170
  const onAbort = () => {
335
171
  clearTimeout(timer);
336
172
  reject(signal.reason);
337
173
  };
338
- signal?.addEventListener("abort", onAbort, { once: true });
174
+ _optionalChain([signal, 'optionalAccess', _38 => _38.addEventListener, 'call', _39 => _39("abort", onAbort, { once: true })]);
339
175
  });
340
176
  }
341
177
  var HttpClient = class {
342
178
  constructor(config) {
343
179
  this.config = config;
344
180
  }
345
- config;
181
+
346
182
  /** The hook call in flight, so that requests failing together share one refresh. */
347
- unauthorized;
183
+
348
184
  /** The response whatever its status, after retries when `retry` is set. */
349
185
  async fetchRaw(req) {
350
186
  let attempt = 0;
@@ -356,7 +192,7 @@ var HttpClient = class {
356
192
  try {
357
193
  response = await this.attempt(req, token);
358
194
  } catch (err) {
359
- if (canRetry && err instanceof APIConnectionError) {
195
+ if (canRetry && err instanceof _chunk74UKKBOOcjs.APIConnectionError) {
360
196
  await sleep(retryDelay(attempt, null), req.signal);
361
197
  attempt++;
362
198
  continue;
@@ -365,11 +201,11 @@ var HttpClient = class {
365
201
  }
366
202
  if (response.status === 401 && !reauthenticated && await this.reauthenticate(req, token)) {
367
203
  reauthenticated = true;
368
- await response.body?.cancel().catch(() => void 0);
204
+ await _optionalChain([response, 'access', _40 => _40.body, 'optionalAccess', _41 => _41.cancel, 'call', _42 => _42(), 'access', _43 => _43.catch, 'call', _44 => _44(() => void 0)]);
369
205
  continue;
370
206
  }
371
207
  if (canRetry && RETRYABLE_STATUS.has(response.status)) {
372
- await response.body?.cancel().catch(() => void 0);
208
+ await _optionalChain([response, 'access', _45 => _45.body, 'optionalAccess', _46 => _46.cancel, 'call', _47 => _47(), 'access', _48 => _48.catch, 'call', _49 => _49(() => void 0)]);
373
209
  await sleep(retryDelay(attempt, response.headers.get("retry-after")), req.signal);
374
210
  attempt++;
375
211
  continue;
@@ -380,7 +216,7 @@ var HttpClient = class {
380
216
  /** The response, or a `SegmindError` for any status outside 2xx. */
381
217
  async request(req) {
382
218
  const response = await this.fetchRaw(req);
383
- if (!response.ok) throw await SegmindError.fromResponse(response);
219
+ if (!response.ok) throw await _chunk74UKKBOOcjs.SegmindError.fromResponse(response);
384
220
  return response;
385
221
  }
386
222
  /** The parsed JSON body of a 2xx response. */
@@ -390,9 +226,9 @@ var HttpClient = class {
390
226
  async sessionToken(req) {
391
227
  if (!this.config.tokenProvider || req.bare) return void 0;
392
228
  try {
393
- return await this.config.tokenProvider() ?? void 0;
229
+ return await _asyncNullishCoalesce(await this.config.tokenProvider(), async () => ( void 0));
394
230
  } catch (err) {
395
- throw new SegmindError(`tokenProvider failed: ${describe(err)}`, { cause: err });
231
+ throw new (0, _chunk74UKKBOOcjs.SegmindError)(`tokenProvider failed: ${describe(err)}`, { cause: err });
396
232
  }
397
233
  }
398
234
  /** Tells the app its token was refused. True when it now has a different one to try. */
@@ -407,14 +243,14 @@ var HttpClient = class {
407
243
  }
408
244
  const next = await this.config.tokenProvider();
409
245
  return Boolean(next) && next !== refused;
410
- } catch {
246
+ } catch (e4) {
411
247
  return false;
412
248
  }
413
249
  }
414
250
  async attempt(req, token) {
415
251
  const { signal } = req;
416
- if (signal?.aborted) throw signal.reason;
417
- const timeout = req.timeout ?? this.config.timeout;
252
+ if (_optionalChain([signal, 'optionalAccess', _50 => _50.aborted])) throw signal.reason;
253
+ const timeout = _nullishCoalesce(req.timeout, () => ( this.config.timeout));
418
254
  const controller = new AbortController();
419
255
  let timedOut = false;
420
256
  const timer = setTimeout(() => {
@@ -422,12 +258,12 @@ var HttpClient = class {
422
258
  controller.abort();
423
259
  }, timeout);
424
260
  const onAbort = () => controller.abort(signal.reason);
425
- signal?.addEventListener("abort", onAbort, { once: true });
261
+ _optionalChain([signal, 'optionalAccess', _51 => _51.addEventListener, 'call', _52 => _52("abort", onAbort, { once: true })]);
426
262
  const headers = req.bare ? { ...req.headers } : { ...this.config.headers, ...req.headers };
427
263
  if (this.config.apiKey && !req.bare) headers["x-api-key"] = this.config.apiKey;
428
264
  if (token) headers.Authorization = `Bearer ${token}`;
429
265
  if (req.body !== void 0) headers["content-type"] = "application/json";
430
- const body = req.rawBody ?? (req.body === void 0 ? void 0 : JSON.stringify(req.body));
266
+ const body = _nullishCoalesce(req.rawBody, () => ( (req.body === void 0 ? void 0 : JSON.stringify(req.body))));
431
267
  try {
432
268
  return await this.config.fetch(withQuery(req.url, req.query), {
433
269
  method: req.method,
@@ -436,12 +272,12 @@ var HttpClient = class {
436
272
  signal: controller.signal
437
273
  });
438
274
  } catch (err) {
439
- if (signal?.aborted) throw signal.reason ?? err;
275
+ if (_optionalChain([signal, 'optionalAccess', _53 => _53.aborted])) throw _nullishCoalesce(signal.reason, () => ( err));
440
276
  const reason = timedOut ? `request timed out after ${timeout} ms` : `connection error: ${describe(err)}`;
441
- throw new APIConnectionError(`${req.method} ${req.url}: ${reason}`, { cause: err });
277
+ throw new (0, _chunk74UKKBOOcjs.APIConnectionError)(`${req.method} ${req.url}: ${reason}`, { cause: err });
442
278
  } finally {
443
279
  clearTimeout(timer);
444
- signal?.removeEventListener("abort", onAbort);
280
+ _optionalChain([signal, 'optionalAccess', _54 => _54.removeEventListener, 'call', _55 => _55("abort", onAbort)]);
445
281
  }
446
282
  }
447
283
  };
@@ -450,7 +286,7 @@ async function readJson(response) {
450
286
  try {
451
287
  return JSON.parse(text);
452
288
  } catch (err) {
453
- throw new SegmindError(`${response.status} response was not JSON`, {
289
+ throw new (0, _chunk74UKKBOOcjs.SegmindError)(`${response.status} response was not JSON`, {
454
290
  status: response.status,
455
291
  body: text.slice(0, 500),
456
292
  cause: err
@@ -512,44 +348,54 @@ function mimeFromName(name) {
512
348
  const extension = name.includes(".") ? name.split(".").pop().toLowerCase() : "";
513
349
  return MIME_BY_EXTENSION[extension];
514
350
  }
515
- async function readFileInput(input, options) {
516
- let bytes;
351
+ async function openFileInput(input, options) {
352
+ let body;
517
353
  let name = options.filename;
518
354
  let mimeType = options.mimeType;
519
355
  if (typeof input === "string") {
520
356
  if (detectRuntime() !== "node") {
521
- throw new SegmindError(`${options.caller}: file paths work in Node only; pass a Blob or bytes`);
357
+ throw new (0, _chunk74UKKBOOcjs.SegmindError)(`${options.caller}: file paths work in Node only; pass a Blob or bytes`);
522
358
  }
523
- const { readFile } = await import(
359
+ const { openAsBlob } = await Promise.resolve().then(() => _interopRequireWildcard(require(
524
360
  /* webpackIgnore: true */
525
361
  /* turbopackIgnore: true */
526
362
  /* @vite-ignore */
527
- "node:fs/promises"
528
- );
363
+ "node:fs"
364
+ )));
529
365
  try {
530
- bytes = new Uint8Array(await readFile(input));
366
+ body = await openAsBlob(input);
531
367
  } catch (err) {
532
- throw new SegmindError(`${options.caller}: cannot read ${JSON.stringify(input)}: ${err.message}`, {
368
+ throw new (0, _chunk74UKKBOOcjs.SegmindError)(`${options.caller}: cannot read ${JSON.stringify(input)}: ${err.message}`, {
533
369
  cause: err
534
370
  });
535
371
  }
536
372
  name ??= input.split(/[\\/]/).pop();
537
373
  } else if (typeof Blob !== "undefined" && input instanceof Blob) {
538
- bytes = new Uint8Array(await input.arrayBuffer());
374
+ body = input;
539
375
  name ??= input.name || void 0;
540
376
  mimeType ??= input.type || void 0;
541
377
  } else {
542
- bytes = input instanceof Uint8Array ? input : new Uint8Array(input);
378
+ body = input instanceof Uint8Array ? input : new Uint8Array(input);
543
379
  }
544
- mimeType ??= name && mimeFromName(name) || sniff(bytes);
380
+ mimeType ??= name && mimeFromName(name) || sniff(await head(body));
545
381
  if (!name || !name.includes(".")) {
546
382
  const extension = mimeType ? EXTENSION_BY_MIME[mimeType] : void 0;
547
383
  if (!extension) {
548
- throw new SegmindError(`${options.caller}: cannot tell the file type; pass { filename: 'name.ext' } or { mimeType }`);
384
+ throw new (0, _chunk74UKKBOOcjs.SegmindError)(`${options.caller}: cannot tell the file type; pass { filename: 'name.ext' } or { mimeType }`);
549
385
  }
550
386
  name = `${name || "upload"}.${extension}`;
551
387
  }
552
- return { bytes, filename: name, mimeType };
388
+ const size = body instanceof Uint8Array ? body.byteLength : body.size;
389
+ return { body, size, filename: name, mimeType };
390
+ }
391
+ async function readFileInput(input, options) {
392
+ const { body, filename, mimeType } = await openFileInput(input, options);
393
+ const bytes = body instanceof Uint8Array ? body : new Uint8Array(await body.arrayBuffer());
394
+ return { bytes, filename, mimeType };
395
+ }
396
+ async function head(body) {
397
+ if (body instanceof Uint8Array) return body;
398
+ return new Uint8Array(await body.slice(0, 16).arrayBuffer());
553
399
  }
554
400
  function sniff(bytes) {
555
401
  const at = (offset, signature) => signature.every((b, i) => bytes[offset + i] === b);
@@ -569,7 +415,7 @@ var Files = class {
569
415
  constructor(client2) {
570
416
  this.client = client2;
571
417
  }
572
- client;
418
+
573
419
  async upload(input, options = {}) {
574
420
  if (Array.isArray(input)) {
575
421
  const uploaded = [];
@@ -579,21 +425,21 @@ var Files = class {
579
425
  return this.uploadOne(input, options);
580
426
  }
581
427
  async uploadOne(input, options) {
582
- const file = await readFileInput(input, { ...options, caller: "files.upload" });
428
+ const file = await openFileInput(input, { ...options, caller: "files.upload" });
583
429
  const url = options.persist ? await this.persist(file, options.signal) : await this.stage(file, options.signal);
584
- return { url, filename: file.filename, size: file.bytes.byteLength, persistent: options.persist === true };
430
+ return { url, filename: file.filename, size: file.size, persistent: options.persist === true };
585
431
  }
586
432
  /** A temporary model input on the inference API's input bucket. */
587
433
  async stage(file, signal) {
588
434
  const ticket = await this.client.http.json({
589
435
  method: "POST",
590
436
  url: `${this.client.spotURL}/inference-request/input-presign`,
591
- body: { filename: file.filename, size: file.bytes.byteLength },
437
+ body: { filename: file.filename, size: file.size },
592
438
  signal,
593
439
  retry: true
594
440
  });
595
441
  if (!ticket.upload_url || !ticket.url) {
596
- throw new SegmindError("files.upload: the presign response had no upload_url or url", { body: ticket });
442
+ throw new (0, _chunk74UKKBOOcjs.SegmindError)("files.upload: the presign response had no upload_url or url", { body: ticket });
597
443
  }
598
444
  const headers = { ...ticket.required_headers };
599
445
  delete headers["Content-Length"];
@@ -605,18 +451,18 @@ var Files = class {
605
451
  async persist(file, signal) {
606
452
  const contentType = file.mimeType;
607
453
  if (!contentType) {
608
- throw new SegmindError(`files.upload: cannot tell the type of ${file.filename}; pass { mimeType } to persist it`);
454
+ throw new (0, _chunk74UKKBOOcjs.SegmindError)(`files.upload: cannot tell the type of ${file.filename}; pass { mimeType } to persist it`);
609
455
  }
610
456
  const { http, assetsURL } = this.client;
611
457
  const ticket = await http.json({
612
458
  method: "POST",
613
459
  url: `${assetsURL}/upload-asset/presign`,
614
- body: { filename: file.filename, contentType, size: file.bytes.byteLength },
460
+ body: { filename: file.filename, contentType, size: file.size },
615
461
  signal,
616
462
  retry: true
617
463
  });
618
464
  if (!ticket.presignedUrl || !ticket.s3Key || !ticket.publicUrl) {
619
- throw new SegmindError("files.upload: the asset presign response had no presignedUrl, s3Key or publicUrl", {
465
+ throw new (0, _chunk74UKKBOOcjs.SegmindError)("files.upload: the asset presign response had no presignedUrl, s3Key or publicUrl", {
620
466
  body: ticket
621
467
  });
622
468
  }
@@ -628,11 +474,14 @@ var Files = class {
628
474
  signal,
629
475
  retry: true
630
476
  });
631
- return confirmed.asset?.url ?? ticket.publicUrl;
477
+ return _nullishCoalesce(_optionalChain([confirmed, 'access', _56 => _56.asset, 'optionalAccess', _57 => _57.url]), () => ( ticket.publicUrl));
632
478
  }
633
- /** A PUT to the same key is idempotent, so it retries. `bare` keeps the API key off the storage host. */
479
+ /**
480
+ * A PUT to the same key is idempotent, so it retries; a `Blob` body can be
481
+ * sent again, unlike a stream. `bare` keeps the API key off the storage host.
482
+ */
634
483
  async put(url, file, headers, signal) {
635
- await this.client.http.request({ method: "PUT", url, rawBody: file.bytes, headers, bare: true, signal, retry: true });
484
+ await this.client.http.request({ method: "PUT", url, rawBody: file.body, headers, bare: true, signal, retry: true });
636
485
  }
637
486
  };
638
487
 
@@ -641,11 +490,11 @@ var Generations = class {
641
490
  constructor(client2) {
642
491
  this.client = client2;
643
492
  }
644
- client;
493
+
645
494
  /** Generated outputs, newest first. */
646
495
  async list(options = {}) {
647
496
  return this.read("/inference-request/generations", options.signal, {
648
- page: options.page ?? 1,
497
+ page: _nullishCoalesce(options.page, () => ( 1)),
649
498
  per_page: options.perPage,
650
499
  model_name: options.modelName,
651
500
  start_date: options.startDate,
@@ -665,13 +514,13 @@ var Generations = class {
665
514
  */
666
515
  async history(options = {}) {
667
516
  return this.read("/inference-request/request-history", options.signal, {
668
- page: options.page ?? 1,
669
- per_page: options.perPage ?? 20,
517
+ page: _nullishCoalesce(options.page, () => ( 1)),
518
+ per_page: _nullishCoalesce(options.perPage, () => ( 20)),
670
519
  from_date: options.fromDate,
671
520
  to_date: options.toDate,
672
521
  model_name: options.modelName,
673
522
  status: options.status,
674
- initiator: [options.initiator ?? []].flat().join(",") || void 0,
523
+ initiator: [_nullishCoalesce(options.initiator, () => ( []))].flat().join(",") || void 0,
675
524
  key_suffix: options.keySuffix,
676
525
  user_id: options.userId,
677
526
  user_email: options.userEmail,
@@ -701,12 +550,12 @@ var Job = class {
701
550
  this.statusUrl = submitResponse.status_url;
702
551
  this.responseUrl = submitResponse.response_url;
703
552
  }
704
- http;
705
- submitResponse;
706
- transform;
707
- requestId;
708
- statusUrl;
709
- responseUrl;
553
+
554
+
555
+
556
+
557
+
558
+
710
559
  /** The current state, without waiting. */
711
560
  async status(options = {}) {
712
561
  return await this.read(this.statusUrl, options.signal);
@@ -717,9 +566,9 @@ var Job = class {
717
566
  */
718
567
  async result(options = {}) {
719
568
  const body = await this.read(this.responseUrl, options.signal);
720
- if (body.status === "FAILED") throw requestFailure(this.requestId, body);
569
+ if (body.status === "FAILED") throw _chunk74UKKBOOcjs.requestFailure.call(void 0, this.requestId, body);
721
570
  if (body.status !== void 0 && body.status !== "COMPLETED") {
722
- throw new SegmindError(`request ${this.requestId} is still ${String(body.status)}; use wait()`, {
571
+ throw new (0, _chunk74UKKBOOcjs.SegmindError)(`request ${this.requestId} is still ${String(body.status)}; use wait()`, {
723
572
  requestId: this.requestId,
724
573
  body
725
574
  });
@@ -728,15 +577,15 @@ var Job = class {
728
577
  }
729
578
  /** Polls until the request finishes, then returns its result. */
730
579
  async wait(options = {}) {
731
- const timeout = options.timeout ?? DEFAULT_WAIT_TIMEOUT_MS;
580
+ const timeout = _nullishCoalesce(options.timeout, () => ( DEFAULT_WAIT_TIMEOUT_MS));
732
581
  const started = Date.now();
733
582
  for (; ; ) {
734
583
  const status = await this.status({ signal: options.signal });
735
- options.onStatus?.(status);
584
+ _optionalChain([options, 'access', _58 => _58.onStatus, 'optionalCall', _59 => _59(status)]);
736
585
  if (status.status === "COMPLETED") return this.result({ signal: options.signal });
737
- if (status.status === "FAILED") throw requestFailure(this.requestId, status);
586
+ if (status.status === "FAILED") throw _chunk74UKKBOOcjs.requestFailure.call(void 0, this.requestId, status);
738
587
  const elapsed = Date.now() - started;
739
- if (elapsed >= timeout) throw new InferenceTimeout(this.requestId, elapsed);
588
+ if (elapsed >= timeout) throw new (0, _chunk74UKKBOOcjs.InferenceTimeout)(this.requestId, elapsed);
740
589
  const delay = pollDelay(options.interval, elapsed, DEFAULT_WAIT_INTERVAL_MS);
741
590
  await sleep(Math.min(delay, timeout - elapsed), options.signal);
742
591
  }
@@ -749,7 +598,7 @@ var Job = class {
749
598
  async read(url, signal) {
750
599
  const response = await this.http.fetchRaw({ method: "GET", url, signal, retry: true });
751
600
  if (response.ok) return readJson(response);
752
- const error = await SegmindError.fromResponse(response, this.requestId);
601
+ const error = await _chunk74UKKBOOcjs.SegmindError.fromResponse(response, this.requestId);
753
602
  const body = error.body;
754
603
  if (body && typeof body === "object" && TERMINAL.has(String(body.status))) {
755
604
  return body;
@@ -767,7 +616,7 @@ var PixelFlows = class {
767
616
  constructor(client2) {
768
617
  this.client = client2;
769
618
  }
770
- client;
619
+
771
620
  /** Runs a workflow and waits for its outputs. */
772
621
  async run(slug, inputs = {}, options = {}) {
773
622
  const job2 = await this.submit(slug, inputs, options);
@@ -776,7 +625,7 @@ var PixelFlows = class {
776
625
  /** Starts a workflow and returns a job to wait on. Never retried: a run bills. */
777
626
  async submit(slug, inputs = {}, options = {}) {
778
627
  const clean = slug.trim().replace(/^\/+/, "");
779
- if (!clean) throw new SegmindError("pixelflows: a workflow slug is required");
628
+ if (!clean) throw new (0, _chunk74UKKBOOcjs.SegmindError)("pixelflows: a workflow slug is required");
780
629
  const route = options.engine === "v1" ? "/workflows/" : "/workflows/v2/";
781
630
  const body = await this.client.http.json({
782
631
  method: "POST",
@@ -787,7 +636,7 @@ var PixelFlows = class {
787
636
  });
788
637
  const requestId = body.request_id;
789
638
  if (typeof requestId !== "string" || !requestId) {
790
- throw new SegmindError("pixelflows: the submit response had no request_id", { body });
639
+ throw new (0, _chunk74UKKBOOcjs.SegmindError)("pixelflows: the submit response had no request_id", { body });
791
640
  }
792
641
  return new PixelflowJob(this, requestId);
793
642
  }
@@ -811,8 +660,8 @@ var PixelflowJob = class {
811
660
  this.pixelflows = pixelflows2;
812
661
  this.requestId = requestId;
813
662
  }
814
- pixelflows;
815
- requestId;
663
+
664
+
816
665
  status(options = {}) {
817
666
  return this.pixelflows.getStatus(this.requestId, options);
818
667
  }
@@ -822,16 +671,16 @@ var PixelflowJob = class {
822
671
  * timeout, so `wait()` can be called again.
823
672
  */
824
673
  async wait(options = {}) {
825
- const timeout = options.timeout ?? DEFAULT_TIMEOUT_MS;
674
+ const timeout = _nullishCoalesce(options.timeout, () => ( DEFAULT_TIMEOUT_MS));
826
675
  const started = Date.now();
827
676
  for (; ; ) {
828
677
  const state = await this.status({ signal: options.signal });
829
- options.onStatus?.(state);
678
+ _optionalChain([options, 'access', _60 => _60.onStatus, 'optionalCall', _61 => _61(state)]);
830
679
  if (DONE.has(state.status)) return state;
831
- if (FAILED.has(state.status)) throw requestFailure(this.requestId, state.raw, failureDetail(state.raw));
680
+ if (FAILED.has(state.status)) throw _chunk74UKKBOOcjs.requestFailure.call(void 0, this.requestId, state.raw, failureDetail(state.raw));
832
681
  const elapsed = Date.now() - started;
833
682
  const delay = pollDelay(options.interval, elapsed, DEFAULT_INTERVAL_MS);
834
- if (elapsed + delay > timeout) throw new InferenceTimeout(this.requestId, elapsed);
683
+ if (elapsed + delay > timeout) throw new (0, _chunk74UKKBOOcjs.InferenceTimeout)(this.requestId, elapsed);
835
684
  await sleep(delay, options.signal);
836
685
  }
837
686
  }
@@ -841,10 +690,10 @@ function toStatus(body) {
841
690
  if (typeof raw.output === "string") {
842
691
  try {
843
692
  raw.output = JSON.parse(raw.output);
844
- } catch {
693
+ } catch (e5) {
845
694
  }
846
695
  }
847
- const status = String(raw.status ?? "UNKNOWN").toUpperCase();
696
+ const status = String(_nullishCoalesce(raw.status, () => ( "UNKNOWN"))).toUpperCase();
848
697
  return { status, outputs: DONE.has(status) ? flattenOutputs(raw.output) : {}, raw };
849
698
  }
850
699
  function flattenOutputs(output) {
@@ -866,25 +715,57 @@ function unwrap(value) {
866
715
  return value;
867
716
  }
868
717
  function failureDetail(body) {
869
- const error = body.error_message ?? body.error;
718
+ const error = _nullishCoalesce(body.error_message, () => ( body.error));
870
719
  if (typeof error === "string") return error;
871
720
  if (error && typeof error === "object") {
872
721
  const e = error;
873
- const text = e.details ?? e.error_message ?? e.error;
722
+ const text = _nullishCoalesce(_nullishCoalesce(e.details, () => ( e.error_message)), () => ( e.error));
874
723
  if (typeof text === "string") return text;
875
724
  }
876
725
  return void 0;
877
726
  }
878
727
 
728
+ // src/realtime-tokens.ts
729
+ var Realtime = class {
730
+ constructor(client2) {
731
+ this.client = client2;
732
+ }
733
+
734
+ /**
735
+ * Mints a session token. Serve it from your backend to the app that opens
736
+ * the session with `connect()` from `segmind/realtime`.
737
+ */
738
+ async createToken(options) {
739
+ const body = { slug: options.slug };
740
+ if (options.creditCeiling !== void 0) body.credit_ceiling = options.creditCeiling;
741
+ if (options.ttl !== void 0) body.ttl = options.ttl;
742
+ return this.client.http.json({
743
+ method: "POST",
744
+ url: `${this.client.baseURL}/v1/realtime/token`,
745
+ body,
746
+ headers: options.initiator ? { "X-Initiator": options.initiator } : void 0,
747
+ signal: options.signal,
748
+ retry: true
749
+ });
750
+ }
751
+ /**
752
+ * A `tokenProvider` that mints with this client's key, for opening sessions
753
+ * from a server: `connect(slug, { tokenProvider: segmind.realtime.tokenProvider() })`.
754
+ */
755
+ tokenProvider(options = {}) {
756
+ return (slug) => this.createToken({ ...options, slug });
757
+ }
758
+ };
759
+
879
760
  // src/version.ts
880
- var VERSION = "0.5.0";
761
+ var VERSION = "0.6.0";
881
762
 
882
763
  // src/webhooks.ts
883
764
  var Webhooks = class {
884
765
  constructor(client2) {
885
766
  this.client = client2;
886
767
  }
887
- client;
768
+
888
769
  /** Every registration; `[]` when you have none. */
889
770
  async get(options = {}) {
890
771
  return this.call("GET", "/get", { signal: options.signal, retry: true });
@@ -943,7 +824,7 @@ var Webhooks = class {
943
824
  };
944
825
  function requireTypes(eventTypes) {
945
826
  if (!Array.isArray(eventTypes) || eventTypes.length === 0) {
946
- throw new SegmindError('webhooks: pass at least one event type, e.g. ["PIXELFLOW"]');
827
+ throw new (0, _chunk74UKKBOOcjs.SegmindError)('webhooks: pass at least one event type, e.g. ["PIXELFLOW"]');
947
828
  }
948
829
  return eventTypes;
949
830
  }
@@ -954,42 +835,44 @@ var DEFAULT_SPOT_URL = "https://api.spotprod.segmind.com";
954
835
  var DEFAULT_CONSOLE_URL = "https://cloud.segmind.com/api";
955
836
  var DEFAULT_ASSETS_URL = "https://platform-api.segmind.com";
956
837
  var Segmind = class {
957
- baseURL;
958
- spotURL;
959
- consoleURL;
960
- assetsURL;
961
- models;
962
- accounts;
838
+
839
+
840
+
841
+
842
+
843
+
963
844
  /** Upload files to pass as model inputs. */
964
- files;
845
+
965
846
  /** Your generations and request history. */
966
- generations;
847
+
967
848
  /** Your webhook registrations. */
968
- webhooks;
849
+
969
850
  /** Run published PixelFlow workflows. */
970
- pixelflows;
851
+
852
+ /** Session tokens for realtime models. The sessions themselves open from `segmind/realtime`. */
853
+
971
854
  /** @internal */
972
- http;
855
+
973
856
  constructor(options = {}) {
974
857
  if (options.apiKey && options.tokenProvider) {
975
- throw new SegmindError("Pass either apiKey or tokenProvider, not both.");
858
+ throw new (0, _chunk74UKKBOOcjs.SegmindError)("Pass either apiKey or tokenProvider, not both.");
976
859
  }
977
- const apiKey = options.apiKey ?? (options.tokenProvider ? void 0 : readEnv("SEGMIND_API_KEY"));
860
+ const apiKey = _nullishCoalesce(options.apiKey, () => ( (options.tokenProvider ? void 0 : readEnv("SEGMIND_API_KEY"))));
978
861
  const runtime = detectRuntime();
979
862
  if (apiKey && (runtime === "browser" || runtime === "react-native") && !options.dangerouslyAllowBrowser) {
980
- throw new SegmindError(
863
+ throw new (0, _chunk74UKKBOOcjs.SegmindError)(
981
864
  "An API key in a browser or mobile app exposes it to every user. Call Segmind from your backend instead, or pass dangerouslyAllowBrowser: true if you accept that risk."
982
865
  );
983
866
  }
984
867
  if (!apiKey && !options.tokenProvider) {
985
- throw new SegmindError("Missing API key: pass { apiKey } or set the SEGMIND_API_KEY environment variable.");
868
+ throw new (0, _chunk74UKKBOOcjs.SegmindError)("Missing API key: pass { apiKey } or set the SEGMIND_API_KEY environment variable.");
986
869
  }
987
- const fetchImpl = options.fetch ?? globalThis.fetch?.bind(globalThis);
988
- if (!fetchImpl) throw new SegmindError("No fetch implementation available: pass { fetch }.");
989
- this.baseURL = trimBase(options.baseURL ?? readEnv("SEGMIND_BASE_URL") ?? DEFAULT_BASE_URL);
990
- this.spotURL = trimSlash(options.spotURL ?? DEFAULT_SPOT_URL);
991
- this.consoleURL = trimSlash(options.consoleURL ?? DEFAULT_CONSOLE_URL);
992
- this.assetsURL = trimSlash(options.assetsURL ?? DEFAULT_ASSETS_URL);
870
+ const fetchImpl = _nullishCoalesce(options.fetch, () => ( _optionalChain([globalThis, 'access', _62 => _62.fetch, 'optionalAccess', _63 => _63.bind, 'call', _64 => _64(globalThis)])));
871
+ if (!fetchImpl) throw new (0, _chunk74UKKBOOcjs.SegmindError)("No fetch implementation available: pass { fetch }.");
872
+ this.baseURL = trimBase(_nullishCoalesce(_nullishCoalesce(options.baseURL, () => ( readEnv("SEGMIND_BASE_URL"))), () => ( DEFAULT_BASE_URL)));
873
+ this.spotURL = trimSlash(_nullishCoalesce(options.spotURL, () => ( DEFAULT_SPOT_URL)));
874
+ this.consoleURL = trimSlash(_nullishCoalesce(options.consoleURL, () => ( DEFAULT_CONSOLE_URL)));
875
+ this.assetsURL = trimSlash(_nullishCoalesce(options.assetsURL, () => ( DEFAULT_ASSETS_URL)));
993
876
  const headers = {
994
877
  "X-Initiator": "SDK-JS",
995
878
  ...initiatorHeaders(options),
@@ -1002,8 +885,8 @@ var Segmind = class {
1002
885
  tokenProvider: options.tokenProvider,
1003
886
  onUnauthorized: options.onUnauthorized,
1004
887
  fetch: fetchImpl,
1005
- timeout: options.timeout ?? 6e5,
1006
- maxRetries: options.maxRetries ?? 2,
888
+ timeout: _nullishCoalesce(options.timeout, () => ( 6e5)),
889
+ maxRetries: _nullishCoalesce(options.maxRetries, () => ( 2)),
1007
890
  headers
1008
891
  });
1009
892
  this.models = new Models(this);
@@ -1012,6 +895,7 @@ var Segmind = class {
1012
895
  this.generations = new Generations(this);
1013
896
  this.webhooks = new Webhooks(this);
1014
897
  this.pixelflows = new PixelFlows(this);
898
+ this.realtime = new Realtime(this);
1015
899
  }
1016
900
  /**
1017
901
  * Runs a model and returns its result: submits to the v2 queue, then polls
@@ -1052,7 +936,7 @@ var Segmind = class {
1052
936
  */
1053
937
  job(requestId) {
1054
938
  const clean = requestId.trim();
1055
- if (!clean) throw new SegmindError("A request id is required.");
939
+ if (!clean) throw new (0, _chunk74UKKBOOcjs.SegmindError)("A request id is required.");
1056
940
  const url = `${this.baseURL}/v2/requests/${encodeURIComponent(clean)}`;
1057
941
  return new Job(this.http, {
1058
942
  request_id: clean,
@@ -1078,7 +962,7 @@ var Segmind = class {
1078
962
  async submitJob(slug, params, options, transform) {
1079
963
  const url = `${this.baseURL}/v2/${path(slug)}`;
1080
964
  const maxRetries = this.http.config.maxRetries;
1081
- let requestId = options.requestId ?? randomRequestId();
965
+ let requestId = _nullishCoalesce(options.requestId, () => ( randomRequestId()));
1082
966
  for (let attempt = 0; ; attempt++) {
1083
967
  const canRetry = attempt < maxRetries;
1084
968
  let response;
@@ -1091,7 +975,7 @@ var Segmind = class {
1091
975
  signal: options.signal
1092
976
  });
1093
977
  } catch (err) {
1094
- if (canRetry && err instanceof APIConnectionError) {
978
+ if (canRetry && err instanceof _chunk74UKKBOOcjs.APIConnectionError) {
1095
979
  await sleep(retryDelay(attempt, null), options.signal);
1096
980
  continue;
1097
981
  }
@@ -1100,7 +984,7 @@ var Segmind = class {
1100
984
  if (response.ok || response.status === 409) {
1101
985
  const body = await readJson(response);
1102
986
  if (response.status === 409 && !body.status_url) {
1103
- throw new SegmindError(`409 ${String(body.error ?? "conflict")}`, {
987
+ throw new (0, _chunk74UKKBOOcjs.SegmindError)(`409 ${String(_nullishCoalesce(body.error, () => ( "conflict")))}`, {
1104
988
  status: 409,
1105
989
  requestId,
1106
990
  body
@@ -1109,17 +993,17 @@ var Segmind = class {
1109
993
  return new Job(this.http, onBase(validateSubmit(body, response.status), this.baseURL), transform);
1110
994
  }
1111
995
  if (canRetry && response.status === 503) {
1112
- await response.body?.cancel().catch(() => void 0);
996
+ await _optionalChain([response, 'access', _65 => _65.body, 'optionalAccess', _66 => _66.cancel, 'call', _67 => _67(), 'access', _68 => _68.catch, 'call', _69 => _69(() => void 0)]);
1113
997
  requestId = randomRequestId();
1114
998
  await sleep(retryDelay(attempt, response.headers.get("retry-after")), options.signal);
1115
999
  continue;
1116
1000
  }
1117
1001
  if (canRetry && (response.status === 429 || response.status === 502 || response.status === 504)) {
1118
- await response.body?.cancel().catch(() => void 0);
1002
+ await _optionalChain([response, 'access', _70 => _70.body, 'optionalAccess', _71 => _71.cancel, 'call', _72 => _72(), 'access', _73 => _73.catch, 'call', _74 => _74(() => void 0)]);
1119
1003
  await sleep(retryDelay(attempt, response.headers.get("retry-after")), options.signal);
1120
1004
  continue;
1121
1005
  }
1122
- throw await SegmindError.fromResponse(response, requestId);
1006
+ throw await _chunk74UKKBOOcjs.SegmindError.fromResponse(response, requestId);
1123
1007
  }
1124
1008
  }
1125
1009
  };
@@ -1128,7 +1012,7 @@ var Models = class {
1128
1012
  constructor(client2) {
1129
1013
  this.client = client2;
1130
1014
  }
1131
- client;
1015
+
1132
1016
  /** One page of the catalog. Pass `offset` from the previous page while `has_more` is true. */
1133
1017
  async list(params = {}, options = {}) {
1134
1018
  return this.client.http.json({
@@ -1183,7 +1067,7 @@ var Accounts = class {
1183
1067
  constructor(client2) {
1184
1068
  this.client = client2;
1185
1069
  }
1186
- client;
1070
+
1187
1071
  /** Account details for the API key. */
1188
1072
  async current(options = {}) {
1189
1073
  return this.client.http.json({
@@ -1206,7 +1090,7 @@ var Accounts = class {
1206
1090
  };
1207
1091
  function validateSubmit(body, status) {
1208
1092
  if (!body.request_id || !body.status_url || !body.response_url) {
1209
- throw new SegmindError(
1093
+ throw new (0, _chunk74UKKBOOcjs.SegmindError)(
1210
1094
  `v2 submit returned ${status} without request_id, status_url and response_url (keys: ${Object.keys(body).sort().join(", ")})`,
1211
1095
  { status, body }
1212
1096
  );
@@ -1215,7 +1099,7 @@ function validateSubmit(body, status) {
1215
1099
  }
1216
1100
  function path(slug) {
1217
1101
  const clean = slug.trim().replace(/^\/+/, "");
1218
- if (!clean) throw new SegmindError("A model slug is required.");
1102
+ if (!clean) throw new (0, _chunk74UKKBOOcjs.SegmindError)("A model slug is required.");
1219
1103
  return clean;
1220
1104
  }
1221
1105
  function onBase(body, baseURL) {
@@ -1287,4 +1171,43 @@ var pixelflows = {
1287
1171
  getStatus: (requestId, options) => client().pixelflows.getStatus(requestId, options),
1288
1172
  poll: (requestId, options) => client().pixelflows.poll(requestId, options)
1289
1173
  };
1174
+
1175
+
1176
+
1177
+
1178
+
1179
+
1180
+
1181
+
1182
+
1183
+
1184
+
1185
+
1186
+
1187
+
1188
+
1189
+
1190
+
1191
+
1192
+
1193
+
1194
+
1195
+
1196
+
1197
+
1198
+
1199
+
1200
+
1201
+
1202
+
1203
+
1204
+
1205
+
1206
+
1207
+
1208
+
1209
+
1210
+
1211
+
1212
+ exports.APIConnectionError = _chunk74UKKBOOcjs.APIConnectionError; exports.Accounts = Accounts; exports.ChatResponse = ChatResponse; exports.DEFAULT_BASE_URL = DEFAULT_BASE_URL; exports.DEFAULT_CONSOLE_URL = DEFAULT_CONSOLE_URL; exports.DEFAULT_SPOT_URL = DEFAULT_SPOT_URL; exports.DEFAULT_WAIT_INTERVAL_MS = DEFAULT_WAIT_INTERVAL_MS; exports.DEFAULT_WAIT_TIMEOUT_MS = DEFAULT_WAIT_TIMEOUT_MS; exports.Files = Files; exports.Generations = Generations; exports.InferenceFailed = _chunk74UKKBOOcjs.InferenceFailed; exports.InferenceTimeout = _chunk74UKKBOOcjs.InferenceTimeout; exports.InsufficientCredits = _chunk74UKKBOOcjs.InsufficientCredits; exports.Job = Job; exports.Models = Models; exports.PixelFlows = PixelFlows; exports.PixelflowJob = PixelflowJob; exports.RateLimited = _chunk74UKKBOOcjs.RateLimited; exports.Realtime = Realtime; exports.Segmind = Segmind; exports.SegmindError = _chunk74UKKBOOcjs.SegmindError; exports.VERSION = VERSION; exports.Webhooks = Webhooks; exports.accounts = accounts; exports.chat = chat; exports.chatSync = chatSync; exports.files = files; exports.generations = generations; exports.imageUrl = imageUrl; exports.job = job; exports.models = models; exports.pixelflows = pixelflows; exports.run = run; exports.runSync = runSync; exports.submit = submit; exports.submitChat = submitChat; exports.webhooks = webhooks;
1290
1213
  //# sourceMappingURL=index.cjs.map