@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
@@ -0,0 +1,101 @@
1
+ import type { AppCommand, AppContext } from "./types.js";
2
+ export declare function useAppSDK<State = unknown, Config extends object = Record<string, unknown>, Command extends AppCommand = AppCommand>(): {
3
+ ready: Promise<AppContext<State, Config>>;
4
+ dispose: (error?: import("./client.js").AppSDKError) => void;
5
+ call: <T = unknown>(method: import("./contracts.js").AppCapability, ...args: unknown[]) => Promise<T>;
6
+ on: {
7
+ <K extends keyof {
8
+ "app.context": AppContext<State_1, Config_1>;
9
+ "app.stop": null;
10
+ state: State_1 | null;
11
+ config: Config_1;
12
+ timer: import("./types.js").AppTimerEvent;
13
+ "audio.job": import("./types.js").AudioJobEvent;
14
+ command: Command_1;
15
+ "app.message": AppCommand;
16
+ "live.status": import("./types.js").AppSourceStatus;
17
+ }>(event: K, handler: (value: {
18
+ "app.context": AppContext<State, Config>;
19
+ "app.stop": null;
20
+ state: State | null;
21
+ config: Config;
22
+ timer: import("./types.js").AppTimerEvent;
23
+ "audio.job": import("./types.js").AudioJobEvent;
24
+ command: Command;
25
+ "app.message": AppCommand;
26
+ "live.status": import("./types.js").AppSourceStatus;
27
+ }[K]) => unknown): () => void;
28
+ <T = unknown>(event: string, handler: (value: NoInfer<T>) => unknown): () => void;
29
+ };
30
+ readonly disposed: boolean;
31
+ lifecycle: {
32
+ ready: () => Promise<void>;
33
+ fail: (message: string) => Promise<void>;
34
+ onStop: (handler: () => unknown) => () => void;
35
+ };
36
+ readonly context: AppContext<State, Config> | undefined;
37
+ supports: (capability: import("./contracts.js").AppCapability) => boolean;
38
+ config: {
39
+ get: () => Promise<Config>;
40
+ update: (values: Partial<Config>) => Promise<Config>;
41
+ onChange: (handler: (value: Config) => unknown) => () => void;
42
+ };
43
+ storage: {
44
+ get: <T = unknown>(key: string) => Promise<T | null>;
45
+ set: (key: string, value: unknown) => Promise<null>;
46
+ delete: (key: string) => Promise<null>;
47
+ };
48
+ state: {
49
+ get: <T = State>() => Promise<T | null>;
50
+ publish: (value: State) => Promise<null>;
51
+ onChange: (handler: (value: State | null) => unknown) => () => void;
52
+ };
53
+ commands: {
54
+ send: (...[type, payload]: import("./types.js").AppCommandArgs<Command>) => Promise<null>;
55
+ on: <T = Command>(handler: (value: NoInfer<T>) => unknown) => () => void;
56
+ };
57
+ views: {
58
+ notify: (type: string, payload?: unknown) => Promise<null>;
59
+ on: <T = AppCommand>(handler: (value: T) => unknown) => () => void;
60
+ };
61
+ live: {
62
+ room: () => Promise<import("./index.js").LiveRoomSnapshot | null>;
63
+ on: {
64
+ <K extends import("./live-events.js").LiveEventType>(type: K, handler: (event: import("./types.js").AppLiveEventMap[K], envelope: import("./contracts.js").AppLiveEnvelope<import("./types.js").AppLiveEventMap[K]>) => unknown): () => void;
65
+ <T>(type: import("./live-events.js").LiveEventType, handler: (event: NoInfer<T>, envelope: import("./contracts.js").AppLiveEnvelope<NoInfer<T>>) => unknown): () => void;
66
+ };
67
+ };
68
+ catalog: {
69
+ gifts: (query: import("./contracts.js").AppGiftQuery) => Promise<import("./contracts.js").AppGiftCatalog>;
70
+ };
71
+ guide: {
72
+ publish: (content: import("./contracts.js").AppGuide) => Promise<void>;
73
+ };
74
+ audio: {
75
+ speak: (text: string, options?: import("./types.js").SpeechOptions) => Promise<{
76
+ jobId: string;
77
+ }>;
78
+ play: (asset: string, options?: import("./types.js").AudioPlayOptions) => Promise<{
79
+ jobId: string;
80
+ }>;
81
+ cancel: (jobId: string) => Promise<null>;
82
+ voices: () => Promise<import("./types.js").AudioVoice[]>;
83
+ onJob: (handler: (event: import("./types.js").AudioJobEvent) => unknown) => () => void;
84
+ };
85
+ timers: {
86
+ set: (key: string, durationMs: number) => Promise<null>;
87
+ cancel: (key: string) => Promise<null>;
88
+ on: (handler: (event: import("./types.js").AppTimerEvent) => unknown) => () => void;
89
+ };
90
+ text: {
91
+ similarity: (first: string, second: string) => Promise<number>;
92
+ };
93
+ assets: {
94
+ image: (url: string) => Promise<string>;
95
+ };
96
+ log: (level: "info" | "warn" | "error", message: string) => Promise<null>;
97
+ };
98
+ export declare function useAppContext<State = unknown, Config extends object = Record<string, unknown>>(): AppContext<State, Config> | undefined;
99
+ export declare function useAppState<T = unknown>(): T | null;
100
+ export declare function useAppConfig<T extends object = Record<string, unknown>>(): T | null;
101
+ export declare function sendAppCommand(type: string, payload?: unknown): Promise<null>;
@@ -0,0 +1,39 @@
1
+ import { useCallback, useMemo, useSyncExternalStore } from "react";
2
+ import { createAppSDK } from "./client.js";
3
+ export function useAppSDK() {
4
+ return useMemo(() => createAppSDK(), []);
5
+ }
6
+ function subscribe(sdk, notify) {
7
+ let active = true;
8
+ const remove = [sdk.on("app.context", notify), sdk.state.onChange(notify), sdk.config.onChange(notify)];
9
+ void sdk.ready
10
+ .then(() => {
11
+ if (active)
12
+ notify();
13
+ })
14
+ .catch(() => {
15
+ if (active)
16
+ notify();
17
+ });
18
+ return () => {
19
+ active = false;
20
+ for (const off of remove)
21
+ off();
22
+ };
23
+ }
24
+ export function useAppContext() {
25
+ const sdk = useAppSDK();
26
+ const listen = useCallback((notify) => subscribe(sdk, notify), [sdk]);
27
+ return useSyncExternalStore(listen, () => sdk.context, () => undefined);
28
+ }
29
+ export function useAppState() {
30
+ const context = useAppContext();
31
+ return context?.state ?? null;
32
+ }
33
+ export function useAppConfig() {
34
+ const context = useAppContext();
35
+ return context?.config ?? null;
36
+ }
37
+ export function sendAppCommand(type, payload) {
38
+ return createAppSDK().commands.send(type, payload);
39
+ }
@@ -0,0 +1,55 @@
1
+ import type { AppBootstrap } from "./contracts.js";
2
+ import type { LiveEvent, LiveEventType } from "./live-events.js";
3
+ export type AppLiveEventMap = {
4
+ [K in LiveEventType]: Extract<LiveEvent, {
5
+ type: K;
6
+ }>;
7
+ };
8
+ export type AppCommand<Type extends string = string, Payload = unknown> = {
9
+ type: Type;
10
+ payload?: Payload;
11
+ };
12
+ export type AppCommandArgs<C extends AppCommand> = C extends AppCommand ? C extends {
13
+ payload: unknown;
14
+ } ? [type: C["type"], payload: C["payload"]] : "payload" extends keyof C ? [type: C["type"], payload?: C["payload"]] : [type: C["type"]] : never;
15
+ export type AppContext<State = unknown, Config extends object = Record<string, unknown>> = Omit<AppBootstrap, "state" | "config"> & {
16
+ state: State | null;
17
+ config: Config;
18
+ };
19
+ export type AudioJobStatus = "queued" | "playing" | "completed" | "cancelled" | "failed";
20
+ export type AudioJobEvent = {
21
+ jobId: string;
22
+ status: AudioJobStatus;
23
+ error?: string;
24
+ };
25
+ export type AudioVoice = {
26
+ id: string;
27
+ name: string;
28
+ language: string;
29
+ };
30
+ export type SpeechOptions = {
31
+ /** 0–1; default 1. */
32
+ volume?: number;
33
+ /** 0.5–2; default 1. */
34
+ rate?: number;
35
+ /** 0.5–2; default 1. */
36
+ pitch?: number;
37
+ voice?: string;
38
+ priority?: "normal" | "high";
39
+ };
40
+ export type AudioPlayOptions = {
41
+ volume?: number;
42
+ rate?: number;
43
+ loop?: boolean;
44
+ };
45
+ export type AppTimerEvent = {
46
+ key: string;
47
+ deadline: number;
48
+ lateBy: number;
49
+ };
50
+ export type AppSourceStatus = {
51
+ id: string | null;
52
+ connected: boolean;
53
+ events: readonly string[];
54
+ room: import("../room-snapshot.js").LiveRoomSnapshot | null;
55
+ };
@@ -0,0 +1 @@
1
+ export {};
package/dist/index.d.ts CHANGED
@@ -1,5 +1 @@
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";
1
+ export * from "./app/index.js";
package/dist/index.js CHANGED
@@ -1,5 +1 @@
1
- export { createSDK } from "./createSDK.js";
2
- export { createMockSDK } from "./mock/index.js";
3
- export { PlatformError } from "./types.js";
4
- // React hooks(可选,非 React 项目不需要 import)
5
- export { useGameState, useGameConfig, sendCmd } from "./react/index.js";
1
+ export * from "./app/index.js";
@@ -0,0 +1,33 @@
1
+ /** Public, read-only room data. Authentication credentials and connection controls are never included. */
2
+ export type RoomMetric = {
3
+ readonly value: number | null;
4
+ readonly observedAt: number | null;
5
+ readonly status: "unknown" | "fresh" | "stale" | "unsupported";
6
+ };
7
+ export type LiveRoomSnapshot = {
8
+ readonly schemaVersion: 1;
9
+ readonly contextId: string;
10
+ readonly revision: number;
11
+ /** An adapter registry ID; new platforms do not require games to upgrade their SDK. */
12
+ readonly platform: string;
13
+ readonly roomId: string;
14
+ readonly title: string | null;
15
+ readonly streamerNickname: string | null;
16
+ readonly streamerAvatar: string | null;
17
+ /** Source-reported broadcast state. A connected collector does not imply a live broadcast. */
18
+ readonly broadcastStatus: "live" | "offline" | "ended" | "unknown";
19
+ readonly dataStatus: "waiting" | "live" | "stale" | "offline";
20
+ readonly connectedAt: number | null;
21
+ readonly updatedAt: number | null;
22
+ readonly metrics: {
23
+ readonly online: RoomMetric;
24
+ readonly platformLikes: RoomMetric;
25
+ /** Platform-reported cumulative viewers, when its semantics are verified by the adapter. */
26
+ readonly totalViewers?: RoomMetric;
27
+ /** Only deduplicated increments received locally within this context, including reconnects. */
28
+ readonly receivedLikes: number;
29
+ readonly receivedComments: number;
30
+ readonly receivedGifts: number;
31
+ readonly receivedEnters: number;
32
+ };
33
+ };
@@ -0,0 +1 @@
1
+ export {};
package/package.json CHANGED
@@ -1,50 +1,50 @@
1
- {
2
- "name": "@live-game/sdk",
3
- "version": "0.4.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
+ {
2
+ "name": "@live-game/sdk",
3
+ "version": "2.0.0-dev.8",
4
+ "type": "module",
5
+ "description": "Local application SDK for browser workers, controls and outputs",
6
+ "main": "dist/index.js",
7
+ "types": "dist/index.d.ts",
8
+ "exports": {
9
+ "./app": {
10
+ "types": "./dist/app/index.d.ts",
11
+ "import": "./dist/app/index.js"
12
+ },
13
+ "./app/react": {
14
+ "types": "./dist/app/react.d.ts",
15
+ "import": "./dist/app/react.js"
16
+ },
17
+ ".": {
18
+ "types": "./dist/index.d.ts",
19
+ "import": "./dist/index.js"
20
+ }
21
+ },
22
+ "files": [
23
+ "dist",
24
+ "README.md",
25
+ "CHANGELOG.md",
26
+ "UPGRADING.md"
27
+ ],
28
+ "publishConfig": {
29
+ "access": "public"
30
+ },
31
+ "scripts": {
32
+ "build": "node scripts/sync-room-contract.mjs && node scripts/sync-app-contract.mjs && node scripts/clean-dist.mjs && tsc -p tsconfig.json",
33
+ "test": "vitest run",
34
+ "check": "node scripts/sync-room-contract.mjs --check && node scripts/sync-app-contract.mjs --check && tsc -p tsconfig.types.json",
35
+ "prepack": "npm run build"
36
+ },
37
+ "peerDependencies": {
38
+ "react": "^19.0.0"
39
+ },
40
+ "peerDependenciesMeta": {
41
+ "react": {
42
+ "optional": true
43
+ }
44
+ },
45
+ "devDependencies": {
46
+ "@types/react": "^19.0.0",
47
+ "typescript": "^5.0.0",
48
+ "vitest": "^2.0.5"
49
+ }
50
+ }
@@ -1,9 +0,0 @@
1
- import type { LiveGameSDK } from "./types.js";
2
- /**
3
- * 创建 SDK 实例
4
- *
5
- * 检测平台宿主注入的 window.__LIVEGAME_SDK__。
6
- * 本地开发请使用 @live-game/cli dev 启动调试服务器。
7
- * Mock 模式已移除——使用 createMockSDK() 进行单元测试。
8
- */
9
- export declare function createSDK(): LiveGameSDK;
package/dist/createSDK.js DELETED
@@ -1,17 +0,0 @@
1
- /**
2
- * 创建 SDK 实例
3
- *
4
- * 检测平台宿主注入的 window.__LIVEGAME_SDK__。
5
- * 本地开发请使用 @live-game/cli dev 启动调试服务器。
6
- * Mock 模式已移除——使用 createMockSDK() 进行单元测试。
7
- */
8
- export function createSDK() {
9
- if (typeof window !== "undefined" &&
10
- window.__LIVEGAME_SDK__) {
11
- return window.__LIVEGAME_SDK__;
12
- }
13
- throw new Error("LiveGame SDK 未检测到平台宿主注入。\n" +
14
- "• 开发调试: 请使用 npx @live-game/dev-cli dev 启动本地调试\n" +
15
- "• 生产环境: 游戏通过平台宿主加载,SDK 自动注入\n" +
16
- "• 单元测试: 请使用 createMockSDK()");
17
- }
@@ -1,2 +0,0 @@
1
- import type { CommandAPI } from '../types.js';
2
- export declare function createMockCommand(): CommandAPI;
@@ -1,8 +0,0 @@
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
- }
@@ -1,3 +0,0 @@
1
- import type { ConfigAPI, GameConfig } from '../types.js';
2
- export declare function setMockConfig(config: GameConfig): void;
3
- export declare function createMockConfig(): ConfigAPI;
@@ -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
- }
@@ -1,6 +0,0 @@
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
- };
@@ -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
- }
@@ -1,3 +0,0 @@
1
- import type { LiveGameSDK } from "../types.js";
2
- /** 创建完整 Mock SDK,用于单元测试和本地 UI 开发 */
3
- export declare function createMockSDK(): LiveGameSDK;
@@ -1,64 +0,0 @@
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,用于单元测试和本地 UI 开发 */
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
- // 生命周期
16
- let readyHandler = null;
17
- let disconnectHandler = null;
18
- let errorHandler = null;
19
- let connected = false;
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; },
29
- on(event, handler) {
30
- events.on(event, handler);
31
- },
32
- off(event, handler) {
33
- events.off(event, handler);
34
- },
35
- storage,
36
- config,
37
- command,
38
- report,
39
- platform,
40
- room: {
41
- async getInfo() {
42
- return new Promise((resolve) => {
43
- events.on("roomInfo", (info) => resolve(info));
44
- });
45
- },
46
- },
47
- state: {
48
- async publish(state) {
49
- await sdkBroadcast("__game_state", state);
50
- },
51
- },
52
- async broadcast(type, data) {
53
- await sdkBroadcast(type, data);
54
- },
55
- async connect() {
56
- console.log("[mock] connected");
57
- connected = true;
58
- readyHandler?.();
59
- },
60
- };
61
- async function sdkBroadcast(type, data) {
62
- console.log(`[mock] broadcast: ${type}`, data);
63
- }
64
- }
@@ -1,6 +0,0 @@
1
- import type { PlatformAPI } from "../types.js";
2
- /**
3
- * 模拟平台能力——本地开发用
4
- * similarity 使用 Levenshtein 编辑距离代替 AI 模型
5
- */
6
- export declare function createMockPlatform(): PlatformAPI;
@@ -1,49 +0,0 @@
1
- /**
2
- * 模拟平台能力——本地开发用
3
- * similarity 使用 Levenshtein 编辑距离代替 AI 模型
4
- */
5
- export function createMockPlatform() {
6
- return {
7
- async similarity(text1, text2) {
8
- return levenshteinSimilarity(text1, text2);
9
- },
10
- async timer(key, durationMs) {
11
- return new Promise((resolve) => {
12
- setTimeout(() => { console.log(`[mock] timer "${key}"`); resolve(); }, durationMs);
13
- });
14
- },
15
- async tts(text, options) {
16
- console.log(`[mock][tts][${options?.priority ?? "normal"}] ${text}`);
17
- },
18
- async 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
- async call(method, ...args) {
23
- console.log(`[mock] platform.call("${method}")`, args);
24
- throw new Error(`Mock 不支持动态能力: ${method}`);
25
- },
26
- };
27
- }
28
- /** Levenshtein 编辑距离相似度(0~1) */
29
- function levenshteinSimilarity(a, b) {
30
- const s1 = a.trim();
31
- const s2 = b.trim();
32
- if (s1 === s2)
33
- return 1;
34
- if (s1.length === 0 || s2.length === 0)
35
- return 0;
36
- const prev = Array.from({ length: s2.length + 1 }, (_, i) => i);
37
- const curr = new Array(s2.length + 1).fill(0);
38
- for (let i = 1; i <= s1.length; i++) {
39
- curr[0] = i;
40
- for (let j = 1; j <= s2.length; j++) {
41
- const cost = s1[i - 1] === s2[j - 1] ? 0 : 1;
42
- curr[j] = Math.min(prev[j] + 1, curr[j - 1] + 1, prev[j - 1] + cost);
43
- }
44
- for (let k = 0; k <= s2.length; k++)
45
- prev[k] = curr[k];
46
- curr.fill(0);
47
- }
48
- return 1 - prev[s2.length] / Math.max(s1.length, s2.length);
49
- }
@@ -1,2 +0,0 @@
1
- import type { ReportAPI } from '../types.js';
2
- export declare function createMockReport(): ReportAPI;
@@ -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
- }
@@ -1,2 +0,0 @@
1
- import type { StorageAPI } from '../types.js';
2
- export declare function createMockStorage(): StorageAPI;