JoYiHubv0.30.0
Api

类型定义

window.JoYiHub 运行时接口与数据结构的完整 TypeScript 类型定义(/api/sdk/joyihub.d.ts)。

网页与原生宿主通过 /api/sdk/joyihub.d.ts(以及 @joyihub/sdk 和 joyihub sdk types)公开 window.JoYiHub 的完整 TypeScript 类型声明。可直接安装 @joyihub/sdk 或通过 joyihub sdk types --out ./joyihub.d.ts 导出到工程目录,获得完整代码补全与静态类型检查:

export type paths = Record<string, never>;
export type webhooks = Record<string, never>;
export interface components {
    schemas: {
        LeaderboardDefinition: {
            enabled: boolean;
            /**
             * Format: uuid
             * @description Release ID where this standings epoch started; omitted for the original standings.
             */
            epoch_release_id?: string;
            /** @description Creator version where this standings epoch started; omitted for the original standings. */
            epoch_version?: string;
            /** @description Current first-place title; empty means no title. */
            first_title: string;
            /** @description Scoring rules are immutable after the first accepted score, including preview scores. */
            has_scores: boolean;
            name: string;
            position: number;
            /** @description Current second-place title; empty means no title. */
            second_title: string;
            /** @enum {string} */
            sort_order: "higher" | "lower";
            /** @description Current third-place title; empty means no title. */
            third_title: string;
            /** @enum {string} */
            unit: "points" | "count" | "milliseconds";
            /** Format: date-time */
            updated_at: string;
        };
        LeaderboardEntry: {
            /** Format: date-time */
            achieved_at: string;
            avatar_hue: number;
            avatar_url: string | null;
            display_name: string;
            id: string;
            rank: number;
            /** @description Configured title for this current rank (1-3); empty when unconfigured or outside the top three. */
            rank_title: string;
            score: number;
        };
        LeaderboardRanking: {
            /** Format: date-time */
            as_of: string;
            ends_at: string | null;
            entries: {
                /** Format: date-time */
                achieved_at: string;
                avatar_hue: number;
                avatar_url: string | null;
                display_name: string;
                id: string;
                rank: number;
                /** @description Configured title for this current rank (1-3); empty when unconfigured or outside the top three. */
                rank_title: string;
                score: number;
            }[];
            /**
             * Format: uuid
             * @description Release ID where this standings epoch started; omitted for the original standings.
             */
            epoch_release_id?: string;
            /** @description Creator version where this standings epoch started; omitted for the original standings. */
            epoch_version?: string;
            leaderboard: {
                enabled: boolean;
                /**
                 * Format: uuid
                 * @description Release ID where this standings epoch started; omitted for the original standings.
                 */
                epoch_release_id?: string;
                /** @description Creator version where this standings epoch started; omitted for the original standings. */
                epoch_version?: string;
                /** @description Current first-place title; empty means no title. */
                first_title: string;
                /** @description Scoring rules are immutable after the first accepted score, including preview scores. */
                has_scores: boolean;
                name: string;
                position: number;
                /** @description Current second-place title; empty means no title. */
                second_title: string;
                /** @enum {string} */
                sort_order: "higher" | "lower";
                /** @description Current third-place title; empty means no title. */
                third_title: string;
                /** @enum {string} */
                unit: "points" | "count" | "milliseconds";
                /** Format: date-time */
                updated_at: string;
            };
            period: string;
            player_rank: {
                entry: {
                    /** Format: date-time */
                    achieved_at: string;
                    avatar_hue: number;
                    avatar_url: string | null;
                    display_name: string;
                    id: string;
                    rank: number;
                    /** @description Configured title for this current rank (1-3); empty when unconfigured or outside the top three. */
                    rank_title: string;
                    score: number;
                } | null;
                ranked: boolean;
            } | null;
            starts_at: string | null;
        };
        PlayerRank: {
            entry: {
                /** Format: date-time */
                achieved_at: string;
                avatar_hue: number;
                avatar_url: string | null;
                display_name: string;
                id: string;
                rank: number;
                /** @description Configured title for this current rank (1-3); empty when unconfigured or outside the top three. */
                rank_title: string;
                score: number;
            } | null;
            ranked: boolean;
        };
        ScoreReceipt: {
            /** Format: date-time */
            accepted_at: string;
            duplicate: boolean;
            position: number;
            results: {
                improved: boolean;
                /** @enum {string} */
                period: "all" | "month" | "week" | "day";
                score: number;
            }[];
            submission_id: string;
        };
        ScoreSubmission: {
            position?: number;
            score: number;
            /**
             * Format: uuid
             * @description Stable lowercase UUID without prefixes; reuse the identical submission when retrying the same release and leaderboard.
             */
            submission_id: string;
        };
        StorageDocument: {
            /** @description Owning signed-in account; hosts verify it before delivering asynchronous replies. */
            account_id: string;
            /** @description Canonical UTF-8 JSON bytes; an empty document occupies zero quota bytes. */
            bytes: number;
            data: {
                [key: string]: string;
            };
            /** @enum {string} */
            environment: "preview" | "published";
            limits: {
                account_bytes: number;
                document_bytes: number;
                key_bytes: number;
                keys: number;
                value_bytes: number;
            };
            namespace_id: string | null;
            revision: number;
            updated_at: string | null;
        };
        StoragePatch: {
            /** Format: uuid */
            namespace_id?: string;
            /** @description String values to atomically merge into the current document. */
            set?: {
                [key: string]: string;
            };
            /** @description Keys to remove; a key cannot also appear in set. */
            delete?: string[];
            /** @description Optional compare-and-swap; a mismatch returns STORAGE_CONFLICT without modifying data. */
            if_revision?: number;
        };
    };
    responses: never;
    parameters: never;
    requestBodies: never;
    headers: never;
    pathItems: never;
}
export type $defs = Record<string, never>;
export type operations = Record<string, never>;

