@bedrock-rbx/ocale 0.3.4 → 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.
Files changed (85) hide show
  1. package/README.md +9 -5
  2. package/dist/badge-cost-mismatch-DrlvhlQc.mjs +47 -0
  3. package/dist/badge-cost-mismatch-DrlvhlQc.mjs.map +1 -0
  4. package/dist/badges.d.mts +228 -184
  5. package/dist/badges.d.mts.map +1 -1
  6. package/dist/badges.mjs +176 -18
  7. package/dist/badges.mjs.map +1 -1
  8. package/dist/capacity-admission-hycCFkTo.d.mts +355 -0
  9. package/dist/capacity-admission-hycCFkTo.d.mts.map +1 -0
  10. package/dist/{data.generated-B2ceLfSn.d.mts → data.generated-D_vpa5-g.d.mts} +23 -23
  11. package/dist/data.generated-D_vpa5-g.d.mts.map +1 -0
  12. package/dist/developer-products.d.mts +181 -186
  13. package/dist/developer-products.d.mts.map +1 -1
  14. package/dist/developer-products.mjs +24 -24
  15. package/dist/developer-products.mjs.map +1 -1
  16. package/dist/game-passes.d.mts +206 -203
  17. package/dist/game-passes.d.mts.map +1 -1
  18. package/dist/game-passes.mjs +26 -21
  19. package/dist/game-passes.mjs.map +1 -1
  20. package/dist/index.d.mts +905 -343
  21. package/dist/index.d.mts.map +1 -1
  22. package/dist/index.mjs +325 -10
  23. package/dist/index.mjs.map +1 -1
  24. package/dist/locales.d.mts +30 -2
  25. package/dist/locales.d.mts.map +1 -0
  26. package/dist/locales.mjs +24 -1
  27. package/dist/locales.mjs.map +1 -1
  28. package/dist/luau-execution.d.mts +154 -151
  29. package/dist/luau-execution.d.mts.map +1 -1
  30. package/dist/luau-execution.mjs +11 -8
  31. package/dist/luau-execution.mjs.map +1 -1
  32. package/dist/{network-error-DR9FX5hb.mjs → network-error-iVSng5MT.mjs} +44 -6
  33. package/dist/network-error-iVSng5MT.mjs.map +1 -0
  34. package/dist/places.d.mts +204 -180
  35. package/dist/places.d.mts.map +1 -1
  36. package/dist/places.mjs +66 -20
  37. package/dist/places.mjs.map +1 -1
  38. package/dist/{poll-timeout-3PXLsabj.mjs → poll-timeout-DzztDymd.mjs} +2 -2
  39. package/dist/{poll-timeout-3PXLsabj.mjs.map → poll-timeout-DzztDymd.mjs.map} +1 -1
  40. package/dist/{polling-helpers-CoVhsC33.mjs → polling-helpers-DfF5dspc.mjs} +249 -83
  41. package/dist/polling-helpers-DfF5dspc.mjs.map +1 -0
  42. package/dist/{price-information-B0tkOoAX.mjs → price-information-DEkEQ8Pq.mjs} +2 -2
  43. package/dist/{price-information-B0tkOoAX.mjs.map → price-information-DEkEQ8Pq.mjs.map} +1 -1
  44. package/dist/resource-client-BCKukheG.d.mts +168 -0
  45. package/dist/resource-client-BCKukheG.d.mts.map +1 -0
  46. package/dist/{resource-client-rqTMkBeR.mjs → resource-client-CaIVr-go.mjs} +586 -158
  47. package/dist/resource-client-CaIVr-go.mjs.map +1 -0
  48. package/dist/retry-C2oHesDx.d.mts +229 -0
  49. package/dist/retry-C2oHesDx.d.mts.map +1 -0
  50. package/dist/{retry-BlX4tUnT.mjs → retry-CMRDvAR4.mjs} +278 -18
  51. package/dist/retry-CMRDvAR4.mjs.map +1 -0
  52. package/dist/storage.d.mts +333 -334
  53. package/dist/storage.d.mts.map +1 -1
  54. package/dist/storage.mjs +29 -22
  55. package/dist/storage.mjs.map +1 -1
  56. package/dist/testing.d.mts +347 -360
  57. package/dist/testing.d.mts.map +1 -1
  58. package/dist/testing.mjs +3 -4
  59. package/dist/testing.mjs.map +1 -1
  60. package/dist/types-CdMr_J1M.d.mts +509 -0
  61. package/dist/types-CdMr_J1M.d.mts.map +1 -0
  62. package/dist/universes.d.mts +619 -422
  63. package/dist/universes.d.mts.map +1 -1
  64. package/dist/universes.mjs +421 -48
  65. package/dist/universes.mjs.map +1 -1
  66. package/dist/{validation-B_Zs1So2.mjs → validation-964VNlbp.mjs} +2 -2
  67. package/dist/{validation-B_Zs1So2.mjs.map → validation-964VNlbp.mjs.map} +1 -1
  68. package/dist/wire-DJqupefn.d.mts +41 -0
  69. package/dist/wire-DJqupefn.d.mts.map +1 -0
  70. package/package.json +14 -14
  71. package/dist/capacity-admission-IDO3fcUC.d.mts +0 -369
  72. package/dist/capacity-admission-IDO3fcUC.d.mts.map +0 -1
  73. package/dist/data.generated-B2ceLfSn.d.mts.map +0 -1
  74. package/dist/network-error-DR9FX5hb.mjs.map +0 -1
  75. package/dist/polling-helpers-CoVhsC33.mjs.map +0 -1
  76. package/dist/resource-client-B6NeFXUv.d.mts +0 -164
  77. package/dist/resource-client-B6NeFXUv.d.mts.map +0 -1
  78. package/dist/resource-client-rqTMkBeR.mjs.map +0 -1
  79. package/dist/retry-BlX4tUnT.mjs.map +0 -1
  80. package/dist/retry-war_-9tb.d.mts +0 -373
  81. package/dist/retry-war_-9tb.d.mts.map +0 -1
  82. package/dist/types-CvYh4SPC.d.mts +0 -386
  83. package/dist/types-CvYh4SPC.d.mts.map +0 -1
  84. package/dist/wire-D3K-a-UP.d.mts +0 -37
  85. package/dist/wire-D3K-a-UP.d.mts.map +0 -1
@@ -1,5 +1,5 @@
1
- import { a as ApiError, n as RateLimitError, o as requestContextOf, r as hasServerRetryGuidance } from "./network-error-DR9FX5hb.mjs";
2
- import { C as parseRateLimitHeaders, S as RequestAbortedError, _ as createFetchHttpClient, b as raceWithAbortAsync, c as defaultRetryDelay, d as shouldRetry, g as PermissionError, h as RateLimitWaitRefusedError, l as hasGuidedWait, m as RequestDeadlineExceededError, p as RetryDelayExceededError, r as IDEMPOTENT_METHOD_DEFAULTS, s as computeRetryWaitMs, u as mergeConfig, v as isUploadRequest, w as withReportedWindow, x as requestAbortedError, y as ABORTED } from "./retry-BlX4tUnT.mjs";
1
+ import { a as ApiError, c as recordPreviousAttempts, n as RateLimitError, o as requestContextOf, r as hasServerRetryGuidance } from "./network-error-iVSng5MT.mjs";
2
+ import { A as withReportedWindow, C as isUploadRequest, D as RequestAbortedError, E as requestAbortedError, M as extractErrorMessage, N as pickDiagnosticHeaders, S as createFetchHttpClient, T as raceWithAbortAsync, _ as RateLimitWaitRefusedError, b as CredentialNotSupportedError, c as defaultRetryDelay, d as mergeConfig, f as shouldRetry, g as RequestDeadlineExceededError, h as RetryDelayExceededError, j as isRecord, k as parseRateLimitHeaders, l as hasGuidedWait, m as UnexpectedResponseError, r as IDEMPOTENT_METHOD_DEFAULTS, s as computeRetryWaitMs, u as isRefusedGuidedWait, v as PermissionError, w as ABORTED, x as CredentialError, y as CredentialRejectedError } from "./retry-CMRDvAR4.mjs";
3
3
  import { setTimeout } from "node:timers/promises";
