@live-game/sdk 0.5.0 → 2.0.0-dev.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,101 @@
1
+ import type { AppCommand, AppContext } from "./types.js";
2
+ export declare function useAppSDK<State = unknown, Config extends object = Record<string, unknown>, Command extends AppCommand = AppCommand>(): {
3
+ ready: Promise<AppContext<State, Config>>;
4
+ dispose: (error?: import("./client.js").AppSDKError) => void;
5
+ call: <T = unknown>(method: import("./contracts.js").AppCapability, ...args: unknown[]) => Promise<T>;
6
+ on: {
7
+ <K extends keyof {
8
+ "app.context": AppContext<State_1, Config_1>;
9
+ "app.stop": null;
10
+ state: State_1 | null;
11
+ config: Config_1;
12
+ timer: import("./types.js").AppTimerEvent;
13
+ "audio.job": import("./types.js").AudioJobEvent;
14
+ command: Command_1;
15
+ "app.message": AppCommand;
16
+ "live.status": import("./types.js").AppSourceStatus;
17
+ }>(event: K, handler: (value: {
18
+ "app.context": AppContext<State, Config>;
19
+ "app.stop": null;
20
+ state: State | null;
21
+ config: Config;
22
+ timer: import("./types.js").AppTimerEvent;
23
+ "audio.job": import("./types.js").AudioJobEvent;
24
+ command: Command;
25
+ "app.message": AppCommand;
26
+ "live.status": import("./types.js").AppSourceStatus;
27
+ }[K]) => unknown): () => void;
28
+ <T = unknown>(event: string, handler: (value: NoInfer<T>) => unknown): () => void;
29
+ };
30
+ readonly disposed: boolean;
31
+ lifecycle: {
32
+ ready: () => Promise<void>;
33
+ fail: (message: string) => Promise<void>;
34
+ onStop: (handler: () => unknown) => () => void;
35
+ };
36
+ readonly context: AppContext<State, Config> | undefined;
37
+ supports: (capability: import("./contracts.js").AppCapability) => boolean;
38
+ config: {
39
+ get: () => Promise<Config>;
40
+ update: (values: Partial<Config>) => Promise<Config>;
41
+ onChange: (handler: (value: Config) => unknown) => () => void;
42
+ };
43
+ storage: {
44
+ get: <T = unknown>(key: string) => Promise<T | null>;
45
+ set: (key: string, value: unknown) => Promise<null>;
46
+ delete: (key: string) => Promise<null>;
47
+ };
48
+ state: {
49
+ get: <T = State>() => Promise<T | null>;
50
+ publish: (value: State) => Promise<null>;
51
+ onChange: (handler: (value: State | null) => unknown) => () => void;
52
+ };
53
+ commands: {
54
+ send: (...[type, payload]: import("./types.js").AppCommandArgs<Command>) => Promise<null>;
55
+ on: <T = Command>(handler: (value: NoInfer<T>) => unknown) => () => void;
56
+ };
57
+ views: {
58
+ notify: (type: string, payload?: unknown) => Promise<null>;
59
+ on: <T = AppCommand>(handler: (value: T) => unknown) => () => void;
60
+ };
61
+ live: {
62
+ room: () => Promise<import("./index.js").LiveRoomSnapshot | null>;
63
+ on: {
64
+ <K extends import("./live-events.js").LiveEventType>(type: K, handler: (event: import("./types.js").AppLiveEventMap[K], envelope: import("./contracts.js").AppLiveEnvelope<import("./types.js").AppLiveEventMap[K]>) => unknown): () => void;
65
+ <T>(type: import("./live-events.js").LiveEventType, handler: (event: NoInfer<T>, envelope: import("./contracts.js").AppLiveEnvelope<NoInfer<T>>) => unknown): () => void;
66
+ };
67
+ };
68
+ catalog: {
69
+ gifts: (query: import("./contracts.js").AppGiftQuery) => Promise<import("./contracts.js").AppGiftCatalog>;
70
+ };
71
+ guide: {
72
+ publish: (content: import("./contracts.js").AppGuide) => Promise<void>;
73
+ };
74
+ audio: {
75
+ speak: (text: string, options?: import("./types.js").SpeechOptions) => Promise<{
76
+ jobId: string;
77
+ }>;
78
+ play: (asset: string, options?: import("./types.js").AudioPlayOptions) => Promise<{
79
+ jobId: string;
80
+ }>;
81
+ cancel: (jobId: string) => Promise<null>;
82
+ voices: () => Promise<import("./types.js").AudioVoice[]>;
83
+ onJob: (handler: (event: import("./types.js").AudioJobEvent) => unknown) => () => void;
84
+ };
85
+ timers: {
86
+ set: (key: string, durationMs: number) => Promise<null>;
87
+ cancel: (key: string) => Promise<null>;
88
+ on: (handler: (event: import("./types.js").AppTimerEvent) => unknown) => () => void;
89
+ };
90
+ text: {
91
+ similarity: (first: string, second: string) => Promise<number>;
92
+ };
93
+ assets: {
94
+ image: (url: string) => Promise<string>;
95
+ };
96
+ log: (level: "info" | "warn" | "error", message: string) => Promise<null>;
97
+ };
98
+ export declare function useAppContext<State = unknown, Config extends object = Record<string, unknown>>(): AppContext<State, Config> | undefined;
99
+ export declare function useAppState<T = unknown>(): T | null;
100
+ export declare function useAppConfig<T extends object = Record<string, unknown>>(): T | null;
101
+ export declare function sendAppCommand(type: string, payload?: unknown): Promise<null>;
@@ -0,0 +1,39 @@
1
+ import { useCallback, useMemo, useSyncExternalStore } from "react";
2
+ import { createAppSDK } from "./client.js";
3
+ export function useAppSDK() {
4
+ return useMemo(() => createAppSDK(), []);
5
+ }
6
+ function subscribe(sdk, notify) {
7
+ let active = true;
8
+ const remove = [sdk.on("app.context", notify), sdk.state.onChange(notify), sdk.config.onChange(notify)];
9
+ void sdk.ready
10
+ .then(() => {
11
+ if (active)
12
+ notify();
13
+ })
14
+ .catch(() => {
15
+ if (active)
16
+ notify();
17
+ });
18
+ return () => {
19
+ active = false;
20
+ for (const off of remove)
21
+ off();
22
+ };
23
+ }
24
+ export function useAppContext() {
25
+ const sdk = useAppSDK();
26
+ const listen = useCallback((notify) => subscribe(sdk, notify), [sdk]);
27
+ return useSyncExternalStore(listen, () => sdk.context, () => undefined);
28
+ }
29
+ export function useAppState() {
30
+ const context = useAppContext();
31
+ return context?.state ?? null;
32
+ }
33
+ export function useAppConfig() {
34
+ const context = useAppContext();
35
+ return context?.config ?? null;
36
+ }
37
+ export function sendAppCommand(type, payload) {
38
+ return createAppSDK().commands.send(type, payload);
39
+ }
@@ -0,0 +1,55 @@
1
+ import type { AppBootstrap } from "./contracts.js";
2
+ import type { LiveEvent, LiveEventType } from "./live-events.js";
3
+ export type AppLiveEventMap = {
4
+ [K in LiveEventType]: Extract<LiveEvent, {
5
+ type: K;
6
+ }>;
7
+ };
8
+ export type AppCommand<Type extends string = string, Payload = unknown> = {
9
+ type: Type;
10
+ payload?: Payload;
11
+ };
12
+ export type AppCommandArgs<C extends AppCommand> = C extends AppCommand ? C extends {
13
+ payload: unknown;
14
+ } ? [type: C["type"], payload: C["payload"]] : "payload" extends keyof C ? [type: C["type"], payload?: C["payload"]] : [type: C["type"]] : never;
15
+ export type AppContext<State = unknown, Config extends object = Record<string, unknown>> = Omit<AppBootstrap, "state" | "config"> & {
16
+ state: State | null;
17
+ config: Config;
18
+ };
19
+ export type AudioJobStatus = "queued" | "playing" | "completed" | "cancelled" | "failed";
20
+ export type AudioJobEvent = {
21
+ jobId: string;
22
+ status: AudioJobStatus;
23
+ error?: string;
24
+ };
25
+ export type AudioVoice = {
26
+ id: string;
27
+ name: string;
28
+ language: string;
29
+ };
30
+ export type SpeechOptions = {
31
+ /** 0–1; default 1. */
32
+ volume?: number;
33
+ /** 0.5–2; default 1. */
34
+ rate?: number;
35
+ /** 0.5–2; default 1. */
36
+ pitch?: number;
37
+ voice?: string;
38
+ priority?: "normal" | "high";
39
+ };
40
+ export type AudioPlayOptions = {
41
+ volume?: number;
42
+ rate?: number;
43
+ loop?: boolean;
44
+ };
45
+ export type AppTimerEvent = {
46
+ key: string;
47
+ deadline: number;
48
+ lateBy: number;
49
+ };
50
+ export type AppSourceStatus = {
51
+ id: string | null;
52
+ connected: boolean;
53
+ events: readonly string[];
54
+ room: import("../room-snapshot.js").LiveRoomSnapshot | null;
55
+ };
@@ -0,0 +1 @@
1
+ export {};
package/dist/index.d.ts CHANGED
@@ -1,6 +1 @@
1
- export { createSDK } from "./createSDK.js";
2
- export { createMockSDK } from "./mock/index.js";
3
- export type { MockLiveGameSDK, MockSDKCall, MockSDKOptions } from "./mock/index.js";
4
- export { PlatformError } from "./types.js";
5
- export type { LiveGameSDK, BaseUserMessage, DanmakuMessage, CommentMessage, GiftMessage, LikeMessage, SocialMessage, RoomStatsMessage, RoomInfo, TimerEvent, BroadcastEvent, EventHandler, StorageAPI, GameConfig, ConfigSchema, ConfigAPI, GameCommand, CommandAPI, SettleResult, ReportAPI, RoomAPI, StateAPI, PlatformAPI, } from "./types.js";
6
- export { useGameState, useGameConfig, sendCmd } from "./react/index.js";
1
+ export * from "./app/index.js";
package/dist/index.js CHANGED
@@ -1,5 +1 @@
1
- export { createSDK } from "./createSDK.js";
2
- export { createMockSDK } from "./mock/index.js";
3
- export { PlatformError } from "./types.js";
4
- // React hooks(可选,非 React 项目不需要 import)
5
- export { useGameState, useGameConfig, sendCmd } from "./react/index.js";
1
+ export * from "./app/index.js";
@@ -0,0 +1,33 @@
1
+ /** Public, read-only room data. Authentication credentials and connection controls are never included. */
2
+ export type RoomMetric = {
3
+ readonly value: number | null;
4
+ readonly observedAt: number | null;
5
+ readonly status: "unknown" | "fresh" | "stale" | "unsupported";
6
+ };
7
+ export type LiveRoomSnapshot = {
8
+ readonly schemaVersion: 1;
9
+ readonly contextId: string;
10
+ readonly revision: number;
11
+ /** An adapter registry ID; new platforms do not require games to upgrade their SDK. */
12
+ readonly platform: string;
13
+ readonly roomId: string;
14
+ readonly title: string | null;
15
+ readonly streamerNickname: string | null;
16
+ readonly streamerAvatar: string | null;
17
+ /** Source-reported broadcast state. A connected collector does not imply a live broadcast. */
18
+ readonly broadcastStatus: "live" | "offline" | "ended" | "unknown";
19
+ readonly dataStatus: "waiting" | "live" | "stale" | "offline";
20
+ readonly connectedAt: number | null;
21
+ readonly updatedAt: number | null;
22
+ readonly metrics: {
23
+ readonly online: RoomMetric;
24
+ readonly platformLikes: RoomMetric;
25
+ /** Platform-reported cumulative viewers, when its semantics are verified by the adapter. */
26
+ readonly totalViewers?: RoomMetric;
27
+ /** Only deduplicated increments received locally within this context, including reconnects. */
28
+ readonly receivedLikes: number;
29
+ readonly receivedComments: number;
30
+ readonly receivedGifts: number;
31
+ readonly receivedEnters: number;
32
+ };
33
+ };
@@ -0,0 +1 @@
1
+ export {};
package/package.json CHANGED
@@ -1,48 +1,50 @@
1
- {
2
- "name": "@live-game/sdk",
3
- "version": "0.5.0",
4
- "type": "module",
5
- "description": "Live Game SDK for game and control iframe integrations.",
6
- "main": "dist/index.js",
7
- "types": "dist/index.d.ts",
8
- "exports": {
9
- ".": {
10
- "types": "./dist/index.d.ts",
11
- "import": "./dist/index.js"
12
- },
13
- "./react": {
14
- "types": "./dist/react/index.d.ts",
15
- "import": "./dist/react/index.js"
1
+ {
2
+ "name": "@live-game/sdk",
3
+ "version": "2.0.0-dev.8",
4
+ "type": "module",
5
+ "description": "Local application SDK for browser workers, controls and outputs",
6
+ "main": "dist/index.js",
7
+ "types": "dist/index.d.ts",
8
+ "exports": {
9
+ "./app": {
10
+ "types": "./dist/app/index.d.ts",
11
+ "import": "./dist/app/index.js"
12
+ },
13
+ "./app/react": {
14
+ "types": "./dist/app/react.d.ts",
15
+ "import": "./dist/app/react.js"
16
+ },
17
+ ".": {
18
+ "types": "./dist/index.d.ts",
19
+ "import": "./dist/index.js"
16
20
  }
17
- },
18
- "files": [
19
- "dist",
20
- "README.md"
21
- ],
22
- "publishConfig": {
23
- "access": "public"
24
- },
21
+ },
22
+ "files": [
23
+ "dist",
24
+ "README.md",
25
+ "CHANGELOG.md",
26
+ "UPGRADING.md"
27
+ ],
28
+ "publishConfig": {
29
+ "access": "public"
30
+ },
25
31
  "scripts": {
26
- "build": "node scripts/clean-dist.mjs && tsc -p tsconfig.json",
32
+ "build": "node scripts/sync-room-contract.mjs && node scripts/sync-app-contract.mjs && node scripts/clean-dist.mjs && tsc -p tsconfig.json",
27
33
  "test": "vitest run",
28
- "check": "tsc --noEmit",
29
- "prepack": "npm run build",
30
- "build:template-zip": "tsx scripts/build-template-zip.ts"
31
- },
32
- "peerDependencies": {
33
- "react": "^19.0.0"
34
- },
35
- "peerDependenciesMeta": {
36
- "react": {
37
- "optional": true
38
- }
39
- },
40
- "devDependencies": {
34
+ "check": "node scripts/sync-room-contract.mjs --check && node scripts/sync-app-contract.mjs --check && tsc -p tsconfig.types.json",
35
+ "prepack": "npm run build"
36
+ },
37
+ "peerDependencies": {
38
+ "react": "^19.0.0"
39
+ },
40
+ "peerDependenciesMeta": {
41
+ "react": {
42
+ "optional": true
43
+ }
44
+ },
45
+ "devDependencies": {
41
46
  "@types/react": "^19.0.0",
42
- "adm-zip": "^0.5.18",
43
- "typescript": "^5.0.0",
44
- "tsx": "^4.0.0",
45
- "vite": "^5.0.0",
47
+ "typescript": "^5.0.0",
46
48
  "vitest": "^2.0.5"
47
- }
48
- }
49
+ }
50
+ }
@@ -1,9 +0,0 @@
1
- import type { LiveGameSDK } from "./types.js";
2
- /**
3
- * 创建 SDK 实例
4
- *
5
- * 检测平台宿主注入的 window.__LIVEGAME_SDK__。
6
- * 本地开发请使用 @live-game/cli dev 启动调试服务器。
7
- * Mock 模式已移除——使用 createMockSDK() 进行单元测试。
8
- */
9
- export declare function createSDK(): LiveGameSDK;
package/dist/createSDK.js DELETED
@@ -1,17 +0,0 @@
1
- /**
2
- * 创建 SDK 实例
3
- *
4
- * 检测平台宿主注入的 window.__LIVEGAME_SDK__。
5
- * 本地开发请使用 @live-game/cli dev 启动调试服务器。
6
- * Mock 模式已移除——使用 createMockSDK() 进行单元测试。
7
- */
8
- export function createSDK() {
9
- if (typeof window !== "undefined" &&
10
- window.__LIVEGAME_SDK__) {
11
- return window.__LIVEGAME_SDK__;
12
- }
13
- throw new Error("LiveGame SDK 未检测到平台宿主注入。\n" +
14
- "• 开发调试: 请使用 npx @live-game/dev-cli dev 启动本地调试\n" +
15
- "• 生产环境: 游戏通过平台宿主加载,SDK 自动注入\n" +
16
- "• 单元测试: 请使用 createMockSDK()");
17
- }
@@ -1,19 +0,0 @@
1
- import { type GameConfig, type LiveGameSDK, type RoomInfo } from "../types.js";
2
- export type MockSDKCall = {
3
- method: string;
4
- args: unknown[];
5
- };
6
- export type MockSDKOptions = {
7
- permissions?: string[];
8
- config?: GameConfig;
9
- storage?: Record<string, string>;
10
- room?: Partial<RoomInfo>;
11
- };
12
- export type MockLiveGameSDK = LiveGameSDK & {
13
- /** Deterministically inject an event; local integration belongs in dev-cli. */
14
- emit<T = unknown>(event: string, data: T): void;
15
- readonly calls: MockSDKCall[];
16
- dispose(): void;
17
- };
18
- /** Deterministic SDK test double. It never starts random background traffic. */
19
- export declare function createMockSDK(options?: MockSDKOptions): MockLiveGameSDK;
@@ -1,95 +0,0 @@
1
- import { PlatformError } from "../types.js";
2
- import { createMockPlatform } from "./platform.js";
3
- const capabilities = [
4
- "events", "events.comment", "events.gift", "events.like", "events.enter", "events.follow", "events.share", "events.fansclub", "events.room_stats", "events.room_message", "events.banner", "events.rank", "events.live_end", "events.raw",
5
- "storage", "storage.get", "storage.set", "storage.delete",
6
- "config", "config.get", "config.getDefault", "config.update",
7
- "command", "command.send", "state", "state.publish",
8
- "platform", "platform.similarity", "platform.timer", "platform.tts",
9
- "report", "report.score", "report.settle", "room", "room.getInfo",
10
- "broadcast", "broadcast.send",
11
- ];
12
- /** Deterministic SDK test double. It never starts random background traffic. */
13
- export function createMockSDK(options = {}) {
14
- const declared = new Set(options.permissions ?? capabilities);
15
- const handlers = new Map();
16
- const calls = [];
17
- const timers = new Set();
18
- const values = new Map(Object.entries(options.storage ?? {}));
19
- let config = { ...(options.config ?? {}) };
20
- let ready = false;
21
- const supports = (capability) => declared.has(capability)
22
- || declared.has(capability.split(".")[0])
23
- || (!capability.includes(".") && [...declared].some((value) => value.startsWith(`${capability}.`)));
24
- const requireCapability = (capability) => {
25
- if (!supports(capability))
26
- throw new PlatformError(`Mock 未开放能力:${capability}`, "CAPABILITY_DISABLED");
27
- };
28
- const record = (method, args) => calls.push({ method, args });
29
- const emit = (event, data) => handlers.get(event)?.forEach((handler) => handler(data));
30
- const platform = createMockPlatform();
31
- const sdk = {
32
- version: "0.5.0",
33
- apiVersion: "1.0",
34
- calls,
35
- supports,
36
- onReady(handler) { if (ready)
37
- queueMicrotask(handler);
38
- else
39
- this.on("__ready", handler); },
40
- onDisconnect(handler) { this.on("__disconnect", handler); },
41
- onError(handler) { this.on("__error", handler); },
42
- on(event, handler) {
43
- if (!handlers.has(event))
44
- handlers.set(event, new Set());
45
- handlers.get(event).add(handler);
46
- },
47
- off(event, handler) { handlers.get(event)?.delete(handler); },
48
- emit,
49
- storage: {
50
- async get(key) { requireCapability("storage.get"); record("storage.get", [key]); return values.get(key) ?? null; },
51
- async set(key, value) { requireCapability("storage.set"); record("storage.set", [key, value]); values.set(key, value); },
52
- async delete(key) { requireCapability("storage.delete"); record("storage.delete", [key]); values.delete(key); },
53
- },
54
- config: {
55
- async get() { requireCapability("config.get"); record("config.get", []); return { ...config }; },
56
- async getDefault() { requireCapability("config.getDefault"); record("config.getDefault", []); return { ...config }; },
57
- async update(next) { requireCapability("config.update"); record("config.update", [next]); config = { ...next }; emit("config", config); },
58
- },
59
- command: {
60
- async send(command) { requireCapability("command.send"); record("command.send", [command]); emit("command", command); },
61
- },
62
- state: {
63
- async publish(state) { requireCapability("state.publish"); record("state.publish", [state]); emit("game_state", state); },
64
- },
65
- report: {
66
- async score(playerId, score) { requireCapability("report.score"); record("report.score", [playerId, score]); },
67
- async settle(results) { requireCapability("report.settle"); record("report.settle", [results]); },
68
- },
69
- room: {
70
- async getInfo() {
71
- requireCapability("room.getInfo");
72
- record("room.getInfo", []);
73
- return { roomId: "mock-room", title: "模拟直播间", streamerNickname: "模拟主播", onlineCount: 0, ...options.room };
74
- },
75
- },
76
- platform: {
77
- async similarity(a, b) { requireCapability("platform.similarity"); record("platform.similarity", [a, b]); return platform.similarity(a, b); },
78
- async timer(key, durationMs) {
79
- requireCapability("platform.timer");
80
- record("platform.timer", [key, durationMs]);
81
- const timer = setTimeout(() => { timers.delete(timer); emit("timer", { key }); }, Math.max(0, durationMs));
82
- timers.add(timer);
83
- },
84
- async tts(text, ttsOptions) { requireCapability("platform.tts"); record("platform.tts", [text, ttsOptions]); },
85
- async call(method, ...args) { throw new PlatformError(`Mock 不支持动态能力:${method}(${args.length})`, "CAPABILITY_DISABLED"); },
86
- },
87
- async broadcast(type, data) { requireCapability("broadcast.send"); record("broadcast.send", [type, data]); emit("broadcast", { type, data }); },
88
- async connect() { if (!ready) {
89
- ready = true;
90
- emit("__ready", undefined);
91
- } },
92
- dispose() { timers.forEach(clearTimeout); timers.clear(); handlers.clear(); },
93
- };
94
- return sdk;
95
- }
@@ -1,6 +0,0 @@
1
- import type { PlatformAPI } from "../types.js";
2
- /**
3
- * 模拟平台能力——本地开发用
4
- * similarity 使用 Levenshtein 编辑距离代替 AI 模型
5
- */
6
- export declare function createMockPlatform(): PlatformAPI;
@@ -1,45 +0,0 @@
1
- /**
2
- * 模拟平台能力——本地开发用
3
- * similarity 使用 Levenshtein 编辑距离代替 AI 模型
4
- */
5
- export function createMockPlatform() {
6
- return {
7
- async similarity(text1, text2) {
8
- return levenshteinSimilarity(text1, text2);
9
- },
10
- async timer(key, durationMs) {
11
- return new Promise((resolve) => {
12
- setTimeout(() => { console.log(`[mock] timer "${key}"`); resolve(); }, durationMs);
13
- });
14
- },
15
- async tts(text, options) {
16
- console.log(`[mock][tts][${options?.priority ?? "normal"}] ${text}`);
17
- },
18
- async call(method, ...args) {
19
- console.log(`[mock] platform.call("${method}")`, args);
20
- throw new Error(`Mock 不支持动态能力: ${method}`);
21
- },
22
- };
23
- }
24
- /** Levenshtein 编辑距离相似度(0~1) */
25
- function levenshteinSimilarity(a, b) {
26
- const s1 = a.trim();
27
- const s2 = b.trim();
28
- if (s1 === s2)
29
- return 1;
30
- if (s1.length === 0 || s2.length === 0)
31
- return 0;
32
- const prev = Array.from({ length: s2.length + 1 }, (_, i) => i);
33
- const curr = new Array(s2.length + 1).fill(0);
34
- for (let i = 1; i <= s1.length; i++) {
35
- curr[0] = i;
36
- for (let j = 1; j <= s2.length; j++) {
37
- const cost = s1[i - 1] === s2[j - 1] ? 0 : 1;
38
- curr[j] = Math.min(prev[j] + 1, curr[j - 1] + 1, prev[j - 1] + cost);
39
- }
40
- for (let k = 0; k <= s2.length; k++)
41
- prev[k] = curr[k];
42
- curr.fill(0);
43
- }
44
- return 1 - prev[s2.length] / Math.max(s1.length, s2.length);
45
- }
@@ -1,6 +0,0 @@
1
- /** 自动接收 host 推送的 game_state */
2
- export declare function useGameState<T = any>(): T | null;
3
- /** 自动接收 host 推送的 config */
4
- export declare function useGameConfig<T = Record<string, unknown>>(): T | null;
5
- /** 向 host 发送游戏命令(自动走 postMessage) */
6
- export declare function sendCmd(type: string, payload?: unknown): Promise<void>;
@@ -1,30 +0,0 @@
1
- // @live-game/sdk/react — React hooks
2
- // 开发者不需要手动监听 postMessage
3
- import { useEffect, useState } from 'react';
4
- import { createSDK } from '../createSDK.js';
5
- /** 自动接收 host 推送的 game_state */
6
- export function useGameState() {
7
- const [state, setState] = useState(null);
8
- useEffect(() => {
9
- const sdk = createSDK();
10
- const handler = (value) => setState(value);
11
- sdk.on('game_state', handler);
12
- return () => sdk.off('game_state', handler);
13
- }, []);
14
- return state;
15
- }
16
- /** 自动接收 host 推送的 config */
17
- export function useGameConfig() {
18
- const [config, setConfig] = useState(null);
19
- useEffect(() => {
20
- const sdk = createSDK();
21
- const handler = (value) => setConfig(value);
22
- sdk.on('config', handler);
23
- return () => sdk.off('config', handler);
24
- }, []);
25
- return config;
26
- }
27
- /** 向 host 发送游戏命令(自动走 postMessage) */
28
- export function sendCmd(type, payload) {
29
- return createSDK().command.send(payload === undefined ? { type } : { type, payload });
30
- }