clashofclans.js 1.5.4 → 2.0.0-dev.2c5b083

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (69) hide show
  1. package/CHANGELOG.md +17 -0
  2. package/LICENSE +2 -1
  3. package/README.md +39 -110
  4. package/dist/client/Client.d.ts +177 -0
  5. package/dist/client/Client.js +237 -0
  6. package/dist/client/EventManager.d.ts +86 -0
  7. package/dist/client/EventManager.js +279 -0
  8. package/dist/index.d.ts +9 -0
  9. package/dist/index.js +21 -0
  10. package/dist/rest/HTTPError.d.ts +24 -0
  11. package/dist/rest/HTTPError.js +42 -0
  12. package/dist/rest/RESTManager.d.ts +56 -0
  13. package/dist/rest/RESTManager.js +123 -0
  14. package/dist/rest/RequestHandler.d.ts +162 -0
  15. package/dist/rest/RequestHandler.js +198 -0
  16. package/dist/rest/Throttler.d.ts +31 -0
  17. package/dist/rest/Throttler.js +86 -0
  18. package/dist/struct/Achievement.d.ts +25 -0
  19. package/dist/struct/Achievement.js +28 -0
  20. package/dist/struct/Badge.d.ts +16 -0
  21. package/dist/struct/Badge.js +27 -0
  22. package/dist/struct/ChatLanguage.d.ts +11 -0
  23. package/dist/struct/ChatLanguage.js +12 -0
  24. package/dist/struct/Clan.d.ts +64 -0
  25. package/dist/struct/Clan.js +44 -0
  26. package/dist/struct/ClanMember.d.ts +32 -0
  27. package/dist/struct/ClanMember.js +28 -0
  28. package/dist/struct/ClanWar.d.ts +137 -0
  29. package/dist/struct/ClanWar.js +198 -0
  30. package/dist/struct/ClanWarLeagueGroup.d.ts +63 -0
  31. package/dist/struct/ClanWarLeagueGroup.js +85 -0
  32. package/dist/struct/ClanWarLog.d.ts +54 -0
  33. package/dist/struct/ClanWarLog.js +46 -0
  34. package/dist/struct/Icon.d.ts +16 -0
  35. package/dist/struct/Icon.js +27 -0
  36. package/dist/struct/Label.d.ts +12 -0
  37. package/dist/struct/Label.js +13 -0
  38. package/dist/struct/League.d.ts +14 -0
  39. package/dist/struct/League.js +18 -0
  40. package/dist/struct/LegendStatistics.d.ts +18 -0
  41. package/dist/struct/LegendStatistics.js +17 -0
  42. package/dist/struct/Location.d.ts +15 -0
  43. package/dist/struct/Location.js +14 -0
  44. package/dist/struct/Player.d.ts +78 -0
  45. package/dist/struct/Player.js +72 -0
  46. package/dist/struct/PlayerClan.d.ts +19 -0
  47. package/dist/struct/PlayerClan.js +19 -0
  48. package/dist/struct/Ranking.d.ts +58 -0
  49. package/dist/struct/Ranking.js +50 -0
  50. package/dist/struct/Season.d.ts +19 -0
  51. package/dist/struct/Season.js +21 -0
  52. package/dist/struct/Unit.d.ts +68 -0
  53. package/dist/struct/Unit.js +90 -0
  54. package/dist/struct/WarLeague.d.ts +11 -0
  55. package/dist/struct/WarLeague.js +16 -0
  56. package/dist/struct/index.d.ts +19 -0
  57. package/dist/struct/index.js +31 -0
  58. package/dist/types/index.d.ts +350 -0
  59. package/dist/types/index.js +2 -0
  60. package/dist/util/Constants.d.ts +41 -0
  61. package/dist/util/Constants.js +122 -0
  62. package/dist/util/Util.d.ts +18 -0
  63. package/dist/util/Util.js +53 -0
  64. package/dist/util/raw.json +1 -0
  65. package/package.json +109 -36
  66. package/src/index.d.ts +0 -811
  67. package/src/index.js +0 -5
  68. package/src/struct/Client.js +0 -481
  69. package/src/util/Extension.js +0 -130
