mowojang 0.4.2 → 0.4.3-dev.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.
package/package.json CHANGED
@@ -1,9 +1,13 @@
1
1
  {
2
2
  "name": "mowojang",
3
- "version": "0.4.2",
3
+ "version": "0.4.3-dev.0",
4
4
  "description": "A simple JavaScript and TypeScript compatible wrapper for the Mowojang-API.",
5
- "main": "dist/src/index.js",
6
- "types": "dist/src/index.d.ts",
5
+ "exports": {
6
+ ".": {
7
+ "types": "./dist/index.d.ts",
8
+ "import": "./dist/index.js"
9
+ }
10
+ },
7
11
  "files": [
8
12
  "dist"
9
13
  ],
@@ -24,16 +28,17 @@
24
28
  "node": ">=22.0.0"
25
29
  },
26
30
  "dependencies": {
27
- "@pixelic/logger": "npm:@jsr/pixelic__logger@^0.0.6",
28
31
  "axios": "^1.16.1",
29
32
  "axios-cache-interceptor": "^1.12.0"
30
33
  },
31
34
  "devDependencies": {
32
35
  "@types/node": "^25.9.1",
36
+ "@pixelic/logger": "npm:@jsr/pixelic__logger@^0.0.6",
37
+ "tsup": "^8.5.1",
33
38
  "typescript": "^6.0.3"
34
39
  },
