Skip to content

Commit

Permalink
Fix lots of minor errors and bugs making everything finally compile a…
Browse files Browse the repository at this point in the history
…gain
  • Loading branch information
phisn committed Nov 7, 2024
1 parent 3c53bea commit 7486525
Show file tree
Hide file tree
Showing 17 changed files with 90 additions and 53 deletions.
1 change: 1 addition & 0 deletions packages/game-player/src/game-player.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ export class GamePlayer implements GameLoopRunnable {
this.moduleVisual = new ModuleVisual(this.store)

if (lobbyConfig) {
console.log(lobbyConfig)
this.store.resources.set("lobbyConfig", lobbyConfig)
this.moduleLobby = new ModuleLobby(this.store)
}
Expand Down
6 changes: 4 additions & 2 deletions packages/game-player/src/model/store.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import * as RAPIER from "@dimforge/rapier2d"
import { EventStore } from "game/src/framework/event"
import { ResourceStore } from "game/src/framework/resource"
import { Game, GameConfig } from "game/src/game"
import { Game } from "game/src/game"
import { LobbyUserDTO } from "shared/src/lobby-api/lobby-api"
import { Scene, WebGLRenderer } from "three"
import { GamePlayerConfig } from "../game-player"
Expand All @@ -15,13 +15,15 @@ export class GamePlayerStore {
public game: Game
public resources: ResourceStore<GamePlayerResources>

constructor(config: GameConfig, renderer: WebGLRenderer) {
constructor(config: GamePlayerConfig, renderer: WebGLRenderer) {
this.events = new EventStore()
this.game = new Game(config, { rapier: RAPIER })
this.resources = new ResourceStore({
renderer,
scene: new Scene(),
})

this.resources.set("config", config)
}
}

Expand Down
4 changes: 2 additions & 2 deletions packages/game-player/src/modules/module-lobby/module-lobby.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import { GamePlayerStore } from "../../model/store"
import { OtherUserRegistry } from "./other-user-registry"

export interface LobbyConfigResource {
lobbyWsUrl: string
lobbyWsUrl: URL
token: string
username: string
}
Expand Down Expand Up @@ -147,6 +147,6 @@ export class ModuleLobby {
this.ws?.close()
this.ws = undefined

setTimeout(() => this.startWebsocket(), this.baseFailureTimeout)
setTimeout(() => this.startWebsocket(), this.baseFailureTimeout * 2 ** this.failureCounter)
}
}
4 changes: 2 additions & 2 deletions packages/server/.dev.vars.sample
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
AUTH_GOOGLE_CLIENT_ID=
AUTH_GOOGLE_CLIENT_SECRET=
ENV_GOOGLE_ID=
ENV_GOOGLE_SECRET=
2 changes: 1 addition & 1 deletion packages/server/src/features/user/user-middleware.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ export const middlewareAuth: MiddlewareHandler<Environment> = async (c, next) =>
throw new HTTPException(401)
}

const token = jwtToken.safeParse(decode(authorization))
const token = jwtToken.safeParse(decode(authorization).payload)

if (token.success === false) {
throw new HTTPException(401)
Expand Down
8 changes: 5 additions & 3 deletions packages/server/src/features/user/user.ts
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,7 @@ export const routeUser = new Hono<Environment>()
},
c.env.ENV_JWT_SECRET,
),
type: "create",
type: "create" as const,
})
} else {
return c.json({
Expand All @@ -100,7 +100,7 @@ export const routeUser = new Hono<Environment>()
},
c.env.ENV_JWT_SECRET,
),
type: "login",
type: "login" as const,
})
}
},
Expand All @@ -121,12 +121,14 @@ export const routeUser = new Hono<Environment>()
const verified = await verify(json.code, c.env.ENV_JWT_SECRET)

if (verified === false) {
console.warn("Failed to verify")
throw new HTTPException(401)
}

const token = signupToken.safeParse(decode(json.code))
const token = signupToken.safeParse(decode(json.code).payload)

if (token.success === false) {
console.warn("Failed to parse token", token.error, decode(json.code).payload)
throw new HTTPException(401)
}

