@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.
- package/dist/badges.d.mts +1 -1
- package/dist/badges.mjs +3 -3
- package/dist/developer-products.d.mts +1 -1
- package/dist/developer-products.mjs +4 -4
- package/dist/game-passes.d.mts +1 -1
- package/dist/game-passes.mjs +4 -4
- package/dist/index.d.mts +108 -3
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +70 -5
- package/dist/index.mjs.map +1 -0
- package/dist/luau-execution.d.mts +2 -2
- package/dist/luau-execution.mjs +4 -4
- package/dist/{rate-limit-Df55K34f.mjs → network-error-DmNy_j-u.mjs} +50 -30
- package/dist/network-error-DmNy_j-u.mjs.map +1 -0
- package/dist/places.d.mts +2 -2
- package/dist/places.mjs +5 -5
- package/dist/{poll-timeout-DpEY-gAc.mjs → poll-timeout-wrPTnGl_.mjs} +2 -2
- package/dist/{poll-timeout-DpEY-gAc.mjs.map → poll-timeout-wrPTnGl_.mjs.map} +1 -1
- package/dist/{polling-Bs0GDvEa.d.mts → polling-0t1wQyVY.d.mts} +20 -13
- package/dist/polling-0t1wQyVY.d.mts.map +1 -0
- package/dist/{polling-helpers-BjFXyaOm.mjs → polling-helpers-CzdT2FS5.mjs} +32 -52
- package/dist/polling-helpers-CzdT2FS5.mjs.map +1 -0
- package/dist/{price-information-Brs8ebsh.mjs → price-information-Czs5cWR1.mjs} +2 -2
- package/dist/{price-information-Brs8ebsh.mjs.map → price-information-Czs5cWR1.mjs.map} +1 -1
- package/dist/resource-client-aqk_V4TD.mjs +717 -0
- package/dist/resource-client-aqk_V4TD.mjs.map +1 -0
- package/dist/{retry-CdpA3z4A.d.mts → retry-Cj5OXCdL.d.mts} +5 -5
- package/dist/{retry-CdpA3z4A.d.mts.map → retry-Cj5OXCdL.d.mts.map} +1 -1
- package/dist/retry-DIK_T_oF.mjs +1322 -0
- package/dist/retry-DIK_T_oF.mjs.map +1 -0
- package/dist/storage.d.mts +3 -2
- package/dist/storage.d.mts.map +1 -1
- package/dist/storage.mjs +3 -3
- package/dist/testing.d.mts +9 -17
- package/dist/testing.d.mts.map +1 -1
- package/dist/testing.mjs +1 -1
- package/dist/{types-mhEalVsR.d.mts → types-D_njb3qW.d.mts} +74 -4
- package/dist/types-D_njb3qW.d.mts.map +1 -0
- package/dist/universes.d.mts +1 -1
- package/dist/universes.mjs +4 -4
- package/dist/{validation-Cg2lBhpQ.mjs → validation-BwjwOJPD.mjs} +2 -2
- package/dist/{validation-Cg2lBhpQ.mjs.map → validation-BwjwOJPD.mjs.map} +1 -1
- package/package.json +1 -1
- package/dist/polling-Bs0GDvEa.d.mts.map +0 -1
- package/dist/polling-helpers-BjFXyaOm.mjs.map +0 -1
- package/dist/rate-limit-Df55K34f.mjs.map +0 -1
- package/dist/resource-client-DtfDWglY.mjs +0 -1177
- package/dist/resource-client-DtfDWglY.mjs.map +0 -1
- package/dist/retry-DM2-tlR8.mjs +0 -458
- package/dist/retry-DM2-tlR8.mjs.map +0 -1
- package/dist/types-mhEalVsR.d.mts.map +0 -1
|
@@ -0,0 +1,1322 @@
|
|
|
1
|
+
import { a as ApiError, i as markServerRetryGuidance, n as RateLimitError, r as hasServerRetryGuidance, s as OpenCloudError, t as NetworkError } from "./network-error-DmNy_j-u.mjs";
|
|
2
|
+
//#region src/internal/utils/try-catch.ts
|
|
3
|
+
/**
|
|
4
|
+
* Wraps a promise into a {@link Result}, catching rejections.
|
|
5
|
+
*
|
|
6
|
+
* @template T - The resolved value type.
|
|
7
|
+
* @param promise - The promise to wrap.
|
|
8
|
+
* @returns A Result containing the resolved value or the rejection error.
|
|
9
|
+
*/
|
|
10
|
+
async function tryCatchAsync(promise) {
|
|
11
|
+
try {
|
|
12
|
+
return {
|
|
13
|
+
data: await promise,
|
|
14
|
+
success: true
|
|
15
|
+
};
|
|
16
|
+
} catch (err) {
|
|
17
|
+
return {
|
|
18
|
+
err: err instanceof Error ? err : new Error(String(err)),
|
|
19
|
+
success: false
|
|
20
|
+
};
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
//#endregion
|
|
24
|
+
//#region src/internal/http/diagnostics.ts
|
|
25
|
+
const MAX_DETAIL_LENGTH = 500;
|
|
26
|
+
const CONTENT_TYPE_HEADER$1 = "content-type";
|
|
27
|
+
const DIAGNOSTIC_HEADER_ALLOWLIST = new Set([
|
|
28
|
+
"cf-ray",
|
|
29
|
+
"server",
|
|
30
|
+
"via",
|
|
31
|
+
"x-request-id"
|
|
32
|
+
]);
|
|
33
|
+
const DIAGNOSTIC_HEADER_PREFIX = "x-roblox-";
|
|
34
|
+
const TITLE_OPEN_PATTERN = /<title[^>]*>/i;
|
|
35
|
+
const H1_OPEN_PATTERN = /<h1[^>]*>/i;
|
|
36
|
+
const TAG_PATTERN = /<[^<>]*>/g;
|
|
37
|
+
const WHITESPACE_PATTERN = /\s+/g;
|
|
38
|
+
/**
|
|
39
|
+
* Extracts a one-line human summary from an HTML gateway error page, or returns
|
|
40
|
+
* `undefined` when the body is not such a page. A load balancer (HAProxy-style)
|
|
41
|
+
* rejects a request before it reaches Open Cloud and answers with an HTML page,
|
|
42
|
+
* not a JSON Open Cloud error; dumping that HTML whole is noise. The body is
|
|
43
|
+
* treated as HTML when the content-type is `text/html` or the trimmed body is
|
|
44
|
+
* tag-led (`<html`/`<!doctype html`), and the summary is taken from the
|
|
45
|
+
* `<title>` (falling back to the first `<h1>`), tags stripped and whitespace
|
|
46
|
+
* collapsed.
|
|
47
|
+
*
|
|
48
|
+
* @param contentType - The response `content-type` header, if present.
|
|
49
|
+
* @param rawText - The raw response body text.
|
|
50
|
+
* @returns The extracted summary, or `undefined` when the body is not an HTML
|
|
51
|
+
* gateway page (or carries no title/h1 text).
|
|
52
|
+
*/
|
|
53
|
+
function extractGatewaySummary(contentType, rawText) {
|
|
54
|
+
if (!isHtmlBody(contentType, rawText)) return;
|
|
55
|
+
return firstTagText(rawText, {
|
|
56
|
+
close: "</title>",
|
|
57
|
+
open: TITLE_OPEN_PATTERN
|
|
58
|
+
}) ?? firstTagText(rawText, {
|
|
59
|
+
close: "</h1>",
|
|
60
|
+
open: H1_OPEN_PATTERN
|
|
61
|
+
});
|
|
62
|
+
}
|
|
63
|
+
/**
|
|
64
|
+
* Filters a lowercased header record down to the diagnostic allowlist: a few
|
|
65
|
+
* named escalation headers plus any `x-roblox-*` header. Keeps errors light and
|
|
66
|
+
* avoids retaining anything sensitive from the full response header set.
|
|
67
|
+
*
|
|
68
|
+
* @param headers - The full header record (lowercased keys).
|
|
69
|
+
* @returns A record containing only the allowlisted headers that were present.
|
|
70
|
+
*/
|
|
71
|
+
function pickDiagnosticHeaders(headers) {
|
|
72
|
+
const picked = {};
|
|
73
|
+
for (const [name, value] of Object.entries(headers)) if (DIAGNOSTIC_HEADER_ALLOWLIST.has(name) || name.startsWith(DIAGNOSTIC_HEADER_PREFIX)) picked[name] = value;
|
|
74
|
+
return picked;
|
|
75
|
+
}
|
|
76
|
+
/**
|
|
77
|
+
* Converts a `Headers` object to a plain record with lowercased keys.
|
|
78
|
+
*
|
|
79
|
+
* @param headers - The `Headers` instance to convert.
|
|
80
|
+
* @returns A record mapping lowercased header names to their values.
|
|
81
|
+
*/
|
|
82
|
+
function headersToRecord(headers) {
|
|
83
|
+
return Object.fromEntries(headers);
|
|
84
|
+
}
|
|
85
|
+
/**
|
|
86
|
+
* Projects a read body to the detail carried on an error: the parsed JSON when
|
|
87
|
+
* it parsed, otherwise the raw text truncated to {@link MAX_DETAIL_LENGTH}.
|
|
88
|
+
*
|
|
89
|
+
* @param text - The raw response body text.
|
|
90
|
+
* @param parsed - The best-effort parse result from the transport's body read.
|
|
91
|
+
* @returns The parsed body, or the truncated raw text on a parse failure.
|
|
92
|
+
*/
|
|
93
|
+
function bodyDetail(text, parsed) {
|
|
94
|
+
return parsed.success ? parsed.data : text.slice(0, MAX_DETAIL_LENGTH);
|
|
95
|
+
}
|
|
96
|
+
/**
|
|
97
|
+
* Builds the error for a 2xx response whose body could not be parsed as JSON,
|
|
98
|
+
* preserving the parse `cause`, the (truncated) raw body, the declared
|
|
99
|
+
* content-type, and the request that produced it so the failure can be
|
|
100
|
+
* diagnosed after the fact.
|
|
101
|
+
*
|
|
102
|
+
* The received length is on the message rather than only on the error, because
|
|
103
|
+
* `details` retains just the first {@link MAX_DETAIL_LENGTH} characters: for a
|
|
104
|
+
* body that stopped mid-token the head says nothing and the length says
|
|
105
|
+
* everything. A `SyntaxError` position equal to this number is a body the edge
|
|
106
|
+
* cut short, not one the API mis-serialized.
|
|
107
|
+
*
|
|
108
|
+
* @param args - The Response, raw body text, request context, and underlying
|
|
109
|
+
* parse error.
|
|
110
|
+
* @returns An ApiError carrying the diagnostic context.
|
|
111
|
+
*/
|
|
112
|
+
function parseFailureError({ cause, context, response, text }) {
|
|
113
|
+
return new ApiError(`Failed to parse response body (content-type: ${response.headers.get(CONTENT_TYPE_HEADER$1) ?? "unknown"}, ${String(text.length)} chars read)`, {
|
|
114
|
+
cause,
|
|
115
|
+
details: text.slice(0, MAX_DETAIL_LENGTH),
|
|
116
|
+
elapsedMs: context.elapsedMs,
|
|
117
|
+
method: context.method,
|
|
118
|
+
responseHeaders: pickDiagnosticHeaders(headersToRecord(response.headers)),
|
|
119
|
+
statusCode: response.status,
|
|
120
|
+
unparsedBodyLength: text.length,
|
|
121
|
+
url: context.url
|
|
122
|
+
});
|
|
123
|
+
}
|
|
124
|
+
function firstTagText(html, tag) {
|
|
125
|
+
const open = tag.open.exec(html);
|
|
126
|
+
if (open === null) return;
|
|
127
|
+
const start = open.index + open[0].length;
|
|
128
|
+
const end = html.toLowerCase().indexOf(tag.close, start);
|
|
129
|
+
if (end === -1) return;
|
|
130
|
+
const text = html.slice(start, end).replace(TAG_PATTERN, " ").replace(WHITESPACE_PATTERN, " ").trim();
|
|
131
|
+
return text === "" ? void 0 : text;
|
|
132
|
+
}
|
|
133
|
+
function isHtmlBody(contentType, rawText) {
|
|
134
|
+
if (contentType?.toLowerCase().includes("text/html") === true) return true;
|
|
135
|
+
const head = rawText.trimStart().toLowerCase();
|
|
136
|
+
return head.startsWith("<html") || head.startsWith("<!doctype html");
|
|
137
|
+
}
|
|
138
|
+
//#endregion
|
|
139
|
+
//#region src/internal/http/http1-dispatcher.ts
|
|
140
|
+
/**
|
|
141
|
+
* Well-known globals under which undici publishes its global dispatcher,
|
|
142
|
+
* newest first. The suffix is undici's own contract version: it moved from
|
|
143
|
+
* `.1` to `.2` in undici 8, so a future major may move it again. Both are
|
|
144
|
+
* probed, and {@link createHttp1Dispatcher} degrades to `undefined` when
|
|
145
|
+
* neither is present — which is also the Bun path, since Bun's `fetch` is not
|
|
146
|
+
* undici-backed and never publishes these.
|
|
147
|
+
*/
|
|
148
|
+
const GLOBAL_DISPATCHER_KEYS = Object.freeze(["undici.globalDispatcher.2", "undici.globalDispatcher.1"]);
|
|
149
|
+
/**
|
|
150
|
+
* Narrow a value read off the global dispatcher to something
|
|
151
|
+
* `Reflect.construct` accepts. Exported so the narrowing is unit-testable: at
|
|
152
|
+
* the call site every rejected shape funnels into the same `undefined`, which
|
|
153
|
+
* makes the branch unobservable from `createHttp1Dispatcher` alone.
|
|
154
|
+
*
|
|
155
|
+
* @param value - The candidate `constructor` read off the global dispatcher.
|
|
156
|
+
* @returns Whether the value can be constructed.
|
|
157
|
+
*/
|
|
158
|
+
function isAgentConstructor(value) {
|
|
159
|
+
return typeof value === "function";
|
|
160
|
+
}
|
|
161
|
+
/**
|
|
162
|
+
* Builds a request dispatcher that negotiates HTTP/1.1 only, by reusing the
|
|
163
|
+
* class of the runtime's own global dispatcher.
|
|
164
|
+
*
|
|
165
|
+
* From Node 26 (undici 8) `fetch` offers h2 in ALPN, which defeats the
|
|
166
|
+
* `connection: close` an upload sets: `connection` is a connection-specific
|
|
167
|
+
* header, so an h2 transport drops it before the wire and pools every upload
|
|
168
|
+
* onto one multiplexed session. One session death then fails every upload in
|
|
169
|
+
* flight. Constructing the same agent with `allowH2: false` restores the
|
|
170
|
+
* per-upload connection the directive was written for.
|
|
171
|
+
*
|
|
172
|
+
* There is no standard `fetch` option for this, so the agent is reached
|
|
173
|
+
* through undici's versioned global symbol and its class rather than through
|
|
174
|
+
* an import — which keeps the package dependency-free. The contract is
|
|
175
|
+
* internal, so every step is guarded: an absent symbol, a non-constructible
|
|
176
|
+
* value, or a constructor that throws all yield `undefined`, and the caller
|
|
177
|
+
* sends the request unmodified.
|
|
178
|
+
*
|
|
179
|
+
* @param scope - The object to read the global dispatcher from. Defaults to
|
|
180
|
+
* `globalThis`; injectable so tests need not mutate the real global.
|
|
181
|
+
* @returns A dispatcher restricted to HTTP/1.1, or `undefined` when this
|
|
182
|
+
* runtime offers no reachable one.
|
|
183
|
+
*/
|
|
184
|
+
function createHttp1Dispatcher(scope = globalThis) {
|
|
185
|
+
for (const key of GLOBAL_DISPATCHER_KEYS) {
|
|
186
|
+
const dispatcher = constructHttp1(Reflect.get(scope, Symbol.for(key)));
|
|
187
|
+
if (dispatcher !== void 0) return dispatcher;
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
/**
|
|
191
|
+
* Reconstructs `agent`'s class with h2 disabled.
|
|
192
|
+
*
|
|
193
|
+
* Most ways `agent` can be wrong already throw: `Reflect.get` rejects a
|
|
194
|
+
* primitive, `null`, and an absent key, and `Reflect.construct` rejects a
|
|
195
|
+
* `constructor` that is not one, or that refuses the options. One shape gets
|
|
196
|
+
* through — a plain object, whose `constructor` is `Object`, so constructing
|
|
197
|
+
* it hands back the options bag. The result is therefore checked against the
|
|
198
|
+
* one part of undici's surface that is public and stable: a `Dispatcher`
|
|
199
|
+
* exposes `dispatch`.
|
|
200
|
+
*
|
|
201
|
+
* @param agent - The candidate global dispatcher; any value, since it comes
|
|
202
|
+
* from an undocumented global.
|
|
203
|
+
* @returns The new dispatcher, or `undefined` when `agent` is not an object
|
|
204
|
+
* whose constructor accepts undici's agent options.
|
|
205
|
+
*/
|
|
206
|
+
function constructHttp1(agent) {
|
|
207
|
+
try {
|
|
208
|
+
const agentClass = Reflect.get(agent, "constructor");
|
|
209
|
+
if (!isAgentConstructor(agentClass)) return;
|
|
210
|
+
const dispatcher = Reflect.construct(agentClass, [{ allowH2: false }]);
|
|
211
|
+
return typeof Reflect.get(dispatcher, "dispatch") === "function" ? dispatcher : void 0;
|
|
212
|
+
} catch {
|
|
213
|
+
return;
|
|
214
|
+
}
|
|
215
|
+
}
|
|
216
|
+
//#endregion
|
|
217
|
+
//#region src/internal/http/rate-limit-sample.ts
|
|
218
|
+
const NON_NEGATIVE_INTEGER_PATTERN = /^\d+$/;
|
|
219
|
+
/**
|
|
220
|
+
* Reduces a comma-separated rate-limit header value (e.g. `"0, 70000"`) to a
|
|
221
|
+
* single non-negative integer via `combine`. Tokens are trimmed; blank,
|
|
222
|
+
* fractional, negative, and non-finite tokens are dropped so a stray value
|
|
223
|
+
* cannot corrupt the result. Returns `undefined` when the header is absent or
|
|
224
|
+
* has no valid tokens.
|
|
225
|
+
*
|
|
226
|
+
* @param headerValue - The raw header value, or `undefined` if missing.
|
|
227
|
+
* @param combine - Pairwise reducer, `Math.min` for remaining, `Math.max` for reset.
|
|
228
|
+
* @returns The reduced value, or `undefined`.
|
|
229
|
+
*/
|
|
230
|
+
function reduceRateLimitTokens(headerValue, combine) {
|
|
231
|
+
if (headerValue === void 0) return;
|
|
232
|
+
const tokens = headerValue.split(",").map((part) => part.trim()).filter((part) => NON_NEGATIVE_INTEGER_PATTERN.test(part)).map((part) => Number(part)).filter((value) => Number.isInteger(value));
|
|
233
|
+
if (tokens.length === 0) return;
|
|
234
|
+
return tokens.reduce(combine);
|
|
235
|
+
}
|
|
236
|
+
/**
|
|
237
|
+
* Parses the `x-ratelimit-remaining` and `x-ratelimit-reset` response headers
|
|
238
|
+
* into a {@link RateLimitSample}. Each header may carry a comma-separated list
|
|
239
|
+
* of per-window values; `remaining` takes the smallest (most constrained) and
|
|
240
|
+
* `resetSeconds` takes the largest (longest wait). Returns `undefined` when
|
|
241
|
+
* either header is missing or has no valid non-negative integer tokens, so a
|
|
242
|
+
* caller can fall back to static pacing.
|
|
243
|
+
*
|
|
244
|
+
* @param headers - Response headers with lowercased keys.
|
|
245
|
+
* @returns The parsed sample, or `undefined` when the budget cannot be read.
|
|
246
|
+
*/
|
|
247
|
+
function parseRateLimitHeaders(headers) {
|
|
248
|
+
const remaining = reduceRateLimitTokens(headers["x-ratelimit-remaining"], (a, b) => {
|
|
249
|
+
return Math.min(a, b);
|
|
250
|
+
});
|
|
251
|
+
const resetSeconds = reduceRateLimitTokens(headers["x-ratelimit-reset"], (a, b) => {
|
|
252
|
+
return Math.max(a, b);
|
|
253
|
+
});
|
|
254
|
+
if (remaining === void 0 || resetSeconds === void 0) return;
|
|
255
|
+
return {
|
|
256
|
+
remaining,
|
|
257
|
+
resetSeconds
|
|
258
|
+
};
|
|
259
|
+
}
|
|
260
|
+
//#endregion
|
|
261
|
+
//#region src/errors/request-aborted.ts
|
|
262
|
+
/**
|
|
263
|
+
* Returned when a caller's `AbortSignal` cancels an Open Cloud request.
|
|
264
|
+
* The reason is preserved so intentional cancellation can be distinguished
|
|
265
|
+
* from transport failures and SDK-owned request timeouts.
|
|
266
|
+
*
|
|
267
|
+
* @since 0.3.1
|
|
268
|
+
*
|
|
269
|
+
* @example
|
|
270
|
+
*
|
|
271
|
+
* ```ts
|
|
272
|
+
* import { RequestAbortedError } from "@bedrock-rbx/ocale";
|
|
273
|
+
*
|
|
274
|
+
* const error = new RequestAbortedError("Request was aborted", {
|
|
275
|
+
* reason: "superseded",
|
|
276
|
+
* });
|
|
277
|
+
*
|
|
278
|
+
* expect(error).toBeInstanceOf(RequestAbortedError);
|
|
279
|
+
* expect(error.reason).toBe("superseded");
|
|
280
|
+
* ```
|
|
281
|
+
*/
|
|
282
|
+
var RequestAbortedError = class extends OpenCloudError {
|
|
283
|
+
name = "RequestAbortedError";
|
|
284
|
+
reason;
|
|
285
|
+
/**
|
|
286
|
+
* Creates a new RequestAbortedError.
|
|
287
|
+
*
|
|
288
|
+
* @param message - Human-readable description of the cancellation.
|
|
289
|
+
* @param options - Error options including the caller's abort reason.
|
|
290
|
+
*/
|
|
291
|
+
constructor(message, options = {}) {
|
|
292
|
+
super(message, options);
|
|
293
|
+
this.reason = options.reason;
|
|
294
|
+
}
|
|
295
|
+
};
|
|
296
|
+
//#endregion
|
|
297
|
+
//#region src/internal/utils/abort.ts
|
|
298
|
+
/**
|
|
299
|
+
* Sentinel returned when an asynchronous operation loses a race with a signal.
|
|
300
|
+
*/
|
|
301
|
+
const ABORTED = Symbol("aborted");
|
|
302
|
+
/**
|
|
303
|
+
* Runs an asynchronous operation and resolves with {@link ABORTED} when the
|
|
304
|
+
* supplied signal fires first. The underlying operation still receives the
|
|
305
|
+
* signal separately so cancellable implementations can release their work.
|
|
306
|
+
*
|
|
307
|
+
* @template T - Value produced by the operation.
|
|
308
|
+
* @param operation - Operation to start after the abort observer is installed.
|
|
309
|
+
* @param signal - Optional caller cancellation signal.
|
|
310
|
+
* @returns The operation's value, or {@link ABORTED} when cancellation wins.
|
|
311
|
+
* @rejects The operation's error when it fails before cancellation.
|
|
312
|
+
*/
|
|
313
|
+
async function raceWithAbortAsync(operation, signal) {
|
|
314
|
+
if (signal === void 0) return operation();
|
|
315
|
+
if (signal.aborted) return ABORTED;
|
|
316
|
+
const { promise, resolve } = Promise.withResolvers();
|
|
317
|
+
function onAbort() {
|
|
318
|
+
resolve(ABORTED);
|
|
319
|
+
}
|
|
320
|
+
signal.addEventListener("abort", onAbort);
|
|
321
|
+
try {
|
|
322
|
+
return await Promise.race([operation(), promise]);
|
|
323
|
+
} finally {
|
|
324
|
+
signal.removeEventListener("abort", onAbort);
|
|
325
|
+
}
|
|
326
|
+
}
|
|
327
|
+
/**
|
|
328
|
+
* Creates the canonical typed failure for caller-request cancellation.
|
|
329
|
+
*
|
|
330
|
+
* @param signal - The caller signal whose reason should be preserved.
|
|
331
|
+
* @returns A cancellation error carrying the signal's reason.
|
|
332
|
+
*/
|
|
333
|
+
function requestAbortedError(signal) {
|
|
334
|
+
return new RequestAbortedError("Request was aborted", { reason: signal?.reason });
|
|
335
|
+
}
|
|
336
|
+
//#endregion
|
|
337
|
+
//#region src/internal/http/request-signal.ts
|
|
338
|
+
/**
|
|
339
|
+
* Composes caller cancellation with Ocale's request deadline. The winning
|
|
340
|
+
* signal's reason is retained by `AbortSignal.any`, allowing failure
|
|
341
|
+
* classification to distinguish cancellation from timeout.
|
|
342
|
+
*
|
|
343
|
+
* @param config - Transport configuration for one request.
|
|
344
|
+
* @returns A caller signal, timeout signal, their composition, or `undefined`.
|
|
345
|
+
*/
|
|
346
|
+
function requestSignal(config) {
|
|
347
|
+
if (config.timeout === void 0) return config.signal;
|
|
348
|
+
const timeout = AbortSignal.timeout(config.timeout);
|
|
349
|
+
return config.signal === void 0 ? timeout : AbortSignal.any([config.signal, timeout]);
|
|
350
|
+
}
|
|
351
|
+
/**
|
|
352
|
+
* Classifies a fetch rejection without confusing a caller abort with the
|
|
353
|
+
* transport's own timeout.
|
|
354
|
+
*
|
|
355
|
+
* @param args - Failure, target, request config, and effective fetch signal.
|
|
356
|
+
* @returns A typed caller cancellation or network failure.
|
|
357
|
+
*/
|
|
358
|
+
function requestFailure({ cause, config, effectiveSignal, target }) {
|
|
359
|
+
if (config.signal?.aborted === true && effectiveSignal?.aborted === true && Object.is(effectiveSignal.reason, config.signal.reason)) return requestAbortedError(config.signal);
|
|
360
|
+
return new NetworkError("Network request failed", {
|
|
361
|
+
cause,
|
|
362
|
+
method: target.method,
|
|
363
|
+
url: target.url
|
|
364
|
+
});
|
|
365
|
+
}
|
|
366
|
+
//#endregion
|
|
367
|
+
//#region src/internal/http/retry-guidance.ts
|
|
368
|
+
const ABBREVIATED_WEEKDAYS = [
|
|
369
|
+
"Sun",
|
|
370
|
+
"Mon",
|
|
371
|
+
"Tue",
|
|
372
|
+
"Wed",
|
|
373
|
+
"Thu",
|
|
374
|
+
"Fri",
|
|
375
|
+
"Sat"
|
|
376
|
+
];
|
|
377
|
+
const ANSI_DATE_PATTERN = /^(Mon|Tue|Wed|Thu|Fri|Sat|Sun) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) ( \d|\d{2}) (\d{2}):(\d{2}):(\d{2}) (\d{4})$/;
|
|
378
|
+
const DELAY_SECONDS_PATTERN = /^\d+$/;
|
|
379
|
+
const FIXED_DATE_PATTERN = /^(Mon|Tue|Wed|Thu|Fri|Sat|Sun), (\d{2}) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) (\d{4}) (\d{2}):(\d{2}):(\d{2}) GMT$/;
|
|
380
|
+
const FULL_WEEKDAY_TO_ABBREVIATED = {
|
|
381
|
+
Friday: "Fri",
|
|
382
|
+
Monday: "Mon",
|
|
383
|
+
Saturday: "Sat",
|
|
384
|
+
Sunday: "Sun",
|
|
385
|
+
Thursday: "Thu",
|
|
386
|
+
Tuesday: "Tue",
|
|
387
|
+
Wednesday: "Wed"
|
|
388
|
+
};
|
|
389
|
+
const MONTHS = [
|
|
390
|
+
"Jan",
|
|
391
|
+
"Feb",
|
|
392
|
+
"Mar",
|
|
393
|
+
"Apr",
|
|
394
|
+
"May",
|
|
395
|
+
"Jun",
|
|
396
|
+
"Jul",
|
|
397
|
+
"Aug",
|
|
398
|
+
"Sep",
|
|
399
|
+
"Oct",
|
|
400
|
+
"Nov",
|
|
401
|
+
"Dec"
|
|
402
|
+
];
|
|
403
|
+
const OBSOLETE_DATE_PATTERN = /^(Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday), (\d{2})-(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)-(\d{2}) (\d{2}):(\d{2}):(\d{2}) GMT$/;
|
|
404
|
+
/**
|
|
405
|
+
* Parses `x-ratelimit-reset` as seconds until quota replenishment. Roblox can
|
|
406
|
+
* report multiple comma-separated windows; the longest valid window is the
|
|
407
|
+
* earliest safe quota retry.
|
|
408
|
+
*
|
|
409
|
+
* @param headerValue - The raw reset value, or `undefined` if missing.
|
|
410
|
+
* @returns The longest reset delay, or `undefined` when absent or invalid.
|
|
411
|
+
*/
|
|
412
|
+
function parseQuotaResetSeconds(headerValue) {
|
|
413
|
+
return reduceRateLimitTokens(headerValue, (a, b) => Math.max(a, b));
|
|
414
|
+
}
|
|
415
|
+
/**
|
|
416
|
+
* Parses the standard `Retry-After` header. RFC 9110 permits either a
|
|
417
|
+
* non-negative integer number of seconds or any HTTP-date form. A date is
|
|
418
|
+
* rounded up so a retry never starts before the server's stated instant.
|
|
419
|
+
*
|
|
420
|
+
* @param headerValue - The raw `Retry-After` value, or `undefined` if missing.
|
|
421
|
+
* @param nowMs - Current Unix time in milliseconds, injectable for tests.
|
|
422
|
+
* @returns The delay in seconds, or `undefined` when absent or invalid.
|
|
423
|
+
*/
|
|
424
|
+
function parseRetryAfterSeconds(headerValue, nowMs = Date.now()) {
|
|
425
|
+
if (headerValue === void 0) return;
|
|
426
|
+
const value = headerValue.trim();
|
|
427
|
+
if (DELAY_SECONDS_PATTERN.test(value)) {
|
|
428
|
+
const seconds = Number(value);
|
|
429
|
+
return Number.isFinite(seconds) ? seconds : void 0;
|
|
430
|
+
}
|
|
431
|
+
const retryAt = parseHttpDate(value, nowMs);
|
|
432
|
+
return retryAt === void 0 ? void 0 : Math.max(0, Math.ceil((retryAt - nowMs) / 1e3));
|
|
433
|
+
}
|
|
434
|
+
/**
|
|
435
|
+
* Chooses the applicable server-directed delay for one 429 response.
|
|
436
|
+
*
|
|
437
|
+
* @param options - Response headers, remaining quota, and optional clock.
|
|
438
|
+
* @returns The delay in seconds, or `undefined` when caller backoff applies.
|
|
439
|
+
*/
|
|
440
|
+
function resolveRetryGuidance({ headers, nowMs, remaining }) {
|
|
441
|
+
const retryAfter = parseRetryAfterSeconds(headers["retry-after"], nowMs);
|
|
442
|
+
if (remaining !== 0) return retryAfter;
|
|
443
|
+
const quotaReset = parseQuotaResetSeconds(headers["x-ratelimit-reset"]);
|
|
444
|
+
return quotaReset === void 0 ? retryAfter : Math.max(retryAfter ?? 0, quotaReset);
|
|
445
|
+
}
|
|
446
|
+
function httpDateTimestamp(parts) {
|
|
447
|
+
if (parts.minute > 59 || parts.second > 59) return;
|
|
448
|
+
const date = /* @__PURE__ */ new Date(0);
|
|
449
|
+
date.setUTCFullYear(parts.year, parts.month, parts.day);
|
|
450
|
+
date.setUTCHours(parts.hour, parts.minute, parts.second, 0);
|
|
451
|
+
return date.getUTCDate() === parts.day && ABBREVIATED_WEEKDAYS[date.getUTCDay()] === parts.weekday ? date.getTime() : void 0;
|
|
452
|
+
}
|
|
453
|
+
function parseAnsiDate(value) {
|
|
454
|
+
const match = ANSI_DATE_PATTERN.exec(value);
|
|
455
|
+
return match === null ? void 0 : httpDateTimestamp({
|
|
456
|
+
day: Number(match[3]),
|
|
457
|
+
hour: Number(match[4]),
|
|
458
|
+
minute: Number(match[5]),
|
|
459
|
+
month: MONTHS.indexOf(String(match[2])),
|
|
460
|
+
second: Number(match[6]),
|
|
461
|
+
weekday: String(match[1]),
|
|
462
|
+
year: Number(match[7])
|
|
463
|
+
});
|
|
464
|
+
}
|
|
465
|
+
function parseFixedDate(value) {
|
|
466
|
+
const match = FIXED_DATE_PATTERN.exec(value);
|
|
467
|
+
return match === null ? void 0 : httpDateTimestamp({
|
|
468
|
+
day: Number(match[2]),
|
|
469
|
+
hour: Number(match[5]),
|
|
470
|
+
minute: Number(match[6]),
|
|
471
|
+
month: MONTHS.indexOf(String(match[3])),
|
|
472
|
+
second: Number(match[7]),
|
|
473
|
+
weekday: String(match[1]),
|
|
474
|
+
year: Number(match[4])
|
|
475
|
+
});
|
|
476
|
+
}
|
|
477
|
+
function parseObsoleteDate(value, nowMs) {
|
|
478
|
+
const match = OBSOLETE_DATE_PATTERN.exec(value);
|
|
479
|
+
if (match === null) return;
|
|
480
|
+
const currentYear = new Date(nowMs).getUTCFullYear();
|
|
481
|
+
let year = Math.floor(currentYear / 100) * 100 + Number(match[4]);
|
|
482
|
+
if (year > currentYear + 50) year -= 100;
|
|
483
|
+
return httpDateTimestamp({
|
|
484
|
+
day: Number(match[2]),
|
|
485
|
+
hour: Number(match[5]),
|
|
486
|
+
minute: Number(match[6]),
|
|
487
|
+
month: MONTHS.indexOf(String(match[3])),
|
|
488
|
+
second: Number(match[7]),
|
|
489
|
+
weekday: String(FULL_WEEKDAY_TO_ABBREVIATED[String(match[1])]),
|
|
490
|
+
year
|
|
491
|
+
});
|
|
492
|
+
}
|
|
493
|
+
function parseHttpDate(value, nowMs) {
|
|
494
|
+
return parseFixedDate(value) ?? parseObsoleteDate(value, nowMs) ?? parseAnsiDate(value);
|
|
495
|
+
}
|
|
496
|
+
//#endregion
|
|
497
|
+
//#region src/internal/http/upload-request.ts
|
|
498
|
+
/**
|
|
499
|
+
* Reports whether a request is an upload: its body is `FormData`
|
|
500
|
+
* (multipart) or `Uint8Array` (raw binary). Upload latency is
|
|
501
|
+
* bandwidth-bound rather than compute-bound, so the SDK applies no default
|
|
502
|
+
* request timeout to these requests; a sensible wall-clock budget depends on
|
|
503
|
+
* payload size and link quality the SDK cannot know.
|
|
504
|
+
*
|
|
505
|
+
* @param request - The built request to classify.
|
|
506
|
+
* @returns `true` when the body is `FormData` or `Uint8Array`.
|
|
507
|
+
*/
|
|
508
|
+
function isUploadRequest(request) {
|
|
509
|
+
return request.body instanceof FormData || request.body instanceof Uint8Array;
|
|
510
|
+
}
|
|
511
|
+
//#endregion
|
|
512
|
+
//#region src/internal/http/fetch-client.ts
|
|
513
|
+
const CONTENT_TYPE_HEADER = "content-type";
|
|
514
|
+
const CONNECTION_HEADER = "connection";
|
|
515
|
+
/**
|
|
516
|
+
* Permissively extracts a machine-readable error code from a response body.
|
|
517
|
+
*
|
|
518
|
+
* Three shapes are checked, in precedence order. Modern Open Cloud responses
|
|
519
|
+
* use `{ errorCode: string, message: string }`; Open Cloud v2 endpoints carry
|
|
520
|
+
* the canonical status in `error` (`{ error: "NOT_FOUND", message: string }`);
|
|
521
|
+
* the legacy game-internationalization endpoints use
|
|
522
|
+
* `{ errors: [{ code: number, message: string }, ...] }`. Numeric legacy codes
|
|
523
|
+
* are returned as strings so callers see one consistent type.
|
|
524
|
+
*
|
|
525
|
+
* `error` is read only when it holds a string. A Google-style nested envelope
|
|
526
|
+
* (`{ error: { code, message, status } }`) puts an object there, and coercing
|
|
527
|
+
* that to a string would hand callers `"[object Object]"` as a status.
|
|
528
|
+
*
|
|
529
|
+
* @param body - The parsed response body (unknown shape).
|
|
530
|
+
* @returns The error code if present, otherwise `undefined`.
|
|
531
|
+
*/
|
|
532
|
+
function extractErrorCode(body) {
|
|
533
|
+
if (body === null || typeof body !== "object") return;
|
|
534
|
+
const errorCode = Reflect.get(body, "errorCode");
|
|
535
|
+
if (typeof errorCode === "string") return errorCode;
|
|
536
|
+
const v2Error = Reflect.get(body, "error");
|
|
537
|
+
if (typeof v2Error === "string") return v2Error;
|
|
538
|
+
return extractLegacyCode(body);
|
|
539
|
+
}
|
|
540
|
+
/**
|
|
541
|
+
* Permissively extracts a human-readable error message from a response body.
|
|
542
|
+
*
|
|
543
|
+
* Modern Open Cloud responses expose `message` at the top level; the legacy
|
|
544
|
+
* game-internationalization endpoints nest it under `errors[0].message`.
|
|
545
|
+
*
|
|
546
|
+
* @param body - The parsed response body (unknown shape).
|
|
547
|
+
* @returns The message if present, otherwise `undefined`.
|
|
548
|
+
*/
|
|
549
|
+
function extractErrorMessage(body) {
|
|
550
|
+
if (body === null || typeof body !== "object") return;
|
|
551
|
+
const message = Reflect.get(body, "message");
|
|
552
|
+
if (typeof message === "string") return message;
|
|
553
|
+
return extractLegacyMessage(body);
|
|
554
|
+
}
|
|
555
|
+
/**
|
|
556
|
+
* Joins the base URL from config with the relative path from the request.
|
|
557
|
+
*
|
|
558
|
+
* @param request - The HTTP request containing the relative URL.
|
|
559
|
+
* @param config - The request config containing the base URL.
|
|
560
|
+
* @returns The fully-qualified URL string.
|
|
561
|
+
*/
|
|
562
|
+
function buildUrl(request, config) {
|
|
563
|
+
return `${config.baseUrl.endsWith("/") ? config.baseUrl.slice(0, -1) : config.baseUrl}${request.url}`;
|
|
564
|
+
}
|
|
565
|
+
/**
|
|
566
|
+
* Constructs the `RequestInit` options for a `fetch` call.
|
|
567
|
+
*
|
|
568
|
+
* @param request - The HTTP request to build options for.
|
|
569
|
+
* @param config - The request config containing API key and timeout.
|
|
570
|
+
* @returns A `RequestInit` object ready for `fetch`.
|
|
571
|
+
*/
|
|
572
|
+
function buildFetchOptions(request, config) {
|
|
573
|
+
const headers = new Headers({ "x-api-key": config.apiKey });
|
|
574
|
+
const options = {
|
|
575
|
+
headers,
|
|
576
|
+
method: request.method
|
|
577
|
+
};
|
|
578
|
+
if (request.body instanceof FormData) options.body = request.body;
|
|
579
|
+
else if (request.body instanceof Uint8Array) {
|
|
580
|
+
headers.set(CONTENT_TYPE_HEADER, "application/octet-stream");
|
|
581
|
+
options.body = request.body;
|
|
582
|
+
} else if (request.body !== void 0) {
|
|
583
|
+
headers.set(CONTENT_TYPE_HEADER, "application/json");
|
|
584
|
+
options.body = JSON.stringify(request.body);
|
|
585
|
+
}
|
|
586
|
+
applyRequestHeaders(headers, request);
|
|
587
|
+
const signal = requestSignal(config);
|
|
588
|
+
if (signal !== void 0) options.signal = signal;
|
|
589
|
+
return options;
|
|
590
|
+
}
|
|
591
|
+
/**
|
|
592
|
+
* Creates an {@link HttpClient} backed by the Fetch API.
|
|
593
|
+
*
|
|
594
|
+
* @param fetchFunc - The fetch implementation to use. Defaults to `globalThis.fetch`.
|
|
595
|
+
* @param seams - Injectable clock and dispatcher factory, so tests need not
|
|
596
|
+
* depend on wall-clock time or on the runtime's global dispatcher.
|
|
597
|
+
* @returns An HttpClient that classifies responses into typed Results.
|
|
598
|
+
*/
|
|
599
|
+
function createFetchHttpClient(fetchFunc = fetch, { createDispatcher = createHttp1Dispatcher, now = Date.now } = {}) {
|
|
600
|
+
const dispatcherFor = createUploadDispatcherCache(createDispatcher);
|
|
601
|
+
return { async request(httpRequest, config) {
|
|
602
|
+
return sendRequestAsync({
|
|
603
|
+
config,
|
|
604
|
+
dispatcherFor,
|
|
605
|
+
fetchFunc,
|
|
606
|
+
httpRequest,
|
|
607
|
+
now
|
|
608
|
+
});
|
|
609
|
+
} };
|
|
610
|
+
}
|
|
611
|
+
function readLegacyErrorEntry(body) {
|
|
612
|
+
const errors = Reflect.get(body, "errors");
|
|
613
|
+
if (!Array.isArray(errors)) return;
|
|
614
|
+
const [first] = errors;
|
|
615
|
+
if (typeof first !== "object" || first === null) return;
|
|
616
|
+
return first;
|
|
617
|
+
}
|
|
618
|
+
function extractLegacyCode(body) {
|
|
619
|
+
const first = readLegacyErrorEntry(body);
|
|
620
|
+
if (first === void 0) return;
|
|
621
|
+
const code = Reflect.get(first, "code");
|
|
622
|
+
if (typeof code === "string") return code;
|
|
623
|
+
return typeof code === "number" ? String(code) : void 0;
|
|
624
|
+
}
|
|
625
|
+
function extractLegacyMessage(body) {
|
|
626
|
+
const first = readLegacyErrorEntry(body);
|
|
627
|
+
if (first === void 0) return;
|
|
628
|
+
const message = Reflect.get(first, "message");
|
|
629
|
+
return typeof message === "string" ? message : void 0;
|
|
630
|
+
}
|
|
631
|
+
/**
|
|
632
|
+
* Merges the request's own headers onto the transport's, then applies the
|
|
633
|
+
* transport-owned connection directive. `x-api-key` is skipped so a request
|
|
634
|
+
* cannot override the configured credential, and the upload directive is set
|
|
635
|
+
* last so a request header cannot silently re-enable pooling for an upload.
|
|
636
|
+
*
|
|
637
|
+
* @param headers - The headers being built for the fetch call. Mutated.
|
|
638
|
+
* @param request - The request whose headers and body shape drive the merge.
|
|
639
|
+
*/
|
|
640
|
+
function applyRequestHeaders(headers, request) {
|
|
641
|
+
const requestHeaders = request.headers ?? {};
|
|
642
|
+
for (const [name, value] of Object.entries(requestHeaders)) {
|
|
643
|
+
if (name.toLowerCase() === "x-api-key") continue;
|
|
644
|
+
headers.set(name, value);
|
|
645
|
+
}
|
|
646
|
+
if (isUploadRequest(request)) headers.set(CONNECTION_HEADER, "close");
|
|
647
|
+
}
|
|
648
|
+
function failureResult(args) {
|
|
649
|
+
return {
|
|
650
|
+
err: requestFailure(args),
|
|
651
|
+
success: false
|
|
652
|
+
};
|
|
653
|
+
}
|
|
654
|
+
/**
|
|
655
|
+
* Runs `send` and reports both its Result and how long it was in flight,
|
|
656
|
+
* measured with `now`. Isolated so the timing start need not sit in the request
|
|
657
|
+
* body ahead of the transport-failure early return.
|
|
658
|
+
*
|
|
659
|
+
* @param now - The clock used to bound the call.
|
|
660
|
+
* @param send - A thunk that issues the fetch.
|
|
661
|
+
* @returns The fetch Result and the elapsed milliseconds.
|
|
662
|
+
*/
|
|
663
|
+
async function timedFetchAsync(now, send) {
|
|
664
|
+
const start = now();
|
|
665
|
+
const fetchResult = await tryCatchAsync(send());
|
|
666
|
+
return {
|
|
667
|
+
elapsedMs: Math.max(0, now() - start),
|
|
668
|
+
fetchResult
|
|
669
|
+
};
|
|
670
|
+
}
|
|
671
|
+
function formatApiErrorMessage({ code, message, status }) {
|
|
672
|
+
const base = `HTTP ${status}`;
|
|
673
|
+
if (message === void 0 && code === void 0) return base;
|
|
674
|
+
if (message === void 0) return `${base} (code ${code})`;
|
|
675
|
+
if (code === void 0) return `${base}: ${message}`;
|
|
676
|
+
return `${base}: ${message} (code ${code})`;
|
|
677
|
+
}
|
|
678
|
+
function createApiError(args) {
|
|
679
|
+
const { context, rawText, response } = args;
|
|
680
|
+
const { status } = response;
|
|
681
|
+
const headers = headersToRecord(response.headers);
|
|
682
|
+
const requestContext = {
|
|
683
|
+
elapsedMs: context.elapsedMs,
|
|
684
|
+
method: context.method,
|
|
685
|
+
responseHeaders: pickDiagnosticHeaders(headers),
|
|
686
|
+
statusCode: status,
|
|
687
|
+
url: context.url
|
|
688
|
+
};
|
|
689
|
+
const gatewaySummary = extractGatewaySummary(headers[CONTENT_TYPE_HEADER], rawText);
|
|
690
|
+
if (gatewaySummary !== void 0) return new ApiError(`HTTP ${status}`, {
|
|
691
|
+
...requestContext,
|
|
692
|
+
gatewaySummary
|
|
693
|
+
});
|
|
694
|
+
const body = bodyDetail(rawText, args.parsed);
|
|
695
|
+
const code = extractErrorCode(body);
|
|
696
|
+
return new ApiError(formatApiErrorMessage({
|
|
697
|
+
code,
|
|
698
|
+
message: extractErrorMessage(body),
|
|
699
|
+
status
|
|
700
|
+
}), {
|
|
701
|
+
...requestContext,
|
|
702
|
+
code,
|
|
703
|
+
details: body
|
|
704
|
+
});
|
|
705
|
+
}
|
|
706
|
+
/**
|
|
707
|
+
* Parses response text as JSON, returning the underlying `SyntaxError` on
|
|
708
|
+
* failure rather than throwing. The synchronous sibling of {@link
|
|
709
|
+
* tryCatchAsync}.
|
|
710
|
+
*
|
|
711
|
+
* @param text - The raw response body text.
|
|
712
|
+
* @returns A Result wrapping the parsed value, or the parse error.
|
|
713
|
+
*/
|
|
714
|
+
function parseJson(text) {
|
|
715
|
+
try {
|
|
716
|
+
return {
|
|
717
|
+
data: JSON.parse(text),
|
|
718
|
+
success: true
|
|
719
|
+
};
|
|
720
|
+
} catch (err) {
|
|
721
|
+
return {
|
|
722
|
+
err: err instanceof Error ? err : new Error(String(err)),
|
|
723
|
+
success: false
|
|
724
|
+
};
|
|
725
|
+
}
|
|
726
|
+
}
|
|
727
|
+
/**
|
|
728
|
+
* Reads a response body once and parses it best-effort: an empty body is a
|
|
729
|
+
* successful `undefined`, otherwise the JSON parse result (which carries the
|
|
730
|
+
* `SyntaxError` on failure). Returns the raw `text` alongside so callers that
|
|
731
|
+
* need the original bytes (parse-failure diagnostics) do not re-read the
|
|
732
|
+
* consumed stream.
|
|
733
|
+
*
|
|
734
|
+
* @param response - The Response whose body to read.
|
|
735
|
+
* @returns The parse result and the raw text.
|
|
736
|
+
*/
|
|
737
|
+
async function readResponseBodyAsync(response) {
|
|
738
|
+
const text = await response.text();
|
|
739
|
+
return {
|
|
740
|
+
parsed: text === "" ? {
|
|
741
|
+
data: void 0,
|
|
742
|
+
success: true
|
|
743
|
+
} : parseJson(text),
|
|
744
|
+
text
|
|
745
|
+
};
|
|
746
|
+
}
|
|
747
|
+
async function createRateLimitErrorAsync(response) {
|
|
748
|
+
const headers = headersToRecord(response.headers);
|
|
749
|
+
const { parsed, text } = await readResponseBodyAsync(response);
|
|
750
|
+
const remaining = reduceRateLimitTokens(headers["x-ratelimit-remaining"], (a, b) => {
|
|
751
|
+
return Math.min(a, b);
|
|
752
|
+
});
|
|
753
|
+
const guidedRetrySeconds = resolveRetryGuidance({
|
|
754
|
+
headers,
|
|
755
|
+
remaining
|
|
756
|
+
});
|
|
757
|
+
const error = new RateLimitError("Rate limited", {
|
|
758
|
+
details: bodyDetail(text, parsed),
|
|
759
|
+
remaining,
|
|
760
|
+
retryAfterSeconds: guidedRetrySeconds ?? 0,
|
|
761
|
+
statusCode: response.status
|
|
762
|
+
});
|
|
763
|
+
return guidedRetrySeconds === void 0 ? error : markServerRetryGuidance(error);
|
|
764
|
+
}
|
|
765
|
+
/**
|
|
766
|
+
* Classifies a fetch `Response` into a typed `Result`.
|
|
767
|
+
*
|
|
768
|
+
* The body is read once and parsed best-effort. Error responses (status >= 300)
|
|
769
|
+
* never require valid JSON: an error body that is not valid JSON degrades to a
|
|
770
|
+
* status-based {@link ApiError} carrying the raw text, and an HTML gateway page
|
|
771
|
+
* is summarized rather than dumped. A parse failure is only fatal on a 2xx,
|
|
772
|
+
* where a parseable body is part of the contract.
|
|
773
|
+
*
|
|
774
|
+
* @param response - The raw fetch Response to classify.
|
|
775
|
+
* @param context - The request context (method, url, elapsed time) threaded
|
|
776
|
+
* onto every {@link ApiError} built here, whether for an error response or
|
|
777
|
+
* for a 2xx whose body would not parse.
|
|
778
|
+
* @returns A Result containing an HttpResponse on success or an OpenCloudError on failure.
|
|
779
|
+
*/
|
|
780
|
+
async function classifyResponseAsync(response, context) {
|
|
781
|
+
if (response.status === 429) return {
|
|
782
|
+
err: await createRateLimitErrorAsync(response),
|
|
783
|
+
success: false
|
|
784
|
+
};
|
|
785
|
+
const { parsed, text } = await readResponseBodyAsync(response);
|
|
786
|
+
if (response.status >= 300) return {
|
|
787
|
+
err: createApiError({
|
|
788
|
+
context,
|
|
789
|
+
parsed,
|
|
790
|
+
rawText: text,
|
|
791
|
+
response
|
|
792
|
+
}),
|
|
793
|
+
success: false
|
|
794
|
+
};
|
|
795
|
+
if (!parsed.success) return {
|
|
796
|
+
err: parseFailureError({
|
|
797
|
+
cause: parsed.err,
|
|
798
|
+
context,
|
|
799
|
+
response,
|
|
800
|
+
text
|
|
801
|
+
}),
|
|
802
|
+
success: false
|
|
803
|
+
};
|
|
804
|
+
return {
|
|
805
|
+
data: {
|
|
806
|
+
body: parsed.data,
|
|
807
|
+
headers: headersToRecord(response.headers),
|
|
808
|
+
status: response.status
|
|
809
|
+
},
|
|
810
|
+
success: true
|
|
811
|
+
};
|
|
812
|
+
}
|
|
813
|
+
async function sendRequestAsync({ config, dispatcherFor, fetchFunc, httpRequest, now }) {
|
|
814
|
+
const url = buildUrl(httpRequest, config);
|
|
815
|
+
const options = buildFetchOptions(httpRequest, config);
|
|
816
|
+
options.dispatcher = dispatcherFor(httpRequest);
|
|
817
|
+
const target = {
|
|
818
|
+
method: httpRequest.method,
|
|
819
|
+
url
|
|
820
|
+
};
|
|
821
|
+
const { elapsedMs, fetchResult } = await timedFetchAsync(now, async () => {
|
|
822
|
+
return fetchFunc(url, options);
|
|
823
|
+
});
|
|
824
|
+
if (!fetchResult.success) return failureResult({
|
|
825
|
+
cause: fetchResult.err,
|
|
826
|
+
config,
|
|
827
|
+
effectiveSignal: options.signal,
|
|
828
|
+
target
|
|
829
|
+
});
|
|
830
|
+
const context = {
|
|
831
|
+
elapsedMs,
|
|
832
|
+
method: target.method,
|
|
833
|
+
url: target.url
|
|
834
|
+
};
|
|
835
|
+
const classified = await tryCatchAsync(classifyResponseAsync(fetchResult.data, context));
|
|
836
|
+
return classified.success ? classified.data : failureResult({
|
|
837
|
+
cause: classified.err,
|
|
838
|
+
config,
|
|
839
|
+
effectiveSignal: options.signal,
|
|
840
|
+
target
|
|
841
|
+
});
|
|
842
|
+
}
|
|
843
|
+
/**
|
|
844
|
+
* Wraps a dispatcher factory in the caching policy uploads need.
|
|
845
|
+
*
|
|
846
|
+
* Resolution happens on the first upload rather than at construction: undici
|
|
847
|
+
* publishes its global dispatcher lazily, so before a process's first `fetch`
|
|
848
|
+
* there is nothing to read. A resolved dispatcher is kept, and an unresolved
|
|
849
|
+
* one is retried on the next upload — so a runtime that publishes late is
|
|
850
|
+
* still picked up, and the first request of a process, which has no pooled
|
|
851
|
+
* connection to lose, is safe either way.
|
|
852
|
+
*
|
|
853
|
+
* @param createDispatcher - Builds the HTTP/1.1-only transport.
|
|
854
|
+
* @returns A function yielding the dispatcher for a request, or `undefined`
|
|
855
|
+
* when the request is not an upload or no dispatcher is available.
|
|
856
|
+
*/
|
|
857
|
+
function createUploadDispatcherCache(createDispatcher) {
|
|
858
|
+
let cached;
|
|
859
|
+
return (request) => {
|
|
860
|
+
if (!isUploadRequest(request)) return;
|
|
861
|
+
cached ??= createDispatcher();
|
|
862
|
+
return cached;
|
|
863
|
+
};
|
|
864
|
+
}
|
|
865
|
+
//#endregion
|
|
866
|
+
//#region src/errors/permission-error.ts
|
|
867
|
+
/**
|
|
868
|
+
* Thrown when the Roblox Open Cloud API returns a 401 or 403 for an operation
|
|
869
|
+
* whose required scopes are known. Subclass of {@link ApiError} carrying the
|
|
870
|
+
* scope strings the operation requires plus the operation key, so a consumer
|
|
871
|
+
* can name them when guiding the user to their API key settings.
|
|
872
|
+
*
|
|
873
|
+
* The scopes are what the operation needs, not a diagnosis of what the
|
|
874
|
+
* credential lacks: a 403 does mean the scopes fall short, but Roblox also
|
|
875
|
+
* answers 401 for a key that is invalid, disabled, or expired. Check
|
|
876
|
+
* {@link ApiError.statusCode} before wording the failure as a missing scope.
|
|
877
|
+
*
|
|
878
|
+
* @since 0.1.0
|
|
879
|
+
*
|
|
880
|
+
* @example
|
|
881
|
+
*
|
|
882
|
+
* ```ts
|
|
883
|
+
* import { PermissionError } from "@bedrock-rbx/ocale";
|
|
884
|
+
*
|
|
885
|
+
* const error = new PermissionError("HTTP 403", {
|
|
886
|
+
* operationKey: "developer-products.create",
|
|
887
|
+
* requiredScopes: ["creator-store-product:write"],
|
|
888
|
+
* statusCode: 403,
|
|
889
|
+
* });
|
|
890
|
+
*
|
|
891
|
+
* expect(error).toBeInstanceOf(PermissionError);
|
|
892
|
+
* expect(error.requiredScopes).toStrictEqual(["creator-store-product:write"]);
|
|
893
|
+
* expect(error.operationKey).toBe("developer-products.create");
|
|
894
|
+
* ```
|
|
895
|
+
*/
|
|
896
|
+
var PermissionError = class extends ApiError {
|
|
897
|
+
name = "PermissionError";
|
|
898
|
+
operationKey;
|
|
899
|
+
requiredScopes;
|
|
900
|
+
/**
|
|
901
|
+
* Creates a new PermissionError.
|
|
902
|
+
*
|
|
903
|
+
* @param message - Human-readable error description.
|
|
904
|
+
* @param options - Error options including status code, the operation key,
|
|
905
|
+
* and the scopes the caller's credential must carry.
|
|
906
|
+
*/
|
|
907
|
+
constructor(message, options) {
|
|
908
|
+
super(message, options);
|
|
909
|
+
this.operationKey = options.operationKey;
|
|
910
|
+
this.requiredScopes = options.requiredScopes;
|
|
911
|
+
}
|
|
912
|
+
};
|
|
913
|
+
//#endregion
|
|
914
|
+
//#region src/internal/utils/find-error-code.ts
|
|
915
|
+
/**
|
|
916
|
+
* Maximum cause-chain depth walked by {@link findErrorCode}. Caps pathological
|
|
917
|
+
* self-referential or deeply nested chains; transport failures surface as
|
|
918
|
+
* `NetworkError → TypeError("fetch failed") → OS Error{code}`, so three
|
|
919
|
+
* levels is the expected shape and five leaves headroom.
|
|
920
|
+
*/
|
|
921
|
+
const MAX_DEPTH = 5;
|
|
922
|
+
/**
|
|
923
|
+
* Walks an error's `cause` chain and returns the first node-style string
|
|
924
|
+
* `code` it finds (for example `"ECONNRESET"`, `"ETIMEDOUT"`). Native `fetch`
|
|
925
|
+
* surfaces a transport reset as a `NetworkError` wrapping a
|
|
926
|
+
* `TypeError("fetch failed")` whose own cause carries the OS-level `code`, so
|
|
927
|
+
* the code lives several links down the chain.
|
|
928
|
+
*
|
|
929
|
+
* @example
|
|
930
|
+
*
|
|
931
|
+
* ```ts
|
|
932
|
+
* import { findErrorCode } from "./find-error-code";
|
|
933
|
+
*
|
|
934
|
+
* const root = Object.assign(new Error("read ECONNRESET"), { code: "ECONNRESET" });
|
|
935
|
+
* const outer = new Error("Network request failed", {
|
|
936
|
+
* cause: new TypeError("fetch failed", { cause: root }),
|
|
937
|
+
* });
|
|
938
|
+
*
|
|
939
|
+
* expect(findErrorCode(outer)).toBe("ECONNRESET");
|
|
940
|
+
* ```
|
|
941
|
+
*
|
|
942
|
+
* @param error - The error to inspect; typically a `NetworkError`.
|
|
943
|
+
* @returns The first string `code` in the chain, or `undefined` if none.
|
|
944
|
+
*/
|
|
945
|
+
function findErrorCode(error) {
|
|
946
|
+
let current = error;
|
|
947
|
+
for (let depth = 0; depth < MAX_DEPTH && current instanceof Error; depth += 1) {
|
|
948
|
+
const code = readCode(current);
|
|
949
|
+
if (code !== void 0) return code;
|
|
950
|
+
current = current.cause;
|
|
951
|
+
}
|
|
952
|
+
}
|
|
953
|
+
function readCode(error) {
|
|
954
|
+
const code = Reflect.get(error, "code");
|
|
955
|
+
return typeof code === "string" ? code : void 0;
|
|
956
|
+
}
|
|
957
|
+
/**
|
|
958
|
+
* `DOMException.name` produced when an `AbortSignal.timeout` fires. This is the
|
|
959
|
+
* web-standard discriminator (stable across Node and Bun, unlike the
|
|
960
|
+
* runtime-specific message) and distinguishes the SDK's own request timeout
|
|
961
|
+
* from a caller-supplied cancellation, which surfaces as `"AbortError"`.
|
|
962
|
+
*/
|
|
963
|
+
const TIMEOUT_ABORT_NAME = "TimeoutError";
|
|
964
|
+
/**
|
|
965
|
+
* Reports whether an error chain was produced by the SDK's own
|
|
966
|
+
* `AbortSignal.timeout` self-abort. Such a `DOMException` carries a numeric
|
|
967
|
+
* `code` (23), so {@link findErrorCode} (which only reads string codes)
|
|
968
|
+
* cannot classify it; this walk keys on `name` instead. A caller-supplied
|
|
969
|
+
* abort (`"AbortError"`) is deliberately not matched.
|
|
970
|
+
*
|
|
971
|
+
* @example
|
|
972
|
+
*
|
|
973
|
+
* ```ts
|
|
974
|
+
* import { isTimeoutAbort } from "./find-error-code";
|
|
975
|
+
*
|
|
976
|
+
* const error = new Error("Network request failed", {
|
|
977
|
+
* cause: new DOMException("timed out", "TimeoutError"),
|
|
978
|
+
* });
|
|
979
|
+
*
|
|
980
|
+
* expect(isTimeoutAbort(error)).toBe(true);
|
|
981
|
+
* expect(isTimeoutAbort(new DOMException("cancelled", "AbortError"))).toBe(false);
|
|
982
|
+
* ```
|
|
983
|
+
*
|
|
984
|
+
* @param error - The error to inspect; typically a `NetworkError`.
|
|
985
|
+
* @returns `true` when a `TimeoutError` abort sits within the cause chain.
|
|
986
|
+
*/
|
|
987
|
+
function isTimeoutAbort(error) {
|
|
988
|
+
let current = error;
|
|
989
|
+
for (let depth = 0; depth < MAX_DEPTH && current instanceof Error; depth += 1) {
|
|
990
|
+
if (Reflect.get(current, "name") === TIMEOUT_ABORT_NAME) return true;
|
|
991
|
+
current = current.cause;
|
|
992
|
+
}
|
|
993
|
+
return false;
|
|
994
|
+
}
|
|
995
|
+
//#endregion
|
|
996
|
+
//#region src/internal/http/retry.ts
|
|
997
|
+
/**
|
|
998
|
+
* Transient transport error codes that are safe to retry for idempotent
|
|
999
|
+
* operations. Connection resets, timeouts, and DNS hiccups are recoverable on
|
|
1000
|
+
* a retry. A self-aborted request timeout carries no OS-level `code`, so
|
|
1001
|
+
* {@link shouldRetry} folds it into this set as `ETIMEDOUT` (via
|
|
1002
|
+
* {@link isTimeoutAbort}) for idempotent methods; create methods retry no
|
|
1003
|
+
* transport codes and so still never re-issue a timed-out write.
|
|
1004
|
+
*
|
|
1005
|
+
* `ERR_HTTP2_STREAM_ERROR`, `ERR_HTTP2_SESSION_ERROR`, and `UND_ERR_INFO` are
|
|
1006
|
+
* the same deaths as spelled by a runtime whose `fetch` negotiates HTTP/2
|
|
1007
|
+
* (Node 26 and later). They differ from the socket codes in one way that
|
|
1008
|
+
* matters: they do not prove the request went unprocessed. `UND_ERR_INFO`
|
|
1009
|
+
* covers both a `GOAWAY` declaring a stream was never started and a stream
|
|
1010
|
+
* that was fully sent, and `UND_ERR_SOCKET` can fire once a response is
|
|
1011
|
+
* already streaming. Retrying them is therefore justified by the operation
|
|
1012
|
+
* being safe to repeat, never by the request having gone unseen — which is
|
|
1013
|
+
* why {@link UPLOAD_METHOD_DEFAULTS}, the one write policy that includes
|
|
1014
|
+
* them, documents its own grounds.
|
|
1015
|
+
*
|
|
1016
|
+
* @since 0.1.0
|
|
1017
|
+
*/
|
|
1018
|
+
const TRANSIENT_TRANSPORT_CODES = Object.freeze([
|
|
1019
|
+
"ECONNRESET",
|
|
1020
|
+
"ECONNREFUSED",
|
|
1021
|
+
"ETIMEDOUT",
|
|
1022
|
+
"EPIPE",
|
|
1023
|
+
"ENETUNREACH",
|
|
1024
|
+
"EHOSTDOWN",
|
|
1025
|
+
"EAI_AGAIN",
|
|
1026
|
+
"UND_ERR_SOCKET",
|
|
1027
|
+
"ERR_HTTP2_STREAM_ERROR",
|
|
1028
|
+
"ERR_HTTP2_SESSION_ERROR",
|
|
1029
|
+
"UND_ERR_INFO"
|
|
1030
|
+
]);
|
|
1031
|
+
/**
|
|
1032
|
+
* Synthetic transport code for a response that came from an edge gateway
|
|
1033
|
+
* rather than Open Cloud ({@link ApiError.gatewaySummary}). Such a response
|
|
1034
|
+
* proves the request was rejected before any Open Cloud handler saw it, so it
|
|
1035
|
+
* is classified alongside {@link TRANSIENT_TRANSPORT_CODES} rather than by its
|
|
1036
|
+
* HTTP status: the status belongs to the gateway, not to the API, and a
|
|
1037
|
+
* gateway `400` says nothing about the validity of the request.
|
|
1038
|
+
*
|
|
1039
|
+
* Name it in a per-request `retryableTransportCodes` override to opt an
|
|
1040
|
+
* operation into (or out of) gateway-rejection retry.
|
|
1041
|
+
*
|
|
1042
|
+
* @since 0.1.2
|
|
1043
|
+
*/
|
|
1044
|
+
const GATEWAY_REJECTED = "GATEWAY_REJECTED";
|
|
1045
|
+
/**
|
|
1046
|
+
* Synthetic transport code for a 2xx whose body could not be parsed as JSON
|
|
1047
|
+
* ({@link ApiError.unparsedBodyLength}). Open Cloud does not answer a success
|
|
1048
|
+
* status with a malformed document; what this failure describes in practice is
|
|
1049
|
+
* a body the edge delivered short, ending mid-token at exactly the length that
|
|
1050
|
+
* arrived. The next read is a fresh body and usually a whole one.
|
|
1051
|
+
*
|
|
1052
|
+
* Classifying it by transport code rather than by HTTP status is what makes it
|
|
1053
|
+
* recoverable at all: the status is a 200, which no `retryableStatuses` list
|
|
1054
|
+
* contains, so a status-keyed decision could only ever say "do not retry".
|
|
1055
|
+
*
|
|
1056
|
+
* Retrying is justified by the operation being safe to repeat, never by the
|
|
1057
|
+
* request having gone unprocessed — a 200 proves it was processed. So this code
|
|
1058
|
+
* is in {@link IDEMPOTENT_METHOD_DEFAULTS} only. Creates and uploads leave it
|
|
1059
|
+
* out: their write landed, and re-issuing it to re-read the answer would risk a
|
|
1060
|
+
* second resource for a response body, which is the wrong trade. A consumer who
|
|
1061
|
+
* can tolerate that duplicate names this code in a per-request
|
|
1062
|
+
* `retryableTransportCodes` override.
|
|
1063
|
+
*
|
|
1064
|
+
* @since 0.1.5
|
|
1065
|
+
*/
|
|
1066
|
+
const RESPONSE_UNPARSEABLE = "RESPONSE_UNPARSEABLE";
|
|
1067
|
+
/**
|
|
1068
|
+
* Default retry policy for idempotent operations (read, list, update,
|
|
1069
|
+
* delete). Safe to retry on rate limits, transient server errors, and
|
|
1070
|
+
* transient transport failures.
|
|
1071
|
+
*/
|
|
1072
|
+
const IDEMPOTENT_METHOD_DEFAULTS = Object.freeze({
|
|
1073
|
+
retryableStatuses: Object.freeze([
|
|
1074
|
+
429,
|
|
1075
|
+
500,
|
|
1076
|
+
502,
|
|
1077
|
+
503,
|
|
1078
|
+
504
|
|
1079
|
+
]),
|
|
1080
|
+
retryableTransportCodes: Object.freeze([...TRANSIENT_TRANSPORT_CODES, RESPONSE_UNPARSEABLE])
|
|
1081
|
+
});
|
|
1082
|
+
/**
|
|
1083
|
+
* Default retry policy for create operations. Retries rate limits only (no
|
|
1084
|
+
* 5xx and no transport-error retries) to prevent duplicate resources, since
|
|
1085
|
+
* Roblox Open Cloud has no idempotency-key support. Consumers who can tolerate
|
|
1086
|
+
* a duplicate opt in per request.
|
|
1087
|
+
*/
|
|
1088
|
+
const CREATE_METHOD_DEFAULTS = Object.freeze({
|
|
1089
|
+
retryableStatuses: Object.freeze([429]),
|
|
1090
|
+
retryableTransportCodes: Object.freeze([])
|
|
1091
|
+
});
|
|
1092
|
+
/**
|
|
1093
|
+
* Default retry policy for upload operations (place publish and save). Keeps
|
|
1094
|
+
* {@link CREATE_METHOD_DEFAULTS}'s 5xx guard (a 5xx comes from Open Cloud and
|
|
1095
|
+
* may describe a write that partly landed), but retries transport failures:
|
|
1096
|
+
* {@link TRANSIENT_TRANSPORT_CODES} and {@link GATEWAY_REJECTED}.
|
|
1097
|
+
*
|
|
1098
|
+
* This is the one write policy that retries codes which do not prove the
|
|
1099
|
+
* request went unprocessed, and the grounds are specific to a place version:
|
|
1100
|
+
* Roblox dedupes identical place content, so a retry that races a publish
|
|
1101
|
+
* which did land returns that same version rather than creating a second one.
|
|
1102
|
+
* That is load-bearing, not incidental — an upload operation without content
|
|
1103
|
+
* dedupe would need its own allowlist.
|
|
1104
|
+
*/
|
|
1105
|
+
const UPLOAD_METHOD_DEFAULTS = Object.freeze({
|
|
1106
|
+
...CREATE_METHOD_DEFAULTS,
|
|
1107
|
+
retryableTransportCodes: Object.freeze([...TRANSIENT_TRANSPORT_CODES, GATEWAY_REJECTED])
|
|
1108
|
+
});
|
|
1109
|
+
/**
|
|
1110
|
+
* Default exponential backoff: 1s → 2s → 4s → 8s → 16s → 30s (capped).
|
|
1111
|
+
*
|
|
1112
|
+
* @example
|
|
1113
|
+
*
|
|
1114
|
+
* ```ts
|
|
1115
|
+
* import { defaultRetryDelay } from "./retry";
|
|
1116
|
+
*
|
|
1117
|
+
* expect(defaultRetryDelay(0)).toBe(1000);
|
|
1118
|
+
* expect(defaultRetryDelay(4)).toBe(16_000);
|
|
1119
|
+
* expect(defaultRetryDelay(10)).toBe(30_000);
|
|
1120
|
+
* ```
|
|
1121
|
+
*
|
|
1122
|
+
* @param attempt - Zero-indexed retry attempt number.
|
|
1123
|
+
* @returns Wait duration in milliseconds.
|
|
1124
|
+
*/
|
|
1125
|
+
function defaultRetryDelay(attempt) {
|
|
1126
|
+
return Math.min(1e3 * 2 ** attempt, 3e4);
|
|
1127
|
+
}
|
|
1128
|
+
/**
|
|
1129
|
+
* Computes how long to wait before the next retry. Prefers valid server
|
|
1130
|
+
* guidance on a {@link RateLimitError}, including an explicit zero-second
|
|
1131
|
+
* delay; otherwise falls through to `retryDelay(attempt)`.
|
|
1132
|
+
*
|
|
1133
|
+
* @example
|
|
1134
|
+
*
|
|
1135
|
+
* ```ts
|
|
1136
|
+
* import { RateLimitError } from "../../errors/rate-limit.ts";
|
|
1137
|
+
* import { computeRetryWaitMs, defaultRetryDelay } from "./retry";
|
|
1138
|
+
*
|
|
1139
|
+
* const error = new RateLimitError("slow down", { retryAfterSeconds: 3 });
|
|
1140
|
+
*
|
|
1141
|
+
* expect(computeRetryWaitMs(error, { attempt: 0, retryDelay: defaultRetryDelay })).toBe(
|
|
1142
|
+
* 3000,
|
|
1143
|
+
* );
|
|
1144
|
+
* ```
|
|
1145
|
+
*
|
|
1146
|
+
* @example
|
|
1147
|
+
*
|
|
1148
|
+
* ```ts
|
|
1149
|
+
* import { ApiError } from "../../errors/api-error.ts";
|
|
1150
|
+
* import { computeRetryWaitMs, defaultRetryDelay } from "./retry";
|
|
1151
|
+
*
|
|
1152
|
+
* const error = new ApiError("server error", { statusCode: 503 });
|
|
1153
|
+
*
|
|
1154
|
+
* expect(computeRetryWaitMs(error, { attempt: 2, retryDelay: defaultRetryDelay })).toBe(
|
|
1155
|
+
* 4000,
|
|
1156
|
+
* );
|
|
1157
|
+
* ```
|
|
1158
|
+
*
|
|
1159
|
+
* @param error - The error returned by the failing request.
|
|
1160
|
+
* @param options - Retry attempt index and fallback delay function.
|
|
1161
|
+
* @returns Wait duration in milliseconds before the next attempt.
|
|
1162
|
+
*/
|
|
1163
|
+
function computeRetryWaitMs(error, options) {
|
|
1164
|
+
if (error instanceof RateLimitError && hasServerRetryGuidance(error)) return error.retryAfterSeconds * 1e3;
|
|
1165
|
+
return options.retryDelay(options.attempt);
|
|
1166
|
+
}
|
|
1167
|
+
/**
|
|
1168
|
+
* Decides whether a failed request is eligible for retry. {@link
|
|
1169
|
+
* RateLimitError} (checked against 429) and {@link ApiError} (checked against
|
|
1170
|
+
* its `statusCode`) are retryable when their status is in `retryableStatuses`.
|
|
1171
|
+
* Two {@link ApiError} shapes are the exception, both checked against
|
|
1172
|
+
* `retryableTransportCodes` with their status never consulted: one carrying a
|
|
1173
|
+
* `gatewaySummary` is checked against {@link GATEWAY_REJECTED}, and one
|
|
1174
|
+
* carrying an `unparsedBodyLength` — a 2xx whose body would not parse —
|
|
1175
|
+
* against {@link RESPONSE_UNPARSEABLE}. A {@link NetworkError} is
|
|
1176
|
+
* retryable when its transport code ({@link findErrorCode}) is in
|
|
1177
|
+
* `retryableTransportCodes`. This is how transient connection resets recover.
|
|
1178
|
+
* A self-aborted request timeout ({@link isTimeoutAbort}) carries no transport
|
|
1179
|
+
* code, so it is classified as `ETIMEDOUT`: recovered for idempotent methods,
|
|
1180
|
+
* never for creates (whose list is empty). All other failures return `false`.
|
|
1181
|
+
*
|
|
1182
|
+
* @example
|
|
1183
|
+
*
|
|
1184
|
+
* ```ts
|
|
1185
|
+
* import { RateLimitError } from "../../errors/rate-limit.ts";
|
|
1186
|
+
* import { shouldRetry } from "./retry";
|
|
1187
|
+
*
|
|
1188
|
+
* const error = new RateLimitError("", { retryAfterSeconds: 1 });
|
|
1189
|
+
*
|
|
1190
|
+
* expect(shouldRetry(error, { retryableStatuses: [429], retryableTransportCodes: [] })).toBe(
|
|
1191
|
+
* true,
|
|
1192
|
+
* );
|
|
1193
|
+
* ```
|
|
1194
|
+
*
|
|
1195
|
+
* @example
|
|
1196
|
+
*
|
|
1197
|
+
* ```ts
|
|
1198
|
+
* import { NetworkError } from "../../errors/network-error.ts";
|
|
1199
|
+
* import { shouldRetry } from "./retry";
|
|
1200
|
+
*
|
|
1201
|
+
* const reset = Object.assign(new Error("read ECONNRESET"), { code: "ECONNRESET" });
|
|
1202
|
+
* const error = new NetworkError("Network request failed", { cause: reset });
|
|
1203
|
+
*
|
|
1204
|
+
* expect(
|
|
1205
|
+
* shouldRetry(error, { retryableStatuses: [], retryableTransportCodes: ["ECONNRESET"] }),
|
|
1206
|
+
* ).toBe(true);
|
|
1207
|
+
* ```
|
|
1208
|
+
*
|
|
1209
|
+
* @param error - The error returned by the failing request.
|
|
1210
|
+
* @param config - Object carrying the retry-eligible status and transport-code lists.
|
|
1211
|
+
* @returns `true` if the error should be retried, `false` otherwise.
|
|
1212
|
+
*/
|
|
1213
|
+
function shouldRetry(error, config) {
|
|
1214
|
+
if (error instanceof RateLimitError) return config.retryableStatuses.includes(429);
|
|
1215
|
+
if (error instanceof ApiError) {
|
|
1216
|
+
if (error.gatewaySummary !== void 0) return config.retryableTransportCodes.includes(GATEWAY_REJECTED);
|
|
1217
|
+
if (error.unparsedBodyLength !== void 0) return config.retryableTransportCodes.includes(RESPONSE_UNPARSEABLE);
|
|
1218
|
+
return config.retryableStatuses.includes(error.statusCode);
|
|
1219
|
+
}
|
|
1220
|
+
if (error instanceof NetworkError) {
|
|
1221
|
+
const code = findErrorCode(error) ?? (isTimeoutAbort(error) ? "ETIMEDOUT" : void 0);
|
|
1222
|
+
return code !== void 0 && config.retryableTransportCodes.includes(code);
|
|
1223
|
+
}
|
|
1224
|
+
return false;
|
|
1225
|
+
}
|
|
1226
|
+
/**
|
|
1227
|
+
* Resolves the effective config for a single request by shallow-merging the
|
|
1228
|
+
* client config, method defaults, and per-request options. Precedence depends
|
|
1229
|
+
* on `methodKind`:
|
|
1230
|
+
*
|
|
1231
|
+
* - `"create"`: method defaults override client config, so client-level
|
|
1232
|
+
* settings cannot silently relax create-method safety. Only explicit
|
|
1233
|
+
* per-request `requestOptions` can.
|
|
1234
|
+
* - `"idempotent"`: client config overrides method defaults, so consumers
|
|
1235
|
+
* can loosen or tighten retry policy globally. `requestOptions` still wins
|
|
1236
|
+
* when provided.
|
|
1237
|
+
*
|
|
1238
|
+
* Array-valued fields like `retryableStatuses` are *replaced*, not extended.
|
|
1239
|
+
*
|
|
1240
|
+
* @template T - Concrete `RetryResolvable` subtype being merged.
|
|
1241
|
+
*
|
|
1242
|
+
* @example
|
|
1243
|
+
*
|
|
1244
|
+
* ```ts
|
|
1245
|
+
* import {
|
|
1246
|
+
* CREATE_METHOD_DEFAULTS,
|
|
1247
|
+
* defaultRetryDelay,
|
|
1248
|
+
* mergeConfig,
|
|
1249
|
+
* type RetryResolvable,
|
|
1250
|
+
* } from "./retry";
|
|
1251
|
+
*
|
|
1252
|
+
* const clientConfig: RetryResolvable = {
|
|
1253
|
+
* apiKey: "k",
|
|
1254
|
+
* baseUrl: "https://apis.roblox.com",
|
|
1255
|
+
* maxRetries: 3,
|
|
1256
|
+
* retryableStatuses: [429, 500],
|
|
1257
|
+
* retryableTransportCodes: [],
|
|
1258
|
+
* retryDelay: defaultRetryDelay,
|
|
1259
|
+
* timeout: 30_000,
|
|
1260
|
+
* };
|
|
1261
|
+
*
|
|
1262
|
+
* const merged = mergeConfig(clientConfig, {
|
|
1263
|
+
* methodDefaults: CREATE_METHOD_DEFAULTS,
|
|
1264
|
+
* methodKind: "create",
|
|
1265
|
+
* });
|
|
1266
|
+
*
|
|
1267
|
+
* expect(merged.retryableStatuses).toStrictEqual([429]);
|
|
1268
|
+
* ```
|
|
1269
|
+
*
|
|
1270
|
+
* @example
|
|
1271
|
+
*
|
|
1272
|
+
* ```ts
|
|
1273
|
+
* import {
|
|
1274
|
+
* defaultRetryDelay,
|
|
1275
|
+
* IDEMPOTENT_METHOD_DEFAULTS,
|
|
1276
|
+
* mergeConfig,
|
|
1277
|
+
* type RetryResolvable,
|
|
1278
|
+
* } from "./retry";
|
|
1279
|
+
*
|
|
1280
|
+
* const clientConfig: RetryResolvable = {
|
|
1281
|
+
* apiKey: "k",
|
|
1282
|
+
* baseUrl: "https://apis.roblox.com",
|
|
1283
|
+
* maxRetries: 3,
|
|
1284
|
+
* retryableStatuses: [429],
|
|
1285
|
+
* retryableTransportCodes: [],
|
|
1286
|
+
* retryDelay: defaultRetryDelay,
|
|
1287
|
+
* timeout: 30_000,
|
|
1288
|
+
* };
|
|
1289
|
+
*
|
|
1290
|
+
* const merged = mergeConfig(clientConfig, {
|
|
1291
|
+
* methodDefaults: IDEMPOTENT_METHOD_DEFAULTS,
|
|
1292
|
+
* methodKind: "idempotent",
|
|
1293
|
+
* requestOptions: { timeout: 10_000 },
|
|
1294
|
+
* });
|
|
1295
|
+
*
|
|
1296
|
+
* expect(merged.retryableStatuses).toStrictEqual([429]);
|
|
1297
|
+
* expect(merged.timeout).toBe(10_000);
|
|
1298
|
+
* ```
|
|
1299
|
+
*
|
|
1300
|
+
* @param clientConfig - Config frozen at client construction.
|
|
1301
|
+
* @param options - Method defaults, method kind, and optional per-request overrides.
|
|
1302
|
+
* @returns A new merged config object. Inputs are not mutated.
|
|
1303
|
+
*/
|
|
1304
|
+
function mergeConfig(clientConfig, { methodDefaults, methodKind, requestOptions }) {
|
|
1305
|
+
switch (methodKind) {
|
|
1306
|
+
case "create": return {
|
|
1307
|
+
...clientConfig,
|
|
1308
|
+
...methodDefaults,
|
|
1309
|
+
...requestOptions
|
|
1310
|
+
};
|
|
1311
|
+
case "idempotent": return {
|
|
1312
|
+
...methodDefaults,
|
|
1313
|
+
...clientConfig,
|
|
1314
|
+
...requestOptions
|
|
1315
|
+
};
|
|
1316
|
+
default: throw new Error(`Unexpected methodKind: ${String(methodKind)}`);
|
|
1317
|
+
}
|
|
1318
|
+
}
|
|
1319
|
+
//#endregion
|
|
1320
|
+
export { requestAbortedError as _, TRANSIENT_TRANSPORT_CODES as a, defaultRetryDelay as c, findErrorCode as d, PermissionError as f, raceWithAbortAsync as g, ABORTED as h, RESPONSE_UNPARSEABLE as i, mergeConfig as l, isUploadRequest as m, GATEWAY_REJECTED as n, UPLOAD_METHOD_DEFAULTS as o, createFetchHttpClient as p, IDEMPOTENT_METHOD_DEFAULTS as r, computeRetryWaitMs as s, CREATE_METHOD_DEFAULTS as t, shouldRetry as u, RequestAbortedError as v, parseRateLimitHeaders as y };
|
|
1321
|
+
|
|
1322
|
+
//# sourceMappingURL=retry-DIK_T_oF.mjs.map
|