export type LeaderboardDefinition = components["schemas"]["LeaderboardDefinition"];
export type LeaderboardEntry = components["schemas"]["LeaderboardEntry"];
export type LeaderboardRanking = components["schemas"]["LeaderboardRanking"];
export type PlayerRank = components["schemas"]["PlayerRank"];
export type ScoreReceipt = components["schemas"]["ScoreReceipt"];
export type ScoreSubmission = components["schemas"]["ScoreSubmission"];
export type StorageDocument = components["schemas"]["StorageDocument"];
export type StoragePatch = components["schemas"]["StoragePatch"];
export type LeaderboardPeriod = ScoreReceipt["results"][number]["period"];
export interface RuntimeInputError extends Error {
  code: "BAD_REQUEST";
  details: { operation: string; field: string };
}

export interface DisplayState {
  device_type: "phone" | "tablet" | "desktop" | "unknown";
  viewport: { width: number; height: number };
  orientation: "portrait" | "landscape";
  immersive: boolean;
  /** Insets in the work's CSS pixels, after rotation and scale. */
  safe_area: { top: number; right: number; bottom: number; left: number };
}

export interface DisplayMode {
  /** auto clears the instance override and follows the available viewport. */
  orientation?: "portrait" | "landscape" | "auto";
  /** Desktop Web only. Mobile clear-screen changes require manual user action; requests reject with DISPLAY_UNSUPPORTED. */
  immersive?: boolean;
}

export interface DisplayChange {
  state: DisplayState;
  changed_fields: (keyof DisplayState)[];
}

export interface RuntimeEntryState {
  search: string;
  params: URLSearchParams;
  hash: string;
  referrer: string | null;
}

export interface RuntimePlayerProfile {
  id: string;
  display_name: string;
  avatar_url: string | null;
  avatar_hue: number;
  is_guest: boolean;
}

export interface RuntimeAuthSnapshot {
  user: RuntimePlayerProfile;
  authenticated: boolean;
  guest: boolean;
}

export interface RuntimeAuthorProfile {
  id: string;
  display_name: string;
  avatar_url: string | null;
  avatar_hue: number;
  bio: string;
}

export interface RuntimeAuthorRelation {
  following: boolean;
  followed_at: string | null;
}

export interface RuntimeProjectRating {
  my_rating: number;
  rating_count: number;
  rating_average: number | null;
}

export type GuideTarget =
  | "rating"
  | "share"
  | "follow"
  | "comment"
  | "leaderboard"
  | "about"
  | "versions"
  | "options"
  | "audio"
  | "fullscreen";

export interface GuideOptions {
  target?: GuideTarget;
  position?: number;
  message?: string;
  open?: boolean;
}

export interface GuideResult {
  ok: boolean;
  target?: string;
  position?: number;
  reason?: string;
}

/** Progress of the current startup phase only; omit total when it is unknown. */
export interface LoadingProgress {
  phase: "download" | "compile" | "initialize";
  completed?: number;
  total?: number;
  unit?: "bytes" | "items";
}

