castle-web-sdk 0.4.47 → 0.4.49
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/README.md +260 -3
- package/dist/castle.d.ts +7 -3
- package/dist/castle.js +2 -0
- package/dist/commands.d.ts +162 -1
- package/dist/commands.js +3 -0
- package/dist/display.d.ts +3 -0
- package/dist/display.js +9 -3
- package/dist/hub.d.ts +33 -6
- package/dist/hub.js +50 -4
- package/dist/multiplayer.d.ts +7 -1
- package/dist/multiplayer.js +140 -40
- package/dist/multiplayerProtocol.d.ts +2 -0
- package/dist/party.d.ts +23 -0
- package/dist/party.js +91 -0
- package/dist/reconnectBudget.d.ts +23 -0
- package/dist/reconnectBudget.js +96 -0
- package/dist/save.d.ts +38 -1
- package/dist/save.js +79 -6
- package/dist/server/hub.d.ts +31 -1
- package/dist/server/hub.js +50 -3
- package/dist/server/platformHandle.d.ts +13 -1
- package/dist/server/storage.d.ts +4 -0
- package/dist/server/storage.js +19 -3
- package/dist/server/wrapper.d.ts +7 -1
- package/dist/server/wrapper.js +10 -1
- package/dist/social.d.ts +9 -0
- package/dist/social.js +5 -0
- package/package.json +1 -1
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
export declare class ReconnectBudget {
|
|
2
|
+
private elapsed;
|
|
3
|
+
private lastSeen;
|
|
4
|
+
private heartbeat;
|
|
5
|
+
private wokeSinceAttempt;
|
|
6
|
+
private gapGraceUsed;
|
|
7
|
+
private frozen;
|
|
8
|
+
private disposed;
|
|
9
|
+
private readonly waiters;
|
|
10
|
+
private readonly page;
|
|
11
|
+
constructor();
|
|
12
|
+
get elapsedMs(): number;
|
|
13
|
+
noteAttempt(): void;
|
|
14
|
+
exhausted(limitMs: number): boolean;
|
|
15
|
+
waitUntilActive(): Promise<void>;
|
|
16
|
+
dispose(): void;
|
|
17
|
+
private readonly freeze;
|
|
18
|
+
private readonly resume;
|
|
19
|
+
private readonly update;
|
|
20
|
+
private readonly observe;
|
|
21
|
+
private stop;
|
|
22
|
+
private wakeWaiters;
|
|
23
|
+
}
|
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
// Recovery gets foreground time to retry. A phone can suspend JavaScript for
|
|
2
|
+
// minutes, so a wall-clock deadline would already be spent when it returns.
|
|
3
|
+
// Not every suspension is announced (a debugger pause, a native app pausing
|
|
4
|
+
// its web view while the document stays visible), so active time accrues in
|
|
5
|
+
// heartbeat steps and a gap longer than one step counts only that step.
|
|
6
|
+
const HEARTBEAT_MS = 1_000;
|
|
7
|
+
const MAX_STEP_MS = 2_000;
|
|
8
|
+
export class ReconnectBudget {
|
|
9
|
+
elapsed = 0;
|
|
10
|
+
lastSeen = null;
|
|
11
|
+
heartbeat = null;
|
|
12
|
+
// Set on every return to the foreground, announced or not; cleared by an attempt.
|
|
13
|
+
wokeSinceAttempt = false;
|
|
14
|
+
// A detected gap earns that try once per outage: a slow phone dropping
|
|
15
|
+
// frames for minutes would otherwise renew it forever.
|
|
16
|
+
gapGraceUsed = false;
|
|
17
|
+
frozen = false;
|
|
18
|
+
disposed = false;
|
|
19
|
+
waiters = new Set();
|
|
20
|
+
page = typeof document === "undefined" ? null : document;
|
|
21
|
+
constructor() {
|
|
22
|
+
this.page?.addEventListener("visibilitychange", this.update);
|
|
23
|
+
this.page?.addEventListener("freeze", this.freeze);
|
|
24
|
+
this.page?.addEventListener("resume", this.resume);
|
|
25
|
+
this.update();
|
|
26
|
+
}
|
|
27
|
+
get elapsedMs() {
|
|
28
|
+
this.observe();
|
|
29
|
+
return this.elapsed;
|
|
30
|
+
}
|
|
31
|
+
noteAttempt() {
|
|
32
|
+
this.wokeSinceAttempt = false;
|
|
33
|
+
}
|
|
34
|
+
// Spent only once an attempt has run since the page last came back, so a
|
|
35
|
+
// stall at the edge of the budget still gets one try with what it holds.
|
|
36
|
+
exhausted(limitMs) {
|
|
37
|
+
return this.elapsedMs >= limitMs && !this.wokeSinceAttempt;
|
|
38
|
+
}
|
|
39
|
+
waitUntilActive() {
|
|
40
|
+
if (this.disposed || this.lastSeen !== null)
|
|
41
|
+
return Promise.resolve();
|
|
42
|
+
return new Promise((resolve) => this.waiters.add(resolve));
|
|
43
|
+
}
|
|
44
|
+
dispose() {
|
|
45
|
+
this.disposed = true;
|
|
46
|
+
this.stop();
|
|
47
|
+
this.page?.removeEventListener("visibilitychange", this.update);
|
|
48
|
+
this.page?.removeEventListener("freeze", this.freeze);
|
|
49
|
+
this.page?.removeEventListener("resume", this.resume);
|
|
50
|
+
this.wakeWaiters();
|
|
51
|
+
}
|
|
52
|
+
freeze = () => {
|
|
53
|
+
this.frozen = true;
|
|
54
|
+
this.update();
|
|
55
|
+
};
|
|
56
|
+
resume = () => {
|
|
57
|
+
this.frozen = false;
|
|
58
|
+
this.update();
|
|
59
|
+
};
|
|
60
|
+
update = () => {
|
|
61
|
+
const active = !this.disposed && !this.frozen && this.page?.visibilityState !== "hidden";
|
|
62
|
+
if (active && this.lastSeen === null) {
|
|
63
|
+
this.lastSeen = Date.now();
|
|
64
|
+
this.heartbeat = setInterval(this.observe, HEARTBEAT_MS);
|
|
65
|
+
this.wokeSinceAttempt = true;
|
|
66
|
+
this.wakeWaiters();
|
|
67
|
+
}
|
|
68
|
+
else if (!active && this.lastSeen !== null) {
|
|
69
|
+
this.stop();
|
|
70
|
+
}
|
|
71
|
+
};
|
|
72
|
+
observe = () => {
|
|
73
|
+
if (this.lastSeen === null)
|
|
74
|
+
return;
|
|
75
|
+
const now = Date.now();
|
|
76
|
+
const gap = now - this.lastSeen;
|
|
77
|
+
if (gap > MAX_STEP_MS && !this.gapGraceUsed) {
|
|
78
|
+
this.gapGraceUsed = true;
|
|
79
|
+
this.wokeSinceAttempt = true;
|
|
80
|
+
}
|
|
81
|
+
this.elapsed += Math.min(Math.max(gap, 0), MAX_STEP_MS);
|
|
82
|
+
this.lastSeen = now;
|
|
83
|
+
};
|
|
84
|
+
stop() {
|
|
85
|
+
this.observe();
|
|
86
|
+
this.lastSeen = null;
|
|
87
|
+
if (this.heartbeat !== null)
|
|
88
|
+
clearInterval(this.heartbeat);
|
|
89
|
+
this.heartbeat = null;
|
|
90
|
+
}
|
|
91
|
+
wakeWaiters() {
|
|
92
|
+
for (const resolve of this.waiters)
|
|
93
|
+
resolve();
|
|
94
|
+
this.waiters.clear();
|
|
95
|
+
}
|
|
96
|
+
}
|
package/dist/save.d.ts
CHANGED
|
@@ -63,6 +63,19 @@ export interface SaveTransactionInput {
|
|
|
63
63
|
checks?: SaveCheck[];
|
|
64
64
|
changes: SaveChange[];
|
|
65
65
|
}
|
|
66
|
+
export interface SaveConditionalCheck extends Omit<SaveCheck, "expectedRevision"> {
|
|
67
|
+
/** Null checks absence without creating the target. */
|
|
68
|
+
expectedRevision: SaveRevision | null;
|
|
69
|
+
}
|
|
70
|
+
export interface SaveConditionalWriteInput extends Omit<SaveTransactionInput, "checks"> {
|
|
71
|
+
checks?: SaveConditionalCheck[];
|
|
72
|
+
/** Session servers only: atomically fence each affected player's progress reset. */
|
|
73
|
+
resetFences?: SaveResetFence[];
|
|
74
|
+
}
|
|
75
|
+
export interface SaveResetFence {
|
|
76
|
+
playerId: string;
|
|
77
|
+
resetGeneration: number;
|
|
78
|
+
}
|
|
66
79
|
export interface SaveInitial {
|
|
67
80
|
target: SaveTarget;
|
|
68
81
|
rows: SaveRows;
|
|
@@ -95,8 +108,24 @@ export type SaveOperation = {
|
|
|
95
108
|
} | {
|
|
96
109
|
state: "unknown";
|
|
97
110
|
};
|
|
98
|
-
export
|
|
111
|
+
export interface SaveRecentOperationsInput {
|
|
112
|
+
limit?: number;
|
|
113
|
+
cursor?: string;
|
|
114
|
+
}
|
|
115
|
+
export interface SaveRecentOperationsPage {
|
|
116
|
+
operations: {
|
|
117
|
+
operationId: string;
|
|
118
|
+
committedAt: string;
|
|
119
|
+
receipt: SaveReceipt;
|
|
120
|
+
}[];
|
|
121
|
+
cursor: string | null;
|
|
122
|
+
}
|
|
123
|
+
export type SaveVerb = "snapshot" | "transaction" | "claim" | "initialize" | "operation" | "conditionalWrite" | "recentOperations";
|
|
99
124
|
export interface SaveApi {
|
|
125
|
+
/** Gated atomic revision check and write, up to eight targets and two players. */
|
|
126
|
+
conditionalWrite(input: SaveConditionalWriteInput): Promise<SaveReceipt>;
|
|
127
|
+
/** Gated caller-scoped receipt discovery after losing local operation IDs. */
|
|
128
|
+
recentOperations(input?: SaveRecentOperationsInput): Promise<SaveRecentOperationsPage>;
|
|
100
129
|
snapshot(input: {
|
|
101
130
|
targets: SaveReadTarget[];
|
|
102
131
|
}): Promise<SaveSnapshot>;
|
|
@@ -156,6 +185,10 @@ export interface SaveErrorEnvelope {
|
|
|
156
185
|
receipt?: SaveReceipt;
|
|
157
186
|
retryAfterMs?: number;
|
|
158
187
|
target?: SaveTarget;
|
|
188
|
+
current?: SaveSnapshot;
|
|
189
|
+
playerId?: string;
|
|
190
|
+
expectedResetGeneration?: number;
|
|
191
|
+
resetGeneration?: number;
|
|
159
192
|
[detail: string]: unknown;
|
|
160
193
|
}
|
|
161
194
|
export declare class SaveError extends CastleError {
|
|
@@ -165,6 +198,10 @@ export declare class SaveError extends CastleError {
|
|
|
165
198
|
readonly receipt?: SaveReceipt;
|
|
166
199
|
readonly retryAfterMs?: number;
|
|
167
200
|
readonly target?: SaveTarget;
|
|
201
|
+
readonly current?: SaveSnapshot;
|
|
202
|
+
readonly playerId?: string;
|
|
203
|
+
readonly expectedResetGeneration?: number;
|
|
204
|
+
readonly resetGeneration?: number;
|
|
168
205
|
constructor(envelope: SaveErrorEnvelope);
|
|
169
206
|
}
|
|
170
207
|
/**
|
package/dist/save.js
CHANGED
|
@@ -7,6 +7,10 @@ export class SaveError extends CastleError {
|
|
|
7
7
|
receipt;
|
|
8
8
|
retryAfterMs;
|
|
9
9
|
target;
|
|
10
|
+
current;
|
|
11
|
+
playerId;
|
|
12
|
+
expectedResetGeneration;
|
|
13
|
+
resetGeneration;
|
|
10
14
|
constructor(envelope) {
|
|
11
15
|
super({
|
|
12
16
|
code: envelope.code,
|
|
@@ -20,6 +24,10 @@ export class SaveError extends CastleError {
|
|
|
20
24
|
this.receipt = envelope.receipt;
|
|
21
25
|
this.retryAfterMs = envelope.retryAfterMs;
|
|
22
26
|
this.target = envelope.target;
|
|
27
|
+
this.current = envelope.current;
|
|
28
|
+
this.playerId = envelope.playerId;
|
|
29
|
+
this.expectedResetGeneration = envelope.expectedResetGeneration;
|
|
30
|
+
this.resetGeneration = envelope.resetGeneration;
|
|
23
31
|
}
|
|
24
32
|
}
|
|
25
33
|
/**
|
|
@@ -241,12 +249,14 @@ function encodeChange(change, server) {
|
|
|
241
249
|
...(remove === undefined ? {} : { remove }),
|
|
242
250
|
};
|
|
243
251
|
}
|
|
244
|
-
function encodeCheck(check, server) {
|
|
252
|
+
function encodeCheck(check, server, conditional = false) {
|
|
245
253
|
const target = validateSaveTarget(check.target, server);
|
|
254
|
+
if (conditional && check.expectedRevision === undefined)
|
|
255
|
+
invalid("Every conditional check needs an expected revision.");
|
|
246
256
|
if (check.expectedRevision === undefined && check.writer === undefined) {
|
|
247
257
|
invalid("A check needs an expected revision or a writer.");
|
|
248
258
|
}
|
|
249
|
-
if (check.expectedRevision !== undefined) {
|
|
259
|
+
if (check.expectedRevision !== undefined && !(conditional && check.expectedRevision === null)) {
|
|
250
260
|
checkText(check.expectedRevision, "expected revision");
|
|
251
261
|
}
|
|
252
262
|
if (check.writer !== undefined)
|
|
@@ -259,7 +269,7 @@ function encodeCheck(check, server) {
|
|
|
259
269
|
...(check.writer === undefined ? {} : { writer: check.writer }),
|
|
260
270
|
};
|
|
261
271
|
}
|
|
262
|
-
function encodeTransaction(input, server) {
|
|
272
|
+
function encodeTransaction(input, server, conditional = false) {
|
|
263
273
|
const changes = checkList(input.changes, "changes").map((change) => encodeChange(change, server));
|
|
264
274
|
const keys = changes.map((change) => saveTargetKey(change.target));
|
|
265
275
|
if (new Set(keys).size !== keys.length) {
|
|
@@ -268,14 +278,35 @@ function encodeTransaction(input, server) {
|
|
|
268
278
|
return {
|
|
269
279
|
operationId: input.operationId,
|
|
270
280
|
expectedAccess: checkText(input.expectedAccess, "expected access"),
|
|
281
|
+
...(input.resetFences === undefined
|
|
282
|
+
? {}
|
|
283
|
+
: { resetFences: encodeResetFences(input.resetFences, server && conditional) }),
|
|
271
284
|
...(input.checks === undefined
|
|
272
285
|
? {}
|
|
273
286
|
: {
|
|
274
|
-
checks: checkList(input.checks, "checks").map((check) => encodeCheck(check, server)),
|
|
287
|
+
checks: checkList(input.checks, "checks").map((check) => encodeCheck(check, server, conditional)),
|
|
275
288
|
}),
|
|
276
289
|
changes,
|
|
277
290
|
};
|
|
278
291
|
}
|
|
292
|
+
function encodeResetFences(value, allowed) {
|
|
293
|
+
if (!allowed || !Array.isArray(value) || value.length < 1 || value.length > 2)
|
|
294
|
+
invalid("resetFences requires one or two players on a server conditional write.");
|
|
295
|
+
const seen = new Set();
|
|
296
|
+
return value.map((entry) => {
|
|
297
|
+
if (!entry || typeof entry !== "object" || Array.isArray(entry) ||
|
|
298
|
+
Reflect.ownKeys(entry).length !== 2 ||
|
|
299
|
+
!Object.hasOwn(entry, "playerId") || !Object.hasOwn(entry, "resetGeneration"))
|
|
300
|
+
invalid("Invalid reset fence.");
|
|
301
|
+
const fence = entry;
|
|
302
|
+
if (typeof fence.playerId !== "string" || !/^[1-9][0-9]{0,19}$/.test(fence.playerId) ||
|
|
303
|
+
seen.has(fence.playerId) || !Number.isInteger(fence.resetGeneration) ||
|
|
304
|
+
fence.resetGeneration < 0 || fence.resetGeneration > 2147483647)
|
|
305
|
+
invalid("Invalid reset fence player or generation.");
|
|
306
|
+
seen.add(fence.playerId);
|
|
307
|
+
return { playerId: fence.playerId, resetGeneration: fence.resetGeneration };
|
|
308
|
+
});
|
|
309
|
+
}
|
|
279
310
|
/** Validates and copies a request; the result is what goes on the wire. */
|
|
280
311
|
export function encodeSaveInput(verb, input, server = false) {
|
|
281
312
|
if (!input || typeof input !== "object" || Array.isArray(input)) {
|
|
@@ -283,12 +314,26 @@ export function encodeSaveInput(verb, input, server = false) {
|
|
|
283
314
|
}
|
|
284
315
|
if (verb === "snapshot")
|
|
285
316
|
return { targets: encodeReads(input.targets, server) };
|
|
317
|
+
if (verb === "recentOperations") {
|
|
318
|
+
const limit = input.limit ?? 16;
|
|
319
|
+
if (!Number.isInteger(limit) || limit < 1 || limit > 32)
|
|
320
|
+
invalid("Recovery limit must be 1 to 32.");
|
|
321
|
+
if (input.cursor !== undefined)
|
|
322
|
+
checkText(input.cursor, "recovery cursor", 2048);
|
|
323
|
+
return { limit, ...(input.cursor === undefined ? {} : { cursor: input.cursor }) };
|
|
324
|
+
}
|
|
286
325
|
checkText(input.operationId, "operation id", MAX_KEY_BYTES);
|
|
287
326
|
if (verb === "operation")
|
|
288
327
|
return { operationId: input.operationId };
|
|
289
|
-
if (verb === "transaction") {
|
|
328
|
+
if (verb === "transaction" || verb === "conditionalWrite") {
|
|
329
|
+
if (verb === "conditionalWrite") {
|
|
330
|
+
const changes = input.changes;
|
|
331
|
+
const checks = input.checks ?? [];
|
|
332
|
+
if (!Array.isArray(changes) || !changes.length || changes.length + checks.length > 8)
|
|
333
|
+
invalid("Conditional writes require 1 to 8 targets.");
|
|
334
|
+
}
|
|
290
335
|
return {
|
|
291
|
-
...encodeTransaction(input, server),
|
|
336
|
+
...encodeTransaction(input, server, verb === "conditionalWrite"),
|
|
292
337
|
};
|
|
293
338
|
}
|
|
294
339
|
if (input.expectedAccess !== undefined) {
|
|
@@ -423,6 +468,34 @@ export function createSaveApi(call, server = false) {
|
|
|
423
468
|
}
|
|
424
469
|
}
|
|
425
470
|
return {
|
|
471
|
+
async conditionalWrite(input) {
|
|
472
|
+
const result = await send("conditionalWrite", { ...input });
|
|
473
|
+
return decodeReceipt(result, input.operationId, input.changes.map((change) => change.target));
|
|
474
|
+
},
|
|
475
|
+
async recentOperations(input = {}) {
|
|
476
|
+
const page = (await send("recentOperations", {
|
|
477
|
+
...input,
|
|
478
|
+
}));
|
|
479
|
+
if (!page ||
|
|
480
|
+
!Array.isArray(page.operations) ||
|
|
481
|
+
page.operations.length > (input.limit ?? 16) ||
|
|
482
|
+
(page.cursor !== null && typeof page.cursor !== "string"))
|
|
483
|
+
invalidResponse();
|
|
484
|
+
return {
|
|
485
|
+
operations: page.operations.map((operation) => {
|
|
486
|
+
if (!operation ||
|
|
487
|
+
typeof operation.operationId !== "string" ||
|
|
488
|
+
typeof operation.committedAt !== "string")
|
|
489
|
+
invalidResponse();
|
|
490
|
+
return {
|
|
491
|
+
operationId: operation.operationId,
|
|
492
|
+
committedAt: operation.committedAt,
|
|
493
|
+
receipt: decodeReceipt(operation.receipt, operation.operationId, []),
|
|
494
|
+
};
|
|
495
|
+
}),
|
|
496
|
+
cursor: page.cursor,
|
|
497
|
+
};
|
|
498
|
+
},
|
|
426
499
|
async snapshot(input) {
|
|
427
500
|
return decodeSnapshot(await send("snapshot", { ...input }), input.targets);
|
|
428
501
|
},
|
package/dist/server/hub.d.ts
CHANGED
|
@@ -184,8 +184,34 @@ export interface MultiplayerHubResultsRead {
|
|
|
184
184
|
* and for a deck that declares no hub block.
|
|
185
185
|
*/
|
|
186
186
|
export interface MultiplayerServerHub {
|
|
187
|
+
/** Present only for an enabled place on a capable runtime. Reports visits; Ghost owns comeback delivery. */
|
|
188
|
+
readonly push?: {
|
|
189
|
+
visit(playerId: string, visit: {
|
|
190
|
+
userId: string;
|
|
191
|
+
timezone: string;
|
|
192
|
+
}): Promise<boolean>;
|
|
193
|
+
};
|
|
194
|
+
/** Durably appends NPC words to a private platform archive. No read operation. */
|
|
195
|
+
archiveText(playerId: string, entry: {
|
|
196
|
+
npcId: string;
|
|
197
|
+
characterId?: string;
|
|
198
|
+
conversationId?: string;
|
|
199
|
+
operationId: string;
|
|
200
|
+
input?: string;
|
|
201
|
+
reply?: string;
|
|
202
|
+
}): Promise<void>;
|
|
203
|
+
/** Numeric hub telemetry; unavailable/refused delivery returns false, never blocks play. */
|
|
204
|
+
track(playerId: string, event: {
|
|
205
|
+
kind: number;
|
|
206
|
+
subject?: number;
|
|
207
|
+
value?: number;
|
|
208
|
+
result?: number;
|
|
209
|
+
flags?: number;
|
|
210
|
+
}): Promise<boolean>;
|
|
187
211
|
/** The owner user id, only in an owner door instance. */
|
|
188
212
|
readonly owner?: string;
|
|
213
|
+
/** Host-pinned inclusive reconnect grace for this hub place, in milliseconds. */
|
|
214
|
+
readonly reconnectWindowMs?: number;
|
|
189
215
|
readonly place: string | null;
|
|
190
216
|
readonly title: string | null;
|
|
191
217
|
readonly result: MultiplayerHubResultShape | null;
|
|
@@ -236,9 +262,13 @@ export interface MultiplayerServerHub {
|
|
|
236
262
|
/**
|
|
237
263
|
* The connected player's mutual friends and follows in either direction among
|
|
238
264
|
* these candidates, in one host read. Missing lists are empty; refusals reject.
|
|
265
|
+
* Optional strict mode rejects malformed raw lists and marks the result validated.
|
|
239
266
|
* These relations belong to this player only; never send them to another client.
|
|
240
267
|
*/
|
|
241
|
-
relationsAmong(playerId: string, userIds: readonly string[]
|
|
268
|
+
relationsAmong(playerId: string, userIds: readonly string[], options?: {
|
|
269
|
+
strict: true;
|
|
270
|
+
}): Promise<{
|
|
271
|
+
validated?: true;
|
|
242
272
|
friends: string[];
|
|
243
273
|
follows: string[];
|
|
244
274
|
followedBy: string[];
|
package/dist/server/hub.js
CHANGED
|
@@ -46,6 +46,11 @@ function unavailable(op, what) {
|
|
|
46
46
|
operation: `session.hub.${op}`,
|
|
47
47
|
});
|
|
48
48
|
}
|
|
49
|
+
function reconnectMetadata(pinned) {
|
|
50
|
+
const value = pinned.reconnectWindowMs;
|
|
51
|
+
return pinned.result === null && typeof value === "number" && Number.isInteger(value) && value > 0 && value <= 180_000
|
|
52
|
+
? { reconnectWindowMs: value } : {};
|
|
53
|
+
}
|
|
49
54
|
export function createServerHub(platformHandle, arrivals, hiddenPair = () => false) {
|
|
50
55
|
const pinned = platformHandle.hub;
|
|
51
56
|
if (!pinned ||
|
|
@@ -72,17 +77,35 @@ export function createServerHub(platformHandle, arrivals, hiddenPair = () => fal
|
|
|
72
77
|
}
|
|
73
78
|
return parsed;
|
|
74
79
|
};
|
|
75
|
-
|
|
80
|
+
const hub = {
|
|
81
|
+
...pushCapability(platformHandle),
|
|
82
|
+
async archiveText(playerId, entry) {
|
|
83
|
+
if (platformHandle.hubTextArchiveEnabled !== true || typeof platformHandle.storage !== "function")
|
|
84
|
+
throw unavailable("archiveText", "archive NPC transcripts");
|
|
85
|
+
if (JSON.parse(await platformHandle.storage("hubTextArchive", JSON.stringify({ ...entry, playerId })))?.recorded !== true)
|
|
86
|
+
throw unavailable("archiveText", "archive NPC transcripts");
|
|
87
|
+
},
|
|
76
88
|
place: typeof pinned.place === "string" ? pinned.place : null,
|
|
77
89
|
title: typeof pinned.title === "string" ? pinned.title : null,
|
|
78
90
|
result: pinned.result ?? null,
|
|
79
91
|
...(typeof pinned.owner === "string" && pinned.owner.length > 0 ? { owner: pinned.owner } : {}),
|
|
92
|
+
...reconnectMetadata(pinned),
|
|
80
93
|
arrival(playerId) {
|
|
81
94
|
return arrivals.get(playerId) ?? null;
|
|
82
95
|
},
|
|
83
96
|
hiddenPair(playerIdA, playerIdB) {
|
|
84
97
|
return hiddenPair(playerIdA, playerIdB);
|
|
85
98
|
},
|
|
99
|
+
async track(playerId, event) {
|
|
100
|
+
try {
|
|
101
|
+
const json = JSON.stringify({ ...event, playerId });
|
|
102
|
+
const raw = await platformHandle.storage?.("hubTrack", json);
|
|
103
|
+
return JSON.parse(raw ?? "null")?.recorded === true;
|
|
104
|
+
}
|
|
105
|
+
catch {
|
|
106
|
+
return false;
|
|
107
|
+
}
|
|
108
|
+
},
|
|
86
109
|
async friendsAmong(playerId, userIds) {
|
|
87
110
|
const json = JSON.stringify({ playerId, userIds: [...userIds] });
|
|
88
111
|
const raw = typeof platformHandle.hubFriendsAmong === "function"
|
|
@@ -91,7 +114,7 @@ export function createServerHub(platformHandle, arrivals, hiddenPair = () => fal
|
|
|
91
114
|
const answer = JSON.parse(raw ?? "null");
|
|
92
115
|
return Array.isArray(answer?.userIds) ? answer.userIds : [];
|
|
93
116
|
},
|
|
94
|
-
async relationsAmong(playerId, userIds) {
|
|
117
|
+
async relationsAmong(playerId, userIds, options = undefined) {
|
|
95
118
|
const asked = new Set(userIds);
|
|
96
119
|
const json = JSON.stringify({ playerId, userIds: [...userIds] });
|
|
97
120
|
let raw;
|
|
@@ -102,10 +125,14 @@ export function createServerHub(platformHandle, arrivals, hiddenPair = () => fal
|
|
|
102
125
|
raw = await platformHandle.storage?.("hubFriendsAmong", json);
|
|
103
126
|
}
|
|
104
127
|
const answer = JSON.parse(raw ?? "null");
|
|
128
|
+
if (options?.strict === true && (!answer || ["userIds", "follows", "followedBy"].some((key) => !Array.isArray(answer[key]) || answer[key].length > 100 || answer[key].some((id) => typeof id !== "string" || !/^\d{1,20}$/.test(id) || !asked.has(id))))) {
|
|
129
|
+
throw new CastleError({ code: "CAULDRON_HUB_INVALID_RESPONSE", message: "The platform returned an invalid friends response.", operation: "session.hub.relationsAmong" });
|
|
130
|
+
}
|
|
105
131
|
const list = (value) => Array.isArray(value)
|
|
106
132
|
? value.filter((id) => typeof id === "string" && asked.has(id))
|
|
107
133
|
: [];
|
|
108
134
|
return {
|
|
135
|
+
...(options?.strict === true ? { validated: true } : {}),
|
|
109
136
|
friends: list(answer?.userIds),
|
|
110
137
|
follows: list(answer?.follows),
|
|
111
138
|
followedBy: list(answer?.followedBy),
|
|
@@ -191,5 +218,25 @@ export function createServerHub(platformHandle, arrivals, hiddenPair = () => fal
|
|
|
191
218
|
players: (read.players ?? {}),
|
|
192
219
|
};
|
|
193
220
|
},
|
|
194
|
-
}
|
|
221
|
+
};
|
|
222
|
+
// Preserve the enumerable API shape and diagnostic serialization of existing
|
|
223
|
+
// places. Opted-in kits call this method explicitly; it adds no wire field.
|
|
224
|
+
Object.defineProperty(hub, "track", { enumerable: false });
|
|
225
|
+
Object.defineProperty(hub, "archiveText", { enumerable: false });
|
|
226
|
+
return Object.freeze(hub);
|
|
227
|
+
}
|
|
228
|
+
async function pushVisitCall(call, playerId, args) {
|
|
229
|
+
try {
|
|
230
|
+
return JSON.parse(await call(JSON.stringify({ ...args, playerId })))?.accepted === true;
|
|
231
|
+
}
|
|
232
|
+
catch {
|
|
233
|
+
return false;
|
|
234
|
+
}
|
|
235
|
+
}
|
|
236
|
+
function pushCapability(handle) {
|
|
237
|
+
if (handle.hub?.push?.version !== 1 || typeof handle.hubPushVisit !== "function")
|
|
238
|
+
return {};
|
|
239
|
+
return { push: {
|
|
240
|
+
visit: (playerId, visit) => pushVisitCall((raw) => handle.hubPushVisit(raw), playerId, visit),
|
|
241
|
+
} };
|
|
195
242
|
}
|
|
@@ -6,6 +6,8 @@ export interface PlayerIdentity {
|
|
|
6
6
|
username: string;
|
|
7
7
|
isAnonymous: boolean;
|
|
8
8
|
scopedUserId?: string;
|
|
9
|
+
/** Trusted hub age boundary; omitted by older hosts. Never client supplied. */
|
|
10
|
+
under13?: boolean;
|
|
9
11
|
}
|
|
10
12
|
export interface PlatformSessionConfig {
|
|
11
13
|
readonly sessionId: string;
|
|
@@ -66,11 +68,16 @@ export interface PlatformHandle {
|
|
|
66
68
|
storage?(op: string, argsJson: string): Promise<string>;
|
|
67
69
|
/** False when the host cannot broker storage, so a call can fail at once. */
|
|
68
70
|
readonly storageEnabled?: boolean;
|
|
71
|
+
readonly hubTextArchiveEnabled?: boolean;
|
|
69
72
|
/** Persistent-world checkpoint broker. The host stamps the hidden world binding. */
|
|
70
73
|
worldCheckpointRead?(): Promise<string>;
|
|
71
74
|
worldCheckpointCommit?(argsJson: string): Promise<string>;
|
|
72
75
|
/** `tools` is the turn's place tools, passed only when non-empty. */
|
|
73
|
-
worldCharacterSend?(grantId: string, tools?: readonly PlatformPlaceTool[]
|
|
76
|
+
worldCharacterSend?(grantId: string, tools?: readonly PlatformPlaceTool[], hubTextArchive?: {
|
|
77
|
+
npcId: string;
|
|
78
|
+
conversationId?: string;
|
|
79
|
+
input: string;
|
|
80
|
+
}): Promise<string>;
|
|
74
81
|
worldCharacterCommand?(grantId: string): Promise<string>;
|
|
75
82
|
worldCharacterRead?(grantId: string): Promise<string>;
|
|
76
83
|
worldCharacterRuntimeCreate?(argsJson: string): Promise<string>;
|
|
@@ -92,6 +99,7 @@ export interface PlatformHandle {
|
|
|
92
99
|
hubResultsRead?(argsJson: string): Promise<string>;
|
|
93
100
|
/** Friends among candidates (hub contract v1.36); older images use storage. */
|
|
94
101
|
hubFriendsAmong?(argsJson: string): Promise<string>;
|
|
102
|
+
hubPushVisit?(argsJson: string): Promise<string>;
|
|
95
103
|
/** Absent on a runtime older than wearables (contract v1.4). */
|
|
96
104
|
hubWear?(argsJson: string): Promise<string>;
|
|
97
105
|
/** Absent on a runtime older than earned items (contract v1.53). */
|
|
@@ -113,7 +121,11 @@ export interface PlatformHubResultShape {
|
|
|
113
121
|
stats: Record<string, "number" | "string">;
|
|
114
122
|
}
|
|
115
123
|
export interface PlatformHubPlace {
|
|
124
|
+
push?: {
|
|
125
|
+
version: 1;
|
|
126
|
+
};
|
|
116
127
|
owner?: string;
|
|
128
|
+
reconnectWindowMs?: number;
|
|
117
129
|
place?: string;
|
|
118
130
|
title?: string | null;
|
|
119
131
|
result?: PlatformHubResultShape | null;
|
package/dist/server/storage.d.ts
CHANGED
|
@@ -51,6 +51,8 @@ export interface ServerStorageBoard {
|
|
|
51
51
|
*/
|
|
52
52
|
export interface ServerPlaythrough {
|
|
53
53
|
readonly generation: number;
|
|
54
|
+
/** Present only after an administrator reset this player's deck progress. */
|
|
55
|
+
readonly resetGeneration?: number;
|
|
54
56
|
/** Explicit narrative changes for this same player and generation. */
|
|
55
57
|
readonly characters: ServerPlaythroughCharacters;
|
|
56
58
|
get<T extends Json = Json>(keys: string[]): Promise<Record<string, T>>;
|
|
@@ -265,6 +267,8 @@ export interface ServerCharacterHistoryOptions {
|
|
|
265
267
|
cursor?: string | null;
|
|
266
268
|
}
|
|
267
269
|
export interface ServerStorage extends SaveApi {
|
|
270
|
+
/** Reads the authoritative progress-reset generation, including never-reset zero. */
|
|
271
|
+
resetGeneration(userId: string): Promise<number>;
|
|
268
272
|
/** Shared by everyone playing the deck, and owned by this server. */
|
|
269
273
|
readonly deck: ServerStorageScope;
|
|
270
274
|
/** One player's public data. Readable by anyone; writable by them or by this server. */
|
package/dist/server/storage.js
CHANGED
|
@@ -76,6 +76,14 @@ export function createServerStorage(platformHandle) {
|
|
|
76
76
|
}, true);
|
|
77
77
|
return {
|
|
78
78
|
...saveApi,
|
|
79
|
+
async resetGeneration(userId) {
|
|
80
|
+
const subject = assertUserId(userId, "session.storage.resetGeneration");
|
|
81
|
+
const value = await call("resetGeneration", { subject });
|
|
82
|
+
if (!Number.isInteger(value) || value < 0 || value > MAX_GENERATION) {
|
|
83
|
+
throw storageError("CAULDRON_STORAGE_INVALID_RESPONSE", "The platform returned an invalid progress reset generation.", "session.storage.resetGeneration");
|
|
84
|
+
}
|
|
85
|
+
return value;
|
|
86
|
+
},
|
|
79
87
|
deck: createScope(call, "DECK", null, saveApi),
|
|
80
88
|
user(userId) {
|
|
81
89
|
// A bad id poisons the scope rather than throwing here, so the failure arrives
|
|
@@ -100,11 +108,11 @@ export function createServerStorage(platformHandle) {
|
|
|
100
108
|
async playthrough(userId) {
|
|
101
109
|
const subject = assertUserId(userId, "session.storage.playthrough");
|
|
102
110
|
const opened = await call("playthroughOpen", { subject });
|
|
103
|
-
return createPlaythrough(call, subject, assertGeneration(opened?.generation));
|
|
111
|
+
return createPlaythrough(call, subject, assertGeneration(opened?.generation), optionalResetGeneration(opened?.resetGeneration));
|
|
104
112
|
},
|
|
105
113
|
};
|
|
106
114
|
}
|
|
107
|
-
function createPlaythrough(call, subject, generation) {
|
|
115
|
+
function createPlaythrough(call, subject, generation, resetGeneration) {
|
|
108
116
|
const characters = Object.freeze({
|
|
109
117
|
async send(input) {
|
|
110
118
|
const characterId = assertNarrativeId(input?.characterId, "characterId");
|
|
@@ -220,6 +228,7 @@ function createPlaythrough(call, subject, generation) {
|
|
|
220
228
|
});
|
|
221
229
|
return Object.freeze({
|
|
222
230
|
generation,
|
|
231
|
+
...(resetGeneration === undefined ? {} : { resetGeneration }),
|
|
223
232
|
characters,
|
|
224
233
|
async get(keys) {
|
|
225
234
|
const entries = await call("playthroughGet", { subject, generation, keys: assertKeys(keys, "session.storage.playthrough.get") });
|
|
@@ -242,7 +251,7 @@ function createPlaythrough(call, subject, generation) {
|
|
|
242
251
|
generation,
|
|
243
252
|
operationId: assertOperationId(operationId),
|
|
244
253
|
});
|
|
245
|
-
return createPlaythrough(call, subject, assertGeneration(reset?.generation));
|
|
254
|
+
return createPlaythrough(call, subject, assertGeneration(reset?.generation), resetGeneration);
|
|
246
255
|
},
|
|
247
256
|
});
|
|
248
257
|
}
|
|
@@ -417,6 +426,13 @@ function assertGeneration(value) {
|
|
|
417
426
|
}
|
|
418
427
|
return value;
|
|
419
428
|
}
|
|
429
|
+
function optionalResetGeneration(value) {
|
|
430
|
+
if (value === undefined || value === null)
|
|
431
|
+
return undefined;
|
|
432
|
+
if (Number.isSafeInteger(value) && value >= 1 && value <= MAX_GENERATION)
|
|
433
|
+
return value;
|
|
434
|
+
throw storageError("CAULDRON_STORAGE_INVALID_RESPONSE", "The platform returned an invalid progress reset generation.", "session.storage.playthrough");
|
|
435
|
+
}
|
|
420
436
|
function assertOperationId(value) {
|
|
421
437
|
if (typeof value !== "string" ||
|
|
422
438
|
value.length === 0 ||
|
package/dist/server/wrapper.d.ts
CHANGED
|
@@ -7,7 +7,7 @@ export type { MultiplayerSessionMode, PlatformHandle, PlatformSessionConfig, Pla
|
|
|
7
7
|
export { createSaveCoordinator } from "../saveCoordinator";
|
|
8
8
|
export type { CoordinatedChange, CoordinatedSave, SaveCoordinator, SaveStatus, } from "../saveCoordinator";
|
|
9
9
|
export { SaveError } from "../save";
|
|
10
|
-
export type { SaveApi, SaveBucketApi, SaveBucketRead, SaveChange, SaveCheck, SaveClaimed, SaveClaimInput, SaveErrorEnvelope, SaveInitial, SaveInitializeInput, SaveOpened, SaveOperation, SaveReadTarget, SaveReceipt, SaveRevision, SaveRows, SaveScope, SaveSelection, SaveSnapshot, SaveTarget, SaveTransactionInput, SaveWriter, } from "../save";
|
|
10
|
+
export type { SaveApi, SaveBucketApi, SaveBucketRead, SaveChange, SaveCheck, SaveConditionalCheck, SaveConditionalWriteInput, SaveResetFence, SaveClaimed, SaveClaimInput, SaveErrorEnvelope, SaveInitial, SaveInitializeInput, SaveOpened, SaveOperation, SaveReadTarget, SaveReceipt, SaveRecentOperationsInput, SaveRecentOperationsPage, SaveRevision, SaveRows, SaveScope, SaveSelection, SaveSnapshot, SaveTarget, SaveTransactionInput, SaveWriter, } from "../save";
|
|
11
11
|
export type { MultiplayerHubArrival, MultiplayerHubBoard, MultiplayerHubOutcome, MultiplayerHubPadUpdateInput, MultiplayerHubPadUpdateResult, MultiplayerHubPlayerResults, MultiplayerHubRecord, MultiplayerHubReportReceipt, MultiplayerHubResultInput, MultiplayerHubResultRow, MultiplayerHubResultShape, MultiplayerHubResultsRead, MultiplayerHubResultsReadInput, MultiplayerHubWearable, MultiplayerHubWearReceipt, MultiplayerHubEarnedClass, MultiplayerHubEarnedItem, MultiplayerHubHomeClass, MultiplayerHubHomeItem, MultiplayerHubUnlockReceipt, MultiplayerHubUnlocksRead, MultiplayerHubWearEarnedReceipt, MultiplayerServerHub, } from "./hub";
|
|
12
12
|
export type { CharacterActionNotice, CharacterGameStateOperation, CharacterGameStateResult, CharacterKnowledgeDeliveryOperation, CharacterKnowledgeDeliveryResult, CharacterKnowledgeSource, CompleteCharacterBeatInput, DeliverCharacterKnowledgeInput, RecordCharacterEventInput, SetCharacterGameStateInput, ShareCharacterClaimInput, ServerStorage, ServerStorageBoard, ServerStorageBoardScore, ServerStorageListEntry, ServerStorageListOptions, ServerStorageListPage, ServerPlaythrough, ServerPlaythroughCharacters, ServerCharacterHistoryOptions, ServerStorageScope, ServerTownStorage, } from "./storage";
|
|
13
13
|
export interface MultiplayerServerPlayer extends PlayerIdentity {
|
|
@@ -288,6 +288,12 @@ export interface MultiplayerWorldCharacterTurn {
|
|
|
288
288
|
export type MultiplayerPlaceTool = PlatformPlaceTool;
|
|
289
289
|
export interface MultiplayerWorldCharacterSendOptions {
|
|
290
290
|
tools?: readonly MultiplayerPlaceTool[];
|
|
291
|
+
/** Private host-brokered transcript metadata, not player-selected. */
|
|
292
|
+
hubTextArchive?: {
|
|
293
|
+
npcId: string;
|
|
294
|
+
conversationId?: string;
|
|
295
|
+
input: string;
|
|
296
|
+
};
|
|
291
297
|
}
|
|
292
298
|
/** One place-tool use by a character during a turn this place admitted. */
|
|
293
299
|
export interface MultiplayerWorldCharacterToolRequest {
|
package/dist/server/wrapper.js
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { CastleError } from "../errors";
|
|
1
2
|
import { isBinaryPayload, toUint8Array, } from "../multiplayerProtocol";
|
|
2
3
|
import { encodeStorageValue, storageError } from "../storageJson";
|
|
3
4
|
import { createServerStorage } from "./storage";
|
|
@@ -1193,6 +1194,11 @@ function assertPlatformWorldCharacterRead(value) {
|
|
|
1193
1194
|
// carrying anything beyond the grant); otherwise this is exactly the tool-less send.
|
|
1194
1195
|
function sendWorldCharacterTurn(platformHandle, grantId, options) {
|
|
1195
1196
|
const tools = options?.tools;
|
|
1197
|
+
if (options?.hubTextArchive !== undefined) {
|
|
1198
|
+
if (platformHandle.hubTextArchiveEnabled !== true)
|
|
1199
|
+
return Promise.reject(new CastleError({ code: 'CAULDRON_HUB_UNAVAILABLE', message: 'This host cannot archive NPC transcripts.', operation: 'worldCharacter.send' }));
|
|
1200
|
+
return platformHandle.worldCharacterSend(grantId, Array.isArray(tools) && typeof platformHandle.worldCharacterToolResult === "function" ? tools : undefined, options.hubTextArchive);
|
|
1201
|
+
}
|
|
1196
1202
|
return Array.isArray(tools) && tools.length > 0 &&
|
|
1197
1203
|
typeof platformHandle.worldCharacterToolResult === "function"
|
|
1198
1204
|
? platformHandle.worldCharacterSend(grantId, tools)
|
|
@@ -1419,10 +1425,11 @@ function joinedPlayer(connId, identity) {
|
|
|
1419
1425
|
delete player.hiddenUserIds;
|
|
1420
1426
|
// A/B arms arrive beside the player; one a host put on it stays off it too.
|
|
1421
1427
|
delete player.experimentVariants;
|
|
1428
|
+
Object.defineProperty(player, "under13", { value: identity.under13 === true, enumerable: false });
|
|
1422
1429
|
return player;
|
|
1423
1430
|
}
|
|
1424
1431
|
const legacy = connId;
|
|
1425
|
-
|
|
1432
|
+
const player = {
|
|
1426
1433
|
playerId: legacy.playerId,
|
|
1427
1434
|
userId: legacy.userId,
|
|
1428
1435
|
username: legacy.username,
|
|
@@ -1430,6 +1437,8 @@ function joinedPlayer(connId, identity) {
|
|
|
1430
1437
|
participantId: legacy.scopedUserId ?? legacy.userId,
|
|
1431
1438
|
...(legacy.scopedUserId ? { scopedUserId: legacy.scopedUserId } : {}),
|
|
1432
1439
|
};
|
|
1440
|
+
Object.defineProperty(player, "under13", { value: legacy.under13 === true, enumerable: false });
|
|
1441
|
+
return player;
|
|
1433
1442
|
}
|
|
1434
1443
|
function parseHandleMessage(text) {
|
|
1435
1444
|
if (typeof text !== "string")
|