@predictasiax/api 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs ADDED
@@ -0,0 +1,1369 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+
30
+ // src/index.ts
31
+ var index_exports = {};
32
+ __export(index_exports, {
33
+ APIPromise: () => APIPromise,
34
+ AccountResource: () => AccountResource,
35
+ ApplyResource: () => ApplyResource,
36
+ CursorPage: () => CursorPage,
37
+ GrantsResource: () => GrantsResource,
38
+ KeysResource: () => KeysResource,
39
+ MarketsResource: () => MarketsResource,
40
+ OrdersResource: () => OrdersResource,
41
+ PagePromise: () => PagePromise,
42
+ PaxAuthError: () => PaxAuthError,
43
+ PaxCircuitBreakerError: () => PaxCircuitBreakerError,
44
+ PaxClient: () => PaxClient,
45
+ PaxConflictError: () => PaxConflictError,
46
+ PaxError: () => PaxError,
47
+ PaxNotFoundError: () => PaxNotFoundError,
48
+ PaxRateLimitError: () => PaxRateLimitError,
49
+ PaxReadOnlyModeError: () => PaxReadOnlyModeError,
50
+ PaxSandboxOnlyError: () => PaxSandboxOnlyError,
51
+ PaxServerError: () => PaxServerError,
52
+ PaxValidationError: () => PaxValidationError,
53
+ PaxWSClient: () => PaxWSClient,
54
+ PaxWrongEnvKeyError: () => PaxWrongEnvKeyError,
55
+ SandboxKeysResource: () => SandboxKeysResource,
56
+ SandboxResource: () => SandboxResource,
57
+ TemplatesResource: () => TemplatesResource,
58
+ VERSION: () => VERSION2,
59
+ buildError: () => buildError,
60
+ buildMessage: () => buildMessage,
61
+ computeBackoff: () => computeBackoff,
62
+ runWithRetry: () => runWithRetry,
63
+ signRequest: () => signRequest
64
+ });
65
+ module.exports = __toCommonJS(index_exports);
66
+
67
+ // src/auth.ts
68
+ function buildMessage(method, path, body, timestampMs) {
69
+ return `${timestampMs}${method.toUpperCase()}${path}${body || ""}`;
70
+ }
71
+ var _nodeCrypto = null;
72
+ var _cryptoLoadAttempted = false;
73
+ async function loadNodeCrypto() {
74
+ if (_cryptoLoadAttempted) return _nodeCrypto;
75
+ _cryptoLoadAttempted = true;
76
+ try {
77
+ const mod = await import("crypto");
78
+ _nodeCrypto = { createHmac: mod.createHmac };
79
+ return _nodeCrypto;
80
+ } catch {
81
+ return null;
82
+ }
83
+ }
84
+ function hasSubtleCrypto() {
85
+ return typeof globalThis.crypto?.subtle?.sign === "function";
86
+ }
87
+ async function signWithWebCrypto(secret, message) {
88
+ const enc = new TextEncoder();
89
+ const key = await globalThis.crypto.subtle.importKey(
90
+ "raw",
91
+ enc.encode(secret),
92
+ { name: "HMAC", hash: "SHA-256" },
93
+ false,
94
+ ["sign"]
95
+ );
96
+ const sig = await globalThis.crypto.subtle.sign("HMAC", key, enc.encode(message));
97
+ return arrayBufferToBase64(sig);
98
+ }
99
+ function arrayBufferToBase64(buf) {
100
+ const bytes = new Uint8Array(buf);
101
+ if (typeof Buffer !== "undefined") return Buffer.from(bytes).toString("base64");
102
+ let bin = "";
103
+ for (let i = 0; i < bytes.length; i++) bin += String.fromCharCode(bytes[i]);
104
+ return globalThis.btoa(bin);
105
+ }
106
+ async function signWithNodeCrypto(secret, message) {
107
+ const nc = await loadNodeCrypto();
108
+ if (!nc) throw new Error("No HMAC backend \u2014 neither node:crypto nor WebCrypto available in this runtime");
109
+ return nc.createHmac("sha256", secret).update(message).digest("base64");
110
+ }
111
+ async function signRequest(input) {
112
+ const ts = String(input.timestampMs ?? Date.now());
113
+ const methodUpper = input.method.toUpperCase();
114
+ const message = ts + methodUpper + input.path + (input.body || "");
115
+ const signature = hasSubtleCrypto() ? await signWithWebCrypto(input.secret, message) : await signWithNodeCrypto(input.secret, message);
116
+ return {
117
+ POLY_ACCESS_KEY: input.keyId,
118
+ POLY_TIMESTAMP: ts,
119
+ POLY_PASSPHRASE: input.passphrase,
120
+ POLY_SIGNATURE: signature
121
+ };
122
+ }
123
+
124
+ // src/errors.ts
125
+ var PaxError = class extends Error {
126
+ code;
127
+ httpStatus;
128
+ requestId;
129
+ details;
130
+ responseJson;
131
+ constructor(opts) {
132
+ const suffix = opts.requestId ? ` (request_id=${opts.requestId})` : "";
133
+ super(`[${opts.code}] ${opts.message}${suffix}`);
134
+ this.name = "PaxError";
135
+ this.code = opts.code;
136
+ this.httpStatus = opts.httpStatus;
137
+ this.requestId = opts.requestId ?? null;
138
+ this.details = opts.details ?? {};
139
+ this.responseJson = opts.responseJson ?? null;
140
+ Object.setPrototypeOf(this, new.target.prototype);
141
+ }
142
+ };
143
+ var PaxAuthError = class extends PaxError {
144
+ constructor(o) {
145
+ super(o);
146
+ this.name = "PaxAuthError";
147
+ Object.setPrototypeOf(this, new.target.prototype);
148
+ }
149
+ };
150
+ var PaxWrongEnvKeyError = class extends PaxAuthError {
151
+ constructor(o) {
152
+ super(o);
153
+ this.name = "PaxWrongEnvKeyError";
154
+ Object.setPrototypeOf(this, new.target.prototype);
155
+ }
156
+ };
157
+ var PaxValidationError = class extends PaxError {
158
+ constructor(o) {
159
+ super(o);
160
+ this.name = "PaxValidationError";
161
+ Object.setPrototypeOf(this, new.target.prototype);
162
+ }
163
+ };
164
+ var PaxNotFoundError = class extends PaxError {
165
+ constructor(o) {
166
+ super(o);
167
+ this.name = "PaxNotFoundError";
168
+ Object.setPrototypeOf(this, new.target.prototype);
169
+ }
170
+ };
171
+ var PaxSandboxOnlyError = class extends PaxNotFoundError {
172
+ constructor(o) {
173
+ super(o);
174
+ this.name = "PaxSandboxOnlyError";
175
+ Object.setPrototypeOf(this, new.target.prototype);
176
+ }
177
+ };
178
+ var PaxConflictError = class extends PaxError {
179
+ constructor(o) {
180
+ super(o);
181
+ this.name = "PaxConflictError";
182
+ Object.setPrototypeOf(this, new.target.prototype);
183
+ }
184
+ };
185
+ var PaxRateLimitError = class extends PaxError {
186
+ retryAfter;
187
+ constructor(o) {
188
+ super(o);
189
+ this.name = "PaxRateLimitError";
190
+ this.retryAfter = o.retryAfter ?? null;
191
+ Object.setPrototypeOf(this, new.target.prototype);
192
+ }
193
+ };
194
+ var PaxServerError = class extends PaxError {
195
+ constructor(o) {
196
+ super(o);
197
+ this.name = "PaxServerError";
198
+ Object.setPrototypeOf(this, new.target.prototype);
199
+ }
200
+ };
201
+ var PaxReadOnlyModeError = class extends PaxError {
202
+ constructor(o) {
203
+ super(o);
204
+ this.name = "PaxReadOnlyModeError";
205
+ Object.setPrototypeOf(this, new.target.prototype);
206
+ }
207
+ };
208
+ var PaxCircuitBreakerError = class extends PaxError {
209
+ constructor(o) {
210
+ super(o);
211
+ this.name = "PaxCircuitBreakerError";
212
+ Object.setPrototypeOf(this, new.target.prototype);
213
+ }
214
+ };
215
+ var CODE_MAP = {
216
+ WRONG_ENV_KEY: PaxWrongEnvKeyError,
217
+ SANDBOX_ONLY: PaxSandboxOnlyError,
218
+ READ_ONLY_MODE: PaxReadOnlyModeError,
219
+ CIRCUIT_BREAKER_OPEN: PaxCircuitBreakerError
220
+ };
221
+ var STATUS_MAP = {
222
+ 400: PaxValidationError,
223
+ 401: PaxAuthError,
224
+ 403: PaxAuthError,
225
+ 404: PaxNotFoundError,
226
+ 409: PaxConflictError,
227
+ 429: PaxRateLimitError,
228
+ 500: PaxServerError,
229
+ 502: PaxServerError,
230
+ 503: PaxServerError,
231
+ 504: PaxServerError
232
+ };
233
+ function buildError(httpStatus, payload, retryAfter = null) {
234
+ let code = "UNKNOWN";
235
+ let message = "Unknown error";
236
+ let details = {};
237
+ const rawErr = payload?.error;
238
+ if (rawErr && typeof rawErr === "object") {
239
+ code = String(rawErr.code ?? "UNKNOWN");
240
+ message = String(rawErr.message ?? code);
241
+ details = rawErr.details ?? {};
242
+ } else if (typeof rawErr === "string") {
243
+ code = rawErr;
244
+ message = String(payload.message ?? code);
245
+ }
246
+ const requestId = payload.meta && typeof payload.meta === "object" ? payload.meta.request_id ?? null : null;
247
+ const ExcClass = CODE_MAP[code] ?? STATUS_MAP[httpStatus] ?? PaxError;
248
+ if (ExcClass === PaxRateLimitError) {
249
+ return new PaxRateLimitError({
250
+ code,
251
+ message,
252
+ httpStatus,
253
+ requestId,
254
+ details,
255
+ responseJson: payload,
256
+ retryAfter
257
+ });
258
+ }
259
+ return new ExcClass({
260
+ code,
261
+ message,
262
+ httpStatus,
263
+ requestId,
264
+ details,
265
+ responseJson: payload
266
+ });
267
+ }
268
+
269
+ // src/request-options.ts
270
+ var PROTECTED_HEADERS = /* @__PURE__ */ new Set(
271
+ [
272
+ "x-api-key",
273
+ "authorization",
274
+ "poly_access_key",
275
+ "poly_timestamp",
276
+ "poly_passphrase",
277
+ "poly_signature",
278
+ "idempotency-key",
279
+ "cache-control"
280
+ ]
281
+ );
282
+ var CRLF_RE = /[\r\n]/;
283
+ function mergeHeaders(managed, extra) {
284
+ if (!extra) return managed;
285
+ const out = { ...managed };
286
+ for (const [k, v] of Object.entries(extra)) {
287
+ if (PROTECTED_HEADERS.has(k.toLowerCase())) continue;
288
+ if (CRLF_RE.test(k) || CRLF_RE.test(v)) {
289
+ throw new Error(`Invalid header \u2014 CR/LF/NUL not allowed: ${JSON.stringify(k)}`);
290
+ }
291
+ out[k] = v;
292
+ }
293
+ return out;
294
+ }
295
+ function chainSignals(userSignal, timeoutMs) {
296
+ const controller = new AbortController();
297
+ const timer = setTimeout(
298
+ () => controller.abort(new DOMException("Request timed out", "TimeoutError")),
299
+ timeoutMs
300
+ );
301
+ let onUserAbort = null;
302
+ if (userSignal) {
303
+ if (userSignal.aborted) {
304
+ controller.abort(userSignal.reason);
305
+ } else {
306
+ onUserAbort = () => controller.abort(userSignal.reason);
307
+ userSignal.addEventListener("abort", onUserAbort, { once: true });
308
+ }
309
+ }
310
+ const cleanup = () => {
311
+ clearTimeout(timer);
312
+ if (userSignal && onUserAbort) userSignal.removeEventListener("abort", onUserAbort);
313
+ };
314
+ return { signal: controller.signal, cleanup };
315
+ }
316
+
317
+ // src/retry.ts
318
+ function isAbortLike(err) {
319
+ if (!err || typeof err !== "object") return false;
320
+ const name = err.name;
321
+ return name === "AbortError" || name === "TimeoutError";
322
+ }
323
+ function isTransientNetworkError(err) {
324
+ if (!err || typeof err !== "object") return false;
325
+ return err instanceof TypeError;
326
+ }
327
+ function computeBackoff(attempt, base = 1, cap = 60, jitter = true) {
328
+ const exp = Math.min(cap, base * Math.pow(2, attempt));
329
+ return jitter ? Math.random() * exp : exp;
330
+ }
331
+ var sleep = (seconds) => new Promise((res) => setTimeout(res, seconds * 1e3));
332
+ async function runWithRetry(fn, opts = {}) {
333
+ const maxAttempts = opts.maxAttempts ?? 5;
334
+ const retryable = new Set(opts.retryableStatuses ?? [429, 500, 502, 504]);
335
+ let lastErr = null;
336
+ for (let attempt = 0; attempt < maxAttempts; attempt++) {
337
+ try {
338
+ return await fn();
339
+ } catch (e) {
340
+ lastErr = e;
341
+ if (isAbortLike(e)) throw e;
342
+ if (e instanceof PaxReadOnlyModeError) throw e;
343
+ if (e instanceof PaxRateLimitError) {
344
+ if (attempt >= maxAttempts - 1) throw e;
345
+ const wait = e.retryAfter ?? computeBackoff(attempt);
346
+ opts.onRetry?.(attempt + 1, e);
347
+ await sleep(wait);
348
+ continue;
349
+ }
350
+ if (e instanceof PaxError) {
351
+ if (!retryable.has(e.httpStatus) || attempt >= maxAttempts - 1) throw e;
352
+ opts.onRetry?.(attempt + 1, e);
353
+ await sleep(computeBackoff(attempt));
354
+ continue;
355
+ }
356
+ if (!isTransientNetworkError(e)) throw e;
357
+ if (attempt >= maxAttempts - 1) throw e;
358
+ opts.onRetry?.(attempt + 1, e);
359
+ await sleep(computeBackoff(attempt));
360
+ }
361
+ }
362
+ throw lastErr;
363
+ }
364
+
365
+ // src/http.ts
366
+ var VERSION = "2.0.0";
367
+ var ENV_URLS = {
368
+ production: "https://api.predictasiax.com/v1",
369
+ prod: "https://api.predictasiax.com/v1",
370
+ live: "https://api.predictasiax.com/v1",
371
+ sandbox: "https://api.predictasiax.com/v1",
372
+ test: "https://api.predictasiax.com/v1"
373
+ };
374
+ var DEFAULT_TIMEOUT_MS = 3e4;
375
+ var DEFAULT_MAX_RETRIES = 5;
376
+ var DEFAULT_MAX_RESPONSE_BYTES = 10 * 1024 * 1024;
377
+ var DEFAULT_USER_AGENT = `pax-api-ts/${VERSION}`;
378
+ var MUTATING_METHODS = /* @__PURE__ */ new Set(["POST", "PUT", "PATCH"]);
379
+ function isLoopback(hostname) {
380
+ return hostname === "localhost" || hostname === "127.0.0.1" || hostname === "::1";
381
+ }
382
+ function validateBaseUrl(url, allowInsecureHttp) {
383
+ let parsed;
384
+ try {
385
+ parsed = new URL(url);
386
+ } catch {
387
+ throw new Error(`Invalid baseUrl: ${url}`);
388
+ }
389
+ if (parsed.protocol === "https:") return;
390
+ if (parsed.protocol === "http:") {
391
+ if (isLoopback(parsed.hostname)) return;
392
+ if (allowInsecureHttp) return;
393
+ throw new Error(
394
+ `baseUrl must use https:// (got ${parsed.protocol}//${parsed.hostname}). Localhost is exempt. To knowingly allow cleartext on non-loopback hosts, set \`allowInsecureHttp: true\` \u2014 never do this in production.`
395
+ );
396
+ }
397
+ throw new Error(`Unsupported baseUrl protocol: ${parsed.protocol}`);
398
+ }
399
+ function randomId() {
400
+ const g = globalThis.crypto;
401
+ if (g && typeof g.randomUUID === "function") return g.randomUUID();
402
+ if (g && typeof g.getRandomValues === "function") {
403
+ const bytes = new Uint8Array(16);
404
+ g.getRandomValues(bytes);
405
+ return Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join("");
406
+ }
407
+ throw new Error("No secure random source available for idempotency-key generation");
408
+ }
409
+ async function readCappedText(response, maxBytes) {
410
+ const contentLengthHeader = response.headers.get("content-length");
411
+ if (contentLengthHeader) {
412
+ const len = parseInt(contentLengthHeader, 10);
413
+ if (!isNaN(len) && len > maxBytes) {
414
+ throw new PaxError({
415
+ code: "RESPONSE_TOO_LARGE",
416
+ message: `Response body ${len} bytes exceeds cap ${maxBytes}`,
417
+ httpStatus: response.status
418
+ });
419
+ }
420
+ }
421
+ if (!response.body) return await response.text();
422
+ const reader = response.body.getReader();
423
+ const chunks = [];
424
+ let total = 0;
425
+ try {
426
+ while (true) {
427
+ const { done, value } = await reader.read();
428
+ if (done) break;
429
+ if (!value) continue;
430
+ total += value.byteLength;
431
+ if (total > maxBytes) {
432
+ try {
433
+ await reader.cancel();
434
+ } catch {
435
+ }
436
+ throw new PaxError({
437
+ code: "RESPONSE_TOO_LARGE",
438
+ message: `Response body exceeded cap ${maxBytes} bytes`,
439
+ httpStatus: response.status
440
+ });
441
+ }
442
+ chunks.push(value);
443
+ }
444
+ } finally {
445
+ try {
446
+ reader.releaseLock();
447
+ } catch {
448
+ }
449
+ }
450
+ const buf = new Uint8Array(total);
451
+ let offset = 0;
452
+ for (const c of chunks) {
453
+ buf.set(c, offset);
454
+ offset += c.byteLength;
455
+ }
456
+ return new TextDecoder("utf-8", { fatal: false }).decode(buf);
457
+ }
458
+ var HttpClient = class {
459
+ baseUrl;
460
+ userAgent;
461
+ apiKey;
462
+ secret;
463
+ passphrase;
464
+ bearerToken;
465
+ timeoutMs;
466
+ maxRetries;
467
+ maxResponseBytes;
468
+ autoIdempotency;
469
+ clockOffsetMs;
470
+ fetchImpl;
471
+ fetchOptions;
472
+ constructor(opts) {
473
+ if (!opts.apiKey && !opts.bearerToken) {
474
+ throw new Error("Provide apiKey or bearerToken");
475
+ }
476
+ if (opts.secret && !opts.passphrase) {
477
+ throw new Error("Provide passphrase together with secret for HMAC");
478
+ }
479
+ if (typeof window !== "undefined" && !opts.dangerouslyAllowBrowser) {
480
+ throw new Error(
481
+ "It looks like you're running PAX SDK in a browser. Server-side keys should never ship to end-users. If this is intentional (e.g. read-only sandbox key on a dev tool), pass `dangerouslyAllowBrowser: true`."
482
+ );
483
+ }
484
+ this.apiKey = opts.apiKey;
485
+ this.secret = opts.secret;
486
+ this.passphrase = opts.passphrase;
487
+ this.bearerToken = opts.bearerToken;
488
+ const env = (opts.env ?? "production").toLowerCase();
489
+ const rawBaseUrl = (opts.baseUrl ?? ENV_URLS[env] ?? ENV_URLS.production).replace(/\/$/, "");
490
+ validateBaseUrl(rawBaseUrl, opts.allowInsecureHttp ?? false);
491
+ this.baseUrl = rawBaseUrl;
492
+ this.timeoutMs = opts.timeoutMs ?? DEFAULT_TIMEOUT_MS;
493
+ this.maxRetries = opts.maxRetries ?? DEFAULT_MAX_RETRIES;
494
+ this.maxResponseBytes = opts.maxResponseBytes ?? DEFAULT_MAX_RESPONSE_BYTES;
495
+ this.autoIdempotency = opts.autoIdempotency ?? true;
496
+ this.clockOffsetMs = opts.clockOffsetMs ?? 0;
497
+ this.userAgent = opts.userAgent ?? DEFAULT_USER_AGENT;
498
+ this.fetchImpl = opts.fetch ?? globalThis.fetch;
499
+ this.fetchOptions = opts.fetchOptions;
500
+ if (!this.fetchImpl) {
501
+ throw new Error("fetch is not available \u2014 Node 18+ required, or pass a fetch impl in opts.fetch");
502
+ }
503
+ }
504
+ buildQueryString(params) {
505
+ if (!params) return "";
506
+ const usp = new URLSearchParams();
507
+ for (const [k, v] of Object.entries(params)) {
508
+ if (v === void 0 || v === null) continue;
509
+ if (Array.isArray(v)) v.forEach((item) => usp.append(k, String(item)));
510
+ else usp.append(k, String(v));
511
+ }
512
+ const qs = usp.toString();
513
+ return qs ? `?${qs}` : "";
514
+ }
515
+ async buildHeaders(method, pathWithQuery, body, idempotencyKey, opts) {
516
+ const managed = {
517
+ "User-Agent": this.userAgent,
518
+ Accept: "application/json",
519
+ // Prevent intermediary caches (browser, corporate proxy, CDN) from
520
+ // retaining authenticated responses.
521
+ "Cache-Control": "no-store"
522
+ };
523
+ if (body) managed["Content-Type"] = "application/json";
524
+ if (idempotencyKey) managed["Idempotency-Key"] = idempotencyKey;
525
+ if (this.secret && this.passphrase && this.apiKey) {
526
+ const sig = await signRequest({
527
+ method,
528
+ path: pathWithQuery,
529
+ body,
530
+ keyId: this.apiKey,
531
+ secret: this.secret,
532
+ passphrase: this.passphrase,
533
+ timestampMs: Date.now() + this.clockOffsetMs
534
+ });
535
+ Object.assign(managed, sig);
536
+ } else if (this.apiKey) {
537
+ managed["X-Api-Key"] = this.apiKey;
538
+ } else if (this.bearerToken) {
539
+ managed["Authorization"] = `Bearer ${this.bearerToken}`;
540
+ }
541
+ return mergeHeaders(managed, opts?.headers);
542
+ }
543
+ resolveIdempotencyKey(method, opts) {
544
+ if (opts && "idempotencyKey" in opts) {
545
+ return opts.idempotencyKey ?? null;
546
+ }
547
+ if (this.autoIdempotency && MUTATING_METHODS.has(method.toUpperCase())) {
548
+ return randomId();
549
+ }
550
+ return null;
551
+ }
552
+ async attempt(method, path, params, jsonBody, idempotencyKey, opts) {
553
+ const qs = this.buildQueryString(params);
554
+ const pathWithQuery = path + qs;
555
+ const url = this.baseUrl + pathWithQuery;
556
+ const body = jsonBody !== void 0 ? JSON.stringify(jsonBody) : "";
557
+ const headers = await this.buildHeaders(method, pathWithQuery, body, idempotencyKey, opts);
558
+ const timeout = opts?.timeout ?? this.timeoutMs;
559
+ const maxResponseBytes = opts?.maxResponseBytes ?? this.maxResponseBytes;
560
+ const { signal, cleanup } = chainSignals(opts?.signal, timeout);
561
+ if (signal.aborted) {
562
+ cleanup();
563
+ throw new DOMException("Request aborted before dispatch", "AbortError");
564
+ }
565
+ let response;
566
+ try {
567
+ response = await this.fetchImpl(url, {
568
+ ...this.fetchOptions,
569
+ method,
570
+ headers,
571
+ body: body || void 0,
572
+ redirect: "manual",
573
+ signal
574
+ });
575
+ } finally {
576
+ cleanup();
577
+ }
578
+ let payload;
579
+ let text = "";
580
+ try {
581
+ text = await readCappedText(response, maxResponseBytes);
582
+ } catch (e) {
583
+ if (e instanceof PaxError) throw e;
584
+ throw e;
585
+ }
586
+ try {
587
+ payload = text ? JSON.parse(text) : {};
588
+ } catch {
589
+ payload = {
590
+ ok: false,
591
+ error: { code: "MALFORMED_RESPONSE", message: text.slice(0, 300) }
592
+ };
593
+ }
594
+ const isOkEnvelope = payload && typeof payload === "object" && payload.ok !== false;
595
+ if (response.status >= 400 || !isOkEnvelope) {
596
+ const retryAfterHeader = response.headers.get("Retry-After");
597
+ const retryAfter = retryAfterHeader !== null ? Number(retryAfterHeader) || null : null;
598
+ throw buildError(response.status, payload, retryAfter);
599
+ }
600
+ return { body: payload, response };
601
+ }
602
+ /**
603
+ * Execute a request with retry-with-backoff on transient failures.
604
+ * Returns the parsed envelope plus the raw Response.
605
+ *
606
+ * The idempotency key is resolved ONCE per call and reused across every
607
+ * retry — this is what prevents double-execution on network flakiness.
608
+ */
609
+ request(method, path, params, jsonBody, opts) {
610
+ const maxAttempts = opts?.maxRetries ?? this.maxRetries;
611
+ const idempotencyKey = this.resolveIdempotencyKey(method, opts);
612
+ return runWithRetry(
613
+ () => this.attempt(method, path, params, jsonBody, idempotencyKey, opts),
614
+ { maxAttempts }
615
+ );
616
+ }
617
+ };
618
+
619
+ // src/api-promise.ts
620
+ var APIPromise = class {
621
+ _run;
622
+ _executed = null;
623
+ constructor(run) {
624
+ this._run = run;
625
+ }
626
+ _exec() {
627
+ if (!this._executed) this._executed = this._run();
628
+ return this._executed;
629
+ }
630
+ then(onFulfilled, onRejected) {
631
+ return this._exec().then((r) => r.data).then(onFulfilled, onRejected);
632
+ }
633
+ catch(onRejected) {
634
+ return this._exec().then((r) => r.data).catch(onRejected);
635
+ }
636
+ finally(onFinally) {
637
+ return this._exec().then((r) => r.data).finally(onFinally);
638
+ }
639
+ /** Return the parsed data plus the raw Response object. */
640
+ async withResponse() {
641
+ const { data, response } = await this._exec();
642
+ return {
643
+ data,
644
+ response,
645
+ requestId: response.headers.get("x-request-id") ?? response.headers.get("request-id") ?? null,
646
+ headers: response.headers,
647
+ status: response.status
648
+ };
649
+ }
650
+ /** Return the raw Response object. Body has already been read for parsing. */
651
+ async asResponse() {
652
+ const { response } = await this._exec();
653
+ return response;
654
+ }
655
+ };
656
+
657
+ // src/pagination.ts
658
+ var CursorPage = class {
659
+ data;
660
+ nextCursor;
661
+ hasMore;
662
+ response;
663
+ _fetchNext;
664
+ _requestOptions;
665
+ constructor(init) {
666
+ this.data = init.data;
667
+ this.nextCursor = init.nextCursor;
668
+ this.hasMore = init.hasMore;
669
+ this.response = init.response;
670
+ this._fetchNext = init.fetchNext;
671
+ this._requestOptions = init.requestOptions;
672
+ }
673
+ hasNextPage() {
674
+ return this.hasMore && this.nextCursor !== null && this.nextCursor !== "";
675
+ }
676
+ getNextPage() {
677
+ if (!this.hasNextPage()) {
678
+ throw new Error("No next page \u2014 call hasNextPage() first");
679
+ }
680
+ return this._fetchNext(this.nextCursor, this._requestOptions);
681
+ }
682
+ /**
683
+ * Async iterate every item across every page. Fetches subsequent pages
684
+ * lazily as the caller consumes.
685
+ */
686
+ async *[Symbol.asyncIterator]() {
687
+ let page = this;
688
+ while (true) {
689
+ for (const item of page.data) yield item;
690
+ if (!page.hasNextPage()) break;
691
+ page = await page.getNextPage();
692
+ }
693
+ }
694
+ /**
695
+ * Collect every item across every page into a single array. Guarded by
696
+ * `limit` to prevent unbounded memory growth.
697
+ */
698
+ async collect(opts = {}) {
699
+ const cap = opts.limit ?? 1e4;
700
+ const out = [];
701
+ for await (const item of this) {
702
+ out.push(item);
703
+ if (out.length >= cap) break;
704
+ }
705
+ return out;
706
+ }
707
+ };
708
+ var PagePromise = class extends APIPromise {
709
+ async *[Symbol.asyncIterator]() {
710
+ const page = await this;
711
+ for await (const item of page) yield item;
712
+ }
713
+ };
714
+
715
+ // src/resources/base.ts
716
+ var Resource = class {
717
+ constructor(_http) {
718
+ this._http = _http;
719
+ }
720
+ _http;
721
+ /** Wrap an unwrapped-data GET/POST/DELETE in APIPromise<T>. */
722
+ _apiPromise(run) {
723
+ return new APIPromise(async () => {
724
+ const raw = await run();
725
+ const data = raw.body?.data ?? raw.body;
726
+ return { data, response: raw.response };
727
+ });
728
+ }
729
+ /**
730
+ * Wrap a paginated GET in APIPromise<CursorPage<T>>.
731
+ *
732
+ * `fetchNext` is a callback the returned CursorPage uses to walk the
733
+ * next page — it must resend the same request with the new cursor and
734
+ * return an APIPromise<CursorPage<T>> so it composes.
735
+ */
736
+ _pagePromise(run, fetchNext, requestOptions) {
737
+ return new PagePromise(async () => {
738
+ const raw = await run();
739
+ const body = raw.body;
740
+ const items = Array.isArray(body?.data) ? body.data : [];
741
+ const nextCursor = body?.next_cursor ?? null;
742
+ const hasMore = body?.has_more ?? (nextCursor !== null && nextCursor !== "");
743
+ const page = new CursorPage({
744
+ data: items,
745
+ nextCursor,
746
+ hasMore,
747
+ response: raw.response,
748
+ fetchNext,
749
+ requestOptions
750
+ });
751
+ return { data: page, response: raw.response };
752
+ });
753
+ }
754
+ };
755
+ function paginationParams(p) {
756
+ if (!p) return {};
757
+ const out = {};
758
+ if (p.limit !== void 0) out.limit = p.limit;
759
+ if (typeof p.cursor === "string") out.cursor = p.cursor;
760
+ return out;
761
+ }
762
+
763
+ // src/resources/account.ts
764
+ var AccountResource = class extends Resource {
765
+ retrieve(opts) {
766
+ return this._apiPromise(
767
+ () => this._http.request("GET", "/v1/account", void 0, void 0, opts)
768
+ );
769
+ }
770
+ positions(opts) {
771
+ return this._apiPromise(
772
+ () => this._http.request("GET", "/v1/account/positions", void 0, void 0, opts)
773
+ );
774
+ }
775
+ trades(params = {}, opts) {
776
+ const query = paginationParams({ limit: params.limit ?? 50, cursor: params.cursor });
777
+ if (params.marketId) query.market_id = params.marketId;
778
+ const fetchNext = (cursor, ro) => this.trades({ ...params, cursor }, ro);
779
+ return this._pagePromise(
780
+ () => this._http.request("GET", "/v1/account/trades", query, void 0, opts),
781
+ fetchNext,
782
+ opts
783
+ );
784
+ }
785
+ };
786
+
787
+ // src/resources/grants.ts
788
+ var GrantsResource = class extends Resource {
789
+ /** List every grant the authenticated user has, oldest last. */
790
+ list(opts) {
791
+ return this._apiPromise(
792
+ () => this._http.request("GET", "/v1/grants", void 0, void 0, opts)
793
+ );
794
+ }
795
+ /** Get a single grant + live vesting calculation. */
796
+ retrieve(id, opts) {
797
+ return this._apiPromise(
798
+ () => this._http.request(
799
+ "GET",
800
+ `/v1/grants/${encodeURIComponent(id)}`,
801
+ void 0,
802
+ void 0,
803
+ opts
804
+ )
805
+ );
806
+ }
807
+ /** Fetch the audit trail for a grant (append-only). */
808
+ events(id, opts) {
809
+ return this._apiPromise(
810
+ () => this._http.request(
811
+ "GET",
812
+ `/v1/grants/${encodeURIComponent(id)}/events`,
813
+ void 0,
814
+ void 0,
815
+ opts
816
+ )
817
+ );
818
+ }
819
+ /**
820
+ * Claim the vested-but-unclaimed amount into your custody balance.
821
+ * Idempotent — the SDK auto-attaches an Idempotency-Key, so retrying a
822
+ * timed-out claim never double-credits.
823
+ *
824
+ * Returns `{ status: "no_op" }` if nothing new has vested since the last
825
+ * claim.
826
+ */
827
+ claim(id, opts) {
828
+ return this._apiPromise(
829
+ () => this._http.request(
830
+ "POST",
831
+ `/v1/grants/${encodeURIComponent(id)}/claim`,
832
+ void 0,
833
+ {},
834
+ opts
835
+ )
836
+ );
837
+ }
838
+ };
839
+
840
+ // src/resources/keys.ts
841
+ var KeysResource = class extends Resource {
842
+ create(params = {}, opts) {
843
+ const body = {
844
+ name: params.name ?? "default",
845
+ scopes: params.scopes ?? ["read"]
846
+ };
847
+ return this._apiPromise(
848
+ () => this._http.request("POST", "/v1/keys", void 0, body, opts)
849
+ );
850
+ }
851
+ list(opts) {
852
+ return this._apiPromise(
853
+ () => this._http.request("GET", "/v1/keys", void 0, void 0, opts)
854
+ );
855
+ }
856
+ revoke(keyId, opts) {
857
+ return this._apiPromise(
858
+ () => this._http.request(
859
+ "DELETE",
860
+ `/v1/keys/${encodeURIComponent(keyId)}`,
861
+ void 0,
862
+ void 0,
863
+ opts
864
+ )
865
+ );
866
+ }
867
+ };
868
+
869
+ // src/resources/markets.ts
870
+ var MarketsResource = class extends Resource {
871
+ /** List markets — auto-paginates. Iterate with `for await (const m of ...)`. */
872
+ list(params = {}, opts) {
873
+ const query = this._buildListQuery(params);
874
+ const fetchNext = (cursor, ro) => this.list({ ...params, cursor }, ro);
875
+ return this._pagePromise(
876
+ () => this._http.request("GET", "/v1/markets", query, void 0, opts),
877
+ fetchNext,
878
+ opts
879
+ );
880
+ }
881
+ retrieve(marketId, opts) {
882
+ return this._apiPromise(
883
+ () => this._http.request("GET", `/v1/markets/${encodeURIComponent(marketId)}`, void 0, void 0, opts)
884
+ );
885
+ }
886
+ create(params, opts) {
887
+ const body = {
888
+ template_id: params.templateId,
889
+ params: params.params
890
+ };
891
+ if (params.creatorMetadata) body.creator_metadata = params.creatorMetadata;
892
+ return this._apiPromise(
893
+ () => this._http.request("POST", "/v1/markets", void 0, body, opts)
894
+ );
895
+ }
896
+ candles(marketId, params, opts) {
897
+ const query = {
898
+ outcome_id: params.outcomeId,
899
+ interval: params.interval ?? "1m",
900
+ limit: params.limit ?? 500
901
+ };
902
+ if (params.fromMs !== void 0) query.from_ms = params.fromMs;
903
+ if (params.toMs !== void 0) query.to_ms = params.toMs;
904
+ return this._apiPromise(
905
+ () => this._http.request("GET", `/v1/candles/${encodeURIComponent(marketId)}`, query, void 0, opts)
906
+ );
907
+ }
908
+ orderbook(marketId, params, opts) {
909
+ const query = {
910
+ outcome_id: params.outcomeId,
911
+ depth: params.depth ?? 20
912
+ };
913
+ return this._apiPromise(
914
+ () => this._http.request("GET", `/v1/orderbook/${encodeURIComponent(marketId)}`, query, void 0, opts)
915
+ );
916
+ }
917
+ /** Public trade tape for a market (all fills, not your fills). */
918
+ trades(marketId, params = {}, opts) {
919
+ const query = { limit: params.limit ?? 50 };
920
+ if (params.outcomeId) query.outcome_id = params.outcomeId;
921
+ if (params.cursor) query.cursor = params.cursor;
922
+ const fetchNext = (cursor, ro) => this.trades(marketId, { ...params, cursor }, ro);
923
+ return this._pagePromise(
924
+ () => this._http.request("GET", `/v1/trades/${encodeURIComponent(marketId)}`, query, void 0, opts),
925
+ fetchNext,
926
+ opts
927
+ );
928
+ }
929
+ _buildListQuery(params) {
930
+ const query = paginationParams({ limit: params.limit ?? 50, cursor: params.cursor });
931
+ if (params.category) query.category = params.category;
932
+ if (params.marketType) query.market_type = params.marketType;
933
+ if (params.status) query.status = params.status;
934
+ return query;
935
+ }
936
+ };
937
+
938
+ // src/resources/orders.ts
939
+ var OrdersResource = class extends Resource {
940
+ place(params, opts) {
941
+ const body = {
942
+ market_id: params.marketId,
943
+ outcome_id: params.outcomeId,
944
+ side: params.side,
945
+ order_type: params.orderType,
946
+ size: String(params.size)
947
+ };
948
+ if (params.price !== void 0) body.price = String(params.price);
949
+ if (params.clientOrderId) body.client_order_id = params.clientOrderId;
950
+ if (params.timeInForce) body.time_in_force = params.timeInForce;
951
+ return this._apiPromise(
952
+ () => this._http.request("POST", "/v1/orders", void 0, body, opts)
953
+ );
954
+ }
955
+ cancel(orderId, opts) {
956
+ return this._apiPromise(
957
+ () => this._http.request(
958
+ "DELETE",
959
+ `/v1/orders/${encodeURIComponent(orderId)}`,
960
+ void 0,
961
+ void 0,
962
+ opts
963
+ )
964
+ );
965
+ }
966
+ list(params = {}, opts) {
967
+ const query = paginationParams({ limit: params.limit ?? 50, cursor: params.cursor });
968
+ if (params.status) query.status = params.status;
969
+ const fetchNext = (cursor, ro) => this.list({ ...params, cursor }, ro);
970
+ return this._pagePromise(
971
+ () => this._http.request("GET", "/v1/account/orders", query, void 0, opts),
972
+ fetchNext,
973
+ opts
974
+ );
975
+ }
976
+ };
977
+
978
+ // src/resources/sandbox.ts
979
+ var SandboxKeysResource = class extends Resource {
980
+ mint(params, opts) {
981
+ const body = {
982
+ org_name: params.orgName,
983
+ contact_email: params.contactEmail ?? null
984
+ };
985
+ return this._apiPromise(
986
+ () => this._http.request(
987
+ "POST",
988
+ "/v1/sandbox-keys",
989
+ void 0,
990
+ body,
991
+ opts
992
+ )
993
+ );
994
+ }
995
+ };
996
+ var ApplyResource = class extends Resource {
997
+ create(params, opts) {
998
+ return this._apiPromise(
999
+ () => this._http.request(
1000
+ "POST",
1001
+ "/v1/apply",
1002
+ void 0,
1003
+ params,
1004
+ opts
1005
+ )
1006
+ );
1007
+ }
1008
+ retrieve(applicationCode, opts) {
1009
+ return this._apiPromise(
1010
+ () => this._http.request(
1011
+ "GET",
1012
+ `/v1/apply/${encodeURIComponent(applicationCode)}`,
1013
+ void 0,
1014
+ void 0,
1015
+ opts
1016
+ )
1017
+ );
1018
+ }
1019
+ };
1020
+ var SandboxResource = class extends Resource {
1021
+ };
1022
+
1023
+ // src/resources/templates.ts
1024
+ var TemplatesResource = class extends Resource {
1025
+ list(params = {}, opts) {
1026
+ const query = {};
1027
+ if (params.category) query.category = params.category;
1028
+ if (params.marketType) query.market_type = params.marketType;
1029
+ return this._apiPromise(
1030
+ () => this._http.request(
1031
+ "GET",
1032
+ "/v1/markets/templates",
1033
+ Object.keys(query).length ? query : void 0,
1034
+ void 0,
1035
+ opts
1036
+ )
1037
+ );
1038
+ }
1039
+ };
1040
+
1041
+ // src/client.ts
1042
+ var VERSION2 = VERSION;
1043
+ var PaxClient = class {
1044
+ _http;
1045
+ markets;
1046
+ templates;
1047
+ orders;
1048
+ account;
1049
+ keys;
1050
+ sandbox;
1051
+ // legacy namespace, kept for import compat
1052
+ sandboxKeys;
1053
+ // POST /v1/sandbox-keys
1054
+ apply;
1055
+ // POST /v1/apply + GET /v1/apply/{code}
1056
+ grants;
1057
+ constructor(opts) {
1058
+ this._http = new HttpClient(opts);
1059
+ this.markets = new MarketsResource(this._http);
1060
+ this.templates = new TemplatesResource(this._http);
1061
+ this.orders = new OrdersResource(this._http);
1062
+ this.account = new AccountResource(this._http);
1063
+ this.keys = new KeysResource(this._http);
1064
+ this.sandbox = new SandboxResource(this._http);
1065
+ this.sandboxKeys = new SandboxKeysResource(this._http);
1066
+ this.apply = new ApplyResource(this._http);
1067
+ this.grants = new GrantsResource(this._http);
1068
+ }
1069
+ get baseUrl() {
1070
+ return this._http.baseUrl;
1071
+ }
1072
+ get userAgent() {
1073
+ return this._http.userAgent;
1074
+ }
1075
+ /** GET /v1/health — top-level, not paginated, always safe. */
1076
+ health(opts) {
1077
+ return new APIPromise(async () => {
1078
+ const raw = await this._http.request(
1079
+ "GET",
1080
+ "/v1/health",
1081
+ void 0,
1082
+ void 0,
1083
+ opts
1084
+ );
1085
+ const data = raw.body?.data ?? raw.body;
1086
+ return { data, response: raw.response };
1087
+ });
1088
+ }
1089
+ };
1090
+
1091
+ // src/ws-client.ts
1092
+ var ENV_URLS2 = {
1093
+ production: "wss://predictasiax.com/ws",
1094
+ prod: "wss://predictasiax.com/ws",
1095
+ live: "wss://predictasiax.com/ws",
1096
+ sandbox: "wss://predictasiax.com/ws",
1097
+ test: "wss://predictasiax.com/ws"
1098
+ };
1099
+ var WS_OPEN = 1;
1100
+ async function resolveWebSocketCtor(override) {
1101
+ if (override) return override;
1102
+ if (typeof globalThis.WebSocket !== "undefined") {
1103
+ return globalThis.WebSocket;
1104
+ }
1105
+ const wsModule = await import("ws");
1106
+ return wsModule.WebSocket;
1107
+ }
1108
+ var PaxWSClient = class {
1109
+ url;
1110
+ apiKey;
1111
+ bearerToken;
1112
+ locale;
1113
+ reconnect;
1114
+ backoffMinSec;
1115
+ backoffMaxSec;
1116
+ pingIntervalMs;
1117
+ wsImplOverride;
1118
+ handlers = /* @__PURE__ */ new Map();
1119
+ catchAll = [];
1120
+ errorHandlers = [];
1121
+ /** Every subscribe/unsubscribe is remembered — resent on reconnect. */
1122
+ subscriptions = /* @__PURE__ */ new Set();
1123
+ ws = null;
1124
+ state = "idle";
1125
+ backoffCurrent;
1126
+ pingTimer = null;
1127
+ stopRequested = false;
1128
+ constructor(opts = {}) {
1129
+ this.apiKey = opts.apiKey;
1130
+ this.bearerToken = opts.bearerToken;
1131
+ this.locale = opts.locale;
1132
+ const env = (opts.env ?? "production").toLowerCase();
1133
+ this.url = opts.url ?? ENV_URLS2[env] ?? ENV_URLS2.production;
1134
+ this.reconnect = opts.reconnect ?? true;
1135
+ this.backoffMinSec = opts.backoffMinSec ?? 1;
1136
+ this.backoffMaxSec = opts.backoffMaxSec ?? 60;
1137
+ this.pingIntervalMs = opts.pingIntervalMs ?? 25e3;
1138
+ this.wsImplOverride = opts.WebSocketImpl;
1139
+ this.backoffCurrent = this.backoffMinSec;
1140
+ if (opts.subscribeOnConnect) {
1141
+ for (const ch of opts.subscribeOnConnect) this.subscriptions.add(ch);
1142
+ }
1143
+ }
1144
+ // ── Event registration ───────────────────────────────────────────────────
1145
+ on(eventType, handler) {
1146
+ if (!this.handlers.has(eventType)) this.handlers.set(eventType, []);
1147
+ this.handlers.get(eventType).push(handler);
1148
+ return this;
1149
+ }
1150
+ off(eventType, handler) {
1151
+ const list = this.handlers.get(eventType);
1152
+ if (!list) return this;
1153
+ const idx = list.indexOf(handler);
1154
+ if (idx >= 0) list.splice(idx, 1);
1155
+ return this;
1156
+ }
1157
+ onAny(handler) {
1158
+ this.catchAll.push(handler);
1159
+ return this;
1160
+ }
1161
+ onError(handler) {
1162
+ this.errorHandlers.push(handler);
1163
+ return this;
1164
+ }
1165
+ // ── Public commands ──────────────────────────────────────────────────────
1166
+ subscribe(channels) {
1167
+ for (const ch of channels) this.subscriptions.add(ch);
1168
+ if (this.isOpen()) this._send({ method: "SUBSCRIBE", params: channels });
1169
+ }
1170
+ unsubscribe(channels) {
1171
+ for (const ch of channels) this.subscriptions.delete(ch);
1172
+ if (this.isOpen()) this._send({ method: "UNSUBSCRIBE", params: channels });
1173
+ }
1174
+ auth(token) {
1175
+ const tok = token ?? this.apiKey ?? this.bearerToken;
1176
+ if (!tok) throw new Error("No auth token \u2014 pass token, apiKey, or bearerToken");
1177
+ this._send({ method: "AUTH", token: tok });
1178
+ }
1179
+ setLocale(locale) {
1180
+ this.locale = locale;
1181
+ if (this.isOpen()) this._send({ method: "LOCALE", locale });
1182
+ }
1183
+ isOpen() {
1184
+ return this.state === "open" && this.ws !== null && this.ws.readyState === WS_OPEN;
1185
+ }
1186
+ /**
1187
+ * Connect once and resolve on OPEN. If `reconnect` is true, subsequent
1188
+ * disconnects will silently trigger reconnect attempts in the background.
1189
+ * If the initial connect fails and `reconnect` is true, the client keeps
1190
+ * trying — the returned promise still resolves as soon as the first OPEN
1191
+ * happens.
1192
+ */
1193
+ connect() {
1194
+ this.stopRequested = false;
1195
+ if (this.state === "open") return Promise.resolve();
1196
+ return new Promise((resolve, reject) => {
1197
+ let resolved = false;
1198
+ const tryConnect = async () => {
1199
+ try {
1200
+ await this._connectOnce(() => {
1201
+ if (!resolved) {
1202
+ resolved = true;
1203
+ resolve();
1204
+ }
1205
+ });
1206
+ } catch (err) {
1207
+ if (!this.reconnect || this.stopRequested) {
1208
+ if (!resolved) {
1209
+ resolved = true;
1210
+ reject(err);
1211
+ }
1212
+ return;
1213
+ }
1214
+ }
1215
+ if (this.stopRequested || !this.reconnect) return;
1216
+ const wait = Math.random() * this.backoffCurrent;
1217
+ this.backoffCurrent = Math.min(this.backoffMaxSec, this.backoffCurrent * 2);
1218
+ setTimeout(() => {
1219
+ void tryConnect();
1220
+ }, wait * 1e3);
1221
+ };
1222
+ void tryConnect();
1223
+ });
1224
+ }
1225
+ /**
1226
+ * Legacy: connect + block forever, re-connecting on close until close().
1227
+ * Equivalent to `await client.connect(); await new Promise(r => client.on("close", r))`.
1228
+ * Kept for parity with Python SDK's `run()`.
1229
+ */
1230
+ async run() {
1231
+ await this.connect();
1232
+ return new Promise((resolve) => {
1233
+ const check = () => {
1234
+ if (this.stopRequested) resolve();
1235
+ else setTimeout(check, 500);
1236
+ };
1237
+ check();
1238
+ });
1239
+ }
1240
+ /** Stop reconnect loop + close current socket. */
1241
+ close() {
1242
+ this.stopRequested = true;
1243
+ this.state = "closing";
1244
+ if (this.pingTimer) {
1245
+ clearInterval(this.pingTimer);
1246
+ this.pingTimer = null;
1247
+ }
1248
+ if (this.ws) {
1249
+ try {
1250
+ this.ws.close();
1251
+ } catch {
1252
+ }
1253
+ }
1254
+ }
1255
+ // ── Internals ────────────────────────────────────────────────────────────
1256
+ _send(obj) {
1257
+ if (!this.ws || this.ws.readyState !== WS_OPEN) {
1258
+ throw new Error("WS not open \u2014 call connect() first, or subscribe() which queues.");
1259
+ }
1260
+ this.ws.send(JSON.stringify(obj));
1261
+ }
1262
+ async _connectOnce(onOpen) {
1263
+ this.state = "connecting";
1264
+ const WSCtor = await resolveWebSocketCtor(this.wsImplOverride);
1265
+ const ws = new WSCtor(this.url);
1266
+ this.ws = ws;
1267
+ return new Promise((resolve, reject) => {
1268
+ let openedOnce = false;
1269
+ ws.onopen = () => {
1270
+ this.state = "open";
1271
+ openedOnce = true;
1272
+ this.backoffCurrent = this.backoffMinSec;
1273
+ const authTok = this.apiKey ?? this.bearerToken;
1274
+ if (authTok) ws.send(JSON.stringify({ method: "AUTH", token: authTok }));
1275
+ if (this.locale) ws.send(JSON.stringify({ method: "LOCALE", locale: this.locale }));
1276
+ if (this.subscriptions.size > 0) {
1277
+ ws.send(JSON.stringify({ method: "SUBSCRIBE", params: [...this.subscriptions] }));
1278
+ }
1279
+ this.pingTimer = setInterval(() => {
1280
+ if (ws.readyState === WS_OPEN) {
1281
+ try {
1282
+ ws.send(JSON.stringify({ method: "PING", ts: Date.now() }));
1283
+ } catch {
1284
+ }
1285
+ }
1286
+ }, this.pingIntervalMs);
1287
+ onOpen();
1288
+ };
1289
+ ws.onmessage = (ev) => {
1290
+ const rawStr = typeof ev.data === "string" ? ev.data : ev.data instanceof ArrayBuffer ? new TextDecoder().decode(ev.data) : ev.data.toString();
1291
+ let evt;
1292
+ try {
1293
+ evt = JSON.parse(rawStr);
1294
+ } catch {
1295
+ return;
1296
+ }
1297
+ for (const cb of this.catchAll) {
1298
+ try {
1299
+ cb(evt);
1300
+ } catch {
1301
+ }
1302
+ }
1303
+ if (typeof evt.type === "string") {
1304
+ const list = this.handlers.get(evt.type);
1305
+ if (list) for (const cb of list) {
1306
+ try {
1307
+ cb(evt);
1308
+ } catch {
1309
+ }
1310
+ }
1311
+ }
1312
+ };
1313
+ ws.onerror = () => {
1314
+ const err = new Error("WebSocket connection error");
1315
+ for (const h of this.errorHandlers) {
1316
+ try {
1317
+ h(err);
1318
+ } catch {
1319
+ }
1320
+ }
1321
+ if (!openedOnce) reject(err);
1322
+ };
1323
+ ws.onclose = () => {
1324
+ this.state = "closed";
1325
+ if (this.pingTimer) {
1326
+ clearInterval(this.pingTimer);
1327
+ this.pingTimer = null;
1328
+ }
1329
+ if (openedOnce) resolve();
1330
+ else reject(new Error("WebSocket closed before OPEN"));
1331
+ };
1332
+ });
1333
+ }
1334
+ };
1335
+ // Annotate the CommonJS export names for ESM import in node:
1336
+ 0 && (module.exports = {
1337
+ APIPromise,
1338
+ AccountResource,
1339
+ ApplyResource,
1340
+ CursorPage,
1341
+ GrantsResource,
1342
+ KeysResource,
1343
+ MarketsResource,
1344
+ OrdersResource,
1345
+ PagePromise,
1346
+ PaxAuthError,
1347
+ PaxCircuitBreakerError,
1348
+ PaxClient,
1349
+ PaxConflictError,
1350
+ PaxError,
1351
+ PaxNotFoundError,
1352
+ PaxRateLimitError,
1353
+ PaxReadOnlyModeError,
1354
+ PaxSandboxOnlyError,
1355
+ PaxServerError,
1356
+ PaxValidationError,
1357
+ PaxWSClient,
1358
+ PaxWrongEnvKeyError,
1359
+ SandboxKeysResource,
1360
+ SandboxResource,
1361
+ TemplatesResource,
1362
+ VERSION,
1363
+ buildError,
1364
+ buildMessage,
1365
+ computeBackoff,
1366
+ runWithRetry,
1367
+ signRequest
1368
+ });
1369
+ //# sourceMappingURL=index.cjs.map