triqai 0.3.0 → 0.4.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/CHANGELOG.md +26 -0
- package/README.md +63 -2
- package/dist/index.cjs +750 -144
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +87 -26
- package/dist/index.d.ts +87 -26
- package/dist/index.js +750 -145
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/dist/index.cjs
CHANGED
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
Object.defineProperty(exports, '__esModule', { value: true });
|
|
4
4
|
|
|
5
5
|
// package.json
|
|
6
|
-
var version = "0.
|
|
6
|
+
var version = "0.4.1";
|
|
7
7
|
|
|
8
8
|
// src/errors.ts
|
|
9
9
|
var TriqaiError = class extends Error {
|
|
@@ -121,11 +121,492 @@ var ConnectionError = class extends TriqaiError {
|
|
|
121
121
|
}
|
|
122
122
|
};
|
|
123
123
|
var TimeoutError = class extends TriqaiError {
|
|
124
|
-
constructor(message) {
|
|
125
|
-
super(message, 0, { code: "timeout" });
|
|
124
|
+
constructor(message, opts) {
|
|
125
|
+
super(message, 0, { code: opts?.code ?? "timeout" });
|
|
126
126
|
this.name = "TimeoutError";
|
|
127
127
|
}
|
|
128
128
|
};
|
|
129
|
+
var PacingTimeoutError = class extends TimeoutError {
|
|
130
|
+
constructor(message) {
|
|
131
|
+
super(message, { code: "pacing_timeout" });
|
|
132
|
+
this.name = "PacingTimeoutError";
|
|
133
|
+
}
|
|
134
|
+
};
|
|
135
|
+
|
|
136
|
+
// src/abort.ts
|
|
137
|
+
var callbacks = /* @__PURE__ */ new WeakMap();
|
|
138
|
+
function onAbort(signal, callback) {
|
|
139
|
+
if (signal.aborted) {
|
|
140
|
+
callback();
|
|
141
|
+
return () => {
|
|
142
|
+
};
|
|
143
|
+
}
|
|
144
|
+
let set = callbacks.get(signal);
|
|
145
|
+
if (!set) {
|
|
146
|
+
const created = /* @__PURE__ */ new Set();
|
|
147
|
+
set = created;
|
|
148
|
+
callbacks.set(signal, created);
|
|
149
|
+
signal.addEventListener("abort", () => {
|
|
150
|
+
callbacks.delete(signal);
|
|
151
|
+
for (const run of [...created]) run();
|
|
152
|
+
}, { once: true });
|
|
153
|
+
}
|
|
154
|
+
const own = set;
|
|
155
|
+
own.add(callback);
|
|
156
|
+
return () => {
|
|
157
|
+
own.delete(callback);
|
|
158
|
+
};
|
|
159
|
+
}
|
|
160
|
+
function abortReason(signal) {
|
|
161
|
+
return signal.reason ?? new DOMException("This operation was aborted", "AbortError");
|
|
162
|
+
}
|
|
163
|
+
function throwIfAborted(signal) {
|
|
164
|
+
if (signal?.aborted) throw abortReason(signal);
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
// src/pacing.ts
|
|
168
|
+
var DEFAULT_CONCURRENCY = 5;
|
|
169
|
+
var COLD_LIMIT = 5;
|
|
170
|
+
var MAX_SHARED_PAUSE_MS = 6e4;
|
|
171
|
+
var LEASE_MS = 1e3;
|
|
172
|
+
var MIN_RATE = 0.1;
|
|
173
|
+
var MAX_CONCURRENCY = 1e3;
|
|
174
|
+
var MAX_TIMER_DELAY = 2147483647;
|
|
175
|
+
var EPSILON = 1e-9;
|
|
176
|
+
var WaiterQueue = class {
|
|
177
|
+
items = [];
|
|
178
|
+
head = 0;
|
|
179
|
+
push(waiter) {
|
|
180
|
+
this.items.push(waiter);
|
|
181
|
+
}
|
|
182
|
+
unshiftAll(waiters) {
|
|
183
|
+
if (waiters.length === 0) return;
|
|
184
|
+
this.items = [...waiters, ...this.items.slice(this.head)];
|
|
185
|
+
this.head = 0;
|
|
186
|
+
}
|
|
187
|
+
peek() {
|
|
188
|
+
while (this.head < this.items.length && this.items[this.head].state !== "queued") this.head++;
|
|
189
|
+
if (this.head === this.items.length) {
|
|
190
|
+
this.items = [];
|
|
191
|
+
this.head = 0;
|
|
192
|
+
return void 0;
|
|
193
|
+
}
|
|
194
|
+
if (this.head > 1024 && this.head * 2 > this.items.length) {
|
|
195
|
+
this.items = this.items.slice(this.head);
|
|
196
|
+
this.head = 0;
|
|
197
|
+
}
|
|
198
|
+
return this.items[this.head];
|
|
199
|
+
}
|
|
200
|
+
shift() {
|
|
201
|
+
const waiter = this.peek();
|
|
202
|
+
if (waiter) this.head++;
|
|
203
|
+
return waiter;
|
|
204
|
+
}
|
|
205
|
+
/** Removes and returns the queued waiters that match, in order. */
|
|
206
|
+
extract(match) {
|
|
207
|
+
const taken = [];
|
|
208
|
+
const kept = [];
|
|
209
|
+
for (let i = this.head; i < this.items.length; i++) {
|
|
210
|
+
const waiter = this.items[i];
|
|
211
|
+
if (waiter.state !== "queued") continue;
|
|
212
|
+
(match(waiter) ? taken : kept).push(waiter);
|
|
213
|
+
}
|
|
214
|
+
this.items = kept;
|
|
215
|
+
this.head = 0;
|
|
216
|
+
return taken;
|
|
217
|
+
}
|
|
218
|
+
};
|
|
219
|
+
var Pacer = class {
|
|
220
|
+
/** How long a call may wait for its first attempt. */
|
|
221
|
+
maxWait;
|
|
222
|
+
maxConcurrency;
|
|
223
|
+
maxRate;
|
|
224
|
+
serverConcurrency;
|
|
225
|
+
serverRate;
|
|
226
|
+
/** When the concurrency limit became known; earlier requests do not lower the window. */
|
|
227
|
+
concurrencyKnownAt;
|
|
228
|
+
/** Enrichments allowed in flight now; lowered by concurrency 429s, then regrown. */
|
|
229
|
+
window;
|
|
230
|
+
successes = 0;
|
|
231
|
+
/** When the window was last lowered; earlier requests do not regrow it. */
|
|
232
|
+
loweredAt = -Infinity;
|
|
233
|
+
/** Enrichment slots held, by queued retries as well as requests in flight. */
|
|
234
|
+
active = 0;
|
|
235
|
+
/** Requests granted and not yet finished. */
|
|
236
|
+
inFlight = 0;
|
|
237
|
+
tokens;
|
|
238
|
+
refilledAt;
|
|
239
|
+
ratePausedUntil = -Infinity;
|
|
240
|
+
slotPausedUntil = -Infinity;
|
|
241
|
+
pumpedAt = -Infinity;
|
|
242
|
+
slotRetries = new WaiterQueue();
|
|
243
|
+
slotQueue = new WaiterQueue();
|
|
244
|
+
rateRetries = new WaiterQueue();
|
|
245
|
+
rateQueue = new WaiterQueue();
|
|
246
|
+
/** Waiters with a future `notBefore`, earliest first. */
|
|
247
|
+
delayed = [];
|
|
248
|
+
/** Grants not yet taken up by their calls. */
|
|
249
|
+
leased = /* @__PURE__ */ new Set();
|
|
250
|
+
timer;
|
|
251
|
+
constructor(options = {}, defaultMaxWait = 3e5) {
|
|
252
|
+
const { maxConcurrency, requestsPerSecond, maxWait = defaultMaxWait } = options;
|
|
253
|
+
if (maxConcurrency !== void 0 && !(Number.isInteger(maxConcurrency) && maxConcurrency >= 1)) {
|
|
254
|
+
throw new Error("pacing.maxConcurrency must be a positive integer");
|
|
255
|
+
}
|
|
256
|
+
if (requestsPerSecond !== void 0 && !(Number.isFinite(requestsPerSecond) && requestsPerSecond > 0)) {
|
|
257
|
+
throw new Error("pacing.requestsPerSecond must be a positive number");
|
|
258
|
+
}
|
|
259
|
+
if (!(Number.isFinite(maxWait) && maxWait > 0 && maxWait <= MAX_TIMER_DELAY)) {
|
|
260
|
+
throw new Error(`pacing.maxWait must be greater than 0 and at most ${MAX_TIMER_DELAY}ms`);
|
|
261
|
+
}
|
|
262
|
+
this.maxConcurrency = maxConcurrency;
|
|
263
|
+
this.maxRate = requestsPerSecond;
|
|
264
|
+
this.maxWait = maxWait;
|
|
265
|
+
this.concurrencyKnownAt = maxConcurrency === void 0 ? Infinity : -Infinity;
|
|
266
|
+
this.window = this.concurrencyLimit();
|
|
267
|
+
this.refilledAt = Date.now();
|
|
268
|
+
this.tokens = this.burst();
|
|
269
|
+
}
|
|
270
|
+
/** Waits until a request may be sent. Rejects on abort or when `deadline` passes. */
|
|
271
|
+
acquire(options) {
|
|
272
|
+
return this.admit({ ...options, hasSlot: false, retry: false, notBefore: -Infinity });
|
|
273
|
+
}
|
|
274
|
+
/**
|
|
275
|
+
* Queues a waiter and resolves when it is granted, without taking the grant
|
|
276
|
+
* up. Callers must claim it; `acquire` and `Permit.retry` do.
|
|
277
|
+
* @internal
|
|
278
|
+
*/
|
|
279
|
+
wait(init) {
|
|
280
|
+
return new Promise((resolve, reject) => {
|
|
281
|
+
const waiter = {
|
|
282
|
+
...init,
|
|
283
|
+
state: "queued",
|
|
284
|
+
leaseUntil: 0,
|
|
285
|
+
resolve,
|
|
286
|
+
reject,
|
|
287
|
+
timer: void 0,
|
|
288
|
+
unsubscribe: void 0
|
|
289
|
+
};
|
|
290
|
+
const now = Date.now();
|
|
291
|
+
const { signal } = init;
|
|
292
|
+
if (signal?.aborted) return this.settleEarly(waiter, abortReason(signal));
|
|
293
|
+
if (now >= init.deadline || init.notBefore >= init.deadline) return this.settleEarly(waiter, init.expired());
|
|
294
|
+
if (Number.isFinite(init.deadline)) {
|
|
295
|
+
waiter.timer = setTimeout(() => {
|
|
296
|
+
this.fail(waiter, waiter.expired());
|
|
297
|
+
this.pump();
|
|
298
|
+
}, Math.min(MAX_TIMER_DELAY, Math.max(0, init.deadline - now)));
|
|
299
|
+
}
|
|
300
|
+
if (signal) {
|
|
301
|
+
waiter.unsubscribe = onAbort(signal, () => {
|
|
302
|
+
this.fail(waiter, abortReason(signal));
|
|
303
|
+
this.pump();
|
|
304
|
+
});
|
|
305
|
+
}
|
|
306
|
+
this.place(waiter, now);
|
|
307
|
+
this.pump();
|
|
308
|
+
});
|
|
309
|
+
}
|
|
310
|
+
/** Takes up a grant. False when it went back to the pool first. @internal */
|
|
311
|
+
claim(waiter) {
|
|
312
|
+
if (waiter.state !== "leased") return false;
|
|
313
|
+
waiter.state = "active";
|
|
314
|
+
this.leased.delete(waiter);
|
|
315
|
+
return true;
|
|
316
|
+
}
|
|
317
|
+
/** Updates the limits from a response's rate-limit headers. */
|
|
318
|
+
observe(headers, slot, status, sentAt) {
|
|
319
|
+
const now = Date.now();
|
|
320
|
+
this.refill(now);
|
|
321
|
+
const concurrency = parseLimit(headers["x-ratelimit-concurrency-limit"]);
|
|
322
|
+
if (concurrency !== void 0 && concurrency > 0) {
|
|
323
|
+
const limit2 = Math.min(MAX_CONCURRENCY, Math.max(1, Math.floor(concurrency)));
|
|
324
|
+
if (limit2 !== this.serverConcurrency) {
|
|
325
|
+
if (this.serverConcurrency === void 0) this.concurrencyKnownAt = Math.min(this.concurrencyKnownAt, now);
|
|
326
|
+
this.serverConcurrency = limit2;
|
|
327
|
+
this.window = this.concurrencyLimit();
|
|
328
|
+
this.successes = 0;
|
|
329
|
+
}
|
|
330
|
+
}
|
|
331
|
+
const scope = headers["x-ratelimit-scope"];
|
|
332
|
+
const limit = parseLimit(headers["x-ratelimit-limit"]);
|
|
333
|
+
if (limit !== void 0 && limit > 0 && scope !== "concurrency") {
|
|
334
|
+
const rateWasKnown = Number.isFinite(this.rate());
|
|
335
|
+
this.serverRate = Math.max(MIN_RATE, limit);
|
|
336
|
+
const remaining = parseLimit(headers["x-ratelimit-remaining"]);
|
|
337
|
+
if (!rateWasKnown) {
|
|
338
|
+
this.tokens = remaining ?? this.burst();
|
|
339
|
+
} else if (remaining !== void 0) {
|
|
340
|
+
const elapsed = Math.max(0, now - sentAt);
|
|
341
|
+
this.tokens = Math.min(this.tokens, remaining + elapsed * this.rate() / 1e3);
|
|
342
|
+
}
|
|
343
|
+
this.tokens = Math.min(this.tokens, this.burst());
|
|
344
|
+
}
|
|
345
|
+
if (slot && status >= 200 && status < 300 && sentAt > this.loweredAt) {
|
|
346
|
+
if (this.window < this.concurrencyLimit() && ++this.successes >= this.window) {
|
|
347
|
+
this.window++;
|
|
348
|
+
this.successes = 0;
|
|
349
|
+
}
|
|
350
|
+
}
|
|
351
|
+
this.pump();
|
|
352
|
+
}
|
|
353
|
+
/**
|
|
354
|
+
* Pauses the limit a 429 names for `delayMs` (at most MAX_SHARED_PAUSE_MS).
|
|
355
|
+
* A 429 without a scope comes from a limit that covers every request.
|
|
356
|
+
*/
|
|
357
|
+
pause(scope, delayMs, slot, sentAt) {
|
|
358
|
+
const now = Date.now();
|
|
359
|
+
const until = now + Math.min(Math.max(0, delayMs), MAX_SHARED_PAUSE_MS);
|
|
360
|
+
if (scope === "concurrency") {
|
|
361
|
+
this.slotPausedUntil = Math.max(this.slotPausedUntil, until);
|
|
362
|
+
if (slot && sentAt >= this.concurrencyKnownAt) {
|
|
363
|
+
this.window = Math.max(1, Math.min(this.window - 1, this.active - 1));
|
|
364
|
+
this.successes = 0;
|
|
365
|
+
this.loweredAt = now;
|
|
366
|
+
}
|
|
367
|
+
this.holdBackSlots();
|
|
368
|
+
} else {
|
|
369
|
+
this.ratePausedUntil = Math.max(this.ratePausedUntil, until);
|
|
370
|
+
if (scope === "rps") {
|
|
371
|
+
this.refill(now);
|
|
372
|
+
this.tokens = Math.min(this.tokens, 0);
|
|
373
|
+
}
|
|
374
|
+
}
|
|
375
|
+
this.pump();
|
|
376
|
+
}
|
|
377
|
+
async admit(init) {
|
|
378
|
+
let waiter = await this.wait(init);
|
|
379
|
+
while (!this.claim(waiter)) {
|
|
380
|
+
waiter = await this.wait({ ...init, hasSlot: false, retry: true });
|
|
381
|
+
}
|
|
382
|
+
return this.permit(waiter);
|
|
383
|
+
}
|
|
384
|
+
permit(waiter) {
|
|
385
|
+
return {
|
|
386
|
+
release: () => this.release(waiter),
|
|
387
|
+
retry: (options) => {
|
|
388
|
+
if (waiter.state !== "active") return this.acquire({ ...options, slot: waiter.slot });
|
|
389
|
+
const { hasSlot } = waiter;
|
|
390
|
+
waiter.hasSlot = false;
|
|
391
|
+
waiter.state = "done";
|
|
392
|
+
this.inFlight--;
|
|
393
|
+
return this.admit({ ...options, slot: waiter.slot, hasSlot, retry: true });
|
|
394
|
+
}
|
|
395
|
+
};
|
|
396
|
+
}
|
|
397
|
+
release(waiter) {
|
|
398
|
+
if (waiter.state !== "active") return;
|
|
399
|
+
waiter.state = "done";
|
|
400
|
+
this.inFlight--;
|
|
401
|
+
if (waiter.hasSlot) {
|
|
402
|
+
waiter.hasSlot = false;
|
|
403
|
+
this.active--;
|
|
404
|
+
}
|
|
405
|
+
this.pump();
|
|
406
|
+
}
|
|
407
|
+
concurrencyLimit() {
|
|
408
|
+
const server = this.serverConcurrency ?? (this.maxConcurrency === void 0 ? DEFAULT_CONCURRENCY : Infinity);
|
|
409
|
+
return Math.min(this.maxConcurrency ?? Infinity, server);
|
|
410
|
+
}
|
|
411
|
+
rate() {
|
|
412
|
+
return Math.min(this.maxRate ?? Infinity, this.serverRate ?? Infinity);
|
|
413
|
+
}
|
|
414
|
+
/** The API's bucket holds as many tokens as its concurrency limit. */
|
|
415
|
+
burst() {
|
|
416
|
+
const rate = this.rate();
|
|
417
|
+
if (!Number.isFinite(rate)) return Infinity;
|
|
418
|
+
const own = this.maxRate === void 0 ? Infinity : Math.ceil(this.maxRate);
|
|
419
|
+
return Math.max(1, Math.min(this.serverConcurrency ?? Math.ceil(rate), own));
|
|
420
|
+
}
|
|
421
|
+
refill(now) {
|
|
422
|
+
const rate = this.rate();
|
|
423
|
+
if (Number.isFinite(rate)) {
|
|
424
|
+
const elapsed = Math.max(0, now - this.refilledAt);
|
|
425
|
+
this.tokens = Math.min(this.burst(), this.tokens + elapsed * rate / 1e3);
|
|
426
|
+
}
|
|
427
|
+
this.refilledAt = now;
|
|
428
|
+
}
|
|
429
|
+
/** Puts a queued waiter where it can next make progress. */
|
|
430
|
+
place(waiter, now) {
|
|
431
|
+
const ready = waiter.hasSlot ? Math.max(waiter.notBefore, this.slotPausedUntil) : waiter.notBefore;
|
|
432
|
+
if (ready > now) {
|
|
433
|
+
waiter.notBefore = ready;
|
|
434
|
+
this.delay(waiter);
|
|
435
|
+
} else if (waiter.slot && !waiter.hasSlot) {
|
|
436
|
+
(waiter.retry ? this.slotRetries : this.slotQueue).push(waiter);
|
|
437
|
+
} else {
|
|
438
|
+
(waiter.retry ? this.rateRetries : this.rateQueue).push(waiter);
|
|
439
|
+
}
|
|
440
|
+
}
|
|
441
|
+
delay(waiter) {
|
|
442
|
+
let low = 0;
|
|
443
|
+
let high = this.delayed.length;
|
|
444
|
+
while (low < high) {
|
|
445
|
+
const mid = low + high >>> 1;
|
|
446
|
+
if (this.delayed[mid].notBefore <= waiter.notBefore) low = mid + 1;
|
|
447
|
+
else high = mid;
|
|
448
|
+
}
|
|
449
|
+
this.delayed.splice(low, 0, waiter);
|
|
450
|
+
}
|
|
451
|
+
nextDelayed() {
|
|
452
|
+
while (this.delayed.length > 0 && this.delayed[0].state !== "queued") this.delayed.shift();
|
|
453
|
+
return this.delayed[0];
|
|
454
|
+
}
|
|
455
|
+
/**
|
|
456
|
+
* After a concurrency 429, requests that hold a slot but have not been sent
|
|
457
|
+
* give it back and wait for the pause; a queued retry keeps its slot.
|
|
458
|
+
*/
|
|
459
|
+
holdBackSlots() {
|
|
460
|
+
const returned = [];
|
|
461
|
+
for (const queue of [this.rateRetries, this.rateQueue]) {
|
|
462
|
+
for (const waiter of queue.extract((w) => w.hasSlot)) {
|
|
463
|
+
if (waiter.retry) {
|
|
464
|
+
waiter.notBefore = Math.max(waiter.notBefore, this.slotPausedUntil);
|
|
465
|
+
this.delay(waiter);
|
|
466
|
+
} else {
|
|
467
|
+
waiter.hasSlot = false;
|
|
468
|
+
this.active--;
|
|
469
|
+
returned.push(waiter);
|
|
470
|
+
}
|
|
471
|
+
}
|
|
472
|
+
}
|
|
473
|
+
this.slotQueue.unshiftAll(returned);
|
|
474
|
+
}
|
|
475
|
+
pump() {
|
|
476
|
+
const now = Date.now();
|
|
477
|
+
if (now < this.pumpedAt) this.clampAfterClockStep(now);
|
|
478
|
+
this.pumpedAt = now;
|
|
479
|
+
this.reclaim(now);
|
|
480
|
+
for (let waiter = this.nextDelayed(); waiter && waiter.notBefore <= now; waiter = this.nextDelayed()) {
|
|
481
|
+
this.delayed.shift();
|
|
482
|
+
if (waiter.hasSlot && this.active > this.window) {
|
|
483
|
+
waiter.hasSlot = false;
|
|
484
|
+
this.active--;
|
|
485
|
+
}
|
|
486
|
+
this.place(waiter, now);
|
|
487
|
+
}
|
|
488
|
+
if (now >= this.slotPausedUntil) {
|
|
489
|
+
while (this.active < this.window) {
|
|
490
|
+
const waiter = this.slotRetries.shift() ?? this.slotQueue.shift();
|
|
491
|
+
if (!waiter) break;
|
|
492
|
+
waiter.hasSlot = true;
|
|
493
|
+
this.active++;
|
|
494
|
+
(waiter.retry ? this.rateRetries : this.rateQueue).push(waiter);
|
|
495
|
+
}
|
|
496
|
+
}
|
|
497
|
+
if (now >= this.ratePausedUntil) {
|
|
498
|
+
this.refill(now);
|
|
499
|
+
const limited = Number.isFinite(this.rate());
|
|
500
|
+
for (; ; ) {
|
|
501
|
+
const queue = this.rateRetries.peek() ? this.rateRetries : this.rateQueue;
|
|
502
|
+
const waiter = queue.peek();
|
|
503
|
+
if (!waiter) break;
|
|
504
|
+
if (limited) {
|
|
505
|
+
if (this.tokens < 1 - EPSILON) break;
|
|
506
|
+
this.tokens -= 1;
|
|
507
|
+
} else if (this.inFlight >= COLD_LIMIT) {
|
|
508
|
+
break;
|
|
509
|
+
}
|
|
510
|
+
queue.shift();
|
|
511
|
+
this.grant(waiter, now);
|
|
512
|
+
}
|
|
513
|
+
}
|
|
514
|
+
this.schedule(now);
|
|
515
|
+
}
|
|
516
|
+
grant(waiter, now) {
|
|
517
|
+
waiter.state = "leased";
|
|
518
|
+
waiter.leaseUntil = now + LEASE_MS;
|
|
519
|
+
this.leased.add(waiter);
|
|
520
|
+
this.inFlight++;
|
|
521
|
+
this.detach(waiter);
|
|
522
|
+
waiter.resolve(waiter);
|
|
523
|
+
}
|
|
524
|
+
/**
|
|
525
|
+
* A wall clock that steps backwards must not stretch a pause, a lease or a
|
|
526
|
+
* retry's wait beyond their own maximums. Mapping every time through the same
|
|
527
|
+
* `min` keeps the delayed queue in order.
|
|
528
|
+
*/
|
|
529
|
+
clampAfterClockStep(now) {
|
|
530
|
+
this.ratePausedUntil = Math.min(this.ratePausedUntil, now + MAX_SHARED_PAUSE_MS);
|
|
531
|
+
this.slotPausedUntil = Math.min(this.slotPausedUntil, now + MAX_SHARED_PAUSE_MS);
|
|
532
|
+
for (const waiter of this.leased) waiter.leaseUntil = Math.min(waiter.leaseUntil, now + LEASE_MS);
|
|
533
|
+
for (const waiter of this.delayed) waiter.notBefore = Math.min(waiter.notBefore, now + MAX_SHARED_PAUSE_MS);
|
|
534
|
+
}
|
|
535
|
+
/** Returns grants not taken up in time to the pool. */
|
|
536
|
+
reclaim(now) {
|
|
537
|
+
for (const waiter of this.leased) {
|
|
538
|
+
if (waiter.leaseUntil > now) continue;
|
|
539
|
+
this.leased.delete(waiter);
|
|
540
|
+
waiter.state = "done";
|
|
541
|
+
this.inFlight--;
|
|
542
|
+
if (waiter.hasSlot) {
|
|
543
|
+
waiter.hasSlot = false;
|
|
544
|
+
this.active--;
|
|
545
|
+
}
|
|
546
|
+
if (Number.isFinite(this.rate())) this.tokens = Math.min(this.burst(), this.tokens + 1);
|
|
547
|
+
}
|
|
548
|
+
}
|
|
549
|
+
/** Keeps at most one shared timer, and none while nothing waits. */
|
|
550
|
+
schedule(now) {
|
|
551
|
+
let wake = Infinity;
|
|
552
|
+
const slotWaiting = this.slotRetries.peek() ?? this.slotQueue.peek();
|
|
553
|
+
if (slotWaiting && this.slotPausedUntil > now) wake = this.slotPausedUntil;
|
|
554
|
+
const rateWaiting = this.rateRetries.peek() ?? this.rateQueue.peek();
|
|
555
|
+
if (rateWaiting) {
|
|
556
|
+
const rate = this.rate();
|
|
557
|
+
if (this.ratePausedUntil > now) wake = Math.min(wake, this.ratePausedUntil);
|
|
558
|
+
else if (Number.isFinite(rate) && this.tokens < 1 - EPSILON) {
|
|
559
|
+
wake = Math.min(wake, now + (1 - this.tokens) * 1e3 / rate);
|
|
560
|
+
}
|
|
561
|
+
}
|
|
562
|
+
const next = this.nextDelayed();
|
|
563
|
+
if (next) wake = Math.min(wake, next.notBefore);
|
|
564
|
+
if ((slotWaiting || rateWaiting || next) && this.leased.size > 0) {
|
|
565
|
+
for (const waiter of this.leased) wake = Math.min(wake, waiter.leaseUntil);
|
|
566
|
+
}
|
|
567
|
+
if (this.timer !== void 0) {
|
|
568
|
+
clearTimeout(this.timer);
|
|
569
|
+
this.timer = void 0;
|
|
570
|
+
}
|
|
571
|
+
if (wake === Infinity) return;
|
|
572
|
+
const delay = Math.min(MAX_TIMER_DELAY, Math.max(1, Math.ceil(wake - now)));
|
|
573
|
+
this.timer = setTimeout(() => {
|
|
574
|
+
this.timer = void 0;
|
|
575
|
+
this.pump();
|
|
576
|
+
}, delay);
|
|
577
|
+
}
|
|
578
|
+
fail(waiter, reason) {
|
|
579
|
+
if (waiter.state !== "queued") return;
|
|
580
|
+
waiter.state = "done";
|
|
581
|
+
this.detach(waiter);
|
|
582
|
+
if (waiter.hasSlot) {
|
|
583
|
+
waiter.hasSlot = false;
|
|
584
|
+
this.active--;
|
|
585
|
+
}
|
|
586
|
+
waiter.reject(reason);
|
|
587
|
+
}
|
|
588
|
+
/** Rejects a waiter before it is queued, freeing a slot it was handed. */
|
|
589
|
+
settleEarly(waiter, reason) {
|
|
590
|
+
waiter.state = "done";
|
|
591
|
+
if (waiter.hasSlot) {
|
|
592
|
+
waiter.hasSlot = false;
|
|
593
|
+
this.active--;
|
|
594
|
+
this.pump();
|
|
595
|
+
}
|
|
596
|
+
waiter.reject(reason);
|
|
597
|
+
}
|
|
598
|
+
detach(waiter) {
|
|
599
|
+
if (waiter.timer !== void 0) clearTimeout(waiter.timer);
|
|
600
|
+
waiter.timer = void 0;
|
|
601
|
+
waiter.unsubscribe?.();
|
|
602
|
+
waiter.unsubscribe = void 0;
|
|
603
|
+
}
|
|
604
|
+
};
|
|
605
|
+
function parseLimit(value) {
|
|
606
|
+
if (value === void 0 || !/^\s*\d+(?:\.\d+)?\s*$/.test(value)) return void 0;
|
|
607
|
+
const n = Number(value);
|
|
608
|
+
return Number.isFinite(n) ? n : void 0;
|
|
609
|
+
}
|
|
129
610
|
|
|
130
611
|
// src/http-client.ts
|
|
131
612
|
var DEFAULT_BASE_URL = "https://api.triqai.com";
|
|
@@ -134,8 +615,9 @@ var DEFAULT_RETRY_DELAY = 500;
|
|
|
134
615
|
var DEFAULT_MAX_RETRY_DELAY = 3e4;
|
|
135
616
|
var DEFAULT_TIMEOUT = 6e4;
|
|
136
617
|
var DEFAULT_MAX_RETRY_TIME = 3e5;
|
|
137
|
-
var
|
|
618
|
+
var MAX_TIMER_DELAY2 = 2147483647;
|
|
138
619
|
var RETRYABLE_STATUS_CODES = /* @__PURE__ */ new Set([429, 500, 503, 504]);
|
|
620
|
+
var MAX_RESET_WAIT_MS = 1e4;
|
|
139
621
|
var HttpClient = class {
|
|
140
622
|
apiKey;
|
|
141
623
|
baseUrl;
|
|
@@ -147,6 +629,7 @@ var HttpClient = class {
|
|
|
147
629
|
defaultHeaders;
|
|
148
630
|
onRequest;
|
|
149
631
|
onResponse;
|
|
632
|
+
pacer;
|
|
150
633
|
constructor(apiKey, config = {}) {
|
|
151
634
|
if (!apiKey) {
|
|
152
635
|
throw new Error(
|
|
@@ -160,23 +643,30 @@ var HttpClient = class {
|
|
|
160
643
|
this.maxRetryDelay = config.maxRetryDelay ?? DEFAULT_MAX_RETRY_DELAY;
|
|
161
644
|
this.timeout = config.timeout ?? DEFAULT_TIMEOUT;
|
|
162
645
|
this.maxRetryTime = config.maxRetryTime ?? DEFAULT_MAX_RETRY_TIME;
|
|
163
|
-
if (!Number.isFinite(this.maxRetryTime) || this.maxRetryTime <= 0 || this.maxRetryTime >
|
|
164
|
-
throw new Error(`maxRetryTime must be greater than 0 and at most ${
|
|
646
|
+
if (!Number.isFinite(this.maxRetryTime) || this.maxRetryTime <= 0 || this.maxRetryTime > MAX_TIMER_DELAY2) {
|
|
647
|
+
throw new Error(`maxRetryTime must be greater than 0 and at most ${MAX_TIMER_DELAY2}ms`);
|
|
165
648
|
}
|
|
166
649
|
this.defaultHeaders = config.defaultHeaders ?? {};
|
|
167
650
|
this.onRequest = config.onRequest;
|
|
168
651
|
this.onResponse = config.onResponse;
|
|
652
|
+
const pacing = config.pacing === void 0 ? pacingByDefault() : config.pacing;
|
|
653
|
+
if (pacing !== true && pacing !== false && !isPlainObject(pacing)) {
|
|
654
|
+
throw new Error("pacing must be a boolean or an options object");
|
|
655
|
+
}
|
|
656
|
+
if (pacing !== false) this.pacer = new Pacer(pacing === true ? {} : pacing, this.maxRetryTime);
|
|
169
657
|
}
|
|
170
|
-
async get(path, query) {
|
|
171
|
-
return this.request("GET", path, void 0, query);
|
|
658
|
+
async get(path, query, options) {
|
|
659
|
+
return this.request("GET", path, void 0, query, void 0, options);
|
|
172
660
|
}
|
|
173
|
-
async post(path, body) {
|
|
174
|
-
return this.request("POST", path, body);
|
|
661
|
+
async post(path, body, options) {
|
|
662
|
+
return this.request("POST", path, body, void 0, void 0, options);
|
|
175
663
|
}
|
|
176
|
-
async delete(path, body) {
|
|
177
|
-
return this.request("DELETE", path, body);
|
|
664
|
+
async delete(path, body, options) {
|
|
665
|
+
return this.request("DELETE", path, body, void 0, void 0, options);
|
|
178
666
|
}
|
|
179
|
-
async request(method, path, body, query, extraHeaders) {
|
|
667
|
+
async request(method, path, body, query, extraHeaders, options) {
|
|
668
|
+
const signal = options?.signal;
|
|
669
|
+
throwIfAborted(signal);
|
|
180
670
|
const url = this.buildUrl(path, query);
|
|
181
671
|
const headers = {
|
|
182
672
|
"X-API-Key": this.apiKey,
|
|
@@ -188,116 +678,161 @@ var HttpClient = class {
|
|
|
188
678
|
if (body !== void 0) {
|
|
189
679
|
headers["Content-Type"] = "application/json";
|
|
190
680
|
}
|
|
191
|
-
const
|
|
681
|
+
const pacer = this.pacer;
|
|
682
|
+
const takesSlot = pacer !== void 0 && takesEnrichmentSlot(method, url);
|
|
683
|
+
let deadline = pacer ? Infinity : performance.now() + this.maxRetryTime;
|
|
684
|
+
const minRetryMs = pacer ? Math.min(1e3, this.timeout / 2) : 0;
|
|
192
685
|
const serializedBody = body !== void 0 ? JSON.stringify(body) : void 0;
|
|
193
686
|
let lastError;
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
687
|
+
let retryAt;
|
|
688
|
+
let permit;
|
|
689
|
+
const budgetExhausted = () => lastError ?? new TimeoutError(`Request exceeded ${this.maxRetryTime}ms total retry budget`);
|
|
690
|
+
try {
|
|
691
|
+
for (let attempt = 0; attempt <= this.maxRetries; attempt++) {
|
|
692
|
+
if (attempt > 0) {
|
|
693
|
+
const delay = retryAt === void 0 ? this.calculateDelay(attempt, lastError) : Math.max(0, retryAt - performance.now());
|
|
694
|
+
retryAt = void 0;
|
|
695
|
+
const cutoff = deadline - minRetryMs;
|
|
696
|
+
if (delay >= cutoff - performance.now()) {
|
|
697
|
+
throw lastError ?? new TimeoutError("Request retry budget exhausted");
|
|
698
|
+
}
|
|
699
|
+
if (permit) {
|
|
700
|
+
const wallOffset = Date.now() - performance.now();
|
|
701
|
+
permit = await permit.retry({
|
|
702
|
+
notBefore: Date.now() + delay,
|
|
703
|
+
deadline: cutoff + wallOffset,
|
|
704
|
+
signal,
|
|
705
|
+
expired: budgetExhausted
|
|
706
|
+
});
|
|
707
|
+
} else {
|
|
708
|
+
await sleep(delay, signal);
|
|
709
|
+
}
|
|
710
|
+
} else if (pacer) {
|
|
711
|
+
permit = await pacer.acquire({
|
|
712
|
+
slot: takesSlot,
|
|
713
|
+
deadline: Date.now() + pacer.maxWait,
|
|
714
|
+
signal,
|
|
715
|
+
expired: () => new PacingTimeoutError(
|
|
716
|
+
`Request waited ${pacer.maxWait}ms for its turn under pacing and was not sent: ${method} ${path}`
|
|
717
|
+
)
|
|
718
|
+
});
|
|
719
|
+
deadline = performance.now() + this.maxRetryTime;
|
|
720
|
+
}
|
|
721
|
+
throwIfAborted(signal);
|
|
722
|
+
const remainingMs = deadline - performance.now();
|
|
723
|
+
if (pacer && attempt > 0 && remainingMs < minRetryMs) {
|
|
198
724
|
throw lastError ?? new TimeoutError("Request retry budget exhausted");
|
|
199
725
|
}
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
const attemptTimeout = Math.min(this.timeout, remainingMs);
|
|
207
|
-
const startMs = Date.now();
|
|
208
|
-
this.onRequest?.({ method, url, headers: { ...headers }, body });
|
|
209
|
-
try {
|
|
210
|
-
const controller = new AbortController();
|
|
211
|
-
const timeoutId = setTimeout(() => controller.abort(), attemptTimeout);
|
|
212
|
-
let response;
|
|
213
|
-
let responseBody;
|
|
726
|
+
if (remainingMs <= 0) {
|
|
727
|
+
throw new TimeoutError(`Request exceeded ${this.maxRetryTime}ms total retry budget`);
|
|
728
|
+
}
|
|
729
|
+
const attemptTimeout = Math.min(this.timeout, remainingMs);
|
|
730
|
+
const startMs = Date.now();
|
|
731
|
+
this.onRequest?.({ method, url, headers: { ...headers }, body });
|
|
214
732
|
try {
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
733
|
+
const controller = new AbortController();
|
|
734
|
+
const timeoutId = setTimeout(() => controller.abort(), attemptTimeout);
|
|
735
|
+
const unlink = signal ? onAbort(signal, () => controller.abort()) : void 0;
|
|
736
|
+
let response;
|
|
737
|
+
let responseBody;
|
|
738
|
+
try {
|
|
739
|
+
response = await fetch(url, {
|
|
740
|
+
method,
|
|
741
|
+
headers,
|
|
742
|
+
body: serializedBody,
|
|
743
|
+
signal: controller.signal
|
|
744
|
+
});
|
|
745
|
+
responseBody = await response.json().catch((err) => {
|
|
746
|
+
if (err instanceof SyntaxError || !response.ok) return null;
|
|
747
|
+
throw err;
|
|
748
|
+
});
|
|
749
|
+
if (controller.signal.aborted && response.ok) {
|
|
750
|
+
throw new DOMException("The operation was aborted.", "AbortError");
|
|
751
|
+
}
|
|
752
|
+
} finally {
|
|
753
|
+
clearTimeout(timeoutId);
|
|
754
|
+
unlink?.();
|
|
227
755
|
}
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
const durationMs = Date.now() - startMs;
|
|
233
|
-
this.onResponse?.({
|
|
234
|
-
status: response.status,
|
|
235
|
-
headers: responseHeaders,
|
|
236
|
-
body: responseBody,
|
|
237
|
-
durationMs,
|
|
238
|
-
retryCount: attempt
|
|
239
|
-
});
|
|
240
|
-
if (response.ok) {
|
|
241
|
-
return {
|
|
242
|
-
data: responseBody,
|
|
756
|
+
const responseHeaders = parseHeaders(response.headers);
|
|
757
|
+
const durationMs = Date.now() - startMs;
|
|
758
|
+
pacer?.observe(responseHeaders, takesSlot, response.status, startMs);
|
|
759
|
+
this.onResponse?.({
|
|
243
760
|
status: response.status,
|
|
244
761
|
headers: responseHeaders,
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
762
|
+
body: responseBody,
|
|
763
|
+
durationMs,
|
|
764
|
+
retryCount: attempt
|
|
765
|
+
});
|
|
766
|
+
if (response.ok) {
|
|
767
|
+
return {
|
|
768
|
+
data: responseBody,
|
|
769
|
+
status: response.status,
|
|
770
|
+
headers: responseHeaders,
|
|
771
|
+
rateLimitInfo: parseRateLimitHeaders(responseHeaders)
|
|
772
|
+
};
|
|
773
|
+
}
|
|
774
|
+
const error = this.mapError(response.status, responseBody, responseHeaders);
|
|
775
|
+
lastError = error;
|
|
776
|
+
if (pacer && error instanceof RateLimitError) {
|
|
777
|
+
const delay = this.rateLimitDelay(attempt + 1, error, responseHeaders);
|
|
778
|
+
retryAt = performance.now() + delay;
|
|
779
|
+
pacer.pause(error.rateLimitInfo.scope, delay, takesSlot, startMs);
|
|
780
|
+
}
|
|
781
|
+
const shouldRetry = this.canRetry(
|
|
262
782
|
attempt,
|
|
263
783
|
method,
|
|
264
784
|
headers,
|
|
265
|
-
isRetryableError(
|
|
785
|
+
isRetryableError(error)
|
|
266
786
|
);
|
|
267
|
-
if (!
|
|
268
|
-
throw err;
|
|
269
|
-
}
|
|
270
|
-
lastError = err;
|
|
271
|
-
continue;
|
|
272
|
-
}
|
|
273
|
-
if (err instanceof DOMException && err.name === "AbortError") {
|
|
274
|
-
lastError = new TimeoutError(
|
|
275
|
-
`Request timed out after ${attemptTimeout}ms: ${method} ${path}`
|
|
276
|
-
);
|
|
277
|
-
if (!this.canRetry(attempt, method, headers, true)) {
|
|
787
|
+
if (!shouldRetry) {
|
|
278
788
|
throw lastError;
|
|
279
789
|
}
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
790
|
+
} catch (err) {
|
|
791
|
+
if (signal?.aborted) throw abortReason(signal);
|
|
792
|
+
if (err instanceof TriqaiError) {
|
|
793
|
+
const canRetry = this.canRetry(
|
|
794
|
+
attempt,
|
|
795
|
+
method,
|
|
796
|
+
headers,
|
|
797
|
+
isRetryableError(err)
|
|
798
|
+
);
|
|
799
|
+
if (!canRetry) {
|
|
800
|
+
throw err;
|
|
801
|
+
}
|
|
802
|
+
lastError = err;
|
|
803
|
+
continue;
|
|
804
|
+
}
|
|
805
|
+
if (err instanceof DOMException && err.name === "AbortError") {
|
|
806
|
+
lastError = new TimeoutError(
|
|
807
|
+
`Request timed out after ${attemptTimeout}ms: ${method} ${path}`
|
|
808
|
+
);
|
|
809
|
+
if (!this.canRetry(attempt, method, headers, true)) {
|
|
810
|
+
throw lastError;
|
|
811
|
+
}
|
|
812
|
+
continue;
|
|
813
|
+
}
|
|
814
|
+
if (isNetworkError(err)) {
|
|
815
|
+
lastError = new ConnectionError(
|
|
816
|
+
`Network error: ${err instanceof Error ? err.message : String(err)}`
|
|
817
|
+
);
|
|
818
|
+
if (!this.canRetry(attempt, method, headers, true)) {
|
|
819
|
+
throw lastError;
|
|
820
|
+
}
|
|
821
|
+
continue;
|
|
288
822
|
}
|
|
289
|
-
|
|
823
|
+
throw err;
|
|
290
824
|
}
|
|
291
|
-
throw err;
|
|
292
825
|
}
|
|
826
|
+
throw lastError ?? new TriqaiError("Request failed after retries", 0);
|
|
827
|
+
} finally {
|
|
828
|
+
permit?.release();
|
|
293
829
|
}
|
|
294
|
-
throw lastError ?? new TriqaiError("Request failed after retries", 0);
|
|
295
830
|
}
|
|
296
831
|
/**
|
|
297
832
|
* Variant that injects custom headers (used by resources for Idempotency-Key etc.).
|
|
298
833
|
*/
|
|
299
|
-
async postWithHeaders(path, body, headers, query) {
|
|
300
|
-
return this.request("POST", path, body, query, headers);
|
|
834
|
+
async postWithHeaders(path, body, headers, query, options) {
|
|
835
|
+
return this.request("POST", path, body, query, headers, options);
|
|
301
836
|
}
|
|
302
837
|
buildUrl(path, query) {
|
|
303
838
|
const isAbsoluteUrl = /^https?:\/\//i.test(path);
|
|
@@ -326,6 +861,22 @@ var HttpClient = class {
|
|
|
326
861
|
const exponential = Math.min(this.retryDelay * Math.pow(2, attempt - 1), this.maxRetryDelay / 1.2);
|
|
327
862
|
return exponential * (1 + 0.2 * Math.random());
|
|
328
863
|
}
|
|
864
|
+
/**
|
|
865
|
+
* The wait after a 429. Without Retry-After, the limit's reset time is used
|
|
866
|
+
* when it is near, measured against the response's Date header so the
|
|
867
|
+
* client's clock does not matter; otherwise the normal backoff.
|
|
868
|
+
*/
|
|
869
|
+
rateLimitDelay(attempt, error, headers) {
|
|
870
|
+
const { retryAfter, reset } = error.rateLimitInfo;
|
|
871
|
+
if (!retryAfter && reset !== void 0) {
|
|
872
|
+
const serverNow = headers.date === void 0 ? NaN : Date.parse(headers.date);
|
|
873
|
+
const untilReset = Date.parse(reset) - (Number.isNaN(serverNow) ? Date.now() : serverNow);
|
|
874
|
+
if (untilReset > 0 && untilReset <= MAX_RESET_WAIT_MS) {
|
|
875
|
+
return untilReset + Math.min(untilReset * 0.2, 1e3) * Math.random();
|
|
876
|
+
}
|
|
877
|
+
}
|
|
878
|
+
return this.calculateDelay(attempt, error);
|
|
879
|
+
}
|
|
329
880
|
canRetry(attempt, method, headers, retryableSignal) {
|
|
330
881
|
return retryableSignal && attempt < this.maxRetries && isIdempotent(method, headers);
|
|
331
882
|
}
|
|
@@ -458,7 +1009,7 @@ function isNetworkError(err) {
|
|
|
458
1009
|
const message = err.message.toLowerCase();
|
|
459
1010
|
const hasNetworkSignal = message.includes("fetch") || message.includes("network") || message.includes("econnreset") || message.includes("enotfound") || message.includes("econnrefused") || message.includes("etimedout");
|
|
460
1011
|
if (err instanceof TypeError) {
|
|
461
|
-
return hasNetworkSignal;
|
|
1012
|
+
return hasNetworkSignal || message === "terminated";
|
|
462
1013
|
}
|
|
463
1014
|
if (err.name === "NetworkError") {
|
|
464
1015
|
return true;
|
|
@@ -469,8 +1020,38 @@ function isNetworkError(err) {
|
|
|
469
1020
|
}
|
|
470
1021
|
return false;
|
|
471
1022
|
}
|
|
472
|
-
function
|
|
473
|
-
|
|
1023
|
+
function takesEnrichmentSlot(method, url) {
|
|
1024
|
+
if (method !== "POST") return false;
|
|
1025
|
+
const path = url.split("?")[0].replace(/\/+$/, "");
|
|
1026
|
+
return path.endsWith("/v1/transactions/enrich");
|
|
1027
|
+
}
|
|
1028
|
+
function pacingByDefault() {
|
|
1029
|
+
const g = globalThis;
|
|
1030
|
+
if (typeof g.process?.versions?.node !== "string") return false;
|
|
1031
|
+
if (g.Deno !== void 0 || g.EdgeRuntime !== void 0 || g.WebSocketPair !== void 0) return false;
|
|
1032
|
+
return g.navigator?.userAgent !== "Cloudflare-Workers";
|
|
1033
|
+
}
|
|
1034
|
+
function isPlainObject(value) {
|
|
1035
|
+
if (typeof value !== "object" || value === null) return false;
|
|
1036
|
+
const proto = Object.getPrototypeOf(value);
|
|
1037
|
+
return proto === Object.prototype || proto === null;
|
|
1038
|
+
}
|
|
1039
|
+
function sleep(ms, signal) {
|
|
1040
|
+
if (!signal) return new Promise((resolve) => setTimeout(resolve, ms));
|
|
1041
|
+
return new Promise((resolve, reject) => {
|
|
1042
|
+
if (signal.aborted) {
|
|
1043
|
+
reject(abortReason(signal));
|
|
1044
|
+
return;
|
|
1045
|
+
}
|
|
1046
|
+
const timer = setTimeout(() => {
|
|
1047
|
+
unsubscribe();
|
|
1048
|
+
resolve();
|
|
1049
|
+
}, ms);
|
|
1050
|
+
const unsubscribe = onAbort(signal, () => {
|
|
1051
|
+
clearTimeout(timer);
|
|
1052
|
+
reject(abortReason(signal));
|
|
1053
|
+
});
|
|
1054
|
+
});
|
|
474
1055
|
}
|
|
475
1056
|
|
|
476
1057
|
// src/resources/banks.ts
|
|
@@ -479,13 +1060,13 @@ var Banks = class {
|
|
|
479
1060
|
this.http = http;
|
|
480
1061
|
}
|
|
481
1062
|
/** Exact, case-insensitive name lookup with an optional country of origin. Costs zero credits. */
|
|
482
|
-
async search(params) {
|
|
483
|
-
const resp = await this.http.get("/v1/banks", { ...params });
|
|
1063
|
+
async search(params, options) {
|
|
1064
|
+
const resp = await this.http.get("/v1/banks", { ...params }, options);
|
|
484
1065
|
return resp.data.data;
|
|
485
1066
|
}
|
|
486
1067
|
/** Retrieve stored bank details by UUID. */
|
|
487
|
-
async get(id) {
|
|
488
|
-
const resp = await this.http.get(`/v1/banks/${encodeURIComponent(id)}
|
|
1068
|
+
async get(id, options) {
|
|
1069
|
+
const resp = await this.http.get(`/v1/banks/${encodeURIComponent(id)}`, void 0, options);
|
|
489
1070
|
return resp.data.data.bank;
|
|
490
1071
|
}
|
|
491
1072
|
};
|
|
@@ -501,6 +1082,7 @@ var Categories = class {
|
|
|
501
1082
|
* Returns the full category tree used for transaction classification,
|
|
502
1083
|
* including MCC, SIC, and NAICS codes.
|
|
503
1084
|
*
|
|
1085
|
+
* @param options - Optional `signal` to cancel the call.
|
|
504
1086
|
* @returns Array of category info objects and the total count.
|
|
505
1087
|
*
|
|
506
1088
|
* @example
|
|
@@ -509,8 +1091,8 @@ var Categories = class {
|
|
|
509
1091
|
* console.log(`${total} categories available`);
|
|
510
1092
|
* ```
|
|
511
1093
|
*/
|
|
512
|
-
async list() {
|
|
513
|
-
const resp = await this.http.get("/v1/categories");
|
|
1094
|
+
async list(options) {
|
|
1095
|
+
const resp = await this.http.get("/v1/categories", void 0, options);
|
|
514
1096
|
return {
|
|
515
1097
|
categories: resp.data.data.categories,
|
|
516
1098
|
total: resp.data.data.total,
|
|
@@ -528,6 +1110,7 @@ var Intermediaries = class {
|
|
|
528
1110
|
* Get an intermediary (payment processor / platform) by ID.
|
|
529
1111
|
*
|
|
530
1112
|
* @param id - Intermediary UUID.
|
|
1113
|
+
* @param options - Optional `signal` to cancel the call.
|
|
531
1114
|
* @returns The intermediary data (name, icon, description, website, domain, etc.).
|
|
532
1115
|
*
|
|
533
1116
|
* @example
|
|
@@ -536,9 +1119,11 @@ var Intermediaries = class {
|
|
|
536
1119
|
* console.log(intermediary.name); // "PayPal", "Square", etc.
|
|
537
1120
|
* ```
|
|
538
1121
|
*/
|
|
539
|
-
async get(id) {
|
|
1122
|
+
async get(id, options) {
|
|
540
1123
|
const resp = await this.http.get(
|
|
541
|
-
`/v1/intermediaries/${encodeURIComponent(id)}
|
|
1124
|
+
`/v1/intermediaries/${encodeURIComponent(id)}`,
|
|
1125
|
+
void 0,
|
|
1126
|
+
options
|
|
542
1127
|
);
|
|
543
1128
|
return resp.data.data.intermediary;
|
|
544
1129
|
}
|
|
@@ -621,12 +1206,12 @@ var IssueReports = class {
|
|
|
621
1206
|
* console.log(report.id, report.status);
|
|
622
1207
|
* ```
|
|
623
1208
|
*/
|
|
624
|
-
async create(params) {
|
|
1209
|
+
async create(params, options) {
|
|
625
1210
|
const resp = await this.http.post("/v1/report-issue", {
|
|
626
1211
|
transaction_id: params.transactionId,
|
|
627
1212
|
description: params.description,
|
|
628
1213
|
fields: params.fields
|
|
629
|
-
});
|
|
1214
|
+
}, options);
|
|
630
1215
|
return resp.data.data.issueReport;
|
|
631
1216
|
}
|
|
632
1217
|
/**
|
|
@@ -643,12 +1228,12 @@ var IssueReports = class {
|
|
|
643
1228
|
* }
|
|
644
1229
|
* ```
|
|
645
1230
|
*/
|
|
646
|
-
async list(params) {
|
|
1231
|
+
async list(params, options) {
|
|
647
1232
|
const fetchPage = async (page, size) => {
|
|
648
1233
|
const query = { page, size };
|
|
649
1234
|
if (params?.status) query.status = params.status;
|
|
650
1235
|
if (params?.transactionId) query.transaction_id = params.transactionId;
|
|
651
|
-
const resp = await this.http.get("/v1/report-issue", query);
|
|
1236
|
+
const resp = await this.http.get("/v1/report-issue", query, options);
|
|
652
1237
|
const pageInfo = {
|
|
653
1238
|
page: resp.data.meta.page,
|
|
654
1239
|
size: resp.data.meta.size,
|
|
@@ -663,11 +1248,14 @@ var IssueReports = class {
|
|
|
663
1248
|
* Get a single issue report by ID.
|
|
664
1249
|
*
|
|
665
1250
|
* @param id - Issue report UUID.
|
|
1251
|
+
* @param options - Optional `signal` to cancel the call.
|
|
666
1252
|
* @returns The issue report details.
|
|
667
1253
|
*/
|
|
668
|
-
async get(id) {
|
|
1254
|
+
async get(id, options) {
|
|
669
1255
|
const resp = await this.http.get(
|
|
670
|
-
`/v1/report-issue/${encodeURIComponent(id)}
|
|
1256
|
+
`/v1/report-issue/${encodeURIComponent(id)}`,
|
|
1257
|
+
void 0,
|
|
1258
|
+
options
|
|
671
1259
|
);
|
|
672
1260
|
return resp.data.data.issueReport;
|
|
673
1261
|
}
|
|
@@ -682,6 +1270,7 @@ var Locations = class {
|
|
|
682
1270
|
* Get a location by ID.
|
|
683
1271
|
*
|
|
684
1272
|
* @param id - Location UUID.
|
|
1273
|
+
* @param options - Optional `signal` to cancel the call.
|
|
685
1274
|
* @returns The location data (name, formatted address, coordinates, phone, rating, etc.).
|
|
686
1275
|
*
|
|
687
1276
|
* @example
|
|
@@ -690,9 +1279,11 @@ var Locations = class {
|
|
|
690
1279
|
* console.log(location.formatted, location.structured.city);
|
|
691
1280
|
* ```
|
|
692
1281
|
*/
|
|
693
|
-
async get(id) {
|
|
1282
|
+
async get(id, options) {
|
|
694
1283
|
const resp = await this.http.get(
|
|
695
|
-
`/v1/locations/${encodeURIComponent(id)}
|
|
1284
|
+
`/v1/locations/${encodeURIComponent(id)}`,
|
|
1285
|
+
void 0,
|
|
1286
|
+
options
|
|
696
1287
|
);
|
|
697
1288
|
return resp.data.data.location;
|
|
698
1289
|
}
|
|
@@ -707,6 +1298,7 @@ var Merchants = class {
|
|
|
707
1298
|
* Get a merchant by ID.
|
|
708
1299
|
*
|
|
709
1300
|
* @param id - Merchant UUID.
|
|
1301
|
+
* @param options - Optional `signal` to cancel the call.
|
|
710
1302
|
* @returns The merchant data (name, icon, website, domain, aliases, etc.).
|
|
711
1303
|
*
|
|
712
1304
|
* @example
|
|
@@ -715,9 +1307,11 @@ var Merchants = class {
|
|
|
715
1307
|
* console.log(merchant.name, merchant.website);
|
|
716
1308
|
* ```
|
|
717
1309
|
*/
|
|
718
|
-
async get(id) {
|
|
1310
|
+
async get(id, options) {
|
|
719
1311
|
const resp = await this.http.get(
|
|
720
|
-
`/v1/merchants/${encodeURIComponent(id)}
|
|
1312
|
+
`/v1/merchants/${encodeURIComponent(id)}`,
|
|
1313
|
+
void 0,
|
|
1314
|
+
options
|
|
721
1315
|
);
|
|
722
1316
|
return resp.data.data.merchant;
|
|
723
1317
|
}
|
|
@@ -741,7 +1335,7 @@ var Transactions = class {
|
|
|
741
1335
|
* Enrich a transaction with merchant, category, location, and entity data.
|
|
742
1336
|
*
|
|
743
1337
|
* @param request - The transaction to enrich (title, country, type, and optional options).
|
|
744
|
-
* @param options - Optional
|
|
1338
|
+
* @param options - Optional idempotency key and `signal` to cancel the call.
|
|
745
1339
|
* @returns The enriched transaction data.
|
|
746
1340
|
*
|
|
747
1341
|
* @example
|
|
@@ -761,7 +1355,9 @@ var Transactions = class {
|
|
|
761
1355
|
const resp = await this.http.postWithHeaders(
|
|
762
1356
|
"/v1/transactions/enrich",
|
|
763
1357
|
request,
|
|
764
|
-
headers
|
|
1358
|
+
headers,
|
|
1359
|
+
void 0,
|
|
1360
|
+
{ signal: options?.signal }
|
|
765
1361
|
);
|
|
766
1362
|
return resp.data;
|
|
767
1363
|
}
|
|
@@ -782,7 +1378,7 @@ var Transactions = class {
|
|
|
782
1378
|
* }
|
|
783
1379
|
* ```
|
|
784
1380
|
*/
|
|
785
|
-
async list(params) {
|
|
1381
|
+
async list(params, options) {
|
|
786
1382
|
const fetchPage = async (page, size) => {
|
|
787
1383
|
const query = {
|
|
788
1384
|
page,
|
|
@@ -794,7 +1390,7 @@ var Transactions = class {
|
|
|
794
1390
|
if (params?.endDate) {
|
|
795
1391
|
query.endDate = params.endDate instanceof Date ? params.endDate.toISOString() : params.endDate;
|
|
796
1392
|
}
|
|
797
|
-
const resp = await this.http.get("/v1/transactions", query);
|
|
1393
|
+
const resp = await this.http.get("/v1/transactions", query, options);
|
|
798
1394
|
const { transactions, pagination } = resp.data.data;
|
|
799
1395
|
return new Page(transactions, pagination, fetchPage);
|
|
800
1396
|
};
|
|
@@ -811,23 +1407,26 @@ var Transactions = class {
|
|
|
811
1407
|
* const { count } = await triqai.transactions.count({ afterDate: "2026-01-01T00:00:00Z" });
|
|
812
1408
|
* ```
|
|
813
1409
|
*/
|
|
814
|
-
async count(params) {
|
|
1410
|
+
async count(params, options) {
|
|
815
1411
|
const query = {};
|
|
816
1412
|
if (params?.afterDate) {
|
|
817
1413
|
query.afterDate = params.afterDate instanceof Date ? params.afterDate.toISOString() : params.afterDate;
|
|
818
1414
|
}
|
|
819
|
-
const resp = await this.http.get("/v1/transactions/count", query);
|
|
1415
|
+
const resp = await this.http.get("/v1/transactions/count", query, options);
|
|
820
1416
|
return resp.data.data;
|
|
821
1417
|
}
|
|
822
1418
|
/**
|
|
823
1419
|
* Get a single transaction by ID.
|
|
824
1420
|
*
|
|
825
1421
|
* @param id - Transaction UUID.
|
|
1422
|
+
* @param options - Optional `signal` to cancel the call.
|
|
826
1423
|
* @returns The enriched transaction record.
|
|
827
1424
|
*/
|
|
828
|
-
async get(id) {
|
|
1425
|
+
async get(id, options) {
|
|
829
1426
|
const resp = await this.http.get(
|
|
830
|
-
`/v1/transactions/${encodeURIComponent(id)}
|
|
1427
|
+
`/v1/transactions/${encodeURIComponent(id)}`,
|
|
1428
|
+
void 0,
|
|
1429
|
+
options
|
|
831
1430
|
);
|
|
832
1431
|
return resp.data.data.transaction;
|
|
833
1432
|
}
|
|
@@ -835,11 +1434,14 @@ var Transactions = class {
|
|
|
835
1434
|
* Delete a transaction by ID.
|
|
836
1435
|
*
|
|
837
1436
|
* @param id - Transaction UUID.
|
|
1437
|
+
* @param options - Optional `signal` to cancel the call.
|
|
838
1438
|
* @returns Confirmation with the deleted transaction ID.
|
|
839
1439
|
*/
|
|
840
|
-
async delete(id) {
|
|
1440
|
+
async delete(id, options) {
|
|
841
1441
|
const resp = await this.http.delete(
|
|
842
|
-
`/v1/transactions/${encodeURIComponent(id)}
|
|
1442
|
+
`/v1/transactions/${encodeURIComponent(id)}`,
|
|
1443
|
+
void 0,
|
|
1444
|
+
options
|
|
843
1445
|
);
|
|
844
1446
|
return resp.data.data;
|
|
845
1447
|
}
|
|
@@ -862,9 +1464,9 @@ var Transactions = class {
|
|
|
862
1464
|
* });
|
|
863
1465
|
* ```
|
|
864
1466
|
*/
|
|
865
|
-
async batchDelete(request) {
|
|
1467
|
+
async batchDelete(request, options) {
|
|
866
1468
|
const body = "afterDate" in request && request.afterDate instanceof Date ? { ...request, afterDate: request.afterDate.toISOString() } : request;
|
|
867
|
-
const resp = await this.http.delete("/v1/transactions/batch", body);
|
|
1469
|
+
const resp = await this.http.delete("/v1/transactions/batch", body, options);
|
|
868
1470
|
return resp.data.data;
|
|
869
1471
|
}
|
|
870
1472
|
};
|
|
@@ -914,8 +1516,8 @@ var Triqai = class {
|
|
|
914
1516
|
* console.log(health.data.version); // "1.1.9"
|
|
915
1517
|
* ```
|
|
916
1518
|
*/
|
|
917
|
-
async health() {
|
|
918
|
-
const resp = await this.http.get("/health");
|
|
1519
|
+
async health(options) {
|
|
1520
|
+
const resp = await this.http.get("/health", void 0, options);
|
|
919
1521
|
return resp.data;
|
|
920
1522
|
}
|
|
921
1523
|
/**
|
|
@@ -930,8 +1532,8 @@ var Triqai = class {
|
|
|
930
1532
|
* console.log(info.data.endpoints);
|
|
931
1533
|
* ```
|
|
932
1534
|
*/
|
|
933
|
-
async apiInfo() {
|
|
934
|
-
const resp = await this.http.get("/v1");
|
|
1535
|
+
async apiInfo(options) {
|
|
1536
|
+
const resp = await this.http.get("/v1", void 0, options);
|
|
935
1537
|
return resp.data;
|
|
936
1538
|
}
|
|
937
1539
|
/**
|
|
@@ -940,10 +1542,11 @@ var Triqai = class {
|
|
|
940
1542
|
*
|
|
941
1543
|
* @param path - API path (e.g. "/v1/some-endpoint").
|
|
942
1544
|
* @param query - Optional query parameters.
|
|
1545
|
+
* @param options - Optional `signal` to cancel the call.
|
|
943
1546
|
* @returns The full HTTP response including headers and rate limit info.
|
|
944
1547
|
*/
|
|
945
|
-
async rawGet(path, query) {
|
|
946
|
-
return this.http.get(path, query);
|
|
1548
|
+
async rawGet(path, query, options) {
|
|
1549
|
+
return this.http.get(path, query, options);
|
|
947
1550
|
}
|
|
948
1551
|
/**
|
|
949
1552
|
* Make a raw POST request to any API path.
|
|
@@ -951,20 +1554,22 @@ var Triqai = class {
|
|
|
951
1554
|
*
|
|
952
1555
|
* @param path - API path (e.g. "/v1/some-endpoint").
|
|
953
1556
|
* @param body - Request body.
|
|
1557
|
+
* @param options - Optional `signal` to cancel the call.
|
|
954
1558
|
* @returns The full HTTP response including headers and rate limit info.
|
|
955
1559
|
*/
|
|
956
|
-
async rawPost(path, body) {
|
|
957
|
-
return this.http.post(path, body);
|
|
1560
|
+
async rawPost(path, body, options) {
|
|
1561
|
+
return this.http.post(path, body, options);
|
|
958
1562
|
}
|
|
959
1563
|
/**
|
|
960
1564
|
* Make a raw DELETE request to any API path.
|
|
961
1565
|
* Useful for accessing endpoints not yet covered by a resource class.
|
|
962
1566
|
*
|
|
963
1567
|
* @param path - API path (e.g. "/v1/some-resource/uuid").
|
|
1568
|
+
* @param options - Optional `signal` to cancel the call.
|
|
964
1569
|
* @returns The full HTTP response including headers and rate limit info.
|
|
965
1570
|
*/
|
|
966
|
-
async rawDelete(path) {
|
|
967
|
-
return this.http.delete(path);
|
|
1571
|
+
async rawDelete(path, options) {
|
|
1572
|
+
return this.http.delete(path, void 0, options);
|
|
968
1573
|
}
|
|
969
1574
|
};
|
|
970
1575
|
|
|
@@ -981,6 +1586,7 @@ exports.GoneError = GoneError;
|
|
|
981
1586
|
exports.InsufficientCreditsError = InsufficientCreditsError;
|
|
982
1587
|
exports.InternalServerError = InternalServerError;
|
|
983
1588
|
exports.NotFoundError = NotFoundError;
|
|
1589
|
+
exports.PacingTimeoutError = PacingTimeoutError;
|
|
984
1590
|
exports.Page = Page;
|
|
985
1591
|
exports.RateLimitError = RateLimitError;
|
|
986
1592
|
exports.ServiceUnavailableError = ServiceUnavailableError;
|