@bedrock-rbx/ocale 0.3.4-beta.1 → 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 (86) 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 +924 -306
  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-sKTsqEc1.mjs → polling-helpers-DfF5dspc.mjs} +249 -83
  41. package/dist/polling-helpers-DfF5dspc.mjs.map +1 -0
  42. package/dist/{price-information-hWXV6DAI.mjs → price-information-DEkEQ8Pq.mjs} +2 -2
  43. package/dist/{price-information-hWXV6DAI.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-CaIVr-go.mjs +1419 -0
  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-vpHMIwaU.mjs → retry-CMRDvAR4.mjs} +390 -20
  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-BvnJjY0S.d.mts +0 -369
  72. package/dist/capacity-admission-BvnJjY0S.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-sKTsqEc1.mjs.map +0 -1
  76. package/dist/resource-client-3cOhqZpX.mjs +0 -899
  77. package/dist/resource-client-3cOhqZpX.mjs.map +0 -1
  78. package/dist/resource-client-BivRq3JZ.d.mts +0 -164
  79. package/dist/resource-client-BivRq3JZ.d.mts.map +0 -1
  80. package/dist/retry-DXEklFrt.d.mts +0 -373
  81. package/dist/retry-DXEklFrt.d.mts.map +0 -1
  82. package/dist/retry-vpHMIwaU.mjs.map +0 -1
  83. package/dist/types-C3Egi37J.d.mts +0 -378
  84. package/dist/types-C3Egi37J.d.mts.map +0 -1
  85. package/dist/wire-D3K-a-UP.d.mts +0 -37
  86. package/dist/wire-D3K-a-UP.d.mts.map +0 -1
