@wildix/xbees-conversations-utils 4.0.1 → 4.0.2

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 (124) hide show
  1. package/dist-cjs/anonymousEmail/index.js +3 -3
  2. package/dist-cjs/rateLimits/RedisCooldown.js +66 -0
  3. package/dist-cjs/rateLimits/constants.js +43 -0
  4. package/dist-cjs/rateLimits/createRateLimitedStreamProxy.js +92 -0
  5. package/dist-cjs/rateLimits/exception/createRateLimitExceededException.js +21 -0
  6. package/dist-cjs/rateLimits/exception/processStreamRateLimitException.js +47 -0
  7. package/dist-cjs/rateLimits/executeStreamRequestWithRateLimitHandling.js +94 -0
  8. package/dist-cjs/rateLimits/generatedMethodNames.js +320 -0
  9. package/dist-cjs/rateLimits/helpers/RedisCooldown.js +174 -0
  10. package/dist-cjs/rateLimits/helpers/createRateLimitExceededException.js +32 -0
  11. package/dist-cjs/rateLimits/helpers/executeWithRateLimitHandling.js +144 -0
  12. package/dist-cjs/rateLimits/helpers/headerUtils.js +40 -0
  13. package/dist-cjs/rateLimits/helpers/isStreamChannelLike.js +23 -0
  14. package/dist-cjs/rateLimits/helpers/processStreamBudgetHeaders.js +93 -0
  15. package/dist-cjs/rateLimits/helpers/processStreamRateLimitException.js +63 -0
  16. package/dist-cjs/rateLimits/helpers/processStreamRateLimitHeaders.js +50 -0
  17. package/dist-cjs/rateLimits/helpers/rateLimitSnapshot.js +31 -0
  18. package/dist-cjs/rateLimits/helpers/registerStreamBudgetInterceptors.js +48 -0
  19. package/dist-cjs/rateLimits/helpers/registerStreamInterceptors.js +58 -0
  20. package/dist-cjs/rateLimits/helpers/splitCallArgsAndOptions.js +21 -0
  21. package/dist-cjs/rateLimits/index.js +7 -0
  22. package/dist-cjs/rateLimits/types.js +3 -0
  23. package/dist-cjs/rateLimits/withStreamRateLimitOptions.js +10 -0
  24. package/dist-cjs/streamRateLimitHandlingProxy/constants.js +42 -0
  25. package/dist-cjs/streamRateLimitHandlingProxy/createRateLimitedStreamProxy.js +92 -0
  26. package/dist-cjs/streamRateLimitHandlingProxy/generatedMethodNames.js +320 -0
  27. package/dist-cjs/streamRateLimitHandlingProxy/helpers/RedisCooldown.js +174 -0
  28. package/dist-cjs/streamRateLimitHandlingProxy/helpers/createRateLimitExceededException.js +29 -0
  29. package/dist-cjs/streamRateLimitHandlingProxy/helpers/executeWithRateLimitHandling.js +153 -0
  30. package/dist-cjs/streamRateLimitHandlingProxy/helpers/headerUtils.js +48 -0
  31. package/dist-cjs/streamRateLimitHandlingProxy/helpers/isStreamChannelLike.js +23 -0
  32. package/dist-cjs/streamRateLimitHandlingProxy/helpers/processStreamBudgetHeaders.js +93 -0
  33. package/dist-cjs/streamRateLimitHandlingProxy/helpers/processStreamRateLimitException.js +63 -0
  34. package/dist-cjs/streamRateLimitHandlingProxy/helpers/processStreamRateLimitHeaders.js +46 -0
  35. package/dist-cjs/streamRateLimitHandlingProxy/helpers/rateLimitSnapshot.js +31 -0
  36. package/dist-cjs/streamRateLimitHandlingProxy/helpers/registerStreamInterceptors.js +64 -0
  37. package/dist-cjs/streamRateLimitHandlingProxy/helpers/sleep.js +6 -0
  38. package/dist-cjs/streamRateLimitHandlingProxy/helpers/splitCallArgsAndOptions.js +21 -0
  39. package/dist-cjs/streamRateLimitHandlingProxy/index.js +5 -0
  40. package/dist-cjs/streamRateLimitHandlingProxy/types.js +3 -0
  41. package/dist-cjs/streamRateLimitHandlingProxy/withStreamRateLimitOptions.js +10 -0
  42. package/dist-es/anonymousEmail/index.js +1 -1
  43. package/dist-es/rateLimits/RedisCooldown.js +62 -0
  44. package/dist-es/rateLimits/constants.js +33 -0
  45. package/dist-es/rateLimits/createRateLimitedStreamProxy.js +88 -0
  46. package/dist-es/rateLimits/exception/createRateLimitExceededException.js +17 -0
  47. package/dist-es/rateLimits/exception/processStreamRateLimitException.js +37 -0
  48. package/dist-es/rateLimits/executeStreamRequestWithRateLimitHandling.js +93 -0
  49. package/dist-es/rateLimits/generatedMethodNames.js +317 -0
  50. package/dist-es/rateLimits/helpers/RedisCooldown.js +170 -0
  51. package/dist-es/rateLimits/helpers/createRateLimitExceededException.js +28 -0
  52. package/dist-es/rateLimits/helpers/executeWithRateLimitHandling.js +140 -0
  53. package/dist-es/rateLimits/helpers/headerUtils.js +34 -0
  54. package/dist-es/rateLimits/helpers/isStreamChannelLike.js +19 -0
  55. package/dist-es/rateLimits/helpers/processStreamBudgetHeaders.js +89 -0
  56. package/dist-es/rateLimits/helpers/processStreamRateLimitException.js +59 -0
  57. package/dist-es/rateLimits/helpers/processStreamRateLimitHeaders.js +46 -0
  58. package/dist-es/rateLimits/helpers/rateLimitSnapshot.js +26 -0
  59. package/dist-es/rateLimits/helpers/registerStreamBudgetInterceptors.js +44 -0
  60. package/dist-es/rateLimits/helpers/registerStreamInterceptors.js +54 -0
  61. package/dist-es/rateLimits/helpers/splitCallArgsAndOptions.js +17 -0
  62. package/dist-es/rateLimits/index.js +4 -0
  63. package/dist-es/rateLimits/types.js +1 -0
  64. package/dist-es/rateLimits/withStreamRateLimitOptions.js +6 -0
  65. package/dist-es/streamRateLimitHandlingProxy/constants.js +32 -0
  66. package/dist-es/streamRateLimitHandlingProxy/createRateLimitedStreamProxy.js +88 -0
  67. package/dist-es/streamRateLimitHandlingProxy/generatedMethodNames.js +317 -0
  68. package/dist-es/streamRateLimitHandlingProxy/helpers/RedisCooldown.js +170 -0
  69. package/dist-es/streamRateLimitHandlingProxy/helpers/createRateLimitExceededException.js +25 -0
  70. package/dist-es/streamRateLimitHandlingProxy/helpers/executeWithRateLimitHandling.js +148 -0
  71. package/dist-es/streamRateLimitHandlingProxy/helpers/headerUtils.js +42 -0
  72. package/dist-es/streamRateLimitHandlingProxy/helpers/isStreamChannelLike.js +19 -0
  73. package/dist-es/streamRateLimitHandlingProxy/helpers/processStreamBudgetHeaders.js +89 -0
  74. package/dist-es/streamRateLimitHandlingProxy/helpers/processStreamRateLimitException.js +59 -0
  75. package/dist-es/streamRateLimitHandlingProxy/helpers/processStreamRateLimitHeaders.js +42 -0
  76. package/dist-es/streamRateLimitHandlingProxy/helpers/rateLimitSnapshot.js +26 -0
  77. package/dist-es/streamRateLimitHandlingProxy/helpers/registerStreamInterceptors.js +60 -0
  78. package/dist-es/streamRateLimitHandlingProxy/helpers/sleep.js +4 -0
  79. package/dist-es/streamRateLimitHandlingProxy/helpers/splitCallArgsAndOptions.js +17 -0
  80. package/dist-es/streamRateLimitHandlingProxy/index.js +2 -0
  81. package/dist-es/streamRateLimitHandlingProxy/types.js +1 -0
  82. package/dist-es/streamRateLimitHandlingProxy/withStreamRateLimitOptions.js +6 -0
  83. package/dist-types/anonymousEmail/index.d.ts +1 -0
  84. package/dist-types/rateLimits/RedisCooldown.d.ts +7 -0
  85. package/dist-types/rateLimits/constants.d.ts +29 -0
  86. package/dist-types/rateLimits/createRateLimitedStreamProxy.d.ts +11 -0
  87. package/dist-types/rateLimits/exception/createRateLimitExceededException.d.ts +12 -0
  88. package/dist-types/rateLimits/exception/processStreamRateLimitException.d.ts +8 -0
  89. package/dist-types/rateLimits/executeStreamRequestWithRateLimitHandling.d.ts +8 -0
  90. package/dist-types/rateLimits/generatedMethodNames.d.ts +11 -0
  91. package/dist-types/rateLimits/helpers/RedisCooldown.d.ts +11 -0
  92. package/dist-types/rateLimits/helpers/createRateLimitExceededException.d.ts +10 -0
  93. package/dist-types/rateLimits/helpers/executeWithRateLimitHandling.d.ts +2 -0
  94. package/dist-types/rateLimits/helpers/headerUtils.d.ts +4 -0
  95. package/dist-types/rateLimits/helpers/isStreamChannelLike.d.ts +6 -0
  96. package/dist-types/rateLimits/helpers/processStreamBudgetHeaders.d.ts +9 -0
  97. package/dist-types/rateLimits/helpers/processStreamRateLimitException.d.ts +3 -0
  98. package/dist-types/rateLimits/helpers/processStreamRateLimitHeaders.d.ts +6 -0
  99. package/dist-types/rateLimits/helpers/rateLimitSnapshot.d.ts +3 -0
  100. package/dist-types/rateLimits/helpers/registerStreamBudgetInterceptors.d.ts +2 -0
  101. package/dist-types/rateLimits/helpers/registerStreamInterceptors.d.ts +2 -0
  102. package/dist-types/rateLimits/helpers/splitCallArgsAndOptions.d.ts +6 -0
  103. package/dist-types/rateLimits/index.d.ts +4 -0
  104. package/dist-types/rateLimits/types.d.ts +68 -0
  105. package/dist-types/rateLimits/withStreamRateLimitOptions.d.ts +6 -0
  106. package/dist-types/streamRateLimitHandlingProxy/constants.d.ts +28 -0
  107. package/dist-types/streamRateLimitHandlingProxy/createRateLimitedStreamProxy.d.ts +11 -0
  108. package/dist-types/streamRateLimitHandlingProxy/generatedMethodNames.d.ts +11 -0
  109. package/dist-types/streamRateLimitHandlingProxy/helpers/RedisCooldown.d.ts +11 -0
  110. package/dist-types/streamRateLimitHandlingProxy/helpers/createRateLimitExceededException.d.ts +10 -0
  111. package/dist-types/streamRateLimitHandlingProxy/helpers/executeWithRateLimitHandling.d.ts +2 -0
  112. package/dist-types/streamRateLimitHandlingProxy/helpers/headerUtils.d.ts +4 -0
  113. package/dist-types/streamRateLimitHandlingProxy/helpers/isStreamChannelLike.d.ts +6 -0
  114. package/dist-types/streamRateLimitHandlingProxy/helpers/processStreamBudgetHeaders.d.ts +9 -0
  115. package/dist-types/streamRateLimitHandlingProxy/helpers/processStreamRateLimitException.d.ts +3 -0
  116. package/dist-types/streamRateLimitHandlingProxy/helpers/processStreamRateLimitHeaders.d.ts +6 -0
  117. package/dist-types/streamRateLimitHandlingProxy/helpers/rateLimitSnapshot.d.ts +3 -0
  118. package/dist-types/streamRateLimitHandlingProxy/helpers/registerStreamInterceptors.d.ts +2 -0
  119. package/dist-types/streamRateLimitHandlingProxy/helpers/sleep.d.ts +2 -0
  120. package/dist-types/streamRateLimitHandlingProxy/helpers/splitCallArgsAndOptions.d.ts +6 -0
  121. package/dist-types/streamRateLimitHandlingProxy/index.d.ts +2 -0
  122. package/dist-types/streamRateLimitHandlingProxy/types.d.ts +68 -0
  123. package/dist-types/streamRateLimitHandlingProxy/withStreamRateLimitOptions.d.ts +6 -0
  124. package/package.json +1 -1
