Skip to content

Commit

Permalink
stuff ig?
Browse files Browse the repository at this point in the history
  • Loading branch information
Owen3H committed Oct 20, 2023
1 parent 0cbed32 commit cf31a33
Show file tree
Hide file tree
Showing 15 changed files with 74 additions and 53 deletions.
3 changes: 2 additions & 1 deletion .eslintrc.json
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,8 @@
"markers": [
"#region",
"#endregion",
"@ts-expect-error"
"@ts-expect-error",
"@ts-ignore"
]
}],
"comma-spacing": 2,
Expand Down
1 change: 1 addition & 0 deletions .npmignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
**/*.tsbuildinfo
8 changes: 3 additions & 5 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -10,22 +10,20 @@
"default": "./dist/main.cjs"
},
"scripts": {
"prepublishOnly": "npm run ci",
"prepublishOnly": "npm run ci && npm run docs",
"ci": "pnpm run lint && pnpm run test && pnpm run build",
"lint": "npx eslint .",
"clean": "rimraf dist",
"build": "npm run clean && rollup -c && tsc --declaration true --emitDeclarationOnly true --declarationMap && npm run docs",
"build": "npm run clean && rollup -c && tsc --declaration true --emitDeclarationOnly true --declarationMap",
"docs": "npx typedoc --options typedoc.json",
"test": "vitest run --config ./vitest.config.ts",
"test-browser": "vitest run --browser.name=chrome --browser.headless --config ./vitest.config.ts"
},
"files": [
"dist",
"src",
"LICENSE",
"README.md",
"package.json",
"endpoints.json"
"package.json"
],
"keywords": [
"earth",
Expand Down
22 changes: 10 additions & 12 deletions src/Map.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
import DataHandler from './helpers/DataHandler.js'

import Towns from './classes/Towns.js'
import Nations from './classes/Nations.js'
import Players from './classes/Players.js'
import Residents from './classes/Residents.js'
import GPS from './classes/GPS.js'
import Towns from './api/Towns.js'
import Nations from './api/Nations.js'
import Players from './api/Players.js'
import Residents from './api/Residents.js'
import GPS from './api/GPS.js'

import * as fn from './utils/functions.js'
import { Point2D, TownBounds, ValidMapName } from './types.js'
Expand Down Expand Up @@ -59,22 +59,20 @@ class Map extends DataHandler {
return inBounds
}

readonly isWilderness = async (location: Point2D) => {
return !(await this.withinTown(location))
}
readonly isWilderness = async (location: Point2D) => !(await this.withinTown(location))

readonly withinBounds = (location: Point2D, bounds: TownBounds) => {
if (fn.strictFalsy(location.x) || fn.strictFalsy(location.z)) {
const obj = JSON.stringify(location)
throw new ReferenceError(`(withinBounds) - Invalid location:\n${obj}`)
}

const xLoc = parseInt(String(location.x))
const zLoc = parseInt(String(location.z))
const locX = fn.safeParseInt(location.x)
const locZ = fn.safeParseInt(location.z)

// Check if the given coordinates are within the bounds or on the bounds
const withinX = xLoc >= Math.min(...bounds.x) && xLoc <= Math.max(...bounds.x)
const withinZ = zLoc >= Math.min(...bounds.z) && zLoc <= Math.max(...bounds.z)
const withinX = locX >= Math.min(...bounds.x) && locX <= Math.max(...bounds.x)
const withinZ = locZ >= Math.min(...bounds.z) && locZ <= Math.max(...bounds.z)

return withinX && withinZ
}
Expand Down
11 changes: 7 additions & 4 deletions src/api/GPS.ts
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,10 @@ class GPS extends Mitt {
}
}
else {
this.lastLoc = { x: player.x, z: player.z }
this.lastLoc = {
x: fn.safeParseInt(player.x),
z: fn.safeParseInt(player.z)
}

try {
const routeInfo = await this.findRoute({
Expand Down Expand Up @@ -126,7 +129,7 @@ class GPS extends Mitt {
// Use reduce to find the minimum distance and corresponding nation
const { distance, nation } = filtered.reduce((acc: any, nation: Nation) => {
const capital = nation.capital
const dist = fn.manhattan(capital.x, capital.z, loc.x, loc.z)
const dist = fn.manhattan(capital.x, capital.z, fn.safeParseInt(loc.x), fn.safeParseInt(loc.z))

// Update acc if this nation is closer
const closer = !acc.distance || dist < acc.distance
Expand All @@ -145,8 +148,8 @@ class GPS extends Mitt {

static cardinalDirection(loc1: Location, loc2: Location) {
// Calculate the differences in x and z coordinates
const deltaX = loc2.x - loc1.x
const deltaZ = loc2.z - loc1.z
const deltaX = fn.safeParseInt(loc2.x) - fn.safeParseInt(loc1.x)
const deltaZ = fn.safeParseInt(loc2.z) - fn.safeParseInt(loc1.z)

const angleRad = Math.atan2(deltaZ, deltaX) // Calculate the angle in radians
const angleDeg = (angleRad * 180) / Math.PI // Convert the angle from radians to degrees
Expand Down
16 changes: 7 additions & 9 deletions src/api/Nations.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,12 +40,10 @@ class Nations implements Base {
len = towns.length

for (let i = 0; i < len; i++) {
const town = towns[i],
nationName = town.nation

if (nationName == "No Nation") {
continue
}
const town = towns[i]

const nationName = town.nation
if (nationName == "No Nation") continue

// Doesn't already exist, create new.
if (!raw[nationName]) {
Expand Down Expand Up @@ -101,11 +99,11 @@ class Nations implements Base {
}

readonly joinable = async (townName: string, nationless = true): Promise<Nation[] | FetchError> => {
let town = null
let town: Town = null
try {
town = await this.map.Towns.get(townName)
town = await this.map.Towns.get(townName) as Town
} catch (_) {
return new FetchError(`Specified town '${townName}' does not exist!`)
throw new FetchError(`Specified town '${townName}' does not exist!`)
}

const nations = await this.all(this.map.getFromCache('towns'))
Expand Down
3 changes: 2 additions & 1 deletion src/api/Players.ts
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,8 @@ class Players implements Base {

return players.filter(p => {
if (p.x == 0 && p.z == 0) return
return fn.hypot(p.x, [xInput, xRadius]) && fn.hypot(p.z, [zInput, zRadius])
return fn.hypot(fn.safeParseInt(p.x), [xInput, xRadius]) &&
fn.hypot(fn.safeParseInt(p.z), [zInput, zRadius])
})
}
}
Expand Down
6 changes: 3 additions & 3 deletions src/types/gps.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,12 +16,12 @@ export type RouteKey = keyof RouteType
export type Route = RouteType[RouteKey]

export type Location = Point2D & {
y?: number
y?: number | string
}

export type Point2D = {
x: number
z: number
x: number | string
z: number | string
}

export type RouteInfo = {
Expand Down
18 changes: 9 additions & 9 deletions src/types/oapi_v2.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { Location } from '../types.js'
import { NestedOmit } from './util.js'
import { NestedOmit, Prettify } from './util.js'

//#region Parsed
export type OAPITown = NestedOmit<RawTown,
Expand Down Expand Up @@ -110,11 +110,11 @@ export type RawEntityPerms<PermsType> = {
}
}

export type RawEntitySpawn = Location & {
export type RawEntitySpawn = Prettify<Location & {
world: string
pitch?: number
yaw?: number
}
}>

export type RawTownCoordinates = {
spawn: RawEntitySpawn
Expand All @@ -125,7 +125,7 @@ export type RawTownCoordinates = {
}
}

export type RawTown = RawEntity & {
export type RawTown = Prettify<RawEntity & {
name: string
board: string
mayor: string
Expand All @@ -138,9 +138,9 @@ export type RawTown = RawEntity & {
residents: string[]
trusted?: string[]
outlaws?: string[]
}
}>

export type RawNation = RawEntity & {
export type RawNation = Prettify<RawEntity & {
name: string
board?: string
king: string
Expand All @@ -151,7 +151,7 @@ export type RawNation = RawEntity & {
residents: string[]
allies?: string[]
enemies?: string[]
}
}>

export type Timestamps = {
joinedNationAt?: number
Expand All @@ -160,7 +160,7 @@ export type Timestamps = {
lastOnline?: number
}

export type RawResident = RawEntity & {
export type RawResident = Prettify<RawEntity & {
name: string
title: string
surname: string
Expand All @@ -169,7 +169,7 @@ export type RawResident = RawEntity & {
timestamps?: Timestamps
perms: RawEntityPerms<RawResidentPerms>
friends?: string[]
}
}>

export type RawServerInfo = {
world: {
Expand Down
6 changes: 5 additions & 1 deletion src/types/util.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,4 +3,8 @@ export type NestedOmit<T, K extends PropertyKey> = {
NestedOmit<T[P], K extends `${Exclude<P, symbol>}.${infer R}` ? R : never>
} extends infer O ? { [P in keyof O]: O[P] } : never;

export type ValidateShape<T, Shape> = T extends Shape ? Exclude<keyof T, keyof Shape> extends never ? T : never : never;
export type ValidateShape<T, Shape> = T extends Shape ? Exclude<keyof T, keyof Shape> extends never ? T : never : never;

export type Prettify<T> = {
[K in keyof T]: T[K]
} & unknown
1 change: 1 addition & 0 deletions src/utils/endpoint.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ if (useDefaultAgent) useDefaultAgent()
* Gets the appropriate endpoint from the given keys.
*/
const get = (dataType: keyof typeof endpoints, map: ValidMapName) => {
//@ts-ignore
return (endpoints[dataType][map.toLowerCase()]) as string
}

