First development of the deploy action (#6)
Some checks failed
Lint / pre-commit Linting (push) Has been cancelled

Deploy js code to an instance of screeps.
Some debugging tools are implemented.

Reviewed-on: #6
Co-authored-by: Philipp Horstenkamp <philipp@horstenkamp.de>
Co-committed-by: Philipp Horstenkamp <philipp@horstenkamp.de>
This commit is contained in:
2023-11-26 18:31:49 +01:00
committed by Philipp Horstenkamp
parent 0858cc69be
commit 6f5729c12a
1039 changed files with 228399 additions and 0 deletions

14
node_modules/screeps-api/.babelrc generated vendored Normal file
View File

@ -0,0 +1,14 @@
{
"presets": [
["env",{
"modules":false,
"targets":{
node: 6
}
}]
],
"plugins": [
"transform-async-to-generator",
"external-helpers"
]
}

41
node_modules/screeps-api/.circleci/config.yml generated vendored Normal file
View File

@ -0,0 +1,41 @@
version: 2
jobs:
build:
working_directory: ~/repo
docker:
- image: circleci/node:8
steps:
- checkout
- restore_cache:
key: dependency-cache-{{ checksum "package.json" }}
- run:
name: install
command: yarn install
- save_cache:
key: dependency-cache-{{ checksum "package.json" }}
paths:
- ./node_modules
- run:
name: lint
command: yarn lint
- run:
name: test
command: yarn test
- store_artifacts:
path: test-results.xml
prefix: tests
- store_test_results:
path: test-results.xml
- deploy:
name: Maybe Deploy
command: |
if [ "${CIRCLE_BRANCH}" == "master" ]; then
echo "//registry.npmjs.org/:_authToken=$NPM_TOKEN" >> ~/.npmrc
npm run 2npm
fi
workflows:
version: 2
build:
jobs:
- build:
context: screeps

4
node_modules/screeps-api/.npmignore generated vendored Normal file
View File

@ -0,0 +1,4 @@
*.sublime-*
node_modules
auth.js
src

13
node_modules/screeps-api/LICENSE generated vendored Normal file
View File

@ -0,0 +1,13 @@
Copyright (c) 2017,
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.

153
node_modules/screeps-api/README.md generated vendored Normal file
View File

@ -0,0 +1,153 @@
# Screeps API
## This is a nodejs API for the game Screeps
[![JavaScript Style Guide](https://img.shields.io/badge/code_style-standard-brightgreen.svg)](https://standardjs.com)
[![License](https://img.shields.io/npm/l/screeps-api.svg)](https://npmjs.com/package/screeps-api)
[![Version](https://img.shields.io/npm/v/screeps-api.svg)](https://npmjs.com/package/screeps-api)
[![Downloads](https://img.shields.io/npm/dw/screeps-api.svg)](https://npmjs.com/package/screeps-api)
[![CircleCI](https://circleci.com/gh/screepers/node-screeps-api/tree/master.svg?style=shield)](https://circleci.com/gh/screepers/node-screeps-api/tree/master)
![npm](https://nodei.co/npm/screeps-api.png "NPM")
## Notice on authentication
As of 12/29/2017 Screeps now uses auth tokens obtained via your screeps account settings.
User/pass auth will stop working February 1, 2018!
[Screeps Announcement](http://blog.screeps.com/2017/12/auth-tokens/)
## CLI Usage
As of 1.7.0, a small CLI program (`screeps-api`) is included.
Server config is specified via a `.screeps.yml` file conforming to the [Unified Credentials File format](https://github.com/screepers/screepers-standards/blob/34bd4e6e5c8250fa0794d915d9f78d3c45326076/SS3-Unified_Credentials_File.md) (Pending [screepers-standard PR #8](https://github.com/screepers/screepers-standards/pull/8))
```
screeps-api
Usage: [options] [command]
Options:
-V, --version output the version number
--server <server> Server config to use (default: main)
-h, --help output usage information
Commands:
raw <cmd> [args...] Execute raw API call
memory [options] [path] Get Memory contents
segment [options] <segment> Get segment contents. Use 'all' to get all)
download [options] Download code
upload [options] <files...> Upload code
```
## API Usage
As of 1.0, all functions return Promises
```javascript
const { ScreepsAPI } = require('screeps-api');
const fs = require('fs');
// Supports @tedivm's [Unified Credentials File format](https://github.com/screepers/screepers-standards/blob/34bd4e6e5c8250fa0794d915d9f78d3c45326076/SS3-Unified_Credentials_File.md) (Pending [screepers-standard PR #8](https://github.com/screepers/screepers-standards/pull/8))
const api = await ScreepsAPI.fromConfig('main', 'appName')
// This loads the server config 'main' and the configs section 'appName' if it exists
// config section can be accessed like this:
// If making a CLI app, its suggested to have a `--server` argument for selection
console.log(api.appConfig.myConfigVar)
// All options are optional
const api = new ScreepsAPI({
token: 'Your Token from Account/Auth Tokens'
protocol: 'https',
hostname: 'screeps.com',
port: 443,
path: '/' // Do no include '/api', it will be added automatically
});
// You can overwrite parameters if needed
api.auth('screeps@email.com','notMyPass',{
protocol: 'https',
hostname: 'screeps.com',
port: 443,
path: '/' // Do no include '/api', it will be added automatically
})
// If you want to point to the screeps PTR (Public Test Realm),
// you can set the 'path' option to '/ptr' and it will work fine.
// Dump Memory
api.memory.get()
.then(memory => {
fs.writeFileSync('memory.json', JSON.stringify(memory))
})
.catch(err => console.error(err));
// Dump Memory Path
api.memory.get('rooms.W0N0')
.then(memory => {
fs.writeFileSync('memory.rooms.W0N0.json', JSON.stringify(memory))
})
.catch(err => console.error(err));
// Get user info
api.me().then((user)=>console.log(user))
// Socket API
api.socket.connect()
// Events have the structure of:
// {
// channel: 'room',
// id: 'E3N3', // Only on certain events
// data: { ... }
// }
api.socket.on('connected',()=>{
// Do stuff after conntected
})
api.socket.on('auth',(event)=>{
event.data.status contains either 'ok' or 'failed'
// Do stuff after auth
})
// Events: (Not a complete list)
// connected disconnected message auth time protocol package subscribe unsubscribe console
// Subscribtions can be queued even before the socket connects or auths,
// although you may want to subscribe from the connected or auth callback to better handle reconnects
api.socket.subscribe('console')
api.socket.on('console',(event)=>{
event.data.messages.log // List of console.log output for tick
})
// Starting in 1.0, you can also pass a handler straight to subscribe!
api.socket.subscribe('console', (event)=>{
event.data.messages.log // List of console.log output for tick
})
// More common examples
api.socket.subscribe('cpu',(event)=>console.log('cpu',event.data))
api.code.get('default').then(data=>console.log('code',data))
api.code.set('default',{
main: 'module.exports.loop = function(){ ... }'
})
api.socket.subscribe('memory/stats',(event)=>{
console.log('stats',event.data)
})
api.socket.subscribe('memory/rooms.E0N0',(event)=>{
console.log('E0N0 Memory',event.data)
})
```
## Endpoint documentation
Server endpoints are listed in the `docs` folder:
* [Endpoints.md](/docs/Endpoints.md) for direct access
* [Websocket_endpoints.md](/docs/Websocket_endpoints.md) for web socket endpoints
Those lists are currently not exhaustive.

4
node_modules/screeps-api/auth.example.js generated vendored Normal file
View File

@ -0,0 +1,4 @@
module.exports = {
email: 'not.mine@email.com',
password: 'notMyPassword',
};

185
node_modules/screeps-api/bin/screeps-api.js generated vendored Normal file
View File

@ -0,0 +1,185 @@
#!/usr/bin/env node
const program = require('commander')
const { ScreepsAPI } = require('../')
const fs = require('fs')
const util = require('util')
const path = require('path')
const readFile = util.promisify(fs.readFile)
const writeFile = util.promisify(fs.writeFile)
async function init (opts) {
return ScreepsAPI.fromConfig(opts.parent.server)
}
async function json (data) {
process.stdout.write(JSON.stringify(data))
}
async function out (data, opts) {
data = await data
data = (data && data.data) || data
if (process.stdout.isTTY) {
console.log(data)
} else {
json(data)
}
}
async function run () {
program
.version(require('../package.json').version)
.option('--server <server>', 'Server config to use', 'main')
program
.command('raw <cmd> [args...]')
.description('Execute raw API call')
.action(async function (cmd, args, opts) {
try {
const api = await init(opts)
const path = cmd.split('.')
let fn = api.raw
for (const part of path) {
fn = fn[part]
}
if (!fn || typeof fn !== 'function') {
console.log('Invalid cmd')
return
}
out(fn(...args))
} catch (e) {
console.error(e)
}
})
program
.command('memory [path]')
.description(`Get Memory contents`)
.option('--set <file>', 'Sets the memory path to the contents of file')
.option('--allow-root', 'Allows writing without path')
.option('-s --shard <shard>', 'Shard to read from', 'shard0')
.option('-f --file <file>', 'File to write data to')
.action(async function (fpath, opts) {
try {
const api = await init(opts)
if (opts.set) {
if (!fpath && !opts.allowRoot) {
throw new Error('Refusing to write to root! Use --allow-root if you really want this.')
}
const data = await readFile(opts.set, 'utf8')
await api.memory.set(fpath, data, opts.shard)
out('Memory written')
} else {
const data = api.memory.get(fpath, opts.shard)
if (opts.file) {
await writeFile(opts.file, data)
} else {
out(data)
}
}
} catch (e) {
console.error(e)
}
})
const seg = program
.command('segment <segment>')
.description(`Get segment contents. Use 'all' to get all)`)
.option('--set <file>', 'Sets the segment content to the contents of file')
.option('-s --shard <shard>', 'Shard to read from', 'shard0')
.option('-d --dir <dir>', 'Directory to save in. Empty files are not written. (defaults to outputing in console)')
.action(async function (segment, opts) {
try {
const api = await init(opts)
if (opts.set) {
const data = await readFile(opts.set, 'utf8')
await api.memory.segment.set(segment, data, opts.shard)
out('Segment Set')
} else {
if (segment === 'all') segment = Array.from({ length: 100 }, (v, k) => k).join(',')
const { data } = await api.memory.segment.get(segment, opts.shard)
const dir = opts.dir
const segments = data
if (dir) {
if (Array.isArray(segments)) {
await Promise.all(segments.map((d, i) => d && writeFile(path.join(dir, `segment_${i}`), d)))
} else {
await writeFile(path.join(dir, `segment_${segment}`), d)
}
out('Segments Saved')
} else {
out(segments)
}
}
} catch (e) {
console.error(e)
}
})
program
.command('download')
.description(`Download code`)
.option('-b --branch <branch>', 'Code branch', 'default')
.option('-d --dir <dir>', 'Directory to save in (defaults to outputing in console)')
.action(async function (opts) {
try {
const api = await init(opts)
const dir = opts.dir
const { modules } = await api.code.get(opts.branch)
if (dir) {
await Promise.all(Object.keys(modules).map(async fn => {
const data = modules[fn]
if (data.binary) {
await writeFile(path.join(dir, `${fn}.wasm`), Buffer.from(data.binary, 'base64'))
} else {
await writeFile(path.join(dir, `${fn}.js`), data)
}
console.log(`Saved ${fn}`)
}))
} else {
out(modules)
}
} catch (e) {
console.error(e)
}
})
program
.command('upload <files...>')
.description(`Upload code`)
.option('-b --branch <branch>', 'Code branch', 'default')
.action(async function (files, opts) {
try {
const api = await init(opts)
const modules = {}
const ps = []
for (const file of files) {
ps.push((async (file) => {
const { name, ext } = path.parse(file)
const data = await readFile(file)
if (ext === '.js') {
modules[name] = data.toString('utf8')
}
if (ext === '.wasm') {
modules[name] = { binary: data.toString('base64') }
}
})(file))
}
await Promise.all(ps)
out(api.code.set(opts.branch, modules))
} catch (e) {
console.error(e)
}
})
if (!process.argv.slice(2).length) {
program.outputHelp()
}
program.parse(process.argv)
}
run().then(data => {
if (!data) return
console.log(JSON.stringify(data.data || data, null, 2))
}).catch(console.error)

20374
node_modules/screeps-api/dist/ScreepsAPI.cjs.js generated vendored Normal file

File diff suppressed because it is too large Load Diff

20368
node_modules/screeps-api/dist/ScreepsAPI.es.js generated vendored Normal file

File diff suppressed because it is too large Load Diff

20375
node_modules/screeps-api/dist/ScreepsAPI.iife.js generated vendored Normal file

File diff suppressed because it is too large Load Diff

20378
node_modules/screeps-api/dist/ScreepsAPI.umd.js generated vendored Normal file

File diff suppressed because it is too large Load Diff

236
node_modules/screeps-api/docs/Endpoints.md generated vendored Normal file
View File

@ -0,0 +1,236 @@
Copied from [python-screeps](https://github.com/screepers/python-screeps/blob/master/docs/Endpoints.md)
Start by sending a request to `auth/signin` with your e-mail address and
password in a JSON object in the POST data. The response JSON object contains a
token (a hex string); remember that value. Each time you make a request that
requires authentication (the leaderboard and terrain ones, at least, don't),
send the most recent token value as both the `X-Token` and `X-Username`
headers. The response will contain a new token value in the `X-Token` header
with which you should replace your saved token. (You can send the token on every
request and just check for a new one in the response, so you don't have to know
exactly which calls require authentication.)
Example request parameters are given below, along with schemata for the server's
responses.
Memory and console endpoints are from
[bzy-xyz](https://gist.github.com/bzy-xyz/9c4d8c9f9498a2d7983d).
You can access the PTR by changing `screeps.com` to `screeps.com/ptr` in all URLs.
# Enumeration values
When an endpoint takes `interval` or `statName` as an argument, the valid values
are the ones listed below.
- interval: 8, 180, 1440 (8 for 1h, 180 for 24h and 1440 for 7 days)
- statName: creepsLost, creepsProduced, energyConstruction, energyControl, energyCreeps, energyHarvested
# Authentication
- [POST] `https://screeps.com/api/auth/signin`
- post data: `{ email, password }`
- response: `{ ok, token }`
# Room information
- `https://screeps.com/api/game/room-overview?interval=8&room=E1N8`
- `{ ok, owner: { username, badge: { type, color1, color2, color3, param, flip } }, stats: { energyHarvested: [ { value, endTime } ], energyConstruction: [ { value, endTime } ], energyCreeps: [ { value, endTime } ], energyControl: [ { value, endTime } ], creepsProduced: [ { value, endTime } ], creepsLost: [ { value, endTime } ] }, statsMax: { energy1440, energyCreeps1440, energy8, energyControl8, creepsLost180, energyHarvested8, energy180, energyConstruction180, creepsProduced8, energyControl1440, energyCreeps8, energyHarvested1440, creepsLost1440, energyConstruction1440, energyHarvested180, creepsProduced180, creepsProduced1440, energyCreeps180, energyControl180, energyConstruction8, creepsLost8 } }`
- `https://screeps.com/api/game/room-terrain?room=E1N8`
- `{ ok, terrain: [ { room, x, y, type } ] }`
- `type` in each element of `terrain` can be "wall" or "swamp"
- `https://screeps.com/api/game/room-terrain?room=E1N8&encoded=1`
- `{ ok, terrain: [ { _id, room, terrain, type } ] }`
- `terrain` is a string of digits, giving the terrain left-to-right and top-to-bottom
- 0: plain, 1: wall, 2: swamp, 3: also wall
- encoded argument can be anything non-empty
- `https://screeps.com/api/game/room-status?room=E1N8`
- `{ _id, status, novice }`
- `status` can at least be "normal" or "out of borders"
- if the room is in a novice area, `novice` will contain the Unix timestamp of the end of the protection (otherwise it is absent)
- `https://screeps.com/api/experimental/pvp?interval=50`
- `{ ok, time, rooms: [ { _id, lastPvpTime } ] }`
- `time` is the current server tick
- `_id` contains the room name for each room, and `lastPvpTime` contains the last tick pvp occurred
- if neither a valid `interval` nor a valid `start` argument is provided, the result of the call is still `ok`, but with an empty rooms array.
- `https://screeps.com/api/experimental/pvp?start=14787157`
- `{ ok, time, rooms: [ { _id, lastPvpTime } ] }`
# Market information
- `https://screeps.com/api/game/market/orders-index`
- `{"ok":1,"list":[{"_id":"XUHO2","count":2}]}`
- `_id` is the resource type, and there will only be one of each type.
- `count` is the number of orders.
- `https://screeps.com/api/game/market/my-orders`
- `{ ok, list: [ { _id, created, user, active, type, amount, remainingAmount, resourceType, price, totalAmount, roomName } ] }`
- `https://screeps.com/api/game/market/orders?resourceType=Z`
- `{ ok, list: [ { _id, created, user, active, type, amount, remainingAmount, resourceType, price, totalAmount, roomName } ] }`
- `resourceType` is one of the RESOURCE_* constants.
- `https://screeps.com/api/user/money-history`
- `{"ok":1,"page":0,"list":[ { _id, date, tick, user, type, balance, change, market: {} } ] }`
- `page` used for pagination.
- `hasMore` is true if there are more pages to view.
- `market`
- New Order- `{ order: { type, resourceType, price, totalAmount, roomName } }`
- Extended Order- `{ extendOrder: { orderId, addAmount } }`
- Fulfilled Order- `{ resourceType, roomName, targetRoomName, price, npc, amount }`
- Price Change - `{ changeOrderPrice: { orderId, oldPrice, newPrice } }`
# Leaderboard
- `https://screeps.com/api/leaderboard/seasons`
- `{ ok, seasons: [ { _id, name, date } ] }`
- the `_id` returned here is used for the season name in the other leaderboard calls
- `https://screeps.com/api/leaderboard/find?mode=world&season=2015-09&username=danny`
- `{ ok, _id, season, user, score, rank }`
- `user` (not `_id`) is the user's _id, as returned by `me` and `user/find`
- `rank` is 0-based
- `https://screeps.com/api/leaderboard/find?mode=world&username=danny`
- `{ ok, list: [ _id, season, user, score, rank ] }`
- lists ranks in all seasons
- `https://screeps.com/api/leaderboard/list?limit=10&mode=world&offset=10&season=2015-09`
- `{ ok, list: [ { _id, season, user, score, rank } ], count, users: { <user's _id>: { _id, username, badge: { type, color1, color2, color3, param, flip }, gcl } } }`
# Messages
- `https://screeps.com/api/user/messages/index`
- `{ ok, messages: [ { _id, message: { _id, user, respondent, date, type, text, unread } } ], users: { <user's _id>: { _id, username, badge: { type, color1, color2, color3, param, flip } } } }`
- `https://screeps.com/api/user/messages/list?respondent=55605a6654db1fa952de8d90`
- `{ ok, messages: [ { _id, date, type, text, unread } ] }`
- [POST] `https://screeps.com/api/user/messages/send`
- post data: `{ respondent, text }`
- `respondent` is the long _id of the user, not the username
- response: `{ ok }`
- `https://screeps.com/api/user/messages/unread-count`
- `{ ok, count }`
# User information
- `https://screeps.com/api/auth/me`
- `{ ok, _id, email, username, cpu, badge: { type, color1, color2, color3, param, flip }, password, notifyPrefs: { sendOnline, errorsInterval, disabledOnMessages, disabled, interval }, gcl, credits, lastChargeTime, lastTweetTime, github: { id, username }, twitter: { username, followers_count } }`
- `https://screeps.com/api/user/find?username=danny`
- `{ ok, user: { _id, username, badge: { type, color1, color2, color3, param, flip }, gcl } }`
- `https://screeps.com/api/user/find?id=55c91dc66e36d62a6167e1b5`
- `{ ok, user: { _id, username, badge: { type, color1, color2, color3, param, flip }, gcl } }`
- `https://screeps.com/api/user/overview?interval=1440&statName=energyControl`
- `{ ok, rooms: [ <room name> ], stats: { <room name>: [ { value, endTime } ] }, statsMax }`
- `https://screeps.com/api/user/respawn-prohibited-rooms`
- `{ ok, rooms: [ <room name> ] }`
- `https://screeps.com/api/user/world-status`
- `{ ok, status }`
- `status` is usually "normal"; it's unknown what else it can be
- `https://screeps.com/api/user/world-start-room`
- `{ ok, room: [ <room name> ] }`
- `room` is an array, but seems to always contain only one element
- `https://screeps.com/api/xsolla/user`
- `{ ok, active }`
- `active` is the Unix timestamp of the end of your current subscribed time
- [POST] `https://screeps.com/api/user/console`
- post data: `{ expression }`
- response: `{ ok, result: { ok, n }, ops: [ { user, expression, _id } ], insertedCount, insertedIds: [ <mongodb id> ] }`
- `https://screeps.com/api/user/memory?path=flags.Flag1`
- `{ ok, data }`
- `data` is the string `gz:` followed by base64-encoded gzipped JSON encoding of the requested memory path
- the path may be empty or absent to retrieve all of Memory
- [POST] `https://screeps.com/api/user/memory`
- post data: `{ path, value }`
- response: `{ ok, result: { ok, n }, ops: [ { user, expression, hidden } ], data, insertedCount, insertedIds }`
- `https://screeps.com/api/user/memory-segment?segment=[0-99]`
- `{ okay, data }`
- response: `{ ok, data: '' }`
- [POST ]`https://screeps.com/api/user/memory-segment`
- post data: `{ segment, data }`
# Manipulating the game world
- [POST] `https://screeps.com/api/game/gen-unique-object-name`
- post data: `{ type }`
- response: `{ ok, name }`
- `type` can be at least "flag" or "spawn"
- [POST] `https://screeps.com/api/game/create-flag`
- post data: `{ room, x, y, name, color, secondaryColor }`
- response: `{ ok, result: { nModified, ok, upserted: [ { index, _id } ], n }, connection: { host, id, port } }`
- 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)
- `connection` looks like some internal MongoDB thing that is irrelevant to us
- [POST] `https://screeps.com/api/game/change-flag`
- post data: `{ _id, room, x, y }`
- response: `{ ok, result: { nModified, ok, n }, connection: { host, id, port } }`
- [POST] `https://screeps.com/api/game/change-flag-color`
- post data: `{ _id, color, secondaryColor }`
- response: `{ ok, result: { nModified, ok, n }, connection: { host, id, port } }`
- [POST] `https://screeps.com/api/game/add-object-intent`
- post data: `{ _id, room, name, intent }`
- response: `{ ok, result: { nModified, ok, upserted: [ { index, _id } ], n }, connection: { host, id, port } }`
- `_id` is the game id of the object to affect (except for destroying structures), `room` is the name of the room it's in
- this method is used for a variety of actions, depending on the `name` and `intent` parameters
- 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 = {}`
- [POST] `https://screeps.com/api/game/set-notify-when-attacked`
- post data: `{ _id, enabled }`
- `enabled` is either `true` or `false` (literal values, not strings)
- response: `{ ok, result: { ok, nModified, n }, connection: { id, host, port } }`
- [POST] `https://screeps.com/api/game/create-construction`
- post data: `{ room, structureType, x, y}`
- `structureType` is the same value as one of the in-game STRUCTURE_* constants ('road', 'spawn', etc.)
- `{ ok, result: { ok, n }, ops: [ { type, room, x, y, structureType, user, progress, progressTotal, _id } ], insertedCount, insertedIds }`
# Other
- `https://screeps.com/api/game/time`
- `{ ok, time }`
- [GET/POST] `https://screeps.com/api/user/code`
- for pushing or pulling code, as documented at http://support.screeps.com/hc/en-us/articles/203022612
- [POST] `https://screeps.com/api/game/map-stats`
- post data: `{ rooms: [ <room name> ], statName: "..."}`
- statName can be "owner0", "claim0", or a stat (see the enumeration above) followed by an interval
- if it is owner0 or claim0, there's no separate stat block in the response
- response: `{ ok, stats: { <room name>: { status, novice, own: { user, level }, <stat>: [ { user, value } ] } }, users: { <user's _id>: { _id, username, badge: { type, color1, color2, color3, param, flip } } } }`
- `status` and `novice` are as per the `room-status` call
- `level` can be 0 to indicate a reserved room
- `https://screeps.com/room-history/E1N8/12340.json`
- `{ timestamp, room, base, ticks: { <time>: <tick update object> } }`
- the number in the URL is the tick to retrieve information for (from 5e5 ticks ago to about 50 ticks ago)
- note that the web interface only shows up to 3e5 ticks ago
- the tick must be a multiple of 20; the response includes information for the 20 ticks starting then
- for the first tick in the result, the tick update object maps from object ids to full object descriptions
- for later ticks, the update includes only changed attributes
- timestamp is milliseconds since the Unix epoch
- [POST] `https://screeps.com/user/activate-ptr`
- `{ok, result: { ok, nModified, n }, connection: { id, host, port } }`
- only works on the PTR

211
node_modules/screeps-api/docs/Websocket_endpoints.md generated vendored Normal file
View File

@ -0,0 +1,211 @@
# Web sockets endpoints list
Currently known endpoints are listed below.
* This list is clearly not exhaustive and comes from empirical observations.
* If you want to add more data, feel free to make a pull request.
## Shards
Any subscription taking a room name is different on servers with shards,
the room name should be prefixed with the shard name ex `shard0/E0N0`.
Note that adding a shard to a server not expecting it may cause an error.
## Subscribing to web sockets endpoints
* Make sure you are authenticated (you should have called `api.auth(...).then(...)` first).
* Connect the socket and wait for connection establishment using `api.socket.connect().then(...)`.
* You can then subscribe to different endpoints using `api.socket.subscribe()`.
* The server will then send periodic events with requested information.
Complete example:
```javascript
const { ScreepsAPI } = require('screeps-api');
try {
// Setup
const api = new ScreepsAPI();
await api.auth("your_email", "your_password"); // authenticate
await api.socket.connect(); // connect socket
// Subscribe to 'cpu' endpoint and get events
api.socket.subscribe('cpu');
api.socket.on('cpu', event => {
console.log(event.data.cpu) // cpu used last tick
});
// You can also put a callback to subscribe()
api.socket.subscribe('console', event => {
event.data.messages.log // List of console.log output for tick
})
} catch(err) {
console.log(err);
}
```
## code
### Description:
Once subscribed, the server will send a new event with full code base every time code base changes.
### Parameters of `event.data`:
Name | Type | Description
--------- | ------ | ------------------
branch | String | Name of the updated branch
modules | Object | Map of files (using file name as key and file content as value)
timestamp | Number | Date of the modification expressed as the number of milli-seconds since 01/01/1970
hash | Number | Some kind of hash, I guess ? (don't ask me how to compute it #FIXME)
### Example:
```javascript
// Subscription
api.socket.subscribe('code', event => console.log(JSON.stringify(event.data)));
```
```javascript
// Results
{
"branch": "simulation",
"modules":{
"main":"console.log(\"Hello world!\");\n",
// other modules...
},
"timestamp": 1500930041802,
"hash": 424324
}
```
## console
### Description:
Once subscribed, the server will send a new event every tick with console logs and return value of commands (if any).
### Parameters of `event.data`:
Name | Type | Description
---------------- | ------ | ------------------
messages.log | Array | Lines shown in console (like if printed by `console.log()`)
messages.results | Array | Array of command results
### Example:
```javascript
// Subscription
api.socket.subscribe('console', event => console.log(JSON.stringify(event.data)));
```
```javascript
// Results after executing `Game.time` in game:
{
"messages": {
"log": [],
"results": ["16746996"]
}
}
// (`Game.time` does not show any log in the console, which is why `messages.log` is empty)
```
## cpu
### Description:
Once subscribed, the server will send a new event every tick with cpu and memory usage.
### Parameters of `event.data`:
Name | Type | Description
------ | ------ | ------------------
cpu | Number | Cpu used last tick
memory | Number | Current memory usage
### Example:
```javascript
// Subscription
api.socket.subscribe('cpu', event => console.log(JSON.stringify(event.data)));
```
```javascript
// Results every tick
{
"cpu": 32,
"memory": 126435
}
```
## room:ROOM_NAME
### Description:
Once subscribed, the server will send a new event every tick with the RoomObjects of present in selected room (`ROOM_NAME`).
RoomObjects seem to have the same properties as within game scripts.
**Atention**, only the first event actually returns the object full properties.
Subsequent events only return the modified properties.
### Parameters of `event.data`:
Name | Type | Description
-------- | ------ | ---------------------------------
objects | Object | Map of RoomObjects indexed by id
gameTime | Number | Current game tick
info | Object | Contains game mode (usually `"world"`)
visual | Object | Room visuals (contents currently unknown #FIXME)
### Example:
```javascript
// Subscription
api.socket.subscribe('room:W7N7', event => console.log(JSON.stringify(event.data))); // For non-sharded servers
api.socket.subscribe('room:shard0/W7N7', event => console.log(JSON.stringify(event.data))); // For sharded servers
```
```javascript
// First event results:
{
"objects": {
"58dbc28b8283ff5308a3c0ba": {
"_id": "58dbc28b8283ff5308a3c0ba",
"room": "W97S73",
"type": "source",
"x": 12, "y": 14,
"energy": 1908,
"energyCapacity": 3000,
"ticksToRegeneration": 300,
"nextRegenerationTime": 20308471,
"invaderHarvested": 45324
},
"59663a8e82b5ab1b911ca1a9": {
"_id": "59663a8e82b5ab1b911ca1a9",
"type": "road",
"x": 17,"y": 42,
"room": "W97S73",
"notifyWhenAttacked": true,
"hits": 22080,
"hitsMax": 25000,
"nextDecayTime": 20308833
},
// other RoomObjects...
},
"gameTime": 20307112,
"info": { "mode": "world" },
"visual": ""
}
```
```javascript
// Results for subsequent events:
{
"objects": {
"58dbc28b8283ff5308a3c0ba": { "energy": 948, "invaderHarvested": 34284 },
"5967d460eebe3d6404c26852": { "nextDecayTime": 20307861 },
// Other modified RoomObjects...
},
"gameTime": 20307112,
"info": { "mode": "world" },
"visual": ""
}
```

3
node_modules/screeps-api/examples/README.md generated vendored Normal file
View File

@ -0,0 +1,3 @@
# Examples
Warning: These examples may be outdated and plain broken.

128
node_modules/screeps-api/examples/console.js generated vendored Normal file
View File

@ -0,0 +1,128 @@
'use strict'
const { ScreepsAPI } = require('../')
// const auth = require('../auth')
const readline = require('readline')
const util = require('util')
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
prompt: 'Screeps> '
})
let auth = {}
let api = new ScreepsAPI()
if (process.argv.length == 3) {
auth = require(process.argv[2])
}
Promise.resolve(auth)
.then(getEmail)
.then(getPassword)
.then(connect)
.then(start)
.catch(() => {
process.exit(1)
})
function connect (auth) {
return new Promise((resolve, reject) => {
console.log('Authenticating...')
api.auth(auth.email, auth.password, (err, result) => {
if (result) {
console.log('Authentication succeeded')
resolve()
}else {
console.log('Authentication failed')
reject()
}
})
})
}
function start () {
return new Promise((resolve, reject) => {
run()
api.socket(() => {
console.log('start')
rl.prompt()
})
})
}
function getEmail (auth) {
if (auth.email) return auth
return new Promise((resolve, reject) => {
rl.question('Screeps Email: ', (email) => {
auth.email = email.trim()
resolve(auth)
})
})
}
function getPassword (auth) {
if (auth.password) return auth
return new Promise((resolve, reject) => {
rl.question('Screeps Password: ', (password) => {
auth.password = password.trim()
resolve(auth)
})
})
}
function run () {
rl.on('line', (line) => {
line = line.trim()
if (line == 'exit') {
console.log('Bye')
process.exit()
return
}
api.console(line)
})
rl.on('close', () => {
console.log('Bye')
process.exit()
return
})
api.on('message', (msg) => {
console.log(msg)
if (msg.slice(0, 7) == 'auth ok') {
api.subscribe('/console')
console.log('Console connected'.green)
}
})
api.on('console', (msg) => {
let [user, data] = msg
if (data.messages) data.messages.log.forEach(l => console.log(l))
if (data.messages) data.messages.results.forEach(l => console.log('>', l.gray))
if (data.error) console.log(data.error.red)
})
}
// Console fix
var fu = function (type, args) {
var t = Math.ceil((rl.line.length + 3) / process.stdout.columns)
var text = util.format.apply(console, args)
rl.output.write('\n\x1B[' + t + 'A\x1B[0J')
rl.output.write(text + '\n')
rl.output.write(new Array(t).join('\n\x1B[E'))
rl._refreshLine()
}
console.log = function () {
fu('log', arguments)
}
console.warn = function () {
fu('warn', arguments)
}
console.info = function () {
fu('info', arguments)
}
console.error = function () {
fu('error', arguments)
}

41
node_modules/screeps-api/examples/dev_test.js generated vendored Normal file
View File

@ -0,0 +1,41 @@
'use strict'
const { ScreepsAPI } = require('../')
const auth = require('../auth')
const WebSocket = require('ws')
let api = new ScreepsAPI()
Promise.resolve()
.then(()=>api.auth(auth.email,auth.password))
.then(()=>api.socket.connect())
.then(()=>{
api.socket.subscribe('console')
api.socket.subscribe('cpu')
})
.catch((err)=>{
console.error('err',err)
})
let socketEvents = ['connected','disconnected','message','auth','time','protocol','package','subscribe','unsubscribe','console']
socketEvents.forEach(ev=>{
api.socket.on(ev,(data)=>{
console.log(ev,data)
})
})
api.socket.on('disconnected',()=>{
api.socket.connect()
})
// api.socket.on('console', (msg) => {
// // console.log('CONSOLE', msg)
// let { data } = msg
// if (data.messages) data.messages.log.forEach(l => console.log('console',l))
// if (data.messages) data.messages.results.forEach(l => console.log('console >', l))
// if (data.error) console.log('error', data.error)
// })
process.on('unhandledRejection', (reason) => {
console.error('err',reason);
process.exit(1);
});

28
node_modules/screeps-api/examples/download_code.js generated vendored Normal file
View File

@ -0,0 +1,28 @@
'use strict'
const ScreepsAPI = require('../')
const auth = require('../auth')
const WebSocket = require('ws')
const fs = require('fs')
let api = new ScreepsAPI(auth)
api.socket(() => {
})
api.on('message', (msg) => {
// console.log('MSG', msg)
if (msg.slice(0, 7) == 'auth ok') {
api.subscribe('/code')
}
})
// Upload your code to trigger this.
api.on('code', (msg)=>{
let [user, data] = msg
fs.mkdirSync(data.branch)
for(let mod in data.modules){
let file = `${data.branch}/${mod}.js`
fs.writeFileSync(file,data.modules[mod])
console.log('Wrote',file)
}
})

14
node_modules/screeps-api/examples/download_memory.js generated vendored Normal file
View File

@ -0,0 +1,14 @@
'use strict'
const { ScreepsAPI } = require('../')
const auth = require('../auth')
const fs = require('fs')
let api = new ScreepsAPI()
Promise.resolve()
.then(()=>api.auth(auth.email,auth.password))
.then(()=>api.memory.get())
.then(memory=>{
fs.writeFileSync('memory.json',JSON.stringify(memory))
})
.catch(err=>console.error(err))

1
node_modules/screeps-api/index.js generated vendored Normal file
View File

@ -0,0 +1 @@
module.exports = require('./dist/ScreepsAPI.cjs.js')

51
node_modules/screeps-api/package.json generated vendored Normal file
View File

@ -0,0 +1,51 @@
{
"name": "screeps-api",
"version": "1.7.2",
"description": "",
"repository": "screepers/node-screeps-api",
"main": "dist/ScreepsAPI.cjs.js",
"module": "dist/ScreepsAPI.es.js",
"scripts": {
"build": "rollup -c",
"prepublish": "npm run build",
"lint": "standard src test",
"test": "mocha",
"2npm": "publish"
},
"author": "Adam Shumann",
"license": "ISC",
"bin": {
"screeps-api": "bin/screeps-api.js"
},
"dependencies": {
"commander": "^2.15.1",
"bluebird": "^3.5.0",
"fetch-ponyfill": "^6.0.2",
"node-fetch": "^2.1.2",
"ws": "^5.2.0",
"yamljs": "^0.3.0"
},
"optionalDependencies": {
"bufferutil": "^3.0.5",
"utf-8-validate": "^4.0.2"
},
"devDependencies": {
"babel-plugin-external-helpers": "^6.22.0",
"babel-plugin-transform-async-to-generator": "^6.24.1",
"babel-preset-env": "^1.6.0",
"babel-preset-es2015": "^6.24.1",
"lodash": "^4.17.4",
"mocha": "^3.5.0",
"publish": "^0.6.0",
"rollup": "^0.45.2",
"rollup-plugin-babel": "^2.7.1",
"rollup-plugin-commonjs": "^8.0.2",
"rollup-plugin-node-builtins": "^2.1.2",
"rollup-plugin-node-resolve": "^3.0.0",
"rollup-watch": "^4.3.1",
"standard": "*"
},
"browser": {
"ws": "./src/ws-browser.js"
}
}

32
node_modules/screeps-api/rollup.config.js generated vendored Normal file
View File

@ -0,0 +1,32 @@
import resolve from 'rollup-plugin-node-resolve'
import builtins from 'rollup-plugin-node-builtins'
import commonjs from 'rollup-plugin-commonjs'
import babel from 'rollup-plugin-babel'
export default {
entry: 'src/index.js',
// external(id){
// return !!require('./package.json').dependencies[id];
// },
globals: {
ws: 'WebSocket',
'node-fetch': 'fetch'
},
external: ['ws', 'fs', 'node-fetch'],
moduleName: 'ScreepsAPI',
targets: [
{ dest: 'dist/ScreepsAPI.iife.js', format: 'iife' },
{ dest: 'dist/ScreepsAPI.umd.js', format: 'umd' },
{ dest: 'dist/ScreepsAPI.cjs.js', format: 'cjs' },
{ dest: 'dist/ScreepsAPI.es.js', format: 'es' }
],
plugins: [
builtins(),
commonjs(),
resolve({
module: true,
preferBuiltins: true
}),
babel()
]
}

159
node_modules/screeps-api/test/api.general.js generated vendored Normal file
View File

@ -0,0 +1,159 @@
const assert = require('assert')
const _ = require('lodash')
const { ScreepsAPI } = require('../')
const auth = require('./credentials')
describe('ScreepsAPI', function () {
this.slow(2000)
this.timeout(5000)
describe('.constructor()', function () {
it('should save passed options', function () {
let options = {
email: 'screeps@email.com',
// don't use a fake password here or API will try to authenticate
protocol: 'https',
hostname: 'screeps.com',
port: 443,
path: '/'
}
let api = new ScreepsAPI(options)
_.each(options, (value, key) => assert.equal(api.opts[key], value, `invalid ${key} option`))
})
it('should assign default options when needed', function () {
const DEFAULTS = {
protocol: 'https',
hostname: 'screeps.com',
port: 443,
path: '/'
}
let api = new ScreepsAPI({})
_.each(DEFAULTS, (value, key) => assert.equal(api.opts[key], value, `invalid ${key} default option`))
})
})
describe('.me()', function () {
it('should return user informations from `/api/auth/me` endpoint', async function () {
let opts = _.omit(auth, ['username', 'password'])
let api = new ScreepsAPI(opts)
await api.auth(auth.username, auth.password)
let infos = await api.me()
assert.equal(infos.ok, 1, 'incorrect server answer: ok should be 1')
assert(_.has(infos, 'email'), 'answer has no email field')
assert(_.has(infos, 'badge'), 'answer has no badge field')
assert(_.has(infos, 'username'), 'answer has no username field')
})
})
describe('.mapToShard()', function () {
it('should do things... but I\'m not sure what exactly...')
})
describe('.setServer()', function () {
it('should save passed options', function () {
let options = {
email: 'screeps@email.com',
protocol: 'https',
hostname: 'screeps.com',
port: 443,
path: '/'
}
let api = new ScreepsAPI()
api.setServer(options)
_.each(options, (value, key) => assert.equal(api.opts[key], value, `invalid ${key} option`))
})
it('should compute opts.url if opts.url wasn\'t provided', function () {
let options1 = { protocol: 'http', hostname: 'screeps.com' }
let options2 = { protocol: 'https', hostname: 'screeps.com', path: '/ptr/' }
let options3 = { protocol: 'https', hostname: 'screeps.com', port: 80, path: '/' }
let api = new ScreepsAPI()
api.setServer(options1)
assert.equal(api.opts['url'], 'http://screeps.com:443/', 'invalid computed url')
api.setServer(options2)
assert.equal(api.opts['url'], 'https://screeps.com:443/ptr/', 'invalid computed url')
api.setServer(options3)
assert.equal(api.opts['url'], 'https://screeps.com:80/', 'invalid computed url')
})
it('should compute opts.pathname if opts.url wasn\'t provided', function () {
let api = new ScreepsAPI()
api.setServer({ path: '/ptr/' })
assert.equal(api.opts['pathname'], '/ptr/', 'pathname was not updated')
api.setServer({ path: '/' })
assert.equal(api.opts['pathname'], '/', 'pathname was not updated')
})
})
describe('.auth()', function () {
it('should save email and password', async function () {
let api = new ScreepsAPI()
await api.auth('screeps@email.com', 'invalid_password').catch(() => { /* do nothing */; })
assert.equal(api.opts.email, 'screeps@email.com', `invalid email option`)
assert.equal(api.opts.password, 'invalid_password', `invalid email option`)
})
it('should update options if opt object was passed', async function () {
let options = {
protocol: 'https',
hostname: 'screeps.com',
port: 443
}
let api = new ScreepsAPI()
await api.auth('email', 'password', options).catch(() => { /* do nothing */; })
_.each(options, (value, key) => assert.equal(api.opts[key], value, `invalid ${key} option`))
})
it('should authenticate and get token', async function () {
let event = false
let opts = _.omit(auth, ['username', 'password'])
let api = new ScreepsAPI(opts)
api.on('token', () => event = true)
await api.auth(auth.username, auth.password)
assert(event, 'token event was not emited')
assert(_.has(api, 'token'), 'token was not saved')
assert.equal(api.__authed, true, 'internal state has not changed (api.__authed)')
})
it('should reject promise in case of error', async function () {
try {
let api = new ScreepsAPI()
await api.auth(auth.username, 'bad password')
} catch (err) {
assert(err.message.match(/Not authorized/i), 'wrong error message')
}
})
})
describe('.req()', function () {
it('should send request to game server and get the answer')
it('can send GET and POST requests')
it('should throw an error in case of 401 and if not authenticated')
it('should read, save and emit authentication token if any')
it('should use opts.path correctly (ie: for PTR)')
// Disabled, offifical PTR is down
// it('should use opts.path correctly (ie: for PTR)', async function() {
// // This test must be run against official server (the only one to use PTR)
// let opts = {
// protocol: 'https',
// hostname: 'screeps.com',
// port: 443,
// }
// // Get official server time
// let api1 = new ScreepsAPI(opts)
// let res1 = await api1.raw.game.time()
// let time1 = res1.time
// // Get PTR time
// opts.path = '/ptr'
// let api2 = new ScreepsAPI(opts)
// let res2 = await api2.raw.game.time()
// let time2 = res2.time
// // Compare them
// assert.notEqual(time1, time2, 'time for official and PTR should be different')
// })
it('should throw an error if response.ok !== 1')
})
describe('.gz()', function () {
it('should unzip data and return JSON')
})
describe('.inflate()', function () {
it('should inflate data')
})
})

45
node_modules/screeps-api/test/api.raw.auth.js generated vendored Normal file
View File

@ -0,0 +1,45 @@
const assert = require('assert');
const _ = require('lodash');
const { ScreepsAPI } = require('../');
const auth = require('./credentials')
describe('api.raw.auth', function() {
this.slow(2000);
this.timeout(5000);
describe('.signin (email, password)', function() {
it('should send a POST request to /api/auth/signin and authenticate', async function() {
let opts = _.omit(auth, ['username', 'password'])
let api = new ScreepsAPI(opts)
let res = await api.raw.auth.signin(auth.username, auth.password)
assert(_.has(res, 'token'), 'no token found in server answer')
assert.equal(res.ok, 1, 'res.ok is incorrect')
})
it('should reject promise if unauthorized', async function() {
try {
let api = new ScreepsAPI()
await api.raw.auth.signin(auth.username, 'invalid_password')
} catch (err) {
assert(err.message.match(/Not authorized/i), 'wrong error message')
}
})
})
describe('.steamTicket (ticket, useNativeAuth = false)', function() {
it('should do things... but I\'m not sure what exactly...')
})
describe('.me ()', function() {
it('should return user informations from `/api/auth/me` endpoint', async function() {
let opts = _.omit(auth, ['username', 'password'])
let api = new ScreepsAPI(opts)
await api.auth(auth.username, auth.password)
let res = await api.raw.auth.me()
assert(_.has(res, 'email'), 'response has no email field')
assert(_.has(res, 'badge'), 'response has no badge field')
assert(_.has(res, 'username'), 'response has no username field')
})
})
})

120
node_modules/screeps-api/test/api.raw.game.js generated vendored Normal file
View File

@ -0,0 +1,120 @@
const assert = require('assert');
const _ = require('lodash');
const { ScreepsAPI } = require('../');
const auth = require('./credentials')
describe('api.raw.userMessages', function() {
this.slow(2000);
this.timeout(5000);
describe('.mapStats (rooms, statName, shard = DEFAULT_SHARD)', function() {
it('should do untested things (for now)')
})
describe('.genUniqueObjectName (type, shard = DEFAULT_SHARD)', function() {
it('should do untested things (for now)')
})
describe('.checkUniqueObjectName (type, name, shard = DEFAULT_SHARD)', function() {
it('should do untested things (for now)')
})
describe('.placeSpawn (room, x, y, name, shard = DEFAULT_SHARD)', function() {
it('should do untested things (for now)')
})
describe('.createFlag (room, x, y, name, color = 1, secondaryColor = 1, shard = DEFAULT_SHARD)', function() {
it('should do untested things (for now)')
})
describe('.genUniqueFlagName (shard = DEFAULT_SHARD)', function() {
it('should do untested things (for now)')
})
describe('.checkUniqueFlagName (name, shard = DEFAULT_SHARD)', function() {
it('should do untested things (for now)')
})
describe('.changeFlagColor (color = 1, secondaryColor = 1, shard = DEFAULT_SHARD)', function() {
it('should do untested things (for now)')
})
describe('.removeFlag (room, name, shard = DEFAULT_SHARD)', function() {
it('should do untested things (for now)')
})
describe('.addObjectIntent (room, name, intent, shard = DEFAULT_SHARD)', function() {
it('should do untested things (for now)')
})
describe('.createConstruction (room, x, y, structureType, name, shard = DEFAULT_SHARD)', function() {
it('should do untested things (for now)')
})
describe('.setNotifyWhenAttacked (_id, enabled = true, shard = DEFAULT_SHARD)', function() {
it('should do untested things (for now)')
})
describe('.createInvader (room, x, y, size, type, boosted = false, shard = DEFAULT_SHARD)', function() {
it('should do untested things (for now)')
})
describe('.removeInvader (_id, shard = DEFAULT_SHARD)', function() {
it('should do untested things (for now)')
})
describe('.time (shard = DEFAULT_SHARD)', function() {
it('should do untested things (for now)')
})
describe('.worldSize (shard = DEFAULT_SHARD)', function() {
it('should do untested things (for now)')
})
describe('.roomTerrain (room, encoded = 1, shard = DEFAULT_SHARD)', function() {
it('should do untested things (for now)')
})
describe('.roomStatus (room, shard = DEFAULT_SHARD)', function() {
it('should do untested things (for now)')
})
describe('.roomOverview (room, interval = 8, shard = DEFAULT_SHARD)', function() {
it('should do untested things (for now)')
})
describe('.market.ordersIndex (shard = DEFAULT_SHARD)', function() {
it('should do untested things (for now)')
})
describe('.market.myOrders ()', function() {
it('should do untested things (for now)')
})
describe('.market.orders (resourceType, shard = DEFAULT_SHARD)', function() {
it('should do untested things (for now)')
})
describe('.market.stats (resourceType, shard = DEFAULT_SHARD)', function() {
it('should do untested things (for now)')
})
// This endpoint is not implemented on S+
describe.skip('.shards.info ()', function() {
it('should send a request to /api/shards/info and return shards informations', async function() {
let opts = _.omit(auth, ['email', 'password'])
let api = new ScreepsAPI(opts)
let res = await api.raw.game.shards.info()
assert.equal(res.ok, 1, 'incorrect server response: ok should be 1')
assert(_.has(res, 'shards'), 'response has no shards field')
res.shards.forEach((shard, idx) => {
assert(_.has(shard, 'name'), `shard ${idx} has no name field`)
assert(_.has(shard, 'rooms'), `shard ${idx} has no rooms field`)
assert(_.has(shard, 'users'), `shard ${idx} has no users field`)
assert(_.has(shard, 'tick'), `shard ${idx} has no tick field`)
})
})
})
})

62
node_modules/screeps-api/test/api.raw.general.js generated vendored Normal file
View File

@ -0,0 +1,62 @@
const assert = require('assert');
const _ = require('lodash');
const { ScreepsAPI } = require('../');
const auth = require('./credentials')
describe('api.raw', function() {
this.slow(2000);
this.timeout(5000);
describe('.version()', function() {
it('should call /api/version endpoint and return version information', async function() {
let opts = _.omit(auth, ['username', 'password'])
let api = new ScreepsAPI(opts)
let res = await api.raw.version()
assert.equal(res.ok, 1, 'incorrect server response: ok should be 1')
assert(_.has(res, 'protocol'), 'response has no protocol field')
assert(_.has(res, 'serverData.historyChunkSize'), 'response has no serverData.historyChunkSize field')
if (api.opts.hostname === 'screeps.com') {
assert(_.has(res, 'package'), 'response has no package field')
assert(_.has(res, 'serverData.shards'), 'response has no serverData.shards field')
}
})
})
describe('.authmod()', function() {
it('should return server name from /authmod for private servers with authmod', async function() {
let opts = _.omit(auth, ['username', 'password'])
let api = new ScreepsAPI(opts)
let res = await api.raw.authmod()
if (api.opts.hostname === 'screeps.com') {
assert.equal(res.name, 'official', 'invalid name for official server')
} else {
assert.equal(res.ok, 1, 'incorrect server response: ok should be 1')
assert(_.has(res, 'name'), 'server response should have a name field')
assert(_.has(res, 'version'), 'server response should have a version field')
}
})
})
// This API is not implemented for private servers
describe.skip('.history(room, tick)', function() {
it('should return room history as a json file', async function() {
let opts = _.omit(auth, ['username', 'password'])
let api = new ScreepsAPI(opts)
// Get current tick (as history is not kept forever)
let res = await api.raw.game.time('shard1')
let time = res.time - 1000 // history is not available right away
// Make sure that time is not a multiple of 20 or 100
time = (time % 20 === 0) ? time - 10 : time
// Try to get history for W1N1
let json = await api.raw.history('W1N1', time, 'shard1')
// Verify results
assert(_.has(json, 'ticks'), 'result has no ticks field')
assert(_.size(json.ticks) >= 20, 'results are incomplete ; official server usually returns 100 ticks and private servers should return at least 20 ticks')
assert.equal(json.room, 'W1N1', 'result room is incorrect')
assert(_.has(json, 'timestamp'), 'result has no timestamp field')
assert(_.has(json, 'base'), 'result has no base field')
})
})
})

59
node_modules/screeps-api/test/api.raw.leaderboard.js generated vendored Normal file
View File

@ -0,0 +1,59 @@
const assert = require('assert');
const _ = require('lodash');
const { ScreepsAPI } = require('../');
const auth = require('./credentials')
describe('api.raw.leaderboard', function() {
this.slow(2000);
this.timeout(5000);
describe('.list ()', function() {
it('should call /api/leaderboard/list endpoint and return leaderboard inforamtion', async function() {
let opts = _.omit(auth, ['username', 'password'])
let api = new ScreepsAPI(opts)
let res = await api.raw.leaderboard.list()
assert.equal(res.ok, 1, 'incorrect server response: ok should be 1')
assert(_.has(res, 'list'), 'server response should have a list field')
assert(_.has(res, 'count'), 'server response should have a count field')
assert(_.has(res, 'users'), 'server response should have a users field')
if (api.opts.url.includes('screeps.com')) {
assert(_.size(res.list) > 0, 'leaderboard list is empty')
assert(_.size(res.users) > 0, 'leaderboard users is empty')
assert(res.count > 0, 'leaderboard count equals 0 (or maybe is negative)')
}
})
it('should return leaderboard data based on world or power stats', async function() {
let opts = _.omit(auth, ['username', 'password'])
let api = new ScreepsAPI(opts)
let res1 = await api.raw.leaderboard.list(10, 'world')
let res2 = await api.raw.leaderboard.list(10, 'power')
if (api.opts.url.includes('screeps.com')) {
assert.notEqual(_.first(res1.list), _.first(res2.list), 'same player shouldn\'t be #1')
}
})
it('should return paginated data', async function() {
let opts = _.omit(auth, ['username', 'password'])
let api = new ScreepsAPI(opts)
let res1 = await api.raw.leaderboard.list(5, 'world')
let res2 = await api.raw.leaderboard.list(10, 'world')
let res3 = await api.raw.leaderboard.list(10, 'world', 9)
if (api.opts.url.includes('screeps.com')) {
assert.equal(_.size(res1.list), 5, 'requested top 5 and got a shorter or longer list')
assert.equal(_.size(res2.list), 10, 'requested top 10 and got a shorter or longer list')
assert.notEqual(_.first(res1.list).user, _.first(res3.list).user, 'offset is not working')
assert.equal(_.first(res1.list).user, _.first(res2.list).user, 'player #1 is incoherent')
assert.equal(_.last(res2.list).user, _.first(res3.list).user, 'player #9 is incoherent')
}
})
})
describe('.find (username, mode = \'world\', season = \'\')', function() {
it('should do untested things (for now)')
})
describe('.seasons ()', function() {
it('should do untested things (for now)')
})
})

27
node_modules/screeps-api/test/api.raw.register.js generated vendored Normal file
View File

@ -0,0 +1,27 @@
const assert = require('assert');
const _ = require('lodash');
const { ScreepsAPI } = require('../');
const auth = require('./credentials')
describe('api.raw.register', function() {
this.slow(2000);
this.timeout(5000);
describe('.checkEmail (email)', function() {
it('should do untested things (for now)')
})
describe('.checkUsername (username)', function() {
it('should do untested things (for now)')
})
describe('.setUsername (username)', function() {
it('should do untested things (for now)')
})
describe('.submit (username, email, password, modules)', function() {
it('should do untested things (for now)')
})
})

204
node_modules/screeps-api/test/api.raw.user.js generated vendored Normal file
View File

@ -0,0 +1,204 @@
const assert = require('assert');
const _ = require('lodash');
const { ScreepsAPI } = require('../');
const auth = require('./credentials')
describe('api.raw.user', function() {
this.slow(3000);
this.timeout(5000);
describe('.badge (badge)', function() {
it('should send a request to /api/user/badge which sets user badge', async function() {
let opts = _.omit(auth, ['username', 'password'])
let api = new ScreepsAPI(opts)
await api.auth(auth.username, auth.password)
// Save previous badge
let res = await api.me()
let initialBadge = res.badge
// Set new badge
let newBadge = { type: 16, color1: '#000000', color2: '#000000', color3:'#000000', param: 100, flip: false }
res = await api.raw.user.badge(newBadge)
assert.equal(res.ok, 1, 'incorrect server response: ok should be 1')
// Check that badge was effectively changed
res = await api.me()
_.each(res.badge, (value, key) => {
assert.equal(value, newBadge[key], `badge ${key} is incorrect`)
})
// Reset badge
res = await api.raw.user.badge(initialBadge)
})
})
describe('.respawn ()', function() {
it('should do untested things (for now)')
})
describe('.branches ()', function() {
it('should send a request to /api/user/branches and return branches list', async function() {
let opts = _.omit(auth, ['username', 'password'])
let api = new ScreepsAPI(opts)
await api.auth(auth.username, auth.password)
let res = await api.raw.user.branches()
assert.equal(res.ok, 1, 'incorrect server response: ok should be 1')
assert(res.list.length > 0, 'no branch found')
})
})
describe('.cloneBranch (branch, newName, defaultModules)', function() {
it('should send a request to /api/user/clone-branch in order to clone @branch into @newName', async function() {
let opts = _.omit(auth, ['username', 'password'])
let api = new ScreepsAPI(opts)
await api.auth(auth.username, auth.password)
// Create a new branch
let res = await api.raw.user.cloneBranch('default', 'screeps-api-testing')
assert.equal(res.ok, 1, 'incorrect server response: ok should be 1')
// Check if branch was indeed created
res = await api.raw.user.branches()
let found = _.find(res.list, { branch: 'screeps-api-testing' })
assert(found != null, 'branch was not cloned')
})
})
describe('.setActiveBranch (branch, activeName)', function() {
it('should send a request to /api/user/set-active-branch in order to define @branch as active', async function() {
let opts = _.omit(auth, ['username', 'password'])
let api = new ScreepsAPI(opts)
await api.auth(auth.username, auth.password)
// Find current active branch for simulator
let res = await api.raw.user.branches()
let initialBranch = _.find(res.list, { activeSim: true })
assert(initialBranch != null, 'cannot find current active branch for simulator')
// Change active branch for simulator
res = await api.raw.user.setActiveBranch('screeps-api-testing', 'activeSim')
assert.equal(res.ok, 1, 'incorrect server response: ok should be 1')
// Check if branch was indeed changed
res = await api.raw.user.branches()
let found = _.find(res.list, { activeSim: true })
assert.equal(found.branch, 'screeps-api-testing', 'branch was not set')
// Reset branch back to initial state
await api.raw.user.setActiveBranch(initialBranch.branch, 'activeSim')
})
})
describe('.deleteBranch (branch)', function() {
it('should send a request to /api/user/delete-branch in order to delete @branch', async function() {
let opts = _.omit(auth, ['username', 'password'])
let api = new ScreepsAPI(opts)
await api.auth(auth.username, auth.password)
// Delete 'screeps-api-testing' branch
let res = await api.raw.user.deleteBranch('screeps-api-testing')
assert.equal(res.ok, 1, 'incorrect server response: ok should be 1')
// Check if branch was indeed deleted
res = await api.raw.user.branches()
let found = _.find(res.list, { branch: 'screeps-api-testing' })
assert(found == null, 'branch was not deleted')
})
})
describe('.notifyPrefs (prefs)', function() {
it('should send a request to /api/user/notify-prefs which sets user preferences', async function() {
let opts = _.omit(auth, ['username', 'password'])
let api = new ScreepsAPI(opts)
await api.auth(auth.username, auth.password)
let defaults = { disabled: false, disabledOnMessages: false, sendOnline: true, interval: 5, errorsInterval: 30 }
// Save previous prefs
let res = await api.me()
let initialPrefs = _.merge(defaults, res.notifyPrefs)
// Set new preferences
let newPrefs = { disabled: true, disabledOnMessages: true, sendOnline: false, interval: 60, errorsInterval: 60 }
res = await api.raw.user.notifyPrefs(newPrefs)
assert.equal(res.ok, 1, 'incorrect server response: ok should be 1')
// Check that preferences were indeed changed
res = await api.me()
_.each(res.notifyPrefs, (value, key) => {
assert.equal(value, newPrefs[key], `preference ${key} is incorrect`)
})
// Reset preferences
res = await api.raw.user.notifyPrefs(initialPrefs)
})
})
describe('.tutorialDone ()', function() {
it('should do untested things (for now)')
})
describe('.email (email)', function() {
it('should do untested things (for now)')
})
describe('.worldStartRoom (shard)', function() {
it('should do untested things (for now)')
})
describe('.worldStatus ()', function() {
it('should do untested things (for now)')
})
describe('.code.get (branch)', function() {
it('should do untested things (for now)')
it('should send a GET request to /api/user/code and return user code from specified branch.', async function() {
let opts = _.omit(auth, ['username', 'password'])
let api = new ScreepsAPI(opts)
await api.auth(auth.username, auth.password)
let res = await api.raw.user.code.get('default')
assert.equal(res.ok, 1, 'incorrect server response: ok should be 1')
assert(_.has(res, 'modules'), 'response has no modules field')
assert(_.has(res, 'branch'), 'response has no branch field')
assert.equal(res.branch, 'default', 'branch is incorrect')
})
})
describe('.code.set (branch, modules, _hash)', function() {
it('should do untested things (for now)')
})
describe('.respawnProhibitedRooms ()', function() {
it('should do untested things (for now)')
})
describe('.memory.get (path, shard = DEFAULT_SHARD)', function() {
it('should do untested things (for now)')
})
describe('.memory.set (path, value, shard = DEFAULT_SHARD)', function() {
it('should do untested things (for now)')
})
describe('.segment.get (segment, shard = DEFAULT_SHARD)', function() {
it('should do untested things (for now)')
})
describe('.segment.set (segment, data, shard = DEFAULT_SHARD)', function() {
it('should do untested things (for now)')
})
describe('.find (username)', function() {
it('should do untested things (for now)')
})
describe('.findById (id)', function() {
it('should do untested things (for now)')
})
describe('.stats (interval)', function() {
it('should do untested things (for now)')
})
describe('.rooms (id)', function() {
it('should do untested things (for now)')
})
describe('.overview (interval, statName)', function() {
it('should do untested things (for now)')
})
describe('.moneyHistory (page = 0)', function() {
it('should do untested things (for now)')
})
describe('.console (expression, shard = DEFAULT_SHARD)', function() {
it('should do untested things (for now)')
})
})

31
node_modules/screeps-api/test/api.raw.userMessage.js generated vendored Normal file
View File

@ -0,0 +1,31 @@
const assert = require('assert');
const _ = require('lodash');
const { ScreepsAPI } = require('../');
const auth = require('./credentials')
describe('api.raw.userMessages', function() {
this.slow(2000);
this.timeout(5000);
describe('.list (respondent)', function() {
it('should do untested things (for now)')
})
describe('.index ()', function() {
it('should do untested things (for now)')
})
describe('.unreadCount ()', function() {
it('should do untested things (for now)')
})
describe('.send (respondent, text)', function() {
it('should do untested things (for now)')
})
describe('.markRead (id)', function() {
it('should do untested things (for now)')
})
})

7
node_modules/screeps-api/test/credentials.js generated vendored Normal file
View File

@ -0,0 +1,7 @@
module.exports = {
username: 'screeps-api-testing',
password: 'mG3r3TIRbDnSrraGnOdIQyBek1hfxu',
protocol: 'https',
hostname: 'server1.screepspl.us',
port: 443,
};

4274
node_modules/screeps-api/yarn.lock generated vendored Normal file

File diff suppressed because it is too large Load Diff