@wovoon/polaris 0.8.1 → 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),须满足:
@@ -79,13 +83,14 @@
79
83
  ## 云函数(function,协议 1)
80
84
 
81
85
  - 作品包站点根下 `functions/<name>.js`(CommonJS),文件名即函数名(2-31 位小写字母开头);
82
- - 每作品最多 16 个、单文件 64KB、总量 256KB;`.wovoon` 声明 `function` 能力即可调用;
86
+ - 每作品最多 16 个;云函数源码不设单文件或累计字节配额。作品归档的整体上传/展开规则与沙箱执行资源规则独立适用;`.wovoon` 声明 `function` 能力即可调用;
83
87
  - 形态:`exports.main = async (event, context) => (任意 JSON)`;入参/返回 ≤32KB;
84
88
  - 沙箱:默认限时 3s,声明可到 60s;最多 16 个并发执行。作品进程无网络、无平台环境变量和数据令牌,通过受信任代理读写集合。Linux 使用只读 Docker 容器(128 MB、0.5 CPU、16 PID);macOS 本地开发使用系统沙箱和 Node 权限模型(64 MB V8 堆,非总内存配额);
85
89
  - `context`:`{ player: {playerId, loggedIn}, cloud: { collection(name): {query, add, set} } }`;
86
90
  - 数据面写权限:仅 `writeRule=SERVER` 的集合(创作者经 manage 接口设置),玩家对该类集合只读;
87
91
  - 计量:作品日调用 200,000 次上限,玩家 30 次/分钟;调用接口 `POST /api/cloud/{app}/functions/{name}`;
88
- - 声明式集合:包站点根 `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/权限;不执行创作者源码。在线保存函数同样不限制源码大小。
89
94
  - 控制台在线管理(创作者登录态):`/api/cloud/manage/{app}/functions` 列表 / `PUT` 保存即部署 / `DELETE` / `POST .../test` 测试调用(系统身份);保存会重新读取函数自描述元数据;
90
95
  - 常驻化声明(写在函数代码内,平台静态读取):`exports.timeoutMs`(1s~60s 长任务档)、
91
96
  `exports.cron`(五字段 cron,分钟粒度调度,事件 `{type:'cron',scheduledAt}`)、
package/dist/client.d.ts CHANGED
@@ -4,6 +4,8 @@
4
4
  * 本模块提供同一 API 的 TypeScript 实现,供构建型项目以模块方式引入。
5
5
  */
6
6
  import { PolarisAds } from "./ads.js";
7
+ import { PolarisCommerce } from "./commerce.js";
8
+ import { PolarisGame, type GameOptions } from "./game.js";
7
9
  export interface PolarisRequestInit {
8
10
  /** 覆盖 API 基址(本地模拟器/自建环境用),默认同源。 */
9
11
  baseUrl?: string;
@@ -44,6 +46,9 @@ export interface PolarisQueryOptions {
44
46
  }
45
47
  declare function parseData<T = Record<string, unknown>>(raw: string): T;
46
48
  export declare class PolarisClient {
49
+ readonly commerce: PolarisCommerce;
50
+ private readonly activeGames;
51
+ game<State = unknown>(mode: string, options: GameOptions<State>): PolarisGame<State>;
47
52
  readonly ads: PolarisAds;
48
53
  private readonly baseUrl;
49
54
  private sessionPromise;
@@ -79,6 +84,7 @@ export declare class PolarisClient {
79
84
  room(roomId: string, options?: {
80
85
  mode?: string;
81
86
  }): {
87
+ trySend: (data: unknown, maxBufferedBytes?: number) => boolean;
82
88
  send: (data: unknown) => void;
83
89
  leave: () => void;
84
90
  onMessage: (callback: (payload: {
@@ -90,6 +96,7 @@ export declare class PolarisClient {
90
96
  };
91
97
  /** 世界总线:全服事件流(权威房间 ctx.worldBroadcast 广播到此),用法同房间。 */
92
98
  world(): {
99
+ trySend: (data: unknown, maxBufferedBytes?: number) => boolean;
93
100
  send: (data: unknown) => void;
94
101
  leave: () => void;
95
102
  onMessage: (callback: (payload: {
@@ -100,7 +107,9 @@ export declare class PolarisClient {
100
107
  onClose: (callback: (payload: unknown) => void) => void;
101
108
  };
102
109
  /** 内置匹配:凑满 exports.matchSize 人成局 → resolve 目标房间号(再 room(roomId, {mode}) 进入)。 */
103
- match(mode: string): Promise<string>;
110
+ match(mode: string, options?: {
111
+ signal?: AbortSignal;
112
+ }): Promise<string>;
104
113
  /** 房间列表(大厅/分线选择)。 */
105
114
  rooms(options?: {
106
115
  mode?: string;
package/dist/client.js CHANGED
@@ -4,6 +4,9 @@
4
4
  * 本模块提供同一 API 的 TypeScript 实现,供构建型项目以模块方式引入。
5
5
  */
6
6
  import { PolarisAds } from "./ads.js";
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
- if (!mode)
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,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 {};
@@ -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
+ }