@cortexkit/opencode-antigravity-auth 3.0.26 → 3.0.27

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 (57) hide show
  1. package/dist/cli.js.map +1 -1
  2. package/dist/cli.meta.json +2 -2
  3. package/dist/index.js +670 -201
  4. package/dist/index.js.map +3 -3
  5. package/dist/index.meta.json +18 -18
  6. package/dist/server.js +874 -325
  7. package/dist/server.js.map +4 -4
  8. package/dist/server.meta.json +1 -1
  9. package/dist/src/ga/server/index.d.ts +3 -1
  10. package/dist/src/ga/server/index.d.ts.map +1 -1
  11. package/dist/src/ga/server/index.js +89 -6
  12. package/dist/src/ga/server/index.js.map +1 -1
  13. package/dist/src/plugin/background-vault-quota-refresh.js +1 -1
  14. package/dist/src/plugin/background-vault-quota-refresh.js.map +1 -1
  15. package/dist/src/plugin/fetch-interceptor.d.ts.map +1 -1
  16. package/dist/src/plugin/fetch-interceptor.js +4 -2
  17. package/dist/src/plugin/fetch-interceptor.js.map +1 -1
  18. package/dist/src/plugin/ga-location-services.d.ts +1 -1
  19. package/dist/src/plugin/ga-location-services.d.ts.map +1 -1
  20. package/dist/src/plugin/ga-location-services.js +27 -20
  21. package/dist/src/plugin/ga-location-services.js.map +1 -1
  22. package/dist/src/plugin/index.js +2 -2
  23. package/dist/src/plugin/index.js.map +1 -1
  24. package/dist/src/plugin/request-helpers.d.ts +139 -0
  25. package/dist/src/plugin/request-helpers.d.ts.map +1 -1
  26. package/dist/src/plugin/request-helpers.js +512 -0
  27. package/dist/src/plugin/request-helpers.js.map +1 -1
  28. package/dist/src/plugin/request.d.ts.map +1 -1
  29. package/dist/src/plugin/request.js +219 -63
  30. package/dist/src/plugin/request.js.map +1 -1
  31. package/dist/src/plugin/shared/request-services.d.ts +1 -1
  32. package/dist/src/plugin/shared/request-services.d.ts.map +1 -1
  33. package/dist/src/plugin/shared/request-services.js +36 -127
  34. package/dist/src/plugin/shared/request-services.js.map +1 -1
  35. package/dist/src/plugin/shared/vault-menu.d.ts +1 -1
  36. package/dist/src/plugin/shared/vault-menu.d.ts.map +1 -1
  37. package/dist/src/plugin/shared/vault-menu.js +4 -2
  38. package/dist/src/plugin/shared/vault-menu.js.map +1 -1
  39. package/dist/src/plugin/shared/vault-request-credentials.d.ts +11 -4
  40. package/dist/src/plugin/shared/vault-request-credentials.d.ts.map +1 -1
  41. package/dist/src/plugin/shared/vault-request-credentials.js +67 -16
  42. package/dist/src/plugin/shared/vault-request-credentials.js.map +1 -1
  43. package/dist/types/src/ga/server/index.d.ts +3 -1
  44. package/dist/types/src/ga/server/index.d.ts.map +1 -1
  45. package/dist/types/src/plugin/fetch-interceptor.d.ts.map +1 -1
  46. package/dist/types/src/plugin/ga-location-services.d.ts +1 -1
  47. package/dist/types/src/plugin/ga-location-services.d.ts.map +1 -1
  48. package/dist/types/src/plugin/request-helpers.d.ts +139 -0
  49. package/dist/types/src/plugin/request-helpers.d.ts.map +1 -1
  50. package/dist/types/src/plugin/request.d.ts.map +1 -1
  51. package/dist/types/src/plugin/shared/request-services.d.ts +1 -1
  52. package/dist/types/src/plugin/shared/request-services.d.ts.map +1 -1
  53. package/dist/types/src/plugin/shared/vault-menu.d.ts +1 -1
  54. package/dist/types/src/plugin/shared/vault-menu.d.ts.map +1 -1
  55. package/dist/types/src/plugin/shared/vault-request-credentials.d.ts +11 -4
  56. package/dist/types/src/plugin/shared/vault-request-credentials.d.ts.map +1 -1
  57. package/package.json +2 -2
