castle-web-sdk 0.4.57 → 0.4.59
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 +216 -44
- package/dist/castle.d.ts +3 -0
- package/dist/castle.js +2 -0
- package/dist/commands.d.ts +37 -0
- package/dist/deckInvites.d.ts +31 -0
- package/dist/deckInvites.js +22 -0
- package/dist/runtime.js +49 -0
- package/dist/save.d.ts +13 -2
- package/dist/save.js +7 -2
- package/dist/server/platformHandle.d.ts +2 -0
- package/dist/server/storage.d.ts +25 -6
- package/dist/server/storage.js +41 -11
- package/dist/server/wrapper.d.ts +4 -0
- package/dist/server/wrapper.js +29 -1
- package/dist/transport.d.ts +1 -0
- package/dist/transport.js +134 -12
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -155,37 +155,77 @@ is. `session.place` is the hub place the host started the session for (see
|
|
|
155
155
|
[`session.hub`](#sessionhub)), and `null` otherwise. It is never taken from a
|
|
156
156
|
client.
|
|
157
157
|
|
|
158
|
+
### `session.sessionSecret` and `session.assets.read`
|
|
159
|
+
|
|
160
|
+
Both are available in `onStart`. `session.sessionSecret` is the host-provided
|
|
161
|
+
signing key for this session, or `undefined` when the host supplies no key.
|
|
162
|
+
The key is read-only and omitted from object inspection, spread, and default JSON
|
|
163
|
+
serialization. Code that names the property, by reading it or by passing it in a
|
|
164
|
+
`JSON.stringify` property list, gets the key. Read it directly through `session.sessionSecret`.
|
|
165
|
+
Keep the key server-side and out of messages, logs, and storage.
|
|
166
|
+
|
|
167
|
+
`await session.assets.read(name)` returns the exact bytes of a mounted session
|
|
168
|
+
asset as a `Uint8Array`, or `null` if the name is absent. On older runtimes
|
|
169
|
+
without session asset support, the promise rejects with an unavailable error.
|
|
170
|
+
`session.assets` is omitted from object keys, spread, and JSON serialization.
|
|
171
|
+
|
|
158
172
|
### `session.storage`
|
|
159
173
|
|
|
160
174
|
A session ends when its last player leaves, and its memory goes with it.
|
|
161
|
-
`session.storage` is what outlives one
|
|
162
|
-
clients see through [`Store`](#store)
|
|
175
|
+
`session.storage` is what outlives one. It is the same store the deck's
|
|
176
|
+
clients see through [`Store`](#store), with the same JSON values and
|
|
177
|
+
the same limits:
|
|
163
178
|
|
|
164
179
|
```js
|
|
165
180
|
export default {
|
|
166
181
|
async onPlayerJoin(session, player) {
|
|
167
|
-
const
|
|
168
|
-
|
|
182
|
+
const key = `wins:${player.userId}`;
|
|
183
|
+
const { [key]: wins = 0 } = await session.storage.deck.get([key]);
|
|
184
|
+
session.send(player.playerId, { type: "wins", wins });
|
|
185
|
+
},
|
|
186
|
+
|
|
187
|
+
async onMessage(session, player, data) {
|
|
188
|
+
if (data.type !== "move") return;
|
|
189
|
+
// Your rules decide the winner from the server's own game state,
|
|
190
|
+
// never from a client saying it won.
|
|
191
|
+
const winner = applyMove(session, player, data);
|
|
192
|
+
if (winner) {
|
|
193
|
+
const wins = await session.storage.deck.increment(`wins:${winner.userId}`);
|
|
194
|
+
session.broadcast({ type: "won", userId: winner.userId, wins });
|
|
195
|
+
}
|
|
169
196
|
},
|
|
170
197
|
|
|
171
198
|
async onShutdown(session) {
|
|
172
|
-
await session.storage.deck.set({ endedAt: Date.now() });
|
|
199
|
+
await session.storage.deck.set({ lastGame: { endedAt: Date.now() } });
|
|
173
200
|
},
|
|
174
201
|
};
|
|
175
202
|
```
|
|
176
203
|
|
|
177
|
-
`session.storage.deck` is shared by everyone playing.
|
|
178
|
-
`session.storage.user(userId)` is one player's public data
|
|
204
|
+
- `session.storage.deck` is shared by everyone playing.
|
|
205
|
+
- `session.storage.user(userId)` is one player's public data, the same
|
|
206
|
+
keys that player reads and writes as `Store.me`.
|
|
207
|
+
- `session.storage.board(name)` is a leaderboard.
|
|
208
|
+
|
|
209
|
+
Each scope has `get(keys)`, `set(values)`, `remove(keys)`,
|
|
210
|
+
`increment(key, delta?)` and `list({ prefix, limit, cursor })`, which
|
|
211
|
+
work as they do on `Store`, and the root and its buckets also support
|
|
212
|
+
the [atomic save API](#atomic-saves). A board has
|
|
213
|
+
`submit(userId, score)`, `top(limit?)` and `get(userId)`.
|
|
214
|
+
|
|
179
215
|
`await session.storage.playthrough(userId)` opens that player's generation-bound
|
|
180
216
|
game state. Its `resetGeneration` is present only after an administrator has
|
|
181
217
|
reset that player's progress for this deck. It is a monotonic reset marker,
|
|
182
218
|
separate from the handle's `generation`, which fences playthrough operations.
|
|
219
|
+
Its `set(values, { check: { target, writer } })` and `remove(keys, { check })`
|
|
220
|
+
take the same optional writer check as `session.storage.user(id).set`: the
|
|
221
|
+
platform applies each request only while `writer` (from `claim`) still holds
|
|
222
|
+
`target`, and otherwise fails it with `CAULDRON_STORAGE_WRITER_LOST`. The check
|
|
223
|
+
is per request: a `set` or `remove` too big for one request is split, and when
|
|
224
|
+
the claim is lost partway the earlier requests stay written and the rest are not
|
|
225
|
+
sent. Without the option the request is unchanged. castle-web serve refuses a checked write instead of emulating it.
|
|
183
226
|
Deck-scope storage writes are not fenced by either generation; a server using
|
|
184
227
|
`session.storage.deck` must discard its own stale queued writes and cached
|
|
185
228
|
per-player values when it observes a newer reset marker.
|
|
186
|
-
`session.storage.board(name)` is a leaderboard. The root and its buckets also
|
|
187
|
-
support the [atomic save API](#atomic-saves). Each scope has the same
|
|
188
|
-
`get`, `set`, `remove`, `increment` and `list` as `Store`.
|
|
189
229
|
|
|
190
230
|
`session.storage.town(userId)` lets a door deck's server read and write one
|
|
191
231
|
signed-in player's rows in its source town's deck scope, for things such as
|
|
@@ -204,20 +244,103 @@ During dev serve, keys live under `town/` in the dev deck's own deck scope,
|
|
|
204
244
|
so testing a door never changes a real town. An unpublished deck still needs
|
|
205
245
|
a published deck id for storage.
|
|
206
246
|
|
|
207
|
-
|
|
247
|
+
Three differences follow from a session server not being a player:
|
|
208
248
|
|
|
209
|
-
- **It owns `deck` scope.** Once a deck has a published server, clients
|
|
210
|
-
that data but no longer write it, which is what lets you keep
|
|
211
|
-
state players cannot forge.
|
|
249
|
+
- **It owns `deck` scope.** Once a deck has a published server, clients
|
|
250
|
+
read that data but no longer write it, which is what lets you keep
|
|
251
|
+
authoritative state players cannot forge. Saving the deck again without
|
|
252
|
+
a server entry hands it back, but only when `save-deck` runs from the
|
|
253
|
+
project that published the server (its
|
|
254
|
+
`.castle/published-server-bundle.json` records that publish); otherwise
|
|
255
|
+
the old server stays published.
|
|
212
256
|
- **It has no self.** There is no `storage.me`, and a user scope or a board
|
|
213
257
|
submission must name the player: `session.storage.user(player.userId)`,
|
|
214
|
-
`session.storage.board("high").submit(player.userId, score)`.
|
|
215
|
-
|
|
216
|
-
|
|
258
|
+
`session.storage.board("high").submit(player.userId, score)`. Castle
|
|
259
|
+
does not check that the id belongs to a real player, so use only the
|
|
260
|
+
`userId` of a `player` Castle gave your callbacks, never one a client
|
|
261
|
+
sends.
|
|
262
|
+
- **It never sees `private`.** `Store.private` is the player's alone, and
|
|
263
|
+
`session.storage` has no way to reach it.
|
|
264
|
+
|
|
265
|
+
A server's writes are not batched the way a client's are: each `set` or
|
|
266
|
+
`remove` is sent at once and resolves when the platform has it. Each
|
|
267
|
+
request commits as a unit, but a `set` with more than 32 keys, or more
|
|
268
|
+
than 316 KB once encoded, goes out as several requests, so it can land
|
|
269
|
+
partly. A value is encoded twice on the way, so one full of quotes or
|
|
270
|
+
backslashes can be refused even under the 256 KB value limit. `remove`
|
|
271
|
+
splits by key count only. A session has its own rate limit, 30 calls and
|
|
272
|
+
2 MB a second, shared by every player in it.
|
|
273
|
+
|
|
274
|
+
Don't await storage in `onStart`: the session is not ready for it yet, so
|
|
275
|
+
a call there can fail or stall. Read on the first join or message
|
|
276
|
+
instead. `onPlayerJoin` runs again when a player reconnects (with the
|
|
277
|
+
same `playerId`), so a counter bumped on join counts reconnects too.
|
|
278
|
+
|
|
279
|
+
`onShutdown` is awaited, so a write you await there gets its chance to
|
|
280
|
+
land, but it can still be refused (by a rate limit, for one), and
|
|
281
|
+
`onShutdown` runs only on a clean stop. An out-of-memory kill or a host
|
|
282
|
+
failing sends no shutdown at all, so save as things change and treat
|
|
283
|
+
`onShutdown` as the last chance, not the plan.
|
|
284
|
+
|
|
285
|
+
#### A leaderboard players can't fake
|
|
286
|
+
|
|
287
|
+
On a deck with a published server, only the server submits scores; a
|
|
288
|
+
client `submit` is refused with `CAULDRON_STORAGE_FORBIDDEN`. Work the
|
|
289
|
+
score out on the server and submit it for the player. Clients show the
|
|
290
|
+
board with `Store.board("high").top(10)` and `Store.board("high").get()`.
|
|
291
|
+
|
|
292
|
+
```js
|
|
293
|
+
export default {
|
|
294
|
+
async onMessage(session, player, data) {
|
|
295
|
+
if (data.type !== "finished") return;
|
|
296
|
+
// From what the server saw of the run, not from anything in `data`.
|
|
297
|
+
const score = scoreRun(session, player);
|
|
298
|
+
const board = session.storage.board("high");
|
|
299
|
+
const best = await board.get(player.userId);
|
|
300
|
+
if (!best || score > best.score) await board.submit(player.userId, score);
|
|
301
|
+
},
|
|
302
|
+
};
|
|
303
|
+
```
|
|
304
|
+
|
|
305
|
+
`submit` replaces the player's score rather than keeping the higher one,
|
|
306
|
+
and this read-then-submit is not atomic: if one player finishes in two
|
|
307
|
+
sessions at the same moment, the lower score can land last. That is rare
|
|
308
|
+
enough to accept for most games.
|
|
309
|
+
|
|
310
|
+
Moving a game that used client submits over to a server keeps the scores
|
|
311
|
+
already on the board, forged ones included. Use a new board name for the
|
|
312
|
+
server's scores.
|
|
313
|
+
|
|
314
|
+
#### Per-player records
|
|
217
315
|
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
316
|
+
Anything the server must be able to trust about a player, such as a coin
|
|
317
|
+
balance, a rating or an unlock, goes in deck scope under a key named
|
|
318
|
+
after them. Every player can read deck scope, so nothing secret goes
|
|
319
|
+
there. A player can write their own `user(userId)` keys from a client,
|
|
320
|
+
so those are only for things they are allowed to set, such as a display
|
|
321
|
+
name or an outfit.
|
|
322
|
+
|
|
323
|
+
```js
|
|
324
|
+
// The coins this server placed, by id.
|
|
325
|
+
const coins = new Map([["c1", { x: 4, y: 2 }], ["c2", { x: 9, y: 7 }]]);
|
|
326
|
+
|
|
327
|
+
export default {
|
|
328
|
+
async onMessage(session, player, data) {
|
|
329
|
+
if (data.type !== "collect") return;
|
|
330
|
+
const coin = coins.get(data.coinId);
|
|
331
|
+
// The server decides: the coin must still be there, and the player
|
|
332
|
+
// must be standing on it by the server's own record of where they are.
|
|
333
|
+
if (!coin || !isTouching(positionOf(player), coin)) return;
|
|
334
|
+
coins.delete(data.coinId);
|
|
335
|
+
const total = await session.storage.deck.increment(`coins:${player.userId}`, 5);
|
|
336
|
+
session.send(player.playerId, { type: "coins", coins: total });
|
|
337
|
+
},
|
|
338
|
+
};
|
|
339
|
+
```
|
|
340
|
+
|
|
341
|
+
Deck-scope keys count against the deck's shared allowance (500 MB and
|
|
342
|
+
1,000,000 keys, see the `Store` limits), not the player's, so keep one
|
|
343
|
+
key or a few per player rather than one per event.
|
|
221
344
|
|
|
222
345
|
### `session.hub`
|
|
223
346
|
|
|
@@ -450,7 +573,11 @@ overwrite each other, a counter can be added to safely from several
|
|
|
450
573
|
places at once, and a deck can hold much more than `Storage` allows and
|
|
451
574
|
read back a slice of it rather than the whole thing.
|
|
452
575
|
|
|
453
|
-
Values
|
|
576
|
+
Values are JSON: numbers, strings, booleans, `null`, and arrays and plain
|
|
577
|
+
objects of those. You get back the same value you stored, not a string, so
|
|
578
|
+
there is nothing to parse. `undefined`, `NaN`, `Infinity`, a `Date`, a class
|
|
579
|
+
instance or a cycle is refused with a `CastleError`
|
|
580
|
+
(`CASTLE_STORAGE_SERIALIZE_FAILED`); store a date as `Date.now()`.
|
|
454
581
|
|
|
455
582
|
Scopes decide who owns a key:
|
|
456
583
|
|
|
@@ -460,7 +587,10 @@ Scopes decide who owns a key:
|
|
|
460
587
|
- `Store.user(userId)` — another player's public data. Anyone can read
|
|
461
588
|
it; only that player, or the deck's session server, can write it.
|
|
462
589
|
- `Store.private` — the current player's own data. Nobody else can read
|
|
463
|
-
it, and a session server never sees it.
|
|
590
|
+
it, and a session server never sees it. Only a client can use it.
|
|
591
|
+
|
|
592
|
+
Each scope has the same five calls: `get`, `set`, `remove`, `increment`
|
|
593
|
+
and `list`.
|
|
464
594
|
|
|
465
595
|
### `Store.<scope>.get<T>(keys): Promise<Record<string, T>>`
|
|
466
596
|
|
|
@@ -469,8 +599,11 @@ the result rather than present as `null`.
|
|
|
469
599
|
|
|
470
600
|
```js
|
|
471
601
|
const { level = 1, name } = await Store.deck.get(["level", "name"]);
|
|
602
|
+
const { save } = await Store.private.get(["save"]); // { coins: 12, ... } or undefined
|
|
472
603
|
```
|
|
473
604
|
|
|
605
|
+
At most 32 keys in one call.
|
|
606
|
+
|
|
474
607
|
### `Store.<scope>.set(values): Promise<void>`
|
|
475
608
|
|
|
476
609
|
Writes several keys. Nearby writes are grouped, so saving on every
|
|
@@ -478,13 +611,20 @@ change costs one request per burst. The promise resolves once the
|
|
|
478
611
|
platform has the write, so a deck can tell whether saving worked.
|
|
479
612
|
|
|
480
613
|
```js
|
|
481
|
-
await Store.
|
|
614
|
+
await Store.me.set({ name: "Ada", outfit: { hat: "tophat", color: "#f80" } });
|
|
482
615
|
```
|
|
483
616
|
|
|
617
|
+
Once the deck publishes a session server, `Store.deck.set` is refused:
|
|
618
|
+
the server owns deck scope. See [`session.storage`](#sessionstorage).
|
|
619
|
+
|
|
484
620
|
### `Store.<scope>.remove(keys): Promise<void>`
|
|
485
621
|
|
|
486
622
|
Removes keys.
|
|
487
623
|
|
|
624
|
+
```js
|
|
625
|
+
await Store.private.remove(["save"]);
|
|
626
|
+
```
|
|
627
|
+
|
|
488
628
|
### `Store.<scope>.increment(key, delta?): Promise<number>`
|
|
489
629
|
|
|
490
630
|
Adds `delta` (default `1`) to a number and returns the new total,
|
|
@@ -499,7 +639,11 @@ const plays = await Store.deck.increment("plays");
|
|
|
499
639
|
### `Store.<scope>.list(options?): Promise<{ entries, cursor }>`
|
|
500
640
|
|
|
501
641
|
Reads a page of keys in order, optionally only those starting with
|
|
502
|
-
`prefix`. Pass the `cursor` from one page to get the next.
|
|
642
|
+
`prefix`. Pass the `cursor` from one page to get the next. A page holds
|
|
643
|
+
100 entries unless you pass a `limit`, and at most 1,000. A page can
|
|
644
|
+
carry up to 1 MB, more than a player's 512 KB a second, so a page of
|
|
645
|
+
large values can be refused even when nothing else is reading; with
|
|
646
|
+
large values, pass a smaller `limit`.
|
|
503
647
|
|
|
504
648
|
```js
|
|
505
649
|
let cursor = null;
|
|
@@ -530,16 +674,22 @@ const top = await Store.board("highscores").top(10);
|
|
|
530
674
|
const mine = await Store.board("highscores").get();
|
|
531
675
|
```
|
|
532
676
|
|
|
533
|
-
- `submit(score)` records the current player's score
|
|
534
|
-
replaces an earlier one, so
|
|
535
|
-
personal best.
|
|
536
|
-
- `top(limit?)` returns the highest scores, best first
|
|
677
|
+
- `submit(score)` records the current player's score, on a deck without
|
|
678
|
+
a session server. A later submission replaces an earlier one, so
|
|
679
|
+
compare first if you only want to keep a personal best.
|
|
680
|
+
- `top(limit?)` returns the highest scores, best first: 10 unless you
|
|
681
|
+
pass a `limit`, and at most 100.
|
|
537
682
|
- `get(userId?)` returns one player's score, defaulting to the current
|
|
538
683
|
player, or `null` if they have none.
|
|
539
684
|
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
|
|
685
|
+
Each score is `{ subject, score, updatedAt }`, where `subject` is the
|
|
686
|
+
player's user id. A board name is at most 128 bytes.
|
|
687
|
+
|
|
688
|
+
A client can only submit its own score, and only on a deck without a
|
|
689
|
+
session server. Once a deck publishes a server, only the server submits
|
|
690
|
+
scores, for any player, after checking the result; a client `submit`
|
|
691
|
+
rejects with `CAULDRON_STORAGE_FORBIDDEN`, while `top` and `get` keep
|
|
692
|
+
working. See the [leaderboard pattern](#a-leaderboard-players-cant-fake).
|
|
543
693
|
|
|
544
694
|
### `Store.usage(): Promise<StoreUsage>`
|
|
545
695
|
|
|
@@ -562,11 +712,11 @@ if (player.byteCount > player.byteLimit * 0.9) {
|
|
|
562
712
|
Each has `byteCount`, `byteLimit`, `keyCount` and `keyLimit`. A board
|
|
563
713
|
score counts as a key. The answer includes the `set` and `remove` calls
|
|
564
714
|
the page made before calling it, even ones still being batched; await an
|
|
565
|
-
`increment` or a board `submit` first if the answer should include it.
|
|
566
|
-
another player's.
|
|
715
|
+
`increment` or a board `submit` first if the answer should include it.
|
|
716
|
+
A player can only ever see their own usage, not another player's.
|
|
567
717
|
|
|
568
|
-
`rate` says how much of the per-second rate limits (the last
|
|
569
|
-
the table below) is spent right now, so a deck that writes often can back
|
|
718
|
+
`rate` says how much of the per-second rate limits (the last three rows
|
|
719
|
+
of the table below) is spent right now, so a deck that writes often can back
|
|
570
720
|
off before a call is refused rather than after:
|
|
571
721
|
|
|
572
722
|
```js
|
|
@@ -580,7 +730,7 @@ if (rate && rate.caller.opsUsed > rate.caller.opsLimit * 0.8) {
|
|
|
580
730
|
one every player of the deck shares.
|
|
581
731
|
- Each has `opsUsed`, `opsLimit`, `bytesUsed` and `bytesLimit`, counted
|
|
582
732
|
over the current one-second window, and the `usage` call itself is
|
|
583
|
-
counted in them.
|
|
733
|
+
counted in them. The session server's own limit is not reported here.
|
|
584
734
|
- `rate.callerClass` names which limit `caller` is: `"client"` for a
|
|
585
735
|
page.
|
|
586
736
|
|
|
@@ -596,7 +746,8 @@ The platform caps key length, value size, how many keys one read may
|
|
|
596
746
|
name, and how much each player may store, and it limits how fast a
|
|
597
747
|
player may read and write. Going over one of these rejects with a
|
|
598
748
|
`CastleError` whose `code` says which, so a deck can tell a player it is
|
|
599
|
-
saving too fast apart from a player who is out of space
|
|
749
|
+
saving too fast apart from a player who is out of space. These are the
|
|
750
|
+
limits for an ordinary deck:
|
|
600
751
|
|
|
601
752
|
| limit | value |
|
|
602
753
|
|---|---|
|
|
@@ -605,18 +756,23 @@ saving too fast apart from a player who is out of space:
|
|
|
605
756
|
| keys in one `get` | 32 |
|
|
606
757
|
| one player's data in a deck | 50 MB, 50,000 keys |
|
|
607
758
|
| the deck's shared data (`Store.deck`) | 500 MB, 1,000,000 keys |
|
|
759
|
+
| a board name, a `list` prefix | 128 bytes |
|
|
608
760
|
| one player's calls | 20 a second, 512 KB a second |
|
|
761
|
+
| one session server's calls | 30 a second, 2 MB a second |
|
|
609
762
|
| every player of a deck together | 500 calls a second, 8 MB a second |
|
|
610
763
|
|
|
611
764
|
These do not reject. `set` and `remove` with more than 32 keys are split
|
|
612
765
|
into several calls by the SDK (each still counts against the rate above).
|
|
613
766
|
A `list` page holds at most 1,000 entries (a larger `limit` is lowered to
|
|
614
767
|
it) and ends early once it reaches 1 MB; take the next page with its
|
|
615
|
-
`cursor`.
|
|
768
|
+
`cursor`. A page still counts against a player's 512 KB a second, so
|
|
769
|
+
lower `limit` when values are large. `top` returns at most 100 scores.
|
|
616
770
|
|
|
617
771
|
A player's data is everything stored for them: their `Store.private`
|
|
618
772
|
keys, their `Store.user(id)` keys, their scores on every board, and
|
|
619
|
-
their `Characters` playthrough.
|
|
773
|
+
their `Characters` playthrough, whoever wrote them. Deck-scope keys count
|
|
774
|
+
against the deck's shared allowance, even when they're named after a
|
|
775
|
+
player.
|
|
620
776
|
Each player has their own allowance, so a deck with more
|
|
621
777
|
players can hold more, and one player filling theirs does not stop
|
|
622
778
|
anyone else. A write that shrinks what a player stores always succeeds,
|
|
@@ -643,12 +799,24 @@ does not fit in one. Ship media with the deck instead.
|
|
|
643
799
|
expected revision creates only an absent target; an explicit `replace` also
|
|
644
800
|
supports importing unregistered legacy rows. `checks` are read-only target
|
|
645
801
|
checks with an expected revision and/or writer; they leave revisions intact.
|
|
646
|
-
- `claim({ operationId, expectedAccess?, target, initial?, load? })`
|
|
647
|
-
takes ownership of a target and returns `{ writer, receipt, snapshot }`.
|
|
802
|
+
- `claim({ operationId, expectedAccess?, target, expectedRevision?, initial?, load? })`
|
|
803
|
+
explicitly takes ownership of a target and returns `{ writer, receipt, snapshot }`.
|
|
648
804
|
`initial: [{ target, rows }]` initializes absent targets only. An absent
|
|
649
805
|
claimed target initializes empty if defaults were omitted. Claiming an
|
|
650
806
|
existing target leaves its data revision unchanged. The latest committed
|
|
651
807
|
claim wins; claimed targets require the current writer on every change.
|
|
808
|
+
With `expectedRevision` (the target's revision from a snapshot, or `null` for
|
|
809
|
+
a target never initialized) and `expectedAccess`, the claim is a
|
|
810
|
+
compare-and-set: it commits only while the target still has that revision and
|
|
811
|
+
then always moves it, so a claim made against the same observation fails with
|
|
812
|
+
`CAULDRON_STORAGE_REVISION_CONFLICT`, `committed: false`, and `current`
|
|
813
|
+
holding the target's revision (no rows). A claim sent late, after a newer
|
|
814
|
+
CAS claim or any change to the target, cannot take it back; a plain claim
|
|
815
|
+
leaves the revision alone, so every claimer of a CAS target must use CAS. Retry with `current`'s revision only while
|
|
816
|
+
the caller should still own it. A player progress reset returns the target
|
|
817
|
+
to never-initialized, so an old `null` observation matches again. Needs a
|
|
818
|
+
platform that knows the field; older ones refuse it with
|
|
819
|
+
`CAULDRON_STORAGE_INVALID_ARGUMENT`.
|
|
652
820
|
- `initialize({ operationId, expectedAccess?, initial, load? })` initializes
|
|
653
821
|
only absent targets and returns `{ receipt, snapshot }`. Concurrent defaults
|
|
654
822
|
are applied once. It never claims ownership or replaces existing data.
|
|
@@ -744,9 +912,13 @@ recovery must check current generations before adopting it. Clients cannot send
|
|
|
744
912
|
reset fences. Omitting them preserves the existing request.
|
|
745
913
|
|
|
746
914
|
One call changes up to eight targets, with up to eight explicit key changes
|
|
747
|
-
per target, across the same deck and at most two players. Every
|
|
748
|
-
its expected revision. A read-only `check` can use `expectedRevision: null`
|
|
749
|
-
to require absence without creating that target
|
|
915
|
+
per target, across the same deck and at most two players. Every changed
|
|
916
|
+
target needs its expected revision. A read-only `check` can use `expectedRevision: null`
|
|
917
|
+
to require absence without creating that target, or carry only a `writer`
|
|
918
|
+
(from `claim`) to commit only while that claim still holds its target, for
|
|
919
|
+
example a one-writer lease's empty user target fencing deck-scope changes.
|
|
920
|
+
A replaced claim fails with `CAULDRON_STORAGE_WRITER_LOST`. Checks count
|
|
921
|
+
toward the eight targets and two players. All changes commit together. Clients may address their
|
|
750
922
|
own user/private targets and writable deck targets; only the deck server can
|
|
751
923
|
condition on another player's user target. Servers cannot access private data.
|
|
752
924
|
Existing quota, byte and rate allowances still apply. A prefix replacement
|
package/dist/castle.d.ts
CHANGED
|
@@ -8,6 +8,9 @@ export type { AvatarResult, CastleAvatarApi } from "./avatar";
|
|
|
8
8
|
export { Characters } from "./characters";
|
|
9
9
|
export type { CastleCharactersApi, CharacterHandle, CharacterHistoryOptions, CharacterSendInput, } from "./characters";
|
|
10
10
|
export { Decks } from "./decks";
|
|
11
|
+
/** @experimental Deck invites are not available to every player yet. */
|
|
12
|
+
export { DeckInvites } from "./deckInvites";
|
|
13
|
+
export type { CastleDeckInvitesApi, DeckInviteArrivalResult, DeckInviteResult, DeckInviteUser, } from "./deckInvites";
|
|
11
14
|
export type { CastleDecksApi, DeckSummary, DecksListParams, DecksListResult } from "./decks";
|
|
12
15
|
export { CastleError } from "./errors";
|
|
13
16
|
export { experiment, experiments, experimentsReady } from "./experiments";
|
package/dist/castle.js
CHANGED
|
@@ -5,6 +5,8 @@ export { Analytics } from "./analytics";
|
|
|
5
5
|
export { Avatar } from "./avatar";
|
|
6
6
|
export { Characters } from "./characters";
|
|
7
7
|
export { Decks } from "./decks";
|
|
8
|
+
/** @experimental Deck invites are not available to every player yet. */
|
|
9
|
+
export { DeckInvites } from "./deckInvites";
|
|
8
10
|
export { CastleError } from "./errors";
|
|
9
11
|
export { experiment, experiments, experimentsReady } from "./experiments";
|
|
10
12
|
export { deckPrefixOf, IMPORTS_DIR, IMPORTS_PREFIX, isImportedFile, resolveDeckFile, } from "./files";
|
package/dist/commands.d.ts
CHANGED
|
@@ -305,6 +305,39 @@ export interface HubHeartsResult {
|
|
|
305
305
|
status: "ok" | "unavailable";
|
|
306
306
|
hearts: string[];
|
|
307
307
|
}
|
|
308
|
+
/**
|
|
309
|
+
* @experimental Deck invites are not available to every player yet, and only
|
|
310
|
+
* a deck whose server config sets `invites: true` can mint them. `reason` is
|
|
311
|
+
* Ghost's refusal code (`FEATURE_NOT_ENABLED`, `CAULDRON_DECK_INVITE_*`) when it
|
|
312
|
+
* gave one, or `UNSUPPORTED_HOST` from a host older than deck invites; it is
|
|
313
|
+
* absent on hosts without deck invites.
|
|
314
|
+
*/
|
|
315
|
+
export type DeckInviteResult = {
|
|
316
|
+
status: "ok";
|
|
317
|
+
url: string;
|
|
318
|
+
expiresAt: string;
|
|
319
|
+
} | {
|
|
320
|
+
status: "unavailable";
|
|
321
|
+
reason?: string;
|
|
322
|
+
};
|
|
323
|
+
/** @experimental The friend who sent the link this play opened with. */
|
|
324
|
+
export interface DeckInviteUser {
|
|
325
|
+
userId: string;
|
|
326
|
+
username: string;
|
|
327
|
+
}
|
|
328
|
+
/**
|
|
329
|
+
* @experimental What arriving through a deck invite link did: the players this
|
|
330
|
+
* one now follows (and who follow back). `unavailable` when the play did not
|
|
331
|
+
* open from a link, is not in a session yet, or the host has no deck invites.
|
|
332
|
+
*/
|
|
333
|
+
export type DeckInviteArrivalResult = {
|
|
334
|
+
status: "ok";
|
|
335
|
+
inviter: DeckInviteUser | null;
|
|
336
|
+
friends: DeckInviteUser[];
|
|
337
|
+
} | {
|
|
338
|
+
status: "unavailable";
|
|
339
|
+
reason?: string;
|
|
340
|
+
};
|
|
308
341
|
/** Hub.chat: only the messages after a cursor an earlier answer returned. */
|
|
309
342
|
export interface HubChatParams {
|
|
310
343
|
after?: string;
|
|
@@ -749,6 +782,8 @@ export interface CommandParams {
|
|
|
749
782
|
"hub.setHearts": {
|
|
750
783
|
doorIds: string[];
|
|
751
784
|
};
|
|
785
|
+
"deck.invite": Record<string, never>;
|
|
786
|
+
"deck.inviteArrival": Record<string, never>;
|
|
752
787
|
"hub.signIn": HubSignInParams;
|
|
753
788
|
"hub.pushPermission": Record<string, never>;
|
|
754
789
|
"hub.pushDestination": Record<string, never>;
|
|
@@ -964,6 +999,8 @@ export interface CommandResult {
|
|
|
964
999
|
"hub.undoInvite": HubReportResult;
|
|
965
1000
|
"hub.hearts": HubHeartsResult;
|
|
966
1001
|
"hub.setHearts": HubHeartsResult;
|
|
1002
|
+
"deck.invite": DeckInviteResult;
|
|
1003
|
+
"deck.inviteArrival": DeckInviteArrivalResult;
|
|
967
1004
|
"hub.signIn": HubSignInResult;
|
|
968
1005
|
"hub.pushPermission": HubPushPermissionResult;
|
|
969
1006
|
"hub.pushDestination": HubPushDestinationResult;
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import type { DeckInviteArrivalResult, DeckInviteResult } from "./commands";
|
|
2
|
+
export type { DeckInviteArrivalResult, DeckInviteResult, DeckInviteUser, } from "./commands";
|
|
3
|
+
/**
|
|
4
|
+
* @experimental Not available to every player yet, and only for a deck whose
|
|
5
|
+
* server config opts in with `invites: true`; the API may still change.
|
|
6
|
+
*
|
|
7
|
+
* Invite links for an ordinary deck: a player in a public multiplayer session
|
|
8
|
+
* makes a link, and a friend who opens it joins that player's public shard and
|
|
9
|
+
* the two follow each other. The host owns the deck, the session and the link's
|
|
10
|
+
* token; a deck never passes any of them.
|
|
11
|
+
*
|
|
12
|
+
* castle.xyz answers these only for the document it inlined into its frame:
|
|
13
|
+
* a deck built before that check (or a page the frame navigated to) gets
|
|
14
|
+
* `{ status: "unavailable", reason: "DOCUMENT_MISMATCH" }`. Rebuild it.
|
|
15
|
+
*/
|
|
16
|
+
export interface CastleDeckInvitesApi {
|
|
17
|
+
/**
|
|
18
|
+
* Make an expiring link into the public session this player joined last.
|
|
19
|
+
* `unavailable` when there is none, on hosts without deck invites, or when
|
|
20
|
+
* Castle refuses (`reason` carries its code).
|
|
21
|
+
*/
|
|
22
|
+
invite(): Promise<DeckInviteResult>;
|
|
23
|
+
/**
|
|
24
|
+
* Once this play has joined a public session: if it opened from an invite
|
|
25
|
+
* link, follow the inviter (and be followed back) and return who. Safe to
|
|
26
|
+
* call again; `unavailable` when the play did not come from a link.
|
|
27
|
+
*/
|
|
28
|
+
inviteArrival(): Promise<DeckInviteArrivalResult>;
|
|
29
|
+
}
|
|
30
|
+
/** @experimental See {@link CastleDeckInvitesApi}. */
|
|
31
|
+
export declare const DeckInvites: CastleDeckInvitesApi;
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import { CastleError } from "./errors";
|
|
2
|
+
import { hostRequest } from "./transport";
|
|
3
|
+
const UNSUPPORTED_HOST = { status: "unavailable", reason: "UNSUPPORTED_HOST" };
|
|
4
|
+
// A host older than deck invites does not know the command.
|
|
5
|
+
async function supported(ask) {
|
|
6
|
+
try {
|
|
7
|
+
return await ask();
|
|
8
|
+
}
|
|
9
|
+
catch (error) {
|
|
10
|
+
if (error instanceof CastleError && error.code === "UNKNOWN_COMMAND")
|
|
11
|
+
return UNSUPPORTED_HOST;
|
|
12
|
+
throw error;
|
|
13
|
+
}
|
|
14
|
+
}
|
|
15
|
+
async function invite() {
|
|
16
|
+
return supported(() => hostRequest("deck.invite", {}));
|
|
17
|
+
}
|
|
18
|
+
async function inviteArrival() {
|
|
19
|
+
return supported(() => hostRequest("deck.inviteArrival", {}));
|
|
20
|
+
}
|
|
21
|
+
/** @experimental See {@link CastleDeckInvitesApi}. */
|
|
22
|
+
export const DeckInvites = { invite, inviteArrival };
|
package/dist/runtime.js
CHANGED
|
@@ -504,6 +504,54 @@ function loadHtml2Canvas() {
|
|
|
504
504
|
}
|
|
505
505
|
return html2canvasPromise;
|
|
506
506
|
}
|
|
507
|
+
// html2canvas crops its output to the target's transformed box and then paints
|
|
508
|
+
// the target with its own transform on top of that, so a translated target comes
|
|
509
|
+
// out shifted by the translation twice over. The play card is one: it centers
|
|
510
|
+
// itself with `translate(-50%, -50%)`, and its capture showed only the stage's
|
|
511
|
+
// lower-right quarter. html2canvas tries to clear the transform itself, but with
|
|
512
|
+
// a plain inline style that loses to the play card's `!important` rule.
|
|
513
|
+
//
|
|
514
|
+
// A pure translation can be traded for an offset that puts the box in the same
|
|
515
|
+
// place with no transform at all, and that is what the clone gets. Scales and
|
|
516
|
+
// rotations have no such equivalent, so those still go to html2canvas as is.
|
|
517
|
+
function untranslateClone(target) {
|
|
518
|
+
if (target === document.body || target === document.documentElement) {
|
|
519
|
+
return undefined;
|
|
520
|
+
}
|
|
521
|
+
const style = getComputedStyle(target);
|
|
522
|
+
const m = /^matrix\(1, 0, 0, 1, (-?[\d.e+-]+), (-?[\d.e+-]+)\)$/.exec(style.transform);
|
|
523
|
+
if (!m)
|
|
524
|
+
return undefined;
|
|
525
|
+
const tx = Number(m[1]);
|
|
526
|
+
const ty = Number(m[2]);
|
|
527
|
+
let position = style.position;
|
|
528
|
+
let left = parseFloat(style.left);
|
|
529
|
+
let top = parseFloat(style.top);
|
|
530
|
+
if (position === "static") {
|
|
531
|
+
// A relative offset moves a static box without moving anything around it,
|
|
532
|
+
// just as the translation did.
|
|
533
|
+
position = "relative";
|
|
534
|
+
left = 0;
|
|
535
|
+
top = 0;
|
|
536
|
+
}
|
|
537
|
+
else if (position === "sticky" || Number.isNaN(left) || Number.isNaN(top)) {
|
|
538
|
+
return undefined;
|
|
539
|
+
}
|
|
540
|
+
// A box held by opposing insets (`inset: 0`) would stretch or shrink when only
|
|
541
|
+
// left/top move, so the clone keeps the size the original was laid out at.
|
|
542
|
+
const width = style.width;
|
|
543
|
+
const height = style.height;
|
|
544
|
+
return (_doc, clone) => {
|
|
545
|
+
clone.style.setProperty("transform", "none", "important");
|
|
546
|
+
clone.style.setProperty("position", position, "important");
|
|
547
|
+
clone.style.setProperty("left", `${left + tx}px`, "important");
|
|
548
|
+
clone.style.setProperty("top", `${top + ty}px`, "important");
|
|
549
|
+
clone.style.setProperty("right", "auto", "important");
|
|
550
|
+
clone.style.setProperty("bottom", "auto", "important");
|
|
551
|
+
clone.style.setProperty("width", width, "important");
|
|
552
|
+
clone.style.setProperty("height", height, "important");
|
|
553
|
+
};
|
|
554
|
+
}
|
|
507
555
|
async function captureWithHtml2Canvas(target) {
|
|
508
556
|
try {
|
|
509
557
|
const mod = await loadHtml2Canvas();
|
|
@@ -511,6 +559,7 @@ async function captureWithHtml2Canvas(target) {
|
|
|
511
559
|
backgroundColor: null,
|
|
512
560
|
scale: devicePixelRatio,
|
|
513
561
|
useCORS: true,
|
|
562
|
+
onclone: untranslateClone(target),
|
|
514
563
|
});
|
|
515
564
|
return c.toDataURL("image/png");
|
|
516
565
|
}
|
package/dist/save.d.ts
CHANGED
|
@@ -63,10 +63,14 @@ export interface SaveTransactionInput {
|
|
|
63
63
|
checks?: SaveCheck[];
|
|
64
64
|
changes: SaveChange[];
|
|
65
65
|
}
|
|
66
|
-
export
|
|
66
|
+
export type SaveConditionalCheck = (Omit<SaveCheck, "expectedRevision"> & {
|
|
67
67
|
/** Null checks absence without creating the target. */
|
|
68
68
|
expectedRevision: SaveRevision | null;
|
|
69
|
-
}
|
|
69
|
+
}) | (Omit<SaveCheck, "expectedRevision" | "writer"> & {
|
|
70
|
+
/** A writer alone fences on a claim, e.g. a one-writer lease's empty target. */
|
|
71
|
+
writer: SaveWriter;
|
|
72
|
+
expectedRevision?: undefined;
|
|
73
|
+
});
|
|
70
74
|
export interface SaveConditionalWriteInput extends Omit<SaveTransactionInput, "checks"> {
|
|
71
75
|
checks?: SaveConditionalCheck[];
|
|
72
76
|
/** Session servers only: atomically fence each affected player's progress reset. */
|
|
@@ -84,6 +88,12 @@ export interface SaveClaimInput {
|
|
|
84
88
|
operationId: string;
|
|
85
89
|
expectedAccess?: string;
|
|
86
90
|
target: SaveTarget;
|
|
91
|
+
/**
|
|
92
|
+
* Compare-and-set: claim only while `target`'s revision is still this one (null:
|
|
93
|
+
* never initialized). A claim carrying it always moves the revision, so another
|
|
94
|
+
* claim made against the same observation is refused with REVISION_CONFLICT.
|
|
95
|
+
*/
|
|
96
|
+
expectedRevision?: SaveRevision | null;
|
|
87
97
|
initial?: SaveInitial[];
|
|
88
98
|
/** Omitted loads the claimed and initial targets. */
|
|
89
99
|
load?: SaveReadTarget[];
|
|
@@ -156,6 +166,7 @@ export interface SaveBucketApi {
|
|
|
156
166
|
operationId: string;
|
|
157
167
|
expectedAccess?: string;
|
|
158
168
|
prefix: string;
|
|
169
|
+
expectedRevision?: SaveRevision | null;
|
|
159
170
|
initial?: {
|
|
160
171
|
prefix: string;
|
|
161
172
|
rows: SaveRows;
|
package/dist/save.js
CHANGED
|
@@ -251,8 +251,6 @@ function encodeChange(change, server) {
|
|
|
251
251
|
}
|
|
252
252
|
function encodeCheck(check, server, conditional = false) {
|
|
253
253
|
const target = validateSaveTarget(check.target, server);
|
|
254
|
-
if (conditional && check.expectedRevision === undefined)
|
|
255
|
-
invalid("Every conditional check needs an expected revision.");
|
|
256
254
|
if (check.expectedRevision === undefined && check.writer === undefined) {
|
|
257
255
|
invalid("A check needs an expected revision or a writer.");
|
|
258
256
|
}
|
|
@@ -350,6 +348,13 @@ export function encodeSaveInput(verb, input, server = false) {
|
|
|
350
348
|
...(verb === "claim"
|
|
351
349
|
? { target: validateSaveTarget(input.target, server) }
|
|
352
350
|
: {}),
|
|
351
|
+
...(verb === "claim" && input.expectedRevision !== undefined
|
|
352
|
+
? {
|
|
353
|
+
expectedRevision: input.expectedRevision === null
|
|
354
|
+
? null
|
|
355
|
+
: checkText(input.expectedRevision, "expected revision", MAX_KEY_BYTES),
|
|
356
|
+
}
|
|
357
|
+
: {}),
|
|
353
358
|
...(input.initial === undefined
|
|
354
359
|
? {}
|
|
355
360
|
: { initial: encodeInitial(input.initial, server) }),
|
|
@@ -41,6 +41,8 @@ export interface PlatformWorldTimeConfig {
|
|
|
41
41
|
advance: "wallClock";
|
|
42
42
|
}
|
|
43
43
|
export interface PlatformHandle {
|
|
44
|
+
readonly sessionSecret?: string;
|
|
45
|
+
readAsset?(name: string): Promise<Uint8Array | null>;
|
|
44
46
|
send(connId: string, text: string): void;
|
|
45
47
|
broadcast(text: string): void;
|
|
46
48
|
sendBinary?(connId: string, bytes: Uint8Array | ArrayBuffer): void;
|
package/dist/server/storage.d.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import type { Json } from "../types";
|
|
2
2
|
import type { CharacterHistory, CharacterOperation } from "../commands";
|
|
3
3
|
import type { PlatformHandle } from "./platformHandle";
|
|
4
|
-
import { type SaveApi, type SaveBucketApi } from "../save";
|
|
4
|
+
import { type SaveApi, type SaveBucketApi, type SaveTarget, type SaveWriter } from "../save";
|
|
5
5
|
export interface ServerStorageListOptions {
|
|
6
6
|
prefix?: string;
|
|
7
7
|
limit?: number;
|
|
@@ -16,11 +16,24 @@ export interface ServerStorageListPage<T extends Json = Json> {
|
|
|
16
16
|
/** Null means there is nothing left. A short page alone does not mean that. */
|
|
17
17
|
cursor: string | null;
|
|
18
18
|
}
|
|
19
|
+
/**
|
|
20
|
+
* Optional writer fence on an ordinary write. The platform applies the write only if
|
|
21
|
+
* `writer` (from `claim`) still holds `target` for this session, checked atomically
|
|
22
|
+
* with the write; otherwise it rejects with `CAULDRON_STORAGE_WRITER_LOST`
|
|
23
|
+
* (`committed: false`) and nothing is written. A `set` large enough to need several
|
|
24
|
+
* requests checks each one, so a claim lost partway stops the rest.
|
|
25
|
+
*/
|
|
26
|
+
export interface ServerStorageWriteOptions {
|
|
27
|
+
check?: {
|
|
28
|
+
target: SaveTarget;
|
|
29
|
+
writer: SaveWriter;
|
|
30
|
+
};
|
|
31
|
+
}
|
|
19
32
|
export interface ServerStorageScope extends SaveBucketApi {
|
|
20
33
|
get<T extends Json = Json>(keys: string[]): Promise<Record<string, T>>;
|
|
21
|
-
set(values: Record<string, Json
|
|
22
|
-
remove(keys: string[]): Promise<void>;
|
|
23
|
-
increment(key: string, delta?: number): Promise<number>;
|
|
34
|
+
set(values: Record<string, Json>, options?: ServerStorageWriteOptions): Promise<void>;
|
|
35
|
+
remove(keys: string[], options?: ServerStorageWriteOptions): Promise<void>;
|
|
36
|
+
increment(key: string, delta?: number, options?: ServerStorageWriteOptions): Promise<number>;
|
|
24
37
|
list<T extends Json = Json>(options?: ServerStorageListOptions): Promise<ServerStorageListPage<T>>;
|
|
25
38
|
}
|
|
26
39
|
export interface ServerTownStorage {
|
|
@@ -56,8 +69,14 @@ export interface ServerPlaythrough {
|
|
|
56
69
|
/** Explicit narrative changes for this same player and generation. */
|
|
57
70
|
readonly characters: ServerPlaythroughCharacters;
|
|
58
71
|
get<T extends Json = Json>(keys: string[]): Promise<Record<string, T>>;
|
|
59
|
-
|
|
60
|
-
|
|
72
|
+
/**
|
|
73
|
+
* With `{ check: { target, writer } }`, as on `session.storage.user(id).set`, the
|
|
74
|
+
* platform applies each request only while `writer` still holds `target`'s claim
|
|
75
|
+
* (CAULDRON_STORAGE_WRITER_LOST otherwise). A split write is checked per request:
|
|
76
|
+
* requests sent before the claim was lost stay written.
|
|
77
|
+
*/
|
|
78
|
+
set(values: Record<string, Json>, options?: ServerStorageWriteOptions): Promise<void>;
|
|
79
|
+
remove(keys: string[], options?: ServerStorageWriteOptions): Promise<void>;
|
|
61
80
|
reset(operationId: string): Promise<ServerPlaythrough>;
|
|
62
81
|
}
|
|
63
82
|
export interface RecordCharacterEventInput {
|
package/dist/server/storage.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { chunked } from "../chunk";
|
|
2
2
|
import { decodeStorageValue, encodeStorageValue, storageError, } from "../storageJson";
|
|
3
|
-
import { createSaveApi, createSaveBucket, preflightSaveRequest, SaveError, } from "../save";
|
|
3
|
+
import { createSaveApi, createSaveBucket, preflightSaveRequest, SaveError, validateSaveTarget, } from "../save";
|
|
4
4
|
// Deck storage for an author's session server.
|
|
5
5
|
//
|
|
6
6
|
// The same store the deck's clients use, reached over the platform channel instead of
|
|
@@ -234,15 +234,17 @@ function createPlaythrough(call, subject, generation, resetGeneration) {
|
|
|
234
234
|
const entries = await call("playthroughGet", { subject, generation, keys: assertKeys(keys, "session.storage.playthrough.get") });
|
|
235
235
|
return decodeEntries(entries, "session.storage.playthrough.get");
|
|
236
236
|
},
|
|
237
|
-
async set(values) {
|
|
237
|
+
async set(values, options) {
|
|
238
|
+
const fence = writerCheck(options, "session.storage.playthrough.set");
|
|
238
239
|
const entries = encodeEntries(values, "session.storage.playthrough.set");
|
|
239
240
|
for (const chunk of batched(entries, "session.storage.playthrough.set")) {
|
|
240
|
-
await call("playthroughSet", { subject, generation, entries: chunk });
|
|
241
|
+
await call("playthroughSet", { subject, generation, entries: chunk, ...fence });
|
|
241
242
|
}
|
|
242
243
|
},
|
|
243
|
-
async remove(keys) {
|
|
244
|
+
async remove(keys, options) {
|
|
245
|
+
const fence = writerCheck(options, "session.storage.playthrough.remove");
|
|
244
246
|
for (const chunk of chunked(assertKeys(keys, "session.storage.playthrough.remove"), MAX_KEYS_PER_CALL)) {
|
|
245
|
-
await call("playthroughDelete", { subject, generation, keys: chunk });
|
|
247
|
+
await call("playthroughDelete", { subject, generation, keys: chunk, ...fence });
|
|
246
248
|
}
|
|
247
249
|
},
|
|
248
250
|
async reset(operationId) {
|
|
@@ -311,19 +313,22 @@ function createScope(call, scope, subject, saveApi) {
|
|
|
311
313
|
});
|
|
312
314
|
return decodeEntries(entries, "session.storage.get");
|
|
313
315
|
},
|
|
314
|
-
async set(values) {
|
|
316
|
+
async set(values, options) {
|
|
317
|
+
const fence = writerCheck(options, "session.storage.set");
|
|
315
318
|
const entries = encodeEntries(values, "session.storage.set");
|
|
316
319
|
for (const chunk of batched(entries)) {
|
|
317
|
-
await call("set", { scope, subject, entries: chunk });
|
|
320
|
+
await call("set", { scope, subject, entries: chunk, ...fence });
|
|
318
321
|
}
|
|
319
322
|
},
|
|
320
|
-
async remove(keys) {
|
|
323
|
+
async remove(keys, options) {
|
|
324
|
+
const fence = writerCheck(options, "session.storage.remove");
|
|
321
325
|
for (const chunk of chunked(assertKeys(keys, "session.storage.remove"), MAX_KEYS_PER_CALL)) {
|
|
322
|
-
await call("delete", { scope, subject, keys: chunk });
|
|
326
|
+
await call("delete", { scope, subject, keys: chunk, ...fence });
|
|
323
327
|
}
|
|
324
328
|
},
|
|
325
|
-
async increment(key, delta = 1) {
|
|
326
|
-
const
|
|
329
|
+
async increment(key, delta = 1, options) {
|
|
330
|
+
const fence = writerCheck(options, "session.storage.increment");
|
|
331
|
+
const value = await call("increment", { scope, subject, key, delta, ...fence });
|
|
327
332
|
return Number(value);
|
|
328
333
|
},
|
|
329
334
|
async list(options = {}) {
|
|
@@ -394,6 +399,31 @@ function assertUserId(userId, operation) {
|
|
|
394
399
|
}
|
|
395
400
|
return userId;
|
|
396
401
|
}
|
|
402
|
+
/**
|
|
403
|
+
* The `writerCheck` request field, or nothing at all when no check was asked for, so
|
|
404
|
+
* an unchecked write sends exactly the request it always has. Bounded (prefix and
|
|
405
|
+
* writer 128 bytes, subject 256) so it fits inside REQUEST_OVERHEAD_BYTES.
|
|
406
|
+
*/
|
|
407
|
+
function writerCheck(options, operation) {
|
|
408
|
+
if (options === undefined || options === null)
|
|
409
|
+
return {};
|
|
410
|
+
if (typeof options !== "object" || Array.isArray(options)) {
|
|
411
|
+
throw storageError("CAULDRON_STORAGE_INVALID_ARGUMENT", "Write options must be an object.", operation);
|
|
412
|
+
}
|
|
413
|
+
if (options.check === undefined)
|
|
414
|
+
return {};
|
|
415
|
+
const check = options.check;
|
|
416
|
+
if (!check || typeof check !== "object" || Array.isArray(check)) {
|
|
417
|
+
throw storageError("CAULDRON_STORAGE_INVALID_ARGUMENT", "A writer check needs a target and a writer.", operation);
|
|
418
|
+
}
|
|
419
|
+
const target = validateSaveTarget(check.target, true);
|
|
420
|
+
if (typeof check.writer !== "string" ||
|
|
421
|
+
check.writer.length === 0 ||
|
|
422
|
+
utf8Length(check.writer) > MAX_KEY_BYTES) {
|
|
423
|
+
throw storageError("CAULDRON_STORAGE_INVALID_ARGUMENT", "A writer check needs the writer from claim.", operation);
|
|
424
|
+
}
|
|
425
|
+
return { writerCheck: { target, writer: check.writer } };
|
|
426
|
+
}
|
|
397
427
|
/**
|
|
398
428
|
* Splits entries into requests that fit both limits: the platform's key count and the
|
|
399
429
|
* channel's frame size.
|
package/dist/server/wrapper.d.ts
CHANGED
|
@@ -22,6 +22,10 @@ export interface MultiplayerServerSession {
|
|
|
22
22
|
readonly sessionId: string;
|
|
23
23
|
readonly deckId: string;
|
|
24
24
|
readonly mode: MultiplayerSessionMode;
|
|
25
|
+
readonly sessionSecret?: string;
|
|
26
|
+
readonly assets: {
|
|
27
|
+
read(name: string): Promise<Uint8Array | null>;
|
|
28
|
+
};
|
|
25
29
|
/**
|
|
26
30
|
* The place the host started this session for (a hub door's destination, or
|
|
27
31
|
* the hub place ghost pinned the session to), or null when the host stamped
|
package/dist/server/wrapper.js
CHANGED
|
@@ -247,7 +247,7 @@ function createAuthorSession(platformHandle, players, arrivals, hidden, variants
|
|
|
247
247
|
return Boolean(hidden.get(a)?.has(userB) || hidden.get(b)?.has(userA));
|
|
248
248
|
});
|
|
249
249
|
const world = createServerWorld(platformHandle);
|
|
250
|
-
|
|
250
|
+
const session = {
|
|
251
251
|
get players() {
|
|
252
252
|
return Array.from(players.values());
|
|
253
253
|
},
|
|
@@ -257,6 +257,14 @@ function createAuthorSession(platformHandle, players, arrivals, hidden, variants
|
|
|
257
257
|
place: typeof platformHandle.config.place === "string"
|
|
258
258
|
? platformHandle.config.place
|
|
259
259
|
: hub?.place ?? null,
|
|
260
|
+
assets: {
|
|
261
|
+
async read(name) {
|
|
262
|
+
if (typeof platformHandle.readAsset !== "function") {
|
|
263
|
+
throw new TypeError("This Castle runtime does not support session assets yet.");
|
|
264
|
+
}
|
|
265
|
+
return platformHandle.readAsset(name);
|
|
266
|
+
},
|
|
267
|
+
},
|
|
260
268
|
storage: createServerStorage(platformHandle),
|
|
261
269
|
world,
|
|
262
270
|
characters: world?.characters ?? createPlaceCharacters(platformHandle),
|
|
@@ -308,6 +316,26 @@ function createAuthorSession(platformHandle, players, arrivals, hidden, variants
|
|
|
308
316
|
platformHandle.disconnect(playerId, reason ?? 1000);
|
|
309
317
|
},
|
|
310
318
|
};
|
|
319
|
+
Object.defineProperty(session, "assets", { enumerable: false });
|
|
320
|
+
// Inspectors can invoke getters. Keep the key in a closure off the inspected target.
|
|
321
|
+
const sessionSecret = platformHandle.sessionSecret;
|
|
322
|
+
return new Proxy(session, {
|
|
323
|
+
get(target, property, receiver) {
|
|
324
|
+
if (property === "sessionSecret")
|
|
325
|
+
return sessionSecret;
|
|
326
|
+
return Reflect.get(target, property, receiver);
|
|
327
|
+
},
|
|
328
|
+
set(target, property, value, receiver) {
|
|
329
|
+
if (property === "sessionSecret")
|
|
330
|
+
return false;
|
|
331
|
+
return Reflect.set(target, property, value, receiver);
|
|
332
|
+
},
|
|
333
|
+
defineProperty(target, property, descriptor) {
|
|
334
|
+
if (property === "sessionSecret")
|
|
335
|
+
return false;
|
|
336
|
+
return Reflect.defineProperty(target, property, descriptor);
|
|
337
|
+
},
|
|
338
|
+
});
|
|
311
339
|
}
|
|
312
340
|
const WORLD_OPERATION_ID_MAX_BYTES = 128;
|
|
313
341
|
const WORLD_OPERATION_ID_MAX_CHARACTERS = 120;
|
package/dist/transport.d.ts
CHANGED
|
@@ -14,6 +14,7 @@ declare global {
|
|
|
14
14
|
__castleSdkHost?: {
|
|
15
15
|
receive: (message: unknown) => void;
|
|
16
16
|
};
|
|
17
|
+
__castleDocumentNonce?: unknown;
|
|
17
18
|
}
|
|
18
19
|
}
|
|
19
20
|
export declare function hostRequest<C extends CommandName>(command: C, params: CommandParams[C], stream?: HostStreamOptions): Promise<CommandResult[C]>;
|
package/dist/transport.js
CHANGED
|
@@ -28,6 +28,100 @@ const INTERACTIVE_COMMANDS = new Set([
|
|
|
28
28
|
"voice.requestJoin",
|
|
29
29
|
"hub.pushPermission",
|
|
30
30
|
]);
|
|
31
|
+
// The deck channel. A web host that inlines the deck into its frame writes a
|
|
32
|
+
// secret for that one document into its source, as
|
|
33
|
+
// `window.__castleDocumentNonce`, before any deck script. The SDK takes it once
|
|
34
|
+
// at load and deletes the global, makes a MessageChannel, and redeems the nonce
|
|
35
|
+
// once, sending it with one port to window.parent (a `deck.channel` request).
|
|
36
|
+
// A host that accepts answers on that port and keeps it; from then on the
|
|
37
|
+
// commands below go only over it, and so do their answers. The frame keeps the
|
|
38
|
+
// other port in this document's memory, so a document the frame navigates to
|
|
39
|
+
// in place (same window, different document) never holds it, and nothing
|
|
40
|
+
// tied to it is ever posted to the frame's window. Opaque to the SDK.
|
|
41
|
+
const DECK_CHANNEL_COMMANDS = new Set([
|
|
42
|
+
"deck.invite",
|
|
43
|
+
"deck.inviteArrival",
|
|
44
|
+
"multiplayer.getSession",
|
|
45
|
+
"multiplayer.joinDestination",
|
|
46
|
+
]);
|
|
47
|
+
const DECK_CHANNEL_HANDSHAKE_MS = 5000;
|
|
48
|
+
let deckPort = null;
|
|
49
|
+
let deckHandshake = null;
|
|
50
|
+
function openDeckChannel(nonce) {
|
|
51
|
+
if (!nonce || typeof MessageChannel === "undefined" || resolveChannel() !== "web") {
|
|
52
|
+
return Promise.resolve();
|
|
53
|
+
}
|
|
54
|
+
return new Promise((resolve) => {
|
|
55
|
+
const { port1, port2 } = new MessageChannel();
|
|
56
|
+
const requestId = `${requestIdPrefix}deckChannel`;
|
|
57
|
+
let settled = false;
|
|
58
|
+
const done = (port) => {
|
|
59
|
+
if (settled)
|
|
60
|
+
return;
|
|
61
|
+
settled = true;
|
|
62
|
+
clearTimeout(timer);
|
|
63
|
+
deckHandshake = null;
|
|
64
|
+
if (port)
|
|
65
|
+
deckPort = port;
|
|
66
|
+
else
|
|
67
|
+
port1.close();
|
|
68
|
+
resolve();
|
|
69
|
+
};
|
|
70
|
+
const timer = setTimeout(() => done(null), DECK_CHANNEL_HANDSHAKE_MS);
|
|
71
|
+
deckHandshake = { requestId, done };
|
|
72
|
+
port1.onmessage = (event) => receiveFromPort(port1, event.data);
|
|
73
|
+
installHostListener();
|
|
74
|
+
try {
|
|
75
|
+
window.parent.postMessage({ castleSdk: CASTLE_SDK_PROTOCOL, requestId, command: "deck.channel", params: {}, documentNonce: nonce }, "*", [port2]);
|
|
76
|
+
}
|
|
77
|
+
catch {
|
|
78
|
+
done(null);
|
|
79
|
+
}
|
|
80
|
+
});
|
|
81
|
+
}
|
|
82
|
+
function receiveFromPort(port, message) {
|
|
83
|
+
const handshake = deckHandshake;
|
|
84
|
+
if (handshake && isResponseEnvelope(message) && message.requestId === handshake.requestId) {
|
|
85
|
+
const data = message.data;
|
|
86
|
+
handshake.done(message.ok && data?.status === "ok" ? port : null);
|
|
87
|
+
return;
|
|
88
|
+
}
|
|
89
|
+
if (port !== deckPort)
|
|
90
|
+
return;
|
|
91
|
+
// The host ended the channel (the frame's document or the deck's page
|
|
92
|
+
// changed): what was sent on it is not answered, and later commands go to
|
|
93
|
+
// window.parent. Each pending one fails as CASTLE_HOST_ERROR, a failure in
|
|
94
|
+
// transit, so a join asks again (hostRetry.ts), now on the window.
|
|
95
|
+
if (message?.castleSdk === CASTLE_SDK_PROTOCOL &&
|
|
96
|
+
message.deckChannelClosed === true) {
|
|
97
|
+
deckPort = null;
|
|
98
|
+
port.close();
|
|
99
|
+
for (const [requestId, entry] of [...pending]) {
|
|
100
|
+
if (entry.port !== port)
|
|
101
|
+
continue;
|
|
102
|
+
forget(requestId);
|
|
103
|
+
entry.reject(new CastleError({
|
|
104
|
+
code: "CASTLE_HOST_ERROR",
|
|
105
|
+
message: `Castle host ended the channel for ${entry.command}.`,
|
|
106
|
+
operation: entry.command,
|
|
107
|
+
}));
|
|
108
|
+
}
|
|
109
|
+
return;
|
|
110
|
+
}
|
|
111
|
+
receive(message, port);
|
|
112
|
+
}
|
|
113
|
+
function takeDocumentNonce() {
|
|
114
|
+
if (typeof window === "undefined")
|
|
115
|
+
return null;
|
|
116
|
+
try {
|
|
117
|
+
const value = window.__castleDocumentNonce;
|
|
118
|
+
delete window.__castleDocumentNonce;
|
|
119
|
+
return typeof value === "string" && value.length > 0 && value.length <= 256 ? value : null;
|
|
120
|
+
}
|
|
121
|
+
catch {
|
|
122
|
+
return null;
|
|
123
|
+
}
|
|
124
|
+
}
|
|
31
125
|
// Request ids carry a per-page prefix so that a host serving several decks at
|
|
32
126
|
// once can key a cancel by requestId alone.
|
|
33
127
|
const requestIdPrefix = `csdk_${Math.random().toString(36).slice(2, 10)}_`;
|
|
@@ -39,7 +133,13 @@ let voiceEventHandler = null;
|
|
|
39
133
|
let hubEventHandler = null;
|
|
40
134
|
export async function hostRequest(command, params, stream = {}) {
|
|
41
135
|
try {
|
|
42
|
-
const
|
|
136
|
+
const channel = resolveChannel();
|
|
137
|
+
const viaDeckChannel = channel === "web" && DECK_CHANNEL_COMMANDS.has(command);
|
|
138
|
+
// Only while the channel request is unanswered: otherwise this sends at once, as ever.
|
|
139
|
+
if (viaDeckChannel && deckHandshake)
|
|
140
|
+
await deckChannelReady;
|
|
141
|
+
const port = viaDeckChannel ? deckPort : null;
|
|
142
|
+
const env = await sendCommand(channel, command, params, stream, port);
|
|
43
143
|
return interpretResponse(command, env);
|
|
44
144
|
}
|
|
45
145
|
catch (error) {
|
|
@@ -136,7 +236,7 @@ function resolveChannel() {
|
|
|
136
236
|
// local dev server (top-level page served by `castle-web serve`).
|
|
137
237
|
return window.parent && window.parent !== window ? "web" : "local";
|
|
138
238
|
}
|
|
139
|
-
function sendCommand(channel, command, params, stream) {
|
|
239
|
+
function sendCommand(channel, command, params, stream, port = null) {
|
|
140
240
|
const requestId = `${requestIdPrefix}${nextRequestId++}`;
|
|
141
241
|
return new Promise((resolve, reject) => {
|
|
142
242
|
if (stream.signal?.aborted) {
|
|
@@ -144,18 +244,21 @@ function sendCommand(channel, command, params, stream) {
|
|
|
144
244
|
return;
|
|
145
245
|
}
|
|
146
246
|
const entry = { command, channel, resolve, reject, onStream: stream.onStream };
|
|
247
|
+
if (port)
|
|
248
|
+
entry.port = port;
|
|
147
249
|
pending.set(requestId, entry);
|
|
148
250
|
restartTimeout(requestId, entry, COMMAND_TIMEOUTS_MS[command] ?? REQUEST_TIMEOUT_MS);
|
|
149
251
|
watchAbort(requestId, entry, stream.signal);
|
|
150
252
|
if (channel === "local") {
|
|
151
|
-
sendLocalCommand(requestId, command, params, receive).catch((error) => {
|
|
253
|
+
sendLocalCommand(requestId, command, params, (message) => receive(message)).catch((error) => {
|
|
152
254
|
forget(requestId);
|
|
153
255
|
reject(error instanceof Error ? error : new Error(String(error)));
|
|
154
256
|
});
|
|
155
257
|
return;
|
|
156
258
|
}
|
|
157
259
|
installHostListener();
|
|
158
|
-
|
|
260
|
+
const envelope = { castleSdk: CASTLE_SDK_PROTOCOL, requestId, command, params };
|
|
261
|
+
postToHost(entry, envelope, stream.transfer);
|
|
159
262
|
});
|
|
160
263
|
}
|
|
161
264
|
// Interactive commands have no timeout; they resolve only when the host replies.
|
|
@@ -186,7 +289,7 @@ function watchAbort(requestId, entry, signal) {
|
|
|
186
289
|
requestId,
|
|
187
290
|
cancel: true,
|
|
188
291
|
};
|
|
189
|
-
|
|
292
|
+
postToHost(entry, envelope);
|
|
190
293
|
}
|
|
191
294
|
entry.reject(cancelledError(entry.command));
|
|
192
295
|
};
|
|
@@ -214,6 +317,12 @@ function cancelledError(command) {
|
|
|
214
317
|
operation: command,
|
|
215
318
|
});
|
|
216
319
|
}
|
|
320
|
+
function postToHost(entry, envelope, transfer = []) {
|
|
321
|
+
if (entry.port)
|
|
322
|
+
entry.port.postMessage(envelope, transfer);
|
|
323
|
+
else if (entry.channel !== "local")
|
|
324
|
+
sendEnvelope(entry.channel, envelope, transfer);
|
|
325
|
+
}
|
|
217
326
|
function sendEnvelope(channel, envelope, transfer = []) {
|
|
218
327
|
if (channel === "mobile") {
|
|
219
328
|
window.ReactNativeWebView?.postMessage(JSON.stringify(envelope));
|
|
@@ -237,15 +346,26 @@ export function installHostListener() {
|
|
|
237
346
|
receive(event.data);
|
|
238
347
|
});
|
|
239
348
|
}
|
|
240
|
-
|
|
349
|
+
// `viaPort`: the deck channel port it came on; null for the window (and the
|
|
350
|
+
// mobile and dev hosts). A request is settled or streamed to only from the
|
|
351
|
+
// channel it was sent on, so a window message naming a port request's id, or
|
|
352
|
+
// the reverse, is ignored.
|
|
353
|
+
function receive(message, viaPort = null) {
|
|
354
|
+
// An answer to the deck channel request on the window is a host without it.
|
|
355
|
+
if (!viaPort && deckHandshake && isResponseEnvelope(message) && message.requestId === deckHandshake.requestId) {
|
|
356
|
+
deckHandshake.done(null);
|
|
357
|
+
return;
|
|
358
|
+
}
|
|
241
359
|
if (isResponseEnvelope(message)) {
|
|
242
|
-
settle(message);
|
|
360
|
+
settle(message, viaPort);
|
|
243
361
|
return;
|
|
244
362
|
}
|
|
245
363
|
if (isStreamEnvelope(message)) {
|
|
246
|
-
deliverStream(message.requestId, message.stream);
|
|
364
|
+
deliverStream(message.requestId, message.stream, viaPort);
|
|
247
365
|
return;
|
|
248
366
|
}
|
|
367
|
+
if (viaPort)
|
|
368
|
+
return;
|
|
249
369
|
const voiceEvent = voiceEventFrom(message);
|
|
250
370
|
if (voiceEvent) {
|
|
251
371
|
voiceEventHandler?.(voiceEvent);
|
|
@@ -260,9 +380,9 @@ function receive(message) {
|
|
|
260
380
|
if (unloadId !== null)
|
|
261
381
|
unloadHandler?.(unloadId);
|
|
262
382
|
}
|
|
263
|
-
function settle(message) {
|
|
383
|
+
function settle(message, viaPort) {
|
|
264
384
|
const entry = pending.get(message.requestId);
|
|
265
|
-
if (!entry) {
|
|
385
|
+
if (!entry || (entry.port ?? null) !== viaPort) {
|
|
266
386
|
return;
|
|
267
387
|
}
|
|
268
388
|
forget(message.requestId);
|
|
@@ -292,9 +412,9 @@ function settle(message) {
|
|
|
292
412
|
}
|
|
293
413
|
}
|
|
294
414
|
// A throwing onStream is logged, and the stream goes on.
|
|
295
|
-
function deliverStream(requestId, event) {
|
|
415
|
+
function deliverStream(requestId, event, viaPort) {
|
|
296
416
|
const entry = pending.get(requestId);
|
|
297
|
-
if (!entry) {
|
|
417
|
+
if (!entry || (entry.port ?? null) !== viaPort) {
|
|
298
418
|
return;
|
|
299
419
|
}
|
|
300
420
|
restartTimeout(requestId, entry, STREAM_IDLE_TIMEOUT_MS);
|
|
@@ -318,3 +438,5 @@ function fromSerializedError(error, command) {
|
|
|
318
438
|
extensions: error?.extensions,
|
|
319
439
|
});
|
|
320
440
|
}
|
|
441
|
+
// Last, once every binding above exists: the deck channel opens at load.
|
|
442
|
+
const deckChannelReady = openDeckChannel(takeDocumentNonce());
|