@byte_fluffy/nexra-sdk 0.1.0-alpha.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +35 -0
- package/dist/catalog-mytCeh5t.d.ts +313 -0
- package/dist/catalog.d.ts +1 -0
- package/dist/catalog.js +10 -0
- package/dist/chunk-ADKRTC6X.js +1512 -0
- package/dist/chunk-FCH5IQP5.js +34 -0
- package/dist/decimal.d.ts +4 -0
- package/dist/decimal.js +8 -0
- package/dist/index.d.ts +1006 -0
- package/dist/index.js +1428 -0
- package/package.json +44 -0
package/dist/index.js
ADDED
|
@@ -0,0 +1,1428 @@
|
|
|
1
|
+
import {
|
|
2
|
+
CatalogClient,
|
|
3
|
+
HttpTransport,
|
|
4
|
+
NexraApiError,
|
|
5
|
+
NexraTaskError,
|
|
6
|
+
NexraWaitTimeoutError,
|
|
7
|
+
getModelSpec,
|
|
8
|
+
jsonBody,
|
|
9
|
+
listModelSpecs,
|
|
10
|
+
queryString,
|
|
11
|
+
sleep
|
|
12
|
+
} from "./chunk-ADKRTC6X.js";
|
|
13
|
+
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
|
+
}
|
|
928
|
+
|
|
929
|
+
// src/assets.ts
|
|
930
|
+
var AssetsClient = class {
|
|
931
|
+
constructor(transport) {
|
|
932
|
+
this.transport = transport;
|
|
933
|
+
}
|
|
934
|
+
transport;
|
|
935
|
+
async upload(file, options = {}) {
|
|
936
|
+
const name = options.name ?? (isFile(file) ? file.name : void 0);
|
|
937
|
+
const headers = new Headers({
|
|
938
|
+
"content-type": file.type || "application/octet-stream",
|
|
939
|
+
"x-nexra-asset-kind": options.kind ?? inferKind(file.type)
|
|
940
|
+
});
|
|
941
|
+
if (name) headers.set("x-nexra-file-name", encodeURIComponent(name));
|
|
942
|
+
return this.transport.json(
|
|
943
|
+
"/assets",
|
|
944
|
+
{
|
|
945
|
+
method: "POST",
|
|
946
|
+
body: file,
|
|
947
|
+
headers,
|
|
948
|
+
signal: options.signal
|
|
949
|
+
},
|
|
950
|
+
{ retryable: false }
|
|
951
|
+
);
|
|
952
|
+
}
|
|
953
|
+
import(request, signal) {
|
|
954
|
+
return this.transport.json("/assets/import", {
|
|
955
|
+
method: "POST",
|
|
956
|
+
...jsonBody(request),
|
|
957
|
+
signal
|
|
958
|
+
});
|
|
959
|
+
}
|
|
960
|
+
get(assetId, signal) {
|
|
961
|
+
return this.transport.json(`/assets/${encodeURIComponent(assetId)}`, {
|
|
962
|
+
signal
|
|
963
|
+
});
|
|
964
|
+
}
|
|
965
|
+
download(asset, signal) {
|
|
966
|
+
const assetId = typeof asset === "string" ? asset : asset.id;
|
|
967
|
+
return this.transport.response(`/assets/${encodeURIComponent(assetId)}/content`, {
|
|
968
|
+
signal
|
|
969
|
+
});
|
|
970
|
+
}
|
|
971
|
+
async stream(asset, signal) {
|
|
972
|
+
const response = await this.download(asset, signal);
|
|
973
|
+
if (!response.body) throw new Error("Asset response did not contain a body stream");
|
|
974
|
+
return response.body;
|
|
975
|
+
}
|
|
976
|
+
};
|
|
977
|
+
function inferKind(mimeType) {
|
|
978
|
+
if (mimeType.startsWith("image/")) return "image";
|
|
979
|
+
if (mimeType.startsWith("video/")) return "video";
|
|
980
|
+
if (mimeType.startsWith("audio/")) return "audio";
|
|
981
|
+
if (mimeType.startsWith("text/") || mimeType === "application/pdf") return "document";
|
|
982
|
+
if (mimeType.includes("zip") || mimeType.includes("tar")) return "archive";
|
|
983
|
+
return "other";
|
|
984
|
+
}
|
|
985
|
+
function isFile(value) {
|
|
986
|
+
return typeof File !== "undefined" && value instanceof File;
|
|
987
|
+
}
|
|
988
|
+
|
|
989
|
+
// src/models.ts
|
|
990
|
+
var ModelsClient = class {
|
|
991
|
+
constructor(transport) {
|
|
992
|
+
this.transport = transport;
|
|
993
|
+
}
|
|
994
|
+
transport;
|
|
995
|
+
search(params = {}, signal) {
|
|
996
|
+
return this.transport.json(
|
|
997
|
+
`/models${queryString({
|
|
998
|
+
q: params.query,
|
|
999
|
+
modality: params.modality,
|
|
1000
|
+
operation: params.operation,
|
|
1001
|
+
category: params.category,
|
|
1002
|
+
limit: params.limit,
|
|
1003
|
+
cursor: params.cursor
|
|
1004
|
+
})}`,
|
|
1005
|
+
{ signal }
|
|
1006
|
+
);
|
|
1007
|
+
}
|
|
1008
|
+
get(model, signal) {
|
|
1009
|
+
return this.transport.json(`/models/${encodeURIComponent(model)}`, {
|
|
1010
|
+
signal
|
|
1011
|
+
});
|
|
1012
|
+
}
|
|
1013
|
+
schema(model, signal) {
|
|
1014
|
+
return this.transport.json(
|
|
1015
|
+
`/models/${encodeURIComponent(model)}/schema`,
|
|
1016
|
+
{ signal }
|
|
1017
|
+
);
|
|
1018
|
+
}
|
|
1019
|
+
};
|
|
1020
|
+
|
|
1021
|
+
// src/input.ts
|
|
1022
|
+
async function normalizeTaskInput(input, assets, signal) {
|
|
1023
|
+
const normalized = await normalizeValue(input, assets, signal, /* @__PURE__ */ new WeakSet());
|
|
1024
|
+
if (!isPlainObject(normalized)) {
|
|
1025
|
+
throw new TypeError("Task input must be a JSON object");
|
|
1026
|
+
}
|
|
1027
|
+
return normalized;
|
|
1028
|
+
}
|
|
1029
|
+
async function normalizeValue(value, assets, signal, ancestors) {
|
|
1030
|
+
if (value === null || typeof value === "string" || typeof value === "boolean") {
|
|
1031
|
+
return value;
|
|
1032
|
+
}
|
|
1033
|
+
if (typeof value === "number") {
|
|
1034
|
+
if (!Number.isFinite(value)) throw new TypeError("Task input numbers must be finite");
|
|
1035
|
+
return value;
|
|
1036
|
+
}
|
|
1037
|
+
if (value instanceof URL) return value.toString();
|
|
1038
|
+
if (typeof Blob !== "undefined" && value instanceof Blob) {
|
|
1039
|
+
const uploaded = await assets.upload(value, { signal });
|
|
1040
|
+
return { assetId: uploaded.id };
|
|
1041
|
+
}
|
|
1042
|
+
if (isMediaAsset(value)) {
|
|
1043
|
+
return { assetId: value.id };
|
|
1044
|
+
}
|
|
1045
|
+
if (isAssetReference(value)) return { assetId: value.assetId };
|
|
1046
|
+
if (Array.isArray(value)) {
|
|
1047
|
+
assertNotCircular(value, ancestors);
|
|
1048
|
+
const normalized = await Promise.all(
|
|
1049
|
+
value.map((item) => normalizeValue(item, assets, signal, ancestors))
|
|
1050
|
+
);
|
|
1051
|
+
ancestors.delete(value);
|
|
1052
|
+
return normalized;
|
|
1053
|
+
}
|
|
1054
|
+
if (isPlainObject(value)) {
|
|
1055
|
+
assertNotCircular(value, ancestors);
|
|
1056
|
+
const normalized = {};
|
|
1057
|
+
for (const [key, item] of Object.entries(value)) {
|
|
1058
|
+
if (item === void 0) continue;
|
|
1059
|
+
normalized[key] = await normalizeValue(item, assets, signal, ancestors);
|
|
1060
|
+
}
|
|
1061
|
+
ancestors.delete(value);
|
|
1062
|
+
return normalized;
|
|
1063
|
+
}
|
|
1064
|
+
throw new TypeError(`Task input contains a non-serializable ${typeof value} value`);
|
|
1065
|
+
}
|
|
1066
|
+
function assertNotCircular(value, ancestors) {
|
|
1067
|
+
if (ancestors.has(value)) throw new TypeError("Task input cannot contain circular references");
|
|
1068
|
+
ancestors.add(value);
|
|
1069
|
+
}
|
|
1070
|
+
function isPlainObject(value) {
|
|
1071
|
+
if (!value || typeof value !== "object") return false;
|
|
1072
|
+
const prototype = Object.getPrototypeOf(value);
|
|
1073
|
+
return prototype === Object.prototype || prototype === null;
|
|
1074
|
+
}
|
|
1075
|
+
function isAssetReference(value) {
|
|
1076
|
+
return isPlainObject(value) && typeof value.assetId === "string";
|
|
1077
|
+
}
|
|
1078
|
+
function isMediaAsset(value) {
|
|
1079
|
+
return isPlainObject(value) && typeof value.id === "string" && typeof value.kind === "string" && typeof value.status === "string" && typeof value.source === "string";
|
|
1080
|
+
}
|
|
1081
|
+
|
|
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
|
+
// src/tasks.ts
|
|
1132
|
+
var TasksClient = class {
|
|
1133
|
+
constructor(transport, assets) {
|
|
1134
|
+
this.transport = transport;
|
|
1135
|
+
this.assets = assets;
|
|
1136
|
+
}
|
|
1137
|
+
transport;
|
|
1138
|
+
assets;
|
|
1139
|
+
async create(model, options) {
|
|
1140
|
+
const input = await normalizeTaskInput(options.input, this.assets, options.signal);
|
|
1141
|
+
const body = {
|
|
1142
|
+
model,
|
|
1143
|
+
input,
|
|
1144
|
+
quoteToken: options.quoteToken,
|
|
1145
|
+
submittedAt: options.submittedAt,
|
|
1146
|
+
metadata: options.metadata,
|
|
1147
|
+
callback_url: options.callback_url,
|
|
1148
|
+
webhook: options.webhook,
|
|
1149
|
+
schemaVersion: options.schemaVersion
|
|
1150
|
+
};
|
|
1151
|
+
const idempotencyKey = options.idempotencyKey ?? crypto.randomUUID();
|
|
1152
|
+
return this.transport.json(
|
|
1153
|
+
"/tasks",
|
|
1154
|
+
{
|
|
1155
|
+
method: "POST",
|
|
1156
|
+
...jsonBody(body),
|
|
1157
|
+
headers: {
|
|
1158
|
+
...jsonBody(body).headers,
|
|
1159
|
+
"idempotency-key": idempotencyKey
|
|
1160
|
+
},
|
|
1161
|
+
signal: options.signal
|
|
1162
|
+
},
|
|
1163
|
+
{ retryable: true }
|
|
1164
|
+
);
|
|
1165
|
+
}
|
|
1166
|
+
get(taskId, signal) {
|
|
1167
|
+
return this.transport.json(`/tasks/${encodeURIComponent(taskId)}`, {
|
|
1168
|
+
signal
|
|
1169
|
+
});
|
|
1170
|
+
}
|
|
1171
|
+
list(params = {}, signal) {
|
|
1172
|
+
return this.transport.json(
|
|
1173
|
+
`/tasks${queryString({
|
|
1174
|
+
status: params.status,
|
|
1175
|
+
model: params.model,
|
|
1176
|
+
limit: params.limit,
|
|
1177
|
+
cursor: params.cursor
|
|
1178
|
+
})}`,
|
|
1179
|
+
{ signal }
|
|
1180
|
+
);
|
|
1181
|
+
}
|
|
1182
|
+
cancel(taskId, signal) {
|
|
1183
|
+
return this.transport.json(
|
|
1184
|
+
`/tasks/${encodeURIComponent(taskId)}/cancel`,
|
|
1185
|
+
{ method: "POST", signal },
|
|
1186
|
+
{ retryable: true }
|
|
1187
|
+
);
|
|
1188
|
+
}
|
|
1189
|
+
async *watch(taskId, options = {}) {
|
|
1190
|
+
let lastEventId = options.lastEventId;
|
|
1191
|
+
let reconnects = 0;
|
|
1192
|
+
let reconnectDelay = 500;
|
|
1193
|
+
const maxReconnects = options.maxReconnects ?? 5;
|
|
1194
|
+
while (true) {
|
|
1195
|
+
const headers = new Headers({ accept: "text/event-stream" });
|
|
1196
|
+
if (lastEventId) headers.set("last-event-id", lastEventId);
|
|
1197
|
+
const response = await this.transport.response(
|
|
1198
|
+
`/tasks/${encodeURIComponent(taskId)}/events`,
|
|
1199
|
+
{ headers, signal: options.signal },
|
|
1200
|
+
{ retryable: false }
|
|
1201
|
+
);
|
|
1202
|
+
let reachedTerminalState = false;
|
|
1203
|
+
for await (const serverEvent of parseServerSentEvents(response)) {
|
|
1204
|
+
if (serverEvent.id) lastEventId = serverEvent.id;
|
|
1205
|
+
if (serverEvent.retry !== void 0) reconnectDelay = serverEvent.retry;
|
|
1206
|
+
const event = JSON.parse(serverEvent.data);
|
|
1207
|
+
yield event;
|
|
1208
|
+
if (event.status && isTerminalTaskStatus(event.status)) {
|
|
1209
|
+
reachedTerminalState = true;
|
|
1210
|
+
}
|
|
1211
|
+
}
|
|
1212
|
+
if (reachedTerminalState) return;
|
|
1213
|
+
if (reconnects >= maxReconnects) return;
|
|
1214
|
+
reconnects += 1;
|
|
1215
|
+
await sleep(reconnectDelay, options.signal);
|
|
1216
|
+
}
|
|
1217
|
+
}
|
|
1218
|
+
async wait(taskId, options = {}) {
|
|
1219
|
+
const timeoutController = new AbortController();
|
|
1220
|
+
const timeoutMs = options.timeoutMs;
|
|
1221
|
+
const timeout = timeoutMs ? setTimeout(() => timeoutController.abort("nexra_wait_timeout"), timeoutMs) : void 0;
|
|
1222
|
+
const signal = combineSignals(options.signal, timeoutMs ? timeoutController.signal : void 0);
|
|
1223
|
+
try {
|
|
1224
|
+
const current = await this.get(taskId, signal);
|
|
1225
|
+
if (isTerminalTaskStatus(current.status) && current.deliveryStatus !== "preparing") return current;
|
|
1226
|
+
try {
|
|
1227
|
+
for await (const event of this.watch(taskId, {
|
|
1228
|
+
signal,
|
|
1229
|
+
lastEventId: options.lastEventId,
|
|
1230
|
+
maxReconnects: options.maxReconnects
|
|
1231
|
+
})) {
|
|
1232
|
+
await options.onEvent?.(event);
|
|
1233
|
+
}
|
|
1234
|
+
} catch (error) {
|
|
1235
|
+
if (signal?.aborted) throw error;
|
|
1236
|
+
if (error instanceof NexraApiError && ![405, 406, 501].includes(error.status)) {
|
|
1237
|
+
throw error;
|
|
1238
|
+
}
|
|
1239
|
+
}
|
|
1240
|
+
while (true) {
|
|
1241
|
+
const task = await this.get(taskId, signal);
|
|
1242
|
+
if (isTerminalTaskStatus(task.status) && task.deliveryStatus !== "preparing") return task;
|
|
1243
|
+
await sleep(options.pollIntervalMs ?? 1e3, signal);
|
|
1244
|
+
}
|
|
1245
|
+
} catch (error) {
|
|
1246
|
+
if (timeoutController.signal.aborted && timeoutMs) {
|
|
1247
|
+
throw new NexraWaitTimeoutError(taskId, timeoutMs);
|
|
1248
|
+
}
|
|
1249
|
+
throw error;
|
|
1250
|
+
} finally {
|
|
1251
|
+
if (timeout) clearTimeout(timeout);
|
|
1252
|
+
}
|
|
1253
|
+
}
|
|
1254
|
+
async run(model, options) {
|
|
1255
|
+
const task = await this.create(model, options);
|
|
1256
|
+
let completed;
|
|
1257
|
+
try {
|
|
1258
|
+
completed = await this.wait(task.id, options);
|
|
1259
|
+
} catch (error) {
|
|
1260
|
+
if (options.cancelOnAbort && options.signal?.aborted) {
|
|
1261
|
+
await this.cancel(task.id).catch(() => void 0);
|
|
1262
|
+
}
|
|
1263
|
+
throw error;
|
|
1264
|
+
}
|
|
1265
|
+
if (completed.status !== "succeeded") {
|
|
1266
|
+
throw new NexraTaskError(completed);
|
|
1267
|
+
}
|
|
1268
|
+
return {
|
|
1269
|
+
taskId: completed.id,
|
|
1270
|
+
output: completed.output,
|
|
1271
|
+
assets: completed.assets ?? [],
|
|
1272
|
+
task: completed
|
|
1273
|
+
};
|
|
1274
|
+
}
|
|
1275
|
+
};
|
|
1276
|
+
function combineSignals(first, second) {
|
|
1277
|
+
const signals = [first, second].filter((signal) => Boolean(signal));
|
|
1278
|
+
if (signals.length === 0) return void 0;
|
|
1279
|
+
if (signals.length === 1) return signals[0];
|
|
1280
|
+
return AbortSignal.any(signals);
|
|
1281
|
+
}
|
|
1282
|
+
|
|
1283
|
+
// src/client.ts
|
|
1284
|
+
var NexraClient = class {
|
|
1285
|
+
assets;
|
|
1286
|
+
catalog;
|
|
1287
|
+
models;
|
|
1288
|
+
tasks;
|
|
1289
|
+
constructor(options = {}) {
|
|
1290
|
+
const transport = new HttpTransport(options);
|
|
1291
|
+
this.assets = new AssetsClient(transport);
|
|
1292
|
+
this.catalog = new CatalogClient(transport);
|
|
1293
|
+
this.models = new ModelsClient(transport);
|
|
1294
|
+
this.tasks = new TasksClient(transport, this.assets);
|
|
1295
|
+
}
|
|
1296
|
+
run(model, options) {
|
|
1297
|
+
return this.tasks.run(model, options);
|
|
1298
|
+
}
|
|
1299
|
+
};
|
|
1300
|
+
function createNexra(options = {}) {
|
|
1301
|
+
return new NexraClient(options);
|
|
1302
|
+
}
|
|
1303
|
+
|
|
1304
|
+
// src/webhooks.ts
|
|
1305
|
+
async function verifyWebhook(request, secret, options = {}) {
|
|
1306
|
+
const webhookId = request.headers.get("nexra-webhook-id");
|
|
1307
|
+
const timestamp = request.headers.get("nexra-webhook-timestamp");
|
|
1308
|
+
const signatureHeader = request.headers.get("nexra-webhook-signature");
|
|
1309
|
+
if (!webhookId || !timestamp || !signatureHeader) return false;
|
|
1310
|
+
const timestampSeconds = Number(timestamp);
|
|
1311
|
+
if (!Number.isFinite(timestampSeconds)) return false;
|
|
1312
|
+
const nowSeconds = Math.floor((options.now ?? /* @__PURE__ */ new Date()).getTime() / 1e3);
|
|
1313
|
+
if (Math.abs(nowSeconds - timestampSeconds) > (options.toleranceSeconds ?? 300)) {
|
|
1314
|
+
return false;
|
|
1315
|
+
}
|
|
1316
|
+
const body = await request.clone().text();
|
|
1317
|
+
const signedPayload = `${webhookId}.${timestamp}.${body}`;
|
|
1318
|
+
const key = await crypto.subtle.importKey(
|
|
1319
|
+
"raw",
|
|
1320
|
+
new TextEncoder().encode(secret),
|
|
1321
|
+
{ name: "HMAC", hash: "SHA-256" },
|
|
1322
|
+
false,
|
|
1323
|
+
["sign"]
|
|
1324
|
+
);
|
|
1325
|
+
const digest = new Uint8Array(
|
|
1326
|
+
await crypto.subtle.sign("HMAC", key, new TextEncoder().encode(signedPayload))
|
|
1327
|
+
);
|
|
1328
|
+
const expected = toBase64Url(digest);
|
|
1329
|
+
const signatures = signatureHeader.split(" ").flatMap((part) => part.split(",")).map((part) => part.trim()).filter((part) => part.startsWith("v1=")).map((part) => part.slice(3));
|
|
1330
|
+
return signatures.some((signature) => timingSafeEqual(signature, expected));
|
|
1331
|
+
}
|
|
1332
|
+
function toBase64Url(bytes) {
|
|
1333
|
+
let binary = "";
|
|
1334
|
+
for (const byte of bytes) binary += String.fromCharCode(byte);
|
|
1335
|
+
return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
|
|
1336
|
+
}
|
|
1337
|
+
function timingSafeEqual(left, right) {
|
|
1338
|
+
if (left.length !== right.length) return false;
|
|
1339
|
+
let difference = 0;
|
|
1340
|
+
for (let index = 0; index < left.length; index += 1) {
|
|
1341
|
+
difference |= left.charCodeAt(index) ^ right.charCodeAt(index);
|
|
1342
|
+
}
|
|
1343
|
+
return difference === 0;
|
|
1344
|
+
}
|
|
1345
|
+
export {
|
|
1346
|
+
ADMIN_USER_ACTIVITY_KINDS,
|
|
1347
|
+
ADMIN_USER_ROLES,
|
|
1348
|
+
ADMIN_USER_STATUSES,
|
|
1349
|
+
AssetsClient,
|
|
1350
|
+
BILLING_CURRENCY,
|
|
1351
|
+
BILLING_EXPORT_DIMENSIONS,
|
|
1352
|
+
BILLING_METRICS,
|
|
1353
|
+
CatalogClient,
|
|
1354
|
+
HttpTransport,
|
|
1355
|
+
MEDIA_KINDS,
|
|
1356
|
+
MONEY_STRING_PATTERN,
|
|
1357
|
+
ModelsClient,
|
|
1358
|
+
NexraApiError,
|
|
1359
|
+
NexraClient,
|
|
1360
|
+
NexraTaskError,
|
|
1361
|
+
NexraWaitTimeoutError,
|
|
1362
|
+
TASK_STATUSES,
|
|
1363
|
+
TOKEN_METRICS,
|
|
1364
|
+
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,
|
|
1378
|
+
ceilDecimal,
|
|
1379
|
+
classifyObservation,
|
|
1380
|
+
createNexra,
|
|
1381
|
+
defaultProbeInterval,
|
|
1382
|
+
defaultProbeTimeout,
|
|
1383
|
+
encodeAdminUserCursor,
|
|
1384
|
+
encodeUsageFilterCursor,
|
|
1385
|
+
encodeUsageKeysetCursor,
|
|
1386
|
+
encodeUsageSummaryCursor,
|
|
1387
|
+
evaluatePriceRule,
|
|
1388
|
+
getModelSpec,
|
|
1389
|
+
isMoneyString,
|
|
1390
|
+
isTerminalTaskStatus,
|
|
1391
|
+
jsonBody,
|
|
1392
|
+
listModelSpecs,
|
|
1393
|
+
modelInputDefaults,
|
|
1394
|
+
modelInputUi,
|
|
1395
|
+
modelUploadRegion,
|
|
1396
|
+
moneyFromUnits,
|
|
1397
|
+
moneyToUnits,
|
|
1398
|
+
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,
|
|
1427
|
+
verifyWebhook
|
|
1428
|
+
};
|