Back to winniegolf
SOURCE / PINNED RELEASE

Made of little things.

winniegolf

Release
017b791c0f4b…
Author-recorded commit
612845c125fd…
License
LICENSE
Author’s source reference
nostr://npub18weq5jzw27gkhwcuf6gu57alcptjdvh78nlulgpkz8s7pnlxfnnspc00s9/wss%3A%2F%2Fgit.napplet.soy%2F/n-2d501957e21

Archive hash verified: 713b42364f27a576…. The source-to-build association is the author’s claim; it has not been independently rebuilt.

src/game/leaderboard.ts
import { cvm } from '@napplet/sdk';
import { runtimeHasDomain } from '../domain-availability.js';

/**
 * Shared scoreboard for a finished round, via the soyLI backend boards service.
 *
 * The whole module is optional: the round is fully playable in a shell that
 * injects no `cvm` domain, or before the generated backend context exists, so
 * every entry point degrades to `null` instead of throwing.
 */

/** Board id registered in `napplet.json` -> `backend.boards`.
 *  v2 is a fresh board for the 10-hole round; v1 scores stay on v1. */
export const BOARD = 'round-strokes-v2';

/** Top of the table we show. */
export const LEADERBOARD_SIZE = 3;

interface BackendContext {
  napplet?: string;
  provider?: { pubkey?: string; relays?: string[] };
  boards?: string[];
}

/**
 * `.napplet-space/soy-backend.json` is generated and git-ignored, so a fresh
 * checkout may not have it yet. A glob keeps the build working either way and
 * still reads the generated file rather than a hand-copied namespace.
 */
const contextModules = import.meta.glob<{ default: BackendContext }>(
  '../../.napplet-space/soy-backend.json',
  { eager: true },
);

function backendContext(): BackendContext | null {
  for (const module of Object.values(contextModules)) {
    const context = module?.default;
    if (context && typeof context.napplet === 'string') return context;
  }
  return null;
}

/** Whether this shell can show a leaderboard at all. */
export function leaderboardAvailable(): boolean {
  if (!runtimeHasDomain('cvm')) return false;
  const context = backendContext();
  return Boolean(context?.napplet && context.provider?.pubkey);
}

export interface LeaderRow {
  /** Display name the player submitted, when they submitted one. */
  name: string | null;
  /** Total strokes for the round. Lower is better on this board. */
  score: number;
  /** Transport actor id; only used to de-duplicate and as a last-resort label. */
  actor: string;
}

async function callBoard(
  tool: string,
  args: Record<string, unknown>,
): Promise<Record<string, unknown> | null> {
  if (!leaderboardAvailable()) return null;
  const context = backendContext();
  if (!context?.napplet || !context.provider?.pubkey) return null;

  const server = {
    pubkey: context.provider.pubkey,
    ...(context.provider.relays ? { relays: context.provider.relays } : {}),
  };
  const ref = { napplet: context.napplet, board: BOARD };

  try {
    const result = await cvm.callTool(server, tool, { ...ref, ...args });
    if (result.isError) return null;
    const structured: unknown = result.structuredContent;
    if (structured && typeof structured === 'object') {
      return structured as Record<string, unknown>;
    }
    // Some providers answer with a JSON text block instead of structured data.
    const text = result.content?.find((block) => block.type === 'text')?.text;
    if (text) {
      const parsed: unknown = JSON.parse(text);
      if (parsed && typeof parsed === 'object') return parsed as Record<string, unknown>;
    }
  } catch {
    // A denied, offline or older provider must leave the napplet usable.
  }
  return null;
}

function readRows(payload: Record<string, unknown> | null): LeaderRow[] {
  const rows: unknown = payload?.rows;
  if (!Array.isArray(rows)) return [];

  const parsed: LeaderRow[] = [];
  for (const entry of rows) {
    if (!entry || typeof entry !== 'object') continue;
    const row = entry as Record<string, unknown>;
    const score = typeof row.score === 'number' ? row.score : Number(row.score);
    if (!Number.isFinite(score)) continue;
    parsed.push({
      score,
      name: typeof row.name === 'string' && row.name.trim() ? row.name.trim() : null,
      actor: typeof row.actor === 'string' ? row.actor : '',
    });
  }

  // The board orders by strokes, but sort here too so the display never depends
  // on a provider's page ordering.
  parsed.sort((a, b) => a.score - b.score || a.actor.localeCompare(b.actor));
  return parsed;
}

/** Read the leading rounds, best first. Returns `null` when unavailable. */
export async function readTopRounds(limit = LEADERBOARD_SIZE): Promise<LeaderRow[] | null> {
  const payload = await callBoard('soy_board_read', { limit: Math.max(1, limit) });
  if (!payload) return null;
  return readRows(payload).slice(0, limit);
}

/**
 * Submit a finished round. A repeat or worse score cannot inflate a personal
 * best, so calling this once per round is safe. Returns whether it landed.
 */
export async function submitRound(score: number, name: string): Promise<boolean> {
  if (!leaderboardAvailable()) return false;
  if (!Number.isFinite(score)) return false;
  const trimmed = name.trim();
  const payload = await callBoard('soy_board_submit', {
    score,
    ...(trimmed ? { name: trimmed.slice(0, 32) } : {}),
  });
  return payload !== null;
}