@wovoon/polaris 0.6.4 → 0.10.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/PROTOCOL.md CHANGED
@@ -4,6 +4,10 @@
4
4
  > 版本规则:协议字段一经发布**只加不改不删**;破坏性变更必须升协议版本号。
5
5
  > 本协议面向人类与 AI coding 工具同等优化:任何 LLM 依据本文档即可完成开发与改造。
6
6
 
7
+ > 协议 1 新增可选常驻玩法子协议 `wovoon.game/1`,其规范见 [平台玩法契约](docs/recipes/platform-game-mode.md)。旧房间接口保留;新玩法须确认目标环境已部署,声明 `gamelogic` 并导出 `gameProtocol=1` 后才启用新限频、快照与恢复语义。
8
+
9
+ > 可选 `commerce` 能力统一商品购买和权益,见 [游戏购买契约](docs/recipes/game-commerce.md)。客户端不能发货;权威消费使用平台事务。共享扩展的 `apiVersion:2` 契约校验同步 JSON 参数与返回值,旧描述式契约继续保留。
10
+
7
11
  ## 1. 包契约(Package Contract)
8
12
 
9
13
  作品以静态归档提交(ZIP / TAR.GZ / TGZ,≤2 GB),须满足:
@@ -43,6 +47,7 @@
43
47
  | `collection:<name>` | 数据集合:带权限规则(读 WORLD/PLAYER,写 OWNER/SERVER)的 JSON 文档 CRUD 与排序查询 | 已实现 |
44
48
  | `function` | 云函数:服务端权威逻辑(受限 Node 沙箱) | 已实现 |
45
49
  | `room` | 房间实时通道:WebSocket 消息中继(多人在线) | 已实现 |
50
+ | `ads` | 可选作品广告容器:宿主按作品租约、平台配置和格式选择已授权广告源;无源立即跳过,不影响游戏 | SDK 0.8.0;Android 横幅/插屏/服务端校验激励,网页无源跳过 |
46
51
 
47
52
  - 未知顶层字段、非法能力名、非法 JSON、不支持协议版本 → **上传扫描直接拒绝**,报错信息包含修复指引;
48
53
  - 能力声明将在对应服务上线后成为**调用前置条件**(未声明则接口拒绝)。
@@ -55,6 +60,13 @@
55
60
 
56
61
  ## 4. 能力契约(Capability APIs)
57
62
 
63
+ 作品广告通过 `WovoonPolaris.ads.capabilities()`、`show()`、`mountBanner()` 调用,
64
+ 独立于 `identity`。宿主处理权限、聚合位、频控、加载与关闭;作品仅提供场景名和
65
+ 横幅容器,不提供广告源或价格。网页未授权时返回 `unavailable`,不得回退到模拟广告。
66
+ 激励广告必须配置服务端验证与作品奖励规则,只信任服务端账本回执。缺配置时 `rewarded` 为 `false`。
67
+ `rewardStatus / rewardBalances / consumeReward` 用于查询与幂等使用作品奖励,见 [激励广告](docs/rewarded-ads.md);开屏由 App 管理。
68
+ 完整接口、结果和暂停恢复约定见 [作品广告容器](docs/ads.md)。
69
+
58
70
  协议 1 的能力 API 面由 `@wovoon/polaris` SDK(本仓库)承载,数据形状:
59
71
 
60
72
  - `identity`:`POST /api/cloud/session` → `{appId, playerId, loggedIn, displayName, avatarUrl}`;
@@ -71,13 +83,14 @@
71
83
  ## 云函数(function,协议 1)
72
84
 
73
85
  - 作品包站点根下 `functions/<name>.js`(CommonJS),文件名即函数名(2-31 位小写字母开头);
74
- - 每作品最多 16 个、单文件 64KB、总量 256KB;`.wovoon` 声明 `function` 能力即可调用;
86
+ - 每作品最多 16 个;云函数源码不设单文件或累计字节配额。作品归档的整体上传/展开规则与沙箱执行资源规则独立适用;`.wovoon` 声明 `function` 能力即可调用;
75
87
  - 形态:`exports.main = async (event, context) => (任意 JSON)`;入参/返回 ≤32KB;
