@byte_fluffy/nexra-sdk 0.1.0-alpha.3 → 0.1.0-alpha.31

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,930 +1,32 @@
1
+ import {
2
+ ceilDecimal,
3
+ multiplyDecimal
4
+ } from "./chunk-FCH5IQP5.js";
1
5
  import {
2
6
  CatalogClient,
3
7
  HttpTransport,
4
8
  NexraApiError,
5
9
  NexraTaskError,
6
10
  NexraWaitTimeoutError,
11
+ applyMediaGeometry,
12
+ applyNoWatermark,
13
+ decodeMediaGeometry,
14
+ encodeMediaGeometry,
15
+ formatModelDisplayName,
7
16
  getModelSpec,
8
17
  jsonBody,
9
18
  listModelSpecs,
19
+ parseServerSentEvents,
20
+ projectMediaGeometry,
10
21
  queryString,
11
22
  sleep
12
- } from "./chunk-IMJZBLDE.js";
23
+ } from "./chunk-QXEDXMFI.js";
13
24
  import {
14
- ceilDecimal,
15
- multiplyDecimal
16
- } from "./chunk-FCH5IQP5.js";
17
-
18
- // ../contracts/src/assets.ts
19
- var MEDIA_KINDS = [
20
- "image",
21
- "video",
22
- "audio",
23
- "document",
24
- "archive",
25
- "other"
26
- ];
27
-
28
- // ../contracts/src/uploaded-media.ts
29
- function modelUploadRegion(regions) {
30
- return regions.length > 0 && regions.every((region) => /^cn(?:-|$)/.test(region.trim().toLowerCase())) ? "cn" : "global";
31
- }
32
- function uploadedMediaUrl(value, region) {
33
- if (!value.startsWith("https://")) return value;
34
- try {
35
- const url = new URL(value);
36
- if (url.username || url.password || url.port || !["tos.nexra-ai.com", "tos2.nexra-ai.com", "upload.nexra-ai.com"].includes(url.hostname) || !url.pathname.startsWith("/user-assets/") || url.pathname === "/user-assets/") return value;
37
- url.hostname = region === "cn" ? "tos.nexra-ai.com" : "tos2.nexra-ai.com";
38
- return url.href;
39
- } catch {
40
- return value;
41
- }
42
- }
43
- function uploadedMediaInput(input, region) {
44
- const visit = (value) => {
45
- if (typeof value === "string") return uploadedMediaUrl(value, region);
46
- if (Array.isArray(value)) return value.map(visit);
47
- if (value !== null && typeof value === "object") {
48
- return Object.fromEntries(Object.entries(value).map(([key, item]) => [
49
- key,
50
- ["text", "texts", "prompt", "negative_prompt", "negativePrompt"].includes(key) ? item : visit(item)
51
- ]));
52
- }
53
- return value;
54
- };
55
- return visit(input);
56
- }
57
-
58
- // ../contracts/src/admin-usage.ts
59
- var USAGE_SOURCES = ["provider", "estimated", "reconciled"];
60
- var USAGE_NORMALIZATION_STATUSES = [
61
- "normalized",
62
- "partial",
63
- "invalid",
64
- "missing"
65
- ];
66
- var USAGE_RATING_STATUSES = [
67
- "billed",
68
- "unsettled",
69
- "billing_failed",
70
- "unpriced",
71
- "usage_missing"
72
- ];
73
- var USAGE_GROUP_BYS = [
74
- "minute",
75
- "hour",
76
- "day",
77
- "month",
78
- "user",
79
- "apiKey",
80
- "provider",
81
- "channel",
82
- "model",
83
- "operation"
84
- ];
85
- var USAGE_AMOUNT_KINDS = ["sale", "cost", "gross"];
86
- var TOKEN_METRICS = [
87
- "input_tokens",
88
- "cached_input_tokens",
89
- "cache_write_tokens",
90
- "cache_creation_5m_input_tokens",
91
- "cache_creation_1h_input_tokens",
92
- "cache_read_input_tokens",
93
- "output_tokens"
94
- ];
95
- var MONEY_STRING_PATTERN = /^-?(?:0|[1-9]\d*)(?:\.\d{1,8})?$/;
96
- var USAGE_FILTER_SELECTION_LIMIT = 200;
97
- function validateUsageFilters(value) {
98
- if (!isObject(value)) throw new Error("Usage filters must be an object");
99
- const filters = value;
100
- const start = Date.parse(String(filters.start));
101
- const end = Date.parse(String(filters.end));
102
- if (!Number.isFinite(start)) throw new Error("filters.start must be an ISO-8601 instant");
103
- if (!Number.isFinite(end)) throw new Error("filters.end must be an ISO-8601 instant");
104
- if (start >= end) throw new Error("filters.end must be after filters.start ([start, end) window)");
105
- if (filters.timeZoneOffsetMinutes !== void 0 && (!Number.isSafeInteger(filters.timeZoneOffsetMinutes) || filters.timeZoneOffsetMinutes < -720 || filters.timeZoneOffsetMinutes > 840)) {
106
- throw new Error("filters.timeZoneOffsetMinutes must be an integer between -720 and 840");
107
- }
108
- for (const key of ["userIds", "apiKeyIds", "providerIds", "channelIds", "modelIds", "operations", "requestStatuses"]) {
109
- const list = filters[key];
110
- if (list !== void 0 && (!isStringArray(list) || list.length > USAGE_FILTER_SELECTION_LIMIT)) {
111
- throw new Error(`filters.${key} must be at most ${USAGE_FILTER_SELECTION_LIMIT} non-empty strings`);
112
- }
113
- }
114
- if (filters.upstreamModelId !== void 0 && (typeof filters.upstreamModelId !== "string" || filters.upstreamModelId === "")) {
115
- throw new Error("filters.upstreamModelId must be a non-empty string");
116
- }
117
- for (const key of ["usageSources", "normalizationStatuses", "ratingStatuses"]) {
118
- const list = filters[key];
119
- if (list === void 0) continue;
120
- if (!isStringArray(list)) throw new Error(`filters.${key} must be an array of non-empty strings`);
121
- const allowed = key === "usageSources" ? USAGE_SOURCES : key === "normalizationStatuses" ? USAGE_NORMALIZATION_STATUSES : USAGE_RATING_STATUSES;
122
- if (list.some((item) => !allowed.includes(item))) {
123
- throw new Error(`filters.${key} contains an unsupported status`);
124
- }
125
- }
126
- }
127
- function validateUsageSummaryQuery(value) {
128
- if (!isObject(value)) throw new Error("Usage summary query must be an object");
129
- validateUsageFilters(value.filters);
130
- if (!Array.isArray(value.groupBy) || value.groupBy.length === 0) {
131
- throw new Error("groupBy must be a non-empty array");
132
- }
133
- const timeGranularities = value.groupBy.filter(
134
- (key) => ["minute", "hour", "day", "month"].includes(String(key))
135
- );
136
- if (timeGranularities.length > 1) {
137
- throw new Error("groupBy accepts at most one time granularity");
138
- }
139
- const seen = /* @__PURE__ */ new Set();
140
- for (const key of value.groupBy) {
141
- if (!USAGE_GROUP_BYS.includes(String(key))) {
142
- throw new Error(`groupBy contains an unsupported key: ${String(key)}`);
143
- }
144
- if (seen.has(String(key))) throw new Error("groupBy contains duplicate keys");
145
- seen.add(String(key));
146
- }
147
- if (!Number.isSafeInteger(value.limit) || value.limit < 1 || value.limit > 500) {
148
- throw new Error("limit must be an integer between 1 and 500");
149
- }
150
- if (value.cursor !== void 0 && (typeof value.cursor !== "string" || value.cursor === "")) {
151
- throw new Error("cursor must be a non-empty string");
152
- }
153
- }
154
- var CURSOR_PREFIX = "v1.offset.";
155
- function encodeUsageSummaryCursor(offset) {
156
- return `${CURSOR_PREFIX}${offset}`;
157
- }
158
- function parseUsageSummaryCursor(value) {
159
- if (!value.startsWith(CURSOR_PREFIX)) return null;
160
- const offset = Number(value.slice(CURSOR_PREFIX.length));
161
- return Number.isSafeInteger(offset) && offset >= 0 ? offset : null;
162
- }
163
- var KEYSET_CURSOR_PREFIX = "v1.key.";
164
- function encodeUsageKeysetCursor(receivedAt, requestId) {
165
- return `${KEYSET_CURSOR_PREFIX}${encodeURIComponent(receivedAt)}|${encodeURIComponent(requestId)}`;
166
- }
167
- function parseUsageKeysetCursor(value) {
168
- if (!value.startsWith(KEYSET_CURSOR_PREFIX)) return null;
169
- const parts = value.slice(KEYSET_CURSOR_PREFIX.length).split("|");
170
- if (parts.length !== 2 || !parts[0] || !parts[1]) return null;
171
- let receivedAt;
172
- let requestId;
173
- try {
174
- receivedAt = decodeURIComponent(parts[0]);
175
- requestId = decodeURIComponent(parts[1]);
176
- } catch {
177
- return null;
178
- }
179
- if (!/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(requestId)) {
180
- return null;
181
- }
182
- if (!/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,6})?Z$/.test(receivedAt) || !Number.isFinite(Date.parse(receivedAt))) return null;
183
- if (new Date(receivedAt).toISOString().slice(0, 19) !== receivedAt.slice(0, 19)) return null;
184
- return { receivedAt, requestId };
185
- }
186
- function validateUsageDetailsQuery(value) {
187
- if (!isObject(value)) throw new Error("Usage details query must be an object");
188
- validateUsageFilters(value.filters);
189
- if (!Number.isSafeInteger(value.limit) || value.limit < 1 || value.limit > 200) {
190
- throw new Error("limit must be an integer between 1 and 200");
191
- }
192
- if (value.cursor !== void 0 && (typeof value.cursor !== "string" || value.cursor === "")) {
193
- throw new Error("cursor must be a non-empty string");
194
- }
195
- }
196
- var USAGE_ANOMALY_CATEGORIES = [
197
- "usage_missing",
198
- "normalization_failed",
199
- "unpriced",
200
- "dimension_mismatch",
201
- "settlement_failed"
202
- ];
203
- function validateUsageAnomaliesQuery(value) {
204
- if (!isObject(value)) throw new Error("Usage anomalies query must be an object");
205
- validateUsageFilters(value.filters);
206
- if (value.categories !== void 0) {
207
- if (!isStringArray(value.categories) || value.categories.some((item) => !USAGE_ANOMALY_CATEGORIES.includes(item))) {
208
- throw new Error("categories contains an unsupported anomaly category");
209
- }
210
- }
211
- if (!Number.isSafeInteger(value.limit) || value.limit < 1 || value.limit > 200) {
212
- throw new Error("limit must be an integer between 1 and 200");
213
- }
214
- if (value.cursor !== void 0 && (typeof value.cursor !== "string" || value.cursor === "")) {
215
- throw new Error("cursor must be a non-empty string");
216
- }
217
- }
218
- function validateUsageAnomalySummaryQuery(value) {
219
- if (!isObject(value)) throw new Error("Usage anomaly summary query must be an object");
220
- validateUsageFilters(value.filters);
221
- if (value.breakdowns !== void 0) {
222
- if (!Array.isArray(value.breakdowns) || value.breakdowns.length > 2 || value.breakdowns.some((item) => !["provider", "channel", "model"].includes(String(item)))) {
223
- throw new Error("breakdowns accepts at most two of provider, channel, model");
224
- }
225
- }
226
- }
227
- function isObject(value) {
228
- return typeof value === "object" && value !== null && !Array.isArray(value);
229
- }
230
- function isStringArray(value) {
231
- return Array.isArray(value) && value.length > 0 && value.every((item) => typeof item === "string" && item !== "");
232
- }
233
-
234
- // ../contracts/src/admin-users.ts
235
- var ADMIN_USER_ROLES = ["admin", "dealer", "user"];
236
- var ADMIN_USER_STATUSES = ["active", "banned"];
237
- function validateAdminUserListQuery(value) {
238
- if (!isObject2(value)) throw new Error("User list query must be an object");
239
- if (value.query !== void 0 && (typeof value.query !== "string" || value.query.trim() === "" || value.query.length > 320)) {
240
- throw new Error("query must be a non-empty string of at most 320 characters");
241
- }
242
- if (value.role !== void 0 && !ADMIN_USER_ROLES.includes(String(value.role))) {
243
- throw new Error("role is not supported");
244
- }
245
- if (value.status !== void 0 && !ADMIN_USER_STATUSES.includes(String(value.status))) {
246
- throw new Error("status is not supported");
247
- }
248
- if (!Number.isSafeInteger(value.limit) || value.limit < 1 || value.limit > 200) {
249
- throw new Error("limit must be an integer between 1 and 200");
250
- }
251
- if (value.cursor !== void 0 && (typeof value.cursor !== "string" || value.cursor === "")) {
252
- throw new Error("cursor must be a non-empty string");
253
- }
254
- }
255
- var USER_CURSOR_PREFIX = "v1.user.";
256
- function encodeAdminUserCursor(cursor) {
257
- return `${USER_CURSOR_PREFIX}${encodeURIComponent(cursor.createdAt)}|${encodeURIComponent(cursor.userId)}`;
258
- }
259
- function parseAdminUserCursor(value) {
260
- try {
261
- if (!value.startsWith(USER_CURSOR_PREFIX)) return null;
262
- const parts = value.slice(USER_CURSOR_PREFIX.length).split("|");
263
- if (parts.length !== 2) return null;
264
- const [encodedCreatedAt, encodedUserId] = parts;
265
- if (!encodedCreatedAt || !encodedUserId) return null;
266
- const createdAt = decodeURIComponent(encodedCreatedAt);
267
- const userId = decodeURIComponent(encodedUserId);
268
- return Number.isFinite(Date.parse(createdAt)) && userId !== "" ? { createdAt, userId } : null;
269
- } catch {
270
- return null;
271
- }
272
- }
273
- var ADMIN_USER_ACTIVITY_KINDS = ["ledger", "recharge", "hold", "audit"];
274
- function isMoneyString(value) {
275
- return MONEY_STRING_PATTERN.test(value);
276
- }
277
- function validateAdminUserUpdate(value) {
278
- if (!isObject2(value)) throw new Error("User update must be an object");
279
- if (typeof value.reason !== "string" || value.reason.trim() === "" || value.reason.length > 500) {
280
- throw new Error("reason is required (at most 500 characters)");
281
- }
282
- if (value.role !== void 0 && !ADMIN_USER_ROLES.includes(String(value.role))) {
283
- throw new Error("role is not supported");
284
- }
285
- if (value.status !== void 0 && !ADMIN_USER_STATUSES.includes(String(value.status))) {
286
- throw new Error("status is not supported");
287
- }
288
- if (value.qpsLimit !== void 0 && (!Number.isSafeInteger(value.qpsLimit) || value.qpsLimit < 1 || value.qpsLimit > 1e5)) {
289
- throw new Error("qpsLimit must be an integer between 1 and 100000");
290
- }
291
- if (value.role === void 0 && value.status === void 0 && value.qpsLimit === void 0) {
292
- throw new Error("At least one of role, status, or qpsLimit is required");
293
- }
294
- }
295
- function validateAdminUserApiKeyUpdate(value) {
296
- if (!isObject2(value)) throw new Error("API key update must be an object");
297
- if (typeof value.reason !== "string" || value.reason.trim() === "" || value.reason.length > 500) {
298
- throw new Error("reason is required (at most 500 characters)");
299
- }
300
- if (value.revoked !== void 0 && typeof value.revoked !== "boolean") {
301
- throw new Error("revoked must be a boolean");
302
- }
303
- if (value.rateLimitPerSecond !== void 0 && value.rateLimitPerSecond !== null && (!Number.isSafeInteger(value.rateLimitPerSecond) || value.rateLimitPerSecond < 1 || value.rateLimitPerSecond > 1e5)) {
304
- throw new Error("rateLimitPerSecond must be an integer between 1 and 100000, or null");
305
- }
306
- if (value.revoked === void 0 && value.rateLimitPerSecond === void 0) {
307
- throw new Error("At least one of revoked or rateLimitPerSecond is required");
308
- }
309
- }
310
- function validateAdminWalletRechargeInput(value) {
311
- if (!isObject2(value)) throw new Error("Wallet recharge must be an object");
312
- if (typeof value.userId !== "string" || value.userId === "") {
313
- throw new Error("userId is required");
314
- }
315
- if (value.currency !== "CNY") {
316
- throw new Error("currency must be CNY");
317
- }
318
- if (typeof value.amount !== "string" || !isMoneyString(value.amount) || value.amount.startsWith("-") || Number(value.amount) <= 0) {
319
- throw new Error("amount must be a positive decimal string");
320
- }
321
- if ((value.amount.split(".")[0]?.length ?? 0) > 12) {
322
- throw new Error("amount exceeds the 12-digit integer limit of the wallet balance");
323
- }
324
- if (typeof value.externalOrderId !== "string" || value.externalOrderId.trim() === "" || value.externalOrderId.trim().length > 240) {
325
- throw new Error("externalOrderId is required (at most 240 characters)");
326
- }
327
- if (typeof value.reason !== "string" || value.reason.trim() === "" || value.reason.length > 500) {
328
- throw new Error("reason is required (at most 500 characters)");
329
- }
330
- }
331
- function isObject2(value) {
332
- return typeof value === "object" && value !== null && !Array.isArray(value);
333
- }
334
-
335
- // ../contracts/src/usage-filter-options.ts
336
- var USAGE_FILTER_KINDS = ["model", "user", "apiKey", "provider", "channel", "operation"];
337
- var MODEL_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
338
- function validId(kind, id) {
339
- return typeof id === "string" && id.length > 0 && id.length <= 128 && !/[\s,|]/u.test(id) && (kind === "user" || kind === "operation" || MODEL_ID.test(id));
340
- }
341
- function encodeUsageFilterCursor(kind, query, id) {
342
- return `usage-filter-v1|${kind}|${encodeURIComponent(query)}|${encodeURIComponent(id)}`;
343
- }
344
- function parseUsageFilterCursor(value, kind, query) {
345
- try {
346
- const parts = value.split("|");
347
- if (parts.length !== 4 || parts[0] !== "usage-filter-v1" || parts[1] !== kind || decodeURIComponent(parts[2]) !== query) return null;
348
- const id = decodeURIComponent(parts[3]);
349
- return validId(kind, id) ? id : null;
350
- } catch {
351
- return null;
352
- }
353
- }
354
- function validateUsageFilterOptionsQuery(kind, value) {
355
- if (!value || typeof value !== "object") throw new Error("\u7B5B\u9009\u67E5\u8BE2\u683C\u5F0F\u4E0D\u6B63\u786E");
356
- const query = value;
357
- if (!Number.isInteger(query.limit) || query.limit < 1 || query.limit > 100) throw new Error("\u4E00\u6B21\u6700\u591A\u67E5\u8BE2 100 \u9879");
358
- if (query.query !== void 0 && (typeof query.query !== "string" || !query.query.trim() || query.query.length > 320)) throw new Error("\u641C\u7D22\u5185\u5BB9\u5FC5\u987B\u4E3A 1 \u81F3 320 \u4E2A\u5B57\u7B26");
359
- if (query.ids !== void 0) {
360
- if (!Array.isArray(query.ids) || !query.ids.length || query.ids.length > query.limit || query.ids.some((id) => !validId(kind, id))) throw new Error("\u8BF7\u8F93\u5165\u6709\u6548\u7684\u5185\u90E8 ID\uFF0C\u4E00\u6B21\u6700\u591A 100 \u9879");
361
- if (query.query !== void 0 || query.cursor !== void 0) throw new Error("ID \u786E\u8BA4\u4E0D\u80FD\u540C\u65F6\u4F7F\u7528\u641C\u7D22\u6216\u5206\u9875");
362
- }
363
- if (query.cursor !== void 0 && (typeof query.cursor !== "string" || query.cursor.length > 4096 || !parseUsageFilterCursor(query.cursor, kind, query.query ?? ""))) throw new Error("\u5206\u9875\u6E38\u6807\u4E0E\u5F53\u524D\u7B5B\u9009\u4E0D\u5339\u914D");
364
- }
365
-
366
- // ../contracts/src/money.ts
367
- var MONEY_SCALE = 100000000n;
368
- var BILLING_CURRENCY = "CNY";
369
- var WALLET_MAX_BALANCE_UNITS = 99999999999999999999n;
370
- function moneyToUnits(value) {
371
- if (!/^-?\d+(\.\d{1,8})?$/.test(value)) throw new Error("Invalid money amount");
372
- const negative = value.startsWith("-");
373
- const [whole = "0", fraction = ""] = (negative ? value.slice(1) : value).split(".");
374
- const units = BigInt(whole) * MONEY_SCALE + BigInt(fraction.padEnd(8, "0"));
375
- return negative ? -units : units;
376
- }
377
- function moneyFromUnits(value) {
378
- const negative = value < 0n;
379
- const absolute = negative ? -value : value;
380
- const fraction = (absolute % MONEY_SCALE).toString().padStart(8, "0").replace(/0+$/, "");
381
- return `${negative ? "-" : ""}${absolute / MONEY_SCALE}${fraction ? `.${fraction}` : ""}`;
382
- }
383
- function multiplyMoney(value, multiplier, ...additionalMultipliers) {
384
- let product = moneyToUnits(value);
385
- if (product < 0n) throw new Error("Money amount must be non-negative");
386
- let divisor = 1n;
387
- for (const multiplierValue of [multiplier, ...additionalMultipliers]) {
388
- const factor = moneyToUnits(multiplierValue);
389
- if (factor <= 0n) throw new Error("Money multiplier must be positive");
390
- product *= factor;
391
- divisor *= MONEY_SCALE;
392
- }
393
- return moneyFromUnits((product + divisor / 2n) / divisor);
394
- }
395
-
396
- // ../contracts/src/model-schema.ts
397
- function object(value) {
398
- return value !== null && typeof value === "object" && !Array.isArray(value) ? value : {};
399
- }
400
- function normalizeModelParameterSchema(source) {
401
- const result = structuredClone(source);
402
- const input = object(result.input);
403
- const properties = object(input.properties);
404
- const ui = object(result.ui);
405
- const fields = object(ui.fields);
406
- const defaults = object(result.defaults);
407
- const order = Array.isArray(ui.order) ? ui.order : [];
408
- for (const [key, value] of Object.entries(properties)) {
409
- if (!value || typeof value !== "object" || Array.isArray(value)) continue;
410
- const position = order.indexOf(key);
411
- const decoration = {
412
- ...position >= 0 ? { order: position } : {},
413
- ...object(fields[key]),
414
- ...object(value["x-ui"])
415
- };
416
- if (Object.keys(decoration).length) value["x-ui"] = decoration;
417
- if (key in defaults) value.default = defaults[key];
418
- }
419
- delete result.ui;
420
- delete result.defaults;
421
- return result;
422
- }
423
- function modelInputDefaults(input) {
424
- return Object.fromEntries(Object.entries(object(input.properties)).flatMap(([key, value]) => {
425
- const field = object(value);
426
- return "default" in field ? [[key, structuredClone(field.default)]] : [];
427
- }));
428
- }
429
- function orderedSchemaProperties(schema) {
430
- const rank = (value) => {
431
- const order = object(object(value)["x-ui"]).order;
432
- return typeof order === "number" ? order : Number.MAX_SAFE_INTEGER;
433
- };
434
- return Object.entries(object(schema.properties)).sort(([, a], [, b]) => rank(a) - rank(b));
435
- }
436
- function modelInputUi(input) {
437
- const entries = orderedSchemaProperties(input);
438
- return {
439
- order: entries.map(([key]) => key),
440
- fields: Object.fromEntries(entries.flatMap(([key, value]) => {
441
- const { order: _order, ...ui } = object(object(value)["x-ui"]);
442
- return Object.keys(ui).length ? [[key, ui]] : [];
443
- }))
444
- };
445
- }
446
-
447
- // ../contracts/src/pricing.ts
448
- var BILLING_METRICS = [
449
- "requests",
450
- "input_tokens",
451
- "cached_input_tokens",
452
- "cache_write_tokens",
453
- "cache_creation_5m_input_tokens",
454
- "cache_creation_1h_input_tokens",
455
- "cache_read_input_tokens",
456
- "output_tokens",
457
- "input_characters",
458
- "input_utf8_bytes",
459
- "input_images",
460
- "output_images",
461
- "input_audio_seconds",
462
- "output_audio_seconds",
463
- "input_video_seconds",
464
- "output_video_seconds",
465
- "provider_credits",
466
- "web_search_requests"
467
- ];
468
- var BILLING_EXPORT_DIMENSIONS = [
469
- "resolution",
470
- "duration",
471
- "layer_decomposition",
472
- "with_audio",
473
- "has_input_video",
474
- "hd",
475
- "prompt_extend",
476
- "modality",
477
- "tier",
478
- "quality",
479
- "image_count",
480
- "input_token_tier",
481
- "input_modality",
482
- "service_tier",
483
- "inference_geo",
484
- "speed",
485
- "region_scope",
486
- "has_reference_image",
487
- "mode"
488
- ];
489
- function allocateDiscountedPriceLines(lines, saleAmount) {
490
- const moneyPattern = /^(?:0|[1-9]\d*)(?:\.\d{1,8})?$/;
491
- if (!moneyPattern.test(saleAmount) || lines.some((line) => !moneyPattern.test(line.amount))) {
492
- throw new Error("Sale allocation requires non-negative eight-decimal money");
493
- }
494
- const target = priceScaled(saleAmount);
495
- const weights = lines.map((line) => priceScaled(line.amount));
496
- const total = weights.reduce((sum, amount) => sum + amount, 0n);
497
- if (target > total) throw new Error("Discounted sale amount exceeds the frozen line total");
498
- const allocations = weights.map((weight) => total === 0n ? 0n : target * weight / total);
499
- let remainder = target - allocations.reduce((sum, amount) => sum + amount, 0n);
500
- return lines.map((line, index) => {
501
- let amount = allocations[index];
502
- if (weights[index] > 0n && remainder > 0n) {
503
- amount += 1n;
504
- remainder -= 1n;
505
- }
506
- return { ...line, discountedAmount: scaledMoney(amount) };
507
- });
508
- }
509
- function validateNormalizedUsage(value) {
510
- if (!isObject3(value) || value.schemaVersion !== 1 || !Array.isArray(value.components)) {
511
- throw new Error("Normalized usage must use the metered v1 envelope");
512
- }
513
- if (value.billingEvidenceComplete !== void 0 && typeof value.billingEvidenceComplete !== "boolean") {
514
- throw new Error("billingEvidenceComplete must be boolean");
515
- }
516
- if (value.components.length === 0 || value.components.length > 64) {
517
- throw new Error("Normalized usage must contain between 1 and 64 components");
518
- }
519
- const identities = /* @__PURE__ */ new Set();
520
- for (const [index, raw] of value.components.entries()) {
521
- if (!isObject3(raw) || !BILLING_METRICS.includes(raw.metric)) {
522
- throw new Error(`Usage component ${index} has an unsupported billing metric`);
523
- }
524
- if (typeof raw.quantity !== "number" || !Number.isFinite(raw.quantity) || raw.quantity < 0) {
525
- throw new Error(`Usage component ${index} quantity must be non-negative`);
526
- }
527
- if (raw.dimensions !== void 0 && (!isObject3(raw.dimensions) || Object.values(raw.dimensions).some((item) => !isPrimitive(item)))) {
528
- throw new Error(`Usage component ${index} dimensions must contain only scalar values`);
529
- }
530
- const identity = `${String(raw.metric)}:${stableDimensions(raw.dimensions)}`;
531
- if (identities.has(identity)) {
532
- throw new Error(`Usage component ${index} duplicates a metric and dimension set`);
533
- }
534
- identities.add(identity);
535
- }
536
- }
537
- function evaluatePriceRule(ruleValue, usageValue) {
538
- validatePriceRule(ruleValue);
539
- validateNormalizedUsage(usageValue);
540
- const rule = ruleValue;
541
- const usage = usageValue;
542
- if (usage.billingEvidenceComplete === false) {
543
- return { status: "incomplete", amount: "0", lines: [], issues: [{ code: "missing_usage", metric: "input_tokens", componentIndex: 0 }] };
544
- }
545
- const lines = [];
546
- const issues = [];
547
- let total = 0n;
548
- for (const [componentIndex, component] of usage.components.entries()) {
549
- const metricRates = rule.rates.filter((rate2) => rate2.metric === component.metric);
550
- if (metricRates.length === 0) continue;
551
- const matching = metricRates.filter((rate2) => dimensionsMatch(
552
- rate2.dimensions,
553
- component.dimensions
554
- ));
555
- if (matching.length === 0) {
556
- if (component.quantity === 0) continue;
557
- issues.push({ code: "dimension_mismatch", metric: component.metric, componentIndex });
558
- continue;
559
- }
560
- const specificity = Math.max(...matching.map((rate2) => Object.keys(rate2.dimensions ?? {}).length));
561
- const selected = matching.filter((rate2) => Object.keys(rate2.dimensions ?? {}).length === specificity);
562
- if (selected.length !== 1) {
563
- if (component.quantity === 0) continue;
564
- issues.push({ code: "ambiguous_rate", metric: component.metric, componentIndex });
565
- continue;
566
- }
567
- const rate = selected[0];
568
- const amount = rateAmount(component.quantity, rate);
569
- total += amount;
570
- lines.push({
571
- metric: component.metric,
572
- quantity: component.quantity,
573
- unitSize: rate.unitSize,
574
- unitPrice: rate.unitPrice,
575
- rounding: rate.rounding,
576
- includedQuantity: rate.includedQuantity ?? 0,
577
- ...rate.dimensions ? { dimensions: { ...rate.dimensions } } : {},
578
- amount: scaledMoney(amount),
579
- ...component.evidence ? { evidence: structuredClone(component.evidence) } : {}
580
- });
581
- }
582
- return {
583
- status: issues.length === 0 ? "rated" : "incomplete",
584
- amount: scaledMoney(total),
585
- lines,
586
- issues
587
- };
588
- }
589
- function validatePriceRule(value) {
590
- if (!isObject3(value) || value.schemaVersion !== 1 || value.type !== "metered") {
591
- throw new Error("Price rule must use the metered v1 envelope");
592
- }
593
- if (!Array.isArray(value.rates) || value.rates.length === 0 || value.rates.length > 32) {
594
- throw new Error("Price rule must contain between 1 and 32 rates");
595
- }
596
- const identities = /* @__PURE__ */ new Set();
597
- for (const [index, raw] of value.rates.entries()) {
598
- if (!isObject3(raw) || !BILLING_METRICS.includes(raw.metric)) {
599
- throw new Error(`Price rate ${index} has an unsupported billing metric`);
600
- }
601
- if (!Number.isSafeInteger(raw.unitSize) || raw.unitSize <= 0) {
602
- throw new Error(`Price rate ${index} unitSize must be a positive integer`);
603
- }
604
- if (typeof raw.unitPrice !== "string" || !/^(?:0|[1-9]\d*)(?:\.\d{1,8})?$/.test(raw.unitPrice)) {
605
- throw new Error(`Price rate ${index} unitPrice must be a non-negative decimal string`);
606
- }
607
- if (!["proportional", "ceil"].includes(String(raw.rounding))) {
608
- throw new Error(`Price rate ${index} has an unsupported rounding mode`);
609
- }
610
- if (raw.includedQuantity !== void 0 && (typeof raw.includedQuantity !== "number" || !Number.isFinite(raw.includedQuantity) || raw.includedQuantity < 0)) {
611
- throw new Error(`Price rate ${index} includedQuantity must be non-negative`);
612
- }
613
- if (raw.dimensions !== void 0 && (!isObject3(raw.dimensions) || Object.values(raw.dimensions).some((item) => !isPrimitive(item)))) {
614
- throw new Error(`Price rate ${index} dimensions must contain only scalar values`);
615
- }
616
- const identity = `${String(raw.metric)}:${stableDimensions(raw.dimensions)}`;
617
- if (identities.has(identity)) {
618
- throw new Error(`Price rate ${index} duplicates a metric and dimension set`);
619
- }
620
- identities.add(identity);
621
- }
622
- }
623
- function isObject3(value) {
624
- return typeof value === "object" && value !== null && !Array.isArray(value);
625
- }
626
- function isPrimitive(value) {
627
- return value === null || ["string", "number", "boolean"].includes(typeof value);
628
- }
629
- function stableDimensions(value) {
630
- if (!isObject3(value)) return "";
631
- return Object.entries(value).sort(([left], [right]) => left.localeCompare(right)).map(([key, item]) => `${JSON.stringify(key)}:${JSON.stringify(item)}`).join(",");
632
- }
633
- var MONEY_SCALE2 = 100000000n;
634
- function dimensionsMatch(expected, actual) {
635
- return Object.entries(expected ?? {}).every(([key, value]) => actual?.[key] === value);
636
- }
637
- function rateAmount(quantity, rate) {
638
- const quantityFraction = subtractFractions(
639
- numberFraction(quantity),
640
- numberFraction(rate.includedQuantity ?? 0)
641
- );
642
- if (quantityFraction.numerator <= 0n) return 0n;
643
- const price = priceScaled(rate.unitPrice);
644
- const unitDenominator = quantityFraction.denominator * BigInt(rate.unitSize);
645
- if (rate.rounding === "ceil") {
646
- const units = divideCeil(quantityFraction.numerator, unitDenominator);
647
- return units * price;
648
- }
649
- return divideHalfUp(quantityFraction.numerator * price, unitDenominator);
650
- }
651
- function priceScaled(value) {
652
- const [whole = "0", fraction = ""] = value.split(".");
653
- return BigInt(whole) * MONEY_SCALE2 + BigInt((fraction + "00000000").slice(0, 8));
654
- }
655
- function scaledMoney(value) {
656
- const whole = value / MONEY_SCALE2;
657
- const fraction = (value % MONEY_SCALE2).toString().padStart(8, "0").replace(/0+$/, "");
658
- return fraction ? `${whole}.${fraction}` : whole.toString();
659
- }
660
- function numberFraction(value) {
661
- const [mantissa, exponentText] = value.toString().toLowerCase().split("e");
662
- const exponent = exponentText ? Number(exponentText) : 0;
663
- const [whole = "0", fraction = ""] = mantissa.split(".");
664
- const digits = `${whole}${fraction}`.replace(/^\+/, "");
665
- const decimalPlaces = fraction.length - exponent;
666
- if (decimalPlaces <= 0) {
667
- return { numerator: BigInt(digits) * 10n ** BigInt(-decimalPlaces), denominator: 1n };
668
- }
669
- return { numerator: BigInt(digits), denominator: 10n ** BigInt(decimalPlaces) };
670
- }
671
- function subtractFractions(left, right) {
672
- return {
673
- numerator: left.numerator * right.denominator - right.numerator * left.denominator,
674
- denominator: left.denominator * right.denominator
675
- };
676
- }
677
- function divideCeil(numerator, denominator) {
678
- return (numerator + denominator - 1n) / denominator;
679
- }
680
- function divideHalfUp(numerator, denominator) {
681
- return (numerator * 2n + denominator) / (denominator * 2n);
682
- }
683
-
684
- // ../contracts/src/metering.ts
685
- function validateMeteringContract(value) {
686
- if (!isObject4(value) || value.schemaVersion !== 1 || !isMeteringKind(value.kind)) {
687
- throw new Error("Metering contract must use schemaVersion 1 and a supported kind");
688
- }
689
- if (!Array.isArray(value.metrics) || value.metrics.length === 0 || value.metrics.length > BILLING_METRICS.length) {
690
- throw new Error("Metering contract must contain supported metrics");
691
- }
692
- const seen = /* @__PURE__ */ new Set();
693
- for (const entry of value.metrics) {
694
- if (!isObject4(entry) || !BILLING_METRICS.includes(entry.metric)) {
695
- throw new Error("Metering contract has an unsupported metric");
696
- }
697
- if (typeof entry.requirement !== "string" || !["required", "conditional", "informational"].includes(entry.requirement)) {
698
- throw new Error("Metering metric has an unsupported requirement");
699
- }
700
- if (seen.has(String(entry.metric))) throw new Error("Metering contract duplicates a metric");
701
- seen.add(String(entry.metric));
702
- if (entry.requirement === "conditional") {
703
- if (typeof entry.whenFeature !== "string" || !entry.whenFeature.trim()) {
704
- throw new Error("Conditional metric requires whenFeature");
705
- }
706
- } else if ("whenFeature" in entry) {
707
- throw new Error("Only conditional metrics may declare whenFeature");
708
- }
709
- }
710
- }
711
- function assessUsageEvidence(contract, usage, features = {}) {
712
- const result = {
713
- kind: "unknown",
714
- evidenceStatus: "invalid",
715
- expectedMetrics: [],
716
- observedMetrics: [],
717
- missingMetrics: [],
718
- issues: []
719
- };
720
- if (contract === void 0 || contract === null) {
721
- result.issues.push("contract_unknown");
722
- return result;
723
- }
724
- try {
725
- validateMeteringContract(contract);
726
- } catch (error) {
727
- result.issues.push(`contract_invalid:${errorMessage(error)}`);
728
- return result;
729
- }
730
- result.kind = contract.kind;
731
- for (const entry of contract.metrics) {
732
- if (entry.requirement === "required") result.expectedMetrics.push(entry.metric);
733
- if (entry.requirement === "conditional") {
734
- const feature = entry.whenFeature;
735
- if (!Object.hasOwn(features, feature) || typeof features[feature] !== "boolean") {
736
- result.issues.push(`condition_unknown:${feature}`);
737
- } else if (features[feature]) {
738
- result.expectedMetrics.push(entry.metric);
739
- }
740
- }
741
- }
742
- if (result.issues.length > 0) return result;
743
- let explicitlyIncomplete = false;
744
- if (usage !== void 0 && usage !== null) {
745
- try {
746
- if (!isObject4(usage) || usage.schemaVersion !== 1 || !Array.isArray(usage.components)) {
747
- throw new Error("Normalized usage must use the metered v1 envelope");
748
- }
749
- if (usage.billingEvidenceComplete !== void 0 && typeof usage.billingEvidenceComplete !== "boolean") {
750
- throw new Error("billingEvidenceComplete must be boolean");
751
- }
752
- if (usage.components.length > 0) validateNormalizedUsage(usage);
753
- const observed = /* @__PURE__ */ new Set();
754
- for (const component of usage.components) {
755
- if (!component.metric.endsWith("_seconds") && component.metric !== "provider_credits" && !Number.isSafeInteger(component.quantity)) {
756
- throw new Error(`Quantity for ${component.metric} must be a safe integer`);
757
- }
758
- if (Object.values(component.dimensions ?? {}).some((value) => typeof value === "number" && !Number.isFinite(value))) {
759
- throw new Error("Usage dimensions must contain finite numeric values");
760
- }
761
- observed.add(component.metric);
762
- }
763
- result.observedMetrics = [...observed];
764
- explicitlyIncomplete = usage.billingEvidenceComplete === false;
765
- } catch (error) {
766
- result.issues.push(`usage_invalid:${errorMessage(error)}`);
767
- return result;
768
- }
769
- }
770
- result.missingMetrics = result.expectedMetrics.filter((metric) => !result.observedMetrics.includes(metric));
771
- if (explicitlyIncomplete) result.issues.push("billing_evidence_incomplete");
772
- result.evidenceStatus = result.expectedMetrics.length === 0 ? "not_expected" : result.missingMetrics.length === result.expectedMetrics.length ? "missing" : result.missingMetrics.length > 0 || explicitlyIncomplete ? "partial" : "complete";
773
- return result;
774
- }
775
- function isObject4(value) {
776
- return value !== null && typeof value === "object" && !Array.isArray(value);
777
- }
778
- function isMeteringKind(value) {
779
- return value === "token" || value === "non_token" || value === "mixed";
780
- }
781
- function errorMessage(error) {
782
- return error instanceof Error ? error.message : String(error);
783
- }
784
-
785
- // ../contracts/src/tasks.ts
786
- var TASK_STATUSES = [
787
- "queued",
788
- "running",
789
- "succeeded",
790
- "failed",
791
- "cancelling",
792
- "cancelled"
793
- ];
794
- function taskReceipt(task) {
795
- return { id: task.id, status: task.status };
796
- }
797
- function taskResult(task) {
798
- return {
799
- id: task.id,
800
- model: task.model,
801
- status: task.status,
802
- ...task.assets.length ? { assets: task.assets } : {},
803
- ...task.requestId ? { requestId: task.requestId } : {},
804
- ...task.output !== void 0 ? { output: task.output } : {},
805
- ...task.error ? { error: task.error } : {},
806
- ...task.deliveryStatus ? { deliveryStatus: task.deliveryStatus } : {},
807
- ...task.settlement ? { settlement: task.settlement } : {}
808
- };
809
- }
810
- function isTerminalTaskStatus(status) {
811
- return status === "succeeded" || status === "failed" || status === "cancelled";
812
- }
813
-
814
- // ../contracts/src/monitoring.ts
815
- function defaultProbeInterval(kind, model) {
816
- if (/music/i.test(model)) return 172800;
817
- if (kind === "audio" && /sound/i.test(model)) return 86400;
818
- return ["language", "embedding", "audio"].includes(kind) ? 3600 : 86400;
819
- }
820
- function defaultProbeTimeout(kind) {
821
- return ["video", "world"].includes(kind) ? 1800 : ["image", "audio"].includes(kind) ? 300 : 120;
822
- }
823
- function classifyObservation(status, httpStatus, code = "") {
824
- if (/cancel|client_disconnect|invalid_input|validation_error/i.test(code) || status === "cancelled")
825
- return "excluded";
826
- if (httpStatus === 429) return "rate_limited";
827
- if (httpStatus === 403 && /geo|region|location|country/i.test(code))
828
- return "restricted";
829
- if (/auth|api.?key|balance|credit|quota_exhaust|model.*(not.?found|not.?exist)|invalid_model/i.test(
830
- code
831
- ))
832
- return "failure";
833
- if ([400, 413, 422].includes(httpStatus ?? 0)) return "excluded";
834
- if (status === "failed" || status === "rejected" || httpStatus !== null && httpStatus >= 400 || /error|incomplete|truncat/i.test(code))
835
- return "failure";
836
- return status === "succeeded" ? "success" : "excluded";
837
- }
838
- var sampleCount = (items) => items.reduce((n, x) => n + (x.count ?? 1), 0);
839
- function availabilityStats(items) {
840
- const success = sampleCount(items.filter((x) => x.result === "success")), failure = sampleCount(items.filter((x) => x.result === "failure"));
841
- return {
842
- success,
843
- failure,
844
- excluded: sampleCount(items.filter((x) => x.result === "excluded")),
845
- rateLimited: sampleCount(items.filter((x) => x.result === "rate_limited")),
846
- restricted: sampleCount(items.filter((x) => x.result === "restricted")),
847
- rate: success + failure ? success / (success + failure) : null
848
- };
849
- }
850
- function availabilityBuckets(items, end, hours, intervalSeconds, core = false) {
851
- const endMs = end.getTime(), first = Math.floor(endMs / 36e5) * 36e5 - (hours - 1) * 36e5;
852
- const sorted = items.filter(
853
- (x) => Number.isFinite(Date.parse(x.at)) && Date.parse(x.at) <= endMs
854
- ).slice().sort((a, b) => Date.parse(a.at) - Date.parse(b.at));
855
- const grace = Math.min(3600, Math.max(300, intervalSeconds * 0.1)) * 1e3;
856
- let cursor = 0;
857
- let prior;
858
- return Array.from({ length: hours }, (_, i) => {
859
- const start = first + i * 36e5, stop = Math.min(start + 36e5, endMs);
860
- const valid = [];
861
- while (cursor < sorted.length && (Date.parse(sorted[cursor].at) < stop || i === hours - 1 && Date.parse(sorted[cursor].at) === endMs)) {
862
- const item = sorted[cursor++];
863
- if (item.result !== "success" && item.result !== "failure") continue;
864
- prior = item;
865
- if (Date.parse(item.at) >= start) valid.push(item);
866
- }
867
- const s = sampleCount(valid.filter((x) => x.result === "success")), f = sampleCount(valid) - s;
868
- const fresh = prior && stop - Date.parse(prior.at) <= intervalSeconds * 1e3 + grace;
869
- const state = valid.length ? s && f ? "mixed" : s ? "success" : "failure" : !core && fresh ? prior.result : "unknown";
870
- const expected = core ? Math.ceil((stop - start) / 3e4) : null;
871
- return {
872
- start: new Date(start).toISOString(),
873
- end: new Date(stop).toISOString(),
874
- state,
875
- evidence: valid.length ? "measured" : !core && fresh ? "carried" : prior ? "expired" : "none",
876
- businessSuccess: sampleCount(
877
- valid.filter((x) => x.source === "business" && x.result === "success")
878
- ),
879
- businessFailure: sampleCount(
880
- valid.filter((x) => x.source === "business" && x.result === "failure")
881
- ),
882
- probeSuccess: sampleCount(
883
- valid.filter((x) => x.source === "probe" && x.result === "success")
884
- ),
885
- probeFailure: sampleCount(
886
- valid.filter((x) => x.source === "probe" && x.result === "failure")
887
- ),
888
- coreSuccess: sampleCount(
889
- valid.filter((x) => x.source === "core" && x.result === "success")
890
- ),
891
- coreFailure: sampleCount(
892
- valid.filter((x) => x.source === "core" && x.result === "failure")
893
- ),
894
- latestAt: prior?.at ?? null,
895
- expectedSamples: expected,
896
- incomplete: expected !== null && sampleCount(valid) < expected
897
- };
898
- });
899
- }
900
- function rateProbeUsage(price, usage) {
901
- if (!usage || !Array.isArray(usage.components) || !usage.components.length)
902
- return void 0;
903
- try {
904
- validatePriceRule(price);
905
- const metrics = new Set(
906
- usage.components.flatMap(
907
- (c) => c && typeof c === "object" && !Array.isArray(c) && typeof c.metric === "string" ? [c.metric] : []
908
- )
909
- );
910
- if (price.rates.some(
911
- (r) => !/^cache|cached_|web_search/.test(r.metric) && !metrics.has(r.metric)
912
- ))
913
- return void 0;
914
- const e = evaluatePriceRule(price, usage);
915
- return e.status === "rated" && e.lines.length > 0 ? e.amount : void 0;
916
- } catch {
917
- return void 0;
918
- }
919
- }
920
- function probeCostExceeds(actual, limit) {
921
- const units = (value) => {
922
- if (!/^\d+(\.\d{1,8})?$/.test(value)) throw new Error("invalid_probe_cost");
923
- const [whole, fraction = ""] = value.split(".");
924
- return BigInt(whole) * 100000000n + BigInt(fraction.padEnd(8, "0"));
925
- };
926
- return units(actual) > units(limit);
927
- }
25
+ MEDIA_KINDS,
26
+ TASK_STATUSES,
27
+ createTaskRequest,
28
+ isTerminalTaskStatus
29
+ } from "./chunk-QBW7OCT3.js";
928
30
 
