@friggframework/core 2.0.0--canary.731.ffe61d3.0 → 2.0.0--canary.657.18fb0ee.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CLAUDE.md +93 -48
- package/application/commands/README.md +11 -17
- package/application/commands/entity-commands.js +60 -18
- package/application/commands/integration-commands.js +0 -63
- package/core/CLAUDE.md +30 -1
- package/core/Worker.js +310 -9
- package/core/create-handler.js +3 -0
- package/core/index.js +6 -0
- package/core/invocation-deadline.js +91 -0
- package/core/invocation-scope.js +30 -24
- package/database/documentdb-encryption-service.js +33 -2
- package/database/documentdb-utils.js +1 -4
- package/database/encryption/README.md +3 -3
- package/database/encryption/encryption-schema-registry.js +29 -109
- package/database/encryption/field-encryption-service.js +16 -55
- package/database/encryption/prisma-encryption-extension.js +9 -6
- package/database/prisma.js +1 -10
- package/encrypt/Cryptor.js +38 -90
- package/errors/fetch-error.js +11 -18
- package/errors/index.js +2 -4
- package/errors/rate-limit-error.js +45 -0
- package/generated/prisma-mongodb/edge.js +2 -6
- package/generated/prisma-mongodb/index.js +2 -10
- package/generated/prisma-mongodb/package.json +1 -1
- package/generated/prisma-mongodb/schema.prisma +1 -1
- package/generated/prisma-mongodb/wasm.js +2 -6
- package/generated/prisma-postgresql/edge.js +2 -6
- package/generated/prisma-postgresql/index.js +2 -10
- package/generated/prisma-postgresql/package.json +1 -1
- package/generated/prisma-postgresql/schema.prisma +1 -1
- package/generated/prisma-postgresql/wasm.js +2 -6
- package/handlers/WEBHOOKS.md +0 -29
- package/handlers/app-definition-loader.js +2 -9
- package/handlers/app-handler-helpers.js +1 -12
- package/handlers/backend-utils.js +30 -1
- package/handlers/workers/integration-defined-workers.js +2 -0
- package/index.js +18 -2
- package/infrastructure/scheduler/eventbridge-scheduler-adapter.js +15 -67
- package/integrations/integration-base.js +9 -52
- package/integrations/integration-router.js +22 -30
- package/integrations/repositories/integration-mapping-repository-documentdb.js +0 -50
- package/integrations/repositories/integration-mapping-repository-interface.js +0 -15
- package/integrations/repositories/integration-mapping-repository-mongo.js +0 -29
- package/integrations/repositories/integration-mapping-repository-postgres.js +0 -30
- package/integrations/repositories/integration-mapping-repository.js +0 -29
- package/integrations/repositories/integration-repository-documentdb.js +0 -32
- package/integrations/repositories/integration-repository-interface.js +0 -30
- package/integrations/repositories/integration-repository-mongo.js +1 -53
- package/integrations/repositories/integration-repository-postgres.js +0 -58
- package/integrations/repositories/process-repository-mongo.js +1 -1
- package/integrations/use-cases/clear-rate-limit-wait.js +28 -0
- package/integrations/use-cases/create-integration.js +19 -57
- package/integrations/use-cases/delete-integration-for-user.js +11 -8
- package/integrations/use-cases/get-integration-instance.js +12 -12
- package/integrations/use-cases/index.js +5 -1
- package/integrations/use-cases/record-rate-limit-wait.js +36 -0
- package/integrations/use-cases/update-integration.js +12 -12
- package/jest-setup.js +2 -13
- package/jest-teardown.js +2 -5
- package/jest.config.js +0 -4
- package/logs/serialize.js +15 -0
- package/modules/requester/oauth-2.js +7 -0
- package/modules/requester/rate-limit/index.js +4 -0
- package/modules/requester/rate-limit/parsers.js +245 -0
- package/modules/requester/rate-limit/policy.js +304 -0
- package/modules/requester/requester.js +187 -9
- package/modules/use-cases/get-entity-options-by-id.js +5 -7
- package/modules/use-cases/get-module.js +8 -29
- package/modules/use-cases/process-authorization-callback.js +27 -78
- package/modules/use-cases/refresh-entity-options.js +5 -7
- package/modules/use-cases/test-module-auth.js +5 -7
- package/modules/utils/map-module-dto.js +3 -5
- package/package.json +8 -9
- package/prisma-mongodb/schema.prisma +1 -1
- package/prisma-postgresql/schema.prisma +1 -1
- package/queues/queue-deferral.js +74 -0
- package/queues/queue-delivery.js +1 -0
- package/queues/queuer-util.js +6 -7
- package/telemetry/otel-telemetry.js +3 -76
- package/telemetry/telemetry-config.js +5 -16
- package/telemetry/telemetry-runtime.js +1 -14
- package/token/repositories/token-repository-documentdb.js +1 -13
- package/token/repositories/token-repository-mongo.js +1 -13
- package/token/repositories/token-repository-postgres.js +1 -13
- package/types/core/index.d.ts +52 -0
- package/types/errors/index.d.ts +47 -0
- package/types/module-plugin/index.d.ts +43 -0
- package/user/tests/doubles/test-user-repository.js +1 -1
- package/user/use-cases/authenticate-user.js +7 -23
- package/user/use-cases/get-user-from-bearer-token.js +2 -7
- package/database/encryption/ciphertext-format.js +0 -24
- package/errors/mapping-already-exists-error.js +0 -14
- package/generated/prisma-mongodb/libquery_engine-linux-arm64-openssl-3.0.x.so.node +0 -0
- package/generated/prisma-postgresql/libquery_engine-linux-arm64-openssl-3.0.x.so.node +0 -0
- package/integrations/use-cases/add-entities-to-integration.js +0 -92
- package/integrations/use-cases/remove-entities-from-integration.js +0 -70
- package/integrations/utils/assert-entity-ids-input.js +0 -42
- package/jest.db.config.js +0 -23
- package/modules/use-cases/create-entity-from-credential.js +0 -105
- package/modules/utils/find-module-definition.js +0 -23
- package/modules/utils/to-credential-id.js +0 -14
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
const keepsCurrentRateLimit = (current, next) => {
|
|
2
|
+
if (!current) return false;
|
|
3
|
+
if (next.status === 'EXHAUSTED') return false;
|
|
4
|
+
if (current.status === 'EXHAUSTED') return true;
|
|
5
|
+
return Date.parse(current.retryAt) > next.retryAt.getTime();
|
|
6
|
+
};
|
|
7
|
+
|
|
8
|
+
class RecordRateLimitWait {
|
|
9
|
+
constructor({ processRepository }) {
|
|
10
|
+
if (!processRepository) {
|
|
11
|
+
throw new Error('processRepository is required');
|
|
12
|
+
}
|
|
13
|
+
this.processRepository = processRepository;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
async execute(processId, wait) {
|
|
17
|
+
const process = await this.processRepository.findById(processId);
|
|
18
|
+
if (keepsCurrentRateLimit(process?.context?.rateLimit, wait)) return;
|
|
19
|
+
await this.processRepository.applyProcessUpdate(processId, {
|
|
20
|
+
set: {
|
|
21
|
+
'context.rateLimit': {
|
|
22
|
+
status: wait.status,
|
|
23
|
+
mechanism: wait.mechanism,
|
|
24
|
+
retryAt: wait.retryAt.toISOString(),
|
|
25
|
+
reason: wait.reason,
|
|
26
|
+
module: wait.module,
|
|
27
|
+
deferrals: wait.deferrals,
|
|
28
|
+
deferralId: wait.deferralId,
|
|
29
|
+
updatedAt: new Date().toISOString(),
|
|
30
|
+
},
|
|
31
|
+
},
|
|
32
|
+
});
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
module.exports = { RecordRateLimitWait };
|
|
@@ -1,4 +1,3 @@
|
|
|
1
|
-
const Boom = require('@hapi/boom');
|
|
2
1
|
const {
|
|
3
2
|
mapIntegrationClassToIntegrationDTO,
|
|
4
3
|
} = require('../utils/map-integration-dto');
|
|
@@ -28,21 +27,16 @@ class UpdateIntegration {
|
|
|
28
27
|
* @param {string} userId - ID of the user requesting the update.
|
|
29
28
|
* @param {Object} config - New configuration object for the integration.
|
|
30
29
|
* @returns {Promise<Object>} The updated integration DTO.
|
|
31
|
-
* @throws {
|
|
32
|
-
* @throws {Error} When integration class is not found.
|
|
30
|
+
* @throws {Error} When integration is not found, doesn't belong to user, or integration class is not found.
|
|
33
31
|
*/
|
|
34
32
|
async execute(integrationId, userId, config) {
|
|
35
33
|
// 1. Get integration record from repository
|
|
36
|
-
const integrationRecord =
|
|
37
|
-
.findIntegrationById(integrationId)
|
|
38
|
-
.catch((error) => {
|
|
39
|
-
if (error.message?.includes('not found')) return null;
|
|
40
|
-
throw error;
|
|
41
|
-
});
|
|
34
|
+
const integrationRecord =
|
|
35
|
+
await this.integrationRepository.findIntegrationById(integrationId);
|
|
42
36
|
|
|
43
|
-
if (!integrationRecord
|
|
44
|
-
throw
|
|
45
|
-
`
|
|
37
|
+
if (!integrationRecord) {
|
|
38
|
+
throw new Error(
|
|
39
|
+
`No integration found by the ID of ${integrationId}`
|
|
46
40
|
);
|
|
47
41
|
}
|
|
48
42
|
|
|
@@ -59,6 +53,12 @@ class UpdateIntegration {
|
|
|
59
53
|
);
|
|
60
54
|
}
|
|
61
55
|
|
|
56
|
+
if (integrationRecord.userId !== userId) {
|
|
57
|
+
throw new Error(
|
|
58
|
+
`Integration ${integrationId} does not belong to User ${userId}`
|
|
59
|
+
);
|
|
60
|
+
}
|
|
61
|
+
|
|
62
62
|
// 3. Load modules based on entity references
|
|
63
63
|
const modules = [];
|
|
64
64
|
for (const entityId of integrationRecord.entitiesIds) {
|
package/jest-setup.js
CHANGED
|
@@ -1,13 +1,2 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
// MongoDB (as @friggframework/test's globalSetup does): nothing in the default
|
|
4
|
-
// suite talks to a live server, and a binary that failed to start used to stop
|
|
5
|
-
// every core suite from running. Suites that need a real database are
|
|
6
|
-
// `*.db.test.js` files, run by `npm run test:db` (see jest.db.config.js).
|
|
7
|
-
const { overrideEnvironment } = require('@friggframework/test');
|
|
8
|
-
|
|
9
|
-
module.exports = async function () {
|
|
10
|
-
if (!process.env.STAGE) {
|
|
11
|
-
overrideEnvironment({ STAGE: 'dev' });
|
|
12
|
-
}
|
|
13
|
-
};
|
|
1
|
+
const {globalSetup} = require('@friggframework/test');
|
|
2
|
+
module.exports = globalSetup;
|
package/jest-teardown.js
CHANGED
package/jest.config.js
CHANGED
|
@@ -20,8 +20,4 @@ module.exports = {
|
|
|
20
20
|
globalTeardown: './jest-teardown.js',
|
|
21
21
|
|
|
22
22
|
setupFilesAfterEnv: ['./logs/jest-logger-setup.js'],
|
|
23
|
-
|
|
24
|
-
// `*.db.test.js` suites talk to a real MongoDB replica set / PostgreSQL
|
|
25
|
-
// and run separately via `npm run test:db` (jest.db.config.js).
|
|
26
|
-
testPathIgnorePatterns: ['/node_modules/', '\\.db\\.test\\.js$'],
|
|
27
23
|
};
|
package/logs/serialize.js
CHANGED
|
@@ -235,6 +235,20 @@ function errorCode(err) {
|
|
|
235
235
|
return undefined;
|
|
236
236
|
}
|
|
237
237
|
|
|
238
|
+
function rateLimitFields(err) {
|
|
239
|
+
const retryAt = attempt(
|
|
240
|
+
() => (err.isRateLimited ? err.retryAt : undefined),
|
|
241
|
+
undefined
|
|
242
|
+
);
|
|
243
|
+
if (!(retryAt instanceof Date) || Number.isNaN(retryAt.getTime())) {
|
|
244
|
+
return {};
|
|
245
|
+
}
|
|
246
|
+
const reason = attempt(() => err.reason, undefined);
|
|
247
|
+
return typeof reason === 'string'
|
|
248
|
+
? { retryAt: retryAt.toISOString(), reason: cleanString(reason) }
|
|
249
|
+
: { retryAt: retryAt.toISOString() };
|
|
250
|
+
}
|
|
251
|
+
|
|
238
252
|
function errorStack(err, type, message) {
|
|
239
253
|
const stack = attempt(() => err.stack, undefined);
|
|
240
254
|
if (typeof stack !== 'string') return undefined;
|
|
@@ -279,6 +293,7 @@ function serializeErrorAt(err, depth, seen) {
|
|
|
279
293
|
if (code !== undefined) out.code = code;
|
|
280
294
|
const status = errorStatus(err);
|
|
281
295
|
if (status !== undefined) out.status = status;
|
|
296
|
+
Object.assign(out, rateLimitFields(err));
|
|
282
297
|
const stack = errorStack(err, type, message);
|
|
283
298
|
if (stack !== undefined) out.stack = stack;
|
|
284
299
|
|
|
@@ -398,6 +398,13 @@ class OAuth2Requester extends Requester {
|
|
|
398
398
|
);
|
|
399
399
|
transportError.statusCode = status;
|
|
400
400
|
transportError.isTokenRefreshTransportFailure = true;
|
|
401
|
+
if (error?.isRateLimited) {
|
|
402
|
+
transportError.isRateLimited = true;
|
|
403
|
+
transportError.retryAt = error.retryAt;
|
|
404
|
+
transportError.waitMs = error.waitMs;
|
|
405
|
+
transportError.reason = error.reason;
|
|
406
|
+
transportError.module = error.module;
|
|
407
|
+
}
|
|
401
408
|
return transportError;
|
|
402
409
|
}
|
|
403
410
|
|
|
@@ -0,0 +1,245 @@
|
|
|
1
|
+
const MAX_HINT_WAIT_MS = 366 * 24 * 60 * 60 * 1000;
|
|
2
|
+
|
|
3
|
+
const SECONDS_PATTERN = /^\d+(?:\.\d+)?$/;
|
|
4
|
+
const HAS_LETTER = /[A-Za-z]/;
|
|
5
|
+
const EPOCH_SECONDS_MIN = 1e9;
|
|
6
|
+
const EPOCH_MILLISECONDS_MIN = 1e12;
|
|
7
|
+
|
|
8
|
+
const RESET_HEADERS = [
|
|
9
|
+
'x-ratelimit-reset',
|
|
10
|
+
'ratelimit-reset',
|
|
11
|
+
'x-rate-limit-reset',
|
|
12
|
+
];
|
|
13
|
+
const REMAINING_HEADERS = [
|
|
14
|
+
'x-ratelimit-remaining',
|
|
15
|
+
'ratelimit-remaining',
|
|
16
|
+
'x-rate-limit-remaining',
|
|
17
|
+
];
|
|
18
|
+
|
|
19
|
+
const isMissing = (value) => value === undefined || value === null;
|
|
20
|
+
|
|
21
|
+
function readEntries(headers, wanted) {
|
|
22
|
+
for (const entry of headers) {
|
|
23
|
+
if (Array.isArray(entry) && String(entry[0]).toLowerCase() === wanted) {
|
|
24
|
+
return entry[1];
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
return undefined;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
function readKeys(headers, wanted) {
|
|
31
|
+
for (const key of Object.keys(headers)) {
|
|
32
|
+
if (key.toLowerCase() === wanted) return headers[key];
|
|
33
|
+
}
|
|
34
|
+
return undefined;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
function headerValue(headers, name) {
|
|
38
|
+
if (!headers || typeof headers !== 'object') return undefined;
|
|
39
|
+
const wanted = name.toLowerCase();
|
|
40
|
+
const hasGet = typeof headers.get === 'function';
|
|
41
|
+
|
|
42
|
+
let value;
|
|
43
|
+
if (hasGet) {
|
|
44
|
+
value = headers.get(name);
|
|
45
|
+
if (isMissing(value)) value = headers.get(wanted);
|
|
46
|
+
}
|
|
47
|
+
if (isMissing(value) && typeof headers[Symbol.iterator] === 'function') {
|
|
48
|
+
value = readEntries(headers, wanted);
|
|
49
|
+
}
|
|
50
|
+
if (isMissing(value) && !hasGet && !Array.isArray(headers)) {
|
|
51
|
+
value = readKeys(headers, wanted);
|
|
52
|
+
}
|
|
53
|
+
if (Array.isArray(value)) value = value[0];
|
|
54
|
+
if (isMissing(value)) return undefined;
|
|
55
|
+
|
|
56
|
+
const text = String(value).trim();
|
|
57
|
+
return text === '' ? undefined : text;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
function definedOnly(fields) {
|
|
61
|
+
const result = {};
|
|
62
|
+
for (const [key, value] of Object.entries(fields)) {
|
|
63
|
+
if (value !== undefined) result[key] = value;
|
|
64
|
+
}
|
|
65
|
+
return result;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
function hintFromWait(waitMs, now, { source = 'header', ...extra } = {}) {
|
|
69
|
+
if (!Number.isFinite(waitMs) || waitMs < 0 || waitMs > MAX_HINT_WAIT_MS) {
|
|
70
|
+
return null;
|
|
71
|
+
}
|
|
72
|
+
return {
|
|
73
|
+
waitMs,
|
|
74
|
+
retryAt: new Date(now + waitMs),
|
|
75
|
+
...definedOnly(extra),
|
|
76
|
+
source,
|
|
77
|
+
};
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
function hintFromRetryAt(retryAt, now, { source = 'header', ...extra } = {}) {
|
|
81
|
+
const at = retryAt instanceof Date ? retryAt.getTime() : Number.NaN;
|
|
82
|
+
if (Number.isNaN(at)) return null;
|
|
83
|
+
const waitMs = Math.max(0, at - now);
|
|
84
|
+
if (waitMs > MAX_HINT_WAIT_MS) return null;
|
|
85
|
+
return { waitMs, retryAt: new Date(at), ...definedOnly(extra), source };
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
function parseDate(text) {
|
|
89
|
+
if (!HAS_LETTER.test(text)) return null;
|
|
90
|
+
const at = Date.parse(text);
|
|
91
|
+
return Number.isNaN(at) ? null : new Date(at);
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
function parseRetryAfter(value, { now = Date.now() } = {}) {
|
|
95
|
+
if (isMissing(value)) return null;
|
|
96
|
+
const text = String(value).trim();
|
|
97
|
+
if (text === '') return null;
|
|
98
|
+
if (SECONDS_PATTERN.test(text))
|
|
99
|
+
return hintFromWait(Number(text) * 1000, now);
|
|
100
|
+
const date = parseDate(text);
|
|
101
|
+
return date ? hintFromRetryAt(date, now) : null;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
function numberOrUndefined(text) {
|
|
105
|
+
if (text === undefined) return undefined;
|
|
106
|
+
const number = Number(text);
|
|
107
|
+
return Number.isFinite(number) ? number : undefined;
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
function firstHeader(headers, names) {
|
|
111
|
+
for (const name of names) {
|
|
112
|
+
const value = headerValue(headers, name);
|
|
113
|
+
if (value !== undefined) return value;
|
|
114
|
+
}
|
|
115
|
+
return undefined;
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
function parseResetValue(text, now, extra) {
|
|
119
|
+
if (SECONDS_PATTERN.test(text)) {
|
|
120
|
+
const number = Number(text);
|
|
121
|
+
if (number >= EPOCH_MILLISECONDS_MIN) {
|
|
122
|
+
return hintFromRetryAt(new Date(number), now, extra);
|
|
123
|
+
}
|
|
124
|
+
if (number >= EPOCH_SECONDS_MIN) {
|
|
125
|
+
return hintFromRetryAt(new Date(number * 1000), now, extra);
|
|
126
|
+
}
|
|
127
|
+
return hintFromWait(number * 1000, now, extra);
|
|
128
|
+
}
|
|
129
|
+
const date = parseDate(text);
|
|
130
|
+
return date ? hintFromRetryAt(date, now, extra) : null;
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
function parseResetHeaders(headers, { now = Date.now() } = {}) {
|
|
134
|
+
const remaining = numberOrUndefined(
|
|
135
|
+
firstHeader(headers, REMAINING_HEADERS)
|
|
136
|
+
);
|
|
137
|
+
const extra = { remaining };
|
|
138
|
+
|
|
139
|
+
const after = headerValue(headers, 'x-ratelimit-reset-after');
|
|
140
|
+
if (after !== undefined && SECONDS_PATTERN.test(after)) {
|
|
141
|
+
return hintFromWait(Number(after) * 1000, now, extra);
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
for (const name of RESET_HEADERS) {
|
|
145
|
+
const value = headerValue(headers, name);
|
|
146
|
+
if (value === undefined) continue;
|
|
147
|
+
const hint = parseResetValue(value, now, extra);
|
|
148
|
+
if (hint) return hint;
|
|
149
|
+
}
|
|
150
|
+
return null;
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
function splitList(text) {
|
|
154
|
+
const items = [];
|
|
155
|
+
let current = '';
|
|
156
|
+
let quoted = false;
|
|
157
|
+
for (const char of text) {
|
|
158
|
+
if (char === '"') quoted = !quoted;
|
|
159
|
+
if (char === ',' && !quoted) {
|
|
160
|
+
items.push(current);
|
|
161
|
+
current = '';
|
|
162
|
+
} else {
|
|
163
|
+
current += char;
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
items.push(current);
|
|
167
|
+
return items.map((item) => item.trim()).filter(Boolean);
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
function parseStructuredItem(item) {
|
|
171
|
+
const [head, ...params] = item.split(';').map((part) => part.trim());
|
|
172
|
+
const values = {};
|
|
173
|
+
for (const param of params) {
|
|
174
|
+
const [key, raw] = param.split('=').map((part) => part.trim());
|
|
175
|
+
if (key) values[key] = numberOrUndefined(raw);
|
|
176
|
+
}
|
|
177
|
+
const name = head.replace(/^"|"$/g, '');
|
|
178
|
+
return {
|
|
179
|
+
name: name || undefined,
|
|
180
|
+
remaining: values.r,
|
|
181
|
+
waitSeconds: values.t,
|
|
182
|
+
};
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
function pickStructured(items) {
|
|
186
|
+
const usable = items.filter(
|
|
187
|
+
(item) => Number.isFinite(item.waitSeconds) && item.waitSeconds >= 0
|
|
188
|
+
);
|
|
189
|
+
usable.sort((a, b) => {
|
|
190
|
+
const byRemaining =
|
|
191
|
+
(a.remaining ?? Infinity) - (b.remaining ?? Infinity);
|
|
192
|
+
if (byRemaining !== 0 && !Number.isNaN(byRemaining)) return byRemaining;
|
|
193
|
+
return b.waitSeconds - a.waitSeconds;
|
|
194
|
+
});
|
|
195
|
+
return usable[0];
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
function readKeyValue(text, key) {
|
|
199
|
+
const match = new RegExp(
|
|
200
|
+
String.raw`(?:^|[,;\s])${key}\s*=\s*([^,;\s]+)`,
|
|
201
|
+
'i'
|
|
202
|
+
).exec(text);
|
|
203
|
+
return match ? match[1] : undefined;
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
function parseIetfRateLimit(headers, { now = Date.now() } = {}) {
|
|
207
|
+
const raw = headerValue(headers, 'ratelimit');
|
|
208
|
+
if (raw === undefined) return null;
|
|
209
|
+
const policyHeader = headerValue(headers, 'ratelimit-policy');
|
|
210
|
+
|
|
211
|
+
if (/;\s*t\s*=/.test(raw)) {
|
|
212
|
+
const chosen = pickStructured(splitList(raw).map(parseStructuredItem));
|
|
213
|
+
if (!chosen) return null;
|
|
214
|
+
return hintFromWait(chosen.waitSeconds * 1000, now, {
|
|
215
|
+
remaining: chosen.remaining,
|
|
216
|
+
policy: chosen.name ?? policyHeader,
|
|
217
|
+
});
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
const reset = readKeyValue(raw, 'reset');
|
|
221
|
+
if (reset === undefined || !SECONDS_PATTERN.test(reset)) return null;
|
|
222
|
+
return hintFromWait(Number(reset) * 1000, now, {
|
|
223
|
+
remaining: numberOrUndefined(readKeyValue(raw, 'remaining')),
|
|
224
|
+
policy: policyHeader,
|
|
225
|
+
});
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
const BUILT_IN_PARSERS = {
|
|
229
|
+
retryAfter: (headers, { now } = {}) =>
|
|
230
|
+
parseRetryAfter(headerValue(headers, 'retry-after'), { now }),
|
|
231
|
+
resetHeaders: parseResetHeaders,
|
|
232
|
+
ietf: parseIetfRateLimit,
|
|
233
|
+
};
|
|
234
|
+
|
|
235
|
+
module.exports = {
|
|
236
|
+
BUILT_IN_PARSERS,
|
|
237
|
+
MAX_HINT_WAIT_MS,
|
|
238
|
+
definedOnly,
|
|
239
|
+
headerValue,
|
|
240
|
+
hintFromRetryAt,
|
|
241
|
+
hintFromWait,
|
|
242
|
+
parseIetfRateLimit,
|
|
243
|
+
parseResetHeaders,
|
|
244
|
+
parseRetryAfter,
|
|
245
|
+
};
|