@@ -0,0 +1,19 @@
1
+ import { Channel } from 'stream-chat';
2
+ function hasFunctionProperty(value, key) {
3
+ return key in value && typeof value[key] === 'function';
4
+ }
5
+ function hasStringProperty(value, key) {
6
+ return key in value && typeof value[key] === 'string';
7
+ }
8
+ export function isStreamChannelLike(value) {
9
+ if (typeof value !== 'object' || value === null) {
10
+ return false;
11
+ }
12
+ if (value instanceof Channel) {
13
+ return true;
14
+ }
15
+ return (hasStringProperty(value, 'cid') &&
16
+ hasFunctionProperty(value, 'sendMessage') &&
17
+ hasFunctionProperty(value, 'queryMembers') &&
18
+ hasFunctionProperty(value, 'updatePartial'));
19
+ }
@@ -0,0 +1,89 @@
1
+ import { BUDGET_CLEAR_USAGE_THRESHOLD, BUDGET_DELAY_MAX_MS, BUDGET_DELAY_MIN_MS, BUDGET_MINIMAL_DELAY_MAX_MS, BUDGET_MINIMAL_DELAY_MIN_MS, BUDGET_RELAXED_DELAY_MAX_MS, BUDGET_RELAXED_DELAY_MIN_MS, BUDGET_RELAXED_USAGE_THRESHOLD, BUDGET_THRESHOLD, STREAM_BUDGET_COOLDOWN_KEY, STREAM_BUDGET_COOLDOWN_KEY_PREFIX, } from '../constants';
2
+ import { parseHeaderNumber } from './headerUtils';
3
+ import { RedisCooldown } from './RedisCooldown';
4
+ function extractBudgetHeaders(headers) {
5
+ return {
6
+ limitMs: parseHeaderNumber(headers ?? {}, 'x-budget-limit-ms'),
7
+ remainingMs: parseHeaderNumber(headers ?? {}, 'x-budget-remaining-ms'),
8
+ usedMs: parseHeaderNumber(headers ?? {}, 'x-budget-used-ms'),
9
+ };
10
+ }
11
+ function isBudgetThresholdReached(limitMs, remainingMs, usedMs) {
12
+ if (limitMs <= 0) {
13
+ return false;
14
+ }
15
+ if (typeof usedMs === 'number' && usedMs / limitMs >= BUDGET_THRESHOLD) {
16
+ return true;
17
+ }
18
+ if (typeof remainingMs === 'number') {
19
+ const remainingThreshold = (1 - BUDGET_THRESHOLD) * limitMs;
20
+ return remainingMs <= remainingThreshold;
21
+ }
22
+ return false;
23
+ }
24
+ function getRandomDelayInRange(minMs, maxMs) {
25
+ return Math.round(minMs + Math.random() * (maxMs - minMs));
26
+ }
27
+ function getBudgetUsage(limitMs, remainingMs, usedMs) {
28
+ if (limitMs <= 0) {
29
+ return 0;
30
+ }
31
+ if (typeof usedMs === 'number' && Number.isFinite(usedMs) && usedMs >= 0) {
32
+ return usedMs / limitMs;
33
+ }
34
+ if (typeof remainingMs === 'number' && Number.isFinite(remainingMs)) {
35
+ return Math.max(0, 1 - remainingMs / limitMs);
36
+ }
37
+ return 0;
38
+ }
39
+ export async function processStreamBudgetHeaders(headers, context) {
40
+ const { logger } = context;
41
+ const { limitMs, remainingMs, usedMs } = extractBudgetHeaders(headers);
42
+ if (limitMs === undefined && remainingMs === undefined && usedMs === undefined) {
43
+ return;
44
+ }
45
+ if (typeof limitMs !== 'number' || !Number.isFinite(limitMs) || limitMs <= 0) {
46
+ return;
47
+ }
48
+ const usage = getBudgetUsage(limitMs, remainingMs, usedMs);
49
+ const thresholdReached = isBudgetThresholdReached(limitMs, remainingMs, usedMs);
50
+ if (thresholdReached) {
51
+ const delayMs = getRandomDelayInRange(BUDGET_DELAY_MIN_MS, BUDGET_DELAY_MAX_MS);
52
+ await RedisCooldown.setRemainingMsExact(STREAM_BUDGET_COOLDOWN_KEY, delayMs, context, {
53
+ keyPrefix: STREAM_BUDGET_COOLDOWN_KEY_PREFIX,
54
+ });
55
+ logger.warn('Stream budget threshold reached, enabling cooldown', {
56
+ budgetLimitMs: limitMs,
57
+ budgetRemainingMs: remainingMs,
58
+ budgetUsedMs: usedMs,
59
+ budgetUsage: usage,
60
+ cooldownMs: delayMs,
61
+ });
62
+ return;
63
+ }
64
+ if (usage < BUDGET_CLEAR_USAGE_THRESHOLD) {
65
+ await RedisCooldown.clear(STREAM_BUDGET_COOLDOWN_KEY, context, {
66
+ keyPrefix: STREAM_BUDGET_COOLDOWN_KEY_PREFIX,
67
+ });
68
+ logger.info('Stream budget is low, clearing cooldown', {
69
+ budgetLimitMs: limitMs,
70
+ budgetRemainingMs: remainingMs,
71
+ budgetUsedMs: usedMs,
72
+ budgetUsage: usage,
73
+ });
74
+ return;
75
+ }
76
+ const delayMs = usage >= BUDGET_RELAXED_USAGE_THRESHOLD
77
+ ? getRandomDelayInRange(BUDGET_RELAXED_DELAY_MIN_MS, BUDGET_RELAXED_DELAY_MAX_MS)
78
+ : getRandomDelayInRange(BUDGET_MINIMAL_DELAY_MIN_MS, BUDGET_MINIMAL_DELAY_MAX_MS);
79
+ await RedisCooldown.setRemainingMsExact(STREAM_BUDGET_COOLDOWN_KEY, delayMs, context, {
80
+ keyPrefix: STREAM_BUDGET_COOLDOWN_KEY_PREFIX,
81
+ });
82
+ logger.info('Stream budget is below threshold, reducing cooldown', {
83
+ budgetLimitMs: limitMs,
84
+ budgetRemainingMs: remainingMs,
85
+ budgetUsedMs: usedMs,
86
+ budgetUsage: usage,
87
+ cooldownMs: delayMs,
88
+ });
89
+ }
@@ -0,0 +1,59 @@
1
+ import { createRateLimitExceededException } from './createRateLimitExceededException';
2
+ import { getHeaderCaseInsensitive, normalizeResetToEpochMs, parseHeaderNumber } from './headerUtils';
3
+ function parseRetryAfterMs(headers) {
4
+ const retryAfter = getHeaderCaseInsensitive(headers, 'retry-after');
5
+ if (typeof retryAfter === 'number' && Number.isFinite(retryAfter) && retryAfter >= 0) {
6
+ return Math.round(retryAfter * 1000);
7
+ }
8
+ if (typeof retryAfter !== 'string') {
9
+ return;
10
+ }
11
+ const asSeconds = Number(retryAfter);
12
+ if (Number.isFinite(asSeconds) && asSeconds >= 0) {
13
+ return Math.round(asSeconds * 1000);
14
+ }
15
+ const asDateMs = Date.parse(retryAfter);
16
+ if (!Number.isNaN(asDateMs)) {
17
+ return Math.max(0, asDateMs - Date.now());
18
+ }
19
+ }
20
+ function getRateLimitFromHeaders(headers) {
21
+ const limit = parseHeaderNumber(headers, 'x-ratelimit-limit');
22
+ const remaining = parseHeaderNumber(headers, 'x-ratelimit-remaining');
23
+ const resetRaw = parseHeaderNumber(headers, 'x-ratelimit-reset');
24
+ if (limit === undefined || remaining === undefined || resetRaw === undefined) {
25
+ return;
26
+ }
27
+ return {
28
+ limit,
29
+ remaining,
30
+ reset: normalizeResetToEpochMs(resetRaw),
31
+ };
32
+ }
33
+ function isStreamHttpRateLimitError(error) {
34
+ return (typeof error === 'object' &&
35
+ error !== null &&
36
+ (('status' in error && error.status === 429) ||
37
+ ('response' in error &&
38
+ typeof error.response === 'object' &&
39
+ error.response !== null &&
40
+ error.response?.status === 429)));
41
+ }
42
+ export function processStreamRateLimitException(error, logger) {
43
+ if (isStreamHttpRateLimitError(error)) {
44
+ const headers = error.response?.headers ?? {};
45
+ const rateLimit = getRateLimitFromHeaders(headers);
46
+ const retryAfterMs = parseRetryAfterMs(headers);
47
+ const message = error.response?.data?.message || error.message || 'Rate limit exceeded';
48
+ logger.warn('Stream rate limit exceeded [HTTP 429]', {
49
+ status: error.status ?? error.response?.status,
50
+ retryAfterMs,
51
+ rateLimit,
52
+ });
53
+ return createRateLimitExceededException({
54
+ rateLimit,
55
+ retryAfterMs,
56
+ message,
57
+ });
58
+ }
59
+ }
@@ -0,0 +1,42 @@
1
+ import { SOFT_THROTTLE_DELAY_HIGH_MS, SOFT_THROTTLE_DELAY_LOW_MS, SOFT_THROTTLE_DELAY_MEDIUM_MS, SOFT_THROTTLE_USAGE_HIGH, SOFT_THROTTLE_USAGE_LOW, SOFT_THROTTLE_USAGE_MEDIUM, STREAM_RATE_LIMIT_COOLDOWN_KEY_PREFIX, STREAM_RATE_LIMIT_SOFT_COOLDOWN_KEY, } from '../constants';
2
+ import { parseHeaderNumber } from './headerUtils';
3
+ import { RedisCooldown } from './RedisCooldown';
4
+ function computeSoftThrottleUsage(limit, remaining) {
5
+ if (limit <= 0) {
6
+ return 0;
7
+ }
8
+ return Math.max(0, 1 - remaining / limit);
9
+ }
10
+ function computeSoftThrottleDelayMs(limit, remaining) {
11
+ const usage = computeSoftThrottleUsage(limit, remaining);
12
+ if (usage >= SOFT_THROTTLE_USAGE_HIGH) {
13
+ return SOFT_THROTTLE_DELAY_HIGH_MS;
14
+ }
15
+ if (usage >= SOFT_THROTTLE_USAGE_MEDIUM) {
16
+ return SOFT_THROTTLE_DELAY_MEDIUM_MS;
17
+ }
18
+ if (usage >= SOFT_THROTTLE_USAGE_LOW) {
19
+ return SOFT_THROTTLE_DELAY_LOW_MS;
20
+ }
21
+ return 0;
22
+ }
23
+ export async function processStreamRateLimitHeaders(headers, context) {
24
+ const limit = parseHeaderNumber(headers ?? {}, 'x-ratelimit-limit');
25
+ const remaining = parseHeaderNumber(headers ?? {}, 'x-ratelimit-remaining');
26
+ if (limit === undefined || remaining === undefined) {
27
+ return;
28
+ }
29
+ if (limit <= 0 || remaining < 0) {
30
+ return;
31
+ }
32
+ const delayMs = computeSoftThrottleDelayMs(limit, remaining);
33
+ if (delayMs > 0) {
34
+ await RedisCooldown.setRemainingMs(STREAM_RATE_LIMIT_SOFT_COOLDOWN_KEY, delayMs, context, {
35
+ keyPrefix: STREAM_RATE_LIMIT_COOLDOWN_KEY_PREFIX,
36
+ });
37
+ return;
38
+ }
39
+ await RedisCooldown.clear(STREAM_RATE_LIMIT_SOFT_COOLDOWN_KEY, context, {
40
+ keyPrefix: STREAM_RATE_LIMIT_COOLDOWN_KEY_PREFIX,
41
+ });
42
+ }
@@ -0,0 +1,26 @@
1
+ const RATE_LIMIT_SNAPSHOT_PARTS_COUNT = 3;
2
+ export function serializeRateLimitSnapshot(snapshot) {
3
+ return `${snapshot.limit},${snapshot.remaining},${snapshot.reset}`;
4
+ }
5
+ export function parseRateLimitSnapshot(snapshot) {
6
+ if (typeof snapshot !== 'string' || snapshot.length === 0) {
7
+ return;
8
+ }
9
+ const parts = snapshot.split(',');
10
+ if (parts.length !== RATE_LIMIT_SNAPSHOT_PARTS_COUNT) {
11
+ return;
12
+ }
13
+ const [limitRaw, remainingRaw, resetRaw] = parts;
14
+ const limit = Number(limitRaw);
15
+ const remaining = Number(remainingRaw);
16
+ const reset = Number(resetRaw);
17
+ if (!Number.isFinite(limit) ||
18
+ !Number.isFinite(remaining) ||
19
+ !Number.isFinite(reset) ||
20
+ limit < 0 ||
21
+ remaining < 0 ||
22
+ reset <= 0) {
23
+ return;
24
+ }
25
+ return { limit, remaining, reset };
26
+ }
@@ -0,0 +1,60 @@
1
+ import { processStreamBudgetHeaders } from './processStreamBudgetHeaders';
2
+ import { processStreamRateLimitHeaders } from './processStreamRateLimitHeaders';
3
+ const attachedInterceptors = new WeakSet();
4
+ function hasResponseInterceptors(value) {
5
+ return ((typeof value === 'object' || typeof value === 'function') &&
6
+ value !== null &&
7
+ typeof value.interceptors?.response?.use === 'function');
8
+ }
9
+ function resolveAxiosInstance(stream) {
10
+ if (hasResponseInterceptors(stream)) {
11
+ return stream;
12
+ }
13
+ if (typeof stream !== 'object' || stream === null) {
14
+ return;
15
+ }
16
+ const maybeStream = stream;
17
+ if (hasResponseInterceptors(maybeStream.axiosInstance)) {
18
+ return maybeStream.axiosInstance;
19
+ }
20
+ if (hasResponseInterceptors(maybeStream._client?.axiosInstance)) {
21
+ return maybeStream._client?.axiosInstance;
22
+ }
23
+ }
24
+ export function registerStreamInterceptors(stream, context) {
25
+ const { logger } = context;
26
+ const axiosInstance = resolveAxiosInstance(stream);
27
+ if (!axiosInstance || !axiosInstance.interceptors?.response?.use) {
28
+ logger.warn('Unable to register stream budget & rate limit interceptors: axios instance not found');
29
+ return;
30
+ }
31
+ if (attachedInterceptors.has(axiosInstance)) {
32
+ return;
33
+ }
34
+ attachedInterceptors.add(axiosInstance);
35
+ try {
36
+ axiosInstance.interceptors.response.use(async (response) => {
37
+ try {
38
+ await processStreamBudgetHeaders(response?.headers, context);
39
+ await processStreamRateLimitHeaders(response?.headers, context);
40
+ }
41
+ catch (error) {
42
+ logger.warn('Failed to process Stream response headers in interceptor', { error });
43
+ }
44
+ return response;
45
+ }, async (error) => {
46
+ try {
47
+ await processStreamBudgetHeaders(error?.response?.headers, context);
48
+ await processStreamRateLimitHeaders(error?.response?.headers, context);
49
+ }
50
+ catch (interceptorError) {
51
+ logger.warn('Failed to process Stream error headers in interceptor', { error: interceptorError });
52
+ }
53
+ return Promise.reject(error);
54
+ });
55
+ }
56
+ catch (error) {
57
+ attachedInterceptors.delete(axiosInstance);
58
+ logger.warn('Failed to register Stream response interceptors', { error });
59
+ }
60
+ }
@@ -0,0 +1,4 @@
1
+ async function sleep(ms) {
2
+ return new Promise((resolve) => setTimeout(resolve, ms));
3
+ }
4
+ export default sleep;
@@ -0,0 +1,17 @@
1
+ import { STREAM_RATE_LIMIT_OPTIONS_MARKER } from '../constants';
2
+ function isStreamRateLimitOptionsToken(value) {
3
+ return typeof value === 'object' && value !== null && STREAM_RATE_LIMIT_OPTIONS_MARKER in value;
4
+ }
5
+ export function splitCallArgsAndOptions(args) {
6
+ if (args.length === 0) {
7
+ return { callArgs: args, callOptions: {} };
8
+ }
9
+ const lastArg = args[args.length - 1];
10
+ if (isStreamRateLimitOptionsToken(lastArg)) {
11
+ return {
12
+ callArgs: args.slice(0, -1),
13
+ callOptions: lastArg[STREAM_RATE_LIMIT_OPTIONS_MARKER],
14
+ };
15
+ }
16
+ return { callArgs: args, callOptions: {} };
17
+ }
@@ -0,0 +1,2 @@
1
+ export * from './createRateLimitedStreamProxy';
2
+ export * from './withStreamRateLimitOptions';
@@ -0,0 +1 @@
1
+ import { STREAM_RATE_LIMIT_OPTIONS_MARKER } from './constants';
@@ -0,0 +1,6 @@
1
+ import { STREAM_RATE_LIMIT_OPTIONS_MARKER } from './constants';
2
+ export function withStreamRateLimitOptions(options) {
3
+ return {
4
+ [STREAM_RATE_LIMIT_OPTIONS_MARKER]: options,
5
+ };
6
+ }
@@ -1,2 +1,3 @@
1
+ export declare const ANONYMOUS_EMAIL_DOMAIN = "anonymous.wildix.com";
1
2
  export declare function generateAnonymousUserEmailOrThrowError(streamId: string): string;
