swcombine.js 0.0.11 → 0.1.0

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 (51) hide show
  1. package/LICENSE +5 -17
  2. package/README.md +668 -97
  3. package/dist/index.d.ts +5 -522
  4. package/dist/index.d.ts.map +1 -0
  5. package/dist/index.js +3 -0
  6. package/dist/index.js.map +23 -0
  7. package/dist/src/auth/index.d.ts +8 -0
  8. package/dist/src/auth/index.d.ts.map +1 -0
  9. package/dist/src/auth/oauth-manager.d.ts +168 -0
  10. package/dist/src/auth/oauth-manager.d.ts.map +1 -0
  11. package/dist/src/auth/oauth.d.ts +101 -0
  12. package/dist/src/auth/oauth.d.ts.map +1 -0
  13. package/dist/src/auth/scopes.d.ts +61 -0
  14. package/dist/src/auth/scopes.d.ts.map +1 -0
  15. package/dist/src/auth/types.d.ts +118 -0
  16. package/dist/src/auth/types.d.ts.map +1 -0
  17. package/dist/src/client/base-resource.d.ts +33 -0
  18. package/dist/src/client/base-resource.d.ts.map +1 -0
  19. package/dist/src/client/client.d.ts +85 -0
  20. package/dist/src/client/client.d.ts.map +1 -0
  21. package/dist/src/client/errors.d.ts +63 -0
  22. package/dist/src/client/errors.d.ts.map +1 -0
  23. package/dist/src/client/http-client.d.ts +35 -0
  24. package/dist/src/client/http-client.d.ts.map +1 -0
  25. package/dist/src/client/index.d.ts +15 -0
  26. package/dist/src/client/index.d.ts.map +1 -0
  27. package/dist/src/client/rate-limit.d.ts +12 -0
  28. package/dist/src/client/rate-limit.d.ts.map +1 -0
  29. package/dist/src/client/resources/api.d.ts +42 -0
  30. package/dist/src/client/resources/api.d.ts.map +1 -0
  31. package/dist/src/client/resources/character.d.ts +98 -0
  32. package/dist/src/client/resources/character.d.ts.map +1 -0
  33. package/dist/src/client/resources/faction.d.ts +70 -0
  34. package/dist/src/client/resources/faction.d.ts.map +1 -0
  35. package/dist/src/client/resources/index.d.ts +8 -0
  36. package/dist/src/client/resources/index.d.ts.map +1 -0
  37. package/dist/src/client/resources/inventory.d.ts +205 -0
  38. package/dist/src/client/resources/inventory.d.ts.map +1 -0
  39. package/dist/src/client/types.d.ts +78 -0
  40. package/dist/src/client/types.d.ts.map +1 -0
  41. package/dist/src/index.d.ts +11 -0
  42. package/dist/src/index.d.ts.map +1 -0
  43. package/dist/src/utils/index.d.ts +6 -0
  44. package/dist/src/utils/index.d.ts.map +1 -0
  45. package/dist/src/utils/timestamp.d.ts +188 -0
  46. package/dist/src/utils/timestamp.d.ts.map +1 -0
  47. package/dist/src/utils/types.d.ts +42 -0
  48. package/dist/src/utils/types.d.ts.map +1 -0
  49. package/package.json +35 -55
  50. package/dist/index.cjs.js +0 -772
  51. package/dist/index.esm.js +0 -772