4
4
  //#region src/internal/utils/is-date-time-string.ts
5
5
  /**
@@ -18,20 +18,6 @@ function isDateTimeString(value) {
18
18
  return !Number.isNaN(parsed.getTime());
19
19
  }
20
20
  //#endregion
21
- //#region src/internal/utils/is-record.ts
22
- /**
23
- * Narrows `value` to a plain JSON-style record. Excludes arrays, class
24
- * instances, primitives, and `null`/`undefined`. Used by resource
25
- * parsers to gate property access on wire bodies whose shape isn't
26
- * known at compile time.
27
- *
28
- * @param value - The unknown value to narrow.
29
- * @returns `true` when `value` is a plain `[object Object]`.
30
- */
31
- function isRecord(value) {
32
- return Object.prototype.toString.call(value) === "[object Object]";
33
- }
34
- //#endregion
35
21
  //#region src/internal/utils/to-json-details.ts
36
22
  /**
37
23
  * Narrows an untyped response body to the `JSONValue` accepted by
@@ -78,6 +64,57 @@ function asJsonObject(value, seen) {
78
64
  return Object.fromEntries(entries);
79
65
  }
80
66
  //#endregion
67
+ //#region src/internal/api-key-only.ts
68
+ /**
69
+ * Fails an OAuth call to an Operation that Roblox accepts only with an API
70
+ * key. Runs before the provider is asked for a token and before any request.
71
+ *
72
+ * @param spec - The method spec's flag and operation limit.
73
+ * @param credential - The effective credential for the call.
74
+ * @returns A {@link CredentialNotSupportedError} failure, or `undefined` when
75
+ * the call may proceed.
76
+ */
77
+ function credentialNotSupportedFailure(spec, credential) {
78
+ if (spec.apiKeyOnly !== true || credential.kind !== "oauth") return;
79
+ const { operationKey } = spec.operationLimit;
80
+ return {
81
+ err: new CredentialNotSupportedError(`Operation ${operationKey} accepts only an API key credential`, { operationKey }),
82
+ success: false
83
+ };
84
+ }
85
+ //#endregion
86
+ //#region src/internal/credential-snapshot.ts
87
+ /**
88
+ * Copies a caller's credential, so a later change to the caller's object
89
+ * cannot change the key or the OAuth identity a client or a queued request
90
+ * uses. An OAuth provider stays a call on the caller's object, so a class
91
+ * method keeps its `this`.
92
+ *
93
+ * @param credential - The caller's credential.
94
+ * @returns A copy the caller does not hold.
95
+ */
96
+ function snapshotCredential(credential) {
97
+ if (credential.kind !== "oauth") return { ...credential };
98
+ return {
99
+ getAccessToken: async (context) => credential.getAccessToken(context),
100
+ identity: credential.identity,
101
+ kind: "oauth"
102
+ };
103
+ }
104
+ /**
105
+ * Copies the credential of a per-request override, if it has one.
106
+ *
107
+ * @template T - The override shape.
108
+ * @param options - The caller's per-request overrides.
109
+ * @returns The overrides, with a credential the caller does not hold.
110
+ */
111
+ function withCredentialSnapshot(options) {
112
+ return options.credential === void 0 ? options : {
113
+ ...options,
114
+ credential: snapshotCredential(options.credential)
115
+ };
116
+ }
117
+ //#endregion
81
118
  //#region src/internal/http/admission-wait.ts
82
119
  /**
83
120
  * Performs one SDK-managed wait and emits a balanced request-scoped lifecycle.
@@ -114,7 +151,7 @@ function notify(observer, event) {
114
151
  }
115
152
  //#endregion
116
153
  //#region src/internal/http/budget-tracker.ts
117
- const MS_PER_SECOND = 1e3;
154
+ const MS_PER_SECOND$1 = 1e3;
118
155
  /**
119
156
  * Tracks the live rate-limit budget for a single scope. Primed by `observe`
120
157
  * from response headers and drawn down by `reserve` as requests leave, so
@@ -136,10 +173,17 @@ const MS_PER_SECOND = 1e3;
136
173
  var BudgetTracker = class {
137
174
  /** Time (ms) the most recent request was allowed out, for spacing. */
138
175
  #lastAllowedAt = void 0;
176
+ /** Token of the latest reservation, compared by identity. */
177
+ #latestReservation = void 0;
139
178
  /** Requests the server grants per window, used when a window rolls over. */
140
179
  #rolloverWindow;
141
180
  #window = void 0;
142
181
  /**
182
+ * Token of the window in force, compared by identity. A new window gets a
183
+ * new token, so a release can tell its window is gone.
184
+ */
185
+ #windowToken = {};
186
+ /**
143
187
  * Creates a tracker for one scope.
144
188
  *
145
189
  * @param documentedWindow - The operation's documented capacity, used
@@ -159,9 +203,10 @@ var BudgetTracker = class {
159
203
  */
160
204
  observe(sample, now) {
161
205
  this.#rolloverWindow = sample.window ?? this.#rolloverWindow;
206
+ this.#windowToken = {};
162
207
  this.#window = {
163
208
  predictedRemaining: sample.remaining,
164
- resetAt: now + sample.resetSeconds * MS_PER_SECOND
209
+ resetAt: now + sample.resetSeconds * MS_PER_SECOND$1
165
210
  };
166
211
  }
167
212
  /**
@@ -169,14 +214,29 @@ var BudgetTracker = class {
169
214
  * and decrements the prediction. A no-op on the prediction while unprimed.
170
215
  *
171
216
  * @param now - The time the request was allowed out, in ms.
217
+ * @returns The reservation, to release if the request is not sent.
172
218
  */
173
219
  reserve(now) {
220
+ const previousAllowedAt = this.#lastAllowedAt;
174
221
  this.#lastAllowedAt = now;
222
+ const reservation = {};
223
+ this.#latestReservation = reservation;
175
224
  const window = this.#windowAt(now);
176
225
  if (window !== void 0) this.#window = {
177
226
  ...window,
178
227
  predictedRemaining: window.predictedRemaining - 1
179
228
  };
229
+ const windowToken = this.#windowToken;
230
+ let isReleased = false;
231
+ return { release: () => {
232
+ if (isReleased) return;
233
+ isReleased = true;
234
+ this.#release({
235
+ previousAllowedAt,
236
+ reservation,
237
+ windowToken
238
+ });
239
+ } };
180
240
  }
