@bedrock-rbx/ocale 0.3.0 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (51) hide show
  1. package/dist/badges.d.mts +1 -1
  2. package/dist/badges.mjs +3 -3
  3. package/dist/developer-products.d.mts +1 -1
  4. package/dist/developer-products.mjs +4 -4
  5. package/dist/game-passes.d.mts +1 -1
  6. package/dist/game-passes.mjs +4 -4
  7. package/dist/index.d.mts +108 -3
  8. package/dist/index.d.mts.map +1 -1
  9. package/dist/index.mjs +70 -5
  10. package/dist/index.mjs.map +1 -0
  11. package/dist/luau-execution.d.mts +2 -2
  12. package/dist/luau-execution.mjs +4 -4
  13. package/dist/{rate-limit-Df55K34f.mjs → network-error-DmNy_j-u.mjs} +50 -30
  14. package/dist/network-error-DmNy_j-u.mjs.map +1 -0
  15. package/dist/places.d.mts +2 -2
  16. package/dist/places.mjs +5 -5
  17. package/dist/{poll-timeout-DpEY-gAc.mjs → poll-timeout-wrPTnGl_.mjs} +2 -2
  18. package/dist/{poll-timeout-DpEY-gAc.mjs.map → poll-timeout-wrPTnGl_.mjs.map} +1 -1
  19. package/dist/{polling-Bs0GDvEa.d.mts → polling-0t1wQyVY.d.mts} +20 -13
  20. package/dist/polling-0t1wQyVY.d.mts.map +1 -0
  21. package/dist/{polling-helpers-BjFXyaOm.mjs → polling-helpers-CzdT2FS5.mjs} +32 -52
  22. package/dist/polling-helpers-CzdT2FS5.mjs.map +1 -0
  23. package/dist/{price-information-Brs8ebsh.mjs → price-information-Czs5cWR1.mjs} +2 -2
  24. package/dist/{price-information-Brs8ebsh.mjs.map → price-information-Czs5cWR1.mjs.map} +1 -1
  25. package/dist/resource-client-aqk_V4TD.mjs +717 -0
  26. package/dist/resource-client-aqk_V4TD.mjs.map +1 -0
  27. package/dist/{retry-CdpA3z4A.d.mts → retry-Cj5OXCdL.d.mts} +5 -5
  28. package/dist/{retry-CdpA3z4A.d.mts.map → retry-Cj5OXCdL.d.mts.map} +1 -1
  29. package/dist/retry-DIK_T_oF.mjs +1322 -0
  30. package/dist/retry-DIK_T_oF.mjs.map +1 -0
  31. package/dist/storage.d.mts +3 -2
  32. package/dist/storage.d.mts.map +1 -1
  33. package/dist/storage.mjs +3 -3
  34. package/dist/testing.d.mts +9 -17
  35. package/dist/testing.d.mts.map +1 -1
  36. package/dist/testing.mjs +1 -1
  37. package/dist/{types-mhEalVsR.d.mts → types-D_njb3qW.d.mts} +74 -4
  38. package/dist/types-D_njb3qW.d.mts.map +1 -0
  39. package/dist/universes.d.mts +1 -1
  40. package/dist/universes.mjs +4 -4
  41. package/dist/{validation-Cg2lBhpQ.mjs → validation-BwjwOJPD.mjs} +2 -2
  42. package/dist/{validation-Cg2lBhpQ.mjs.map → validation-BwjwOJPD.mjs.map} +1 -1
  43. package/package.json +1 -1
  44. package/dist/polling-Bs0GDvEa.d.mts.map +0 -1
  45. package/dist/polling-helpers-BjFXyaOm.mjs.map +0 -1
  46. package/dist/rate-limit-Df55K34f.mjs.map +0 -1
  47. package/dist/resource-client-DtfDWglY.mjs +0 -1177
  48. package/dist/resource-client-DtfDWglY.mjs.map +0 -1
  49. package/dist/retry-DM2-tlR8.mjs +0 -458
  50. package/dist/retry-DM2-tlR8.mjs.map +0 -1
  51. package/dist/types-mhEalVsR.d.mts.map +0 -1