package/src/index.js DELETED
@@ -1,5 +0,0 @@
1
- module.exports = {
2
- Client: require('./struct/Client'),
3
- version: require('../package.json').version,
4
- Extension: require('./util/Extension').Extension
5
- };
@@ -1,481 +0,0 @@
1
- const { Extension } = require('../util/Extension');
2
- const fetch = require('node-fetch');
3
-
4
- /**
5
- * Represents Base Client
6
- * @class
7
- * @example
8
- * const { Client } = require('clashofclans.js');
9
- */
10
- class Client {
11
- /**
12
- * Represents Clash of Clans API
13
- *
14
- * In order to access the API, you need a developer account and a key for your application.
15
- *
16
- * {@link https://developer.clashofclans.com}
17
- * @param {ClientOptions} [options={}] - Client Options
18
- * @example
19
- * const { Client } = require('clashofclans.js');
20
- * const client = new Client({ keys: ['API_KEY'] });
21
- */
22
- constructor(options = {}) {
23
- this._tokenIndex = 0;
24
- this.timeout = options.timeout || 0;
25
- this.keys = options.keys || options.token;
26
- this.baseURL = options.baseURL || 'https://api.clashofclans.com/v1';
27
-
28
- if (options.token) {
29
- process.emitWarning(
30
- 'The `token` field is considered deprecated and will be removed in the next version, use `keys` instead.',
31
- 'DeprecationWarning'
32
- );
33
- }
34
- }
35
-
36
- /**
37
- * Initialize Extension class and create keys
38
- * @param {ExtensionOptions} options Required extension options.
39
- * @returns {string[]} Created Tokens
40
- * @example
41
- * const { Client } = require('clashofclans.js');
42
- * const client = new Client();
43
- * (async () => {
44
- * await client.init({ email: '', password: '' });
45
- * // you would have to run the `init` method just for once.
46
- *
47
- * const data = await client.clan('#2PP');
48
- * console.log(data);
49
- * })();
50
- */
51
- async init(options = {}) {
52
- this.keys = [];
53
-
54
- const ext = new Extension({
55
- email: options.email,
56
- keyName: options.keyName,
57
- password: options.password,
58
- keyCount: options.keyCount,
59
- keyDescription: options.keyDescription
60
- });
61
-
62
- return ext.login().then(() => {
63
- this.keys = ext.keys;
64
- return ext.keys;
65
- });
66
- }
67
-
68
- get _tokens() {
69
- return Array.isArray(this.keys) ? [...this.keys] : [this.keys];
70
- }
71
-
72
- get _token() {
73
- const token = this._tokens[this._tokenIndex];
74
- this._tokenIndex = (this._tokenIndex + 1) >= this._tokens.length ? 0 : this._tokenIndex + 1;
75
- return token;
76
- }
77
-
78
- async fetch(path) {
79
- const res = await fetch(`${this.baseURL}${path}`, {
80
- method: 'GET',
81
- headers: {
82
- Authorization: `Bearer ${this._token}`,
83
- Accept: 'application/json'
84
- },
85
- timeout: Number(this.timeout)
86
- }).catch(() => null);
87
-
88
- return this.toJSON(res);
89
- }
90
-
91
- async toJSON(res) {
92
- const parsed = await res?.json().catch(() => null);
93
- if (!parsed) return { ok: false, statusCode: res?.status ?? 504, maxAge: 0 };
94
-
95
- const maxAge = res?.headers.get('cache-control')?.split('=')?.[1] ?? 0;
96
- return Object.assign(parsed, { statusCode: res?.status ?? 504, ok: res?.status === 200, maxAge: Number(maxAge) * 1000 });
97
- }
98
-
99
- /**
100
- * Parse a clan or player Tag
101
- * @param {string} tag Tag of clans or players
102
- * @throws {TypeError} The "tag" argument must be of type string
103
- * @returns {string} Fixed Tag
104
- * @example
105
- * // Fix Lowercase, Zero and Missing Hash #
106
- * client.parseTag('PccVqqGO'); // #PCCVQQG0
107
- */
108
- parseTag(tag) {
109
- if (tag && typeof tag === 'string') {
110
- return `#${tag.toUpperCase().replace(/O|o/g, '0').replace(/^#/g, '')}`;
111
- }
112
- throw TypeError('The "tag" argument must be of type string.');
113
- }
114
-
115
- encodeTag(tag) {
116
- return encodeURIComponent(this.parseTag(tag));
117
- }
118
-
119
- /**
120
- * Search clans
121
- * @param {ClanSearchOptions} [options={}] - Search clans by name or filtering parameters.
122
- *
123
- * **- If name is used as part of search query, it needs to be at least three characters long.**
124
- *
125
- * **- Name search parameter is interpreted as wild card search, so it may appear anywhere in the clan name.**
126
- * @example
127
- * client.clans({ name: 'air hounds', limit: 10 });
128
- * // or
129
- * client.clans({ minMembers: 40, maxMembers: 50 });
130
- * @returns {Promise<Object>} Object
131
- */
132
- async clans(options) {
133
- const query = new URLSearchParams(options).toString();
134
- return this.fetch(`/clans?${query}`);
135
- }
136
-
137
- /**
138
- * Get clan information
139
- * @param {string} clanTag - Tag of the clan.
140
- * @example
141
- * client.clan('#8QU8J9LP');
142
- * @returns {Promise<Object>} Object
143
- */
144
- async clan(clanTag) {
145
- return this.fetch(`/clans/${this.encodeTag(clanTag)}`);
146
- }
147
-
148
- /**
149
- * List clan members
150
- * @param {string} clanTag - Tag of the clan.
151
- * @param {SearchOptions} [options={}] - Optional options
152
- * @example
153
- * client.clanMembers('#8QU8J9LP', { limit: 10 });
154
- * @returns {Promise<Object>} Object
155
- */
156
- async clanMembers(clanTag, options) {
157
- const query = new URLSearchParams(options).toString();
158
- return this.fetch(`/clans/${this.encodeTag(clanTag)}/members?${query}`);
159
- }
160
-
161
- /**
162
- * Detailed clan members
163
- * @param {Array.<{ tag: string }>} members - List of members
164
- * @example
165
- * const data = await client.clan('#8QU8J9LP');
166
- * client.detailedClanMembers(data.memberList);
167
- * @returns {Promise<Object>} Player Objects
168
- */
169
- async detailedClanMembers(members) {
170
- return Promise.all(members.map(mem => this.player(mem.tag)));
171
- }
172
-
173
- /**
174
- * Retrieve clan's clan war log
175
- * @param {string} clanTag - Tag of the clan.
176
- * @param {SearchOptions} [options={}] - Optional options
177
- * @example
178
- * client.clanWarLog('#8QU8J9LP', { limit: 10 });
179
- * @returns {Promise<Object>} Object
180
- */
181
- async clanWarLog(clanTag, options) {
182
- const query = new URLSearchParams(options).toString();
183
- return this.fetch(`/clans/${this.encodeTag(clanTag)}/warlog?${query}`);
184
- }
185
-
186
- /**
187
- * Retrieve information about clan's current clan war
188
- * @param {string} clanTag - Tag of the clan.
189
- * @param {SearchOptions} [options={}] - Optional options
190
- * @example
191
- * client.currentClanWar('#8QU8J9LP');
192
- * @returns {Promise<Object>} Object
193
- */
194
- async currentClanWar(clanTag, options) {
195
- const query = new URLSearchParams(options).toString();
196
- return this.fetch(`/clans/${this.encodeTag(clanTag, true)}/currentwar?${query}`);
197
- }
198
-
199
- /**
200
- * Retrieve information about clan's current clan war league group
201
- * @param {string} clanTag - Tag of the clan.
202
- * @example
203
- * client.clanWarLeague('#8QU8J9LP');
204
- * @returns {Promise<Object>} Object
205
- */
206
- async clanWarLeague(clanTag) {
207
- return this.fetch(`/clans/${this.encodeTag(clanTag)}/currentwar/leaguegroup`);
208
- }
209
-
210
- /**
211
- * Retrieve information about individual clan war league war
212
- * @param {string} warTag - WarTag of a CWL round.
213
- * @example
214
- * client.clanWarLeagueWar('#2QJQPYLJU');
215
- * @returns {Promise<Object>} Object
216
- */
217
- async clanWarLeagueWar(warTag) {
218
- return this.fetch(`/clanwarleagues/wars/${this.encodeTag(warTag)}`);
219
- }
220
-
221
- /**
222
- * Get player information.
223
- * @param {string} playerTag - Tag of the player.
224
- * @example
225
- * client.player('#9Q92C8R20');
226
- * @returns {Promise<Object>} Object
227
- */
228
- async player(playerTag) {
229
- return this.fetch(`/players/${this.encodeTag(playerTag)}`);
230
- }
231
-
232
- /**
233
- * Verify player API token that can be found from the game settings. This API call can be used to check that players own the game accounts they claim to own as they need to provide the one-time use API token that exists inside the game.
234
- * @param {string} playerTag Tag of the player.
235
- * @param {string} token Player API token.
236
- * @example
237
- * client.verifyPlayerToken('#9Q92C8R20', 'pd3NN9x2');
238
- * @returns {Promise<Object>} Object
239
- */
240
- async verifyPlayerToken(playerTag, token) {
241
- const res = await fetch(`${this.baseURL}/players/${this.encodeTag(playerTag)}/verifytoken`, {
242
- method: 'POST',
243
- body: JSON.stringify({ token }),
244
- headers: {
245
- Authorization: `Bearer ${this._token}`,
246
- Accept: 'application/json'
247
- },
248
- timeout: Number(this.timeout)
249
- }).catch(() => null);
250
-
251
- return this.toJSON(res);
252
- }
253
-
254
- /**
255
- * List Leagues
256
- * @param {SearchOptions} [options={}] - Optional options
257
- * @example
258
- * client.leagues();
259
- * @returns {Promise<Object>} Object
260
- */
261
- async leagues(options) {
262
- const query = new URLSearchParams(options).toString();
263
- return this.fetch(`/leagues?${query}`);
264
- }
265
-
266
- /**
267
- * Get league information
268
- * @param {string} leagueId - Identifier of the league.
269
- * @example
270
- * client.league('29000022');
271
- * @returns {Promise<Object>} Object
272
- */
273
- async league(leagueId) {
274
- return this.fetch(`/leagues/${leagueId}`);
275
- }
276
-
277
- /**
278
- * Get league seasons. Note that league season information is available only for Legend League.
279
- * @param {string} leagueId - Identifier of the league.
280
- * @param {SearchOptions} [options={}] - Optional options
281
- * @example
282
- * client.leagueSeason('29000022', { limit: 10 });
283
- * @returns {Promise<Object>} Object
284
- */
285
- async leagueSeason(leagueId, options) {
286
- const query = new URLSearchParams(options).toString();
287
- return this.fetch(`/leagues/${leagueId}/seasons?${query}`);
288
- }
289
-
290
- /**
291
- * Get league season rankings. Note that league season information is available only for Legend League.
292
- * @param {string} leagueId - Identifier of the league.
293
- * @param {string} seasonId - Identifier of the season.
294
- * @param {SearchOptions} [options={}] - Optional options
295
- * @example
296
- * client.leagueRanking('29000022', '2020-03', { limit: 10 });
297
- * @returns {Promise<Object>} Object
298
- */
299
- async leagueRanking(leagueId, seasonId, options) {
300
- const query = new URLSearchParams(options).toString();
301
- return this.fetch(`/leagues/${leagueId}/seasons/${seasonId}?${query}`);
302
- }
303
-
304
- /**
305
- * List war leagues
306
- * @param {SearchOptions} [options={}] - Optional options
307
- * @example
308
- * client.warLeagues();
309
- * @returns {Promise<Object>} Object
310
- */
311
- async warLeagues(options) {
312
- const query = new URLSearchParams(options).toString();
313
- return this.fetch(`/warleagues?${query}`);
314
- }
315
-
316
- /**
317
- * Get war league information
318
- * @param {string} leagueId - Identifier of the league.
319
- * @example
320
- * client.warLeague('48000018');
321
- * @returns {Promise<Object>} Object
322
- */
323
- async warLeague(leagueId) {
324
- return this.fetch(`/warleagues/${leagueId}`);
325
- }
326
-
327
- /**
328
- * List locations
329
- * @param {SearchOptions} [options={}] - Optional options
330
- * @example
331
- * client.locations();
332
- * // OR
333
- * client.locations({ limit: 10 });
334
- * @returns {Promise<Object>} Object
335
- */
336
- async locations(options) {
337
- const query = new URLSearchParams(options).toString();
338
- return this.fetch(`/locations?${query}`);
339
- }
340
-
341
- /**
342
- * Get information about specific location
343
- * @param {string} locationId - Identifier of the location to retrieve.
344
- * @example
345
- * client.location('32000107');
346
- * @returns {Promise<Object>} Object
347
- */
348
- async location(locationId) {
349
- return this.fetch(`/locations/${locationId}`);
350
- }
351
-
352
- /**
353
- * Get clan rankings for a specific location
354
- * @param {string|'global'} locationId - Identifier of the location to retrieve.
355
- * @param {SearchOptions} [options={}] - Optional options
356
- * @example
357
- * client.clanRanks('32000107', { limit: 10 });
358
- * @returns {Promise<Object>} Object
359
- */
360
- async clanRanks(locationId, options) {
361
- const query = new URLSearchParams(options).toString();
362
- return this.fetch(`/locations/${locationId}/rankings/clans?${query}`);
363
- }
364
-
365
- /**
366
- * Get player rankings for a specific location
367
- * @param {string|'global'} locationId - Identifier of the location to retrieve.
368
- * @param {SearchOptions} [options={}] - Optional options
369
- * @example
370
- * client.playerRanks('32000107', { limit: 10 });
371
- * @returns {Promise<Object>} Object
372
- */
373
- async playerRanks(locationId, options) {
374
- const query = new URLSearchParams(options).toString();
375
- return this.fetch(`/locations/${locationId}/rankings/players?${query}`);
376
- }
377
-
378
- /**
379
- * Get clan versus rankings for a specific location
380
- * @param {string|'global'} locationId - Identifier of the location to retrieve.
381
- * @param {SearchOptions} [options={}] - Optional options
382
- * @example
383
- * client.versusClanRanks('32000107', { limit: 10 });
384
- * @returns {Promise<Object>} Object
385
- */
386
- async versusClanRanks(locationId, options) {
387
- const query = new URLSearchParams(options).toString();
388
- return this.fetch(`/locations/${locationId}/rankings/clans-versus?${query}`);
389
- }
390
-
391
- /**
392
- * Get player versus rankings for a specific location
393
- * @param {string|'global'} locationId - Identifier of the location to retrieve.
394
- * @param {SearchOptions} [options={}] - Optional options
395
- * @example
396
- * client.versusPlayerRanks('32000107', { limit: 10 });
397
- * @returns {Promise<Object>} Object
398
- */
399
- async versusPlayerRanks(locationId, options) {
400
- const query = new URLSearchParams(options).toString();
401
- return this.fetch(`/locations/${locationId}/rankings/players-versus?${query}`);
402
- }
403
-
404
- /**
405
- * List clan labels
406
- * @param {SearchOptions} [options={}] - Optional options
407
- * @example
408
- * client.clanLabels();
409
- * @returns {Promise<Object>} Object
410
- */
411
- async clanLabels(options) {
412
- const query = new URLSearchParams(options).toString();
413
- return this.fetch(`/labels/clans?${query}`);
414
- }
415
-
416
- /**
417
- * List player labels
418
- * @param {SearchOptions} [options={}] - Optional options
419
- * @example
420
- * client.playerLabels();
421
- * @returns {Promise<Object>} Object
422
- */
423
- async playerLabels(options) {
424
- const query = new URLSearchParams(options).toString();
425
- return this.fetch(`/labels/players?${query}`);
426
- }
427
-
428
- /**
429
- * Get information about the current gold pass season.
430
- * @returns {Promise<Object>} Object
431
- */
432
- async goldPassSeason() {
433
- return this.fetch('/goldpass/seasons/current');
434
- }
435
- }
436
-
437
- module.exports = Client;
438
-
439
- /**
440
- * TypeDefs
441
- * @namespace core
442
- */
443
-
444
- /**
445
- * Base Client Options
446
- * @typedef {Object} ClientOptions
447
- * @memberof core
448
- * @property {string} keys - Clash of Clans API keys(s)
449
- * @property {number} timeout - Request timeout in millisecond
450
- * @property {string} [baseURL] - Clash of Clans API Base URL
451
- */
452
-
453
- /**
454
- * Clan Search Options
455
- *
456
- * **- If name is used as part of search query, it needs to be at least three characters long.**
457
- *
458
- * **- Name search parameter is interpreted as wild card search, so it may appear anywhere in the clan name.**
459
- * @typedef {Object} ClanSearchOptions
460
- * @memberof core
461
- * @property {string} name - Search clans by name.
462
- * @property {string} warFrequency - Filter by clan war frequency
463
- * @property {string} locationId - Filter by clan location identifier. For list of available locations, refer to getLocations operation
464
- * @property {number} minMembers - Filter by minimum number of clan members
465
- * @property {number} maxMembers - Filter by maximum number of clan members
466
- * @property {number} minClanPoints - Filter by minimum amount of clan points.
467
- * @property {number} minClanLevel - Filter by minimum clan level.
468
- * @property {number} limit - Limit the number of items returned in the response.
469
- * @property {string} after - Return only items that occur after this marker. Before marker can be found from the response, inside the 'paging' property. Note that only after or before can be specified for a request, not both.
470
- * @property {string} before - Return only items that occur before this marker. Before marker can be found from the response, inside the 'paging' property. Note that only after or before can be specified for a request, not both.
471
- * @property {string} labelIds - Comma separatered list of label IDs to use for filtering results.
472
- */
473
-
474
- /**
475
- * Search Options
476
- * @typedef {Object} SearchOptions
477
- * @memberof core
478
- * @property {number} limit - Limit the number of items returned in the response.
479
- * @property {string} after - Return only items that occur after this marker. Before marker can be found from the response, inside the 'paging' property. Note that only after or before can be specified for a request, not both.
480
- * @property {string} before - Return only items that occur before this marker. Before marker can be found from the response, inside the 'paging' property. Note that only after or before can be specified for a request, not both.
481
- */
@@ -1,130 +0,0 @@
1
- const fetch = require('node-fetch');
2
-
3
- /**
4
- * Extension class for creating Clash of Clans API keys for the external IP the code is running on.
5
- * @class
6
- * @example
7
- * const { Extension } = require('clashofclans.js');
8
- */
9
- class Extension {
10
- /**
11
- * Extension
12
- * @param {ExtensionOptions} options - Required extension options.
13
- * @example
14
- * (async () => {
15
- * const ext = new Extension({ email: '', password: '' });
16
- * await ext.login();
17
- * // you would have to run the `login` method just for once.
18
- *
19
- * console.log(ext.keys);
20
- * })();
21
- */
22
- constructor(options = {}) {
23
- this._keys = [];
24
- this.email = options.email;
25
- this.password = options.password;
26
- this.keyCount = Math.min(options.keyCount, 10) || 1;
27
- this.keyName = options.keyName || 'Created by clashofclans.js client';
28
- this.keyDescription = options.keyDescription || new Date().toUTCString();
29
- this.baseURL = options.baseURL || 'https://developer.clashofclans.com/api';
30
- }
31
-
32
- /**
33
- * Created Keys
34
- * @type {string[]}
35
- */
36
- get keys() {
37
- return this._keys;
38
- }
39
-
40
- /**
41
- * Initialize Login method.
42
- * @returns {string[]}
43
- * @throws {Error} Failed to create API Tokens!
44
- */
45
- async login() {
46
- this._keys = []; // Clear Expired Keys
47
-
48
- const res = await fetch(`${this.baseURL}/login`, {
49
- method: 'POST',
50
- headers: { 'Content-Type': 'application/json' },
51
- body: JSON.stringify({ email: this.email, password: this.password })
52
- });
53
-
54
- const data = await res.json();
55
- if (data.status && data.status.message === 'ok') {
56
- await this.getKeys(res.headers.get('set-cookie'));
57
- return this.keys;
58
- }
59
- throw Error(`[Login Failed] email: ${this.email}, password: ${this.password}`);
60
- }
61
-
62
- async getKeys(cookie) {
63
- const res = await fetch(`${this.baseURL}/apikey/list`, {
64
- method: 'POST',
65
- headers: { 'Content-Type': 'application/json', cookie }
66
- });
67
-
68
- const data = await res.json();
69
- if (!res.ok) {
70
- throw Error(`Failed to Fetch Keys [${JSON.stringify(data)}]`);
71
- }
72
- const keys = data.keys?.filter(key => key.name === this.keyName);
73
- if (!keys.length) return this.createKey(cookie);
74
-
75
- if (this.keyCount > (10 - (data.keys.length - keys.length))) {
76
- throw Error(`Insufficient slot to create ${this.keyCount} key(s).`);
77
- }
78
-
79
- for (const key of keys) await this.revokeKey(key, cookie);
80
- return Promise.all(Array(this.keyCount).fill(0).map(() => this.createKey(cookie)));
81
- }
82
-
83
- async revokeKey(key, cookie) {
84
- const res = await fetch(`${this.baseURL}/apikey/revoke`, {
85
- method: 'POST',
86
- headers: { 'Content-Type': 'application/json', cookie },
87
- body: JSON.stringify({ id: key.id })
88
- });
89
-
90
- return res.json().catch(() => null);
91
- }
92
-
93
- async createKey(cookie) {
94
- const IP = await this.getIP();
95
- const res = await fetch(`${this.baseURL}/apikey/create`, {
96
- method: 'POST',
97
- headers: { 'Content-Type': 'application/json', cookie },
98
- body: JSON.stringify({
99
- name: this.keyName,
100
- description: this.keyDescription,
101
- cidrRanges: [IP]
102
- })
103
- });
104
-
105
- const data = await res.json();
106
- if (res.ok && data.key) {
107
- return this._keys.push(data.key.key);
108
- }
109
- throw Error(`Failed to create API Tokens. IP: ${IP} [${JSON.stringify(data)}]`);
110
- }
111
-
112
- async getIP() {
113
- const res = await fetch('https://api.ipify.org/');
114
- return res.text();
115
- }
116
- }
117
-
118
- module.exports = { Extension };
119
-
120
- /**
121
- * Extension client options
122
- * @memberof core
123
- * @typedef {Object} ExtensionOptions
124
- * @param {string} email Developer account Email
125
- * @param {string} password Developer account Password
126
- * @param {number} [keyCount=1] Number of Key(s)
127
- * @param {string} [keyName='Created by clashofclans.js client'] Name of the Key(s)
128
- * @param {string} [keyDescription=new Date().toUTCString()] Description of the Key(s)
129
- * @param {string} [baseURL='https://developer.clashofclans.com/api'] Developer Site Base URL
130
- */