castle-web-cli 0.4.230 → 0.4.232

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 (92) 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/dist/serverBundle.js +5 -3
  11. package/kits/base/castle.json +1 -1
  12. package/kits/base/sdk/README.md +148 -1
  13. package/kits/base/sdk/castle.d.ts +4 -0
  14. package/kits/base/sdk/castle.js +2 -0
  15. package/kits/base/sdk/commands.d.ts +15 -0
  16. package/kits/base/sdk/multiplayer.js +52 -4
  17. package/kits/base/sdk/save.d.ts +197 -0
  18. package/kits/base/sdk/save.js +525 -0
  19. package/kits/base/sdk/saveCoordinator.d.ts +39 -0
  20. package/kits/base/sdk/saveCoordinator.js +252 -0
  21. package/kits/base/sdk/server/storage.d.ts +3 -2
  22. package/kits/base/sdk/server/storage.js +25 -5
  23. package/kits/base/sdk/server/wrapper.d.ts +4 -0
  24. package/kits/base/sdk/server/wrapper.js +2 -0
  25. package/kits/base/sdk/store.d.ts +3 -2
  26. package/kits/base/sdk/store.js +5 -0
  27. package/kits/hub-game/CLAUDE.md +29 -4
  28. package/kits/hub-game/code/client/avatar.js +39 -0
  29. package/kits/hub-game/code/client/chat.js +12 -0
  30. package/kits/hub-game/code/client/chrome.js +237 -13
  31. package/kits/hub-game/code/client/grab.js +166 -7
  32. package/kits/hub-game/code/client/hats.js +26 -0
  33. package/kits/hub-game/code/client/hookLayer.js +36 -3
  34. package/kits/hub-game/code/client/hudClear.js +126 -0
  35. package/kits/hub-game/code/client/state.js +35 -1
  36. package/kits/hub-game/code/client/talk.js +10 -36
  37. package/kits/hub-game/code/client/tiers.js +505 -0
  38. package/kits/hub-game/code/client/together.js +144 -4
  39. package/kits/hub-game/code/client/wear.js +96 -14
  40. package/kits/hub-game/code/server/actors.js +5 -0
  41. package/kits/hub-game/code/server/grab.js +299 -13
  42. package/kits/hub-game/code/server/hub.js +162 -7
  43. package/kits/hub-game/code/server/manifest.js +80 -8
  44. package/kits/hub-game/code/server/npcs.js +21 -33
  45. package/kits/hub-game/code/server/party.js +75 -6
  46. package/kits/hub-game/code/server/say.js +8 -2
  47. package/kits/hub-game/code/server/wear.js +116 -11
  48. package/kits/hub-game/code/systems/hub.js +386 -21
  49. package/kits/hub-game/docs/contract.md +285 -19
  50. package/kits/hub-game/package.json +1 -1
  51. package/kits/hub-game/scripts/test-chat.mjs +32 -0
  52. package/kits/hub-game/scripts/test-grab-client.mjs +511 -0
  53. package/kits/hub-game/scripts/test-grab.mjs +857 -3
  54. package/kits/hub-game/scripts/test-hats.mjs +229 -0
  55. package/kits/hub-game/scripts/test-hub-trip.mjs +721 -0
  56. package/kits/hub-game/scripts/test-hud-clear.mjs +676 -0
  57. package/kits/hub-game/scripts/test-manifest.mjs +122 -1
  58. package/kits/hub-game/scripts/test-npcs.mjs +34 -24
  59. package/kits/hub-game/scripts/test-party.mjs +108 -4
  60. package/kits/hub-game/scripts/test-say.mjs +59 -2
  61. package/kits/hub-game/scripts/test-tiers.mjs +854 -0
  62. package/kits/hub-game/scripts/test-together.mjs +33 -1
  63. package/kits/hub-game/scripts/test-try-on.mjs +940 -0
  64. package/kits/physics-2d/CLAUDE.md +2 -0
  65. package/kits/physics-2d/castle.json +2 -2
  66. package/kits/physics-2d/engine/scene.js +127 -0
  67. package/kits/physics-2d/package.json +1 -1
  68. package/kits/physics-2d/scripts/test-skip-unchanged.mjs +298 -0
  69. package/kits/physics-3d/CLAUDE.md +531 -0
  70. package/kits/physics-3d/behaviors/Player.jsx +437 -3
  71. package/kits/physics-3d/castle.json +3 -3
  72. package/kits/physics-3d/docs/pxmodel-format.md +4 -0
  73. package/kits/physics-3d/engine3d/Scene3DPlayer.jsx +33 -1
  74. package/kits/physics-3d/engine3d/actornode.js +253 -0
  75. package/kits/physics-3d/engine3d/nearshadows.js +600 -0
  76. package/kits/physics-3d/engine3d/optimize.js +49 -0
  77. package/kits/physics-3d/engine3d/orbitinput.js +277 -0
  78. package/kits/physics-3d/engine3d/unchanged.js +153 -0
  79. package/kits/physics-3d/engine3d/world3d.js +525 -11
  80. package/kits/physics-3d/package.json +1 -1
  81. package/kits/physics-3d/scripts/Player.before-orbit.mjs +310 -0
  82. package/kits/physics-3d/scripts/Scene3DPlayer.before-orbit.jsx +337 -0
  83. package/kits/physics-3d/scripts/test-camera-follow.mjs +543 -0
  84. package/kits/physics-3d/scripts/test-camera-orbit.mjs +2105 -0
  85. package/kits/physics-3d/scripts/test-drop-empty-parts.mjs +787 -0
  86. package/kits/physics-3d/scripts/test-near-shadows.mjs +1073 -0
  87. package/kits/physics-3d/scripts/test-static-actors.mjs +667 -0
  88. package/kits/physics-3d/scripts/test-static-passes.mjs +459 -0
  89. package/kits/physics-3d/scripts/test-static-physics.mjs +128 -0
  90. package/kits/physics-3d/scripts/test-steady-hover.mjs +633 -0
  91. package/kits/physics-3d/systems/physics3d.js +273 -9
  92. package/package.json +1 -1
