@live-game/sdk 0.4.0 → 0.5.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 +14 -0
- package/dist/index.d.ts +2 -1
- package/dist/mock/index.d.ts +19 -3
- package/dist/mock/index.js +82 -51
- package/dist/mock/platform.js +0 -4
- package/dist/react/index.d.ts +1 -1
- package/dist/react/index.js +10 -20
- package/dist/types.d.ts +42 -28
- package/package.json +9 -11
- package/dist/mock/command.d.ts +0 -2
- package/dist/mock/command.js +0 -8
- package/dist/mock/config.d.ts +0 -3
- package/dist/mock/config.js +0 -17
- package/dist/mock/events.d.ts +0 -6
- package/dist/mock/events.js +0 -79
- package/dist/mock/report.d.ts +0 -2
- package/dist/mock/report.js +0 -12
- package/dist/mock/storage.d.ts +0 -2
- package/dist/mock/storage.js +0 -14
- package/dist/utils.d.ts +0 -24
- package/dist/utils.js +0 -151
package/README.md
CHANGED
|
@@ -2,6 +2,10 @@
|
|
|
2
2
|
|
|
3
3
|
SDK for Live Game iframe apps and control panels.
|
|
4
4
|
|
|
5
|
+
Production and local integration both use the host-injected SDK. `createMockSDK()` is a deterministic unit-test double; it does not generate random traffic.
|
|
6
|
+
|
|
7
|
+
Version 0.5.0 adds injectable deterministic mocks and complete event types. The former `./utils` subpath is removed; use the documented package entry points. The host communication protocol remains `apiVersion: 1.0`, and runtime capability availability is determined by the host and manifest permissions.
|
|
8
|
+
|
|
5
9
|
```ts
|
|
6
10
|
import { createSDK } from "@live-game/sdk";
|
|
7
11
|
import { useGameState, useGameConfig, sendCmd } from "@live-game/sdk/react";
|
|
@@ -21,3 +25,13 @@ Publish game state for control panels:
|
|
|
21
25
|
```ts
|
|
22
26
|
await sdk.state.publish({ round: 2, status: "playing" });
|
|
23
27
|
```
|
|
28
|
+
|
|
29
|
+
Deterministic test flow:
|
|
30
|
+
|
|
31
|
+
```ts
|
|
32
|
+
const sdk = createMockSDK({ permissions: ["events.comment", "command"] });
|
|
33
|
+
sdk.emit("comment", { content: "苹果" });
|
|
34
|
+
await sdk.command.send({ type: "start" });
|
|
35
|
+
expect(sdk.calls[0].method).toBe("command.send");
|
|
36
|
+
sdk.dispose();
|
|
37
|
+
```
|
package/dist/index.d.ts
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
export { createSDK } from "./createSDK.js";
|
|
2
2
|
export { createMockSDK } from "./mock/index.js";
|
|
3
|
+
export type { MockLiveGameSDK, MockSDKCall, MockSDKOptions } from "./mock/index.js";
|
|
3
4
|
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 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";
|
|
5
6
|
export { useGameState, useGameConfig, sendCmd } from "./react/index.js";
|
package/dist/mock/index.d.ts
CHANGED
|
@@ -1,3 +1,19 @@
|
|
|
1
|
-
import type
|
|
2
|
-
|
|
3
|
-
|
|
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;
|
package/dist/mock/index.js
CHANGED
|
@@ -1,64 +1,95 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { createMockStorage } from "./storage.js";
|
|
3
|
-
import { createMockConfig } from "./config.js";
|
|
4
|
-
import { createMockCommand } from "./command.js";
|
|
5
|
-
import { createMockReport } from "./report.js";
|
|
1
|
+
import { PlatformError } from "../types.js";
|
|
6
2
|
import { createMockPlatform } from "./platform.js";
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
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));
|
|
14
30
|
const platform = createMockPlatform();
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
},
|
|
26
|
-
onReady(handler) { readyHandler = handler; },
|
|
27
|
-
onDisconnect(handler) { disconnectHandler = handler; },
|
|
28
|
-
onError(handler) { errorHandler = handler; },
|
|
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); },
|
|
29
42
|
on(event, handler) {
|
|
30
|
-
|
|
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); },
|
|
31
61
|
},
|
|
32
|
-
|
|
33
|
-
|
|
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]); },
|
|
34
68
|
},
|
|
35
|
-
storage,
|
|
36
|
-
config,
|
|
37
|
-
command,
|
|
38
|
-
report,
|
|
39
|
-
platform,
|
|
40
69
|
room: {
|
|
41
70
|
async getInfo() {
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
}
|
|
71
|
+
requireCapability("room.getInfo");
|
|
72
|
+
record("room.getInfo", []);
|
|
73
|
+
return { roomId: "mock-room", title: "模拟直播间", streamerNickname: "模拟主播", onlineCount: 0, ...options.room };
|
|
45
74
|
},
|
|
46
75
|
},
|
|
47
|
-
|
|
48
|
-
async
|
|
49
|
-
|
|
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);
|
|
50
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"); },
|
|
51
86
|
},
|
|
52
|
-
async broadcast(type, data) {
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
readyHandler?.();
|
|
59
|
-
},
|
|
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(); },
|
|
60
93
|
};
|
|
61
|
-
|
|
62
|
-
console.log(`[mock] broadcast: ${type}`, data);
|
|
63
|
-
}
|
|
94
|
+
return sdk;
|
|
64
95
|
}
|
package/dist/mock/platform.js
CHANGED
|
@@ -15,10 +15,6 @@ export function createMockPlatform() {
|
|
|
15
15
|
async tts(text, options) {
|
|
16
16
|
console.log(`[mock][tts][${options?.priority ?? "normal"}] ${text}`);
|
|
17
17
|
},
|
|
18
|
-
async randomWords(answer, words, count) {
|
|
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
18
|
async call(method, ...args) {
|
|
23
19
|
console.log(`[mock] platform.call("${method}")`, args);
|
|
24
20
|
throw new Error(`Mock 不支持动态能力: ${method}`);
|
package/dist/react/index.d.ts
CHANGED
|
@@ -3,4 +3,4 @@ export declare function useGameState<T = any>(): T | null;
|
|
|
3
3
|
/** 自动接收 host 推送的 config */
|
|
4
4
|
export declare function useGameConfig<T = Record<string, unknown>>(): T | null;
|
|
5
5
|
/** 向 host 发送游戏命令(自动走 postMessage) */
|
|
6
|
-
export declare function sendCmd(type: string, payload?: unknown): void
|
|
6
|
+
export declare function sendCmd(type: string, payload?: unknown): Promise<void>;
|
package/dist/react/index.js
CHANGED
|
@@ -1,17 +1,15 @@
|
|
|
1
1
|
// @live-game/sdk/react — React hooks
|
|
2
2
|
// 开发者不需要手动监听 postMessage
|
|
3
3
|
import { useEffect, useState } from 'react';
|
|
4
|
+
import { createSDK } from '../createSDK.js';
|
|
4
5
|
/** 自动接收 host 推送的 game_state */
|
|
5
6
|
export function useGameState() {
|
|
6
7
|
const [state, setState] = useState(null);
|
|
7
8
|
useEffect(() => {
|
|
8
|
-
const
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
};
|
|
13
|
-
window.addEventListener('message', handler);
|
|
14
|
-
return () => window.removeEventListener('message', handler);
|
|
9
|
+
const sdk = createSDK();
|
|
10
|
+
const handler = (value) => setState(value);
|
|
11
|
+
sdk.on('game_state', handler);
|
|
12
|
+
return () => sdk.off('game_state', handler);
|
|
15
13
|
}, []);
|
|
16
14
|
return state;
|
|
17
15
|
}
|
|
@@ -19,22 +17,14 @@ export function useGameState() {
|
|
|
19
17
|
export function useGameConfig() {
|
|
20
18
|
const [config, setConfig] = useState(null);
|
|
21
19
|
useEffect(() => {
|
|
22
|
-
const
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
};
|
|
27
|
-
window.addEventListener('message', handler);
|
|
28
|
-
return () => window.removeEventListener('message', handler);
|
|
20
|
+
const sdk = createSDK();
|
|
21
|
+
const handler = (value) => setConfig(value);
|
|
22
|
+
sdk.on('config', handler);
|
|
23
|
+
return () => sdk.off('config', handler);
|
|
29
24
|
}, []);
|
|
30
25
|
return config;
|
|
31
26
|
}
|
|
32
27
|
/** 向 host 发送游戏命令(自动走 postMessage) */
|
|
33
28
|
export function sendCmd(type, payload) {
|
|
34
|
-
|
|
35
|
-
type: 'sdk:call',
|
|
36
|
-
method: 'command.send',
|
|
37
|
-
id: Math.random().toString(36).slice(2),
|
|
38
|
-
args: payload ? [{ type, payload }] : [{ type }]
|
|
39
|
-
}, '*');
|
|
29
|
+
return createSDK().command.send(payload === undefined ? { type } : { type, payload });
|
|
40
30
|
}
|
package/dist/types.d.ts
CHANGED
|
@@ -1,26 +1,39 @@
|
|
|
1
|
-
export interface
|
|
1
|
+
export interface BaseUserMessage {
|
|
2
2
|
id: string;
|
|
3
3
|
userId: string;
|
|
4
4
|
nickname: string;
|
|
5
|
-
|
|
5
|
+
avatar?: string;
|
|
6
6
|
timestamp: number;
|
|
7
7
|
}
|
|
8
|
-
export interface
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
8
|
+
export interface DanmakuMessage extends BaseUserMessage {
|
|
9
|
+
content: string;
|
|
10
|
+
similarity?: number;
|
|
11
|
+
}
|
|
12
|
+
export type CommentMessage = DanmakuMessage;
|
|
13
|
+
export interface GiftMessage extends BaseUserMessage {
|
|
12
14
|
giftId: string;
|
|
13
|
-
giftName
|
|
15
|
+
giftName?: string;
|
|
14
16
|
count: number;
|
|
15
17
|
diamondValue: number;
|
|
16
|
-
|
|
18
|
+
comboId?: string;
|
|
17
19
|
}
|
|
18
|
-
export interface LikeMessage {
|
|
19
|
-
userId: string;
|
|
20
|
-
nickname: string;
|
|
20
|
+
export interface LikeMessage extends BaseUserMessage {
|
|
21
21
|
count: number;
|
|
22
|
-
timestamp: number;
|
|
23
22
|
}
|
|
23
|
+
export type SocialMessage = BaseUserMessage & {
|
|
24
|
+
type: "enter" | "follow" | "share" | "fansclub";
|
|
25
|
+
target?: string;
|
|
26
|
+
count?: number;
|
|
27
|
+
action?: number;
|
|
28
|
+
content?: string;
|
|
29
|
+
};
|
|
30
|
+
export type RoomStatsMessage = {
|
|
31
|
+
id: string;
|
|
32
|
+
roomId: string;
|
|
33
|
+
online: number;
|
|
34
|
+
totalViewers?: number;
|
|
35
|
+
timestamp: number;
|
|
36
|
+
};
|
|
24
37
|
export interface RoomInfo {
|
|
25
38
|
roomId: string;
|
|
26
39
|
title: string;
|
|
@@ -34,17 +47,18 @@ export interface StorageAPI {
|
|
|
34
47
|
delete(key: string): Promise<void>;
|
|
35
48
|
}
|
|
36
49
|
export type GameConfig = Record<string, unknown>;
|
|
37
|
-
export
|
|
38
|
-
type:
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
}
|
|
50
|
+
export type ConfigSchema = Record<string, {
|
|
51
|
+
type: string;
|
|
52
|
+
label?: string;
|
|
53
|
+
description?: string;
|
|
54
|
+
default?: unknown;
|
|
55
|
+
required?: boolean;
|
|
56
|
+
enum?: unknown[];
|
|
57
|
+
[key: string]: unknown;
|
|
58
|
+
}>;
|
|
46
59
|
export interface ConfigAPI {
|
|
47
60
|
get(): Promise<GameConfig>;
|
|
61
|
+
/** @deprecated 平台只有一份当前有效配置,请使用 get()。 */
|
|
48
62
|
getDefault(): Promise<GameConfig>;
|
|
49
63
|
update(config: GameConfig): Promise<void>;
|
|
50
64
|
}
|
|
@@ -89,11 +103,6 @@ export interface PlatformAPI {
|
|
|
89
103
|
tts(text: string, options?: {
|
|
90
104
|
priority?: "high" | "normal";
|
|
91
105
|
}): Promise<void>;
|
|
92
|
-
/** 随机词 + 语义相似度批量计算 */
|
|
93
|
-
randomWords(answer: string, words: string[], count: number): Promise<{
|
|
94
|
-
word: string;
|
|
95
|
-
similarity: number;
|
|
96
|
-
}[]>;
|
|
97
106
|
/** 动态能力调用(平台新增能力时,老 SDK 无需升级) */
|
|
98
107
|
call(method: string, ...args: unknown[]): Promise<unknown>;
|
|
99
108
|
}
|
|
@@ -111,6 +120,8 @@ export declare class PlatformError extends Error {
|
|
|
111
120
|
export interface LiveGameSDK {
|
|
112
121
|
/** SDK 版本号 */
|
|
113
122
|
readonly version: string;
|
|
123
|
+
/** 稳定的宿主通信协议版本;同一主版本内只做兼容性扩展。 */
|
|
124
|
+
readonly apiVersion: string;
|
|
114
125
|
/** 检测平台是否支持指定能力 */
|
|
115
126
|
supports(capability: string): boolean;
|
|
116
127
|
/** SDK 就绪回调 */
|
|
@@ -122,10 +133,13 @@ export interface LiveGameSDK {
|
|
|
122
133
|
on(event: 'danmaku' | 'comment', handler: EventHandler<DanmakuMessage>): void;
|
|
123
134
|
on(event: 'gift', handler: EventHandler<GiftMessage>): void;
|
|
124
135
|
on(event: 'like', handler: EventHandler<LikeMessage>): void;
|
|
125
|
-
on(event: 'roomInfo'
|
|
126
|
-
on(event: '
|
|
136
|
+
on(event: 'roomInfo', handler: EventHandler<RoomInfo>): void;
|
|
137
|
+
on(event: 'room_stats', handler: EventHandler<RoomStatsMessage>): void;
|
|
138
|
+
on(event: 'enter' | 'follow' | 'share' | 'fansclub', handler: EventHandler<SocialMessage>): void;
|
|
139
|
+
on(event: 'live_event' | 'theme_change' | 'game_state' | 'config' | 'command', handler: EventHandler<unknown>): void;
|
|
127
140
|
on(event: 'timer', handler: EventHandler<TimerEvent>): void;
|
|
128
141
|
on(event: 'broadcast', handler: EventHandler<BroadcastEvent>): void;
|
|
142
|
+
on<T = unknown>(event: string, handler: EventHandler<T>): void;
|
|
129
143
|
off(event: string, handler: EventHandler<any>): void;
|
|
130
144
|
storage: StorageAPI;
|
|
131
145
|
config: ConfigAPI;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@live-game/sdk",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.5.0",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"description": "Live Game SDK for game and control iframe integrations.",
|
|
6
6
|
"main": "dist/index.js",
|
|
@@ -13,11 +13,7 @@
|
|
|
13
13
|
"./react": {
|
|
14
14
|
"types": "./dist/react/index.d.ts",
|
|
15
15
|
"import": "./dist/react/index.js"
|
|
16
|
-
}
|
|
17
|
-
"./utils": {
|
|
18
|
-
"types": "./dist/utils.d.ts",
|
|
19
|
-
"import": "./dist/utils.js"
|
|
20
|
-
}
|
|
16
|
+
}
|
|
21
17
|
},
|
|
22
18
|
"files": [
|
|
23
19
|
"dist",
|
|
@@ -26,9 +22,10 @@
|
|
|
26
22
|
"publishConfig": {
|
|
27
23
|
"access": "public"
|
|
28
24
|
},
|
|
29
|
-
"scripts": {
|
|
30
|
-
"build": "node scripts/clean-dist.mjs && tsc -p tsconfig.json",
|
|
31
|
-
"
|
|
25
|
+
"scripts": {
|
|
26
|
+
"build": "node scripts/clean-dist.mjs && tsc -p tsconfig.json",
|
|
27
|
+
"test": "vitest run",
|
|
28
|
+
"check": "tsc --noEmit",
|
|
32
29
|
"prepack": "npm run build",
|
|
33
30
|
"build:template-zip": "tsx scripts/build-template-zip.ts"
|
|
34
31
|
},
|
|
@@ -41,10 +38,11 @@
|
|
|
41
38
|
}
|
|
42
39
|
},
|
|
43
40
|
"devDependencies": {
|
|
44
|
-
"@types/react": "^
|
|
41
|
+
"@types/react": "^19.0.0",
|
|
45
42
|
"adm-zip": "^0.5.18",
|
|
46
43
|
"typescript": "^5.0.0",
|
|
47
44
|
"tsx": "^4.0.0",
|
|
48
|
-
"vite": "^5.0.0"
|
|
45
|
+
"vite": "^5.0.0",
|
|
46
|
+
"vitest": "^2.0.5"
|
|
49
47
|
}
|
|
50
48
|
}
|
package/dist/mock/command.d.ts
DELETED
package/dist/mock/command.js
DELETED
package/dist/mock/config.d.ts
DELETED
package/dist/mock/config.js
DELETED
|
@@ -1,17 +0,0 @@
|
|
|
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
|
-
}
|
package/dist/mock/events.d.ts
DELETED
package/dist/mock/events.js
DELETED
|
@@ -1,79 +0,0 @@
|
|
|
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
|
-
}
|
package/dist/mock/report.d.ts
DELETED
package/dist/mock/report.js
DELETED
|
@@ -1,12 +0,0 @@
|
|
|
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
|
-
}
|
package/dist/mock/storage.d.ts
DELETED
package/dist/mock/storage.js
DELETED
|
@@ -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
|
-
}
|
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
|
-
}
|