@agent-score/commerce 2.1.0 → 2.1.1

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 (64) hide show
  1. package/README.md +1 -1
  2. package/dist/challenge/index.js.map +1 -1
  3. package/dist/challenge/index.mjs.map +1 -1
  4. package/dist/{checkout-Bd_4aQ6c.d.mts → checkout-BRw_caGr.d.mts} +1 -22
  5. package/dist/{checkout-BH-I_Ns8.d.ts → checkout-CuSNUJFX.d.ts} +1 -22
  6. package/dist/core.js +1 -1
  7. package/dist/core.js.map +1 -1
  8. package/dist/core.mjs +1 -1
  9. package/dist/core.mjs.map +1 -1
  10. package/dist/{default_rails-BxBzcCA1.d.ts → default_rails-C5gKZJMI.d.ts} +11 -1
  11. package/dist/{default_rails-BWAquZeu.d.mts → default_rails-XFCuRddA.d.mts} +11 -1
  12. package/dist/discovery/index.d.mts +1 -1
  13. package/dist/discovery/index.d.ts +1 -1
  14. package/dist/identity/express.js +1 -1
  15. package/dist/identity/express.js.map +1 -1
  16. package/dist/identity/express.mjs +1 -1
  17. package/dist/identity/express.mjs.map +1 -1
  18. package/dist/identity/fastify.js +1 -1
  19. package/dist/identity/fastify.js.map +1 -1
  20. package/dist/identity/fastify.mjs +1 -1
  21. package/dist/identity/fastify.mjs.map +1 -1
  22. package/dist/identity/hono.js +1 -1
  23. package/dist/identity/hono.js.map +1 -1
  24. package/dist/identity/hono.mjs +1 -1
  25. package/dist/identity/hono.mjs.map +1 -1
  26. package/dist/identity/nextjs.js +1 -1
  27. package/dist/identity/nextjs.js.map +1 -1
  28. package/dist/identity/nextjs.mjs +1 -1
  29. package/dist/identity/nextjs.mjs.map +1 -1
  30. package/dist/identity/policy.js +22 -23363
  31. package/dist/identity/policy.js.map +1 -1
  32. package/dist/identity/policy.mjs +1 -23366
  33. package/dist/identity/policy.mjs.map +1 -1
  34. package/dist/identity/web.js +1 -1
  35. package/dist/identity/web.js.map +1 -1
  36. package/dist/identity/web.mjs +1 -1
  37. package/dist/identity/web.mjs.map +1 -1
  38. package/dist/index.d.mts +72 -5
  39. package/dist/index.d.ts +72 -5
  40. package/dist/index.js +256 -136
  41. package/dist/index.js.map +1 -1
  42. package/dist/index.mjs +253 -134
  43. package/dist/index.mjs.map +1 -1
  44. package/dist/middleware/express.js.map +1 -1
  45. package/dist/middleware/express.mjs.map +1 -1
  46. package/dist/middleware/fastify.js.map +1 -1
  47. package/dist/middleware/fastify.mjs.map +1 -1
  48. package/dist/middleware/hono.js.map +1 -1
  49. package/dist/middleware/hono.mjs.map +1 -1
  50. package/dist/middleware/nextjs.js.map +1 -1
  51. package/dist/middleware/nextjs.mjs.map +1 -1
  52. package/dist/middleware/web.js.map +1 -1
  53. package/dist/middleware/web.mjs.map +1 -1
  54. package/dist/payment/index.d.mts +13 -17
  55. package/dist/payment/index.d.ts +13 -17
  56. package/dist/payment/index.js +80 -4
  57. package/dist/payment/index.js.map +1 -1
  58. package/dist/payment/index.mjs +79 -4
  59. package/dist/payment/index.mjs.map +1 -1
  60. package/dist/stripe-multichain/index.js +53 -4
  61. package/dist/stripe-multichain/index.js.map +1 -1
  62. package/dist/stripe-multichain/index.mjs +53 -4
  63. package/dist/stripe-multichain/index.mjs.map +1 -1
  64. package/package.json +4 -4
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/middleware/express.ts","../../src/_redis.ts","../../src/middleware/_core.ts"],"sourcesContent":["import {\n RATE_LIMIT_JSON_BODY,\n createRateLimiter,\n defaultKeyFromForwardedFor,\n type RateLimitCoreOptions,\n} from './_core';\nimport type { NextFunction, Request, RequestHandler, Response } from 'express';\n\nexport interface RateLimitExpressOptions extends RateLimitCoreOptions {\n /** Bucket key resolver. Default: first hop of `x-forwarded-for`, else req.ip, else `'unknown'`. */\n keyResolver?: (req: Request) => string;\n}\n\nexport function rateLimitExpress(opts: RateLimitExpressOptions = {}): RequestHandler {\n const limiter = createRateLimiter(opts);\n const keyResolver =\n opts.keyResolver ??\n ((req: Request): string => {\n const forwarded = req.header('x-forwarded-for');\n if (forwarded) return defaultKeyFromForwardedFor(forwarded);\n return req.ip ?? 'unknown';\n });\n\n return async (req: Request, res: Response, next: NextFunction) => {\n const { allowed, remaining, limit } = await limiter.check(keyResolver(req));\n res.setHeader('X-RateLimit-Limit', String(limit));\n res.setHeader('X-RateLimit-Remaining', String(remaining));\n if (!allowed) {\n res.setHeader('Cache-Control', 'no-store');\n res.status(429).json(RATE_LIMIT_JSON_BODY);\n return;\n }\n next();\n };\n}\n","/** Shared lazy `ioredis` factory. Used by `quote_cache`, `middleware/_core`,\n * and `stripe-multichain/pi-cache` so they don't drift on connect-timeout,\n * TLS handling, or error-logging posture.\n *\n * `ioredis` is an optional peer dep — callers pass `redisUrl` (or rely on\n * `process.env.REDIS_URL`); when unset or the lazy import fails, this returns\n * null and the caller falls back to its in-process `Map`.\n *\n * Not part of the public API.\n */\n\n/** Minimal Redis surface — each caller intersects with its own usage\n * (incr/expire for rate-limit, get/set/del for caches). Returning `unknown`\n * on commands keeps the shape narrow; cast at the call site. */\nexport interface MinimalRedis {\n on(event: 'error', handler: (err: Error) => void): unknown;\n}\n\nexport interface CreateRedisOptions {\n /** Override `process.env.REDIS_URL` for tests. */\n url?: string;\n /** Logging label, e.g. `'quote-cache'` / `'rate-limit'` / `'pi-cache'`. */\n label: string;\n /** Connect timeout in ms. Default `3000`. */\n connectTimeout?: number;\n /** Per-request retry cap. Default `1`. */\n maxRetriesPerRequest?: number;\n}\n\n/** Lazy-import ioredis and construct a client. Returns null when:\n * - no URL is configured (caller falls back to in-memory)\n * - `ioredis` isn't installed (optional peer; caller falls back to in-memory)\n * - the import throws for any other reason\n *\n * `rediss://` URLs auto-enable TLS. The error handler logs with the caller's\n * label so multi-cache deployments can tell which subsystem complained. */\nasync function tryCreateRedis<T extends MinimalRedis>(opts: CreateRedisOptions): Promise<T | null> {\n const url = opts.url ?? process.env.REDIS_URL;\n if (!url) return null;\n try {\n const mod = (await import('ioredis')) as unknown as { default: new (url: string, opts?: unknown) => T };\n const client = new mod.default(url, {\n connectTimeout: opts.connectTimeout ?? 3000,\n maxRetriesPerRequest: opts.maxRetriesPerRequest ?? 1,\n tls: url.startsWith('rediss://') ? {} : undefined,\n });\n client.on('error', (err) => console.error(`[${opts.label}] Redis error:`, err.message));\n return client;\n } catch {\n return null;\n }\n}\n\n/** Memoized-promise variant: call once per caller; subsequent calls return the\n * same promise. Pairs with the pattern `let p: Promise<T|null> | null = null;\n * const getRedis = () => (p ??= tryCreateRedis(...))` in callers that want\n * per-call promise caching without managing the closure themselves. */\nexport function memoizedRedis<T extends MinimalRedis>(opts: CreateRedisOptions): () => Promise<T | null> {\n let promise: Promise<T | null> | null = null;\n return () => {\n if (!promise) promise = tryCreateRedis<T>(opts);\n return promise;\n };\n}\n","import { memoizedRedis, type MinimalRedis } from '../_redis';\n\nexport interface RateLimitCoreOptions {\n windowSeconds?: number;\n maxRequests?: number;\n /** Redis connection URL. Default: `process.env.REDIS_URL`. Falls back to in-memory when unset or the lazy `ioredis` import fails. */\n redisUrl?: string;\n /** Per-instance key prefix so multiple limiters sharing a Redis don't collide. */\n keyPrefix?: string;\n}\n\nexport interface RateLimitDecision {\n allowed: boolean;\n remaining: number;\n limit: number;\n}\n\nexport interface RateLimiter {\n check(key: string): Promise<RateLimitDecision>;\n}\n\ninterface RedisLike extends MinimalRedis {\n incr(key: string): Promise<number>;\n expire(key: string, seconds: number): Promise<unknown>;\n}\n\n/** Framework-agnostic rate limiter. Hono / Express / Fastify / Next.js / Web adapters\n * share one core. Each `createRateLimiter` call owns its own memory map + redis\n * connection, so multiple instances in the same process don't share state unless\n * they share a Redis with the same `keyPrefix`. */\nexport function createRateLimiter(opts: RateLimitCoreOptions = {}): RateLimiter {\n const windowSeconds = opts.windowSeconds ?? 60;\n const maxRequests = opts.maxRequests ?? 60;\n const keyPrefix = opts.keyPrefix ?? 'rl:';\n\n const memMap = new Map<string, { count: number; resetAt: number }>();\n const getRedis = memoizedRedis<RedisLike>({ url: opts.redisUrl, label: 'rate-limit' });\n\n const checkMem = (key: string): RateLimitDecision => {\n const now = Date.now();\n const entry = memMap.get(key);\n if (!entry || entry.resetAt < now) {\n memMap.set(key, { count: 1, resetAt: now + windowSeconds * 1000 });\n return { allowed: true, remaining: maxRequests - 1, limit: maxRequests };\n }\n entry.count++;\n const remaining = Math.max(0, maxRequests - entry.count);\n return { allowed: entry.count <= maxRequests, remaining, limit: maxRequests };\n };\n\n return {\n async check(key: string): Promise<RateLimitDecision> {\n const r = await getRedis();\n if (!r) return checkMem(key);\n try {\n const fullKey = `${keyPrefix}${key}`;\n const count = await r.incr(fullKey);\n if (count === 1) await r.expire(fullKey, windowSeconds);\n const remaining = Math.max(0, maxRequests - count);\n return { allowed: count <= maxRequests, remaining, limit: maxRequests };\n } catch {\n return checkMem(key);\n }\n },\n };\n}\n\nexport const RATE_LIMIT_JSON_BODY = {\n error: { code: 'rate_limited', message: 'Too many requests' },\n} as const;\n\n/** Default key resolver: first hop of `x-forwarded-for`, else `'unknown'`. Works on any\n * framework's request once you adapt the header read. */\nexport function defaultKeyFromForwardedFor(forwardedFor: string | null | undefined): string {\n if (!forwardedFor) return 'unknown';\n return forwardedFor.split(',')[0]?.trim() || 'unknown';\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACoCA,eAAe,eAAuC,MAA6C;AACjG,QAAM,MAAM,KAAK,OAAO,QAAQ,IAAI;AACpC,MAAI,CAAC,IAAK,QAAO;AACjB,MAAI;AACF,UAAM,MAAO,MAAM,OAAO,SAAS;AACnC,UAAM,SAAS,IAAI,IAAI,QAAQ,KAAK;AAAA,MAClC,gBAAgB,KAAK,kBAAkB;AAAA,MACvC,sBAAsB,KAAK,wBAAwB;AAAA,MACnD,KAAK,IAAI,WAAW,WAAW,IAAI,CAAC,IAAI;AAAA,IAC1C,CAAC;AACD,WAAO,GAAG,SAAS,CAAC,QAAQ,QAAQ,MAAM,IA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E,SAAS,SAAS,aAAa,WAAW,OAAO,YAAY;AAAA,MACxE,QAAQ;AACN,eAAO,SAAS,GAAG;AAAA,MACrB;AAAA,IACF;AAAA,EACF;AACF;AAEO,IAAM,uBAAuB;AAAA,EAClC,OAAO,EAAE,MAAM,gBAAgB,SAAS,oBAAoB;AAC9D;AAIO,SAAS,2BAA2B,cAAiD;AAC1F,MAAI,CAAC,aAAc,QAAO;AAC1B,SAAO,aAAa,MAAM,GAAG,EAAE,CAAC,GAAG,KAAK,KAAK;AAC/C;;;AF/DO,SAAS,iBAAiB,OAAgC,CAAC,GAAmB;AACnF,QAAM,UAAU,kBAAkB,IAAI;AACtC,QAAM,cACJ,KAAK,gBACJ,CAAC,QAAyB;AACzB,UAAM,YAAY,IAAI,OAAO,iBAAiB;AAC9C,QAAI,UAAW,QAAO,2BAA2B,SAAS;AAC1D,WAAO,IAAI,MAAM;AAAA,EACnB;AAEF,SAAO,OAAO,KAAc,KAAe,SAAuB;AAChE,UAAM,EAAE,SAAS,WAAW,MAAM,IAAI,MAAM,QAAQ,MAAM,YAAY,GAAG,CAAC;AAC1E,QAAI,UAAU,qBAAqB,OAAO,KAAK,CAAC;AAChD,QAAI,UAAU,yBAAyB,OAAO,SAAS,CAAC;AACxD,QAAI,CAAC,SAAS;AACZ,UAAI,UAAU,iBAAiB,UAAU;AACzC,UAAI,OAAO,GAAG,EAAE,KAAK,oBAAoB;AACzC;AAAA,IACF;AACA,SAAK;AAAA,EACP;AACF;","names":[]}
1
+ {"version":3,"sources":["../../src/middleware/express.ts","../../src/_redis.ts","../../src/middleware/_core.ts"],"sourcesContent":["import {\n RATE_LIMIT_JSON_BODY,\n createRateLimiter,\n defaultKeyFromForwardedFor,\n type RateLimitCoreOptions,\n} from './_core';\nimport type { NextFunction, Request, RequestHandler, Response } from 'express';\n\nexport interface RateLimitExpressOptions extends RateLimitCoreOptions {\n /** Bucket key resolver. Default: first hop of `x-forwarded-for`, else req.ip, else `'unknown'`. */\n keyResolver?: (req: Request) => string;\n}\n\nexport function rateLimitExpress(opts: RateLimitExpressOptions = {}): RequestHandler {\n const limiter = createRateLimiter(opts);\n const keyResolver =\n opts.keyResolver ??\n ((req: Request): string => {\n const forwarded = req.header('x-forwarded-for');\n if (forwarded) return defaultKeyFromForwardedFor(forwarded);\n return req.ip ?? 'unknown';\n });\n\n return async (req: Request, res: Response, next: NextFunction) => {\n const { allowed, remaining, limit } = await limiter.check(keyResolver(req));\n res.setHeader('X-RateLimit-Limit', String(limit));\n res.setHeader('X-RateLimit-Remaining', String(remaining));\n if (!allowed) {\n res.setHeader('Cache-Control', 'no-store');\n res.status(429).json(RATE_LIMIT_JSON_BODY);\n return;\n }\n next();\n };\n}\n","/** Shared lazy `ioredis` factory. Used by `quote_cache`, `middleware/_core`,\n * and `stripe-multichain/pi-cache` so they don't drift on connect-timeout,\n * TLS handling, or error-logging posture.\n *\n * `ioredis` is an optional peer dep — callers pass `redisUrl` (or rely on\n * `process.env.REDIS_URL`); when unset or the lazy import fails, this returns\n * null and the caller falls back to its in-process `Map`.\n *\n * Not part of the public API.\n */\n\n/** Minimal Redis surface — each caller intersects with its own usage\n * (incr/expire for rate-limit, get/set/del for caches). Returning `unknown`\n * on commands keeps the shape narrow; cast at the call site. */\nexport interface MinimalRedis {\n on(event: 'error', handler: (err: Error) => void): unknown;\n}\n\nexport interface CreateRedisOptions {\n /** Override `process.env.REDIS_URL` for tests. */\n url?: string;\n /** Logging label, e.g. `'quote-cache'` / `'rate-limit'` / `'pi-cache'`. */\n label: string;\n /** Connect timeout in ms. Default `3000`. */\n connectTimeout?: number;\n /** Per-request retry cap. Default `1`. */\n maxRetriesPerRequest?: number;\n}\n\n/** Lazy-import ioredis and construct a client. Returns null when:\n * - no URL is configured (caller falls back to in-memory)\n * - `ioredis` isn't installed (optional peer; caller falls back to in-memory)\n * - the import throws for any other reason\n *\n * `rediss://` URLs auto-enable TLS. The error handler logs with the caller's\n * label so multi-cache deployments can tell which subsystem complained. */\nasync function tryCreateRedis<T extends MinimalRedis>(opts: CreateRedisOptions): Promise<T | null> {\n const url = opts.url ?? process.env.REDIS_URL;\n if (!url) return null;\n try {\n const mod = (await import('ioredis')) as unknown as { default: new (url: string, opts?: unknown) => T };\n const client = new mod.default(url, {\n connectTimeout: opts.connectTimeout ?? 3000,\n maxRetriesPerRequest: opts.maxRetriesPerRequest ?? 1,\n tls: url.startsWith('rediss://') ? {} : undefined,\n });\n client.on('error', (err) => console.error(`[${opts.label}] Redis error:`, err.message));\n return client;\n } catch {\n return null;\n }\n}\n\n/** Memoized-promise variant: call once per caller; subsequent calls return the\n * same promise. Pairs with the pattern `let p: Promise<T|null> | null = null;\n * const getRedis = () => (p ??= tryCreateRedis(...))` in callers that want\n * per-call promise caching without managing the closure themselves. */\nexport function memoizedRedis<T extends MinimalRedis>(opts: CreateRedisOptions): () => Promise<T | null> {\n let promise: Promise<T | null> | null = null;\n return () => {\n if (!promise) promise = tryCreateRedis<T>(opts);\n return promise;\n };\n}\n","import { memoizedRedis, type MinimalRedis } from '../_redis';\n\nexport interface RateLimitCoreOptions {\n windowSeconds?: number;\n maxRequests?: number;\n /** Redis connection URL. Default: `process.env.REDIS_URL`. Falls back to in-memory when unset or the lazy `ioredis` import fails. */\n redisUrl?: string;\n /** Per-instance key prefix so multiple limiters sharing a Redis don't collide. */\n keyPrefix?: string;\n}\n\ninterface RateLimitDecision {\n allowed: boolean;\n remaining: number;\n limit: number;\n}\n\nexport interface RateLimiter {\n check(key: string): Promise<RateLimitDecision>;\n}\n\ninterface RedisLike extends MinimalRedis {\n incr(key: string): Promise<number>;\n expire(key: string, seconds: number): Promise<unknown>;\n}\n\n/** Framework-agnostic rate limiter. Hono / Express / Fastify / Next.js / Web adapters\n * share one core. Each `createRateLimiter` call owns its own memory map + redis\n * connection, so multiple instances in the same process don't share state unless\n * they share a Redis with the same `keyPrefix`. */\nexport function createRateLimiter(opts: RateLimitCoreOptions = {}): RateLimiter {\n const windowSeconds = opts.windowSeconds ?? 60;\n const maxRequests = opts.maxRequests ?? 60;\n const keyPrefix = opts.keyPrefix ?? 'rl:';\n\n const memMap = new Map<string, { count: number; resetAt: number }>();\n const getRedis = memoizedRedis<RedisLike>({ url: opts.redisUrl, label: 'rate-limit' });\n\n const checkMem = (key: string): RateLimitDecision => {\n const now = Date.now();\n const entry = memMap.get(key);\n if (!entry || entry.resetAt < now) {\n memMap.set(key, { count: 1, resetAt: now + windowSeconds * 1000 });\n return { allowed: true, remaining: maxRequests - 1, limit: maxRequests };\n }\n entry.count++;\n const remaining = Math.max(0, maxRequests - entry.count);\n return { allowed: entry.count <= maxRequests, remaining, limit: maxRequests };\n };\n\n return {\n async check(key: string): Promise<RateLimitDecision> {\n const r = await getRedis();\n if (!r) return checkMem(key);\n try {\n const fullKey = `${keyPrefix}${key}`;\n const count = await r.incr(fullKey);\n if (count === 1) await r.expire(fullKey, windowSeconds);\n const remaining = Math.max(0, maxRequests - count);\n return { allowed: count <= maxRequests, remaining, limit: maxRequests };\n } catch {\n return checkMem(key);\n }\n },\n };\n}\n\nexport const RATE_LIMIT_JSON_BODY = {\n error: { code: 'rate_limited', message: 'Too many requests' },\n} as const;\n\n/** Default key resolver: first hop of `x-forwarded-for`, else `'unknown'`. Works on any\n * framework's request once you adapt the header read. */\nexport function defaultKeyFromForwardedFor(forwardedFor: string | null | undefined): string {\n if (!forwardedFor) return 'unknown';\n return forwardedFor.split(',')[0]?.trim() || 'unknown';\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACoCA,eAAe,eAAuC,MAA6C;AACjG,QAAM,MAAM,KAAK,OAAO,QAAQ,IAAI;AACpC,MAAI,CAAC,IAAK,QAAO;AACjB,MAAI;AACF,UAAM,MAAO,MAAM,OAAO,SAAS;AACnC,UAAM,SAAS,IAAI,IAAI,QAAQ,KAAK;AAAA,MAClC,gBAAgB,KAAK,kBAAkB;AAAA,MACvC,sBAAsB,KAAK,wBAAwB;AAAA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O;AAClC,YAAI,UAAU,EAAG,OAAM,EAAE,OAAO,SAAS,aAAa;AACtD,cAAM,YAAY,KAAK,IAAI,GAAG,cAAc,KAAK;AACjD,eAAO,EAAE,SAAS,SAAS,aAAa,WAAW,OAAO,YAAY;AAAA,MACxE,QAAQ;AACN,eAAO,SAAS,GAAG;AAAA,MACrB;AAAA,IACF;AAAA,EACF;AACF;AAEO,IAAM,uBAAuB;AAAA,EAClC,OAAO,EAAE,MAAM,gBAAgB,SAAS,oBAAoB;AAC9D;AAIO,SAAS,2BAA2B,cAAiD;AAC1F,MAAI,CAAC,aAAc,QAAO;AAC1B,SAAO,aAAa,MAAM,GAAG,EAAE,CAAC,GAAG,KAAK,KAAK;AAC/C;;;AF/DO,SAAS,iBAAiB,OAAgC,CAAC,GAAmB;AACnF,QAAM,UAAU,kBAAkB,IAAI;AACtC,QAAM,cACJ,KAAK,gBACJ,CAAC,QAAyB;AACzB,UAAM,YAAY,IAAI,OAAO,iBAAiB;AAC9C,QAAI,UAAW,QAAO,2BAA2B,SAAS;AAC1D,WAAO,IAAI,MAAM;AAAA,EACnB;AAEF,SAAO,OAAO,KAAc,KAAe,SAAuB;AAChE,UAAM,EAAE,SAAS,WAAW,MAAM,IAAI,MAAM,QAAQ,MAAM,YAAY,GAAG,CAAC;AAC1E,QAAI,UAAU,qBAAqB,OAAO,KAAK,CAAC;AAChD,QAAI,UAAU,yBAAyB,OAAO,SAAS,CAAC;AACxD,QAAI,CAAC,SAAS;AACZ,UAAI,UAAU,iBAAiB,UAAU;AACzC,UAAI,OAAO,GAAG,EAAE,KAAK,oBAAoB;AACzC;AAAA,IACF;AACA,SAAK;AAAA,EACP;AACF;","names":[]}
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/_redis.ts","../../src/middleware/_core.ts","../../src/middleware/express.ts"],"sourcesContent":["/** Shared lazy `ioredis` factory. Used by `quote_cache`, `middleware/_core`,\n * and `stripe-multichain/pi-cache` so they don't drift on connect-timeout,\n * TLS handling, or error-logging posture.\n *\n * `ioredis` is an optional peer dep — callers pass `redisUrl` (or rely on\n * `process.env.REDIS_URL`); when unset or the lazy import fails, this returns\n * null and the caller falls back to its in-process `Map`.\n *\n * Not part of the public API.\n */\n\n/** Minimal Redis surface — each caller intersects with its own usage\n * (incr/expire for rate-limit, get/set/del for caches). Returning `unknown`\n * on commands keeps the shape narrow; cast at the call site. */\nexport interface MinimalRedis {\n on(event: 'error', handler: (err: Error) => void): unknown;\n}\n\nexport interface CreateRedisOptions {\n /** Override `process.env.REDIS_URL` for tests. */\n url?: string;\n /** Logging label, e.g. `'quote-cache'` / `'rate-limit'` / `'pi-cache'`. */\n label: string;\n /** Connect timeout in ms. Default `3000`. */\n connectTimeout?: number;\n /** Per-request retry cap. Default `1`. */\n maxRetriesPerRequest?: number;\n}\n\n/** Lazy-import ioredis and construct a client. Returns null when:\n * - no URL is configured (caller falls back to in-memory)\n * - `ioredis` isn't installed (optional peer; caller falls back to in-memory)\n * - the import throws for any other reason\n *\n * `rediss://` URLs auto-enable TLS. The error handler logs with the caller's\n * label so multi-cache deployments can tell which subsystem complained. */\nasync function tryCreateRedis<T extends MinimalRedis>(opts: CreateRedisOptions): Promise<T | null> {\n const url = opts.url ?? process.env.REDIS_URL;\n if (!url) return null;\n try {\n const mod = (await import('ioredis')) as unknown as { default: new (url: string, opts?: unknown) => T };\n const client = new mod.default(url, {\n connectTimeout: opts.connectTimeout ?? 3000,\n maxRetriesPerRequest: opts.maxRetriesPerRequest ?? 1,\n tls: url.startsWith('rediss://') ? {} : undefined,\n });\n client.on('error', (err) => console.error(`[${opts.label}] Redis error:`, err.message));\n return client;\n } catch {\n return null;\n }\n}\n\n/** Memoized-promise variant: call once per caller; subsequent calls return the\n * same promise. Pairs with the pattern `let p: Promise<T|null> | null = null;\n * const getRedis = () => (p ??= tryCreateRedis(...))` in callers that want\n * per-call promise caching without managing the closure themselves. */\nexport function memoizedRedis<T extends MinimalRedis>(opts: CreateRedisOptions): () => Promise<T | null> {\n let promise: Promise<T | null> | null = null;\n return () => {\n if (!promise) promise = tryCreateRedis<T>(opts);\n return promise;\n };\n}\n","import { memoizedRedis, type MinimalRedis } from '../_redis';\n\nexport interface RateLimitCoreOptions {\n windowSeconds?: number;\n maxRequests?: number;\n /** Redis connection URL. Default: `process.env.REDIS_URL`. Falls back to in-memory when unset or the lazy `ioredis` import fails. */\n redisUrl?: string;\n /** Per-instance key prefix so multiple limiters sharing a Redis don't collide. */\n keyPrefix?: string;\n}\n\nexport interface RateLimitDecision {\n allowed: boolean;\n remaining: number;\n limit: number;\n}\n\nexport interface RateLimiter {\n check(key: string): Promise<RateLimitDecision>;\n}\n\ninterface RedisLike extends MinimalRedis {\n incr(key: string): Promise<number>;\n expire(key: string, seconds: number): Promise<unknown>;\n}\n\n/** Framework-agnostic rate limiter. Hono / Express / Fastify / Next.js / Web adapters\n * share one core. Each `createRateLimiter` call owns its own memory map + redis\n * connection, so multiple instances in the same process don't share state unless\n * they share a Redis with the same `keyPrefix`. */\nexport function createRateLimiter(opts: RateLimitCoreOptions = {}): RateLimiter {\n const windowSeconds = opts.windowSeconds ?? 60;\n const maxRequests = opts.maxRequests ?? 60;\n const keyPrefix = opts.keyPrefix ?? 'rl:';\n\n const memMap = new Map<string, { count: number; resetAt: number }>();\n const getRedis = memoizedRedis<RedisLike>({ url: opts.redisUrl, label: 'rate-limit' });\n\n const checkMem = (key: string): RateLimitDecision => {\n const now = Date.now();\n const entry = memMap.get(key);\n if (!entry || entry.resetAt < now) {\n memMap.set(key, { count: 1, resetAt: now + windowSeconds * 1000 });\n return { allowed: true, remaining: maxRequests - 1, limit: maxRequests };\n }\n entry.count++;\n const remaining = Math.max(0, maxRequests - entry.count);\n return { allowed: entry.count <= maxRequests, remaining, limit: maxRequests };\n };\n\n return {\n async check(key: string): Promise<RateLimitDecision> {\n const r = await getRedis();\n if (!r) return checkMem(key);\n try {\n const fullKey = `${keyPrefix}${key}`;\n const count = await r.incr(fullKey);\n if (count === 1) await r.expire(fullKey, windowSeconds);\n const remaining = Math.max(0, maxRequests - count);\n return { allowed: count <= maxRequests, remaining, limit: maxRequests };\n } catch {\n return checkMem(key);\n }\n },\n };\n}\n\nexport const RATE_LIMIT_JSON_BODY = {\n error: { code: 'rate_limited', message: 'Too many requests' },\n} as const;\n\n/** Default key resolver: first hop of `x-forwarded-for`, else `'unknown'`. Works on any\n * framework's request once you adapt the header read. */\nexport function defaultKeyFromForwardedFor(forwardedFor: string | null | undefined): string {\n if (!forwardedFor) return 'unknown';\n return forwardedFor.split(',')[0]?.trim() || 'unknown';\n}\n","import {\n RATE_LIMIT_JSON_BODY,\n createRateLimiter,\n defaultKeyFromForwardedFor,\n type RateLimitCoreOptions,\n} from './_core';\nimport type { NextFunction, Request, RequestHandler, Response } from 'express';\n\nexport interface RateLimitExpressOptions extends RateLimitCoreOptions {\n /** Bucket key resolver. Default: first hop of `x-forwarded-for`, else req.ip, else `'unknown'`. */\n keyResolver?: (req: Request) => string;\n}\n\nexport function rateLimitExpress(opts: RateLimitExpressOptions = {}): RequestHandler {\n const limiter = createRateLimiter(opts);\n const keyResolver =\n opts.keyResolver ??\n ((req: Request): string => {\n const forwarded = req.header('x-forwarded-for');\n if (forwarded) return defaultKeyFromForwardedFor(forwarded);\n return req.ip ?? 'unknown';\n });\n\n return async (req: Request, res: Response, next: NextFunction) => {\n const { allowed, remaining, limit } = await limiter.check(keyResolver(req));\n res.setHeader('X-RateLimit-Limit', String(limit));\n res.setHeader('X-RateLimit-Remaining', String(remaining));\n if (!allowed) {\n res.setHeader('Cache-Control', 'no-store');\n res.status(429).json(RATE_LIMIT_JSON_BODY);\n return;\n }\n next();\n };\n}\n"],"mappings":";AAoCA,eAAe,eAAuC,MAA6C;AACjG,QAAM,MAAM,KAAK,OAAO,QAAQ,IAAI;AACpC,MAAI,CAAC,IAAK,QAAO;AACjB,MAAI;AACF,UAAM,MAAO,MAAM,OAAO,SAAS;AACnC,UAAM,SAAS,IAAI,IAAI,QAAQ,KAAK;AAAA,M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U,GAAG,SAAS,GAAG,GAAG;AAClC,cAAM,QAAQ,MAAM,EAAE,KAAK,OAAO;AAClC,YAAI,UAAU,EAAG,OAAM,EAAE,OAAO,SAAS,aAAa;AACtD,cAAM,YAAY,KAAK,IAAI,GAAG,cAAc,KAAK;AACjD,eAAO,EAAE,SAAS,SAAS,aAAa,WAAW,OAAO,YAAY;AAAA,MACxE,QAAQ;AACN,eAAO,SAAS,GAAG;AAAA,MACrB;AAAA,IACF;AAAA,EACF;AACF;AAEO,IAAM,uBAAuB;AAAA,EAClC,OAAO,EAAE,MAAM,gBAAgB,SAAS,oBAAoB;AAC9D;AAIO,SAAS,2BAA2B,cAAiD;AAC1F,MAAI,CAAC,aAAc,QAAO;AAC1B,SAAO,aAAa,MAAM,GAAG,EAAE,CAAC,GAAG,KAAK,KAAK;AAC/C;;;AC/DO,SAAS,iBAAiB,OAAgC,CAAC,GAAmB;AACnF,QAAM,UAAU,kBAAkB,IAAI;AACtC,QAAM,cACJ,KAAK,gBACJ,CAAC,QAAyB;AACzB,UAAM,YAAY,IAAI,OAAO,iBAAiB;AAC9C,QAAI,UAAW,QAAO,2BAA2B,SAAS;AAC1D,WAAO,IAAI,MAAM;AAAA,EACnB;AAEF,SAAO,OAAO,KAAc,KAAe,SAAuB;AAChE,UAAM,EAAE,SAAS,WAAW,MAAM,IAAI,MAAM,QAAQ,MAAM,YAAY,GAAG,CAAC;AAC1E,QAAI,UAAU,qBAAqB,OAAO,KAAK,CAAC;AAChD,QAAI,UAAU,yBAAyB,OAAO,SAAS,CAAC;AACxD,QAAI,CAAC,SAAS;AACZ,UAAI,UAAU,iBAAiB,UAAU;AACzC,UAAI,OAAO,GAAG,EAAE,KAAK,oBAAoB;AACzC;AAAA,IACF;AACA,SAAK;AAAA,EACP;AACF;","names":[]}
1
+ {"version":3,"sources":["../../src/_redis.ts","../../src/middleware/_core.ts","../../src/middleware/express.ts"],"sourcesContent":["/** Shared lazy `ioredis` factory. Used by `quote_cache`, `middleware/_core`,\n * and `stripe-multichain/pi-cache` so they don't drift on connect-timeout,\n * TLS handling, or error-logging posture.\n *\n * `ioredis` is an optional peer dep — callers pass `redisUrl` (or rely on\n * `process.env.REDIS_URL`); when unset or the lazy import fails, this returns\n * null and the caller falls back to its in-process `Map`.\n *\n * Not part of the public API.\n */\n\n/** Minimal Redis surface — each caller intersects with its own usage\n * (incr/expire for rate-limit, get/set/del for caches). Returning `unknown`\n * on commands keeps the shape narrow; cast at the call site. */\nexport interface MinimalRedis {\n on(event: 'error', handler: (err: Error) => void): unknown;\n}\n\nexport interface CreateRedisOptions {\n /** Override `process.env.REDIS_URL` for tests. */\n url?: string;\n /** Logging label, e.g. `'quote-cache'` / `'rate-limit'` / `'pi-cache'`. */\n label: string;\n /** Connect timeout in ms. Default `3000`. */\n connectTimeout?: number;\n /** Per-request retry cap. Default `1`. */\n maxRetriesPerRequest?: number;\n}\n\n/** Lazy-import ioredis and construct a client. Returns null when:\n * - no URL is configured (caller falls back to in-memory)\n * - `ioredis` isn't installed (optional peer; caller falls back to in-memory)\n * - the import throws for any other reason\n *\n * `rediss://` URLs auto-enable TLS. The error handler logs with the caller's\n * label so multi-cache deployments can tell which subsystem complained. */\nasync function tryCreateRedis<T extends MinimalRedis>(opts: CreateRedisOptions): Promise<T | null> {\n const url = opts.url ?? process.env.REDIS_URL;\n if (!url) return null;\n try {\n const mod = (await import('ioredis')) as unknown as { default: new (url: string, opts?: unknown) => T };\n const client = new mod.default(url, {\n connectTimeout: opts.connectTimeout ?? 3000,\n maxRetriesPerRequest: opts.maxRetriesPerRequest ?? 1,\n tls: url.startsWith('rediss://') ? {} : undefined,\n });\n client.on('error', (err) => console.error(`[${opts.label}] Redis error:`, err.message));\n return client;\n } catch {\n return null;\n }\n}\n\n/** Memoized-promise variant: call once per caller; subsequent calls return the\n * same promise. Pairs with the pattern `let p: Promise<T|null> | null = null;\n * const getRedis = () => (p ??= tryCreateRedis(...))` in callers that want\n * per-call promise caching without managing the closure themselves. */\nexport function memoizedRedis<T extends MinimalRedis>(opts: CreateRedisOptions): () => Promise<T | null> {\n let promise: Promise<T | null> | null = null;\n return () => {\n if (!promise) promise = tryCreateRedis<T>(opts);\n return promise;\n };\n}\n","import { memoizedRedis, type MinimalRedis } from '../_redis';\n\nexport interface RateLimitCoreOptions {\n windowSeconds?: number;\n maxRequests?: number;\n /** Redis connection URL. Default: `process.env.REDIS_URL`. Falls back to in-memory when unset or the lazy `ioredis` import fails. */\n redisUrl?: string;\n /** Per-instance key prefix so multiple limiters sharing a Redis don't collide. */\n keyPrefix?: string;\n}\n\ninterface RateLimitDecision {\n allowed: boolean;\n remaining: number;\n limit: number;\n}\n\nexport interface RateLimiter {\n check(key: string): Promise<RateLimitDecision>;\n}\n\ninterface RedisLike extends MinimalRedis {\n incr(key: string): Promise<number>;\n expire(key: string, seconds: number): Promise<unknown>;\n}\n\n/** Framework-agnostic rate limiter. Hono / Express / Fastify / Next.js / Web adapters\n * share one core. Each `createRateLimiter` call owns its own memory map + redis\n * connection, so multiple instances in the same process don't share state unless\n * they share a Redis with the same `keyPrefix`. */\nexport function createRateLimiter(opts: RateLimitCoreOptions = {}): RateLimiter {\n const windowSeconds = opts.windowSeconds ?? 60;\n const maxRequests = opts.maxRequests ?? 60;\n const keyPrefix = opts.keyPrefix ?? 'rl:';\n\n const memMap = new Map<string, { count: number; resetAt: number }>();\n const getRedis = memoizedRedis<RedisLike>({ url: opts.redisUrl, label: 'rate-limit' });\n\n const checkMem = (key: string): RateLimitDecision => {\n const now = Date.now();\n const entry = memMap.get(key);\n if (!entry || entry.resetAt < now) {\n memMap.set(key, { count: 1, resetAt: now + windowSeconds * 1000 });\n return { allowed: true, remaining: maxRequests - 1, limit: maxRequests };\n }\n entry.count++;\n const remaining = Math.max(0, maxRequests - entry.count);\n return { allowed: entry.count <= maxRequests, remaining, limit: maxRequests };\n };\n\n return {\n async check(key: string): Promise<RateLimitDecision> {\n const r = await getRedis();\n if (!r) return checkMem(key);\n try {\n const fullKey = `${keyPrefix}${key}`;\n const count = await r.incr(fullKey);\n if (count === 1) await r.expire(fullKey, windowSeconds);\n const remaining = Math.max(0, maxRequests - count);\n return { allowed: count <= maxRequests, remaining, limit: maxRequests };\n } catch {\n return checkMem(key);\n }\n },\n };\n}\n\nexport const RATE_LIMIT_JSON_BODY = {\n error: { code: 'rate_limited', message: 'Too many requests' },\n} as const;\n\n/** Default key resolver: first hop of `x-forwarded-for`, else `'unknown'`. Works on any\n * framework's request once you adapt the header read. */\nexport function defaultKeyFromForwardedFor(forwardedFor: string | null | undefined): string {\n if (!forwardedFor) return 'unknown';\n return forwardedFor.split(',')[0]?.trim() || 'unknown';\n}\n","import {\n RATE_LIMIT_JSON_BODY,\n createRateLimiter,\n defaultKeyFromForwardedFor,\n type RateLimitCoreOptions,\n} from './_core';\nimport type { NextFunction, Request, RequestHandler, Response } from 'express';\n\nexport interface RateLimitExpressOptions extends RateLimitCoreOptions {\n /** Bucket key resolver. Default: first hop of `x-forwarded-for`, else req.ip, else `'unknown'`. */\n keyResolver?: (req: Request) => string;\n}\n\nexport function rateLimitExpress(opts: RateLimitExpressOptions = {}): RequestHandler {\n const limiter = createRateLimiter(opts);\n const keyResolver =\n opts.keyResolver ??\n ((req: Request): string => {\n const forwarded = req.header('x-forwarded-for');\n if (forwarded) return defaultKeyFromForwardedFor(forwarded);\n return req.ip ?? 'unknown';\n });\n\n return async (req: Request, res: Response, next: NextFunction) => {\n const { allowed, remaining, limit } = await limiter.check(keyResolver(req));\n res.setHeader('X-RateLimit-Limit', String(limit));\n res.setHeader('X-RateLimit-Remaining', String(remaining));\n if (!allowed) {\n res.setHeader('Cache-Control', 'no-store');\n res.status(429).json(RATE_LIMIT_JSON_BODY);\n return;\n }\n next();\n };\n}\n"],"mappings":";AAoCA,eAAe,eAAuC,MAA6C;AACjG,QAAM,MAAM,KAAK,OAAO,QAAQ,IAAI;AACpC,MAAI,CAAC,IAAK,QAAO;AACjB,MAAI;AACF,UAAM,MAAO,MAAM,OAAO,SAA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middleware/_core.ts"],"sourcesContent":["import {\n RATE_LIMIT_JSON_BODY,\n createRateLimiter,\n defaultKeyFromForwardedFor,\n type RateLimitCoreOptions,\n} from './_core';\nimport type { FastifyReply, FastifyRequest, preHandlerHookHandler } from 'fastify';\n\nexport interface RateLimitFastifyOptions extends RateLimitCoreOptions {\n /** Bucket key resolver. Default: first hop of `x-forwarded-for`, else `req.ip`, else `'unknown'`. */\n keyResolver?: (req: FastifyRequest) => string;\n}\n\nexport function rateLimitFastify(opts: RateLimitFastifyOptions = {}): preHandlerHookHandler {\n const limiter = createRateLimiter(opts);\n const keyResolver =\n opts.keyResolver ??\n ((req: FastifyRequest): string => {\n const forwarded = req.headers['x-forwarded-for'];\n const forwardedStr = Array.isArray(forwarded) ? forwarded[0] : forwarded;\n if (forwardedStr) return defaultKeyFromForwardedFor(forwardedStr);\n return req.ip ?? 'unknown';\n });\n\n return async (req: FastifyRequest, reply: FastifyReply) => {\n const { allowed, remaining, limit } = await limiter.check(keyResolver(req));\n reply.header('X-RateLimit-Limit', String(limit));\n reply.header('X-RateLimit-Remaining', String(remaining));\n if (!allowed) {\n reply.header('Cache-Control', 'no-store');\n reply.code(429).send(RATE_LIMIT_JSON_BODY);\n }\n };\n}\n","/** Shared lazy `ioredis` factory. Used by `quote_cache`, `middleware/_core`,\n * and `stripe-multichain/pi-cache` so they don't drift on connect-timeout,\n * TLS handling, or error-logging posture.\n *\n * `ioredis` is an optional peer dep — callers pass `redisUrl` (or rely on\n * `process.env.REDIS_URL`); when unset or the lazy import fails, this returns\n * null and the caller falls back to its in-process `Map`.\n *\n * Not part of the public API.\n */\n\n/** Minimal Redis surface — each caller intersects with its own usage\n * (incr/expire for rate-limit, get/set/del for caches). Returning `unknown`\n * on commands keeps the shape narrow; cast at the call site. */\nexport interface MinimalRedis {\n on(event: 'error', handler: (err: Error) => void): unknown;\n}\n\nexport interface CreateRedisOptions {\n /** Override `process.env.REDIS_URL` for tests. */\n url?: string;\n /** Logging label, e.g. `'quote-cache'` / `'rate-limit'` / `'pi-cache'`. */\n label: string;\n /** Connect timeout in ms. Default `3000`. */\n connectTimeout?: number;\n /** Per-request retry cap. Default `1`. */\n maxRetriesPerRequest?: number;\n}\n\n/** Lazy-import ioredis and construct a client. Returns null when:\n * - no URL is configured (caller falls back to in-memory)\n * - `ioredis` isn't installed (optional peer; caller falls back to in-memory)\n * - the import throws for any other reason\n *\n * `rediss://` URLs auto-enable TLS. The error handler logs with the caller's\n * label so multi-cache deployments can tell which subsystem complained. */\nasync function tryCreateRedis<T extends MinimalRedis>(opts: CreateRedisOptions): Promise<T | null> {\n const url = opts.url ?? process.env.REDIS_URL;\n if (!url) return null;\n try {\n const mod = (await import('ioredis')) as unknown as { default: new (url: string, opts?: unknown) => T };\n const client = new mod.default(url, {\n connectTimeout: opts.connectTimeout ?? 3000,\n maxRetriesPerRequest: opts.maxRetriesPerRequest ?? 1,\n tls: url.startsWith('rediss://') ? {} : undefined,\n });\n client.on('error', (err) => console.error(`[${opts.label}] Redis error:`, err.message));\n return client;\n } catch {\n return null;\n }\n}\n\n/** Memoized-promise variant: call once per caller; subsequent calls return the\n * same promise. Pairs with the pattern `let p: Promise<T|null> | null = null;\n * const getRedis = () => (p ??= tryCreateRedis(...))` in callers that want\n * per-call promise caching without managing the closure themselves. */\nexport function memoizedRedis<T extends MinimalRedis>(opts: CreateRedisOptions): () => Promise<T | null> {\n let promise: Promise<T | null> | null = null;\n return () => {\n if (!promise) promise = tryCreateRedis<T>(opts);\n return promise;\n };\n}\n","import { memoizedRedis, type MinimalRedis } from '../_redis';\n\nexport interface RateLimitCoreOptions {\n windowSeconds?: number;\n maxRequests?: number;\n /** Redis connection URL. Default: `process.env.REDIS_URL`. Falls back to in-memory when unset or the lazy `ioredis` import fails. */\n redisUrl?: string;\n /** Per-instance key prefix so multiple limiters sharing a Redis don't collide. */\n keyPrefix?: string;\n}\n\nexport interface RateLimitDecision {\n allowed: boolean;\n remaining: number;\n limit: number;\n}\n\nexport interface RateLimiter {\n check(key: string): Promise<RateLimitDecision>;\n}\n\ninterface RedisLike extends MinimalRedis {\n incr(key: string): Promise<number>;\n expire(key: string, seconds: number): Promise<unknown>;\n}\n\n/** Framework-agnostic rate limiter. Hono / Express / Fastify / Next.js / Web adapters\n * share one core. Each `createRateLimiter` call owns its own memory map + redis\n * connection, so multiple instances in the same process don't share state unless\n * they share a Redis with the same `keyPrefix`. */\nexport function createRateLimiter(opts: RateLimitCoreOptions = {}): RateLimiter {\n const windowSeconds = opts.windowSeconds ?? 60;\n const maxRequests = opts.maxRequests ?? 60;\n const keyPrefix = opts.keyPrefix ?? 'rl:';\n\n const memMap = new Map<string, { count: number; resetAt: number }>();\n const getRedis = memoizedRedis<RedisLike>({ url: opts.redisUrl, label: 'rate-limit' });\n\n const checkMem = (key: string): RateLimitDecision => {\n const now = Date.now();\n const entry = memMap.get(key);\n if (!entry || entry.resetAt < now) {\n memMap.set(key, { count: 1, resetAt: now + windowSeconds * 1000 });\n return { allowed: true, remaining: maxRequests - 1, limit: maxRequests };\n }\n entry.count++;\n const remaining = Math.max(0, maxRequests - entry.count);\n return { allowed: entry.count <= maxRequests, remaining, limit: maxRequests };\n };\n\n return {\n async check(key: string): Promise<RateLimitDecision> {\n const r = await getRedis();\n if (!r) return checkMem(key);\n try {\n const fullKey = `${keyPrefix}${key}`;\n const count = await r.incr(fullKey);\n if (count === 1) await r.expire(fullKey, windowSeconds);\n const remaining = Math.max(0, maxRequests - count);\n return { allowed: count <= maxRequests, remaining, limit: maxRequests };\n } catch {\n return checkMem(key);\n }\n },\n };\n}\n\nexport const RATE_LIMIT_JSON_BODY = {\n error: { code: 'rate_limited', message: 'Too many requests' },\n} as const;\n\n/** Default key resolver: first hop of `x-forwarded-for`, else `'unknown'`. Works on any\n * framework's request once you adapt the header read. */\nexport function defaultKeyFromForwardedFor(forwardedFor: string | null | undefined): string {\n if (!forwardedFor) return 'unknown';\n return forwardedFor.split(',')[0]?.trim() || 'unknown';\n}\n"],"mappings":";;;;;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C;AAC/C,UAAM,OAAO,yBAAyB,OAAO,SAAS,CAAC;AACvD,QAAI,CAAC,SAAS;AACZ,YAAM,OAAO,iBAAiB,UAAU;AACxC,YAAM,KAAK,GAAG,EAAE,KAAK,oBAAoB;AAAA,IAC3C;AAAA,EACF;AACF;","names":[]}
1
+ {"version":3,"sources":["../../src/middleware/fastify.ts","../../src/_redis.ts","../../src/middleware/_core.ts"],"sourcesContent":["import {\n RATE_LIMIT_JSON_BODY,\n createRateLimiter,\n defaultKeyFromForwardedFor,\n type RateLimitCoreOptions,\n} from './_core';\nimport type { FastifyReply, FastifyRequest, preHandlerHookHandler } from 'fastify';\n\nexport interface RateLimitFastifyOptions extends RateLimitCoreOptions {\n /** Bucket key resolver. Default: first hop of `x-forwarded-for`, else `req.ip`, else `'unknown'`. */\n keyResolver?: (req: FastifyRequest) => string;\n}\n\nexport function rateLimitFastify(opts: RateLimitFastifyOptions = {}): preHandlerHookHandler {\n const limiter = createRateLimiter(opts);\n const keyResolver =\n opts.keyResolver ??\n ((req: FastifyRequest): string => {\n const forwarded = req.headers['x-forwarded-for'];\n const forwardedStr = Array.isArray(forwarded) ? forwarded[0] : forwarded;\n if (forwardedStr) return defaultKeyFromForwardedFor(forwardedStr);\n return req.ip ?? 'unknown';\n });\n\n return async (req: FastifyRequest, reply: FastifyReply) => {\n const { allowed, remaining, limit } = await limiter.check(keyResolver(req));\n reply.header('X-RateLimit-Limit', String(limit));\n reply.header('X-RateLimit-Remaining', String(remaining));\n if (!allowed) {\n reply.header('Cache-Control', 'no-store');\n reply.code(429).send(RATE_LIMIT_JSON_BODY);\n }\n };\n}\n","/** Shared lazy `ioredis` factory. Used by `quote_cache`, `middleware/_core`,\n * and `stripe-multichain/pi-cache` so they don't drift on connect-timeout,\n * TLS handling, or error-logging posture.\n *\n * `ioredis` is an optional peer dep — callers pass `redisUrl` (or rely on\n * `process.env.REDIS_URL`); when unset or the lazy import fails, this returns\n * null and the caller falls back to its in-process `Map`.\n *\n * Not part of the public API.\n */\n\n/** Minimal Redis surface — each caller intersects with its own usage\n * (incr/expire for rate-limit, get/set/del for caches). Returning `unknown`\n * on commands keeps the shape narrow; cast at the call site. */\nexport interface MinimalRedis {\n on(event: 'error', handler: (err: Error) => void): unknown;\n}\n\nexport interface CreateRedisOptions {\n /** Override `process.env.REDIS_URL` for tests. */\n url?: string;\n /** Logging label, e.g. `'quote-cache'` / `'rate-limit'` / `'pi-cache'`. */\n label: string;\n /** Connect timeout in ms. Default `3000`. */\n connectTimeout?: number;\n /** Per-request retry cap. Default `1`. */\n maxRetriesPerRequest?: number;\n}\n\n/** Lazy-import ioredis and construct a client. Returns null when:\n * - no URL is configured (caller falls back to in-memory)\n * - `ioredis` isn't installed (optional peer; caller falls back to in-memory)\n * - the import throws for any other reason\n *\n * `rediss://` URLs auto-enable TLS. The error handler logs with the caller's\n * label so multi-cache deployments can tell which subsystem complained. */\nasync function tryCreateRedis<T extends MinimalRedis>(opts: CreateRedisOptions): Promise<T | null> {\n const url = opts.url ?? process.env.REDIS_URL;\n if (!url) return null;\n try {\n const mod = (await import('ioredis')) as unknown as { default: new (url: string, opts?: unknown) => T };\n const client = new mod.default(url, {\n connectTimeout: opts.connectTimeout ?? 3000,\n maxRetriesPerRequest: opts.maxRetriesPerRequest ?? 1,\n tls: url.startsWith('rediss://') ? {} : undefined,\n });\n client.on('error', (err) => console.error(`[${opts.label}] Redis error:`, err.message));\n return client;\n } catch {\n return null;\n }\n}\n\n/** Memoized-promise variant: call once per caller; subsequent calls return the\n * same promise. Pairs with the pattern `let p: Promise<T|null> | null = null;\n * const getRedis = () => (p ??= tryCreateRedis(...))` in callers that want\n * per-call promise caching without managing the closure themselves. */\nexport function memoizedRedis<T extends MinimalRedis>(opts: CreateRedisOptions): () => Promise<T | null> {\n let promise: Promise<T | null> | null = null;\n return () => {\n if (!promise) promise = tryCreateRedis<T>(opts);\n return promise;\n };\n}\n","import { memoizedRedis, type MinimalRedis } from '../_redis';\n\nexport interface RateLimitCoreOptions {\n windowSeconds?: number;\n maxRequests?: number;\n /** Redis connection URL. Default: `process.env.REDIS_URL`. Falls back to in-memory when unset or the lazy `ioredis` import fails. */\n redisUrl?: string;\n /** Per-instance key prefix so multiple limiters sharing a Redis don't collide. */\n keyPrefix?: string;\n}\n\ninterface RateLimitDecision {\n allowed: boolean;\n remaining: number;\n limit: number;\n}\n\nexport interface RateLimiter {\n check(key: string): Promise<RateLimitDecision>;\n}\n\ninterface RedisLike extends MinimalRedis {\n incr(key: string): Promise<number>;\n expire(key: string, seconds: number): Promise<unknown>;\n}\n\n/** Framework-agnostic rate limiter. Hono / Express / Fastify / Next.js / Web adapters\n * share one core. Each `createRateLimiter` call owns its own memory map + redis\n * connection, so multiple instances in the same process don't share state unless\n * they share a Redis with the same `keyPrefix`. */\nexport function createRateLimiter(opts: RateLimitCoreOptions = {}): RateLimiter {\n const windowSeconds = opts.windowSeconds ?? 60;\n const maxRequests = opts.maxRequests ?? 60;\n const keyPrefix = opts.keyPrefix ?? 'rl:';\n\n const memMap = new Map<string, { count: number; resetAt: number }>();\n const getRedis = memoizedRedis<RedisLike>({ url: opts.redisUrl, label: 'rate-limit' });\n\n const checkMem = (key: string): RateLimitDecision => {\n const now = Date.now();\n const entry = memMap.get(key);\n if (!entry || entry.resetAt < now) {\n memMap.set(key, { count: 1, resetAt: now + windowSeconds * 1000 });\n return { allowed: true, remaining: maxRequests - 1, limit: maxRequests };\n }\n entry.count++;\n const remaining = Math.max(0, maxRequests - entry.count);\n return { allowed: entry.count <= maxRequests, remaining, limit: maxRequests };\n };\n\n return {\n async check(key: string): Promise<RateLimitDecision> {\n const r = await getRedis();\n if (!r) return checkMem(key);\n try {\n const fullKey = `${keyPrefix}${key}`;\n const count = await r.incr(fullKey);\n if (count === 1) await r.expire(fullKey, windowSeconds);\n const remaining = Math.max(0, maxRequests - count);\n return { allowed: count <= maxRequests, remaining, limit: maxRequests };\n } catch {\n return checkMem(key);\n }\n },\n };\n}\n\nexport const RATE_LIMIT_JSON_BODY = {\n error: { code: 'rate_limited', message: 'Too many requests' },\n} as const;\n\n/** Default key resolver: first hop of `x-forwarded-for`, else `'unknown'`. Works on any\n * framework's request once you adapt the header read. */\nexport function defaultKeyFromForwardedFor(forwardedFor: string | null | undefined): string {\n if (!forwardedFor) return 'unknown';\n return forwardedFor.split(',')[0]?.trim() || 'unknown';\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACoCA,eAAe,eAAuC,MAA6C;AACjG,QAAM,MAAM,KAAK,OAAO,QAAQ,IAAI;AACpC,MAAI,CAAC,IAAK,QAAO;AACjB,MAAI;AACF,UAAM,MAAO,MAAM,OAAO,SAAS;AACnC,UAAM,SAAS,IAAI,IAAI,QAAQ,KAAK;AAAA,MAClC,gBAAgB,KAAK,kBAAkB;AAAA,MACvC,sBAAsB,KAAK,wBAAwB;AAAA,MACnD,KAAK,IAAI,WAAW,WAAW,IAAI,CAAC,IAAI;AAAA,IAC1C,CAAC;AACD,WAAO,GAAG,SAAS,CAAC,QAAQ,QAAQ,MAAM,IAAI,KAAK,KAAK,kBAAkB,IAAI,OAAO,CAAC;AACtF,WAAO;AAAA,EACT,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AAMO,SAAS,cAAsC,MAAmD;AACvG,MAAI,UAAoC;AACxC,SAAO,MAAM;AACX,QAAI,CAAC,QAAS,WAAU,eAAkB,IAAI;AAC9C,WAAO;AAAA,EACT;AACF;;;ACjCO,SAAS,kBAAkB,OAA6B,CAAC,GAAgB;AAC9E,QAAM,gBAAgB,KAAK,iBAAiB;AAC5C,QAAM,cAAc,KAAK,eAAe;AACxC,QAAM,YAAY,KAAK,aAAa;AAEpC,QAAM,SAAS,oBAAI,IAAgD;AACnE,QAAM,WAAW,cAAyB,EAAE,KAAK,KAAK,UAAU,OAAO,aAAa,CAAC;AAErF,QAAM,WAAW,CAAC,QAAmC;AACnD,UAAM,MAAM,KAAK,IAAI;AACrB,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C,IAAI;AAC/D,QAAI,aAAc,QAAO,2BAA2B,YAAY;AAChE,WAAO,IAAI,MAAM;AAAA,EACnB;AAEF,SAAO,OAAO,KAAqB,UAAwB;AACzD,UAAM,EAAE,SAAS,WAAW,MAAM,IAAI,MAAM,QAAQ,MAAM,YAAY,GAAG,CAAC;AAC1E,UAAM,OAAO,qBAAqB,OAAO,KAAK,CAAC;AAC/C,UAAM,OAAO,yBAAyB,OAAO,SAAS,CAAC;AACvD,QAAI,CAAC,SAAS;AACZ,YAAM,OAAO,iBAAiB,UAAU;AACxC,YAAM,KAAK,GAAG,EAAE,KAAK,oBAAoB;AAAA,IAC3C;AAAA,EACF;AACF;","names":[]}
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/_redis.ts","../../src/middleware/_core.ts","../../src/middleware/fastify.ts"],"sourcesContent":["/** Shared lazy `ioredis` factory. Used by `quote_cache`, `middleware/_core`,\n * and `stripe-multichain/pi-cache` so they don't drift on connect-timeout,\n * TLS handling, or error-logging posture.\n *\n * `ioredis` is an optional peer dep — callers pass `redisUrl` (or rely on\n * `process.env.REDIS_URL`); when unset or the lazy import fails, this returns\n * null and the caller falls back to its in-process `Map`.\n *\n * Not part of the public API.\n */\n\n/** Minimal Redis surface — each caller intersects with its own usage\n * (incr/expire for rate-limit, get/set/del for caches). Returning `unknown`\n * on commands keeps the shape narrow; cast at the call site. */\nexport interface MinimalRedis {\n on(event: 'error', handler: (err: Error) => void): unknown;\n}\n\nexport interface CreateRedisOptions {\n /** Override `process.env.REDIS_URL` for tests. */\n url?: string;\n /** Logging label, e.g. `'quote-cache'` / `'rate-limit'` / `'pi-cache'`. */\n label: string;\n /** Connect timeout in ms. Default `3000`. */\n connectTimeout?: number;\n /** Per-request retry cap. Default `1`. */\n maxRetriesPerRequest?: number;\n}\n\n/** Lazy-import ioredis and construct a client. Returns null when:\n * - no URL is configured (caller falls back to in-memory)\n * - `ioredis` isn't installed (optional peer; caller falls back to in-memory)\n * - the import throws for any other reason\n *\n * `rediss://` URLs auto-enable TLS. The error handler logs with the caller's\n * label so multi-cache deployments can tell which subsystem complained. */\nasync function tryCreateRedis<T extends MinimalRedis>(opts: CreateRedisOptions): Promise<T | null> {\n const url = opts.url ?? process.env.REDIS_URL;\n if (!url) return null;\n try {\n const mod = (await import('ioredis')) as unknown as { default: new (url: string, opts?: unknown) => T };\n const client = new mod.default(url, {\n connectTimeout: opts.connectTimeout ?? 3000,\n maxRetriesPerRequest: opts.maxRetriesPerRequest ?? 1,\n tls: url.startsWith('rediss://') ? {} : undefined,\n });\n client.on('error', (err) => console.error(`[${opts.label}] Redis error:`, err.message));\n return client;\n } catch {\n return null;\n }\n}\n\n/** Memoized-promise variant: call once per caller; subsequent calls return the\n * same promise. Pairs with the pattern `let p: Promise<T|null> | null = null;\n * const getRedis = () => (p ??= tryCreateRedis(...))` in callers that want\n * per-call promise caching without managing the closure themselves. */\nexport function memoizedRedis<T extends MinimalRedis>(opts: CreateRedisOptions): () => Promise<T | null> {\n let promise: Promise<T | null> | null = null;\n return () => {\n if (!promise) promise = tryCreateRedis<T>(opts);\n return promise;\n };\n}\n","import { memoizedRedis, type MinimalRedis } from '../_redis';\n\nexport interface RateLimitCoreOptions {\n windowSeconds?: number;\n maxRequests?: number;\n /** Redis connection URL. Default: `process.env.REDIS_URL`. Falls back to in-memory when unset or the lazy `ioredis` import fails. */\n redisUrl?: string;\n /** Per-instance key prefix so multiple limiters sharing a Redis don't collide. */\n keyPrefix?: string;\n}\n\nexport interface RateLimitDecision {\n allowed: boolean;\n remaining: number;\n limit: number;\n}\n\nexport interface RateLimiter {\n check(key: string): Promise<RateLimitDecision>;\n}\n\ninterface RedisLike extends MinimalRedis {\n incr(key: string): Promise<number>;\n expire(key: string, seconds: number): Promise<unknown>;\n}\n\n/** Framework-agnostic rate limiter. Hono / Express / Fastify / Next.js / Web adapters\n * share one core. Each `createRateLimiter` call owns its own memory map + redis\n * connection, so multiple instances in the same process don't share state unless\n * they share a Redis with the same `keyPrefix`. */\nexport function createRateLimiter(opts: RateLimitCoreOptions = {}): RateLimiter {\n const windowSeconds = opts.windowSeconds ?? 60;\n const maxRequests = opts.maxRequests ?? 60;\n const keyPrefix = opts.keyPrefix ?? 'rl:';\n\n const memMap = new Map<string, { count: number; resetAt: number }>();\n const getRedis = memoizedRedis<RedisLike>({ url: opts.redisUrl, label: 'rate-limit' });\n\n const checkMem = (key: string): RateLimitDecision => {\n const now = Date.now();\n const entry = memMap.get(key);\n if (!entry || entry.resetAt < now) {\n memMap.set(key, { count: 1, resetAt: now + windowSeconds * 1000 });\n return { allowed: true, remaining: maxRequests - 1, limit: maxRequests };\n }\n entry.count++;\n const remaining = Math.max(0, maxRequests - entry.count);\n return { allowed: entry.count <= maxRequests, remaining, limit: maxRequests };\n };\n\n return {\n async check(key: string): Promise<RateLimitDecision> {\n const r = await getRedis();\n if (!r) return checkMem(key);\n try {\n const fullKey = `${keyPrefix}${key}`;\n const count = await r.incr(fullKey);\n if (count === 1) await r.expire(fullKey, windowSeconds);\n const remaining = Math.max(0, maxRequests - count);\n return { allowed: count <= maxRequests, remaining, limit: maxRequests };\n } catch {\n return checkMem(key);\n }\n },\n };\n}\n\nexport const RATE_LIMIT_JSON_BODY = {\n error: { code: 'rate_limited', message: 'Too many requests' },\n} as const;\n\n/** Default key resolver: first hop of `x-forwarded-for`, else `'unknown'`. Works on any\n * framework's request once you adapt the header read. */\nexport function defaultKeyFromForwardedFor(forwardedFor: string | null | undefined): string {\n if (!forwardedFor) return 'unknown';\n return forwardedFor.split(',')[0]?.trim() || 'unknown';\n}\n","import {\n RATE_LIMIT_JSON_BODY,\n createRateLimiter,\n defaultKeyFromForwardedFor,\n type RateLimitCoreOptions,\n} from './_core';\nimport type { FastifyReply, FastifyRequest, preHandlerHookHandler } from 'fastify';\n\nexport interface RateLimitFastifyOptions extends RateLimitCoreOptions {\n /** Bucket key resolver. Default: first hop of `x-forwarded-for`, else `req.ip`, else `'unknown'`. */\n keyResolver?: (req: FastifyRequest) => string;\n}\n\nexport function rateLimitFastify(opts: RateLimitFastifyOptions = {}): preHandlerHookHandler {\n const limiter = createRateLimiter(opts);\n const keyResolver =\n opts.keyResolver ??\n ((req: FastifyRequest): string => {\n const forwarded = req.headers['x-forwarded-for'];\n const forwardedStr = Array.isArray(forwarded) ? forwarded[0] : forwarded;\n if (forwardedStr) return defaultKeyFromForwardedFor(forwardedStr);\n return req.ip ?? 'unknown';\n });\n\n return async (req: FastifyRequest, reply: FastifyReply) => {\n const { allowed, remaining, limit } = await limiter.check(keyResolver(req));\n reply.header('X-RateLimit-Limit', String(limit));\n reply.header('X-RateLimit-Remaining', String(remaining));\n if (!allowed) {\n reply.header('Cache-Control', 'no-store');\n reply.code(429).send(RATE_LIMIT_JSON_BODY);\n }\n };\n}\n"],"mappings":";AAoCA,eAAe,eAAuC,MAA6C;AACjG,QAAM,MAAM,KAAK,OAAO,QAAQ,IAAI;AACpC,MAAI,CAAC,IAAK,QAAO;AACjB,MAAI;AACF,UAAM,MAAO,MAAM,OAAO,SAAS;AACnC,UAAM,SAAS,IAAI,IAAI,QAAQ,KAAK;AAAA,MAClC,gBAAgB,KAAK,kBAAkB;AAAA,MACvC,sBAAsB,KAAK,wBAAwB;AAAA,MACnD,KAAK,IAAI,WAAW,WAAW,IAAI,CAAC,IAAI;AAAA,IAC1C,CAAC;AACD,WAAO,GAAG,SAAS,CAAC,QAAQ,QAAQ,MAAM,IAAI,KAAK,KAAK,kBAAkB,IAAI,OAAO,CAAC;AACtF,WAAO;AAAA,EACT,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AAMO,SAAS,cAAsC,MAAmD;AACvG,MAAI,UAAoC;AACxC,SAAO,MAAM;AACX,QAAI,CAAC,QAAS,WAAU,eAAkB,IAAI;AAC9C,WAAO;AAAA,EACT;AACF;;;ACjCO,SAAS,kBAAkB,OAA6B,CAAC,GAAgB;AAC9E,QAAM,gBAAgB,KAAK,iBAAiB;AAC5C,QAAM,cAAc,KAAK,eAAe;AACxC,QAAM,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,CAAC,GAA0B;AAC1F,QAAM,UAAU,kBAAkB,IAAI;AACtC,QAAM,cACJ,KAAK,gBACJ,CAAC,QAAgC;AAChC,UAAM,YAAY,IAAI,QAAQ,iBAAiB;AAC/C,UAAM,eAAe,MAAM,QAAQ,SAAS,IAAI,UAAU,CAAC,IAAI;AAC/D,QAAI,aAAc,QAAO,2BAA2B,YAAY;AAChE,WAAO,IAAI,MAAM;AAAA,EACnB;AAEF,SAAO,OAAO,KAAqB,UAAwB;AACzD,UAAM,EAAE,SAAS,WAAW,MAAM,IAAI,MAAM,QAAQ,MAAM,YAAY,GAAG,CAAC;AAC1E,UAAM,OAAO,qBAAqB,OAAO,KAAK,CAAC;AAC/C,UAAM,OAAO,yBAAyB,OAAO,SAAS,CAAC;AACvD,QAAI,CAAC,SAAS;AACZ,YAAM,OAAO,iBAAiB,UAAU;AACxC,YAAM,KAAK,GAAG,EAAE,KAAK,oBAAoB;AAAA,IAC3C;AAAA,EACF;AACF;","names":[]}
1
+ {"version":3,"sources":["../../src/_redis.ts","../../src/middleware/_core.ts","../../src/middleware/fastify.ts"],"sourcesContent":["/** Shared lazy `ioredis` factory. Used by `quote_cache`, `middleware/_core`,\n * and `stripe-multichain/pi-cache` so they don't drift on connect-timeout,\n * TLS handling, or error-logging posture.\n *\n * `ioredis` is an optional peer dep — callers pass `redisUrl` (or rely on\n * `process.env.REDIS_URL`); when unset or the lazy import fails, this returns\n * null and the caller falls back to its in-process `Map`.\n *\n * Not part of the public API.\n */\n\n/** Minimal Redis surface — each caller intersects with its own usage\n * (incr/expire for rate-limit, get/set/del for caches). Returning `unknown`\n * on commands keeps the shape narrow; cast at the call site. */\nexport interface MinimalRedis {\n on(event: 'error', handler: (err: Error) => void): unknown;\n}\n\nexport interface CreateRedisOptions {\n /** Override `process.env.REDIS_URL` for tests. */\n url?: string;\n /** Logging label, e.g. `'quote-cache'` / `'rate-limit'` / `'pi-cache'`. */\n label: string;\n /** Connect timeout in ms. Default `3000`. */\n connectTimeout?: number;\n /** Per-request retry cap. Default `1`. */\n maxRetriesPerRequest?: number;\n}\n\n/** Lazy-import ioredis and construct a client. Returns null when:\n * - no URL is configured (caller falls back to in-memory)\n * - `ioredis` isn't installed (optional peer; caller falls back to in-memory)\n * - the import throws for any other reason\n *\n * `rediss://` URLs auto-enable TLS. The error handler logs with the caller's\n * label so multi-cache deployments can tell which subsystem complained. */\nasync function tryCreateRedis<T extends MinimalRedis>(opts: CreateRedisOptions): Promise<T | null> {\n const url = opts.url ?? process.env.REDIS_URL;\n if (!url) return null;\n try {\n const mod = (await import('ioredis')) as unknown as { default: new (url: string, opts?: unknown) => T };\n const client = new mod.default(url, {\n connectTimeout: opts.connectTimeout ?? 3000,\n maxRetriesPerRequest: opts.maxRetriesPerRequest ?? 1,\n tls: url.startsWith('rediss://') ? {} : undefined,\n });\n client.on('error', (err) => console.error(`[${opts.label}] Redis error:`, err.message));\n return client;\n } catch {\n return null;\n }\n}\n\n/** Memoized-promise variant: call once per caller; subsequent calls return the\n * same promise. Pairs with the pattern `let p: Promise<T|null> | null = null;\n * const getRedis = () => (p ??= tryCreateRedis(...))` in callers that want\n * per-call promise caching without managing the closure themselves. */\nexport function memoizedRedis<T extends MinimalRedis>(opts: CreateRedisOptions): () => Promise<T | null> {\n let promise: Promise<T | null> | null = null;\n return () => {\n if (!promise) promise = tryCreateRedis<T>(opts);\n return promise;\n };\n}\n","import { memoizedRedis, type MinimalRedis } from '../_redis';\n\nexport interface RateLimitCoreOptions {\n windowSeconds?: number;\n maxRequests?: number;\n /** Redis connection URL. Default: `process.env.REDIS_URL`. Falls back to in-memory when unset or the lazy `ioredis` import fails. */\n redisUrl?: string;\n /** Per-instance key prefix so multiple limiters sharing a Redis don't collide. */\n keyPrefix?: string;\n}\n\ninterface RateLimitDecision {\n allowed: boolean;\n remaining: number;\n limit: number;\n}\n\nexport interface RateLimiter {\n check(key: string): Promise<RateLimitDecision>;\n}\n\ninterface RedisLike extends MinimalRedis {\n incr(key: string): Promise<number>;\n expire(key: string, seconds: number): Promise<unknown>;\n}\n\n/** Framework-agnostic rate limiter. Hono / Express / Fastify / Next.js / Web adapters\n * share one core. Each `createRateLimiter` call owns its own memory map + redis\n * connection, so multiple instances in the same process don't share state unless\n * they share a Redis with the same `keyPrefix`. */\nexport function createRateLimiter(opts: RateLimitCoreOptions = {}): RateLimiter {\n const windowSeconds = opts.windowSeconds ?? 60;\n const maxRequests = opts.maxRequests ?? 60;\n const keyPrefix = opts.keyPrefix ?? 'rl:';\n\n const memMap = new Map<string, { count: number; resetAt: number }>();\n const getRedis = memoizedRedis<RedisLike>({ url: opts.redisUrl, label: 'rate-limit' });\n\n const checkMem = (key: string): RateLimitDecision => {\n const now = Date.now();\n const entry = memMap.get(key);\n if (!entry || entry.resetAt < now) {\n memMap.set(key, { count: 1, resetAt: now + windowSeconds * 1000 });\n return { allowed: true, remaining: maxRequests - 1, limit: maxRequests };\n }\n entry.count++;\n const remaining = Math.max(0, maxRequests - entry.count);\n return { allowed: entry.count <= maxRequests, remaining, limit: maxRequests };\n };\n\n return {\n async check(key: string): Promise<RateLimitDecision> {\n const r = await getRedis();\n if (!r) return checkMem(key);\n try {\n const fullKey = `${keyPrefix}${key}`;\n const count = await r.incr(fullKey);\n if (count === 1) await r.expire(fullKey, windowSeconds);\n const remaining = Math.max(0, maxRequests - count);\n return { allowed: count <= maxRequests, remaining, limit: maxRequests };\n } catch {\n return checkMem(key);\n }\n },\n };\n}\n\nexport const RATE_LIMIT_JSON_BODY = {\n error: { code: 'rate_limited', message: 'Too many requests' },\n} as const;\n\n/** Default key resolver: first hop of `x-forwarded-for`, else `'unknown'`. Works on any\n * framework's request once you adapt the header read. */\nexport function defaultKeyFromForwardedFor(forwardedFor: string | null | undefined): string {\n if (!forwardedFor) return 'unknown';\n return forwardedFor.split(',')[0]?.trim() || 'unknown';\n}\n","import {\n RATE_LIMIT_JSON_BODY,\n createRateLimiter,\n defaultKeyFromForwardedFor,\n type RateLimitCoreOptions,\n} from './_core';\nimport type { FastifyReply, FastifyRequest, preHandlerHookHandler } from 'fastify';\n\nexport interface RateLimitFastifyOptions extends RateLimitCoreOptions {\n /** Bucket key resolver. Default: first hop of `x-forwarded-for`, else `req.ip`, else `'unknown'`. */\n keyResolver?: (req: FastifyRequest) => string;\n}\n\nexport function rateLimitFastify(opts: RateLimitFastifyOptions = {}): preHandlerHookHandler {\n const limiter = createRateLimiter(opts);\n const keyResolver =\n opts.keyResolver ??\n ((req: FastifyRequest): string => {\n const forwarded = req.headers['x-forwarded-for'];\n const forwardedStr = Array.isArray(forwarded) ? forwarded[0] : forwarded;\n if (forwardedStr) return defaultKeyFromForwardedFor(forwardedStr);\n return req.ip ?? 'unknown';\n });\n\n return async (req: FastifyRequest, reply: FastifyReply) => {\n const { allowed, remaining, limit } = await limiter.check(keyResolver(req));\n reply.header('X-RateLimit-Limit', String(limit));\n reply.header('X-RateLimit-Remaining', String(remaining));\n if (!allowed) {\n reply.header('Cache-Control', 'no-store');\n reply.code(429).send(RATE_LIMIT_JSON_BODY);\n }\n };\n}\n"],"mappings":";AAoCA,eAAe,eAAuC,MAA6C;AACjG,QAAM,MAAM,KAAK,OAAO,QAAQ,IAAI;AACpC,MAAI,CAAC,IAAK,QAAO;AACjB,MAAI;AACF,UAAM,MAAO,MAAM,OAAO,SAAS;AACnC,UAAM,SAAS,IAAI,IAAI,QAAQ,KAAK;AAAA,MAClC,gBAAgB,KAAK,kBAAkB;AAAA,MACvC,sBAAsB,KAAK,wBAAwB;AAAA,MACnD,KAAK,IAAI,WAAW,WAAW,IAAI,CAAC,IAAI;AAAA,IAC1C,CAAC;AACD,WAAO,GAAG,SAAS,CAAC,QAAQ,QAAQ,MAAM,IAAI,KAAK,KAAK,kBAAkB,IAAI,OAAO,CAAC;AACtF,WAAO;AAAA,EACT,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AAMO,SAAS,cAAsC,MAAmD;AACvG,MAAI,UAAoC;AACxC,SAAO,MAAM;AACX,QAAI,CAAC,QAAS,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BAAoB;AAC9D;AAIO,SAAS,2BAA2B,cAAiD;AAC1F,MAAI,CAAC,aAAc,QAAO;AAC1B,SAAO,aAAa,MAAM,GAAG,EAAE,CAAC,GAAG,KAAK,KAAK;AAC/C;;;AC/DO,SAAS,iBAAiB,OAAgC,CAAC,GAA0B;AAC1F,QAAM,UAAU,kBAAkB,IAAI;AACtC,QAAM,cACJ,KAAK,gBACJ,CAAC,QAAgC;AAChC,UAAM,YAAY,IAAI,QAAQ,iBAAiB;AAC/C,UAAM,eAAe,MAAM,QAAQ,SAAS,IAAI,UAAU,CAAC,IAAI;AAC/D,QAAI,aAAc,QAAO,2BAA2B,YAAY;AAChE,WAAO,IAAI,MAAM;AAAA,EACnB;AAEF,SAAO,OAAO,KAAqB,UAAwB;AACzD,UAAM,EAAE,SAAS,WAAW,MAAM,IAAI,MAAM,QAAQ,MAAM,YAAY,GAAG,CAAC;AAC1E,UAAM,OAAO,qBAAqB,OAAO,KAAK,CAAC;AAC/C,UAAM,OAAO,yBAAyB,OAAO,SAAS,CAAC;AACvD,QAAI,CAAC,SAAS;AACZ,YAAM,OAAO,iBAAiB,UAAU;AACxC,YAAM,KAAK,GAAG,EAAE,KAAK,oBAAoB;AAAA,IAC3C;AAAA,EACF;AACF;","names":[]}
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/middleware/hono.ts","../../src/_redis.ts","../../src/middleware/_core.ts"],"sourcesContent":["import {\n RATE_LIMIT_JSON_BODY,\n createRateLimiter,\n defaultKeyFromForwardedFor,\n type RateLimitCoreOptions,\n} from './_core';\nimport type { Context, MiddlewareHandler, Next } from 'hono';\n\nexport interface RateLimitHonoOptions extends RateLimitCoreOptions {\n /** Bucket key resolver. Default: first hop of `x-forwarded-for`, else `'unknown'`. */\n keyResolver?: (c: Context) => string;\n}\n\nexport function rateLimitHono(opts: RateLimitHonoOptions = {}): MiddlewareHandler {\n const limiter = createRateLimiter(opts);\n const keyResolver = opts.keyResolver ?? ((c: Context) => defaultKeyFromForwardedFor(c.req.header('x-forwarded-for')));\n\n return async (c: Context, next: Next) => {\n const { allowed, remaining, limit } = await limiter.check(keyResolver(c));\n c.header('X-RateLimit-Limit', String(limit));\n c.header('X-RateLimit-Remaining', String(remaining));\n if (!allowed) {\n return c.json(RATE_LIMIT_JSON_BODY, 429, { 'Cache-Control': 'no-store' });\n }\n await next();\n };\n}\n","/** Shared lazy `ioredis` factory. Used by `quote_cache`, `middleware/_core`,\n * and `stripe-multichain/pi-cache` so they don't drift on connect-timeout,\n * TLS handling, or error-logging posture.\n *\n * `ioredis` is an optional peer dep — callers pass `redisUrl` (or rely on\n * `process.env.REDIS_URL`); when unset or the lazy import fails, this returns\n * null and the caller falls back to its in-process `Map`.\n *\n * Not part of the public API.\n */\n\n/** Minimal Redis surface — each caller intersects with its own usage\n * (incr/expire for rate-limit, get/set/del for caches). Returning `unknown`\n * on commands keeps the shape narrow; cast at the call site. */\nexport interface MinimalRedis {\n on(event: 'error', handler: (err: Error) => void): unknown;\n}\n\nexport interface CreateRedisOptions {\n /** Override `process.env.REDIS_URL` for tests. */\n url?: string;\n /** Logging label, e.g. `'quote-cache'` / `'rate-limit'` / `'pi-cache'`. */\n label: string;\n /** Connect timeout in ms. Default `3000`. */\n connectTimeout?: number;\n /** Per-request retry cap. Default `1`. */\n maxRetriesPerRequest?: number;\n}\n\n/** Lazy-import ioredis and construct a client. Returns null when:\n * - no URL is configured (caller falls back to in-memory)\n * - `ioredis` isn't installed (optional peer; caller falls back to in-memory)\n * - the import throws for any other reason\n *\n * `rediss://` URLs auto-enable TLS. The error handler logs with the caller's\n * label so multi-cache deployments can tell which subsystem complained. */\nasync function tryCreateRedis<T extends MinimalRedis>(opts: CreateRedisOptions): Promise<T | null> {\n const url = opts.url ?? process.env.REDIS_URL;\n if (!url) return null;\n try {\n const mod = (await import('ioredis')) as unknown as { default: new (url: string, opts?: unknown) => T };\n const client = new mod.default(url, {\n connectTimeout: opts.connectTimeout ?? 3000,\n maxRetriesPerRequest: opts.maxRetriesPerRequest ?? 1,\n tls: url.startsWith('rediss://') ? {} : undefined,\n });\n client.on('error', (err) => console.error(`[${opts.label}] Redis error:`, err.message));\n return client;\n } catch {\n return null;\n }\n}\n\n/** Memoized-promise variant: call once per caller; subsequent calls return the\n * same promise. Pairs with the pattern `let p: Promise<T|null> | null = null;\n * const getRedis = () => (p ??= tryCreateRedis(...))` in callers that want\n * per-call promise caching without managing the closure themselves. */\nexport function memoizedRedis<T extends MinimalRedis>(opts: CreateRedisOptions): () => Promise<T | null> {\n let promise: Promise<T | null> | null = null;\n return () => {\n if (!promise) promise = tryCreateRedis<T>(opts);\n return promise;\n };\n}\n","import { memoizedRedis, type MinimalRedis } from '../_redis';\n\nexport interface RateLimitCoreOptions {\n windowSeconds?: number;\n maxRequests?: number;\n /** Redis connection URL. Default: `process.env.REDIS_URL`. Falls back to in-memory when unset or the lazy `ioredis` import fails. */\n redisUrl?: string;\n /** Per-instance key prefix so multiple limiters sharing a Redis don't collide. */\n keyPrefix?: string;\n}\n\nexport interface RateLimitDecision {\n allowed: boolean;\n remaining: number;\n limit: number;\n}\n\nexport interface RateLimiter {\n check(key: string): Promise<RateLimitDecision>;\n}\n\ninterface RedisLike extends MinimalRedis {\n incr(key: string): Promise<number>;\n expire(key: string, seconds: number): Promise<unknown>;\n}\n\n/** Framework-agnostic rate limiter. Hono / Express / Fastify / Next.js / Web adapters\n * share one core. Each `createRateLimiter` call owns its own memory map + redis\n * connection, so multiple instances in the same process don't share state unless\n * they share a Redis with the same `keyPrefix`. */\nexport function createRateLimiter(opts: RateLimitCoreOptions = {}): RateLimiter {\n const windowSeconds = opts.windowSeconds ?? 60;\n const maxRequests = opts.maxRequests ?? 60;\n const keyPrefix = opts.keyPrefix ?? 'rl:';\n\n const memMap = new Map<string, { count: number; resetAt: number }>();\n const getRedis = memoizedRedis<RedisLike>({ url: opts.redisUrl, label: 'rate-limit' });\n\n const checkMem = (key: string): RateLimitDecision => {\n const now = Date.now();\n const entry = memMap.get(key);\n if (!entry || entry.resetAt < now) {\n memMap.set(key, { count: 1, resetAt: now + windowSeconds * 1000 });\n return { allowed: true, remaining: maxRequests - 1, limit: maxRequests };\n }\n entry.count++;\n const remaining = Math.max(0, maxRequests - entry.count);\n return { allowed: entry.count <= maxRequests, remaining, limit: maxRequests };\n };\n\n return {\n async check(key: string): Promise<RateLimitDecision> {\n const r = await getRedis();\n if (!r) return checkMem(key);\n try {\n const fullKey = `${keyPrefix}${key}`;\n const count = await r.incr(fullKey);\n if (count === 1) await r.expire(fullKey, windowSeconds);\n const remaining = Math.max(0, maxRequests - count);\n return { allowed: count <= maxRequests, remaining, limit: maxRequests };\n } catch {\n return checkMem(key);\n }\n },\n };\n}\n\nexport const RATE_LIMIT_JSON_BODY = {\n error: { code: 'rate_limited', message: 'Too many requests' },\n} as const;\n\n/** Default key resolver: first hop of `x-forwarded-for`, else `'unknown'`. Works on any\n * framework's request once you adapt the header read. */\nexport function defaultKeyFromForwardedFor(forwardedFor: string | null | undefined): string {\n if (!forwardedFor) return 'unknown';\n return forwardedFor.split(',')[0]?.trim() || 'unknown';\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACoCA,eAAe,eAAuC,MAA6C;AACjG,QAAM,MAAM,KAAK,OAAO,QAAQ,IAAI;AACpC,MAAI,CAAC,IAAK,QAAO;AACjB,MAAI;AACF,UAAM,MAAO,MAAM,OAAO,SAAS;AACnC,UAAM,SAAS,IAAI,IAAI,QAAQ,KAAK;AAAA,MAClC,gBAAgB,KAAK,kBAAkB;AAAA,MACvC,sBAAsB,KAAK,wBAAwB;AAAA,MACnD,KAAK,IAAI,WAAW,WAAW,IAAI,CAAC,IAAI;AAAA,IAC1C,CAAC;AACD,WAAO,GAAG,SAAS,CAAC,QAAQ,QAAQ,MAAM,IAAI,KAAK,KAAK,kBAAkB,IAAI,OAAO,CAAC;AACtF,WAAO;AAAA,EACT,QAAQ;AACN,WAAO;AAAA,E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B;AAAA,IACF;AAAA,EACF;AACF;AAEO,IAAM,uBAAuB;AAAA,EAClC,OAAO,EAAE,MAAM,gBAAgB,SAAS,oBAAoB;AAC9D;AAIO,SAAS,2BAA2B,cAAiD;AAC1F,MAAI,CAAC,aAAc,QAAO;AAC1B,SAAO,aAAa,MAAM,GAAG,EAAE,CAAC,GAAG,KAAK,KAAK;AAC/C;;;AF/DO,SAAS,cAAc,OAA6B,CAAC,GAAsB;AAChF,QAAM,UAAU,kBAAkB,IAAI;AACtC,QAAM,cAAc,KAAK,gBAAgB,CAAC,MAAe,2BAA2B,EAAE,IAAI,OAAO,iBAAiB,CAAC;AAEnH,SAAO,OAAO,GAAY,SAAe;AACvC,UAAM,EAAE,SAAS,WAAW,MAAM,IAAI,MAAM,QAAQ,MAAM,YAAY,CAAC,CAAC;AACxE,MAAE,OAAO,qBAAqB,OAAO,KAAK,CAAC;AAC3C,MAAE,OAAO,yBAAyB,OAAO,SAAS,CAAC;AACnD,QAAI,CAAC,SAAS;AACZ,aAAO,EAAE,KAAK,sBAAsB,KAAK,EAAE,iBAAiB,WAAW,CAAC;AAAA,IAC1E;AACA,UAAM,KAAK;AAAA,EACb;AACF;","names":[]}
1
+ {"version":3,"sources":["../../src/middleware/hono.ts","../../src/_redis.ts","../../src/middleware/_core.ts"],"sourcesContent":["import {\n RATE_LIMIT_JSON_BODY,\n createRateLimiter,\n defaultKeyFromForwardedFor,\n type RateLimitCoreOptions,\n} from './_core';\nimport type { Context, MiddlewareHandler, Next } from 'hono';\n\nexport interface RateLimitHonoOptions extends RateLimitCoreOptions {\n /** Bucket key resolver. Default: first hop of `x-forwarded-for`, else `'unknown'`. */\n keyResolver?: (c: Context) => string;\n}\n\nexport function rateLimitHono(opts: RateLimitHonoOptions = {}): MiddlewareHandler {\n const limiter = createRateLimiter(opts);\n const keyResolver = opts.keyResolver ?? ((c: Context) => defaultKeyFromForwardedFor(c.req.header('x-forwarded-for')));\n\n return async (c: Context, next: Next) => {\n const { allowed, remaining, limit } = await limiter.check(keyResolver(c));\n c.header('X-RateLimit-Limit', String(limit));\n c.header('X-RateLimit-Remaining', String(remaining));\n if (!allowed) {\n return c.json(RATE_LIMIT_JSON_BODY, 429, { 'Cache-Control': 'no-store' });\n }\n await next();\n };\n}\n","/** Shared lazy `ioredis` factory. Used by `quote_cache`, `middleware/_core`,\n * and `stripe-multichain/pi-cache` so they don't drift on connect-timeout,\n * TLS handling, or error-logging posture.\n *\n * `ioredis` is an optional peer dep — callers pass `redisUrl` (or rely on\n * `process.env.REDIS_URL`); when unset or the lazy import fails, this returns\n * null and the caller falls back to its in-process `Map`.\n *\n * Not part of the public API.\n */\n\n/** Minimal Redis surface — each caller intersects with its own usage\n * (incr/expire for rate-limit, get/set/del for caches). Returning `unknown`\n * on commands keeps the shape narrow; cast at the call site. */\nexport interface MinimalRedis {\n on(event: 'error', handler: (err: Error) => void): unknown;\n}\n\nexport interface CreateRedisOptions {\n /** Override `process.env.REDIS_URL` for tests. */\n url?: string;\n /** Logging label, e.g. `'quote-cache'` / `'rate-limit'` / `'pi-cache'`. */\n label: string;\n /** Connect timeout in ms. Default `3000`. */\n connectTimeout?: number;\n /** Per-request retry cap. Default `1`. */\n maxRetriesPerRequest?: number;\n}\n\n/** Lazy-import ioredis and construct a client. Returns null when:\n * - no URL is configured (caller falls back to in-memory)\n * - `ioredis` isn't installed (optional peer; caller falls back to in-memory)\n * - the import throws for any other reason\n *\n * `rediss://` URLs auto-enable TLS. The error handler logs with the caller's\n * label so multi-cache deployments can tell which subsystem complained. */\nasync function tryCreateRedis<T extends MinimalRedis>(opts: CreateRedisOptions): Promise<T | null> {\n const url = opts.url ?? process.env.REDIS_URL;\n if (!url) return null;\n try {\n const mod = (await import('ioredis')) as unknown as { default: new (url: string, opts?: unknown) => T };\n const client = new mod.default(url, {\n connectTimeout: opts.connectTimeout ?? 3000,\n maxRetriesPerRequest: opts.maxRetriesPerRequest ?? 1,\n tls: url.startsWith('rediss://') ? {} : undefined,\n });\n client.on('error', (err) => console.error(`[${opts.label}] Redis error:`, err.message));\n return client;\n } catch {\n return null;\n }\n}\n\n/** Memoized-promise variant: call once per caller; subsequent calls return the\n * same promise. Pairs with the pattern `let p: Promise<T|null> | null = null;\n * const getRedis = () => (p ??= tryCreateRedis(...))` in callers that want\n * per-call promise caching without managing the closure themselves. */\nexport function memoizedRedis<T extends MinimalRedis>(opts: CreateRedisOptions): () => Promise<T | null> {\n let promise: Promise<T | null> | null = null;\n return () => {\n if (!promise) promise = tryCreateRedis<T>(opts);\n return promise;\n };\n}\n","import { memoizedRedis, type MinimalRedis } from '../_redis';\n\nexport interface RateLimitCoreOptions {\n windowSeconds?: number;\n maxRequests?: number;\n /** Redis connection URL. Default: `process.env.REDIS_URL`. Falls back to in-memory when unset or the lazy `ioredis` import fails. */\n redisUrl?: string;\n /** Per-instance key prefix so multiple limiters sharing a Redis don't collide. */\n keyPrefix?: string;\n}\n\ninterface RateLimitDecision {\n allowed: boolean;\n remaining: number;\n limit: number;\n}\n\nexport interface RateLimiter {\n check(key: string): Promise<RateLimitDecision>;\n}\n\ninterface RedisLike extends MinimalRedis {\n incr(key: string): Promise<number>;\n expire(key: string, seconds: number): Promise<unknown>;\n}\n\n/** Framework-agnostic rate limiter. Hono / Express / Fastify / Next.js / Web adapters\n * share one core. Each `createRateLimiter` call owns its own memory map + redis\n * connection, so multiple instances in the same process don't share state unless\n * they share a Redis with the same `keyPrefix`. */\nexport function createRateLimiter(opts: RateLimitCoreOptions = {}): RateLimiter {\n const windowSeconds = opts.windowSeconds ?? 60;\n const maxRequests = opts.maxRequests ?? 60;\n const keyPrefix = opts.keyPrefix ?? 'rl:';\n\n const memMap = new Map<string, { count: number; resetAt: number }>();\n const getRedis = memoizedRedis<RedisLike>({ url: opts.redisUrl, label: 'rate-limit' });\n\n const checkMem = (key: string): RateLimitDecision => {\n const now = Date.now();\n const entry = memMap.get(key);\n if (!entry || entry.resetAt < now) {\n memMap.set(key, { count: 1, resetAt: now + windowSeconds * 1000 });\n return { allowed: true, remaining: maxRequests - 1, limit: maxRequests };\n }\n entry.count++;\n const remaining = Math.max(0, maxRequests - entry.count);\n return { allowed: entry.count <= maxRequests, remaining, limit: maxRequests };\n };\n\n return {\n async check(key: string): Promise<RateLimitDecision> {\n const r = await getRedis();\n if (!r) return checkMem(key);\n try {\n const fullKey = `${keyPrefix}${key}`;\n const count = await r.incr(fullKey);\n if (count === 1) await r.expire(fullKey, windowSeconds);\n const remaining = Math.max(0, maxRequests - count);\n return { allowed: count <= maxRequests, remaining, limit: maxRequests };\n } catch {\n return checkMem(key);\n }\n },\n };\n}\n\nexport const RATE_LIMIT_JSON_BODY = {\n error: { code: 'rate_limited', message: 'Too many requests' },\n} as const;\n\n/** Default key resolver: first hop of `x-forwarded-for`, else `'unknown'`. Works on any\n * framework's request once you adapt the header read. */\nexport function defaultKeyFromForwardedFor(forwardedFor: string | null | undefined): string {\n if (!forwardedFor) return 'unknown';\n return forwardedFor.split(',')[0]?.trim() || 'unknown';\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACoCA,eAAe,eAAuC,MAA6C;AACjG,QAAM,MAAM,KAAK,OAAO,QAAQ,IAAI;AACpC,MAAI,CAAC,IAAK,QAAO;AACjB,MAAI;AACF,UAAM,MAAO,MAAM,OAAO,SAAS;AACnC,UAAM,SAAS,IAAI,IAAI,QAAQ,KAAK;AAAA,MAClC,gBAAgB,KAAK,kBAAkB;AAAA,MACvC,sBAAsB,KAAK,wBAAwB;AAAA,MACnD,KAAK,IAAI,WAAW,WAAW,IAAI,CAAC,IAAI;AAAA,IAC1C,CAAC;AACD,WAAO,GAAG,SAAS,CAAC,QAAQ,QAAQ,MAAM,IAAI,KAAK,KAAK,kBAAkB,IAAI,OAAO,CAAC;AACtF,WAAO;AAAA,EACT,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AAMO,SAAS,cAAsC,MAAmD;AACvG,MAAI,UAAoC;AACx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ClC,OAAO,EAAE,MAAM,gBAAgB,SAAS,oBAAoB;AAC9D;AAIO,SAAS,2BAA2B,cAAiD;AAC1F,MAAI,CAAC,aAAc,QAAO;AAC1B,SAAO,aAAa,MAAM,GAAG,EAAE,CAAC,GAAG,KAAK,KAAK;AAC/C;;;AF/DO,SAAS,cAAc,OAA6B,CAAC,GAAsB;AAChF,QAAM,UAAU,kBAAkB,IAAI;AACtC,QAAM,cAAc,KAAK,gBAAgB,CAAC,MAAe,2BAA2B,EAAE,IAAI,OAAO,iBAAiB,CAAC;AAEnH,SAAO,OAAO,GAAY,SAAe;AACvC,UAAM,EAAE,SAAS,WAAW,MAAM,IAAI,MAAM,QAAQ,MAAM,YAAY,CAAC,CAAC;AACxE,MAAE,OAAO,qBAAqB,OAAO,KAAK,CAAC;AAC3C,MAAE,OAAO,yBAAyB,OAAO,SAAS,CAAC;AACnD,QAAI,CAAC,SAAS;AACZ,aAAO,EAAE,KAAK,sBAAsB,KAAK,EAAE,iBAAiB,WAAW,CAAC;AAAA,IAC1E;AACA,UAAM,KAAK;AAAA,EACb;AACF;","names":[]}
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/_redis.ts","../../src/middleware/_core.ts","../../src/middleware/hono.ts"],"sourcesContent":["/** Shared lazy `ioredis` factory. Used by `quote_cache`, `middleware/_core`,\n * and `stripe-multichain/pi-cache` so they don't drift on connect-timeout,\n * TLS handling, or error-logging posture.\n *\n * `ioredis` is an optional peer dep — callers pass `redisUrl` (or rely on\n * `process.env.REDIS_URL`); when unset or the lazy import fails, this returns\n * null and the caller falls back to its in-process `Map`.\n *\n * Not part of the public API.\n */\n\n/** Minimal Redis surface — each caller intersects with its own usage\n * (incr/expire for rate-limit, get/set/del for caches). Returning `unknown`\n * on commands keeps the shape narrow; cast at the call site. */\nexport interface MinimalRedis {\n on(event: 'error', handler: (err: Error) => void): unknown;\n}\n\nexport interface CreateRedisOptions {\n /** Override `process.env.REDIS_URL` for tests. */\n url?: string;\n /** Logging label, e.g. `'quote-cache'` / `'rate-limit'` / `'pi-cache'`. */\n label: string;\n /** Connect timeout in ms. Default `3000`. */\n connectTimeout?: number;\n /** Per-request retry cap. Default `1`. */\n maxRetriesPerRequest?: number;\n}\n\n/** Lazy-import ioredis and construct a client. Returns null when:\n * - no URL is configured (caller falls back to in-memory)\n * - `ioredis` isn't installed (optional peer; caller falls back to in-memory)\n * - the import throws for any other reason\n *\n * `rediss://` URLs auto-enable TLS. The error handler logs with the caller's\n * label so multi-cache deployments can tell which subsystem complained. */\nasync function tryCreateRedis<T extends MinimalRedis>(opts: CreateRedisOptions): Promise<T | null> {\n const url = opts.url ?? process.env.REDIS_URL;\n if (!url) return null;\n try {\n const mod = (await import('ioredis')) as unknown as { default: new (url: string, opts?: unknown) => T };\n const client = new mod.default(url, {\n connectTimeout: opts.connectTimeout ?? 3000,\n maxRetriesPerRequest: opts.maxRetriesPerRequest ?? 1,\n tls: url.startsWith('rediss://') ? {} : undefined,\n });\n client.on('error', (err) => console.error(`[${opts.label}] Redis error:`, err.message));\n return client;\n } catch {\n return null;\n }\n}\n\n/** Memoized-promise variant: call once per caller; subsequent calls return the\n * same promise. Pairs with the pattern `let p: Promise<T|null> | null = null;\n * const getRedis = () => (p ??= tryCreateRedis(...))` in callers that want\n * per-call promise caching without managing the closure themselves. */\nexport function memoizedRedis<T extends MinimalRedis>(opts: CreateRedisOptions): () => Promise<T | null> {\n let promise: Promise<T | null> | null = null;\n return () => {\n if (!promise) promise = tryCreateRedis<T>(opts);\n return promise;\n };\n}\n","import { memoizedRedis, type MinimalRedis } from '../_redis';\n\nexport interface RateLimitCoreOptions {\n windowSeconds?: number;\n maxRequests?: number;\n /** Redis connection URL. Default: `process.env.REDIS_URL`. Falls back to in-memory when unset or the lazy `ioredis` import fails. */\n redisUrl?: string;\n /** Per-instance key prefix so multiple limiters sharing a Redis don't collide. */\n keyPrefix?: string;\n}\n\nexport interface RateLimitDecision {\n allowed: boolean;\n remaining: number;\n limit: number;\n}\n\nexport interface RateLimiter {\n check(key: string): Promise<RateLimitDecision>;\n}\n\ninterface RedisLike extends MinimalRedis {\n incr(key: string): Promise<number>;\n expire(key: string, seconds: number): Promise<unknown>;\n}\n\n/** Framework-agnostic rate limiter. Hono / Express / Fastify / Next.js / Web adapters\n * share one core. Each `createRateLimiter` call owns its own memory map + redis\n * connection, so multiple instances in the same process don't share state unless\n * they share a Redis with the same `keyPrefix`. */\nexport function createRateLimiter(opts: RateLimitCoreOptions = {}): RateLimiter {\n const windowSeconds = opts.windowSeconds ?? 60;\n const maxRequests = opts.maxRequests ?? 60;\n const keyPrefix = opts.keyPrefix ?? 'rl:';\n\n const memMap = new Map<string, { count: number; resetAt: number }>();\n const getRedis = memoizedRedis<RedisLike>({ url: opts.redisUrl, label: 'rate-limit' });\n\n const checkMem = (key: string): RateLimitDecision => {\n const now = Date.now();\n const entry = memMap.get(key);\n if (!entry || entry.resetAt < now) {\n memMap.set(key, { count: 1, resetAt: now + windowSeconds * 1000 });\n return { allowed: true, remaining: maxRequests - 1, limit: maxRequests };\n }\n entry.count++;\n const remaining = Math.max(0, maxRequests - entry.count);\n return { allowed: entry.count <= maxRequests, remaining, limit: maxRequests };\n };\n\n return {\n async check(key: string): Promise<RateLimitDecision> {\n const r = await getRedis();\n if (!r) return checkMem(key);\n try {\n const fullKey = `${keyPrefix}${key}`;\n const count = await r.incr(fullKey);\n if (count === 1) await r.expire(fullKey, windowSeconds);\n const remaining = Math.max(0, maxRequests - count);\n return { allowed: count <= maxRequests, remaining, limit: maxRequests };\n } catch {\n return checkMem(key);\n }\n },\n };\n}\n\nexport const RATE_LIMIT_JSON_BODY = {\n error: { code: 'rate_limited', message: 'Too many requests' },\n} as const;\n\n/** Default key resolver: first hop of `x-forwarded-for`, else `'unknown'`. Works on any\n * framework's request once you adapt the header read. */\nexport function defaultKeyFromForwardedFor(forwardedFor: string | null | undefined): string {\n if (!forwardedFor) return 'unknown';\n return forwardedFor.split(',')[0]?.trim() || 'unknown';\n}\n","import {\n RATE_LIMIT_JSON_BODY,\n createRateLimiter,\n defaultKeyFromForwardedFor,\n type RateLimitCoreOptions,\n} from './_core';\nimport type { Context, MiddlewareHandler, Next } from 'hono';\n\nexport interface RateLimitHonoOptions extends RateLimitCoreOptions {\n /** Bucket key resolver. Default: first hop of `x-forwarded-for`, else `'unknown'`. */\n keyResolver?: (c: Context) => string;\n}\n\nexport function rateLimitHono(opts: RateLimitHonoOptions = {}): MiddlewareHandler {\n const limiter = createRateLimiter(opts);\n const keyResolver = opts.keyResolver ?? ((c: Context) => defaultKeyFromForwardedFor(c.req.header('x-forwarded-for')));\n\n return async (c: Context, next: Next) => {\n const { allowed, remaining, limit } = await limiter.check(keyResolver(c));\n c.header('X-RateLimit-Limit', String(limit));\n c.header('X-RateLimit-Remaining', String(remaining));\n if (!allowed) {\n return c.json(RATE_LIMIT_JSON_BODY, 429, { 'Cache-Control': 'no-store' });\n }\n await next();\n };\n}\n"],"mappings":";AAoCA,eAAe,eAAuC,MAA6C;AACjG,QAAM,MAAM,KAAK,OAAO,QAAQ,IAAI;AACpC,MAAI,CAAC,IAAK,QAAO;AACjB,MAAI;AACF,UAAM,MAAO,MAAM,OAAO,SAAS;AACnC,UAAM,SAAS,IAAI,IAAI,QAAQ,KAAK;AAAA,MAClC,gBAAgB,KAAK,kBAAkB;AAAA,MACvC,sBAAsB,KAAK,wBAAwB;AAAA,MACnD,KAAK,IAAI,WAAW,WAAW,IAAI,CAAC,IAAI;AAAA,IAC1C,CAAC;AACD,WAAO,GAAG,SAAS,CAAC,QAAQ,QAAQ,MAAM,IAAI,KAAK,KAAK,kBAAkB,IAAI,OAAO,CAAC;AACtF,WAAO;AAAA,EACT,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AAMO,SAAS,cAAsC,MAAmD;AACvG,MAAI,UAAoC;AACxC,SAAO,MAAM;AACX,QAAI,CAAC,QAAS,WAAU,eAAkB,IAAI;AAC9C,WAAO;AAAA,EACT;AACF;;;ACjCO,SAAS,kBAAkB,O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AAC1B,SAAO,aAAa,MAAM,GAAG,EAAE,CAAC,GAAG,KAAK,KAAK;AAC/C;;;AC/DO,SAAS,cAAc,OAA6B,CAAC,GAAsB;AAChF,QAAM,UAAU,kBAAkB,IAAI;AACtC,QAAM,cAAc,KAAK,gBAAgB,CAAC,MAAe,2BAA2B,EAAE,IAAI,OAAO,iBAAiB,CAAC;AAEnH,SAAO,OAAO,GAAY,SAAe;AACvC,UAAM,EAAE,SAAS,WAAW,MAAM,IAAI,MAAM,QAAQ,MAAM,YAAY,CAAC,CAAC;AACxE,MAAE,OAAO,qBAAqB,OAAO,KAAK,CAAC;AAC3C,MAAE,OAAO,yBAAyB,OAAO,SAAS,CAAC;AACnD,QAAI,CAAC,SAAS;AACZ,aAAO,EAAE,KAAK,sBAAsB,KAAK,EAAE,iBAAiB,WAAW,CAAC;AAAA,IAC1E;AACA,UAAM,KAAK;AAAA,EACb;AACF;","names":[]}
1
+ {"version":3,"sources":["../../src/_redis.ts","../../src/middleware/_core.ts","../../src/middleware/hono.ts"],"sourcesContent":["/** Shared lazy `ioredis` factory. Used by `quote_cache`, `middleware/_core`,\n * and `stripe-multichain/pi-cache` so they don't drift on connect-timeout,\n * TLS handling, or error-logging posture.\n *\n * `ioredis` is an optional peer dep — callers pass `redisUrl` (or rely on\n * `process.env.REDIS_URL`); when unset or the lazy import fails, this returns\n * null and the caller falls back to its in-process `Map`.\n *\n * Not part of the public API.\n */\n\n/** Minimal Redis surface — each caller intersects with its own usage\n * (incr/expire for rate-limit, get/set/del for caches). Returning `unknown`\n * on commands keeps the shape narrow; cast at the call site. */\nexport interface MinimalRedis {\n on(event: 'error', handler: (err: Error) => void): unknown;\n}\n\nexport interface CreateRedisOptions {\n /** Override `process.env.REDIS_URL` for tests. */\n url?: string;\n /** Logging label, e.g. `'quote-cache'` / `'rate-limit'` / `'pi-cache'`. */\n label: string;\n /** Connect timeout in ms. Default `3000`. */\n connectTimeout?: number;\n /** Per-request retry cap. Default `1`. */\n maxRetriesPerRequest?: number;\n}\n\n/** Lazy-import ioredis and construct a client. Returns null when:\n * - no URL is configured (caller falls back to in-memory)\n * - `ioredis` isn't installed (optional peer; caller falls back to in-memory)\n * - the import throws for any other reason\n *\n * `rediss://` URLs auto-enable TLS. The error handler logs with the caller's\n * label so multi-cache deployments can tell which subsystem complained. */\nasync function tryCreateRedis<T extends MinimalRedis>(opts: CreateRedisOptions): Promise<T | null> {\n const url = opts.url ?? process.env.REDIS_URL;\n if (!url) return null;\n try {\n const mod = (await import('ioredis')) as unknown as { default: new (url: string, opts?: unknown) => T };\n const client = new mod.default(url, {\n connectTimeout: opts.connectTimeout ?? 3000,\n maxRetriesPerRequest: opts.maxRetriesPerRequest ?? 1,\n tls: url.startsWith('rediss://') ? {} : undefined,\n });\n client.on('error', (err) => console.error(`[${opts.label}] Redis error:`, err.message));\n return client;\n } catch {\n return null;\n }\n}\n\n/** Memoized-promise variant: call once per caller; subsequent calls return the\n * same promise. Pairs with the pattern `let p: Promise<T|null> | null = null;\n * const getRedis = () => (p ??= tryCreateRedis(...))` in callers that want\n * per-call promise caching without managing the closure themselves. */\nexport function memoizedRedis<T extends MinimalRedis>(opts: CreateRedisOptions): () => Promise<T | null> {\n let promise: Promise<T | null> | null = null;\n return () => {\n if (!promise) promise = tryCreateRedis<T>(opts);\n return promise;\n };\n}\n","import { memoizedRedis, type MinimalRedis } from '../_redis';\n\nexport interface RateLimitCoreOptions {\n windowSeconds?: number;\n maxRequests?: number;\n /** Redis connection URL. Default: `process.env.REDIS_URL`. Falls back to in-memory when unset or the lazy `ioredis` import fails. */\n redisUrl?: string;\n /** Per-instance key prefix so multiple limiters sharing a Redis don't collide. */\n keyPrefix?: string;\n}\n\ninterface RateLimitDecision {\n allowed: boolean;\n remaining: number;\n limit: number;\n}\n\nexport interface RateLimiter {\n check(key: string): Promise<RateLimitDecision>;\n}\n\ninterface RedisLike extends MinimalRedis {\n incr(key: string): Promise<number>;\n expire(key: string, seconds: number): Promise<unknown>;\n}\n\n/** Framework-agnostic rate limiter. Hono / Express / Fastify / Next.js / Web adapters\n * share one core. Each `createRateLimiter` call owns its own memory map + redis\n * connection, so multiple instances in the same process don't share state unless\n * they share a Redis with the same `keyPrefix`. */\nexport function createRateLimiter(opts: RateLimitCoreOptions = {}): RateLimiter {\n const windowSeconds = opts.windowSeconds ?? 60;\n const maxRequests = opts.maxRequests ?? 60;\n const keyPrefix = opts.keyPrefix ?? 'rl:';\n\n const memMap = new Map<string, { count: number; resetAt: number }>();\n const getRedis = memoizedRedis<RedisLike>({ url: opts.redisUrl, label: 'rate-limit' });\n\n const checkMem = (key: string): RateLimitDecision => {\n const now = Date.now();\n const entry = memMap.get(key);\n if (!entry || entry.resetAt < now) {\n memMap.set(key, { count: 1, resetAt: now + windowSeconds * 1000 });\n return { allowed: true, remaining: maxRequests - 1, limit: maxRequests };\n }\n entry.count++;\n const remaining = Math.max(0, maxRequests - entry.count);\n return { allowed: entry.count <= maxRequests, remaining, limit: maxRequests };\n };\n\n return {\n async check(key: string): Promise<RateLimitDecision> {\n const r = await getRedis();\n if (!r) return checkMem(key);\n try {\n const fullKey = `${keyPrefix}${key}`;\n const count = await r.incr(fullKey);\n if (count === 1) await r.expire(fullKey, windowSeconds);\n const remaining = Math.max(0, maxRequests - count);\n return { allowed: count <= maxRequests, remaining, limit: maxRequests };\n } catch {\n return checkMem(key);\n }\n },\n };\n}\n\nexport const RATE_LIMIT_JSON_BODY = {\n error: { code: 'rate_limited', message: 'Too many requests' },\n} as const;\n\n/** Default key resolver: first hop of `x-forwarded-for`, else `'unknown'`. Works on any\n * framework's request once you adapt the header read. */\nexport function defaultKeyFromForwardedFor(forwardedFor: string | null | undefined): string {\n if (!forwardedFor) return 'unknown';\n return forwardedFor.split(',')[0]?.trim() || 'unknown';\n}\n","import {\n RATE_LIMIT_JSON_BODY,\n createRateLimiter,\n defaultKeyFromForwardedFor,\n type RateLimitCoreOptions,\n} from './_core';\nimport type { Context, MiddlewareHandler, Next } from 'hono';\n\nexport interface RateLimitHonoOptions extends RateLimitCoreOptions {\n /** Bucket key resolver. Default: first hop of `x-forwarded-for`, else `'unknown'`. */\n keyResolver?: (c: Context) => string;\n}\n\nexport function rateLimitHono(opts: RateLimitHonoOptions = {}): MiddlewareHandler {\n const limiter = createRateLimiter(opts);\n const keyResolver = opts.keyResolver ?? ((c: Context) => defaultKeyFromForwardedFor(c.req.header('x-forwarded-for')));\n\n return async (c: Context, next: Next) => {\n const { allowed, remaining, limit } = await limiter.check(keyResolver(c));\n c.header('X-RateLimit-Limit', String(limit));\n c.header('X-RateLimit-Remaining', String(remaining));\n if (!allowed) {\n return c.json(RATE_LIMIT_JSON_BODY, 429, { 'Cache-Control': 'no-store' });\n }\n await next();\n };\n}\n"],"mappings":";AAoCA,eAAe,eAAuC,MAA6C;AACjG,QAAM,MAAM,KAAK,OAAO,QAAQ,IAAI;AACpC,MAAI,CAAC,IAAK,QAAO;AACjB,MAAI;AACF,UAAM,MAAO,MAAM,OAAO,SAAS;AACnC,UAAM,SAAS,IAAI,IAAI,QAAQ,KAAK;AAAA,MAClC,gBAAgB,KAAK,kBAAkB;AAAA,MACvC,sBAAsB,KAAK,wBAAwB;AAAA,MACnD,KAAK,IAAI,WAAW,WAAW,IAAI,CAAC,IAAI;AAAA,IAC1C,CAAC;AACD,WAAO,GAAG,SAAS,CAAC,QAAQ,QAAQ,MAAM,IAAI,KAAK,KAAK,kBAAkB,IAAI,OAAO,CAAC;AACtF,WAAO;AAAA,EACT,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AAMO,SAAS,cAAsC,MAAmD;AACvG,MAAI,UAAoC;AACxC,SAAO,MAAM;AACX,QAAI,CAAC,QAAS,WAAU,eAAkB,IAAI;AAC9C,WAAO;AAAA,EACT;AACF;;;ACjCO,SAAS,kBAAkB,OAA6B,CAAC,GAAgB;AAC9E,QAAM,gBAAgB,KAAK,iBAAiB;AAC5C,QAAM,cAAc,KAAK,eAAe;AACxC,QAAM,YAAY,KAAK,aAAa;AAEpC,Q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AU,kBAAkB,IAAI;AACtC,QAAM,cAAc,KAAK,gBAAgB,CAAC,MAAe,2BAA2B,EAAE,IAAI,OAAO,iBAAiB,CAAC;AAEnH,SAAO,OAAO,GAAY,SAAe;AACvC,UAAM,EAAE,SAAS,WAAW,MAAM,IAAI,MAAM,QAAQ,MAAM,YAAY,CAAC,CAAC;AACxE,MAAE,OAAO,qBAAqB,OAAO,KAAK,CAAC;AAC3C,MAAE,OAAO,yBAAyB,OAAO,SAAS,CAAC;AACnD,QAAI,CAAC,SAAS;AACZ,aAAO,EAAE,KAAK,sBAAsB,KAAK,EAAE,iBAAiB,WAAW,CAAC;AAAA,IAC1E;AACA,UAAM,KAAK;AAAA,EACb;AACF;","names":[]}
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/middleware/nextjs.ts","../../src/_redis.ts","../../src/middleware/_core.ts","../../src/middleware/web.ts"],"sourcesContent":["import { createRateLimit, type RateLimitWebOptions } from './web';\n\n/**\n * Wrap a Next.js App Router route handler with rate limiting. When the bucket is\n * exhausted the wrapper returns a 429 directly; otherwise `handler` runs with the\n * `X-RateLimit-Limit` / `X-RateLimit-Remaining` headers already merged into the\n * outgoing response.\n *\n * ```ts\n * // app/api/route.ts\n * import { withRateLimit } from '@agent-score/commerce/middleware/nextjs';\n *\n * export const POST = withRateLimit({ maxRequests: 60, windowSeconds: 60 }, async (req) => {\n * return Response.json({ ok: true });\n * });\n * ```\n */\nexport function withRateLimit<TReq extends Request = Request>(\n opts: RateLimitWebOptions,\n handler: (req: TReq) => Response | Promise<Response>,\n): (req: TReq) => Promise<Response> {\n const guard = createRateLimit(opts);\n return async (req: TReq) => {\n const result = await guard(req);\n if (!result.allowed) return result.response;\n const downstream = await handler(req);\n downstream.headers.set('X-RateLimit-Limit', String(result.limit));\n downstream.headers.set('X-RateLimit-Remaining', String(result.remaining));\n return downstream;\n };\n}\n\nexport { createRateLimit, type RateLimitGuard, type RateLimitGuardResult, type RateLimitWebOptions } from './web';\n","/** Shared lazy `ioredis` factory. Used by `quote_cache`, `middleware/_core`,\n * and `stripe-multichain/pi-cache` so they don't drift on connect-timeout,\n * TLS handling, or error-logging posture.\n *\n * `ioredis` is an optional peer dep — callers pass `redisUrl` (or rely on\n * `process.env.REDIS_URL`); when unset or the lazy import fails, this returns\n * null and the caller falls back to its in-process `Map`.\n *\n * Not part of the public API.\n */\n\n/** Minimal Redis surface — each caller intersects with its own usage\n * (incr/expire for rate-limit, get/set/del for caches). Returning `unknown`\n * on commands keeps the shape narrow; cast at the call site. */\nexport interface MinimalRedis {\n on(event: 'error', handler: (err: Error) => void): unknown;\n}\n\nexport interface CreateRedisOptions {\n /** Override `process.env.REDIS_URL` for tests. */\n url?: string;\n /** Logging label, e.g. `'quote-cache'` / `'rate-limit'` / `'pi-cache'`. */\n label: string;\n /** Connect timeout in ms. Default `3000`. */\n connectTimeout?: number;\n /** Per-request retry cap. Default `1`. */\n maxRetriesPerRequest?: number;\n}\n\n/** Lazy-import ioredis and construct a client. Returns null when:\n * - no URL is configured (caller falls back to in-memory)\n * - `ioredis` isn't installed (optional peer; caller falls back to in-memory)\n * - the import throws for any other reason\n *\n * `rediss://` URLs auto-enable TLS. The error handler logs with the caller's\n * label so multi-cache deployments can tell which subsystem complained. */\nasync function tryCreateRedis<T extends MinimalRedis>(opts: CreateRedisOptions): Promise<T | null> {\n const url = opts.url ?? process.env.REDIS_URL;\n if (!url) return null;\n try {\n const mod = (await import('ioredis')) as unknown as { default: new (url: string, opts?: unknown) => T };\n const client = new mod.default(url, {\n connectTimeout: opts.connectTimeout ?? 3000,\n maxRetriesPerRequest: opts.maxRetriesPerRequest ?? 1,\n tls: url.startsWith('rediss://') ? {} : undefined,\n });\n client.on('error', (err) => console.error(`[${opts.label}] Redis error:`, err.message));\n return client;\n } catch {\n return null;\n }\n}\n\n/** Memoized-promise variant: call once per caller; subsequent calls return the\n * same promise. Pairs with the pattern `let p: Promise<T|null> | null = null;\n * const getRedis = () => (p ??= tryCreateRedis(...))` in callers that want\n * per-call promise caching without managing the closure themselves. */\nexport function memoizedRedis<T extends MinimalRedis>(opts: CreateRedisOptions): () => Promise<T | null> {\n let promise: Promise<T | null> | null = null;\n return () => {\n if (!promise) promise = tryCreateRedis<T>(opts);\n return promise;\n };\n}\n","import { memoizedRedis, type MinimalRedis } from '../_redis';\n\nexport interface RateLimitCoreOptions {\n windowSeconds?: number;\n maxRequests?: number;\n /** Redis connection URL. Default: `process.env.REDIS_URL`. Falls back to in-memory when unset or the lazy `ioredis` import fails. */\n redisUrl?: string;\n /** Per-instance key prefix so multiple limiters sharing a Redis don't collide. */\n keyPrefix?: string;\n}\n\nexport interface RateLimitDecision {\n allowed: boolean;\n remaining: number;\n limit: number;\n}\n\nexport interface RateLimiter {\n check(key: string): Promise<RateLimitDecision>;\n}\n\ninterface RedisLike extends MinimalRedis {\n incr(key: string): Promise<number>;\n expire(key: string, seconds: number): Promise<unknown>;\n}\n\n/** Framework-agnostic rate limiter. Hono / Express / Fastify / Next.js / Web adapters\n * share one core. Each `createRateLimiter` call owns its own memory map + redis\n * connection, so multiple instances in the same process don't share state unless\n * they share a Redis with the same `keyPrefix`. */\nexport function createRateLimiter(opts: RateLimitCoreOptions = {}): RateLimiter {\n const windowSeconds = opts.windowSeconds ?? 60;\n const maxRequests = opts.maxRequests ?? 60;\n const keyPrefix = opts.keyPrefix ?? 'rl:';\n\n const memMap = new Map<string, { count: number; resetAt: number }>();\n const getRedis = memoizedRedis<RedisLike>({ url: opts.redisUrl, label: 'rate-limit' });\n\n const checkMem = (key: string): RateLimitDecision => {\n const now = Date.now();\n const entry = memMap.get(key);\n if (!entry || entry.resetAt < now) {\n memMap.set(key, { count: 1, resetAt: now + windowSeconds * 1000 });\n return { allowed: true, remaining: maxRequests - 1, limit: maxRequests };\n }\n entry.count++;\n const remaining = Math.max(0, maxRequests - entry.count);\n return { allowed: entry.count <= maxRequests, remaining, limit: maxRequests };\n };\n\n return {\n async check(key: string): Promise<RateLimitDecision> {\n const r = await getRedis();\n if (!r) return checkMem(key);\n try {\n const fullKey = `${keyPrefix}${key}`;\n const count = await r.incr(fullKey);\n if (count === 1) await r.expire(fullKey, windowSeconds);\n const remaining = Math.max(0, maxRequests - count);\n return { allowed: count <= maxRequests, remaining, limit: maxRequests };\n } catch {\n return checkMem(key);\n }\n },\n };\n}\n\nexport const RATE_LIMIT_JSON_BODY = {\n error: { code: 'rate_limited', message: 'Too many requests' },\n} as const;\n\n/** Default key resolver: first hop of `x-forwarded-for`, else `'unknown'`. Works on any\n * framework's request once you adapt the header read. */\nexport function defaultKeyFromForwardedFor(forwardedFor: string | null | undefined): string {\n if (!forwardedFor) return 'unknown';\n return forwardedFor.split(',')[0]?.trim() || 'unknown';\n}\n","import {\n RATE_LIMIT_JSON_BODY,\n createRateLimiter,\n defaultKeyFromForwardedFor,\n type RateLimitCoreOptions,\n} from './_core';\n\nexport interface RateLimitWebOptions extends RateLimitCoreOptions {\n /** Bucket key resolver. Default: first hop of `x-forwarded-for`, else `'unknown'`. */\n keyResolver?: (req: Request) => string;\n}\n\nexport type RateLimitGuardResult =\n | { allowed: true; remaining: number; limit: number; response?: undefined }\n | { allowed: false; remaining: number; limit: number; response: Response };\n\nexport type RateLimitGuard = (req: Request) => Promise<RateLimitGuardResult>;\n\n/**\n * Build a rate-limit guard for Web Fetch–style handlers. Call `guard(req)` at the top\n * of your route. When `allowed === false`, return `result.response` directly.\n */\nexport function createRateLimit(opts: RateLimitWebOptions = {}): RateLimitGuard {\n const limiter = createRateLimiter(opts);\n const keyResolver =\n opts.keyResolver ?? ((req: Request) => defaultKeyFromForwardedFor(req.headers.get('x-forwarded-for')));\n\n return async (req: Request) => {\n const { allowed, remaining, limit } = await limiter.check(keyResolver(req));\n const baseHeaders = {\n 'X-RateLimit-Limit': String(limit),\n 'X-RateLimit-Remaining': String(remaining),\n };\n if (!allowed) {\n const response = new Response(JSON.stringify(RATE_LIMIT_JSON_BODY), {\n status: 429,\n headers: { ...baseHeaders, 'Content-Type': 'application/json', 'Cache-Control': 'no-store' },\n });\n return { allowed: false, remaining, limit, response };\n }\n return { allowed: true, remaining, limit };\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACoCA,eAAe,eAAuC,MAA6C;AACjG,QAAM,MAAM,KAAK,OAAO,QAAQ,IAAI;AACpC,MAAI,CAAC,IAAK,QAAO;AACjB,MAAI;AACF,UAAM,MAAO,MAAM,OAAO,SAAS;AACnC,UAAM,SAAS,IAAI,IAAI,QAAQ,KAAK;AAAA,MAClC,gBAAgB,KAAK,kBAAkB;AAAA,MACvC,sBAAsB,KAAK,wBAAwB;AAAA,MACnD,KAAK,IAAI,WAAW,WAAW,IAAI,CAAC,IAAI;AAAA,IAC1C,CAAC;AACD,WAAO,GAAG,SAAS,CAAC,QAAQ,QAAQ,MAAM,IAAI,KAAK,KAAK,kBAAkB,IAAI,OAAO,CAAC;AACtF,WAAO;AAAA,EACT,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AAMO,SAAS,cAAsC,MAAmD;AACvG,MAAI,UAAoC;AACxC,SAAO,MAAM;AACX,QAAI,CAAC,QAAS,WAAU,eAAkB,IAAI;AAC9C,WAAO;AAAA,EACT;AACF;;;ACjCO,SAAS,kBAAkB,OAA6B,CAAC,GAAgB;AAC9E,QAAM,gBAAgB,KAAK,iBAAiB;AAC5C,QAAM,cAAc,KAAK,eAAe;AACxC,QAAM,YAAY,KAAK,aAAa;AAEpC,QAAM,SAAS,oBAAI,IAAgD;AACnE,QAAM,WAAW,cAAyB,EAAE,KAAK,KAAK,UAAU,OAAO,aAAa,CAAC;AAErF,QAAM,WAAW,CAAC,QAAmC;AACnD,UAAM,MAAM,KAAK,IAAI;AACrB,UAAM,QAAQ,OAAO,IAAI,GAAG;AAC5B,QAAI,CAAC,SAAS,MAAM,UAAU,KAAK;AACjC,aAAO,IAAI,KAAK,EAAE,OAAO,GAAG,SAAS,MAAM,gBAAgB,IAAK,CA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,IAC3C;AACA,QAAI,CAAC,SAAS;AACZ,YAAM,WAAW,IAAI,SAAS,KAAK,UAAU,oBAAoB,GAAG;AAAA,QAClE,QAAQ;AAAA,QACR,SAAS,EAAE,GAAG,aAAa,gBAAgB,oBAAoB,iBAAiB,WAAW;AAAA,MAC7F,CAAC;AACD,aAAO,EAAE,SAAS,OAAO,WAAW,OAAO,SAAS;AAAA,IACtD;AACA,WAAO,EAAE,SAAS,MAAM,WAAW,MAAM;AAAA,EAC3C;AACF;;;AHzBO,SAAS,cACd,MACA,SACkC;AAClC,QAAM,QAAQ,gBAAgB,IAAI;AAClC,SAAO,OAAO,QAAc;AAC1B,UAAM,SAAS,MAAM,MAAM,GAAG;AAC9B,QAAI,CAAC,OAAO,QAAS,QAAO,OAAO;AACnC,UAAM,aAAa,MAAM,QAAQ,GAAG;AACpC,eAAW,QAAQ,IAAI,qBAAqB,OAAO,OAAO,KAAK,CAAC;AAChE,eAAW,QAAQ,IAAI,yBAAyB,OAAO,OAAO,SAAS,CAAC;AACxE,WAAO;AAAA,EACT;AACF;","names":[]}
1
+ {"version":3,"sources":["../../src/middleware/nextjs.ts","../../src/_redis.ts","../../src/middleware/_core.ts","../../src/middleware/web.ts"],"sourcesContent":["import { createRateLimit, type RateLimitWebOptions } from './web';\n\n/**\n * Wrap a Next.js App Router route handler with rate limiting. When the bucket is\n * exhausted the wrapper returns a 429 directly; otherwise `handler` runs with the\n * `X-RateLimit-Limit` / `X-RateLimit-Remaining` headers already merged into the\n * outgoing response.\n *\n * ```ts\n * // app/api/route.ts\n * import { withRateLimit } from '@agent-score/commerce/middleware/nextjs';\n *\n * export const POST = withRateLimit({ maxRequests: 60, windowSeconds: 60 }, async (req) => {\n * return Response.json({ ok: true });\n * });\n * ```\n */\nexport function withRateLimit<TReq extends Request = Request>(\n opts: RateLimitWebOptions,\n handler: (req: TReq) => Response | Promise<Response>,\n): (req: TReq) => Promise<Response> {\n const guard = createRateLimit(opts);\n return async (req: TReq) => {\n const result = await guard(req);\n if (!result.allowed) return result.response;\n const downstream = await handler(req);\n downstream.headers.set('X-RateLimit-Limit', String(result.limit));\n downstream.headers.set('X-RateLimit-Remaining', String(result.remaining));\n return downstream;\n };\n}\n\nexport { createRateLimit, type RateLimitGuard, type RateLimitGuardResult, type RateLimitWebOptions } from './web';\n","/** Shared lazy `ioredis` factory. Used by `quote_cache`, `middleware/_core`,\n * and `stripe-multichain/pi-cache` so they don't drift on connect-timeout,\n * TLS handling, or error-logging posture.\n *\n * `ioredis` is an optional peer dep — callers pass `redisUrl` (or rely on\n * `process.env.REDIS_URL`); when unset or the lazy import fails, this returns\n * null and the caller falls back to its in-process `Map`.\n *\n * Not part of the public API.\n */\n\n/** Minimal Redis surface — each caller intersects with its own usage\n * (incr/expire for rate-limit, get/set/del for caches). Returning `unknown`\n * on commands keeps the shape narrow; cast at the call site. */\nexport interface MinimalRedis {\n on(event: 'error', handler: (err: Error) => void): unknown;\n}\n\nexport interface CreateRedisOptions {\n /** Override `process.env.REDIS_URL` for tests. */\n url?: string;\n /** Logging label, e.g. `'quote-cache'` / `'rate-limit'` / `'pi-cache'`. */\n label: string;\n /** Connect timeout in ms. Default `3000`. */\n connectTimeout?: number;\n /** Per-request retry cap. Default `1`. */\n maxRetriesPerRequest?: number;\n}\n\n/** Lazy-import ioredis and construct a client. Returns null when:\n * - no URL is configured (caller falls back to in-memory)\n * - `ioredis` isn't installed (optional peer; caller falls back to in-memory)\n * - the import throws for any other reason\n *\n * `rediss://` URLs auto-enable TLS. The error handler logs with the caller's\n * label so multi-cache deployments can tell which subsystem complained. */\nasync function tryCreateRedis<T extends MinimalRedis>(opts: CreateRedisOptions): Promise<T | null> {\n const url = opts.url ?? process.env.REDIS_URL;\n if (!url) return null;\n try {\n const mod = (await import('ioredis')) as unknown as { default: new (url: string, opts?: unknown) => T };\n const client = new mod.default(url, {\n connectTimeout: opts.connectTimeout ?? 3000,\n maxRetriesPerRequest: opts.maxRetriesPerRequest ?? 1,\n tls: url.startsWith('rediss://') ? {} : undefined,\n });\n client.on('error', (err) => console.error(`[${opts.label}] Redis error:`, err.message));\n return client;\n } catch {\n return null;\n }\n}\n\n/** Memoized-promise variant: call once per caller; subsequent calls return the\n * same promise. Pairs with the pattern `let p: Promise<T|null> | null = null;\n * const getRedis = () => (p ??= tryCreateRedis(...))` in callers that want\n * per-call promise caching without managing the closure themselves. */\nexport function memoizedRedis<T extends MinimalRedis>(opts: CreateRedisOptions): () => Promise<T | null> {\n let promise: Promise<T | null> | null = null;\n return () => {\n if (!promise) promise = tryCreateRedis<T>(opts);\n return promise;\n };\n}\n","import { memoizedRedis, type MinimalRedis } from '../_redis';\n\nexport interface RateLimitCoreOptions {\n windowSeconds?: number;\n maxRequests?: number;\n /** Redis connection URL. Default: `process.env.REDIS_URL`. Falls back to in-memory when unset or the lazy `ioredis` import fails. */\n redisUrl?: string;\n /** Per-instance key prefix so multiple limiters sharing a Redis don't collide. */\n keyPrefix?: string;\n}\n\ninterface RateLimitDecision {\n allowed: boolean;\n remaining: number;\n limit: number;\n}\n\nexport interface RateLimiter {\n check(key: string): Promise<RateLimitDecision>;\n}\n\ninterface RedisLike extends MinimalRedis {\n incr(key: string): Promise<number>;\n expire(key: string, seconds: number): Promise<unknown>;\n}\n\n/** Framework-agnostic rate limiter. Hono / Express / Fastify / Next.js / Web adapters\n * share one core. Each `createRateLimiter` call owns its own memory map + redis\n * connection, so multiple instances in the same process don't share state unless\n * they share a Redis with the same `keyPrefix`. */\nexport function createRateLimiter(opts: RateLimitCoreOptions = {}): RateLimiter {\n const windowSeconds = opts.windowSeconds ?? 60;\n const maxRequests = opts.maxRequests ?? 60;\n const keyPrefix = opts.keyPrefix ?? 'rl:';\n\n const memMap = new Map<string, { count: number; resetAt: number }>();\n const getRedis = memoizedRedis<RedisLike>({ url: opts.redisUrl, label: 'rate-limit' });\n\n const checkMem = (key: string): RateLimitDecision => {\n const now = Date.now();\n const entry = memMap.get(key);\n if (!entry || entry.resetAt < now) {\n memMap.set(key, { count: 1, resetAt: now + windowSeconds * 1000 });\n return { allowed: true, remaining: maxRequests - 1, limit: maxRequests };\n }\n entry.count++;\n const remaining = Math.max(0, maxRequests - entry.count);\n return { allowed: entry.count <= maxRequests, remaining, limit: maxRequests };\n };\n\n return {\n async check(key: string): Promise<RateLimitDecision> {\n const r = await getRedis();\n if (!r) return checkMem(key);\n try {\n const fullKey = `${keyPrefix}${key}`;\n const count = await r.incr(fullKey);\n if (count === 1) await r.expire(fullKey, windowSeconds);\n const remaining = Math.max(0, maxRequests - count);\n return { allowed: count <= maxRequests, remaining, limit: maxRequests };\n } catch {\n return checkMem(key);\n }\n },\n };\n}\n\nexport const RATE_LIMIT_JSON_BODY = {\n error: { code: 'rate_limited', message: 'Too many requests' },\n} as const;\n\n/** Default key resolver: first hop of `x-forwarded-for`, else `'unknown'`. Works on any\n * framework's request once you adapt the header read. */\nexport function defaultKeyFromForwardedFor(forwardedFor: string | null | undefined): string {\n if (!forwardedFor) return 'unknown';\n return forwardedFor.split(',')[0]?.trim() || 'unknown';\n}\n","import {\n RATE_LIMIT_JSON_BODY,\n createRateLimiter,\n defaultKeyFromForwardedFor,\n type RateLimitCoreOptions,\n} from './_core';\n\nexport interface RateLimitWebOptions extends RateLimitCoreOptions {\n /** Bucket key resolver. Default: first hop of `x-forwarded-for`, else `'unknown'`. */\n keyResolver?: (req: Request) => string;\n}\n\nexport type RateLimitGuardResult =\n | { allowed: true; remaining: number; limit: number; response?: undefined }\n | { allowed: false; remaining: number; limit: number; response: Response };\n\nexport type RateLimitGuard = (req: Request) => Promise<RateLimitGuardResult>;\n\n/**\n * Build a rate-limit guard for Web Fetch–style handlers. Call `guard(req)` at the top\n * of your route. When `allowed === false`, return `result.response` directly.\n */\nexport function createRateLimit(opts: RateLimitWebOptions = {}): RateLimitGuard {\n const limiter = createRateLimiter(opts);\n const keyResolver =\n opts.keyResolver ?? ((req: Request) => defaultKeyFromForwardedFor(req.headers.get('x-forwarded-for')));\n\n return async (req: Request) => {\n const { allowed, remaining, limit } = await limiter.check(keyResolver(req));\n const baseHeaders = {\n 'X-RateLimit-Limit': String(limit),\n 'X-RateLimit-Remaining': String(remaining),\n };\n if (!allowed) {\n const response = new Response(JSON.stringify(RATE_LIMIT_JSON_BODY), {\n status: 429,\n headers: { ...baseHeaders, 'Content-Type': 'application/json', 'Cache-Control': 'no-store' },\n });\n return { allowed: false, remaining, limit, response };\n }\n return { allowed: true, remaining, limit };\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACoCA,eAAe,eAAuC,MAA6C;AACjG,QAAM,MAAM,KAAK,OAAO,QAAQ,IAAI;AACpC,MAAI,CAAC,IAAK,QAAO;AACjB,MAAI;AACF,UAAM,MAAO,MAAM,OAAO,SAAS;AACnC,UAAM,SAAS,IAAI,IAAI,QAAQ,KAAK;AAAA,MAClC,gBAAgB,KAAK,kBAAkB;AAAA,MACvC,sBAAsB,KAAK,wBAAwB;AAAA,MACnD,KAAK,IAAI,WAAW,WAAW,IAAI,CAAC,IAAI;AAAA,IAC1C,CAAC;AACD,WAAO,GAAG,SAAS,CAAC,QAAQ,QAAQ,MAAM,IAAI,KAAK,KAAK,kBAAkB,IAAI,OAAO,CAAC;AACtF,WAAO;AAAA,EACT,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AAMO,SAAS,cAAsC,MAAmD;AACvG,MAAI,UAAoC;AACxC,SAAO,MAAM;AACX,QAAI,CAAC,QAAS,WAAU,eAAkB,IAAI;AAC9C,WAAO;AAAA,EACT;AACF;;;ACjCO,SAAS,kBAAkB,OAA6B,CAAC,GAAgB;AAC9E,QAAM,gBAAgB,KAAK,iBAAiB;AAC5C,QAAM,cAAc,KAAK,eAAe;AACxC,QAAM,YAAY,KAAK,aAAa;AAEpC,QAAM,SAAS,oBAAI,IAAgD;AACnE,QAAM,WAAW,cAAyB,EAAE,KAAK,KAAK,UAAU,OAAO,aAAa,CAAC;AAErF,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AiB,CAAC;AAEtG,SAAO,OAAO,QAAiB;AAC7B,UAAM,EAAE,SAAS,WAAW,MAAM,IAAI,MAAM,QAAQ,MAAM,YAAY,GAAG,CAAC;AAC1E,UAAM,cAAc;AAAA,MAClB,qBAAqB,OAAO,KAAK;AAAA,MACjC,yBAAyB,OAAO,SAAS;AAAA,IAC3C;AACA,QAAI,CAAC,SAAS;AACZ,YAAM,WAAW,IAAI,SAAS,KAAK,UAAU,oBAAoB,GAAG;AAAA,QAClE,QAAQ;AAAA,QACR,SAAS,EAAE,GAAG,aAAa,gBAAgB,oBAAoB,iBAAiB,WAAW;AAAA,MAC7F,CAAC;AACD,aAAO,EAAE,SAAS,OAAO,WAAW,OAAO,SAAS;AAAA,IACtD;AACA,WAAO,EAAE,SAAS,MAAM,WAAW,MAAM;AAAA,EAC3C;AACF;;;AHzBO,SAAS,cACd,MACA,SACkC;AAClC,QAAM,QAAQ,gBAAgB,IAAI;AAClC,SAAO,OAAO,QAAc;AAC1B,UAAM,SAAS,MAAM,MAAM,GAAG;AAC9B,QAAI,CAAC,OAAO,QAAS,QAAO,OAAO;AACnC,UAAM,aAAa,MAAM,QAAQ,GAAG;AACpC,eAAW,QAAQ,IAAI,qBAAqB,OAAO,OAAO,KAAK,CAAC;AAChE,eAAW,QAAQ,IAAI,yBAAyB,OAAO,OAAO,SAAS,CAAC;AACxE,WAAO;AAAA,EACT;AACF;","names":[]}
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/_redis.ts","../../src/middleware/_core.ts","../../src/middleware/web.ts","../../src/middleware/nextjs.ts"],"sourcesContent":["/** Shared lazy `ioredis` factory. Used by `quote_cache`, `middleware/_core`,\n * and `stripe-multichain/pi-cache` so they don't drift on connect-timeout,\n * TLS handling, or error-logging posture.\n *\n * `ioredis` is an optional peer dep — callers pass `redisUrl` (or rely on\n * `process.env.REDIS_URL`); when unset or the lazy import fails, this returns\n * null and the caller falls back to its in-process `Map`.\n *\n * Not part of the public API.\n */\n\n/** Minimal Redis surface — each caller intersects with its own usage\n * (incr/expire for rate-limit, get/set/del for caches). Returning `unknown`\n * on commands keeps the shape narrow; cast at the call site. */\nexport interface MinimalRedis {\n on(event: 'error', handler: (err: Error) => void): unknown;\n}\n\nexport interface CreateRedisOptions {\n /** Override `process.env.REDIS_URL` for tests. */\n url?: string;\n /** Logging label, e.g. `'quote-cache'` / `'rate-limit'` / `'pi-cache'`. */\n label: string;\n /** Connect timeout in ms. Default `3000`. */\n connectTimeout?: number;\n /** Per-request retry cap. Default `1`. */\n maxRetriesPerRequest?: number;\n}\n\n/** Lazy-import ioredis and construct a client. Returns null when:\n * - no URL is configured (caller falls back to in-memory)\n * - `ioredis` isn't installed (optional peer; caller falls back to in-memory)\n * - the import throws for any other reason\n *\n * `rediss://` URLs auto-enable TLS. The error handler logs with the caller's\n * label so multi-cache deployments can tell which subsystem complained. */\nasync function tryCreateRedis<T extends MinimalRedis>(opts: CreateRedisOptions): Promise<T | null> {\n const url = opts.url ?? process.env.REDIS_URL;\n if (!url) return null;\n try {\n const mod = (await import('ioredis')) as unknown as { default: new (url: string, opts?: unknown) => T };\n const client = new mod.default(url, {\n connectTimeout: opts.connectTimeout ?? 3000,\n maxRetriesPerRequest: opts.maxRetriesPerRequest ?? 1,\n tls: url.startsWith('rediss://') ? {} : undefined,\n });\n client.on('error', (err) => console.error(`[${opts.label}] Redis error:`, err.message));\n return client;\n } catch {\n return null;\n }\n}\n\n/** Memoized-promise variant: call once per caller; subsequent calls return the\n * same promise. Pairs with the pattern `let p: Promise<T|null> | null = null;\n * const getRedis = () => (p ??= tryCreateRedis(...))` in callers that want\n * per-call promise caching without managing the closure themselves. */\nexport function memoizedRedis<T extends MinimalRedis>(opts: CreateRedisOptions): () => Promise<T | null> {\n let promise: Promise<T | null> | null = null;\n return () => {\n if (!promise) promise = tryCreateRedis<T>(opts);\n return promise;\n };\n}\n","import { memoizedRedis, type MinimalRedis } from '../_redis';\n\nexport interface RateLimitCoreOptions {\n windowSeconds?: number;\n maxRequests?: number;\n /** Redis connection URL. Default: `process.env.REDIS_URL`. Falls back to in-memory when unset or the lazy `ioredis` import fails. */\n redisUrl?: string;\n /** Per-instance key prefix so multiple limiters sharing a Redis don't collide. */\n keyPrefix?: string;\n}\n\nexport interface RateLimitDecision {\n allowed: boolean;\n remaining: number;\n limit: number;\n}\n\nexport interface RateLimiter {\n check(key: string): Promise<RateLimitDecision>;\n}\n\ninterface RedisLike extends MinimalRedis {\n incr(key: string): Promise<number>;\n expire(key: string, seconds: number): Promise<unknown>;\n}\n\n/** Framework-agnostic rate limiter. Hono / Express / Fastify / Next.js / Web adapters\n * share one core. Each `createRateLimiter` call owns its own memory map + redis\n * connection, so multiple instances in the same process don't share state unless\n * they share a Redis with the same `keyPrefix`. */\nexport function createRateLimiter(opts: RateLimitCoreOptions = {}): RateLimiter {\n const windowSeconds = opts.windowSeconds ?? 60;\n const maxRequests = opts.maxRequests ?? 60;\n const keyPrefix = opts.keyPrefix ?? 'rl:';\n\n const memMap = new Map<string, { count: number; resetAt: number }>();\n const getRedis = memoizedRedis<RedisLike>({ url: opts.redisUrl, label: 'rate-limit' });\n\n const checkMem = (key: string): RateLimitDecision => {\n const now = Date.now();\n const entry = memMap.get(key);\n if (!entry || entry.resetAt < now) {\n memMap.set(key, { count: 1, resetAt: now + windowSeconds * 1000 });\n return { allowed: true, remaining: maxRequests - 1, limit: maxRequests };\n }\n entry.count++;\n const remaining = Math.max(0, maxRequests - entry.count);\n return { allowed: entry.count <= maxRequests, remaining, limit: maxRequests };\n };\n\n return {\n async check(key: string): Promise<RateLimitDecision> {\n const r = await getRedis();\n if (!r) return checkMem(key);\n try {\n const fullKey = `${keyPrefix}${key}`;\n const count = await r.incr(fullKey);\n if (count === 1) await r.expire(fullKey, windowSeconds);\n const remaining = Math.max(0, maxRequests - count);\n return { allowed: count <= maxRequests, remaining, limit: maxRequests };\n } catch {\n return checkMem(key);\n }\n },\n };\n}\n\nexport const RATE_LIMIT_JSON_BODY = {\n error: { code: 'rate_limited', message: 'Too many requests' },\n} as const;\n\n/** Default key resolver: first hop of `x-forwarded-for`, else `'unknown'`. Works on any\n * framework's request once you adapt the header read. */\nexport function defaultKeyFromForwardedFor(forwardedFor: string | null | undefined): string {\n if (!forwardedFor) return 'unknown';\n return forwardedFor.split(',')[0]?.trim() || 'unknown';\n}\n","import {\n RATE_LIMIT_JSON_BODY,\n createRateLimiter,\n defaultKeyFromForwardedFor,\n type RateLimitCoreOptions,\n} from './_core';\n\nexport interface RateLimitWebOptions extends RateLimitCoreOptions {\n /** Bucket key resolver. Default: first hop of `x-forwarded-for`, else `'unknown'`. */\n keyResolver?: (req: Request) => string;\n}\n\nexport type RateLimitGuardResult =\n | { allowed: true; remaining: number; limit: number; response?: undefined }\n | { allowed: false; remaining: number; limit: number; response: Response };\n\nexport type RateLimitGuard = (req: Request) => Promise<RateLimitGuardResult>;\n\n/**\n * Build a rate-limit guard for Web Fetch–style handlers. Call `guard(req)` at the top\n * of your route. When `allowed === false`, return `result.response` directly.\n */\nexport function createRateLimit(opts: RateLimitWebOptions = {}): RateLimitGuard {\n const limiter = createRateLimiter(opts);\n const keyResolver =\n opts.keyResolver ?? ((req: Request) => defaultKeyFromForwardedFor(req.headers.get('x-forwarded-for')));\n\n return async (req: Request) => {\n const { allowed, remaining, limit } = await limiter.check(keyResolver(req));\n const baseHeaders = {\n 'X-RateLimit-Limit': String(limit),\n 'X-RateLimit-Remaining': String(remaining),\n };\n if (!allowed) {\n const response = new Response(JSON.stringify(RATE_LIMIT_JSON_BODY), {\n status: 429,\n headers: { ...baseHeaders, 'Content-Type': 'application/json', 'Cache-Control': 'no-store' },\n });\n return { allowed: false, remaining, limit, response };\n }\n return { allowed: true, remaining, limit };\n };\n}\n","import { createRateLimit, type RateLimitWebOptions } from './web';\n\n/**\n * Wrap a Next.js App Router route handler with rate limiting. When the bucket is\n * exhausted the wrapper returns a 429 directly; otherwise `handler` runs with the\n * `X-RateLimit-Limit` / `X-RateLimit-Remaining` headers already merged into the\n * outgoing response.\n *\n * ```ts\n * // app/api/route.ts\n * import { withRateLimit } from '@agent-score/commerce/middleware/nextjs';\n *\n * export const POST = withRateLimit({ maxRequests: 60, windowSeconds: 60 }, async (req) => {\n * return Response.json({ ok: true });\n * });\n * ```\n */\nexport function withRateLimit<TReq extends Request = Request>(\n opts: RateLimitWebOptions,\n handler: (req: TReq) => Response | Promise<Response>,\n): (req: TReq) => Promise<Response> {\n const guard = createRateLimit(opts);\n return async (req: TReq) => {\n const result = await guard(req);\n if (!result.allowed) return result.response;\n const downstream = await handler(req);\n downstream.headers.set('X-RateLimit-Limit', String(result.limit));\n downstream.headers.set('X-RateLimit-Remaining', String(result.remaining));\n return downstream;\n };\n}\n\nexport { createRateLimit, type RateLimitGuard, type RateLimitGuardResult, type RateLimitWebOptions } from './web';\n"],"mappings":";AAoCA,eAAe,eAAuC,MAA6C;AACjG,QAAM,MAAM,KAAK,OAAO,QAAQ,IAAI;AACpC,MAAI,CAAC,IAAK,QAAO;AACjB,MAAI;AACF,UAAM,MAAO,MAAM,OAAO,SAAS;AACnC,UAAM,SAAS,IAAI,IAAI,QAAQ,KAAK;AAAA,MAClC,gBAAgB,KAAK,kBAAkB;AAAA,MACvC,sBAAsB,KAAK,wBAAwB;AAAA,MACnD,KAAK,IAAI,WAAW,WAAW,IAAI,CAAC,IAAI;AAAA,IAC1C,CAAC;AACD,WAAO,GAAG,SAAS,CAAC,QAAQ,QAAQ,MAAM,IAAI,KAAK,KAAK,kBAAkB,IAAI,OAAO,CAAC;AACtF,WAAO;AAAA,EACT,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AAMO,SAAS,cAAsC,MAAmD;AACvG,MAAI,UAAoC;AACxC,SAAO,MAAM;AACX,QAAI,CAAC,QAAS,WAAU,eAAkB,IAAI;AAC9C,WAAO;AAAA,EACT;AACF;;;ACjCO,SAAS,kBAAkB,OAA6B,CAAC,GAAgB;AAC9E,QAAM,gBAAgB,KAAK,iBAAiB;AAC5C,QAAM,cAAc,K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O,SAAS,gBAAgB,OAA4B,CAAC,GAAmB;AAC9E,QAAM,UAAU,kBAAkB,IAAI;AACtC,QAAM,cACJ,KAAK,gBAAgB,CAAC,QAAiB,2BAA2B,IAAI,QAAQ,IAAI,iBAAiB,CAAC;AAEtG,SAAO,OAAO,QAAiB;AAC7B,UAAM,EAAE,SAAS,WAAW,MAAM,IAAI,MAAM,QAAQ,MAAM,YAAY,GAAG,CAAC;AAC1E,UAAM,cAAc;AAAA,MAClB,qBAAqB,OAAO,KAAK;AAAA,MACjC,yBAAyB,OAAO,SAAS;AAAA,IAC3C;AACA,QAAI,CAAC,SAAS;AACZ,YAAM,WAAW,IAAI,SAAS,KAAK,UAAU,oBAAoB,GAAG;AAAA,QAClE,QAAQ;AAAA,QACR,SAAS,EAAE,GAAG,aAAa,gBAAgB,oBAAoB,iBAAiB,WAAW;AAAA,MAC7F,CAAC;AACD,aAAO,EAAE,SAAS,OAAO,WAAW,OAAO,SAAS;AAAA,IACtD;AACA,WAAO,EAAE,SAAS,MAAM,WAAW,MAAM;AAAA,EAC3C;AACF;;;ACzBO,SAAS,cACd,MACA,SACkC;AAClC,QAAM,QAAQ,gBAAgB,IAAI;AAClC,SAAO,OAAO,QAAc;AAC1B,UAAM,SAAS,MAAM,MAAM,GAAG;AAC9B,QAAI,CAAC,OAAO,QAAS,QAAO,OAAO;AACnC,UAAM,aAAa,MAAM,QAAQ,GAAG;AACpC,eAAW,QAAQ,IAAI,qBAAqB,OAAO,OAAO,KAAK,CAAC;AAChE,eAAW,QAAQ,IAAI,yBAAyB,OAAO,OAAO,SAAS,CAAC;AACxE,WAAO;AAAA,EACT;AACF;","names":[]}
1
+ {"version":3,"sources":["../../src/_redis.ts","../../src/middleware/_core.ts","../../src/middleware/web.ts","../../src/middleware/nextjs.ts"],"sourcesContent":["/** Shared lazy `ioredis` factory. Used by `quote_cache`, `middleware/_core`,\n * and `stripe-multichain/pi-cache` so they don't drift on connect-timeout,\n * TLS handling, or error-logging posture.\n *\n * `ioredis` is an optional peer dep — callers pass `redisUrl` (or rely on\n * `process.env.REDIS_URL`); when unset or the lazy import fails, this returns\n * null and the caller falls back to its in-process `Map`.\n *\n * Not part of the public API.\n */\n\n/** Minimal Redis surface — each caller intersects with its own usage\n * (incr/expire for rate-limit, get/set/del for caches). Returning `unknown`\n * on commands keeps the shape narrow; cast at the call site. */\nexport interface MinimalRedis {\n on(event: 'error', handler: (err: Error) => void): unknown;\n}\n\nexport interface CreateRedisOptions {\n /** Override `process.env.REDIS_URL` for tests. */\n url?: string;\n /** Logging label, e.g. `'quote-cache'` / `'rate-limit'` / `'pi-cache'`. */\n label: string;\n /** Connect timeout in ms. Default `3000`. */\n connectTimeout?: number;\n /** Per-request retry cap. Default `1`. */\n maxRetriesPerRequest?: number;\n}\n\n/** Lazy-import ioredis and construct a client. Returns null when:\n * - no URL is configured (caller falls back to in-memory)\n * - `ioredis` isn't installed (optional peer; caller falls back to in-memory)\n * - the import throws for any other reason\n *\n * `rediss://` URLs auto-enable TLS. The error handler logs with the caller's\n * label so multi-cache deployments can tell which subsystem complained. */\nasync function tryCreateRedis<T extends MinimalRedis>(opts: CreateRedisOptions): Promise<T | null> {\n const url = opts.url ?? process.env.REDIS_URL;\n if (!url) return null;\n try {\n const mod = (await import('ioredis')) as unknown as { default: new (url: string, opts?: unknown) => T };\n const client = new mod.default(url, {\n connectTimeout: opts.connectTimeout ?? 3000,\n maxRetriesPerRequest: opts.maxRetriesPerRequest ?? 1,\n tls: url.startsWith('rediss://') ? {} : undefined,\n });\n client.on('error', (err) => console.error(`[${opts.label}] Redis error:`, err.message));\n return client;\n } catch {\n return null;\n }\n}\n\n/** Memoized-promise variant: call once per caller; subsequent calls return the\n * same promise. Pairs with the pattern `let p: Promise<T|null> | null = null;\n * const getRedis = () => (p ??= tryCreateRedis(...))` in callers that want\n * per-call promise caching without managing the closure themselves. */\nexport function memoizedRedis<T extends MinimalRedis>(opts: CreateRedisOptions): () => Promise<T | null> {\n let promise: Promise<T | null> | null = null;\n return () => {\n if (!promise) promise = tryCreateRedis<T>(opts);\n return promise;\n };\n}\n","import { memoizedRedis, type MinimalRedis } from '../_redis';\n\nexport interface RateLimitCoreOptions {\n windowSeconds?: number;\n maxRequests?: number;\n /** Redis connection URL. Default: `process.env.REDIS_URL`. Falls back to in-memory when unset or the lazy `ioredis` import fails. */\n redisUrl?: string;\n /** Per-instance key prefix so multiple limiters sharing a Redis don't collide. */\n keyPrefix?: string;\n}\n\ninterface RateLimitDecision {\n allowed: boolean;\n remaining: number;\n limit: number;\n}\n\nexport interface RateLimiter {\n check(key: string): Promise<RateLimitDecision>;\n}\n\ninterface RedisLike extends MinimalRedis {\n incr(key: string): Promise<number>;\n expire(key: string, seconds: number): Promise<unknown>;\n}\n\n/** Framework-agnostic rate limiter. Hono / Express / Fastify / Next.js / Web adapters\n * share one core. Each `createRateLimiter` call owns its own memory map + redis\n * connection, so multiple instances in the same process don't share state unless\n * they share a Redis with the same `keyPrefix`. */\nexport function createRateLimiter(opts: RateLimitCoreOptions = {}): RateLimiter {\n const windowSeconds = opts.windowSeconds ?? 60;\n const maxRequests = opts.maxRequests ?? 60;\n const keyPrefix = opts.keyPrefix ?? 'rl:';\n\n const memMap = new Map<string, { count: number; resetAt: number }>();\n const getRedis = memoizedRedis<RedisLike>({ url: opts.redisUrl, label: 'rate-limit' });\n\n const checkMem = (key: string): RateLimitDecision => {\n const now = Date.now();\n const entry = memMap.get(key);\n if (!entry || entry.resetAt < now) {\n memMap.set(key, { count: 1, resetAt: now + windowSeconds * 1000 });\n return { allowed: true, remaining: maxRequests - 1, limit: maxRequests };\n }\n entry.count++;\n const remaining = Math.max(0, maxRequests - entry.count);\n return { allowed: entry.count <= maxRequests, remaining, limit: maxRequests };\n };\n\n return {\n async check(key: string): Promise<RateLimitDecision> {\n const r = await getRedis();\n if (!r) return checkMem(key);\n try {\n const fullKey = `${keyPrefix}${key}`;\n const count = await r.incr(fullKey);\n if (count === 1) await r.expire(fullKey, windowSeconds);\n const remaining = Math.max(0, maxRequests - count);\n return { allowed: count <= maxRequests, remaining, limit: maxRequests };\n } catch {\n return checkMem(key);\n }\n },\n };\n}\n\nexport const RATE_LIMIT_JSON_BODY = {\n error: { code: 'rate_limited', message: 'Too many requests' },\n} as const;\n\n/** Default key resolver: first hop of `x-forwarded-for`, else `'unknown'`. Works on any\n * framework's request once you adapt the header read. */\nexport function defaultKeyFromForwardedFor(forwardedFor: string | null | undefined): string {\n if (!forwardedFor) return 'unknown';\n return forwardedFor.split(',')[0]?.trim() || 'unknown';\n}\n","import {\n RATE_LIMIT_JSON_BODY,\n createRateLimiter,\n defaultKeyFromForwardedFor,\n type RateLimitCoreOptions,\n} from './_core';\n\nexport interface RateLimitWebOptions extends RateLimitCoreOptions {\n /** Bucket key resolver. Default: first hop of `x-forwarded-for`, else `'unknown'`. */\n keyResolver?: (req: Request) => string;\n}\n\nexport type RateLimitGuardResult =\n | { allowed: true; remaining: number; limit: number; response?: undefined }\n | { allowed: false; remaining: number; limit: number; response: Response };\n\nexport type RateLimitGuard = (req: Request) => Promise<RateLimitGuardResult>;\n\n/**\n * Build a rate-limit guard for Web Fetch–style handlers. Call `guard(req)` at the top\n * of your route. When `allowed === false`, return `result.response` directly.\n */\nexport function createRateLimit(opts: RateLimitWebOptions = {}): RateLimitGuard {\n const limiter = createRateLimiter(opts);\n const keyResolver =\n opts.keyResolver ?? ((req: Request) => defaultKeyFromForwardedFor(req.headers.get('x-forwarded-for')));\n\n return async (req: Request) => {\n const { allowed, remaining, limit } = await limiter.check(keyResolver(req));\n const baseHeaders = {\n 'X-RateLimit-Limit': String(limit),\n 'X-RateLimit-Remaining': String(remaining),\n };\n if (!allowed) {\n const response = new Response(JSON.stringify(RATE_LIMIT_JSON_BODY), {\n status: 429,\n headers: { ...baseHeaders, 'Content-Type': 'application/json', 'Cache-Control': 'no-store' },\n });\n return { allowed: false, remaining, limit, response };\n }\n return { allowed: true, remaining, limit };\n };\n}\n","import { createRateLimit, type RateLimitWebOptions } from './web';\n\n/**\n * Wrap a Next.js App Router route handler with rate limiting. When the bucket is\n * exhausted the wrapper returns a 429 directly; otherwise `handler` runs with the\n * `X-RateLimit-Limit` / `X-RateLimit-Remaining` headers already merged into the\n * outgoing response.\n *\n * ```ts\n * // app/api/route.ts\n * import { withRateLimit } from '@agent-score/commerce/middleware/nextjs';\n *\n * export const POST = withRateLimit({ maxRequests: 60, windowSeconds: 60 }, async (req) => {\n * return Response.json({ ok: true });\n * });\n * ```\n */\nexport function withRateLimit<TReq extends Request = Request>(\n opts: RateLimitWebOptions,\n handler: (req: TReq) => Response | Promise<Response>,\n): (req: TReq) => Promise<Response> {\n const guard = createRateLimit(opts);\n return async (req: TReq) => {\n const result = await guard(req);\n if (!result.allowed) return result.response;\n const downstream = await handler(req);\n downstream.headers.set('X-RateLimit-Limit', String(result.limit));\n downstream.headers.set('X-RateLimit-Remaining', String(result.remaining));\n return downstream;\n };\n}\n\nexport { createRateLimit, type RateLimitGuard, type RateLimitGuardResult, type RateLimitWebOptions } from './web';\n"],"mappings":";AAoCA,eAAe,eAAuC,MAA6C;AACjG,QAAM,MAAM,KAAK,OAAO,QAAQ,IAAI;AACpC,MAAI,CAAC,IAAK,QAAO;AACjB,MAAI;AACF,UAAM,MAAO,MAAM,OAAO,SAAS;AACnC,UAAM,SAAS,IAAI,IAAI,QAAQ,KAAK;AAAA,MAClC,gBAAgB,KAAK,kBAAkB;AAAA,MACvC,sBAAsB,KAAK,wBAAwB;AAAA,MACnD,KAAK,IAAI,WAAW,WAAW,IAAI,CAAC,IAAI;AAAA,IAC1C,CAAC;AACD,WAAO,GAAG,SAAS,CAAC,QAAQ,QAAQ,MAAM,IAAI,KAAK,KAAK,kBAAkB,IAAI,OAAO,CAAC;AACtF,WAAO;AAAA,EACT,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AAMO,SAAS,cAAsC,MAAmD;AACvG,MAAI,UAAoC;AACxC,SAAO,MAAM;AACX,QAAI,CAAC,QAAS,WAAU,eAAkB,IA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ts"],"sourcesContent":["import {\n RATE_LIMIT_JSON_BODY,\n createRateLimiter,\n defaultKeyFromForwardedFor,\n type RateLimitCoreOptions,\n} from './_core';\n\nexport interface RateLimitWebOptions extends RateLimitCoreOptions {\n /** Bucket key resolver. Default: first hop of `x-forwarded-for`, else `'unknown'`. */\n keyResolver?: (req: Request) => string;\n}\n\nexport type RateLimitGuardResult =\n | { allowed: true; remaining: number; limit: number; response?: undefined }\n | { allowed: false; remaining: number; limit: number; response: Response };\n\nexport type RateLimitGuard = (req: Request) => Promise<RateLimitGuardResult>;\n\n/**\n * Build a rate-limit guard for Web Fetch–style handlers. Call `guard(req)` at the top\n * of your route. When `allowed === false`, return `result.response` directly.\n */\nexport function createRateLimit(opts: RateLimitWebOptions = {}): RateLimitGuard {\n const limiter = createRateLimiter(opts);\n const keyResolver =\n opts.keyResolver ?? ((req: Request) => defaultKeyFromForwardedFor(req.headers.get('x-forwarded-for')));\n\n return async (req: Request) => {\n const { allowed, remaining, limit } = await limiter.check(keyResolver(req));\n const baseHeaders = {\n 'X-RateLimit-Limit': String(limit),\n 'X-RateLimit-Remaining': String(remaining),\n };\n if (!allowed) {\n const response = new Response(JSON.stringify(RATE_LIMIT_JSON_BODY), {\n status: 429,\n headers: { ...baseHeaders, 'Content-Type': 'application/json', 'Cache-Control': 'no-store' },\n });\n return { allowed: false, remaining, limit, response };\n }\n return { allowed: true, remaining, limit };\n };\n}\n","/** Shared lazy `ioredis` factory. Used by `quote_cache`, `middleware/_core`,\n * and `stripe-multichain/pi-cache` so they don't drift on connect-timeout,\n * TLS handling, or error-logging posture.\n *\n * `ioredis` is an optional peer dep — callers pass `redisUrl` (or rely on\n * `process.env.REDIS_URL`); when unset or the lazy import fails, this returns\n * null and the caller falls back to its in-process `Map`.\n *\n * Not part of the public API.\n */\n\n/** Minimal Redis surface — each caller intersects with its own usage\n * (incr/expire for rate-limit, get/set/del for caches). Returning `unknown`\n * on commands keeps the shape narrow; cast at the call site. */\nexport interface MinimalRedis {\n on(event: 'error', handler: (err: Error) => void): unknown;\n}\n\nexport interface CreateRedisOptions {\n /** Override `process.env.REDIS_URL` for tests. */\n url?: string;\n /** Logging label, e.g. `'quote-cache'` / `'rate-limit'` / `'pi-cache'`. */\n label: string;\n /** Connect timeout in ms. Default `3000`. */\n connectTimeout?: number;\n /** Per-request retry cap. Default `1`. */\n maxRetriesPerRequest?: number;\n}\n\n/** Lazy-import ioredis and construct a client. Returns null when:\n * - no URL is configured (caller falls back to in-memory)\n * - `ioredis` isn't installed (optional peer; caller falls back to in-memory)\n * - the import throws for any other reason\n *\n * `rediss://` URLs auto-enable TLS. The error handler logs with the caller's\n * label so multi-cache deployments can tell which subsystem complained. */\nasync function tryCreateRedis<T extends MinimalRedis>(opts: CreateRedisOptions): Promise<T | null> {\n const url = opts.url ?? process.env.REDIS_URL;\n if (!url) return null;\n try {\n const mod = (await import('ioredis')) as unknown as { default: new (url: string, opts?: unknown) => T };\n const client = new mod.default(url, {\n connectTimeout: opts.connectTimeout ?? 3000,\n maxRetriesPerRequest: opts.maxRetriesPerRequest ?? 1,\n tls: url.startsWith('rediss://') ? {} : undefined,\n });\n client.on('error', (err) => console.error(`[${opts.label}] Redis error:`, err.message));\n return client;\n } catch {\n return null;\n }\n}\n\n/** Memoized-promise variant: call once per caller; subsequent calls return the\n * same promise. Pairs with the pattern `let p: Promise<T|null> | null = null;\n * const getRedis = () => (p ??= tryCreateRedis(...))` in callers that want\n * per-call promise caching without managing the closure themselves. */\nexport function memoizedRedis<T extends MinimalRedis>(opts: CreateRedisOptions): () => Promise<T | null> {\n let promise: Promise<T | null> | null = null;\n return () => {\n if (!promise) promise = tryCreateRedis<T>(opts);\n return promise;\n };\n}\n","import { memoizedRedis, type MinimalRedis } from '../_redis';\n\nexport interface RateLimitCoreOptions {\n windowSeconds?: number;\n maxRequests?: number;\n /** Redis connection URL. Default: `process.env.REDIS_URL`. Falls back to in-memory when unset or the lazy `ioredis` import fails. */\n redisUrl?: string;\n /** Per-instance key prefix so multiple limiters sharing a Redis don't collide. */\n keyPrefix?: string;\n}\n\nexport interface RateLimitDecision {\n allowed: boolean;\n remaining: number;\n limit: number;\n}\n\nexport interface RateLimiter {\n check(key: string): Promise<RateLimitDecision>;\n}\n\ninterface RedisLike extends MinimalRedis {\n incr(key: string): Promise<number>;\n expire(key: string, seconds: number): Promise<unknown>;\n}\n\n/** Framework-agnostic rate limiter. Hono / Express / Fastify / Next.js / Web adapters\n * share one core. Each `createRateLimiter` call owns its own memory map + redis\n * connection, so multiple instances in the same process don't share state unless\n * they share a Redis with the same `keyPrefix`. */\nexport function createRateLimiter(opts: RateLimitCoreOptions = {}): RateLimiter {\n const windowSeconds = opts.windowSeconds ?? 60;\n const maxRequests = opts.maxRequests ?? 60;\n const keyPrefix = opts.keyPrefix ?? 'rl:';\n\n const memMap = new Map<string, { count: number; resetAt: number }>();\n const getRedis = memoizedRedis<RedisLike>({ url: opts.redisUrl, label: 'rate-limit' });\n\n const checkMem = (key: string): RateLimitDecision => {\n const now = Date.now();\n const entry = memMap.get(key);\n if (!entry || entry.resetAt < now) {\n memMap.set(key, { count: 1, resetAt: now + windowSeconds * 1000 });\n return { allowed: true, remaining: maxRequests - 1, limit: maxRequests };\n }\n entry.count++;\n const remaining = Math.max(0, maxRequests - entry.count);\n return { allowed: entry.count <= maxRequests, remaining, limit: maxRequests };\n };\n\n return {\n async check(key: string): Promise<RateLimitDecision> {\n const r = await getRedis();\n if (!r) return checkMem(key);\n try {\n const fullKey = `${keyPrefix}${key}`;\n const count = await r.incr(fullKey);\n if (count === 1) await r.expire(fullKey, windowSeconds);\n const remaining = Math.max(0, maxRequests - count);\n return { allowed: count <= maxRequests, remaining, limit: maxRequests };\n } catch {\n return checkMem(key);\n }\n },\n };\n}\n\nexport const RATE_LIMIT_JSON_BODY = {\n error: { code: 'rate_limited', message: 'Too many requests' },\n} as const;\n\n/** Default key resolver: first hop of `x-forwarded-for`, else `'unknown'`. Works on any\n * framework's request once you adapt the header read. */\nexport function defaultKeyFromForwardedFor(forwardedFor: string | null | undefined): string {\n if (!forwardedFor) return 'unknown';\n return forwardedFor.split(',')[0]?.trim() || 'unknown';\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACoCA,eAAe,eAAuC,MAA6C;AACjG,QAAM,MAAM,KAAK,OAAO,QAAQ,IAAI;AACpC,MAAI,CAAC,IAAK,QAAO;AACjB,MAAI;AACF,UAAM,MAAO,MAAM,OAAO,SAAS;AACnC,UAAM,SAAS,IAAI,IAAI,QAAQ,KAAK;AAAA,MAClC,gBAAgB,KAAK,kBAAkB;AAAA,MACvC,sBAAsB,KAAK,wBAAwB;AAAA,MACnD,KAAK,IAAI,WAAW,WAAW,IAAI,CAAC,IAAI;AAAA,IAC1C,CAAC;AACD,WAAO,GAAG,SAAS,CAAC,QAAQ,QAAQ,MAAM,IAAI,KAAK,KAAK,kBAAkB,IAAI,OAAO,CAAC;AACtF,WAAO;AAAA,EACT,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AAMO,SAAS,cAAsC,MAAmD;AACvG,MAAI,UAAoC;AACxC,SAAO,MAAM;AACX,QAAI,CAAC,QAAS,WAAU,eAAkB,IAAI;AAC9C,WAAO;AAAA,EACT;AACF;;;ACjCO,SAAS,kBAAkB,OAA6B,CAAC,GAAgB;AAC9E,QAAM,gBAAgB,KAAK,iBAAiB;AAC5C,QAAM,cAAc,KAAK,eAAe;AACxC,QAAM,YAAY,KAAK,aAAa;AAEpC,QAAM,SAAS,oBAAI,IAAgD;AACnE,QAAM,WAAW,cAAyB,EAAE,KAAK,KAAK,UAAU,OAAO,aAAa,CAAC;AAErF,QAAM,WAAW,CAAC,QAAmC;AACnD,UAAM,MAAM,KAAK,IAAI;AACrB,UAAM,QAAQ,OAAO,IAAI,GAAG;AAC5B,QAAI,CAAC,SAAS,MAAM,UAAU,KAAK;AACjC,aAAO,IAAI,KAAK,EAAE,OAAO,GAAG,SAAS,MA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yB,OAAO,SAAS;AAAA,IAC3C;AACA,QAAI,CAAC,SAAS;AACZ,YAAM,WAAW,IAAI,SAAS,KAAK,UAAU,oBAAoB,GAAG;AAAA,QAClE,QAAQ;AAAA,QACR,SAAS,EAAE,GAAG,aAAa,gBAAgB,oBAAoB,iBAAiB,WAAW;AAAA,MAC7F,CAAC;AACD,aAAO,EAAE,SAAS,OAAO,WAAW,OAAO,SAAS;AAAA,IACtD;AACA,WAAO,EAAE,SAAS,MAAM,WAAW,MAAM;AAAA,EAC3C;AACF;","names":[]}
1
+ {"version":3,"sources":["../../src/middleware/web.ts","../../src/_redis.ts","../../src/middleware/_core.ts"],"sourcesContent":["import {\n RATE_LIMIT_JSON_BODY,\n createRateLimiter,\n defaultKeyFromForwardedFor,\n type RateLimitCoreOptions,\n} from './_core';\n\nexport interface RateLimitWebOptions extends RateLimitCoreOptions {\n /** Bucket key resolver. Default: first hop of `x-forwarded-for`, else `'unknown'`. */\n keyResolver?: (req: Request) => string;\n}\n\nexport type RateLimitGuardResult =\n | { allowed: true; remaining: number; limit: number; response?: undefined }\n | { allowed: false; remaining: number; limit: number; response: Response };\n\nexport type RateLimitGuard = (req: Request) => Promise<RateLimitGuardResult>;\n\n/**\n * Build a rate-limit guard for Web Fetch–style handlers. Call `guard(req)` at the top\n * of your route. When `allowed === false`, return `result.response` directly.\n */\nexport function createRateLimit(opts: RateLimitWebOptions = {}): RateLimitGuard {\n const limiter = createRateLimiter(opts);\n const keyResolver =\n opts.keyResolver ?? ((req: Request) => defaultKeyFromForwardedFor(req.headers.get('x-forwarded-for')));\n\n return async (req: Request) => {\n const { allowed, remaining, limit } = await limiter.check(keyResolver(req));\n const baseHeaders = {\n 'X-RateLimit-Limit': String(limit),\n 'X-RateLimit-Remaining': String(remaining),\n };\n if (!allowed) {\n const response = new Response(JSON.stringify(RATE_LIMIT_JSON_BODY), {\n status: 429,\n headers: { ...baseHeaders, 'Content-Type': 'application/json', 'Cache-Control': 'no-store' },\n });\n return { allowed: false, remaining, limit, response };\n }\n return { allowed: true, remaining, limit };\n };\n}\n","/** Shared lazy `ioredis` factory. Used by `quote_cache`, `middleware/_core`,\n * and `stripe-multichain/pi-cache` so they don't drift on connect-timeout,\n * TLS handling, or error-logging posture.\n *\n * `ioredis` is an optional peer dep — callers pass `redisUrl` (or rely on\n * `process.env.REDIS_URL`); when unset or the lazy import fails, this returns\n * null and the caller falls back to its in-process `Map`.\n *\n * Not part of the public API.\n */\n\n/** Minimal Redis surface — each caller intersects with its own usage\n * (incr/expire for rate-limit, get/set/del for caches). Returning `unknown`\n * on commands keeps the shape narrow; cast at the call site. */\nexport interface MinimalRedis {\n on(event: 'error', handler: (err: Error) => void): unknown;\n}\n\nexport interface CreateRedisOptions {\n /** Override `process.env.REDIS_URL` for tests. */\n url?: string;\n /** Logging label, e.g. `'quote-cache'` / `'rate-limit'` / `'pi-cache'`. */\n label: string;\n /** Connect timeout in ms. Default `3000`. */\n connectTimeout?: number;\n /** Per-request retry cap. Default `1`. */\n maxRetriesPerRequest?: number;\n}\n\n/** Lazy-import ioredis and construct a client. Returns null when:\n * - no URL is configured (caller falls back to in-memory)\n * - `ioredis` isn't installed (optional peer; caller falls back to in-memory)\n * - the import throws for any other reason\n *\n * `rediss://` URLs auto-enable TLS. The error handler logs with the caller's\n * label so multi-cache deployments can tell which subsystem complained. */\nasync function tryCreateRedis<T extends MinimalRedis>(opts: CreateRedisOptions): Promise<T | null> {\n const url = opts.url ?? process.env.REDIS_URL;\n if (!url) return null;\n try {\n const mod = (await import('ioredis')) as unknown as { default: new (url: string, opts?: unknown) => T };\n const client = new mod.default(url, {\n connectTimeout: opts.connectTimeout ?? 3000,\n maxRetriesPerRequest: opts.maxRetriesPerRequest ?? 1,\n tls: url.startsWith('rediss://') ? {} : undefined,\n });\n client.on('error', (err) => console.error(`[${opts.label}] Redis error:`, err.message));\n return client;\n } catch {\n return null;\n }\n}\n\n/** Memoized-promise variant: call once per caller; subsequent calls return the\n * same promise. Pairs with the pattern `let p: Promise<T|null> | null = null;\n * const getRedis = () => (p ??= tryCreateRedis(...))` in callers that want\n * per-call promise caching without managing the closure themselves. */\nexport function memoizedRedis<T extends MinimalRedis>(opts: CreateRedisOptions): () => Promise<T | null> {\n let promise: Promise<T | null> | null = null;\n return () => {\n if (!promise) promise = tryCreateRedis<T>(opts);\n return promise;\n };\n}\n","import { memoizedRedis, type MinimalRedis } from '../_redis';\n\nexport interface RateLimitCoreOptions {\n windowSeconds?: number;\n maxRequests?: number;\n /** Redis connection URL. Default: `process.env.REDIS_URL`. Falls back to in-memory when unset or the lazy `ioredis` import fails. */\n redisUrl?: string;\n /** Per-instance key prefix so multiple limiters sharing a Redis don't collide. */\n keyPrefix?: string;\n}\n\ninterface RateLimitDecision {\n allowed: boolean;\n remaining: number;\n limit: number;\n}\n\nexport interface RateLimiter {\n check(key: string): Promise<RateLimitDecision>;\n}\n\ninterface RedisLike extends MinimalRedis {\n incr(key: string): Promise<number>;\n expire(key: string, seconds: number): Promise<unknown>;\n}\n\n/** Framework-agnostic rate limiter. Hono / Express / Fastify / Next.js / Web adapters\n * share one core. Each `createRateLimiter` call owns its own memory map + redis\n * connection, so multiple instances in the same process don't share state unless\n * they share a Redis with the same `keyPrefix`. */\nexport function createRateLimiter(opts: RateLimitCoreOptions = {}): RateLimiter {\n const windowSeconds = opts.windowSeconds ?? 60;\n const maxRequests = opts.maxRequests ?? 60;\n const keyPrefix = opts.keyPrefix ?? 'rl:';\n\n const memMap = new Map<string, { count: number; resetAt: number }>();\n const getRedis = memoizedRedis<RedisLike>({ url: opts.redisUrl, label: 'rate-limit' });\n\n const checkMem = (key: string): RateLimitDecision => {\n const now = Date.now();\n const entry = memMap.get(key);\n if (!entry || entry.resetAt < now) {\n memMap.set(key, { count: 1, resetAt: now + windowSeconds * 1000 });\n return { allowed: true, remaining: maxRequests - 1, limit: maxRequests };\n }\n entry.count++;\n const remaining = Math.max(0, maxRequests - entry.count);\n return { allowed: entry.count <= maxRequests, remaining, limit: maxRequests };\n };\n\n return {\n async check(key: string): Promise<RateLimitDecision> {\n const r = await getRedis();\n if (!r) return checkMem(key);\n try {\n const fullKey = `${keyPrefix}${key}`;\n const count = await r.incr(fullKey);\n if (count === 1) await r.expire(fullKey, windowSeconds);\n const remaining = Math.max(0, maxRequests - count);\n return { allowed: count <= maxRequests, remaining, limit: maxRequests };\n } catch {\n return checkMem(key);\n }\n },\n };\n}\n\nexport const RATE_LIMIT_JSON_BODY = {\n error: { code: 'rate_limited', message: 'Too many requests' },\n} as const;\n\n/** Default key resolver: first hop of `x-forwarded-for`, else `'unknown'`. Works on any\n * framework's request once you adapt the header read. */\nexport function defaultKeyFromForwardedFor(forwardedFor: string | null | undefined): string {\n if (!forwardedFor) return 'unknown';\n return forwardedFor.split(',')[0]?.trim() || 'unknown';\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACoCA,eAAe,eAAuC,MAA6C;AACjG,QAAM,MAAM,KAAK,OAAO,QAAQ,IAAI;AACpC,MAAI,CAAC,IAAK,QAAO;AACjB,MAAI;AACF,UAAM,MAAO,MAAM,OAAO,SAAS;AACnC,UAAM,SAAS,IAAI,IAAI,QAAQ,KAAK;AAAA,MAClC,gBAAgB,KAAK,kBAAkB;AAAA,MACvC,sBAAsB,KAAK,wBAAwB;AAAA,MACnD,KAAK,IAAI,WAAW,WAAW,IAAI,CAAC,IAAI;AAAA,IAC1C,CAAC;AACD,WAAO,GAAG,SAAS,CAAC,QAAQ,QAAQ,MAAM,IAAI,KAAK,KAAK,kBAAkB,IAAI,OAAO,CAAC;AACtF,WAAO;AAAA,EACT,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AAMO,SAAS,cAAsC,MAAmD;AACvG,MAAI,UAAoC;AACxC,SAAO,MAAM;AACX,QAAI,CAAC,QAAS,WAAU,eAAkB,IAAI;AAC9C,WAAO;AAAA,EACT;AACF;;;ACjCO,SAAS,kBAAkB,OAA6B,CAAC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O,aAAa,MAAM,GAAG,EAAE,CAAC,GAAG,KAAK,KAAK;AAC/C;;;AFtDO,SAAS,gBAAgB,OAA4B,CAAC,GAAmB;AAC9E,QAAM,UAAU,kBAAkB,IAAI;AACtC,QAAM,cACJ,KAAK,gBAAgB,CAAC,QAAiB,2BAA2B,IAAI,QAAQ,IAAI,iBAAiB,CAAC;AAEtG,SAAO,OAAO,QAAiB;AAC7B,UAAM,EAAE,SAAS,WAAW,MAAM,IAAI,MAAM,QAAQ,MAAM,YAAY,GAAG,CAAC;AAC1E,UAAM,cAAc;AAAA,MAClB,qBAAqB,OAAO,KAAK;AAAA,MACjC,yBAAyB,OAAO,SAAS;AAAA,IAC3C;AACA,QAAI,CAAC,SAAS;AACZ,YAAM,WAAW,IAAI,SAAS,KAAK,UAAU,oBAAoB,GAAG;AAAA,QAClE,QAAQ;AAAA,QACR,SAAS,EAAE,GAAG,aAAa,gBAAgB,oBAAoB,iBAAiB,WAAW;AAAA,MAC7F,CAAC;AACD,aAAO,EAAE,SAAS,OAAO,WAAW,OAAO,SAAS;AAAA,IACtD;AACA,WAAO,EAAE,SAAS,MAAM,WAAW,MAAM;AAAA,EAC3C;AACF;","names":[]}
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/_redis.ts","../../src/middleware/_core.ts","../../src/middleware/web.ts"],"sourcesContent":["/** Shared lazy `ioredis` factory. Used by `quote_cache`, `middleware/_core`,\n * and `stripe-multichain/pi-cache` so they don't drift on connect-timeout,\n * TLS handling, or error-logging posture.\n *\n * `ioredis` is an optional peer dep — callers pass `redisUrl` (or rely on\n * `process.env.REDIS_URL`); when unset or the lazy import fails, this returns\n * null and the caller falls back to its in-process `Map`.\n *\n * Not part of the public API.\n */\n\n/** Minimal Redis surface — each caller intersects with its own usage\n * (incr/expire for rate-limit, get/set/del for caches). Returning `unknown`\n * on commands keeps the shape narrow; cast at the call site. */\nexport interface MinimalRedis {\n on(event: 'error', handler: (err: Error) => void): unknown;\n}\n\nexport interface CreateRedisOptions {\n /** Override `process.env.REDIS_URL` for tests. */\n url?: string;\n /** Logging label, e.g. `'quote-cache'` / `'rate-limit'` / `'pi-cache'`. */\n label: string;\n /** Connect timeout in ms. Default `3000`. */\n connectTimeout?: number;\n /** Per-request retry cap. Default `1`. */\n maxRetriesPerRequest?: number;\n}\n\n/** Lazy-import ioredis and construct a client. Returns null when:\n * - no URL is configured (caller falls back to in-memory)\n * - `ioredis` isn't installed (optional peer; caller falls back to in-memory)\n * - the import throws for any other reason\n *\n * `rediss://` URLs auto-enable TLS. The error handler logs with the caller's\n * label so multi-cache deployments can tell which subsystem complained. */\nasync function tryCreateRedis<T extends MinimalRedis>(opts: CreateRedisOptions): Promise<T | null> {\n const url = opts.url ?? process.env.REDIS_URL;\n if (!url) return null;\n try {\n const mod = (await import('ioredis')) as unknown as { default: new (url: string, opts?: unknown) => T };\n const client = new mod.default(url, {\n connectTimeout: opts.connectTimeout ?? 3000,\n maxRetriesPerRequest: opts.maxRetriesPerRequest ?? 1,\n tls: url.startsWith('rediss://') ? {} : undefined,\n });\n client.on('error', (err) => console.error(`[${opts.label}] Redis error:`, err.message));\n return client;\n } catch {\n return null;\n }\n}\n\n/** Memoized-promise variant: call once per caller; subsequent calls return the\n * same promise. Pairs with the pattern `let p: Promise<T|null> | null = null;\n * const getRedis = () => (p ??= tryCreateRedis(...))` in callers that want\n * per-call promise caching without managing the closure themselves. */\nexport function memoizedRedis<T extends MinimalRedis>(opts: CreateRedisOptions): () => Promise<T | null> {\n let promise: Promise<T | null> | null = null;\n return () => {\n if (!promise) promise = tryCreateRedis<T>(opts);\n return promise;\n };\n}\n","import { memoizedRedis, type MinimalRedis } from '../_redis';\n\nexport interface RateLimitCoreOptions {\n windowSeconds?: number;\n maxRequests?: number;\n /** Redis connection URL. Default: `process.env.REDIS_URL`. Falls back to in-memory when unset or the lazy `ioredis` import fails. */\n redisUrl?: string;\n /** Per-instance key prefix so multiple limiters sharing a Redis don't collide. */\n keyPrefix?: string;\n}\n\nexport interface RateLimitDecision {\n allowed: boolean;\n remaining: number;\n limit: number;\n}\n\nexport interface RateLimiter {\n check(key: string): Promise<RateLimitDecision>;\n}\n\ninterface RedisLike extends MinimalRedis {\n incr(key: string): Promise<number>;\n expire(key: string, seconds: number): Promise<unknown>;\n}\n\n/** Framework-agnostic rate limiter. Hono / Express / Fastify / Next.js / Web adapters\n * share one core. Each `createRateLimiter` call owns its own memory map + redis\n * connection, so multiple instances in the same process don't share state unless\n * they share a Redis with the same `keyPrefix`. */\nexport function createRateLimiter(opts: RateLimitCoreOptions = {}): RateLimiter {\n const windowSeconds = opts.windowSeconds ?? 60;\n const maxRequests = opts.maxRequests ?? 60;\n const keyPrefix = opts.keyPrefix ?? 'rl:';\n\n const memMap = new Map<string, { count: number; resetAt: number }>();\n const getRedis = memoizedRedis<RedisLike>({ url: opts.redisUrl, label: 'rate-limit' });\n\n const checkMem = (key: string): RateLimitDecision => {\n const now = Date.now();\n const entry = memMap.get(key);\n if (!entry || entry.resetAt < now) {\n memMap.set(key, { count: 1, resetAt: now + windowSeconds * 1000 });\n return { allowed: true, remaining: maxRequests - 1, limit: maxRequests };\n }\n entry.count++;\n const remaining = Math.max(0, maxRequests - entry.count);\n return { allowed: entry.count <= maxRequests, remaining, limit: maxRequests };\n };\n\n return {\n async check(key: string): Promise<RateLimitDecision> {\n const r = await getRedis();\n if (!r) return checkMem(key);\n try {\n const fullKey = `${keyPrefix}${key}`;\n const count = await r.incr(fullKey);\n if (count === 1) await r.expire(fullKey, windowSeconds);\n const remaining = Math.max(0, maxRequests - count);\n return { allowed: count <= maxRequests, remaining, limit: maxRequests };\n } catch {\n return checkMem(key);\n }\n },\n };\n}\n\nexport const RATE_LIMIT_JSON_BODY = {\n error: { code: 'rate_limited', message: 'Too many requests' },\n} as const;\n\n/** Default key resolver: first hop of `x-forwarded-for`, else `'unknown'`. Works on any\n * framework's request once you adapt the header read. */\nexport function defaultKeyFromForwardedFor(forwardedFor: string | null | undefined): string {\n if (!forwardedFor) return 'unknown';\n return forwardedFor.split(',')[0]?.trim() || 'unknown';\n}\n","import {\n RATE_LIMIT_JSON_BODY,\n createRateLimiter,\n defaultKeyFromForwardedFor,\n type RateLimitCoreOptions,\n} from './_core';\n\nexport interface RateLimitWebOptions extends RateLimitCoreOptions {\n /** Bucket key resolver. Default: first hop of `x-forwarded-for`, else `'unknown'`. */\n keyResolver?: (req: Request) => string;\n}\n\nexport type RateLimitGuardResult =\n | { allowed: true; remaining: number; limit: number; response?: undefined }\n | { allowed: false; remaining: number; limit: number; response: Response };\n\nexport type RateLimitGuard = (req: Request) => Promise<RateLimitGuardResult>;\n\n/**\n * Build a rate-limit guard for Web Fetch–style handlers. Call `guard(req)` at the top\n * of your route. When `allowed === false`, return `result.response` directly.\n */\nexport function createRateLimit(opts: RateLimitWebOptions = {}): RateLimitGuard {\n const limiter = createRateLimiter(opts);\n const keyResolver =\n opts.keyResolver ?? ((req: Request) => defaultKeyFromForwardedFor(req.headers.get('x-forwarded-for')));\n\n return async (req: Request) => {\n const { allowed, remaining, limit } = await limiter.check(keyResolver(req));\n const baseHeaders = {\n 'X-RateLimit-Limit': String(limit),\n 'X-RateLimit-Remaining': String(remaining),\n };\n if (!allowed) {\n const response = new Response(JSON.stringify(RATE_LIMIT_JSON_BODY), {\n status: 429,\n headers: { ...baseHeaders, 'Content-Type': 'application/json', 'Cache-Control': 'no-store' },\n });\n return { allowed: false, remaining, limit, response };\n }\n return { allowed: true, remaining, limit };\n };\n}\n"],"mappings":";AAoCA,eAAe,eAAuC,MAA6C;AACjG,QAAM,MAAM,KAAK,OAAO,QAAQ,IAAI;AACpC,MAAI,CAAC,IAAK,QAAO;AACjB,MAAI;AACF,UAAM,MAAO,MAAM,OAAO,SAAS;AACnC,UAAM,SAAS,IAAI,IAAI,QAAQ,KAAK;AAAA,MAClC,gBAAgB,KAAK,kBAAkB;AAAA,MACvC,sBAAsB,KAAK,wBAAwB;AAAA,MACnD,KAAK,IAAI,WAAW,WAAW,IAAI,CAAC,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,SAAS,aAAa;AACtD,cAAM,YAAY,KAAK,IAAI,GAAG,cAAc,KAAK;AACjD,eAAO,EAAE,SAAS,SAAS,aAAa,WAAW,OAAO,YAAY;AAAA,MACxE,QAAQ;AACN,eAAO,SAAS,GAAG;AAAA,MACrB;AAAA,IACF;AAAA,EACF;AACF;AAEO,IAAM,uBAAuB;AAAA,EAClC,OAAO,EAAE,MAAM,gBAAgB,SAAS,oBAAoB;AAC9D;AAIO,SAAS,2BAA2B,cAAiD;AAC1F,MAAI,CAAC,aAAc,QAAO;AAC1B,SAAO,aAAa,MAAM,GAAG,EAAE,CAAC,GAAG,KAAK,KAAK;AAC/C;;;ACtDO,SAAS,gBAAgB,OAA4B,CAAC,GAAmB;AAC9E,QAAM,UAAU,kBAAkB,IAAI;AACtC,QAAM,cACJ,KAAK,gBAAgB,CAAC,QAAiB,2BAA2B,IAAI,QAAQ,IAAI,iBAAiB,CAAC;AAEtG,SAAO,OAAO,QAAiB;AAC7B,UAAM,EAAE,SAAS,WAAW,MAAM,IAAI,MAAM,QAAQ,MAAM,YAAY,GAAG,CAAC;AAC1E,UAAM,cAAc;AAAA,MAClB,qBAAqB,OAAO,KAAK;AAAA,MACjC,yBAAyB,OAAO,SAAS;AAAA,IAC3C;AACA,QAAI,CAAC,SAAS;AACZ,YAAM,WAAW,IAAI,SAAS,KAAK,UAAU,oBAAoB,GAAG;AAAA,QAClE,QAAQ;AAAA,QACR,SAAS,EAAE,GAAG,aAAa,gBAAgB,oBAAoB,iBAAiB,WAAW;AAAA,MAC7F,CAAC;AACD,aAAO,EAAE,SAAS,OAAO,WAAW,OAAO,SAAS;AAAA,IACtD;AACA,WAAO,EAAE,SAAS,MAAM,WAAW,MAAM;AAAA,EAC3C;AACF;","names":[]}
1
+ {"version":3,"sources":["../../src/_redis.ts","../../src/middleware/_core.ts","../../src/middleware/web.ts"],"sourcesContent":["/** Shared lazy `ioredis` factory. Used by `quote_cache`, `middleware/_core`,\n * and `stripe-multichain/pi-cache` so they don't drift on connect-timeout,\n * TLS handling, or error-logging posture.\n *\n * `ioredis` is an optional peer dep — callers pass `redisUrl` (or rely on\n * `process.env.REDIS_URL`); when unset or the lazy import fails, this returns\n * null and the caller falls back to its in-process `Map`.\n *\n * Not part of the public API.\n */\n\n/** Minimal Redis surface — each caller intersects with its own usage\n * (incr/expire for rate-limit, get/set/del for caches). Returning `unknown`\n * on commands keeps the shape narrow; cast at the call site. */\nexport interface MinimalRedis {\n on(event: 'error', handler: (err: Error) => void): unknown;\n}\n\nexport interface CreateRedisOptions {\n /** Override `process.env.REDIS_URL` for tests. */\n url?: string;\n /** Logging label, e.g. `'quote-cache'` / `'rate-limit'` / `'pi-cache'`. */\n label: string;\n /** Connect timeout in ms. Default `3000`. */\n connectTimeout?: number;\n /** Per-request retry cap. Default `1`. */\n maxRetriesPerRequest?: number;\n}\n\n/** Lazy-import ioredis and construct a client. Returns null when:\n * - no URL is configured (caller falls back to in-memory)\n * - `ioredis` isn't installed (optional peer; caller falls back to in-memory)\n * - the import throws for any other reason\n *\n * `rediss://` URLs auto-enable TLS. The error handler logs with the caller's\n * label so multi-cache deployments can tell which subsystem complained. */\nasync function tryCreateRedis<T extends MinimalRedis>(opts: CreateRedisOptions): Promise<T | null> {\n const url = opts.url ?? process.env.REDIS_URL;\n if (!url) return null;\n try {\n const mod = (await import('ioredis')) as unknown as { default: new (url: string, opts?: unknown) => T };\n const client = new mod.default(url, {\n connectTimeout: opts.connectTimeout ?? 3000,\n maxRetriesPerRequest: opts.maxRetriesPerRequest ?? 1,\n tls: url.startsWith('rediss://') ? {} : undefined,\n });\n client.on('error', (err) => console.error(`[${opts.label}] Redis error:`, err.message));\n return client;\n } catch {\n return null;\n }\n}\n\n/** Memoized-promise variant: call once per caller; subsequent calls return the\n * same promise. Pairs with the pattern `let p: Promise<T|null> | null = null;\n * const getRedis = () => (p ??= tryCreateRedis(...))` in callers that want\n * per-call promise caching without managing the closure themselves. */\nexport function memoizedRedis<T extends MinimalRedis>(opts: CreateRedisOptions): () => Promise<T | null> {\n let promise: Promise<T | null> | null = null;\n return () => {\n if (!promise) promise = tryCreateRedis<T>(opts);\n return promise;\n };\n}\n","import { memoizedRedis, type MinimalRedis } from '../_redis';\n\nexport interface RateLimitCoreOptions {\n windowSeconds?: number;\n maxRequests?: number;\n /** Redis connection URL. Default: `process.env.REDIS_URL`. Falls back to in-memory when unset or the lazy `ioredis` import fails. */\n redisUrl?: string;\n /** Per-instance key prefix so multiple limiters sharing a Redis don't collide. */\n keyPrefix?: string;\n}\n\ninterface RateLimitDecision {\n allowed: boolean;\n remaining: number;\n limit: number;\n}\n\nexport interface RateLimiter {\n check(key: string): Promise<RateLimitDecision>;\n}\n\ninterface RedisLike extends MinimalRedis {\n incr(key: string): Promise<number>;\n expire(key: string, seconds: number): Promise<unknown>;\n}\n\n/** Framework-agnostic rate limiter. Hono / Express / Fastify / Next.js / Web adapters\n * share one core. Each `createRateLimiter` call owns its own memory map + redis\n * connection, so multiple instances in the same process don't share state unless\n * they share a Redis with the same `keyPrefix`. */\nexport function createRateLimiter(opts: RateLimitCoreOptions = {}): RateLimiter {\n const windowSeconds = opts.windowSeconds ?? 60;\n const maxRequests = opts.maxRequests ?? 60;\n const keyPrefix = opts.keyPrefix ?? 'rl:';\n\n const memMap = new Map<string, { count: number; resetAt: number }>();\n const getRedis = memoizedRedis<RedisLike>({ url: opts.redisUrl, label: 'rate-limit' });\n\n const checkMem = (key: string): RateLimitDecision => {\n const now = Date.now();\n const entry = memMap.get(key);\n if (!entry || entry.resetAt < now) {\n memMap.set(key, { count: 1, resetAt: now + windowSeconds * 1000 });\n return { allowed: true, remaining: maxRequests - 1, limit: maxRequests };\n }\n entry.count++;\n const remaining = Math.max(0, maxRequests - entry.count);\n return { allowed: entry.count <= maxRequests, remaining, limit: maxRequests };\n };\n\n return {\n async check(key: string): Promise<RateLimitDecision> {\n const r = await getRedis();\n if (!r) return checkMem(key);\n try {\n const fullKey = `${keyPrefix}${key}`;\n const count = await r.incr(fullKey);\n if (count === 1) await r.expire(fullKey, windowSeconds);\n const remaining = Math.max(0, maxRequests - count);\n return { allowed: count <= maxRequests, remaining, limit: maxRequests };\n } catch {\n return checkMem(key);\n }\n },\n };\n}\n\nexport const RATE_LIMIT_JSON_BODY = {\n error: { code: 'rate_limited', message: 'Too many requests' },\n} as const;\n\n/** Default key resolver: first hop of `x-forwarded-for`, else `'unknown'`. Works on any\n * framework's request once you adapt the header read. */\nexport function defaultKeyFromForwardedFor(forwardedFor: string | null | undefined): string {\n if (!forwardedFor) return 'unknown';\n return forwardedFor.split(',')[0]?.trim() || 'unknown';\n}\n","import {\n RATE_LIMIT_JSON_BODY,\n createRateLimiter,\n defaultKeyFromForwardedFor,\n type RateLimitCoreOptions,\n} from './_core';\n\nexport interface RateLimitWebOptions extends RateLimitCoreOptions {\n /** Bucket key resolver. Default: first hop of `x-forwarded-for`, else `'unknown'`. */\n keyResolver?: (req: Request) => string;\n}\n\nexport type RateLimitGuardResult =\n | { allowed: true; remaining: number; limit: number; response?: undefined }\n | { allowed: false; remaining: number; limit: number; response: Response };\n\nexport type RateLimitGuard = (req: Request) => Promise<RateLimitGuardResult>;\n\n/**\n * Build a rate-limit guard for Web Fetch–style handlers. Call `guard(req)` at the top\n * of your route. When `allowed === false`, return `result.response` directly.\n */\nexport function createRateLimit(opts: RateLimitWebOptions = {}): RateLimitGuard {\n const limiter = createRateLimiter(opts);\n const keyResolver =\n opts.keyResolver ?? ((req: Request) => defaultKeyFromForwardedFor(req.headers.get('x-forwarded-for')));\n\n return async (req: Request) => {\n const { allowed, remaining, limit } = await limiter.check(keyResolver(req));\n const baseHeaders = {\n 'X-RateLimit-Limit': String(limit),\n 'X-RateLimit-Remaining': String(remaining),\n };\n if (!allowed) {\n const response = new Response(JSON.stringify(RATE_LIMIT_JSON_BODY), {\n status: 429,\n headers: { ...baseHeaders, 'Content-Type': 'application/json', 'Cache-Control': 'no-store' },\n });\n return { allowed: false, remaining, limit, response };\n }\n return { allowed: true, remaining,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G,aAAa,gBAAgB,oBAAoB,iBAAiB,WAAW;AAAA,MAC7F,CAAC;AACD,aAAO,EAAE,SAAS,OAAO,WAAW,OAAO,SAAS;AAAA,IACtD;AACA,WAAO,EAAE,SAAS,MAAM,WAAW,MAAM;AAAA,EAC3C;AACF;","names":[]}
@@ -5,7 +5,7 @@ export { B as BuildX402AcceptsForOptions, C as CreateX402ServerOptions, X as X40
5
5
  export { a as aliasAmountFields, p as paymentRequiredHeader, w as wwwAuthenticateHeader } from '../wwwauthenticate-D_FMnPgU.mjs';
6
6
  import { S as SignerNetwork } from '../signer-3FAit11j.mjs';
7
7
  export { P as PaymentSigner, e as extractPaymentSigner, a as extractPaymentSignerFromAuth, b as extractSignerForPrecheck, r as readX402PaymentHeader } from '../signer-3FAit11j.mjs';
8
- export { B as BuildDefaultCheckoutRailsOptions, a as BuildMppxComposeRailsOptions, H as HeadersLike, b as asHeaders, c as buildDefaultCheckoutRails, d as buildMppxComposeRails, f as formatUsdCents, h as hasMppxHeader, e as hasPaymentHeader, g as hasX402Header, l as loadSolanaFeePayer, r as readHeader, u as usdToAtomic } from '../default_rails-BWAquZeu.mjs';
8
+ export { B as BuildDefaultCheckoutRailsOptions, a as BuildMppxComposeRailsOptions, H as HeadersLike, b as asHeaders, c as buildDefaultCheckoutRails, d as buildMppxComposeRails, f as formatUsdCents, h as hasMppxHeader, e as hasPaymentHeader, g as hasX402Header, l as loadSolanaFeePayer, r as readHeader, u as usdToAtomic } from '../default_rails-XFCuRddA.mjs';
9
9
 
10
10
  /**
11
11
  * Build the base64-encoded `request` blob for an MPP Payment directive (per the
@@ -569,21 +569,17 @@ type MppxComposeResult = {
569
569
  challenge: Response;
570
570
  [k: string]: unknown;
571
571
  };
572
- /**
573
- * Run `mppx.compose(...intents)(request)` with a typed return. Replaces the
574
- * `(mppx as any).compose(...intents)(request)` cast every hand-rolled
575
- * `composeMppx` hook ends up writing.
576
- *
577
- * @example
578
- * ```ts
579
- * const result = await composeMppxRequest(mppx, [
580
- * ['tempo/charge', { amount, currency, decimals, recipient }],
581
- * ['stripe/charge', { amount, currency: 'usd', decimals: 2 }],
582
- * ], ctx.request.raw);
583
- * if (result.status === 402) return { status: 402, headers: mppxChallengeHeaders(result) };
584
- * return { status: 200, raw: result };
585
- * ```
586
- */
572
+ /** Run `fn` inside an async context that captures the inner mppx
573
+ * verification error (when one fires). Returns the function's result
574
+ * plus the captured `failureReason` string (null if no error fired or
575
+ * no console.error hit during this scope). Used by `Checkout.handleMppx`
576
+ * to surface typed error codes (`tempo_key_not_registered`, etc.) on
577
+ * the 402 path without changing the per-merchant `composeMppx` API.
578
+ */
579
+ declare function runWithMppxFailureCapture<T>(fn: () => Promise<T>): Promise<{
580
+ result: T;
581
+ failureReason: string | null;
582
+ }>;
587
583
  declare function composeMppxRequest(mppx: unknown, intents: readonly unknown[], request: Request): Promise<MppxComposeResult>;
588
584
  /**
589
585
  * Extract the 402 challenge response's headers as a plain `Record<string, string>`,
@@ -894,4 +890,4 @@ declare function isEvmNetwork(input: NetworkLike): boolean;
894
890
  * network spec — this helper treats it as false. */
895
891
  declare function isSolanaNetwork(input: NetworkLike): boolean;
896
892
 
897
- export { type ClassifiedX402Error, type MppxComposeResult, type MppxRailSpec, type NetworkFamily, type PaymentHeadersRail, type PaymentHeadersResult, type ProcessX402SettleResult, type RailDefinition, type RailName, SETTLEMENT_OVERRIDES_HEADER, type SettlementHandlers, type SettlementOverrides, type SettlementPayloadLike, SignerNetwork, SolanaMppRailSpec, StripeRailSpec, TempoRailSpec, TempoSessionRailSpec, USDC, type VerifyX402RequestResult, X402BaseRailSpec, X402Server, type X402ServerLike, X402_SUPPORTED_BASE_NETWORKS, type ZeroSettleRail, type ZeroSettleResult, buildIdempotencyKey, buildPaymentDirective, buildPaymentHeaders, buildPaymentRequestBlob, classifyOrchestrationError, classifyX402SettleResult, composeMppxRequest, createMppxServer, detectRailFromHeaders, dispatchSettlementByNetwork, isEvmNetwork, isSolanaNetwork, lazyMppxServer, lazyX402Server, lookupRail, mppxChallengeHeaders, networkFamily, networks, paymentDirective, processX402Settle, rails, registerX402SchemesV1V2, settlementOverrideHeader, validateX402NetworkConfig, verifyX402Request, wrapSolanaChargeWithFinalizedBlockhash, zeroAmountCarveOut };
893
+ export { type ClassifiedX402Error, type MppxComposeResult, type MppxRailSpec, type NetworkFamily, type PaymentHeadersRail, type PaymentHeadersResult, type ProcessX402SettleResult, type RailDefinition, type RailName, SETTLEMENT_OVERRIDES_HEADER, type SettlementHandlers, type SettlementOverrides, type SettlementPayloadLike, SignerNetwork, SolanaMppRailSpec, StripeRailSpec, TempoRailSpec, TempoSessionRailSpec, USDC, type VerifyX402RequestResult, X402BaseRailSpec, X402Server, type X402ServerLike, X402_SUPPORTED_BASE_NETWORKS, type ZeroSettleRail, type ZeroSettleResult, buildIdempotencyKey, buildPaymentDirective, buildPaymentHeaders, buildPaymentRequestBlob, classifyOrchestrationError, classifyX402SettleResult, composeMppxRequest, createMppxServer, detectRailFromHeaders, dispatchSettlementByNetwork, isEvmNetwork, isSolanaNetwork, lazyMppxServer, lazyX402Server, lookupRail, mppxChallengeHeaders, networkFamily, networks, paymentDirective, processX402Settle, rails, registerX402SchemesV1V2, runWithMppxFailureCapture, settlementOverrideHeader, validateX402NetworkConfig, verifyX402Request, wrapSolanaChargeWithFinalizedBlockhash, zeroAmountCarveOut };