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