export type RuntimeCapability =
  | "storage"
  | "leaderboard"
  | "multiplayer"
  | "display"
  | "guide"
  | "player.login"
  | "social.author"
  | "social.relation"
  | "social.rating"
  | "share"
  | "copy"
  | "saveFile"
  | "saveImage"
  | "openExternal"
  | "wakeLock"
  | "haptic"
  | "fullscreen"
  | "camera"
  | "microphone"
  | "navigate"
  | "close";

export interface MultiplayerConnectOptions {
  room?: string;
  name?: string;
  initialState?: Record<string, unknown>;
}

export interface MultiplayerPlayer {
  id: string;
  uid: string;
  name: string;
  avatarUrl: string;
  connected: boolean;
  team: number;
  state: Record<string, unknown>;
  stateRaw: Record<string, unknown>;
}

export interface MultiplayerObject {
  id: string;
  epoch: number;
  owner: string | undefined;
  isMine: boolean;
  state: Record<string, unknown>;
  stateRaw: Record<string, unknown>;
}

export interface MultiplayerObjectClaimOptions {
  authority?: "host";
}

export interface MultiplayerObjectClaimResult {
  requestId: string;
  operation: "claim" | "release" | "remove";
  id: string;
  accepted: boolean;
  owner?: string;
  sequence: number;
  reason?: string;
}

export interface MultiplayerChatMessage {
  id: number;
  from: string;
  name: string;
  text: string;
  at: number;
}

export interface MultiplayerQueueState {
  position: number;
  size: number;
}

export interface MultiplayerMatchView {
  status: string;
  role: "player" | "spectator";
  queue: MultiplayerQueueState;
  players: string[];
  connectedPlayers: string[];
  opponents: string[];
  teams: Record<string, string[]>;
  scores: Record<string, number>;
  championId: string | null;
  challengerId: string | null;
  roundId: number;
  winnerId: string | null;
  message: string;
  startsAt: number | null;
  endsBy: number | null;
  startsInMs: number | null;
  endsInMs: number | null;
}

export interface MultiplayerRoomSession {
  readonly id: string;
  readonly roomId: string;
  readonly code: string;
  readonly host: string;
  readonly isHost: boolean;
  readonly connected: boolean;
  readonly players: Map<string, MultiplayerPlayer>;
  readonly activePlayers: Map<string, MultiplayerPlayer>;
  readonly me: {
    set(next: Record<string, unknown>): void;
    snap(next: Record<string, unknown>): void;
    readonly state: Record<string, unknown>;
  };
  readonly shared: {
    get(key: string): unknown;
    set(key: string, value: unknown): void;
    set(patch: Record<string, unknown>): void;
    keys(): string[];
    readonly state: Record<string, unknown>;
  };
  readonly objects: {
    claim(id: string): boolean;
    claimConfirmed(id: string, options?: MultiplayerObjectClaimOptions): Promise<MultiplayerObjectClaimResult>;
    release(id: string): void;
    releaseConfirmed(id: string, options?: MultiplayerObjectClaimOptions): Promise<MultiplayerObjectClaimResult>;
    remove(id: string): void;
    removeConfirmed(id: string, options?: MultiplayerObjectClaimOptions): Promise<MultiplayerObjectClaimResult>;
    set(id: string, state: Record<string, unknown>): void;
    snap(id: string, state: Record<string, unknown>): void;
    get(id: string): MultiplayerObject | undefined;
    ids(): string[];
  };
  readonly inputs: {
    send(payload: unknown): void;
    on(callback: (from: string, payload: unknown) => void): () => void;
  };
  readonly chat: {
    send(text: string): void;
    on(callback: (message: MultiplayerChatMessage) => void): () => void;
    readonly history: MultiplayerChatMessage[];
    mute(playerId: string): void;
    unmute(playerId: string): void;
    readonly muted: string[];
  };
  onHostTick(hz: number, callback: (dtMs: number) => void): () => void;
  setRoomOpen(open: boolean): void;
  send(type: string, payload?: unknown): void;
  on(event: "join" | "change", callback: (playerId: string, state: Record<string, unknown>) => void): () => void;
  on(event: "leave" | "host" | "object", callback: (id: string) => void): () => void;
  on(event: "shared", callback: (key: string, value: unknown) => void): () => void;
  on(event: "room:open", callback: (info: { open: boolean }) => void): () => void;
  on(event: "disconnect", callback: (info: { code: number; reason: string }) => void): () => void;
  on(event: "error", callback: (error: Error & { code?: string }) => void): () => void;
  on(event: string, callback: (payload: unknown, from?: string) => void): () => void;
  leave(): void;
  serverNow(): number;
  readonly rtt: number;
  readonly clockSynced: boolean;
  timeUntil(epochMs: number): number;
}