181
241
  /**
182
242
  * Milliseconds to wait before the next request is allowed.
@@ -195,6 +255,13 @@ var BudgetTracker = class {
195
255
  const interval = window.spacingMs ?? (resetAt - now) / predictedRemaining;
196
256
  return Math.max(0, this.#lastAllowedAt + interval - now);
197
257
  }
258
+ #release({ previousAllowedAt, reservation, windowToken }) {
259
+ if (reservation === this.#latestReservation) this.#lastAllowedAt = previousAllowedAt;
260
+ if (this.#window !== void 0 && windowToken === this.#windowToken) this.#window = {
261
+ ...this.#window,
262
+ predictedRemaining: this.#window.predictedRemaining + 1
263
+ };
264
+ }
198
265
  /**
199
266
  * The window in force at `now`, opening the next one at full capacity once
200
267
  * the current window's reset has passed.
@@ -205,7 +272,8 @@ var BudgetTracker = class {
205
272
  #windowAt(now) {
206
273
  if (this.#window !== void 0 && now >= this.#window.resetAt) {
207
274
  const { capacity, windowSeconds } = this.#rolloverWindow;
208
- const windowMs = windowSeconds * MS_PER_SECOND;
275
+ const windowMs = windowSeconds * MS_PER_SECOND$1;
276
+ this.#windowToken = {};
209
277
  this.#window = {
210
278
  predictedRemaining: capacity,
211
279
  resetAt: now + windowMs,
@@ -218,6 +286,7 @@ var BudgetTracker = class {
218
286
  //#endregion
219
287
  //#region src/internal/http/request-deadline.ts
220
288
  const DEADLINE_ELAPSED = Symbol("request deadline elapsed");
289
+ /** The longest delay a timer accepts; `AbortSignal.timeout` throws above it. */
221
290
  const MAX_ABORT_TIMEOUT_MS = 2147483647;
222
291
  /**
223
292
  * Resolves one signal that spans the whole logical request.
@@ -243,24 +312,27 @@ function requestLifecycle(deadlineMs, callerSignal) {
243
312
  * Returns a typed failure when the deadline signal ended the request.
244
313
  *
245
314
  * @param lifecycle - Signals and timestamp for the logical request.
315
+ * @param cause - The failure the deadline failure replaces, if any.
246
316
  * @returns A deadline failure, or `undefined` when another signal won.
247
317
  */
248
- function elapsedDeadlineFailure({ deadlineMs, deadlineSignal, signal }) {
318
+ function elapsedDeadlineFailure({ deadlineMs, deadlineSignal, signal }, cause) {
249
319
  if (deadlineMs === void 0 || deadlineSignal?.aborted !== true || !Object.is(signal?.reason, deadlineSignal.reason)) return;
250
320
  return new RequestDeadlineExceededError("Request deadline elapsed", {
321
+ cause,
251
322
  deadlineMs,
252
323
  remainingMs: 0
253
324
  });
254
325
  }
255
326
  /**
256
327
  * Reclassifies an internal abort when the request deadline supplied its signal.
328
+ * The abort becomes the deadline failure's `cause`.
257
329
  *
258
330
  * @param error - Error returned by the request pipeline.
259
331
  * @param lifecycle - Signals and timestamp for the logical request.
260
332
  * @returns A deadline failure, or `undefined` for other failures.
261
333
  */
262
334
  function deadlineFailureFromError(error, lifecycle) {
263
- return error instanceof RequestAbortedError ? elapsedDeadlineFailure(lifecycle) : void 0;
335
+ return error instanceof RequestAbortedError ? elapsedDeadlineFailure(lifecycle, error) : void 0;
264
336
  }
265
337
  /**
266
338
  * Refuses a known admission wait that cannot fit before the deadline.
@@ -304,6 +376,7 @@ function waitMessage(waitMs, remainingMs) {
304
376
  //#endregion
305
377
  //#region src/internal/http/budget-gate.ts
306
378
  const REPORTED_BUDGET_REASON = "reported-budget";
379
+ const MS_PER_SECOND = 1e3;
307
380
  /**
308
381
  * Header-primed rate-limit gate shared across a client. Holds one
309
382
  * {@link BudgetTracker} per {@link BudgetScope}. Before each request the caller
@@ -318,6 +391,7 @@ const REPORTED_BUDGET_REASON = "reported-budget";
318
391
  */
319
392
  var BudgetGate = class {
320
393
  #chains = /* @__PURE__ */ new Map();
394
+ #lockouts = /* @__PURE__ */ new Map();
321
395
  #pendingGates = /* @__PURE__ */ new Map();
322
396
  #sleep;
323
397
  #trackers = /* @__PURE__ */ new Map();
@@ -335,18 +409,19 @@ var BudgetGate = class {
335
409
  * or rejected, so one failed attempt cannot poison later gates on the
336
410
  * scope.
337
411
  *
338
- * @param scope - The API key and operation to gate on.
412
+ * @param scope - The credential and operation to gate on.
339
413
  * @param context - Request-local observer and cancellation signal.
414
+ * @returns The reserved slot. Release it when the request is not sent.
340
415
  * @rejects {@link RequestAbortedError} when the caller cancels while waiting.
416
+ * @rejects {@link RateLimitWaitRefusedError} while the scope is locked out.
341
417
  */
342
418
  async gateAsync(scope, { deadlineMs, observer, signal } = {}) {
343
419
  const key = scopeKey(scope);
344
- const tracker = this.#tracker(key, scope.documentedWindow);
345
420
  const pendingGates = this.#pendingGates.get(key) ?? 0;
346
421
  const waitsForEarlierGate = pendingGates > 0;
347
422
  this.#pendingGates.set(key, pendingGates + 1);
348
423
  const completed = (this.#chains.get(key) ?? Promise.resolve()).catch(ignoreRejection$1).then(async () => {
349
- return this.#gateOnce(tracker, {
424
+ return this.#gateOnce(scope, {
350
425
  deadlineMs,
351
426
  observer: waitsForEarlierGate ? void 0 : observer,
352
427
  signal
@@ -355,13 +430,27 @@ var BudgetGate = class {
355
430
  const remainingGates = (this.#pendingGates.get(key) ?? 1) - 1;
356
431
  this.#pendingGates.set(key, remainingGates);
357
432
  });
358
- this.#chains.set(key, completed.catch(ignoreRejection$1));
359
- if (waitsForEarlierGate) await observeAdmissionWaitAsync({
433
+ this.#chains.set(key, completed.then(ignoreRejection$1).catch(ignoreRejection$1));
434
+ if (waitsForEarlierGate) return observeAdmissionWaitAsync({
360
435
  observer,
361
436
  reason: REPORTED_BUDGET_REASON,
362
437
  waitAsync: async () => waitForGateAsync(completed, signal)
363
438
  });
364
- else await waitForGateAsync(completed, signal);
439
+ return waitForGateAsync(completed, signal);
440
+ }
441
+ /**
442
+ * Locks the scope out until the refused 429's guided wait ends. Until then
443
+ * every gate on the scope is refused at once, without sleeping or
444
+ * reserving budget. The latest lockout replaces any earlier one.
445
+ *
446
+ * @param scope - The same scope passed to {@link gateAsync}.
447
+ * @param cause - The 429 whose guided wait was too long to take.
448
+ */
449
+ lockOut(scope, cause) {
450
+ this.#lockouts.set(scopeKey(scope), {
451
+ cause,
452
+ resetAt: Date.now() + cause.retryAfterSeconds * MS_PER_SECOND
453
+ });
365
454
  }
366
455
  /**
367
456
  * Folds a response's parsed budget back onto the scope. A `undefined`
@@ -375,15 +464,55 @@ var BudgetGate = class {
375
464
  if (sample === void 0) return;
376
465
  this.#tracker(scopeKey(scope), scope.documentedWindow).observe(sample, Date.now());
377
466
  }
378
- async #gateOnce(tracker, { deadlineMs, observer, signal }) {
467
+ /**
468
+ * Refuses a request at once while its scope is locked out, so it fails
469
+ * before taking a static queue slot or waiting on anything.
470
+ *
471
+ * @param scope - The same scope passed to {@link gateAsync}.
472
+ * @throws {@link RateLimitWaitRefusedError} While the scope is locked out.
473
+ */
474
+ refuseDuringLockout(scope) {
475
+ this.#refuseDuringLockout(scopeKey(scope));
476
+ }
477
+ /**
478
+ * Swaps a request's result for the lockout refusal while its scope is
479
+ * locked out, for a lockout that began after the request passed its gate.
480
+ *
481
+ * @param scope - The same scope passed to {@link gateAsync}.
482
+ * @param result - The request's result so far.
483
+ * @returns The refusal while the scope is locked out, else `result`.
484
+ */
485
+ refuseIfLockedOut(scope, result) {
486
+ const refusal = this.#lockoutRefusal(scopeKey(scope));
487
+ return refusal === void 0 ? result : {
488
+ err: refusal,
489
+ success: false
490
+ };
491
+ }
492
+ async #gateOnce(scope, { deadlineMs, observer, signal }) {
379
493
  if (signal?.aborted === true) throw requestAbortedError(signal);
494
+ const key = scopeKey(scope);
495
+ const tracker = this.#tracker(key, scope.documentedWindow);
496
+ this.#refuseDuringLockout(key);
380
497
  const waitMs = tracker.waitMs(Date.now());
381
- if (waitMs > 0) await this.#waitAsync(waitMs, {
382
- deadlineMs,
383
- observer,
384
- signal
385
- });
386
- tracker.reserve(Date.now());
498
+ if (waitMs > 0) {
499
+ await this.#waitAsync(waitMs, {
500
+ deadlineMs,
501
+ observer,
502
+ signal
503
+ });
504
+ this.#refuseDuringLockout(key);
505
+ }
506
+ return tracker.reserve(Date.now());
507
+ }
508
+ #lockoutRefusal(key) {
509
+ const lockout = this.#lockouts.get(key);
510
+ const now = Date.now();
511
+ return lockout !== void 0 && now < lockout.resetAt ? lockoutRefusal(lockout, now) : void 0;
512
+ }
513
+ #refuseDuringLockout(key) {
514
+ const refusal = this.#lockoutRefusal(key);
515
+ if (refusal !== void 0) throw refusal;
387
516
  }