@@ -2083,4 +2083,516 @@ export function createNativeGoogleErrorResponse(options) {
2083
2083
  headers,
2084
2084
  });
2085
2085
  }
2086
+ /**
2087
+ * Extracts a non-null, non-array Antigravity error record from an envelope or
2088
+ * outer array wrapper. Primitives and arrays are not coerced to writable objects.
2089
+ */
2090
+ export function extractAntigravityError(body) {
2091
+ if (!body || typeof body !== 'object')
2092
+ return null;
2093
+ let target = body;
2094
+ if (Array.isArray(body)) {
2095
+ if (body.length === 0 ||
2096
+ !body[0] ||
2097
+ typeof body[0] !== 'object' ||
2098
+ Array.isArray(body[0])) {
2099
+ return null;
2100
+ }
2101
+ target = body[0];
2102
+ }
2103
+ const candidate = target.error;
2104
+ if (candidate && typeof candidate === 'object' && !Array.isArray(candidate)) {
2105
+ return candidate;
2106
+ }
2107
+ return null;
2108
+ }
2109
+ const MAX_FINITE_WAIT_MS = BigInt(Math.ceil(Number.MAX_VALUE));
2110
+ const MAX_FINITE_WAIT_SECONDS = (MAX_FINITE_WAIT_MS + 999n) / 1000n;
2111
+ const MAX_FINITE_FORWARDING_MS = MAX_FINITE_WAIT_SECONDS * 1000n;
2112
+ const RFC_HTTP_DATE_REGEX = /^(?: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$/;
2113
+ export function validateRetryAfterSecondsBigInt(raw) {
2114
+ if (raw === null || raw === undefined)
2115
+ return null;
2116
+ if (typeof raw === 'bigint') {
2117
+ return raw >= 0n && raw <= MAX_FINITE_WAIT_SECONDS ? raw : null;
2118
+ }
2119
+ if (typeof raw === 'number') {
2120
+ if (!Number.isFinite(raw) || raw < 0 || !Number.isInteger(raw)) {
2121
+ return null;
2122
+ }
2123
+ const b = BigInt(raw);
2124
+ return b <= MAX_FINITE_WAIT_SECONDS ? b : null;
2125
+ }
2126
+ if (typeof raw !== 'string')
2127
+ return null;
2128
+ const trimmed = raw.trim();
2129
+ if (trimmed.length === 0)
2130
+ return null;
2131
+ if (/^\d+$/.test(trimmed)) {
2132
+ if (trimmed.length > 309)
2133
+ return null;
2134
+ const val = BigInt(trimmed);
2135
+ return val >= 0n && val <= MAX_FINITE_WAIT_SECONDS ? val : null;
2136
+ }
2137
+ if (RFC_HTTP_DATE_REGEX.test(trimmed)) {
2138
+ const parsedDate = Date.parse(trimmed);
2139
+ if (!Number.isNaN(parsedDate)) {
2140
+ const roundtrip = new Date(parsedDate).toUTCString();
2141
+ if (roundtrip === trimmed) {
2142
+ const diffSec = Math.ceil((parsedDate - Date.now()) / 1000);
2143
+ if (diffSec >= 0 && Number.isSafeInteger(diffSec)) {
2144
+ return BigInt(diffSec);
2145
+ }
2146
+ }
2147
+ }
2148
+ }
2149
+ return null;
2150
+ }
2151
+ export function validateRetryAfterMsBigInt(raw) {
2152
+ if (raw === null || raw === undefined)
2153
+ return null;
2154
+ if (typeof raw === 'bigint') {
2155
+ return raw >= 0n && raw <= MAX_FINITE_FORWARDING_MS ? raw : null;
2156
+ }
2157
+ if (typeof raw === 'number') {
2158
+ if (!Number.isFinite(raw) || raw < 0 || !Number.isInteger(raw)) {
2159
+ return null;
2160
+ }
2161
+ const b = BigInt(raw);
2162
+ return b <= MAX_FINITE_FORWARDING_MS ? b : null;
2163
+ }
2164
+ if (typeof raw !== 'string')
2165
+ return null;
2166
+ const trimmed = raw.trim();
2167
+ if (trimmed.length === 0 || !/^\d+$/.test(trimmed))
2168
+ return null;
2169
+ if (trimmed.length > 309)
2170
+ return null;
2171
+ const val = BigInt(trimmed);
2172
+ return val >= 0n && val <= MAX_FINITE_FORWARDING_MS ? val : null;
2173
+ }
2174
+ export function deriveRetryHeaderPairFromMs(ms) {
2175
+ if (typeof ms !== 'bigint' || ms < 0n || ms > MAX_FINITE_FORWARDING_MS) {
2176
+ throw new RangeError(`deriveRetryHeaderPairFromMs: ms must be a non-negative BigInt <= MAX_FINITE_FORWARDING_MS (got ${String(ms)})`);
2177
+ }
2178
+ const sec = (ms + 999n) / 1000n;
2179
+ return {
2180
+ 'retry-after': sec.toString(),
2181
+ 'retry-after-ms': ms.toString(),
2182
+ };
2183
+ }
2184
+ export function deriveRetryHeaderPairFromSeconds(sec) {
2185
+ if (typeof sec !== 'bigint' || sec < 0n || sec > MAX_FINITE_WAIT_SECONDS) {
2186
+ throw new RangeError(`deriveRetryHeaderPairFromSeconds: sec must be a non-negative BigInt <= MAX_FINITE_WAIT_SECONDS (got ${String(sec)})`);
2187
+ }
2188
+ const ms = sec * 1000n;
2189
+ return {
2190
+ 'retry-after': sec.toString(),
2191
+ 'retry-after-ms': ms.toString(),
2192
+ };
2193
+ }
2194
+ /**
2195
+ * Validate a Retry-After header value as non-negative integer seconds.
2196
+ * Accepts non-negative finite integers, integer numeric strings, and valid RFC HTTP date strings.
2197
+ * Rejects NaN, Infinity, negative values (< 0), floats, and out-of-range numbers.
2198
+ */
2199
+ export function validateRetryAfterSeconds(raw) {
2200
+ const val = validateRetryAfterSecondsBigInt(raw);
2201
+ if (val === null)
2202
+ return null;
2203
+ const num = Number(val);
2204
+ return Number.isFinite(num) ? num : null;
2205
+ }
2206
+ /**
2207
+ * Validate a retry-after-ms header value as non-negative integer milliseconds.
2208
+ * Accepts non-negative finite integers and integer numeric strings.
2209
+ * Rejects fractions, negative values (< 0), and out-of-range numbers.
2210
+ */
2211
+ export function validateRetryAfterMs(raw) {
2212
+ const val = validateRetryAfterMsBigInt(raw);
2213
+ if (val === null)
2214
+ return null;
2215
+ const num = Number(val);
2216
+ return Number.isFinite(num) ? num : null;
2217
+ }
2218
+ /**
2219
+ * Extract validated retry headers from source headers (Headers instance or plain record).
2220
+ * Selects ONE authoritative delay (preferring retry-after-ms for millisecond precision)
2221
+ * and derives BOTH 'retry-after' and 'retry-after-ms' from that single value, ensuring
2222
+ * conflicting header pairs (e.g. Retry-After: 90 vs retry-after-ms: 60000) can never disagree.
2223
+ */
2224
+ export function collectForwardedHeaders(sourceHeaders) {
2225
+ if (!sourceHeaders)
2226
+ return {};
2227
+ const getHeader = (name) => {
2228
+ if (typeof sourceHeaders.get === 'function') {
2229
+ return sourceHeaders.get(name);
2230
+ }
2231
+ const record = sourceHeaders;
2232
+ for (const [key, value] of Object.entries(record)) {
2233
+ if (key.toLowerCase() === name)
2234
+ return value;
2235
+ }
2236
+ return undefined;
2237
+ };
2238
+ const rawRetryAfterMs = getHeader('retry-after-ms');
2239
+ const validMs = validateRetryAfterMsBigInt(rawRetryAfterMs);
2240
+ if (validMs !== null) {
2241
+ return deriveRetryHeaderPairFromMs(validMs);
2242
+ }
2243
+ const rawRetryAfter = getHeader('retry-after');
2244
+ const validSec = validateRetryAfterSecondsBigInt(rawRetryAfter);
2245
+ if (validSec !== null) {
2246
+ return deriveRetryHeaderPairFromSeconds(validSec);
2247
+ }
2248
+ return {};
2249
+ }
2250
+ /**
2251
+ * Check whether an error response or message represents a quota / rate-limit
2252
+ * condition. A message is a quota message only when:
2253
+ * - the response status is 429; or
2254
+ * - a structured detail names a quota reason (`QuotaFailure`, or an `ErrorInfo`
2255
+ * reason of QUOTA_EXHAUSTED / RATE_LIMIT_EXCEEDED / RESOURCE_EXHAUSTED); or
2256
+ * - the message carries a reset clause and a quota word, such as
2257
+ * "Quota exceeded. Resets in 30s.".
2258
+ *
2259
+ * A 400 whose text merely contains the word "quota", and a bare reset clause
2260
+ * such as "Session resets in 5m", are not quota errors: they must never be
2261
+ * rewritten with "quota resets in" or have a delay read from their text.
2262
+ */
2263
+ export function isQuotaError(status, message, details) {
2264
+ if (status === 429)
2265
+ return true;
2266
+ const lower = (message ?? '').toLowerCase();
2267
+ if (hasQuotaResetClause(lower))
2268
+ return true;
2269
+ return hasStructuredQuotaReason(details);
2270
+ }
2271
+ const QUOTA_REASON_CODES = new Set([
2272
+ 'QUOTA_EXHAUSTED',
2273
+ 'RATE_LIMIT_EXCEEDED',
2274
+ 'RESOURCE_EXHAUSTED',
2275
+ ]);
2276
+ /** True when the lowercased message names a quota word and announces a reset. */
2277
+ function hasQuotaResetClause(lowerMessage) {
2278
+ if (lowerMessage.length === 0)
2279
+ return false;
2280
+ if (extractResetDurationFromText(lowerMessage) === null)
2281
+ return false;
2282
+ return (lowerMessage.includes('quota') ||
2283
+ lowerMessage.includes('rate limit') ||
2284
+ lowerMessage.includes('rate_limit') ||
2285
+ lowerMessage.includes('resource_exhausted'));
2286
+ }
2287
+ /** True when a structured detail carries a quota reason code or QuotaFailure. */
2288
+ function hasStructuredQuotaReason(details) {
2289
+ if (!Array.isArray(details))
2290
+ return false;
2291
+ return details.some((detail) => {
2292
+ if (!detail || typeof detail !== 'object')
2293
+ return false;
2294
+ const record = detail;
2295
+ const type = record['@type'];
2296
+ if (typeof type === 'string' && type.includes('google.rpc.QuotaFailure'))
2297
+ return true;
2298
+ const reason = record.reason;
2299
+ if (typeof reason === 'string' && QUOTA_REASON_CODES.has(reason))
2300
+ return true;
2301
+ // QuotaFailure / ErrorInfo details may be nested inside a wrapped detail.
2302
+ const nested = record.details;
2303
+ return Array.isArray(nested) ? hasStructuredQuotaReason(nested) : false;
2304
+ });
2305
+ }
2306
+ export const RESET_CLAUSE_REGEX = /\b(?:quota\s+)?resets?\s+(?:in|after)\s+(?=\d+(?:\.\d+)?[ \t]*(?:ms|[dhms]))((?:(?:\d+(?:\.\d+)?[ \t]*d)[ \t]*)?(?:(?:\d+(?:\.\d+)?[ \t]*h)[ \t]*)?(?:(?:\d+(?:\.\d+)?[ \t]*m(?!s))[ \t]*)?(?:(?:\d+(?:\.\d+)?[ \t]*s)[ \t]*)?(?:(?:\d+(?:\.\d+)?[ \t]*ms))?)(?![a-zA-Z0-9_-])/gi;
2307
+ /**
2308
+ * Extract the raw duration string from a reset clause if present, without
2309
+ * consuming punctuation, prose, or following credential tokens.
2310
+ */
2311
+ export function extractResetDurationFromText(text) {
2312
+ if (typeof text !== 'string' || text.length === 0)
2313
+ return null;
2314
+ const regex = new RegExp(RESET_CLAUSE_REGEX.source, 'i');
2315
+ const match = text.match(regex);
2316
+ if (!match?.[1])
2317
+ return null;
2318
+ const raw = match[1].trim().replace(/[.,;:]+$/, '');
2319
+ return raw.length > 0 ? raw : null;
2320
+ }
2321
+ /**
2322
+ * Normalise only captured reset clauses so unrelated credential-like text is
2323
+ * unchanged before redaction:
2324
+ * - "Resets in 45s before retry." -> "quota resets in 45s before retry."
2325
+ * - "Resets in 2h55m14s. 1d2h3m4s5e-synthetic-opaque-credential" -> "quota resets in 2h 55m 14s. 1d2h3m4s5e-synthetic-opaque-credential"
2326
+ * - Does not touch tokens or numbers outside the reset clause.
2327
+ */
2328
+ export function normalizeResetDuration(text) {
2329
+ if (typeof text !== 'string' || text.length === 0)
2330
+ return text;
2331
+ return text.replace(RESET_CLAUSE_REGEX, (_match, rawDuration) => {
2332
+ if (!rawDuration)
2333
+ return _match;
2334
+ const duration = String(rawDuration).match(/^(.*?)([ \t]*)$/);
2335
+ if (!duration)
2336
+ return _match;
2337
+ const spaced = (duration[1] ?? '').replace(/(\d+(?:\.\d+)?)[ \t]*(ms|[dhms])(?=\d)/gi, '$1$2 ');
2338
+ return `quota resets in ${spaced}${duration[2] ?? ''}`;
2339
+ });
2340
+ }
2341
+ /**
2342
+ * Format a positive millisecond wait as a parser-friendly duration string ("2h 55m 14s").
2343
+ * Seconds are rounded up.
2344
+ */
2345
+ export function formatResetDuration(waitMs) {
2346
+ const totalSeconds = Math.max(0, Math.ceil(waitMs / 1000));
2347
+ const hours = Math.floor(totalSeconds / 3600);
2348
+ const minutes = Math.floor((totalSeconds % 3600) / 60);
2349
+ const seconds = totalSeconds % 60;
2350
+ const segments = [];
2351
+ if (hours > 0)
2352
+ segments.push(`${hours}h`);
2353
+ if (minutes > 0)
2354
+ segments.push(`${minutes}m`);
2355
+ segments.push(`${seconds}s`);
2356
+ return segments.join(' ');
2357
+ }
2358
+ export const DURATION_REGEX = /^(?:(\d+(?:\.\d+)?|\.\d+)[ \t]*d)?(?:[ \t]*(\d+(?:\.\d+)?|\.\d+)[ \t]*h)?(?:[ \t]*(\d+(?:\.\d+)?|\.\d+)[ \t]*m(?!s))?(?:[ \t]*(\d+(?:\.\d+)?|\.\d+)[ \t]*s)?(?:[ \t]*(\d+(?:\.\d+)?|\.\d+)[ \t]*ms)?$/i;
2359
+ function parseDecimalComponent(str, multMs) {
2360
+ const parts = str.split('.');
2361
+ const intStr = parts[0] ?? '';
2362
+ const fracStr = parts[1] ?? '';
2363
+ // Lexical bounds: reject if integer part (ignoring leading zeros) > 15 digits
2364
+ const effectiveIntStr = intStr.replace(/^0+/, '');
2365
+ if (effectiveIntStr.length > 15)
2366
+ return null;
2367
+ if (str.length > 60)
2368
+ return null;
2369
+ const intPart = intStr.length > 0 ? BigInt(intStr) : 0n;
2370
+ return { intPart, fracStr, mult: multMs };
2371
+ }
2372
+ /**
2373
+ * Strictly ordered whole-string duration grammar:
2374
+ * Days -> Hours -> Minutes -> Seconds -> Milliseconds
2375
+ * Components can be compact (2h55m14s) or separated by horizontal whitespace (2h 55m 14s).
2376
+ * Rejects partial tokens ('1hgarbage', 'x5s'), out-of-order components ('1m2h'),
2377
+ * non-positive totals (unless allowZero), non-finite / overflow (400 digits), and unsafe numbers.
2378
+ * Zero components in positive Go durations such as "1h0m0s" remain valid.
2379
+ */
2380
+ export function parseDurationToMs(duration, options) {
2381
+ const big = parseDurationToMsBigInt(duration, options);
2382
+ if (big === null)
2383
+ return null;
2384
+ if (big > BigInt(Number.MAX_SAFE_INTEGER))
2385
+ return null;
2386
+ return Number(big);
2387
+ }
2388
+ export function parseDurationToMsBigInt(duration, options) {
2389
+ if (typeof duration !== 'string')
2390
+ return null;
2391
+ const trimmed = duration.trim();
2392
+ if (trimmed.length === 0)
2393
+ return null;
2394
+ let dStr;
2395
+ let hStr;
2396
+ let mStr;
2397
+ let sStr;
2398
+ let msStr;
2399
+ const match = trimmed.match(DURATION_REGEX);
2400
+ if (match) {
2401
+ ;
2402
+ [, dStr, hStr, mStr, sStr, msStr] = match;
2403
+ }
2404
+ // If no unit match and allowBareSeconds is enabled, check for bare decimal number
2405
+ if (dStr === undefined &&
2406
+ hStr === undefined &&
2407
+ mStr === undefined &&
2408
+ sStr === undefined &&
2409
+ msStr === undefined) {
2410
+ if (options?.allowBareSeconds &&
2411
+ /^(?:\d+(?:\.\d+)?|\.\d+)$/.test(trimmed)) {
2412
+ sStr = trimmed;
2413
+ }
2414
+ else {
2415
+ return null;
2416
+ }
2417
+ }
2418
+ const rawComponents = [];
2419
+ if (dStr !== undefined)
2420
+ rawComponents.push({ str: dStr, mult: 86400000n });
2421
+ if (hStr !== undefined)
2422
+ rawComponents.push({ str: hStr, mult: 3600000n });
2423
+ if (mStr !== undefined)
2424
+ rawComponents.push({ str: mStr, mult: 60000n });
2425
+ if (sStr !== undefined)
2426
+ rawComponents.push({ str: sStr, mult: 1000n });
2427
+ if (msStr !== undefined)
2428
+ rawComponents.push({ str: msStr, mult: 1n });
2429
+ if (rawComponents.length === 0)
2430
+ return null;
2431
+ let maxFracDigits = 0;
2432
+ const parsedComponents = [];
2433
+ for (const rc of rawComponents) {
2434
+ const parsed = parseDecimalComponent(rc.str, rc.mult);
2435
+ if (!parsed)
2436
+ return null;
2437
+ if (parsed.fracStr.length > maxFracDigits) {
2438
+ maxFracDigits = parsed.fracStr.length;
2439
+ }
2440
+ parsedComponents.push(parsed);
2441
+ }
2442
+ const commonDenominator = 10n ** BigInt(maxFracDigits);
2443
+ let totalScaledNumerator = 0n;
2444
+ for (const c of parsedComponents) {
2445
+ const fracLen = BigInt(c.fracStr.length);
2446
+ const fracVal = c.fracStr.length > 0 ? BigInt(c.fracStr) : 0n;
2447
+ const scaleFactor = 10n ** (BigInt(maxFracDigits) - fracLen);
2448
+ const numerator = (c.intPart * commonDenominator + fracVal * scaleFactor) * c.mult;
2449
+ totalScaledNumerator += numerator;
2450
+ }
2451
+ if (totalScaledNumerator === 0n) {
2452
+ return options?.allowZero ? 0n : null;
2453
+ }
2454
+ const quotient = totalScaledNumerator / commonDenominator;
2455
+ const remainder = totalScaledNumerator % commonDenominator;
2456
+ let rounded = remainder * 2n >= commonDenominator ? quotient + 1n : quotient;
2457
+ if (rounded === 0n) {
2458
+ // Any positive supported duration below 1 ms rounds to min 1n
2459
+ rounded = 1n;
2460
+ }
2461
+ if (rounded > MAX_FINITE_FORWARDING_MS) {
2462
+ return null;
2463
+ }
2464
+ return rounded;
2465
+ }
2466
+ /**
2467
+ * Resolves authoritative retry metadata following unified executor precedence:
2468
+ * 1. First VALID RetryInfo scanning all entries (invalid first doesn't hide later)
2469
+ * 2. First valid metadata.quotaResetDelay (timestamp retained)
2470
+ * 3. Fields only the GA (Gemini API) error envelope carries:
2471
+ * retryAfterMs -> resetAfterMs -> retryAfterSeconds
2472
+ * 4. Quota classified original message reset clause
2473
+ * 5. HTTP headers: ms before seconds
2474
+ */
2475
+ export function resolveRetryMetadata(options) {
2476
+ const { details, message, status, headers, retryAfterMs, resetAfterMs, retryAfterSeconds, allowZero, allowBareSeconds, } = options;
2477
+ const bodyParserOptions = {
2478
+ allowZero,
2479
+ allowBareSeconds,
2480
+ };
2481
+ // 1. First VALID RetryInfo scanning all entries
2482
+ if (Array.isArray(details)) {
2483
+ for (const entry of details) {
2484
+ if (!entry || typeof entry !== 'object' || Array.isArray(entry))
2485
+ continue;
2486
+ const type = entry['@type'];
2487
+ if (typeof type === 'string' && type.includes('google.rpc.RetryInfo')) {
2488
+ const retryDelay = entry.retryDelay;
2489
+ if (typeof retryDelay === 'string') {
2490
+ const ms = parseDurationToMsBigInt(retryDelay, bodyParserOptions);
2491
+ if (ms !== null) {
2492
+ return { delayMs: ms };
2493
+ }
2494
+ }
2495
+ else if (typeof retryDelay === 'number') {
2496
+ if (Number.isFinite(retryDelay) && retryDelay >= 0) {
2497
+ const scaled = retryDelay * 1000;
2498
+ if (Number.isFinite(scaled)) {
2499
+ const rounded = Math.round(scaled);
2500
+ if (Number.isSafeInteger(rounded) && rounded >= 0) {
2501
+ // Only a true zero is a zero delay. A positive value below
2502
+ // 1ms keeps the documented minimum of 1ms, as text does.
2503
+ if (retryDelay === 0) {
2504
+ if (allowZero)
2505
+ return { delayMs: 0n };
2506
+ }
2507
+ else {
2508
+ return { delayMs: BigInt(Math.max(1, rounded)) };
2509
+ }
2510
+ }
2511
+ }
2512
+ }
2513
+ // Unsafe or overflow numeric is invalid; continue scanning for later valid RetryInfo/metadata/message/headers
2514
+ }
2515
+ }
2516
+ }
2517
+ // 2. First valid metadata.quotaResetDelay (timestamp retained)
2518
+ for (const entry of details) {
2519
+ if (!entry || typeof entry !== 'object' || Array.isArray(entry))
2520
+ continue;
2521
+ const metadata = entry.metadata;
2522
+ if (metadata &&
2523
+ typeof metadata === 'object' &&
2524
+ !Array.isArray(metadata)) {
2525
+ const quotaResetDelay = metadata
2526
+ .quotaResetDelay;
2527
+ if (typeof quotaResetDelay === 'string') {
2528
+ const ms = parseDurationToMsBigInt(quotaResetDelay, bodyParserOptions);
2529
+ if (ms !== null) {
2530
+ const quotaResetTime = typeof metadata
2531
+ .quotaResetTimeStamp === 'string'
2532
+ ? metadata
2533
+ .quotaResetTimeStamp
2534
+ : typeof metadata
2535
+ .quotaResetTime === 'string'
2536
+ ? metadata
2537
+ .quotaResetTime
2538
+ : undefined;
2539
+ return {
2540
+ delayMs: ms,
2541
+ ...(quotaResetTime !== undefined ? { quotaResetTime } : {}),
2542
+ };
2543
+ }
2544
+ }
2545
+ }
2546
+ }
2547
+ }
2548
+ // 3. Fields only the GA (Gemini API) error envelope carries:
2549
+ // retryAfterMs -> resetAfterMs -> retryAfterSeconds
2550
+ const validGaMs = validateRetryAfterMsBigInt(retryAfterMs);
2551
+ if (validGaMs !== null) {
2552
+ return { delayMs: validGaMs };
2553
+ }
2554
+ const validResetMs = validateRetryAfterMsBigInt(resetAfterMs);
2555
+ if (validResetMs !== null) {
2556
+ return { delayMs: validResetMs };
2557
+ }
2558
+ const validGaSec = validateRetryAfterSecondsBigInt(retryAfterSeconds);
2559
+ if (validGaSec !== null) {
2560
+ return { delayMs: validGaSec * 1000n };
2561
+ }
2562
+ // 4. Quota classified original message reset clause
2563
+ if (isQuotaError(status, message, details) && typeof message === 'string') {
2564
+ const rawDuration = extractResetDurationFromText(message);
2565
+ if (rawDuration !== null) {
2566
+ const ms = parseDurationToMsBigInt(rawDuration, bodyParserOptions);
2567
+ if (ms !== null) {
2568
+ return { delayMs: ms };
2569
+ }
2570
+ }
2571
+ }
2572
+ // 5. HTTP headers: ms before seconds
2573
+ if (headers) {
2574
+ const getHeader = (name) => {
2575
+ if (typeof headers.get === 'function') {
2576
+ return headers.get(name);
2577
+ }
2578
+ const record = headers;
2579
+ for (const [key, value] of Object.entries(record)) {
2580
+ if (key.toLowerCase() === name)
2581
+ return value;
2582
+ }
2583
+ return undefined;
2584
+ };
2585
+ const rawMs = getHeader('retry-after-ms');
2586
+ const validHeaderMs = validateRetryAfterMsBigInt(rawMs);
2587
+ if (validHeaderMs !== null) {
2588
+ return { delayMs: validHeaderMs };
2589
+ }
2590
+ const rawSec = getHeader('retry-after');
2591
+ const validHeaderSec = validateRetryAfterSecondsBigInt(rawSec);
2592
+ if (validHeaderSec !== null) {
2593
+ return { delayMs: validHeaderSec * 1000n };
2594
+ }
2595
+ }
2596
+ return null;
2597
+ }
2086
2598
  //# sourceMappingURL=request-helpers.js.map