76
88
  - 沙箱:默认限时 3s,声明可到 60s;最多 16 个并发执行。作品进程无网络、无平台环境变量和数据令牌,通过受信任代理读写集合。Linux 使用只读 Docker 容器(128 MB、0.5 CPU、16 PID);macOS 本地开发使用系统沙箱和 Node 权限模型(64 MB V8 堆,非总内存配额);
77
89
  - `context`:`{ player: {playerId, loggedIn}, cloud: { collection(name): {query, add, set} } }`;
78
90
  - 数据面写权限:仅 `writeRule=SERVER` 的集合(创作者经 manage 接口设置),玩家对该类集合只读;
79
91
  - 计量:作品日调用 200,000 次上限,玩家 30 次/分钟;调用接口 `POST /api/cloud/{app}/functions/{name}`;
80
- - 声明式集合:包站点根 `collections.json`(`{"集合名":{"read":"WORLD|PLAYER","write":"OWNER|SERVER"}}`,≤8 条,64KB),发布时自动创建/对齐权限——AI 工具零控制台交互路径;
92
+ - 声明式集合:包站点根 `collections.json`(`{"集合名":{"read":"WORLD|PLAYER","write":"OWNER|SERVER"}}`,256 KiB,集合数量受套餐配额约束且声明不超过 1024 条),发布时自动创建/对齐权限——AI 工具零控制台交互路径;
93
+ - 发布预检与实际发布共用云能力包结构规则:检查站点根下的函数路径、名称、数量、非空源码,以及集合 JSON/权限;不执行创作者源码。在线保存函数同样不限制源码大小。
81
94
  - 控制台在线管理(创作者登录态):`/api/cloud/manage/{app}/functions` 列表 / `PUT` 保存即部署 / `DELETE` / `POST .../test` 测试调用(系统身份);保存会重新读取函数自描述元数据;
82
95
  - 常驻化声明(写在函数代码内,平台静态读取):`exports.timeoutMs`(1s~60s 长任务档)、
83
96
  `exports.cron`(五字段 cron,分钟粒度调度,事件 `{type:'cron',scheduledAt}`)、