35
40
  "scripts": {
36
- "build": "pnpm tsc",
41
+ "build": "tsup",
37
42
  "test": "node test test/index.js",
38
43
  "prettier:check": "pnpm dlx prettier . --check",
39
44
  "prettier:write": "pnpm dlx prettier . --write"
package/dist/package.json DELETED
@@ -1,42 +0,0 @@
1
- {
2
- "name": "mowojang",
3
- "version": "0.4.2",
4
- "description": "A simple JavaScript and TypeScript compatible wrapper for the Mowojang-API.",
5
- "main": "dist/src/index.js",
6
- "types": "dist/src/index.d.ts",
7
- "files": [
8
- "dist"
9
- ],
10
- "type": "module",
11
- "scripts": {
12
- "build": "pnpm tsc",
13
- "test": "node test test/index.js",
14
- "prettier:check": "pnpm dlx prettier . --check",
15
- "prettier:write": "pnpm dlx prettier . --write",
16
- "prepare": "pnpm build"
17
- },
18
- "repository": {
19
- "type": "git",
20
- "url": "https://github.com/Pixelicc/mowojang-js"
21
- },
22
- "keywords": [
23
- "Minecraft",
24
- "Mowojang",
25
- "Wrapper",
26
- "API"
27
- ],
28
- "author": "Pixelic",
29
- "license": "MIT",
30
- "engines": {
31
- "node": ">=22.0.0"
32
- },
33
- "dependencies": {
34
- "@pixelic/logger": "npm:@jsr/pixelic__logger@^0.0.6",
35
- "axios": "^1.16.1",
36
- "axios-cache-interceptor": "^1.12.0"
37
- },
38
- "devDependencies": {
39
- "@types/node": "^25.9.1",
40
- "typescript": "^6.0.3"
41
- }
42
- }
@@ -1,5 +0,0 @@
1
- import { type AxiosCacheInstance } from "axios-cache-interceptor";
2
- import type { AxiosOptions } from "../types/index.d.ts";
3
- import type { Logger } from "@pixelic/logger";
4
- declare const _default: (options: AxiosOptions, logger: Logger) => AxiosCacheInstance;
5
- export default _default;
@@ -1,67 +0,0 @@
1
- import axios from "axios";
2
- import { setupCache } from "axios-cache-interceptor";
3
- import PackageJSON from "../package.json" with { type: "json" };
4
- export default (options, logger) => {
5
- const instance = setupCache(axios.create({
6
- timeout: options?.timeout ?? 10000,
7
- maxRedirects: 0,
8
- headers: {
9
- "User-Agent": `axios/${axios.VERSION} mowojang/${PackageJSON.version} (https://www.npmjs.com/package/mowojang)`,
10
- Accept: "application/json",
11
- },
12
- }), {
13
- methods: ["get", "post"],
14
- cacheTakeover: false,
15
- ...options?.cache,
16
- });
17
- instance.interceptors.request.use((req) => {
18
- // @ts-expect-error
19
- req.internalId = Math.random().toString(16).slice(2, 10).padEnd(8, "0");
20
- // @ts-expect-error
21
- logger.debug("Mowojang", `(${req.internalId}) ${req.method?.toUpperCase()} ${axios.getUri(req)}`);
22
- return req;
23
- });
24
- instance.interceptors.response.use((res) => {
25
- if (res.cached) {
26
- logger.debug("Mowojang",
27
- // @ts-expect-error
28
- `(${res.config.internalId}) ${res.stale ? "GET-CACHE-STALE" : "GET-CACHE"} ${axios.getUri(res.config)}`);
29
- }
30
- return res;
31
- }, (err) => {
32
- const isConnectionError = err.code === "ECONNRESET" || err.code === "ETIMEDOUT" || (err?.response?.status ?? 0) >= 500;
33
- if (isConnectionError) {
34
- const fullURL = axios.getUri(err.config);
35
- const host = new URL(fullURL).host;
36
- /**
37
- * If Mowojang (mowojang.matdoes.dev) is down, this falls back to Seraph (mowojang.seraph.si).
38
- * This gets ignored if a different `baseURL` is passed in the initial config.
39
- */
40
- if (host === "mowojang.matdoes.dev" && !err.config._retry) {
41
- err.config._retry = true;
42
- err.config.url = fullURL.replace("mowojang.matdoes.dev", "mowojang.seraph.si");
43
- if (err.config.baseURL)
44
- delete err.config.baseURL;
45
- logger.critical("Mowojang", `(${err.config.internalId}) Failed to establish connection to mowojang.matdoes.dev`);
46
- if (options.fallback) {
47
- logger.info("Mowojang", `(${err.config.internalId}) Retrying request with fallback of mowojang.seraph.si`);
48
- }
49
- logger.info("Mowojang", `Check Status of Mowojang on: https://mowojang-status.pixelic.dev`);
50
- if (options.fallback)
51
- return instance(err.config);
52
- }
53
- else if (host === "mowojang.seraph.si") {
54
- logger.critical("Mowojang", `(${err.config.internalId}) Failed to establish connection to mowojang.seraph.si`);
55
- logger.info("Mowojang", `Check Status of Seraph on: https://mowojang-status.pixelic.dev`);
56
- }
57
- else {
58
- /**
59
- * Logging fallback for a different `baseURL` passed in the initial config.
60
- */
61
- logger.critical("Mowojang", `(${err.config.internalId}) Failed to establish connection to ${host}`);
62
- }
63
- }
64
- return Promise.reject(err);
65
- });
66
- return instance;
67
- };
@@ -1,258 +0,0 @@
1
- import { isAxiosError } from "axios";
2
- import axiosInstance from "./axiosInstance.js";
3
- import { validateArray, validatePlayer, validateUUID } from "./validators.js";
4
- import { undashUUID } from "./utils.js";
5
- import { Logger } from "@pixelic/logger";
6
- export default class Client {
7
- logger;
8
- axios;
9
- validation;
10
- baseURL;
11
- constructor(clientOptions) {
12
- this.logger = new Logger(clientOptions?.logger);
13
- this.validation = clientOptions?.validation ?? {};
14
- this.baseURL = (clientOptions?.baseURL ?? "https://mowojang.matdoes.dev").toLowerCase();
15
- this.axios = axiosInstance({ fallback: true, ...clientOptions }, this.logger);
16
- }
17
- shouldValidate(config) {
18
- return this.validation?.enabled || config?.validation?.enabled || false;
19
- }
20
- getValidationMinLength(config) {
21
- if (this.validation?.minimumUsernameLength === 1)
22
- return 1;
23
- if (this.validation?.minimumUsernameLength === 2)
24
- return 2;
25
- if (config?.validation?.minimumUsernameLength === 1)
26
- return 1;
27
- if (config?.validation?.minimumUsernameLength === 2)
28
- return 2;
29
- return undefined;
30
- }
31
- /**
32
- * Returns an Array of Player Profiles consisting of their Usernames and UUIDs
33
- *
34
- * Players considered "INVALID" are excluded from the results
35
- */
36
- async getProfiles(players, config) {
37
- try {
38
- if (this.shouldValidate(config) && !validateArray(players, validatePlayer, this.getValidationMinLength(config)))
39
- return { data: null, error: "INVALID_INPUT" };
40
- players = players
41
- .map((player) => {
42
- if (validateUUID(player))
43
- return undashUUID(player);
44
- return player.toLowerCase();
45
- })
46
- .sort();
47
- const usePost = config?.usePost ?? false;
48
- if (usePost) {
49
- const fetchResponse = await this.axios.post(this.baseURL, players, {
50
- cache: config?.cache ?? { ttl: 15 * 60 * 1000 },
51
- });
52
- if (!Array.isArray(fetchResponse?.data))
53
- return { data: null, error: "UNKNOWN_ERROR" };
54
- return {
55
- data: fetchResponse.data.map((player) => {
56
- return {
57
- UUID: player.id,
58
- username: player.name,
59
- };
60
- }),
61
- error: null,
62
- };
63
- }
64
- // Default fallback to GET requests via getProfile()
65
- const profilePromises = [];
66
- players.forEach((player) => {
67
- // @ts-ignore
68
- profilePromises.push(this.getProfile(player, config));
69
- });
70
- const profiles = (await Promise.all(profilePromises)).filter((p) => p.data !== null).map((p) => p.data);
71
- return {
72
- // @ts-ignore
73
- data: profiles,
74
- error: null,
75
- };
76
- }
77
- catch {
78
- return { data: null, error: "UNKNOWN_ERROR" };
79
- }
80
- }
81
- /**
82
- * Returns a Player's Profile consisting of their Username and UUID
83
- *
84
- */
85
- async getProfile(player, config) {
86
- try {
87
- if (this.shouldValidate(config) && !validatePlayer(player, this.getValidationMinLength(config)))
88
- return { data: null, error: "INVALID_INPUT" };
89
- const fetchResponse = await this.axios.get(`${this.baseURL}/${player}`, {
90
- cache: config?.cache ?? { ttl: 15 * 60 * 1000 },
91
- });
92
- return {
93
- data: {
94
- UUID: fetchResponse.data.id,
95
- username: fetchResponse.data.name,
96
- },
97
- error: null,
98
- };
99
- }
100
- catch {
101
- return { data: null, error: "INVALID_PLAYER" };
102
- }
103
- }
104
- /**
105
- * A Simple Wrapper to Retrieve Only the UUID of a Player's Profile
106
- *
107
- */
108
- async getUUID(username, config) {
109
- const profile = await this.getProfile(username, config);
110
- if (profile.error)
111
- return null;
112
- return profile.data.UUID;
113
- }
114
- /**
115
- * A Simple Wrapper to Retrieve Only the Username of a Player's Profile
116
- *
117
- */
118
- async getUsername(UUID, config) {
119
- const profile = await this.getProfile(UUID, config);
120
- if (profile.error)
121
- return null;
122
- return profile.data.username;
123
- }
124
- /**
125
- * Returns an Array of Player Sessions consisting of their Usernames, UUIDs, Skins and Capes
126
- *
127
- * Players considered "INVALID" are excluded from the results
128
- */
129
- async getSessions(players, config) {
130
- try {
131
- if (this.shouldValidate(config) && !validateArray(players, validatePlayer, this.getValidationMinLength(config)))
132
- return { data: null, error: "INVALID_INPUT" };
133
- players = players.map((player) => {
134
- if (validateUUID(player))
135
- return undashUUID(player);
136
- return player.toLowerCase();
137
- });
138
- const sessionsPromises = [];
139
- players.forEach((player) => {
140
- // @ts-ignore
141
- sessionsPromises.push(this.getSession(player, config));
142
- });
143
- const sessions = (await Promise.all(sessionsPromises))
144
- .filter((session) => session.data !== null)
145
- .map((session) => session.data);
146
- return {
147
- // @ts-ignore
148
- data: sessions,
149
- error: null,
150
- };
151
- }
152
- catch {
153
- return { data: null, error: "UNKNOWN_ERROR" };
154
- }
155
- }
156
- /**
157
- * Returns a Player's Sessions consisting of their Username, UUID, Skin and Cape
158
- *
159
- */
160
- async getSession(player, config) {
161
- if (this.shouldValidate(config) && !validatePlayer(player, this.getValidationMinLength(config)))
162
- return { data: null, error: "INVALID_INPUT" };
163
- const UUID = await this.getUUID(player);
164
- if (!UUID)
165
- return { data: null, error: "INVALID_PLAYER" };
166
- return await this.axios
167
- .get(`${this.baseURL}/session/minecraft/profile/${UUID}`, {
168
- cache: config?.cache ?? { ttl: 15 * 60 * 1000 },
169
- })
170
- .then((fetchResponse) => {
171
- let textures = fetchResponse.data.properties.find((property) => property.name === "textures").value;
172
- let skin = null;
173
- let cape = null;
174
- if (textures) {
175
- textures = JSON.parse(Buffer.from(textures, "base64").toString()).textures;
176
- if (textures.SKIN) {
177
- skin = {
178
- url: textures.SKIN.url,
179
- hash: textures.SKIN.url.split("/").at(-1),
180
- metadata: {
181
- slim: textures.SKIN?.metadata?.model === "slim",
182
- },
183
- };
184
- }
185
- if (textures.CAPE) {
186
- cape = {
187
- url: textures.CAPE.url,
188
- hash: textures.CAPE.url.split("/").at(-1),
189
- };
190
- }
191
- }
192
- return {
193
- data: {
194
- UUID: fetchResponse.data.id,
195
- username: fetchResponse.data.name,
196
- skin,
197
- cape,
198
- actions: fetchResponse.data.profileActions,
199
- },
200
- error: null,
201
- };
202
- })
203
- .catch((fetchError) => {
204
- if (isAxiosError(fetchError)) {
205
- return { data: null, error: "INVALID_PLAYER" };
206
- }
207
- return { data: null, error: "UNKNOWN_ERROR" };
208
- });
209
- }
210
- /**
211
- * A Simple Wrapper to Retrieve Only the Skin from a Player's Session
212
- *
213
- */
214
- async getSkin(player, config) {
215
- const session = await this.getSession(player, config);
216
- if (session.error)
217
- return null;
218
- return session.data.skin;
219
- }
220
- /**
221
- * A Simple Wrapper to Retrieve Only the Player's Skin from their Session Data Loaded into a Buffer
222
- *
223
- */
224
- async getSkinBuffer(player, config) {
225
- const session = await this.getSession(player, config);
226
- if (session.error || !session.data.skin)
227
- return null;
228
- const fetchResponse = await this.axios.get(session.data.skin.url, {
229
- responseType: "arraybuffer",
230
- cache: config?.cache ?? { ttl: 24 * 60 * 60 * 1000 },
231
- });
232
- return Buffer.from(fetchResponse.data, "base64");
233
- }
234
- /**
235
- * A Simple Wrapper to Retrieve Only the Cape Data from a Player's Session
236
- *
237
- */
238
- async getCape(player, config) {
239
- const session = await this.getSession(player, config);
240
- if (session.error)
241
- return null;
242
- return session.data.cape;
243
- }
244
- /**
245
- * A Simple Wrapper to Retrieve Only the Player's Cape from their Session Data Loaded into a Buffer
246
- *
247
- */
248
- async getCapeBuffer(player, config) {
249
- const session = await this.getSession(player, config);
250
- if (session.error || !session.data.cape)
251
- return null;
252
- const fetchResponse = await this.axios.get(session.data.cape.url, {
253
- responseType: "arraybuffer",
254
- cache: config?.cache ?? { ttl: 30 * 24 * 60 * 60 * 1000 },
255
- });
256
- return Buffer.from(fetchResponse.data, "base64");
257
- }
258
- }
@@ -1,16 +0,0 @@
1
- import client from "./client.js";
2
- import { buildStorage, buildMemoryStorage } from "axios-cache-interceptor";
3
- export declare const Client: typeof client;
4
- export declare const validate: {
5
- player: (player: import("../types/player.js").Player, minimumUsernameLength?: 1 | 2) => boolean;
6
- UUID: (UUID: import("../types/player.js").UUID) => boolean;
7
- username: (username: string, minimumLength?: 1 | 2) => boolean;
8
- };
9
- export declare const utils: {
10
- dashUUID: (UUID: import("../types/player.js").UUID) => import("../types/player.js").UUID;
11
- undashUUID: (UUID: import("../types/player.js").UUID) => import("../types/player.js").UUID;
12
- };
13
- export declare const cache: {
14
- buildStorage: typeof buildStorage;
15
- buildMemoryStorage: typeof buildMemoryStorage;
16
- };
package/dist/src/index.js DELETED
@@ -1,18 +0,0 @@
1
- import client from "./client.js";
2
- import { dashUUID, undashUUID } from "./utils.js";
3
- import { validatePlayer, validateUUID, validateUsername } from "./validators.js";
4
- import { buildStorage, buildMemoryStorage } from "axios-cache-interceptor";
5
- export const Client = client;
6
- export const validate = {
7
- player: validatePlayer,
8
- UUID: validateUUID,
9
- username: validateUsername,
10
- };
11
- export const utils = {
12
- dashUUID,
13
- undashUUID,
14
- };
15
- export const cache = {
16
- buildStorage,
17
- buildMemoryStorage,
18
- };
@@ -1,11 +0,0 @@
1
- import type { UUID } from "../types/index.d.ts";
2
- /**
3
- * Removes dashes from a UUID string
4
- *
5
- */
6
- export declare const undashUUID: (UUID: UUID) => UUID;
7
- /**
8
- * Adds dashes to a UUID string if not already dashed
9
- *
10
- */
11
- export declare const dashUUID: (UUID: UUID) => UUID;
package/dist/src/utils.js DELETED
@@ -1,10 +0,0 @@
1
- /**
2
- * Removes dashes from a UUID string
3
- *
4
- */
5
- export const undashUUID = (UUID) => UUID.replace(/-/g, "").toLowerCase();
6
- /**
7
- * Adds dashes to a UUID string if not already dashed
8
- *
9
- */
10
- export const dashUUID = (UUID) => undashUUID(UUID).replace(/(.{8})(.{4})(.{4})(.{4})(.{12})/, "$1-$2-$3-$4-$5");
@@ -1,19 +0,0 @@
1
- import type { UUID, Player } from "../types/index.d.ts";
2
- /**
3
- * Validates a UUID string both dashed or undashed
4
- *
5
- */
6
- export declare const validateUUID: (UUID: UUID) => boolean;
7
- /**
8
- * Validates a Minecraft Username
9
- *
10
- * @param minimumLength Allows you to set a custom minimum length needed to pass the validation process. This option only exists as older Minecraft Usernames were allowed to be shorter than 3 characters.
11
- */
12
- export declare const validateUsername: (username: string, minimumLength?: 1 | 2) => boolean;
13
- /**
14
- * Validates a Minecraft Player by either validating their Username or supplied UUID
15
- *
16
- * @param minimumUsernameLength Allows you to set a custom minimum length needed to pass the validation process. This option only exists as older Minecraft Usernames were allowed to be shorter than 3 characters.
17
- */
18
- export declare const validatePlayer: (player: Player, minimumUsernameLength?: 1 | 2) => boolean;
19
- export declare const validateArray: <T>(array: T[], validatorFunction: (item: T, ...params: any[]) => boolean, ...params: any[]) => boolean;
@@ -1,38 +0,0 @@
1
- import { undashUUID } from "./utils.js";
2
- /**
3
- * Validates a UUID string both dashed or undashed
4
- *
5
- */
6
- export const validateUUID = (UUID) => {
7
- if (typeof UUID !== "string")
8
- return false;
9
- UUID = undashUUID(UUID);
10
- if (UUID.length !== 32)
11
- return false;
12
- return /[0-9a-f]{12}4[0-9a-f]{19}/.test(UUID);
13
- };
14
- /**
15
- * Validates a Minecraft Username
16
- *
17
- * @param minimumLength Allows you to set a custom minimum length needed to pass the validation process. This option only exists as older Minecraft Usernames were allowed to be shorter than 3 characters.
18
- */
19
- export const validateUsername = (username, minimumLength) => {
20
- if (typeof username !== "string")
21
- return false;
22
- if (minimumLength === 1)
23
- return /^[a-zA-Z0-9_]{1,16}$/.test(username);
24
- if (minimumLength === 2)
25
- return /^[a-zA-Z0-9_]{2,16}$/.test(username);
26
- return /^[a-zA-Z0-9_]{3,16}$/.test(username);
27
- };
28
- /**
29
- * Validates a Minecraft Player by either validating their Username or supplied UUID
30
- *
31
- * @param minimumUsernameLength Allows you to set a custom minimum length needed to pass the validation process. This option only exists as older Minecraft Usernames were allowed to be shorter than 3 characters.
32
- */
33
- export const validatePlayer = (player, minimumUsernameLength) => validateUUID(player) || validateUsername(player, minimumUsernameLength);
34
- export const validateArray = (array, validatorFunction, ...params) => {
35
- if (!Array.isArray(array))
36
- return false;
37
- return array.every((item) => validatorFunction(item, ...params));
38
- };
@@ -1,3 +0,0 @@
1
- export type * from "./misc.d.ts";
2
- export type * from "./player.d.ts";
3
- export type * from "./structures.d.ts";
@@ -1 +0,0 @@
1
- export {};
@@ -1,31 +0,0 @@
1
- import { LoggerConfig } from "@pixelic/logger";
2
- import type { CacheOptions, CacheRequestConfig } from "axios-cache-interceptor";
3
- export type ClientOptions = {
4
- logger?: LoggerConfig;
5
- validation?: ValidationOptions;
6
- timeout?: number;
7
- cache?: CacheOptions;
8
- baseURL?: string;
9
- fallback?: boolean;
10
- };
11
- export type AxiosOptions = {
12
- timeout?: number;
13
- cache?: CacheOptions;
14
- fallback: boolean;
15
- };
16
- export type ValidationOptions = {
17
- enabled?: boolean;
18
- minimumUsernameLength?: 1 | 2;
19
- };
20
- export type MowojangRequestConfig = {
21
- validation?: ValidationOptions;
22
- cache?: CacheRequestConfig<any, any>["cache"];
23
- };
24
- export type MowojangError = "INVALID_PLAYER";
25
- export type MowojangResponse<D, E extends MowojangError | undefined> = Promise<{
26
- data: D;
27
- error: null;
28
- } | {
29
- data: null;
30
- error: E extends undefined ? "UNKNOWN_ERROR" | "INVALID_INPUT" : E | "UNKNOWN_ERROR" | "INVALID_INPUT";
31
- }>;
@@ -1 +0,0 @@
1
- export {};
@@ -1,18 +0,0 @@
1
- /**
2
- * Minecraft Username or UUIDv4 (both undashed and dashed will be accepted)
3
- *
4
- * @example "Technoblade" or "b876ec32-e396-476b-a115-8438d83c67d4"
5
- */
6
- export type Player = string | UUID;
7
- /**
8
- * Minecraft Username
9
- *
10
- * @example "Pixelic"
11
- */
12
- export type Username = string;
13
- /**
14
- * Minecraft UUIDv4 (both undashed and dashed will be accepted)
15
- *
16
- * @example b876ec32e396476ba1158438d83c67d4
17
- */
18
- export type UUID = string;
@@ -1 +0,0 @@
1
- export {};
@@ -1,23 +0,0 @@
1
- import type { UUID, Username } from "./index.d.ts";
2
- export type MowojangProfile = {
3
- UUID: UUID;
4
- username: Username;
5
- };
6
- export type MowojangSession = {
7
- UUID: UUID;
8
- username: Username;
9
- skin: MowojangSkin;
10
- cape: MowojangCape;
11
- actions: ("FORCED_NAME_CHANGE" | "USING_BANNED_SKIN")[];
12
- };
13
- export type MowojangSkin = null | {
14
- url: string;
15
- hash: string;
16
- metadata: {
17
- slim: boolean;
18
- };
19
- };
20
- export type MowojangCape = null | {
21
- url: string;
22
- hash: string;
23
- };
@@ -1 +0,0 @@
1
- export {};