@live-game/sdk 0.1.0 → 0.2.0

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.
package/README.md CHANGED
@@ -15,3 +15,9 @@ const config = await sdk.config.get();
15
15
  await sdk.config.update({ ...config, duration: 180 });
16
16
  await sdk.command.send({ type: "next_round" });
17
17
  ```
18
+
19
+ Publish game state for control panels:
20
+
21
+ ```ts
22
+ await sdk.state.publish({ round: 2, status: "playing" });
23
+ ```
package/dist/createSDK.js CHANGED
@@ -11,7 +11,7 @@ export function createSDK() {
11
11
  return window.__LIVEGAME_SDK__;
12
12
  }
13
13
  throw new Error("LiveGame SDK 未检测到平台宿主注入。\n" +
14
- "• 开发调试: 请使用 npx @live-game/cli dev 启动本地调试\n" +
14
+ "• 开发调试: 请使用 npx @live-game/dev-cli dev 启动本地调试\n" +
15
15
  "• 生产环境: 游戏通过平台宿主加载,SDK 自动注入\n" +
16
16
  "• 单元测试: 请使用 createMockSDK()");
17
17
  }
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- export { createSDK } from './createSDK.js';
2
- export { createMockSDK } from './mock/index.js';
3
- export type { LiveGameSDK, DanmakuMessage, GiftMessage, LikeMessage, RoomInfo, TimerEvent, BroadcastEvent, EventHandler, StorageAPI, GameConfig, ConfigSchema, ConfigAPI, GameCommand, CommandAPI, SettleResult, ReportAPI, RoomAPI, PlatformAPI, } from './types.js';
4
- export { useGameState, useGameConfig, sendCmd } from './react/index.js';
5
- export type { GameEngine, GameContext, EngineManifest, EngineLiveEvent, EngineStorageAPI, EngineReportAPI, PlatformCapabilities, GameCommand as EngineGameCommand, ConfigField, } from './engine/index.js';
1
+ export { createSDK } from "./createSDK.js";
2
+ export { createMockSDK } from "./mock/index.js";
3
+ export { PlatformError } from "./types.js";
4
+ export type { LiveGameSDK, DanmakuMessage, GiftMessage, LikeMessage, RoomInfo, TimerEvent, BroadcastEvent, EventHandler, StorageAPI, GameConfig, ConfigSchema, ConfigAPI, GameCommand, CommandAPI, SettleResult, ReportAPI, RoomAPI, StateAPI, PlatformAPI, } from "./types.js";
5
+ export { useGameState, useGameConfig, sendCmd } from "./react/index.js";
package/dist/index.js CHANGED
@@ -1,4 +1,5 @@
1
- export { createSDK } from './createSDK.js';
2
- export { createMockSDK } from './mock/index.js';
1
+ export { createSDK } from "./createSDK.js";
2
+ export { createMockSDK } from "./mock/index.js";
3
+ export { PlatformError } from "./types.js";
3
4
  // React hooks(可选,非 React 项目不需要 import)
4
- export { useGameState, useGameConfig, sendCmd } from './react/index.js';
5
+ export { useGameState, useGameConfig, sendCmd } from "./react/index.js";
@@ -1,3 +1,3 @@
1
1
  import type { LiveGameSDK } from "../types.js";
2
- /** 创建完整 Mock SDK,用于本地开发 */
2
+ /** 创建完整 Mock SDK,用于单元测试和本地 UI 开发 */
3
3
  export declare function createMockSDK(): LiveGameSDK;
@@ -4,7 +4,7 @@ import { createMockConfig } from "./config.js";
4
4
  import { createMockCommand } from "./command.js";
5
5
  import { createMockReport } from "./report.js";
6
6
  import { createMockPlatform } from "./platform.js";
7
- /** 创建完整 Mock SDK,用于本地开发 */
7
+ /** 创建完整 Mock SDK,用于单元测试和本地 UI 开发 */
8
8
  export function createMockSDK() {
9
9
  const events = createMockEvents();
10
10
  const storage = createMockStorage();
@@ -12,7 +12,20 @@ export function createMockSDK() {
12
12
  const command = createMockCommand();
13
13
  const report = createMockReport();
14
14
  const platform = createMockPlatform();
15
+ // 生命周期
16
+ let readyHandler = null;
17
+ let disconnectHandler = null;
18
+ let errorHandler = null;
19
+ let connected = false;
15
20
  return {
21
+ version: "0.2.0",
22
+ supports(capability) {
23
+ const builtIn = ["similarity", "timer", "tts", "randomWords", "storage", "broadcast", "report.score", "report.settle"];
24
+ return builtIn.includes(capability);
25
+ },
26
+ onReady(handler) { readyHandler = handler; },
27
+ onDisconnect(handler) { disconnectHandler = handler; },
28
+ onError(handler) { errorHandler = handler; },
16
29
  on(event, handler) {
17
30
  events.on(event, handler);
18
31
  },
@@ -31,12 +44,21 @@ export function createMockSDK() {
31
44
  });
32
45
  },
33
46
  },
47
+ state: {
48
+ async publish(state) {
49
+ await sdkBroadcast("__game_state", state);
50
+ },
51
+ },
34
52
  async broadcast(type, data) {
35
- console.log(`[mock] broadcast: ${type}`, data);
53
+ await sdkBroadcast(type, data);
36
54
  },
37
55
  async connect() {
38
- console.log("[mock] connected to live event stream");
39
- // Mock 模式自动生成模拟事件(由 events.ts 处理)
56
+ console.log("[mock] connected");
57
+ connected = true;
58
+ readyHandler?.();
40
59
  },
41
60
  };
61
+ async function sdkBroadcast(type, data) {
62
+ console.log(`[mock] broadcast: ${type}`, data);
63
+ }
42
64
  }
@@ -9,23 +9,19 @@ export function createMockPlatform() {
9
9
  },
10
10
  async timer(key, durationMs) {
11
11
  return new Promise((resolve) => {
12
- setTimeout(() => {
13
- console.log(`[mock platform] timer "${key}" fired after ${durationMs}ms`);
14
- resolve();
15
- }, durationMs);
12
+ setTimeout(() => { console.log(`[mock] timer "${key}"`); resolve(); }, durationMs);
16
13
  });
17
14
  },
18
15
  async tts(text, options) {
19
- const level = options?.priority ?? "normal";
20
- console.log(`[mock platform][tts][${level}] ${text}`);
16
+ console.log(`[mock][tts][${options?.priority ?? "normal"}] ${text}`);
21
17
  },
22
18
  async randomWords(answer, words, count) {
23
- const sameLength = words.filter((w) => w.length === answer.length);
24
- const selected = [...sameLength].sort(() => Math.random() - 0.5).slice(0, count);
25
- return selected.map((word) => ({
26
- word,
27
- similarity: levenshteinSimilarity(word, answer),
28
- }));
19
+ const selected = words.filter(w => w.length === answer.length).sort(() => Math.random() - 0.5).slice(0, count);
20
+ return selected.map(w => ({ word: w, similarity: levenshteinSimilarity(w, answer) }));
21
+ },
22
+ async call(method, ...args) {
23
+ console.log(`[mock] platform.call("${method}")`, args);
24
+ throw new Error(`Mock 不支持动态能力: ${method}`);
29
25
  },
30
26
  };
31
27
  }
package/dist/types.d.ts CHANGED
@@ -67,6 +67,10 @@ export interface ReportAPI {
67
67
  export interface RoomAPI {
68
68
  getInfo(): Promise<RoomInfo>;
69
69
  }
70
+ export interface StateAPI {
71
+ /** 发布当前游戏状态,供控制端 useGameState() 读取 */
72
+ publish(state: unknown): Promise<void>;
73
+ }
70
74
  /** 定时器事件 */
71
75
  export interface TimerEvent {
72
76
  key: string;
@@ -90,13 +94,36 @@ export interface PlatformAPI {
90
94
  word: string;
91
95
  similarity: number;
92
96
  }[]>;
97
+ /** 动态能力调用(平台新增能力时,老 SDK 无需升级) */
98
+ call(method: string, ...args: unknown[]): Promise<unknown>;
99
+ }
100
+ /** 平台连接就绪时触发(connect 成功后) */
101
+ export type ReadyHandler = () => void;
102
+ /** 与平台断开连接时触发 */
103
+ export type DisconnectHandler = (reason?: string) => void;
104
+ /** 平台错误 */
105
+ export type ErrorHandler = (error: PlatformError) => void;
106
+ export declare class PlatformError extends Error {
107
+ code: "TIMEOUT" | "RATE_LIMIT" | "AUTH_EXPIRED" | "CAPABILITY_DISABLED" | "NETWORK_ERROR" | "UNKNOWN";
108
+ statusCode?: number;
109
+ constructor(message: string, code: PlatformError["code"], statusCode?: number);
93
110
  }
94
111
  export interface LiveGameSDK {
112
+ /** SDK 版本号 */
113
+ readonly version: string;
114
+ /** 检测平台是否支持指定能力 */
115
+ supports(capability: string): boolean;
116
+ /** SDK 就绪回调 */
117
+ onReady(handler: ReadyHandler): void;
118
+ /** 断开连接回调 */
119
+ onDisconnect(handler: DisconnectHandler): void;
120
+ /** 错误回调 */
121
+ onError(handler: ErrorHandler): void;
95
122
  on(event: 'danmaku' | 'comment', handler: EventHandler<DanmakuMessage>): void;
96
123
  on(event: 'gift', handler: EventHandler<GiftMessage>): void;
97
124
  on(event: 'like', handler: EventHandler<LikeMessage>): void;
98
125
  on(event: 'roomInfo' | 'room_stats', handler: EventHandler<RoomInfo>): void;
99
- on(event: 'enter' | 'follow' | 'share' | 'fansclub' | 'live_event' | 'theme_change' | 'game_state' | 'config', handler: EventHandler<unknown>): void;
126
+ on(event: 'enter' | 'follow' | 'share' | 'fansclub' | 'live_event' | 'theme_change' | 'game_state' | 'config' | 'command', handler: EventHandler<unknown>): void;
100
127
  on(event: 'timer', handler: EventHandler<TimerEvent>): void;
101
128
  on(event: 'broadcast', handler: EventHandler<BroadcastEvent>): void;
102
129
  off(event: string, handler: EventHandler<any>): void;
@@ -105,9 +132,10 @@ export interface LiveGameSDK {
105
132
  command: CommandAPI;
106
133
  report: ReportAPI;
107
134
  room: RoomAPI;
135
+ state: StateAPI;
108
136
  platform: PlatformAPI;
109
137
  /** 广播自定义事件给所有客户端 */
110
138
  broadcast(type: string, data?: unknown): Promise<void>;
111
- /** 连接直播事件流(仅 production 模式,Mock 模式自动模拟事件) */
139
+ /** 连接直播事件流 */
112
140
  connect(): Promise<void>;
113
141
  }
package/dist/types.js CHANGED
@@ -1,3 +1,11 @@
1
1
  // ===== 事件类型 =====
2
- export {};
2
+ // ===== 标准错误 =====
3
+ export class PlatformError extends Error {
4
+ constructor(message, code, statusCode) {
5
+ super(message);
6
+ this.name = "PlatformError";
7
+ this.code = code;
8
+ this.statusCode = statusCode;
9
+ }
10
+ }
3
11
  // CreateSDKOptions 已移除 —— createSDK() 不再接受参数,Mock 使用 createMockSDK()
@@ -1,10 +1,6 @@
1
1
  /**
2
- * 引擎工具函数
3
- * 开发者在 engine.ts 中导入这些函数,Vite 构建时会打包进 engine.js
4
- * 导入路径: import { obfuscate, ... } from '@live-game/sdk/engine/utils'
5
- *
6
- * 注意:这些函数同时存在于 @live-game/live-core/game-utils(供 api-server 使用)
7
- * 两边保持同步,但 SDK 侧不依赖 live-core(避免循环依赖和额外依赖)
2
+ * 游戏工具函数
3
+ * 导入路径: import { obfuscate, ... } from '@live-game/sdk/utils'
8
4
  */
9
5
  export declare function obfuscate(word: string): string;
10
6
  export declare function deobfuscate(obfuscated: string): string;
@@ -1,10 +1,6 @@
1
1
  /**
2
- * 引擎工具函数
3
- * 开发者在 engine.ts 中导入这些函数,Vite 构建时会打包进 engine.js
4
- * 导入路径: import { obfuscate, ... } from '@live-game/sdk/engine/utils'
5
- *
6
- * 注意:这些函数同时存在于 @live-game/live-core/game-utils(供 api-server 使用)
7
- * 两边保持同步,但 SDK 侧不依赖 live-core(避免循环依赖和额外依赖)
2
+ * 游戏工具函数
3
+ * 导入路径: import { obfuscate, ... } from '@live-game/sdk/utils'
8
4
  */
9
5
  // ===== 答案混淆(XOR + Base64) =====
10
6
  export function obfuscate(word) {
package/package.json CHANGED
@@ -1,57 +1,50 @@
1
- {
2
- "name": "@live-game/sdk",
3
- "version": "0.1.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"
16
- },
17
- "./engine": {
18
- "types": "./dist/engine/index.d.ts",
19
- "import": "./dist/engine/index.js"
20
- },
21
- "./engine/mock": {
22
- "types": "./dist/engine/mock.d.ts",
23
- "import": "./dist/engine/mock.js"
24
- },
25
- "./engine/utils": {
26
- "types": "./dist/engine/utils.d.ts",
27
- "import": "./dist/engine/utils.js"
28
- }
29
- },
30
- "files": [
31
- "dist",
32
- "README.md"
33
- ],
34
- "publishConfig": {
35
- "access": "public"
36
- },
37
- "scripts": {
38
- "build": "node scripts/clean-dist.mjs && tsc -p tsconfig.json",
39
- "check": "tsc --noEmit",
40
- "prepack": "npm run build",
41
- "build:template-zip": "tsx scripts/build-template-zip.ts"
42
- },
43
- "peerDependencies": {
44
- "react": "^19.0.0"
45
- },
46
- "peerDependenciesMeta": {
47
- "react": {
48
- "optional": true
49
- }
50
- },
51
- "devDependencies": {
52
- "@types/react": "^18.0.0",
53
- "typescript": "^5.0.0",
54
- "tsx": "^4.0.0",
55
- "vite": "^5.0.0"
56
- }
57
- }
1
+ {
2
+ "name": "@live-game/sdk",
3
+ "version": "0.2.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"
16
+ },
17
+ "./utils": {
18
+ "types": "./dist/utils.d.ts",
19
+ "import": "./dist/utils.js"
20
+ }
21
+ },
22
+ "files": [
23
+ "dist",
24
+ "README.md"
25
+ ],
26
+ "publishConfig": {
27
+ "access": "public"
28
+ },
29
+ "scripts": {
30
+ "build": "node scripts/clean-dist.mjs && tsc -p tsconfig.json",
31
+ "check": "tsc --noEmit",
32
+ "prepack": "npm run build",
33
+ "build:template-zip": "tsx scripts/build-template-zip.ts"
34
+ },
35
+ "peerDependencies": {
36
+ "react": "^19.0.0"
37
+ },
38
+ "peerDependenciesMeta": {
39
+ "react": {
40
+ "optional": true
41
+ }
42
+ },
43
+ "devDependencies": {
44
+ "@types/react": "^18.0.0",
45
+ "adm-zip": "^0.5.18",
46
+ "typescript": "^5.0.0",
47
+ "tsx": "^4.0.0",
48
+ "vite": "^5.0.0"
49
+ }
50
+ }
@@ -1 +0,0 @@
1
- export type { GameEngine, GameContext, EngineManifest, EngineLiveEvent, EngineStorageAPI, EngineReportAPI, PlatformCapabilities, GameCommand, ConfigField, } from "./types.js";
@@ -1,3 +0,0 @@
1
- // @live-game/sdk/engine —— 游戏引擎类型导出
2
- // 开发者使用: import type { GameEngine, GameContext } from '@live-game/sdk/engine'
3
- export {};
@@ -1,55 +0,0 @@
1
- /**
2
- * engine/mock.ts —— 本地开发用 Mock 引擎上下文
3
- *
4
- * 开发者在本地测试 engine.ts 时,不需要连接平台即可调用所有平台能力。
5
- *
6
- * 用法:
7
- * import { createMockEngineContext } from "@live-game/sdk/engine/mock";
8
- * import { engine } from "./src/engine";
9
- *
10
- * const ctx = createMockEngineContext({
11
- * config: { duration: 60 },
12
- * initialState: engine.createInitialState({ duration: 60 }),
13
- * });
14
- *
15
- * engine.onStart?.(ctx);
16
- * engine.onEvent?.({ type: "comment", text: "苹果" }, ctx);
17
- * console.log(ctx.state);
18
- */
19
- import type { GameContext, EngineLiveEvent } from "./types.js";
20
- interface MockEngineOptions {
21
- /** 初始游戏配置 */
22
- config?: Record<string, unknown>;
23
- /** 初始游戏状态(通常由 createInitialState 生成) */
24
- initialState?: Record<string, unknown>;
25
- /** 持久化存储后端(默认:内存 Map) */
26
- storageBackend?: Map<string, string>;
27
- /** 语义相似度实现(默认:简单的字符串相等判断) */
28
- similarityImpl?: (text1: string, text2: string) => number;
29
- /** 事件回调(方便在测试中断言 broadcast 内容) */
30
- onBroadcast?: (message: unknown) => void;
31
- /** 积分上报回调 */
32
- onScoreReport?: (playerId: string, score: number) => void;
33
- }
34
- /**
35
- * 创建一个用于本地开发的 Mock 引擎上下文。
36
- *
37
- * 所有平台能力都有本地实现:
38
- * - storage → 内存 Map(可注入)
39
- * - similarity → Levenshtein 编辑距离(可注入)
40
- * - tts → console.log
41
- * - broadcast → console.table / onBroadcast 回调
42
- * - setTimer → 真实的 setTimeout
43
- */
44
- export declare function createMockEngineContext<TState extends Record<string, unknown> = Record<string, unknown>>(options?: MockEngineOptions): GameContext<TState>;
45
- /**
46
- * 创建模拟的直播事件,方便在测试中注入到 engine.onEvent
47
- */
48
- export declare function createMockEvent(overrides?: Partial<EngineLiveEvent>): EngineLiveEvent;
49
- /** 创建模拟弹幕事件 */
50
- export declare function mockComment(text: string, overrides?: Partial<EngineLiveEvent>): EngineLiveEvent;
51
- /** 创建模拟礼物事件 */
52
- export declare function mockGift(giftName: string, count?: number, overrides?: Partial<EngineLiveEvent>): EngineLiveEvent;
53
- /** 创建模拟点赞事件 */
54
- export declare function mockLike(count?: number, overrides?: Partial<EngineLiveEvent>): EngineLiveEvent;
55
- export {};
@@ -1,161 +0,0 @@
1
- /**
2
- * 计算两个字符串的编辑距离相似度(Levenshtein)
3
- * 返回值 0~1,1 表示完全相同
4
- */
5
- function defaultSimilarity(text1, text2) {
6
- const a = text1.trim();
7
- const b = text2.trim();
8
- if (a === b)
9
- return 1;
10
- if (a.length === 0 || b.length === 0)
11
- return 0;
12
- const lenA = a.length;
13
- const lenB = b.length;
14
- // 用一维数组优化空间
15
- const prev = Array.from({ length: lenB + 1 }, (_, i) => i);
16
- const curr = new Array(lenB + 1).fill(0);
17
- for (let i = 1; i <= lenA; i++) {
18
- curr[0] = i;
19
- for (let j = 1; j <= lenB; j++) {
20
- const cost = a[i - 1] === b[j - 1] ? 0 : 1;
21
- curr[j] = Math.min(prev[j] + 1, // 删除
22
- curr[j - 1] + 1, // 插入
23
- prev[j - 1] + cost // 替换
24
- );
25
- }
26
- // 交换数组
27
- const tmp = prev;
28
- for (let k = 0; k <= lenB; k++) {
29
- tmp[k] = curr[k];
30
- }
31
- curr.fill(0);
32
- }
33
- const maxLen = Math.max(lenA, lenB);
34
- return 1 - prev[lenB] / maxLen;
35
- }
36
- // ===== Mock 实现 =====
37
- /**
38
- * 创建一个用于本地开发的 Mock 引擎上下文。
39
- *
40
- * 所有平台能力都有本地实现:
41
- * - storage → 内存 Map(可注入)
42
- * - similarity → Levenshtein 编辑距离(可注入)
43
- * - tts → console.log
44
- * - broadcast → console.table / onBroadcast 回调
45
- * - setTimer → 真实的 setTimeout
46
- */
47
- export function createMockEngineContext(options = {}) {
48
- const storageBackend = options.storageBackend ?? new Map();
49
- const similarityImpl = options.similarityImpl ?? defaultSimilarity;
50
- const state = (options.initialState ?? {});
51
- const config = options.config ?? {};
52
- const timers = new Map();
53
- const ctx = {
54
- roomId: "mock-room",
55
- gameId: "mock-game",
56
- get config() {
57
- return config;
58
- },
59
- get state() {
60
- return state;
61
- },
62
- set state(v) {
63
- Object.assign(state, v);
64
- },
65
- // 广播
66
- broadcast(message) {
67
- if (options.onBroadcast) {
68
- options.onBroadcast(message);
69
- }
70
- else {
71
- console.log("[engine broadcast]", JSON.stringify(message, null, 2));
72
- }
73
- },
74
- // 定时器
75
- setTimer(key, delayMs, callback) {
76
- if (timers.has(key)) {
77
- clearTimeout(timers.get(key));
78
- }
79
- timers.set(key, setTimeout(() => {
80
- timers.delete(key);
81
- callback();
82
- }, delayMs));
83
- },
84
- clearTimer(key) {
85
- const timer = timers.get(key);
86
- if (timer) {
87
- clearTimeout(timer);
88
- timers.delete(key);
89
- }
90
- },
91
- clearAllTimers() {
92
- for (const [, timer] of timers) {
93
- clearTimeout(timer);
94
- }
95
- timers.clear();
96
- },
97
- // 持久化存储
98
- storage: {
99
- async get(key) {
100
- return storageBackend.get(key) ?? null;
101
- },
102
- async set(key, value) {
103
- storageBackend.set(key, value);
104
- },
105
- async delete(key) {
106
- storageBackend.delete(key);
107
- },
108
- },
109
- // 积分上报
110
- report: {
111
- async score(playerId, score) {
112
- if (options.onScoreReport) {
113
- options.onScoreReport(playerId, score);
114
- }
115
- else {
116
- console.log(`[engine report] score: playerId=${playerId} score=${score}`);
117
- }
118
- },
119
- async settle(results) {
120
- console.table(results);
121
- },
122
- },
123
- // 平台能力
124
- platform: {
125
- async similarity(text1, text2) {
126
- return similarityImpl(text1, text2);
127
- },
128
- async tts(text, ttsOptions) {
129
- const priority = ttsOptions?.priority ?? "normal";
130
- console.log(`[engine tts][${priority}] ${text}`);
131
- },
132
- },
133
- };
134
- return ctx;
135
- }
136
- // ===== 模拟事件生成器 =====
137
- /**
138
- * 创建模拟的直播事件,方便在测试中注入到 engine.onEvent
139
- */
140
- export function createMockEvent(overrides = {}) {
141
- return {
142
- type: "comment",
143
- roomId: "mock-room",
144
- userId: `user-${Math.random().toString(36).slice(2, 8)}`,
145
- nickname: "测试用户",
146
- ts: Date.now(),
147
- ...overrides,
148
- };
149
- }
150
- /** 创建模拟弹幕事件 */
151
- export function mockComment(text, overrides = {}) {
152
- return createMockEvent({ type: "comment", text, similarity: 0, ...overrides });
153
- }
154
- /** 创建模拟礼物事件 */
155
- export function mockGift(giftName, count = 1, overrides = {}) {
156
- return createMockEvent({ type: "gift", giftName, count, ...overrides });
157
- }
158
- /** 创建模拟点赞事件 */
159
- export function mockLike(count = 1, overrides = {}) {
160
- return createMockEvent({ type: "like", count, ...overrides });
161
- }
@@ -1,120 +0,0 @@
1
- /** 直播事件基类 */
2
- export interface EngineLiveEvent {
3
- type: string;
4
- roomId: string;
5
- userId: string;
6
- nickname: string;
7
- avatar?: string;
8
- ts: number;
9
- text?: string;
10
- giftId?: string;
11
- giftName?: string;
12
- count?: number;
13
- similarity?: number;
14
- [key: string]: unknown;
15
- }
16
- /** 配置字段定义(与 GameManifest.configSchema 一致) */
17
- export interface ConfigField {
18
- type: "string" | "number" | "boolean" | "wordBank" | "hintRules" | "giftSelect";
19
- label?: string;
20
- description?: string;
21
- default?: unknown;
22
- enum?: string[];
23
- fixedCount?: number;
24
- }
25
- /** 引擎清单 —— 声明游戏的基本信息与配置 schema */
26
- export interface EngineManifest {
27
- /** 游戏唯一标识(小写字母+数字+连字符) */
28
- id: string;
29
- /** 游戏显示名称 */
30
- name: string;
31
- /** 语义化版本号 */
32
- version: string;
33
- /** 配置字段定义(用于 GameConfigForm 动态渲染) */
34
- configSchema?: Record<string, ConfigField>;
35
- }
36
- /** 控制端发送的游戏指令 */
37
- export interface GameCommand {
38
- type: string;
39
- actorId?: string;
40
- actorName?: string;
41
- payload?: Record<string, unknown>;
42
- }
43
- /** 持久化存储 API —— 按 gameId + roomId 隔离 */
44
- export interface EngineStorageAPI {
45
- get(key: string): Promise<string | null>;
46
- set(key: string, value: string): Promise<void>;
47
- delete(key: string): Promise<void>;
48
- }
49
- /** 积分上报 API */
50
- export interface EngineReportAPI {
51
- /** 上报单个玩家积分 */
52
- score(playerId: string, score: number): Promise<void>;
53
- /** 上报本局结算结果 */
54
- settle(results: {
55
- playerId: string;
56
- score: number;
57
- rank?: number;
58
- }[]): Promise<void>;
59
- }
60
- /** 平台能力 —— 引擎可调用的平台服务 */
61
- export interface PlatformCapabilities {
62
- /** 语义相似度计算(两个文本的相似度,0~1) */
63
- similarity(text1: string, text2: string): Promise<number>;
64
- /** TTS 语音播报(向观众端推送语音消息) */
65
- tts(text: string, options?: {
66
- priority?: "high" | "normal";
67
- }): Promise<void>;
68
- }
69
- /** 引擎运行时上下文 —— 引擎通过 ctx 与平台交互 */
70
- export interface GameContext<TState = unknown> {
71
- /** 直播间 ID */
72
- roomId: string;
73
- /** 游戏 ID */
74
- gameId: string;
75
- /** 当前游戏配置(主播自定义后的值) */
76
- config: Record<string, unknown>;
77
- /** 游戏状态 —— 引擎读写此字段 */
78
- state: TState;
79
- /** 向所有观众和控制端广播消息 */
80
- broadcast(message: unknown): void;
81
- /** 注册一个命名定时器(同 key 会自动取消上一个) */
82
- setTimer(key: string, delayMs: number, callback: () => void): void;
83
- /** 取消指定定时器 */
84
- clearTimer(key: string): void;
85
- /** 取消所有定时器(onFinish 时自动调用) */
86
- clearAllTimers(): void;
87
- /** 持久化 KV 存储(按 gameId 隔离,跨场次持久化) */
88
- storage: EngineStorageAPI;
89
- /** 积分上报与结算 */
90
- report: EngineReportAPI;
91
- /** 平台能力(similarity / tts 等) */
92
- platform: PlatformCapabilities;
93
- }
94
- /**
95
- * 游戏引擎接口 —— 开发者在 engine.ts 中 export const engine: GameEngine<TState>
96
- *
97
- * 生命周期:
98
- * createInitialState → onStart → [onEvent / onCommand / onTick / onConfigUpdate] → onFinish
99
- * 恢复场次时:onResume 替代 onStart
100
- */
101
- export interface GameEngine<TState = unknown> {
102
- /** 引擎清单 */
103
- manifest: EngineManifest;
104
- /** 根据初始配置创建初始状态(每次新场次调用一次) */
105
- createInitialState(config: Record<string, unknown>): TState;
106
- /** 场次启动(新场次) */
107
- onStart?(ctx: GameContext<TState>): void;
108
- /** 场次恢复(从快照恢复,如 api-server 重启后) */
109
- onResume?(ctx: GameContext<TState>): void;
110
- /** 直播事件到达 */
111
- onEvent?(event: EngineLiveEvent, ctx: GameContext<TState>): void;
112
- /** 控制端发送指令 */
113
- onCommand?(command: GameCommand, ctx: GameContext<TState>): void;
114
- /** 每秒时钟滴答(用于倒计时等需要精确计时的逻辑) */
115
- onTick?(ctx: GameContext<TState>): void;
116
- /** 配置更新(主播在控制台修改了游戏参数) */
117
- onConfigUpdate?(ctx: GameContext<TState>): void;
118
- /** 场次结束,返回结算数据 */
119
- onFinish?(ctx: GameContext<TState>): Record<string, unknown>;
120
- }
@@ -1,4 +0,0 @@
1
- // ===== 游戏引擎接口类型定义 =====
2
- // 开发者编写 engine.ts 时引用这些类型
3
- // 编译后的 engine.js 在 api-server Worker Thread 沙箱中执行
4
- export {};