@@ -0,0 +1,717 @@
1
+ import { a as ApiError, n as RateLimitError, o as requestContextOf, r as hasServerRetryGuidance } from "./network-error-DmNy_j-u.mjs";
2
+ import { _ as requestAbortedError, c as defaultRetryDelay, f as PermissionError, g as raceWithAbortAsync, h as ABORTED, l as mergeConfig, m as isUploadRequest, p as createFetchHttpClient, r as IDEMPOTENT_METHOD_DEFAULTS, s as computeRetryWaitMs, u as shouldRetry, v as RequestAbortedError, y as parseRateLimitHeaders } from "./retry-DIK_T_oF.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/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
+ //#region src/internal/utils/to-json-details.ts
36
+ /**
37
+ * Narrows an untyped response body to the `JSONValue` accepted by
38
+ * `ApiError.details`. `HttpResponse.body` is `unknown` because a transport may
39
+ * hand back anything, but only a JSON graph is safe to retain on an error for
40
+ * diagnostics. Anything else — functions, symbols, bigints, class instances,
41
+ * or a cyclic graph — is dropped rather than asserted through.
42
+ *
43
+ * @param value - The parsed response body, or `undefined` for an empty body.
44
+ * @returns The value as a `JSONValue`, or `undefined` when it is absent or not
45
+ * JSON-representable.
46
+ */
47
+ function toJsonDetails(value) {
48
+ return asJsonValue(value, /* @__PURE__ */ new Set());
49
+ }
50
+ function asJsonValue(value, seen) {
51
+ if (value === null) return null;
52
+ if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") return value;
53
+ if (Array.isArray(value)) return asJsonArray(value, seen);
54
+ if (isRecord(value)) return asJsonObject(value, seen);
55
+ }
56
+ function asJsonArray(value, seen) {
57
+ if (seen.has(value)) return;
58
+ seen.add(value);
59
+ const items = [];
60
+ for (const item of value) {
61
+ const converted = asJsonValue(item, seen);
62
+ if (converted === void 0) return;
63
+ items.push(converted);
64
+ }
65
+ seen.delete(value);
66
+ return items;
67
+ }
68
+ function asJsonObject(value, seen) {
69
+ if (seen.has(value)) return;
70
+ seen.add(value);
71
+ const entries = [];
72
+ for (const [key, item] of Object.entries(value)) {
73
+ const converted = asJsonValue(item, seen);
74
+ if (converted === void 0) return;
75
+ entries.push([key, converted]);
76
+ }
77
+ seen.delete(value);
78
+ return Object.fromEntries(entries);
79
+ }
80
+ //#endregion
81
+ //#region src/internal/http/admission-wait.ts
82
+ /**
83
+ * Performs one SDK-managed wait and emits a balanced request-scoped lifecycle.
84
+ * Observer failures are deliberately ignored: observation cannot become part
85
+ * of admission control.
86
+ *
87
+ * @template T - Value produced by the observed wait.
88
+ * @param options - Wait metadata, observer, and the wait operation itself.
89
+ * @returns The value produced by the wait.
90
+ */
91
+ async function observeAdmissionWaitAsync({ durationMs, observer, reason, waitAsync }) {
92
+ const details = {
93
+ ...durationMs === void 0 ? {} : { durationMs },
94
+ reason
95
+ };
96
+ notify(observer, {
97
+ ...details,
98
+ phase: "started"
99
+ });
100
+ try {
101
+ return await waitAsync();
102
+ } finally {
103
+ notify(observer, {
104
+ ...details,
105
+ phase: "ended"
106
+ });
107
+ }
108
+ }
109
+ function notify(observer, event) {
110
+ try {
111
+ const notification = observer?.(event);
112
+ if (notification !== void 0) Promise.resolve(notification).catch(Boolean);
113
+ } catch {}
114
+ }
115
+ //#endregion
116
+ //#region src/internal/http/budget-tracker.ts
117
+ const MS_PER_SECOND = 1e3;
118
+ /**
119
+ * Tracks the live rate-limit budget for a single scope. Primed by `observe`
120
+ * from response headers and drawn down by `reserve` as requests leave, so
121
+ * `waitMs` can pace requests across the window.
122
+ *
123
+ * Pacing has two regimes. While budget remains, requests are spread evenly over
124
+ * the time left in the window (`timeLeft / remaining`), so a burst does not
125
+ * spend the whole window's budget up front and then stall. Once the budget is
126
+ * spent, requests hold until the window resets. Budget and reset time move
127
+ * together as one window, so the tracker is either unprimed or fully primed,
128
+ * never half-known.
129
+ */
130
+ var BudgetTracker = class {
131
+ /** Time (ms) the most recent request was allowed out, for spacing. */
132
+ #lastAllowedAt = void 0;
133
+ #window = void 0;
134
+ /**
135
+ * Folds a fresh server reading in, replacing any prior window. The latest
136
+ * reading wins: observe time is monotonic, so the most recently resolved
137
+ * response is the best current estimate. The spacing reference is left
138
+ * untouched so a window refresh does not reset pacing mid-stream.
139
+ *
140
+ * @param sample - Parsed `remaining`/`resetSeconds` from a response.
141
+ * @param now - The current time in ms.
142
+ */
143
+ observe(sample, now) {
144
+ this.#window = {
145
+ predictedRemaining: sample.remaining,
146
+ resetAt: now + sample.resetSeconds * MS_PER_SECOND
147
+ };
148
+ }
149
+ /**
150
+ * Accounts for one request leaving at `now`: records the spacing reference
151
+ * and decrements the prediction. A no-op on the prediction while unprimed.
152
+ *
153
+ * @param now - The time the request was allowed out, in ms.
154
+ */
155
+ reserve(now) {
156
+ this.#lastAllowedAt = now;
157
+ if (this.#window !== void 0) this.#window = {
158
+ ...this.#window,
159
+ predictedRemaining: this.#window.predictedRemaining - 1
160
+ };
161
+ }
162
+ /**
163
+ * Milliseconds to wait before the next request is allowed.
164
+ *
165
+ * @param now - The current time in ms.
166
+ * @returns `0` when a request may go now (unprimed, or the first paced send);
167
+ * the time until reset when the budget is spent; otherwise the time until
168
+ * this request's evenly-spaced slot.
169
+ */
170
+ waitMs(now) {
171
+ if (this.#window === void 0) return 0;
172
+ const { predictedRemaining, resetAt } = this.#window;
173
+ if (predictedRemaining <= 0) return Math.max(0, resetAt - now);
174
+ if (this.#lastAllowedAt === void 0) return 0;
175
+ const interval = (resetAt - now) / predictedRemaining;
176
+ return Math.max(0, this.#lastAllowedAt + interval - now);
177
+ }
178
+ };
179
+ //#endregion
180
+ //#region src/internal/http/budget-gate.ts
181
+ /**
182
+ * Header-primed rate-limit gate shared across a client. Holds one
183
+ * {@link BudgetTracker} per {@link BudgetScope}. Before each request the caller
184
+ * gates on the request's scope (sleeping if that budget is spent), and after
185
+ * each response folds the parsed sample back in, so a later call on the same
186
+ * scope can head off a 429 the static per-operation token bucket cannot
187
+ * foresee.
188
+ *
189
+ * Gating is serialized per scope through a promise chain so concurrent
190
+ * requests on one scope cannot read the same budget and reserve the same slot;
191
+ * each waits for the prior gate's reserve before computing its own.
192
+ */
193
+ var BudgetGate = class {
194
+ #chains = /* @__PURE__ */ new Map();
195
+ #pendingGates = /* @__PURE__ */ new Map();
196
+ #sleep;
197
+ #trackers = /* @__PURE__ */ new Map();
198
+ /**
199
+ * Creates a gate bound to an injectable sleep.
200
+ *
201
+ * @param sleep - Injectable sleep (tests pass a fake clock).
202
+ */
203
+ constructor(sleep) {
204
+ this.#sleep = sleep;
205
+ }
206
+ /**
207
+ * Holds until the scope's budget permits a send, then reserves one slot.
208
+ * Runs after the prior gate on the same scope settles, whether it resolved
209
+ * or rejected, so one failed attempt cannot poison later gates on the
210
+ * scope.
211
+ *
212
+ * @param scope - The API key and operation to gate on.
213
+ * @param context - Request-local observer and cancellation signal.
214
+ * @rejects {@link RequestAbortedError} when the caller cancels while waiting.
215
+ */
216
+ async gateAsync(scope, { observer, signal } = {}) {
217
+ const key = scopeKey(scope);
218
+ const pendingGates = this.#pendingGates.get(key) ?? 0;
219
+ const waitsForEarlierGate = pendingGates > 0;
220
+ this.#pendingGates.set(key, pendingGates + 1);
221
+ const completed = (this.#chains.get(key) ?? Promise.resolve()).catch(ignoreRejection$1).then(async () => {
222
+ return this.#gateOnce(key, {
223
+ observer: waitsForEarlierGate ? void 0 : observer,
224
+ signal
225
+ });
226
+ }).finally(() => {
227
+ const remainingGates = (this.#pendingGates.get(key) ?? 1) - 1;
228
+ this.#pendingGates.set(key, remainingGates);
229
+ });
230
+ this.#chains.set(key, completed.catch(ignoreRejection$1));
231
+ if (waitsForEarlierGate) await observeAdmissionWaitAsync({
232
+ observer,
233
+ reason: "reported-budget",
234
+ waitAsync: async () => waitForGateAsync(completed, signal)
235
+ });
236
+ else await waitForGateAsync(completed, signal);
237
+ }
238
+ /**
239
+ * Folds a response's parsed budget back onto the scope. A `undefined`
240
+ * sample (headers absent or non-numeric) is ignored, leaving the scope on
241
+ * static pacing.
242
+ *
243
+ * @param scope - The same scope passed to {@link gateAsync}.
244
+ * @param sample - Parsed sample, or `undefined` when none was reported.
245
+ */
246
+ observe(scope, sample) {
247
+ if (sample === void 0) return;
248
+ this.#tracker(scopeKey(scope)).observe(sample, Date.now());
249
+ }
250
+ async #gateOnce(key, { observer, signal }) {
251
+ if (signal?.aborted === true) throw requestAbortedError(signal);
252
+ const tracker = this.#tracker(key);
253
+ const waitMs = tracker.waitMs(Date.now());
254
+ if (waitMs > 0) await observeAdmissionWaitAsync({
255
+ durationMs: waitMs,
256
+ observer,
257
+ reason: "reported-budget",
258
+ waitAsync: async () => {
259
+ if (await raceWithAbortAsync(async () => this.#sleep(waitMs, signal), signal) === ABORTED) throw requestAbortedError(signal);
260
+ }
261
+ });
262
+ tracker.reserve(Date.now());
263
+ }
264
+ #tracker(key) {
265
+ const existing = this.#trackers.get(key);
266
+ if (existing !== void 0) return existing;
267
+ const tracker = new BudgetTracker();
268
+ this.#trackers.set(key, tracker);
269
+ return tracker;
270
+ }
271
+ };
272
+ function ignoreRejection$1() {}
273
+ async function waitForGateAsync(gate, signal) {
274
+ if (await raceWithAbortAsync(async () => gate, signal) === ABORTED) throw requestAbortedError(signal);
275
+ }
276
+ /**
277
+ * Composes the map key one budget window is tracked under.
278
+ *
279
+ * @param scope - The API key and operation naming the window.
280
+ * @returns The key for the tracker and chain maps.
281
+ */
282
+ function scopeKey({ apiKey, operationKey }) {
283
+ return `${apiKey}::${operationKey}`;
284
+ }
285
+ //#endregion
286
+ //#region src/internal/http/execute.ts
287
+ /**
288
+ * Retry-aware orchestration loop. Coordinates a single logical request,
289
+ * looping over `options.send` until it succeeds, the error is non-retryable,
290
+ * or `options.config.maxRetries` is exhausted. Fires observability hooks
291
+ * at each transition. Domain- and queue-agnostic: `send` may be any
292
+ * callback, including one wrapped by a rate-limit queue.
293
+ *
294
+ * @param request - The immutable request to send.
295
+ * @param options - The transport callback, resolved config, hooks, and sleep.
296
+ * @returns The first success, or the final error after retries are exhausted.
297
+ */
298
+ async function executeWithRetryAsync(request, options) {
299
+ const { admissionWaitObserver, config, hooks, signal, sleep } = options;
300
+ if (signal?.aborted === true) return abortedResult(signal);
301
+ let result = await attemptAsync(request, options);
302
+ for (let retry = 0; retry < config.maxRetries; retry++) {
303
+ if (result.success || !shouldRetry(result.err, config)) return result;
304
+ const { err } = result;
305
+ hooks.onRetry?.(retry + 1, err);
306
+ const waitMs = computeRetryWaitMs(err, {
307
+ attempt: retry,
308
+ retryDelay: config.retryDelay
309
+ });
310
+ hooks.onRateLimit?.(waitMs);
311
+ if (await observeAdmissionWaitAsync({
312
+ durationMs: waitMs,
313
+ observer: admissionWaitObserver,
314
+ reason: "retry-delay",
315
+ waitAsync: async () => raceWithAbortAsync(async () => sleep(waitMs, signal), signal)
316
+ }) === ABORTED) return abortedResult(signal);
317
+ result = await attemptAsync(request, options);
318
+ }
319
+ return result;
320
+ }
321
+ function abortedResult(signal) {
322
+ return {
323
+ err: requestAbortedError(signal),
324
+ success: false
325
+ };
326
+ }
327
+ async function attemptAsync(request, { hooks, send, signal }) {
328
+ hooks.onRequest?.(request);
329
+ const attempt = await raceWithAbortAsync(async () => send(request), signal);
330
+ return attempt === ABORTED ? abortedResult(signal) : attempt;
331
+ }
332
+ //#endregion
333
+ //#region src/internal/http/rate-limit-observation.ts
334
+ /**
335
+ * Extracts a {@link RateLimitSample} from a transport result so the budget gate
336
+ * can be fed from every attempt. A 2xx carries the budget in its headers. A 429
337
+ * only primes the gate when it reports an exhausted quota and valid guidance;
338
+ * a capacity refusal with requests remaining must not turn its unrelated quota
339
+ * reset into a budget wait. Any other error yields `undefined`.
340
+ *
341
+ * @param result - The classified transport result for one attempt.
342
+ * @returns The parsed sample, or `undefined` when none was reported.
343
+ */
344
+ function rateLimitSampleFromResult(result) {
345
+ if (result.success) return parseRateLimitHeaders(result.data.headers);
346
+ const { err } = result;
347
+ if (err instanceof RateLimitError && err.remaining === 0 && hasServerRetryGuidance(err)) return {
348
+ remaining: err.remaining,
349
+ resetSeconds: err.retryAfterSeconds
350
+ };
351
+ }
352
+ //#endregion
353
+ //#region src/internal/http/rate-limit-queue.ts
354
+ /**
355
+ * Token-bucket rate limiter for a single `(apiKey, operation)` pair. Every
356
+ * call to `acquire` consumes one token; when the bucket is empty the call
357
+ * waits until a token regenerates before invoking the task. Tokens refill at
358
+ * `maxPerSecond` per second, up to the operation's `burstCapacity`.
359
+ *
360
+ * Implemented as a leaky bucket tracking drain debt in ms. `#lastCheck`
361
+ * advances by `waitMs` after every sleep so the algorithm stays correct
362
+ * whether or not the injected sleep moves `Date.now()` forward. `#bucketLevel`
363
+ * and `#maxBucketLevel` are both ms of drain debt, so the ceiling is the burst
364
+ * expressed in that unit: `burstCapacity` refill intervals. Deriving it any
365
+ * other way (notably `maxPerSecond * intervalMs`, whose units cancel to a
366
+ * constant 1000) starves every operation slower than one request per second.
367
+ */
368
+ var RateLimitQueue = class {
369
+ #hooks;
370
+ #intervalMs;
371
+ #maxBucketLevel;
372
+ #sleep;
373
+ #bucketLevel = 0;
374
+ #chain = Promise.resolve();
375
+ #lastCheck = Date.now();
376
+ #pendingAcquisitions = 0;
377
+ /**
378
+ * Creates a rate-limit queue bound to a single operation.
379
+ *
380
+ * @param limit - The operation key and its per-second request ceiling.
381
+ * @param hooks - Observability callbacks; `onRateLimit` fires when the
382
+ * bucket is empty and a sleep is about to start.
383
+ * @param sleep - Injectable sleep (tests pass a fake).
384
+ */
385
+ constructor(limit, hooks, sleep) {
386
+ this.#intervalMs = 1e3 / limit.maxPerSecond;
387
+ const burstCapacity = limit.burstCapacity ?? Math.max(1, limit.maxPerSecond);
388
+ this.#maxBucketLevel = burstCapacity * this.#intervalMs;
389
+ this.#hooks = hooks;
390
+ this.#sleep = sleep;
391
+ }
392
+ /**
393
+ * Waits for a token — sleeping and firing `hooks.onRateLimit` if the
394
+ * bucket is empty — then executes `task`. Concurrent callers are
395
+ * serialized at token acquisition; tasks themselves run independently
396
+ * once their token is secured.
397
+ *
398
+ * @param task - The request to run once a token is available.
399
+ * @param context - Request-local observer and cancellation signal.
400
+ * @returns The value produced by `task`.
401
+ * @rejects {@link RequestAbortedError} when the caller cancels while queued.
402
+ */
403
+ async acquireAsync(task, { observer, signal } = {}) {
404
+ const waitsForEarlierAcquisition = this.#pendingAcquisitions > 0;
405
+ this.#pendingAcquisitions++;
406
+ const waitForTokenAsync = async () => {
407
+ return this.#waitForToken({
408
+ observer: waitsForEarlierAcquisition ? void 0 : observer,
409
+ signal
410
+ });
411
+ };
412
+ const completed = this.#chain.catch(ignoreRejection).then(waitForTokenAsync).finally(() => {
413
+ this.#pendingAcquisitions--;
414
+ });
415
+ this.#chain = completed.catch(ignoreRejection);
416
+ if (waitsForEarlierAcquisition) await observeAdmissionWaitAsync({
417
+ observer,
418
+ reason: "operation-queue",
419
+ waitAsync: async () => waitForTurnAsync(completed, signal)
420
+ });
421
+ else await waitForTurnAsync(completed, signal);
422
+ return task();
423
+ }
424
+ async #waitForToken({ observer, signal }) {
425
+ if (signal?.aborted === true) throw requestAbortedError(signal);
426
+ const now = Math.max(Date.now(), this.#lastCheck);
427
+ const drained = Math.max(0, this.#bucketLevel - (now - this.#lastCheck));
428
+ this.#lastCheck = now;
429
+ if (drained + this.#intervalMs <= this.#maxBucketLevel) {
430
+ this.#bucketLevel = drained + this.#intervalMs;
431
+ return;
432
+ }
433
+ const waitMs = drained + this.#intervalMs - this.#maxBucketLevel;
434
+ this.#hooks.onRateLimit?.(waitMs);
435
+ await observeAdmissionWaitAsync({
436
+ durationMs: waitMs,
437
+ observer,
438
+ reason: "operation-queue",
439
+ waitAsync: async () => {
440
+ if (await raceWithAbortAsync(async () => this.#sleep(waitMs, signal), signal) === ABORTED) throw requestAbortedError(signal);
441
+ }
442
+ });
443
+ this.#bucketLevel = this.#maxBucketLevel;
444
+ this.#lastCheck = now + waitMs;
445
+ }
446
+ };
447
+ function ignoreRejection() {}
448
+ async function waitForTurnAsync(turn, signal) {
449
+ if (await raceWithAbortAsync(async () => turn, signal) === ABORTED) throw requestAbortedError(signal);
450
+ }
451
+ //#endregion
452
+ //#region src/internal/utils/sleep.ts
453
+ /**
454
+ * Timer-backed production sleep that releases its timer on cancellation.
455
+ *
456
+ * @param ms - Duration to wait in milliseconds.
457
+ * @param signal - Optional caller cancellation signal.
458
+ */
459
+ async function defaultSleepAsync(ms, signal) {
460
+ await setTimeout(ms, void 0, { signal });
461
+ }
462
+ //#endregion
463
+ //#region src/internal/http/resolve-dependencies.ts
464
+ /**
465
+ * Resolves the concrete HTTP client and sleep implementation a resource
466
+ * client should use. Falls back to the fetch-backed HTTP client and the
467
+ * default `setTimeout`-based sleep when the caller omits the test seams.
468
+ *
469
+ * Extracted so resource client constructors can keep their dependency
470
+ * resolution logic in a single, unit-testable place; this makes the
471
+ * default branches easy to cover without stubbing globals like `fetch`.
472
+ *
473
+ * @param options - Optional {@link HttpClient} and {@link SleepFunc} test seams.
474
+ * @returns A {@link ResolvedDependencies} with defaults applied.
475
+ */
476
+ function resolveDependencies(options) {
477
+ return {
478
+ httpClient: options.httpClient ?? createFetchHttpClient(),
479
+ sleep: options.sleep ?? defaultSleepAsync
480
+ };
481
+ }
482
+ //#endregion
483
+ //#region src/internal/resource-client.ts
484
+ /**
485
+ * Wraps an infallible request build as a {@link Result}-returning
486
+ * `buildRequest` callback compatible with {@link ResourceMethodSpec}.
487
+ * Use from a resource client whose builder cannot fail; resource clients
488
+ * with local validation should construct the {@link Result} directly.
489
+ *
490
+ * @param request - The pre-built {@link HttpRequest}.
491
+ * @returns A success Result wrapping the request.
492
+ */
493
+ function okRequest(request) {
494
+ return {
495
+ data: request,
496
+ success: true
497
+ };
498
+ }
499
+ /**
500
+ * A {@link ResourceMethodSpec.parse} implementation for endpoints that return
501
+ * no business payload on success (such as `DELETE` and reorder operations).
502
+ * Surfaces `undefined` data and never inspects the response body.
503
+ *
504
+ * @returns A success Result with `undefined` data.
505
+ */
506
+ function parseEmptyResponse() {
507
+ return {
508
+ data: void 0,
509
+ success: true
510
+ };
511
+ }
512
+ const CLIENT_DEFAULTS = Object.freeze({
513
+ baseUrl: "https://apis.roblox.com",
514
+ maxRetries: 3,
515
+ retryableStatuses: IDEMPOTENT_METHOD_DEFAULTS.retryableStatuses,
516
+ retryableTransportCodes: IDEMPOTENT_METHOD_DEFAULTS.retryableTransportCodes,
517
+ retryDelay: defaultRetryDelay,
518
+ timeout: 3e4
519
+ });
520
+ /**
521
+ * Internal orchestrator shared by every Open Cloud resource client. Holds
522
+ * the frozen client config, observability hooks, injected HTTP client and
523
+ * sleep, and the per-effective-key rate-limit queue registry. Resource
524
+ * classes compose one instance and dispatch every public method through
525
+ * {@link ResourceClient.executeAsync} with a per-method {@link ResourceMethodSpec}.
526
+ * Not exported from any package subpath; reachable only via sibling
527
+ * `src/resources/**` modules in this package.
528
+ */
529
+ var ResourceClient = class {
530
+ #budgets;
531
+ #config;
532
+ #hooks;
533
+ #httpClient;
534
+ #queues = /* @__PURE__ */ new Map();
535
+ #sleep;
536
+ /**
537
+ * Creates a new {@link ResourceClient}. Resolves the injected HTTP
538
+ * client and sleep (defaulting to fetch + `setTimeout`) and freezes the
539
+ * merged client config so subsequent calls cannot mutate it.
540
+ *
541
+ * @param options - Client-level configuration including the API key
542
+ * and optional construction-time test seams.
543
+ */
544
+ constructor({ apiKey, hooks, httpClient, sleep, ...overrides }) {
545
+ const resolved = resolveDependencies({
546
+ httpClient,
547
+ sleep
548
+ });
549
+ this.#httpClient = resolved.httpClient;
550
+ this.#sleep = resolved.sleep;
551
+ this.#budgets = new BudgetGate(this.#sleep);
552
+ this.#hooks = hooks ?? {};
553
+ this.#config = Object.freeze({
554
+ ...CLIENT_DEFAULTS,
555
+ apiKey,
556
+ ...overrides
557
+ });
558
+ }
559
+ /**
560
+ * Dispatches a single resource-method call. Merges the frozen client
561
+ * config with the method's `methodDefaults` and the caller's optional
562
+ * per-request `options`, routes through the effective-apiKey rate-limit
563
+ * queue, runs the retry loop, and finally parses the response with the
564
+ * spec's parser.
565
+ *
566
+ * @param call - The per-method spec, resource-specific parameters, and
567
+ * optional per-request overrides.
568
+ * @returns The parsed success payload or the {@link OpenCloudError} that
569
+ * caused the request to fail. Never throws.
570
+ * @rejects An unexpected collaborator failure unrelated to caller cancellation.
571
+ */
572
+ async executeAsync({ options, parameters, spec }) {
573
+ const signal = options?.signal;
574
+ if (signal?.aborted === true) return {
575
+ err: requestAbortedError(signal),
576
+ success: false
577
+ };
578
+ const { onAdmissionWait, signal: _signal, ...requestOptions } = options ?? {};
579
+ const merged = mergeConfig(this.#config, {
580
+ methodDefaults: spec.methodDefaults,
581
+ methodKind: spec.methodKind,
582
+ requestOptions
583
+ });
584
+ const requestResult = spec.buildRequest(parameters);
585
+ if (!requestResult.success) return requestResult;
586
+ const request = requestResult.data;
587
+ const requestConfig = buildRequestConfig({
588
+ merged,
589
+ options,
590
+ request
591
+ });
592
+ const httpResult = await this.#dispatchAsync({
593
+ merged,
594
+ observer: onAdmissionWait,
595
+ operationLimit: spec.operationLimit,
596
+ request,
597
+ requestConfig,
598
+ signal
599
+ });
600
+ if (!httpResult.success) return {
601
+ err: enrichPermissionError(httpResult.err, spec),
602
+ success: false
603
+ };
604
+ return spec.parse(httpResult.data);
605
+ }
606
+ /**
607
+ * Returns the sleep function used by this client instance.
608
+ *
609
+ * @returns The sleep function injected at construction time.
610
+ */
611
+ get sleep() {
612
+ return this.#sleep;
613
+ }
614
+ async #dispatchAsync({ merged, observer, operationLimit, request, requestConfig, signal }) {
615
+ const queue = this.#getQueue(merged.apiKey, operationLimit);
616
+ try {
617
+ return await queue.acquireAsync(async () => {
618
+ return executeWithRetryAsync(request, {
619
+ admissionWaitObserver: observer,
620
+ config: merged,
621
+ hooks: this.#hooks,
622
+ send: this.#gatedSend({
623
+ observer,
624
+ requestConfig,
625
+ scope: {
626
+ apiKey: merged.apiKey,
627
+ operationKey: operationLimit.operationKey
628
+ },
629
+ signal
630
+ }),
631
+ signal,
632
+ sleep: this.#sleep
633
+ });
634
+ }, {
635
+ observer,
636
+ signal
637
+ });
638
+ } catch (err) {
639
+ return dispatchFailure(err);
640
+ }
641
+ }
642
+ /**
643
+ * Builds the transport callback for one logical call, wrapping the HTTP
644
+ * client with the budget gate: each attempt waits on the scope's budget
645
+ * before sending, then folds the response's reported budget back in so the
646
+ * next attempt (or a later call on the same scope) can head off a 429.
647
+ *
648
+ * @param inputs - Budget scope, transport config, observer, and caller signal.
649
+ * @returns A send callback for {@link executeWithRetryAsync}.
650
+ */
651
+ #gatedSend({ observer, requestConfig, scope, signal }) {
652
+ return async (toSend) => {
653
+ await this.#budgets.gateAsync(scope, {
654
+ observer,
655
+ signal
656
+ });
657
+ const sendResult = await this.#httpClient.request(toSend, requestConfig);
658
+ this.#budgets.observe(scope, rateLimitSampleFromResult(sendResult));
659
+ return sendResult;
660
+ };
661
+ }
662
+ #getQueue(apiKey, limit) {
663
+ const key = `${apiKey}::${limit.operationKey}`;
664
+ const existing = this.#queues.get(key);
665
+ if (existing !== void 0) return existing;
666
+ const queue = new RateLimitQueue(limit, this.#hooks, this.#sleep);
667
+ this.#queues.set(key, queue);
668
+ return queue;
669
+ }
670
+ };
671
+ function dispatchFailure(err) {
672
+ if (err instanceof RequestAbortedError) return {
673
+ err,
674
+ success: false
675
+ };
676
+ throw err;
677
+ }
678
+ /**
679
+ * Resolves the per-request {@link RequestConfig}. Upload requests
680
+ * ({@link isUploadRequest}) carry no default timeout: a multi-megabyte place
681
+ * file over a slow link is bandwidth-bound, so a client-side deadline only
682
+ * fires spuriously. An explicit `options.timeout` still applies to any
683
+ * request; every non-upload request keeps the merged default.
684
+ *
685
+ * @param inputs - The merged config, the built request, and per-request overrides.
686
+ * @returns The config to hand to the transport, with `timeout` omitted when
687
+ * no client-side deadline should apply.
688
+ */
689
+ function buildRequestConfig({ merged, options, request }) {
690
+ const shouldOmitDefaultTimeout = options?.timeout === void 0 && isUploadRequest(request);
691
+ return {
692
+ apiKey: merged.apiKey,
693
+ baseUrl: merged.baseUrl,
694
+ ...options?.signal === void 0 ? {} : { signal: options.signal },
695
+ ...shouldOmitDefaultTimeout ? {} : { timeout: merged.timeout }
696
+ };
697
+ }
698
+ function enrichPermissionError(err, spec) {
699
+ if (spec.requiredScopes === void 0) return err;
700
+ if (err instanceof PermissionError) return err;
701
+ if (!(err instanceof ApiError)) return err;
702
+ if (err.statusCode !== 401 && err.statusCode !== 403) return err;
703
+ if (err.gatewaySummary !== void 0) return err;
704
+ return new PermissionError(err.message, {
705
+ ...requestContextOf(err),
706
+ cause: err.cause,
707
+ code: err.code,
708
+ details: err.details,
709
+ operationKey: spec.operationLimit.operationKey,
710
+ requiredScopes: spec.requiredScopes,
711
+ statusCode: err.statusCode
712
+ });
713
+ }
714
+ //#endregion
715
+ export { isRecord as a, toJsonDetails as i, okRequest as n, isDateTimeString as o, parseEmptyResponse as r, ResourceClient as t };
716
+
717
+ //# sourceMappingURL=resource-client-aqk_V4TD.mjs.map