Expand Down
16 changes: 12 additions & 4 deletions packages/server/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,11 +11,19 @@ import { routeWorld } from "./features/world/world"
const app = new Hono<Environment>()
.use(timing())
.use((c, next) => {
const corsMiddleware = cors({
origin: c.env.ENV_JWT_SECRET,
})
const origins = c.env.ENV_URL_CLIENT.split(",")
const origin = c.req.header("Origin")

return corsMiddleware(c, next)
if (origin && origins.includes(origin)) {
const corsMiddleware = cors({
credentials: true,
origin,
})

return corsMiddleware(c, next)
} else {
return next()
}
})
.use((c, next) => {
c.set("db", drizzle(c.env.DB))
Expand Down
6 changes: 3 additions & 3 deletions packages/server/wrangler.toml
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,13 @@ compatibility_flags = [ "nodejs_compat" ]
tail_consumers = [{service = "polyburn-worker-tail"}]

[dev]
port = 8080
port = 3002
local_protocol = "http"

[vars]
ENV_JWT_SECRET = "my_secret_password"
ENV_URL_CLIENT = "http://localhost:3000/,http://localhost:8080/"
ENV_URL_API = "http://localhost:8080/"
ENV_URL_CLIENT = "http://localhost:3000,http://localhost:3002"
ENV_URL_API = "http://localhost:3002"

[[d1_databases]]
migrations_dir = "drizzle"
Expand Down
2 changes: 1 addition & 1 deletion packages/web/src/common/hooks/UseAuth.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ export function useAuth(): AuthApi {

const responseJson = await response.json()

if (responseJson.type === "prompt-create") {
if (responseJson.type === "create") {
useGlobalStore.getState().newModal({
modal: function CreateModal() {
return (
Expand Down
5 changes: 4 additions & 1 deletion packages/web/src/common/hooks/use-auth-state.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,5 +2,8 @@ import { useSyncExternalStore } from "react"
import { authService } from "../services/auth-service"

export function useAuthState() {
useSyncExternalStore(authService.subscribeAuthState, () => authService.getState())
return useSyncExternalStore(
x => authService.subscribeAuthState(x),
() => authService.getState(),
)
}
8 changes: 6 additions & 2 deletions packages/web/src/common/services/auth-service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,9 @@ class AuthService {
jwt: authObject.jwt,
}

this.fetchUserInfo()
setTimeout(() => {
this.fetchUserInfo()
})
} else {
this.state = {
type: "offline",
Expand Down Expand Up @@ -128,6 +130,8 @@ class AuthService {

const responseJson = await response.json()

await this.fetchUserInfo()

return responseJson.type
}

Expand All @@ -139,7 +143,7 @@ class AuthService {
}

private async fetchUserInfo() {
if (this.state.type !== "fetching") {
if (this.state.type === "unauthenticated") {
throw new Error("No JWT found")
}

Expand Down
4 changes: 2 additions & 2 deletions packages/web/src/common/services/world-service.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import Dexie from "dexie"
import { WorldDTO } from "shared/src/server/world"
import { useAuthStore } from "../store/auth-store"
import { authService } from "./auth-service"
import { rpc } from "./rpc"

const db = new Dexie("polyburn-cache-worlds") as Dexie & {
Expand All @@ -17,7 +17,7 @@ export class WorldService {
async sync() {}

async list(): Promise<WorldDTO[]> {
if (useAuthStore.getState().currentUser === undefined) {
if (authService.getState() === "offline") {
return db.worlds.limit(25).toArray()
}

Expand Down
14 changes: 8 additions & 6 deletions packages/web/src/components/layout/navbar/NavbarAuthButton.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { useAuthState } from "../../../common/hooks/use-auth-state"
import { useAuth } from "../../../common/hooks/UseAuth"
import { authService } from "../../../common/services/auth-service"
import { useGlobalStore } from "../../../common/store"
import { BoxArrowInRight } from "../../common/svg/BoxArrowInRight"
import { Person } from "../../common/svg/Person"

Expand All @@ -20,24 +21,25 @@ function AuthButtonRaw(props: {

export function NavbarAuthButton() {
const authApi = useAuth()
const user = useAppStore(x => x.currentUser)
const authState = useAuthState()
const user = useGlobalStore(x => x.currentUser)

switch (authService.getState()) {
case AuthState.Unauthenticated:
switch (authState) {
case "unauthenticated":
return (
<AuthButtonRaw onClick={() => authApi.login()}>
<BoxArrowInRight width="32" height="32" className="pr-2" />
</AuthButtonRaw>
)

case AuthState.Pending:
case "fetching":
return (
<AuthButtonRaw className="btn-disabled">
<div className="loading loading-sm" />
</AuthButtonRaw>
)

case AuthState.Authenticated:
case "authenticated":
return (
<div className="flex items-center space-x-4">
<div className="font-outfit xs:flex hidden text-lg">{user?.username}</div>
Expand Down
2 changes: 1 addition & 1 deletion packages/web/src/pages/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ export function App() {
</Route>
<Route path="/" element={<Layout />}>
<Route path="/" element={<Navigate to="/campaign" replace />} />
<Route path="/play/:world/:gamemode" element={<Player />} />
<Route path="/play/:worldname/:gamemode" element={<Player />} />
<Route path="/slot" element={<Slot />} />
<Route path="*" element={<NotFound />} />
</Route>
Expand Down
2 changes: 1 addition & 1 deletion packages/web/src/pages/player/FinishedPopup.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ export function FinishedPopup(props: { store: PlayerStore }) {
}

export function FinishedInfoContainer(props: { store: PlayerStoreFinished; onClick(): void }) {
const summary = props.store.gamePlayerStore.game.store.resources.get("summary")
const summary = props.store.gamePlayer.store.game.store.resources.get("summary")

return (
<InfoContainer
Expand Down
4 changes: 2 additions & 2 deletions packages/web/src/pages/player/Player.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ export function Player() {
function RefreshButton(props: { store: PlayerStoreRunning }) {
return (
<div
onClick={() => props.store.gamePlayerStore.game.onReset()}
onClick={() => props.store.gamePlayer.onReset()}
className="btn btn-square btn-ghost absolute left-0 top-0 z-10 m-4"
>
<ArrowClockwise width="32" height="32" />
Expand All @@ -28,7 +28,7 @@ function RefreshButton(props: { store: PlayerStoreRunning }) {
}

export function GameCanvas(props: { store: PlayerStoreRunning }) {
const canvas = props.store.gamePlayerStore.resources.get("renderer").domElement
const canvas = props.store.gamePlayer.store.resources.get("renderer").domElement

useEffect(() => {
console.log("Setting up new canvas")
Expand Down
Loading

0 comments on commit 7486525

Please sign in to comment.