package/dist/index.cjs.js DELETED
@@ -1,772 +0,0 @@
1
- "use strict";
2
- var __defProp = Object.defineProperty;
3
- var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
4
- var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
5
- Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
6
- class GenericResource {
7
- constructor(resourceName) {
8
- __publicField(this, "resourceName");
9
- this.resourceName = resourceName;
10
- }
11
- async get(endpointUrl, accessToken) {
12
- try {
13
- const url = `https://www.swcombine.com/ws/v2.0/${this.resourceName}/${endpointUrl}`;
14
- return await fetch(url, {
15
- headers: {
16
- Accept: "application/json",
17
- ...accessToken ? { Authorization: `OAuth ${accessToken}` } : {}
18
- }
19
- }).then((resp) => {
20
- if (resp.status >= 500) {
21
- console.log("responded:", resp.status);
22
- throw new Error("Not a valid response");
23
- } else if (resp.status >= 200 && resp.status < 300) {
24
- return resp.json();
25
- } else {
26
- return resp.json();
27
- }
28
- });
29
- } catch (err) {
30
- console.warn(err);
31
- throw err;
32
- }
33
- }
34
- }
35
- class PublicApiResource extends GenericResource {
36
- constructor() {
37
- super("api");
38
- }
39
- /**
40
- * Get a list of all permissions in the SWC webservices.
41
- */
42
- async getPermissions() {
43
- const response = await this.get("permissions");
44
- const permissionDtos = [];
45
- if ("error_code" in response.swcapi) {
46
- throw new Error("Something went wrong while attempting to retrieve permissions from the webservices.");
47
- }
48
- for (const apiPermission of response.swcapi.permissions.permission) {
49
- const { name, description, inherits } = apiPermission.attributes;
50
- const inheritsArray = inherits.length == 0 ? [] : inherits.split(" ");
51
- permissionDtos.push({ name, description, inherits: inheritsArray });
52
- }
53
- permissionDtos.sort((a, b) => {
54
- return b.inherits.includes(a.name) ? -1 : 1;
55
- });
56
- const permissions = {};
57
- for (const dto of permissionDtos) {
58
- const inheritedPermissions = dto.inherits.map((x) => permissions[x]);
59
- permissions[dto.name] = { name: dto.name, description: dto.description, inheritedPermissions };
60
- }
61
- return Object.values(permissions);
62
- }
63
- }
64
- class SwcUid {
65
- constructor(param1, id) {
66
- __publicField(this, "_entityType");
67
- __publicField(this, "_id");
68
- if (typeof param1 === "string") {
69
- const [uidType, id2] = param1.split(":");
70
- this._entityType = Number.parseInt(uidType, 10);
71
- this._id = Number.parseInt(id2, 10);
72
- return;
73
- }
74
- this._entityType = param1;
75
- this._id = id;
76
- }
77
- get entityType() {
78
- return this._entityType;
79
- }
80
- get id() {
81
- return this._id;
82
- }
83
- get uid() {
84
- return `${this._entityType}:${this._id}`;
85
- }
86
- }
87
- var SwcUidType;
88
- (function(SwcUidType2) {
89
- SwcUidType2[SwcUidType2["character"] = 1] = "character";
90
- SwcUidType2[SwcUidType2["ship"] = 2] = "ship";
91
- SwcUidType2[SwcUidType2["vehicle"] = 3] = "vehicle";
92
- SwcUidType2[SwcUidType2["facility"] = 4] = "facility";
93
- SwcUidType2[SwcUidType2["station"] = 5] = "station";
94
- SwcUidType2[SwcUidType2["city"] = 7] = "city";
95
- SwcUidType2[SwcUidType2["planet"] = 8] = "planet";
96
- SwcUidType2[SwcUidType2["system"] = 9] = "system";
97
- SwcUidType2[SwcUidType2["npc"] = 10] = "npc";
98
- SwcUidType2[SwcUidType2["creature"] = 11] = "creature";
99
- SwcUidType2[SwcUidType2["item"] = 12] = "item";
100
- SwcUidType2[SwcUidType2["droid"] = 13] = "droid";
101
- SwcUidType2[SwcUidType2["datacard"] = 14] = "datacard";
102
- SwcUidType2[SwcUidType2["material"] = 16] = "material";
103
- SwcUidType2[SwcUidType2["stock"] = 17] = "stock";
104
- SwcUidType2[SwcUidType2["weapon"] = 18] = "weapon";
105
- SwcUidType2[SwcUidType2["faction"] = 20] = "faction";
106
- SwcUidType2[SwcUidType2["race"] = 22] = "race";
107
- SwcUidType2[SwcUidType2["sector"] = 25] = "sector";
108
- SwcUidType2[SwcUidType2["customImage"] = 37] = "customImage";
109
- })(SwcUidType || (SwcUidType = {}));
110
- const _SwcTimestamp = class _SwcTimestamp {
111
- /**
112
- * Create a new SwcTimestamp object for a specific moment in Combine Galactic Time.
113
- * @param {TimestampMoment} source
114
- */
115
- constructor(source) {
116
- __publicField(this, "year");
117
- __publicField(this, "day");
118
- __publicField(this, "hour");
119
- __publicField(this, "minute");
120
- __publicField(this, "second");
121
- const { year, day, hour = 0, minute = 0, second = 0 } = source;
122
- this.year = year;
123
- this.day = day;
124
- this.hour = hour;
125
- this.minute = minute;
126
- this.second = second;
127
- }
128
- /**
129
- * Convert a unix timestamp to Combine Galactic Time.
130
- * @param {number} unixTimestamp timestamp to convert. Can be either seconds or milliseconds, the code will detect which units to use.
131
- * @returns {SwcTimestamp}
132
- */
133
- static fromUnixTimestamp(unixTimestamp) {
134
- if (unixTimestamp < 1e11) {
135
- unixTimestamp = unixTimestamp * 1e3;
136
- }
137
- return this.calculateSwcTimestampFromMillisecondsSinceStart(unixTimestamp - this.swcStart.getTime());
138
- }
139
- /**
140
- * Convert a Date object into Combine Galactic Time.
141
- * @param {Date} date
142
- * @returns {SwcTimestamp}
143
- */
144
- static fromDate(date) {
145
- return this.calculateSwcTimestampFromMillisecondsSinceStart(date.getTime() - this.swcStart.getTime());
146
- }
147
- /**
148
- * Get the current Combine Galactic Time.
149
- * @returns {SwcTimestamp}
150
- */
151
- static now() {
152
- return _SwcTimestamp.fromDate(/* @__PURE__ */ new Date());
153
- }
154
- /**
155
- *
156
- * @param {number} msSinceSwcStart
157
- * @returns {SwcTimestamp}
158
- * @private
159
- */
160
- static calculateSwcTimestampFromMillisecondsSinceStart(msSinceSwcStart) {
161
- const msPerYear = 365 * 24 * 60 * 60 * 1e3;
162
- const msPerDay = 24 * 60 * 60 * 1e3;
163
- const msPerHour = 60 * 60 * 1e3;
164
- const msPerMinute = 60 * 1e3;
165
- const year = Math.floor(msSinceSwcStart / msPerYear);
166
- msSinceSwcStart -= year * msPerYear;
167
- const day = Math.floor(msSinceSwcStart / msPerDay);
168
- msSinceSwcStart -= day * msPerDay;
169
- const hour = Math.floor(msSinceSwcStart / msPerHour);
170
- msSinceSwcStart -= hour * msPerHour;
171
- const minute = Math.floor(msSinceSwcStart / msPerMinute);
172
- msSinceSwcStart -= minute * msPerMinute;
173
- const seconds = Math.floor(msSinceSwcStart / 1e3);
174
- return new _SwcTimestamp({
175
- year,
176
- day: day + 1,
177
- hour,
178
- minute,
179
- second: seconds
180
- });
181
- }
182
- /**
183
- * Convert the SWC timestamp into a unix timestamp
184
- * @param {'sec' | 'ms' | 'seconds' | 'milliseconds'} unit Whether the unix timestamp should be in seconds or milliseconds.
185
- * @returns {number}
186
- */
187
- toUnixTimestamp(unit) {
188
- const raw = this.calculateMillisecondsSinceStartFromSwcTimestamp() + _SwcTimestamp.swcStart.getTime();
189
- if (unit === "sec" || unit === "seconds") {
190
- return raw / 1e3;
191
- } else {
192
- return raw;
193
- }
194
- }
195
- /**
196
- * Convert the SWC timestamp into a Date object.
197
- * @returns {Date}
198
- */
199
- toDate() {
200
- return new Date(this.calculateMillisecondsSinceStartFromSwcTimestamp() + _SwcTimestamp.swcStart.getTime());
201
- }
202
- asMoment() {
203
- return { year: this.year, day: this.day, hour: this.hour, minute: this.minute };
204
- }
205
- /**
206
- * @returns {number}
207
- */
208
- getYear() {
209
- return this.year;
210
- }
211
- /**
212
- * @returns {number}
213
- */
214
- getDay() {
215
- return this.day;
216
- }
217
- /**
218
- * @returns {number}
219
- */
220
- getHour() {
221
- return this.hour;
222
- }
223
- /**
224
- * @returns {number}
225
- */
226
- getMinute() {
227
- return this.minute;
228
- }
229
- /**
230
- * @returns {number}
231
- */
232
- getSecond() {
233
- return this.second;
234
- }
235
- /**
236
- * Calculate a new timestamp by adding time to this timestamp, and return the newly calculated timestamp.
237
- * @param duration
238
- */
239
- add(duration) {
240
- const unixTime = this.toUnixTimestamp("sec");
241
- return _SwcTimestamp.fromUnixTimestamp(unixTime + durationToSeconds(duration));
242
- }
243
- /**
244
- * Calculate a new timestamp by subtracting time from this timestamp, and return the newly calculated timestamp.
245
- * @param duration
246
- */
247
- subtract(duration) {
248
- const unixTime = this.toUnixTimestamp("sec");
249
- return _SwcTimestamp.fromUnixTimestamp(Math.max(unixTime - durationToSeconds(duration), _SwcTimestamp.swcStart.getTime() / 1e3));
250
- }
251
- getDurationTo(otherTimestamp) {
252
- const startTime = this.toUnixTimestamp("sec");
253
- const endTime = otherTimestamp.toUnixTimestamp("sec");
254
- return secondsToDuration(endTime - startTime);
255
- }
256
- /**
257
- * Convert the SWC timestamp to a string (i.e. Year 25 Day 60, 12:45:21).
258
- * You can either pass in a preset name, or a custom format string.
259
- * The following preset formats are available:
260
- *
261
- * 'full': Year 25 Day 60, 6:03:12<br>
262
- * 'minute': Year 25 Day 60, 6:03<br>
263
- * 'day': Year 25 Day 60<br>
264
- * 'shortFull': Y25 D60, 6:03:12<br>
265
- * 'shortMinute': Y25 D60, 6:03<br>
266
- * 'shortDay': Y26 D60<br>
267
- * <br>
268
- * If passing in a custom formatting string, you can use substitution tags to fill in variables. These tags are wrapped in {} and are case-insensitive. The following substitution tags are available:<br>
269
- * {y}: year<br>
270
- * {d}: day<br>
271
- * {h}: hour<br>
272
- * {m}: minute<br>
273
- * {s}: second<br>
274
- * double the tag to get leading zeroes. i.e. {h} = 8, {hh} = 08.<br>
275
- * {hms} is a shorthand for {hh}:{mm}:{ss}.<br>
276
- * Example: '{hms} on Day {d} of Year {y}' becomes '08:12:14 on Day 6 of Year 25'.
277
- * @param format format to use, or custom formatting string.
278
- */
279
- toString(format = "full") {
280
- switch (format) {
281
- case "full":
282
- return `Year ${this.year} Day ${this.day}, ${this.hour}:${this.minute.toString().padStart(2, "0")}:${this.second.toString().padStart(2, "0")}`;
283
- case "minute":
284
- return `Year ${this.year} Day ${this.day}, ${this.hour}:${this.minute.toString().padStart(2, "0")}`;
285
- case "day":
286
- return `Year ${this.year} Day ${this.day}`;
287
- case "shortFull":
288
- return `Y${this.year} D${this.day}, ${this.hour}:${this.minute.toString().padStart(2, "0")}:${this.second.toString().padStart(2, "0")}`;
289
- case "shortMinute":
290
- return `Y${this.year} D${this.day}, ${this.hour}:${this.minute.toString().padStart(2, "0")}}`;
291
- case "shortDay":
292
- return `Y${this.year} D${this.day}`;
293
- }
294
- let formattedString = "";
295
- let currentTag = "";
296
- let isInTag = false;
297
- format.split("").forEach((char) => {
298
- if (char === "{" && !isInTag) {
299
- isInTag = true;
300
- return;
301
- }
302
- if (char === "}" && isInTag) {
303
- formattedString += this.substituteTag(currentTag);
304
- isInTag = false;
305
- currentTag = "";
306
- return;
307
- }
308
- if (isInTag) {
309
- currentTag += char;
310
- } else {
311
- formattedString += char;
312
- }
313
- });
314
- return formattedString;
315
- }
316
- substituteTag(tag) {
317
- if (tag.localeCompare("y", "en", { sensitivity: "accent" }) === 0) {
318
- return this.year.toString();
319
- }
320
- if (tag.localeCompare("yy", "en", { sensitivity: "accent" }) === 0) {
321
- return this.year.toString().padStart(2, "0");
322
- }
323
- if (tag.localeCompare("d", "en", { sensitivity: "accent" }) === 0) {
324
- return this.day.toString();
325
- }
326
- if (tag.localeCompare("dd", "en", { sensitivity: "accent" }) === 0) {
327
- return this.day.toString().padStart(2, "0");
328
- }
329
- if (tag.localeCompare("h", "en", { sensitivity: "accent" }) === 0) {
330
- return this.hour.toString();
331
- }
332
- if (tag.localeCompare("hh", "en", { sensitivity: "accent" }) === 0) {
333
- return this.hour.toString().padStart(2, "0");
334
- }
335
- if (tag.localeCompare("m", "en", { sensitivity: "accent" }) === 0) {
336
- return this.minute.toString();
337
- }
338
- if (tag.localeCompare("mm", "en", { sensitivity: "accent" }) === 0) {
339
- return this.minute.toString().padStart(2, "0");
340
- }
341
- if (tag.localeCompare("s", "en", { sensitivity: "accent" }) === 0) {
342
- return this.second.toString();
343
- }
344
- if (tag.localeCompare("ss", "en", { sensitivity: "accent" }) === 0) {
345
- return this.second.toString().padStart(2, "0");
346
- }
347
- if (tag.localeCompare("hms", "en", { sensitivity: "accent" }) === 0) {
348
- return `${this.hour.toString().padStart(2, "0")}:${this.minute.toString().padStart(2, "0")}:${this.second.toString().padStart(2, "0")}`;
349
- }
350
- return "";
351
- }
352
- /**
353
- * @returns {number}
354
- * @private
355
- */
356
- calculateMillisecondsSinceStartFromSwcTimestamp() {
357
- const msPerYear = 365 * 24 * 60 * 60 * 1e3;
358
- const msPerDay = 24 * 60 * 60 * 1e3;
359
- const msPerHour = 60 * 60 * 1e3;
360
- const msPerMinute = 60 * 1e3;
361
- let msSinceSwcStart = 0;
362
- msSinceSwcStart += this.year * msPerYear;
363
- msSinceSwcStart += (this.day - 1) * msPerDay;
364
- msSinceSwcStart += this.hour * msPerHour;
365
- msSinceSwcStart += this.minute * msPerMinute;
366
- msSinceSwcStart += this.second * 1e3;
367
- return msSinceSwcStart;
368
- }
369
- };
370
- __publicField(_SwcTimestamp, "swcStart", new Date(Date.UTC(1998, 11, 3, 7, 0, 0)));
371
- let SwcTimestamp = _SwcTimestamp;
372
- const durationToSeconds = (duration) => (duration.years || 0) * 365 * 24 * 60 * 60 + (duration.days || 0) * 24 * 60 * 60 + (duration.hours || 0) * 60 * 60 + (duration.minutes || 0) * 60 + (duration.seconds || 0);
373
- const secondsToDuration = (seconds) => {
374
- const secPerYear = 365 * 24 * 60 * 60;
375
- const secPerDay = 24 * 60 * 60;
376
- const secPerHour = 60 * 60;
377
- const secPerMinute = 60;
378
- let secondsToConvert = seconds;
379
- const years = Math.floor(seconds / secPerYear);
380
- secondsToConvert -= years * secPerYear;
381
- const days = Math.floor(seconds / secPerDay);
382
- secondsToConvert -= days * secPerDay;
383
- const hours = Math.floor(seconds / secPerHour);
384
- secondsToConvert -= hours * secPerHour;
385
- const minutes = Math.floor(seconds / secPerMinute);
386
- secondsToConvert -= minutes * secPerMinute;
387
- return { years, days, hours, minutes, seconds: secondsToConvert };
388
- };
389
- function mapSwcResponseToCharacterResponse(swc) {
390
- var _a, _b;
391
- return {
392
- uid: new SwcUid(swc.uid),
393
- name: swc.name,
394
- image: swc.image,
395
- hp: swc.health,
396
- maxHp: swc.healthMax,
397
- xp: swc.XP,
398
- level: swc.XPLevel,
399
- isProfilePrivate: swc.attributes.isprivate === "true",
400
- gender: swc.gender,
401
- biography: swc.biography,
402
- lastLogin: !swc.lastlogin ? void 0 : SwcTimestamp.fromUnixTimestamp(Number.parseInt(swc.lastlogin.timestamp, 10)),
403
- shortDescription: swc.shortdescription,
404
- race: !swc.race.value ? void 0 : { uid: new SwcUid(swc.race.attributes.uid), name: swc.race.value },
405
- isForceAware: !((_b = (_a = swc.force) == null ? void 0 : _a.attributes) == null ? void 0 : _b.isAware) ? void 0 : swc.force.attributes.isAware === "true",
406
- credits: !swc.credits.value ? void 0 : swc.credits.value,
407
- factions: mapSwcFactions(swc.factions),
408
- skills: mapSwcSkills(swc.skills),
409
- factionPrivileges: mapSwcPrivileges(swc.privileges),
410
- location: mapSwcLocation(swc.location)
411
- };
412
- }
413
- function mapSwcFactions(factions) {
414
- if (factions === void 0 || factions.length === 0) {
415
- return [];
416
- }
417
- return factions.map((faction) => ({
418
- uid: new SwcUid(faction.attributes.uid),
419
- name: faction.value,
420
- isPrimary: faction.primary
421
- }));
422
- }
423
- function mapSwcSkills(skills) {
424
- if (!skills.value) {
425
- return void 0;
426
- }
427
- return {
428
- strength: skills.value.general[0].skill.find((x) => x.attributes.type === "strength").value,
429
- dexterity: skills.value.general[0].skill.find((x) => x.attributes.type === "dexterity").value,
430
- speed: skills.value.general[0].skill.find((x) => x.attributes.type === "speed").value,
431
- dodge: skills.value.general[0].skill.find((x) => x.attributes.type === "dodge").value,
432
- projectileWeapons: skills.value.general[0].skill.find((x) => x.attributes.type === "projectile").value,
433
- nonProjectileWeapons: skills.value.general[0].skill.find((x) => x.attributes.type === "nonProjectile").value,
434
- medical: skills.value.social[0].skill.find((x) => x.attributes.type === "medical").value,
435
- diplomacy: skills.value.social[0].skill.find((x) => x.attributes.type === "diplomacy").value,
436
- crafting: skills.value.social[0].skill.find((x) => x.attributes.type === "crafting").value,
437
- management: skills.value.social[0].skill.find((x) => x.attributes.type === "management").value,
438
- perception: skills.value.social[0].skill.find((x) => x.attributes.type === "perception").value,
439
- stealth: skills.value.social[0].skill.find((x) => x.attributes.type === "stealth").value,
440
- rndHull: skills.value.science[0].skill.find((x) => x.attributes.type === "rndHull").value,
441
- rndElectronics: skills.value.science[0].skill.find((x) => x.attributes.type === "rndElectronics").value,
442
- rndEngines: skills.value.science[0].skill.find((x) => x.attributes.type === "rndEngines").value,
443
- rndWeapons: skills.value.science[0].skill.find((x) => x.attributes.type === "rndWeapons").value,
444
- repair: skills.value.science[0].skill.find((x) => x.attributes.type === "repair").value,
445
- computerOperations: skills.value.science[0].skill.find((x) => x.attributes.type === "compOps").value,
446
- fighterPiloting: skills.value.space[0].skill.find((x) => x.attributes.type === "fighterPiloting").value,
447
- fighterCombat: skills.value.space[0].skill.find((x) => x.attributes.type === "fighterCombat").value,
448
- capitalPiloting: skills.value.space[0].skill.find((x) => x.attributes.type === "capitalPiloting").value,
449
- capitalCombat: skills.value.space[0].skill.find((x) => x.attributes.type === "capitalCombat").value,
450
- spaceCommand: skills.value.space[0].skill.find((x) => x.attributes.type === "spaceCommand").value,
451
- vehiclePiloting: skills.value.ground[0].skill.find((x) => x.attributes.type === "vehiclePiloting").value,
452
- vehicleCombat: skills.value.ground[0].skill.find((x) => x.attributes.type === "vehicleCombat").value,
453
- infantryCommand: skills.value.ground[0].skill.find((x) => x.attributes.type === "infantryCommand").value,
454
- vehicleCommand: skills.value.ground[0].skill.find((x) => x.attributes.type === "vehicleCommand").value,
455
- heavyWeapons: skills.value.ground[0].skill.find((x) => x.attributes.type === "heavyWeapons").value
456
- };
457
- }
458
- function mapSwcPrivileges(privileges) {
459
- if (!privileges.value) {
460
- return void 0;
461
- }
462
- return {
463
- factionId: privileges.value.attributes.faction_id,
464
- factionName: privileges.value.attributes.faction_name,
465
- privilegeCount: privileges.value.attributes.count,
466
- privileges: {
467
- setInfoFields: findPrivilege(privileges.value, "members", "set_infofields"),
468
- viewMemberList: findPrivilege(privileges.value, "members", "view_memberlist"),
469
- acceptOrDeclineMembers: findPrivilege(privileges.value, "members", "accept_decline_members"),
470
- expelMembers: findPrivilege(privileges.value, "members", "expel_members"),
471
- isFactionLeader: findPrivilege(privileges.value, "members", "faction_leader"),
472
- viewCredits: findPrivilege(privileges.value, "finance", "view_credits"),
473
- sendCredits: findPrivilege(privileges.value, "finance", "send_credits"),
474
- viewTransactions: findPrivilege(privileges.value, "finance", "view_transactions"),
475
- viewBudgets: findPrivilege(privileges.value, "finance", "view_budgets"),
476
- modifyBudgets: findPrivilege(privileges.value, "finance", "modify_budgets"),
477
- setTaxLevels: findPrivilege(privileges.value, "finance", "set_tax_levels"),
478
- operateVendors: findPrivilege(privileges.value, "finance", "operate_vendors"),
479
- givePrivileges: findPrivilege(privileges.value, "privileges", "give_privs"),
480
- changePasscode: findPrivilege(privileges.value, "privileges", "change_passcode"),
481
- protectAssets: findPrivilege(privileges.value, "privileges", "protect_assets"),
482
- combatEvents: findPrivilege(privileges.value, "privileges", "combat_events"),
483
- manageTemplates: findPrivilege(privileges.value, "privileges", "manage_templates"),
484
- canSeeOverview: findPrivilege(privileges.value, "privileges", "can_see_overview"),
485
- canViewPanelRequests: findPrivilege(privileges.value, "privileges", "can_view_panel_requests"),
486
- enforceArrestWarrant: findPrivilege(privileges.value, "arrest_execute", "enforce_arrest_warrant"),
487
- enforceDeathWarrant: findPrivilege(privileges.value, "arrest_execute", "enforce_death_warrant"),
488
- releasePrisoners: findPrivilege(privileges.value, "arrest_execute", "release_prisoners"),
489
- issueArrestWarrant: findPrivilege(privileges.value, "arrest_execute", "issue_arrest_warrant"),
490
- issueDeathWarrant: findPrivilege(privileges.value, "arrest_execute", "issue_death_warrant"),
491
- modifyFriendFoeList: findPrivilege(privileges.value, "arrest_execute", "modify_iff_list"),
492
- hasSecurityAuthorisation: findPrivilege(privileges.value, "arrest_execute", "security_authorisation"),
493
- postGnsSocial: findPrivilege(privileges.value, "gns", "gns_social"),
494
- postGnsMilitary: findPrivilege(privileges.value, "gns", "gns_military"),
495
- postGnsPolitics: findPrivilege(privileges.value, "gns", "gns_politics"),
496
- postGnsEconomics: findPrivilege(privileges.value, "gns", "gns_economics"),
497
- gnsCensorship: findPrivilege(privileges.value, "gns", "gns_censorship"),
498
- produceInFacilities: findPrivilege(privileges.value, "production", "produce_in_facilities"),
499
- produceInStations: findPrivilege(privileges.value, "production", "produce_in_stations"),
500
- canAbortProduction: findPrivilege(privileges.value, "production", "can_abort_production"),
501
- assignDatacards: findPrivilege(privileges.value, "production", "assign_datacards"),
502
- revokeAssignedDatacards: findPrivilege(privileges.value, "production", "revoke_assigned_datacards"),
503
- constructFacilities: findPrivilege(privileges.value, "production", "construct_facilities"),
504
- constructCities: findPrivilege(privileges.value, "production", "construct_cities"),
505
- constructStations: findPrivilege(privileges.value, "production", "construct_stations"),
506
- canAbortConstruction: findPrivilege(privileges.value, "production", "can_abort_construction"),
507
- performAsteroidMining: findPrivilege(privileges.value, "production", "perform_asteroid_mining"),
508
- performRecycling: findPrivilege(privileges.value, "production", "perform_recycling"),
509
- purchaseNpcs: findPrivilege(privileges.value, "npc_management", "npc_purchase"),
510
- editNpcs: findPrivilege(privileges.value, "npc_management", "npc_edit"),
511
- fireNpcs: findPrivilege(privileges.value, "npc_management", "npc_fire"),
512
- isSecondInCommand: findPrivilege(privileges.value, "second_in_command", "second_in_command"),
513
- assignTags: findPrivilege(privileges.value, "tags", "assign_tags"),
514
- renameTags: findPrivilege(privileges.value, "tags", "rename_tags"),
515
- createTags: findPrivilege(privileges.value, "tags", "create_tags"),
516
- deleteTags: findPrivilege(privileges.value, "tags", "delete_tags"),
517
- viewCombatReports: findPrivilege(privileges.value, "combat_reports", "view_combat_reports"),
518
- launchGarrisonSquad: findPrivilege(privileges.value, "combat_reports", "launch_garrison_squad"),
519
- modifyGarrisonReserve: findPrivilege(privileges.value, "combat_reports", "modify_garrison_reserve"),
520
- launchCargoSquad: findPrivilege(privileges.value, "npc_transport", "cargo_squad_launch"),
521
- linkCargoBase: findPrivilege(privileges.value, "npc_transport", "cargo_base_link"),
522
- viewCargoSquad: findPrivilege(privileges.value, "npc_transport", "cargo_squad_view"),
523
- changeFactionProfile: findPrivilege(privileges.value, "faction_management", "change_faction_profile"),
524
- renameFaction: findPrivilege(privileges.value, "faction_management", "rename_faction"),
525
- factionCustomImages: findPrivilege(privileges.value, "faction_management", "faction_custom_images"),
526
- createSubfactions: findPrivilege(privileges.value, "faction_management", "create_subfactions"),
527
- manageSubfactionMembers: findPrivilege(privileges.value, "faction_management", "manage_subfaction_members"),
528
- subfactionFullPrivileges: findPrivilege(privileges.value, "faction_management", "subfaction_full_privileges"),
529
- manageFactionModules: findPrivilege(privileges.value, "faction_management", "manage_faction_modules"),
530
- manageAlliance: findPrivilege(privileges.value, "faction_management", "manage_alliance"),
531
- viewShips: findPrivilege(privileges.value, "ship", "view"),
532
- assignShips: findPrivilege(privileges.value, "ship", "assign"),
533
- renameShips: findPrivilege(privileges.value, "ship", "rename"),
534
- makeoverShips: findPrivilege(privileges.value, "ship", "makeover"),
535
- viewVehicles: findPrivilege(privileges.value, "vehicle", "view"),
536
- assignVehicles: findPrivilege(privileges.value, "vehicle", "assign"),
537
- renameVehicles: findPrivilege(privileges.value, "vehicle", "rename"),
538
- makeoverVehicles: findPrivilege(privileges.value, "vehicle", "makeover"),
539
- viewItems: findPrivilege(privileges.value, "item", "view"),
540
- assignItems: findPrivilege(privileges.value, "item", "assign"),
541
- renameItems: findPrivilege(privileges.value, "item", "rename"),
542
- makeoverItems: findPrivilege(privileges.value, "item", "makeover"),
543
- viewDroids: findPrivilege(privileges.value, "droid", "view"),
544
- assignDroids: findPrivilege(privileges.value, "droid", "assign"),
545
- renameDroids: findPrivilege(privileges.value, "droid", "rename"),
546
- makeoverDroids: findPrivilege(privileges.value, "droid", "makeover"),
547
- viewStations: findPrivilege(privileges.value, "station", "view"),
548
- assignStations: findPrivilege(privileges.value, "station", "assign"),
549
- renameStations: findPrivilege(privileges.value, "station", "rename"),
550
- makeoverStations: findPrivilege(privileges.value, "station", "makeover"),
551
- stationControlRoom: findPrivilege(privileges.value, "station", "controlroom"),
552
- manageStationPermissions: findPrivilege(privileges.value, "station", "permissions"),
553
- viewFacilities: findPrivilege(privileges.value, "facility", "view"),
554
- assignFacilities: findPrivilege(privileges.value, "facility", "assign"),
555
- renameFacilities: findPrivilege(privileges.value, "facility", "rename"),
556
- makeoverFacilities: findPrivilege(privileges.value, "facility", "makeover"),
557
- facilityControlRoom: findPrivilege(privileges.value, "facility", "controlroom"),
558
- manageFacilityPermissions: findPrivilege(privileges.value, "facility", "permissions"),
559
- viewMaterials: findPrivilege(privileges.value, "materials", "view"),
560
- assignMaterials: findPrivilege(privileges.value, "materials", "assign"),
561
- renameMaterials: findPrivilege(privileges.value, "materials", "rename"),
562
- makeoverMaterials: findPrivilege(privileges.value, "materials", "makeover"),
563
- viewNpcs: findPrivilege(privileges.value, "npc", "view"),
564
- assignNpcs: findPrivilege(privileges.value, "npc", "assign"),
565
- renameNpcs: findPrivilege(privileges.value, "npc", "rename"),
566
- makeoverNpcs: findPrivilege(privileges.value, "npc", "makeover"),
567
- viewCities: findPrivilege(privileges.value, "cities", "view"),
568
- assignCities: findPrivilege(privileges.value, "cities", "assign"),
569
- renameCities: findPrivilege(privileges.value, "cities", "rename"),
570
- makeoverCities: findPrivilege(privileges.value, "cities", "makeover"),
571
- manageCityPermissions: findPrivilege(privileges.value, "cities", "permissions"),
572
- viewCreatures: findPrivilege(privileges.value, "creature", "view"),
573
- assignCreatures: findPrivilege(privileges.value, "creature", "assign"),
574
- renameCreatures: findPrivilege(privileges.value, "creature", "rename"),
575
- makeoverCreatures: findPrivilege(privileges.value, "creature", "makeover"),
576
- viewPlanets: findPrivilege(privileges.value, "planets", "view"),
577
- assignPlanets: findPrivilege(privileges.value, "planets", "assign"),
578
- viewStocks: findPrivilege(privileges.value, "stock", "view"),
579
- makeoverStocks: findPrivilege(privileges.value, "stock", "makeover"),
580
- viewDatacards: findPrivilege(privileges.value, "datacard", "view")
581
- }
582
- };
583
- }
584
- function findPrivilege(privileges, groupName, privilegeName) {
585
- const group = privileges.privilegegroup.find((x) => x.attributes.name === groupName);
586
- if (!group)
587
- return false;
588
- const privilege = group.privilege.find((x) => x.attributes.uid === privilegeName);
589
- return !!privilege && privilege.value === "true";
590
- }
591
- function mapSwcLocation(location) {
592
- var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l;
593
- if (!location)
594
- return void 0;
595
- return {
596
- container: !location.container.value ? void 0 : {
597
- uid: new SwcUid(location.container.attributes.uid),
598
- name: location.container.value,
599
- type: location.container.attributes.type
600
- },
601
- sector: !((_a = location.sector) == null ? void 0 : _a.value) ? void 0 : { uid: new SwcUid(location.sector.attributes.uid), name: location.sector.value },
602
- system: !((_b = location.system) == null ? void 0 : _b.value) ? void 0 : { uid: new SwcUid(location.system.attributes.uid), name: location.system.value },
603
- planet: !((_c = location.planet) == null ? void 0 : _c.value) ? void 0 : { uid: new SwcUid(location.planet.attributes.uid), name: location.planet.value },
604
- city: !((_d = location.city) == null ? void 0 : _d.value) ? void 0 : { uid: new SwcUid(location.city.attributes.uid), name: location.city.value },
605
- coordinates: {
606
- galaxy: parseCoords((_e = location.coordinates.galaxy.attributes) == null ? void 0 : _e.x, (_f = location.coordinates.galaxy.attributes) == null ? void 0 : _f.y),
607
- system: parseCoords((_g = location.coordinates.system.attributes) == null ? void 0 : _g.x, (_h = location.coordinates.system.attributes) == null ? void 0 : _h.y),
608
- surface: parseCoords((_i = location.coordinates.surface.attributes) == null ? void 0 : _i.x, (_j = location.coordinates.surface.attributes) == null ? void 0 : _j.y),
609
- ground: parseCoords((_k = location.coordinates.ground.attributes) == null ? void 0 : _k.x, (_l = location.coordinates.ground.attributes) == null ? void 0 : _l.y)
610
- }
611
- };
612
- }
613
- function parseCoords(x, y) {
614
- if (x === null || x === void 0 || y === null || y === void 0)
615
- return { x: null, y: null };
616
- const intX = typeof x === "number" ? x : Number.parseInt(x, 10);
617
- const intY = typeof y === "number" ? y : Number.parseInt(y, 10);
618
- if (!Number.isFinite(intX) || !Number.isFinite(intY))
619
- return { x: null, y: null };
620
- return { x: intX, y: intY };
621
- }
622
- class PublicCharacterResource extends GenericResource {
623
- constructor() {
624
- super("character");
625
- }
626
- async handleCheck(handle) {
627
- const response = await this.get(`handlecheck/${handle}`);
628
- if ("error_code" in response.swcapi) {
629
- return void 0;
630
- }
631
- return { handle: response.swcapi.character.handle, uid: new SwcUid(response.swcapi.character.uid) };
632
- }
633
- }
634
- class AuthenticatedCharacterResource extends PublicCharacterResource {
635
- constructor(auth) {
636
- super();
637
- __publicField(this, "auth");
638
- this.auth = auth;
639
- }
640
- async getCurrentCharacter() {
641
- const accessToken = await this.auth.getAccessToken();
642
- const response = await this.get("", accessToken);
643
- if ("error_code" in response.swcapi) {
644
- throw new Error(`Something went wrong while attempting to call the GET character endpoint: ${response.swcapi.error_message}`);
645
- }
646
- return mapSwcResponseToCharacterResponse(response.swcapi.character);
647
- }
648
- }
649
- class AuthService {
650
- constructor(config) {
651
- __publicField(this, "config");
652
- __publicField(this, "tokenInfo");
653
- this.config = config;
654
- }
655
- get isAuthenticated() {
656
- if (!this.tokenInfo)
657
- return false;
658
- if (/* @__PURE__ */ new Date() >= this.tokenInfo.expiryTime && !this.tokenInfo.refreshToken) {
659
- this.tokenInfo = void 0;
660
- return false;
661
- }
662
- return true;
663
- }
664
- async getAccessToken() {
665
- var _a;
666
- if (this.tokenInfo && /* @__PURE__ */ new Date() < this.tokenInfo.expiryTime) {
667
- return this.tokenInfo.accessToken;
668
- }
669
- if (!((_a = this.tokenInfo) == null ? void 0 : _a.refreshToken)) {
670
- this.tokenInfo = void 0;
671
- throw new Error("No access token available or access token has expired, and no refresh token is available to refresh it.");
672
- }
673
- await this.refreshToken();
674
- return this.tokenInfo.accessToken;
675
- }
676
- /**
677
- *
678
- * @param scopesToRequest Indicates the resource access your application is requesting. The values passed in this parameter inform the consent page shown to the user. There is an inverse relationship between the number of permissions requested and the likelihood of obtaining user consent
679
- * @param stateToAdd Indicates any state which may be useful to your application upon receipt of the response. The Web Service Authorization Server roundtrips this parameter, so your application receives the same value it sent. Possible uses include redirecting the user to the correct resource in your site, nonces, and cross-site-request-forgery mitigations.
680
- */
681
- getAuthorizationUrl(scopesToRequest, stateToAdd) {
682
- const params = new URLSearchParams();
683
- params.append("response_type", "code");
684
- params.append("client_id", this.config.clientId);
685
- params.append("redirect_uri", this.config.redirectUri);
686
- params.append("state", stateToAdd || "");
687
- params.append("scope", (this.config.defaultScopes || []).concat(scopesToRequest || []).join(" "));
688
- params.append("access_type", this.config.accessType);
689
- params.append("renew_previously_granted", this.config.renewPreviouslyGranted ? "yes" : "no");
690
- return `https://www.swcombine.com/ws/oauth2/auth/?${params.toString()}`;
691
- }
692
- async exchangeCode(code) {
693
- const form = new FormData();
694
- form.append("grant_type", "authorization_code");
695
- form.append("code", code);
696
- form.append("client_id", this.config.clientId);
697
- form.append("client_secret", this.config.clientSecret);
698
- form.append("redirect_uri", this.config.redirectUri);
699
- form.append("access_type", this.config.accessType);
700
- const response = await fetch("https://www.swcombine.com/ws/oauth2/token/", {
701
- method: "POST",
702
- body: form,
703
- headers: { Accept: "application/json" }
704
- });
705
- if (!response.ok) {
706
- throw new Error("Something went wrong while attempting to exchange an authorization code for an access token.");
707
- }
708
- const payload = await response.json();
709
- this.tokenInfo = {
710
- accessToken: payload.access_token,
711
- expiryTime: new Date((/* @__PURE__ */ new Date()).getTime() + payload.expires_in * 1e3),
712
- refreshToken: payload.refresh_token
713
- };
714
- }
715
- setTokenInfo(tokenInfo) {
716
- this.tokenInfo = tokenInfo;
717
- }
718
- getTokenInfo() {
719
- return this.tokenInfo ? { ...this.tokenInfo } : void 0;
720
- }
721
- async refreshToken() {
722
- if (!this.tokenInfo || !this.tokenInfo.refreshToken || this.config.accessType !== "offline") {
723
- throw new Error("Cannot refresh access token.");
724
- }
725
- const form = new FormData();
726
- form.append("grant_type", "refresh_token");
727
- form.append("access_type", this.config.accessType);
728
- form.append("client_id", this.config.clientId);
729
- form.append("client_secret", this.config.clientSecret);
730
- form.append("refresh_token", this.tokenInfo.refreshToken);
731
- const response = await fetch("https://www.swcombine.com/ws/oauth2/token/", {
732
- method: "POST",
733
- body: form,
734
- headers: { Accept: "application/json" }
735
- });
736
- if (!response.ok) {
737
- throw new Error("Something went wrong while attempting to exchange a refresh token to an access token.");
738
- }
739
- const payload = await response.json();
740
- this.tokenInfo = {
741
- accessToken: payload.access_token,
742
- expiryTime: new Date((/* @__PURE__ */ new Date()).getTime() + payload.expires_in * 1e3),
743
- refreshToken: payload.refresh_token
744
- };
745
- }
746
- }
747
- class SwcClient {
748
- constructor() {
749
- __publicField(this, "api");
750
- __publicField(this, "character");
751
- this.api = new PublicApiResource();
752
- this.character = new PublicCharacterResource();
753
- }
754
- static public() {
755
- return new SwcClient();
756
- }
757
- static withOAuth(oAuthConfig) {
758
- return new SwcClientWithOAuth(oAuthConfig);
759
- }
760
- }
761
- class SwcClientWithOAuth extends SwcClient {
762
- constructor(config) {
763
- super();
764
- __publicField(this, "auth");
765
- this.auth = new AuthService(config);
766
- this.character = new AuthenticatedCharacterResource(this.auth);
767
- }
768
- }
769
- exports.AuthService = AuthService;
770
- exports.SwcClient = SwcClient;
771
- exports.SwcClientWithOAuth = SwcClientWithOAuth;
772
- exports.SwcTimestamp = SwcTimestamp;