Compare commits
3 Commits
v0.1.8
...
551190b801
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
551190b801 | ||
| 8789c5414e | |||
|
|
7a1c91c858 |
@@ -11,6 +11,10 @@
|
|||||||
# PORT=7331
|
# PORT=7331
|
||||||
|
|
||||||
# Goose CLI migration config (only needed for running goose manually)
|
# Goose CLI migration config (only needed for running goose manually)
|
||||||
|
# Gitea API token for downloading datastar-pro from private repo (CI/Docker only).
|
||||||
|
# Not needed for local dev — falls back to copying from ../optional/.
|
||||||
|
# VENDOR_TOKEN=
|
||||||
|
|
||||||
GOOSE_DRIVER=sqlite3
|
GOOSE_DRIVER=sqlite3
|
||||||
GOOSE_DBSTRING=data/games.db?_pragma=foreign_keys(1)&_pragma=journal_mode(WAL)
|
GOOSE_DBSTRING=data/games.db?_pragma=foreign_keys(1)&_pragma=journal_mode(WAL)
|
||||||
GOOSE_MIGRATION_DIR=db/migrations
|
GOOSE_MIGRATION_DIR=db/migrations
|
||||||
|
|||||||
@@ -61,11 +61,13 @@ jobs:
|
|||||||
mkdir -p $DEPLOY_DIR/data
|
mkdir -p $DEPLOY_DIR/data
|
||||||
|
|
||||||
- name: Rebuild and restart
|
- name: Rebuild and restart
|
||||||
|
env:
|
||||||
|
VENDOR_TOKEN: ${{ secrets.VENDOR_TOKEN }}
|
||||||
run: |
|
run: |
|
||||||
cd $DEPLOY_DIR
|
cd $DEPLOY_DIR
|
||||||
VERSION=$(git describe --tags --always)
|
VERSION=$(git describe --tags --always)
|
||||||
COMMIT=$(git rev-parse --short HEAD)
|
COMMIT=$(git rev-parse --short HEAD)
|
||||||
VERSION=$VERSION COMMIT=$COMMIT docker compose up -d --build --remove-orphans
|
VERSION=$VERSION COMMIT=$COMMIT VENDOR_TOKEN=$VENDOR_TOKEN docker compose up -d --build --remove-orphans
|
||||||
|
|
||||||
- name: Prune unused images
|
- name: Prune unused images
|
||||||
run: docker image prune -f
|
run: docker image prune -f
|
||||||
|
|||||||
4
.gitignore
vendored
4
.gitignore
vendored
@@ -27,6 +27,10 @@
|
|||||||
*_templ.go
|
*_templ.go
|
||||||
assets/css/output.css
|
assets/css/output.css
|
||||||
|
|
||||||
|
# Downloaded client-side libs (fetched by cmd/downloader)
|
||||||
|
assets/js/datastar/*
|
||||||
|
assets/css/daisyui/*
|
||||||
|
|
||||||
# Deploy scripts and configs
|
# Deploy scripts and configs
|
||||||
!deploy/*.sh
|
!deploy/*.sh
|
||||||
!deploy/*.service
|
!deploy/*.service
|
||||||
|
|||||||
249
AGENTS.md
249
AGENTS.md
@@ -9,6 +9,7 @@ Instructions for AI coding agents working in this repository.
|
|||||||
task live # Hot-reload dev server (templ + tailwind + air)
|
task live # Hot-reload dev server (templ + tailwind + air)
|
||||||
task build # Production build to bin/games
|
task build # Production build to bin/games
|
||||||
task run # Build and run server
|
task run # Build and run server
|
||||||
|
task download # Download pinned client-side libs (datastar-pro, daisyui)
|
||||||
|
|
||||||
# Quality
|
# Quality
|
||||||
task test # Run all tests: go test ./...
|
task test # Run all tests: go test ./...
|
||||||
@@ -16,106 +17,80 @@ task lint # Run linter: golangci-lint run
|
|||||||
|
|
||||||
# Single test
|
# Single test
|
||||||
go test -run TestName ./path/to/package
|
go test -run TestName ./path/to/package
|
||||||
|
go test -v -run TestHandleLogin_Success ./features/auth
|
||||||
|
|
||||||
# Code generation
|
# Code generation
|
||||||
task build:templ # Compile .templ files
|
task build:templ # Compile .templ files (go tool templ generate)
|
||||||
task build:styles # Build TailwindCSS
|
task build:styles # Build TailwindCSS (go tool gotailwind)
|
||||||
go generate ./... # Run sqlc for DB queries
|
|
||||||
```
|
```
|
||||||
|
|
||||||
|
Tools (templ, air, gotailwind, goose, sqlc) are managed via Go 1.25's `tool` directive in go.mod — no separate installs needed.
|
||||||
|
|
||||||
## Workflow Rules
|
## Workflow Rules
|
||||||
|
|
||||||
- **Never merge PRs without explicit user approval.** Create the PR, push changes, then wait.
|
- **Never merge PRs without explicit user approval.** Create the PR, push changes, then wait.
|
||||||
- Always use PRs via `tea` CLI - never push directly to main.
|
- Always use PRs via `tea` CLI — never push directly to main.
|
||||||
- Write semantic commit messages focusing on "why" not "what".
|
- Write semantic commit messages focusing on "why" not "what".
|
||||||
|
|
||||||
## Project Structure
|
## Project Structure
|
||||||
|
|
||||||
```
|
```
|
||||||
games/
|
games/
|
||||||
├── connect4/, snake/ # Game logic packages (pure Go)
|
├── connect4/, snake/ # Game logic packages (pure Go, no HTTP)
|
||||||
├── features/ # Feature modules (handlers, routes, templates)
|
├── features/ # Feature modules (handlers, routes, templates)
|
||||||
│ ├── auth/ # Login/register
|
│ ├── auth/ # Login/register (standard HTTP, not SSE)
|
||||||
│ ├── c4game/ # Connect 4 UI
|
│ ├── c4game/ # Connect 4 UI + services
|
||||||
│ ├── snakegame/ # Snake UI
|
│ ├── snakegame/ # Snake UI + services
|
||||||
│ ├── lobby/ # Game lobby
|
│ ├── lobby/ # Game lobby
|
||||||
│ └── common/ # Shared components, layouts
|
│ └── common/ # Shared components, layouts
|
||||||
├── chat/ # Reusable chat room (NATS + persistence)
|
├── chat/ # Reusable chat room (NATS + optional DB persistence)
|
||||||
|
├── auth/ # Password hashing/validation (pure, no HTTP)
|
||||||
├── db/ # SQLite, migrations, sqlc queries
|
├── db/ # SQLite, migrations, sqlc queries
|
||||||
├── assets/ # Static files (embedded)
|
├── cmd/downloader/ # Build-time tool: fetches datastar-pro + daisyui
|
||||||
└── config/, logging/, nats/, sessions/, router/ # Infrastructure
|
├── assets/ # Static files (embedded in prod, filesystem in dev)
|
||||||
|
└── config/, logging/, nats/, sessions/, router/, player/, version/
|
||||||
```
|
```
|
||||||
|
|
||||||
## Code Style
|
## Code Style
|
||||||
|
|
||||||
### Imports
|
### Imports
|
||||||
|
|
||||||
Organize in three groups: stdlib, third-party, local. The linter enforces this.
|
Three groups separated by blank lines: stdlib, third-party, local. Enforced by goimports with `local-prefixes: github.com/ryanhamamura/games`.
|
||||||
|
|
||||||
```go
|
```go
|
||||||
import (
|
import (
|
||||||
"context"
|
|
||||||
"fmt"
|
"fmt"
|
||||||
"net/http"
|
"net/http"
|
||||||
|
|
||||||
"github.com/go-chi/chi/v5"
|
"github.com/go-chi/chi/v5"
|
||||||
"github.com/rs/zerolog/log"
|
|
||||||
|
|
||||||
"github.com/ryanhamamura/games/connect4"
|
"github.com/ryanhamamura/games/connect4"
|
||||||
"github.com/ryanhamamura/games/db/repository"
|
|
||||||
)
|
)
|
||||||
```
|
```
|
||||||
|
|
||||||
### Naming Conventions
|
|
||||||
|
|
||||||
| Type | Convention | Examples |
|
|
||||||
|------|------------|----------|
|
|
||||||
| Files | lowercase, underscores | `config_dev.go`, `handlers.go` |
|
|
||||||
| HTTP handlers | `Handle` prefix | `HandleGamePage`, `HandleLogin` |
|
|
||||||
| Constructors | `New` prefix | `NewStore`, `NewRoom` |
|
|
||||||
| Getters | `Get` prefix | `GetPlayerID`, `GetGame` |
|
|
||||||
| Setup functions | `Setup` prefix | `SetupRoutes`, `SetupLogger` |
|
|
||||||
| Types | PascalCase | `Game`, `Player`, `Instance` |
|
|
||||||
| Status enums | `Status` prefix | `StatusWaitingForPlayer`, `StatusInProgress` |
|
|
||||||
| Session keys | `Key` prefix | `KeyPlayerID`, `KeyUserID` |
|
|
||||||
|
|
||||||
### Error Handling
|
### Error Handling
|
||||||
|
|
||||||
1. **Wrap errors with context:**
|
```go
|
||||||
```go
|
// Wrap errors with context
|
||||||
return fmt.Errorf("loading game %s: %w", id, err)
|
return fmt.Errorf("loading game %s: %w", id, err)
|
||||||
```
|
|
||||||
|
|
||||||
2. **Return (result, error) tuples:**
|
// Combine cleanup errors with errors.Join
|
||||||
```go
|
return nil, errors.Join(fmt.Errorf("pinging database: %w", err), DB.Close())
|
||||||
func loadGame(queries *repository.Queries, id string) (*Game, error)
|
|
||||||
```
|
|
||||||
|
|
||||||
3. **Best-effort operations** - use nolint comment:
|
// Best-effort operations
|
||||||
```go
|
nc.Publish(subject, nil) //nolint:errcheck // best-effort notification
|
||||||
nc.Publish(subject, nil) //nolint:errcheck // best-effort notification
|
|
||||||
```
|
|
||||||
|
|
||||||
4. **HTTP errors:**
|
// HTTP errors
|
||||||
```go
|
http.Error(w, "game not found", http.StatusNotFound)
|
||||||
http.Error(w, "game not found", http.StatusNotFound)
|
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
|
||||||
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
|
|
||||||
```
|
```
|
||||||
|
|
||||||
### Comments
|
### Comments
|
||||||
|
|
||||||
- Focus on **why**, not **how**. Avoid superfluous comments.
|
- Focus on **why**, not **how**. Avoid superfluous comments.
|
||||||
- Package comments at top of primary file:
|
- Package comments at top of primary file.
|
||||||
```go
|
- Function comments for exported functions.
|
||||||
// Package connect4 implements Connect 4 game logic, state management, and persistence.
|
|
||||||
package connect4
|
|
||||||
```
|
|
||||||
- Function comments for exported functions:
|
|
||||||
```go
|
|
||||||
// DropPiece attempts to drop a piece in the given column.
|
|
||||||
// Returns (row placed, success).
|
|
||||||
func (g *Game) DropPiece(col, playerColor int) (int, bool)
|
|
||||||
```
|
|
||||||
|
|
||||||
## Go Patterns
|
## Go Patterns
|
||||||
|
|
||||||
@@ -125,129 +100,119 @@ Handlers receive dependencies and return `http.HandlerFunc`:
|
|||||||
|
|
||||||
```go
|
```go
|
||||||
func HandleGamePage(store *connect4.Store, sm *scs.SessionManager) http.HandlerFunc {
|
func HandleGamePage(store *connect4.Store, sm *scs.SessionManager) http.HandlerFunc {
|
||||||
return func(w http.ResponseWriter, r *http.Request) {
|
return func(w http.ResponseWriter, r *http.Request) { /* ... */ }
|
||||||
// use store, sm here
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
### Mutex for Concurrent Access
|
### Cleanup Function Returns
|
||||||
|
|
||||||
|
Infrastructure init functions return a cleanup func the caller defers:
|
||||||
|
|
||||||
```go
|
```go
|
||||||
type Store struct {
|
cleanupDB, err := db.Init(cfg.DBPath)
|
||||||
games map[string]*Instance
|
defer cleanupDB()
|
||||||
gamesMu sync.RWMutex
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *Store) Get(id string) (*Instance, bool) {
|
|
||||||
s.gamesMu.RLock()
|
|
||||||
defer s.gamesMu.RUnlock()
|
|
||||||
inst, ok := s.games[id]
|
|
||||||
return inst, ok
|
|
||||||
}
|
|
||||||
```
|
```
|
||||||
|
|
||||||
### Build Tags for Environment
|
### Store/Instance Pattern
|
||||||
|
|
||||||
```go
|
Game state uses a two-tier pattern: a thread-safe **Store** (map + RWMutex) holding **Instance** wrappers (individual game + own mutex + DB queries). Stores lazy-load from DB on cache miss.
|
||||||
//go:build dev
|
|
||||||
|
|
||||||
//go:build !dev
|
### Build Tags
|
||||||
```
|
|
||||||
|
|
||||||
### Embedded Filesystems
|
`//go:build dev` and `//go:build !dev` switch behavior for static asset serving (filesystem vs embedded hashfs) and config loading.
|
||||||
|
|
||||||
```go
|
|
||||||
//go:embed assets
|
|
||||||
var assets embed.FS
|
|
||||||
|
|
||||||
//go:embed migrations/*.sql
|
|
||||||
var MigrationFS embed.FS
|
|
||||||
```
|
|
||||||
|
|
||||||
### Graceful Shutdown
|
|
||||||
|
|
||||||
```go
|
|
||||||
eg, egctx := errgroup.WithContext(ctx)
|
|
||||||
eg.Go(func() error { return server.ListenAndServe() })
|
|
||||||
eg.Go(func() error {
|
|
||||||
<-egctx.Done()
|
|
||||||
return server.Shutdown(context.Background())
|
|
||||||
})
|
|
||||||
return eg.Wait()
|
|
||||||
```
|
|
||||||
|
|
||||||
## Templ + Datastar Patterns
|
## Templ + Datastar Patterns
|
||||||
|
|
||||||
### SSE Connection with Disabled Cancellation
|
### Architecture: Everything Is a Stream
|
||||||
|
|
||||||
Datastar cancels SSE on user interaction by default. Disable for persistent connections:
|
The core mental model: **the server owns all state and continuously projects it to the browser over SSE**. There is no client-side state management. The browser connects to an event stream, and the server pushes full HTML fragments whenever something changes. Datastar morphs these into the DOM — the client is a thin rendering surface.
|
||||||
|
|
||||||
|
User actions (clicks, keypresses) trigger short POST/DELETE requests back to the server. The server mutates state, publishes a NATS signal, and every connected SSE stream picks up the change and re-renders. The client never needs to know what changed — it just receives the new truth and morphs to match.
|
||||||
|
|
||||||
|
This means: **always send whole components down the wire.** Don't try to diff or send minimal patches. Render the full templ component, call `sse.PatchElementTempl()`, and let Datastar's morph handle the rest. The only exception is appending to a list (e.g. chat messages).
|
||||||
|
|
||||||
|
**Signals follow command-query segregation.** Signals are *commands* — they carry the user's intent to the server (form input values, button clicks). The SSE stream is the *query* — it continuously projects the server's truth into the DOM. Keep signals thin: form input buffers (`chatMsg`, `nickname`), pure UI state the server never needs (`activeTab`), and request indicators. Don't use signals to hold application state — that arrives from the server via SSE.
|
||||||
|
|
||||||
|
### SSE Event Loop
|
||||||
|
|
||||||
|
Both game event handlers follow the same structure:
|
||||||
|
1. Subscribe to NATS channels **before** creating SSE (avoids missed messages)
|
||||||
|
2. Send initial full-state patch
|
||||||
|
3. `select` loop over: context done, game updates (drain channel first), chat messages (append), 1-second heartbeat (full re-render)
|
||||||
|
|
||||||
```go
|
```go
|
||||||
|
// Handler side — long-lived SSE with Brotli compression
|
||||||
|
sse := datastar.NewSSE(w, r, datastar.WithCompression(
|
||||||
|
datastar.WithBrotli(datastar.WithBrotliLevel(5)),
|
||||||
|
))
|
||||||
|
sse.PatchElementTempl(components.GameBoard(game))
|
||||||
|
|
||||||
|
// Template side — disable Datastar's default SSE cancellation on interaction
|
||||||
data-init={ fmt.Sprintf("@get('/games/%s/events',{requestCancellation:'disabled'})", g.ID) }
|
data-init={ fmt.Sprintf("@get('/games/%s/events',{requestCancellation:'disabled'})", g.ID) }
|
||||||
```
|
```
|
||||||
|
|
||||||
### Prevent Script Duplication on SSE Patches
|
### Client-Server Interactions
|
||||||
|
|
||||||
Use `templ.NewOnceHandle()` for scripts in components that get patched:
|
|
||||||
|
|
||||||
```go
|
```go
|
||||||
var scriptHandle = templ.NewOnceHandle()
|
// Trigger SSE actions from templates
|
||||||
|
data-on:click={ datastar.PostSSE("/games/%s/drop?col=%d", g.ID, colIdx) }
|
||||||
|
data-on:click={ datastar.DeleteSSE("/games/%s", g.ID) }
|
||||||
|
|
||||||
templ MyComponent() {
|
// Read client signals in handlers
|
||||||
<div id="my-component">...</div>
|
var signals struct { ChatMsg string `json:"chatMsg"` }
|
||||||
@scriptHandle.Once() {
|
datastar.ReadSignals(r, &signals)
|
||||||
@myScript()
|
|
||||||
}
|
// Clear input after submission
|
||||||
}
|
sse.MarshalAndPatchSignals(map[string]any{"chatMsg": ""})
|
||||||
|
|
||||||
|
// Redirect via SSE
|
||||||
|
sse.Redirectf("/games/%s", newGame.ID())
|
||||||
```
|
```
|
||||||
|
|
||||||
### Conditional Classes with templ.KV
|
### Appending Elements (Chat Messages)
|
||||||
|
|
||||||
|
The one exception to whole-component morphing is chat, where messages are appended individually:
|
||||||
|
|
||||||
```go
|
```go
|
||||||
class={
|
sse.PatchElementTempl(
|
||||||
"status status-sm",
|
chatcomponents.ChatMessage(msg, cfg),
|
||||||
templ.KV("status-success", isConnected),
|
datastar.WithSelectorID("c4-chat-history"),
|
||||||
templ.KV("status-error", !isConnected),
|
datastar.WithModeAppend(),
|
||||||
}
|
)
|
||||||
```
|
```
|
||||||
|
|
||||||
### Datastar SSE Responses
|
### Datastar Template Attributes
|
||||||
|
|
||||||
```go
|
- `data-signals` — declare reactive state
|
||||||
sse := datastar.NewSSE(w, r)
|
- `data-bind` — two-way input binding
|
||||||
sse.MergeFragmentTempl(components.GameBoard(game))
|
- `data-show` — conditional visibility
|
||||||
|
- `data-class` — reactive CSS classes
|
||||||
|
- `data-morph-ignore` — prevent SSE from overwriting an element (e.g. chat input)
|
||||||
|
|
||||||
|
## Testing
|
||||||
|
|
||||||
|
```bash
|
||||||
|
task test # All tests
|
||||||
|
go test -run TestHandleLogin_Success ./features/auth # Single test
|
||||||
|
go test -v ./features/auth # Verbose package
|
||||||
```
|
```
|
||||||
|
|
||||||
|
- Use `testutil.NewTestDB(t)` for tests needing a database
|
||||||
|
- Use `testutil.NewTestSessionManager(db)` for session-aware tests
|
||||||
|
- Use `config.LoadForTest()` to set safe defaults without .env
|
||||||
|
- Tests use external test packages (`package auth_test`)
|
||||||
|
|
||||||
## Tech Stack
|
## Tech Stack
|
||||||
|
|
||||||
| Layer | Technology |
|
| Layer | Technology |
|
||||||
|-------|------------|
|
|-------|------------|
|
||||||
| Templates | templ (type-safe HTML) |
|
| Templates | templ (type-safe HTML) |
|
||||||
| Reactivity | Datastar (SSE-driven) |
|
| Reactivity | Datastar Pro (SSE-driven) |
|
||||||
| CSS | TailwindCSS v4 + daisyUI |
|
| CSS | TailwindCSS v4 + daisyUI |
|
||||||
| Router | chi/v5 |
|
| Router | chi/v5 |
|
||||||
| Sessions | scs/v2 |
|
| Sessions | scs/v2 (SQLite-backed) |
|
||||||
| Database | SQLite (modernc.org/sqlite) |
|
| Database | SQLite (modernc.org/sqlite) |
|
||||||
| Migrations | goose |
|
| Migrations | goose (embedded SQL) |
|
||||||
| SQL codegen | sqlc |
|
| SQL codegen | sqlc |
|
||||||
| Pub/sub | Embedded NATS |
|
| Pub/sub | Embedded NATS (nil-payload signals) |
|
||||||
| Logging | zerolog |
|
| Logging | zerolog + slog (bridged via slog-zerolog) |
|
||||||
|
|
||||||
## Testing
|
|
||||||
|
|
||||||
```bash
|
|
||||||
# All tests
|
|
||||||
task test
|
|
||||||
|
|
||||||
# Single test
|
|
||||||
go test -run TestDropPiece ./connect4
|
|
||||||
|
|
||||||
# With verbose output
|
|
||||||
go test -v -run TestDropPiece ./connect4
|
|
||||||
|
|
||||||
# Test a package
|
|
||||||
go test ./connect4/...
|
|
||||||
```
|
|
||||||
|
|
||||||
Use `testutil.SetupTestDB()` for tests requiring database access.
|
|
||||||
|
|||||||
@@ -10,6 +10,11 @@ COPY go.mod go.sum ./
|
|||||||
RUN go mod download
|
RUN go mod download
|
||||||
|
|
||||||
COPY . .
|
COPY . .
|
||||||
|
|
||||||
|
RUN --mount=type=secret,id=vendor_token \
|
||||||
|
VENDOR_TOKEN=$(cat /run/secrets/vendor_token) \
|
||||||
|
go run cmd/downloader/main.go
|
||||||
|
|
||||||
RUN go tool templ generate
|
RUN go tool templ generate
|
||||||
RUN go tool gotailwind -i assets/css/input.css -o assets/css/output.css --minify
|
RUN go tool gotailwind -i assets/css/input.css -o assets/css/output.css --minify
|
||||||
RUN --mount=type=cache,target=/root/.cache/go-build \
|
RUN --mount=type=cache,target=/root/.cache/go-build \
|
||||||
|
|||||||
@@ -2,9 +2,12 @@ version: "3"
|
|||||||
|
|
||||||
tasks:
|
tasks:
|
||||||
download:
|
download:
|
||||||
desc: Download latest client-side libs
|
desc: Download pinned client-side libs
|
||||||
cmds:
|
cmds:
|
||||||
- go run cmd/downloader/main.go
|
- go run cmd/downloader/main.go
|
||||||
|
status:
|
||||||
|
- test -f assets/js/datastar/datastar.js
|
||||||
|
- test -f assets/css/daisyui/daisyui.js
|
||||||
|
|
||||||
build:templ:
|
build:templ:
|
||||||
desc: Compile .templ files to Go
|
desc: Compile .templ files to Go
|
||||||
@@ -31,6 +34,7 @@ tasks:
|
|||||||
cmds:
|
cmds:
|
||||||
- go build -o bin/games .
|
- go build -o bin/games .
|
||||||
deps:
|
deps:
|
||||||
|
- download
|
||||||
- build:templ
|
- build:templ
|
||||||
- build:styles
|
- build:styles
|
||||||
|
|
||||||
@@ -58,6 +62,7 @@ tasks:
|
|||||||
live:
|
live:
|
||||||
desc: Dev mode with hot-reload
|
desc: Dev mode with hot-reload
|
||||||
deps:
|
deps:
|
||||||
|
- download
|
||||||
- live:templ
|
- live:templ
|
||||||
- live:styles
|
- live:styles
|
||||||
- live:server
|
- live:server
|
||||||
|
|||||||
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
@@ -1,8 +1,8 @@
|
|||||||
@import 'tailwindcss';
|
@import 'tailwindcss';
|
||||||
|
|
||||||
@source not "./daisyui{,*}.mjs";
|
@source not "./daisyui/daisyui{,*}.js";
|
||||||
@plugin "./daisyui.mjs";
|
@plugin "./daisyui/daisyui.js";
|
||||||
@plugin "./daisyui-theme.mjs" {
|
@plugin "./daisyui/daisyui-theme.js" {
|
||||||
name: "stealth";
|
name: "stealth";
|
||||||
default: true;
|
default: true;
|
||||||
color-scheme: light;
|
color-scheme: light;
|
||||||
|
|||||||
1
assets/js/README.md
Normal file
1
assets/js/README.md
Normal file
@@ -0,0 +1 @@
|
|||||||
|
Downloaded by cmd/downloader at build time.
|
||||||
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
@@ -1,30 +1,20 @@
|
|||||||
package main
|
package main
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"encoding/json"
|
||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
"io"
|
"io"
|
||||||
"log/slog"
|
"log/slog"
|
||||||
"net/http"
|
"net/http"
|
||||||
|
"net/url"
|
||||||
"os"
|
"os"
|
||||||
"path/filepath"
|
"path/filepath"
|
||||||
"sync"
|
"sync"
|
||||||
)
|
|
||||||
|
|
||||||
// Asset directories, relative to project root.
|
"github.com/ryanhamamura/games/assets"
|
||||||
const (
|
|
||||||
jsDir = "assets/js"
|
|
||||||
cssDir = "assets/css"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
// files maps download URLs to local destination paths.
|
|
||||||
var files = map[string]string{
|
|
||||||
"https://raw.githubusercontent.com/starfederation/datastar/main/bundles/datastar.js": jsDir + "/datastar.js",
|
|
||||||
"https://raw.githubusercontent.com/starfederation/datastar/main/bundles/datastar.js.map": jsDir + "/datastar.js.map",
|
|
||||||
"https://github.com/saadeghi/daisyui/releases/latest/download/daisyui.mjs": cssDir + "/daisyui.mjs",
|
|
||||||
"https://github.com/saadeghi/daisyui/releases/latest/download/daisyui-theme.mjs": cssDir + "/daisyui-theme.mjs",
|
|
||||||
}
|
|
||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
if err := run(); err != nil {
|
if err := run(); err != nil {
|
||||||
slog.Error("failure", "error", err)
|
slog.Error("failure", "error", err)
|
||||||
@@ -32,16 +22,243 @@ func main() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Pinned dependency versions — update these to upgrade.
|
||||||
|
const (
|
||||||
|
datastarVersion = "v1.0.0-RC.8" // Pro build — fetched from private Gitea repo
|
||||||
|
daisyuiVersion = "v5.5.19"
|
||||||
|
)
|
||||||
|
|
||||||
|
// dependencies tracks pinned versions alongside their GitHub coordinates
|
||||||
|
// so the version check can look up the latest release for each.
|
||||||
|
var dependencies = []dependency{
|
||||||
|
{name: "datastar", owner: "starfederation", repo: "datastar", pinnedVersion: datastarVersion},
|
||||||
|
{name: "daisyui", owner: "saadeghi", repo: "daisyui", pinnedVersion: daisyuiVersion},
|
||||||
|
}
|
||||||
|
|
||||||
|
type dependency struct {
|
||||||
|
name string
|
||||||
|
owner string
|
||||||
|
repo string
|
||||||
|
pinnedVersion string
|
||||||
|
}
|
||||||
|
|
||||||
|
// datastar-pro sources, in order of preference.
|
||||||
|
const (
|
||||||
|
giteaRawURL = "https://gitea.adriatica.io/ryan/vendor-libs/raw/branch/main/datastar/datastar.js"
|
||||||
|
localFallbackPath = "../optional/web/resources/static/datastar/datastar.js"
|
||||||
|
)
|
||||||
|
|
||||||
func run() error {
|
func run() error {
|
||||||
dirs := []string{jsDir, cssDir}
|
jsDir := assets.DirectoryPath + "/js/datastar"
|
||||||
|
cssDir := assets.DirectoryPath + "/css/daisyui"
|
||||||
|
|
||||||
for _, dir := range dirs {
|
daisyuiBase := "https://github.com/saadeghi/daisyui/releases/download/" + daisyuiVersion + "/"
|
||||||
if err := os.MkdirAll(dir, 0755); err != nil {
|
|
||||||
return fmt.Errorf("create directory %s: %w", dir, err)
|
downloads := map[string]string{
|
||||||
}
|
daisyuiBase + "daisyui.js": cssDir + "/daisyui.js",
|
||||||
|
daisyuiBase + "daisyui-theme.js": cssDir + "/daisyui-theme.js",
|
||||||
}
|
}
|
||||||
|
|
||||||
return download(files)
|
directories := []string{jsDir, cssDir}
|
||||||
|
|
||||||
|
if err := removeDirectories(directories); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := createDirectories(directories); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := acquireDatastar(jsDir + "/datastar.js"); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := download(downloads); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
checkForUpdates()
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// acquireDatastar fetches datastar-pro from the private Gitea repo when
|
||||||
|
// GITEA_TOKEN is set, otherwise copies from the local optional project.
|
||||||
|
func acquireDatastar(dest string) error {
|
||||||
|
if token := os.Getenv("VENDOR_TOKEN"); token != "" {
|
||||||
|
slog.Info("downloading datastar-pro from private repo...")
|
||||||
|
return downloadWithAuth(giteaRawURL, dest, token)
|
||||||
|
}
|
||||||
|
|
||||||
|
slog.Info("copying datastar-pro from local fallback...", "src", localFallbackPath)
|
||||||
|
return copyFile(localFallbackPath, dest)
|
||||||
|
}
|
||||||
|
|
||||||
|
func copyFile(src, dest string) error {
|
||||||
|
in, err := os.Open(src) //nolint:gosec // paths are hardcoded constants
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("open %s: %w", src, err)
|
||||||
|
}
|
||||||
|
defer in.Close() //nolint:errcheck
|
||||||
|
|
||||||
|
out, err := os.Create(dest) //nolint:gosec // paths are hardcoded constants
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("create %s: %w", dest, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if _, err := io.Copy(out, in); err != nil {
|
||||||
|
out.Close() //nolint:errcheck
|
||||||
|
return fmt.Errorf("copy to %s: %w", dest, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := out.Close(); err != nil {
|
||||||
|
return fmt.Errorf("close %s: %w", dest, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func downloadWithAuth(rawURL, dest, token string) error {
|
||||||
|
req, err := http.NewRequest(http.MethodGet, rawURL, nil)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("create request for %s: %w", rawURL, err)
|
||||||
|
}
|
||||||
|
req.Header.Set("Authorization", "token "+token)
|
||||||
|
|
||||||
|
resp, err := http.DefaultClient.Do(req) //nolint:gosec // URL is built from compile-time constants
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("GET %s: %w", rawURL, err)
|
||||||
|
}
|
||||||
|
defer resp.Body.Close() //nolint:errcheck
|
||||||
|
|
||||||
|
if resp.StatusCode != http.StatusOK {
|
||||||
|
return fmt.Errorf("GET %s: status %s", rawURL, resp.Status)
|
||||||
|
}
|
||||||
|
|
||||||
|
out, err := os.Create(dest) //nolint:gosec // paths are hardcoded constants
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("create %s: %w", dest, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if _, err := io.Copy(out, resp.Body); err != nil {
|
||||||
|
out.Close() //nolint:errcheck
|
||||||
|
return fmt.Errorf("write %s: %w", dest, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := out.Close(); err != nil {
|
||||||
|
return fmt.Errorf("close %s: %w", dest, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// checkForUpdates queries the GitHub releases API for each dependency
|
||||||
|
// and logs a notice if a newer version is available. Failures are
|
||||||
|
// logged but never cause the download to fail.
|
||||||
|
func checkForUpdates() {
|
||||||
|
var wg sync.WaitGroup
|
||||||
|
|
||||||
|
for _, dep := range dependencies {
|
||||||
|
wg.Go(func() {
|
||||||
|
latest, err := latestGitHubRelease(dep.owner, dep.repo)
|
||||||
|
if err != nil {
|
||||||
|
slog.Warn("could not check for updates", "dependency", dep.name, "error", err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if latest != dep.pinnedVersion {
|
||||||
|
slog.Warn("newer version available",
|
||||||
|
"dependency", dep.name,
|
||||||
|
"pinned", dep.pinnedVersion,
|
||||||
|
"latest", latest,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
wg.Wait()
|
||||||
|
}
|
||||||
|
|
||||||
|
// githubRelease is the minimal subset of the GitHub releases API response we need.
|
||||||
|
type githubRelease struct {
|
||||||
|
TagName string `json:"tag_name"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func latestGitHubRelease(owner, repo string) (string, error) {
|
||||||
|
u := &url.URL{
|
||||||
|
Scheme: "https",
|
||||||
|
Host: "api.github.com",
|
||||||
|
Path: fmt.Sprintf("/repos/%s/%s/releases/latest", owner, repo),
|
||||||
|
}
|
||||||
|
|
||||||
|
req, err := http.NewRequest(http.MethodGet, u.String(), nil)
|
||||||
|
if err != nil {
|
||||||
|
return "", fmt.Errorf("creating request: %w", err)
|
||||||
|
}
|
||||||
|
req.Header.Set("Accept", "application/vnd.github+json")
|
||||||
|
|
||||||
|
resp, err := http.DefaultClient.Do(req) //nolint:gosec
|
||||||
|
if err != nil {
|
||||||
|
return "", fmt.Errorf("fetching release: %w", err)
|
||||||
|
}
|
||||||
|
defer resp.Body.Close() //nolint:errcheck
|
||||||
|
|
||||||
|
if resp.StatusCode != http.StatusOK {
|
||||||
|
return "", fmt.Errorf("unexpected status %s", resp.Status)
|
||||||
|
}
|
||||||
|
|
||||||
|
var release githubRelease
|
||||||
|
if err := json.NewDecoder(resp.Body).Decode(&release); err != nil {
|
||||||
|
return "", fmt.Errorf("decoding response: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
return release.TagName, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func removeDirectories(dirs []string) error {
|
||||||
|
var wg sync.WaitGroup
|
||||||
|
errCh := make(chan error, len(dirs))
|
||||||
|
|
||||||
|
for _, path := range dirs {
|
||||||
|
wg.Go(func() {
|
||||||
|
if err := os.RemoveAll(path); err != nil {
|
||||||
|
errCh <- fmt.Errorf("remove directory %s: %w", path, err)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
wg.Wait()
|
||||||
|
close(errCh)
|
||||||
|
|
||||||
|
var errs []error
|
||||||
|
for err := range errCh {
|
||||||
|
errs = append(errs, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
return errors.Join(errs...)
|
||||||
|
}
|
||||||
|
|
||||||
|
func createDirectories(dirs []string) error {
|
||||||
|
var wg sync.WaitGroup
|
||||||
|
errCh := make(chan error, len(dirs))
|
||||||
|
|
||||||
|
for _, path := range dirs {
|
||||||
|
wg.Go(func() {
|
||||||
|
if err := os.MkdirAll(path, 0755); err != nil {
|
||||||
|
errCh <- fmt.Errorf("create directory %s: %w", path, err)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
wg.Wait()
|
||||||
|
close(errCh)
|
||||||
|
|
||||||
|
var errs []error
|
||||||
|
for err := range errCh {
|
||||||
|
errs = append(errs, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
return errors.Join(errs...)
|
||||||
}
|
}
|
||||||
|
|
||||||
func download(files map[string]string) error {
|
func download(files map[string]string) error {
|
||||||
@@ -71,15 +288,15 @@ func download(files map[string]string) error {
|
|||||||
return errors.Join(errs...)
|
return errors.Join(errs...)
|
||||||
}
|
}
|
||||||
|
|
||||||
func downloadFile(url, dest string) error {
|
func downloadFile(rawURL, dest string) error {
|
||||||
resp, err := http.Get(url) //nolint:gosec,noctx // static URLs, simple tool
|
resp, err := http.Get(rawURL) //nolint:gosec,noctx // static URLs, simple tool
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return fmt.Errorf("GET %s: %w", url, err)
|
return fmt.Errorf("GET %s: %w", rawURL, err)
|
||||||
}
|
}
|
||||||
defer resp.Body.Close() //nolint:errcheck
|
defer resp.Body.Close() //nolint:errcheck
|
||||||
|
|
||||||
if resp.StatusCode != http.StatusOK {
|
if resp.StatusCode != http.StatusOK {
|
||||||
return fmt.Errorf("GET %s: status %s", url, resp.Status)
|
return fmt.Errorf("GET %s: status %s", rawURL, resp.Status)
|
||||||
}
|
}
|
||||||
|
|
||||||
out, err := os.Create(dest) //nolint:gosec // paths are hardcoded constants
|
out, err := os.Create(dest) //nolint:gosec // paths are hardcoded constants
|
||||||
|
|||||||
@@ -5,6 +5,8 @@ services:
|
|||||||
args:
|
args:
|
||||||
VERSION: ${VERSION:-dev}
|
VERSION: ${VERSION:-dev}
|
||||||
COMMIT: ${COMMIT:-unknown}
|
COMMIT: ${COMMIT:-unknown}
|
||||||
|
secrets:
|
||||||
|
- vendor_token
|
||||||
container_name: games
|
container_name: games
|
||||||
restart: unless-stopped
|
restart: unless-stopped
|
||||||
ports:
|
ports:
|
||||||
@@ -16,3 +18,7 @@ services:
|
|||||||
- PORT=8080
|
- PORT=8080
|
||||||
volumes:
|
volumes:
|
||||||
- ./data:/data
|
- ./data:/data
|
||||||
|
|
||||||
|
secrets:
|
||||||
|
vendor_token:
|
||||||
|
environment: VENDOR_TOKEN
|
||||||
|
|||||||
@@ -24,7 +24,7 @@ templ GamePage(g *connect4.Game, myColor int, messages []chat.Message, chatCfg c
|
|||||||
}
|
}
|
||||||
|
|
||||||
templ GameContent(g *connect4.Game, myColor int, messages []chat.Message, chatCfg chatcomponents.Config) {
|
templ GameContent(g *connect4.Game, myColor int, messages []chat.Message, chatCfg chatcomponents.Config) {
|
||||||
<div id="game-content">
|
<div id="game-content" class="flex flex-col items-center gap-4">
|
||||||
@sharedcomponents.LiveClock()
|
@sharedcomponents.LiveClock()
|
||||||
@sharedcomponents.BackToLobby()
|
@sharedcomponents.BackToLobby()
|
||||||
@sharedcomponents.StealthTitle("text-3xl font-bold")
|
@sharedcomponents.StealthTitle("text-3xl font-bold")
|
||||||
|
|||||||
@@ -12,7 +12,7 @@ templ Base(title string) {
|
|||||||
<head>
|
<head>
|
||||||
<title>{ title }</title>
|
<title>{ title }</title>
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=0"/>
|
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=0"/>
|
||||||
<script defer type="module" src={ assets.StaticPath("js/datastar.js") }></script>
|
<script defer type="module" src={ assets.StaticPath("js/datastar/datastar.js") }></script>
|
||||||
<link href={ assets.StaticPath("css/output.css") } rel="stylesheet" type="text/css"/>
|
<link href={ assets.StaticPath("css/output.css") } rel="stylesheet" type="text/css"/>
|
||||||
</head>
|
</head>
|
||||||
<body class="flex flex-col h-screen">
|
<body class="flex flex-col h-screen">
|
||||||
|
|||||||
@@ -43,7 +43,7 @@ templ GamePage(sg *snake.SnakeGame, mySlot int, messages []chat.Message, chatCfg
|
|||||||
}
|
}
|
||||||
|
|
||||||
templ GameContent(sg *snake.SnakeGame, mySlot int, messages []chat.Message, chatCfg chatcomponents.Config, gameID string) {
|
templ GameContent(sg *snake.SnakeGame, mySlot int, messages []chat.Message, chatCfg chatcomponents.Config, gameID string) {
|
||||||
<div id="game-content">
|
<div id="game-content" class="flex flex-col items-center gap-4">
|
||||||
@components.LiveClock()
|
@components.LiveClock()
|
||||||
@components.BackToLobby()
|
@components.BackToLobby()
|
||||||
<h1 class="text-3xl font-bold">~~~~</h1>
|
<h1 class="text-3xl font-bold">~~~~</h1>
|
||||||
|
|||||||
Reference in New Issue
Block a user