@@ -66,6 +66,11 @@ const COMMAND_NAMES = [
66
66
  "characters.status",
67
67
  "characters.history",
68
68
  "characters.reset",
69
+ "cauldronStorage.snapshot",
70
+ "cauldronStorage.operation",
71
+ "cauldronStorage.transaction",
72
+ "cauldronStorage.claim",
73
+ "cauldronStorage.initialize",
69
74
  "cauldronStorage.get",
70
75
  "cauldronStorage.set",
71
76
  "cauldronStorage.delete",
@@ -256,6 +261,12 @@ function runCommand(ctx, command, params, caps, options) {
256
261
  return charactersHistory(ctx, params, gql);
257
262
  case "characters.reset":
258
263
  return charactersReset(ctx, params, gql);
264
+ case "cauldronStorage.snapshot":
265
+ case "cauldronStorage.operation":
266
+ case "cauldronStorage.transaction":
267
+ case "cauldronStorage.claim":
268
+ case "cauldronStorage.initialize":
269
+ return cauldronSave(ctx, command, params, gql);
259
270
  case "cauldronStorage.get":
260
271
  return cauldronStorageGet(ctx, params, gql);
261
272
  case "cauldronStorage.set":
@@ -2111,6 +2122,33 @@ function asStoreEntries(value, command) {
2111
2122
  };
2112
2123
  });
2113
2124
  }
