@zorveus/sdk 0.1.8 → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -1,3 +1,24 @@
1
+ import {
2
+ APIConnectionError,
3
+ APIStatusError,
4
+ AppConnectionNotFoundError,
5
+ AuthenticationError,
6
+ CapExceededError,
7
+ CreditGrantExpiredError,
8
+ InsufficientFundsError,
9
+ InternalServerError,
10
+ NotFoundError,
11
+ PermissionDeniedError,
12
+ ProductUserAllowanceInsufficientError,
13
+ RateLimitError,
14
+ ReservationConflictError,
15
+ UnprocessableEntityError,
16
+ ZorveusBusinessError,
17
+ ZorveusError,
18
+ createAPIError,
19
+ parseZorveusGatewayError
20
+ } from "./chunk-6SPZ5W5D.mjs";
21
+
1
22
  // src/http/headers.ts
2
23
  function buildHeaders(options) {
3
24
  const headers = {
@@ -21,178 +42,6 @@ function buildHeaders(options) {
21
42
  return headers;
22
43
  }
23
44
 
24
- // src/errors/zorveus-error.ts
25
- var ZorveusError = class extends Error {
26
- status;
27
- code;
28
- param;
29
- type;
30
- headers;
31
- rawBody;
32
- constructor(message, options = {}) {
33
- super(message);
34
- this.name = "ZorveusError";
35
- this.status = options.status;
36
- this.code = options.code;
37
- this.param = options.param;
38
- this.type = options.type;
39
- this.headers = options.headers;
40
- this.rawBody = options.rawBody;
41
- if (options.cause) {
42
- this.cause = options.cause;
43
- }
44
- Object.setPrototypeOf(this, new.target.prototype);
45
- }
46
- };
47
- var APIConnectionError = class extends ZorveusError {
48
- constructor(message = "Connection to Zorveus API failed", options = {}) {
49
- super(message, options);
50
- this.name = "APIConnectionError";
51
- if (options.cause) {
52
- this.cause = options.cause;
53
- }
54
- }
55
- };
56
- var APIStatusError = class extends ZorveusError {
57
- constructor(message, options) {
58
- super(message, options);
59
- this.name = "APIStatusError";
60
- }
61
- };
62
- var AuthenticationError = class extends APIStatusError {
63
- constructor(message = "Invalid or expired Zorveus credentials", options = {}) {
64
- super(message, { ...options, status: options.status ?? 401 });
65
- this.name = "AuthenticationError";
66
- }
67
- };
68
- var PermissionDeniedError = class extends APIStatusError {
69
- constructor(message = "Permission denied for this operation or model", options = {}) {
70
- super(message, { ...options, status: options.status ?? 403 });
71
- this.name = "PermissionDeniedError";
72
- }
73
- };
74
- var NotFoundError = class extends APIStatusError {
75
- constructor(message = "Resource not found", options = {}) {
76
- super(message, { ...options, status: options.status ?? 404 });
77
- this.name = "NotFoundError";
78
- }
79
- };
80
- var UnprocessableEntityError = class extends APIStatusError {
81
- constructor(message = "Request validation failed", options = {}) {
82
- super(message, { ...options, status: options.status ?? 422 });
83
- this.name = "UnprocessableEntityError";
84
- }
85
- };
86
- var RateLimitError = class extends APIStatusError {
87
- constructor(message = "Rate limit exceeded. Please retry after some time.", options = {}) {
88
- super(message, { ...options, status: options.status ?? 429 });
89
- this.name = "RateLimitError";
90
- }
91
- };
92
- var InternalServerError = class extends APIStatusError {
93
- constructor(message = "Zorveus internal server error", options = {}) {
94
- super(message, { ...options, status: options.status ?? 500 });
95
- this.name = "InternalServerError";
96
- }
97
- };
98
- var ZorveusBusinessError = class extends APIStatusError {
99
- constructor(message, options) {
100
- super(message, options);
101
- this.name = "ZorveusBusinessError";
102
- }
103
- };
104
- var InsufficientFundsError = class extends ZorveusBusinessError {
105
- constructor(message = "Wallet balance exhausted. Top up required.", options = {}) {
106
- super(message, { ...options, status: options.status ?? 402, code: options.code ?? "insufficient_funds" });
107
- this.name = "InsufficientFundsError";
108
- }
109
- };
110
- var CapExceededError = class extends ZorveusBusinessError {
111
- constructor(message = "Spending cap limit reached", options = {}) {
112
- super(message, { ...options, status: options.status ?? 402, code: options.code ?? "cap_exceeded" });
113
- this.name = "CapExceededError";
114
- }
115
- };
116
- var CreditGrantExpiredError = class extends ZorveusBusinessError {
117
- constructor(message = "Product user credit grant has expired", options = {}) {
118
- super(message, { ...options, status: options.status ?? 403, code: options.code ?? "credit_grant_expired" });
119
- this.name = "CreditGrantExpiredError";
120
- }
121
- };
122
- function createAPIError(status, body, headers) {
123
- let message = `Request failed with status ${status}`;
124
- let code;
125
- let param;
126
- let type;
127
- let parsedBody = body;
128
- if (typeof body === "string") {
129
- try {
130
- parsedBody = JSON.parse(body);
131
- } catch {
132
- try {
133
- parsedBody = JSON.parse(body.replace(/'/g, '"'));
134
- } catch {
135
- const codeMatch = body.match(/['"]code['"]\s*:\s*['"]([^'"]+)['"]/);
136
- const msgMatch = body.match(/['"]message['"]\s*:\s*['"]([^'"]+)['"]/);
137
- if (msgMatch?.[1]) message = msgMatch[1];
138
- if (codeMatch?.[1]) code = codeMatch[1];
139
- }
140
- }
141
- }
142
- if (parsedBody && typeof parsedBody === "object") {
143
- const obj = parsedBody;
144
- if (obj.error && typeof obj.error === "object") {
145
- const err = obj.error;
146
- if (typeof err.message === "string") message = err.message;
147
- if (typeof err.code === "string") code = err.code;
148
- if (typeof err.param === "string") param = err.param;
149
- if (typeof err.type === "string") type = err.type;
150
- } else if (typeof obj.detail === "string") {
151
- message = obj.detail;
152
- } else if (Array.isArray(obj.detail) && obj.detail.length > 0) {
153
- const first = obj.detail[0];
154
- if (first && typeof first.msg === "string") {
155
- message = first.msg;
156
- }
157
- } else if (typeof obj.message === "string") {
158
- message = obj.message;
159
- }
160
- }
161
- const options = { status, code, param, type, headers, rawBody: body };
162
- const normalizedCode = (code || "").toLowerCase();
163
- if (normalizedCode.includes("cap_exceed") || normalizedCode.includes("spend_cap") || message.toLowerCase().includes("spending cap")) {
164
- return new CapExceededError(message, options);
165
- }
166
- if (normalizedCode.includes("insufficient_funds") || normalizedCode.includes("balance_exhausted") || normalizedCode.includes("insufficient_balance") || normalizedCode.includes("wallet_empty") || message.toLowerCase().includes("insufficient funds") || message.toLowerCase().includes("balance exhausted") || message.toLowerCase().includes("wallet is empty")) {
167
- return new InsufficientFundsError(message, options);
168
- }
169
- if (normalizedCode.includes("grant_expired")) {
170
- return new CreditGrantExpiredError(message, options);
171
- }
172
- if (status === 401) {
173
- return new AuthenticationError(message, options);
174
- }
175
- if (status === 402) {
176
- return new InsufficientFundsError(message, options);
177
- }
178
- if (status === 403) {
179
- return new PermissionDeniedError(message, options);
180
- }
181
- if (status === 404) {
182
- return new NotFoundError(message, options);
183
- }
184
- if (status === 422) {
185
- return new UnprocessableEntityError(message, options);
186
- }
187
- if (status === 429) {
188
- return new RateLimitError(message, options);
189
- }
190
- if (status >= 500) {
191
- return new InternalServerError(message, options);
192
- }
193
- return new APIStatusError(message, options);
194
- }
195
-
196
45
  // src/http/transport.ts
197
46
  var HTTPTransport = class {
198
47
  apiKey;
@@ -436,6 +285,9 @@ function formatGatewayMetadata(meta) {
436
285
  if (meta.externalUserId) {
437
286
  result.external_user_id = meta.externalUserId;
438
287
  }
288
+ if (meta.productEndUserId) {
289
+ result.product_end_user_id = meta.productEndUserId;
290
+ }
439
291
  if (meta.displayName !== void 0 || meta.userEmail !== void 0 || meta.metadata !== void 0) {
440
292
  result.product_user = {
441
293
  display_name: meta.displayName ?? null,
@@ -492,6 +344,17 @@ var Chat = class {
492
344
  }
493
345
  };
494
346
 
347
+ // src/types/usage-events.ts
348
+ function normalInputTokens(event) {
349
+ if (event.cache_usage_breakdown_status !== "reported" || event.input_tokens === null) {
350
+ return null;
351
+ }
352
+ return Math.max(
353
+ 0,
354
+ event.input_tokens - event.cache_read_input_tokens - event.cache_creation_input_tokens - event.cache_creation_1h_input_tokens
355
+ );
356
+ }
357
+
495
358
  // src/resources/embeddings.ts
496
359
  var Embeddings = class {
497
360
  transport;
@@ -603,9 +466,6 @@ function isValidDecimalString(value) {
603
466
  return decimalRegex.test(trimmed);
604
467
  }
605
468
  function assertDecimalString(value, fieldName) {
606
- if (typeof value === "number") {
607
- return value.toFixed(4);
608
- }
609
469
  if (isValidDecimalString(value)) {
610
470
  return value.trim();
611
471
  }
@@ -613,6 +473,36 @@ function assertDecimalString(value, fieldName) {
613
473
  `Field '${fieldName}' must be a valid decimal string (e.g. "15.0000"), received: ${JSON.stringify(value)}`
614
474
  );
615
475
  }
476
+ function formatDecimalString(value, fractionDigits = 2) {
477
+ const decimal = assertDecimalString(value, "value");
478
+ if (!Number.isInteger(fractionDigits) || fractionDigits < 0) {
479
+ throw new RangeError("fractionDigits must be a non-negative integer");
480
+ }
481
+ const negative = decimal.startsWith("-");
482
+ const unsigned = negative ? decimal.slice(1) : decimal;
483
+ const [integer, fraction = ""] = unsigned.split(".");
484
+ const roundedInput = fraction.padEnd(fractionDigits + 1, "0");
485
+ let scaled = BigInt(integer + roundedInput.slice(0, fractionDigits).padEnd(fractionDigits, "0"));
486
+ if (Number(roundedInput[fractionDigits] ?? "0") >= 5) scaled += 1n;
487
+ const digits = scaled.toString().padStart(fractionDigits + 1, "0");
488
+ const formatted = fractionDigits === 0 ? digits : `${digits.slice(0, -fractionDigits)}.${digits.slice(-fractionDigits)}`;
489
+ return negative && scaled !== 0n ? `-${formatted}` : formatted;
490
+ }
491
+ function decimalPercentage(numerator, denominator) {
492
+ const toScaledInteger = (value, scale) => {
493
+ const [integer, fraction = ""] = assertDecimalString(value, "value").split(".");
494
+ return BigInt(integer + fraction.padEnd(scale, "0").slice(0, scale));
495
+ };
496
+ const fractionDigits = Math.max(
497
+ numerator.split(".")[1]?.length ?? 0,
498
+ denominator.split(".")[1]?.length ?? 0
499
+ );
500
+ const top = toScaledInteger(numerator, fractionDigits);
501
+ const bottom = toScaledInteger(denominator, fractionDigits);
502
+ if (bottom <= 0n) return 0;
503
+ const basisPoints = top * 10000n / bottom;
504
+ return Number(basisPoints) / 100;
505
+ }
616
506
 
617
507
  // src/resources/product-users.ts
618
508
  var ProductUsers = class {
@@ -705,6 +595,7 @@ var ProductUsers = class {
705
595
  async list(params = {}, options = {}) {
706
596
  const query = {};
707
597
  if (params.orgId) query.org_id = params.orgId;
598
+ if (params.appId) query.app_id = params.appId;
708
599
  if (params.limit !== void 0) query.limit = params.limit;
709
600
  if (params.offset !== void 0) query.offset = params.offset;
710
601
  return this.transport.request("/product-users", {
@@ -828,12 +719,13 @@ var ProviderCredentials = class {
828
719
  this.transport = transport;
829
720
  }
830
721
  /**
831
- * Registers an organization BYOK provider credential via Service Key (`POST /provider-credentials/org-programmatic`).
722
+ * Registers an organization BYOK provider credential via Service Key (`POST /provider-credentials`).
832
723
  */
833
724
  async create(params, options = {}) {
834
725
  const payload = {
835
726
  provider: params.provider,
836
727
  credential_name: params.credentialName,
728
+ secret: params.apiKey,
837
729
  api_key: params.apiKey,
838
730
  secret_kind: params.secretKind || "api_key",
839
731
  model_policies: params.modelPolicies || [],
@@ -853,7 +745,7 @@ var ProviderCredentials = class {
853
745
  );
854
746
  }
855
747
  /**
856
- * Lists BYOK provider credentials for an organization (`GET /provider-credentials/org-programmatic`).
748
+ * Lists BYOK provider credentials for an organization (`GET /provider-credentials`).
857
749
  */
858
750
  async list(params = {}, options = {}) {
859
751
  const query = {};
@@ -868,6 +760,13 @@ var ProviderCredentials = class {
868
760
  }
869
761
  );
870
762
  }
763
+ /** Retrieves one BYOK provider credential by ID. */
764
+ async get(providerCredentialId, options = {}) {
765
+ return this.transport.request(
766
+ `/provider-credentials/org-programmatic/${encodeURIComponent(providerCredentialId)}`,
767
+ { method: "GET", ...options }
768
+ );
769
+ }
871
770
  /**
872
771
  * Rotates a provider credential secret (`POST /provider-credentials/org-programmatic/{id}/rotate`).
873
772
  */
@@ -913,10 +812,40 @@ var ProviderCredentials = class {
913
812
  }
914
813
  };
915
814
 
815
+ // src/resources/usage-events.ts
816
+ var UsageEvents = class {
817
+ constructor(transport) {
818
+ this.transport = transport;
819
+ }
820
+ transport;
821
+ /** Lists immutable usage events with cursor pagination. */
822
+ async list(params = {}, options = {}) {
823
+ return this.transport.request("/dashboard-api/usage/events", {
824
+ method: "GET",
825
+ query: {
826
+ org_id: params.orgId,
827
+ app_id: params.appId,
828
+ app_connection_id: params.appConnectionId,
829
+ product_end_user_id: params.productEndUserId,
830
+ model: params.model,
831
+ provider: params.provider,
832
+ billing_mode: params.billingMode,
833
+ status: params.status,
834
+ created_after: params.createdAfter,
835
+ created_before: params.createdBefore,
836
+ limit: params.limit,
837
+ cursor: params.cursor
838
+ },
839
+ ...options
840
+ });
841
+ }
842
+ };
843
+
916
844
  // src/service-client.ts
917
845
  var ZorveusServiceClient = class {
918
846
  productUsers;
919
847
  providerCredentials;
848
+ usageEvents;
920
849
  transport;
921
850
  constructor(options) {
922
851
  if (!options || !options.apiKey) {
@@ -935,6 +864,7 @@ var ZorveusServiceClient = class {
935
864
  });
936
865
  this.productUsers = new ProductUsers(this.transport);
937
866
  this.providerCredentials = new ProviderCredentials(this.transport);
867
+ this.usageEvents = new UsageEvents(this.transport);
938
868
  }
939
869
  };
940
870
 
@@ -1135,6 +1065,7 @@ var ZorveusOAuth = class {
1135
1065
  export {
1136
1066
  APIConnectionError,
1137
1067
  APIStatusError,
1068
+ AppConnectionNotFoundError,
1138
1069
  AuthenticationError,
1139
1070
  CapExceededError,
1140
1071
  CreditGrantExpiredError,
@@ -1142,7 +1073,9 @@ export {
1142
1073
  InternalServerError,
1143
1074
  NotFoundError,
1144
1075
  PermissionDeniedError,
1076
+ ProductUserAllowanceInsufficientError,
1145
1077
  RateLimitError,
1078
+ ReservationConflictError,
1146
1079
  UnprocessableEntityError,
1147
1080
  Zorveus,
1148
1081
  ZorveusBusinessError,
@@ -1152,7 +1085,11 @@ export {
1152
1085
  ZorveusServiceClient,
1153
1086
  assertDecimalString,
1154
1087
  createAPIError,
1088
+ decimalPercentage,
1089
+ formatDecimalString,
1155
1090
  formatGatewayMetadata,
1156
- isValidDecimalString
1091
+ isValidDecimalString,
1092
+ normalInputTokens,
1093
+ parseZorveusGatewayError
1157
1094
  };
1158
1095
  //# sourceMappingURL=index.mjs.map