export interface MultiplayerMatchHandle extends MultiplayerRoomSession {
  readonly session: MultiplayerRoomSession | null;
  readonly matchmaking: MultiplayerMatchView;
  on(event: "searching", callback: () => void): () => void;
  on(event: "queue", callback: (state: MultiplayerQueueState) => void): () => void;
  on(event: "matched" | "spectate", callback: (seat: { roomId: string; code: string; role: string }) => void): () => void;
  on(event: "matchStart" | "matchUpdate" | "matchEnded", callback: (match: Record<string, unknown>) => void): () => void;
  on(event: "join" | "change", callback: (playerId: string, state: Record<string, unknown>) => void): () => void;
  on(event: "leave" | "host" | "object", callback: (id: string) => void): () => void;
  on(event: "shared", callback: (key: string, value: unknown) => void): () => void;
  on(event: "room:open", callback: (info: { open: boolean }) => void): () => void;
  on(event: "disconnect", callback: (info: { code: number; reason: string }) => void): () => void;
  on(event: "error", callback: (error: Error & { code?: string }) => void): () => void;
  on(event: string, callback: (payload: unknown, from?: string) => void): () => void;
  eliminated(): void;
  score(delta?: number): void;
  finish(): void;
  retry(): void;
  cancel(): void;
}

export type RuntimeQualityMode = "performance" | "balanced" | "native";
export type RuntimeFrameRateMode = "30" | "60" | "vsync" | "uncapped";

export interface RuntimePerformanceStats {
  fps: number;
  low1pFps: number;
  frameTimeMs: number;
  jankFrames: number;
  jankRatio: number;
  longTaskCount: number;
  fpsHistory: number[];
  ttfbMs: number;
  domReadyMs: number;
  ttfiMs: number;
  resourceCount: number;
  cachedResourceCount: number;
  casHitCount: number;
  casManifestCount: number;
  transferKB: number;
  backend: string;
  gpuRenderer: string;
  canvasWidth: number;
  canvasHeight: number;
  cssWidth: number;
  cssHeight: number;
  dpr: number;
  nativeDpr: number;
  qualityMode: RuntimeQualityMode;
  frameRateMode: RuntimeFrameRateMode;
  pointerLocked: boolean;
  hasFocus: boolean;
  interactiveReady: boolean;
  heapUsedMB: number;
  heapTotalMB: number;
}

export interface JoYiHubSDK {
  readonly version: "2.0";

  /** Business readiness, distinct from document load and automatic inference. */
  lifecycle: {
    /** Call before engine/resource initialization; does not start gameplay. */
    prepare(): void;
    /** Opt into host loading UI. Report actual work, never timer-based estimates; finish with ready(). */
    progress(progress: LoadingProgress): void;
    /** Call once controls are bound and the initial playable scene is rendered. */
    ready(): void;
  };

  player: {
    /** Returns the current player identity snapshot synchronously. */
    getProfile(): RuntimePlayerProfile;
    isAuthenticated(): boolean;
    /** Opens the host sign-in flow without reloading the work (Web and supported native hosts). */
    requestLogin(options?: string | { reason?: string }): Promise<RuntimeAuthSnapshot>;
    /** Invokes immediately with the current snapshot and whenever authentication state changes. */
    onAuthChange(callback: (snapshot: RuntimeAuthSnapshot) => void): () => void;
  };

  storage: {
    read(options?: { namespace_id?: string }): Promise<StorageDocument>;
    patch(options?: StoragePatch): Promise<StorageDocument>;
  };

  leaderboard: {
    /** Create once per completed run and slot; the frozen object is reused for retries within the same release. */
    createSubmission(options: Pick<ScoreSubmission, "position" | "score">): Readonly<ScoreSubmission>;
    /** Requires the stable submission_id. Rejects unknown fields, coercions and malformed values. */
    submitScore(options: ScoreSubmission): Promise<ScoreReceipt>;
    getEntries(options?: { position?: number; period?: LeaderboardPeriod; limit?: number }): Promise<LeaderboardRanking>;
    getPlayerRank(options?: { position?: number; period?: LeaderboardPeriod }): Promise<PlayerRank>;
    open(options?: number | { position?: number; message?: string }): Promise<GuideResult>;
  };