Expand Down
23 changes: 18 additions & 5 deletions src/utils/functions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -58,10 +58,22 @@ function getAveragePos(arr: Point2D[]) {
}
}

const asBool = (str: string) => str == "true",
range = (args: number[]) => Math.round((Math.max(...args) + Math.min(...args)) / 2),
average = (arr: Point2D[], key: keyof Point2D) => arr.map(obj => obj[key]).reduce((a, b) => a + b) / arr.length,
sqr = (a: Point2D, b: Point2D, range: number) => Math.hypot(a.x - b.x, a.z - b.z) <= range
const asBool = (str: string) => str == "true"
const range = (args: number[]) => Math.round((Math.max(...args) + Math.min(...args)) / 2)

const sqr = (a: Point2D, b: Point2D, range: number) => Math.hypot(
safeParseInt(a.x) - safeParseInt(b.x),
safeParseInt(a.z) - safeParseInt(b.z)
) <= range

const average = (nums: Point2D[], key: keyof Point2D) => {
const sum = nums.map(obj => obj[key]).reduce((a, b) => safeParseInt(a) + safeParseInt(b))
return safeParseInt(sum) / nums.length
}

const safeParseInt = (num: number | string) => {
return typeof num === "number" ? num : parseInt(num)
}

const getExisting = <T>(a1: any[], a2: string[], key: keyof T) => {
const filter = (x: string) => a1.find(e => x?.toLowerCase() == e[key]?.toLowerCase()) ?? NotFound(x),
Expand Down Expand Up @@ -114,5 +126,6 @@ export {
euclidean,
manhattan,
strictFalsy,
genRandomString
genRandomString,
safeParseInt
}
2 changes: 1 addition & 1 deletion tests/nations.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ describe('Nations', () => {
assertType<Nation | Nation[]>(nation)

expect(nation.name).toBe('Venice')
console.log(nation)
//console.log(nation)
})

it('should return different nation info on Aurora and Nova', async () => {
Expand Down
4 changes: 3 additions & 1 deletion tests/towns.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,8 @@ describe('Towns', () => {
expect(town).toBeDefined()
expectTypeOf(town).not.toEqualTypeOf<Error>()
assertType<Town[]>(town)

console.log(town)
})

it('can get towns invitable to specified nation', async () => {
Expand All @@ -36,7 +38,7 @@ describe('Towns', () => {
])

expect(novaTown).not.toEqual(auroraTown)
expect(novaTown.stats).toBeUndefined()
expect(novaTown['stats']).toBeUndefined()

expect(auroraTown.stats).toBeDefined()
expect(auroraTown.wiki).toBeDefined()
Expand Down
3 changes: 2 additions & 1 deletion tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
"moduleDetection": "force",
"target": "ES2017",
"outDir": "dist",
"noImplicitAny": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"removeComments": true,
Expand All @@ -20,6 +21,6 @@
"tslib": ["node_modules/tslib/tslib.d.ts"]
}
},
"include": ["src", "endpoints.json"],
"include": ["src"],
"exclude": ["node_modules", "docs", "tests", "dist"]
}

0 comments on commit cf31a33

Please sign in to comment.