import { IRateLimiterOptions, RateLimiterAbstract, RateLimiterQueue } from "rate-limiter-flexible"; import { ClosedError, MotionError, MotionFetchError, UnsafeFetchError } from "./error.js"; /** Motion API client. * * @remarks * * Simple wrapper around the usemotion.com API. Just provide a user ID * and API key, and then start making requests. * * Warning: Motion {@link https://docs.usemotion.com/docs/motion-rest-api/44e37c461ba67-motion-rest-api#rate-limit-information | enforces} * its rate limit strictly. Excessive overruns of the rate limit can * result in losing your API privileges and having to get them back * through customer support. * * This client will not exceed the rate limit so long as only one * instance makes requests to the Motion API for any one user and no * calls are made directly to any of the `unsafe_` methods. If you * require more advanced usage, you can pass a custom rate limiter. * * @public */ export declare class Motion { /** {@inheritDoc MotionOptions.userId} */ readonly userId: string | null; /** {@inheritDoc MotionOptions.apiKey} */ private readonly apiKey; /** {@inheritDoc MotionOptions.baseUrl} */ readonly baseUrl: string; /** Request queue. */ readonly requestQueue: RateLimiterQueue; /** {@inheritDoc MotionOptions.requestLimiter} */ readonly requestLimiter: RateLimiterAbstract; /** {@inheritDoc MotionOptions.overrunLimiter}*/ readonly overrunLimiter: RateLimiterAbstract; /** Rate limiter key where requests are tracked. */ readonly requestLimiterKey: string; /** Rate limiter key where overruns are tracked. */ readonly overrunLimiterKey: string; private _closedReason; /** Create a Motion API client. * * @remarks * Initializes a Motion API client with the provided user ID and API key. * Consult the {@link https://help.usemotion.com/integrations/integrations-101/api-docs | Motion API docs} for how to get an API key. * * If there may be multiple `Motion` clients sharing the same user, * you must pass a custom request rate limiter and a custom overrun * rate limiter that share the same backing store as the other * `Motion` clients. * * You may adjust the maximum number of queued requests; the * default is {@link defaultQueueSize}. * * `motion-sdk` does not throw. If the constructor is called with * invalid arguments or if another error occurs, the client will be * closed immediately. The error will be set in * {@link Motion.closedReason | closedReason}. * * @example * Basic usage: * ```typescript * const motion = new Motion({ * userId: 'my-user-id', * apiKey: 'my-api-key', * }); * ``` * * @example * Or, you can set the environment variables `MOTION_USER_ID` and * `MOTION_API_KEY`. Then: * ```typescript * const motion = new Motion(); * ``` * * @example * To set custom rate limiters: * * ```typescript * // 1 request per 5 seconds * const requestLimiter = new RateLimiterMemory({ * points: 1, * duration: 5, // seconds * }); * // 2 overruns per day * const overrunLimiter = new RateLimiterMemory({ * points: 2, * duration: 60 * 60 * 24, * }); * const motion = new Motion({ * requestLimiter, * overrunLimiter, * maxQueueSize: 0, // Disable queue * }); * await motion.fetch("/users/me"); * ``` * * The requestLimiter and overrunLimiter must be instances of the * {@link https://github.com/animir/node-rate-limiter-flexible/blob/master/lib/RateLimiterAbstract.js | RateLimiterAbstract} * class from {@link https://www.npmjs.com/package/rate-limiter-flexible | rate-limiter-flexible}. * * As of this writing, `rate-limiter-flexible` provides rate limiters * backed by Redis, Prisma, DynamoDB, process Memory, Cluster or PM2, * Memcached, MongoDB, MySQL, and PostgreSQL. Refer to their * documentation for more detailed help. * * The default limiter is * {@link https://github.com/animir/node-rate-limiter-flexible/blob/master/lib/RateLimiterMemory.js | RateLimiterMemory} * with the limits from {@link recommendedRateLimits}. The maximum * queue size is given by {@link defaultQueueSize}. * * @param opts - Object with client parameters * * @public */ constructor(opts?: MotionOptions); /** Safe entry point to the HTTP layer. * * @remarks * This function makes an HTTP request to the Motion API. The request * and return values are the same as the platform * {@link https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API | fetch()}, * except some logic is added for authentication and session management. * If a string is passed as the request URL, the API's base URL will * be prepended. * * This method enforces a client-side rate limit so as not to exceed * Motion's API rate limits. If there have been too many recent * requests, the request will be queued up to the client's maximum * queue size. An error will be returned if the queue is overflowing * or if there is an issue with the rate limit. * * In the event the request limiter is misconfigured and Motion returns * a 429 Limit Exceeded response, `fetch` assumes the client has * entered an unsafe state. The client will close immediately and make * no further requests. The overrun will be recorded with the overrun * limiter. * * @example * A basic example: * ```typescript * const response = await motion.fetch("/users/me"); * if (!isMotionError(response) && response.ok) { * const json = await response.json(); * console.log(JSON.stringify(json)); * // {"id":"elp69uRwOplFSiM3llAGhixqmPTP","name":"Bill Lumbergh","email":"blumbergh@initech.com"} * } * ``` * * @param input - URL or Request object * @param init - Request parameters * @returns {@link https://developer.mozilla.org/en-US/docs/Web/API/Response | Response} or a {@link MotionFetchError} */ fetch(input: string | URL | globalThis.Request, init?: RequestInit): Promise; /** Status of the client. * * @returns `true` if the client initialized successfully and can * still be used to make requests. * */ isOpen(): boolean; /** Reason the client was closed, if any. */ get closedReason(): ClosedReason | null; /** Terminate the client and free any associated resources. * * @remarks * After calling, it will be impossible to make requests to Motion under most * circumstances. Some `unsafe_` methods will continue to work. * * @param reason - Developer-readable explanation for the closure. * @param cause - Error that precipitated the closure, if any. */ close(reason: string, cause?: MotionError): undefined | ClosedError; /** Low-level interface to the Motion API. * * @remarks * This function makes a call to the Motion API. The request and * return values are the same as the platform * {@link https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API | fetch()}, * except some logic is added for authentication and session management. * If a string is passed as the request URL, the API's base URL will * be prepended. * * `unsafe_fetch` does not respect rate limiting or anything else about * the client's state. It can be called and will happily make requests * to the Motion API even if the limit is already exceeded and even if * {@link Motion.close | close} has been called. It will _not_ update * the internal rate limiter, even if Motion reports a rate limit overrun. * * Normally this function should be called only from * {@link Motion.fetch}, but it is exposed to accommodate performance * optimizations by advanced users. Use at your own peril. * * @param input - URL or Request object. * @param init - Request parameters. * * @returns {@link https://developer.mozilla.org/en-US/docs/Web/API/Response | Response} or an {@link UnsafeFetchError} */ unsafe_fetch(input: string | URL | globalThis.Request, init?: RequestInit): Promise; private handleLimitExceeded; private setHeaders; private waitForTurn; } /** Arguments to the {@link Motion} constructor. * @public * */ export interface MotionOptions { /** Base URL of the API. * * @remarks * Base URL the client should target. Useful to override in development. * * Motion provides a mock API at {@link motionMockBaseUrl}. * * @defaultValue * The constructor uses the following URLs in order of precedence: * 1. The URL set explicitly in the `MotionOptions` object. * 2. Value of {@link motionBaseUrl}. * */ baseUrl?: string; /** ID of the Motion user making the requests. * * @defaultValue This can instead be set with an environment variable, * `process.env.MOTION_USER_ID`. * */ userId?: string; /** API key for the requests. * * @defaultValue This can instead be set with an environment variable, * `process.env.MOTION_API_KEY`. * */ apiKey?: string; /** Rate limiter that tracks number of requests. * * @remarks * The default rate limiter will suffice for non-concurrent usage patterns. * If you are using multiple {@link Motion} objects with the same user ID, * make sure each client has the same limiter. * * See {@link https://github.com/animir/node-rate-limiter-flexible?tab=readme-ov-file#docs-and-examples | rate-limiter-flexible}. * * @defaultValue {@link https://github.com/animir/node-rate-limiter-flexible/wiki/Memory | RateLimiterMemory} with the {@link recommendedRateLimits | recommended} rate limit. */ requestLimiter?: RateLimiterAbstract; /** Rate limiter that tracks how many times we've exceeded the limit recently. * * @remarks * The default rate limiter will suffice for non-concurrent usage patterns. * If you are using multiple {@link Motion} objects with the same user ID, * make sure each client has the same limiter and uses the same key. * * An "overrun" refers an instance of exceeding Motion's maximum number * of requests per minute and receiving a 429 Limit Exceeded response. * Too many overruns results in automatic and permanent lockout. * * See {@link https://github.com/animir/node-rate-limiter-flexible?tab=readme-ov-file#docs-and-examples | rate-limiter-flexible}. * * @defaultValue {@link https://github.com/animir/node-rate-limiter-flexible/wiki/Memory | RateLimiterMemory} with the {@link recommendedRateLimits | recommended} rate limit. */ overrunLimiter?: RateLimiterAbstract; /** Maximum number of queued requests. */ maxQueueSize?: number; } /** Rate limit information about the Motion API. * * @remarks * Motion has two rate limits: * * - If you exceed 12 requests in a minute, Motion will return 429 * Limit Exceeded and disable your API access for an hour. * `motion-sdk` calls that an 'overrun'. * - If you have three overruns in a day, Motion will disable your * API access until you contact support and ask them to restore it. * * `motion-sdk` is an _unofficial_ client and its authors are not * affiliated with Motion. Always consult the * {@link https://docs.usemotion.com/docs/motion-rest-api/44e37c461ba67-motion-rest-api#rate-limit-information | official API reference } * for up-to-date rate limit information. * * @public * */ export interface MotionRateLimits { /** Rate limiter parameters for requests. */ requests: Required>; /** Rate limiter parameters for overruns. */ overruns: Required>; } /** End-of-life information on a {@link Motion} client. * * @public */ export interface ClosedReason { /** Brief, developer-readable explanation for the closure. */ reason: string; /** Error that caused the client to closed, if any. */ cause?: MotionError; } export default Motion; //# sourceMappingURL=motion.d.ts.map