2125
+ // A save is one GraphQL call taking its request as JSON. The deck's params are
2126
+ // that request; the deck id comes from the host.
2127
+ async function cauldronSave(ctx, command, params, gql) {
2128
+ const { field, query } = CAULDRON_SAVE_DOCUMENTS[command];
2129
+ const deckId = requireDeckId(ctx, command);
2130
+ const variables = command === "cauldronStorage.operation"
2131
+ ? { deckId, operationId: params.operationId }
2132
+ : { deckId, input: params };
2133
+ // One client charge cannot exceed the whole 512 KiB/s byte-rate window, so a
2134
+ // bigger request can never succeed.
2135
+ const encodedBytes = new TextEncoder().encode(JSON.stringify({ query, variables })).length;
2136
+ if (encodedBytes > CLIENT_SAVE_REQUEST_MAX_BYTES) {
2137
+ throw new HostCommandError("CAULDRON_STORAGE_TOO_LARGE", `The save request is ${encodedBytes} bytes, over the ${CLIENT_SAVE_REQUEST_MAX_BYTES} a client may send.`, command, {
2138
+ operationId: params.operationId,
2139
+ retryable: false,
2140
+ committed: false,
2141
+ encodedBytes,
2142
+ limitBytes: CLIENT_SAVE_REQUEST_MAX_BYTES,
2143
+ });
2144
+ }
2145
+ const data = await graphql(gql, query, variables, command);
2146
+ const result = data[field];
2147
+ if (result === null || result === undefined) {
2148
+ throw new HostCommandError("CAULDRON_STORAGE_INVALID_RESPONSE", "Storage returned no save result.", command, { operationId: params.operationId, retryable: false, committed: "unknown" });
2149
+ }
2150
+ return result;
2151
+ }
2114
2152
  async function cauldronStorageGet(ctx, params, gql) {
2115
2153
  const deckId = requireDeckId(ctx, "cauldronStorage.get");
2116
2154
  const data = await graphql(gql, CAULDRON_STORAGE_GET_QUERY, {
@@ -2617,6 +2655,49 @@ const CAULDRON_MULTIPLAYER_DESTINATION_SESSION_QUERY = `
2617
2655
  }
2618
2656
  }
2619
2657
  `;
2658
+ const CLIENT_SAVE_REQUEST_MAX_BYTES = 512 * 1024;
2659
+ const CAULDRON_SAVE_DOCUMENTS = {
2660
+ "cauldronStorage.snapshot": {
2661
+ field: "cauldronStorageSnapshot",
2662
+ query: `
2663
+ query CastleCauldronStorageSnapshot($deckId: ID!, $input: Json!) {
2664
+ cauldronStorageSnapshot(deckId: $deckId, input: $input)
2665
+ }
2666
+ `,
2667
+ },
2668
+ "cauldronStorage.operation": {
2669
+ field: "cauldronStorageOperation",
2670
+ query: `
2671
+ query CastleCauldronStorageOperation($deckId: ID!, $operationId: String!) {
2672
+ cauldronStorageOperation(deckId: $deckId, operationId: $operationId)
2673
+ }
2674
+ `,
2675
+ },
2676
+ "cauldronStorage.transaction": {
2677
+ field: "cauldronStorageTransaction",
2678
+ query: `
2679
+ mutation CastleCauldronStorageTransaction($deckId: ID!, $input: Json!) {
2680
+ cauldronStorageTransaction(deckId: $deckId, input: $input)
2681
+ }
2682
+ `,
2683
+ },
2684
+ "cauldronStorage.claim": {
2685
+ field: "cauldronStorageClaim",
2686
+ query: `
2687
+ mutation CastleCauldronStorageClaim($deckId: ID!, $input: Json!) {
2688
+ cauldronStorageClaim(deckId: $deckId, input: $input)
2689
+ }
2690
+ `,
2691
+ },
2692
+ "cauldronStorage.initialize": {
2693
+ field: "cauldronStorageInitialize",
2694
+ query: `
2695
+ mutation CastleCauldronStorageInitialize($deckId: ID!, $input: Json!) {
2696
+ cauldronStorageInitialize(deckId: $deckId, input: $input)
2697
+ }
2698
+ `,
2699
+ },
2700
+ };
2620
2701
  const CAULDRON_STORAGE_GET_QUERY = `
2621
2702
  query CastleCauldronStorageGet(
2622
2703
  $deckId: ID!
@@ -0,0 +1,36 @@
1
+ /** Who is calling, as the serve knows it. */
2
+ export interface DevSaveCaller {
3
+ /** Receipts are looked up per principal. */
4
+ principal: string;
5
+ /** A claim's writer works only for the same binding: the session, or the page's user. */
6
+ binding: string;
7
+ server: boolean;
8
+ userId?: string;
9
+ /** Whether a client may write deck scope: only a deck without a session server. */
10
+ deckWritable: boolean;
11
+ /** The encoded reply the platform would send, measured against `replyBytes`. */
12
+ replyEnvelope: (value: unknown) => unknown;
13
+ replyBytes: number;
14
+ }
15
+ export type DevSaveResult = {
16
+ ok: true;
17
+ value: unknown;
18
+ } | {
19
+ ok: false;
20
+ error: {
21
+ code: string;
22
+ message: string;
23
+ [detail: string]: unknown;
24
+ };
25
+ };
26
+ export declare const SAVE_VERBS: ReadonlySet<string>;
27
+ export declare class DevSaveStorage {
28
+ readonly access: `${string}-${string}-${string}-${string}-${string}`;
29
+ private state;
30
+ private readonly operations;
31
+ execute(verb: string, input: Record<string, unknown>, caller: DevSaveCaller): DevSaveResult;
32
+ private replay;
33
+ private commit;
34
+ private snapshot;
35
+ private reply;
36
+ }
@@ -0,0 +1,469 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ export const SAVE_VERBS = new Set([
3
+ 'snapshot',
4
+ 'operation',
5
+ 'transaction',
6
+ 'claim',
7
+ 'initialize',
8
+ ]);
9
+ const MAX_KEY_BYTES = 128;
10
+ const MAX_SUBJECT_BYTES = 256;
11
+ const MAX_VALUE_BYTES = 256 * 1024;
12
+ class SaveFailure extends Error {
13
+ code;
14
+ details;
15
+ constructor(code, message, details = {}) {
16
+ super(message);
17
+ this.code = code;
18
+ this.details = details;
19
+ }
20
+ }
21
+ function fail(code, message, details = {}) {
22
+ throw new SaveFailure(`CAULDRON_STORAGE_${code}`, message, details);
23
+ }
24
+ export class DevSaveStorage {
25
+ // Stands for the deck's reset epoch, which never moves during a serve.
26
+ access = randomUUID();
27
+ state = { rows: new Map(), targets: new Map(), version: 0 };
28
+ operations = new Map();
29
+ execute(verb, input, caller) {
30
+ const operationId = typeof input?.operationId === 'string' ? input.operationId : undefined;
31
+ let replayed;
32
+ try {
33
+ if (!input || typeof input !== 'object')
34
+ fail('INVALID_ARGUMENT', 'Expected an object.');
35
+ if (verb === 'snapshot') {
36
+ return this.reply(caller, this.snapshot(this.state, reads(input.targets, caller)));
37
+ }
38
+ const id = text(input.operationId, 'operation id', MAX_KEY_BYTES);
39
+ const stored = this.operations.get(JSON.stringify([caller.principal, id]));
40
+ stored?.writes.forEach((target) => assertWrite(target, caller));
41
+ if (verb === 'operation') {
42
+ return this.reply(caller, stored ? { state: 'committed', receipt: stored.receipt } : { state: 'unknown' });
43
+ }
44
+ if (!['transaction', 'claim', 'initialize'].includes(verb)) {
45
+ fail('INVALID_ARGUMENT', `Unknown save verb ${verb}.`);
46
+ }
47
+ const request = parseWrite(verb, input, caller);
48
+ if (stored) {
49
+ if (stored.digest !== request.digest) {
50
+ fail('OPERATION_MISMATCH', 'The operation id was used before with different input.');
51
+ }
52
+ replayed = stored.receipt;
53
+ return this.replay(verb, request, stored, caller);
54
+ }
55
+ return this.commit(verb, id, request, caller);
56
+ }
57
+ catch (error) {
58
+ if (!(error instanceof SaveFailure))
59
+ throw error;
60
+ return {
61
+ ok: false,
62
+ error: {
63
+ ...error.details,
64
+ code: error.code,
65
+ message: error.message,
66
+ operationId,
67
+ retryable: false,
68
+ // A repeat of a committed operation stays committed, whatever failed after.
69
+ ...(replayed ? { committed: true, receipt: replayed } : { committed: false }),
70
+ },
71
+ };
72
+ }
73
+ }
74
+ // The stored receipt answers a repeat. A repeated claim whose writer has since
75
+ // been replaced fails rather than claiming again.
76
+ replay(verb, request, stored, caller) {
77
+ if (verb === 'transaction')
78
+ return this.reply(caller, stored.receipt);
79
+ if (stored.claim) {
80
+ const claimed = this.state.targets.get(targetId(stored.claim));
81
+ if (claimed?.writer !== stored.receipt.writer || claimed?.writerBinding !== caller.binding) {
82
+ fail('WRITER_LOST', 'The target was claimed again since.', {
83
+ target: publicTarget(stored.claim),
84
+ });
85
+ }
86
+ }
87
+ return this.reply(caller, {
88
+ receipt: stored.receipt,
89
+ ...(stored.claim ? { writer: stored.receipt.writer } : {}),
90
+ snapshot: this.snapshot(this.state, request.load),
91
+ });
92
+ }
93
+ commit(verb, operationId, request, caller) {
94
+ if (request.expectedAccess !== undefined && request.expectedAccess !== this.access) {
95
+ fail('STALE_ACCESS', 'Storage was reset since that access; reload before saving.');
96
+ }
97
+ const next = copyState(this.state);
98
+ const touched = [
99
+ ...request.changes.map((change) => change.target),
100
+ ...request.checks.map((check) => check.target),
101
+ ...request.initial.map((entry) => entry.target),
102
+ ...(request.claim ? [request.claim] : []),
103
+ ];
104
+ assertNoOverlap(next, touched);
105
+ for (const check of request.checks)
106
+ checkAuthority(next, this.access, check, false, caller);
107
+ for (const change of request.changes)
108
+ checkAuthority(next, this.access, change, true, caller);
109
+ const changed = [];
110
+ for (const change of request.changes) {
111
+ applyChange(next, change);
112
+ changed.push(change.target);
113
+ }
114
+ for (const entry of request.initial) {
115
+ if (!next.targets.has(targetId(entry.target))) {
116
+ applyChange(next, { target: entry.target, put: entry.rows });
117
+ }
118
+ changed.push(entry.target);
119
+ }
120
+ let writer;
121
+ if (request.claim) {
122
+ const id = targetId(request.claim);
123
+ if (!next.targets.has(id))
124
+ applyChange(next, { target: request.claim, put: {} });
125
+ writer = randomUUID();
126
+ Object.assign(next.targets.get(id), { writer, writerBinding: caller.binding });
127
+ changed.push(request.claim);
128
+ }
129
+ const unique = new Map(changed.map((target) => [targetId(target), target]));
130
+ const receipt = {
131
+ operationId,
132
+ access: this.access,
133
+ revisions: [...unique.values()].map((target) => ({
134
+ target: publicTarget(target),
135
+ revision: revisionOf(this.access, next.targets.get(targetId(target))),
136
+ })),
137
+ ...(writer ? { writer } : {}),
138
+ };
139
+ const value = verb === 'transaction'
140
+ ? receipt
141
+ : { receipt, ...(writer ? { writer } : {}), snapshot: this.snapshot(next, request.load) };
142
+ // The reply is measured before anything is kept, as the platform does.
143
+ const result = this.reply(caller, value);
144
+ this.state = next;
145
+ this.operations.set(JSON.stringify([caller.principal, operationId]), {
146
+ digest: request.digest,
147
+ receipt,
148
+ writes: request.writes,
149
+ ...(request.claim ? { claim: request.claim } : {}),
150
+ });
151
+ return result;
152
+ }
153
+ snapshot(state, reads) {
154
+ return {
155
+ access: this.access,
156
+ targets: reads.map((read) => {
157
+ const target = state.targets.get(targetId(read.target));
158
+ const rows = rowsIn(state, read.target);
159
+ if (!target && rows.length > 0) {
160
+ fail('LEGACY_DATA_PRESENT', 'Rows under this prefix belong to no target.', {
161
+ target: publicTarget(read.target),
162
+ });
163
+ }
164
+ const select = read.select;
165
+ const selected = rows.filter(([key]) => select?.keys ? select.keys.includes(key) : key.startsWith(select?.prefix ?? ''));
166
+ return {
167
+ target: publicTarget(read.target),
168
+ revision: target ? revisionOf(this.access, target) : null,
169
+ rows: Object.fromEntries(selected.map(([key, value]) => [key, JSON.parse(value)])),
170
+ complete: !select || select.prefix === read.target.prefix,
171
+ };
172
+ }),
173
+ };
174
+ }
175
+ reply(caller, value) {
176
+ const encodedBytes = Buffer.byteLength(JSON.stringify(caller.replyEnvelope(value)), 'utf8');
177
+ if (encodedBytes > caller.replyBytes) {
178
+ fail('TOO_LARGE', 'The reply is over its byte allowance.', {
179
+ encodedBytes,
180
+ limitBytes: caller.replyBytes,
181
+ });
182
+ }
183
+ return { ok: true, value: structuredClone(value) };
184
+ }
185
+ }
186
+ function parseWrite(verb, input, caller) {
187
+ const fields = verb === 'transaction'
188
+ ? ['operationId', 'expectedAccess', 'checks', 'changes']
189
+ : verb === 'claim'
190
+ ? ['operationId', 'expectedAccess', 'target', 'initial', 'load']
191
+ : ['operationId', 'expectedAccess', 'initial', 'load'];
192
+ if (Object.keys(input).some((field) => !fields.includes(field))) {
193
+ fail('INVALID_ARGUMENT', 'Unknown field in the save request.');
194
+ }
195
+ if (verb === 'transaction' || input.expectedAccess !== undefined) {
196
+ text(input.expectedAccess, 'expected access');
197
+ }
198
+ if (verb === 'initialize' && input.initial === undefined) {
199
+ fail('INVALID_ARGUMENT', 'initialize needs initial targets.');
200
+ }
201
+ const changes = verb === 'transaction'
202
+ ? list(input.changes, 'changes').map((value) => change(value, caller))
203
+ : [];
204
+ const checks = verb === 'transaction'
205
+ ? list(input.checks ?? [], 'checks').map((value) => check(value, caller))
206
+ : [];
207
+ const initial = verb === 'transaction'
208
+ ? []
209
+ : list(input.initial ?? [], 'initial').map((value) => {
210
+ const entry = value;
211
+ const target = resolveTarget(entry.target, caller);
212
+ return { target, rows: rows(entry.rows, target) };
213
+ });
214
+ assertOnce(changes.map((entry) => entry.target), 'changed');
215
+ assertOnce(initial.map((entry) => entry.target), 'initial');
216
+ const claim = verb === 'claim' ? resolveTarget(input.target, caller) : undefined;
217
+ const writes = [...changes.map((entry) => entry.target), ...initial.map((entry) => entry.target)];
218
+ if (claim)
219
+ writes.push(claim);
220
+ writes.forEach((target) => assertWrite(target, caller));
221
+ const load = verb === 'transaction' ? [] : reads(input.load ?? [], caller);
222
+ return {
223
+ ...(typeof input.expectedAccess === 'string' ? { expectedAccess: input.expectedAccess } : {}),
224
+ checks,
225
+ changes,
226
+ initial,
227
+ ...(claim ? { claim } : {}),
228
+ load,
229
+ writes,
230
+ digest: canonicalJson({ verb, input }),
231
+ };
232
+ }
233
+ function change(value, caller) {
234
+ const entry = value;
235
+ const target = resolveTarget(entry.target, caller);
236
+ if (entry.expectedRevision !== null)
237
+ text(entry.expectedRevision, 'expected revision');
238
+ if (entry.writer !== undefined)
239
+ text(entry.writer, 'writer');
240
+ if (entry.replace !== undefined && (entry.put !== undefined || entry.remove !== undefined)) {
241
+ fail('INVALID_ARGUMENT', 'replace cannot be combined with put or remove.');
242
+ }
243
+ const put = entry.put === undefined ? undefined : rows(entry.put, target);
244
+ const remove = entry.remove === undefined
245
+ ? undefined
246
+ : list(entry.remove, 'remove').map((key) => keyIn(key, target));
247
+ if (remove?.some((key) => put && Object.hasOwn(put, key))) {
248
+ fail('INVALID_ARGUMENT', 'A key cannot be both put and removed.');
249
+ }
250
+ return {
251
+ target,
252
+ expectedRevision: entry.expectedRevision,
253
+ ...(entry.writer === undefined ? {} : { writer: entry.writer }),
254
+ ...(put ? { put } : {}),
255
+ ...(remove ? { remove } : {}),
256
+ ...(entry.replace === undefined ? {} : { replace: rows(entry.replace, target) }),
257
+ };
258
+ }
259
+ function check(value, caller) {
260
+ const entry = value;
261
+ const target = resolveTarget(entry.target, caller);
262
+ if (entry.expectedRevision === undefined && entry.writer === undefined) {
263
+ fail('INVALID_ARGUMENT', 'A check needs an expected revision or a writer.');
264
+ }
265
+ if (entry.expectedRevision !== undefined)
266
+ text(entry.expectedRevision, 'expected revision');
267
+ if (entry.writer !== undefined)
268
+ text(entry.writer, 'writer');
269
+ return { target, expectedRevision: entry.expectedRevision, writer: entry.writer };
270
+ }
271
+ function reads(value, caller) {
272
+ return list(value, 'targets').map((entry) => {
273
+ const read = entry;
274
+ const target = resolveTarget(read.target, caller);
275
+ const select = read.select;
276
+ if (select === undefined)
277
+ return { target };
278
+ if ((select.prefix === undefined) === (select.keys === undefined)) {
279
+ fail('INVALID_ARGUMENT', 'A selection has either keys or a prefix.');
280
+ }
281
+ if (select.prefix !== undefined)
282
+ return { target, select: { prefix: keyIn(select.prefix, target) } };
283
+ return { target, select: { keys: list(select.keys, 'keys').map((key) => keyIn(key, target)) } };
284
+ });
285
+ }
286
+ // A client's user and private targets default to the signed-in player. Private
287
+ // storage is the page's own: servers cannot reach it, and nobody else's is visible.
288
+ function resolveTarget(value, caller) {
289
+ if (!value || typeof value !== 'object')
290
+ fail('INVALID_ARGUMENT', 'Invalid save target.');
291
+ const scope = String(value.scope).toLowerCase();
292
+ const prefix = text(value.prefix, 'target prefix', MAX_KEY_BYTES);
293
+ if (scope === 'deck') {
294
+ if (value.subject !== undefined)
295
+ fail('INVALID_ARGUMENT', 'Deck targets have no subject.');
296
+ return { scope, prefix };
297
+ }
298
+ if (scope === 'private') {
299
+ if (caller.server)
300
+ fail('FORBIDDEN', 'Session servers cannot access private storage.');
301
+ if (!caller.userId || (value.subject !== undefined && value.subject !== caller.userId)) {
302
+ fail('FORBIDDEN', 'Private storage belongs to the signed-in player.');
303
+ }
304
+ return { scope, subject: caller.userId, prefix };
305
+ }
306
+ if (scope !== 'user')
307
+ fail('INVALID_ARGUMENT', 'Invalid storage scope.');
308
+ const subject = value.subject ?? (caller.server ? undefined : caller.userId);
309
+ return { scope, subject: text(subject, 'subject', MAX_SUBJECT_BYTES), prefix };
310
+ }
311
+ function assertWrite(target, caller) {
312
+ if (caller.server)
313
+ return;
314
+ const allowed = target.scope === 'deck' ? caller.deckWritable : target.subject === caller.userId;
315
+ if (!allowed)
316
+ fail('FORBIDDEN', 'This caller cannot write that target.', { target: publicTarget(target) });
317
+ }
318
+ function assertOnce(targets, field) {
319
+ if (new Set(targets.map(targetId)).size !== targets.length) {
320
+ fail('INVALID_ARGUMENT', `Each ${field} target appears once.`);
321
+ }
322
+ }
323
+ // Registered prefixes in one bucket may not overlap, so every key has one target.
324
+ function assertNoOverlap(state, touched) {
325
+ const registered = [...state.targets.keys()].map((id) => JSON.parse(id));
326
+ for (const target of touched) {
327
+ const others = [
328
+ ...registered.map(([scope, subject, prefix]) => ({
329
+ scope,
330
+ subject: subject ?? undefined,
331
+ prefix,
332
+ })),
333
+ ...touched,
334
+ ];
335
+ for (const other of others) {
336
+ if (bucketId(other) === bucketId(target) &&
337
+ other.prefix !== target.prefix &&
338
+ (other.prefix.startsWith(target.prefix) || target.prefix.startsWith(other.prefix))) {
339
+ fail('PREFIX_OVERLAP', 'Target prefixes in one bucket cannot overlap.', {
340
+ target: publicTarget(target),
341
+ });
342
+ }
343
+ }
344
+ }
345
+ }
346
+ // A claimed target takes changes only from its current writer, with the binding
347
+ // that claimed it. A check may name a writer for a target it does not change.
348
+ function checkAuthority(state, access, entry, isWrite, caller) {
349
+ const target = state.targets.get(targetId(entry.target));
350
+ const revision = target ? revisionOf(access, target) : null;
351
+ if (entry.expectedRevision !== undefined && entry.expectedRevision !== revision) {
352
+ fail('REVISION_CONFLICT', 'The target changed since that revision.', {
353
+ target: publicTarget(entry.target),
354
+ });
355
+ }
356
+ if (entry.writer !== undefined || (isWrite && target?.writer)) {
357
+ if (!target?.writer ||
358
+ entry.writer !== target.writer ||
359
+ target.writerBinding !== caller.binding) {
360
+ fail('WRITER_LOST', 'The target was claimed by another writer.', {
361
+ target: publicTarget(entry.target),
362
+ });
363
+ }
364
+ }
365
+ }
366
+ function revisionOf(access, target) {
367
+ return `${access}:${target.version}`;
368
+ }
369
+ function applyChange(state, entry) {
370
+ const id = targetId(entry.target);
371
+ const bucket = state.rows.get(bucketId(entry.target)) ?? new Map();
372
+ state.rows.set(bucketId(entry.target), bucket);
373
+ if (entry.replace !== undefined) {
374
+ for (const [key] of rowsIn(state, entry.target))
375
+ bucket.delete(key);
376
+ }
377
+ for (const [key, value] of Object.entries(entry.replace ?? entry.put ?? {}))
378
+ bucket.set(key, value);
379
+ for (const key of entry.remove ?? [])
380
+ bucket.delete(key);
381
+ state.version++;
382
+ const target = state.targets.get(id);
383
+ state.targets.set(id, { ...target, version: state.version });
384
+ }
385
+ function rowsIn(state, target) {
386
+ const bucket = state.rows.get(bucketId(target));
387
+ if (!bucket)
388
+ return [];
389
+ return [...bucket]
390
+ .filter(([key]) => key.startsWith(target.prefix))
391
+ .sort(([a], [b]) => Buffer.compare(Buffer.from(a), Buffer.from(b)));
392
+ }
393
+ function copyState(state) {
394
+ return {
395
+ rows: new Map([...state.rows].map(([id, bucket]) => [id, new Map(bucket)])),
396
+ targets: new Map([...state.targets].map(([id, target]) => [id, { ...target }])),
397
+ version: state.version,
398
+ };
399
+ }
400
+ function targetId(target) {
401
+ return JSON.stringify([target.scope, target.subject ?? null, target.prefix]);
402
+ }
403
+ function bucketId(target) {
404
+ return JSON.stringify([target.scope, target.subject ?? null]);
405
+ }
406
+ function publicTarget(target) {
407
+ return {
408
+ scope: target.scope,
409
+ ...(target.scope === 'user' ? { subject: target.subject } : {}),
410
+ prefix: target.prefix,
411
+ };
412
+ }
413
+ function rows(value, target) {
414
+ if (!value || typeof value !== 'object' || Array.isArray(value)) {
415
+ fail('INVALID_ARGUMENT', 'Rows must be an object of keys to JSON values.');
416
+ }
417
+ const encoded = {};
418
+ for (const [key, child] of Object.entries(value)) {
419
+ keyIn(key, target);
420
+ const json = canonicalJson(child);
421
+ if (Buffer.byteLength(json, 'utf8') > MAX_VALUE_BYTES) {
422
+ fail('INVALID_VALUE', `The value of ${key} is over 256 KiB.`);
423
+ }
424
+ encoded[key] = json;
425
+ }
426
+ return encoded;
427
+ }
428
+ function keyIn(key, target) {
429
+ if (!text(key, 'key', MAX_KEY_BYTES).startsWith(target.prefix)) {
430
+ fail('INVALID_ARGUMENT', 'The key is outside its target.', { target: publicTarget(target) });
431
+ }
432
+ return key;
433
+ }
434
+ function text(value, field, maxBytes) {
435
+ if (typeof value !== 'string' ||
436
+ value.length === 0 ||
437
+ value.includes('\0') ||
438
+ /[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/.test(value) ||
439
+ (maxBytes !== undefined && Buffer.byteLength(value, 'utf8') > maxBytes)) {
440
+ fail('INVALID_ARGUMENT', `Invalid ${field}.`);
441
+ }
442
+ return value;
443
+ }
444
+ function list(value, field) {
445
+ if (!Array.isArray(value))
446
+ fail('INVALID_ARGUMENT', `${field} must be an array.`);
447
+ return value;
448
+ }
449
+ // Sorted keys, so the same request always encodes the same way.
450
+ function canonicalJson(value) {
451
+ if (Array.isArray(value))
452
+ return `[${value.map(canonicalJson).join(',')}]`;
453
+ if (value && typeof value === 'object') {
454
+ const entries = Object.entries(value)
455
+ .filter(([, child]) => child !== undefined)
456
+ .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0));
457
+ const fields = entries.map(([key, child]) => `${JSON.stringify(key)}:${canonicalJson(child)}`);
458
+ // Concatenated: a template starting with a brace reads as a GraphQL document to
459
+ // scripts/tests/sandbox-graphql-fields.mjs.
460
+ return '{' + fields.join(',') + '}';
461
+ }
462
+ if (typeof value === 'number' && !Number.isFinite(value)) {
463
+ fail('INVALID_VALUE', 'Storage numbers must be finite.');
464
+ }
465
+ if (value === undefined || typeof value === 'function' || typeof value === 'bigint') {
466
+ fail('INVALID_VALUE', 'Storage values must be JSON.');
467
+ }
468
+ return JSON.stringify(value);
469
+ }
@@ -40,17 +40,27 @@ socket.on('close', () => {
40
40
  });
41
41
  const pendingStorage = new Map();
42
42
  let nextStorageRequestId = 1;
43
+ // The serve closes the platform socket on a frame bigger than this
44
+ // (devSessionServer.ts, platformWss), so a request that does not fit fails here.
45
+ const PLATFORM_FRAME_MAX_BYTES = 129 * 1024;
43
46
  function requestStorage(op, argsJson) {
44
47
  const reqId = String(nextStorageRequestId++);
48
+ const args = JSON.parse(argsJson);
49
+ const frame = { protocolVersion: PROTOCOL_VERSION, t: 'storageRequest', reqId, op, args };
50
+ const encodedBytes = Buffer.byteLength(JSON.stringify(frame), 'utf8');
51
+ if (encodedBytes > PLATFORM_FRAME_MAX_BYTES) {
52
+ const input = args.input;
53
+ return Promise.reject(storageFailure('CAULDRON_STORAGE_TOO_LARGE', `The storage request is ${encodedBytes} bytes, over the ${PLATFORM_FRAME_MAX_BYTES} the local platform accepts.`, {
54
+ operationId: input?.operationId ?? args.operationId,
55
+ retryable: false,
56
+ committed: false,
57
+ encodedBytes,
58
+ limitBytes: PLATFORM_FRAME_MAX_BYTES,
59
+ }));
60
+ }
45
61
  return new Promise((resolve, reject) => {
46
62
  pendingStorage.set(reqId, { resolve, reject });
47
- send({
48
- protocolVersion: PROTOCOL_VERSION,
49
- t: 'storageRequest',
50
- reqId,
51
- op,
52
- args: JSON.parse(argsJson),
53
- });
63
+ send(frame);
54
64
  });
55
65
  }
56
66
  function settleStorageMessage(text) {
@@ -73,7 +83,7 @@ function settleStorageMessage(text) {
73
83
  }
74
84
  else {
75
85
  const error = asRecord(frame.error);
76
- pending.reject(storageFailure(asText(error.code, 'CAULDRON_STORAGE_UNAVAILABLE'), asText(error.message, 'storage request failed')));
86
+ pending.reject(storageFailure(asText(error.code, 'CAULDRON_STORAGE_UNAVAILABLE'), asText(error.message, 'storage request failed'), error));
77
87
  }
78
88
  return true;
79
89
  }
@@ -83,10 +93,10 @@ function failPendingStorage(message) {
83
93
  }
84
94
  pendingStorage.clear();
85
95
  }
86
- function storageFailure(code, message) {
87
- const error = new Error(message);
88
- error.code = code;
89
- return error;
96
+ // The details (whether a save committed, its receipt) ride along as `extensions`,
97
+ // as a host's GraphQL error carries them.
98
+ function storageFailure(code, message, details = {}) {
99
+ return Object.assign(new Error(message), { code, extensions: details });
90
100
  }
91
101
  async function handleMessage(data, isBinary) {
92
102
  if (isBinary)