388
517
  #tracker(key, documentedWindow) {
389
518
  const existing = this.#trackers.get(key);
@@ -409,18 +538,93 @@ var BudgetGate = class {
409
538
  });
410
539
  }
411
540
  };
541
+ /**
542
+ * Composes the map key one credential and operation are tracked under. The
543
+ * budget gate and the rate-limit queues share it.
544
+ *
545
+ * @param scope - The credential key and operation naming the window.
546
+ * @returns The key for the tracker, chain and queue maps.
547
+ */
548
+ function scopeKey({ credentialKey, operationKey }) {
549
+ return `${credentialKey}::${operationKey}`;
550
+ }
551
+ function lockoutRefusal({ cause, resetAt }, now) {
552
+ const secondsLeft = Math.ceil((resetAt - now) / MS_PER_SECOND);
553
+ const remainingLockout = new RateLimitError(cause.message, {
554
+ cause,
555
+ code: cause.code,
556
+ details: cause.details,
557
+ remaining: cause.remaining,
558
+ responseHeaders: cause.responseHeaders,
559
+ retryAfterSeconds: secondsLeft,
560
+ source: cause.source,
561
+ statusCode: cause.statusCode
562
+ });
563
+ return new RateLimitWaitRefusedError(`Rate limit lockout on this operation lasts another ${secondsLeft}s; request not sent`, { cause: remainingLockout });
564
+ }
412
565
  function ignoreRejection$1() {}
413
566
  async function waitForGateAsync(gate, signal) {
414
- if (await raceWithAbortAsync(async () => gate, signal) === ABORTED) throw requestAbortedError(signal);
567
+ const gateResult = await raceWithAbortAsync(async () => gate, signal);
568
+ if (gateResult === ABORTED) throw requestAbortedError(signal);
569
+ return gateResult;
415
570
  }
571
+ //#endregion
572
+ //#region src/internal/http/credential-rejection.ts
573
+ /** The v1 body message Roblox sends on a 502 after an app removal. */
574
+ const SCOPE_AUTHORIZATION_FAILED = "Scope authorization failed.";
575
+ const OAUTH_PERMISSION_HINT = "The OAuth grant may not include the required scope or this universe.";
416
576
  /**
417
- * Composes the map key one budget window is tracked under.
577
+ * Turns Roblox's refusal of an OAuth token into a
578
+ * {@link CredentialRejectedError}: a non-gateway 401, or a non-gateway 502
579
+ * whose body message is "Scope authorization failed.". The result is not an
580
+ * `ApiError`, so the retry loop never retries it. Every other error, and
581
+ * every error on an API-key credential, passes through unchanged.
418
582
  *
419
- * @param scope - The API key and operation naming the window.
420
- * @returns The key for the tracker and chain maps.
583
+ * @param err - The transport error for one attempt.
584
+ * @param credential - The effective credential of the call.
585
+ * @returns The classified error.
421
586
  */