package/dist/ads.d.ts ADDED
@@ -0,0 +1,77 @@
1
+ /** Optional host capability. Browsers and older/iOS hosts without an approved source skip immediately. */
2
+ export type PolarisAdFormat = "banner" | "interstitial" | "rewarded";
3
+ export type PolarisAdStatus = "shown" | "closed" | "unavailable" | "no_fill" | "busy" | "frequency_capped" | "cancelled" | "error";
4
+ export interface PolarisRewardReceipt {
5
+ requestId: string;
6
+ status: "pending" | "granted" | "expired";
7
+ rewardKey: string;
8
+ rewardName: string;
9
+ amount: number;
10
+ grantedAt: string | null;
11
+ }
12
+ export interface PolarisRewardBalance {
13
+ rewardKey: string;
14
+ balance: number;
15
+ }
16
+ export interface PolarisRewardSpend {
17
+ clientId: string;
18
+ rewardKey: string;
19
+ amount: number;
20
+ balanceAfter: number;
21
+ }
22
+ export interface PolarisAdResult {
23
+ status: PolarisAdStatus;
24
+ reason?: string;
25
+ requestId?: string;
26
+ rewarded: boolean;
27
+ reward?: PolarisRewardReceipt;
28
+ }
29
+ export type PolarisRewardRequest = (action: "status" | "balances" | "consume", body: object) => Promise<unknown>;
30
+ export interface PolarisAdCapabilities {
31
+ surface: "android" | "web";
32
+ banner: boolean;
33
+ interstitial: boolean;
34
+ rewarded: boolean;
35
+ reason?: string;
36
+ }
37
+ export interface PolarisAdOptions {
38
+ /** Stable scene name, not a network ad-unit ID. */
39
+ placement: string;
40
+ onPause?: () => void;
41
+ onResume?: () => void;
42
+ }
43
+ export interface PolarisBanner {
44
+ ready: Promise<PolarisAdResult>;
45
+ closed: Promise<PolarisAdResult>;
46
+ destroy(): void;
47
+ }
48
+ export declare class PolarisAds {
49
+ private readonly host;
50
+ private readonly rewardRequest?;
51
+ private readonly releases;
52
+ private generation;
53
+ constructor(host?: typeof globalThis, rewardRequest?: PolarisRewardRequest | undefined);
54
+ private bridge;
55
+ capabilities(): Promise<PolarisAdCapabilities>;
56
+ show(options: PolarisAdOptions & {
57
+ format: "interstitial" | "rewarded";
58
+ }): Promise<PolarisAdResult>;
59
+ /** Query after a delayed callback, reconnect or reload. Reading a receipt never grants it again. */
60
+ rewardStatus(requestId: string): Promise<PolarisRewardReceipt>;
61
+ /** Durable, work-scoped virtual balances are available on web as well as Android. */
62
+ rewardBalances(): Promise<PolarisRewardBalance[]>;
63
+ /** Keep clientId for retries after uncertain network results. Never generate a new ID for a retry. */
64
+ consumeReward(input: {
65
+ clientId: string;
66
+ rewardKey: string;
67
+ amount: number;
68
+ }): Promise<PolarisRewardSpend>;
69
+ private queryReward;
70
+ mountBanner(container: HTMLElement, options: Pick<PolarisAdOptions, "placement">): PolarisBanner;
71
+ /** Cancel outstanding requests when a game scene/client is replaced. */
72
+ dispose(): void;
73
+ private validPlacement;
74
+ private result;
75
+ private finished;
76
+ private open;
77
+ }
package/dist/ads.js ADDED
@@ -0,0 +1,228 @@
1
+ export class PolarisAds {
2
+ constructor(host = globalThis, rewardRequest) {
3
+ this.host = host;
4
+ this.rewardRequest = rewardRequest;
5
+ this.releases = new Set();
6
+ this.generation = 0;
7
+ }
8
+ bridge() {
9
+ const bridge = this.host.WovoonNativeAds;
10
+ return bridge && typeof bridge.postMessage === "function" &&
11
+ typeof bridge.addEventListener === "function" && typeof bridge.removeEventListener === "function" ? bridge : undefined;
12
+ }
13
+ async capabilities() {
14
+ if (!this.bridge())
15
+ return { surface: "web", banner: false, interstitial: false, rewarded: false, reason: "NO_AUTHORIZED_SOURCE" };
16
+ const response = await this.open("capabilities", {}).ready;
17
+ const value = response;
18
+ return { surface: "android", banner: value.banner === true, interstitial: value.interstitial === true,
19
+ rewarded: !!this.rewardRequest && value.rewarded === true && value.rewardProtocol === 1,
20
+ ...(value.reason ? { reason: value.reason } : {}) };
21
+ }
22
+ show(options) {
23
+ if (!options || !["interstitial", "rewarded"].includes(options.format) || !this.validPlacement(options.placement)) {
24
+ return Promise.resolve(this.result("error", "INVALID_ARGUMENT"));
25
+ }
26
+ const generation = this.generation;
27
+ return this.open("show", { format: options.format, placement: options.placement }, options).closed.then(async (result) => {
28
+ if (generation !== this.generation)
29
+ return this.result("cancelled");
30
+ if (options.format !== "rewarded" || !result.requestId || result.status !== "closed")
31
+ return result;
32
+ try {
33
+ const reward = await this.rewardStatus(result.requestId);
34
+ if (generation !== this.generation)
35
+ return this.result("cancelled");
36
+ return { ...result, rewarded: reward.status === "granted", reward,
37
+ ...(reward.status === "pending" ? { reason: "REWARD_PENDING" } : {}) };
38
+ }
39
+ catch {
40
+ if (generation !== this.generation)
41
+ return this.result("cancelled");
42
+ // Preserve the request ID for recovery. An unavailable query is never reported as a missing reward.
43
+ return { ...result, rewarded: false, reason: "REWARD_STATUS_UNAVAILABLE" };
44
+ }
45
+ });
46
+ }
47
+ /** Query after a delayed callback, reconnect or reload. Reading a receipt never grants it again. */
48
+ async rewardStatus(requestId) {
49
+ if (!/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(requestId))
50
+ throw new Error("INVALID_REWARD_REQUEST");
51
+ const value = await this.queryReward("status", { requestId });
52
+ if (!value || value.requestId !== requestId || !["pending", "granted", "expired"].includes(value.status) ||
53
+ !this.validPlacement(value.rewardKey) || typeof value.rewardName !== "string" ||
54
+ !Number.isInteger(value.amount) || value.amount < 1 || value.amount > 10000 ||
55
+ (value.status === "granted" && (typeof value.grantedAt !== "string" || !Number.isFinite(Date.parse(value.grantedAt))))) {
56
+ throw new Error("INVALID_REWARD_RECEIPT");
57
+ }
58
+ return value;
59
+ }
60
+ /** Durable, work-scoped virtual balances are available on web as well as Android. */
61
+ async rewardBalances() {
62
+ const value = await this.queryReward("balances", {});
63
+ if (!Array.isArray(value) || value.some(item => !item || !this.validPlacement(item.rewardKey) ||
64
+ !Number.isSafeInteger(item.balance) || item.balance < 0))
65
+ throw new Error("INVALID_REWARD_BALANCE");
66
+ return value;
67
+ }
68
+ /** Keep clientId for retries after uncertain network results. Never generate a new ID for a retry. */
69
+ async consumeReward(input) {
70
+ if (!input || !/^[A-Za-z0-9_-]{1,96}$/.test(input.clientId) || !this.validPlacement(input.rewardKey) ||
71
+ !Number.isInteger(input.amount) || input.amount < 1 || input.amount > 10000)
72
+ throw new Error("INVALID_REWARD_CONSUME");
73
+ const value = await this.queryReward("consume", input);
74
+ if (!value || value.clientId !== input.clientId || value.rewardKey !== input.rewardKey || value.amount !== input.amount ||
75
+ !Number.isSafeInteger(value.balanceAfter) || value.balanceAfter < 0)
76
+ throw new Error("INVALID_REWARD_SPEND");
77
+ return value;
78
+ }
79
+ async queryReward(action, input) {
80
+ if (!this.rewardRequest)
81
+ throw new Error("REWARD_API_UNAVAILABLE");
82
+ let timer;
83
+ const generation = this.generation;
84
+ try {
85
+ const result = await Promise.race([this.rewardRequest(action, input), new Promise((_, reject) => {
86
+ timer = this.host.setTimeout(() => reject(new Error("REWARD_QUERY_TIMEOUT")), 8000);
87
+ })]);
88
+ if (generation !== this.generation)
89
+ throw new Error("REWARD_CONTEXT_CHANGED");
90
+ return result;
91
+ }
92
+ finally {
93
+ if (timer !== undefined)
94
+ this.host.clearTimeout(timer);
95
+ }
96
+ }
97
+ mountBanner(container, options) {
98
+ // No DOM mutation, network request, timer or empty placeholder when no source exists.
99
+ if (!this.bridge())
100
+ return this.finished(this.result("unavailable", "NO_AUTHORIZED_SOURCE"));
101
+ if (!container || typeof container.getBoundingClientRect !== "function" || !this.validPlacement(options?.placement)) {
102
+ return this.finished(this.result("error", "INVALID_ARGUMENT"));
103
+ }
104
+ const rect = () => {
105
+ const b = container.getBoundingClientRect();
106
+ const style = this.host.getComputedStyle(container);
107
+ const visible = container.isConnected && this.host.document.visibilityState === "visible" &&
108
+ style.visibility === "visible" && style.display !== "none" && Number(style.opacity) > 0 &&
109
+ b.top >= 0 && b.left >= 0 && b.bottom <= this.host.innerHeight && b.right <= this.host.innerWidth;
110
+ return { x: b.left, y: b.top, width: b.width, height: b.height,
111
+ viewportWidth: this.host.innerWidth, viewportHeight: this.host.innerHeight, visible };
112
+ };
113
+ const first = rect();
114
+ if (!first.visible || first.width < 320 || first.height < 50) {
115
+ return this.finished(this.result("unavailable", "CONTAINER_NOT_VISIBLE"));
116
+ }
117
+ const handle = this.open("show", { format: "banner", placement: options.placement, rect: first });
118
+ const update = () => handle.send("resize", { rect: rect() });
119
+ // Native expires the view if geometry stops arriving (navigation, frozen/hidden document).
120
+ const timer = this.host.setInterval(update, 500);
121
+ this.host.addEventListener("scroll", update, true);
122
+ this.host.addEventListener("resize", update);
123
+ this.host.document.addEventListener("visibilitychange", update);
124
+ void handle.closed.then(() => {
125
+ this.host.clearInterval(timer);
126
+ this.host.removeEventListener("scroll", update, true);
127
+ this.host.removeEventListener("resize", update);
128
+ this.host.document.removeEventListener("visibilitychange", update);
129
+ });
130
+ return handle;
131
+ }
132
+ /** Cancel outstanding requests when a game scene/client is replaced. */
133
+ dispose() { this.generation++; for (const release of [...this.releases])
134
+ release(); }
135
+ validPlacement(value) { return typeof value === "string" && /^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/.test(value); }
136
+ result(status, reason) { return { status, ...(reason ? { reason } : {}), rewarded: false }; }
137
+ finished(value) { return { ready: Promise.resolve(value), closed: Promise.resolve(value), destroy() { }, send(_action, _params) { } }; }
138
+ open(action, params, options) {
139
+ const bridge = this.bridge();
140
+ if (!bridge)
141
+ return this.finished(this.result("unavailable", "NO_AUTHORIZED_SOURCE"));
142
+ const id = `ad-${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`;
143
+ let resolveReady;
144
+ let resolveClosed;
145
+ const ready = new Promise(r => { resolveReady = r; });
146
+ const closed = new Promise(r => { resolveClosed = r; });
147
+ let done = false, paused = false;
148
+ const callback = (fn) => { try {
149
+ fn?.();
150
+ }
151
+ catch { /* game callbacks cannot break cleanup */ } };
152
+ const send = (nextAction, value = {}) => {
153
+ if (!done)
154
+ bridge.postMessage(JSON.stringify({ channel: "wovoon:ads:v1", id, action: nextAction, ...value }));
155
+ };
156
+ const finish = (result) => {
157
+ if (done)
158
+ return;
159
+ done = true;
160
+ this.host.clearTimeout(timer);
161
+ bridge.removeEventListener("message", listener);
162
+ this.releases.delete(destroy);
163
+ this.host.removeEventListener?.("pagehide", destroy);
164
+ resolveReady(result);
165
+ resolveClosed(result);
166
+ if (paused)
167
+ callback(options?.onResume);
168
+ };
169
+ const destroy = () => {
170
+ try {
171
+ send("destroy");
172
+ }
173
+ catch { /* a detached native port is already unavailable */ }
174
+ finally {
175
+ finish(this.result("cancelled"));
176
+ }
177
+ };
178
+ const listener = (event) => {
179
+ let value;
180
+ try {
181
+ value = JSON.parse(event.data);
182
+ }
183
+ catch {
184
+ return;
185
+ }
186
+ if (!value || value.channel !== "wovoon:ads:v1" || value.id !== id || done)
187
+ return;
188
+ if (value.event === "presenting") {
189
+ this.host.clearTimeout(timer);
190
+ if (!paused) {
191
+ paused = true;
192
+ callback(options?.onPause);
193
+ }
194
+ return;
195
+ }
196
+ const result = value.result;
197
+ if (!result || !["shown", "closed", "unavailable", "no_fill", "busy", "frequency_capped", "cancelled", "error"].includes(result.status))
198
+ return;
199
+ // A JS/native callback is never proof of a server-verified reward.
200
+ const safe = { ...result, rewarded: action === "capabilities" && result.rewarded === true };
201
+ delete safe.reward;
202
+ if (value.event === "shown" && action !== "capabilities") {
203
+ resolveReady(safe);
204
+ this.host.clearTimeout(timer);
205
+ }
206
+ else
207
+ finish(safe);
208
+ };
209
+ const timer = this.host.setTimeout(() => {
210
+ try {
211
+ send("destroy");
212
+ }
213
+ finally {
214
+ finish(this.result("unavailable", "HOST_TIMEOUT"));
215
+ }
216
+ }, action === "capabilities" ? 6000 : 30000);
217
+ bridge.addEventListener("message", listener);
218
+ this.releases.add(destroy);
219
+ this.host.addEventListener?.("pagehide", destroy);
220
+ try {
221
+ send(action, params);
222
+ }
223
+ catch {
224
+ finish(this.result("unavailable", "HOST_UNAVAILABLE"));
225
+ }
226
+ return { ready, closed, destroy, send };
227
+ }
228
+ }
package/dist/client.d.ts CHANGED
@@ -3,6 +3,9 @@
3
3
  * 在作品内通过 <script> 引入平台下发的 /api/cloud/sdk.js(全局 WovoonCloud)即可使用,
