triqai 0.2.8 → 0.4.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/CHANGELOG.md +39 -0
- package/README.md +102 -5
- package/dist/index.cjs +808 -144
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +279 -41
- package/dist/index.d.ts +279 -41
- package/dist/index.js +807 -145
- package/dist/index.js.map +1 -1
- package/openapi-public.yaml +192 -26
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// package.json
|
|
2
|
-
var version = "0.
|
|
2
|
+
var version = "0.4.0";
|
|
3
3
|
|
|
4
4
|
// src/errors.ts
|
|
5
5
|
var TriqaiError = class extends Error {
|
|
@@ -63,16 +63,25 @@ var ClientDisconnectedError = class extends TriqaiError {
|
|
|
63
63
|
};
|
|
64
64
|
var DuplicateRequestError = class extends TriqaiError {
|
|
65
65
|
state;
|
|
66
|
+
/** `payload_mismatch` when the key was already used for a different request. */
|
|
67
|
+
reason;
|
|
66
68
|
duplicateRequestId;
|
|
67
69
|
retryAfter;
|
|
68
70
|
constructor(message, opts) {
|
|
69
71
|
super(message, 409, { code: "DUPLICATE_REQUEST", ...opts });
|
|
70
72
|
this.name = "DuplicateRequestError";
|
|
71
73
|
this.state = opts?.state;
|
|
74
|
+
this.reason = opts?.reason;
|
|
72
75
|
this.duplicateRequestId = opts?.duplicateRequestId;
|
|
73
76
|
this.retryAfter = opts?.retryAfter;
|
|
74
77
|
}
|
|
75
78
|
};
|
|
79
|
+
var GoneError = class extends TriqaiError {
|
|
80
|
+
constructor(message, opts) {
|
|
81
|
+
super(message, 410, { code: "gone", ...opts });
|
|
82
|
+
this.name = "GoneError";
|
|
83
|
+
}
|
|
84
|
+
};
|
|
76
85
|
var RateLimitError = class extends TriqaiError {
|
|
77
86
|
rateLimitInfo;
|
|
78
87
|
constructor(message, rateLimitInfo, opts) {
|
|
@@ -108,11 +117,492 @@ var ConnectionError = class extends TriqaiError {
|
|
|
108
117
|
}
|
|
109
118
|
};
|
|
110
119
|
var TimeoutError = class extends TriqaiError {
|
|
111
|
-
constructor(message) {
|
|
112
|
-
super(message, 0, { code: "timeout" });
|
|
120
|
+
constructor(message, opts) {
|
|
121
|
+
super(message, 0, { code: opts?.code ?? "timeout" });
|
|
113
122
|
this.name = "TimeoutError";
|
|
114
123
|
}
|
|
115
124
|
};
|
|
125
|
+
var PacingTimeoutError = class extends TimeoutError {
|
|
126
|
+
constructor(message) {
|
|
127
|
+
super(message, { code: "pacing_timeout" });
|
|
128
|
+
this.name = "PacingTimeoutError";
|
|
129
|
+
}
|
|
130
|
+
};
|
|
131
|
+
|
|
132
|
+
// src/abort.ts
|
|
133
|
+
var callbacks = /* @__PURE__ */ new WeakMap();
|
|
134
|
+
function onAbort(signal, callback) {
|
|
135
|
+
if (signal.aborted) {
|
|
136
|
+
callback();
|
|
137
|
+
return () => {
|
|
138
|
+
};
|
|
139
|
+
}
|
|
140
|
+
let set = callbacks.get(signal);
|
|
141
|
+
if (!set) {
|
|
142
|
+
const created = /* @__PURE__ */ new Set();
|
|
143
|
+
set = created;
|
|
144
|
+
callbacks.set(signal, created);
|
|
145
|
+
signal.addEventListener("abort", () => {
|
|
146
|
+
callbacks.delete(signal);
|
|
147
|
+
for (const run of [...created]) run();
|
|
148
|
+
}, { once: true });
|
|
149
|
+
}
|
|
150
|
+
const own = set;
|
|
151
|
+
own.add(callback);
|
|
152
|
+
return () => {
|
|
153
|
+
own.delete(callback);
|
|
154
|
+
};
|
|
155
|
+
}
|
|
156
|
+
function abortReason(signal) {
|
|
157
|
+
return signal.reason ?? new DOMException("This operation was aborted", "AbortError");
|
|
158
|
+
}
|
|
159
|
+
function throwIfAborted(signal) {
|
|
160
|
+
if (signal?.aborted) throw abortReason(signal);
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
// src/pacing.ts
|
|
164
|
+
var DEFAULT_CONCURRENCY = 5;
|
|
165
|
+
var COLD_LIMIT = 5;
|
|
166
|
+
var MAX_SHARED_PAUSE_MS = 6e4;
|
|
167
|
+
var LEASE_MS = 1e3;
|
|
168
|
+
var MIN_RATE = 0.1;
|
|
169
|
+
var MAX_CONCURRENCY = 1e3;
|
|
170
|
+
var MAX_TIMER_DELAY = 2147483647;
|
|
171
|
+
var EPSILON = 1e-9;
|
|
172
|
+
var WaiterQueue = class {
|
|
173
|
+
items = [];
|
|
174
|
+
head = 0;
|
|
175
|
+
push(waiter) {
|
|
176
|
+
this.items.push(waiter);
|
|
177
|
+
}
|
|
178
|
+
unshiftAll(waiters) {
|
|
179
|
+
if (waiters.length === 0) return;
|
|
180
|
+
this.items = [...waiters, ...this.items.slice(this.head)];
|
|
181
|
+
this.head = 0;
|
|
182
|
+
}
|
|
183
|
+
peek() {
|
|
184
|
+
while (this.head < this.items.length && this.items[this.head].state !== "queued") this.head++;
|
|
185
|
+
if (this.head === this.items.length) {
|
|
186
|
+
this.items = [];
|
|
187
|
+
this.head = 0;
|
|
188
|
+
return void 0;
|
|
189
|
+
}
|
|
190
|
+
if (this.head > 1024 && this.head * 2 > this.items.length) {
|
|
191
|
+
this.items = this.items.slice(this.head);
|
|
192
|
+
this.head = 0;
|
|
193
|
+
}
|
|
194
|
+
return this.items[this.head];
|
|
195
|
+
}
|
|
196
|
+
shift() {
|
|
197
|
+
const waiter = this.peek();
|
|
198
|
+
if (waiter) this.head++;
|
|
199
|
+
return waiter;
|
|
200
|
+
}
|
|
201
|
+
/** Removes and returns the queued waiters that match, in order. */
|
|
202
|
+
extract(match) {
|
|
203
|
+
const taken = [];
|
|
204
|
+
const kept = [];
|
|
205
|
+
for (let i = this.head; i < this.items.length; i++) {
|
|
206
|
+
const waiter = this.items[i];
|
|
207
|
+
if (waiter.state !== "queued") continue;
|
|
208
|
+
(match(waiter) ? taken : kept).push(waiter);
|
|
209
|
+
}
|
|
210
|
+
this.items = kept;
|
|
211
|
+
this.head = 0;
|
|
212
|
+
return taken;
|
|
213
|
+
}
|
|
214
|
+
};
|
|
215
|
+
var Pacer = class {
|
|
216
|
+
/** How long a call may wait for its first attempt. */
|
|
217
|
+
maxWait;
|
|
218
|
+
maxConcurrency;
|
|
219
|
+
maxRate;
|
|
220
|
+
serverConcurrency;
|
|
221
|
+
serverRate;
|
|
222
|
+
/** When the concurrency limit became known; earlier requests do not lower the window. */
|
|
223
|
+
concurrencyKnownAt;
|
|
224
|
+
/** Enrichments allowed in flight now; lowered by concurrency 429s, then regrown. */
|
|
225
|
+
window;
|
|
226
|
+
successes = 0;
|
|
227
|
+
/** When the window was last lowered; earlier requests do not regrow it. */
|
|
228
|
+
loweredAt = -Infinity;
|
|
229
|
+
/** Enrichment slots held, by queued retries as well as requests in flight. */
|
|
230
|
+
active = 0;
|
|
231
|
+
/** Requests granted and not yet finished. */
|
|
232
|
+
inFlight = 0;
|
|
233
|
+
tokens;
|
|
234
|
+
refilledAt;
|
|
235
|
+
ratePausedUntil = -Infinity;
|
|
236
|
+
slotPausedUntil = -Infinity;
|
|
237
|
+
pumpedAt = -Infinity;
|
|
238
|
+
slotRetries = new WaiterQueue();
|
|
239
|
+
slotQueue = new WaiterQueue();
|
|
240
|
+
rateRetries = new WaiterQueue();
|
|
241
|
+
rateQueue = new WaiterQueue();
|
|
242
|
+
/** Waiters with a future `notBefore`, earliest first. */
|
|
243
|
+
delayed = [];
|
|
244
|
+
/** Grants not yet taken up by their calls. */
|
|
245
|
+
leased = /* @__PURE__ */ new Set();
|
|
246
|
+
timer;
|
|
247
|
+
constructor(options = {}, defaultMaxWait = 3e5) {
|
|
248
|
+
const { maxConcurrency, requestsPerSecond, maxWait = defaultMaxWait } = options;
|
|
249
|
+
if (maxConcurrency !== void 0 && !(Number.isInteger(maxConcurrency) && maxConcurrency >= 1)) {
|
|
250
|
+
throw new Error("pacing.maxConcurrency must be a positive integer");
|
|
251
|
+
}
|
|
252
|
+
if (requestsPerSecond !== void 0 && !(Number.isFinite(requestsPerSecond) && requestsPerSecond > 0)) {
|
|
253
|
+
throw new Error("pacing.requestsPerSecond must be a positive number");
|
|
254
|
+
}
|
|
255
|
+
if (!(Number.isFinite(maxWait) && maxWait > 0 && maxWait <= MAX_TIMER_DELAY)) {
|
|
256
|
+
throw new Error(`pacing.maxWait must be greater than 0 and at most ${MAX_TIMER_DELAY}ms`);
|
|
257
|
+
}
|
|
258
|
+
this.maxConcurrency = maxConcurrency;
|
|
259
|
+
this.maxRate = requestsPerSecond;
|
|
260
|
+
this.maxWait = maxWait;
|
|
261
|
+
this.concurrencyKnownAt = maxConcurrency === void 0 ? Infinity : -Infinity;
|
|
262
|
+
this.window = this.concurrencyLimit();
|
|
263
|
+
this.refilledAt = Date.now();
|
|
264
|
+
this.tokens = this.burst();
|
|
265
|
+
}
|
|
266
|
+
/** Waits until a request may be sent. Rejects on abort or when `deadline` passes. */
|
|
267
|
+
acquire(options) {
|
|
268
|
+
return this.admit({ ...options, hasSlot: false, retry: false, notBefore: -Infinity });
|
|
269
|
+
}
|
|
270
|
+
/**
|
|
271
|
+
* Queues a waiter and resolves when it is granted, without taking the grant
|
|
272
|
+
* up. Callers must claim it; `acquire` and `Permit.retry` do.
|
|
273
|
+
* @internal
|
|
274
|
+
*/
|
|
275
|
+
wait(init) {
|
|
276
|
+
return new Promise((resolve, reject) => {
|
|
277
|
+
const waiter = {
|
|
278
|
+
...init,
|
|
279
|
+
state: "queued",
|
|
280
|
+
leaseUntil: 0,
|
|
281
|
+
resolve,
|
|
282
|
+
reject,
|
|
283
|
+
timer: void 0,
|
|
284
|
+
unsubscribe: void 0
|
|
285
|
+
};
|
|
286
|
+
const now = Date.now();
|
|
287
|
+
const { signal } = init;
|
|
288
|
+
if (signal?.aborted) return this.settleEarly(waiter, abortReason(signal));
|
|
289
|
+
if (now >= init.deadline || init.notBefore >= init.deadline) return this.settleEarly(waiter, init.expired());
|
|
290
|
+
if (Number.isFinite(init.deadline)) {
|
|
291
|
+
waiter.timer = setTimeout(() => {
|
|
292
|
+
this.fail(waiter, waiter.expired());
|
|
293
|
+
this.pump();
|
|
294
|
+
}, Math.min(MAX_TIMER_DELAY, Math.max(0, init.deadline - now)));
|
|
295
|
+
}
|
|
296
|
+
if (signal) {
|
|
297
|
+
waiter.unsubscribe = onAbort(signal, () => {
|
|
298
|
+
this.fail(waiter, abortReason(signal));
|
|
299
|
+
this.pump();
|
|
300
|
+
});
|
|
301
|
+
}
|
|
302
|
+
this.place(waiter, now);
|
|
303
|
+
this.pump();
|
|
304
|
+
});
|
|
305
|
+
}
|
|
306
|
+
/** Takes up a grant. False when it went back to the pool first. @internal */
|
|
307
|
+
claim(waiter) {
|
|
308
|
+
if (waiter.state !== "leased") return false;
|
|
309
|
+
waiter.state = "active";
|
|
310
|
+
this.leased.delete(waiter);
|
|
311
|
+
return true;
|
|
312
|
+
}
|
|
313
|
+
/** Updates the limits from a response's rate-limit headers. */
|
|
314
|
+
observe(headers, slot, status, sentAt) {
|
|
315
|
+
const now = Date.now();
|
|
316
|
+
this.refill(now);
|
|
317
|
+
const concurrency = parseLimit(headers["x-ratelimit-concurrency-limit"]);
|
|
318
|
+
if (concurrency !== void 0 && concurrency > 0) {
|
|
319
|
+
const limit2 = Math.min(MAX_CONCURRENCY, Math.max(1, Math.floor(concurrency)));
|
|
320
|
+
if (limit2 !== this.serverConcurrency) {
|
|
321
|
+
if (this.serverConcurrency === void 0) this.concurrencyKnownAt = Math.min(this.concurrencyKnownAt, now);
|
|
322
|
+
this.serverConcurrency = limit2;
|
|
323
|
+
this.window = this.concurrencyLimit();
|
|
324
|
+
this.successes = 0;
|
|
325
|
+
}
|
|
326
|
+
}
|
|
327
|
+
const scope = headers["x-ratelimit-scope"];
|
|
328
|
+
const limit = parseLimit(headers["x-ratelimit-limit"]);
|
|
329
|
+
if (limit !== void 0 && limit > 0 && scope !== "concurrency") {
|
|
330
|
+
const rateWasKnown = Number.isFinite(this.rate());
|
|
331
|
+
this.serverRate = Math.max(MIN_RATE, limit);
|
|
332
|
+
const remaining = parseLimit(headers["x-ratelimit-remaining"]);
|
|
333
|
+
if (!rateWasKnown) {
|
|
334
|
+
this.tokens = remaining ?? this.burst();
|
|
335
|
+
} else if (remaining !== void 0) {
|
|
336
|
+
const elapsed = Math.max(0, now - sentAt);
|
|
337
|
+
this.tokens = Math.min(this.tokens, remaining + elapsed * this.rate() / 1e3);
|
|
338
|
+
}
|
|
339
|
+
this.tokens = Math.min(this.tokens, this.burst());
|
|
340
|
+
}
|
|
341
|
+
if (slot && status >= 200 && status < 300 && sentAt > this.loweredAt) {
|
|
342
|
+
if (this.window < this.concurrencyLimit() && ++this.successes >= this.window) {
|
|
343
|
+
this.window++;
|
|
344
|
+
this.successes = 0;
|
|
345
|
+
}
|
|
346
|
+
}
|
|
347
|
+
this.pump();
|
|
348
|
+
}
|
|
349
|
+
/**
|
|
350
|
+
* Pauses the limit a 429 names for `delayMs` (at most MAX_SHARED_PAUSE_MS).
|
|
351
|
+
* A 429 without a scope comes from a limit that covers every request.
|
|
352
|
+
*/
|
|
353
|
+
pause(scope, delayMs, slot, sentAt) {
|
|
354
|
+
const now = Date.now();
|
|
355
|
+
const until = now + Math.min(Math.max(0, delayMs), MAX_SHARED_PAUSE_MS);
|
|
356
|
+
if (scope === "concurrency") {
|
|
357
|
+
this.slotPausedUntil = Math.max(this.slotPausedUntil, until);
|
|
358
|
+
if (slot && sentAt >= this.concurrencyKnownAt) {
|
|
359
|
+
this.window = Math.max(1, Math.min(this.window - 1, this.active - 1));
|
|
360
|
+
this.successes = 0;
|
|
361
|
+
this.loweredAt = now;
|
|
362
|
+
}
|
|
363
|
+
this.holdBackSlots();
|
|
364
|
+
} else {
|
|
365
|
+
this.ratePausedUntil = Math.max(this.ratePausedUntil, until);
|
|
366
|
+
if (scope === "rps") {
|
|
367
|
+
this.refill(now);
|
|
368
|
+
this.tokens = Math.min(this.tokens, 0);
|
|
369
|
+
}
|
|
370
|
+
}
|
|
371
|
+
this.pump();
|
|
372
|
+
}
|
|
373
|
+
async admit(init) {
|
|
374
|
+
let waiter = await this.wait(init);
|
|
375
|
+
while (!this.claim(waiter)) {
|
|
376
|
+
waiter = await this.wait({ ...init, hasSlot: false, retry: true });
|
|
377
|
+
}
|
|
378
|
+
return this.permit(waiter);
|
|
379
|
+
}
|
|
380
|
+
permit(waiter) {
|
|
381
|
+
return {
|
|
382
|
+
release: () => this.release(waiter),
|
|
383
|
+
retry: (options) => {
|
|
384
|
+
if (waiter.state !== "active") return this.acquire({ ...options, slot: waiter.slot });
|
|
385
|
+
const { hasSlot } = waiter;
|
|
386
|
+
waiter.hasSlot = false;
|
|
387
|
+
waiter.state = "done";
|
|
388
|
+
this.inFlight--;
|
|
389
|
+
return this.admit({ ...options, slot: waiter.slot, hasSlot, retry: true });
|
|
390
|
+
}
|
|
391
|
+
};
|
|
392
|
+
}
|
|
393
|
+
release(waiter) {
|
|
394
|
+
if (waiter.state !== "active") return;
|
|
395
|
+
waiter.state = "done";
|
|
396
|
+
this.inFlight--;
|
|
397
|
+
if (waiter.hasSlot) {
|
|
398
|
+
waiter.hasSlot = false;
|
|
399
|
+
this.active--;
|
|
400
|
+
}
|
|
401
|
+
this.pump();
|
|
402
|
+
}
|
|
403
|
+
concurrencyLimit() {
|
|
404
|
+
const server = this.serverConcurrency ?? (this.maxConcurrency === void 0 ? DEFAULT_CONCURRENCY : Infinity);
|
|
405
|
+
return Math.min(this.maxConcurrency ?? Infinity, server);
|
|
406
|
+
}
|
|
407
|
+
rate() {
|
|
408
|
+
return Math.min(this.maxRate ?? Infinity, this.serverRate ?? Infinity);
|
|
409
|
+
}
|
|
410
|
+
/** The API's bucket holds as many tokens as its concurrency limit. */
|
|
411
|
+
burst() {
|
|
412
|
+
const rate = this.rate();
|
|
413
|
+
if (!Number.isFinite(rate)) return Infinity;
|
|
414
|
+
const own = this.maxRate === void 0 ? Infinity : Math.ceil(this.maxRate);
|
|
415
|
+
return Math.max(1, Math.min(this.serverConcurrency ?? Math.ceil(rate), own));
|
|
416
|
+
}
|
|
417
|
+
refill(now) {
|
|
418
|
+
const rate = this.rate();
|
|
419
|
+
if (Number.isFinite(rate)) {
|
|
420
|
+
const elapsed = Math.max(0, now - this.refilledAt);
|
|
421
|
+
this.tokens = Math.min(this.burst(), this.tokens + elapsed * rate / 1e3);
|
|
422
|
+
}
|
|
423
|
+
this.refilledAt = now;
|
|
424
|
+
}
|
|
425
|
+
/** Puts a queued waiter where it can next make progress. */
|
|
426
|
+
place(waiter, now) {
|
|
427
|
+
const ready = waiter.hasSlot ? Math.max(waiter.notBefore, this.slotPausedUntil) : waiter.notBefore;
|
|
428
|
+
if (ready > now) {
|
|
429
|
+
waiter.notBefore = ready;
|
|
430
|
+
this.delay(waiter);
|
|
431
|
+
} else if (waiter.slot && !waiter.hasSlot) {
|
|
432
|
+
(waiter.retry ? this.slotRetries : this.slotQueue).push(waiter);
|
|
433
|
+
} else {
|
|
434
|
+
(waiter.retry ? this.rateRetries : this.rateQueue).push(waiter);
|
|
435
|
+
}
|
|
436
|
+
}
|
|
437
|
+
delay(waiter) {
|
|
438
|
+
let low = 0;
|
|
439
|
+
let high = this.delayed.length;
|
|
440
|
+
while (low < high) {
|
|
441
|
+
const mid = low + high >>> 1;
|
|
442
|
+
if (this.delayed[mid].notBefore <= waiter.notBefore) low = mid + 1;
|
|
443
|
+
else high = mid;
|
|
444
|
+
}
|
|
445
|
+
this.delayed.splice(low, 0, waiter);
|
|
446
|
+
}
|
|
447
|
+
nextDelayed() {
|
|
448
|
+
while (this.delayed.length > 0 && this.delayed[0].state !== "queued") this.delayed.shift();
|
|
449
|
+
return this.delayed[0];
|
|
450
|
+
}
|
|
451
|
+
/**
|
|
452
|
+
* After a concurrency 429, requests that hold a slot but have not been sent
|
|
453
|
+
* give it back and wait for the pause; a queued retry keeps its slot.
|
|
454
|
+
*/
|
|
455
|
+
holdBackSlots() {
|
|
456
|
+
const returned = [];
|
|
457
|
+
for (const queue of [this.rateRetries, this.rateQueue]) {
|
|
458
|
+
for (const waiter of queue.extract((w) => w.hasSlot)) {
|
|
459
|
+
if (waiter.retry) {
|
|
460
|
+
waiter.notBefore = Math.max(waiter.notBefore, this.slotPausedUntil);
|
|
461
|
+
this.delay(waiter);
|
|
462
|
+
} else {
|
|
463
|
+
waiter.hasSlot = false;
|
|
464
|
+
this.active--;
|
|
465
|
+
returned.push(waiter);
|
|
466
|
+
}
|
|
467
|
+
}
|
|
468
|
+
}
|
|
469
|
+
this.slotQueue.unshiftAll(returned);
|
|
470
|
+
}
|
|
471
|
+
pump() {
|
|
472
|
+
const now = Date.now();
|
|
473
|
+
if (now < this.pumpedAt) this.clampAfterClockStep(now);
|
|
474
|
+
this.pumpedAt = now;
|
|
475
|
+
this.reclaim(now);
|
|
476
|
+
for (let waiter = this.nextDelayed(); waiter && waiter.notBefore <= now; waiter = this.nextDelayed()) {
|
|
477
|
+
this.delayed.shift();
|
|
478
|
+
if (waiter.hasSlot && this.active > this.window) {
|
|
479
|
+
waiter.hasSlot = false;
|
|
480
|
+
this.active--;
|
|
481
|
+
}
|
|
482
|
+
this.place(waiter, now);
|
|
483
|
+
}
|
|
484
|
+
if (now >= this.slotPausedUntil) {
|
|
485
|
+
while (this.active < this.window) {
|
|
486
|
+
const waiter = this.slotRetries.shift() ?? this.slotQueue.shift();
|
|
487
|
+
if (!waiter) break;
|
|
488
|
+
waiter.hasSlot = true;
|
|
489
|
+
this.active++;
|
|
490
|
+
(waiter.retry ? this.rateRetries : this.rateQueue).push(waiter);
|
|
491
|
+
}
|
|
492
|
+
}
|
|
493
|
+
if (now >= this.ratePausedUntil) {
|
|
494
|
+
this.refill(now);
|
|
495
|
+
const limited = Number.isFinite(this.rate());
|
|
496
|
+
for (; ; ) {
|
|
497
|
+
const queue = this.rateRetries.peek() ? this.rateRetries : this.rateQueue;
|
|
498
|
+
const waiter = queue.peek();
|
|
499
|
+
if (!waiter) break;
|
|
500
|
+
if (limited) {
|
|
501
|
+
if (this.tokens < 1 - EPSILON) break;
|
|
502
|
+
this.tokens -= 1;
|
|
503
|
+
} else if (this.inFlight >= COLD_LIMIT) {
|
|
504
|
+
break;
|
|
505
|
+
}
|
|
506
|
+
queue.shift();
|
|
507
|
+
this.grant(waiter, now);
|
|
508
|
+
}
|
|
509
|
+
}
|
|
510
|
+
this.schedule(now);
|
|
511
|
+
}
|
|
512
|
+
grant(waiter, now) {
|
|
513
|
+
waiter.state = "leased";
|
|
514
|
+
waiter.leaseUntil = now + LEASE_MS;
|
|
515
|
+
this.leased.add(waiter);
|
|
516
|
+
this.inFlight++;
|
|
517
|
+
this.detach(waiter);
|
|
518
|
+
waiter.resolve(waiter);
|
|
519
|
+
}
|
|
520
|
+
/**
|
|
521
|
+
* A wall clock that steps backwards must not stretch a pause, a lease or a
|
|
522
|
+
* retry's wait beyond their own maximums. Mapping every time through the same
|
|
523
|
+
* `min` keeps the delayed queue in order.
|
|
524
|
+
*/
|
|
525
|
+
clampAfterClockStep(now) {
|
|
526
|
+
this.ratePausedUntil = Math.min(this.ratePausedUntil, now + MAX_SHARED_PAUSE_MS);
|
|
527
|
+
this.slotPausedUntil = Math.min(this.slotPausedUntil, now + MAX_SHARED_PAUSE_MS);
|
|
528
|
+
for (const waiter of this.leased) waiter.leaseUntil = Math.min(waiter.leaseUntil, now + LEASE_MS);
|
|
529
|
+
for (const waiter of this.delayed) waiter.notBefore = Math.min(waiter.notBefore, now + MAX_SHARED_PAUSE_MS);
|
|
530
|
+
}
|
|
531
|
+
/** Returns grants not taken up in time to the pool. */
|
|
532
|
+
reclaim(now) {
|
|
533
|
+
for (const waiter of this.leased) {
|
|
534
|
+
if (waiter.leaseUntil > now) continue;
|
|
535
|
+
this.leased.delete(waiter);
|
|
536
|
+
waiter.state = "done";
|
|
537
|
+
this.inFlight--;
|
|
538
|
+
if (waiter.hasSlot) {
|
|
539
|
+
waiter.hasSlot = false;
|
|
540
|
+
this.active--;
|
|
541
|
+
}
|
|
542
|
+
if (Number.isFinite(this.rate())) this.tokens = Math.min(this.burst(), this.tokens + 1);
|
|
543
|
+
}
|
|
544
|
+
}
|
|
545
|
+
/** Keeps at most one shared timer, and none while nothing waits. */
|
|
546
|
+
schedule(now) {
|
|
547
|
+
let wake = Infinity;
|
|
548
|
+
const slotWaiting = this.slotRetries.peek() ?? this.slotQueue.peek();
|
|
549
|
+
if (slotWaiting && this.slotPausedUntil > now) wake = this.slotPausedUntil;
|
|
550
|
+
const rateWaiting = this.rateRetries.peek() ?? this.rateQueue.peek();
|
|
551
|
+
if (rateWaiting) {
|
|
552
|
+
const rate = this.rate();
|
|
553
|
+
if (this.ratePausedUntil > now) wake = Math.min(wake, this.ratePausedUntil);
|
|
554
|
+
else if (Number.isFinite(rate) && this.tokens < 1 - EPSILON) {
|
|
555
|
+
wake = Math.min(wake, now + (1 - this.tokens) * 1e3 / rate);
|
|
556
|
+
}
|
|
557
|
+
}
|
|
558
|
+
const next = this.nextDelayed();
|
|
559
|
+
if (next) wake = Math.min(wake, next.notBefore);
|
|
560
|
+
if ((slotWaiting || rateWaiting || next) && this.leased.size > 0) {
|
|
561
|
+
for (const waiter of this.leased) wake = Math.min(wake, waiter.leaseUntil);
|
|
562
|
+
}
|
|
563
|
+
if (this.timer !== void 0) {
|
|
564
|
+
clearTimeout(this.timer);
|
|
565
|
+
this.timer = void 0;
|
|
566
|
+
}
|
|
567
|
+
if (wake === Infinity) return;
|
|
568
|
+
const delay = Math.min(MAX_TIMER_DELAY, Math.max(1, Math.ceil(wake - now)));
|
|
569
|
+
this.timer = setTimeout(() => {
|
|
570
|
+
this.timer = void 0;
|
|
571
|
+
this.pump();
|
|
572
|
+
}, delay);
|
|
573
|
+
}
|
|
574
|
+
fail(waiter, reason) {
|
|
575
|
+
if (waiter.state !== "queued") return;
|
|
576
|
+
waiter.state = "done";
|
|
577
|
+
this.detach(waiter);
|
|
578
|
+
if (waiter.hasSlot) {
|
|
579
|
+
waiter.hasSlot = false;
|
|
580
|
+
this.active--;
|
|
581
|
+
}
|
|
582
|
+
waiter.reject(reason);
|
|
583
|
+
}
|
|
584
|
+
/** Rejects a waiter before it is queued, freeing a slot it was handed. */
|
|
585
|
+
settleEarly(waiter, reason) {
|
|
586
|
+
waiter.state = "done";
|
|
587
|
+
if (waiter.hasSlot) {
|
|
588
|
+
waiter.hasSlot = false;
|
|
589
|
+
this.active--;
|
|
590
|
+
this.pump();
|
|
591
|
+
}
|
|
592
|
+
waiter.reject(reason);
|
|
593
|
+
}
|
|
594
|
+
detach(waiter) {
|
|
595
|
+
if (waiter.timer !== void 0) clearTimeout(waiter.timer);
|
|
596
|
+
waiter.timer = void 0;
|
|
597
|
+
waiter.unsubscribe?.();
|
|
598
|
+
waiter.unsubscribe = void 0;
|
|
599
|
+
}
|
|
600
|
+
};
|
|
601
|
+
function parseLimit(value) {
|
|
602
|
+
if (value === void 0 || !/^\s*\d+(?:\.\d+)?\s*$/.test(value)) return void 0;
|
|
603
|
+
const n = Number(value);
|
|
604
|
+
return Number.isFinite(n) ? n : void 0;
|
|
605
|
+
}
|
|
116
606
|
|
|
117
607
|
// src/http-client.ts
|
|
118
608
|
var DEFAULT_BASE_URL = "https://api.triqai.com";
|
|
@@ -121,8 +611,9 @@ var DEFAULT_RETRY_DELAY = 500;
|
|
|
121
611
|
var DEFAULT_MAX_RETRY_DELAY = 3e4;
|
|
122
612
|
var DEFAULT_TIMEOUT = 6e4;
|
|
123
613
|
var DEFAULT_MAX_RETRY_TIME = 3e5;
|
|
124
|
-
var
|
|
614
|
+
var MAX_TIMER_DELAY2 = 2147483647;
|
|
125
615
|
var RETRYABLE_STATUS_CODES = /* @__PURE__ */ new Set([429, 500, 503, 504]);
|
|
616
|
+
var MAX_RESET_WAIT_MS = 1e4;
|
|
126
617
|
var HttpClient = class {
|
|
127
618
|
apiKey;
|
|
128
619
|
baseUrl;
|
|
@@ -134,6 +625,7 @@ var HttpClient = class {
|
|
|
134
625
|
defaultHeaders;
|
|
135
626
|
onRequest;
|
|
136
627
|
onResponse;
|
|
628
|
+
pacer;
|
|
137
629
|
constructor(apiKey, config = {}) {
|
|
138
630
|
if (!apiKey) {
|
|
139
631
|
throw new Error(
|
|
@@ -147,23 +639,30 @@ var HttpClient = class {
|
|
|
147
639
|
this.maxRetryDelay = config.maxRetryDelay ?? DEFAULT_MAX_RETRY_DELAY;
|
|
148
640
|
this.timeout = config.timeout ?? DEFAULT_TIMEOUT;
|
|
149
641
|
this.maxRetryTime = config.maxRetryTime ?? DEFAULT_MAX_RETRY_TIME;
|
|
150
|
-
if (!Number.isFinite(this.maxRetryTime) || this.maxRetryTime <= 0 || this.maxRetryTime >
|
|
151
|
-
throw new Error(`maxRetryTime must be greater than 0 and at most ${
|
|
642
|
+
if (!Number.isFinite(this.maxRetryTime) || this.maxRetryTime <= 0 || this.maxRetryTime > MAX_TIMER_DELAY2) {
|
|
643
|
+
throw new Error(`maxRetryTime must be greater than 0 and at most ${MAX_TIMER_DELAY2}ms`);
|
|
152
644
|
}
|
|
153
645
|
this.defaultHeaders = config.defaultHeaders ?? {};
|
|
154
646
|
this.onRequest = config.onRequest;
|
|
155
647
|
this.onResponse = config.onResponse;
|
|
648
|
+
const pacing = config.pacing === void 0 ? pacingByDefault() : config.pacing;
|
|
649
|
+
if (pacing !== true && pacing !== false && !isPlainObject(pacing)) {
|
|
650
|
+
throw new Error("pacing must be a boolean or an options object");
|
|
651
|
+
}
|
|
652
|
+
if (pacing !== false) this.pacer = new Pacer(pacing === true ? {} : pacing, this.maxRetryTime);
|
|
156
653
|
}
|
|
157
|
-
async get(path, query) {
|
|
158
|
-
return this.request("GET", path, void 0, query);
|
|
654
|
+
async get(path, query, options) {
|
|
655
|
+
return this.request("GET", path, void 0, query, void 0, options);
|
|
159
656
|
}
|
|
160
|
-
async post(path, body) {
|
|
161
|
-
return this.request("POST", path, body);
|
|
657
|
+
async post(path, body, options) {
|
|
658
|
+
return this.request("POST", path, body, void 0, void 0, options);
|
|
162
659
|
}
|
|
163
|
-
async delete(path) {
|
|
164
|
-
return this.request("DELETE", path);
|
|
660
|
+
async delete(path, body, options) {
|
|
661
|
+
return this.request("DELETE", path, body, void 0, void 0, options);
|
|
165
662
|
}
|
|
166
|
-
async request(method, path, body, query, extraHeaders) {
|
|
663
|
+
async request(method, path, body, query, extraHeaders, options) {
|
|
664
|
+
const signal = options?.signal;
|
|
665
|
+
throwIfAborted(signal);
|
|
167
666
|
const url = this.buildUrl(path, query);
|
|
168
667
|
const headers = {
|
|
169
668
|
"X-API-Key": this.apiKey,
|
|
@@ -175,115 +674,161 @@ var HttpClient = class {
|
|
|
175
674
|
if (body !== void 0) {
|
|
176
675
|
headers["Content-Type"] = "application/json";
|
|
177
676
|
}
|
|
178
|
-
const
|
|
677
|
+
const pacer = this.pacer;
|
|
678
|
+
const takesSlot = pacer !== void 0 && takesEnrichmentSlot(method, url);
|
|
679
|
+
let deadline = pacer ? Infinity : performance.now() + this.maxRetryTime;
|
|
680
|
+
const minRetryMs = pacer ? Math.min(1e3, this.timeout / 2) : 0;
|
|
179
681
|
const serializedBody = body !== void 0 ? JSON.stringify(body) : void 0;
|
|
180
682
|
let lastError;
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
683
|
+
let retryAt;
|
|
684
|
+
let permit;
|
|
685
|
+
const budgetExhausted = () => lastError ?? new TimeoutError(`Request exceeded ${this.maxRetryTime}ms total retry budget`);
|
|
686
|
+
try {
|
|
687
|
+
for (let attempt = 0; attempt <= this.maxRetries; attempt++) {
|
|
688
|
+
if (attempt > 0) {
|
|
689
|
+
const delay = retryAt === void 0 ? this.calculateDelay(attempt, lastError) : Math.max(0, retryAt - performance.now());
|
|
690
|
+
retryAt = void 0;
|
|
691
|
+
const cutoff = deadline - minRetryMs;
|
|
692
|
+
if (delay >= cutoff - performance.now()) {
|
|
693
|
+
throw lastError ?? new TimeoutError("Request retry budget exhausted");
|
|
694
|
+
}
|
|
695
|
+
if (permit) {
|
|
696
|
+
const wallOffset = Date.now() - performance.now();
|
|
697
|
+
permit = await permit.retry({
|
|
698
|
+
notBefore: Date.now() + delay,
|
|
699
|
+
deadline: cutoff + wallOffset,
|
|
700
|
+
signal,
|
|
701
|
+
expired: budgetExhausted
|
|
702
|
+
});
|
|
703
|
+
} else {
|
|
704
|
+
await sleep(delay, signal);
|
|
705
|
+
}
|
|
706
|
+
} else if (pacer) {
|
|
707
|
+
permit = await pacer.acquire({
|
|
708
|
+
slot: takesSlot,
|
|
709
|
+
deadline: Date.now() + pacer.maxWait,
|
|
710
|
+
signal,
|
|
711
|
+
expired: () => new PacingTimeoutError(
|
|
712
|
+
`Request waited ${pacer.maxWait}ms for its turn under pacing and was not sent: ${method} ${path}`
|
|
713
|
+
)
|
|
714
|
+
});
|
|
715
|
+
deadline = performance.now() + this.maxRetryTime;
|
|
716
|
+
}
|
|
717
|
+
throwIfAborted(signal);
|
|
718
|
+
const remainingMs = deadline - performance.now();
|
|
719
|
+
if (pacer && attempt > 0 && remainingMs < minRetryMs) {
|
|
185
720
|
throw lastError ?? new TimeoutError("Request retry budget exhausted");
|
|
186
721
|
}
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
const attemptTimeout = Math.min(this.timeout, remainingMs);
|
|
194
|
-
const startMs = Date.now();
|
|
195
|
-
this.onRequest?.({ method, url, headers: { ...headers }, body });
|
|
196
|
-
try {
|
|
197
|
-
const controller = new AbortController();
|
|
198
|
-
const timeoutId = setTimeout(() => controller.abort(), attemptTimeout);
|
|
199
|
-
let response;
|
|
200
|
-
let responseBody;
|
|
722
|
+
if (remainingMs <= 0) {
|
|
723
|
+
throw new TimeoutError(`Request exceeded ${this.maxRetryTime}ms total retry budget`);
|
|
724
|
+
}
|
|
725
|
+
const attemptTimeout = Math.min(this.timeout, remainingMs);
|
|
726
|
+
const startMs = Date.now();
|
|
727
|
+
this.onRequest?.({ method, url, headers: { ...headers }, body });
|
|
201
728
|
try {
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
729
|
+
const controller = new AbortController();
|
|
730
|
+
const timeoutId = setTimeout(() => controller.abort(), attemptTimeout);
|
|
731
|
+
const unlink = signal ? onAbort(signal, () => controller.abort()) : void 0;
|
|
732
|
+
let response;
|
|
733
|
+
let responseBody;
|
|
734
|
+
try {
|
|
735
|
+
response = await fetch(url, {
|
|
736
|
+
method,
|
|
737
|
+
headers,
|
|
738
|
+
body: serializedBody,
|
|
739
|
+
signal: controller.signal
|
|
740
|
+
});
|
|
741
|
+
responseBody = await response.json().catch((err) => {
|
|
742
|
+
if (err instanceof SyntaxError || !response.ok) return null;
|
|
743
|
+
throw err;
|
|
744
|
+
});
|
|
745
|
+
if (controller.signal.aborted && response.ok) {
|
|
746
|
+
throw new DOMException("The operation was aborted.", "AbortError");
|
|
747
|
+
}
|
|
748
|
+
} finally {
|
|
749
|
+
clearTimeout(timeoutId);
|
|
750
|
+
unlink?.();
|
|
214
751
|
}
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
const durationMs = Date.now() - startMs;
|
|
220
|
-
this.onResponse?.({
|
|
221
|
-
status: response.status,
|
|
222
|
-
headers: responseHeaders,
|
|
223
|
-
body: responseBody,
|
|
224
|
-
durationMs,
|
|
225
|
-
retryCount: attempt
|
|
226
|
-
});
|
|
227
|
-
if (response.ok) {
|
|
228
|
-
return {
|
|
229
|
-
data: responseBody,
|
|
752
|
+
const responseHeaders = parseHeaders(response.headers);
|
|
753
|
+
const durationMs = Date.now() - startMs;
|
|
754
|
+
pacer?.observe(responseHeaders, takesSlot, response.status, startMs);
|
|
755
|
+
this.onResponse?.({
|
|
230
756
|
status: response.status,
|
|
231
757
|
headers: responseHeaders,
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
758
|
+
body: responseBody,
|
|
759
|
+
durationMs,
|
|
760
|
+
retryCount: attempt
|
|
761
|
+
});
|
|
762
|
+
if (response.ok) {
|
|
763
|
+
return {
|
|
764
|
+
data: responseBody,
|
|
765
|
+
status: response.status,
|
|
766
|
+
headers: responseHeaders,
|
|
767
|
+
rateLimitInfo: parseRateLimitHeaders(responseHeaders)
|
|
768
|
+
};
|
|
769
|
+
}
|
|
770
|
+
const error = this.mapError(response.status, responseBody, responseHeaders);
|
|
771
|
+
lastError = error;
|
|
772
|
+
if (pacer && error instanceof RateLimitError) {
|
|
773
|
+
const delay = this.rateLimitDelay(attempt + 1, error, responseHeaders);
|
|
774
|
+
retryAt = performance.now() + delay;
|
|
775
|
+
pacer.pause(error.rateLimitInfo.scope, delay, takesSlot, startMs);
|
|
776
|
+
}
|
|
777
|
+
const shouldRetry = this.canRetry(
|
|
248
778
|
attempt,
|
|
249
779
|
method,
|
|
250
780
|
headers,
|
|
251
|
-
|
|
252
|
-
);
|
|
253
|
-
if (!canRetry) {
|
|
254
|
-
throw err;
|
|
255
|
-
}
|
|
256
|
-
lastError = err;
|
|
257
|
-
continue;
|
|
258
|
-
}
|
|
259
|
-
if (err instanceof DOMException && err.name === "AbortError") {
|
|
260
|
-
lastError = new TimeoutError(
|
|
261
|
-
`Request timed out after ${attemptTimeout}ms: ${method} ${path}`
|
|
781
|
+
isRetryableError(error)
|
|
262
782
|
);
|
|
263
|
-
if (!
|
|
783
|
+
if (!shouldRetry) {
|
|
264
784
|
throw lastError;
|
|
265
785
|
}
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
786
|
+
} catch (err) {
|
|
787
|
+
if (signal?.aborted) throw abortReason(signal);
|
|
788
|
+
if (err instanceof TriqaiError) {
|
|
789
|
+
const canRetry = this.canRetry(
|
|
790
|
+
attempt,
|
|
791
|
+
method,
|
|
792
|
+
headers,
|
|
793
|
+
isRetryableError(err)
|
|
794
|
+
);
|
|
795
|
+
if (!canRetry) {
|
|
796
|
+
throw err;
|
|
797
|
+
}
|
|
798
|
+
lastError = err;
|
|
799
|
+
continue;
|
|
274
800
|
}
|
|
275
|
-
|
|
801
|
+
if (err instanceof DOMException && err.name === "AbortError") {
|
|
802
|
+
lastError = new TimeoutError(
|
|
803
|
+
`Request timed out after ${attemptTimeout}ms: ${method} ${path}`
|
|
804
|
+
);
|
|
805
|
+
if (!this.canRetry(attempt, method, headers, true)) {
|
|
806
|
+
throw lastError;
|
|
807
|
+
}
|
|
808
|
+
continue;
|
|
809
|
+
}
|
|
810
|
+
if (isNetworkError(err)) {
|
|
811
|
+
lastError = new ConnectionError(
|
|
812
|
+
`Network error: ${err instanceof Error ? err.message : String(err)}`
|
|
813
|
+
);
|
|
814
|
+
if (!this.canRetry(attempt, method, headers, true)) {
|
|
815
|
+
throw lastError;
|
|
816
|
+
}
|
|
817
|
+
continue;
|
|
818
|
+
}
|
|
819
|
+
throw err;
|
|
276
820
|
}
|
|
277
|
-
throw err;
|
|
278
821
|
}
|
|
822
|
+
throw lastError ?? new TriqaiError("Request failed after retries", 0);
|
|
823
|
+
} finally {
|
|
824
|
+
permit?.release();
|
|
279
825
|
}
|
|
280
|
-
throw lastError ?? new TriqaiError("Request failed after retries", 0);
|
|
281
826
|
}
|
|
282
827
|
/**
|
|
283
828
|
* Variant that injects custom headers (used by resources for Idempotency-Key etc.).
|
|
284
829
|
*/
|
|
285
|
-
async postWithHeaders(path, body, headers, query) {
|
|
286
|
-
return this.request("POST", path, body, query, headers);
|
|
830
|
+
async postWithHeaders(path, body, headers, query, options) {
|
|
831
|
+
return this.request("POST", path, body, query, headers, options);
|
|
287
832
|
}
|
|
288
833
|
buildUrl(path, query) {
|
|
289
834
|
const isAbsoluteUrl = /^https?:\/\//i.test(path);
|
|
@@ -304,7 +849,7 @@ var HttpClient = class {
|
|
|
304
849
|
return qs ? `${base}?${qs}` : base;
|
|
305
850
|
}
|
|
306
851
|
calculateDelay(attempt, lastError) {
|
|
307
|
-
const retryAfter = lastError instanceof RateLimitError ? lastError.rateLimitInfo.retryAfter : lastError instanceof ServiceUnavailableError ? lastError.retryAfter : void 0;
|
|
852
|
+
const retryAfter = lastError instanceof RateLimitError ? lastError.rateLimitInfo.retryAfter : lastError instanceof ServiceUnavailableError || lastError instanceof DuplicateRequestError ? lastError.retryAfter : void 0;
|
|
308
853
|
if (retryAfter) {
|
|
309
854
|
const minimumDelay = retryAfter * 1e3;
|
|
310
855
|
return minimumDelay + Math.min(minimumDelay * 0.2, 1e3) * Math.random();
|
|
@@ -312,6 +857,22 @@ var HttpClient = class {
|
|
|
312
857
|
const exponential = Math.min(this.retryDelay * Math.pow(2, attempt - 1), this.maxRetryDelay / 1.2);
|
|
313
858
|
return exponential * (1 + 0.2 * Math.random());
|
|
314
859
|
}
|
|
860
|
+
/**
|
|
861
|
+
* The wait after a 429. Without Retry-After, the limit's reset time is used
|
|
862
|
+
* when it is near, measured against the response's Date header so the
|
|
863
|
+
* client's clock does not matter; otherwise the normal backoff.
|
|
864
|
+
*/
|
|
865
|
+
rateLimitDelay(attempt, error, headers) {
|
|
866
|
+
const { retryAfter, reset } = error.rateLimitInfo;
|
|
867
|
+
if (!retryAfter && reset !== void 0) {
|
|
868
|
+
const serverNow = headers.date === void 0 ? NaN : Date.parse(headers.date);
|
|
869
|
+
const untilReset = Date.parse(reset) - (Number.isNaN(serverNow) ? Date.now() : serverNow);
|
|
870
|
+
if (untilReset > 0 && untilReset <= MAX_RESET_WAIT_MS) {
|
|
871
|
+
return untilReset + Math.min(untilReset * 0.2, 1e3) * Math.random();
|
|
872
|
+
}
|
|
873
|
+
}
|
|
874
|
+
return this.calculateDelay(attempt, error);
|
|
875
|
+
}
|
|
315
876
|
canRetry(attempt, method, headers, retryableSignal) {
|
|
316
877
|
return retryableSignal && attempt < this.maxRetries && isIdempotent(method, headers);
|
|
317
878
|
}
|
|
@@ -339,10 +900,13 @@ var HttpClient = class {
|
|
|
339
900
|
return new DuplicateRequestError(parsed.message, {
|
|
340
901
|
...opts,
|
|
341
902
|
state: details?.state,
|
|
903
|
+
reason: details?.reason,
|
|
342
904
|
duplicateRequestId: details?.requestId,
|
|
343
905
|
retryAfter: details?.retryAfterSeconds
|
|
344
906
|
});
|
|
345
907
|
}
|
|
908
|
+
case 410:
|
|
909
|
+
return new GoneError(parsed.message, opts);
|
|
346
910
|
case 422: {
|
|
347
911
|
const fieldErrors = parsed.error?.details?.fieldErrors;
|
|
348
912
|
return new ValidationError(parsed.message, fieldErrors, opts);
|
|
@@ -424,6 +988,12 @@ function parseErrorBody(body) {
|
|
|
424
988
|
meta: meta?.generatedAt ? meta : void 0
|
|
425
989
|
};
|
|
426
990
|
}
|
|
991
|
+
function isRetryableError(err) {
|
|
992
|
+
if (err instanceof DuplicateRequestError) {
|
|
993
|
+
return err.reason === void 0 && (err.state === "in_progress" || err.state === "completed");
|
|
994
|
+
}
|
|
995
|
+
return RETRYABLE_STATUS_CODES.has(err.statusCode);
|
|
996
|
+
}
|
|
427
997
|
function isIdempotent(method, headers) {
|
|
428
998
|
if (method === "GET" || method === "DELETE") return true;
|
|
429
999
|
return Object.entries(headers).some(
|
|
@@ -446,8 +1016,38 @@ function isNetworkError(err) {
|
|
|
446
1016
|
}
|
|
447
1017
|
return false;
|
|
448
1018
|
}
|
|
449
|
-
function
|
|
450
|
-
|
|
1019
|
+
function takesEnrichmentSlot(method, url) {
|
|
1020
|
+
if (method !== "POST") return false;
|
|
1021
|
+
const path = url.split("?")[0].replace(/\/+$/, "");
|
|
1022
|
+
return path.endsWith("/v1/transactions/enrich");
|
|
1023
|
+
}
|
|
1024
|
+
function pacingByDefault() {
|
|
1025
|
+
const g = globalThis;
|
|
1026
|
+
if (typeof g.process?.versions?.node !== "string") return false;
|
|
1027
|
+
if (g.Deno !== void 0 || g.EdgeRuntime !== void 0 || g.WebSocketPair !== void 0) return false;
|
|
1028
|
+
return g.navigator?.userAgent !== "Cloudflare-Workers";
|
|
1029
|
+
}
|
|
1030
|
+
function isPlainObject(value) {
|
|
1031
|
+
if (typeof value !== "object" || value === null) return false;
|
|
1032
|
+
const proto = Object.getPrototypeOf(value);
|
|
1033
|
+
return proto === Object.prototype || proto === null;
|
|
1034
|
+
}
|
|
1035
|
+
function sleep(ms, signal) {
|
|
1036
|
+
if (!signal) return new Promise((resolve) => setTimeout(resolve, ms));
|
|
1037
|
+
return new Promise((resolve, reject) => {
|
|
1038
|
+
if (signal.aborted) {
|
|
1039
|
+
reject(abortReason(signal));
|
|
1040
|
+
return;
|
|
1041
|
+
}
|
|
1042
|
+
const timer = setTimeout(() => {
|
|
1043
|
+
unsubscribe();
|
|
1044
|
+
resolve();
|
|
1045
|
+
}, ms);
|
|
1046
|
+
const unsubscribe = onAbort(signal, () => {
|
|
1047
|
+
clearTimeout(timer);
|
|
1048
|
+
reject(abortReason(signal));
|
|
1049
|
+
});
|
|
1050
|
+
});
|
|
451
1051
|
}
|
|
452
1052
|
|
|
453
1053
|
// src/resources/banks.ts
|
|
@@ -456,13 +1056,13 @@ var Banks = class {
|
|
|
456
1056
|
this.http = http;
|
|
457
1057
|
}
|
|
458
1058
|
/** Exact, case-insensitive name lookup with an optional country of origin. Costs zero credits. */
|
|
459
|
-
async search(params) {
|
|
460
|
-
const resp = await this.http.get("/v1/banks", { ...params });
|
|
1059
|
+
async search(params, options) {
|
|
1060
|
+
const resp = await this.http.get("/v1/banks", { ...params }, options);
|
|
461
1061
|
return resp.data.data;
|
|
462
1062
|
}
|
|
463
1063
|
/** Retrieve stored bank details by UUID. */
|
|
464
|
-
async get(id) {
|
|
465
|
-
const resp = await this.http.get(`/v1/banks/${encodeURIComponent(id)}
|
|
1064
|
+
async get(id, options) {
|
|
1065
|
+
const resp = await this.http.get(`/v1/banks/${encodeURIComponent(id)}`, void 0, options);
|
|
466
1066
|
return resp.data.data.bank;
|
|
467
1067
|
}
|
|
468
1068
|
};
|
|
@@ -478,6 +1078,7 @@ var Categories = class {
|
|
|
478
1078
|
* Returns the full category tree used for transaction classification,
|
|
479
1079
|
* including MCC, SIC, and NAICS codes.
|
|
480
1080
|
*
|
|
1081
|
+
* @param options - Optional `signal` to cancel the call.
|
|
481
1082
|
* @returns Array of category info objects and the total count.
|
|
482
1083
|
*
|
|
483
1084
|
* @example
|
|
@@ -486,8 +1087,8 @@ var Categories = class {
|
|
|
486
1087
|
* console.log(`${total} categories available`);
|
|
487
1088
|
* ```
|
|
488
1089
|
*/
|
|
489
|
-
async list() {
|
|
490
|
-
const resp = await this.http.get("/v1/categories");
|
|
1090
|
+
async list(options) {
|
|
1091
|
+
const resp = await this.http.get("/v1/categories", void 0, options);
|
|
491
1092
|
return {
|
|
492
1093
|
categories: resp.data.data.categories,
|
|
493
1094
|
total: resp.data.data.total,
|
|
@@ -505,6 +1106,7 @@ var Intermediaries = class {
|
|
|
505
1106
|
* Get an intermediary (payment processor / platform) by ID.
|
|
506
1107
|
*
|
|
507
1108
|
* @param id - Intermediary UUID.
|
|
1109
|
+
* @param options - Optional `signal` to cancel the call.
|
|
508
1110
|
* @returns The intermediary data (name, icon, description, website, domain, etc.).
|
|
509
1111
|
*
|
|
510
1112
|
* @example
|
|
@@ -513,9 +1115,11 @@ var Intermediaries = class {
|
|
|
513
1115
|
* console.log(intermediary.name); // "PayPal", "Square", etc.
|
|
514
1116
|
* ```
|
|
515
1117
|
*/
|
|
516
|
-
async get(id) {
|
|
1118
|
+
async get(id, options) {
|
|
517
1119
|
const resp = await this.http.get(
|
|
518
|
-
`/v1/intermediaries/${encodeURIComponent(id)}
|
|
1120
|
+
`/v1/intermediaries/${encodeURIComponent(id)}`,
|
|
1121
|
+
void 0,
|
|
1122
|
+
options
|
|
519
1123
|
);
|
|
520
1124
|
return resp.data.data.intermediary;
|
|
521
1125
|
}
|
|
@@ -598,12 +1202,12 @@ var IssueReports = class {
|
|
|
598
1202
|
* console.log(report.id, report.status);
|
|
599
1203
|
* ```
|
|
600
1204
|
*/
|
|
601
|
-
async create(params) {
|
|
1205
|
+
async create(params, options) {
|
|
602
1206
|
const resp = await this.http.post("/v1/report-issue", {
|
|
603
1207
|
transaction_id: params.transactionId,
|
|
604
1208
|
description: params.description,
|
|
605
1209
|
fields: params.fields
|
|
606
|
-
});
|
|
1210
|
+
}, options);
|
|
607
1211
|
return resp.data.data.issueReport;
|
|
608
1212
|
}
|
|
609
1213
|
/**
|
|
@@ -620,12 +1224,12 @@ var IssueReports = class {
|
|
|
620
1224
|
* }
|
|
621
1225
|
* ```
|
|
622
1226
|
*/
|
|
623
|
-
async list(params) {
|
|
1227
|
+
async list(params, options) {
|
|
624
1228
|
const fetchPage = async (page, size) => {
|
|
625
1229
|
const query = { page, size };
|
|
626
1230
|
if (params?.status) query.status = params.status;
|
|
627
1231
|
if (params?.transactionId) query.transaction_id = params.transactionId;
|
|
628
|
-
const resp = await this.http.get("/v1/report-issue", query);
|
|
1232
|
+
const resp = await this.http.get("/v1/report-issue", query, options);
|
|
629
1233
|
const pageInfo = {
|
|
630
1234
|
page: resp.data.meta.page,
|
|
631
1235
|
size: resp.data.meta.size,
|
|
@@ -640,11 +1244,14 @@ var IssueReports = class {
|
|
|
640
1244
|
* Get a single issue report by ID.
|
|
641
1245
|
*
|
|
642
1246
|
* @param id - Issue report UUID.
|
|
1247
|
+
* @param options - Optional `signal` to cancel the call.
|
|
643
1248
|
* @returns The issue report details.
|
|
644
1249
|
*/
|
|
645
|
-
async get(id) {
|
|
1250
|
+
async get(id, options) {
|
|
646
1251
|
const resp = await this.http.get(
|
|
647
|
-
`/v1/report-issue/${encodeURIComponent(id)}
|
|
1252
|
+
`/v1/report-issue/${encodeURIComponent(id)}`,
|
|
1253
|
+
void 0,
|
|
1254
|
+
options
|
|
648
1255
|
);
|
|
649
1256
|
return resp.data.data.issueReport;
|
|
650
1257
|
}
|
|
@@ -659,6 +1266,7 @@ var Locations = class {
|
|
|
659
1266
|
* Get a location by ID.
|
|
660
1267
|
*
|
|
661
1268
|
* @param id - Location UUID.
|
|
1269
|
+
* @param options - Optional `signal` to cancel the call.
|
|
662
1270
|
* @returns The location data (name, formatted address, coordinates, phone, rating, etc.).
|
|
663
1271
|
*
|
|
664
1272
|
* @example
|
|
@@ -667,9 +1275,11 @@ var Locations = class {
|
|
|
667
1275
|
* console.log(location.formatted, location.structured.city);
|
|
668
1276
|
* ```
|
|
669
1277
|
*/
|
|
670
|
-
async get(id) {
|
|
1278
|
+
async get(id, options) {
|
|
671
1279
|
const resp = await this.http.get(
|
|
672
|
-
`/v1/locations/${encodeURIComponent(id)}
|
|
1280
|
+
`/v1/locations/${encodeURIComponent(id)}`,
|
|
1281
|
+
void 0,
|
|
1282
|
+
options
|
|
673
1283
|
);
|
|
674
1284
|
return resp.data.data.location;
|
|
675
1285
|
}
|
|
@@ -684,6 +1294,7 @@ var Merchants = class {
|
|
|
684
1294
|
* Get a merchant by ID.
|
|
685
1295
|
*
|
|
686
1296
|
* @param id - Merchant UUID.
|
|
1297
|
+
* @param options - Optional `signal` to cancel the call.
|
|
687
1298
|
* @returns The merchant data (name, icon, website, domain, aliases, etc.).
|
|
688
1299
|
*
|
|
689
1300
|
* @example
|
|
@@ -692,9 +1303,11 @@ var Merchants = class {
|
|
|
692
1303
|
* console.log(merchant.name, merchant.website);
|
|
693
1304
|
* ```
|
|
694
1305
|
*/
|
|
695
|
-
async get(id) {
|
|
1306
|
+
async get(id, options) {
|
|
696
1307
|
const resp = await this.http.get(
|
|
697
|
-
`/v1/merchants/${encodeURIComponent(id)}
|
|
1308
|
+
`/v1/merchants/${encodeURIComponent(id)}`,
|
|
1309
|
+
void 0,
|
|
1310
|
+
options
|
|
698
1311
|
);
|
|
699
1312
|
return resp.data.data.merchant;
|
|
700
1313
|
}
|
|
@@ -718,7 +1331,7 @@ var Transactions = class {
|
|
|
718
1331
|
* Enrich a transaction with merchant, category, location, and entity data.
|
|
719
1332
|
*
|
|
720
1333
|
* @param request - The transaction to enrich (title, country, type, and optional options).
|
|
721
|
-
* @param options - Optional
|
|
1334
|
+
* @param options - Optional idempotency key and `signal` to cancel the call.
|
|
722
1335
|
* @returns The enriched transaction data.
|
|
723
1336
|
*
|
|
724
1337
|
* @example
|
|
@@ -735,15 +1348,12 @@ var Transactions = class {
|
|
|
735
1348
|
const headers = {
|
|
736
1349
|
"Idempotency-Key": options?.idempotencyKey ?? await createIdempotencyKey()
|
|
737
1350
|
};
|
|
738
|
-
const query = {};
|
|
739
|
-
if (options?.force) {
|
|
740
|
-
query.force = "true";
|
|
741
|
-
}
|
|
742
1351
|
const resp = await this.http.postWithHeaders(
|
|
743
1352
|
"/v1/transactions/enrich",
|
|
744
1353
|
request,
|
|
745
1354
|
headers,
|
|
746
|
-
|
|
1355
|
+
void 0,
|
|
1356
|
+
{ signal: options?.signal }
|
|
747
1357
|
);
|
|
748
1358
|
return resp.data;
|
|
749
1359
|
}
|
|
@@ -764,7 +1374,7 @@ var Transactions = class {
|
|
|
764
1374
|
* }
|
|
765
1375
|
* ```
|
|
766
1376
|
*/
|
|
767
|
-
async list(params) {
|
|
1377
|
+
async list(params, options) {
|
|
768
1378
|
const fetchPage = async (page, size) => {
|
|
769
1379
|
const query = {
|
|
770
1380
|
page,
|
|
@@ -776,21 +1386,43 @@ var Transactions = class {
|
|
|
776
1386
|
if (params?.endDate) {
|
|
777
1387
|
query.endDate = params.endDate instanceof Date ? params.endDate.toISOString() : params.endDate;
|
|
778
1388
|
}
|
|
779
|
-
const resp = await this.http.get("/v1/transactions", query);
|
|
1389
|
+
const resp = await this.http.get("/v1/transactions", query, options);
|
|
780
1390
|
const { transactions, pagination } = resp.data.data;
|
|
781
1391
|
return new Page(transactions, pagination, fetchPage);
|
|
782
1392
|
};
|
|
783
1393
|
return fetchPage(params?.page ?? 1, params?.size ?? 25);
|
|
784
1394
|
}
|
|
1395
|
+
/**
|
|
1396
|
+
* Count your organization's transactions.
|
|
1397
|
+
*
|
|
1398
|
+
* @param params - Optional `afterDate` to count only transactions created on or after it.
|
|
1399
|
+
* @returns The number of matching transactions.
|
|
1400
|
+
*
|
|
1401
|
+
* @example
|
|
1402
|
+
* ```ts
|
|
1403
|
+
* const { count } = await triqai.transactions.count({ afterDate: "2026-01-01T00:00:00Z" });
|
|
1404
|
+
* ```
|
|
1405
|
+
*/
|
|
1406
|
+
async count(params, options) {
|
|
1407
|
+
const query = {};
|
|
1408
|
+
if (params?.afterDate) {
|
|
1409
|
+
query.afterDate = params.afterDate instanceof Date ? params.afterDate.toISOString() : params.afterDate;
|
|
1410
|
+
}
|
|
1411
|
+
const resp = await this.http.get("/v1/transactions/count", query, options);
|
|
1412
|
+
return resp.data.data;
|
|
1413
|
+
}
|
|
785
1414
|
/**
|
|
786
1415
|
* Get a single transaction by ID.
|
|
787
1416
|
*
|
|
788
1417
|
* @param id - Transaction UUID.
|
|
1418
|
+
* @param options - Optional `signal` to cancel the call.
|
|
789
1419
|
* @returns The enriched transaction record.
|
|
790
1420
|
*/
|
|
791
|
-
async get(id) {
|
|
1421
|
+
async get(id, options) {
|
|
792
1422
|
const resp = await this.http.get(
|
|
793
|
-
`/v1/transactions/${encodeURIComponent(id)}
|
|
1423
|
+
`/v1/transactions/${encodeURIComponent(id)}`,
|
|
1424
|
+
void 0,
|
|
1425
|
+
options
|
|
794
1426
|
);
|
|
795
1427
|
return resp.data.data.transaction;
|
|
796
1428
|
}
|
|
@@ -798,19 +1430,46 @@ var Transactions = class {
|
|
|
798
1430
|
* Delete a transaction by ID.
|
|
799
1431
|
*
|
|
800
1432
|
* @param id - Transaction UUID.
|
|
1433
|
+
* @param options - Optional `signal` to cancel the call.
|
|
801
1434
|
* @returns Confirmation with the deleted transaction ID.
|
|
802
1435
|
*/
|
|
803
|
-
async delete(id) {
|
|
1436
|
+
async delete(id, options) {
|
|
804
1437
|
const resp = await this.http.delete(
|
|
805
|
-
`/v1/transactions/${encodeURIComponent(id)}
|
|
1438
|
+
`/v1/transactions/${encodeURIComponent(id)}`,
|
|
1439
|
+
void 0,
|
|
1440
|
+
options
|
|
806
1441
|
);
|
|
807
1442
|
return resp.data.data;
|
|
808
1443
|
}
|
|
1444
|
+
/**
|
|
1445
|
+
* Delete many transactions in one request.
|
|
1446
|
+
*
|
|
1447
|
+
* Pass exactly one of `all: true` (every transaction in your organization),
|
|
1448
|
+
* `afterDate` (transactions created on or after it), or `ids` (at most 1000
|
|
1449
|
+
* UUIDs). The API rejects any other combination with a 422 `ValidationError`.
|
|
1450
|
+
* A 503 means cleanup is incomplete; like other DELETE requests, it is retried
|
|
1451
|
+
* automatically, and `count` then covers only the final attempt.
|
|
1452
|
+
*
|
|
1453
|
+
* @param request - The single selection mode.
|
|
1454
|
+
* @returns Confirmation with the number of transactions deleted.
|
|
1455
|
+
*
|
|
1456
|
+
* @example
|
|
1457
|
+
* ```ts
|
|
1458
|
+
* const { count } = await triqai.transactions.batchDelete({
|
|
1459
|
+
* ids: ["550e8400-e29b-41d4-a716-446655440000"],
|
|
1460
|
+
* });
|
|
1461
|
+
* ```
|
|
1462
|
+
*/
|
|
1463
|
+
async batchDelete(request, options) {
|
|
1464
|
+
const body = "afterDate" in request && request.afterDate instanceof Date ? { ...request, afterDate: request.afterDate.toISOString() } : request;
|
|
1465
|
+
const resp = await this.http.delete("/v1/transactions/batch", body, options);
|
|
1466
|
+
return resp.data.data;
|
|
1467
|
+
}
|
|
809
1468
|
};
|
|
810
1469
|
|
|
811
1470
|
// src/client.ts
|
|
812
1471
|
var Triqai = class {
|
|
813
|
-
/** Enrich, list, get, and delete transactions. */
|
|
1472
|
+
/** Enrich, list, count, get, and delete transactions. */
|
|
814
1473
|
transactions;
|
|
815
1474
|
/** List the full category taxonomy. */
|
|
816
1475
|
categories;
|
|
@@ -853,8 +1512,8 @@ var Triqai = class {
|
|
|
853
1512
|
* console.log(health.data.version); // "1.1.9"
|
|
854
1513
|
* ```
|
|
855
1514
|
*/
|
|
856
|
-
async health() {
|
|
857
|
-
const resp = await this.http.get("/health");
|
|
1515
|
+
async health(options) {
|
|
1516
|
+
const resp = await this.http.get("/health", void 0, options);
|
|
858
1517
|
return resp.data;
|
|
859
1518
|
}
|
|
860
1519
|
/**
|
|
@@ -869,8 +1528,8 @@ var Triqai = class {
|
|
|
869
1528
|
* console.log(info.data.endpoints);
|
|
870
1529
|
* ```
|
|
871
1530
|
*/
|
|
872
|
-
async apiInfo() {
|
|
873
|
-
const resp = await this.http.get("/v1");
|
|
1531
|
+
async apiInfo(options) {
|
|
1532
|
+
const resp = await this.http.get("/v1", void 0, options);
|
|
874
1533
|
return resp.data;
|
|
875
1534
|
}
|
|
876
1535
|
/**
|
|
@@ -879,10 +1538,11 @@ var Triqai = class {
|
|
|
879
1538
|
*
|
|
880
1539
|
* @param path - API path (e.g. "/v1/some-endpoint").
|
|
881
1540
|
* @param query - Optional query parameters.
|
|
1541
|
+
* @param options - Optional `signal` to cancel the call.
|
|
882
1542
|
* @returns The full HTTP response including headers and rate limit info.
|
|
883
1543
|
*/
|
|
884
|
-
async rawGet(path, query) {
|
|
885
|
-
return this.http.get(path, query);
|
|
1544
|
+
async rawGet(path, query, options) {
|
|
1545
|
+
return this.http.get(path, query, options);
|
|
886
1546
|
}
|
|
887
1547
|
/**
|
|
888
1548
|
* Make a raw POST request to any API path.
|
|
@@ -890,26 +1550,28 @@ var Triqai = class {
|
|
|
890
1550
|
*
|
|
891
1551
|
* @param path - API path (e.g. "/v1/some-endpoint").
|
|
892
1552
|
* @param body - Request body.
|
|
1553
|
+
* @param options - Optional `signal` to cancel the call.
|
|
893
1554
|
* @returns The full HTTP response including headers and rate limit info.
|
|
894
1555
|
*/
|
|
895
|
-
async rawPost(path, body) {
|
|
896
|
-
return this.http.post(path, body);
|
|
1556
|
+
async rawPost(path, body, options) {
|
|
1557
|
+
return this.http.post(path, body, options);
|
|
897
1558
|
}
|
|
898
1559
|
/**
|
|
899
1560
|
* Make a raw DELETE request to any API path.
|
|
900
1561
|
* Useful for accessing endpoints not yet covered by a resource class.
|
|
901
1562
|
*
|
|
902
1563
|
* @param path - API path (e.g. "/v1/some-resource/uuid").
|
|
1564
|
+
* @param options - Optional `signal` to cancel the call.
|
|
903
1565
|
* @returns The full HTTP response including headers and rate limit info.
|
|
904
1566
|
*/
|
|
905
|
-
async rawDelete(path) {
|
|
906
|
-
return this.http.delete(path);
|
|
1567
|
+
async rawDelete(path, options) {
|
|
1568
|
+
return this.http.delete(path, void 0, options);
|
|
907
1569
|
}
|
|
908
1570
|
};
|
|
909
1571
|
|
|
910
1572
|
// src/index.ts
|
|
911
1573
|
var index_default = Triqai;
|
|
912
1574
|
|
|
913
|
-
export { AuthenticationError, AuthorizationError, ClientDisconnectedError, ConnectionError, DuplicateRequestError, GatewayTimeoutError, InsufficientCreditsError, InternalServerError, NotFoundError, Page, RateLimitError, ServiceUnavailableError, TimeoutError, Triqai, TriqaiError, ValidationError, index_default as default };
|
|
1575
|
+
export { AuthenticationError, AuthorizationError, ClientDisconnectedError, ConnectionError, DuplicateRequestError, GatewayTimeoutError, GoneError, InsufficientCreditsError, InternalServerError, NotFoundError, PacingTimeoutError, Page, RateLimitError, ServiceUnavailableError, TimeoutError, Triqai, TriqaiError, ValidationError, index_default as default };
|
|
914
1576
|
//# sourceMappingURL=index.js.map
|
|
915
1577
|
//# sourceMappingURL=index.js.map
|