  multiplayer: {
    connect(options?: MultiplayerConnectOptions): Promise<MultiplayerRoomSession>;
    matchmake(options?: MultiplayerConnectOptions): Promise<MultiplayerMatchHandle>;
    createPrivate(options?: MultiplayerConnectOptions): Promise<MultiplayerMatchHandle>;
    joinPrivate(code: string, options?: MultiplayerConnectOptions): Promise<MultiplayerMatchHandle>;
  };

  display: {
    getState(): Promise<DisplayState>;
    /** Delivers a full initial state, then actual changes. Unsubscribe is idempotent. */
    subscribe(listener: (change: DisplayChange) => void): Promise<() => void>;
    /** Resolves after layout confirmation. Concurrent changes reject with DISPLAY_BUSY. */
    setMode(options: DisplayMode): Promise<DisplayState>;
    getEntry(): RuntimeEntryState;
    onClosing(callback: () => void): () => void;
    navigate(target: string): Promise<{ ok: boolean }>;
    close(): Promise<{ ok: boolean }>;
  };

  guide: {
    spotlight(targetOrOptions: GuideTarget | GuideOptions, options?: Omit<GuideOptions, "target">): Promise<GuideResult>;
    rate(options?: string | Omit<GuideOptions, "target">): Promise<GuideResult>;
    share(options?: string | Omit<GuideOptions, "target">): Promise<GuideResult>;
    follow(options?: string | Omit<GuideOptions, "target">): Promise<GuideResult>;
    comment(options?: string | Omit<GuideOptions, "target">): Promise<GuideResult>;
    leaderboard(options?: number | { position?: number; message?: string }): Promise<GuideResult>;
    about(options?: string | Omit<GuideOptions, "target">): Promise<GuideResult>;
    versions(options?: string | Omit<GuideOptions, "target">): Promise<GuideResult>;
    options(options?: string | Omit<GuideOptions, "target">): Promise<GuideResult>;
    audio(options?: string | Omit<GuideOptions, "target">): Promise<GuideResult>;
    fullscreen(options?: string | Omit<GuideOptions, "target">): Promise<GuideResult>;
  };

  social: {
    getAuthorProfile(): Promise<RuntimeAuthorProfile>;
    getAuthorRelation(): Promise<RuntimeAuthorRelation>;
    getProjectRating(): Promise<RuntimeProjectRating>;
  };

  system: {
    /** Detects the current transport/API, not login, permission, connectivity or operation success. */
    supports(capability: RuntimeCapability): boolean;
    share(options?: { text?: string; params?: Record<string, string | number | boolean> }): Promise<{ status: "shared" | "copied" | "dismissed" | "unavailable"; url: string }>;
    copyText(text: string): Promise<{ ok: boolean; error?: string }>;
    saveFile(file: Blob | string, name?: string): Promise<{ ok: boolean; error?: string }>;
    saveImage(input: string | { image?: string; dataUrl?: string; url?: string }): Promise<{ ok: boolean; error?: string }>;
    openExternal(url: string): Promise<{ ok: boolean; error?: string }>;
    keepAwake(on: boolean): Promise<{ ok: boolean; error?: string }>;
    haptic(kind?: "selection" | "light" | "medium" | "heavy" | "success" | "warning" | "error"): void;
    /** Standard browser fullscreen for standalone pages. Hosted desktop clear-screen uses display.setMode. */
    setFullscreen(on: boolean): Promise<{ ok: boolean; error?: string }>;
    releasePointerLock(): void;
  };

  media: {
    requestCamera(options?: { facingMode?: string; video?: MediaTrackConstraints }): Promise<MediaStream>;
    requestMicrophone(options?: { audio?: MediaTrackConstraints | boolean }): Promise<MediaStream>;
    stopMedia(stream?: MediaStream): Promise<void>;
  };

  performance: {
    getStats(): RuntimePerformanceStats;
    setQualityMode(mode: RuntimeQualityMode): void;
    setFrameRateMode(mode: RuntimeFrameRateMode): void;
  };
}

declare global {
  var JoYiHub: JoYiHubSDK;
  interface Window {
    JoYiHub: JoYiHubSDK;
  }
}