castle-web-cli 0.4.230 → 0.4.231

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.
Files changed (69) hide show
  1. package/dist/castle-host/host.js +81 -0
  2. package/dist/devSaveStorage.d.ts +36 -0
  3. package/dist/devSaveStorage.js +469 -0
  4. package/dist/devSessionChild.js +22 -12
  5. package/dist/devSessionServer.js +8 -2
  6. package/dist/devSessionStorage.d.ts +9 -0
  7. package/dist/devSessionStorage.js +66 -1
  8. package/dist/init.js +1 -1
  9. package/dist/serve.js +5 -1
  10. package/kits/base/castle.json +1 -1
  11. package/kits/base/sdk/README.md +148 -1
  12. package/kits/base/sdk/castle.d.ts +4 -0
  13. package/kits/base/sdk/castle.js +2 -0
  14. package/kits/base/sdk/commands.d.ts +15 -0
  15. package/kits/base/sdk/multiplayer.js +52 -4
  16. package/kits/base/sdk/save.d.ts +197 -0
  17. package/kits/base/sdk/save.js +525 -0
  18. package/kits/base/sdk/saveCoordinator.d.ts +39 -0
  19. package/kits/base/sdk/saveCoordinator.js +252 -0
  20. package/kits/base/sdk/server/storage.d.ts +3 -2
  21. package/kits/base/sdk/server/storage.js +25 -5
  22. package/kits/base/sdk/server/wrapper.d.ts +4 -0
  23. package/kits/base/sdk/server/wrapper.js +2 -0
  24. package/kits/base/sdk/store.d.ts +3 -2
  25. package/kits/base/sdk/store.js +5 -0
  26. package/kits/hub-game/CLAUDE.md +4 -1
  27. package/kits/hub-game/code/client/chrome.js +43 -9
  28. package/kits/hub-game/code/client/grab.js +142 -7
  29. package/kits/hub-game/code/client/hookLayer.js +7 -1
  30. package/kits/hub-game/code/client/state.js +13 -1
  31. package/kits/hub-game/code/client/talk.js +10 -36
  32. package/kits/hub-game/code/client/tiers.js +480 -0
  33. package/kits/hub-game/code/client/together.js +78 -3
  34. package/kits/hub-game/code/server/grab.js +3 -2
  35. package/kits/hub-game/code/server/hub.js +99 -5
  36. package/kits/hub-game/code/server/manifest.js +34 -7
  37. package/kits/hub-game/code/server/npcs.js +21 -33
  38. package/kits/hub-game/code/server/party.js +64 -6
  39. package/kits/hub-game/code/systems/hub.js +133 -16
  40. package/kits/hub-game/docs/contract.md +84 -14
  41. package/kits/hub-game/package.json +1 -1
  42. package/kits/hub-game/scripts/test-grab-client.mjs +328 -0
  43. package/kits/hub-game/scripts/test-hub-trip.mjs +208 -0
  44. package/kits/hub-game/scripts/test-manifest.mjs +47 -1
  45. package/kits/hub-game/scripts/test-npcs.mjs +34 -24
  46. package/kits/hub-game/scripts/test-party.mjs +87 -4
  47. package/kits/hub-game/scripts/test-tiers.mjs +666 -0
  48. package/kits/hub-game/scripts/test-together.mjs +33 -1
  49. package/kits/physics-2d/CLAUDE.md +2 -0
  50. package/kits/physics-2d/castle.json +2 -2
  51. package/kits/physics-2d/engine/scene.js +92 -0
  52. package/kits/physics-2d/package.json +1 -1
  53. package/kits/physics-2d/scripts/test-skip-unchanged.mjs +254 -0
  54. package/kits/physics-3d/CLAUDE.md +279 -0
  55. package/kits/physics-3d/behaviors/Player.jsx +74 -1
  56. package/kits/physics-3d/castle.json +3 -3
  57. package/kits/physics-3d/engine3d/Scene3DPlayer.jsx +1 -1
  58. package/kits/physics-3d/engine3d/actornode.js +253 -0
  59. package/kits/physics-3d/engine3d/nearshadows.js +600 -0
  60. package/kits/physics-3d/engine3d/unchanged.js +153 -0
  61. package/kits/physics-3d/engine3d/world3d.js +465 -7
  62. package/kits/physics-3d/package.json +1 -1
  63. package/kits/physics-3d/scripts/test-camera-follow.mjs +533 -0
  64. package/kits/physics-3d/scripts/test-near-shadows.mjs +1073 -0
  65. package/kits/physics-3d/scripts/test-static-actors.mjs +662 -0
  66. package/kits/physics-3d/scripts/test-static-passes.mjs +459 -0
  67. package/kits/physics-3d/scripts/test-static-physics.mjs +128 -0
  68. package/kits/physics-3d/systems/physics3d.js +182 -3
  69. package/package.json +1 -1