@@ -0,0 +1,1419 @@
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
+ import { setTimeout } from "node:timers/promises";
4
+ //#region src/internal/utils/is-date-time-string.ts
5
+ /**
6
+ * Narrows `value` to a string that parses to a real {@link Date} via the
7
+ * `Date(string)` constructor. Used by resource parsers to gate
8
+ * `format: date-time` wire fields before handing them to `new Date(...)`,
9
+ * which silently produces an `Invalid Date` for invalid input.
10
+ *
11
+ * @param value - The unknown wire value to validate.
12
+ * @returns `true` when `value` is a string and `new Date(value).getTime()`
13
+ * is not `NaN`.
14
+ */
15
+ function isDateTimeString(value) {
16
+ if (typeof value !== "string") return false;
17
+ const parsed = new Date(value);
18
+ return !Number.isNaN(parsed.getTime());
19
+ }
20
+ //#endregion
21
+ //#region src/internal/utils/to-json-details.ts
22
+ /**
23
+ * Narrows an untyped response body to the `JSONValue` accepted by
24
+ * `ApiError.details`. `HttpResponse.body` is `unknown` because a transport may
25
+ * hand back anything, but only a JSON graph is safe to retain on an error for
26
+ * diagnostics. Anything else — functions, symbols, bigints, class instances,
27
+ * or a cyclic graph — is dropped rather than asserted through.
28
+ *
29
+ * @param value - The parsed response body, or `undefined` for an empty body.
30
+ * @returns The value as a `JSONValue`, or `undefined` when it is absent or not
31
+ * JSON-representable.
32
+ */
33
+ function toJsonDetails(value) {
34
+ return asJsonValue(value, /* @__PURE__ */ new Set());
35
+ }
36
+ function asJsonValue(value, seen) {
37
+ if (value === null) return null;
38
+ if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") return value;
39
+ if (Array.isArray(value)) return asJsonArray(value, seen);
40
+ if (isRecord(value)) return asJsonObject(value, seen);
41
+ }
42
+ function asJsonArray(value, seen) {
43
+ if (seen.has(value)) return;
44
+ seen.add(value);
45
+ const items = [];
46
+ for (const item of value) {
47
+ const converted = asJsonValue(item, seen);
48
+ if (converted === void 0) return;
49
+ items.push(converted);
50
+ }
51
+ seen.delete(value);
52
+ return items;
53
+ }
54
+ function asJsonObject(value, seen) {
55
+ if (seen.has(value)) return;
56
+ seen.add(value);
57
+ const entries = [];
58
+ for (const [key, item] of Object.entries(value)) {
59
+ const converted = asJsonValue(item, seen);
60
+ if (converted === void 0) return;
61
+ entries.push([key, converted]);
62
+ }
63
+ seen.delete(value);
64
+ return Object.fromEntries(entries);
65
+ }
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
118
+ //#region src/internal/http/admission-wait.ts
119
+ /**
120
+ * Performs one SDK-managed wait and emits a balanced request-scoped lifecycle.
121
+ * Observer failures are deliberately ignored: observation cannot become part
122
+ * of admission control.
123
+ *
124
+ * @template T - Value produced by the observed wait.
125
+ * @param options - Wait metadata, observer, and the wait operation itself.
126
+ * @returns The value produced by the wait.
127
+ */
128
+ async function observeAdmissionWaitAsync({ durationMs, observer, reason, waitAsync }) {
129
+ const details = {
130
+ ...durationMs === void 0 ? {} : { durationMs },
131
+ reason
132
+ };
133
+ notify(observer, {
134
+ ...details,
135
+ phase: "started"
136
+ });
137
+ try {
138
+ return await waitAsync();
139
+ } finally {
140
+ notify(observer, {
141
+ ...details,
142
+ phase: "ended"
143
+ });
144
+ }
145
+ }
146
+ function notify(observer, event) {
147
+ try {
148
+ const notification = observer?.(event);
149
+ if (notification !== void 0) Promise.resolve(notification).catch(Boolean);
150
+ } catch {}
151
+ }
152
+ //#endregion
153
+ //#region src/internal/http/budget-tracker.ts
154
+ const MS_PER_SECOND$1 = 1e3;
155
+ /**
156
+ * Tracks the live rate-limit budget for a single scope. Primed by `observe`
157
+ * from response headers and drawn down by `reserve` as requests leave, so
158
+ * `waitMs` can pace requests across the window.
159
+ *
160
+ * Pacing has two regimes. While budget remains, requests are spread evenly over
161
+ * the time left in the window (`timeLeft / remaining`), so a burst does not
162
+ * spend the whole window's budget up front and then stall. Once the budget is
163
+ * spent, requests hold until the window resets. Budget and reset time move
164
+ * together as one window, so the tracker is either unprimed or fully primed,
165
+ * never half-known.
166
+ *
167
+ * Once a primed window's reset passes with no fresh reading, the next window
168
+ * opens holding the scope's capacity: the last capacity a response reported,
169
+ * or the operation's documented one. Requests queued behind a reset are
170
+ * admitted at that capacity per window, spaced one window-length divided by
171
+ * capacity apart.
172
+ */
173
+ var BudgetTracker = class {
174
+ /** Time (ms) the most recent request was allowed out, for spacing. */
175
+ #lastAllowedAt = void 0;
176
+ /** Token of the latest reservation, compared by identity. */
177
+ #latestReservation = void 0;
178
+ /** Requests the server grants per window, used when a window rolls over. */
179
+ #rolloverWindow;
180
+ #window = void 0;
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
+ /**
187
+ * Creates a tracker for one scope.
188
+ *
189
+ * @param documentedWindow - The operation's documented capacity, used
190
+ * until a response reports one.
191
+ */
192
+ constructor(documentedWindow) {
193
+ this.#rolloverWindow = documentedWindow;
194
+ }
195
+ /**
196
+ * Folds a fresh server reading in, replacing any prior window. The latest
197
+ * reading wins: observe time is monotonic, so the most recently resolved
198
+ * response is the best current estimate. The spacing reference is left
199
+ * untouched so a window refresh does not reset pacing mid-stream.
200
+ *
201
+ * @param sample - Parsed `remaining`/`resetSeconds` from a response.
202
+ * @param now - The current time in ms.
203
+ */
204
+ observe(sample, now) {
205
+ this.#rolloverWindow = sample.window ?? this.#rolloverWindow;
206
+ this.#windowToken = {};
207
+ this.#window = {
208
+ predictedRemaining: sample.remaining,
209
+ resetAt: now + sample.resetSeconds * MS_PER_SECOND$1
210
+ };
211
+ }
212
+ /**
213
+ * Accounts for one request leaving at `now`: records the spacing reference
214
+ * and decrements the prediction. A no-op on the prediction while unprimed.
215
+ *
216
+ * @param now - The time the request was allowed out, in ms.
217
+ * @returns The reservation, to release if the request is not sent.
218
+ */
219
+ reserve(now) {
220
+ const previousAllowedAt = this.#lastAllowedAt;
221
+ this.#lastAllowedAt = now;
222
+ const reservation = {};
223
+ this.#latestReservation = reservation;
224
+ const window = this.#windowAt(now);
225
+ if (window !== void 0) this.#window = {
226
+ ...window,
227
+ predictedRemaining: window.predictedRemaining - 1
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
+ } };
240
+ }
241
+ /**
242
+ * Milliseconds to wait before the next request is allowed.
243
+ *
244
+ * @param now - The current time in ms.
245
+ * @returns `0` when a request may go now (unprimed, or the first paced send);
246
+ * the time until reset when the budget is spent; otherwise the time until
247
+ * this request's evenly-spaced slot.
248
+ */
249
+ waitMs(now) {
250
+ const window = this.#windowAt(now);
251
+ if (window === void 0) return 0;
252
+ const { predictedRemaining, resetAt } = window;
253
+ if (predictedRemaining <= 0) return Math.max(0, resetAt - now);
254
+ if (this.#lastAllowedAt === void 0) return 0;
255
+ const interval = window.spacingMs ?? (resetAt - now) / predictedRemaining;
256
+ return Math.max(0, this.#lastAllowedAt + interval - now);
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
+ }
265
+ /**
266
+ * The window in force at `now`, opening the next one at full capacity once
267
+ * the current window's reset has passed.
268
+ *
269
+ * @param now - The current time in ms.
270
+ * @returns The live window, or `undefined` while unprimed.
271
+ */
272
+ #windowAt(now) {
273
+ if (this.#window !== void 0 && now >= this.#window.resetAt) {
274
+ const { capacity, windowSeconds } = this.#rolloverWindow;
275
+ const windowMs = windowSeconds * MS_PER_SECOND$1;
276
+ this.#windowToken = {};
277
+ this.#window = {
278
+ predictedRemaining: capacity,
279
+ resetAt: now + windowMs,
280
+ spacingMs: windowMs / capacity
281
+ };
282
+ }
283
+ return this.#window;
284
+ }
285
+ };
286
+ //#endregion
287
+ //#region src/internal/http/request-deadline.ts
288
+ const DEADLINE_ELAPSED = Symbol("request deadline elapsed");
289
+ /** The longest delay a timer accepts; `AbortSignal.timeout` throws above it. */
290
+ const MAX_ABORT_TIMEOUT_MS = 2147483647;
291
+ /**
292
+ * Resolves one signal that spans the whole logical request.
293
+ *
294
+ * @param deadlineMs - Absolute deadline, as Unix epoch milliseconds.
295
+ * @param callerSignal - Optional caller cancellation signal.
296
+ * @returns Signals that span and classify the logical request.
297
+ */
298
+ function requestLifecycle(deadlineMs, callerSignal) {
299
+ if (deadlineMs === void 0) return {
300
+ deadlineMs,
301
+ deadlineSignal: void 0,
302
+ signal: callerSignal
303
+ };
304
+ const deadlineSignal = deadlineTimeout(deadlineMs);
305
+ return {
306
+ deadlineMs,
307
+ deadlineSignal,
308
+ signal: callerSignal === void 0 ? deadlineSignal : AbortSignal.any([callerSignal, deadlineSignal])
309
+ };
310
+ }
311
+ /**
312
+ * Returns a typed failure when the deadline signal ended the request.
313
+ *
314
+ * @param lifecycle - Signals and timestamp for the logical request.
315
+ * @param cause - The failure the deadline failure replaces, if any.
316
+ * @returns A deadline failure, or `undefined` when another signal won.
317
+ */
318
+ function elapsedDeadlineFailure({ deadlineMs, deadlineSignal, signal }, cause) {
319
+ if (deadlineMs === void 0 || deadlineSignal?.aborted !== true || !Object.is(signal?.reason, deadlineSignal.reason)) return;
320
+ return new RequestDeadlineExceededError("Request deadline elapsed", {
321
+ cause,
322
+ deadlineMs,
323
+ remainingMs: 0
324
+ });
325
+ }
326
+ /**
327
+ * Reclassifies an internal abort when the request deadline supplied its signal.
328
+ * The abort becomes the deadline failure's `cause`.
329
+ *
330
+ * @param error - Error returned by the request pipeline.
331
+ * @param lifecycle - Signals and timestamp for the logical request.
332
+ * @returns A deadline failure, or `undefined` for other failures.
333
+ */
334
+ function deadlineFailureFromError(error, lifecycle) {
335
+ return error instanceof RequestAbortedError ? elapsedDeadlineFailure(lifecycle, error) : void 0;
336
+ }
337
+ /**
338
+ * Refuses a known admission wait that cannot fit before the deadline.
339
+ *
340
+ * @param inputs - Deadline, wait duration, reason, and optional cause.
341
+ * @returns A typed refusal, or `undefined` when the wait fits.
342
+ */
343
+ function waitDeadlineFailure({ cause, deadlineMs, waitMs, waitReason }) {
344
+ if (deadlineMs === void 0) return;
345
+ const now = Date.now();
346
+ const remainingMs = Math.max(0, deadlineMs - now);
347
+ if (now < deadlineMs && waitMs <= remainingMs) return;
348
+ const options = {
349
+ cause,
350
+ deadlineMs,
351
+ remainingMs,
352
+ waitMs,
353
+ waitReason
354
+ };
355
+ return new RequestDeadlineExceededError(waitMessage(waitMs, remainingMs), options);
356
+ }
357
+ function armDeadlineTimeout(controller, deadlineMs) {
358
+ const remainingMs = deadlineMs - Date.now();
359
+ if (remainingMs <= 0) {
360
+ controller.abort(DEADLINE_ELAPSED);
361
+ return;
362
+ }
363
+ AbortSignal.timeout(Math.min(Math.ceil(remainingMs), MAX_ABORT_TIMEOUT_MS)).addEventListener("abort", () => {
364
+ armDeadlineTimeout(controller, deadlineMs);
365
+ });
366
+ }
367
+ function deadlineTimeout(deadlineMs) {
368
+ const controller = new AbortController();
369
+ if (Number.isFinite(deadlineMs)) armDeadlineTimeout(controller, deadlineMs);
370
+ else controller.abort(DEADLINE_ELAPSED);
371
+ return controller.signal;
372
+ }
373
+ function waitMessage(waitMs, remainingMs) {
374
+ return `Admission wait would take ${waitMs / 1e3}s; ${remainingMs / 1e3}s remain before the request deadline`;
375
+ }
376
+ //#endregion
377
+ //#region src/internal/http/budget-gate.ts
378
+ const REPORTED_BUDGET_REASON = "reported-budget";
379
+ const MS_PER_SECOND = 1e3;
380
+ /**
381
+ * Header-primed rate-limit gate shared across a client. Holds one
382
+ * {@link BudgetTracker} per {@link BudgetScope}. Before each request the caller
383
+ * gates on the request's scope (sleeping if that budget is spent), and after
384
+ * each response folds the parsed sample back in, so a later call on the same
385
+ * scope can head off a 429 the static per-operation token bucket cannot
386
+ * foresee.
387
+ *
388
+ * Gating is serialized per scope through a promise chain so concurrent
389
+ * requests on one scope cannot read the same budget and reserve the same slot;
390
+ * each waits for the prior gate's reserve before computing its own.
391
+ */
392
+ var BudgetGate = class {
393
+ #chains = /* @__PURE__ */ new Map();
394
+ #lockouts = /* @__PURE__ */ new Map();
395
+ #pendingGates = /* @__PURE__ */ new Map();
396
+ #sleep;
397
+ #trackers = /* @__PURE__ */ new Map();
398
+ /**
399
+ * Creates a gate bound to an injectable sleep.
400
+ *
401
+ * @param sleep - Injectable sleep (tests pass a fake clock).
402
+ */
403
+ constructor(sleep) {
404
+ this.#sleep = sleep;
405
+ }
406
+ /**
407
+ * Holds until the scope's budget permits a send, then reserves one slot.
408
+ * Runs after the prior gate on the same scope settles, whether it resolved
409
+ * or rejected, so one failed attempt cannot poison later gates on the
410
+ * scope.
411
+ *
412
+ * @param scope - The credential and operation to gate on.
413
+ * @param context - Request-local observer and cancellation signal.
414
+ * @returns The reserved slot. Release it when the request is not sent.
415
+ * @rejects {@link RequestAbortedError} when the caller cancels while waiting.
416
+ * @rejects {@link RateLimitWaitRefusedError} while the scope is locked out.
417
+ */
418
+ async gateAsync(scope, { deadlineMs, observer, signal } = {}) {
419
+ const key = scopeKey(scope);
420
+ const pendingGates = this.#pendingGates.get(key) ?? 0;
421
+ const waitsForEarlierGate = pendingGates > 0;
422
+ this.#pendingGates.set(key, pendingGates + 1);
423
+ const completed = (this.#chains.get(key) ?? Promise.resolve()).catch(ignoreRejection$1).then(async () => {
424
+ return this.#gateOnce(scope, {
425
+ deadlineMs,
426
+ observer: waitsForEarlierGate ? void 0 : observer,
427
+ signal
428
+ });
429
+ }).finally(() => {
430
+ const remainingGates = (this.#pendingGates.get(key) ?? 1) - 1;
431
+ this.#pendingGates.set(key, remainingGates);
432
+ });
433
+ this.#chains.set(key, completed.then(ignoreRejection$1).catch(ignoreRejection$1));
434
+ if (waitsForEarlierGate) return observeAdmissionWaitAsync({
435
+ observer,
436
+ reason: REPORTED_BUDGET_REASON,
437
+ waitAsync: async () => waitForGateAsync(completed, signal)
438
+ });
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
+ });
454
+ }
455
+ /**
456
+ * Folds a response's parsed budget back onto the scope. A `undefined`
457
+ * sample (headers absent or non-numeric) is ignored, leaving the scope on
458
+ * static pacing.
459
+ *
460
+ * @param scope - The same scope passed to {@link gateAsync}.
461
+ * @param sample - Parsed sample, or `undefined` when none was reported.
462
+ */
463
+ observe(scope, sample) {
464
+ if (sample === void 0) return;
465
+ this.#tracker(scopeKey(scope), scope.documentedWindow).observe(sample, Date.now());
466
+ }
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 }) {
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);
497
+ const waitMs = tracker.waitMs(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;
516
+ }
517
+ #tracker(key, documentedWindow) {
518
+ const existing = this.#trackers.get(key);
519
+ if (existing !== void 0) return existing;
520
+ const tracker = new BudgetTracker(documentedWindow);
521
+ this.#trackers.set(key, tracker);
522
+ return tracker;
523
+ }
524
+ async #waitAsync(waitMs, { deadlineMs, observer, signal }) {
525
+ const refusal = waitDeadlineFailure({
526
+ deadlineMs,
527
+ waitMs,
528
+ waitReason: REPORTED_BUDGET_REASON
529
+ });
530
+ if (refusal !== void 0) throw refusal;
531
+ await observeAdmissionWaitAsync({
532
+ durationMs: waitMs,
533
+ observer,
534
+ reason: REPORTED_BUDGET_REASON,
535
+ waitAsync: async () => {
536
+ if (await raceWithAbortAsync(async () => this.#sleep(waitMs, signal), signal) === ABORTED) throw requestAbortedError(signal);
537
+ }
538
+ });
539
+ }
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
+ }
565
+ function ignoreRejection$1() {}
566
+ async function waitForGateAsync(gate, signal) {
567
+ const gateResult = await raceWithAbortAsync(async () => gate, signal);
568
+ if (gateResult === ABORTED) throw requestAbortedError(signal);
569
+ return gateResult;
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.";
576
+ /**
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.
582
+ *
583
+ * @param err - The transport error for one attempt.
584
+ * @param credential - The effective credential of the call.
585
+ * @returns The classified error.
586
+ */
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}`;
628
+ }
629
+ //#endregion
630
+ //#region src/internal/http/execute.ts
631
+ /**
632
+ * Retry-aware orchestration loop. Coordinates a single logical request,
633
+ * looping over `options.send` until it succeeds, the error is non-retryable,
634
+ * or `options.config.maxRetries` is exhausted. Server-guided rate-limit waits
635
+ * do not count against `maxRetries`; the request deadline and `signal` bound
636
+ * them. Fires observability hooks at each transition. Queue-agnostic: `send`
637
+ * may be any callback, including one wrapped by a rate-limit queue.
638
+ *
639
+ * @param request - The immutable request to send.
640
+ * @param options - The transport callback, resolved config, hooks, and sleep.
641
+ * @returns The first success, or the final error after retries are exhausted.
642
+ */
643
+ async function executeWithRetryAsync(request, options) {
644
+ const { config, deadlineMs, hooks, signal } = options;
645
+ if (signal?.aborted === true) return abortedResult(signal);
646
+ let result = await attemptAsync(request, options);
647
+ let retries = 0;
648
+ let earlier = [];
649
+ while (!result.success) {
650
+ const failure = result.err;
651
+ const plan = planRetry(failure, {
652
+ config,
653
+ deadlineMs,
654
+ retries
655
+ });
656
+ if (plan === void 0) return failed(failure, earlier);
657
+ if ("refusal" in plan) return failed(plan.refusal, earlier);
658
+ retries += plan.spendsAttempt ? 1 : 0;
659
+ earlier = [...earlier, failure];
660
+ announceRetry({
661
+ attempt: earlier.length,
662
+ error: failure,
663
+ hooks,
664
+ waitMs: plan.waitMs
665
+ });
666
+ if (await waitForRetryAsync(plan.waitMs, options) === ABORTED) return failed(requestAbortedError(signal), earlier);
667
+ result = await attemptAsync(request, options);
668
+ }
669
+ return result;
670
+ }
671
+ function failed(err, earlier) {
672
+ return {
673
+ err: recordPreviousAttempts(err, earlier),
674
+ success: false
675
+ };
676
+ }
677
+ function retryRefusal({ cause, deadlineMs, retryAfterMs }) {
678
+ if (deadlineMs === void 0) return;
679
+ const refusal = waitDeadlineFailure({
680
+ cause,
681
+ deadlineMs,
682
+ waitMs: retryAfterMs,
683
+ waitReason: "retry-delay"
684
+ });
685
+ if (refusal === void 0) return;
686
+ const { remainingMs } = refusal;
687
+ return new RetryDelayExceededError(`Retry delay would wait ${retryAfterMs / 1e3}s; ${remainingMs / 1e3}s remain before the request deadline`, {
688
+ cause,
689
+ deadlineMs,
690
+ remainingMs,
691
+ retryAfterMs
692
+ });
693
+ }
694
+ function guidedWaitRefusal(cause) {
695
+ return new RateLimitWaitRefusedError(`Rate limit asks for a ${cause.retryAfterSeconds}s wait, longer than the 60s the SDK waits out`, { cause });
696
+ }
697
+ /**
698
+ * Decides what follows a failed attempt. A rate limit carrying a server-guided
699
+ * wait is waited out without spending one of `maxRetries`, unless the wait is
700
+ * longer than {@link MAX_GUIDED_WAIT_SECONDS}, which is refused outright; every
701
+ * other retryable failure spends one.
702
+ *
703
+ * @param err - The failure the attempt returned.
704
+ * @param state - Resolved config, request deadline, and attempts spent so far.
705
+ * @returns The wait to take, a refusal to return instead, or `undefined` to
706
+ * return the failure as is.
707
+ */
708
+ function planRetry(err, { config, deadlineMs, retries }) {
709
+ if (!shouldRetry(err, config)) return;
710
+ const guided = hasGuidedWait(err);
711
+ if (!guided && retries >= config.maxRetries) return;
712
+ if (isRefusedGuidedWait(err)) return { refusal: guidedWaitRefusal(err) };
713
+ const waitMs = computeRetryWaitMs(err, {
714
+ attempt: retries,
715
+ retryDelay: config.retryDelay
716
+ });
717
+ const refusal = retryRefusal({
718
+ cause: err,
719
+ deadlineMs,
720
+ retryAfterMs: waitMs
721
+ });
722
+ return refusal === void 0 ? {
723
+ spendsAttempt: !guided,
724
+ waitMs
725
+ } : { refusal };
726
+ }
727
+ async function waitForRetryAsync(waitMs, { admissionWaitObserver, signal, sleep }) {
728
+ return observeAdmissionWaitAsync({
729
+ durationMs: waitMs,
730
+ observer: admissionWaitObserver,
731
+ reason: "retry-delay",
732
+ waitAsync: async () => raceWithAbortAsync(async () => sleep(waitMs, signal), signal)
733
+ });
734
+ }
735
+ function announceRetry({ attempt, error, hooks, waitMs }) {
736
+ hooks.onRetry?.(attempt, error);
737
+ hooks.onRateLimit?.(waitMs);
738
+ }
739
+ function abortedResult(signal) {
740
+ return {
741
+ err: requestAbortedError(signal),
742
+ success: false
743
+ };
744
+ }
745
+ async function attemptAsync(request, { hooks, send, signal }) {
746
+ hooks.onRequest?.(request);
747
+ const attempt = await raceWithAbortAsync(async () => send(request), signal);
748
+ return attempt === ABORTED ? abortedResult(signal) : attempt;
749
+ }
750
+ //#endregion
751
+ //#region src/internal/http/rate-limit-observation.ts
752
+ /**
753
+ * Extracts a {@link RateLimitSample} from a transport result so the budget
754
+ * gate can be fed from every attempt. A 2xx carries the budget in its headers.
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
759
+ * the window capacity its `x-ratelimit-limit` header reports. Any other error
760
+ * yields `undefined`.
761
+ *
762
+ * @param result - The classified transport result for one attempt.
763
+ * @returns The parsed sample, or `undefined` when none was reported.
764
+ */
765
+ function rateLimitSampleFromResult(result) {
766
+ if (result.success) return parseRateLimitHeaders(result.data.headers);
767
+ const { err } = result;
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);
799
+ }
800
+ //#endregion
801
+ //#region src/internal/http/rate-limit-queue.ts
802
+ const OPERATION_QUEUE_REASON = "operation-queue";
803
+ /**
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`.
808
+ *
809
+ * Implemented as a leaky bucket tracking drain debt in ms. `#lastCheck`
810
+ * advances by `waitMs` after every sleep so the algorithm stays correct
811
+ * whether or not the injected sleep moves `Date.now()` forward. `#bucketLevel`
812
+ * and `#maxBucketLevel` are both ms of drain debt, so the ceiling is the burst
813
+ * expressed in that unit: `burstCapacity` refill intervals. Deriving it any
814
+ * other way (notably `maxPerSecond * intervalMs`, whose units cancel to a
815
+ * constant 1000) starves every operation slower than one request per second.
816
+ */
817
+ var RateLimitQueue = class {
818
+ #hooks;
819
+ #intervalMs;
820
+ #maxBucketLevel;
821
+ #sleep;
822
+ #bucketLevel = 0;
823
+ #chain = Promise.resolve();
824
+ #lastCheck = Date.now();
825
+ #pendingAcquisitions = 0;
826
+ /**
827
+ * Creates a rate-limit queue bound to a single operation.
828
+ *
829
+ * @param limit - The operation key and its per-second request ceiling.
830
+ * @param hooks - Observability callbacks; `onRateLimit` fires when the
831
+ * bucket is empty and a sleep is about to start.
832
+ * @param sleep - Injectable sleep (tests pass a fake).
833
+ */
834
+ constructor(limit, hooks, sleep) {
835
+ this.#intervalMs = 1e3 / limit.maxPerSecond;
836
+ this.#maxBucketLevel = documentedWindow(limit).capacity * this.#intervalMs;
837
+ this.#hooks = hooks;
838
+ this.#sleep = sleep;
839
+ }
840
+ /**
841
+ * Waits for a token — sleeping and firing `hooks.onRateLimit` if the
842
+ * bucket is empty — then executes `task`. Concurrent callers are
843
+ * serialized at token acquisition; tasks themselves run independently
844
+ * once their token is secured.
845
+ *
846
+ * @param task - The request to run once a token is available.
847
+ * @param context - Request-local observer and cancellation signal.
848
+ * @returns The value produced by `task`.
849
+ * @rejects {@link RequestAbortedError} when the caller cancels while queued.
850
+ */
851
+ async acquireAsync(task, { deadlineMs, observer, signal } = {}) {
852
+ const waitsForEarlierAcquisition = this.#pendingAcquisitions > 0;
853
+ this.#pendingAcquisitions++;
854
+ const waitForTokenAsync = async () => {
855
+ return this.#waitForToken({
856
+ deadlineMs,
857
+ observer: waitsForEarlierAcquisition ? void 0 : observer,
858
+ signal
859
+ });
860
+ };
861
+ const completed = this.#chain.catch(ignoreRejection).then(waitForTokenAsync).finally(() => {
862
+ this.#pendingAcquisitions--;
863
+ });
864
+ this.#chain = completed.catch(ignoreRejection);
865
+ if (waitsForEarlierAcquisition) await observeAdmissionWaitAsync({
866
+ observer,
867
+ reason: OPERATION_QUEUE_REASON,
868
+ waitAsync: async () => waitForTurnAsync(completed, signal)
869
+ });
870
+ else await waitForTurnAsync(completed, signal);
871
+ return task();
872
+ }
873
+ async #waitAsync({ deadlineMs, now, observer, signal, waitMs }) {
874
+ const refusal = waitDeadlineFailure({
875
+ deadlineMs,
876
+ waitMs,
877
+ waitReason: OPERATION_QUEUE_REASON
878
+ });
879
+ if (refusal !== void 0) throw refusal;
880
+ this.#hooks.onRateLimit?.(waitMs);
881
+ await observeAdmissionWaitAsync({
882
+ durationMs: waitMs,
883
+ observer,
884
+ reason: OPERATION_QUEUE_REASON,
885
+ waitAsync: async () => {
886
+ if (await raceWithAbortAsync(async () => this.#sleep(waitMs, signal), signal) === ABORTED) throw requestAbortedError(signal);
887
+ }
888
+ });
889
+ this.#bucketLevel = this.#maxBucketLevel;
890
+ this.#lastCheck = now + waitMs;
891
+ }
892
+ async #waitForToken({ deadlineMs, observer, signal }) {
893
+ if (signal?.aborted === true) throw requestAbortedError(signal);
894
+ const now = Math.max(Date.now(), this.#lastCheck);
895
+ const drained = Math.max(0, this.#bucketLevel - (now - this.#lastCheck));
896
+ this.#lastCheck = now;
897
+ if (drained + this.#intervalMs <= this.#maxBucketLevel) {
898
+ this.#bucketLevel = drained + this.#intervalMs;
899
+ return;
900
+ }
901
+ const waitMs = drained + this.#intervalMs - this.#maxBucketLevel;
902
+ await this.#waitAsync({
903
+ deadlineMs,
904
+ now,
905
+ observer,
906
+ signal,
907
+ waitMs
908
+ });
909
+ }
910
+ };
911
+ /**
912
+ * Expresses an operation's documented limit as a fixed window: its burst
913
+ * capacity, granted once per the time the sustained rate takes to refill it.
914
+ *
915
+ * @param limit - The operation's documented rate limit.
916
+ * @returns The capacity granted per window and the window's length.
917
+ */
918
+ function documentedWindow(limit) {
919
+ const capacity = limit.burstCapacity ?? Math.max(1, limit.maxPerSecond);
920
+ return {
921
+ capacity,
922
+ windowSeconds: capacity / limit.maxPerSecond
923
+ };
924
+ }
925
+ function ignoreRejection() {}
926
+ async function waitForTurnAsync(turn, signal) {
927
+ if (await raceWithAbortAsync(async () => turn, signal) === ABORTED) throw requestAbortedError(signal);
928
+ }
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
953
+ //#region src/internal/utils/sleep.ts
954
+ /**
955
+ * Timer-backed production sleep that releases its timer on cancellation.
956
+ *
957
+ * @param ms - Duration to wait in milliseconds.
958
+ * @param signal - Optional caller cancellation signal.
959
+ */
960
+ async function defaultSleepAsync(ms, signal) {
961
+ await setTimeout(ms, void 0, { signal });
962
+ }
963
+ //#endregion
964
+ //#region src/internal/http/resolve-dependencies.ts
965
+ /**
966
+ * Resolves the concrete HTTP client and sleep implementation a resource
967
+ * client should use. Falls back to the fetch-backed HTTP client and the
968
+ * default `setTimeout`-based sleep when the caller omits the test seams.
969
+ *
970
+ * Extracted so resource client constructors can keep their dependency
971
+ * resolution logic in a single, unit-testable place; this makes the
972
+ * default branches easy to cover without stubbing globals like `fetch`.
973
+ *
974
+ * @param options - Optional {@link HttpClient} and {@link SleepFunc} test seams.
975
+ * @returns A {@link ResolvedDependencies} with defaults applied.
976
+ */
977
+ function resolveDependencies(options) {
978
+ return {
979
+ httpClient: options.httpClient ?? createFetchHttpClient(),
980
+ sleep: options.sleep ?? defaultSleepAsync
981
+ };
982
+ }
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
1161
+ //#region src/internal/resource-client.ts
1162
+ /**
1163
+ * Wraps an infallible request build as a {@link Result}-returning
1164
+ * `buildRequest` callback compatible with {@link ResourceMethodSpec}.
1165
+ * Use from a resource client whose builder cannot fail; resource clients
1166
+ * with local validation should construct the {@link Result} directly.
1167
+ *
1168
+ * @param request - The pre-built {@link HttpRequest}.
1169
+ * @returns A success Result wrapping the request.
1170
+ */
1171
+ function okRequest(request) {
1172
+ return {
1173
+ data: request,
1174
+ success: true
1175
+ };
1176
+ }
1177
+ /**
1178
+ * A {@link ResourceMethodSpec.parse} implementation for endpoints that return
1179
+ * no business payload on success (such as `DELETE` and reorder operations).
1180
+ * Surfaces `undefined` data and never inspects the response body.
1181
+ *
1182
+ * @returns A success Result with `undefined` data.
1183
+ */
1184
+ function parseEmptyResponse() {
1185
+ return {
1186
+ data: void 0,
1187
+ success: true
1188
+ };
1189
+ }
1190
+ const CLIENT_DEFAULTS = Object.freeze({
1191
+ baseUrl: "https://apis.roblox.com",
1192
+ maxRetries: 3,
1193
+ retryableStatuses: IDEMPOTENT_METHOD_DEFAULTS.retryableStatuses,
1194
+ retryableTransportCodes: IDEMPOTENT_METHOD_DEFAULTS.retryableTransportCodes,
1195
+ retryDelay: defaultRetryDelay,
1196
+ timeout: 3e4
1197
+ });
1198
+ /**
1199
+ * Internal orchestrator shared by every Open Cloud resource client. Holds
1200
+ * the frozen client config, observability hooks, injected HTTP client and
1201
+ * sleep, and the per-effective-key rate-limit queue registry. Resource
1202
+ * classes compose one instance and dispatch every public method through
1203
+ * {@link ResourceClient.executeAsync} with a per-method {@link ResourceMethodSpec}.
1204
+ * Not exported from any package subpath; reachable only via sibling
1205
+ * `src/resources/**` modules in this package.
1206
+ */
1207
+ var ResourceClient = class {
1208
+ #budgets;
1209
+ #config;
1210
+ #hooks;
1211
+ #httpClient;
1212
+ #queues = /* @__PURE__ */ new Map();
1213
+ #reportHint;
1214
+ #sleep;
1215
+ /**
1216
+ * Creates a new {@link ResourceClient}. Resolves the injected HTTP
1217
+ * client and sleep (defaulting to fetch + `setTimeout`) and freezes the
1218
+ * merged client config so subsequent calls cannot mutate it.
1219
+ *
1220
+ * @param options - Client-level configuration including the credential
1221
+ * and optional construction-time test seams.
1222
+ */
1223
+ constructor({ hooks, httpClient, reportHint, sleep, ...overrides }) {
1224
+ const resolved = resolveDependencies({
1225
+ httpClient,
1226
+ sleep
1227
+ });
1228
+ this.#httpClient = resolved.httpClient;
1229
+ this.#sleep = resolved.sleep;
1230
+ this.#budgets = new BudgetGate(this.#sleep);
1231
+ this.#hooks = hooks ?? {};
1232
+ this.#reportHint = reportHint ?? true;
1233
+ this.#config = Object.freeze({
1234
+ ...CLIENT_DEFAULTS,
1235
+ ...overrides,
1236
+ credential: snapshotCredential(overrides.credential)
1237
+ });
1238
+ }
1239
+ /**
1240
+ * Dispatches a single resource-method call. Merges the frozen client
1241
+ * config with the method's `methodDefaults` and the caller's optional
1242
+ * per-request `options`, routes through the effective-credential rate-limit
1243
+ * queue, runs the retry loop, and finally parses the response with the
1244
+ * spec's parser.
1245
+ *
1246
+ * @param call - The per-method spec, resource-specific parameters, and
1247
+ * optional per-request overrides.
1248
+ * @returns The parsed success payload or the {@link OpenCloudError} that
1249
+ * caused the request to fail. Never throws.
1250
+ * @rejects An unexpected collaborator failure unrelated to caller cancellation.
1251
+ */
1252
+ async executeAsync({ exemptsLockout, options, parameters, refineError, spec }) {
1253
+ const start = startRequest(options);
1254
+ if (!start.success) return start;
1255
+ const { admission, lifecycle, requestOptions } = start.data;
1256
+ const { credential, merged } = authenticateCall(this.#merge(spec, requestOptions), spec);
1257
+ const requestResult = credentialNotSupportedFailure(spec, merged.credential) ?? spec.buildRequest(parameters);
1258
+ if (!requestResult.success) return requestResult;
1259
+ const request = requestResult.data;
1260
+ const { signal } = admission;
1261
+ const requestConfig = buildRequestConfig({
1262
+ merged,
1263
+ options,
1264
+ request,
1265
+ signal
1266
+ });
1267
+ return finishRequest({
1268
+ httpResult: await this.#dispatchAsync({
1269
+ admission,
1270
+ credential,
1271
+ exemptsLockout,
1272
+ merged,
1273
+ operationLimit: spec.operationLimit,
1274
+ refineError,
1275
+ request,
1276
+ requestConfig
1277
+ }),
1278
+ lifecycle,
1279
+ merged,
1280
+ request,
1281
+ spec
1282
+ }, this.#reportHint);
1283
+ }
1284
+ /**
1285
+ * Returns the sleep function used by this client instance.
1286
+ *
1287
+ * @returns The sleep function injected at construction time.
1288
+ */
1289
+ get sleep() {
1290
+ return this.#sleep;
1291
+ }
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);
1296
+ try {
1297
+ this.#budgets.refuseDuringLockout(scope);
1298
+ return await queue.acquireAsync(async () => {
1299
+ return executeWithRetryAsync(request, {
1300
+ admissionWaitObserver: admission.observer,
1301
+ config: merged,
1302
+ deadlineMs: admission.deadlineMs,
1303
+ hooks: this.#hooks,
1304
+ send: this.#gatedSend({
1305
+ admission,
1306
+ credential,
1307
+ exemptsLockout,
1308
+ refineError,
1309
+ requestConfig,
1310
+ scope
1311
+ }),
1312
+ signal: admission.signal,
1313
+ sleep: this.#sleep
1314
+ });
1315
+ }, admission);
1316
+ } catch (err) {
1317
+ return dispatchFailure(err);
1318
+ }
1319
+ }
1320
+ /**
1321
+ * Builds the transport callback for one logical call, wrapping the HTTP
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.
1328
+ *
1329
+ * @param inputs - Budget scope, transport config, observer, and caller signal.
1330
+ * @returns A send callback for {@link executeWithRetryAsync}.
1331
+ */
1332
+ #gatedSend({ admission, credential, exemptsLockout, refineError, requestConfig, scope }) {
1333
+ return async (toSend) => {
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
+ }),
1350
+ success: false
1351
+ };
1352
+ observeAttempt(this.#budgets, {
1353
+ exemptsLockout,
1354
+ scope,
1355
+ transportResult
1356
+ });
1357
+ return sendResult;
1358
+ };
1359
+ }
1360
+ #getQueue(credentialKey, limit) {
1361
+ const key = scopeKey({
1362
+ credentialKey,
1363
+ operationKey: limit.operationKey
1364
+ });
1365
+ const existing = this.#queues.get(key);
1366
+ if (existing !== void 0) return existing;
1367
+ const queue = new RateLimitQueue(limit, this.#hooks, this.#sleep);
1368
+ this.#queues.set(key, queue);
1369
+ return queue;
1370
+ }
1371
+ #merge(spec, requestOptions) {
1372
+ return mergeConfig(this.#config, {
1373
+ methodDefaults: spec.methodDefaults,
1374
+ methodKind: spec.methodKind,
1375
+ requestOptions
1376
+ });
1377
+ }
1378
+ };
1379
+ function budgetScopeFor(credentialKey, operationLimit) {
1380
+ return {
1381
+ credentialKey,
1382
+ documentedWindow: documentedWindow(operationLimit),
1383
+ operationKey: operationLimit.operationKey
1384
+ };
1385
+ }
1386
+ function dispatchFailure(err) {
1387
+ if (err instanceof RequestAbortedError || err instanceof RequestDeadlineExceededError || err instanceof RateLimitWaitRefusedError) return {
1388
+ err,
1389
+ success: false
1390
+ };
1391
+ throw err;
1392
+ }
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,
1408
+ operationKey: spec.operationLimit.operationKey,
1409
+ requiredScopes: spec.requiredScopes
1410
+ });
1411
+ return {
1412
+ err: recordPreviousAttempts(err, httpResult.err.previousAttempts),
1413
+ success: false
1414
+ };
1415
+ }
1416
+ //#endregion
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 };
1418
+
1419
+ //# sourceMappingURL=resource-client-CaIVr-go.mjs.map