@bedrock-rbx/ocale 0.1.3 → 0.1.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/badges.d.mts +21 -6
- package/dist/badges.d.mts.map +1 -1
- package/dist/badges.mjs +10 -11
- package/dist/badges.mjs.map +1 -1
- package/dist/developer-products.d.mts +22 -11
- package/dist/developer-products.d.mts.map +1 -1
- package/dist/developer-products.mjs +21 -20
- package/dist/developer-products.mjs.map +1 -1
- package/dist/game-passes.d.mts +5 -5
- package/dist/game-passes.mjs +18 -20
- package/dist/game-passes.mjs.map +1 -1
- package/dist/index.d.mts +10 -6
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +5 -5
- package/dist/luau-execution.d.mts +5 -3
- package/dist/luau-execution.d.mts.map +1 -1
- package/dist/luau-execution.mjs +22 -18
- package/dist/luau-execution.mjs.map +1 -1
- package/dist/places.d.mts +2 -2
- package/dist/places.d.mts.map +1 -1
- package/dist/places.mjs +31 -31
- package/dist/places.mjs.map +1 -1
- package/dist/{poll-timeout-BfxUWWCZ.mjs → poll-timeout-VZuy48ii.mjs} +2 -2
- package/dist/{poll-timeout-BfxUWWCZ.mjs.map → poll-timeout-VZuy48ii.mjs.map} +1 -1
- package/dist/{polling-rj0dGREg.d.mts → polling-CG12rHaz.d.mts} +29 -11
- package/dist/polling-CG12rHaz.d.mts.map +1 -0
- package/dist/{polling-helpers-DkJcWZpp.mjs → polling-helpers-O2Pk3rN0.mjs} +53 -53
- package/dist/polling-helpers-O2Pk3rN0.mjs.map +1 -0
- package/dist/{price-information-ClGhSmgI.mjs → price-information-CBkLZjYs.mjs} +2 -2
- package/dist/{price-information-ClGhSmgI.mjs.map → price-information-CBkLZjYs.mjs.map} +1 -1
- package/dist/{rate-limit-Dh2leqaB.mjs → rate-limit-D1MQZNAE.mjs} +8 -4
- package/dist/rate-limit-D1MQZNAE.mjs.map +1 -0
- package/dist/{resource-client-CsbYSKwf.mjs → resource-client-6KaHBVI7.mjs} +190 -98
- package/dist/resource-client-6KaHBVI7.mjs.map +1 -0
- package/dist/{retry-CMzwdn1c.mjs → retry-D1HKlycK.mjs} +51 -21
- package/dist/retry-D1HKlycK.mjs.map +1 -0
- package/dist/{retry-BEh37aK2.d.mts → retry-DANH6mM9.d.mts} +61 -13
- package/dist/retry-DANH6mM9.d.mts.map +1 -0
- package/dist/storage.d.mts +33 -8
- package/dist/storage.d.mts.map +1 -1
- package/dist/storage.mjs +24 -33
- package/dist/storage.mjs.map +1 -1
- package/dist/testing.d.mts +50 -16
- package/dist/testing.d.mts.map +1 -1
- package/dist/testing.mjs +5 -3
- package/dist/testing.mjs.map +1 -1
- package/dist/{types-CRiJg5EQ.d.mts → types-DXai6-hU.d.mts} +5 -3
- package/dist/{types-CRiJg5EQ.d.mts.map → types-DXai6-hU.d.mts.map} +1 -1
- package/dist/universes.d.mts +7 -4
- package/dist/universes.d.mts.map +1 -1
- package/dist/universes.mjs +20 -25
- package/dist/universes.mjs.map +1 -1
- package/dist/{validation-xJZRa8tX.mjs → validation-BJ0-hNLs.mjs} +2 -2
- package/dist/{validation-xJZRa8tX.mjs.map → validation-BJ0-hNLs.mjs.map} +1 -1
- package/package.json +4 -3
- package/dist/polling-helpers-DkJcWZpp.mjs.map +0 -1
- package/dist/polling-rj0dGREg.d.mts.map +0 -1
- package/dist/rate-limit-Dh2leqaB.mjs.map +0 -1
- package/dist/resource-client-CsbYSKwf.mjs.map +0 -1
- package/dist/retry-BEh37aK2.d.mts.map +0 -1
- package/dist/retry-CMzwdn1c.mjs.map +0 -1
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { n as NetworkError, r as ApiError, t as RateLimitError } from "./rate-limit-
|
|
2
|
-
import {
|
|
1
|
+
import { n as NetworkError, r as ApiError, t as RateLimitError } from "./rate-limit-D1MQZNAE.mjs";
|
|
2
|
+
import { c as defaultRetryDelay, f as PermissionError, l as mergeConfig, r as IDEMPOTENT_METHOD_DEFAULTS, s as computeRetryWaitMs, u as shouldRetry } from "./retry-D1HKlycK.mjs";
|
|
3
3
|
import { setTimeout } from "node:timers/promises";
|
|
4
4
|
//#region src/internal/utils/is-date-time-string.ts
|
|
5
5
|
/**
|
|
@@ -32,6 +32,52 @@ function isRecord(value) {
|
|
|
32
32
|
return Object.prototype.toString.call(value) === "[object Object]";
|
|
33
33
|
}
|
|
34
34
|
//#endregion
|
|
35
|
+
//#region src/internal/utils/to-json-details.ts
|
|
36
|
+
/**
|
|
37
|
+
* Narrows an untyped response body to the `JSONValue` accepted by
|
|
38
|
+
* `ApiError.details`. `HttpResponse.body` is `unknown` because a transport may
|
|
39
|
+
* hand back anything, but only a JSON graph is safe to retain on an error for
|
|
40
|
+
* diagnostics. Anything else — functions, symbols, bigints, class instances,
|
|
41
|
+
* or a cyclic graph — is dropped rather than asserted through.
|
|
42
|
+
*
|
|
43
|
+
* @param value - The parsed response body, or `undefined` for an empty body.
|
|
44
|
+
* @returns The value as a `JSONValue`, or `undefined` when it is absent or not
|
|
45
|
+
* JSON-representable.
|
|
46
|
+
*/
|
|
47
|
+
function toJsonDetails(value) {
|
|
48
|
+
return asJsonValue(value, /* @__PURE__ */ new Set());
|
|
49
|
+
}
|
|
50
|
+
function asJsonValue(value, seen) {
|
|
51
|
+
if (value === null) return null;
|
|
52
|
+
if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") return value;
|
|
53
|
+
if (Array.isArray(value)) return asJsonArray(value, seen);
|
|
54
|
+
if (isRecord(value)) return asJsonObject(value, seen);
|
|
55
|
+
}
|
|
56
|
+
function asJsonArray(value, seen) {
|
|
57
|
+
if (seen.has(value)) return;
|
|
58
|
+
seen.add(value);
|
|
59
|
+
const items = [];
|
|
60
|
+
for (const item of value) {
|
|
61
|
+
const converted = asJsonValue(item, seen);
|
|
62
|
+
if (converted === void 0) return;
|
|
63
|
+
items.push(converted);
|
|
64
|
+
}
|
|
65
|
+
seen.delete(value);
|
|
66
|
+
return items;
|
|
67
|
+
}
|
|
68
|
+
function asJsonObject(value, seen) {
|
|
69
|
+
if (seen.has(value)) return;
|
|
70
|
+
seen.add(value);
|
|
71
|
+
const entries = [];
|
|
72
|
+
for (const [key, item] of Object.entries(value)) {
|
|
73
|
+
const converted = asJsonValue(item, seen);
|
|
74
|
+
if (converted === void 0) return;
|
|
75
|
+
entries.push([key, converted]);
|
|
76
|
+
}
|
|
77
|
+
seen.delete(value);
|
|
78
|
+
return Object.fromEntries(entries);
|
|
79
|
+
}
|
|
80
|
+
//#endregion
|
|
35
81
|
//#region src/internal/http/budget-tracker.ts
|
|
36
82
|
const MS_PER_SECOND = 1e3;
|
|
37
83
|
/**
|
|
@@ -131,10 +177,10 @@ var BudgetGate = class {
|
|
|
131
177
|
*
|
|
132
178
|
* @param scope - The scope key to gate on (the effective API key).
|
|
133
179
|
*/
|
|
134
|
-
async
|
|
180
|
+
async gateAsync(scope) {
|
|
135
181
|
const previous = this.#chains.get(scope) ?? Promise.resolve();
|
|
136
|
-
const
|
|
137
|
-
const mine = previous.then(
|
|
182
|
+
const runGateAsync = async () => this.#gateOnce(scope);
|
|
183
|
+
const mine = previous.then(runGateAsync, runGateAsync);
|
|
138
184
|
this.#chains.set(scope, mine);
|
|
139
185
|
await mine;
|
|
140
186
|
}
|
|
@@ -143,7 +189,7 @@ var BudgetGate = class {
|
|
|
143
189
|
* sample (headers absent or non-numeric) is ignored, leaving the scope on
|
|
144
190
|
* static pacing.
|
|
145
191
|
*
|
|
146
|
-
* @param scope - The same scope key passed to {@link
|
|
192
|
+
* @param scope - The same scope key passed to {@link gateAsync}.
|
|
147
193
|
* @param sample - Parsed sample, or `undefined` when none was reported.
|
|
148
194
|
*/
|
|
149
195
|
observe(scope, sample) {
|
|
@@ -177,13 +223,12 @@ var BudgetGate = class {
|
|
|
177
223
|
* @param options - The transport callback, resolved config, hooks, and sleep.
|
|
178
224
|
* @returns The first success, or the final error after retries are exhausted.
|
|
179
225
|
*/
|
|
180
|
-
async function
|
|
181
|
-
|
|
182
|
-
async function attempt() {
|
|
226
|
+
async function executeWithRetryAsync(request, { config, hooks, send, sleep }) {
|
|
227
|
+
async function attemptAsync() {
|
|
183
228
|
hooks.onRequest?.(request);
|
|
184
229
|
return send(request);
|
|
185
230
|
}
|
|
186
|
-
let result = await
|
|
231
|
+
let result = await attemptAsync();
|
|
187
232
|
for (let retry = 0; retry < config.maxRetries; retry++) {
|
|
188
233
|
if (result.success || !shouldRetry(result.err, config)) return result;
|
|
189
234
|
const { err } = result;
|
|
@@ -194,7 +239,7 @@ async function executeWithRetry(request, options) {
|
|
|
194
239
|
});
|
|
195
240
|
hooks.onRateLimit?.(waitMs);
|
|
196
241
|
await sleep(waitMs);
|
|
197
|
-
result = await
|
|
242
|
+
result = await attemptAsync();
|
|
198
243
|
}
|
|
199
244
|
return result;
|
|
200
245
|
}
|
|
@@ -229,8 +274,12 @@ function reduceRateLimitTokens(headerValue, combine) {
|
|
|
229
274
|
* @returns The parsed sample, or `undefined` when the budget cannot be read.
|
|
230
275
|
*/
|
|
231
276
|
function parseRateLimitHeaders(headers) {
|
|
232
|
-
const remaining = reduceRateLimitTokens(headers["x-ratelimit-remaining"], (a, b) =>
|
|
233
|
-
|
|
277
|
+
const remaining = reduceRateLimitTokens(headers["x-ratelimit-remaining"], (a, b) => {
|
|
278
|
+
return Math.min(a, b);
|
|
279
|
+
});
|
|
280
|
+
const resetSeconds = reduceRateLimitTokens(headers["x-ratelimit-reset"], (a, b) => {
|
|
281
|
+
return Math.max(a, b);
|
|
282
|
+
});
|
|
234
283
|
if (remaining === void 0 || resetSeconds === void 0) return;
|
|
235
284
|
return {
|
|
236
285
|
remaining,
|
|
@@ -262,12 +311,16 @@ function rateLimitSampleFromResult(result) {
|
|
|
262
311
|
/**
|
|
263
312
|
* Token-bucket rate limiter for a single `(apiKey, operation)` pair. Every
|
|
264
313
|
* call to `acquire` consumes one token; when the bucket is empty the call
|
|
265
|
-
* waits until a token regenerates before invoking the task.
|
|
266
|
-
*
|
|
314
|
+
* waits until a token regenerates before invoking the task. Tokens refill at
|
|
315
|
+
* `maxPerSecond` per second, up to the operation's `burstCapacity`.
|
|
267
316
|
*
|
|
268
317
|
* Implemented as a leaky bucket tracking drain debt in ms. `#lastCheck`
|
|
269
318
|
* advances by `waitMs` after every sleep so the algorithm stays correct
|
|
270
|
-
* whether or not the injected sleep moves `Date.now()` forward.
|
|
319
|
+
* whether or not the injected sleep moves `Date.now()` forward. `#bucketLevel`
|
|
320
|
+
* and `#maxBucketLevel` are both ms of drain debt, so the ceiling is the burst
|
|
321
|
+
* expressed in that unit: `burstCapacity` refill intervals. Deriving it any
|
|
322
|
+
* other way (notably `maxPerSecond * intervalMs`, whose units cancel to a
|
|
323
|
+
* constant 1000) starves every operation slower than one request per second.
|
|
271
324
|
*/
|
|
272
325
|
var RateLimitQueue = class {
|
|
273
326
|
#hooks;
|
|
@@ -287,7 +340,8 @@ var RateLimitQueue = class {
|
|
|
287
340
|
*/
|
|
288
341
|
constructor(limit, hooks, sleep) {
|
|
289
342
|
this.#intervalMs = 1e3 / limit.maxPerSecond;
|
|
290
|
-
|
|
343
|
+
const burstCapacity = limit.burstCapacity ?? Math.max(1, limit.maxPerSecond);
|
|
344
|
+
this.#maxBucketLevel = burstCapacity * this.#intervalMs;
|
|
291
345
|
this.#hooks = hooks;
|
|
292
346
|
this.#sleep = sleep;
|
|
293
347
|
}
|
|
@@ -300,7 +354,7 @@ var RateLimitQueue = class {
|
|
|
300
354
|
* @param task - The request to run once a token is available.
|
|
301
355
|
* @returns The value produced by `task`.
|
|
302
356
|
*/
|
|
303
|
-
async
|
|
357
|
+
async acquireAsync(task) {
|
|
304
358
|
const myTurn = this.#chain.then(async () => this.#waitForToken());
|
|
305
359
|
this.#chain = myTurn;
|
|
306
360
|
await myTurn;
|
|
@@ -330,7 +384,7 @@ var RateLimitQueue = class {
|
|
|
330
384
|
* @param promise - The promise to wrap.
|
|
331
385
|
* @returns A Result containing the resolved value or the rejection error.
|
|
332
386
|
*/
|
|
333
|
-
async function
|
|
387
|
+
async function tryCatchAsync(promise) {
|
|
334
388
|
try {
|
|
335
389
|
return {
|
|
336
390
|
data: await promise,
|
|
@@ -345,6 +399,8 @@ async function tryCatch(promise) {
|
|
|
345
399
|
}
|
|
346
400
|
//#endregion
|
|
347
401
|
//#region src/internal/http/diagnostics.ts
|
|
402
|
+
const MAX_DETAIL_LENGTH = 500;
|
|
403
|
+
const CONTENT_TYPE_HEADER$1 = "content-type";
|
|
348
404
|
const DIAGNOSTIC_HEADER_ALLOWLIST = new Set([
|
|
349
405
|
"cf-ray",
|
|
350
406
|
"server",
|
|
@@ -352,9 +408,9 @@ const DIAGNOSTIC_HEADER_ALLOWLIST = new Set([
|
|
|
352
408
|
"x-request-id"
|
|
353
409
|
]);
|
|
354
410
|
const DIAGNOSTIC_HEADER_PREFIX = "x-roblox-";
|
|
355
|
-
const
|
|
356
|
-
const
|
|
357
|
-
const TAG_PATTERN = /<[
|
|
411
|
+
const TITLE_OPEN_PATTERN = /<title[^>]*>/i;
|
|
412
|
+
const H1_OPEN_PATTERN = /<h1[^>]*>/i;
|
|
413
|
+
const TAG_PATTERN = /<[^<>]*>/g;
|
|
358
414
|
const WHITESPACE_PATTERN = /\s+/g;
|
|
359
415
|
/**
|
|
360
416
|
* Extracts a one-line human summary from an HTML gateway error page, or returns
|
|
@@ -373,7 +429,13 @@ const WHITESPACE_PATTERN = /\s+/g;
|
|
|
373
429
|
*/
|
|
374
430
|
function extractGatewaySummary(contentType, rawText) {
|
|
375
431
|
if (!isHtmlBody(contentType, rawText)) return;
|
|
376
|
-
return firstTagText(rawText,
|
|
432
|
+
return firstTagText(rawText, {
|
|
433
|
+
close: "</title>",
|
|
434
|
+
open: TITLE_OPEN_PATTERN
|
|
435
|
+
}) ?? firstTagText(rawText, {
|
|
436
|
+
close: "</h1>",
|
|
437
|
+
open: H1_OPEN_PATTERN
|
|
438
|
+
});
|
|
377
439
|
}
|
|
378
440
|
/**
|
|
379
441
|
* Filters a lowercased header record down to the diagnostic allowlist: a few
|
|
@@ -388,10 +450,61 @@ function pickDiagnosticHeaders(headers) {
|
|
|
388
450
|
for (const [name, value] of Object.entries(headers)) if (DIAGNOSTIC_HEADER_ALLOWLIST.has(name) || name.startsWith(DIAGNOSTIC_HEADER_PREFIX)) picked[name] = value;
|
|
389
451
|
return picked;
|
|
390
452
|
}
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
453
|
+
/**
|
|
454
|
+
* Converts a `Headers` object to a plain record with lowercased keys.
|
|
455
|
+
*
|
|
456
|
+
* @param headers - The `Headers` instance to convert.
|
|
457
|
+
* @returns A record mapping lowercased header names to their values.
|
|
458
|
+
*/
|
|
459
|
+
function headersToRecord(headers) {
|
|
460
|
+
return Object.fromEntries(headers);
|
|
461
|
+
}
|
|
462
|
+
/**
|
|
463
|
+
* Projects a read body to the detail carried on an error: the parsed JSON when
|
|
464
|
+
* it parsed, otherwise the raw text truncated to {@link MAX_DETAIL_LENGTH}.
|
|
465
|
+
*
|
|
466
|
+
* @param text - The raw response body text.
|
|
467
|
+
* @param parsed - The best-effort parse result from the transport's body read.
|
|
468
|
+
* @returns The parsed body, or the truncated raw text on a parse failure.
|
|
469
|
+
*/
|
|
470
|
+
function bodyDetail(text, parsed) {
|
|
471
|
+
return parsed.success ? parsed.data : text.slice(0, MAX_DETAIL_LENGTH);
|
|
472
|
+
}
|
|
473
|
+
/**
|
|
474
|
+
* Builds the error for a 2xx response whose body could not be parsed as JSON,
|
|
475
|
+
* preserving the parse `cause`, the (truncated) raw body, the declared
|
|
476
|
+
* content-type, and the request that produced it so the failure can be
|
|
477
|
+
* diagnosed after the fact.
|
|
478
|
+
*
|
|
479
|
+
* The received length is on the message rather than only on the error, because
|
|
480
|
+
* `details` retains just the first {@link MAX_DETAIL_LENGTH} characters: for a
|
|
481
|
+
* body that stopped mid-token the head says nothing and the length says
|
|
482
|
+
* everything. A `SyntaxError` position equal to this number is a body the edge
|
|
483
|
+
* cut short, not one the API mis-serialized.
|
|
484
|
+
*
|
|
485
|
+
* @param args - The Response, raw body text, request context, and underlying
|
|
486
|
+
* parse error.
|
|
487
|
+
* @returns An ApiError carrying the diagnostic context.
|
|
488
|
+
*/
|
|
489
|
+
function parseFailureError({ cause, context, response, text }) {
|
|
490
|
+
return new ApiError(`Failed to parse response body (content-type: ${response.headers.get(CONTENT_TYPE_HEADER$1) ?? "unknown"}, ${String(text.length)} chars read)`, {
|
|
491
|
+
cause,
|
|
492
|
+
details: text.slice(0, MAX_DETAIL_LENGTH),
|
|
493
|
+
elapsedMs: context.elapsedMs,
|
|
494
|
+
method: context.method,
|
|
495
|
+
responseHeaders: pickDiagnosticHeaders(headersToRecord(response.headers)),
|
|
496
|
+
statusCode: response.status,
|
|
497
|
+
unparsedBodyLength: text.length,
|
|
498
|
+
url: context.url
|
|
499
|
+
});
|
|
500
|
+
}
|
|
501
|
+
function firstTagText(html, tag) {
|
|
502
|
+
const open = tag.open.exec(html);
|
|
503
|
+
if (open === null) return;
|
|
504
|
+
const start = open.index + open[0].length;
|
|
505
|
+
const end = html.toLowerCase().indexOf(tag.close, start);
|
|
506
|
+
if (end === -1) return;
|
|
507
|
+
const text = html.slice(start, end).replace(TAG_PATTERN, " ").replace(WHITESPACE_PATTERN, " ").trim();
|
|
395
508
|
return text === "" ? void 0 : text;
|
|
396
509
|
}
|
|
397
510
|
function isHtmlBody(contentType, rawText) {
|
|
@@ -411,6 +524,18 @@ function isHtmlBody(contentType, rawText) {
|
|
|
411
524
|
*/
|
|
412
525
|
const GLOBAL_DISPATCHER_KEYS = Object.freeze(["undici.globalDispatcher.2", "undici.globalDispatcher.1"]);
|
|
413
526
|
/**
|
|
527
|
+
* Narrow a value read off the global dispatcher to something
|
|
528
|
+
* `Reflect.construct` accepts. Exported so the narrowing is unit-testable: at
|
|
529
|
+
* the call site every rejected shape funnels into the same `undefined`, which
|
|
530
|
+
* makes the branch unobservable from `createHttp1Dispatcher` alone.
|
|
531
|
+
*
|
|
532
|
+
* @param value - The candidate `constructor` read off the global dispatcher.
|
|
533
|
+
* @returns Whether the value can be constructed.
|
|
534
|
+
*/
|
|
535
|
+
function isAgentConstructor(value) {
|
|
536
|
+
return typeof value === "function";
|
|
537
|
+
}
|
|
538
|
+
/**
|
|
414
539
|
* Builds a request dispatcher that negotiates HTTP/1.1 only, by reusing the
|
|
415
540
|
* class of the runtime's own global dispatcher.
|
|
416
541
|
*
|
|
@@ -458,6 +583,7 @@ function createHttp1Dispatcher(scope = globalThis) {
|
|
|
458
583
|
function constructHttp1(agent) {
|
|
459
584
|
try {
|
|
460
585
|
const agentClass = Reflect.get(agent, "constructor");
|
|
586
|
+
if (!isAgentConstructor(agentClass)) return;
|
|
461
587
|
const dispatcher = Reflect.construct(agentClass, [{ allowH2: false }]);
|
|
462
588
|
return typeof Reflect.get(dispatcher, "dispatch") === "function" ? dispatcher : void 0;
|
|
463
589
|
} catch {
|
|
@@ -481,19 +607,9 @@ function isUploadRequest(request) {
|
|
|
481
607
|
}
|
|
482
608
|
//#endregion
|
|
483
609
|
//#region src/internal/http/fetch-client.ts
|
|
484
|
-
const MAX_DETAIL_LENGTH = 500;
|
|
485
610
|
const CONTENT_TYPE_HEADER = "content-type";
|
|
486
611
|
const CONNECTION_HEADER = "connection";
|
|
487
612
|
/**
|
|
488
|
-
* Converts a `Headers` object to a plain record with lowercased keys.
|
|
489
|
-
*
|
|
490
|
-
* @param headers - The `Headers` instance to convert.
|
|
491
|
-
* @returns A record mapping lowercased header names to their values.
|
|
492
|
-
*/
|
|
493
|
-
function headersToRecord(headers) {
|
|
494
|
-
return Object.fromEntries(headers);
|
|
495
|
-
}
|
|
496
|
-
/**
|
|
497
613
|
* Permissively extracts a machine-readable error code from a response body.
|
|
498
614
|
*
|
|
499
615
|
* Modern Open Cloud responses use `{ errorCode: string, message: string }`;
|
|
@@ -527,11 +643,11 @@ function extractErrorMessage(body) {
|
|
|
527
643
|
return extractLegacyMessage(body);
|
|
528
644
|
}
|
|
529
645
|
/**
|
|
530
|
-
* Parses the `x-ratelimit-reset` header value into seconds. On a 429 the
|
|
531
|
-
* is a comma-separated list of per-window reset times (e.g. `"22, 0"`,
|
|
532
|
-
* per rate-limit window); the largest value is the longest-resetting
|
|
533
|
-
* the only safe wait that won't retry into a still-exhausted
|
|
534
|
-
* value is treated as a one-element list.
|
|
646
|
+
* Parses the `x-ratelimit-reset` header value into seconds. On a 429 the
|
|
647
|
+
* header is a comma-separated list of per-window reset times (e.g. `"22, 0"`,
|
|
648
|
+
* one entry per rate-limit window); the largest value is the longest-resetting
|
|
649
|
+
* window and the only safe wait that won't retry into a still-exhausted
|
|
650
|
+
* window. A single value is treated as a one-element list.
|
|
535
651
|
*
|
|
536
652
|
* @param headerValue - The raw header value, or `undefined` if missing.
|
|
537
653
|
* @returns The number of seconds to wait, or 0 if missing/invalid.
|
|
@@ -582,8 +698,7 @@ function buildFetchOptions(request, config) {
|
|
|
582
698
|
* depend on wall-clock time or on the runtime's global dispatcher.
|
|
583
699
|
* @returns An HttpClient that classifies responses into typed Results.
|
|
584
700
|
*/
|
|
585
|
-
function createFetchHttpClient(fetchFunc =
|
|
586
|
-
const { createDispatcher = createHttp1Dispatcher, now = Date.now } = seams;
|
|
701
|
+
function createFetchHttpClient(fetchFunc = fetch, { createDispatcher = createHttp1Dispatcher, now = Date.now } = {}) {
|
|
587
702
|
const dispatcherFor = createUploadDispatcherCache(createDispatcher);
|
|
588
703
|
return { async request(httpRequest, config) {
|
|
589
704
|
const url = buildUrl(httpRequest, config);
|
|
@@ -593,7 +708,9 @@ function createFetchHttpClient(fetchFunc = globalThis.fetch, seams = {}) {
|
|
|
593
708
|
method: httpRequest.method,
|
|
594
709
|
url
|
|
595
710
|
};
|
|
596
|
-
const { elapsedMs, fetchResult } = await
|
|
711
|
+
const { elapsedMs, fetchResult } = await timedFetchAsync(now, async () => {
|
|
712
|
+
return fetchFunc(url, options);
|
|
713
|
+
});
|
|
597
714
|
if (!fetchResult.success) return {
|
|
598
715
|
err: networkError(fetchResult.err, target),
|
|
599
716
|
success: false
|
|
@@ -603,7 +720,7 @@ function createFetchHttpClient(fetchFunc = globalThis.fetch, seams = {}) {
|
|
|
603
720
|
method: target.method,
|
|
604
721
|
url: target.url
|
|
605
722
|
};
|
|
606
|
-
const classified = await
|
|
723
|
+
const classified = await tryCatchAsync(classifyResponseAsync(fetchResult.data, context));
|
|
607
724
|
if (!classified.success) return {
|
|
608
725
|
err: networkError(classified.err, target),
|
|
609
726
|
success: false
|
|
@@ -679,9 +796,9 @@ function createUploadDispatcherCache(createDispatcher) {
|
|
|
679
796
|
* @param send - A thunk that issues the fetch.
|
|
680
797
|
* @returns The fetch Result and the elapsed milliseconds.
|
|
681
798
|
*/
|
|
682
|
-
async function
|
|
799
|
+
async function timedFetchAsync(now, send) {
|
|
683
800
|
const start = now();
|
|
684
|
-
const fetchResult = await
|
|
801
|
+
const fetchResult = await tryCatchAsync(send());
|
|
685
802
|
return {
|
|
686
803
|
elapsedMs: Math.max(0, now() - start),
|
|
687
804
|
fetchResult
|
|
@@ -694,25 +811,13 @@ function networkError(cause, target) {
|
|
|
694
811
|
url: target.url
|
|
695
812
|
});
|
|
696
813
|
}
|
|
697
|
-
function formatApiErrorMessage(
|
|
698
|
-
const { code, message, status } = parts;
|
|
814
|
+
function formatApiErrorMessage({ code, message, status }) {
|
|
699
815
|
const base = `HTTP ${status}`;
|
|
700
816
|
if (message === void 0 && code === void 0) return base;
|
|
701
817
|
if (message === void 0) return `${base} (code ${code})`;
|
|
702
818
|
if (code === void 0) return `${base}: ${message}`;
|
|
703
819
|
return `${base}: ${message} (code ${code})`;
|
|
704
820
|
}
|
|
705
|
-
/**
|
|
706
|
-
* Projects a read body to the detail carried on an error: the parsed JSON when
|
|
707
|
-
* it parsed, otherwise the raw text truncated to {@link MAX_DETAIL_LENGTH}.
|
|
708
|
-
*
|
|
709
|
-
* @param text - The raw response body text.
|
|
710
|
-
* @param parsed - The best-effort parse result from {@link readResponseBody}.
|
|
711
|
-
* @returns The parsed body, or the truncated raw text on a parse failure.
|
|
712
|
-
*/
|
|
713
|
-
function bodyDetail(text, parsed) {
|
|
714
|
-
return parsed.success ? parsed.data : text.slice(0, MAX_DETAIL_LENGTH);
|
|
715
|
-
}
|
|
716
821
|
function createApiError(args) {
|
|
717
822
|
const { context, rawText, response } = args;
|
|
718
823
|
const { status } = response;
|
|
@@ -743,7 +848,8 @@ function createApiError(args) {
|
|
|
743
848
|
}
|
|
744
849
|
/**
|
|
745
850
|
* Parses response text as JSON, returning the underlying `SyntaxError` on
|
|
746
|
-
* failure rather than throwing. The synchronous sibling of {@link
|
|
851
|
+
* failure rather than throwing. The synchronous sibling of {@link
|
|
852
|
+
* tryCatchAsync}.
|
|
747
853
|
*
|
|
748
854
|
* @param text - The raw response body text.
|
|
749
855
|
* @returns A Result wrapping the parsed value, or the parse error.
|
|
@@ -771,7 +877,7 @@ function parseJson(text) {
|
|
|
771
877
|
* @param response - The Response whose body to read.
|
|
772
878
|
* @returns The parse result and the raw text.
|
|
773
879
|
*/
|
|
774
|
-
async function
|
|
880
|
+
async function readResponseBodyAsync(response) {
|
|
775
881
|
const text = await response.text();
|
|
776
882
|
return {
|
|
777
883
|
parsed: text === "" ? {
|
|
@@ -781,32 +887,19 @@ async function readResponseBody(response) {
|
|
|
781
887
|
text
|
|
782
888
|
};
|
|
783
889
|
}
|
|
784
|
-
async function
|
|
890
|
+
async function createRateLimitErrorAsync(response) {
|
|
785
891
|
const headers = headersToRecord(response.headers);
|
|
786
|
-
const { parsed, text } = await
|
|
892
|
+
const { parsed, text } = await readResponseBodyAsync(response);
|
|
787
893
|
return new RateLimitError("Rate limited", {
|
|
788
894
|
details: bodyDetail(text, parsed),
|
|
789
|
-
remaining: reduceRateLimitTokens(headers["x-ratelimit-remaining"], (a, b) =>
|
|
895
|
+
remaining: reduceRateLimitTokens(headers["x-ratelimit-remaining"], (a, b) => {
|
|
896
|
+
return Math.min(a, b);
|
|
897
|
+
}),
|
|
790
898
|
retryAfterSeconds: parseRetryAfterSeconds(headers["x-ratelimit-reset"]),
|
|
791
899
|
statusCode: response.status
|
|
792
900
|
});
|
|
793
901
|
}
|
|
794
902
|
/**
|
|
795
|
-
* Builds the error for a 2xx response whose body could not be parsed as JSON,
|
|
796
|
-
* preserving the parse `cause`, the (truncated) raw body, and the declared
|
|
797
|
-
* content-type so the failure can be diagnosed after the fact.
|
|
798
|
-
*
|
|
799
|
-
* @param args - The Response, raw body text, and underlying parse error.
|
|
800
|
-
* @returns An ApiError carrying the diagnostic context.
|
|
801
|
-
*/
|
|
802
|
-
function parseFailureError({ cause, response, text }) {
|
|
803
|
-
return new ApiError(`Failed to parse response body (content-type: ${response.headers.get(CONTENT_TYPE_HEADER) ?? "unknown"})`, {
|
|
804
|
-
cause,
|
|
805
|
-
details: text.slice(0, MAX_DETAIL_LENGTH),
|
|
806
|
-
statusCode: response.status
|
|
807
|
-
});
|
|
808
|
-
}
|
|
809
|
-
/**
|
|
810
903
|
* Classifies a fetch `Response` into a typed `Result`.
|
|
811
904
|
*
|
|
812
905
|
* The body is read once and parsed best-effort. Error responses (status >= 300)
|
|
@@ -817,15 +910,16 @@ function parseFailureError({ cause, response, text }) {
|
|
|
817
910
|
*
|
|
818
911
|
* @param response - The raw fetch Response to classify.
|
|
819
912
|
* @param context - The request context (method, url, elapsed time) threaded
|
|
820
|
-
* onto
|
|
913
|
+
* onto every {@link ApiError} built here, whether for an error response or
|
|
914
|
+
* for a 2xx whose body would not parse.
|
|
821
915
|
* @returns A Result containing an HttpResponse on success or an OpenCloudError on failure.
|
|
822
916
|
*/
|
|
823
|
-
async function
|
|
917
|
+
async function classifyResponseAsync(response, context) {
|
|
824
918
|
if (response.status === 429) return {
|
|
825
|
-
err: await
|
|
919
|
+
err: await createRateLimitErrorAsync(response),
|
|
826
920
|
success: false
|
|
827
921
|
};
|
|
828
|
-
const { parsed, text } = await
|
|
922
|
+
const { parsed, text } = await readResponseBodyAsync(response);
|
|
829
923
|
if (response.status >= 300) return {
|
|
830
924
|
err: createApiError({
|
|
831
925
|
context,
|
|
@@ -838,6 +932,7 @@ async function classifyResponse(response, context) {
|
|
|
838
932
|
if (!parsed.success) return {
|
|
839
933
|
err: parseFailureError({
|
|
840
934
|
cause: parsed.err,
|
|
935
|
+
context,
|
|
841
936
|
response,
|
|
842
937
|
text
|
|
843
938
|
}),
|
|
@@ -915,7 +1010,7 @@ const CLIENT_DEFAULTS = Object.freeze({
|
|
|
915
1010
|
* the frozen client config, observability hooks, injected HTTP client and
|
|
916
1011
|
* sleep, and the per-effective-key rate-limit queue registry. Resource
|
|
917
1012
|
* classes compose one instance and dispatch every public method through
|
|
918
|
-
* {@link ResourceClient.
|
|
1013
|
+
* {@link ResourceClient.executeAsync} with a per-method {@link ResourceMethodSpec}.
|
|
919
1014
|
* Not exported from any package subpath; reachable only via sibling
|
|
920
1015
|
* `src/resources/**` modules in this package.
|
|
921
1016
|
*/
|
|
@@ -934,8 +1029,7 @@ var ResourceClient = class {
|
|
|
934
1029
|
* @param options - Client-level configuration including the API key
|
|
935
1030
|
* and optional construction-time test seams.
|
|
936
1031
|
*/
|
|
937
|
-
constructor(
|
|
938
|
-
const { apiKey, hooks, httpClient, sleep, ...overrides } = options;
|
|
1032
|
+
constructor({ apiKey, hooks, httpClient, sleep, ...overrides }) {
|
|
939
1033
|
const resolved = resolveDependencies({
|
|
940
1034
|
httpClient,
|
|
941
1035
|
sleep
|
|
@@ -962,8 +1056,7 @@ var ResourceClient = class {
|
|
|
962
1056
|
* @returns The parsed success payload or the {@link OpenCloudError} that
|
|
963
1057
|
* caused the request to fail. Never throws.
|
|
964
1058
|
*/
|
|
965
|
-
async
|
|
966
|
-
const { options, parameters, spec } = call;
|
|
1059
|
+
async executeAsync({ options, parameters, spec }) {
|
|
967
1060
|
const merged = mergeConfig(this.#config, {
|
|
968
1061
|
methodDefaults: spec.methodDefaults,
|
|
969
1062
|
methodKind: spec.methodKind,
|
|
@@ -976,8 +1069,8 @@ var ResourceClient = class {
|
|
|
976
1069
|
options,
|
|
977
1070
|
request: requestResult.data
|
|
978
1071
|
});
|
|
979
|
-
const httpResult = await this.#getQueue(merged.apiKey, spec.operationLimit).
|
|
980
|
-
return
|
|
1072
|
+
const httpResult = await this.#getQueue(merged.apiKey, spec.operationLimit).acquireAsync(async () => {
|
|
1073
|
+
return executeWithRetryAsync(requestResult.data, {
|
|
981
1074
|
config: merged,
|
|
982
1075
|
hooks: this.#hooks,
|
|
983
1076
|
send: this.#gatedSend(merged.apiKey, requestConfig),
|
|
@@ -1006,11 +1099,11 @@ var ResourceClient = class {
|
|
|
1006
1099
|
*
|
|
1007
1100
|
* @param apiKey - The effective API key to gate on.
|
|
1008
1101
|
* @param requestConfig - The resolved per-request transport config.
|
|
1009
|
-
* @returns A send callback for {@link
|
|
1102
|
+
* @returns A send callback for {@link executeWithRetryAsync}.
|
|
1010
1103
|
*/
|
|
1011
1104
|
#gatedSend(apiKey, requestConfig) {
|
|
1012
1105
|
return async (toSend) => {
|
|
1013
|
-
await this.#budgets.
|
|
1106
|
+
await this.#budgets.gateAsync(apiKey);
|
|
1014
1107
|
const sendResult = await this.#httpClient.request(toSend, requestConfig);
|
|
1015
1108
|
this.#budgets.observe(apiKey, rateLimitSampleFromResult(sendResult));
|
|
1016
1109
|
return sendResult;
|
|
@@ -1036,8 +1129,7 @@ var ResourceClient = class {
|
|
|
1036
1129
|
* @returns The config to hand to the transport, with `timeout` omitted when
|
|
1037
1130
|
* no client-side deadline should apply.
|
|
1038
1131
|
*/
|
|
1039
|
-
function buildRequestConfig(
|
|
1040
|
-
const { merged, options, request } = inputs;
|
|
1132
|
+
function buildRequestConfig({ merged, options, request }) {
|
|
1041
1133
|
const shouldOmitDefaultTimeout = options?.timeout === void 0 && isUploadRequest(request);
|
|
1042
1134
|
return {
|
|
1043
1135
|
apiKey: merged.apiKey,
|
|
@@ -1060,6 +1152,6 @@ function enrichPermissionError(err, spec) {
|
|
|
1060
1152
|
});
|
|
1061
1153
|
}
|
|
1062
1154
|
//#endregion
|
|
1063
|
-
export {
|
|
1155
|
+
export { isRecord as a, toJsonDetails as i, okRequest as n, isDateTimeString as o, parseEmptyResponse as r, ResourceClient as t };
|
|
1064
1156
|
|
|
1065
|
-
//# sourceMappingURL=resource-client-
|
|
1157
|
+
//# sourceMappingURL=resource-client-6KaHBVI7.mjs.map
|