@@ -8,7 +8,8 @@ import { fileURLToPath } from 'url';
8
8
  import { WebSocketServer, WebSocket } from 'ws';
9
9
  import { readCastleJson, resolveServerConfig } from './castleJson.js';
10
10
  import { OutboundFrameMeter } from './devSessionFrameBudget.js';
11
- import { runDevStorageOperation } from './devSessionStorage.js';
11
+ import { SAVE_VERBS } from './devSaveStorage.js';
12
+ import { runDevSave, runDevStorageOperation } from './devSessionStorage.js';
12
13
  import { rawDataToString } from './rawData.js';
13
14
  import { bundleServerModule } from './serverBundle.js';
14
15
  import { devDeckCastleJsons, devDeckSessionKey } from './contentPack.js';
@@ -598,13 +599,18 @@ class DevSessionImpl {
598
599
  this.log('log', warning);
599
600
  }
600
601
  async handleStorageRequest(reqId, op, args) {
602
+ const socket = this.platformSocket;
601
603
  const deckId = readCastleJson(this.projectDir)?.deckId;
602
604
  // Local serve has no host credential to stamp a remote player's authority. Its
603
605
  // authenticated OPEN roster proves presence here; GraphQL separately restricts
604
606
  // funded audience sends to the signed-in CLI user's own subject.
605
- const result = await runDevStorageOperation(deckId, op, args, this.connectedPlayers().map((player) => player.userId));
607
+ const result = SAVE_VERBS.has(op)
608
+ ? runDevSave(this.projectDir, this.sessionId, op, args)
609
+ : await runDevStorageOperation(deckId, op, args, this.connectedPlayers().map((player) => player.userId));
606
610
  // The child may have restarted while this was out; its replacement never asked, so
607
611
  // there is nobody to tell.
612
+ if (this.platformSocket !== socket)
613
+ return;
608
614
  this.sendPlatform({
609
615
  protocolVersion: PROTOCOL_VERSION,
610
616
  t: 'storageResult',
@@ -1,9 +1,18 @@
1
+ import type { GraphqlResponse } from './castle-host/host.js';
1
2
  export interface DevStorageResult {
2
3
  ok: boolean;
3
4
  value?: unknown;
4
5
  error?: {
5
6
  code: string;
6
7
  message: string;
8
+ [detail: string]: unknown;
7
9
  };
8
10
  }
11
+ /** A session server's save. Its args are what the platform's storage route takes. */
12
+ export declare function runDevSave(projectDir: string, sessionId: string, op: string, args: Record<string, unknown>): DevStorageResult;
13
+ /**
14
+ * A page's save, answered in place of the GraphQL call the browser host makes
15
+ * for it. Undefined for every other document, which goes to the real API.
16
+ */
17
+ export declare function devSaveGraphql(projectDir: string, userId: string | null, query: string, variables: Record<string, unknown>): GraphqlResponse | undefined;
9
18
  export declare function runDevStorageOperation(deckId: string | undefined, op: string, args: Record<string, unknown>, connectedUserIds?: readonly string[]): Promise<DevStorageResult>;
@@ -1,4 +1,62 @@
1
1
  import { graphql } from './api.js';
2
+ import { readCastleJson } from './castleJson.js';
3
+ import { DevSaveStorage } from './devSaveStorage.js';
4
+ // The platform's reply allowance for one storage call: its byte-rate window.
5
+ const SERVER_REPLY_BYTES = 2 * 1024 * 1024;
6
+ const CLIENT_REPLY_BYTES = 512 * 1024;
7
+ const saveStores = new Map();
8
+ function saveStoreFor(projectDir) {
9
+ let store = saveStores.get(projectDir);
10
+ if (!store) {
11
+ store = new DevSaveStorage();
12
+ saveStores.set(projectDir, store);
13
+ }
14
+ return store;
15
+ }
16
+ /** A session server's save. Its args are what the platform's storage route takes. */
17
+ export function runDevSave(projectDir, sessionId, op, args) {
18
+ const input = op === 'operation' ? args : args.input;
19
+ return saveStoreFor(projectDir).execute(op, input, {
20
+ principal: 'server',
21
+ binding: `session:${sessionId}`,
22
+ server: true,
23
+ deckWritable: true,
24
+ replyEnvelope: (value) => ({ value }),
25
+ replyBytes: SERVER_REPLY_BYTES,
26
+ });
27
+ }
28
+ const SAVE_FIELDS = {
29
+ cauldronStorageSnapshot: 'snapshot',
30
+ cauldronStorageOperation: 'operation',
31
+ cauldronStorageTransaction: 'transaction',
32
+ cauldronStorageClaim: 'claim',
33
+ cauldronStorageInitialize: 'initialize',
34
+ };
35
+ /**
36
+ * A page's save, answered in place of the GraphQL call the browser host makes
37
+ * for it. Undefined for every other document, which goes to the real API.
38
+ */
39
+ export function devSaveGraphql(projectDir, userId, query, variables) {
40
+ const field = /\b(cauldronStorage[A-Z][A-Za-z]*)\s*\(/.exec(query)?.[1];
41
+ const op = field && SAVE_FIELDS[field];
42
+ if (!field || !op)
43
+ return undefined;
44
+ const input = op === 'operation'
45
+ ? { operationId: variables.operationId }
46
+ : variables.input;
47
+ const result = saveStoreFor(projectDir).execute(op, input, {
48
+ principal: `user:${userId}`,
49
+ binding: `user:${userId}`,
50
+ server: false,
51
+ ...(userId ? { userId } : {}),
52
+ deckWritable: !readCastleJson(projectDir)?.server,
53
+ replyEnvelope: (value) => ({ data: { [field]: value } }),
54
+ replyBytes: CLIENT_REPLY_BYTES,
55
+ });
56
+ return result.ok
57
+ ? { data: { [field]: result.value } }
58
+ : { errors: [{ message: result.error.message, extensions: result.error }] };
59
+ }
2
60
  const SCOPE_ARGS = `
3
61
  $deckId: ID!
4
62
  $scope: CauldronStorageScope!
@@ -402,7 +460,14 @@ export async function runDevStorageOperation(deckId, op, args, connectedUserIds
402
460
  const error = response.errors?.[0];
403
461
  if (error) {
404
462
  const code = error.extensions?.code;
405
- return failure(typeof code === 'string' ? code : 'CAULDRON_STORAGE_UNAVAILABLE', error.message ?? 'storage request failed');
463
+ return {
464
+ ok: false,
465
+ error: {
466
+ ...error.extensions,
467
+ code: typeof code === 'string' ? code : 'CAULDRON_STORAGE_UNAVAILABLE',
468
+ message: error.message ?? 'storage request failed',
469
+ },
470
+ };
406
471
  }
407
472
  return { ok: true, value: response.data?.[operation.field] ?? null };
408
473
  }
package/dist/init.js CHANGED
@@ -64,7 +64,7 @@ const BARE_SCAFFOLDS = [
64
64
  // Registry version of castle-web-sdk to inject when scaffolding from a
65
65
  // globally-installed castle-web (not from inside the workspace). Bumped
66
66
  // alongside cli/sdk version bumps.
67
- const PUBLISHED_SDK_VERSION = '0.4.45';
67
+ const PUBLISHED_SDK_VERSION = '0.4.46';
68
68
  // Range, not a pin: `castle-web-fonts` is its own package precisely so a tenth
69
69
  // face can ship without a cli release, and a caret range means an existing
70
70
  // deck's next install picks it up. Nothing here has to move when it does.
package/dist/serve.js CHANGED
@@ -29,6 +29,7 @@ import { graphql as castleGraphql } from './api.js';
29
29
  import { executeCommand } from './castle-host/host.js';
30
30
  import { DevHubVisit, readDevHubDoors } from './devHub.js';
31
31
  import { DevExperiments } from './devExperiments.js';
32
+ import { devSaveGraphql } from './devSessionStorage.js';
32
33
  import { serveOracleStream } from './deckAgentRoute.js';
33
34
  import { ServeSecurity } from './serveSecurity.js';
34
35
  import { atomicWriteFileSync } from './atomicFile.js';
@@ -886,7 +887,10 @@ async function handleCastleCommand(ws, projectDir, broadcast, multiplayer, multi
886
887
  // does have: this process can't draw it, so the fetched payload goes to the
887
888
  // shell, which mounts the same panel the app and the website use.
888
889
  const result = await executeCommand(ctx, command, params, {
889
- graphqlFetch: castleGraphql,
890
+ graphqlFetch: (query, variables) => {
891
+ const save = devSaveGraphql(projectDir, ctx.userId, query, variables);
892
+ return save ? Promise.resolve(save) : castleGraphql(query, variables);
893
+ },
890
894
  oracleStream,
891
895
  showLeaderboard: (payload) => broadcast({ type: 'castle_leaderboard_show', payload }),
892
896
  hub: devHubVisit(ws, playSessionSlot, projectDir, multiplayer, multiplayerUrl),
@@ -82,7 +82,7 @@
82
82
  "title": "base",
83
83
  "deckId": "yRcmH4_aYllE",
84
84
  "cardId": "zkFdingmIm3m",
85
- "publishedVersion": "2026-10-04T01:28:15.203Z",
85
+ "publishedVersion": "2026-10-04T22:42:38.248Z",
86
86
  "provides": [
87
87
  "castle-web-sdk"
88
88
  ]
@@ -53,6 +53,12 @@ connection.onMessage((message) => receiveServerMessage(message));
53
53
  connection.send({ type: "ready" });
54
54
  ```
55
55
 
56
+ Attach `onMessage` in the same step that receives the connection (right after
57
+ `await Multiplayer.join(...)`). On a hub join (`mode: "hub"`), which resolves a
58
+ little after the socket's hello, messages the place sent in between, such as
59
+ the snapshot it greets a player with, are kept for that first listener. A
60
+ listener attached later gets only what arrives after it.
61
+
56
62
  Named rooms use `{ mode: "named", key: "room-name" }`; party sessions use
57
63
  `{ mode: "party" }`. Only one connection can be live per deck instance. The SDK
58
64
  reconnects temporary socket drops automatically. `onStateChange` reports
@@ -141,7 +147,8 @@ export default {
141
147
 
142
148
  `session.storage.deck` is shared by everyone playing.
143
149
  `session.storage.user(userId)` is one player's public data.
144
- `session.storage.board(name)` is a leaderboard. Each scope has the same
150
+ `session.storage.board(name)` is a leaderboard. The root and its buckets also
151
+ support the [atomic save API](#atomic-saves). Each scope has the same
145
152
  `get`, `set`, `remove`, `increment` and `list` as `Store`.
146
153
 
147
154
  Two differences follow from a session server not being a player:
@@ -469,6 +476,146 @@ A value is JSON, so binary data such as a picture or a video clip costs
469
476
  about a third more once encoded, and a clip of more than a few seconds
470
477
  does not fit in one. Ship media with the deck instead.
471
478
 
479
+ ### Atomic saves
480
+
481
+ `Store` and `session.storage` expose the same typed save methods:
482
+
483
+ - `snapshot({ targets: [{ target, select? }] })` reads every selected target at
484
+ one consistent point. `select` is `{ prefix }` or `{ keys }` within the
485
+ target; omitted selection reads its whole prefix. The result has `access`
486
+ and `targets: [{ target, revision, rows, complete }]`. `complete` describes
487
+ coverage of the entire target. A successful `null` revision means absent;
488
+ an initialized empty target has a revision. A failed read never means absent.
489
+ - `transaction({ operationId, expectedAccess, checks?, changes })` commits all
490
+ changes together. Each change has `target`, `expectedRevision` (string or
491
+ `null`), optional `writer`, and either `put`/`remove` or `replace`. `replace`
492
+ removes omitted rows within the prefix. Each target appears once. A `null`
493
+ expected revision creates only an absent target; an explicit `replace` also
494
+ supports importing unregistered legacy rows. `checks` are read-only target
495
+ checks with an expected revision and/or writer; they leave revisions intact.
496
+ - `claim({ operationId, expectedAccess?, target, initial?, load? })` explicitly
497
+ takes ownership of a target and returns `{ writer, receipt, snapshot }`.
498
+ `initial: [{ target, rows }]` initializes absent targets only. An absent
499
+ claimed target initializes empty if defaults were omitted. Claiming an
500
+ existing target leaves its data revision unchanged. The latest committed
501
+ claim wins; claimed targets require the current writer on every change.
502
+ - `initialize({ operationId, expectedAccess?, initial, load? })` initializes
503
+ only absent targets and returns `{ receipt, snapshot }`. Concurrent defaults
504
+ are applied once. It never claims ownership or replaces existing data.
505
+ - `operation(operationId)` returns `{ state: "committed", receipt }` or
506
+ `{ state: "unknown" }`. Unknown does not cancel a delayed request. Settle it
507
+ by replaying the original input and ID.
508
+
509
+ A target is `{ scope: "deck" | "user" | "private", subject?, prefix }`.
510
+ The prefix must be nonempty, and registered prefixes in a bucket cannot
511
+ intersect. All row keys stay inside their target. `subject` is only for user
512
+ scope; omitted subject means the current player. Session servers must name a
513
+ user and cannot access private targets. Permissions and quotas are unchanged:
514
+ deck-scoped bags remain publicly readable and share the deck allowance.
515
+ `rows`, `put` and `replace` are maps of keys to JSON values, validated through
516
+ the same JSON handling as ordinary Store writes.
517
+
518
+ A receipt contains `operationId`, `access`, `revisions: [{ target, revision }]`
519
+ and, for claims, `writer`. Access and revisions are opaque. Use snapshot access
520
+ as `expectedAccess`; reset and undo invalidate old access, revisions and writer
521
+ tokens. Claim/initialize may omit expected access for a deliberate first open.
522
+ When `load` is omitted, the SDK requests the claimed/initial targets. Supply
523
+ an explicit `load` to choose other targets or smaller projections.
524
+
525
+ Every bucket also has `target(prefix)` and the same methods with a `prefix`
526
+ wherever the root takes a `target`: `snapshot({ prefix, select? })`,
527
+ `transaction({ changes: [{ prefix, ... }], checks?: [{ prefix, ... }] })`,
528
+ `claim({ prefix, initial?: [{ prefix, rows }], load?: [{ prefix, select? }] })`,
529
+ `initialize({ initial: [{ prefix, rows }], load? })` and `operation(id)`.
530
+ Root methods can combine buckets atomically:
531
+
532
+ ```js
533
+ const room = session.storage.deck.target(`room:${roomId}:`);
534
+ const bag = session.storage.deck.target(`bag:${roomId}:${userId}:`);
535
+ const opened = await session.storage.claim({
536
+ operationId: crypto.randomUUID(),
537
+ target: room,
538
+ initial: [{ target: room, rows: roomDefaults }, { target: bag, rows: starterBag }],
539
+ load: [{ target: room }, { target: bag }],
540
+ });
541
+ const receipt = await session.storage.transaction({
542
+ operationId: actionId,
543
+ expectedAccess: opened.snapshot.access,
544
+ changes: [
545
+ { target: room, expectedRevision: opened.snapshot.targets[0].revision,
546
+ writer: opened.writer, put: changedRoomRows, remove: deletedRoomKeys },
547
+ { target: bag, expectedRevision: opened.snapshot.targets[1].revision,
548
+ put: changedBagRows },
549
+ ],
550
+ });
551
+ // Acknowledge the gameplay action only after this receipt.
552
+ ```
553
+
554
+ Atomic saves bypass ordinary coalescing and 32-key splitting. They are never
555
+ split into partial writes or retried as ordinary SETs. A request or snapshot
556
+ that exceeds a transport or single-charge byte allowance fails with
557
+ `CAULDRON_STORAGE_TOO_LARGE`; narrow the selection or reduce the atomic payload.
558
+ Ordinary `set`, `remove` and `increment` reject keys inside registered targets
559
+ with `CAULDRON_STORAGE_MANAGED_TARGET`.
560
+
561
+ Save methods reject with `SaveError`, exported from the client and server SDK.
562
+ It carries `code`, `message`, `operationId`, `retryable`,
563
+ `committed: false | true | "unknown"`, and optional `receipt`, `retryAfterMs`
564
+ and `target`. Extra platform details remain in `extensions`. Conflicts, writer
565
+ loss and stale access require explicit reload/rebuild. A replayed historical
566
+ claim can fail with writer loss while `committed === true` and its original
567
+ receipt; it never takes ownership again. Transport ambiguity keeps the outcome
568
+ unknown until receipt lookup or identical replay settles it.
569
+
570
+ ### Save coordinator
571
+
572
+ `createSaveCoordinator`, from `castle-web-sdk` or `castle-web-sdk/server`,
573
+ sends a deck's transactions in order and keeps each one until it settles:
574
+
575
+ ```js
576
+ const saves = createSaveCoordinator(session.storage, opened.snapshot, [
577
+ { target: room, writer: opened.writer },
578
+ ]);
579
+ const receipt = await saves.submit({
580
+ operationId: actionId,
581
+ checks: [{ target: room, writer: opened.writer }],
582
+ changes: [{ target: bag, put: changedBagRows }],
583
+ });
584
+ await saves.flush();
585
+ // saves.status is "pending", "saved" or "blocked".
586
+ ```
587
+
588
+ `submit` copies the save and resolves with its receipt once it commits. A
589
+ change without `expectedRevision` takes the target's revision from the latest
590
+ receipt, filled in when the save is first sent; a change without `writer`
591
+ takes the one passed in for its target. Saves are sent one at a time, in
592
+ order. A save whose reply was lost is looked up by its id and, when the
593
+ platform has no receipt for it, sent again unchanged.
594
+
595
+ A failure that cannot be settled that way sets `status` to `"blocked"` and
596
+ holds back every save behind it. When the outcome is unknown or the error is
597
+ retryable, the save's promise stays pending and `retry()` sends the same
598
+ request again. When the save definitely did not commit (a conflict, a lost
599
+ writer), its promise rejects and the coordinator stays blocked: reload a
600
+ snapshot and start a new coordinator. It never claims or rebuilds a save on
601
+ its own. `error`, `pendingOperationIds` and `revision(target)` show its state.
602
+
603
+ `flush()` resolves once every save submitted before it has committed, and
604
+ rejects if the queue blocks first. Saves submitted after it do not hold it up,
605
+ and an earlier receipt never marks a later save saved. For start-over, call
606
+ `discardUnsent()` and submit the replacement: saves already sent still settle
607
+ first, and the replacement goes out at the revision they leave.
608
+
609
+ Keep the coordinator in the page when a private worker is replaced. A page or
610
+ process that dies loses the saves it had not sent and the ids of those it had;
611
+ reopening restores the last committed snapshot.
612
+
613
+ During `castle-web serve`, the serve answers the save API itself, from one
614
+ in-memory store per project shared by its pages and named sessions. Its rows,
615
+ receipts and writers survive a runtime restart and are lost when the serve
616
+ exits. Ordinary `get`, `set` and `list` still use the deck's real storage, and
617
+ the two do not see each other's rows.
618
+
472
619
  ## Storage
473
620
 
474
621
  > Older API, still supported and not going away. New decks should use
@@ -46,3 +46,7 @@ export type { CastleClockZone, CastleDateParts, CastleTimeApi } from "./time";
46
46
  export type { Json } from "./types";
47
47
  export { User } from "./user";
48
48
  export type { CastleUser, CastleUserApi } from "./user";
49
+ export { createSaveCoordinator } from "./saveCoordinator";
50
+ export type { CoordinatedChange, CoordinatedSave, SaveCoordinator, SaveStatus, } from "./saveCoordinator";
51
+ export { SaveError } from "./save";
52
+ 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";
@@ -24,3 +24,5 @@ export { SharedStorage, Storage } from "./storage";
24
24
  export { Store } from "./store";
25
25
  export { Time } from "./time";
26
26
  export { User } from "./user";
27
+ export { createSaveCoordinator } from "./saveCoordinator";
28
+ export { SaveError } from "./save";
@@ -1,3 +1,4 @@
1
+ import type { SaveClaimed, SaveClaimInput, SaveInitializeInput, SaveOpened, SaveOperation, SaveReadTarget, SaveReceipt, SaveSnapshot, SaveTransactionInput } from "./save";
1
2
  import type { Json } from "./types";
2
3
  export declare const CASTLE_SDK_PROTOCOL = 1;
3
4
  export type StorageBlob = Record<string, string>;
@@ -584,6 +585,15 @@ export interface CommandParams {
584
585
  characterId: string;
585
586
  operationId: string;
586
587
  };
588
+ "cauldronStorage.snapshot": {
589
+ targets: SaveReadTarget[];
590
+ };
591
+ "cauldronStorage.transaction": SaveTransactionInput;
592
+ "cauldronStorage.claim": SaveClaimInput;
593
+ "cauldronStorage.initialize": SaveInitializeInput;
594
+ "cauldronStorage.operation": {
595
+ operationId: string;
596
+ };
587
597
  "cauldronStorage.get": {
588
598
  scope: StoreScope;
589
599
  subject?: string | null;
@@ -721,6 +731,11 @@ export interface CommandResult {
721
731
  "characters.status": CharacterOperation;
722
732
  "characters.history": CharacterHistory;
723
733
  "characters.reset": CharacterAdmission;
734
+ "cauldronStorage.snapshot": SaveSnapshot;
735
+ "cauldronStorage.transaction": SaveReceipt;
736
+ "cauldronStorage.claim": SaveClaimed;
737
+ "cauldronStorage.initialize": SaveOpened;
738
+ "cauldronStorage.operation": SaveOperation;
724
739
  "cauldronStorage.get": {
725
740
  entries: StoreEntry[];
726
741
  };
@@ -55,6 +55,7 @@ async function join(options) {
55
55
  connection.leave();
56
56
  throw multiplayerError("MULTIPLAYER_UNAVAILABLE", "The hub trip could not be completed; the player is still where they were.", "Multiplayer.join");
57
57
  }
58
+ connection.handedOver();
58
59
  return connection;
59
60
  }
60
61
  // A hub handoff is joined as it was acquired; it cannot be acquired again.
@@ -169,6 +170,8 @@ async function joinDestination(options) {
169
170
  activeConnection = connection;
170
171
  return { status: "joined", connection, audience: acquired.audience };
171
172
  }
173
+ // How many messages are kept for a deck that has not attached a listener yet.
174
+ const EARLY_MESSAGES_MAX = 512;
172
175
  class MultiplayerConnectionImpl {
173
176
  request;
174
177
  onClosed;
@@ -192,6 +195,16 @@ class MultiplayerConnectionImpl {
192
195
  sharedCharactersSupported = false;
193
196
  pendingCharacterRequests = new Map();
194
197
  messages = new Set();
198
+ // Messages that arrived before the deck had a listener, on a hub join only.
199
+ // A hub join resolves some tasks after the socket's hello (it first commits
200
+ // with the host), and a place greets a player with a snapshot in that gap:
201
+ // with nobody listening it was dropped, and the deck never saw the state it
202
+ // joined into. They are kept, in order, for a listener attached as soon as
203
+ // the deck is handed the connection (`handedOver`); a deck that attaches one
204
+ // later gets only what arrives from then on. Null on every other join, which
205
+ // resolves in the hello's own task: nothing is kept there and delivery is
206
+ // exactly what it always was.
207
+ early = null;
195
208
  rosters = new Set();
196
209
  states = new Set();
197
210
  voiceImpl = new MultiplayerVoiceImpl({
@@ -312,8 +325,43 @@ class MultiplayerConnectionImpl {
312
325
  }
313
326
  onMessage(callback) {
314
327
  this.messages.add(callback);
328
+ const early = this.early;
329
+ if (early) {
330
+ // The first listener takes what arrived before it; later ones get only
331
+ // what arrives from now on, as before.
332
+ this.early = null;
333
+ for (const data of early) {
334
+ // A listener that leaves part-way hears no more.
335
+ if (this.currentState === "closed")
336
+ break;
337
+ callListener(callback, data);
338
+ }
339
+ }
315
340
  return () => this.messages.delete(callback);
316
341
  }
342
+ /**
343
+ * The deck is being handed this connection. Whatever arrived before that is
344
+ * kept through the deck's own next step (the code after its `await`), where
345
+ * a kit attaches its listener; after that, nothing more is kept.
346
+ */
347
+ handedOver() {
348
+ if (!this.early)
349
+ return;
350
+ setTimeout(() => {
351
+ if (this.messages.size === 0)
352
+ this.early = null;
353
+ }, 0);
354
+ }
355
+ deliver(data) {
356
+ if (this.early && this.messages.size === 0) {
357
+ // Bounded: a deck that never listens does not grow this forever.
358
+ if (this.early.length < EARLY_MESSAGES_MAX)
359
+ this.early.push(data);
360
+ return;
361
+ }
362
+ for (const callback of this.messages)
363
+ callListener(callback, data);
364
+ }
317
365
  onRoster(callback) {
318
366
  this.rosters.add(callback);
319
367
  if (this.roster)
@@ -343,6 +391,7 @@ class MultiplayerConnectionImpl {
343
391
  hostRequest("hub.cancel", { nonce }).catch(() => { });
344
392
  return;
345
393
  }
394
+ this.early = [];
346
395
  this.hubCommit = commitHubTrip(nonce, this.currentSessionId);
347
396
  }
348
397
  hubCommitted() {
@@ -516,8 +565,7 @@ class MultiplayerConnectionImpl {
516
565
  this.acceptRoster(frame);
517
566
  break;
518
567
  case "m":
519
- for (const callback of this.messages)
520
- callListener(callback, frame.d);
568
+ this.deliver(frame.d);
521
569
  break;
522
570
  case "worldCharacterResult":
523
571
  this.acceptWorldCharacterResult(frame);
@@ -542,8 +590,7 @@ class MultiplayerConnectionImpl {
542
590
  if (bytes.byteLength < 1 || bytes[0] !== BINARY_MESSAGE_TAG)
543
591
  return;
544
592
  const payload = new Uint8Array(buffer, 1);
545
- for (const callback of this.messages)
546
- callListener(callback, payload);
593
+ this.deliver(payload);
547
594
  }
548
595
  acceptRoster(frame) {
549
596
  const players = frame.players.slice();
@@ -653,6 +700,7 @@ class MultiplayerConnectionImpl {
653
700
  this.socketAttempt += 1;
654
701
  closeSocket(socket, 1000, "session closed");
655
702
  this.currentState = "closed";
703
+ this.early = null;
656
704
  this.voiceImpl.dispose();
657
705
  for (const callback of this.states)
658
706
  callStateListener(callback, "closed", metadata);