422
- function scopeKey({ apiKey, operationKey }) {
423
- return `${apiKey}::${operationKey}`;
587
+ function classifyCredentialRejection(err, credential) {
588
+ if (credential.kind !== "oauth" || !isTokenRefusal(err)) return err;
589
+ return new CredentialRejectedError(err.message, {
590
+ cause: err,
591
+ code: err.code,
592
+ identity: credential.identity,
593
+ statusCode: err.statusCode
594
+ });
595
+ }
596
+ /**
597
+ * Upgrades a non-gateway 401 or 403 `ApiError` to a {@link PermissionError}
598
+ * when the method declares its scopes. On an OAuth credential the message
599
+ * adds a hint that the grant may not include the scope or this universe.
600
+ *
601
+ * @param err - The final error of the call.
602
+ * @param context - The credential, operation key and declared scopes.
603
+ * @returns The upgraded error, or `err` unchanged.
604
+ */
605
+ function enrichPermissionError(err, { credential, operationKey, requiredScopes }) {
606
+ if (requiredScopes === void 0) return err;
607
+ if (err instanceof PermissionError) return err;
608
+ if (!(err instanceof ApiError)) return err;
609
+ if (err.statusCode !== 401 && err.statusCode !== 403) return err;
610
+ if (err.gatewaySummary !== void 0) return err;
611
+ return new PermissionError(permissionMessage(err.message, credential), {
612
+ ...requestContextOf(err),
613
+ cause: err.cause,
614
+ code: err.code,
615
+ details: err.details,
616
+ operationKey,
617
+ requiredScopes,
618
+ statusCode: err.statusCode
619
+ });
620
+ }
621
+ function isTokenRefusal(err) {
622
+ if (!(err instanceof ApiError) || err.gatewaySummary !== void 0) return false;
623
+ return err.statusCode === 401 || err.statusCode === 502 && extractErrorMessage(err.details) === SCOPE_AUTHORIZATION_FAILED;
624
+ }
625
+ function permissionMessage(message, credential) {
626
+ if (credential.kind !== "oauth") return message;
627
+ return `${message}${message.endsWith(".") ? " " : ". "}${OAUTH_PERMISSION_HINT}`;
424
628
  }
425
629
  //#endregion
426
630
  //#region src/internal/http/execute.ts
@@ -441,31 +645,35 @@ async function executeWithRetryAsync(request, options) {
441
645
  if (signal?.aborted === true) return abortedResult(signal);
442
646
  let result = await attemptAsync(request, options);
443
647
  let retries = 0;
444
- let waits = 0;
648
+ let earlier = [];
445
649
  while (!result.success) {
446
- const plan = planRetry(result.err, {
650
+ const failure = result.err;
651
+ const plan = planRetry(failure, {
447
652
  config,
448
653
  deadlineMs,
449
654
  retries
450
655
  });
451
- if (plan === void 0) return result;
452
- if ("refusal" in plan) return {
453
- err: plan.refusal,
454
- success: false
455
- };
656
+ if (plan === void 0) return failed(failure, earlier);
657
+ if ("refusal" in plan) return failed(plan.refusal, earlier);
456
658
  retries += plan.spendsAttempt ? 1 : 0;
457
- waits += 1;
659
+ earlier = [...earlier, failure];
458
660
  announceRetry({
459
- attempt: waits,
460
- error: result.err,
661
+ attempt: earlier.length,
662
+ error: failure,
461
663
  hooks,
462
664
  waitMs: plan.waitMs
463
665
  });
464
- if (await waitForRetryAsync(plan.waitMs, options) === ABORTED) return abortedResult(signal);
666
+ if (await waitForRetryAsync(plan.waitMs, options) === ABORTED) return failed(requestAbortedError(signal), earlier);
465
667
  result = await attemptAsync(request, options);
466
668
  }
467
669
  return result;
468
670
  }
671
+ function failed(err, earlier) {
672
+ return {
673
+ err: recordPreviousAttempts(err, earlier),
674
+ success: false
675
+ };
676
+ }
469
677
  function retryRefusal({ cause, deadlineMs, retryAfterMs }) {
470
678
  if (deadlineMs === void 0) return;
471
679
  const refusal = waitDeadlineFailure({
@@ -501,7 +709,7 @@ function planRetry(err, { config, deadlineMs, retries }) {
501
709
  if (!shouldRetry(err, config)) return;
502
710
  const guided = hasGuidedWait(err);
503
711
  if (!guided && retries >= config.maxRetries) return;
504
- if (guided && err.retryAfterSeconds > 60) return { refusal: guidedWaitRefusal(err) };
712
+ if (isRefusedGuidedWait(err)) return { refusal: guidedWaitRefusal(err) };
505
713
  const waitMs = computeRetryWaitMs(err, {
506
714
  attempt: retries,
507
715
  retryDelay: config.retryDelay
@@ -544,10 +752,10 @@ async function attemptAsync(request, { hooks, send, signal }) {
544
752
  /**
545
753
  * Extracts a {@link RateLimitSample} from a transport result so the budget
546
754
  * gate can be fed from every attempt. A 2xx carries the budget in its headers.
547
- * A 429 only primes the gate when it reports zero remaining and valid
548
- * guidance. This is a conservative scheduling condition, not a semantic
549
- * classification of the 429. A 429 asking for a longer wait than the SDK takes
550
- * is refused, so it does not hold later requests either. A 429 also carries
755
+ * A 429 with valid server guidance primes the gate as spent for its guided
756
+ * wait, whatever `x-ratelimit-remaining` reports: the remaining count is only
757
+ * a pacing hint on 2xx responses. A 429 asking for a longer wait than the SDK
758
+ * takes is refused, so it does not prime the gate either. A 429 also carries
551
759
  * the window capacity its `x-ratelimit-limit` header reports. Any other error
552
760
  * yields `undefined`.
553
761
  *
@@ -557,19 +765,46 @@ async function attemptAsync(request, { hooks, send, signal }) {
557
765
  function rateLimitSampleFromResult(result) {
558
766
  if (result.success) return parseRateLimitHeaders(result.data.headers);
559
767
  const { err } = result;
560
- if (err instanceof RateLimitError && err.remaining === 0 && hasServerRetryGuidance(err) && err.retryAfterSeconds <= 60) return withReportedWindow({
561
- remaining: err.remaining,
562
- resetSeconds: err.retryAfterSeconds
563
- }, err.responseHeaders?.["x-ratelimit-limit"]);
768
+ if (err instanceof RateLimitError && hasServerRetryGuidance(err) && err.retryAfterSeconds <= 60) {
769
+ const sample = {
770
+ remaining: 0,
771
+ resetSeconds: err.retryAfterSeconds
772
+ };
773
+ return withReportedWindow(sample, err.responseHeaders?.["x-ratelimit-limit"]);
774
+ }
775
+ }
776
+ /**
777
+ * Picks out a 429 whose guided wait is longer than the SDK waits out on its
778
+ * own. Such a lockout is refused, and later requests on the same scope fail
779
+ * locally until it ends instead of reaching the server.
780
+ *
781
+ * @param result - The classified transport result for one attempt.
782
+ * @returns The locking 429, or `undefined` for any other result.
783
+ */
784
+ function rateLimitLockoutFromResult(result) {
785
+ return !result.success && isRefusedGuidedWait(result.err) ? result.err : void 0;
786
+ }
787
+ /**
788
+ * Feeds one attempt back into the budget gate: its reported budget always,
789
+ * and a long 429 as a lockout unless the caller exempts it (such as a 429
790
+ * naming tasks that occupy a Luau place).
791
+ *
792
+ * @param budgets - The gate shared across the client.
793
+ * @param attempt - The scope, transport result, and lockout exemption.
794
+ */
795
+ function observeAttempt(budgets, { exemptsLockout, scope, transportResult }) {
796
+ budgets.observe(scope, rateLimitSampleFromResult(transportResult));
797
+ const lockout = rateLimitLockoutFromResult(transportResult);
798
+ if (lockout !== void 0 && exemptsLockout?.(lockout) !== true) budgets.lockOut(scope, lockout);
564
799
  }
565
800
  //#endregion
566
801
  //#region src/internal/http/rate-limit-queue.ts
567
802
  const OPERATION_QUEUE_REASON = "operation-queue";
568
803
  /**
569
- * Token-bucket rate limiter for a single `(apiKey, operation)` pair. Every
570
- * call to `acquire` consumes one token; when the bucket is empty the call
571
- * waits until a token regenerates before invoking the task. Tokens refill at
572
- * `maxPerSecond` per second, up to the operation's `burstCapacity`.
804
+ * Token-bucket rate limiter for a single `(credential identity, operation)`
805
+ * pair. Every call to `acquire` consumes one token; when the bucket is empty
806
+ * the call waits until a token regenerates before invoking the task. Tokens
807
+ * refill at `maxPerSecond` per second, up to the operation's `burstCapacity`.
573
808
  *
574
809
  * Implemented as a leaky bucket tracking drain debt in ms. `#lastCheck`
575
810
  * advances by `waitMs` after every sleep so the algorithm stays correct
@@ -692,6 +927,29 @@ async function waitForTurnAsync(turn, signal) {
692
927
  if (await raceWithAbortAsync(async () => turn, signal) === ABORTED) throw requestAbortedError(signal);
693
928
  }
694
929
  //#endregion
930
+ //#region src/internal/http/request-config.ts
931
+ /**
932
+ * Resolves the per-request {@link RequestConfig}, less the credential, which
933
+ * is resolved per transport attempt. Upload requests ({@link isUploadRequest})
934
+ * carry no default timeout: a multi-megabyte place file over a slow link is
935
+ * bandwidth-bound, so a transport-attempt timeout only fires spuriously. An
936
+ * explicit `options.timeout` still applies to any request; every non-upload
937
+ * request keeps the merged default.
938
+ *
939
+ * @param inputs - The merged config, the built request, and per-request
940
+ * overrides.
941
+ * @returns The config to hand to the transport, with `timeout` omitted when
942
+ * no transport-attempt timeout should apply.
943
+ */
944
+ function buildRequestConfig({ merged, options, request, signal }) {
945
+ const shouldOmitDefaultTimeout = options?.timeout === void 0 && isUploadRequest(request);
946
+ return {
947
+ baseUrl: merged.baseUrl,
948
+ ...signal === void 0 ? {} : { signal },
949
+ ...shouldOmitDefaultTimeout ? {} : { timeout: merged.timeout }
950
+ };
951
+ }
952
+ //#endregion
695
953
  //#region src/internal/utils/sleep.ts
696
954
  /**
697
955
  * Timer-backed production sleep that releases its timer on cancellation.
@@ -723,6 +981,183 @@ function resolveDependencies(options) {
723
981
  };
724
982
  }
725
983
  //#endregion
984
+ //#region src/internal/http/start-request.ts
985
+ /**
986
+ * Resolve the request-only controls of one call before its request is
987
+ * built: fail at once on an already-aborted caller signal or an elapsed
988
+ * deadline, otherwise start the request lifecycle and split the per-call
989
+ * options from the admission controls.
990
+ *
991
+ * @param options - The caller's per-request options, if any.
992
+ * @returns The resolved controls, or the abort or deadline failure.
993
+ */
994
+ function startRequest(options) {
995
+ const callerSignal = options?.signal;
996
+ if (callerSignal?.aborted === true) return {
997
+ err: requestAbortedError(callerSignal),
998
+ success: false
999
+ };
1000
+ const lifecycle = requestLifecycle(options?.deadlineMs, callerSignal);
1001
+ const deadlineFailure = elapsedDeadlineFailure(lifecycle);
1002
+ if (deadlineFailure !== void 0) return {
1003
+ err: deadlineFailure,
1004
+ success: false
1005
+ };
1006
+ const { deadlineMs, onAdmissionWait, signal: _signal, ...requestOptions } = options ?? {};
1007
+ return {
1008
+ data: {
1009
+ admission: {
1010
+ deadlineMs,
1011
+ observer: onAdmissionWait,
1012
+ signal: lifecycle.signal
1013
+ },
1014
+ lifecycle,
1015
+ requestOptions: withCredentialSnapshot(requestOptions)
1016
+ },
1017
+ success: true
1018
+ };
1019
+ }
1020
+ //#endregion
1021
+ //#region src/internal/http/credential.ts
1022
+ /**
1023
+ * Names the rate-limit bucket a credential draws on. The key is namespaced by
1024
+ * kind, so an OAuth identity never shares a bucket with an equal API key. An
1025
+ * OAuth credential keys on its identity, so a token rotation keeps the bucket.
1026
+ *
1027
+ * @param credential - The effective credential.
1028
+ * @returns The bucket key. It holds the API key, so keep it in private maps.
1029
+ */
1030
+ function credentialQueueKey(credential) {
1031
+ return credential.kind === "apiKey" ? `apiKey:${credential.apiKey}` : `oauth:${credential.identity}`;
1032
+ }
1033
+ /**
1034
+ * Turns the effective credential into the header-ready form for one transport
1035
+ * attempt. Calls an OAuth provider once; a throw or a rejection becomes a
1036
+ * {@link CredentialError} whose `cause` is the provider's error.
1037
+ *
1038
+ * @param credential - The effective credential.
1039
+ * @param signal - The request's signal, handed to an OAuth provider. A
1040
+ * request with no signal hands the provider one that never aborts.
1041
+ * @returns The resolved credential, or the provider failure.
1042
+ */
1043
+ async function resolveAttemptCredentialAsync(credential, signal) {
1044
+ if (credential.kind === "apiKey") return {
1045
+ data: {
1046
+ apiKey: credential.apiKey,
1047
+ kind: "apiKey"
1048
+ },
1049
+ success: true
1050
+ };
1051
+ try {
1052
+ return {
1053
+ data: {
1054
+ accessToken: await credential.getAccessToken({ signal: signal ?? neverAbortingSignal() }),
1055
+ kind: "oauth"
1056
+ },
1057
+ success: true
1058
+ };
1059
+ } catch (err) {
1060
+ return {
1061
+ err: new CredentialError("OAuth credential provider failed", { cause: err }),
1062
+ success: false
1063
+ };
1064
+ }
1065
+ }
1066
+ function neverAbortingSignal() {
1067
+ return new AbortController().signal;
1068
+ }
1069
+ //#endregion
1070
+ //#region src/internal/http/unauthenticated.ts
1071
+ const UNAUTHENTICATED_QUEUE_KEY = "none";
1072
+ const UNAUTHENTICATED = Object.freeze({
1073
+ data: Object.freeze({ kind: "none" }),
1074
+ success: true
1075
+ });
1076
+ /**
1077
+ * Applies a method's authentication to the merged config. An unauthenticated
1078
+ * method is served from its own origin and carries no credential. A
1079
+ * `{ kind: "none" }` credential carries none either.
1080
+ *
1081
+ * @param merged - The merged config of the call.
1082
+ * @param spec - The method's authentication declaration.
1083
+ * @returns The config to send with and the credential, if any.
1084
+ */
1085
+ function authenticateCall(merged, { unauthenticatedBaseUrl }) {
1086
+ if (unauthenticatedBaseUrl !== void 0) return {
1087
+ credential: void 0,
1088
+ merged: {
1089
+ ...merged,
1090
+ baseUrl: unauthenticatedBaseUrl
1091
+ }
1092
+ };
1093
+ return {
1094
+ credential: merged.credential.kind === "none" ? void 0 : merged.credential,
1095
+ merged
1096
+ };
1097
+ }
1098
+ /**
1099
+ * Keys the rate-limit queue of a call. Every unauthenticated call shares one
1100
+ * key, since Roblox counts those per caller.
1101
+ *
1102
+ * @param credential - The call's credential, or `undefined` when it sends
1103
+ * none.
1104
+ * @returns The credential's queue key, or the shared unauthenticated key.
1105
+ */
1106
+ function callQueueKey(credential) {
1107
+ return credential === void 0 ? UNAUTHENTICATED_QUEUE_KEY : credentialQueueKey(credential);
1108
+ }
1109
+ /**
1110
+ * Resolves the credential one attempt sends. An unauthenticated call sends
1111
+ * none and runs no OAuth provider.
1112
+ *
1113
+ * @param credential - The call's credential, if any.
1114
+ * @param signal - The caller's cancellation signal.
1115
+ * @returns The resolved credential, or the provider failure.
1116
+ */
1117
+ async function resolveCallCredentialAsync(credential, signal) {
1118
+ return credential === void 0 ? UNAUTHENTICATED : resolveAttemptCredentialAsync(credential, signal);
1119
+ }
1120
+ /**
1121
+ * Refines one attempt's transport error, then classifies a refused OAuth
1122
+ * token. An unauthenticated call sent no token, so none was refused.
1123
+ *
1124
+ * @param err - The transport error of the attempt.
1125
+ * @param context - The call's credential and optional refinement.
1126
+ * @returns The classified error.
1127
+ */
1128
+ function classifySendError(err, { credential, refineError }) {
1129
+ const refined = refineError === void 0 ? err : refineError(err);
1130
+ return credential === void 0 ? refined : classifyCredentialRejection(refined, credential);
1131
+ }
1132
+ //#endregion
1133
+ //#region src/internal/with-request-context.ts
1134
+ const TRAILING_SLASH = /\/$/;
1135
+ /**
1136
+ * Rebuilds a parser's {@link UnexpectedResponseError} with the request it
1137
+ * answered. A parser sees only the response, so the call site adds the method,
1138
+ * the full URL, and the allowlisted response headers, and ends the message with
1139
+ * the bug report link when `reportHint` is set. Any other error is returned
1140
+ * unchanged.
1141
+ *
1142
+ * @param err - The parser's error.
1143
+ * @param exchange - The base URL, the request sent, and the response parsed.
1144
+ * @returns `err`, carrying the request context when it is an unexpected
1145
+ * response.
1146
+ */
1147
+ function withRequestContext(err, { baseUrl, reportHint, request, response }) {
1148
+ if (!(err instanceof UnexpectedResponseError)) return err;
1149
+ return new UnexpectedResponseError(err.message, {
1150
+ cause: err.cause,
1151
+ code: err.code,
1152
+ details: err.details,
1153
+ method: request.method,
1154
+ reportHint,
1155
+ responseHeaders: pickDiagnosticHeaders({ ...response.headers }),
1156
+ statusCode: err.statusCode,
1157
+ url: `${baseUrl.replace(TRAILING_SLASH, "")}${request.url}`
1158
+ });
1159
+ }
1160
+ //#endregion
726
1161
  //#region src/internal/resource-client.ts
727
1162
  /**
728
1163
  * Wraps an infallible request build as a {@link Result}-returning
@@ -775,16 +1210,17 @@ var ResourceClient = class {
775
1210
  #hooks;
776
1211
  #httpClient;
777
1212
  #queues = /* @__PURE__ */ new Map();
1213
+ #reportHint;
778
1214
  #sleep;
779
1215
  /**
780
1216
  * Creates a new {@link ResourceClient}. Resolves the injected HTTP
781
1217
  * client and sleep (defaulting to fetch + `setTimeout`) and freezes the
782
1218
  * merged client config so subsequent calls cannot mutate it.
783
1219
  *
784
- * @param options - Client-level configuration including the API key
1220
+ * @param options - Client-level configuration including the credential
785
1221
  * and optional construction-time test seams.
786
1222
  */
787
- constructor({ apiKey, hooks, httpClient, sleep, ...overrides }) {
1223
+ constructor({ hooks, httpClient, reportHint, sleep, ...overrides }) {
788
1224
  const resolved = resolveDependencies({
789
1225
  httpClient,
790
1226
  sleep
@@ -793,16 +1229,17 @@ var ResourceClient = class {
793
1229
  this.#sleep = resolved.sleep;
794
1230
  this.#budgets = new BudgetGate(this.#sleep);
795
1231
  this.#hooks = hooks ?? {};
1232
+ this.#reportHint = reportHint ?? true;
796
1233
  this.#config = Object.freeze({
797
1234
  ...CLIENT_DEFAULTS,
798
- apiKey,
799
- ...overrides
1235
+ ...overrides,
1236
+ credential: snapshotCredential(overrides.credential)
800
1237
  });
801
1238
  }
802
1239
  /**
803
1240
  * Dispatches a single resource-method call. Merges the frozen client
804
1241
  * config with the method's `methodDefaults` and the caller's optional
805
- * per-request `options`, routes through the effective-apiKey rate-limit
1242
+ * per-request `options`, routes through the effective-credential rate-limit
806
1243
  * queue, runs the retry loop, and finally parses the response with the
807
1244
  * spec's parser.
808
1245
  *
@@ -812,16 +1249,12 @@ var ResourceClient = class {
812
1249
  * caused the request to fail. Never throws.
813
1250
  * @rejects An unexpected collaborator failure unrelated to caller cancellation.
814
1251
  */
815
- async executeAsync({ options, parameters, refineError, spec }) {
1252
+ async executeAsync({ exemptsLockout, options, parameters, refineError, spec }) {
816
1253
  const start = startRequest(options);
817
1254
  if (!start.success) return start;
818
1255
  const { admission, lifecycle, requestOptions } = start.data;
819
- const merged = mergeConfig(this.#config, {
820
- methodDefaults: spec.methodDefaults,
821
- methodKind: spec.methodKind,
822
- requestOptions
823
- });
824
- const requestResult = spec.buildRequest(parameters);
1256
+ const { credential, merged } = authenticateCall(this.#merge(spec, requestOptions), spec);
1257
+ const requestResult = credentialNotSupportedFailure(spec, merged.credential) ?? spec.buildRequest(parameters);
825
1258
  if (!requestResult.success) return requestResult;
826
1259
  const request = requestResult.data;
827
1260
  const { signal } = admission;
@@ -834,6 +1267,8 @@ var ResourceClient = class {
834
1267
  return finishRequest({
835
1268
  httpResult: await this.#dispatchAsync({
836
1269
  admission,
1270
+ credential,
1271
+ exemptsLockout,
837
1272
  merged,
838
1273
  operationLimit: spec.operationLimit,
839
1274
  refineError,
@@ -841,8 +1276,10 @@ var ResourceClient = class {
841
1276
  requestConfig
842
1277
  }),
843
1278
  lifecycle,
1279
+ merged,
1280
+ request,
844
1281
  spec
845
- });
1282
+ }, this.#reportHint);
846
1283
  }
847
1284
  /**
848
1285
  * Returns the sleep function used by this client instance.
@@ -852,9 +1289,12 @@ var ResourceClient = class {
852
1289
  get sleep() {
853
1290
  return this.#sleep;
854
1291
  }
855
- async #dispatchAsync({ admission, merged, operationLimit, refineError, request, requestConfig }) {
856
- const queue = this.#getQueue(merged.apiKey, operationLimit);
1292
+ async #dispatchAsync({ admission, credential, exemptsLockout, merged, operationLimit, refineError, request, requestConfig }) {
1293
+ const credentialKey = callQueueKey(credential);
1294
+ const queue = this.#getQueue(credentialKey, operationLimit);
1295
+ const scope = budgetScopeFor(credentialKey, operationLimit);
857
1296
  try {
1297
+ this.#budgets.refuseDuringLockout(scope);
858
1298
  return await queue.acquireAsync(async () => {
859
1299
  return executeWithRetryAsync(request, {
860
1300
  admissionWaitObserver: admission.observer,
@@ -863,13 +1303,11 @@ var ResourceClient = class {
863
1303
  hooks: this.#hooks,
864
1304
  send: this.#gatedSend({
865
1305
  admission,
1306
+ credential,
1307
+ exemptsLockout,
866
1308
  refineError,
867
1309
  requestConfig,
868
- scope: {
869
- apiKey: merged.apiKey,
870
- documentedWindow: documentedWindow(operationLimit),
871
- operationKey: operationLimit.operationKey
872
- }
1310
+ scope
873
1311
  }),
874
1312
  signal: admission.signal,
875
1313
  sleep: this.#sleep
@@ -881,111 +1319,101 @@ var ResourceClient = class {
881
1319
  }
882
1320
  /**
883
1321
  * Builds the transport callback for one logical call, wrapping the HTTP
884
- * client with the budget gate: each attempt waits on the scope's budget
885
- * before sending, then folds the response's reported budget back in so the
886
- * next attempt (or a later call on the same scope) can head off a 429.
1322
+ * client with the budget gate: each attempt waits on the scope's budget,
1323
+ * then resolves the credential (an OAuth provider runs here, after every
1324
+ * admission wait) before sending, then folds the response's reported
1325
+ * budget back in so the next attempt (or a later call on the same scope)
1326
+ * can head off a 429. A provider failure, or a lockout that began while the
1327
+ * provider ran, ends the attempt unsent and gives its budget slot back.
887
1328
  *
888
1329
  * @param inputs - Budget scope, transport config, observer, and caller signal.
889
1330
  * @returns A send callback for {@link executeWithRetryAsync}.
890
1331
  */
891
- #gatedSend({ admission, refineError, requestConfig, scope }) {
1332
+ #gatedSend({ admission, credential, exemptsLockout, refineError, requestConfig, scope }) {
892
1333
  return async (toSend) => {
893
- await this.#budgets.gateAsync(scope, admission);
894
- const transportResult = await this.#httpClient.request(toSend, requestConfig);
895
- const sendResult = refineError === void 0 || transportResult.success ? transportResult : {
896
- err: refineError(transportResult.err),
1334
+ const reservation = await this.#budgets.gateAsync(scope, admission);
1335
+ const attempted = await resolveCallCredentialAsync(credential, admission.signal);
1336
+ const resolved = this.#budgets.refuseIfLockedOut(scope, attempted);
1337
+ if (!resolved.success) {
1338
+ reservation.release();
1339
+ return resolved;
1340
+ }
1341
+ const transportResult = await this.#httpClient.request(toSend, {
1342
+ ...requestConfig,
1343
+ credential: resolved.data
1344
+ });
1345
+ const sendResult = transportResult.success ? transportResult : {
1346
+ err: classifySendError(transportResult.err, {
1347
+ credential,
1348
+ refineError
1349
+ }),
897
1350
  success: false
898
1351
  };
899
- this.#budgets.observe(scope, rateLimitSampleFromResult(transportResult));
1352
+ observeAttempt(this.#budgets, {
1353
+ exemptsLockout,
1354
+ scope,
1355
+ transportResult
1356
+ });
900
1357
  return sendResult;
901
1358
  };
902
1359
  }
903
- #getQueue(apiKey, limit) {
904
- const key = `${apiKey}::${limit.operationKey}`;
1360
+ #getQueue(credentialKey, limit) {
1361
+ const key = scopeKey({
1362
+ credentialKey,
1363
+ operationKey: limit.operationKey
1364
+ });
905
1365
  const existing = this.#queues.get(key);
906
1366
  if (existing !== void 0) return existing;
907
1367
  const queue = new RateLimitQueue(limit, this.#hooks, this.#sleep);
908
1368
  this.#queues.set(key, queue);
909
1369
  return queue;
910
1370
  }
1371
+ #merge(spec, requestOptions) {
1372
+ return mergeConfig(this.#config, {
1373
+ methodDefaults: spec.methodDefaults,
1374
+ methodKind: spec.methodKind,
1375
+ requestOptions
1376
+ });
1377
+ }
911
1378
  };
912
- function startRequest(options) {
913
- const callerSignal = options?.signal;
914
- if (callerSignal?.aborted === true) return {
915
- err: requestAbortedError(callerSignal),
916
- success: false
917
- };
918
- const lifecycle = requestLifecycle(options?.deadlineMs, callerSignal);
919
- const deadlineFailure = elapsedDeadlineFailure(lifecycle);
920
- if (deadlineFailure !== void 0) return {
921
- err: deadlineFailure,
922
- success: false
923
- };
924
- const { deadlineMs, onAdmissionWait, signal: _signal, ...requestOptions } = options ?? {};
1379
+ function budgetScopeFor(credentialKey, operationLimit) {
925
1380
  return {
926
- data: {
927
- admission: {
928
- deadlineMs,
929
- observer: onAdmissionWait,
930
- signal: lifecycle.signal
931
- },
932
- lifecycle,
933
- requestOptions
934
- },
935
- success: true
1381
+ credentialKey,
1382
+ documentedWindow: documentedWindow(operationLimit),
1383
+ operationKey: operationLimit.operationKey
936
1384
  };
937
1385
  }
938
1386
  function dispatchFailure(err) {
939
- if (err instanceof RequestAbortedError || err instanceof RequestDeadlineExceededError) return {
1387
+ if (err instanceof RequestAbortedError || err instanceof RequestDeadlineExceededError || err instanceof RateLimitWaitRefusedError) return {
940
1388
  err,
941
1389
  success: false
942
1390
  };
943
1391
  throw err;
944
1392
  }
945
- /**
946
- * Resolves the per-request {@link RequestConfig}. Upload requests
947
- * ({@link isUploadRequest}) carry no default timeout: a multi-megabyte place
948
- * file over a slow link is bandwidth-bound, so a transport-attempt timeout only
949
- * fires spuriously. An explicit `options.timeout` still applies to any
950
- * request; every non-upload request keeps the merged default.
951
- *
952
- * @param inputs - The merged config, the built request, and per-request overrides.
953
- * @returns The config to hand to the transport, with `timeout` omitted when
954
- * no transport-attempt timeout should apply.
955
- */
956
- function buildRequestConfig({ merged, options, request, signal }) {
957
- const shouldOmitDefaultTimeout = options?.timeout === void 0 && isUploadRequest(request);
958
- return {
959
- apiKey: merged.apiKey,
960
- baseUrl: merged.baseUrl,
961
- ...signal === void 0 ? {} : { signal },
962
- ...shouldOmitDefaultTimeout ? {} : { timeout: merged.timeout }
963
- };
964
- }
965
- function enrichPermissionError(err, spec) {
966
- if (spec.requiredScopes === void 0) return err;
967
- if (err instanceof PermissionError) return err;
968
- if (!(err instanceof ApiError)) return err;
969
- if (err.statusCode !== 401 && err.statusCode !== 403) return err;
970
- if (err.gatewaySummary !== void 0) return err;
971
- return new PermissionError(err.message, {
972
- ...requestContextOf(err),
973
- cause: err.cause,
974
- code: err.code,
975
- details: err.details,
1393
+ function finishRequest({ httpResult, lifecycle, merged, request, spec }, reportHint) {
1394
+ if (httpResult.success) {
1395
+ const parsed = spec.parse(httpResult.data);
1396
+ return parsed.success ? parsed : {
1397
+ err: withRequestContext(parsed.err, {
1398
+ baseUrl: merged.baseUrl,
1399
+ reportHint,
1400
+ request,
1401
+ response: httpResult.data
1402
+ }),
1403
+ success: false
1404
+ };
1405
+ }
1406
+ const err = deadlineFailureFromError(httpResult.err, lifecycle) ?? enrichPermissionError(httpResult.err, {
1407
+ credential: merged.credential,
976
1408
  operationKey: spec.operationLimit.operationKey,
977
- requiredScopes: spec.requiredScopes,
978
- statusCode: err.statusCode
1409
+ requiredScopes: spec.requiredScopes
979
1410
  });
980
- }
981
- function finishRequest({ httpResult, lifecycle, spec }) {
982
- if (httpResult.success) return spec.parse(httpResult.data);
983
1411
  return {
984
- err: deadlineFailureFromError(httpResult.err, lifecycle) ?? enrichPermissionError(httpResult.err, spec),
1412
+ err: recordPreviousAttempts(err, httpResult.err.previousAttempts),
985
1413
  success: false
986
1414
  };
987
1415
  }
988
1416
  //#endregion
989
- export { observeAdmissionWaitAsync as a, isDateTimeString as c, waitDeadlineFailure as i, okRequest as n, toJsonDetails as o, parseEmptyResponse as r, isRecord as s, ResourceClient as t };
1417
+ export { waitDeadlineFailure as a, isDateTimeString as c, MAX_ABORT_TIMEOUT_MS as i, okRequest as n, observeAdmissionWaitAsync as o, parseEmptyResponse as r, toJsonDetails as s, ResourceClient as t };
990
1418
 
991
- //# sourceMappingURL=resource-client-rqTMkBeR.mjs.map
1419
+ //# sourceMappingURL=resource-client-CaIVr-go.mjs.map