@wovoon/polaris 0.8.1 → 0.15.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 +9 -11
- package/dist/ads.d.ts +10 -10
- package/dist/ads.js +52 -45
- package/dist/client.d.ts +10 -6
- package/dist/client.js +46 -32
- package/dist/commerce.d.ts +61 -0
- package/dist/commerce.js +176 -0
- package/dist/game-sync.d.ts +31 -0
- package/dist/game-sync.js +90 -0
- package/dist/game.d.ts +82 -0
- package/dist/game.js +194 -0
- package/dist/index.d.ts +6 -3
- package/dist/index.js +4 -1
- package/dist/match.d.ts +10 -0
- package/dist/match.js +74 -0
- package/dist/protocol.d.ts +3 -1
- package/dist/protocol.js +1 -1
- package/docs/ads.md +13 -68
- package/docs/cli.md +24 -11
- package/docs/errors.md +1 -1
- package/docs/local-scenarios.md +22 -0
- package/docs/manifest.md +5 -3
- package/docs/quickstart.md +1 -1
- package/docs/recipes/competitive-games.md +16 -44
- package/docs/recipes/game-commerce.md +65 -0
- package/docs/recipes/platform-game-mode.md +119 -0
- package/docs/recipes/rewarded-placement.md +6 -4
- package/docs/remote-preview.md +45 -0
- package/docs/rewarded-ads.md +21 -21
- package/docs/sdk.md +2 -3
- package/llms.txt +13 -7
- package/package.json +2 -2
package/PROTOCOL.md
CHANGED
|
@@ -1,9 +1,13 @@
|
|
|
1
1
|
# wovoon 平台协议 v1(Polaris)
|
|
2
2
|
|
|
3
3
|
> 本文件是 wovoon 开发者协议的**正典定义**(canonical spec)。前端永远静态托管;后端能力由 wovoon 大后台按本协议提供。
|
|
4
|
-
>
|
|
4
|
+
> 版本规则:使用能力前须核对 SDK 版本、当前能力列表和宿主支持;退役能力不提供空实现,作品升级时须同步更新声明及调用。
|
|
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,7 +47,7 @@
|
|
|
43
47
|
| `collection:<name>` | 数据集合:带权限规则(读 WORLD/PLAYER,写 OWNER/SERVER)的 JSON 文档 CRUD 与排序查询 | 已实现 |
|
|
44
48
|
| `function` | 云函数:服务端权威逻辑(受限 Node 沙箱) | 已实现 |
|
|
45
49
|
| `room` | 房间实时通道:WebSocket 消息中继(多人在线) | 已实现 |
|
|
46
|
-
| `ads` |
|
|
50
|
+
| `ads` | 作品激励广告:GroMore 原生 Android 广告与服务端验签奖励;顷悟提供隔离的模拟预览,不提供作品横幅或插屏 | SDK 0.15 / CLI 0.22,需对应运行时 |
|
|
47
51
|
|
|
48
52
|
- 未知顶层字段、非法能力名、非法 JSON、不支持协议版本 → **上传扫描直接拒绝**,报错信息包含修复指引;
|
|
49
53
|
- 能力声明将在对应服务上线后成为**调用前置条件**(未声明则接口拒绝)。
|
|
@@ -56,13 +60,6 @@
|
|
|
56
60
|
|
|
57
61
|
## 4. 能力契约(Capability APIs)
|
|
58
62
|
|
|
59
|
-
作品广告通过 `WovoonPolaris.ads.capabilities()`、`show()`、`mountBanner()` 调用,
|
|
60
|
-
独立于 `identity`。宿主处理权限、聚合位、频控、加载与关闭;作品仅提供场景名和
|
|
61
|
-
横幅容器,不提供广告源或价格。网页未授权时返回 `unavailable`,不得回退到模拟广告。
|
|
62
|
-
激励广告必须配置服务端验证与作品奖励规则,只信任服务端账本回执。缺配置时 `rewarded` 为 `false`。
|
|
63
|
-
`rewardStatus / rewardBalances / consumeReward` 用于查询与幂等使用作品奖励,见 [激励广告](docs/rewarded-ads.md);开屏由 App 管理。
|
|
64
|
-
完整接口、结果和暂停恢复约定见 [作品广告容器](docs/ads.md)。
|
|
65
|
-
|
|
66
63
|
协议 1 的能力 API 面由 `@wovoon/polaris` SDK(本仓库)承载,数据形状:
|
|
67
64
|
|
|
68
65
|
- `identity`:`POST /api/cloud/session` → `{appId, playerId, loggedIn, displayName, avatarUrl}`;
|
|
@@ -79,13 +76,14 @@
|
|
|
79
76
|
## 云函数(function,协议 1)
|
|
80
77
|
|
|
81
78
|
- 作品包站点根下 `functions/<name>.js`(CommonJS),文件名即函数名(2-31 位小写字母开头);
|
|
82
|
-
- 每作品最多 16
|
|
79
|
+
- 每作品最多 16 个;云函数源码不设单文件或累计字节配额。作品归档的整体上传/展开规则与沙箱执行资源规则独立适用;`.wovoon` 声明 `function` 能力即可调用;
|
|
83
80
|
- 形态:`exports.main = async (event, context) => (任意 JSON)`;入参/返回 ≤32KB;
|
|
84
81
|
- 沙箱:默认限时 3s,声明可到 60s;最多 16 个并发执行。作品进程无网络、无平台环境变量和数据令牌,通过受信任代理读写集合。Linux 使用只读 Docker 容器(128 MB、0.5 CPU、16 PID);macOS 本地开发使用系统沙箱和 Node 权限模型(64 MB V8 堆,非总内存配额);
|
|
85
82
|
- `context`:`{ player: {playerId, loggedIn}, cloud: { collection(name): {query, add, set} } }`;
|
|
86
83
|
- 数据面写权限:仅 `writeRule=SERVER` 的集合(创作者经 manage 接口设置),玩家对该类集合只读;
|
|
87
84
|
- 计量:作品日调用 200,000 次上限,玩家 30 次/分钟;调用接口 `POST /api/cloud/{app}/functions/{name}`;
|
|
88
|
-
- 声明式集合:包站点根 `collections.json`(`{"集合名":{"read":"WORLD|PLAYER","write":"OWNER|SERVER"}}
|
|
85
|
+
- 声明式集合:包站点根 `collections.json`(`{"集合名":{"read":"WORLD|PLAYER","write":"OWNER|SERVER"}}`,256 KiB,集合数量受套餐配额约束且声明不超过 1024 条),发布时自动创建/对齐权限——AI 工具零控制台交互路径;
|
|
86
|
+
- 发布预检与实际发布共用云能力包结构规则:检查站点根下的函数路径、名称、数量、非空源码,以及集合 JSON/权限;不执行创作者源码。在线保存函数同样不限制源码大小。
|
|
89
87
|
- 控制台在线管理(创作者登录态):`/api/cloud/manage/{app}/functions` 列表 / `PUT` 保存即部署 / `DELETE` / `POST .../test` 测试调用(系统身份);保存会重新读取函数自描述元数据;
|
|
90
88
|
- 常驻化声明(写在函数代码内,平台静态读取):`exports.timeoutMs`(1s~60s 长任务档)、
|
|
91
89
|
`exports.cron`(五字段 cron,分钟粒度调度,事件 `{type:'cron',scheduledAt}`)、
|
package/dist/ads.d.ts
CHANGED
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
/** Optional host capability. Browsers and older/iOS hosts without an approved source skip immediately. */
|
|
2
|
-
export type PolarisAdFormat = "
|
|
2
|
+
export type PolarisAdFormat = "rewarded";
|
|
3
3
|
export type PolarisAdStatus = "shown" | "closed" | "unavailable" | "no_fill" | "busy" | "frequency_capped" | "cancelled" | "error";
|
|
4
4
|
export interface PolarisRewardReceipt {
|
|
5
|
+
simulated?: boolean;
|
|
5
6
|
requestId: string;
|
|
6
7
|
status: "pending" | "granted" | "expired";
|
|
7
8
|
rewardKey: string;
|
|
@@ -20,6 +21,7 @@ export interface PolarisRewardSpend {
|
|
|
20
21
|
balanceAfter: number;
|
|
21
22
|
}
|
|
22
23
|
export interface PolarisAdResult {
|
|
24
|
+
simulated?: boolean;
|
|
23
25
|
status: PolarisAdStatus;
|
|
24
26
|
reason?: string;
|
|
25
27
|
requestId?: string;
|
|
@@ -28,11 +30,14 @@ export interface PolarisAdResult {
|
|
|
28
30
|
}
|
|
29
31
|
export type PolarisRewardRequest = (action: "status" | "balances" | "consume", body: object) => Promise<unknown>;
|
|
30
32
|
export interface PolarisAdCapabilities {
|
|
31
|
-
|
|
33
|
+
simulated?: boolean;
|
|
34
|
+
surface: "android" | "ios" | "web" | "preview";
|
|
32
35
|
banner: boolean;
|
|
33
36
|
interstitial: boolean;
|
|
34
37
|
rewarded: boolean;
|
|
35
38
|
reason?: string;
|
|
39
|
+
/** A preview host tests the public contract; it is never native-device acceptance. */
|
|
40
|
+
previewTarget?: "web" | "mobile";
|
|
36
41
|
}
|
|
37
42
|
export interface PolarisAdOptions {
|
|
38
43
|
/** Stable scene name, not a network ad-unit ID. */
|
|
@@ -40,11 +45,6 @@ export interface PolarisAdOptions {
|
|
|
40
45
|
onPause?: () => void;
|
|
41
46
|
onResume?: () => void;
|
|
42
47
|
}
|
|
43
|
-
export interface PolarisBanner {
|
|
44
|
-
ready: Promise<PolarisAdResult>;
|
|
45
|
-
closed: Promise<PolarisAdResult>;
|
|
46
|
-
destroy(): void;
|
|
47
|
-
}
|
|
48
48
|
export declare class PolarisAds {
|
|
49
49
|
private readonly host;
|
|
50
50
|
private readonly rewardRequest?;
|
|
@@ -54,10 +54,11 @@ export declare class PolarisAds {
|
|
|
54
54
|
private bridge;
|
|
55
55
|
capabilities(): Promise<PolarisAdCapabilities>;
|
|
56
56
|
show(options: PolarisAdOptions & {
|
|
57
|
-
format: "
|
|
57
|
+
format: "rewarded";
|
|
58
58
|
}): Promise<PolarisAdResult>;
|
|
59
59
|
/** Query after a delayed callback, reconnect or reload. Reading a receipt never grants it again. */
|
|
60
60
|
rewardStatus(requestId: string): Promise<PolarisRewardReceipt>;
|
|
61
|
+
private readReward;
|
|
61
62
|
/** Durable, work-scoped virtual balances are available on web as well as Android. */
|
|
62
63
|
rewardBalances(): Promise<PolarisRewardBalance[]>;
|
|
63
64
|
/** Keep clientId for retries after uncertain network results. Never generate a new ID for a retry. */
|
|
@@ -67,8 +68,7 @@ export declare class PolarisAds {
|
|
|
67
68
|
amount: number;
|
|
68
69
|
}): Promise<PolarisRewardSpend>;
|
|
69
70
|
private queryReward;
|
|
70
|
-
|
|
71
|
-
/** Cancel outstanding requests when a game scene/client is replaced. */
|
|
71
|
+
/** Release a request and invalidate delayed replies when the work or player changes. */
|
|
72
72
|
dispose(): void;
|
|
73
73
|
private validPlacement;
|
|
74
74
|
private result;
|
package/dist/ads.js
CHANGED
|
@@ -15,14 +15,19 @@ export class PolarisAds {
|
|
|
15
15
|
return { surface: "web", banner: false, interstitial: false, rewarded: false, reason: "NO_AUTHORIZED_SOURCE" };
|
|
16
16
|
const response = await this.open("capabilities", {}).ready;
|
|
17
17
|
const value = response;
|
|
18
|
-
|
|
18
|
+
const surface = ["android", "ios", "web", "preview"].includes(String(value.surface)) ? value.surface : "android";
|
|
19
|
+
return { surface, banner: false, interstitial: false,
|
|
20
|
+
...(surface === "preview" ? { simulated: true } : {}),
|
|
19
21
|
rewarded: !!this.rewardRequest && value.rewarded === true && value.rewardProtocol === 1,
|
|
22
|
+
...(surface === "preview" && ["web", "mobile"].includes(String(value.previewTarget)) ? { previewTarget: value.previewTarget } : {}),
|
|
20
23
|
...(value.reason ? { reason: value.reason } : {}) };
|
|
21
24
|
}
|
|
22
25
|
show(options) {
|
|
23
|
-
if (!options || !["
|
|
26
|
+
if (!options || !["rewarded"].includes(options.format) || !this.validPlacement(options.placement)) {
|
|
24
27
|
return Promise.resolve(this.result("error", "INVALID_ARGUMENT"));
|
|
25
28
|
}
|
|
29
|
+
if (options.format !== "rewarded")
|
|
30
|
+
return Promise.resolve(this.result("unavailable", "FORMAT_NOT_SUPPORTED"));
|
|
26
31
|
const generation = this.generation;
|
|
27
32
|
return this.open("show", { format: options.format, placement: options.placement }, options).closed.then(async (result) => {
|
|
28
33
|
if (generation !== this.generation)
|
|
@@ -30,11 +35,25 @@ export class PolarisAds {
|
|
|
30
35
|
if (options.format !== "rewarded" || !result.requestId || result.status !== "closed")
|
|
31
36
|
return result;
|
|
32
37
|
try {
|
|
33
|
-
|
|
38
|
+
let reward = await this.readReward(result.requestId, 2000);
|
|
39
|
+
// The native close can race the server callback. Poll the same receipt,
|
|
40
|
+
// never create another ad request or infer a grant from native/JS flags.
|
|
41
|
+
for (const delay of [250, 750, 1500]) {
|
|
42
|
+
if (reward.status !== "pending" || generation !== this.generation)
|
|
43
|
+
break;
|
|
44
|
+
await new Promise(resolve => {
|
|
45
|
+
const finish = () => { this.host.clearTimeout(timer); this.releases.delete(finish); resolve(); };
|
|
46
|
+
const timer = this.host.setTimeout(finish, delay);
|
|
47
|
+
this.releases.add(finish);
|
|
48
|
+
});
|
|
49
|
+
if (generation !== this.generation)
|
|
50
|
+
return this.result("cancelled");
|
|
51
|
+
reward = await this.readReward(result.requestId, 2000);
|
|
52
|
+
}
|
|
34
53
|
if (generation !== this.generation)
|
|
35
54
|
return this.result("cancelled");
|
|
36
55
|
return { ...result, rewarded: reward.status === "granted", reward,
|
|
37
|
-
|
|
56
|
+
reason: reward.status === "pending" ? "REWARD_PENDING" : reward.status === "expired" ? "REWARD_EXPIRED" : undefined };
|
|
38
57
|
}
|
|
39
58
|
catch {
|
|
40
59
|
if (generation !== this.generation)
|
|
@@ -46,9 +65,12 @@ export class PolarisAds {
|
|
|
46
65
|
}
|
|
47
66
|
/** Query after a delayed callback, reconnect or reload. Reading a receipt never grants it again. */
|
|
48
67
|
async rewardStatus(requestId) {
|
|
68
|
+
return this.readReward(requestId, 8000);
|
|
69
|
+
}
|
|
70
|
+
async readReward(requestId, timeout) {
|
|
49
71
|
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
72
|
throw new Error("INVALID_REWARD_REQUEST");
|
|
51
|
-
const value = await this.queryReward("status", { requestId });
|
|
73
|
+
const value = await this.queryReward("status", { requestId }, timeout);
|
|
52
74
|
if (!value || value.requestId !== requestId || !["pending", "granted", "expired"].includes(value.status) ||
|
|
53
75
|
!this.validPlacement(value.rewardKey) || typeof value.rewardName !== "string" ||
|
|
54
76
|
!Number.isInteger(value.amount) || value.amount < 1 || value.amount > 10000 ||
|
|
@@ -76,14 +98,14 @@ export class PolarisAds {
|
|
|
76
98
|
throw new Error("INVALID_REWARD_SPEND");
|
|
77
99
|
return value;
|
|
78
100
|
}
|
|
79
|
-
async queryReward(action, input) {
|
|
101
|
+
async queryReward(action, input, timeout = 8000) {
|
|
80
102
|
if (!this.rewardRequest)
|
|
81
103
|
throw new Error("REWARD_API_UNAVAILABLE");
|
|
82
104
|
let timer;
|
|
83
105
|
const generation = this.generation;
|
|
84
106
|
try {
|
|
85
107
|
const result = await Promise.race([this.rewardRequest(action, input), new Promise((_, reject) => {
|
|
86
|
-
timer = this.host.setTimeout(() => reject(new Error("REWARD_QUERY_TIMEOUT")),
|
|
108
|
+
timer = this.host.setTimeout(() => reject(new Error("REWARD_QUERY_TIMEOUT")), timeout);
|
|
87
109
|
})]);
|
|
88
110
|
if (generation !== this.generation)
|
|
89
111
|
throw new Error("REWARD_CONTEXT_CHANGED");
|
|
@@ -94,42 +116,7 @@ export class PolarisAds {
|
|
|
94
116
|
this.host.clearTimeout(timer);
|
|
95
117
|
}
|
|
96
118
|
}
|
|
97
|
-
|
|
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. */
|
|
119
|
+
/** Release a request and invalidate delayed replies when the work or player changes. */
|
|
133
120
|
dispose() { this.generation++; for (const release of [...this.releases])
|
|
134
121
|
release(); }
|
|
135
122
|
validPlacement(value) { return typeof value === "string" && /^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/.test(value); }
|
|
@@ -145,6 +132,7 @@ export class PolarisAds {
|
|
|
145
132
|
const ready = new Promise(r => { resolveReady = r; });
|
|
146
133
|
const closed = new Promise(r => { resolveClosed = r; });
|
|
147
134
|
let done = false, paused = false;
|
|
135
|
+
let phase = "initial";
|
|
148
136
|
const callback = (fn) => { try {
|
|
149
137
|
fn?.();
|
|
150
138
|
}
|
|
@@ -185,7 +173,23 @@ export class PolarisAds {
|
|
|
185
173
|
}
|
|
186
174
|
if (!value || value.channel !== "wovoon:ads:v1" || value.id !== id || done)
|
|
187
175
|
return;
|
|
176
|
+
// Reading the native reward confirmation is not SDK loading or ad presentation.
|
|
177
|
+
// Accept each transition once so duplicate host events cannot extend its deadline.
|
|
178
|
+
if (value.event === "awaiting_confirmation" && action === "show" &&
|
|
179
|
+
params.format === "rewarded" && phase === "initial") {
|
|
180
|
+
phase = "confirmation";
|
|
181
|
+
this.host.clearTimeout(timer);
|
|
182
|
+
timer = this.host.setTimeout(timeout, 300000);
|
|
183
|
+
return;
|
|
184
|
+
}
|
|
185
|
+
if (value.event === "loading" && phase === "confirmation") {
|
|
186
|
+
phase = "loading";
|
|
187
|
+
this.host.clearTimeout(timer);
|
|
188
|
+
timer = this.host.setTimeout(timeout, 30000);
|
|
189
|
+
return;
|
|
190
|
+
}
|
|
188
191
|
if (value.event === "presenting") {
|
|
192
|
+
phase = "presenting";
|
|
189
193
|
this.host.clearTimeout(timer);
|
|
190
194
|
if (!paused) {
|
|
191
195
|
paused = true;
|
|
@@ -200,20 +204,23 @@ export class PolarisAds {
|
|
|
200
204
|
const safe = { ...result, rewarded: action === "capabilities" && result.rewarded === true };
|
|
201
205
|
delete safe.reward;
|
|
202
206
|
if (value.event === "shown" && action !== "capabilities") {
|
|
207
|
+
phase = "presenting";
|
|
203
208
|
resolveReady(safe);
|
|
204
209
|
this.host.clearTimeout(timer);
|
|
205
210
|
}
|
|
206
211
|
else
|
|
207
212
|
finish(safe);
|
|
208
213
|
};
|
|
209
|
-
const
|
|
214
|
+
const timeout = () => {
|
|
210
215
|
try {
|
|
211
216
|
send("destroy");
|
|
212
217
|
}
|
|
218
|
+
catch { /* a detached host must still settle the request */ }
|
|
213
219
|
finally {
|
|
214
220
|
finish(this.result("unavailable", "HOST_TIMEOUT"));
|
|
215
221
|
}
|
|
216
|
-
}
|
|
222
|
+
};
|
|
223
|
+
let timer = this.host.setTimeout(timeout, action === "capabilities" ? 6000 : 30000);
|
|
217
224
|
bridge.addEventListener("message", listener);
|
|
218
225
|
this.releases.add(destroy);
|
|
219
226
|
this.host.addEventListener?.("pagehide", destroy);
|
package/dist/client.d.ts
CHANGED
|
@@ -1,9 +1,6 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* @wovoon/polaris 运行时客户端(协议 1)。
|
|
3
|
-
* 在作品内通过 <script> 引入平台下发的 /api/cloud/sdk.js(全局 WovoonCloud)即可使用,
|
|
4
|
-
* 本模块提供同一 API 的 TypeScript 实现,供构建型项目以模块方式引入。
|
|
5
|
-
*/
|
|
6
1
|
import { PolarisAds } from "./ads.js";
|
|
2
|
+
import { PolarisCommerce } from "./commerce.js";
|
|
3
|
+
import { PolarisGame, type GameOptions } from "./game.js";
|
|
7
4
|
export interface PolarisRequestInit {
|
|
8
5
|
/** 覆盖 API 基址(本地模拟器/自建环境用),默认同源。 */
|
|
9
6
|
baseUrl?: string;
|
|
@@ -44,6 +41,9 @@ export interface PolarisQueryOptions {
|
|
|
44
41
|
}
|
|
45
42
|
declare function parseData<T = Record<string, unknown>>(raw: string): T;
|
|
46
43
|
export declare class PolarisClient {
|
|
44
|
+
readonly commerce: PolarisCommerce;
|
|
45
|
+
private readonly activeGames;
|
|
46
|
+
game<State = unknown>(mode: string, options: GameOptions<State>): PolarisGame<State>;
|
|
47
47
|
readonly ads: PolarisAds;
|
|
48
48
|
private readonly baseUrl;
|
|
49
49
|
private sessionPromise;
|
|
@@ -79,6 +79,7 @@ export declare class PolarisClient {
|
|
|
79
79
|
room(roomId: string, options?: {
|
|
80
80
|
mode?: string;
|
|
81
81
|
}): {
|
|
82
|
+
trySend: (data: unknown, maxBufferedBytes?: number) => boolean;
|
|
82
83
|
send: (data: unknown) => void;
|
|
83
84
|
leave: () => void;
|
|
84
85
|
onMessage: (callback: (payload: {
|
|
@@ -90,6 +91,7 @@ export declare class PolarisClient {
|
|
|
90
91
|
};
|
|
91
92
|
/** 世界总线:全服事件流(权威房间 ctx.worldBroadcast 广播到此),用法同房间。 */
|
|
92
93
|
world(): {
|
|
94
|
+
trySend: (data: unknown, maxBufferedBytes?: number) => boolean;
|
|
93
95
|
send: (data: unknown) => void;
|
|
94
96
|
leave: () => void;
|
|
95
97
|
onMessage: (callback: (payload: {
|
|
@@ -100,7 +102,9 @@ export declare class PolarisClient {
|
|
|
100
102
|
onClose: (callback: (payload: unknown) => void) => void;
|
|
101
103
|
};
|
|
102
104
|
/** 内置匹配:凑满 exports.matchSize 人成局 → resolve 目标房间号(再 room(roomId, {mode}) 进入)。 */
|
|
103
|
-
match(mode: string
|
|
105
|
+
match(mode: string, options?: {
|
|
106
|
+
signal?: AbortSignal;
|
|
107
|
+
}): Promise<string>;
|
|
104
108
|
/** 房间列表(大厅/分线选择)。 */
|
|
105
109
|
rooms(options?: {
|
|
106
110
|
mode?: string;
|
package/dist/client.js
CHANGED
|
@@ -1,9 +1,12 @@
|
|
|
1
|
+
import { PolarisAds } from "./ads.js";
|
|
1
2
|
/**
|
|
2
3
|
* @wovoon/polaris 运行时客户端(协议 1)。
|
|
3
4
|
* 在作品内通过 <script> 引入平台下发的 /api/cloud/sdk.js(全局 WovoonCloud)即可使用,
|
|
4
5
|
* 本模块提供同一 API 的 TypeScript 实现,供构建型项目以模块方式引入。
|
|
5
6
|
*/
|
|
6
|
-
import {
|
|
7
|
+
import { matchRoom } from "./match.js";
|
|
8
|
+
import { PolarisCommerce } from "./commerce.js";
|
|
9
|
+
import { PolarisGame } from "./game.js";
|
|
7
10
|
export class PolarisError extends Error {
|
|
8
11
|
constructor(message, code = "WOVOON_CLOUD_ERROR") {
|
|
9
12
|
super(message);
|
|
@@ -20,11 +23,33 @@ function parseData(raw) {
|
|
|
20
23
|
}
|
|
21
24
|
}
|
|
22
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
|
+
}
|
|
23
41
|
webSocketOrigin() {
|
|
24
42
|
const runtime = String(globalThis.__wovoonRuntimeWsBase ?? "");
|
|
25
43
|
return this.baseUrl || runtime || (typeof location === "undefined" ? "http://localhost" : location.origin);
|
|
26
44
|
}
|
|
27
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();
|
|
28
53
|
this.ads = new PolarisAds(globalThis, (action, body) => {
|
|
29
54
|
const target = this.detectTarget();
|
|
30
55
|
if (!target)
|
|
@@ -41,6 +66,9 @@ export class PolarisClient {
|
|
|
41
66
|
/** 指定作品目标:deploymentId(运行地址自动识别)或 appId。 */
|
|
42
67
|
configure(options) {
|
|
43
68
|
this.ads.dispose();
|
|
69
|
+
for (const game of this.activeGames.values())
|
|
70
|
+
game.leave();
|
|
71
|
+
this.activeGames.clear();
|
|
44
72
|
for (const room of this.activeRooms.values())
|
|
45
73
|
room.leave();
|
|
46
74
|
this.collectionsWatch.generation++;
|
|
@@ -147,6 +175,21 @@ export class PolarisClient {
|
|
|
147
175
|
}
|
|
148
176
|
};
|
|
149
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
|
+
},
|
|
150
193
|
send: (data) => {
|
|
151
194
|
if (!socket || socket.readyState !== 1)
|
|
152
195
|
return;
|
|
@@ -238,37 +281,8 @@ export class PolarisClient {
|
|
|
238
281
|
return this.room("__world");
|
|
239
282
|
}
|
|
240
283
|
/** 内置匹配:凑满 exports.matchSize 人成局 → resolve 目标房间号(再 room(roomId, {mode}) 进入)。 */
|
|
241
|
-
match(mode) {
|
|
242
|
-
|
|
243
|
-
throw new PolarisError("match(mode) 需要模式名", "WOVOON_ARGUMENT");
|
|
244
|
-
return new Promise((resolve, reject) => {
|
|
245
|
-
this.session().then(() => {
|
|
246
|
-
const queue = this.room(`__match_${mode}`);
|
|
247
|
-
let done = false;
|
|
248
|
-
const timer = setTimeout(() => {
|
|
249
|
-
if (done)
|
|
250
|
-
return;
|
|
251
|
-
done = true;
|
|
252
|
-
try {
|
|
253
|
-
queue.leave();
|
|
254
|
-
}
|
|
255
|
-
catch { /* 已关 */ }
|
|
256
|
-
reject(new PolarisError("匹配等待超时(120 秒)", "WOVOON_MATCH_TIMEOUT"));
|
|
257
|
-
}, 120000);
|
|
258
|
-
queue.onMessage((payload) => {
|
|
259
|
-
const frame = payload;
|
|
260
|
-
if (done || frame?.type !== "matched" || !frame.roomId)
|
|
261
|
-
return;
|
|
262
|
-
done = true;
|
|
263
|
-
clearTimeout(timer);
|
|
264
|
-
try {
|
|
265
|
-
queue.leave();
|
|
266
|
-
}
|
|
267
|
-
catch { /* 已关 */ }
|
|
268
|
-
resolve(frame.roomId);
|
|
269
|
-
});
|
|
270
|
-
}).catch(reject);
|
|
271
|
-
});
|
|
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));
|
|
272
286
|
}
|
|
273
287
|
/** 房间列表(大厅/分线选择)。 */
|
|
274
288
|
rooms(options) {
|
|
@@ -0,0 +1,61 @@
|
|
|
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
|
+
/** Only the localhost simulator sets this; it never denotes real money. */
|
|
15
|
+
localFixture?: boolean;
|
|
16
|
+
}
|
|
17
|
+
export interface PurchaseProduct {
|
|
18
|
+
productCode: string;
|
|
19
|
+
name: string;
|
|
20
|
+
productType: "ONE_TIME" | "CONSUMABLE";
|
|
21
|
+
priceCents: number;
|
|
22
|
+
currency: string;
|
|
23
|
+
}
|
|
24
|
+
export interface PurchaseEntitlement {
|
|
25
|
+
productCode: string;
|
|
26
|
+
productType: "ONE_TIME" | "CONSUMABLE";
|
|
27
|
+
quantity: number;
|
|
28
|
+
}
|
|
29
|
+
type Request = (action: string, body: object) => Promise<unknown>;
|
|
30
|
+
interface CommerceBridge {
|
|
31
|
+
postMessage(value: string): void;
|
|
32
|
+
addEventListener(type: string, listener: (event: {
|
|
33
|
+
data: string;
|
|
34
|
+
}) => void): void;
|
|
35
|
+
removeEventListener(type: string, listener: (event: {
|
|
36
|
+
data: string;
|
|
37
|
+
}) => void): void;
|
|
38
|
+
}
|
|
39
|
+
type CommerceHost = typeof globalThis & {
|
|
40
|
+
WovoonNativeCommerce?: CommerceBridge;
|
|
41
|
+
};
|
|
42
|
+
/** Native responses describe presentation only; callers must still query the platform order. */
|
|
43
|
+
export declare function openNativePurchase(orderId: string, host?: CommerceHost): Promise<string>;
|
|
44
|
+
export declare class PolarisCommerce {
|
|
45
|
+
private readonly request;
|
|
46
|
+
constructor(request: Request);
|
|
47
|
+
catalog(): Promise<{
|
|
48
|
+
products: PurchaseProduct[];
|
|
49
|
+
providers: Record<string, boolean>;
|
|
50
|
+
}>;
|
|
51
|
+
entitlements(): Promise<PurchaseEntitlement[]>;
|
|
52
|
+
checkout(productCode: string, options: {
|
|
53
|
+
provider: "ALIPAY" | "WECHAT_PAY";
|
|
54
|
+
idempotencyKey: string;
|
|
55
|
+
}): Promise<PurchaseOrder>;
|
|
56
|
+
order(orderId: string): Promise<PurchaseOrder>;
|
|
57
|
+
/** Built-in checkout presentation. Closing it does not cancel/refund a provider order. */
|
|
58
|
+
present(order: PurchaseOrder, host?: typeof globalThis): Promise<PurchaseOrder>;
|
|
59
|
+
private receipt;
|
|
60
|
+
}
|
|
61
|
+
export {};
|