929
31
  // src/assets.ts
930
32
  var AssetsClient = class {
@@ -962,6 +64,38 @@ var AssetsClient = class {
962
64
  signal
963
65
  });
964
66
  }
67
+ certifyForSeedance(asset, request = {}, signal) {
68
+ const assetId = typeof asset === "string" ? asset : asset.id;
69
+ return this.transport.json(
70
+ `/assets/${encodeURIComponent(assetId)}/certifications/seedance`,
71
+ {
72
+ method: "POST",
73
+ ...jsonBody(request),
74
+ signal
75
+ },
76
+ { retryable: false }
77
+ );
78
+ }
79
+ getSeedanceCertification(asset, signal) {
80
+ const assetId = typeof asset === "string" ? asset : asset.id;
81
+ return this.transport.json(
82
+ `/assets/${encodeURIComponent(assetId)}/certifications/seedance`,
83
+ { signal }
84
+ );
85
+ }
86
+ async waitForSeedanceCertification(asset, options = {}) {
87
+ const pollIntervalMs = positiveInteger(options.pollIntervalMs ?? 2e3, "pollIntervalMs");
88
+ const timeoutMs = positiveInteger(options.timeoutMs ?? 3e5, "timeoutMs");
89
+ const deadline = Date.now() + timeoutMs;
90
+ while (true) {
91
+ const certification = await this.getSeedanceCertification(asset, options.signal);
92
+ if (certification.status !== "processing") return certification;
93
+ if (Date.now() >= deadline) {
94
+ throw new Error("Timed out waiting for Seedance Asset certification");
95
+ }
96
+ await wait(Math.min(pollIntervalMs, Math.max(1, deadline - Date.now())), options.signal);
97
+ }
98
+ }
965
99
  download(asset, signal) {
966
100
  const assetId = typeof asset === "string" ? asset : asset.id;
967
101
  return this.transport.response(`/assets/${encodeURIComponent(assetId)}/content`, {
@@ -974,6 +108,20 @@ var AssetsClient = class {
974
108
  return response.body;
975
109
  }
976
110
  };
111
+ function positiveInteger(value, name) {
112
+ if (!Number.isSafeInteger(value) || value < 1) throw new TypeError(`${name} must be a positive integer`);
113
+ return value;
114
+ }
115
+ async function wait(milliseconds, signal) {
116
+ if (signal?.aborted) throw signal.reason;
117
+ await new Promise((resolve, reject) => {
118
+ const timer = setTimeout(resolve, milliseconds);
119
+ signal?.addEventListener("abort", () => {
120
+ clearTimeout(timer);
121
+ reject(signal.reason);
122
+ }, { once: true });
123
+ });
124
+ }
977
125
  function inferKind(mimeType) {
978
126
  if (mimeType.startsWith("image/")) return "image";
979
127
  if (mimeType.startsWith("video/")) return "video";
@@ -987,13 +135,16 @@ function isFile(value) {
987
135
  }
988
136
 
989
137
  // src/models.ts
138
+ function withModelDisplayName(model) {
139
+ return { ...model, displayName: formatModelDisplayName(model.displayName) };
140
+ }
990
141
  var ModelsClient = class {
991
142
  constructor(transport) {
992
143
  this.transport = transport;
993
144
  }
994
145
  transport;
995
- search(params = {}, signal) {
996
- return this.transport.json(
146
+ async search(params = {}, signal) {
147
+ const page = await this.transport.json(
997
148
  `/models${queryString({
998
149
  q: params.query,
999
150
  modality: params.modality,
@@ -1004,11 +155,16 @@ var ModelsClient = class {
1004
155
  })}`,
1005
156
  { signal }
1006
157
  );
158
+ return { ...page, data: page.data.map(withModelDisplayName) };
1007
159
  }
1008
- get(model, signal) {
1009
- return this.transport.json(`/models/${encodeURIComponent(model)}`, {
160
+ async get(model, signal) {
161
+ const detail = await this.transport.json(`/models/${encodeURIComponent(model)}`, {
1010
162
  signal
1011
163
  });
164
+ return {
165
+ ...withModelDisplayName(detail),
166
+ ...detail.familyVersions ? { familyVersions: detail.familyVersions.map(withModelDisplayName) } : {}
167
+ };
1012
168
  }
1013
169
  schema(model, signal) {
1014
170
  return this.transport.json(
@@ -1016,6 +172,36 @@ var ModelsClient = class {
1016
172
  { signal }
1017
173
  );
1018
174
  }
175
+ resources(model, resource, signal) {
176
+ return this.transport.json(
177
+ `/models/${encodeURIComponent(model)}/resources/${encodeURIComponent(resource)}`,
178
+ { signal }
179
+ );
180
+ }
181
+ };
182
+
183
+ // src/voices.ts
184
+ var VoicesClient = class {
185
+ constructor(transport) {
186
+ this.transport = transport;
187
+ }
188
+ transport;
189
+ async list(signal) {
190
+ const response = await this.transport.json("/voices", { signal });
191
+ return response.data;
192
+ }
193
+ get(voiceId, signal) {
194
+ return this.transport.json(`/voices/${encodeURIComponent(voiceId)}`, { signal });
195
+ }
196
+ create(request, options) {
197
+ if (!options.idempotencyKey.trim()) throw new TypeError("Idempotency-Key is required");
198
+ return this.transport.json("/voices", {
199
+ method: "POST",
200
+ ...jsonBody(request),
201
+ headers: { "content-type": "application/json", "idempotency-key": options.idempotencyKey },
202
+ signal: options.signal
203
+ }, { retryable: true });
204
+ }
1019
205
  };
1020
206
 
1021
207
  // src/input.ts
@@ -1079,55 +265,6 @@ function isMediaAsset(value) {
1079
265
  return isPlainObject(value) && typeof value.id === "string" && typeof value.kind === "string" && typeof value.status === "string" && typeof value.source === "string";
1080
266
  }
1081
267
 
1082
- // src/sse.ts
1083
- async function* parseServerSentEvents(response) {
1084
- if (!response.body) throw new Error("SSE response did not contain a body");
1085
- const reader = response.body.getReader();
1086
- const decoder = new TextDecoder();
1087
- let buffer = "";
1088
- let current = emptyEvent();
1089
- while (true) {
1090
- const { value, done } = await reader.read();
1091
- buffer += decoder.decode(value, { stream: !done });
1092
- const lines = buffer.split(/\r?\n/);
1093
- buffer = done ? "" : lines.pop() ?? "";
1094
- for (const line of lines) {
1095
- if (line === "") {
1096
- const event = buildEvent(current);
1097
- current = emptyEvent();
1098
- if (event) yield event;
1099
- continue;
1100
- }
1101
- if (line.startsWith(":")) continue;
1102
- const separator = line.indexOf(":");
1103
- const field = separator === -1 ? line : line.slice(0, separator);
1104
- let content = separator === -1 ? "" : line.slice(separator + 1);
1105
- if (content.startsWith(" ")) content = content.slice(1);
1106
- if (field === "data") current.data.push(content);
1107
- else if (field === "event") current.event = content;
1108
- else if (field === "id") current.id = content;
1109
- else if (field === "retry") current.retry = Number(content);
1110
- }
1111
- if (done) {
1112
- const event = buildEvent(current);
1113
- if (event) yield event;
1114
- return;
1115
- }
1116
- }
1117
- }
1118
- function emptyEvent() {
1119
- return { data: [] };
1120
- }
1121
- function buildEvent(pending) {
1122
- if (pending.data.length === 0) return void 0;
1123
- return {
1124
- id: pending.id,
1125
- event: pending.event,
1126
- retry: Number.isFinite(pending.retry) ? pending.retry : void 0,
1127
- data: pending.data.join("\n")
1128
- };
1129
- }
1130
-
1131
268
  // src/tasks.ts
1132
269
  var TasksClient = class {
1133
270
  constructor(transport, assets) {
@@ -1136,18 +273,18 @@ var TasksClient = class {
1136
273
  }
1137
274
  transport;
1138
275
  assets;
1139
- async create(model, options) {
1140
- const input = await normalizeTaskInput(options.input, this.assets, options.signal);
1141
- const body = {
1142
- model,
1143
- input,
276
+ async create(model, input, options = {}) {
277
+ const schema = getModelSpec(model)?.operations[0]?.inputSchema;
278
+ const mapped = schema && input && typeof input === "object" && !Array.isArray(input) ? applyNoWatermark(schema, applyMediaGeometry(schema, input)) : input;
279
+ const normalizedInput = await normalizeTaskInput(mapped, this.assets, options.signal);
280
+ const body = createTaskRequest(model, normalizedInput, {
1144
281
  quoteToken: options.quoteToken,
1145
282
  submittedAt: options.submittedAt,
1146
283
  metadata: options.metadata,
1147
284
  callback_url: options.callback_url,
1148
285
  webhook: options.webhook,
1149
286
  schemaVersion: options.schemaVersion
1150
- };
287
+ });
1151
288
  const idempotencyKey = options.idempotencyKey ?? crypto.randomUUID();
1152
289
  return this.transport.json(
1153
290
  "/tasks",
@@ -1206,7 +343,9 @@ var TasksClient = class {
1206
343
  const event = JSON.parse(serverEvent.data);
1207
344
  yield event;
1208
345
  if (event.status && isTerminalTaskStatus(event.status)) {
1209
- reachedTerminalState = true;
346
+ const task = event.payload?.task;
347
+ const deliveryPreparing = task && typeof task === "object" && !Array.isArray(task) && task.deliveryStatus === "preparing";
348
+ if (!deliveryPreparing) reachedTerminalState = true;
1210
349
  }
1211
350
  }
1212
351
  if (reachedTerminalState) return;
@@ -1251,8 +390,8 @@ var TasksClient = class {
1251
390
  if (timeout) clearTimeout(timeout);
1252
391
  }
1253
392
  }
1254
- async run(model, options) {
1255
- const task = await this.create(model, options);
393
+ async run(model, input, options = {}) {
394
+ const task = await this.create(model, input, options);
1256
395
  let completed;
1257
396
  try {
1258
397
  completed = await this.wait(task.id, options);
@@ -1286,15 +425,17 @@ var NexraClient = class {
1286
425
  catalog;
1287
426
  models;
1288
427
  tasks;
428
+ voices;
1289
429
  constructor(options = {}) {
1290
430
  const transport = new HttpTransport(options);
1291
431
  this.assets = new AssetsClient(transport);
1292
432
  this.catalog = new CatalogClient(transport);
1293
433
  this.models = new ModelsClient(transport);
1294
434
  this.tasks = new TasksClient(transport, this.assets);
435
+ this.voices = new VoicesClient(transport);
1295
436
  }
1296
- run(model, options) {
1297
- return this.tasks.run(model, options);
437
+ run(model, input, options = {}) {
438
+ return this.tasks.run(model, input, options);
1298
439
  }
1299
440
  };
1300
441
  function createNexra(options = {}) {
@@ -1343,86 +484,27 @@ function timingSafeEqual(left, right) {
1343
484
  return difference === 0;
1344
485
  }
1345
486
  export {
1346
- ADMIN_USER_ACTIVITY_KINDS,
1347
- ADMIN_USER_ROLES,
1348
- ADMIN_USER_STATUSES,
1349
487
  AssetsClient,
1350
- BILLING_CURRENCY,
1351
- BILLING_EXPORT_DIMENSIONS,
1352
- BILLING_METRICS,
1353
488
  CatalogClient,
1354
- HttpTransport,
1355
489
  MEDIA_KINDS,
1356
- MONEY_STRING_PATTERN,
1357
490
  ModelsClient,
1358
491
  NexraApiError,
1359
492
  NexraClient,
1360
493
  NexraTaskError,
1361
494
  NexraWaitTimeoutError,
1362
495
  TASK_STATUSES,
1363
- TOKEN_METRICS,
1364
496
  TasksClient,
1365
- USAGE_AMOUNT_KINDS,
1366
- USAGE_ANOMALY_CATEGORIES,
1367
- USAGE_FILTER_KINDS,
1368
- USAGE_FILTER_SELECTION_LIMIT,
1369
- USAGE_GROUP_BYS,
1370
- USAGE_NORMALIZATION_STATUSES,
1371
- USAGE_RATING_STATUSES,
1372
- USAGE_SOURCES,
1373
- WALLET_MAX_BALANCE_UNITS,
1374
- allocateDiscountedPriceLines,
1375
- assessUsageEvidence,
1376
- availabilityBuckets,
1377
- availabilityStats,
497
+ VoicesClient,
498
+ applyMediaGeometry,
1378
499
  ceilDecimal,
1379
- classifyObservation,
1380
500
  createNexra,
1381
- defaultProbeInterval,
1382
- defaultProbeTimeout,
1383
- encodeAdminUserCursor,
1384
- encodeUsageFilterCursor,
1385
- encodeUsageKeysetCursor,
1386
- encodeUsageSummaryCursor,
1387
- evaluatePriceRule,
501
+ decodeMediaGeometry,
502
+ encodeMediaGeometry,
503
+ formatModelDisplayName,
1388
504
  getModelSpec,
1389
- isMoneyString,
1390
505
  isTerminalTaskStatus,
1391
- jsonBody,
1392
506
  listModelSpecs,
1393
- modelInputDefaults,
1394
- modelInputUi,
1395
- modelUploadRegion,
1396
- moneyFromUnits,
1397
- moneyToUnits,
1398
507
  multiplyDecimal,
1399
- multiplyMoney,
1400
- normalizeModelParameterSchema,
1401
- orderedSchemaProperties,
1402
- parseAdminUserCursor,
1403
- parseUsageFilterCursor,
1404
- parseUsageKeysetCursor,
1405
- parseUsageSummaryCursor,
1406
- probeCostExceeds,
1407
- queryString,
1408
- rateProbeUsage,
1409
- sleep,
1410
- taskReceipt,
1411
- taskResult,
1412
- uploadedMediaInput,
1413
- uploadedMediaUrl,
1414
- validateAdminUserApiKeyUpdate,
1415
- validateAdminUserListQuery,
1416
- validateAdminUserUpdate,
1417
- validateAdminWalletRechargeInput,
1418
- validateMeteringContract,
1419
- validateNormalizedUsage,
1420
- validatePriceRule,
1421
- validateUsageAnomaliesQuery,
1422
- validateUsageAnomalySummaryQuery,
1423
- validateUsageDetailsQuery,
1424
- validateUsageFilterOptionsQuery,
1425
- validateUsageFilters,
1426
- validateUsageSummaryQuery,
508
+ projectMediaGeometry,
1427
509
  verifyWebhook
1428
510
  };