@live-game/sdk 0.4.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.
Files changed (46) hide show
  1. package/CHANGELOG.md +24 -0
  2. package/README.md +101 -10
  3. package/UPGRADING.md +36 -0
  4. package/dist/app/client.d.ts +112 -0
  5. package/dist/app/client.js +324 -0
  6. package/dist/app/contracts.d.ts +180 -0
  7. package/dist/app/contracts.js +41 -0
  8. package/dist/app/define-app.d.ts +99 -0
  9. package/dist/app/define-app.js +19 -0
  10. package/dist/app/images.d.ts +7 -0
  11. package/dist/app/images.js +61 -0
  12. package/dist/app/index.d.ts +7 -0
  13. package/dist/app/index.js +6 -0
  14. package/dist/app/live-events.d.ts +161 -0
  15. package/dist/app/live-events.js +15 -0
  16. package/dist/app/react.d.ts +101 -0
  17. package/dist/app/react.js +39 -0
  18. package/dist/app/types.d.ts +55 -0
  19. package/dist/app/types.js +1 -0
  20. package/dist/index.d.ts +1 -5
  21. package/dist/index.js +1 -5
  22. package/dist/room-snapshot.d.ts +33 -0
  23. package/dist/room-snapshot.js +1 -0
  24. package/package.json +50 -50
  25. package/dist/createSDK.d.ts +0 -9
  26. package/dist/createSDK.js +0 -17
  27. package/dist/mock/command.d.ts +0 -2
  28. package/dist/mock/command.js +0 -8
  29. package/dist/mock/config.d.ts +0 -3
  30. package/dist/mock/config.js +0 -17
  31. package/dist/mock/events.d.ts +0 -6
  32. package/dist/mock/events.js +0 -79
  33. package/dist/mock/index.d.ts +0 -3
  34. package/dist/mock/index.js +0 -64
  35. package/dist/mock/platform.d.ts +0 -6
  36. package/dist/mock/platform.js +0 -49
  37. package/dist/mock/report.d.ts +0 -2
  38. package/dist/mock/report.js +0 -12
  39. package/dist/mock/storage.d.ts +0 -2
  40. package/dist/mock/storage.js +0 -14
  41. package/dist/react/index.d.ts +0 -6
  42. package/dist/react/index.js +0 -40
  43. package/dist/types.d.ts +0 -141
  44. package/dist/types.js +0 -11
  45. package/dist/utils.d.ts +0 -24
  46. package/dist/utils.js +0 -151