2
3
  export declare function isAnonymousUserEmail(value: string): boolean;
@@ -0,0 +1,7 @@
1
+ import {LoggerContext, RedisContext} from './types';
2
+
3
+ export declare class RedisCooldown {
4
+ static getRemainingMs(cooldownKey: string, context: RedisContext & LoggerContext): Promise<number>;
5
+
6
+ static setRemainingMs(cooldownKey: string, cooldownMs: number, context: RedisContext & LoggerContext): Promise<void>;
7
+ }
@@ -0,0 +1,29 @@
1
+ import { StreamRateLimitRetryOptions } from './types';
2
+ export { CHANNEL_METHOD_NAMES, CHANNEL_SYNC_METHOD_NAMES, CHANNEL_SYNC_PROXY_RESULT_METHOD_NAMES, STREAM_CHANNEL_RESULT_METHOD_NAMES, STREAM_METHOD_NAMES, STREAM_SYNC_CHANNEL_RESULT_METHOD_NAMES, STREAM_SYNC_METHOD_NAMES, } from './generatedMethodNames';
3
+ export declare const DEFAULT_MAX_DELAY_MS = 5000;
4
+ export declare const DEFAULT_RETRY_AFTER_MS = 10000;
5
+ export declare const DEFAULT_JITTER_MS = 150;
6
+ export declare const RETRY_AFTER_BUFFER_MS = 1000;
7
+ export declare const STREAM_RATE_LIMIT_COOLDOWN_KEY_PREFIX = "stream-rate-limit-cooldown:";
8
+ export declare const STREAM_BUDGET_COOLDOWN_KEY_PREFIX = "stream-budget-cooldown:";
9
+ export declare const STREAM_RATE_LIMIT_OPTIONS_MARKER = "__xbsRateLimitOptions";
10
+ export declare const STREAM_RATE_LIMIT_SOFT_COOLDOWN_KEY = "stream-rate-limit-soft-global";
11
+ export declare const STREAM_RATE_LIMIT_METADATA_KEY_SUFFIX = ":meta";
12
+ export declare const STREAM_BUDGET_COOLDOWN_KEY = "stream-budget-global";
13
+ export declare const BUDGET_THRESHOLD = 0.8;
14
+ export declare const BUDGET_DELAY_MIN_MS = 30000;
15
+ export declare const BUDGET_DELAY_MAX_MS = 60000;
16
+ export declare const BUDGET_CLEAR_USAGE_THRESHOLD = 0.6;
17
+ export declare const BUDGET_RELAXED_USAGE_THRESHOLD = 0.7;
18
+ export declare const BUDGET_RELAXED_DELAY_MIN_MS = 5000;
19
+ export declare const BUDGET_RELAXED_DELAY_MAX_MS = 10000;
20
+ export declare const BUDGET_MINIMAL_DELAY_MIN_MS = 1000;
21
+ export declare const BUDGET_MINIMAL_DELAY_MAX_MS = 2000;
22
+ export declare const BUDGET_COOLDOWN_SLEEP_CHUNK_MS = 3000;
23
+ export declare const SOFT_THROTTLE_USAGE_LOW = 0.7;
24
+ export declare const SOFT_THROTTLE_USAGE_MEDIUM = 0.85;
25
+ export declare const SOFT_THROTTLE_USAGE_HIGH = 0.95;
26
+ export declare const SOFT_THROTTLE_DELAY_LOW_MS = 500;
27
+ export declare const SOFT_THROTTLE_DELAY_MEDIUM_MS = 1500;
28
+ export declare const SOFT_THROTTLE_DELAY_HIGH_MS = 3000;
29
+ export declare const DEFAULT_OPTIONS: StreamRateLimitRetryOptions;
@@ -0,0 +1,11 @@
1
+ import { StreamChat } from 'stream-chat';
2
+ import { StreamType } from '../stream';
3
+ import { LoggerContext, MethodWithRateLimitOptions, RedisContext } from './types';
4
+ export type RateLimited<T extends object> = {
5
+ [Key in keyof T]: MethodWithRateLimitOptions<T[Key]>;
6
+ };
7
+ /**
8
+ * Creates a proxy around a Stream client that transparently applies rate-limit handling
9
+ * to method calls and recursively wraps returned channel objects with the same behavior.
10
+ */
11
+ export declare function createRateLimitedStreamProxy(stream: StreamChat<StreamType>, context: LoggerContext & RedisContext): RateLimited<StreamChat<StreamType>>;
@@ -0,0 +1,12 @@
1
+ import {RateLimitExceededException} from '@wildix/xbees-conversations-client';
2
+
3
+ import {RateLimitsInfo} from 'stream-chat';
4
+
5
+ type Options = {
6
+ rateLimit?: RateLimitsInfo;
7
+ message?: string;
8
+ operation?: string;
9
+ retryAfterMs?: number;
10
+ };
11
+ export declare function createRateLimitExceededException(options?: Options): RateLimitExceededException;
12
+ export {};
@@ -0,0 +1,8 @@
1
+ import {RateLimitExceededException} from '@wildix/xbees-conversations-client';
2
+
3
+ import {Logger} from '@aws-lambda-powertools/logger';
4
+
5
+ export declare function processStreamRateLimitException(
6
+ error: unknown,
7
+ logger: Logger,
8
+ ): RateLimitExceededException | undefined;
@@ -0,0 +1,8 @@
1
+ import {LoggerContext, RedisContext, StreamOperationType, StreamRateLimitRetryOptions} from './types';
2
+
3
+ export declare function executeStreamRequestWithRateLimitHandling<T>(
4
+ execute: () => Promise<T>,
5
+ operation: StreamOperationType,
6
+ context: LoggerContext & RedisContext,
7
+ options?: Partial<StreamRateLimitRetryOptions>,
8
+ ): Promise<T>;
@@ -0,0 +1,11 @@
1
+ /**
2
+ * This file is auto-generated by `scripts/generateRateLimitMethodNames.mjs`.
3
+ * Do not edit manually.
4
+ */
5
+ export declare const STREAM_METHOD_NAMES: readonly ["_addChannelConfig", "_buildWSPayload", "_callClientListeners", "_createImport", "_createImportURL", "_deleteUserMessageReference", "_enrichAxiosOptions", "_getConnectionID", "_getImport", "_getToken", "_handleClientEvent", "_handleUserEvent", "_hasConnectionID", "_isUsingServerAuth", "_listImports", "_logApiError", "_logApiRequest", "_logApiResponse", "_muteStatus", "_normalizeDate", "_normalizeExpiration", "_queryFlagReports", "_queryFlags", "_reviewFlagReport", "_sayHi", "_setToken", "_setupConnection", "_setUser", "_startCleaning", "_unblockMessage", "_updateMemberWatcherReferences", "_updateUserMessageReferences", "_updateUserReferences", "_validateAndGetMessageId", "addDevice", "banUser", "channel", "closeConnection", "commitMessage", "connect", "connectAnonymousUser", "connectUser", "createAbortControllerForNextRequest", "createBlockList", "createCampaign", "createChannelType", "createCommand", "createPermission", "createRole", "createSegment", "createToken", "deactivateUser", "deactivateUsers", "delete", "deleteBlockList", "deleteCampaign", "deleteChannels", "deleteChannelType", "deleteCommand", "deleteMessage", "deletePermission", "deletePushProvider", "deleteRole", "deleteSegment", "deleteUser", "deleteUsers", "devToken", "disconnect", "disconnectUser", "dispatchEvent", "doAxiosRequest", "enrichURL", "errorFromResponse", "exportChannel", "exportChannels", "exportUser", "exportUsers", "flagMessage", "flagUser", "get", "getAppSettings", "getAuthType", "getBlockList", "getCallToken", "getChannelById", "getChannelByMembers", "getChannelType", "getCommand", "getDevices", "getExportChannelStatus", "getMessage", "getPermission", "getRateLimits", "getTask", "getUnreadCount", "getUserAgent", "handleEvent", "handleResponse", "hydrateActiveChannels", "listBlockLists", "listChannelTypes", "listCommands", "listPermissions", "listPushProviders", "listRoles", "markAllRead", "markChannelsRead", "muteUser", "off", "on", "openConnection", "partialUpdateMessage", "partialUpdateUser", "partialUpdateUsers", "patch", "pinMessage", "post", "put", "queryBannedUsers", "queryCampaigns", "queryChannels", "queryMessageFlags", "queryRecipients", "querySegments", "queryUsers", "reactivateUser", "reactivateUsers", "recoverState", "removeDevice", "removeShadowBan", "restoreUsers", "resumeCampaign", "revokeTokens", "revokeUsersToken", "revokeUserToken", "scheduleCampaign", "search", "sendFile", "sendUserCustomEvent", "setAnonymousUser", "setBaseURL", "setGuestUser", "setLocalDevice", "setUser", "setUserAgent", "shadowBan", "stopCampaign", "sync", "testCampaign", "testPushSettings", "testSQSSettings", "translateMessage", "unbanUser", "unblockMessage", "unflagMessage", "unflagUser", "unmuteUser", "unpinMessage", "updateAppSettings", "updateBlockList", "updateCampaign", "updateChannelType", "updateCommand", "updateMessage", "updatePermission", "updateSegment", "updateUser", "updateUsers", "upsertPushProvider", "upsertUser", "upsertUsers", "userMuteStatus", "verifyWebhook"];
6
+ export declare const STREAM_SYNC_METHOD_NAMES: readonly ["_addChannelConfig", "_buildWSPayload", "_callClientListeners", "_deleteUserMessageReference", "_enrichAxiosOptions", "_getConnectionID", "_getToken", "_handleClientEvent", "_handleUserEvent", "_hasConnectionID", "_isUsingServerAuth", "_logApiError", "_logApiRequest", "_logApiResponse", "_muteStatus", "_normalizeDate", "_normalizeExpiration", "_sayHi", "_setUser", "_startCleaning", "_updateMemberWatcherReferences", "_updateUserMessageReferences", "_updateUserReferences", "_validateAndGetMessageId", "createAbortControllerForNextRequest", "createToken", "devToken", "dispatchEvent", "errorFromResponse", "getAuthType", "getUserAgent", "handleEvent", "handleResponse", "off", "on", "setBaseURL", "setLocalDevice", "setUserAgent", "userMuteStatus", "verifyWebhook"];
7
+ export declare const STREAM_CHANNEL_RESULT_METHOD_NAMES: readonly ["channel", "getChannelById", "getChannelByMembers", "hydrateActiveChannels", "queryChannels"];
8
+ export declare const STREAM_SYNC_CHANNEL_RESULT_METHOD_NAMES: readonly ["channel", "getChannelById", "getChannelByMembers", "hydrateActiveChannels"];
9
+ export declare const CHANNEL_METHOD_NAMES: readonly ["_callChannelListeners", "_channelURL", "_checkInitialized", "_countMessageAsUnread", "_disconnect", "_extendEventWithOwnReactions", "_handleChannelEvent", "_initializeState", "_update", "acceptInvite", "addMembers", "addModerators", "assignRoles", "banUser", "clean", "countUnread", "countUnreadMentions", "create", "createCall", "delete", "deleteFile", "deleteImage", "deleteReaction", "demoteModerators", "disableSlowMode", "enableSlowMode", "getClient", "getConfig", "getMessagesById", "getPinnedMessages", "getReactions", "getReplies", "hide", "inviteMembers", "keystroke", "lastMessage", "lastRead", "markRead", "markUnread", "mute", "muteStatus", "off", "on", "query", "queryMembers", "rejectInvite", "removeMembers", "removeShadowBan", "search", "sendAction", "sendEvent", "sendFile", "sendImage", "sendMessage", "sendReaction", "shadowBan", "show", "stopTyping", "stopWatching", "truncate", "unbanUser", "unmute", "update", "updatePartial", "watch"];
10
+ export declare const CHANNEL_SYNC_METHOD_NAMES: readonly ["_callChannelListeners", "_channelURL", "_checkInitialized", "_countMessageAsUnread", "_disconnect", "_extendEventWithOwnReactions", "_handleChannelEvent", "_initializeState", "clean", "countUnread", "countUnreadMentions", "getConfig", "lastMessage", "lastRead", "muteStatus", "off", "on"];
11
+ export declare const CHANNEL_SYNC_PROXY_RESULT_METHOD_NAMES: readonly ["getClient"];
@@ -0,0 +1,11 @@
1
+ import { LoggerContext, RedisContext, RedisCooldownOptions } from '../types';
2
+ export declare class RedisCooldown {
3
+ private static resolveRedisKey;
4
+ static getRemainingMs(cooldownKey: string, context: RedisContext & LoggerContext, options?: RedisCooldownOptions): Promise<number>;
5
+ static setRemainingMs(cooldownKey: string, cooldownMs: number, context: RedisContext & LoggerContext, options?: RedisCooldownOptions): Promise<void>;
6
+ static setRemainingMsExact(cooldownKey: string, cooldownMs: number, context: RedisContext & LoggerContext, options?: RedisCooldownOptions): Promise<void>;
7
+ static getValue(cooldownKey: string, context: RedisContext & LoggerContext, options?: RedisCooldownOptions): Promise<string | undefined>;
8
+ static setValueWithRemainingMs(cooldownKey: string, value: string, cooldownMs: number, context: RedisContext & LoggerContext, options?: RedisCooldownOptions): Promise<void>;
9
+ static setRemainingMsWithValue(cooldownKey: string, valueKey: string, value: string, cooldownMs: number, context: RedisContext & LoggerContext, options?: RedisCooldownOptions): Promise<void>;
10
+ static clear(cooldownKey: string, context: RedisContext & LoggerContext, options?: RedisCooldownOptions): Promise<void>;
11
+ }
@@ -0,0 +1,10 @@
1
+ import { RateLimitExceededException } from '@wildix/xbees-conversations-client';
2
+ import { RateLimitsInfo } from 'stream-chat';
3
+ type Options = {
4
+ rateLimit?: RateLimitsInfo;
5
+ message?: string;
6
+ operation?: string;
7
+ retryAfterMs?: number;
8
+ };
9
+ export declare function createRateLimitExceededException(options?: Options): RateLimitExceededException;
10
+ export {};
@@ -0,0 +1,2 @@
1
+ import { LoggerContext, RedisContext, StreamOperationType, StreamRateLimitRetryOptions } from '../types';
2
+ export declare function executeWithRateLimitHandling<T>(execute: () => Promise<T>, operation: StreamOperationType, context: LoggerContext & RedisContext, options: StreamRateLimitRetryOptions): Promise<T>;
@@ -0,0 +1,4 @@
1
+ import { StreamHeaders } from '../types';
2
+ export declare function getHeaderCaseInsensitive(headers: StreamHeaders | Record<string, unknown> | undefined, key: string): unknown;
3
+ export declare function parseHeaderNumber(headers: StreamHeaders | Record<string, unknown>, key: string): number | undefined;
4
+ export declare function normalizeResetToEpochMs(reset: number): number;
@@ -0,0 +1,6 @@
1
+ /**
2
+ * Detects Stream channel-like objects.
3
+ * These objects should be correctly wrapped to keep rate-limit behavior
4
+ * on methods returned from other proxied calls.
5
+ */
6
+ export declare function isStreamChannelLike(value: unknown): value is object;
@@ -0,0 +1,9 @@
1
+ import { LoggerContext, RedisContext, StreamHeaders } from '../types';
2
+ /**
3
+ * Updates app-wide Stream budget cooldown in Redis based on x-budget-* headers.
4
+ * - If budget usage reaches the threshold (>=80%), enables cooldown for 30-60s.
5
+ * - If usage is between 60% and 80%, keeps a shorter cooldown.
6
+ * - If usage drops below 60%, clears cooldown.
7
+ * - If headers are missing/invalid, leaves current cooldown unchanged.
8
+ */
9
+ export declare function processStreamBudgetHeaders(headers: StreamHeaders | undefined, context: LoggerContext & RedisContext): Promise<void>;
@@ -0,0 +1,3 @@
1
+ import { RateLimitExceededException } from '@wildix/xbees-conversations-client';
2
+ import { Logger } from '@aws-lambda-powertools/logger';
3
+ export declare function processStreamRateLimitException(error: unknown, logger: Logger): RateLimitExceededException | undefined;
@@ -0,0 +1,6 @@
1
+ import { LoggerContext, RedisContext, StreamHeaders } from '../types';
2
+ /**
3
+ * Applies soft global throttle from x-ratelimit-* headers to smooth bursts
4
+ * before hard 429 throttling starts.
5
+ */
6
+ export declare function processStreamRateLimitHeaders(headers: StreamHeaders | undefined, context: LoggerContext & RedisContext): Promise<void>;
@@ -0,0 +1,3 @@
1
+ import { StreamRateLimitSnapshot } from '../types';
2
+ export declare function serializeRateLimitSnapshot(snapshot: StreamRateLimitSnapshot): string;
3
+ export declare function parseRateLimitSnapshot(snapshot: string | null | undefined): StreamRateLimitSnapshot | undefined;
@@ -0,0 +1,2 @@
1
+ import { LoggerContext, RedisContext } from '../types';
2
+ export declare function registerStreamBudgetInterceptors(stream: unknown, context: LoggerContext & RedisContext): void;
@@ -0,0 +1,2 @@
1
+ import { LoggerContext, RedisContext } from '../types';
2
+ export declare function registerStreamInterceptors(stream: unknown, context: LoggerContext & RedisContext): void;
@@ -0,0 +1,6 @@
1
+ import { ArgsAndOptions } from '../types';
2
+ /**
3
+ * Splits original call args and optional rate-limit options token.
4
+ * If no token is provided, options fallback to an empty object.
5
+ */
6
+ export declare function splitCallArgsAndOptions(args: unknown[]): ArgsAndOptions;
@@ -0,0 +1,4 @@
1
+ export * from './createRateLimitedStreamProxy';
2
+ export * from './helpers/createRateLimitExceededException';
3
+ export * from './helpers/processStreamRateLimitException';
4
+ export * from './withStreamRateLimitOptions';
@@ -0,0 +1,68 @@
1
+ import Redis from 'ioredis';
2
+ import { StreamChat } from 'stream-chat';
3
+ import { StreamChannel, StreamType } from '../stream';
4
+ import { STREAM_RATE_LIMIT_OPTIONS_MARKER } from './constants';
5
+ import { Logger } from '@aws-lambda-powertools/logger';
6
+ export type StreamOperationType = keyof StreamChat<StreamType> | keyof StreamChannel;
7
+ export interface StreamRateLimitRetryOptions {
8
+ enableCooldown: boolean;
9
+ maxAttempts: number;
10
+ maxDelayMs: number;
11
+ maxRetryableDelayMs: number;
12
+ }
13
+ export type StreamRateLimitOptionsToken = {
14
+ [STREAM_RATE_LIMIT_OPTIONS_MARKER]: Partial<StreamRateLimitRetryOptions>;
15
+ };
16
+ export type MethodWithRateLimitOptions<T> = T extends (...args: infer Args) => infer Result ? T & ((...args: [...Args, StreamRateLimitOptionsToken?]) => Result) : T;
17
+ export type RedisContext = {
18
+ redis: Redis;
19
+ };
20
+ export type LoggerContext = {
21
+ logger: Logger;
22
+ };
23
+ export type ArgsAndOptions = {
24
+ callArgs: unknown[];
25
+ callOptions: Partial<StreamRateLimitRetryOptions>;
26
+ };
27
+ /** Optional Redis key namespace override for cooldown records. */
28
+ export type RedisCooldownOptions = {
29
+ keyPrefix?: string;
30
+ };
31
+ /** Generic HTTP headers shape returned by the Stream SDK transport layer. */
32
+ export type StreamHeaders = Record<string, unknown>;
33
+ /** Parsed GetStream budget headers used to manage app-wide cooldown. */
34
+ export type StreamBudgetHeaders = {
35
+ limitMs?: number;
36
+ remainingMs?: number;
37
+ usedMs?: number;
38
+ };
39
+ export type StreamRateLimitSnapshot = {
40
+ limit: number;
41
+ remaining: number;
42
+ reset: number;
43
+ };
44
+ /** Axios response shape used by budget interceptor. */
45
+ export type StreamBudgetInterceptorResponse = {
46
+ headers?: StreamHeaders;
47
+ };
48
+ /** Axios error shape used by budget interceptor. */
49
+ export type StreamBudgetInterceptorError = {
50
+ response?: StreamBudgetInterceptorResponse;
51
+ };
52
+ /** Minimal axios response interceptor manager contract required by this package. */
53
+ export type AxiosResponseInterceptorManagerLike = {
54
+ use: (onFulfilled?: (response: StreamBudgetInterceptorResponse) => unknown | Promise<unknown>, onRejected?: (error: StreamBudgetInterceptorError) => unknown | Promise<unknown>) => unknown;
55
+ };
56
+ /** Minimal axios instance contract required to register budget interceptors. */
57
+ export type AxiosLikeWithResponseInterceptors = {
58
+ interceptors?: {
59
+ response?: AxiosResponseInterceptorManagerLike;
60
+ };
61
+ };
62
+ /** Stream client variants where axios transport can be discovered. */
63
+ export type StreamClientWithAxiosCandidates = {
64
+ axiosInstance?: unknown;
65
+ _client?: {
66
+ axiosInstance?: unknown;
67
+ };
68
+ };
@@ -0,0 +1,6 @@
1
+ import { StreamRateLimitOptionsToken, StreamRateLimitRetryOptions } from './types';
2
+ /**
3
+ * Creates a marker token that can be passed as the last argument to proxied Stream methods.
4
+ * The proxy strips this token from original method args and uses it as per-call retry options.
5
+ */
6
+ export declare function withStreamRateLimitOptions(options: Partial<StreamRateLimitRetryOptions>): StreamRateLimitOptionsToken;