{"version":3,"file":"useRateLimit.cjs","sources":["../../src/useRateLimit.ts"],"sourcesContent":["import {\n  InternalServerError,\n  NextFunc,\n  Props,\n  RateLimitError,\n  Response,\n  response\n} from '@exobase/core'\nimport type { Duration } from 'durhuman'\nimport dur from 'durhuman'\nimport { isFunction, tryit } from 'radash'\n\nexport interface IRateLimitStore {\n  /**\n   * A function that should incrament the currently stored\n   * number of requests in the current window and return\n   * both the total number of requests made in the current\n   * window and the beginning timestamp of the window.\n   */\n  inc: (key: string) => Promise<{\n    count: number\n    timestamp: number\n  }>\n  reset: (key: string) => Promise<void>\n}\n\nexport interface IRateLimitLogger {\n  log: (...args: any[]) => void\n  warn: (...args: any[]) => void\n  error: (...args: any[]) => void\n}\n\nexport type UseRateLimitLimit = {\n  /**\n   * Time to live: The amount of time before we should consider an\n   * item in the cache to be fresh. The hook will ignore an item in\n   * the cache if the TTL has passed.\n   */\n  window: Duration\n  /**\n   * The maximum number of requests allowed for a single identity\n   * during the window.\n   */\n  max: number\n}\n\nexport type UseRateLimitOption<TProps extends Props = Props> = {\n  /**\n   * A string unique to the items you are using this hook to cache.\n   * You'll likely want to use a unique key in every endpoint\n   */\n  key: string\n  limit:\n    | UseRateLimitLimit\n    | ((props: TProps) => UseRateLimitLimit | Promise<UseRateLimitLimit>)\n  /**\n   * A mapping function to convert the args into an object that should\n   * be used to generate the cache key.\n   */\n  toIdentity: (props: TProps) => string\n  /**\n   * If passed, the hook will log information about the caching using\n   * this object. If nothing is passed the hook will be silent.\n   */\n  logger?: IRateLimitLogger\n  /**\n   * An optional function telling the rate limit hook\n   * where to get the store object.\n   */\n  store?:\n    | IRateLimitStore\n    | ((props: TProps) => IRateLimitStore | Promise<IRateLimitStore>)\n  /**\n   * Strict tells the rate limit hook if it should return an error\n   * to the user when an error is thrown while interacting with\n   * the store. If strict is false, errors will be ignored and the\n   * will be called.\n   */\n  strict?: boolean\n}\n\nexport async function withRateLimiting<TProps extends Props>(\n  func: NextFunc<TProps>,\n  {\n    key: prefix,\n    limit: limitFn,\n    toIdentity,\n    logger,\n    strict = true,\n    store: storeFn\n  }: UseRateLimitOption<TProps>,\n  props: TProps\n) {\n  const key = `${prefix}.${toIdentity(props)}`\n  const services = props.services as { store?: IRateLimitStore }\n  if (!storeFn && !services.store) {\n    logger?.error(\n      '[useRateLimit] Misconfigured, a store must be passed either in the services or options',\n      {\n        options: { store: storeFn },\n        services: { store: services.store }\n      }\n    )\n    throw new InternalServerError(\n      'useRateLimit hook requires a store to persist activity',\n      {\n        key: 'exo.rate-limit.misconfig'\n      }\n    )\n  }\n  const limit = await Promise.resolve(\n    isFunction(limitFn) ? limitFn(props) : limitFn\n  )\n  const store = await Promise.resolve(\n    storeFn ? (isFunction(storeFn) ? storeFn(props) : storeFn) : services.store!\n  )\n  const [err, record] = await tryit(store.inc)(key)\n  if (err) {\n    logger?.error('[useRateLimit] Error on store.inc', { err, key })\n    if (strict === false) return await func(props)\n    throw new InternalServerError(\n      'useRateLimit store threw an error while executing incrament operation',\n      {\n        key: 'exo.rate-limit.misconfig',\n        cause: err\n      }\n    )\n  }\n  if (!record) {\n    logger?.error('[useRateLimit] Store.inc returned nothing', { key })\n    if (strict === false) return await func(props)\n    throw new InternalServerError(\n      'useRateLimit did not return a valid record',\n      {\n        key: 'exo.rate-limit.misconfig'\n      }\n    )\n  }\n  const { count, timestamp } = record\n  const elapsed = Date.now() - timestamp\n  const windowHasPassed = elapsed > dur(limit.window, 'milliseconds')\n\n  const headers = {\n    'X-RateLimit-Limit': `${limit.max}`,\n    'X-RateLimit-Remaining': `${limit.max - count}`,\n    'X-RateLimit-Reset': `${dur(limit.window, 'milliseconds') - elapsed}`\n  }\n\n  if (windowHasPassed) {\n    await store.reset(key)\n  } else {\n    if (count > limit.max) {\n      logger?.log('[useRateLimit] Rate limit exceeded', {\n        key,\n        count,\n        timestamp,\n        max: limit.max,\n        window: limit.window\n      })\n      throw new RateLimitError('Too Many Requests', {\n        key: 'exo.rate-limit.exceeded'\n      })\n    }\n  }\n  const [error, result] = await tryit(func)(props)\n  const res = response(error, result)\n  const responseWithHeaders: Response = {\n    ...res,\n    headers: {\n      ...res.headers,\n      ...headers\n    }\n  }\n  return responseWithHeaders\n}\n\nexport const useRateLimit: <TProps extends Props>(\n  options: UseRateLimitOption<\n    TProps & {\n      services: {\n        store?: IRateLimitStore\n      }\n    }\n  >\n) => (\n  func: NextFunc<\n    Props<\n      {},\n      {\n        store?: IRateLimitStore\n      }\n    >\n  >\n) => NextFunc<TProps> = options => func => props =>\n  withRateLimiting(func, options, props)\n"],"names":["InternalServerError","isFunction","tryit","RateLimitError","response"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AAiFA,eAAsB,iBACpB,IACA,EAAA;AAAA,EACE,GAAK,EAAA,MAAA;AAAA,EACL,KAAO,EAAA,OAAA;AAAA,EACP,UAAA;AAAA,EACA,MAAA;AAAA,EACA,MAAS,GAAA,IAAA;AAAA,EACT,KAAO,EAAA,OAAA;AACT,CAAA,EACA,KACA,EAAA;AACA,EAAA,MAAM,GAAM,GAAA,CAAA,EAAG,MAAU,CAAA,CAAA,EAAA,UAAA,CAAW,KAAK,CAAA,CAAA,CAAA,CAAA;AACzC,EAAA,MAAM,WAAW,KAAM,CAAA,QAAA,CAAA;AACvB,EAAA,IAAI,CAAC,OAAA,IAAW,CAAC,QAAA,CAAS,KAAO,EAAA;AAC/B,IAAQ,MAAA,IAAA,IAAA,GAAA,KAAA,CAAA,GAAA,MAAA,CAAA,KAAA;AAAA,MACN,wFAAA;AAAA,MACA;AAAA,QACE,OAAA,EAAS,EAAE,KAAA,EAAO,OAAQ,EAAA;AAAA,QAC1B,QAAU,EAAA,EAAE,KAAO,EAAA,QAAA,CAAS,KAAM,EAAA;AAAA,OACpC;AAAA,KAAA,CAAA;AAEF,IAAA,MAAM,IAAIA,wBAAA;AAAA,MACR,wDAAA;AAAA,MACA;AAAA,QACE,GAAK,EAAA,0BAAA;AAAA,OACP;AAAA,KACF,CAAA;AAAA,GACF;AACA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