@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 +15 -2
- package/dist/ads.d.ts +77 -0
- package/dist/ads.js +228 -0
- package/dist/client.d.ts +12 -1
- package/dist/client.js +53 -31
- package/dist/commerce.d.ts +59 -0
- package/dist/commerce.js +174 -0
- package/dist/game-sync.d.ts +31 -0
- package/dist/game-sync.js +90 -0
- package/dist/game.d.ts +76 -0
- package/dist/game.js +178 -0
- package/dist/index.d.ts +8 -0
- package/dist/index.js +4 -0
- package/dist/match.d.ts +10 -0
- package/dist/match.js +55 -0
- package/dist/protocol.d.ts +1 -1
- package/dist/protocol.js +1 -1
- package/docs/ads.md +78 -0
- package/docs/manifest.md +8 -1
- package/docs/recipes/game-commerce.md +63 -0
- package/docs/recipes/platform-game-mode.md +130 -0
- package/docs/recipes/rewarded-placement.md +103 -0
- package/docs/rewarded-ads.md +88 -0
- package/docs/sdk.md +5 -0
- package/llms.txt +9 -2
- package/package.json +2 -2
package/dist/commerce.js
ADDED
|
@@ -0,0 +1,174 @@
|
|
|
1
|
+
const uuid = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
2
|
+
const terminal = new Set(["FULFILLED", "PAID_REVIEW", "FAILED", "EXPIRED", "REFUNDING", "REFUNDED", "PARTIALLY_REFUNDED"]);
|
|
3
|
+
/** Native responses describe presentation only; callers must still query the platform order. */
|
|
4
|
+
export function openNativePurchase(orderId, host = globalThis) {
|
|
5
|
+
if (!uuid.test(orderId))
|
|
6
|
+
return Promise.reject(Error("INVALID_PURCHASE_ORDER"));
|
|
7
|
+
const bridge = host.WovoonNativeCommerce;
|
|
8
|
+
if (!bridge?.postMessage || !bridge.addEventListener || !bridge.removeEventListener)
|
|
9
|
+
return Promise.resolve("unavailable");
|
|
10
|
+
return new Promise(resolve => {
|
|
11
|
+
const id = `purchase_${Date.now()}_${Math.random().toString(36).slice(2)}`;
|
|
12
|
+
const finish = (status) => { clearTimeout(timer); bridge.removeEventListener("message", receive); resolve(status); };
|
|
13
|
+
const receive = (event) => {
|
|
14
|
+
try {
|
|
15
|
+
const value = JSON.parse(event.data);
|
|
16
|
+
if (value.channel === "wovoon:commerce:v1" && value.id === id && ["opened", "finished", "cancelled", "unavailable"].includes(value.status))
|
|
17
|
+
finish(value.status);
|
|
18
|
+
}
|
|
19
|
+
catch { }
|
|
20
|
+
};
|
|
21
|
+
const timer = setTimeout(() => finish("unavailable"), 120000);
|
|
22
|
+
bridge.addEventListener("message", receive);
|
|
23
|
+
try {
|
|
24
|
+
bridge.postMessage(JSON.stringify({ channel: "wovoon:commerce:v1", action: "open", id, orderId }));
|
|
25
|
+
}
|
|
26
|
+
catch {
|
|
27
|
+
finish("unavailable");
|
|
28
|
+
}
|
|
29
|
+
});
|
|
30
|
+
}
|
|
31
|
+
export class PolarisCommerce {
|
|
32
|
+
constructor(request) {
|
|
33
|
+
this.request = request;
|
|
34
|
+
}
|
|
35
|
+
async catalog() {
|
|
36
|
+
return await this.request("catalog", {});
|
|
37
|
+
}
|
|
38
|
+
async entitlements() {
|
|
39
|
+
const rows = await this.request("entitlements", {});
|
|
40
|
+
if (!Array.isArray(rows) || rows.some(r => !r || typeof r.productCode !== "string" || !["ONE_TIME", "CONSUMABLE"].includes(r.productType) || !Number.isSafeInteger(r.quantity) || r.quantity < 0))
|
|
41
|
+
throw Error("INVALID_PURCHASE_ENTITLEMENTS");
|
|
42
|
+
return rows;
|
|
43
|
+
}
|
|
44
|
+
async checkout(productCode, options) {
|
|
45
|
+
if (!/^[a-zA-Z0-9_.-]{1,60}$/.test(productCode) || !options || !["ALIPAY", "WECHAT_PAY"].includes(options.provider) || !/^[a-zA-Z0-9_.:-]{1,80}$/.test(options.idempotencyKey))
|
|
46
|
+
throw Error("INVALID_PURCHASE_REQUEST");
|
|
47
|
+
// Caller persists the key BEFORE sending. A transport failure must reuse the same key.
|
|
48
|
+
return this.receipt(await this.request("checkout", { productCode, ...options }));
|
|
49
|
+
}
|
|
50
|
+
async order(orderId) {
|
|
51
|
+
if (!uuid.test(orderId))
|
|
52
|
+
throw Error("INVALID_PURCHASE_ORDER");
|
|
53
|
+
const result = this.receipt(await this.request("order", { orderId }));
|
|
54
|
+
if (result.orderId !== orderId)
|
|
55
|
+
throw Error("INVALID_PURCHASE_ORDER");
|
|
56
|
+
return result;
|
|
57
|
+
}
|
|
58
|
+
/** Built-in checkout presentation. Closing it does not cancel/refund a provider order. */
|
|
59
|
+
present(order, host = globalThis) {
|
|
60
|
+
this.receipt(order);
|
|
61
|
+
if (terminal.has(order.status))
|
|
62
|
+
return Promise.resolve(order);
|
|
63
|
+
if (!host.document?.body)
|
|
64
|
+
return Promise.reject(Error("PURCHASE_UI_UNAVAILABLE"));
|
|
65
|
+
return new Promise(resolve => {
|
|
66
|
+
const doc = host.document, overlay = doc.createElement("div"), panel = doc.createElement("div");
|
|
67
|
+
overlay.setAttribute("role", "dialog");
|
|
68
|
+
overlay.setAttribute("aria-modal", "true");
|
|
69
|
+
overlay.setAttribute("aria-label", "Wovoon 支付");
|
|
70
|
+
overlay.style.cssText = "position:fixed;inset:0;z-index:2147483647;background:#000b;display:grid;place-items:center;padding:16px";
|
|
71
|
+
panel.style.cssText = "background:#fff;color:#15171b;padding:24px;border-radius:16px;max-width:380px;width:100%;font:16px system-ui;text-align:center";
|
|
72
|
+
const title = doc.createElement("h2");
|
|
73
|
+
title.textContent = `支付 ¥${(order.amountCents / 100).toFixed(2)}`;
|
|
74
|
+
const status = doc.createElement("p");
|
|
75
|
+
status.textContent = "支付完成后,平台确认到账才会发放游戏权益。";
|
|
76
|
+
panel.append(title, status);
|
|
77
|
+
if (order.checkoutType === "QR_CODE_DATA_URL" && /^data:image\/png;base64,[A-Za-z0-9+/=]+$/.test(order.checkoutPayload || "")) {
|
|
78
|
+
const image = doc.createElement("img");
|
|
79
|
+
image.src = order.checkoutPayload;
|
|
80
|
+
image.alt = "微信支付二维码";
|
|
81
|
+
image.style.cssText = "width:100%;max-width:260px";
|
|
82
|
+
panel.append(image);
|
|
83
|
+
}
|
|
84
|
+
else if (order.checkoutType === "REDIRECT") {
|
|
85
|
+
let url;
|
|
86
|
+
try {
|
|
87
|
+
url = new URL(order.checkoutPayload || "");
|
|
88
|
+
}
|
|
89
|
+
catch {
|
|
90
|
+
overlay.remove();
|
|
91
|
+
throw Error("INVALID_CHECKOUT_URL");
|
|
92
|
+
}
|
|
93
|
+
if (url.protocol !== "https:" || (url.port && url.port !== "443") || !/(^|\.)(alipay\.com|alipaydev\.com)$/.test(url.hostname) || url.username || url.password)
|
|
94
|
+
throw Error("INVALID_CHECKOUT_URL");
|
|
95
|
+
if (host.WovoonNativeCommerce) {
|
|
96
|
+
const pay = doc.createElement("button");
|
|
97
|
+
pay.type = "button";
|
|
98
|
+
pay.textContent = "前往支付宝支付";
|
|
99
|
+
pay.onclick = async () => {
|
|
100
|
+
pay.disabled = true;
|
|
101
|
+
try {
|
|
102
|
+
const result = await openNativePurchase(order.orderId, host);
|
|
103
|
+
status.textContent = result === "unavailable" ? "暂时无法打开支付页,请稍后重试或扫描二维码。" : "请返回后查询平台订单结果。打开或关闭支付页不会重复购买。";
|
|
104
|
+
}
|
|
105
|
+
finally {
|
|
106
|
+
pay.disabled = false;
|
|
107
|
+
}
|
|
108
|
+
};
|
|
109
|
+
panel.append(pay);
|
|
110
|
+
}
|
|
111
|
+
else {
|
|
112
|
+
const link = doc.createElement("a");
|
|
113
|
+
link.href = url.href;
|
|
114
|
+
link.target = "_blank";
|
|
115
|
+
link.rel = "noopener noreferrer";
|
|
116
|
+
link.textContent = "前往支付宝支付";
|
|
117
|
+
panel.append(link);
|
|
118
|
+
}
|
|
119
|
+
if (/^data:image\/png;base64,[A-Za-z0-9+/=]+$/.test(order.checkoutQrCode || "")) {
|
|
120
|
+
const image = doc.createElement("img");
|
|
121
|
+
image.src = order.checkoutQrCode;
|
|
122
|
+
image.alt = "支付宝支付二维码";
|
|
123
|
+
image.style.cssText = "display:block;width:100%;max-width:260px;margin:auto";
|
|
124
|
+
panel.append(image);
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
const refresh = doc.createElement("button"), close = doc.createElement("button");
|
|
128
|
+
refresh.textContent = "已完成支付,查询结果";
|
|
129
|
+
close.textContent = "稍后查询";
|
|
130
|
+
for (const button of [refresh, close]) {
|
|
131
|
+
button.type = "button";
|
|
132
|
+
button.style.cssText = "display:block;margin:16px auto 0;padding:10px 16px";
|
|
133
|
+
panel.append(button);
|
|
134
|
+
}
|
|
135
|
+
let ended = false, current = order;
|
|
136
|
+
const finish = () => { if (ended)
|
|
137
|
+
return; ended = true; overlay.remove(); resolve(current); };
|
|
138
|
+
close.onclick = finish;
|
|
139
|
+
refresh.onclick = async () => {
|
|
140
|
+
refresh.disabled = true;
|
|
141
|
+
try {
|
|
142
|
+
current = await this.order(order.orderId);
|
|
143
|
+
if (ended)
|
|
144
|
+
return;
|
|
145
|
+
if (current.status === "FULFILLED") {
|
|
146
|
+
status.textContent = "支付成功,游戏权益已到账。";
|
|
147
|
+
close.textContent = "返回游戏";
|
|
148
|
+
}
|
|
149
|
+
else if (terminal.has(current.status)) {
|
|
150
|
+
status.textContent = current.status === "PAID_REVIEW" ? "已记录收款,订单需平台审核。请在 Wovoon 联系客服核对。" : "订单已结束,请查询订单记录。";
|
|
151
|
+
}
|
|
152
|
+
else
|
|
153
|
+
status.textContent = "平台仍在等待支付结果。无需再次购买,请稍后重新查询。";
|
|
154
|
+
}
|
|
155
|
+
catch {
|
|
156
|
+
if (!ended)
|
|
157
|
+
status.textContent = "暂时无法查询支付结果。订单已保留,请稍后查询。";
|
|
158
|
+
}
|
|
159
|
+
finally {
|
|
160
|
+
refresh.disabled = false;
|
|
161
|
+
}
|
|
162
|
+
};
|
|
163
|
+
overlay.append(panel);
|
|
164
|
+
doc.body.append(overlay);
|
|
165
|
+
refresh.focus();
|
|
166
|
+
});
|
|
167
|
+
}
|
|
168
|
+
receipt(value) {
|
|
169
|
+
const order = value;
|
|
170
|
+
if (!order || !uuid.test(order.orderId) || typeof order.status !== "string" || !["CREATED", "PAYING", "PAID", ...terminal].includes(order.status) || !Number.isSafeInteger(order.amountCents) || order.amountCents <= 0 || order.currency !== "CNY")
|
|
171
|
+
throw Error("INVALID_PURCHASE_RECEIPT");
|
|
172
|
+
return order;
|
|
173
|
+
}
|
|
174
|
+
}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import type { GameSnapshot } from "./game.js";
|
|
2
|
+
/** Render remote state between two authoritative snapshots. Never extrapolates indefinitely. */
|
|
3
|
+
export declare class GameTimeline<State> {
|
|
4
|
+
private readonly interpolate;
|
|
5
|
+
readonly delayMs: number;
|
|
6
|
+
private readonly capacity;
|
|
7
|
+
private frames;
|
|
8
|
+
private renderedTime;
|
|
9
|
+
constructor(interpolate: (a: State, b: State, alpha: number) => State, delayMs?: number, capacity?: number);
|
|
10
|
+
push(snapshot: GameSnapshot<State>, now?: number): void;
|
|
11
|
+
sample(now?: number): State | undefined;
|
|
12
|
+
reset(): void;
|
|
13
|
+
}
|
|
14
|
+
/** Optional deterministic prediction. Replays locally only; never resubmits network commands. */
|
|
15
|
+
export declare class GamePrediction<State, Input> {
|
|
16
|
+
private readonly simulate;
|
|
17
|
+
private readonly maxPending;
|
|
18
|
+
private pending;
|
|
19
|
+
private lastSequence;
|
|
20
|
+
private acknowledged;
|
|
21
|
+
private instance;
|
|
22
|
+
private predicted;
|
|
23
|
+
constructor(initial: State, simulate: (state: State, input: Input) => State, maxPending?: number);
|
|
24
|
+
/** Call only after game.submit(input) returns this accepted sequence. */
|
|
25
|
+
predict(sequence: number, input: Input): boolean;
|
|
26
|
+
reconcile(authoritative: State, acknowledged: number, instanceId: string): State;
|
|
27
|
+
/** Disconnects cancel local speculation. The server remains authoritative. */
|
|
28
|
+
reset(authoritative: State): void;
|
|
29
|
+
get state(): State;
|
|
30
|
+
get pendingCount(): number;
|
|
31
|
+
}
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
/** Render remote state between two authoritative snapshots. Never extrapolates indefinitely. */
|
|
2
|
+
export class GameTimeline {
|
|
3
|
+
constructor(interpolate, delayMs = 100, capacity = 32) {
|
|
4
|
+
this.interpolate = interpolate;
|
|
5
|
+
this.delayMs = delayMs;
|
|
6
|
+
this.capacity = capacity;
|
|
7
|
+
this.frames = [];
|
|
8
|
+
this.renderedTime = -Infinity;
|
|
9
|
+
if (!Number.isFinite(delayMs) || delayMs < 0 || delayMs > 1000 || !Number.isInteger(capacity) || capacity < 2 || capacity > 256)
|
|
10
|
+
throw new Error("Invalid interpolation buffer settings");
|
|
11
|
+
}
|
|
12
|
+
push(snapshot, now = performance.now()) {
|
|
13
|
+
if (!Number.isFinite(snapshot.serverTime) || !Number.isFinite(now))
|
|
14
|
+
return;
|
|
15
|
+
const last = this.frames[this.frames.length - 1]?.snapshot;
|
|
16
|
+
if (last && last.instanceId !== snapshot.instanceId)
|
|
17
|
+
this.reset();
|
|
18
|
+
else if (last && (snapshot.sequence <= last.sequence || snapshot.serverTime < last.serverTime))
|
|
19
|
+
return;
|
|
20
|
+
this.frames.push({ snapshot, arrived: now });
|
|
21
|
+
if (this.frames.length > this.capacity)
|
|
22
|
+
this.frames.shift();
|
|
23
|
+
}
|
|
24
|
+
sample(now = performance.now()) {
|
|
25
|
+
const newest = this.frames[this.frames.length - 1];
|
|
26
|
+
if (!newest)
|
|
27
|
+
return undefined;
|
|
28
|
+
// A late packet must not rewind the rendered world when its arrival resets the clock anchor.
|
|
29
|
+
const target = Math.max(this.renderedTime, Math.min(newest.snapshot.serverTime, newest.snapshot.serverTime + Math.max(0, now - newest.arrived) - this.delayMs));
|
|
30
|
+
this.renderedTime = target;
|
|
31
|
+
const first = this.frames[0].snapshot;
|
|
32
|
+
if (target <= first.serverTime)
|
|
33
|
+
return first.state;
|
|
34
|
+
for (let i = 1; i < this.frames.length; i++) {
|
|
35
|
+
const before = this.frames[i - 1].snapshot, after = this.frames[i].snapshot;
|
|
36
|
+
if (target <= after.serverTime) {
|
|
37
|
+
const span = after.serverTime - before.serverTime;
|
|
38
|
+
return this.interpolate(before.state, after.state, span <= 0 ? 1 : Math.max(0, Math.min(1, (target - before.serverTime) / span)));
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
return newest.snapshot.state;
|
|
42
|
+
}
|
|
43
|
+
reset() { this.frames = []; this.renderedTime = -Infinity; }
|
|
44
|
+
}
|
|
45
|
+
/** Optional deterministic prediction. Replays locally only; never resubmits network commands. */
|
|
46
|
+
export class GamePrediction {
|
|
47
|
+
constructor(initial, simulate, maxPending = 128) {
|
|
48
|
+
this.simulate = simulate;
|
|
49
|
+
this.maxPending = maxPending;
|
|
50
|
+
this.pending = [];
|
|
51
|
+
this.lastSequence = 0;
|
|
52
|
+
this.acknowledged = 0;
|
|
53
|
+
this.instance = "";
|
|
54
|
+
if (!Number.isInteger(maxPending) || maxPending < 1 || maxPending > 1024)
|
|
55
|
+
throw new Error("Invalid prediction buffer limit");
|
|
56
|
+
this.predicted = structuredClone(initial);
|
|
57
|
+
}
|
|
58
|
+
/** Call only after game.submit(input) returns this accepted sequence. */
|
|
59
|
+
predict(sequence, input) {
|
|
60
|
+
if (!Number.isSafeInteger(sequence) || sequence <= this.lastSequence || this.pending.length >= this.maxPending)
|
|
61
|
+
return false;
|
|
62
|
+
const saved = structuredClone(input);
|
|
63
|
+
const next = this.simulate(structuredClone(this.predicted), structuredClone(saved));
|
|
64
|
+
this.pending.push({ sequence, input: saved });
|
|
65
|
+
this.lastSequence = sequence;
|
|
66
|
+
this.predicted = next;
|
|
67
|
+
return true;
|
|
68
|
+
}
|
|
69
|
+
reconcile(authoritative, acknowledged, instanceId) {
|
|
70
|
+
if (!Number.isSafeInteger(acknowledged) || acknowledged < 0)
|
|
71
|
+
throw new Error("Invalid input acknowledgement");
|
|
72
|
+
if (this.instance && this.instance !== instanceId)
|
|
73
|
+
this.pending = [];
|
|
74
|
+
else if (acknowledged < this.acknowledged)
|
|
75
|
+
return this.state;
|
|
76
|
+
this.instance = instanceId;
|
|
77
|
+
this.acknowledged = acknowledged;
|
|
78
|
+
this.lastSequence = Math.max(this.lastSequence, acknowledged);
|
|
79
|
+
this.pending = this.pending.filter(command => command.sequence > acknowledged);
|
|
80
|
+
let next = structuredClone(authoritative);
|
|
81
|
+
for (const command of this.pending)
|
|
82
|
+
next = this.simulate(next, structuredClone(command.input));
|
|
83
|
+
this.predicted = next;
|
|
84
|
+
return this.state;
|
|
85
|
+
}
|
|
86
|
+
/** Disconnects cancel local speculation. The server remains authoritative. */
|
|
87
|
+
reset(authoritative) { this.pending = []; this.predicted = structuredClone(authoritative); this.acknowledged = 0; this.instance = ""; }
|
|
88
|
+
get state() { return structuredClone(this.predicted); }
|
|
89
|
+
get pendingCount() { return this.pending.length; }
|
|
90
|
+
}
|
package/dist/game.d.ts
ADDED
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
import { GameTimeline } from "./game-sync.js";
|
|
2
|
+
export interface GameRoom {
|
|
3
|
+
trySend(data: unknown, maxBufferedBytes?: number): boolean;
|
|
4
|
+
leave(): void;
|
|
5
|
+
onMessage(callback: (frame: {
|
|
6
|
+
from?: string;
|
|
7
|
+
data?: unknown;
|
|
8
|
+
error?: string;
|
|
9
|
+
}) => void): void;
|
|
10
|
+
onPresence(callback: (frame: unknown) => void): void;
|
|
11
|
+
onClose(callback: (frame: unknown) => void): void;
|
|
12
|
+
}
|
|
13
|
+
export interface GameSnapshot<State> {
|
|
14
|
+
protocol: "wovoon.game/1";
|
|
15
|
+
kind: "snapshot";
|
|
16
|
+
instanceId: string;
|
|
17
|
+
sequence: number;
|
|
18
|
+
tick: number;
|
|
19
|
+
serverTime: number;
|
|
20
|
+
state: State;
|
|
21
|
+
you?: string;
|
|
22
|
+
acknowledgements: Record<string, number>;
|
|
23
|
+
}
|
|
24
|
+
export interface GameOptions<State> {
|
|
25
|
+
roomId: string;
|
|
26
|
+
onState?: (state: State, snapshot: GameSnapshot<State>) => void;
|
|
27
|
+
onStatus?: (status: "connecting" | "connected" | "reconnecting" | "closed" | "error") => void;
|
|
28
|
+
/** A new instance is a new server simulation, not a promise of crash recovery. */
|
|
29
|
+
onReset?: (previousInstanceId: string, nextInstanceId: string) => void;
|
|
30
|
+
onError?: (message: string) => void;
|
|
31
|
+
onLatency?: (roundTripMs: number) => void;
|
|
32
|
+
maxReconnectMs?: number;
|
|
33
|
+
interpolation?: {
|
|
34
|
+
delayMs?: number;
|
|
35
|
+
interpolate: (a: State, b: State, alpha: number) => State;
|
|
36
|
+
};
|
|
37
|
+
}
|
|
38
|
+
/** Platform-managed state transport with optional rendering interpolation. Gameplay prediction is explicit. */
|
|
39
|
+
export declare class PolarisGame<State = unknown> {
|
|
40
|
+
private readonly openRoom;
|
|
41
|
+
readonly mode: string;
|
|
42
|
+
private readonly options;
|
|
43
|
+
readonly ready: Promise<void>;
|
|
44
|
+
readonly timeline?: GameTimeline<State>;
|
|
45
|
+
playerId: string;
|
|
46
|
+
private room?;
|
|
47
|
+
private closed;
|
|
48
|
+
private generation;
|
|
49
|
+
private inputSequence;
|
|
50
|
+
private snapshotSequence;
|
|
51
|
+
private instanceId;
|
|
52
|
+
private joined;
|
|
53
|
+
private outageAt;
|
|
54
|
+
private attempts;
|
|
55
|
+
private reconnect?;
|
|
56
|
+
private handshake?;
|
|
57
|
+
private heartbeat?;
|
|
58
|
+
private lastReceived;
|
|
59
|
+
private settled;
|
|
60
|
+
private resolveReady;
|
|
61
|
+
private rejectReady;
|
|
62
|
+
readonly clientId: string;
|
|
63
|
+
constructor(openRoom: (id: string, options: {
|
|
64
|
+
mode: string;
|
|
65
|
+
}) => GameRoom, mode: string, options: GameOptions<State>);
|
|
66
|
+
private emit;
|
|
67
|
+
private status;
|
|
68
|
+
private connect;
|
|
69
|
+
/** False means not submitted. Inputs are never silently queued/replayed across a disconnect. */
|
|
70
|
+
input(input: unknown): boolean;
|
|
71
|
+
/** Accepted sequence for optional deterministic prediction; null means not sent. */
|
|
72
|
+
submit(input: unknown): number | null;
|
|
73
|
+
private finish;
|
|
74
|
+
sample(now?: number): State | undefined;
|
|
75
|
+
leave(): void;
|
|
76
|
+
}
|
package/dist/game.js
ADDED
|
@@ -0,0 +1,178 @@
|
|
|
1
|
+
import { GameTimeline } from "./game-sync.js";
|
|
2
|
+
/** Platform-managed state transport with optional rendering interpolation. Gameplay prediction is explicit. */
|
|
3
|
+
export class PolarisGame {
|
|
4
|
+
constructor(openRoom, mode, options) {
|
|
5
|
+
this.openRoom = openRoom;
|
|
6
|
+
this.mode = mode;
|
|
7
|
+
this.options = options;
|
|
8
|
+
this.playerId = "";
|
|
9
|
+
this.closed = false;
|
|
10
|
+
this.generation = 0;
|
|
11
|
+
this.inputSequence = 0;
|
|
12
|
+
this.snapshotSequence = 0;
|
|
13
|
+
this.instanceId = "";
|
|
14
|
+
this.joined = false;
|
|
15
|
+
this.outageAt = 0;
|
|
16
|
+
this.attempts = 0;
|
|
17
|
+
this.lastReceived = 0;
|
|
18
|
+
this.settled = false;
|
|
19
|
+
this.clientId = "game_" + Date.now().toString(36) + "_" + Math.random().toString(36).slice(2);
|
|
20
|
+
if (!/^[a-z][a-z0-9_]{1,31}$/.test(mode) || !/^[a-zA-Z0-9_-]{1,64}$/.test(options.roomId))
|
|
21
|
+
throw new Error("game(mode, {roomId}) requires a valid mode and room id");
|
|
22
|
+
if (options.maxReconnectMs !== undefined && (!Number.isFinite(options.maxReconnectMs) || options.maxReconnectMs < 0 || options.maxReconnectMs > 300000))
|
|
23
|
+
throw new Error("maxReconnectMs must be between 0 and 300000");
|
|
24
|
+
if (options.interpolation)
|
|
25
|
+
this.timeline = new GameTimeline(options.interpolation.interpolate, options.interpolation.delayMs);
|
|
26
|
+
this.ready = new Promise((resolve, reject) => { this.resolveReady = resolve; this.rejectReady = reject; });
|
|
27
|
+
this.connect();
|
|
28
|
+
}
|
|
29
|
+
emit(action) { try {
|
|
30
|
+
action?.();
|
|
31
|
+
}
|
|
32
|
+
catch { /* callbacks do not break transport cleanup */ } }
|
|
33
|
+
status(status) {
|
|
34
|
+
this.emit(() => this.options.onStatus?.(status));
|
|
35
|
+
}
|
|
36
|
+
connect() {
|
|
37
|
+
if (this.closed)
|
|
38
|
+
return;
|
|
39
|
+
const generation = ++this.generation;
|
|
40
|
+
this.joined = false;
|
|
41
|
+
this.status(this.attempts ? "reconnecting" : "connecting");
|
|
42
|
+
let room;
|
|
43
|
+
let failed = false;
|
|
44
|
+
const fail = () => {
|
|
45
|
+
if (failed || this.closed || generation !== this.generation)
|
|
46
|
+
return;
|
|
47
|
+
failed = true;
|
|
48
|
+
clearTimeout(this.handshake);
|
|
49
|
+
clearInterval(this.heartbeat);
|
|
50
|
+
this.joined = false;
|
|
51
|
+
try {
|
|
52
|
+
room?.leave();
|
|
53
|
+
}
|
|
54
|
+
catch { /* transport already failed */ }
|
|
55
|
+
this.outageAt || (this.outageAt = Date.now());
|
|
56
|
+
if (Date.now() - this.outageAt >= (this.options.maxReconnectMs ?? 30000)) {
|
|
57
|
+
this.finish("error", "游戏连接恢复超时,请重新进入作品");
|
|
58
|
+
return;
|
|
59
|
+
}
|
|
60
|
+
this.status("reconnecting");
|
|
61
|
+
if (this.closed)
|
|
62
|
+
return;
|
|
63
|
+
const delay = Math.min(3000, 250 * 2 ** Math.min(this.attempts++, 4));
|
|
64
|
+
this.reconnect = setTimeout(() => this.connect(), delay);
|
|
65
|
+
};
|
|
66
|
+
try {
|
|
67
|
+
room = this.openRoom(this.options.roomId, { mode: this.mode });
|
|
68
|
+
}
|
|
69
|
+
catch {
|
|
70
|
+
fail();
|
|
71
|
+
return;
|
|
72
|
+
}
|
|
73
|
+
this.room = room;
|
|
74
|
+
this.handshake = setTimeout(fail, 8000);
|
|
75
|
+
room.onClose(fail);
|
|
76
|
+
room.onPresence(frame => {
|
|
77
|
+
if (this.closed || generation !== this.generation)
|
|
78
|
+
return;
|
|
79
|
+
if (frame?.type === "joined") {
|
|
80
|
+
this.playerId = String(frame.you ?? "");
|
|
81
|
+
room.trySend({ protocol: "wovoon.game/1", kind: "resume" });
|
|
82
|
+
}
|
|
83
|
+
});
|
|
84
|
+
room.onMessage(frame => {
|
|
85
|
+
if (this.closed || failed || generation !== this.generation)
|
|
86
|
+
return;
|
|
87
|
+
if (frame.error) {
|
|
88
|
+
this.emit(() => this.options.onError?.(String(frame.error)));
|
|
89
|
+
return;
|
|
90
|
+
}
|
|
91
|
+
if (frame.from !== "server" || !frame.data || typeof frame.data !== "object")
|
|
92
|
+
return;
|
|
93
|
+
const data = frame.data;
|
|
94
|
+
if (data.protocol !== "wovoon.game/1")
|
|
95
|
+
return;
|
|
96
|
+
if (data.kind === "pong" && typeof data.clientTime === "number") {
|
|
97
|
+
this.lastReceived = Date.now();
|
|
98
|
+
this.emit(() => this.options.onLatency?.(Math.max(0, Date.now() - data.clientTime)));
|
|
99
|
+
return;
|
|
100
|
+
}
|
|
101
|
+
if (data.kind !== "snapshot" || !Number.isSafeInteger(data.sequence) || data.sequence < 1
|
|
102
|
+
|| typeof data.instanceId !== "string" || !Number.isFinite(data.serverTime) || !("state" in data)
|
|
103
|
+
|| !Number.isSafeInteger(data.tick) || data.tick < 0 || !data.acknowledgements || typeof data.acknowledgements !== "object")
|
|
104
|
+
return;
|
|
105
|
+
this.lastReceived = Date.now();
|
|
106
|
+
if (data.instanceId !== this.instanceId) {
|
|
107
|
+
if (this.instanceId)
|
|
108
|
+
this.emit(() => this.options.onReset?.(this.instanceId, data.instanceId));
|
|
109
|
+
if (this.closed)
|
|
110
|
+
return;
|
|
111
|
+
this.instanceId = data.instanceId;
|
|
112
|
+
this.snapshotSequence = 0;
|
|
113
|
+
}
|
|
114
|
+
if (data.sequence <= this.snapshotSequence)
|
|
115
|
+
return;
|
|
116
|
+
this.snapshotSequence = data.sequence;
|
|
117
|
+
if (typeof data.you === "string")
|
|
118
|
+
this.playerId = data.you;
|
|
119
|
+
this.timeline?.push(data);
|
|
120
|
+
if (!this.joined) {
|
|
121
|
+
this.joined = true;
|
|
122
|
+
this.outageAt = 0;
|
|
123
|
+
this.attempts = 0;
|
|
124
|
+
clearTimeout(this.handshake);
|
|
125
|
+
this.status("connected");
|
|
126
|
+
if (this.closed)
|
|
127
|
+
return;
|
|
128
|
+
if (!this.settled) {
|
|
129
|
+
this.settled = true;
|
|
130
|
+
this.resolveReady();
|
|
131
|
+
}
|
|
132
|
+
this.heartbeat = setInterval(() => {
|
|
133
|
+
if (Date.now() - this.lastReceived > 8000) {
|
|
134
|
+
fail();
|
|
135
|
+
return;
|
|
136
|
+
}
|
|
137
|
+
room.trySend({ protocol: "wovoon.game/1", kind: "ping", clientTime: Date.now() });
|
|
138
|
+
}, 2000);
|
|
139
|
+
}
|
|
140
|
+
this.emit(() => this.options.onState?.(data.state, data));
|
|
141
|
+
});
|
|
142
|
+
}
|
|
143
|
+
/** False means not submitted. Inputs are never silently queued/replayed across a disconnect. */
|
|
144
|
+
input(input) { return this.submit(input) !== null; }
|
|
145
|
+
/** Accepted sequence for optional deterministic prediction; null means not sent. */
|
|
146
|
+
submit(input) {
|
|
147
|
+
if (this.closed || !this.joined || !this.room)
|
|
148
|
+
return null;
|
|
149
|
+
const sequence = this.inputSequence + 1;
|
|
150
|
+
if (!this.room.trySend({ protocol: "wovoon.game/1", kind: "input", clientId: this.clientId, sequence, input }, 64 * 1024))
|
|
151
|
+
return null;
|
|
152
|
+
this.inputSequence = sequence;
|
|
153
|
+
return sequence;
|
|
154
|
+
}
|
|
155
|
+
finish(status, message) {
|
|
156
|
+
if (this.closed)
|
|
157
|
+
return;
|
|
158
|
+
this.closed = true;
|
|
159
|
+
++this.generation;
|
|
160
|
+
clearTimeout(this.reconnect);
|
|
161
|
+
clearTimeout(this.handshake);
|
|
162
|
+
clearInterval(this.heartbeat);
|
|
163
|
+
try {
|
|
164
|
+
this.room?.leave();
|
|
165
|
+
}
|
|
166
|
+
catch { /* cleanup must still settle ready */ }
|
|
167
|
+
this.timeline?.reset();
|
|
168
|
+
this.status(status);
|
|
169
|
+
if (message)
|
|
170
|
+
this.emit(() => this.options.onError?.(message));
|
|
171
|
+
if (!this.settled) {
|
|
172
|
+
this.settled = true;
|
|
173
|
+
this.rejectReady(new Error(message ?? "游戏连接已关闭"));
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
sample(now) { return this.timeline?.sample(now); }
|
|
177
|
+
leave() { this.finish("closed"); }
|
|
178
|
+
}
|
package/dist/index.d.ts
CHANGED
|
@@ -1,5 +1,13 @@
|
|
|
1
1
|
/** Polaris protocol 1: identity, collections, functions and realtime rooms. */
|
|
2
2
|
export { WOVOON_PROTOCOL_VERSION, COLLECTION_NAME_PATTERN, isValidCollectionName, CAPABILITY_PATTERN, isValidCapability, WovoonProtocolError, } from "./protocol.js";
|
|
3
3
|
export { PolarisClient, PolarisError, parseData } from "./client.js";
|
|
4
|
+
export { GameTimeline, GamePrediction } from "./game-sync.js";
|
|
5
|
+
export { PolarisGame } from "./game.js";
|
|
6
|
+
export type { GameOptions, GameSnapshot, GameRoom } from "./game.js";
|
|
7
|
+
export { PolarisAds } from "./ads.js";
|
|
8
|
+
export { PolarisCommerce } from "./commerce.js";
|
|
9
|
+
export type { PurchaseOrder, PurchaseProduct, PurchaseEntitlement } from "./commerce.js";
|
|
10
|
+
export type { PolarisAdFormat, PolarisAdStatus, PolarisAdResult, PolarisAdCapabilities, PolarisAdOptions, PolarisBanner } from "./ads.js";
|
|
11
|
+
export type { PolarisRewardReceipt, PolarisRewardBalance, PolarisRewardSpend } from "./ads.js";
|
|
4
12
|
export type { WovoonCapability, WovoonCollectionName, WovoonManifest, WovoonSession, WovoonDocument, WovoonQueryOptions, WovoonFunctionEvent, WovoonFunctionResult, WovoonRoomFrame, } from "./protocol.js";
|
|
5
13
|
export type { PolarisRequestInit, PolarisSessionView, PolarisDocumentView, PolarisQueryOptions } from "./client.js";
|
package/dist/index.js
CHANGED
|
@@ -1,3 +1,7 @@
|
|
|
1
1
|
/** Polaris protocol 1: identity, collections, functions and realtime rooms. */
|
|
2
2
|
export { WOVOON_PROTOCOL_VERSION, COLLECTION_NAME_PATTERN, isValidCollectionName, CAPABILITY_PATTERN, isValidCapability, WovoonProtocolError, } from "./protocol.js";
|
|
3
3
|
export { PolarisClient, PolarisError, parseData } from "./client.js";
|
|
4
|
+
export { GameTimeline, GamePrediction } from "./game-sync.js";
|
|
5
|
+
export { PolarisGame } from "./game.js";
|
|
6
|
+
export { PolarisAds } from "./ads.js";
|
|
7
|
+
export { PolarisCommerce } from "./commerce.js";
|
package/dist/match.d.ts
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
export interface MatchQueue {
|
|
2
|
+
leave(): void;
|
|
3
|
+
onMessage(listener: (payload: any) => void): unknown;
|
|
4
|
+
}
|
|
5
|
+
export interface MatchAssignment {
|
|
6
|
+
status: string;
|
|
7
|
+
roomId?: string;
|
|
8
|
+
}
|
|
9
|
+
/** The persisted seat repairs a lost WebSocket notification. It never starts another order/room. */
|
|
10
|
+
export declare function matchRoom(mode: string, connect: () => MatchQueue, query: (action: "status" | "cancel") => Promise<MatchAssignment>, signal?: AbortSignal): Promise<string>;
|
package/dist/match.js
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
/** The persisted seat repairs a lost WebSocket notification. It never starts another order/room. */
|
|
2
|
+
export async function matchRoom(mode, connect, query, signal) {
|
|
3
|
+
if (!/^[a-z][a-z0-9_]{1,31}$/.test(mode))
|
|
4
|
+
throw Error("INVALID_MATCH_MODE");
|
|
5
|
+
if (signal?.aborted)
|
|
6
|
+
throw Error("MATCH_CANCELLED");
|
|
7
|
+
const old = await query("status").catch(() => undefined);
|
|
8
|
+
if (signal?.aborted)
|
|
9
|
+
throw Error("MATCH_CANCELLED");
|
|
10
|
+
if (old?.status === "ASSIGNED" && old.roomId)
|
|
11
|
+
return old.roomId;
|
|
12
|
+
if (old?.status === "JOINED")
|
|
13
|
+
await query("cancel");
|
|
14
|
+
return new Promise((resolve, reject) => {
|
|
15
|
+
let ended = false, timer;
|
|
16
|
+
const queue = connect();
|
|
17
|
+
const finish = (room, error) => {
|
|
18
|
+
if (ended)
|
|
19
|
+
return;
|
|
20
|
+
ended = true;
|
|
21
|
+
clearTimeout(timeout);
|
|
22
|
+
if (timer)
|
|
23
|
+
clearTimeout(timer);
|
|
24
|
+
signal?.removeEventListener("abort", abort);
|
|
25
|
+
try {
|
|
26
|
+
queue.leave();
|
|
27
|
+
}
|
|
28
|
+
catch { }
|
|
29
|
+
if (room)
|
|
30
|
+
resolve(room);
|
|
31
|
+
else
|
|
32
|
+
reject(error || Error("MATCH_CANCELLED"));
|
|
33
|
+
};
|
|
34
|
+
const abort = () => finish(undefined, Error("MATCH_CANCELLED"));
|
|
35
|
+
const timeout = setTimeout(() => finish(undefined, Error("WOVOON_MATCH_TIMEOUT")), 120000);
|
|
36
|
+
signal?.addEventListener("abort", abort, { once: true });
|
|
37
|
+
if (signal?.aborted) {
|
|
38
|
+
abort();
|
|
39
|
+
return;
|
|
40
|
+
}
|
|
41
|
+
queue.onMessage(frame => { if (frame?.type === "matched" && typeof frame.roomId === "string")
|
|
42
|
+
finish(frame.roomId); });
|
|
43
|
+
const poll = async () => {
|
|
44
|
+
const seat = await query("status").catch(() => undefined);
|
|
45
|
+
if (ended)
|
|
46
|
+
return;
|
|
47
|
+
if (seat?.status === "ASSIGNED" && seat.roomId) {
|
|
48
|
+
finish(seat.roomId);
|
|
49
|
+
return;
|
|
50
|
+
}
|
|
51
|
+
timer = setTimeout(poll, 1500);
|
|
52
|
+
};
|
|
53
|
+
timer = setTimeout(poll, 1500);
|
|
54
|
+
});
|
|
55
|
+
}
|
package/dist/protocol.d.ts
CHANGED
|
@@ -5,7 +5,7 @@
|
|
|
5
5
|
/** 协议版本。协议 1 是当前唯一支持的版本。 */
|
|
6
6
|
export declare const WOVOON_PROTOCOL_VERSION: 1;
|
|
7
7
|
/** 协议 1 冻结的能力名。集合能力形如 `collection:${WovoonCollectionName}`。 */
|
|
8
|
-
export type WovoonCapability = "identity" | `collection:${WovoonCollectionName}` | "function" | "room" | "room:competitive" | "gamelogic";
|
|
8
|
+
export type WovoonCapability = "identity" | `collection:${WovoonCollectionName}` | "function" | "room" | "room:competitive" | "ads" | "commerce" | "gamelogic";
|
|
9
9
|
/** 集合名:2-32 位,小写字母开头,仅小写字母/数字/下划线。运行时校验用下方正则。 */
|
|
10
10
|
export type WovoonCollectionName = string;
|
|
11
11
|
export declare const COLLECTION_NAME_PATTERN: RegExp;
|
package/dist/protocol.js
CHANGED
|
@@ -9,7 +9,7 @@ export function isValidCollectionName(name) {
|
|
|
9
9
|
return COLLECTION_NAME_PATTERN.test(name);
|
|
10
10
|
}
|
|
11
11
|
/** manifest 里单个能力名的完整合法形态(与平台 AssetSecurityScanner.parseContract 的校验一致)。 */
|
|
12
|
-
export const CAPABILITY_PATTERN = /^(identity|function|room|room:competitive|gamelogic|collection:[a-z][a-z0-9_]{1,31})$/;
|
|
12
|
+
export const CAPABILITY_PATTERN = /^(identity|function|room|room:competitive|gamelogic|ads|commerce|collection:[a-z][a-z0-9_]{1,31})$/;
|
|
13
13
|
export function isValidCapability(value) {
|
|
14
14
|
return CAPABILITY_PATTERN.test(value);
|
|
15
15
|
}
|