4
4
  * 本模块提供同一 API 的 TypeScript 实现,供构建型项目以模块方式引入。
5
5
  */
6
+ import { PolarisAds } from "./ads.js";
7
+ import { PolarisCommerce } from "./commerce.js";
8
+ import { PolarisGame, type GameOptions } from "./game.js";
6
9
  export interface PolarisRequestInit {
7
10
  /** 覆盖 API 基址(本地模拟器/自建环境用),默认同源。 */
8
11
  baseUrl?: string;
@@ -43,6 +46,10 @@ export interface PolarisQueryOptions {
43
46
  }
44
47
  declare function parseData<T = Record<string, unknown>>(raw: string): T;
45
48
  export declare class PolarisClient {
49
+ readonly commerce: PolarisCommerce;
50
+ private readonly activeGames;
51
+ game<State = unknown>(mode: string, options: GameOptions<State>): PolarisGame<State>;
52
+ readonly ads: PolarisAds;
46
53
  private readonly baseUrl;
47
54
  private sessionPromise;
48
55
  private target;
@@ -77,6 +84,7 @@ export declare class PolarisClient {
77
84
  room(roomId: string, options?: {
78
85
  mode?: string;
79
86
  }): {
87
+ trySend: (data: unknown, maxBufferedBytes?: number) => boolean;
80
88
  send: (data: unknown) => void;
81
89
  leave: () => void;
82
90
  onMessage: (callback: (payload: {
@@ -88,6 +96,7 @@ export declare class PolarisClient {
88
96
  };
89
97
  /** 世界总线:全服事件流(权威房间 ctx.worldBroadcast 广播到此),用法同房间。 */
90
98
  world(): {
99
+ trySend: (data: unknown, maxBufferedBytes?: number) => boolean;
91
100
  send: (data: unknown) => void;
92
101
  leave: () => void;
93
102
  onMessage: (callback: (payload: {
@@ -98,7 +107,9 @@ export declare class PolarisClient {
98
107
  onClose: (callback: (payload: unknown) => void) => void;
99
108
  };
100
109
  /** 内置匹配:凑满 exports.matchSize 人成局 → resolve 目标房间号(再 room(roomId, {mode}) 进入)。 */
101
- match(mode: string): Promise<string>;
110
+ match(mode: string, options?: {
111
+ signal?: AbortSignal;
112
+ }): Promise<string>;
102
113
  /** 房间列表(大厅/分线选择)。 */
103
114
  rooms(options?: {
104
115
  mode?: string;
package/dist/client.js CHANGED
@@ -3,6 +3,10 @@
3
3
  * 在作品内通过 <script> 引入平台下发的 /api/cloud/sdk.js(全局 WovoonCloud)即可使用,
4
4
  * 本模块提供同一 API 的 TypeScript 实现,供构建型项目以模块方式引入。
5
5
  */
6
+ import { PolarisAds } from "./ads.js";
7
+ import { matchRoom } from "./match.js";
8
+ import { PolarisCommerce } from "./commerce.js";
9
+ import { PolarisGame } from "./game.js";
6
10
  export class PolarisError extends Error {
7
11
  constructor(message, code = "WOVOON_CLOUD_ERROR") {
8
12
  super(message);
@@ -19,11 +23,39 @@ function parseData(raw) {
19
23
  }
20
24
  }
21
25
  export class PolarisClient {
26
+ game(mode, options) {
27
+ this.activeGames.get(options.roomId)?.leave();
28
+ let game, ended = false;
29
+ game = new PolarisGame((id, roomOptions) => this.room(id, roomOptions), mode, { ...options, onStatus: status => {
30
+ if (status === "closed" || status === "error") {
31
+ ended = true;
32
+ if (game && this.activeGames.get(options.roomId) === game)
33
+ this.activeGames.delete(options.roomId);
34
+ }
35
+ options.onStatus?.(status);
36
+ } });
37
+ if (!ended)
38
+ this.activeGames.set(options.roomId, game);
39
+ return game;
40
+ }
22
41
  webSocketOrigin() {
23
42
  const runtime = String(globalThis.__wovoonRuntimeWsBase ?? "");
24
43
  return this.baseUrl || runtime || (typeof location === "undefined" ? "http://localhost" : location.origin);
25
44
  }
26
45
  constructor(init = {}) {
46
+ this.commerce = new PolarisCommerce((action, body) => {
47
+ const target = this.detectTarget();
48
+ if (!target)
49
+ return Promise.reject(new PolarisError("请从平台运行作品", "WOVOON_TARGET_MISSING"));
50
+ return this.request("POST", `/api/cloud/${encodeURIComponent(target)}/commerce/${action}`, body);
51
+ });
52
+ this.activeGames = new Map();
53
+ this.ads = new PolarisAds(globalThis, (action, body) => {
54
+ const target = this.detectTarget();
55
+ if (!target)
56
+ return Promise.reject(new PolarisError("请从平台运行作品", "WOVOON_TARGET_MISSING"));
57
+ return this.request("POST", `/api/cloud/${encodeURIComponent(target)}/ad-rewards/${action}`, body);
58
+ });
27
59
  this.sessionPromise = null;
28
60
  this.target = "";
29
61
  this.collectionsWatch = { listeners: [], socket: null, pending: false, generation: 0 };
@@ -33,6 +65,10 @@ export class PolarisClient {
33
65
  }
34
66
  /** 指定作品目标:deploymentId(运行地址自动识别)或 appId。 */
35
67
  configure(options) {
68
+ this.ads.dispose();
69
+ for (const game of this.activeGames.values())
70
+ game.leave();
71
+ this.activeGames.clear();
36
72
  for (const room of this.activeRooms.values())
37
73
  room.leave();
38
74
  this.collectionsWatch.generation++;
@@ -139,6 +175,21 @@ export class PolarisClient {
139
175
  }
140
176
  };
141
177
  const handle = {
178
+ trySend: (data, maxBufferedBytes = 64 * 1024) => {
179
+ if (!socket || socket.readyState !== 1 || left)
180
+ return false;
181
+ const text = JSON.stringify({ type: "msg", data });
182
+ const bytes = new TextEncoder().encode(text).byteLength;
183
+ if (bytes > 8 * 1024 || (socket.bufferedAmount || 0) + bytes > maxBufferedBytes)
184
+ return false;
185
+ try {
186
+ socket.send(text);
187
+ return true;
188
+ }
189
+ catch {
190
+ return false;
191
+ }
192
+ },
142
193
  send: (data) => {
143
194
  if (!socket || socket.readyState !== 1)
144
195
  return;
@@ -230,37 +281,8 @@ export class PolarisClient {
230
281
  return this.room("__world");
231
282
  }
232
283
  /** 内置匹配:凑满 exports.matchSize 人成局 → resolve 目标房间号(再 room(roomId, {mode}) 进入)。 */
233
- match(mode) {
234
- if (!mode)
235
- throw new PolarisError("match(mode) 需要模式名", "WOVOON_ARGUMENT");
236
- return new Promise((resolve, reject) => {
237
- this.session().then(() => {
238
- const queue = this.room(`__match_${mode}`);
239
- let done = false;
240
- const timer = setTimeout(() => {
241
- if (done)
242
- return;
243
- done = true;
244
- try {
245
- queue.leave();
246
- }
247
- catch { /* 已关 */ }
248
- reject(new PolarisError("匹配等待超时(120 秒)", "WOVOON_MATCH_TIMEOUT"));
249
- }, 120000);
250
- queue.onMessage((payload) => {
251
- const frame = payload;
252
- if (done || frame?.type !== "matched" || !frame.roomId)
253
- return;
254
- done = true;
255
- clearTimeout(timer);
256
- try {
257
- queue.leave();
258
- }
259
- catch { /* 已关 */ }
260
- resolve(frame.roomId);
261
- });
262
- }).catch(reject);
263
- });
284
+ match(mode, options) {
285
+ return this.session().then(data => matchRoom(mode, () => this.room(`__match_${mode}`), action => this.request("POST", `/api/cloud/${data.appId}/match/${action}`, { mode }), options?.signal));
264
286
  }
265
287
  /** 房间列表(大厅/分线选择)。 */
266
288
  rooms(options) {
@@ -0,0 +1,59 @@
1
+ /** All ownership comes from authenticated server receipts; returning from a payment page proves nothing. */
2
+ export interface PurchaseOrder {
3
+ orderId: string;
4
+ orderNo: string;
5
+ status: string;
6
+ appId: string;
7
+ productId: string;
8
+ amountCents: number;
9
+ currency: string;
10
+ expiresAt: string;
11
+ checkoutType?: string | null;
12
+ checkoutPayload?: string | null;
13
+ checkoutQrCode?: string | null;
14
+ }
15
+ export interface PurchaseProduct {
16
+ productCode: string;
17
+ name: string;
18
+ productType: "ONE_TIME" | "CONSUMABLE";
19
+ priceCents: number;
20
+ currency: string;
21
+ }
22
+ export interface PurchaseEntitlement {
23
+ productCode: string;
24
+ productType: "ONE_TIME" | "CONSUMABLE";
25
+ quantity: number;
26
+ }
27
+ type Request = (action: string, body: object) => Promise<unknown>;
28
+ interface CommerceBridge {
29
+ postMessage(value: string): void;
30
+ addEventListener(type: string, listener: (event: {
31
+ data: string;
32
+ }) => void): void;
33
+ removeEventListener(type: string, listener: (event: {
34
+ data: string;
35
+ }) => void): void;
36
+ }
37
+ type CommerceHost = typeof globalThis & {
38
+ WovoonNativeCommerce?: CommerceBridge;
39
+ };
40
+ /** Native responses describe presentation only; callers must still query the platform order. */
41
+ export declare function openNativePurchase(orderId: string, host?: CommerceHost): Promise<string>;
42
+ export declare class PolarisCommerce {
43
+ private readonly request;
44
+ constructor(request: Request);
45
+ catalog(): Promise<{
46
+ products: PurchaseProduct[];
47
+ providers: Record<string, boolean>;
48
+ }>;
49
+ entitlements(): Promise<PurchaseEntitlement[]>;
50
+ checkout(productCode: string, options: {
51
+ provider: "ALIPAY" | "WECHAT_PAY";
52
+ idempotencyKey: string;
53
+ }): Promise<PurchaseOrder>;
54
+ order(orderId: string): Promise<PurchaseOrder>;
55
+ /** Built-in checkout presentation. Closing it does not cancel/refund a provider order. */
56
+ present(order: PurchaseOrder, host?: typeof globalThis): Promise<PurchaseOrder>;
57
+ private receipt;
58
+ }
59
+ export {};