screeps-api
    Preparing search index...

    Class ScreepsHttpClient

    Provides access to the Screeps HTTP Http.

    Please note that the Screeps HTTP API is not technically a public API; it merely exists to power the game's official Steam and web clients. While the game's developers welcome its use, the implicit caveat is that the API is subject to change without warning.

    All endpoint methods are asynchronous.

    Some of endpoints behave differently on official servers (i.e. any server with the screeps.com hostname) than they do on unofficial/private servers. Any known discrepancies are documented on the relevant endpoint.

    Almost all endpoints require the user to be authenticated to use. Any known exceptions to this rule are documented.

    All endpoint methods are backed by req, which provides shared error handling logic, etc. If an endpoint does not have a corresponding method defined here, req may be called to access that endpoint directly (albeit without request parameter or response type annotations). Please consider submitting a PR to add functions for any missing endpoints!

    Instances should typically be initialized via ScreepsHttpClient.fromConfig, but the constructor can also be called directly if you prefer to handle loading the credentials and configuration options yourself.

    ScreepsSocketClient for the WebSocket API client (accessible via ScreepsHttpClient.socket)

    // To access the `GET /api/auth/me` endpoint:
    const me = await Http.authMe()

    Hierarchy

    • EventEmitter
      • ScreepsHttpClient
    Index

    Guides

    Endpoints: /

    Top-level API endpoints

    Endpoints: /auth

    Endpoints for authenticating to the server or checking authentication status

    Endpoints: /experimental

    Endpoints that are not yet considered stable. Their request parameters and response formats are subject to change without warning (even more so than the rest of the API), and they may not be available on all servers.

    Currently, all endpoints in this category are used to query for current/recent PVP activity.

    See the Endpoints: /warpath category for similar endpoints

    Endpoints: /game

    Endpoints used to read or modify game state

    Endpoints: /game/market

    Endpoints for reading or modifying the state of the in-game market

    Endpoints: /game/shards

    Endpoints: /leaderboard

    Endpoints for querying control/power leaderboards

    See the Endpoints: /scoreboard category for seasonal world competition leaderboards

    Endpoints: /register

    Endpoints for creating new user accounts

    Endpoints: /scoreboard

    Endpoints for querying scoreboard results

    This appears to only be relevant to seasonal world competitions/events.

    See also:

    • Endpoints: /seasons category: seasonal world metadata endpoints
    • Endpoints: /leaderboard category: for non-seasonal leaderboard endpoints

    Endpoints: /seasons

    Endpoints for seasonal world events. See the Endpoints: /scoreboard category for seasonal world scoreboard endpoints

    Endpoints: /servers

    Endpoints that provide information about other servers

    Endpoints: /user

    Endpoints for reading or modifying state about the authenticated user, or for looking up information on other users

    Endpoints: /user/code

    Endpoints for downloading or uploading code

    Endpoints: /user/decorations

    Endpoints for managing decorations

    Endpoints: /user/memory

    Endpoints for reading from or writing to Memory.

    Endpoints: /user/memory/segment

    Endpoints for reading from or writing to RawMemory.segments.

    Endpoints: /user/messages

    Endpoints for reading or managing in-game messages

    Endpoints: /warpath

    Endpoints for querying current/recent PVP activity by room.

    These may not be implemented on all servers. Most notably, they are not available on official servers, but the third-party service Voight-Kampff provides these and more for official servers and popular community servers.

    See the Endpoints: /experimental category for similar endpoints

    Other

    Endpoints: /

    • Fetch a chunk of history data for a single room.

      Official Endpoint: GET /room-history/${shard}/${room}/${tick}.json Unofficial Endpoint: GET /room-history

      Parameters

      • room: string

        Name of the room for which to fetch history

      • tick: number

        Tick for which history should be fetched

      • Optionalshard: string

        The name of the shard to use (ignored by unofficial servers). Defaults to ScreepsClientConfig.defaultShard if undefined.

      Returns Promise<ScreepsRoomHistoryResponse>

      Error if shard and ScreepsClientConfig.defaultShard are undefined while using an official server

      ScreepsApiError if history is unsupported or the requested chunk is missing

      • HTTP 500: this is an unofficial server that does not record room history
      • HTTP 404: the requested history chunk does not exist

      version returns the history chunk size to expect

    Endpoints: /auth

    • Authenticate to the server using email/password credentials.

      This authentication method has not worked on official servers since 2018, but it is still used for unofficial servers.

      Endpoint: POST /api/auth/signin

      Parameters

      • email: string

        The email address used for registration

      • password: string

        The password used for registration

      Returns Promise<AuthSigninResponse>

    • Authenticate via Steam SSO.

      Steam and Github SSO are the only permitted authentication methods on official servers.

      Endpoint: POST /api/auth/steam-ticket

      Parameters

      • ticket: unknown

        Do you know what this does? If so, please submit a PR!

      • useNativeAuth: boolean = false

        Do you know what this does? If so, please submit a PR!

      Returns Promise<ScreepsUnknownResponse>

    Endpoints: /experimental

    Endpoints: /game

    • Trigger an action on one or more objects.

      This endpoint is used for a variety of actions, depending on the name and intent parameters.

      Endpoint: POST /api/game/add-object-intent

      Parameters

      • _id: string

        the ID of the object that should perform the intent

      • room: string

        the name of the room the object is in

      • name: string

        name of the intent (ex: 'move')

      • Optionalintent: string

        JSON string describing the target(s) of the intent (for actions like 'heal' or 'build')

      • Optionalshard: string

        The name of the shard to use (ignored by unofficial servers). Defaults to ScreepsClientConfig.defaultShard if undefined.

      Returns Promise<ScreepsDbUpsertResponse>

      Error if shard and ScreepsClientConfig.defaultShard are undefined while using an official server

      remove flag: name = "remove", intent = {}
      
      destroy structure: _id = "room", name = "destroyStructure", intent = [ {id: <structure id>, roomName, <room name>, user: <user id>} ]
      can destroy multiple structures at once
      suicide creep: name = "suicide", intent = {id: <creep id>}
      
      unclaim controller: name = "unclaim", intent = {id: <controller id>}
      intent can be an empty object for suicide and unclaim, but the web interface sends the id in it, as described
      remove construction site: name = "remove", intent = {}
      
    • Check whether or not a flag name is in use.

      Checks all existing flags owned by the authenticated user on the specified shard for one with the specified name.

      Endpoint: POST /api/game/check-unique-flag-name

      Parameters

      • name: string

        The name to check

      • Optionalshard: string

        The name of the shard to use (ignored by unofficial servers). Defaults to ScreepsClientConfig.defaultShard if undefined.

      Returns Promise<ScreepsResponse>

      Error if shard and ScreepsClientConfig.defaultShard are undefined while using an official server. Also throws an error if the flag name is already in use.

    • Check whether or not a name for a room object is in use by any other room object of the same type on the specified shard.

      Endpoint: POST /api/game/check-unique-object-name

      Parameters

      • type: string

        The type of object being named. 'spawn' is the only known valid argument for this param. 'flag' and 'creep' will cause an error.

      • name: string

        The name to check

      • Optionalshard: string

        The name of the shard to use (ignored by unofficial servers). Defaults to ScreepsClientConfig.defaultShard if undefined.

      Returns Promise<ScreepsResponse>

      Error if shard and ScreepsClientConfig.defaultShard are undefined while using an official server.

      ScreepsApiError if the object name is already in use.

    • Create a new flag or move an existing one with the specified name.

      Unlike the runtime API equivalent of this endpoint, room visibility is not required here.

      Endpoint: POST /api/game/create-flag

      Parameters

      • room: string

        Name of the room in which the flag should be placed

      • x: number

        X-coordinate of the flag's room position

      • y: number

        Y-coordinate of the flag's room position

      • name: string

        The name of the flag. If the name is already in use, the current flag with this name will be moved to the specified position.

      • color: FlagColor = FlagColors.White

        The color of the left side of the flag

      • secondaryColor: FlagColor = FlagColors.White

        The color of the right side of the flag

      • Optionalshard: string

        The name of the shard to use (ignored by unofficial servers). Defaults to ScreepsClientConfig.defaultShard if undefined.

      Returns Promise<ScreepsDbUpsertResponse>

      A generic MongoDB upsert response:

      • If the name is new, result.upserted[0]._id is the game id of the created flag
      • If not, this moves the flag and the response does not contain the ID (but the ID doesn't change)

      Error if shard and ScreepsClientConfig.defaultShard are undefined while using an official server

    • Create an invader creep in a room claimed by the authenticated user.

      Create a single invader to test the defenses of one of your rooms. This can be called multiple times in succession to simulate a raid group.

      Invaders created by this endpoint will not drop any resources on death. They can be removed by gameRemoveInvader

      This operation is only permitted on exit positions of rooms claimed by the authenticated user.

      Endpoint: POST /api/game/create-invader

      Parameters

      • room: string

        Name of the room in which to spawn

      • x: number

        X-coordinate of the invader's room position

      • y: number

        Y-coordinate of the invader's room position

      • size: "big" | "small"

        The body size of the invader. In real invasions, the small size spawns in unclaimed and low-RCL rooms, while the large size spawns in high-RCL rooms.

      • type: "Melee" | "Ranged" | "Healer"

        The role of the invader, which will determine its body part types, boost types, and behavior.

      • boosted: boolean = false

        If true, the invader will be spawned with boosted parts.

      • Optionalshard: string

        The name of the shard to use (ignored by unofficial servers). Defaults to ScreepsClientConfig.defaultShard if undefined.

      Returns Promise<ScreepsUnknownResponse>

      Error if shard and ScreepsClientConfig.defaultShard are undefined while using an official server

    • Generate a name for a new room object.

      The generated name will be unique across all other objects of that type owned by the authenticated user on the specified shard.

      Endpoint: POST /api/game/gen-unique-object-name

      Parameters

      • type: string

        The type of object for which to generate the name (ex: "flag" or "spawn")

      • Optionalshard: string

        The name of the shard to use (ignored by unofficial servers). Defaults to ScreepsClientConfig.defaultShard if undefined.

      Returns Promise<GameGenUniqueNameResponse>

      Error if shard and ScreepsClientConfig.defaultShard are undefined while using an official server

    • Place the authenticated user's first spawn structure.

      This operation is only permitted when the user's world status is equal to 'empty'.

      Endpoint: POST /api/game/place-spawn

      Parameters

      • room: string

        Name of the room in which the spawn should be placed

      • x: number

        X-coordinate of the spawn's room position

      • y: number

        Y-coordinate of the spawn's room position

      • Optionalname: string

        An optional name to assign to the placed spawn

      • Optionalshard: string

        The name of the shard to use (ignored by unofficial servers). Defaults to ScreepsClientConfig.defaultShard if undefined.

      Returns Promise<ScreepsUnknownResponse>

      Error if shard and ScreepsClientConfig.defaultShard are undefined while using an official server

    Endpoints: /game/market

    Endpoints: /game/shards

    Endpoints: /leaderboard

    • Fetch the leaderboard rankings for a specific user.

      This endpoint does not require authentication.

      Endpoint: GET /api/leaderboard/find

      Parameters

      • username: string

        The name of the user

      • mode: LeaderboardMode = Http.LeaderboardModes.World

        'world' (control points) or 'power' (power processed)

      • Optionalseason: string

        An optional date in the format YYYY-MM. If undefined, the user's ranks for all seasons is returned.

      Returns Promise<LeaderboardFindResponse>

    • Fetch the leaderboard rankings for a specific user.

      This endpoint does not require authentication.

      Endpoint: GET /api/leaderboard/list

      Parameters

      • limit: number = 10

        The number of user results to include per response

      • mode: LeaderboardMode = Http.LeaderboardModes.World

        'world' (control points) or 'power' (power processed)

      • offset: number | null = 0

        The index (starting at zero) of the first leaderboard position that should be included in the response

      • Optionalseason: string

        A date in the format YYYY-MM, NOT a seasonal world name/number. Defaults to the current season.

      Returns Promise<LeaderboardListResponse>

    Endpoints: /register

    • Create a new user account.

      Endpoint: POST /api/register/submit

      Parameters

      • username: string

        The username to use for this new account

      • email: string

        The email address to associate with this new account

      • password: string

        The password to use for this new account. It is unclear whether or not this is accepted or even allowed on official servers.

      • Optionalmodules: UserCodeModules

        Initial bot code to deploy for this user

      Returns Promise<ScreepsUnknownResponse>

    Endpoints: /scoreboard

    • Query scoreboard results. This appears to only be relevant to seasonal world competitions/events.

      Endpoint: GET /api/scoreboard/list

      Parameters

      • offset: number = 0

        The index (starting at zero) of the first leaderboard position that should be included in the response

      • limit: number = 20

        The number of users to return per request. The maximum valid value is 20.

      Returns Promise<ScoreboardListResponse>

    Endpoints: /seasons

    • Fetch metadata for the current season. Only works on official servers when a seasonal world competition is active or about to start.

      Endpoint: GET /api/seasons/current

      Returns Promise<SeasonsCurrentResponse | null>

      Metadata on the current season, or null if a seasonal world competition is not active or about to start

      ScreepsApiError HTTP 404 if called on an unofficial server

    Endpoints: /servers

    Endpoints: /user

    • Create a copy of a code branch.

      Endpoint: POST /api/user/clone-branch

      Parameters

      • branch: string

        The name of the code branch to clone

      • newName: string

        The name of the new code branch

      • defaultModules: unknown

        Do you know what this does? If so, please submit a PR!

      Returns Promise<ScreepsUnknownResponse>

      userBranches to list available branches

    • Evaluate a JavaScript expression in the context of the authenticated user's bot's runtime environment.

      This expression is evaluated after the user's loop function runs. CPU costs and limits apply as they would to code in the loop function.

      Endpoint: POST /api/user/console

      Parameters

      • expression: string

        The JavaScript expression to evaluate.

      • Optionalshard: string

        The name of the shard to use (ignored by unofficial servers). Defaults to ScreepsClientConfig.defaultShard if undefined.

      Returns Promise<UserConsoleResponse>

      Error if shard and ScreepsClientConfig.defaultShard are undefined while using an official server

    • Get an overview of the authenticated user's stats broken down by room and time.

      Endpoint: GET /api/user/overview

      Parameters

      • interval: RoomStatInterval = 8

        Size of each time slot in minutes; only specific values are allowed:

        • 8: 8 minutes each; 64 minutes total
        • 180: 3 hours each; 24 hours total
        • 1440: 24 hours each; 8 days total
      • statName: RoomStat = RoomStats.EnergyControl

        The stat to view for this user

      Returns Promise<UserOverviewResponse>

    • Update the code branch that will be used by the server or the simulator.

      Endpoint: POST /api/user/set-active-branch

      Parameters

      • branch: string

        The name of the code branch to activate

      • activeName: "activeWorld" | "activeSim"

        The environment for which this code branch should be activated:

        • 'activeWorld': activate branch on the server
        • 'activeSim': activate branch on the simulator

      Returns Promise<ScreepsUnknownResponse>

      userBranches to list available branches

    Endpoints: /user/code

    Endpoints: /user/decorations

    • Spend pixels to create one or more decorations.

      Endpoint: POST /api/user/decorations/pixelize

      Parameters

      • count: number

        The number of decorations to generate.

      • theme: string = ''

        The theme from which to generate decorations. Note that specifying a theme increases the pixelization cost. Set to an empty string to create decorations from any theme.

      Returns Promise<ScreepsUnknownResponse>

    Endpoints: /user/memory

    • Updates part or all of the authenticated user's Memory.

      Endpoint: POST /api/user/memory

      Parameters

      • path: string | undefined

        The portion of the Memory JSON object to write (ex: 'flags.Flag1'). WARNING: If undefined/empty, overwrites the entire Memory object.

      • value: unknown

        The value to write to the specified Memory path. This will completely replace the previous value.

      • Optionalshard: string

        The name of the shard to use (ignored by unofficial servers). Defaults to ScreepsClientConfig.defaultShard if undefined.

      Returns Promise<UserMemorySetResponse>

      Error if shard and ScreepsClientConfig.defaultShard are undefined while using an official server

    Endpoints: /user/memory/segment

    • Fetch the contents of one or more RawMemory.segments.

      Endpoint: GET /api/user/memory-segment

      Parameters

      • segment: string | number | (string | number)[]

        One or more segment IDs to read. Multiple IDs can be specified in a single string by separating the IDs with commas.

      • Optionalshard: string

        The name of the shard to use (ignored by unofficial servers). Defaults to ScreepsClientConfig.defaultShard if undefined.

      Returns Promise<UserMemorySegmentGetResponse>

      Error if shard and ScreepsClientConfig.defaultShard are undefined while using an official server

      // Fetch a single segment
      Http.user.memory.segment.get(7, 'shard3')
      // Fetch a multiple segments with an ID array
      Http.user.memory.segment.get([7, '13'], 'shard3')
      // Fetch a multiple segments with a comma-delimited ID list
      Http.user.memory.segment.get('7,13,30', 'shard3')

    Endpoints: /user/messages

    • Send a message on behalf of the authenticated user.

      Endpoint: POST /api/user/messages/send

      Parameters

      • respondent: string

        The long _id of the user, not the username

      • text: string

        The text of the message to send

      Returns Promise<ScreepsUnknownResponse>

    Endpoints: /warpath

    Other

    AUTH: "auth" = 'auth'

    Fired immediately before authentication status changes.

    Payload: boolean Whether or not the client is now authenticated

    RATE_LIMIT: "rateLimit" = 'rateLimit'

    Fired when a rate limit is exceeded

    Payload: RateLimitEvent The latest rate limit state

    RESPONSE: "response" = 'response'

    Fired when a response is received from the HTTP API.

    Payload: AxiosResponse The HTTP response

    RESPONSE_RESULT: "responseResult" = 'responseResult'

    Fired when a response is received from the HTTP API.

    Payload: ScreepsHttpResponse The HTTP response, including params of the associated request

    TOKEN: "token" = 'token'

    Fired immediately before ScreepsHttpClient.token is updated.

    Payload: string The new API token

    • get currentLeaderboardSeason(): string

      Get the current leaderboard season (not the current seasonal world season)

      Returns string

      the Endpoints: /leaderboard category

    • get isOfficialServer(): boolean

      True if this client is configured for the official world, PTR, or seasonal world servers

      Returns boolean

    • get isPtrServer(): boolean

      True if this client is configured for the public test realm (PTR) server

      Returns boolean

    • get isSeasonServer(): boolean

      True if this client is configured for the seasonal world server

      Returns boolean

    • get rateLimitResetUrl(): string

      Generate an URL that can be opened in a browser to reset rate limits for all endpoints.

      The generated URL is specific to the API token currently in use.

      Returns string

      Error if no API token is available.

    • The Symbol.for('nodejs.rejection') method is called in case a promise rejection happens when emitting an event and captureRejections is enabled on the emitter. It is possible to use events.captureRejectionSymbol in place of Symbol.for('nodejs.rejection').

      import { EventEmitter, captureRejectionSymbol } from 'node:events';

      class MyClass extends EventEmitter {
      constructor() {
      super({ captureRejections: true });
      }

      [captureRejectionSymbol](err, event, ...args) {
      console.log('rejection happened for', event, 'with', err, ...args);
      this.destroy(err);
      }

      destroy(err) {
      // Tear the resource down here.
      }
      }

      Parameters

      • error: Error
      • event: string | symbol
      • ...args: any[]

      Returns void

      v13.4.0, v12.16.0

    • Alias for emitter.on(eventName, listener).

      Type Parameters

      • E extends string | symbol

      Parameters

      • eventName: string | symbol
      • listener: (...args: any[]) => void

      Returns this

      v0.1.26

    • Authenticate to the server using the email and password from the provided ScreepsServerConfig.

      Typically, this should not be called directly; it will be triggered automatically when a request is made to an endpoint that requires authentication.

      Parameters

      • Optionalcause: unknown

        if provided, will be attached to the error thrown when authentication credentials are missing

      Returns Promise<AuthSigninResponse | undefined>

      ScreepsApiError if authentication fails

    • Synchronously calls each of the listeners registered for the event named eventName, in the order they were registered, passing the supplied arguments to each.

      Returns true if the event had listeners, false otherwise.

      import { EventEmitter } from 'node:events';
      const myEmitter = new EventEmitter();

      // First listener
      myEmitter.on('event', function firstListener() {
      console.log('Helloooo! first listener');
      });
      // Second listener
      myEmitter.on('event', function secondListener(arg1, arg2) {
      console.log(`event with parameters ${arg1}, ${arg2} in second listener`);
      });
      // Third listener
      myEmitter.on('event', function thirdListener(...args) {
      const parameters = args.join(', ');
      console.log(`event with parameters ${parameters} in third listener`);
      });

      console.log(myEmitter.listeners('event'));

      myEmitter.emit('event', 1, 2, 3, 4, 5);

      // Prints:
      // [
      // [Function: firstListener],
      // [Function: secondListener],
      // [Function: thirdListener]
      // ]
      // Helloooo! first listener
      // event with parameters 1, 2 in second listener
      // event with parameters 1, 2, 3, 4, 5 in third listener

      Type Parameters

      • E extends string | symbol

      Parameters

      • eventName: string | symbol
      • ...args: any[]

      Returns boolean

      v0.1.26

    • Returns an array listing the events for which the emitter has registered listeners.

      import { EventEmitter } from 'node:events';

      const myEE = new EventEmitter();
      myEE.on('foo', () => {});
      myEE.on('bar', () => {});

      const sym = Symbol('symbol');
      myEE.on(sym, () => {});

      console.log(myEE.eventNames());
      // Prints: [ 'foo', 'bar', Symbol(symbol) ]

      Returns (string | symbol)[]

      v6.0.0

    • Returns the current max listener value for the EventEmitter which is either set by emitter.setMaxListeners(n) or defaults to events.defaultMaxListeners.

      Returns number

      v1.0.0

    • Returns the number of listeners listening for the event named eventName. If listener is provided, it will return how many times the listener is found in the list of the listeners of the event.

      Type Parameters

      • E extends string | symbol

      Parameters

      • eventName: string | symbol

        The name of the event being listened for

      • Optionallistener: (...args: any[]) => void

        The event handler function

      Returns number

      v3.2.0

    • Returns a copy of the array of listeners for the event named eventName.

      server.on('connection', (stream) => {
      console.log('someone connected!');
      });
      console.log(util.inspect(server.listeners('connection')));
      // Prints: [ [Function] ]

      Type Parameters

      • E extends string | symbol

      Parameters

      • eventName: string | symbol

      Returns ((...args: any[]) => void)[]

      v0.1.26

    • Type Parameters

      • R extends Response

      Parameters

      • this: void
      • res: R & { list?: unknown; rooms?: unknown; shards?: unknown }

      Returns R

    • Alias for emitter.removeListener().

      Type Parameters

      • E extends string | symbol

      Parameters

      • eventName: string | symbol
      • listener: (...args: any[]) => void

      Returns this

      v10.0.0

    • Adds the listener function to the end of the listeners array for the event named eventName. No checks are made to see if the listener has already been added. Multiple calls passing the same combination of eventName and listener will result in the listener being added, and called, multiple times.

      server.on('connection', (stream) => {
      console.log('someone connected!');
      });

      Returns a reference to the EventEmitter, so that calls can be chained.

      By default, event listeners are invoked in the order they are added. The emitter.prependListener() method can be used as an alternative to add the event listener to the beginning of the listeners array.

      import { EventEmitter } from 'node:events';
      const myEE = new EventEmitter();
      myEE.on('foo', () => console.log('a'));
      myEE.prependListener('foo', () => console.log('b'));
      myEE.emit('foo');
      // Prints:
      // b
      // a

      Type Parameters

      • E extends string | symbol

      Parameters

      • eventName: string | symbol

        The name of the event.

      • listener: (...args: any[]) => void

        The callback function

      Returns this

      v0.1.101

    • Adds a one-time listener function for the event named eventName. The next time eventName is triggered, this listener is removed and then invoked.

      server.once('connection', (stream) => {
      console.log('Ah, we have our first user!');
      });

      Returns a reference to the EventEmitter, so that calls can be chained.

      By default, event listeners are invoked in the order they are added. The emitter.prependOnceListener() method can be used as an alternative to add the event listener to the beginning of the listeners array.

      import { EventEmitter } from 'node:events';
      const myEE = new EventEmitter();
      myEE.once('foo', () => console.log('a'));
      myEE.prependOnceListener('foo', () => console.log('b'));
      myEE.emit('foo');
      // Prints:
      // b
      // a

      Type Parameters

      • E extends string | symbol

      Parameters

      • eventName: string | symbol

        The name of the event.

      • listener: (...args: any[]) => void

        The callback function

      Returns this

      v0.3.0

    • Adds the listener function to the beginning of the listeners array for the event named eventName. No checks are made to see if the listener has already been added. Multiple calls passing the same combination of eventName and listener will result in the listener being added, and called, multiple times.

      server.prependListener('connection', (stream) => {
      console.log('someone connected!');
      });

      Returns a reference to the EventEmitter, so that calls can be chained.

      Type Parameters

      • E extends string | symbol

      Parameters

      • eventName: string | symbol

        The name of the event.

      • listener: (...args: any[]) => void

        The callback function

      Returns this

      v6.0.0

    • Adds a one-time listener function for the event named eventName to the beginning of the listeners array. The next time eventName is triggered, this listener is removed, and then invoked.

      server.prependOnceListener('connection', (stream) => {
      console.log('Ah, we have our first user!');
      });

      Returns a reference to the EventEmitter, so that calls can be chained.

      Type Parameters

      • E extends string | symbol

      Parameters

      • eventName: string | symbol

        The name of the event.

      • listener: (...args: any[]) => void

        The callback function

      Returns this

      v6.0.0

    • Returns a copy of the array of listeners for the event named eventName, including any wrappers (such as those created by .once()).

      import { EventEmitter } from 'node:events';
      const emitter = new EventEmitter();
      emitter.once('log', () => console.log('log once'));

      // Returns a new Array with a function `onceWrapper` which has a property
      // `listener` which contains the original listener bound above
      const listeners = emitter.rawListeners('log');
      const logFnWrapper = listeners[0];

      // Logs "log once" to the console and does not unbind the `once` event
      logFnWrapper.listener();

      // Logs "log once" to the console and removes the listener
      logFnWrapper();

      emitter.on('log', () => console.log('log persistently'));
      // Will return a new Array with a single function bound by `.on()` above
      const newListeners = emitter.rawListeners('log');

      // Logs "log persistently" twice
      newListeners[0]();
      emitter.emit('log');

      Type Parameters

      • E extends string | symbol

      Parameters

      • eventName: string | symbol

      Returns ((...args: any[]) => void)[]

      v9.4.0

    • Removes all listeners, or those of the specified eventName.

      It is bad practice to remove listeners added elsewhere in the code, particularly when the EventEmitter instance was created by some other component or module (e.g. sockets or file streams).

      Returns a reference to the EventEmitter, so that calls can be chained.

      Type Parameters

      • E extends string | symbol

      Parameters

      • OptionaleventName: string | symbol

      Returns this

      v0.1.26

    • Removes the specified listener from the listener array for the event named eventName.

      const callback = (stream) => {
      console.log('someone connected!');
      };
      server.on('connection', callback);
      // ...
      server.removeListener('connection', callback);

      removeListener() will remove, at most, one instance of a listener from the listener array. If any single listener has been added multiple times to the listener array for the specified eventName, then removeListener() must be called multiple times to remove each instance.

      Once an event is emitted, all listeners attached to it at the time of emitting are called in order. This implies that any removeListener() or removeAllListeners() calls after emitting and before the last listener finishes execution will not remove them from emit() in progress. Subsequent events behave as expected.

      import { EventEmitter } from 'node:events';
      class MyEmitter extends EventEmitter {}
      const myEmitter = new MyEmitter();

      const callbackA = () => {
      console.log('A');
      myEmitter.removeListener('event', callbackB);
      };

      const callbackB = () => {
      console.log('B');
      };

      myEmitter.on('event', callbackA);

      myEmitter.on('event', callbackB);

      // callbackA removes listener callbackB but it will still be called.
      // Internal listener array at time of emit [callbackA, callbackB]
      myEmitter.emit('event');
      // Prints:
      // A
      // B

      // callbackB is now removed.
      // Internal listener array [callbackA]
      myEmitter.emit('event');
      // Prints:
      // A

      Because listeners are managed using an internal array, calling this will change the position indexes of any listener registered after the listener being removed. This will not impact the order in which listeners are called, but it means that any copies of the listener array as returned by the emitter.listeners() method will need to be recreated.

      When a single function has been added as a handler multiple times for a single event (as in the example below), removeListener() will remove the most recently added instance. In the example the once('ping') listener is removed:

      import { EventEmitter } from 'node:events';
      const ee = new EventEmitter();

      function pong() {
      console.log('pong');
      }

      ee.on('ping', pong);
      ee.once('ping', pong);
      ee.removeListener('ping', pong);

      ee.emit('ping');
      ee.emit('ping');

      Returns a reference to the EventEmitter, so that calls can be chained.

      Type Parameters

      • E extends string | symbol

      Parameters

      • eventName: string | symbol
      • listener: (...args: any[]) => void

      Returns this

      v0.1.26

    • Send an API request to the server.

      Unless you are retrying a request using a ScreepsHttpRequest instance, this should not be called directly. Instead, use the appropriate endpoint method to apply the correct request parameter and response body types.

      If an endpoint you use does not have an associated method, please consider submitting a PR to implement it.

      Parameters

      • method: ScreepsHttpMethod

        The HTTP method to use

      • path: string

        The URL path of the endpoint. This will be appeneded to ScreepsServerConfig.url.

      • Optionalparams: unknown

        The request parameters

      • retriesAttempted: number = 0

        The number of retries already attempted due to HTTP 429 errors. This argument should not be provided by consumers.

      Returns Promise<any>

      The parsed response body

    • By default EventEmitters will print a warning if more than 10 listeners are added for a particular event. This is a useful default that helps finding memory leaks. The emitter.setMaxListeners() method allows the limit to be modified for this specific EventEmitter instance. The value can be set to Infinity (or 0) to indicate an unlimited number of listeners.

      Returns a reference to the EventEmitter, so that calls can be chained.

      Parameters

      • n: number

      Returns this

      v0.3.5

    • Search for a config/credential file and initializes the client from the first file found.

      Authentication will occur automatically if email/password credentials are provided in lieu of an API token.

      Alternatively, the client can be initialized by passing a configuration object directly to the constructor.

      Parameters

      Returns Promise<ScreepsHttpClient>

      A configured and authenticated ScreepsHttpClient instance

      Error if the selected config file is invalid or if no config files are found