reqon-dsl 0.2.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/settings.local.json +31 -0
- package/.claude/skills/api-integration.md +125 -0
- package/.claude/skills/database-schema.md +51 -0
- package/.claude/skills/dsl-design.md +80 -0
- package/.claude/skills/property-testing.md +143 -0
- package/.claude/skills/reqon/SKILL.md +44 -0
- package/.claude/skills/reqon/references/examples.md +206 -0
- package/.claude/skills/reqon/references/syntax.md +263 -0
- package/.claude/skills/vscode-extension.md +113 -0
- package/.github/dependabot.yml +32 -0
- package/.github/pull_request_template.md +21 -0
- package/.github/workflows/ci.yml +174 -0
- package/.github/workflows/release.yml +73 -0
- package/CLAUDE.md +72 -0
- package/CONTRIBUTING.md +161 -0
- package/README.md +235 -0
- package/TODO.md +51 -0
- package/dist/ast/index.d.ts +1 -0
- package/dist/ast/index.js +1 -0
- package/dist/ast/nodes.d.ts +237 -0
- package/dist/ast/nodes.js +12 -0
- package/dist/auth/auth.test.d.ts +1 -0
- package/dist/auth/auth.test.js +255 -0
- package/dist/auth/circuit-breaker.d.ts +115 -0
- package/dist/auth/circuit-breaker.js +267 -0
- package/dist/auth/credentials.d.ts +91 -0
- package/dist/auth/credentials.js +169 -0
- package/dist/auth/index.d.ts +5 -0
- package/dist/auth/index.js +8 -0
- package/dist/auth/oauth2-provider.d.ts +41 -0
- package/dist/auth/oauth2-provider.js +131 -0
- package/dist/auth/rate-limiter.d.ts +61 -0
- package/dist/auth/rate-limiter.js +380 -0
- package/dist/auth/token-store.d.ts +30 -0
- package/dist/auth/token-store.js +148 -0
- package/dist/auth/types.d.ts +142 -0
- package/dist/auth/types.js +1 -0
- package/dist/cli.d.ts +2 -0
- package/dist/cli.js +270 -0
- package/dist/errors/errors.test.d.ts +1 -0
- package/dist/errors/errors.test.js +165 -0
- package/dist/errors/index.d.ts +83 -0
- package/dist/errors/index.js +159 -0
- package/dist/execution/execution.test.d.ts +1 -0
- package/dist/execution/execution.test.js +246 -0
- package/dist/execution/index.d.ts +4 -0
- package/dist/execution/index.js +2 -0
- package/dist/execution/state.d.ts +136 -0
- package/dist/execution/state.js +82 -0
- package/dist/execution/store.d.ts +52 -0
- package/dist/execution/store.js +120 -0
- package/dist/index.d.ts +27 -0
- package/dist/index.js +57 -0
- package/dist/integration.test.d.ts +1 -0
- package/dist/integration.test.js +168 -0
- package/dist/interpreter/context.d.ts +15 -0
- package/dist/interpreter/context.js +29 -0
- package/dist/interpreter/evaluator.d.ts +5 -0
- package/dist/interpreter/evaluator.js +223 -0
- package/dist/interpreter/evaluator.test.d.ts +1 -0
- package/dist/interpreter/evaluator.test.js +512 -0
- package/dist/interpreter/executor.d.ts +131 -0
- package/dist/interpreter/executor.js +663 -0
- package/dist/interpreter/fetch-handler.d.ts +43 -0
- package/dist/interpreter/fetch-handler.js +203 -0
- package/dist/interpreter/http.d.ts +57 -0
- package/dist/interpreter/http.js +210 -0
- package/dist/interpreter/http.test.d.ts +1 -0
- package/dist/interpreter/http.test.js +299 -0
- package/dist/interpreter/index.d.ts +7 -0
- package/dist/interpreter/index.js +7 -0
- package/dist/interpreter/pagination.d.ts +63 -0
- package/dist/interpreter/pagination.js +155 -0
- package/dist/interpreter/progress.test.d.ts +1 -0
- package/dist/interpreter/progress.test.js +216 -0
- package/dist/interpreter/schema-matcher.d.ts +16 -0
- package/dist/interpreter/schema-matcher.js +136 -0
- package/dist/interpreter/schema-matcher.test.d.ts +1 -0
- package/dist/interpreter/schema-matcher.test.js +122 -0
- package/dist/interpreter/signals.d.ts +57 -0
- package/dist/interpreter/signals.js +73 -0
- package/dist/interpreter/step-handlers/for-handler.d.ts +17 -0
- package/dist/interpreter/step-handlers/for-handler.js +51 -0
- package/dist/interpreter/step-handlers/index.d.ts +8 -0
- package/dist/interpreter/step-handlers/index.js +8 -0
- package/dist/interpreter/step-handlers/map-handler.d.ts +10 -0
- package/dist/interpreter/step-handlers/map-handler.js +20 -0
- package/dist/interpreter/step-handlers/match-handler.d.ts +27 -0
- package/dist/interpreter/step-handlers/match-handler.js +61 -0
- package/dist/interpreter/step-handlers/store-handler.d.ts +13 -0
- package/dist/interpreter/step-handlers/store-handler.js +66 -0
- package/dist/interpreter/step-handlers/types.d.ts +15 -0
- package/dist/interpreter/step-handlers/types.js +1 -0
- package/dist/interpreter/step-handlers/validate-handler.d.ts +10 -0
- package/dist/interpreter/step-handlers/validate-handler.js +26 -0
- package/dist/interpreter/step-handlers/webhook-handler.d.ts +36 -0
- package/dist/interpreter/step-handlers/webhook-handler.js +104 -0
- package/dist/lexer/index.d.ts +10 -0
- package/dist/lexer/index.js +12 -0
- package/dist/lexer/lexer.d.ts +24 -0
- package/dist/lexer/lexer.js +264 -0
- package/dist/lexer/lexer.test.d.ts +1 -0
- package/dist/lexer/lexer.test.js +259 -0
- package/dist/lexer/tokens.d.ts +69 -0
- package/dist/lexer/tokens.js +146 -0
- package/dist/loader/index.d.ts +36 -0
- package/dist/loader/index.js +220 -0
- package/dist/loader/loader.test.d.ts +1 -0
- package/dist/loader/loader.test.js +287 -0
- package/dist/oas/index.d.ts +4 -0
- package/dist/oas/index.js +2 -0
- package/dist/oas/loader.d.ts +21 -0
- package/dist/oas/loader.js +82 -0
- package/dist/oas/oas.test.d.ts +1 -0
- package/dist/oas/oas.test.js +218 -0
- package/dist/oas/validator.d.ts +12 -0
- package/dist/oas/validator.js +227 -0
- package/dist/parser/base.d.ts +33 -0
- package/dist/parser/base.js +97 -0
- package/dist/parser/expressions.d.ts +27 -0
- package/dist/parser/expressions.js +248 -0
- package/dist/parser/expressions.test.d.ts +1 -0
- package/dist/parser/expressions.test.js +378 -0
- package/dist/parser/index.d.ts +3 -0
- package/dist/parser/index.js +3 -0
- package/dist/parser/match.test.d.ts +1 -0
- package/dist/parser/match.test.js +254 -0
- package/dist/parser/parser.d.ts +68 -0
- package/dist/parser/parser.js +1229 -0
- package/dist/parser/parser.test.d.ts +1 -0
- package/dist/parser/parser.test.js +333 -0
- package/dist/parser/schedule.test.d.ts +1 -0
- package/dist/parser/schedule.test.js +241 -0
- package/dist/plugin.d.ts +35 -0
- package/dist/plugin.js +68 -0
- package/dist/scheduler/cron-parser.d.ts +32 -0
- package/dist/scheduler/cron-parser.js +198 -0
- package/dist/scheduler/cron-parser.test.d.ts +1 -0
- package/dist/scheduler/cron-parser.test.js +188 -0
- package/dist/scheduler/index.d.ts +3 -0
- package/dist/scheduler/index.js +2 -0
- package/dist/scheduler/scheduler.d.ts +81 -0
- package/dist/scheduler/scheduler.js +376 -0
- package/dist/scheduler/types.d.ts +65 -0
- package/dist/scheduler/types.js +1 -0
- package/dist/stores/factory.d.ts +36 -0
- package/dist/stores/factory.js +73 -0
- package/dist/stores/file.d.ts +60 -0
- package/dist/stores/file.js +173 -0
- package/dist/stores/file.test.d.ts +1 -0
- package/dist/stores/file.test.js +165 -0
- package/dist/stores/index.d.ts +6 -0
- package/dist/stores/index.js +5 -0
- package/dist/stores/memory.d.ts +19 -0
- package/dist/stores/memory.js +51 -0
- package/dist/stores/memory.test.d.ts +1 -0
- package/dist/stores/memory.test.js +157 -0
- package/dist/stores/postgrest.d.ts +55 -0
- package/dist/stores/postgrest.js +217 -0
- package/dist/stores/stores.test.d.ts +1 -0
- package/dist/stores/stores.test.js +158 -0
- package/dist/stores/types.d.ts +31 -0
- package/dist/stores/types.js +26 -0
- package/dist/sync/index.d.ts +4 -0
- package/dist/sync/index.js +2 -0
- package/dist/sync/state.d.ts +69 -0
- package/dist/sync/state.js +66 -0
- package/dist/sync/store.d.ts +49 -0
- package/dist/sync/store.js +93 -0
- package/dist/sync/sync.test.d.ts +1 -0
- package/dist/sync/sync.test.js +221 -0
- package/dist/utils/async.d.ts +7 -0
- package/dist/utils/async.js +9 -0
- package/dist/utils/file.d.ts +38 -0
- package/dist/utils/file.js +92 -0
- package/dist/utils/index.d.ts +4 -0
- package/dist/utils/index.js +4 -0
- package/dist/utils/logger.d.ts +34 -0
- package/dist/utils/logger.js +39 -0
- package/dist/utils/path.d.ts +12 -0
- package/dist/utils/path.js +41 -0
- package/dist/webhook/index.d.ts +8 -0
- package/dist/webhook/index.js +7 -0
- package/dist/webhook/server.d.ts +84 -0
- package/dist/webhook/server.js +319 -0
- package/dist/webhook/store.d.ts +67 -0
- package/dist/webhook/store.js +193 -0
- package/dist/webhook/types.d.ts +88 -0
- package/dist/webhook/types.js +6 -0
- package/docusaurus/README.md +41 -0
- package/docusaurus/docs/advanced/execution-state.md +283 -0
- package/docusaurus/docs/advanced/extending-reqon.md +388 -0
- package/docusaurus/docs/advanced/multi-file-missions.md +250 -0
- package/docusaurus/docs/advanced/parallel-execution.md +353 -0
- package/docusaurus/docs/api-reference.md +443 -0
- package/docusaurus/docs/authentication/api-key.md +339 -0
- package/docusaurus/docs/authentication/basic.md +276 -0
- package/docusaurus/docs/authentication/bearer.md +282 -0
- package/docusaurus/docs/authentication/oauth2.md +317 -0
- package/docusaurus/docs/authentication/overview.md +251 -0
- package/docusaurus/docs/cli.md +229 -0
- package/docusaurus/docs/core-concepts/actions.md +286 -0
- package/docusaurus/docs/core-concepts/missions.md +264 -0
- package/docusaurus/docs/core-concepts/schemas.md +353 -0
- package/docusaurus/docs/core-concepts/sources.md +339 -0
- package/docusaurus/docs/core-concepts/stores.md +332 -0
- package/docusaurus/docs/dsl-syntax/expressions.md +361 -0
- package/docusaurus/docs/dsl-syntax/fetch.md +293 -0
- package/docusaurus/docs/dsl-syntax/for-loops.md +324 -0
- package/docusaurus/docs/dsl-syntax/map.md +345 -0
- package/docusaurus/docs/dsl-syntax/match.md +387 -0
- package/docusaurus/docs/dsl-syntax/pipelines.md +397 -0
- package/docusaurus/docs/dsl-syntax/validate.md +401 -0
- package/docusaurus/docs/error-handling/dead-letter-queues.md +399 -0
- package/docusaurus/docs/error-handling/flow-control.md +337 -0
- package/docusaurus/docs/error-handling/retry-strategies.md +368 -0
- package/docusaurus/docs/examples.md +488 -0
- package/docusaurus/docs/getting-started.md +256 -0
- package/docusaurus/docs/http/circuit-breaker.md +401 -0
- package/docusaurus/docs/http/incremental-sync.md +394 -0
- package/docusaurus/docs/http/pagination.md +361 -0
- package/docusaurus/docs/http/rate-limiting.md +383 -0
- package/docusaurus/docs/http/requests.md +328 -0
- package/docusaurus/docs/http/retry.md +402 -0
- package/docusaurus/docs/intro.md +90 -0
- package/docusaurus/docs/openapi/loading-specs.md +305 -0
- package/docusaurus/docs/openapi/operation-calls.md +314 -0
- package/docusaurus/docs/openapi/overview.md +212 -0
- package/docusaurus/docs/openapi/response-validation.md +344 -0
- package/docusaurus/docs/scheduling/cron.md +305 -0
- package/docusaurus/docs/scheduling/daemon-mode.md +317 -0
- package/docusaurus/docs/scheduling/intervals.md +289 -0
- package/docusaurus/docs/scheduling/overview.md +231 -0
- package/docusaurus/docs/stores/custom-adapters.md +376 -0
- package/docusaurus/docs/stores/file.md +236 -0
- package/docusaurus/docs/stores/memory.md +193 -0
- package/docusaurus/docs/stores/overview.md +274 -0
- package/docusaurus/docs/stores/postgrest.md +316 -0
- package/docusaurus/docusaurus.config.ts +148 -0
- package/docusaurus/package-lock.json +18029 -0
- package/docusaurus/package.json +47 -0
- package/docusaurus/sidebars.ts +155 -0
- package/docusaurus/src/components/HomepageFeatures/index.tsx +105 -0
- package/docusaurus/src/components/HomepageFeatures/styles.module.css +12 -0
- package/docusaurus/src/css/custom.css +169 -0
- package/docusaurus/src/pages/index.module.css +48 -0
- package/docusaurus/src/pages/index.tsx +110 -0
- package/docusaurus/src/pages/markdown-page.md +7 -0
- package/docusaurus/static/.nojekyll +0 -0
- package/docusaurus/static/img/docusaurus-social-card.jpg +0 -0
- package/docusaurus/static/img/docusaurus.png +0 -0
- package/docusaurus/static/img/favicon.ico +0 -0
- package/docusaurus/static/img/logo.svg +10 -0
- package/docusaurus/static/img/undraw_docusaurus_mountain.svg +171 -0
- package/docusaurus/static/img/undraw_docusaurus_react.svg +170 -0
- package/docusaurus/static/img/undraw_docusaurus_tree.svg +40 -0
- package/docusaurus/tsconfig.json +8 -0
- package/examples/README.md +112 -0
- package/examples/error-handling/README.md +150 -0
- package/examples/error-handling/payment-processor.vague +287 -0
- package/examples/github-sync/README.md +74 -0
- package/examples/github-sync/fetch-issues.vague +47 -0
- package/examples/github-sync/fetch-prs.vague +40 -0
- package/examples/github-sync/mission.vague +101 -0
- package/examples/github-sync/normalize.vague +70 -0
- package/examples/jsonplaceholder/README.md +28 -0
- package/examples/jsonplaceholder/posts.vague +48 -0
- package/examples/petstore/README.md +35 -0
- package/examples/petstore/openapi.yaml +97 -0
- package/examples/petstore/sync.vague +52 -0
- package/examples/temporal-comparison/README.md +297 -0
- package/examples/temporal-comparison/reconciliation.vague +355 -0
- package/examples/temporal-comparison/temporal/activities/index.ts +8 -0
- package/examples/temporal-comparison/temporal/activities/shipstation.ts +225 -0
- package/examples/temporal-comparison/temporal/activities/shopify.ts +257 -0
- package/examples/temporal-comparison/temporal/activities/storage.ts +198 -0
- package/examples/temporal-comparison/temporal/activities/stripe.ts +169 -0
- package/examples/temporal-comparison/temporal/activities/validation.ts +205 -0
- package/examples/temporal-comparison/temporal/client/schedule.ts +218 -0
- package/examples/temporal-comparison/temporal/config/retry.ts +63 -0
- package/examples/temporal-comparison/temporal/types/index.ts +129 -0
- package/examples/temporal-comparison/temporal/workers/main.ts +130 -0
- package/examples/temporal-comparison/temporal/workflows/orderReconciliation.ts +262 -0
- package/examples/xero/README.md +88 -0
- package/examples/xero/invoices.vague +189 -0
- package/package.json +40 -0
- package/src/api-integration.test.ts +954 -0
- package/src/ast/index.ts +1 -0
- package/src/ast/nodes.ts +310 -0
- package/src/auth/auth.test.ts +326 -0
- package/src/auth/circuit-breaker.test.ts +390 -0
- package/src/auth/circuit-breaker.ts +379 -0
- package/src/auth/credentials.test.ts +273 -0
- package/src/auth/credentials.ts +246 -0
- package/src/auth/index.ts +40 -0
- package/src/auth/oauth2-provider.ts +177 -0
- package/src/auth/rate-limiter.ts +459 -0
- package/src/auth/token-store.ts +177 -0
- package/src/auth/types.ts +159 -0
- package/src/benchmark/e2e.bench.ts +288 -0
- package/src/benchmark/evaluator.bench.ts +331 -0
- package/src/benchmark/fixtures.ts +295 -0
- package/src/benchmark/index.ts +108 -0
- package/src/benchmark/lexer.bench.ts +69 -0
- package/src/benchmark/parser.bench.ts +103 -0
- package/src/benchmark/resilience.bench.ts +193 -0
- package/src/benchmark/store.bench.ts +147 -0
- package/src/benchmark/utils.ts +230 -0
- package/src/cli.ts +313 -0
- package/src/errors/errors.test.ts +234 -0
- package/src/errors/index.ts +223 -0
- package/src/execution/execution.test.ts +307 -0
- package/src/execution/index.ts +21 -0
- package/src/execution/state.ts +207 -0
- package/src/execution/store.ts +188 -0
- package/src/index.ts +169 -0
- package/src/integration.test.ts +192 -0
- package/src/interpreter/context.ts +57 -0
- package/src/interpreter/evaluator.test.ts +796 -0
- package/src/interpreter/evaluator.ts +245 -0
- package/src/interpreter/executor.ts +946 -0
- package/src/interpreter/fetch-handler.ts +302 -0
- package/src/interpreter/http.test.ts +423 -0
- package/src/interpreter/http.ts +308 -0
- package/src/interpreter/index.ts +32 -0
- package/src/interpreter/pagination.ts +207 -0
- package/src/interpreter/progress.test.ts +276 -0
- package/src/interpreter/schema-matcher.test.ts +160 -0
- package/src/interpreter/schema-matcher.ts +168 -0
- package/src/interpreter/signals.ts +73 -0
- package/src/interpreter/step-handlers/for-handler.ts +65 -0
- package/src/interpreter/step-handlers/index.ts +17 -0
- package/src/interpreter/step-handlers/map-handler.ts +24 -0
- package/src/interpreter/step-handlers/match-handler.ts +101 -0
- package/src/interpreter/step-handlers/store-handler.ts +78 -0
- package/src/interpreter/step-handlers/types.ts +17 -0
- package/src/interpreter/step-handlers/validate-handler.ts +30 -0
- package/src/interpreter/step-handlers/webhook-handler.ts +142 -0
- package/src/lexer/index.ts +18 -0
- package/src/lexer/lexer.test.ts +316 -0
- package/src/lexer/tokens.ts +179 -0
- package/src/loader/index.ts +288 -0
- package/src/loader/loader.test.ts +360 -0
- package/src/oas/index.ts +4 -0
- package/src/oas/loader.ts +126 -0
- package/src/oas/oas.test.ts +254 -0
- package/src/oas/validator.ts +299 -0
- package/src/parser/base.ts +124 -0
- package/src/parser/expressions.test.ts +525 -0
- package/src/parser/expressions.ts +314 -0
- package/src/parser/index.ts +3 -0
- package/src/parser/match.test.ts +296 -0
- package/src/parser/parser.test.ts +739 -0
- package/src/parser/parser.ts +1469 -0
- package/src/parser/schedule.test.ts +287 -0
- package/src/parser/webhook.test.ts +248 -0
- package/src/plugin.ts +83 -0
- package/src/scheduler/cron-parser.test.ts +236 -0
- package/src/scheduler/cron-parser.ts +236 -0
- package/src/scheduler/index.ts +10 -0
- package/src/scheduler/scheduler.ts +443 -0
- package/src/scheduler/types.ts +71 -0
- package/src/stores/factory.ts +104 -0
- package/src/stores/file.test.ts +276 -0
- package/src/stores/file.ts +211 -0
- package/src/stores/index.ts +6 -0
- package/src/stores/memory.test.ts +238 -0
- package/src/stores/memory.ts +63 -0
- package/src/stores/postgrest.test.ts +488 -0
- package/src/stores/postgrest.ts +263 -0
- package/src/stores/stores.test.ts +197 -0
- package/src/stores/types.ts +58 -0
- package/src/sync/index.ts +16 -0
- package/src/sync/state.ts +126 -0
- package/src/sync/store.ts +139 -0
- package/src/sync/sync.test.ts +271 -0
- package/src/utils/async.ts +10 -0
- package/src/utils/file.ts +106 -0
- package/src/utils/index.ts +14 -0
- package/src/utils/logger.ts +53 -0
- package/src/utils/path.ts +47 -0
- package/src/webhook/index.ts +15 -0
- package/src/webhook/server.test.ts +253 -0
- package/src/webhook/server.ts +389 -0
- package/src/webhook/store.ts +239 -0
- package/src/webhook/types.ts +93 -0
- package/tsconfig.json +17 -0
- package/vitest.config.ts +39 -0
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* OAuth2 auth provider with automatic token refresh
|
|
3
|
+
*/
|
|
4
|
+
export class OAuth2AuthProvider {
|
|
5
|
+
connectionId;
|
|
6
|
+
store;
|
|
7
|
+
config;
|
|
8
|
+
refreshBuffer;
|
|
9
|
+
refreshPromise = null;
|
|
10
|
+
constructor(options) {
|
|
11
|
+
this.connectionId = options.connectionId;
|
|
12
|
+
this.store = options.store;
|
|
13
|
+
this.config = options.config;
|
|
14
|
+
this.refreshBuffer = (options.config.refreshBuffer ?? 300) * 1000; // Convert to ms
|
|
15
|
+
}
|
|
16
|
+
async getToken() {
|
|
17
|
+
const tokens = await this.store.get(this.connectionId);
|
|
18
|
+
if (!tokens) {
|
|
19
|
+
throw new Error(`No tokens found for connection: ${this.connectionId}`);
|
|
20
|
+
}
|
|
21
|
+
// Check if we need to refresh
|
|
22
|
+
if (this.shouldRefresh(tokens)) {
|
|
23
|
+
return this.refreshToken();
|
|
24
|
+
}
|
|
25
|
+
// Update last used time
|
|
26
|
+
await this.store.touch(this.connectionId);
|
|
27
|
+
return tokens.accessToken;
|
|
28
|
+
}
|
|
29
|
+
async refreshToken() {
|
|
30
|
+
// Deduplicate concurrent refresh requests
|
|
31
|
+
if (this.refreshPromise) {
|
|
32
|
+
return this.refreshPromise;
|
|
33
|
+
}
|
|
34
|
+
this.refreshPromise = this.doRefresh();
|
|
35
|
+
try {
|
|
36
|
+
return await this.refreshPromise;
|
|
37
|
+
}
|
|
38
|
+
finally {
|
|
39
|
+
this.refreshPromise = null;
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
async doRefresh() {
|
|
43
|
+
const tokens = await this.store.get(this.connectionId);
|
|
44
|
+
if (!tokens?.refreshToken) {
|
|
45
|
+
throw new Error(`No refresh token available for connection: ${this.connectionId}`);
|
|
46
|
+
}
|
|
47
|
+
const body = new URLSearchParams({
|
|
48
|
+
grant_type: 'refresh_token',
|
|
49
|
+
refresh_token: tokens.refreshToken,
|
|
50
|
+
client_id: this.config.clientId,
|
|
51
|
+
});
|
|
52
|
+
if (this.config.clientSecret) {
|
|
53
|
+
body.set('client_secret', this.config.clientSecret);
|
|
54
|
+
}
|
|
55
|
+
const response = await fetch(this.config.tokenEndpoint, {
|
|
56
|
+
method: 'POST',
|
|
57
|
+
headers: {
|
|
58
|
+
'Content-Type': 'application/x-www-form-urlencoded',
|
|
59
|
+
},
|
|
60
|
+
body,
|
|
61
|
+
});
|
|
62
|
+
if (!response.ok) {
|
|
63
|
+
const error = await response.text();
|
|
64
|
+
throw new Error(`Token refresh failed: ${response.status} ${error}`);
|
|
65
|
+
}
|
|
66
|
+
const data = (await response.json());
|
|
67
|
+
const newTokens = {
|
|
68
|
+
accessToken: data.access_token,
|
|
69
|
+
refreshToken: data.refresh_token ?? tokens.refreshToken, // Keep old if not rotated
|
|
70
|
+
tokenType: data.token_type ?? 'Bearer',
|
|
71
|
+
scope: data.scope,
|
|
72
|
+
};
|
|
73
|
+
// Calculate expiry
|
|
74
|
+
if (data.expires_in) {
|
|
75
|
+
newTokens.expiresAt = new Date(Date.now() + data.expires_in * 1000);
|
|
76
|
+
}
|
|
77
|
+
await this.store.set(this.connectionId, newTokens);
|
|
78
|
+
await this.store.touch(this.connectionId);
|
|
79
|
+
return newTokens.accessToken;
|
|
80
|
+
}
|
|
81
|
+
shouldRefresh(tokens) {
|
|
82
|
+
if (!tokens.expiresAt) {
|
|
83
|
+
return false; // No expiry info, assume valid
|
|
84
|
+
}
|
|
85
|
+
const now = Date.now();
|
|
86
|
+
const expiresAt = tokens.expiresAt.getTime();
|
|
87
|
+
// Refresh if within buffer of expiry
|
|
88
|
+
return expiresAt - now < this.refreshBuffer;
|
|
89
|
+
}
|
|
90
|
+
getTokenInfo() {
|
|
91
|
+
// Synchronous - returns cached info
|
|
92
|
+
return {
|
|
93
|
+
connectionId: this.connectionId,
|
|
94
|
+
};
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
/**
|
|
98
|
+
* Simple bearer token provider (no refresh)
|
|
99
|
+
*/
|
|
100
|
+
export class BearerTokenProvider {
|
|
101
|
+
token;
|
|
102
|
+
constructor(token) {
|
|
103
|
+
this.token = token;
|
|
104
|
+
}
|
|
105
|
+
async getToken() {
|
|
106
|
+
return this.token;
|
|
107
|
+
}
|
|
108
|
+
getTokenInfo() {
|
|
109
|
+
return {};
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
/**
|
|
113
|
+
* API key provider
|
|
114
|
+
*/
|
|
115
|
+
export class ApiKeyProvider {
|
|
116
|
+
apiKey;
|
|
117
|
+
headerName;
|
|
118
|
+
constructor(apiKey, headerName = 'X-API-Key') {
|
|
119
|
+
this.apiKey = apiKey;
|
|
120
|
+
this.headerName = headerName;
|
|
121
|
+
}
|
|
122
|
+
async getToken() {
|
|
123
|
+
return this.apiKey;
|
|
124
|
+
}
|
|
125
|
+
getHeaderName() {
|
|
126
|
+
return this.headerName;
|
|
127
|
+
}
|
|
128
|
+
getTokenInfo() {
|
|
129
|
+
return {};
|
|
130
|
+
}
|
|
131
|
+
}
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
import type { RateLimiter, RateLimitInfo, RateLimitStatus, RateLimitConfig, RateLimitCallbacks } from './types.js';
|
|
2
|
+
/**
|
|
3
|
+
* Rate limit timeout error - thrown when maxWait is exceeded
|
|
4
|
+
*/
|
|
5
|
+
export declare class RateLimitTimeoutError extends Error {
|
|
6
|
+
source: string;
|
|
7
|
+
waitedSeconds: number;
|
|
8
|
+
maxWait: number;
|
|
9
|
+
constructor(source: string, waitedSeconds: number, maxWait: number);
|
|
10
|
+
}
|
|
11
|
+
/**
|
|
12
|
+
* Rate limit error - thrown when strategy is 'fail'
|
|
13
|
+
*/
|
|
14
|
+
export declare class RateLimitError extends Error {
|
|
15
|
+
source: string;
|
|
16
|
+
resetAt?: Date | undefined;
|
|
17
|
+
constructor(source: string, resetAt?: Date | undefined);
|
|
18
|
+
}
|
|
19
|
+
export declare class AdaptiveRateLimiter implements RateLimiter {
|
|
20
|
+
private defaultConfig;
|
|
21
|
+
private state;
|
|
22
|
+
private configs;
|
|
23
|
+
private callbacks;
|
|
24
|
+
private lastCleanup;
|
|
25
|
+
private maxStaleAgeMs;
|
|
26
|
+
private responsesSinceCleanup;
|
|
27
|
+
constructor(defaultConfig?: Partial<RateLimitConfig>, options?: {
|
|
28
|
+
maxStaleAgeMs?: number;
|
|
29
|
+
});
|
|
30
|
+
/**
|
|
31
|
+
* Clean up stale entries from the state map to prevent memory leaks
|
|
32
|
+
*/
|
|
33
|
+
private cleanup;
|
|
34
|
+
/**
|
|
35
|
+
* Get the number of tracked endpoints (for monitoring)
|
|
36
|
+
*/
|
|
37
|
+
getTrackedEndpointCount(): number;
|
|
38
|
+
/**
|
|
39
|
+
* Force cleanup of stale entries
|
|
40
|
+
*/
|
|
41
|
+
forceCleanup(): void;
|
|
42
|
+
private getKey;
|
|
43
|
+
private getConfig;
|
|
44
|
+
configure(source: string, config: RateLimitConfig): void;
|
|
45
|
+
setCallbacks(callbacks: RateLimitCallbacks): void;
|
|
46
|
+
canProceed(source: string, endpoint?: string): Promise<boolean>;
|
|
47
|
+
waitForCapacity(source: string, endpoint?: string): Promise<void>;
|
|
48
|
+
getThrottleDelay(source: string, endpoint?: string): number;
|
|
49
|
+
recordResponse(source: string, info: RateLimitInfo, endpoint?: string): void;
|
|
50
|
+
getStatus(source: string, endpoint?: string): RateLimitStatus;
|
|
51
|
+
}
|
|
52
|
+
/**
|
|
53
|
+
* Parse rate limit info from HTTP response headers
|
|
54
|
+
*
|
|
55
|
+
* Supports common header patterns:
|
|
56
|
+
* - X-RateLimit-Remaining, X-RateLimit-Limit, X-RateLimit-Reset
|
|
57
|
+
* - RateLimit-Remaining, RateLimit-Limit, RateLimit-Reset
|
|
58
|
+
* - X-Rate-Limit-Remaining, etc.
|
|
59
|
+
* - Retry-After (from 429 responses)
|
|
60
|
+
*/
|
|
61
|
+
export declare function parseRateLimitHeaders(headers: Record<string, string>): RateLimitInfo;
|
|
@@ -0,0 +1,380 @@
|
|
|
1
|
+
import { sleep } from '../utils/async.js';
|
|
2
|
+
/** Max age for stale entries (default: 1 hour) */
|
|
3
|
+
const DEFAULT_MAX_STALE_AGE_MS = 60 * 60 * 1000;
|
|
4
|
+
/** Cleanup interval (default: 5 minutes) */
|
|
5
|
+
const CLEANUP_INTERVAL_MS = 5 * 60 * 1000;
|
|
6
|
+
/** Max number of entries before forced cleanup */
|
|
7
|
+
const MAX_ENTRIES_BEFORE_CLEANUP = 1000;
|
|
8
|
+
const DEFAULT_CONFIG = {
|
|
9
|
+
strategy: 'pause',
|
|
10
|
+
maxWait: 300,
|
|
11
|
+
notifyAt: 10,
|
|
12
|
+
fallbackRpm: 60,
|
|
13
|
+
};
|
|
14
|
+
/**
|
|
15
|
+
* Rate limit timeout error - thrown when maxWait is exceeded
|
|
16
|
+
*/
|
|
17
|
+
export class RateLimitTimeoutError extends Error {
|
|
18
|
+
source;
|
|
19
|
+
waitedSeconds;
|
|
20
|
+
maxWait;
|
|
21
|
+
constructor(source, waitedSeconds, maxWait) {
|
|
22
|
+
super(`Rate limit timeout: waited ${waitedSeconds}s (max: ${maxWait}s) for ${source}`);
|
|
23
|
+
this.source = source;
|
|
24
|
+
this.waitedSeconds = waitedSeconds;
|
|
25
|
+
this.maxWait = maxWait;
|
|
26
|
+
this.name = 'RateLimitTimeoutError';
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
/**
|
|
30
|
+
* Rate limit error - thrown when strategy is 'fail'
|
|
31
|
+
*/
|
|
32
|
+
export class RateLimitError extends Error {
|
|
33
|
+
source;
|
|
34
|
+
resetAt;
|
|
35
|
+
constructor(source, resetAt) {
|
|
36
|
+
const resetIn = resetAt ? Math.ceil((resetAt.getTime() - Date.now()) / 1000) : undefined;
|
|
37
|
+
super(`Rate limited on ${source}${resetIn ? ` - resets in ${resetIn}s` : ''}`);
|
|
38
|
+
this.source = source;
|
|
39
|
+
this.resetAt = resetAt;
|
|
40
|
+
this.name = 'RateLimitError';
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
/**
|
|
44
|
+
* Adaptive rate limiter that learns from response headers
|
|
45
|
+
* Supports pause, throttle, and fail strategies
|
|
46
|
+
*/
|
|
47
|
+
/** Number of responses between cleanup checks */
|
|
48
|
+
const CLEANUP_CHECK_INTERVAL = 100;
|
|
49
|
+
export class AdaptiveRateLimiter {
|
|
50
|
+
defaultConfig;
|
|
51
|
+
state = new Map();
|
|
52
|
+
configs = new Map();
|
|
53
|
+
callbacks = {};
|
|
54
|
+
lastCleanup = Date.now();
|
|
55
|
+
maxStaleAgeMs;
|
|
56
|
+
responsesSinceCleanup = 0;
|
|
57
|
+
constructor(defaultConfig = {}, options = {}) {
|
|
58
|
+
this.defaultConfig = defaultConfig;
|
|
59
|
+
this.maxStaleAgeMs = options.maxStaleAgeMs ?? DEFAULT_MAX_STALE_AGE_MS;
|
|
60
|
+
}
|
|
61
|
+
/**
|
|
62
|
+
* Clean up stale entries from the state map to prevent memory leaks
|
|
63
|
+
*/
|
|
64
|
+
cleanup() {
|
|
65
|
+
const now = Date.now();
|
|
66
|
+
// Skip if cleanup was done recently and we're under the entry limit
|
|
67
|
+
if (now - this.lastCleanup < CLEANUP_INTERVAL_MS &&
|
|
68
|
+
this.state.size < MAX_ENTRIES_BEFORE_CLEANUP) {
|
|
69
|
+
return;
|
|
70
|
+
}
|
|
71
|
+
this.lastCleanup = now;
|
|
72
|
+
const nowDate = new Date(now);
|
|
73
|
+
const staleThreshold = new Date(now - this.maxStaleAgeMs);
|
|
74
|
+
for (const [key, state] of this.state) {
|
|
75
|
+
// Remove if:
|
|
76
|
+
// 1. Reset time has passed AND no recent requests
|
|
77
|
+
// 2. Last request is older than max stale age
|
|
78
|
+
const isResetPassed = state.resetAt && state.resetAt < nowDate;
|
|
79
|
+
const isRetryPassed = !state.retryAfter || state.retryAfter < nowDate;
|
|
80
|
+
const isStale = state.lastRequestAt && state.lastRequestAt < staleThreshold;
|
|
81
|
+
if ((isResetPassed && isRetryPassed && isStale) || (!state.lastRequestAt && isResetPassed)) {
|
|
82
|
+
this.state.delete(key);
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
/**
|
|
87
|
+
* Get the number of tracked endpoints (for monitoring)
|
|
88
|
+
*/
|
|
89
|
+
getTrackedEndpointCount() {
|
|
90
|
+
return this.state.size;
|
|
91
|
+
}
|
|
92
|
+
/**
|
|
93
|
+
* Force cleanup of stale entries
|
|
94
|
+
*/
|
|
95
|
+
forceCleanup() {
|
|
96
|
+
this.lastCleanup = 0;
|
|
97
|
+
this.cleanup();
|
|
98
|
+
}
|
|
99
|
+
getKey(source, endpoint) {
|
|
100
|
+
return endpoint ? `${source}:${endpoint}` : source;
|
|
101
|
+
}
|
|
102
|
+
getConfig(source) {
|
|
103
|
+
const sourceConfig = this.configs.get(source) ?? {};
|
|
104
|
+
return { ...DEFAULT_CONFIG, ...this.defaultConfig, ...sourceConfig };
|
|
105
|
+
}
|
|
106
|
+
configure(source, config) {
|
|
107
|
+
this.configs.set(source, config);
|
|
108
|
+
}
|
|
109
|
+
setCallbacks(callbacks) {
|
|
110
|
+
this.callbacks = callbacks;
|
|
111
|
+
}
|
|
112
|
+
async canProceed(source, endpoint) {
|
|
113
|
+
const key = this.getKey(source, endpoint);
|
|
114
|
+
const state = this.state.get(key);
|
|
115
|
+
if (!state)
|
|
116
|
+
return true;
|
|
117
|
+
const now = new Date();
|
|
118
|
+
// Check retry-after (from 429)
|
|
119
|
+
if (state.retryAfter && state.retryAfter > now) {
|
|
120
|
+
return false;
|
|
121
|
+
}
|
|
122
|
+
// Check if we've reset
|
|
123
|
+
if (state.resetAt && state.resetAt <= now) {
|
|
124
|
+
// Reset has passed, clear the limit
|
|
125
|
+
this.state.delete(key);
|
|
126
|
+
return true;
|
|
127
|
+
}
|
|
128
|
+
// Check remaining quota
|
|
129
|
+
if (state.remaining !== undefined && state.remaining <= 0) {
|
|
130
|
+
return false;
|
|
131
|
+
}
|
|
132
|
+
return true;
|
|
133
|
+
}
|
|
134
|
+
async waitForCapacity(source, endpoint) {
|
|
135
|
+
const config = this.getConfig(source);
|
|
136
|
+
const key = this.getKey(source, endpoint);
|
|
137
|
+
// Check if we can proceed immediately
|
|
138
|
+
if (await this.canProceed(source, endpoint)) {
|
|
139
|
+
// In throttle mode, add delay between requests
|
|
140
|
+
if (config.strategy === 'throttle') {
|
|
141
|
+
const delay = this.getThrottleDelay(source, endpoint);
|
|
142
|
+
if (delay > 0) {
|
|
143
|
+
await sleep(delay);
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
return;
|
|
147
|
+
}
|
|
148
|
+
// We're rate limited
|
|
149
|
+
const state = this.state.get(key);
|
|
150
|
+
const now = Date.now();
|
|
151
|
+
// Calculate wait time
|
|
152
|
+
let waitUntil;
|
|
153
|
+
if (state?.retryAfter) {
|
|
154
|
+
waitUntil = state.retryAfter;
|
|
155
|
+
}
|
|
156
|
+
else if (state?.resetAt) {
|
|
157
|
+
waitUntil = state.resetAt;
|
|
158
|
+
}
|
|
159
|
+
else {
|
|
160
|
+
// No reset info, use fallback
|
|
161
|
+
waitUntil = new Date(now + 60000);
|
|
162
|
+
}
|
|
163
|
+
const totalWaitMs = waitUntil.getTime() - now;
|
|
164
|
+
const totalWaitSeconds = Math.ceil(totalWaitMs / 1000);
|
|
165
|
+
// Check strategy
|
|
166
|
+
if (config.strategy === 'fail') {
|
|
167
|
+
throw new RateLimitError(source, state?.resetAt);
|
|
168
|
+
}
|
|
169
|
+
// Check if wait exceeds max
|
|
170
|
+
if (totalWaitSeconds > config.maxWait) {
|
|
171
|
+
throw new RateLimitTimeoutError(source, 0, config.maxWait);
|
|
172
|
+
}
|
|
173
|
+
// Emit rate limited event
|
|
174
|
+
const event = {
|
|
175
|
+
source,
|
|
176
|
+
endpoint,
|
|
177
|
+
waitSeconds: totalWaitSeconds,
|
|
178
|
+
remaining: state?.remaining,
|
|
179
|
+
resetAt: state?.resetAt,
|
|
180
|
+
strategy: config.strategy,
|
|
181
|
+
};
|
|
182
|
+
this.callbacks.onRateLimited?.(event);
|
|
183
|
+
// Wait with periodic updates
|
|
184
|
+
const startTime = Date.now();
|
|
185
|
+
let lastNotify = 0;
|
|
186
|
+
while (!(await this.canProceed(source, endpoint))) {
|
|
187
|
+
const elapsed = Math.floor((Date.now() - startTime) / 1000);
|
|
188
|
+
// Check timeout
|
|
189
|
+
if (elapsed >= config.maxWait) {
|
|
190
|
+
throw new RateLimitTimeoutError(source, elapsed, config.maxWait);
|
|
191
|
+
}
|
|
192
|
+
// Periodic notification
|
|
193
|
+
if (elapsed >= config.notifyAt && elapsed - lastNotify >= 10) {
|
|
194
|
+
lastNotify = elapsed;
|
|
195
|
+
this.callbacks.onWaiting?.({
|
|
196
|
+
...event,
|
|
197
|
+
elapsedSeconds: elapsed,
|
|
198
|
+
waitSeconds: Math.max(0, totalWaitSeconds - elapsed),
|
|
199
|
+
});
|
|
200
|
+
}
|
|
201
|
+
// Sleep in chunks (check every 1-5 seconds)
|
|
202
|
+
const remainingMs = waitUntil.getTime() - Date.now();
|
|
203
|
+
const sleepMs = Math.min(Math.max(remainingMs, 1000), 5000);
|
|
204
|
+
await sleep(sleepMs);
|
|
205
|
+
}
|
|
206
|
+
// Emit resumed event
|
|
207
|
+
const waitedSeconds = Math.floor((Date.now() - startTime) / 1000);
|
|
208
|
+
this.callbacks.onResumed?.({ source, endpoint, waitedSeconds });
|
|
209
|
+
}
|
|
210
|
+
getThrottleDelay(source, endpoint) {
|
|
211
|
+
const key = this.getKey(source, endpoint);
|
|
212
|
+
const state = this.state.get(key);
|
|
213
|
+
const config = this.getConfig(source);
|
|
214
|
+
if (config.strategy !== 'throttle')
|
|
215
|
+
return 0;
|
|
216
|
+
if (!state)
|
|
217
|
+
return 0;
|
|
218
|
+
const now = Date.now();
|
|
219
|
+
// If we have remaining count and reset time, calculate optimal spacing
|
|
220
|
+
if (state.remaining !== undefined &&
|
|
221
|
+
state.remaining > 0 &&
|
|
222
|
+
state.resetAt &&
|
|
223
|
+
state.resetAt.getTime() > now) {
|
|
224
|
+
const msUntilReset = state.resetAt.getTime() - now;
|
|
225
|
+
// Space requests evenly across remaining time
|
|
226
|
+
const optimalInterval = msUntilReset / state.remaining;
|
|
227
|
+
// Check time since last request
|
|
228
|
+
if (state.lastRequestAt) {
|
|
229
|
+
const msSinceLastRequest = now - state.lastRequestAt.getTime();
|
|
230
|
+
const delay = Math.max(0, optimalInterval - msSinceLastRequest);
|
|
231
|
+
return Math.round(delay);
|
|
232
|
+
}
|
|
233
|
+
return Math.round(optimalInterval);
|
|
234
|
+
}
|
|
235
|
+
// Fallback: use configured RPM
|
|
236
|
+
const intervalMs = 60000 / config.fallbackRpm;
|
|
237
|
+
if (state.lastRequestAt) {
|
|
238
|
+
const msSinceLastRequest = now - state.lastRequestAt.getTime();
|
|
239
|
+
return Math.max(0, Math.round(intervalMs - msSinceLastRequest));
|
|
240
|
+
}
|
|
241
|
+
return 0;
|
|
242
|
+
}
|
|
243
|
+
recordResponse(source, info, endpoint) {
|
|
244
|
+
const key = this.getKey(source, endpoint);
|
|
245
|
+
const now = new Date();
|
|
246
|
+
const state = this.state.get(key) ?? {};
|
|
247
|
+
if (info.remaining !== undefined) {
|
|
248
|
+
state.remaining = info.remaining;
|
|
249
|
+
}
|
|
250
|
+
if (info.limit !== undefined) {
|
|
251
|
+
state.limit = info.limit;
|
|
252
|
+
}
|
|
253
|
+
if (info.resetAt) {
|
|
254
|
+
state.resetAt = info.resetAt;
|
|
255
|
+
}
|
|
256
|
+
if (info.retryAfter !== undefined) {
|
|
257
|
+
state.retryAfter = new Date(now.getTime() + info.retryAfter * 1000);
|
|
258
|
+
}
|
|
259
|
+
state.lastRequestAt = now;
|
|
260
|
+
this.state.set(key, state);
|
|
261
|
+
// Periodically clean up stale entries (every N responses)
|
|
262
|
+
this.responsesSinceCleanup++;
|
|
263
|
+
if (this.responsesSinceCleanup >= CLEANUP_CHECK_INTERVAL) {
|
|
264
|
+
this.responsesSinceCleanup = 0;
|
|
265
|
+
this.cleanup();
|
|
266
|
+
}
|
|
267
|
+
}
|
|
268
|
+
getStatus(source, endpoint) {
|
|
269
|
+
const key = this.getKey(source, endpoint);
|
|
270
|
+
const state = this.state.get(key);
|
|
271
|
+
const now = new Date();
|
|
272
|
+
if (!state) {
|
|
273
|
+
return { isLimited: false };
|
|
274
|
+
}
|
|
275
|
+
const isLimited = (state.retryAfter && state.retryAfter > now) ||
|
|
276
|
+
(state.remaining !== undefined && state.remaining <= 0 && state.resetAt && state.resetAt > now);
|
|
277
|
+
let resetInSeconds;
|
|
278
|
+
if (isLimited && state.resetAt) {
|
|
279
|
+
resetInSeconds = Math.ceil((state.resetAt.getTime() - now.getTime()) / 1000);
|
|
280
|
+
}
|
|
281
|
+
else if (isLimited && state.retryAfter) {
|
|
282
|
+
resetInSeconds = Math.ceil((state.retryAfter.getTime() - now.getTime()) / 1000);
|
|
283
|
+
}
|
|
284
|
+
return {
|
|
285
|
+
remaining: state.remaining,
|
|
286
|
+
limit: state.limit,
|
|
287
|
+
resetAt: state.resetAt,
|
|
288
|
+
isLimited: Boolean(isLimited),
|
|
289
|
+
resetInSeconds,
|
|
290
|
+
};
|
|
291
|
+
}
|
|
292
|
+
}
|
|
293
|
+
/**
|
|
294
|
+
* Parse rate limit info from HTTP response headers
|
|
295
|
+
*
|
|
296
|
+
* Supports common header patterns:
|
|
297
|
+
* - X-RateLimit-Remaining, X-RateLimit-Limit, X-RateLimit-Reset
|
|
298
|
+
* - RateLimit-Remaining, RateLimit-Limit, RateLimit-Reset
|
|
299
|
+
* - X-Rate-Limit-Remaining, etc.
|
|
300
|
+
* - Retry-After (from 429 responses)
|
|
301
|
+
*/
|
|
302
|
+
export function parseRateLimitHeaders(headers) {
|
|
303
|
+
const info = {};
|
|
304
|
+
// Normalize headers to lowercase for matching
|
|
305
|
+
const normalized = {};
|
|
306
|
+
for (const [key, value] of Object.entries(headers)) {
|
|
307
|
+
normalized[key.toLowerCase()] = value;
|
|
308
|
+
}
|
|
309
|
+
// Parse remaining
|
|
310
|
+
const remainingKey = findHeader(normalized, [
|
|
311
|
+
'x-ratelimit-remaining',
|
|
312
|
+
'ratelimit-remaining',
|
|
313
|
+
'x-rate-limit-remaining',
|
|
314
|
+
]);
|
|
315
|
+
if (remainingKey) {
|
|
316
|
+
info.remaining = parseInt(normalized[remainingKey], 10);
|
|
317
|
+
}
|
|
318
|
+
// Parse limit
|
|
319
|
+
const limitKey = findHeader(normalized, [
|
|
320
|
+
'x-ratelimit-limit',
|
|
321
|
+
'ratelimit-limit',
|
|
322
|
+
'x-rate-limit-limit',
|
|
323
|
+
]);
|
|
324
|
+
if (limitKey) {
|
|
325
|
+
info.limit = parseInt(normalized[limitKey], 10);
|
|
326
|
+
}
|
|
327
|
+
// Parse reset
|
|
328
|
+
const resetKey = findHeader(normalized, [
|
|
329
|
+
'x-ratelimit-reset',
|
|
330
|
+
'ratelimit-reset',
|
|
331
|
+
'x-rate-limit-reset',
|
|
332
|
+
]);
|
|
333
|
+
if (resetKey) {
|
|
334
|
+
const resetValue = normalized[resetKey];
|
|
335
|
+
// Could be Unix timestamp or ISO date
|
|
336
|
+
const asNumber = parseInt(resetValue, 10);
|
|
337
|
+
if (!isNaN(asNumber)) {
|
|
338
|
+
// Unix timestamp (seconds)
|
|
339
|
+
if (asNumber > 1000000000000) {
|
|
340
|
+
// Already in milliseconds
|
|
341
|
+
info.resetAt = new Date(asNumber);
|
|
342
|
+
}
|
|
343
|
+
else {
|
|
344
|
+
// In seconds
|
|
345
|
+
info.resetAt = new Date(asNumber * 1000);
|
|
346
|
+
}
|
|
347
|
+
}
|
|
348
|
+
else {
|
|
349
|
+
// Try as date string
|
|
350
|
+
const parsed = new Date(resetValue);
|
|
351
|
+
if (!isNaN(parsed.getTime())) {
|
|
352
|
+
info.resetAt = parsed;
|
|
353
|
+
}
|
|
354
|
+
}
|
|
355
|
+
}
|
|
356
|
+
// Parse Retry-After (usually from 429 responses)
|
|
357
|
+
const retryAfter = normalized['retry-after'];
|
|
358
|
+
if (retryAfter) {
|
|
359
|
+
const asNumber = parseInt(retryAfter, 10);
|
|
360
|
+
if (!isNaN(asNumber)) {
|
|
361
|
+
info.retryAfter = asNumber;
|
|
362
|
+
}
|
|
363
|
+
else {
|
|
364
|
+
// HTTP-date format
|
|
365
|
+
const parsed = new Date(retryAfter);
|
|
366
|
+
if (!isNaN(parsed.getTime())) {
|
|
367
|
+
info.retryAfter = Math.ceil((parsed.getTime() - Date.now()) / 1000);
|
|
368
|
+
}
|
|
369
|
+
}
|
|
370
|
+
}
|
|
371
|
+
return info;
|
|
372
|
+
}
|
|
373
|
+
function findHeader(headers, candidates) {
|
|
374
|
+
for (const candidate of candidates) {
|
|
375
|
+
if (candidate in headers) {
|
|
376
|
+
return candidate;
|
|
377
|
+
}
|
|
378
|
+
}
|
|
379
|
+
return undefined;
|
|
380
|
+
}
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import type { TokenStore, OAuth2Tokens } from './types.js';
|
|
2
|
+
/**
|
|
3
|
+
* In-memory token store - useful for development and single-process deployments
|
|
4
|
+
*/
|
|
5
|
+
export declare class InMemoryTokenStore implements TokenStore {
|
|
6
|
+
private tokens;
|
|
7
|
+
get(connectionId: string): Promise<OAuth2Tokens | null>;
|
|
8
|
+
set(connectionId: string, tokens: OAuth2Tokens): Promise<void>;
|
|
9
|
+
delete(connectionId: string): Promise<void>;
|
|
10
|
+
touch(connectionId: string): Promise<void>;
|
|
11
|
+
list(): Promise<string[]>;
|
|
12
|
+
/** Get tokens that need proactive refresh (approaching expiry or non-use expiry) */
|
|
13
|
+
getTokensNeedingRefresh(bufferSeconds?: number): Promise<string[]>;
|
|
14
|
+
}
|
|
15
|
+
/**
|
|
16
|
+
* File-based token store - persists tokens to a JSON file
|
|
17
|
+
* Suitable for CLI tools and single-user scenarios
|
|
18
|
+
*/
|
|
19
|
+
export declare class FileTokenStore implements TokenStore {
|
|
20
|
+
private filePath;
|
|
21
|
+
private cache;
|
|
22
|
+
constructor(filePath: string);
|
|
23
|
+
private load;
|
|
24
|
+
private save;
|
|
25
|
+
get(connectionId: string): Promise<OAuth2Tokens | null>;
|
|
26
|
+
set(connectionId: string, tokens: OAuth2Tokens): Promise<void>;
|
|
27
|
+
delete(connectionId: string): Promise<void>;
|
|
28
|
+
touch(connectionId: string): Promise<void>;
|
|
29
|
+
list(): Promise<string[]>;
|
|
30
|
+
}
|