@live-game/sdk 0.1.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 ADDED
@@ -0,0 +1,17 @@
1
+ # @live-game/sdk
2
+
3
+ SDK for Live Game iframe apps and control panels.
4
+
5
+ ```ts
6
+ import { createSDK } from "@live-game/sdk";
7
+ import { useGameState, useGameConfig, sendCmd } from "@live-game/sdk/react";
8
+ ```
9
+
10
+ Common control-panel flow:
11
+
12
+ ```ts
13
+ const sdk = createSDK();
14
+ const config = await sdk.config.get();
15
+ await sdk.config.update({ ...config, duration: 180 });
16
+ await sdk.command.send({ type: "next_round" });
17
+ ```
@@ -0,0 +1,9 @@
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;
@@ -0,0 +1,17 @@
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/cli dev 启动本地调试\n" +
15
+ "• 生产环境: 游戏通过平台宿主加载,SDK 自动注入\n" +
16
+ "• 单元测试: 请使用 createMockSDK()");
17
+ }
@@ -0,0 +1 @@
1
+ export type { GameEngine, GameContext, EngineManifest, EngineLiveEvent, EngineStorageAPI, EngineReportAPI, PlatformCapabilities, GameCommand, ConfigField, } from "./types.js";
@@ -0,0 +1,3 @@
1
+ // @live-game/sdk/engine —— 游戏引擎类型导出
2
+ // 开发者使用: import type { GameEngine, GameContext } from '@live-game/sdk/engine'
3
+ export {};
@@ -0,0 +1,55 @@
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 {};
@@ -0,0 +1,161 @@
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
+ }
@@ -0,0 +1,120 @@
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
+ }
@@ -0,0 +1,4 @@
1
+ // ===== 游戏引擎接口类型定义 =====
2
+ // 开发者编写 engine.ts 时引用这些类型
3
+ // 编译后的 engine.js 在 api-server Worker Thread 沙箱中执行
4
+ export {};
@@ -0,0 +1,28 @@
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(避免循环依赖和额外依赖)
8
+ */
9
+ export declare function obfuscate(word: string): string;
10
+ export declare function deobfuscate(obfuscated: string): string;
11
+ export interface WordItem {
12
+ category: string;
13
+ partOfSpeech: string;
14
+ answer: string;
15
+ hints: string[];
16
+ }
17
+ export declare function parseWordsConfig(configWords: unknown): WordItem[];
18
+ export declare function generateSameLengthAnswers(words: WordItem[], currentAnswer: string, count?: number): string[];
19
+ export declare function matchesGiftName(event: {
20
+ giftId?: unknown;
21
+ giftName?: unknown;
22
+ }, expectedName: unknown): boolean;
23
+ export declare function getRankLabel(score: number): string;
24
+ export declare function readDuration(config: Record<string, unknown>, defaultDuration?: number): number;
25
+ export declare function readHintRules(config: Record<string, unknown>): {
26
+ likeRequired: number;
27
+ afterSeconds: number;
28
+ }[];
@@ -0,0 +1,153 @@
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(避免循环依赖和额外依赖)
8
+ */
9
+ // ===== 答案混淆(XOR + Base64) =====
10
+ export function obfuscate(word) {
11
+ const xor = word
12
+ .split("")
13
+ .map((c) => String.fromCharCode(c.charCodeAt(0) ^ 42))
14
+ .join("");
15
+ // Node.js Worker 中 Buffer 可用,浏览器 fallback 到 btoa
16
+ if (typeof Buffer !== "undefined") {
17
+ return Buffer.from(xor, "utf-8").toString("base64");
18
+ }
19
+ return btoa(xor);
20
+ }
21
+ export function deobfuscate(obfuscated) {
22
+ try {
23
+ let xor;
24
+ if (typeof Buffer !== "undefined") {
25
+ xor = Buffer.from(obfuscated, "base64").toString("utf-8");
26
+ }
27
+ else {
28
+ xor = atob(obfuscated);
29
+ }
30
+ return xor
31
+ .split("")
32
+ .map((c) => String.fromCharCode(c.charCodeAt(0) ^ 42))
33
+ .join("");
34
+ }
35
+ catch {
36
+ return "";
37
+ }
38
+ }
39
+ export function parseWordsConfig(configWords) {
40
+ if (Array.isArray(configWords)) {
41
+ return configWords
42
+ .map((item) => {
43
+ const row = item;
44
+ return {
45
+ category: String(row.category ?? "").trim(),
46
+ partOfSpeech: String(row.partOfSpeech ?? "名词").trim() || "名词",
47
+ answer: String(row.answer ?? row.word ?? "").trim(),
48
+ hints: Array.isArray(row.hints)
49
+ ? row.hints.map((hint) => String(hint).trim()).filter(Boolean)
50
+ : [],
51
+ };
52
+ })
53
+ .filter((item) => item.category && item.answer);
54
+ }
55
+ if (typeof configWords !== "string")
56
+ return [];
57
+ return configWords
58
+ .split(",")
59
+ .map((part) => part.split(":").map((item) => item.trim()))
60
+ .filter((parts) => parts[0] && parts[1])
61
+ .map(([category, answer, ...hints]) => ({
62
+ category,
63
+ partOfSpeech: "名词",
64
+ answer,
65
+ hints: hints.filter(Boolean),
66
+ }));
67
+ }
68
+ export function generateSameLengthAnswers(words, currentAnswer, count = 100) {
69
+ const candidates = words
70
+ .map((word) => word.answer)
71
+ .filter((answer) => answer.length === currentAnswer.length);
72
+ if (!candidates.length)
73
+ return [];
74
+ const answers = [];
75
+ while (answers.length < count) {
76
+ answers.push(...[...candidates].sort(() => Math.random() - 0.5));
77
+ }
78
+ return answers.slice(0, count);
79
+ }
80
+ // ===== 礼物匹配 =====
81
+ export function matchesGiftName(event, expectedName) {
82
+ const expected = normalizeGiftName(expectedName);
83
+ const actual = normalizeGiftName(event.giftName);
84
+ if (actual && actual === expected)
85
+ return true;
86
+ return expected === "小心心" && String(event.giftId ?? "").trim() === "1";
87
+ }
88
+ function normalizeGiftName(value) {
89
+ return String(value ?? "").trim().replace(/\s+/g, "");
90
+ }
91
+ // ===== 段位 =====
92
+ export function getRankLabel(score) {
93
+ if (score < 10)
94
+ return "青铜 5";
95
+ if (score < 20)
96
+ return "青铜 3";
97
+ if (score < 30)
98
+ return "青铜 1";
99
+ if (score < 50)
100
+ return "白银 5";
101
+ if (score < 80)
102
+ return "白银 3";
103
+ if (score < 120)
104
+ return "白银 1";
105
+ if (score < 200)
106
+ return "黄金 5";
107
+ if (score < 300)
108
+ return "黄金 3";
109
+ if (score < 500)
110
+ return "黄金 1";
111
+ if (score < 1000)
112
+ return "钻石 5";
113
+ if (score < 2000)
114
+ return "钻石 1";
115
+ return "王者 5";
116
+ }
117
+ // ===== 配置读取 =====
118
+ export function readDuration(config, defaultDuration = 240) {
119
+ const seconds = Number(config.duration ?? defaultDuration);
120
+ return Number.isFinite(seconds) && seconds > 0
121
+ ? Math.floor(seconds)
122
+ : defaultDuration;
123
+ }
124
+ export function readHintRules(config) {
125
+ const defaultRules = [
126
+ { likeRequired: 50, afterSeconds: 0 },
127
+ { likeRequired: 150, afterSeconds: 40 },
128
+ { likeRequired: 300, afterSeconds: 100 },
129
+ ];
130
+ try {
131
+ if (config && Array.isArray(config.hintRules)) {
132
+ const rules = config.hintRules
133
+ .map((rule) => {
134
+ if (!rule || typeof rule !== "object")
135
+ return null;
136
+ const likeRequired = Math.max(0, Math.floor(Number(rule.likeRequired ?? 0)));
137
+ const afterSeconds = Math.max(0, Math.floor(Number(rule.afterSeconds ?? 0)));
138
+ return Number.isNaN(likeRequired) || Number.isNaN(afterSeconds)
139
+ ? null
140
+ : { likeRequired, afterSeconds };
141
+ })
142
+ .filter((rule) => !!rule && rule.likeRequired > 0)
143
+ .slice(0, 3);
144
+ if (rules.length) {
145
+ return Array.from({ length: 3 }, (_, i) => rules[i] ?? defaultRules[i]);
146
+ }
147
+ }
148
+ }
149
+ catch {
150
+ // ignore
151
+ }
152
+ return defaultRules;
153
+ }
@@ -0,0 +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';
package/dist/index.js ADDED
@@ -0,0 +1,4 @@
1
+ export { createSDK } from './createSDK.js';
2
+ export { createMockSDK } from './mock/index.js';
3
+ // React hooks(可选,非 React 项目不需要 import)
4
+ export { useGameState, useGameConfig, sendCmd } from './react/index.js';
@@ -0,0 +1,2 @@
1
+ import type { CommandAPI } from '../types.js';
2
+ export declare function createMockCommand(): CommandAPI;
@@ -0,0 +1,8 @@
1
+ export function createMockCommand() {
2
+ return {
3
+ async send(cmd) {
4
+ // eslint-disable-next-line no-console
5
+ console.log('[SDK Mock] 发指令:', cmd.type, cmd.payload ?? '');
6
+ },
7
+ };
8
+ }
@@ -0,0 +1,3 @@
1
+ import type { ConfigAPI, GameConfig } from '../types.js';
2
+ export declare function setMockConfig(config: GameConfig): void;
3
+ export declare function createMockConfig(): ConfigAPI;
@@ -0,0 +1,17 @@
1
+ let mockConfig = {};
2
+ export function setMockConfig(config) {
3
+ mockConfig = config;
4
+ }
5
+ export function createMockConfig() {
6
+ return {
7
+ async get() {
8
+ return { ...mockConfig };
9
+ },
10
+ async getDefault() {
11
+ return { ...mockConfig };
12
+ },
13
+ async update(config) {
14
+ mockConfig = { ...config };
15
+ },
16
+ };
17
+ }
@@ -0,0 +1,6 @@
1
+ import type { EventHandler } from '../types.js';
2
+ export declare function createMockEvents(): {
3
+ on: (event: string, handler: EventHandler<any>) => void;
4
+ off: (event: string, handler: EventHandler<any>) => void;
5
+ cleanup: () => void;
6
+ };
@@ -0,0 +1,79 @@
1
+ // 假弹幕池
2
+ const danmakuPool = [
3
+ '加油!', '太强了!', '哈哈哈哈', '666', '???',
4
+ '来了来了', '主播好厉害', '这游戏好玩', '冲啊', '牛批'
5
+ ];
6
+ let danmakuId = 1;
7
+ let giftId = 1;
8
+ export function createMockEvents() {
9
+ const handlers = new Map();
10
+ const timers = [];
11
+ // 每 3s 发一条假弹幕
12
+ timers.push(setInterval(() => {
13
+ const triggered = handlers.get('danmaku');
14
+ if (!triggered || triggered.size === 0)
15
+ return;
16
+ const msg = {
17
+ id: `mock_dm_${danmakuId++}`,
18
+ userId: `mock_user_${Math.floor(Math.random() * 100)}`,
19
+ nickname: `观众${Math.floor(Math.random() * 100)}`,
20
+ content: danmakuPool[Math.floor(Math.random() * danmakuPool.length)],
21
+ timestamp: Date.now(),
22
+ };
23
+ triggered.forEach(h => h(msg));
24
+ }, 3000));
25
+ // 每 8s 发一条假送礼
26
+ timers.push(setInterval(() => {
27
+ const triggered = handlers.get('gift');
28
+ if (!triggered || triggered.size === 0)
29
+ return;
30
+ const msg = {
31
+ id: `mock_gift_${giftId++}`,
32
+ userId: `mock_user_${Math.floor(Math.random() * 100)}`,
33
+ nickname: `粉丝${Math.floor(Math.random() * 100)}`,
34
+ giftId: 'mock_gift_001',
35
+ giftName: '小心心',
36
+ count: 1,
37
+ diamondValue: 1,
38
+ timestamp: Date.now(),
39
+ };
40
+ triggered.forEach(h => h(msg));
41
+ }, 8000));
42
+ // 每 15s 发一次假点赞
43
+ timers.push(setInterval(() => {
44
+ const triggered = handlers.get('like');
45
+ if (!triggered || triggered.size === 0)
46
+ return;
47
+ const msg = {
48
+ userId: `mock_user_${Math.floor(Math.random() * 100)}`,
49
+ nickname: `观众${Math.floor(Math.random() * 100)}`,
50
+ count: Math.floor(Math.random() * 10) + 1,
51
+ timestamp: Date.now(),
52
+ };
53
+ triggered.forEach(h => h(msg));
54
+ }, 15000));
55
+ return {
56
+ on(event, handler) {
57
+ if (!handlers.has(event))
58
+ handlers.set(event, new Set());
59
+ handlers.get(event).add(handler);
60
+ // roomInfo 首次注册时立即回调假数据
61
+ if (event === 'roomInfo') {
62
+ const info = {
63
+ roomId: 'mock_room_001',
64
+ title: '模拟直播间',
65
+ streamerNickname: '模拟主播',
66
+ onlineCount: Math.floor(Math.random() * 1000) + 100,
67
+ };
68
+ handler(info);
69
+ }
70
+ },
71
+ off(event, handler) {
72
+ handlers.get(event)?.delete(handler);
73
+ },
74
+ cleanup() {
75
+ timers.forEach(clearInterval);
76
+ handlers.clear();
77
+ },
78
+ };
79
+ }
@@ -0,0 +1,3 @@
1
+ import type { LiveGameSDK } from "../types.js";
2
+ /** 创建完整 Mock SDK,用于本地开发 */
3
+ export declare function createMockSDK(): LiveGameSDK;
@@ -0,0 +1,42 @@
1
+ import { createMockEvents } from "./events.js";
2
+ import { createMockStorage } from "./storage.js";
3
+ import { createMockConfig } from "./config.js";
4
+ import { createMockCommand } from "./command.js";
5
+ import { createMockReport } from "./report.js";
6
+ import { createMockPlatform } from "./platform.js";
7
+ /** 创建完整 Mock SDK,用于本地开发 */
8
+ export function createMockSDK() {
9
+ const events = createMockEvents();
10
+ const storage = createMockStorage();
11
+ const config = createMockConfig();
12
+ const command = createMockCommand();
13
+ const report = createMockReport();
14
+ const platform = createMockPlatform();
15
+ return {
16
+ on(event, handler) {
17
+ events.on(event, handler);
18
+ },
19
+ off(event, handler) {
20
+ events.off(event, handler);
21
+ },
22
+ storage,
23
+ config,
24
+ command,
25
+ report,
26
+ platform,
27
+ room: {
28
+ async getInfo() {
29
+ return new Promise((resolve) => {
30
+ events.on("roomInfo", (info) => resolve(info));
31
+ });
32
+ },
33
+ },
34
+ async broadcast(type, data) {
35
+ console.log(`[mock] broadcast: ${type}`, data);
36
+ },
37
+ async connect() {
38
+ console.log("[mock] connected to live event stream");
39
+ // Mock 模式自动生成模拟事件(由 events.ts 处理)
40
+ },
41
+ };
42
+ }
@@ -0,0 +1,6 @@
1
+ import type { PlatformAPI } from "../types.js";
2
+ /**
3
+ * 模拟平台能力——本地开发用
4
+ * similarity 使用 Levenshtein 编辑距离代替 AI 模型
5
+ */
6
+ export declare function createMockPlatform(): PlatformAPI;
@@ -0,0 +1,53 @@
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(() => {
13
+ console.log(`[mock platform] timer "${key}" fired after ${durationMs}ms`);
14
+ resolve();
15
+ }, durationMs);
16
+ });
17
+ },
18
+ async tts(text, options) {
19
+ const level = options?.priority ?? "normal";
20
+ console.log(`[mock platform][tts][${level}] ${text}`);
21
+ },
22
+ 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
+ }));
29
+ },
30
+ };
31
+ }
32
+ /** Levenshtein 编辑距离相似度(0~1) */
33
+ function levenshteinSimilarity(a, b) {
34
+ const s1 = a.trim();
35
+ const s2 = b.trim();
36
+ if (s1 === s2)
37
+ return 1;
38
+ if (s1.length === 0 || s2.length === 0)
39
+ return 0;
40
+ const prev = Array.from({ length: s2.length + 1 }, (_, i) => i);
41
+ const curr = new Array(s2.length + 1).fill(0);
42
+ for (let i = 1; i <= s1.length; i++) {
43
+ curr[0] = i;
44
+ for (let j = 1; j <= s2.length; j++) {
45
+ const cost = s1[i - 1] === s2[j - 1] ? 0 : 1;
46
+ curr[j] = Math.min(prev[j] + 1, curr[j - 1] + 1, prev[j - 1] + cost);
47
+ }
48
+ for (let k = 0; k <= s2.length; k++)
49
+ prev[k] = curr[k];
50
+ curr.fill(0);
51
+ }
52
+ return 1 - prev[s2.length] / Math.max(s1.length, s2.length);
53
+ }
@@ -0,0 +1,2 @@
1
+ import type { ReportAPI } from '../types.js';
2
+ export declare function createMockReport(): ReportAPI;
@@ -0,0 +1,12 @@
1
+ export function createMockReport() {
2
+ return {
3
+ async score(playerId, score) {
4
+ // eslint-disable-next-line no-console
5
+ console.log(`[SDK Mock] 上报积分: player=${playerId} score=${score}`);
6
+ },
7
+ async settle(results) {
8
+ // eslint-disable-next-line no-console
9
+ console.log('[SDK Mock] 上报结算:', results);
10
+ },
11
+ };
12
+ }
@@ -0,0 +1,2 @@
1
+ import type { StorageAPI } from '../types.js';
2
+ export declare function createMockStorage(): StorageAPI;
@@ -0,0 +1,14 @@
1
+ const PREFIX = 'lg_mock_';
2
+ export function createMockStorage() {
3
+ return {
4
+ async get(key) {
5
+ return localStorage.getItem(PREFIX + key);
6
+ },
7
+ async set(key, value) {
8
+ localStorage.setItem(PREFIX + key, value);
9
+ },
10
+ async delete(key) {
11
+ localStorage.removeItem(PREFIX + key);
12
+ },
13
+ };
14
+ }
@@ -0,0 +1,6 @@
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): void;
@@ -0,0 +1,40 @@
1
+ // @live-game/sdk/react — React hooks
2
+ // 开发者不需要手动监听 postMessage
3
+ import { useEffect, useState } from 'react';
4
+ /** 自动接收 host 推送的 game_state */
5
+ export function useGameState() {
6
+ const [state, setState] = useState(null);
7
+ useEffect(() => {
8
+ const handler = (e) => {
9
+ if (e.data?.type === 'sdk:event' && e.data?.event === 'game_state') {
10
+ setState(e.data.data);
11
+ }
12
+ };
13
+ window.addEventListener('message', handler);
14
+ return () => window.removeEventListener('message', handler);
15
+ }, []);
16
+ return state;
17
+ }
18
+ /** 自动接收 host 推送的 config */
19
+ export function useGameConfig() {
20
+ const [config, setConfig] = useState(null);
21
+ useEffect(() => {
22
+ const handler = (e) => {
23
+ if (e.data?.type === 'sdk:event' && e.data?.event === 'config') {
24
+ setConfig(e.data.data);
25
+ }
26
+ };
27
+ window.addEventListener('message', handler);
28
+ return () => window.removeEventListener('message', handler);
29
+ }, []);
30
+ return config;
31
+ }
32
+ /** 向 host 发送游戏命令(自动走 postMessage) */
33
+ export function sendCmd(type, payload) {
34
+ window.parent.postMessage({
35
+ type: 'sdk:call',
36
+ method: 'command.send',
37
+ id: Math.random().toString(36).slice(2),
38
+ args: payload ? [{ type, payload }] : [{ type }]
39
+ }, '*');
40
+ }
@@ -0,0 +1,113 @@
1
+ export interface DanmakuMessage {
2
+ id: string;
3
+ userId: string;
4
+ nickname: string;
5
+ content: string;
6
+ timestamp: number;
7
+ }
8
+ export interface GiftMessage {
9
+ id: string;
10
+ userId: string;
11
+ nickname: string;
12
+ giftId: string;
13
+ giftName: string;
14
+ count: number;
15
+ diamondValue: number;
16
+ timestamp: number;
17
+ }
18
+ export interface LikeMessage {
19
+ userId: string;
20
+ nickname: string;
21
+ count: number;
22
+ timestamp: number;
23
+ }
24
+ export interface RoomInfo {
25
+ roomId: string;
26
+ title: string;
27
+ streamerNickname: string;
28
+ onlineCount: number;
29
+ }
30
+ export type EventHandler<T> = (data: T) => void;
31
+ export interface StorageAPI {
32
+ get(key: string): Promise<string | null>;
33
+ set(key: string, value: string): Promise<void>;
34
+ delete(key: string): Promise<void>;
35
+ }
36
+ export type GameConfig = Record<string, unknown>;
37
+ export interface ConfigSchema {
38
+ type: 'object';
39
+ properties?: Record<string, {
40
+ type: 'string' | 'number' | 'boolean';
41
+ title?: string;
42
+ default?: unknown;
43
+ enum?: string[];
44
+ }>;
45
+ }
46
+ export interface ConfigAPI {
47
+ get(): Promise<GameConfig>;
48
+ getDefault(): Promise<GameConfig>;
49
+ update(config: GameConfig): Promise<void>;
50
+ }
51
+ export interface GameCommand {
52
+ type: string;
53
+ payload?: unknown;
54
+ }
55
+ export interface CommandAPI {
56
+ send(cmd: GameCommand): Promise<void>;
57
+ }
58
+ export interface SettleResult {
59
+ playerId: string;
60
+ score: number;
61
+ rank?: number;
62
+ }
63
+ export interface ReportAPI {
64
+ score(playerId: string, score: number): Promise<void>;
65
+ settle(results: SettleResult[]): Promise<void>;
66
+ }
67
+ export interface RoomAPI {
68
+ getInfo(): Promise<RoomInfo>;
69
+ }
70
+ /** 定时器事件 */
71
+ export interface TimerEvent {
72
+ key: string;
73
+ }
74
+ /** 自定义广播事件 */
75
+ export interface BroadcastEvent {
76
+ type: string;
77
+ data: unknown;
78
+ }
79
+ export interface PlatformAPI {
80
+ /** 语义相似度(0~1),调用平台 AI 模型 */
81
+ similarity(text1: string, text2: string): Promise<number>;
82
+ /** 平台级精确定时器(不受浏览器节流),到期后触发 timer 事件 */
83
+ timer(key: string, durationMs: number): Promise<void>;
84
+ /** TTS 语音播报 */
85
+ tts(text: string, options?: {
86
+ priority?: "high" | "normal";
87
+ }): Promise<void>;
88
+ /** 随机词 + 语义相似度批量计算 */
89
+ randomWords(answer: string, words: string[], count: number): Promise<{
90
+ word: string;
91
+ similarity: number;
92
+ }[]>;
93
+ }
94
+ export interface LiveGameSDK {
95
+ on(event: 'danmaku' | 'comment', handler: EventHandler<DanmakuMessage>): void;
96
+ on(event: 'gift', handler: EventHandler<GiftMessage>): void;
97
+ on(event: 'like', handler: EventHandler<LikeMessage>): void;
98
+ 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;
100
+ on(event: 'timer', handler: EventHandler<TimerEvent>): void;
101
+ on(event: 'broadcast', handler: EventHandler<BroadcastEvent>): void;
102
+ off(event: string, handler: EventHandler<any>): void;
103
+ storage: StorageAPI;
104
+ config: ConfigAPI;
105
+ command: CommandAPI;
106
+ report: ReportAPI;
107
+ room: RoomAPI;
108
+ platform: PlatformAPI;
109
+ /** 广播自定义事件给所有客户端 */
110
+ broadcast(type: string, data?: unknown): Promise<void>;
111
+ /** 连接直播事件流(仅 production 模式,Mock 模式自动模拟事件) */
112
+ connect(): Promise<void>;
113
+ }
package/dist/types.js ADDED
@@ -0,0 +1,3 @@
1
+ // ===== 事件类型 =====
2
+ export {};
3
+ // CreateSDKOptions 已移除 —— createSDK() 不再接受参数,Mock 使用 createMockSDK()
package/package.json ADDED
@@ -0,0 +1,57 @@
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
+ }