@@ -1,14 +0,0 @@
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
- }
@@ -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): void;
@@ -1,40 +0,0 @@
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
- }
package/dist/types.d.ts DELETED
@@ -1,141 +0,0 @@
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
- export interface StateAPI {
71
- /** 发布当前游戏状态,供控制端 useGameState() 读取 */
72
- publish(state: unknown): Promise<void>;
73
- }
74
- /** 定时器事件 */
75
- export interface TimerEvent {
76
- key: string;
77
- }
78
- /** 自定义广播事件 */
79
- export interface BroadcastEvent {
80
- type: string;
81
- data: unknown;
82
- }
83
- export interface PlatformAPI {
84
- /** 语义相似度(0~1),调用平台 AI 模型 */
85
- similarity(text1: string, text2: string): Promise<number>;
86
- /** 平台级精确定时器(不受浏览器节流),到期后触发 timer 事件 */
87
- timer(key: string, durationMs: number): Promise<void>;
88
- /** TTS 语音播报 */
89
- tts(text: string, options?: {
90
- priority?: "high" | "normal";
91
- }): Promise<void>;
92
- /** 随机词 + 语义相似度批量计算 */
93
- randomWords(answer: string, words: string[], count: number): Promise<{
94
- word: string;
95
- similarity: number;
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);
110
- }
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;
122
- on(event: 'danmaku' | 'comment', handler: EventHandler<DanmakuMessage>): void;
123
- on(event: 'gift', handler: EventHandler<GiftMessage>): void;
124
- on(event: 'like', handler: EventHandler<LikeMessage>): void;
125
- on(event: 'roomInfo' | 'room_stats', handler: EventHandler<RoomInfo>): void;
126
- on(event: 'enter' | 'follow' | 'share' | 'fansclub' | 'live_event' | 'theme_change' | 'game_state' | 'config' | 'command', handler: EventHandler<unknown>): void;
127
- on(event: 'timer', handler: EventHandler<TimerEvent>): void;
128
- on(event: 'broadcast', handler: EventHandler<BroadcastEvent>): void;
129
- off(event: string, handler: EventHandler<any>): void;
130
- storage: StorageAPI;
131
- config: ConfigAPI;
132
- command: CommandAPI;
133
- report: ReportAPI;
134
- room: RoomAPI;
135
- state: StateAPI;
136
- platform: PlatformAPI;
137
- /** 广播自定义事件给所有客户端 */
138
- broadcast(type: string, data?: unknown): Promise<void>;
139
- /** 连接直播事件流 */
140
- connect(): Promise<void>;
141
- }
package/dist/types.js DELETED
@@ -1,11 +0,0 @@
1
- // ===== 事件类型 =====
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
- }
11
- // CreateSDKOptions 已移除 —— createSDK() 不再接受参数,Mock 使用 createMockSDK()
package/dist/utils.d.ts DELETED
@@ -1,24 +0,0 @@
1
- /**
2
- * 游戏工具函数
3
- * 导入路径: import { obfuscate, ... } from '@live-game/sdk/utils'
4
- */
5
- export declare function obfuscate(word: string): string;
6
- export declare function deobfuscate(obfuscated: string): string;
7
- export interface WordItem {
8
- category: string;
9
- partOfSpeech: string;
10
- answer: string;
11
- hints: string[];
12
- }
13
- export declare function parseWordsConfig(configWords: unknown): WordItem[];
14
- export declare function generateSameLengthAnswers(words: WordItem[], currentAnswer: string, count?: number): string[];
15
- export declare function matchesGiftName(event: {
16
- giftId?: unknown;
17
- giftName?: unknown;
18
- }, expectedName: unknown): boolean;
19
- export declare function getRankLabel(score: number): string;
20
- export declare function readDuration(config: Record<string, unknown>, defaultDuration?: number): number;
21
- export declare function readHintRules(config: Record<string, unknown>): {
22
- likeRequired: number;
23
- afterSeconds: number;
24
- }[];
package/dist/utils.js DELETED
@@ -1,151 +0,0 @@
1
- /**
2
- * 游戏工具函数
3
- * 导入路径: import { obfuscate, ... } from '@live-game/sdk/utils'
4
- */
5
- // ===== 答案混淆(XOR + Base64) =====
6
- export function obfuscate(word) {
7
- const xor = word
8
- .split("")
9
- .map((c) => String.fromCharCode(c.charCodeAt(0) ^ 42))
10
- .join("");
11
- // Node.js Worker 中 Buffer 可用,浏览器 fallback 到 btoa
12
- if (typeof Buffer !== "undefined") {
13
- return Buffer.from(xor, "utf-8").toString("base64");
14
- }
15
- const bytes = new TextEncoder().encode(xor);
16
- return btoa(String.fromCharCode(...bytes));
17
- }
18
- export function deobfuscate(obfuscated) {
19
- try {
20
- let xor;
21
- if (typeof Buffer !== "undefined") {
22
- xor = Buffer.from(obfuscated, "base64").toString("utf-8");
23
- }
24
- else {
25
- const bytes = Uint8Array.from(atob(obfuscated), (char) => char.charCodeAt(0));
26
- xor = new TextDecoder().decode(bytes);
27
- }
28
- return xor
29
- .split("")
30
- .map((c) => String.fromCharCode(c.charCodeAt(0) ^ 42))
31
- .join("");
32
- }
33
- catch {
34
- return "";
35
- }
36
- }
37
- export function parseWordsConfig(configWords) {
38
- if (Array.isArray(configWords)) {
39
- return configWords
40
- .map((item) => {
41
- const row = item;
42
- return {
43
- category: String(row.category ?? "").trim(),
44
- partOfSpeech: String(row.partOfSpeech ?? "名词").trim() || "名词",
45
- answer: String(row.answer ?? row.word ?? "").trim(),
46
- hints: Array.isArray(row.hints)
47
- ? row.hints.map((hint) => String(hint).trim()).filter(Boolean)
48
- : [],
49
- };
50
- })
51
- .filter((item) => item.category && item.answer);
52
- }
53
- if (typeof configWords !== "string")
54
- return [];
55
- return configWords
56
- .split(",")
57
- .map((part) => part.split(":").map((item) => item.trim()))
58
- .filter((parts) => parts[0] && parts[1])
59
- .map(([category, answer, ...hints]) => ({
60
- category,
61
- partOfSpeech: "名词",
62
- answer,
63
- hints: hints.filter(Boolean),
64
- }));
65
- }
66
- export function generateSameLengthAnswers(words, currentAnswer, count = 100) {
67
- const candidates = words
68
- .map((word) => word.answer)
69
- .filter((answer) => answer.length === currentAnswer.length);
70
- if (!candidates.length)
71
- return [];
72
- const answers = [];
73
- while (answers.length < count) {
74
- answers.push(...[...candidates].sort(() => Math.random() - 0.5));
75
- }
76
- return answers.slice(0, count);
77
- }
78
- // ===== 礼物匹配 =====
79
- export function matchesGiftName(event, expectedName) {
80
- const expected = normalizeGiftName(expectedName);
81
- const actual = normalizeGiftName(event.giftName);
82
- if (actual && actual === expected)
83
- return true;
84
- return expected === "小心心" && String(event.giftId ?? "").trim() === "1";
85
- }
86
- function normalizeGiftName(value) {
87
- return String(value ?? "").trim().replace(/\s+/g, "");
88
- }
89
- // ===== 段位 =====
90
- export function getRankLabel(score) {
91
- if (score < 10)
92
- return "青铜 5";
93
- if (score < 20)
94
- return "青铜 3";
95
- if (score < 30)
96
- return "青铜 1";
97
- if (score < 50)
98
- return "白银 5";
99
- if (score < 80)
100
- return "白银 3";
101
- if (score < 120)
102
- return "白银 1";
103
- if (score < 200)
104
- return "黄金 5";
105
- if (score < 300)
106
- return "黄金 3";
107
- if (score < 500)
108
- return "黄金 1";
109
- if (score < 1000)
110
- return "钻石 5";
111
- if (score < 2000)
112
- return "钻石 1";
113
- return "王者 5";
114
- }
115
- // ===== 配置读取 =====
116
- export function readDuration(config, defaultDuration = 240) {
117
- const seconds = Number(config.duration ?? defaultDuration);
118
- return Number.isFinite(seconds) && seconds > 0
119
- ? Math.floor(seconds)
120
- : defaultDuration;
121
- }
122
- export function readHintRules(config) {
123
- const defaultRules = [
124
- { likeRequired: 50, afterSeconds: 0 },
125
- { likeRequired: 150, afterSeconds: 40 },
126
- { likeRequired: 300, afterSeconds: 100 },
127
- ];
128
- try {
129
- if (config && Array.isArray(config.hintRules)) {
130
- const rules = config.hintRules
131
- .map((rule) => {
132
- if (!rule || typeof rule !== "object")
133
- return null;
134
- const likeRequired = Math.max(0, Math.floor(Number(rule.likeRequired ?? 0)));
135
- const afterSeconds = Math.max(0, Math.floor(Number(rule.afterSeconds ?? 0)));
136
- return Number.isNaN(likeRequired) || Number.isNaN(afterSeconds)
137
- ? null
138
- : { likeRequired, afterSeconds };
139
- })
140
- .filter((rule) => !!rule && rule.likeRequired > 0)
141
- .slice(0, 3);
142
- if (rules.length) {
143
- return Array.from({ length: 3 }, (_, i) => rules[i] ?? defaultRules[i]);
144
- }
145
- }
146
- }
147
- catch {
148
- // ignore
149
- }
150
- return defaultRules;
151
- }