@hypersoniclabs/helix-sdk 0.1.2 → 0.1.9

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 (115) hide show
  1. package/README.md +859 -8
  2. package/dist/action-surface.d.ts +182 -0
  3. package/dist/action-surface.js +1032 -0
  4. package/dist/action-surface.js.map +1 -0
  5. package/dist/camera.d.ts +65 -1
  6. package/dist/camera.js +568 -0
  7. package/dist/camera.js.map +1 -1
  8. package/dist/dev-shell/criteria.d.ts +46 -0
  9. package/dist/dev-shell/criteria.js +98 -0
  10. package/dist/dev-shell/criteria.js.map +1 -0
  11. package/dist/dev-shell/index.d.ts +189 -0
  12. package/dist/dev-shell/index.js +287 -0
  13. package/dist/dev-shell/index.js.map +1 -0
  14. package/dist/dev-shell/keys.d.ts +14 -0
  15. package/dist/dev-shell/keys.js +78 -0
  16. package/dist/dev-shell/keys.js.map +1 -0
  17. package/dist/dev-shell/simulator.d.ts +436 -0
  18. package/dist/dev-shell/simulator.js +1634 -0
  19. package/dist/dev-shell/simulator.js.map +1 -0
  20. package/dist/dev-shell/state.d.ts +148 -0
  21. package/dist/dev-shell/state.js +196 -0
  22. package/dist/dev-shell/state.js.map +1 -0
  23. package/dist/device-definition-resolver.d.ts +34 -0
  24. package/dist/device-definition-resolver.js +172 -0
  25. package/dist/device-definition-resolver.js.map +1 -0
  26. package/dist/device-trial.d.ts +3 -0
  27. package/dist/device-trial.js +132 -0
  28. package/dist/device-trial.js.map +1 -0
  29. package/dist/devices.d.ts +228 -0
  30. package/dist/devices.js +198 -0
  31. package/dist/devices.js.map +1 -0
  32. package/dist/dreamerAudio.d.ts +126 -0
  33. package/dist/dreamerAudio.js +135 -0
  34. package/dist/dreamerAudio.js.map +1 -0
  35. package/dist/generated/runtime-contract.d.ts +15529 -0
  36. package/dist/generated/runtime-contract.js +20470 -0
  37. package/dist/generated/runtime-contract.js.map +1 -0
  38. package/dist/index.d.ts +272 -15
  39. package/dist/index.js +1401 -91
  40. package/dist/index.js.map +1 -1
  41. package/dist/interaction-mode.d.ts +172 -0
  42. package/dist/interaction-mode.js +553 -0
  43. package/dist/interaction-mode.js.map +1 -0
  44. package/dist/internal/avatar-pose.d.ts +25 -0
  45. package/dist/internal/avatar-pose.js +46 -0
  46. package/dist/internal/avatar-pose.js.map +1 -0
  47. package/dist/internal/keyed-collection.d.ts +2 -0
  48. package/dist/internal/keyed-collection.js +12 -0
  49. package/dist/internal/keyed-collection.js.map +1 -0
  50. package/dist/internal/vehicle-detach-action.d.ts +2 -0
  51. package/dist/internal/vehicle-detach-action.js +6 -0
  52. package/dist/internal/vehicle-detach-action.js.map +1 -0
  53. package/dist/matchmaking.d.ts +433 -0
  54. package/dist/matchmaking.js +1487 -0
  55. package/dist/matchmaking.js.map +1 -0
  56. package/dist/materials.d.ts +122 -0
  57. package/dist/materials.js +217 -0
  58. package/dist/materials.js.map +1 -0
  59. package/dist/multiplayer-accessors.d.ts +100 -0
  60. package/dist/multiplayer-accessors.js +200 -0
  61. package/dist/multiplayer-accessors.js.map +1 -0
  62. package/dist/multiplayer-contract/avatar-pose.d.ts +112 -0
  63. package/dist/multiplayer-contract/avatar-pose.js +250 -0
  64. package/dist/multiplayer-contract/avatar-pose.js.map +1 -0
  65. package/dist/multiplayer-contract/credential.d.ts +38 -0
  66. package/dist/multiplayer-contract/final-rest.d.ts +66 -0
  67. package/dist/multiplayer-contract/final-rest.js +38 -0
  68. package/dist/multiplayer-contract/final-rest.js.map +1 -0
  69. package/dist/multiplayer-contract/index.d.ts +11 -5
  70. package/dist/multiplayer-contract/index.js +16 -5
  71. package/dist/multiplayer-contract/index.js.map +1 -1
  72. package/dist/multiplayer-contract/messages.d.ts +461 -14
  73. package/dist/multiplayer-contract/messages.js +141 -15
  74. package/dist/multiplayer-contract/messages.js.map +1 -1
  75. package/dist/multiplayer-contract/room.d.ts +55 -4
  76. package/dist/multiplayer-contract/state.d.ts +181 -1
  77. package/dist/multiplayer-contract/state.js.map +1 -1
  78. package/dist/multiplayer-final-rest.d.ts +32 -0
  79. package/dist/multiplayer-final-rest.js +217 -0
  80. package/dist/multiplayer-final-rest.js.map +1 -0
  81. package/dist/multiplayer.d.ts +507 -16
  82. package/dist/multiplayer.js +2242 -73
  83. package/dist/multiplayer.js.map +1 -1
  84. package/dist/package.json +3 -0
  85. package/dist/protocol.d.ts +668 -5
  86. package/dist/protocol.js +101 -1
  87. package/dist/protocol.js.map +1 -1
  88. package/dist/runtime-contract/index.d.ts +15 -0
  89. package/dist/runtime-contract/index.js +12 -0
  90. package/dist/runtime-contract/index.js.map +1 -0
  91. package/dist/server-clock.d.ts +25 -0
  92. package/dist/server-clock.js +88 -0
  93. package/dist/server-clock.js.map +1 -0
  94. package/dist/tsconfig.build.tsbuildinfo +1 -1
  95. package/dist/universal-vehicles.d.ts +111 -0
  96. package/dist/universal-vehicles.js +2 -0
  97. package/dist/universal-vehicles.js.map +1 -0
  98. package/dist/vault.d.ts +562 -0
  99. package/dist/vault.js +365 -0
  100. package/dist/vault.js.map +1 -0
  101. package/dist/vehicle-specialty-placement.d.ts +28 -0
  102. package/dist/vehicle-specialty-placement.js +154 -0
  103. package/dist/vehicle-specialty-placement.js.map +1 -0
  104. package/dist/vehicle-specialty-transport.d.ts +78 -0
  105. package/dist/vehicle-specialty-transport.js +183 -0
  106. package/dist/vehicle-specialty-transport.js.map +1 -0
  107. package/dist/voice.d.ts +229 -0
  108. package/dist/voice.js +1348 -0
  109. package/dist/voice.js.map +1 -0
  110. package/generated/runtime-contract/helix-runtime-contract.json +13332 -0
  111. package/generated/runtime-contract/known-answer.json +20471 -0
  112. package/generated/runtime-contract/known-answer.schema.json +630 -0
  113. package/generated/runtime-contract/runtime-contract.schema.json +607 -0
  114. package/generated/runtime-contract/unreal/HelixRuntimeContract.generated.h +908 -0
  115. package/package.json +32 -6
@@ -0,0 +1,1634 @@
1
+ // The simulated half of `helix dev`: it answers the SDK's 34-method request table from in-memory state,
2
+ // with production's real shell-lane caps and error shapes. Transport-free and synchronous — index.ts
3
+ // wires it to postMessage; a CLI debug menu can drive the same methods directly.
4
+ //
5
+ // Honesty doctrine (build plan §3.6): every answer is logged with a SIMULATED prefix, purchase results
6
+ // carry NO receipt, and the caps below are the REAL ones — a simulator more permissive than production
7
+ // manufactures false positives. Room-lane fences (CONSUME_MAX_PER_MIN / STORAGE_MAX_WRITES_PER_MIN in
8
+ // helix-colyseus-server/src/tuning.ts) are deliberately absent: a shell simulator can never reach them.
9
+ import { PURCHASE_STATUS_MEANING } from '../protocol.js';
10
+ import { DEV_SHELL_CRITERIA_FIELD_PATTERN, devShellCriteriaSatisfied, formatDevShellCriteria, measureDevShellCriteria, } from './criteria.js';
11
+ import { checkDevShellRead, checkDevShellWrite, isPlatformKey } from './keys.js';
12
+ import { addInventoryItem, applyDevShellGrants, cloneDevShellState, DEV_SHELL_SIMULATED_EMOTES, devShellEntitlementsSnapshot, devShellProductRef, findDevShellListing, findDevShellProduct, refreshDevShellPasses, } from './state.js';
13
+ /** Stamped on every simulated answer. Never call this mode "test" — Roblox's test mode costs real money. */
14
+ export const DEV_SHELL_LOG_PREFIX = '[helix dev · SIMULATED]';
15
+ /**
16
+ * The SHELL lane's real limits, with their production sources. Enforcing them is what keeps a local pass
17
+ * meaningful — and matching the loud shapes exercises a world's error paths for free.
18
+ */
19
+ export const DEV_SHELL_CAPS = {
20
+ /** data-store.constants.ts DATA_STORE_USER_WRITE_LIMIT_PER_WINDOW. */
21
+ playerWritesPerMinute: 30,
22
+ /** The free KvStoragePlan's writeOpsPerMinute (DATA_STORE_WRITE_LIMIT_PER_WINDOW is its fallback). */
23
+ worldWritesPerMinute: 600,
24
+ /** entitlements.service.ts CONSUME_RATE_MAX. */
25
+ consumesPerMinute: 120,
26
+ windowMs: 60_000,
27
+ /** DATA_STORE_MAX_VALUE_BYTES. */
28
+ maxValueBytes: 256 * 1024,
29
+ /** DATA_STORE_MAX_KEYS / DATA_STORE_MAX_TOTAL_BYTES. */
30
+ maxKeys: 50_000,
31
+ maxTotalBytes: 100 * 1024 * 1024,
32
+ /** DATA_STORE_LIST_MAX_LIMIT. */
33
+ listPageMax: 100,
34
+ /** LeaderboardController.DEFAULT_LIMIT, and the SDK's own MAX_LEADERBOARD_LIMIT. */
35
+ leaderboardPageDefault: 25,
36
+ leaderboardPageMax: 100,
37
+ /** DATA_STORE_SESSION_BOARD_CAP — boards a session may lazily create. */
38
+ sessionBoardCap: 8,
39
+ /** LEADERBOARD_DEFAULT_SIZE — entries a board keeps. */
40
+ boardSize: 100,
41
+ };
42
+ /**
43
+ * How long a real-flow poke (a data-store write, a purchase settle) waits before criteria re-evaluate —
44
+ * the backend's ACHIEVEMENT_CRITERIA_DEBOUNCE_MS default. Debug-menu evidence evaluates immediately
45
+ * (the local analog of the admin sweep). Local unlocks are therefore never SLOWER than production's.
46
+ */
47
+ export const DEV_SHELL_ACHIEVEMENT_DEBOUNCE_MS = 3_000;
48
+ export const DEV_SHELL_PURCHASE_FAILURE_MODES = [
49
+ 'InsufficientFunds',
50
+ 'PriceChanged',
51
+ 'Pending',
52
+ ];
53
+ /** The manifest validator's room-type name grammar (`default` is reserved, at most 8 types). */
54
+ export const DEV_SHELL_ROOM_TYPE_NAME_PATTERN = /^[a-z][a-z0-9-]{0,31}$/;
55
+ export const DEV_SHELL_ROOM_TYPES_MAX = 8;
56
+ /**
57
+ * How long a simulated ticket stays redeemable. The contract pins the ticket CREDENTIAL at 60 s; the ticket
58
+ * row's own lifetime is the backend's choice, so this is a stand-in, overridable per ticket (`ttlMs`).
59
+ */
60
+ export const DEV_SHELL_ROOM_TICKET_TTL_MS = 60_000;
61
+ /**
62
+ * The backend's refusal `code`s for the room-types routes, with the status each is served under. A client
63
+ * branches on the CODE: two of the 410s and two of the 404s mean different things, and an unrelated 404
64
+ * (world not found) shares a status with all of them.
65
+ */
66
+ export const DEV_SHELL_ROOM_REFUSALS = {
67
+ 'unknown-room-type': 404,
68
+ 'ticket-required': 403,
69
+ 'unknown-room-ticket': 404,
70
+ 'room-ticket-expired': 410,
71
+ 'room-ticket-used': 410,
72
+ 'room-instance-closed': 410,
73
+ 'unknown-room-instance': 404,
74
+ };
75
+ export const DEV_SHELL_QUEUE_ID_PATTERN = /^[a-z][a-z0-9-]{0,31}$/;
76
+ export const DEV_SHELL_QUEUES_MAX = 16;
77
+ /** The platform's party size cap. */
78
+ export const DEV_SHELL_PARTY_MAX_SIZE = 12;
79
+ /** Pending invites one party may have out at a time. */
80
+ export const DEV_SHELL_PARTY_PENDING_INVITES_MAX = 10;
81
+ /** How long a party invite stays answerable. */
82
+ export const DEV_SHELL_PARTY_INVITE_TTL_MS = 5 * 60_000;
83
+ /** How long a simulated join code lasts. */
84
+ export const DEV_SHELL_PARTY_CODE_TTL_MS = 10 * 60_000;
85
+ const REFUSE = 'refuse';
86
+ const isRecord = (v) => typeof v === 'object' && v !== null && !Array.isArray(v);
87
+ const payloadOf = (payload) => (isRecord(payload) ? payload : {});
88
+ const str = (v) => (typeof v === 'string' ? v : '');
89
+ const num = (v) => (typeof v === 'number' && Number.isFinite(v) ? v : NaN);
90
+ // Exact UTF-8 length without TextEncoder (absent from jest-environment-jsdom), matching the backend's
91
+ // Buffer.byteLength check on the serialized value.
92
+ const utf8Bytes = (value) => {
93
+ let bytes = 0;
94
+ for (let i = 0; i < value.length; i += 1) {
95
+ const code = value.charCodeAt(i);
96
+ if (code < 0x80)
97
+ bytes += 1;
98
+ else if (code < 0x800)
99
+ bytes += 2;
100
+ else if (code >= 0xd800 && code <= 0xdbff) {
101
+ bytes += 4;
102
+ i += 1;
103
+ }
104
+ else
105
+ bytes += 3;
106
+ }
107
+ return bytes;
108
+ };
109
+ const completedOf = (status) => PURCHASE_STATUS_MEANING[status].ownsAfter;
110
+ /**
111
+ * The 34-method split, exhaustive by construction: a method that is neither simulated nor deliberately
112
+ * refused is a silent hole, and a widened HelixRequestMethod breaks this Record at compile time.
113
+ *
114
+ * The thirteen refusals need a real platform surface, pipeline, or rig. Two caveats for the docs:
115
+ * `avatar.getEquipped` is a DEAD union member (the SDK fetches the API directly and never routes it
116
+ * here), and refusing avatar.getLoadout/updateLoadout surfaces world-side as the SDK's live-fetch
117
+ * fallback failing — not as this error string.
118
+ *
119
+ * `emotes.getEquipped` is SIMULATED rather than refused, unlike its `emotes.openCustomizer` neighbour,
120
+ * and the difference is what each one needs. The customizer needs a real shell UI and a real account
121
+ * to edit; a loadout READ needs neither — it is data, and a stub is a truthful answer as long as it
122
+ * cannot be mistaken for the creator's own (see DEV_SHELL_SIMULATED_EMOTES). Refusing it instead put
123
+ * `helix dev` in the one state the runtime reports as "Couldn't load your emotes", so the platform's
124
+ * own local command could not show a creator the wheel at all.
125
+ */
126
+ const DEV_SHELL_METHODS = {
127
+ 'wallet.getBalance': (sim) => sim.getBalance(),
128
+ // Listen host admission is a native player-host action (profile `listen`); the browser dev-shell
129
+ // has no host session or capability to admit against, so it refuses rather than simulating.
130
+ 'listen.consume': REFUSE,
131
+ 'listen.release': REFUSE,
132
+ 'listen.heartbeat': REFUSE,
133
+ 'listen.close': REFUSE,
134
+ 'marketplace.purchase': (sim, payload) => sim.purchase(str(payloadOf(payload).ref), str(payloadOf(payload).idempotencyKey)),
135
+ 'marketplace.getListings': (sim, payload) => sim.getListings(payloadOf(payload)),
136
+ 'iwp.getContext': (sim, payload) => sim.getPurchaseContext(str(payloadOf(payload).ref)),
137
+ 'iwp.getPurchase': (sim, payload) => sim.getPurchase(str(payloadOf(payload).idempotencyKey || payloadOf(payload).key), typeof payloadOf(payload).ref === 'string' ? str(payloadOf(payload).ref) : undefined),
138
+ 'iwp.getEntitlements': (sim) => sim.getEntitlements(),
139
+ 'iwp.consumeEntitlement': (sim, payload) => sim.consumeEntitlement(str(payloadOf(payload).code), num(payloadOf(payload).amount), str(payloadOf(payload).opId)),
140
+ 'inventory.hasItem': (sim, payload) => sim.hasItem(str(payloadOf(payload).itemId)),
141
+ 'inventory.getQuantity': (sim, payload) => sim.getQuantity(str(payloadOf(payload).itemId)),
142
+ 'inventory.getMyItems': (sim) => sim.getMyItems(),
143
+ 'inventory.equipItem': (sim, payload) => sim.equipItem(str(payloadOf(payload).itemId)),
144
+ 'dataStore.get': (sim, payload) => sim.dataStoreGet(str(payloadOf(payload).key)),
145
+ 'dataStore.getEntry': (sim, payload) => sim.dataStoreGetEntry(str(payloadOf(payload).key)),
146
+ 'dataStore.set': (sim, payload) => sim.dataStoreSet(str(payloadOf(payload).key), payloadOf(payload).value, typeof payloadOf(payload).expectedVersion === 'number' ? num(payloadOf(payload).expectedVersion) : undefined),
147
+ 'dataStore.delete': (sim, payload) => sim.dataStoreDelete(str(payloadOf(payload).key), typeof payloadOf(payload).expectedVersion === 'number' ? num(payloadOf(payload).expectedVersion) : undefined),
148
+ 'dataStore.list': (sim, payload) => sim.dataStoreList(payloadOf(payload)),
149
+ 'leaderboard.submit': (sim, payload) => sim.leaderboardSubmit(str(payloadOf(payload).board), num(payloadOf(payload).score), payloadOf(payload).order === 'asc' ? 'asc' : payloadOf(payload).order === 'desc' ? 'desc' : undefined),
150
+ 'leaderboard.top': (sim, payload) => sim.leaderboardTop(str(payloadOf(payload).board), typeof payloadOf(payload).limit === 'number' ? num(payloadOf(payload).limit) : undefined, payloadOf(payload).order === 'asc' ? 'asc' : payloadOf(payload).order === 'desc' ? 'desc' : undefined),
151
+ 'achievements.list': (sim) => sim.achievementsList(),
152
+ 'achievements.mine': (sim) => sim.achievementsMine(),
153
+ 'avatar.getEquipped': REFUSE,
154
+ 'avatar.getLoadout': REFUSE,
155
+ 'avatar.updateLoadout': REFUSE,
156
+ 'avatar.openCreator': REFUSE,
157
+ 'emotes.openCustomizer': REFUSE,
158
+ // No payload by design: the real shell resolves the player from its own session, so there is
159
+ // nothing for the caller to name — and the simulator has exactly one simulated player anyway.
160
+ 'emotes.getEquipped': (sim) => sim.emotesGetEquipped(),
161
+ 'camera.savePhoto': REFUSE,
162
+ // Refused for the same reason, one layer up: there is no camera RIG here. Answering with a state
163
+ // no rig applied is the fake success the camera contract exists to forbid, so `helix dev` says no
164
+ // and a page that wants to exercise the world's camera drives it with handle.sendCameraState().
165
+ 'camera.control': REFUSE,
166
+ // The quick-slot ring. All six refused, and the split between them is the same one `emotes.*`
167
+ // draws: `get` is DATA and could in principle be stubbed, but a ring is a set of the CREATOR'S
168
+ // OWN owned instances — there are none here, and a stub ring would name instance ids that exist
169
+ // nowhere, which `activate` would then be asked to move. The two doors need a real shell UI, and
170
+ // `patch`/`activate`/`deactivate` need the platform's one-place state machine to write to. A
171
+ // refusal is the truthful answer; the runtime reads it as "this shell has no quick slots" and
172
+ // draws no ring, rather than one that cannot be used.
173
+ 'quickSlots.get': REFUSE,
174
+ 'quickSlots.patch': REFUSE,
175
+ 'quickSlots.activate': REFUSE,
176
+ 'quickSlots.deactivate': REFUSE,
177
+ 'quickSlots.openCustomizer': REFUSE,
178
+ 'quickSlots.browseAll': REFUSE,
179
+ };
180
+ const methodNames = (simulated) => Object.keys(DEV_SHELL_METHODS).filter((method) => (DEV_SHELL_METHODS[method] === REFUSE) !== simulated);
181
+ /** The 21 methods `helix dev` answers from simulated state. */
182
+ export const DEV_SHELL_SIMULATED_METHODS = methodNames(true);
183
+ /** The 13 methods `helix dev` refuses — they need a real platform surface, asset pipeline, camera rig,
184
+ * or (the quick-slot six) the platform's one-place state machine and the creator's own owned instances. */
185
+ export const DEV_SHELL_REFUSED_METHODS = methodNames(false);
186
+ export class DevShellSimulator {
187
+ options;
188
+ state;
189
+ products;
190
+ listings;
191
+ // Transient bookkeeping — deliberately NOT persisted: a rate window that survived a reload would
192
+ // refuse writes for a minute of wall-clock the player never spent in the world.
193
+ playerWrites = [];
194
+ worldWrites = [];
195
+ consumes = [];
196
+ consumeOps = new Map();
197
+ purchaseFailure = null;
198
+ forceSaveFailure = false;
199
+ achievementPokeTimer = null;
200
+ // Room types: transient like the rate windows above — a ticket is a 60-second object and an instance lives
201
+ // as long as its room, so persisting either into the player's state file would only manufacture stale rows.
202
+ roomTypes = new Map();
203
+ roomInstances = new Map();
204
+ roomTickets = new Map();
205
+ roomSerial = 0;
206
+ // Matchmaking and parties: transient for the same reason — a queue ticket lives only while it is polled.
207
+ queues = new Map();
208
+ queueTicket = null;
209
+ party = null;
210
+ partyInvites = [];
211
+ outgoingInvites = new Map();
212
+ // The simulated player's own party's join code, and codes of other players' parties (the debug hand).
213
+ partyCode = null;
214
+ // How the last ticket ended, served on `none` for 60 s; and a party member said to hold a standing match.
215
+ queueEnded = null;
216
+ memberWithMatch = null;
217
+ foreignCodes = new Map();
218
+ socialSerial = 0;
219
+ constructor(options) {
220
+ this.options = options;
221
+ this.setRoomTypes(options.roomTypes);
222
+ this.setQueues(options.queues);
223
+ this.state = options.state;
224
+ this.products = options.products?.products ?? [];
225
+ this.listings = options.products?.listings ?? [];
226
+ // Registration runs a one-pass backfill crediting everyone who already qualifies; evaluating at
227
+ // construction is the local equivalent, so pre-existing evidence unlocks at boot, not on the next write.
228
+ this.evaluateAchievements();
229
+ }
230
+ // ─────────────────────────── plumbing ───────────────────────────
231
+ /** Route one helix:request. Never throws — a thrown handler would strand the world's promise. */
232
+ handle(method, payload) {
233
+ const handler = DEV_SHELL_METHODS[method];
234
+ if (!handler) {
235
+ // A method outside HelixRequestMethod — a newer world, or the shell-only surface helixgame.com
236
+ // adds (home.*, ui.*). The real shell answers the same way.
237
+ const error = `Helix: unknown method "${method}"`;
238
+ this.log(`${method} → unknown`, error);
239
+ return { ok: false, error };
240
+ }
241
+ if (handler === REFUSE) {
242
+ const error = `${method} is not simulated in \`helix dev\` — it needs the real asset pipeline. Run the world in a HELIX shell to exercise it.`;
243
+ this.log(`${method} → refused`, error);
244
+ return { ok: false, error, errorCode: 'not-simulated' };
245
+ }
246
+ let answer;
247
+ try {
248
+ answer = handler(this, payload);
249
+ }
250
+ catch (e) {
251
+ answer = { ok: false, error: e instanceof Error ? e.message : 'simulated request failed' };
252
+ }
253
+ if (answer.ok)
254
+ this.log(`${method} → ok`, answer.result);
255
+ else
256
+ this.log(`${method} → error: ${answer.error}`, answer.errorCode);
257
+ return answer;
258
+ }
259
+ snapshot() {
260
+ refreshDevShellPasses(this.state);
261
+ return cloneDevShellState(this.state);
262
+ }
263
+ replaceState(state) {
264
+ this.state = state;
265
+ this.consumeOps.clear();
266
+ this.evaluateAchievements();
267
+ }
268
+ setProducts(seed) {
269
+ this.products = seed?.products ?? [];
270
+ this.listings = seed?.listings ?? [];
271
+ // The product set feeds the iwp measurement (which settled rows resolve to a world product).
272
+ this.evaluateAchievements();
273
+ }
274
+ /** Cancel a pending debounced evaluation — the dispose() seam. A cancelled poke heals on the next one. */
275
+ cancelPendingAchievementPoke() {
276
+ if (this.achievementPokeTimer !== null)
277
+ clearTimeout(this.achievementPokeTimer);
278
+ this.achievementPokeTimer = null;
279
+ }
280
+ log(message, detail) {
281
+ this.options.log(`${DEV_SHELL_LOG_PREFIX} ${message}`, detail);
282
+ }
283
+ touched() {
284
+ this.options.onStateChange?.(cloneDevShellState(this.state));
285
+ }
286
+ emit(event, data) {
287
+ this.options.emit(event, data);
288
+ }
289
+ // Charge one token against a sliding window. The per-player window is charged FIRST and a denied
290
+ // token is not consumed, so an over-cap player never spends from the shared world budget.
291
+ charge(window, max) {
292
+ const cutoff = Date.now() - DEV_SHELL_CAPS.windowMs;
293
+ while (window.length > 0 && window[0] <= cutoff)
294
+ window.shift();
295
+ if (window.length >= max)
296
+ return false;
297
+ window.push(Date.now());
298
+ return true;
299
+ }
300
+ rateLimited(message) {
301
+ return { ok: false, error: message, errorCode: 'rate-limited' };
302
+ }
303
+ // ─────────────────────────── wallet / marketplace ───────────────────────────
304
+ getBalance() {
305
+ return { ok: true, result: { ...this.state.wallet, updatedAt: new Date().toISOString() } };
306
+ }
307
+ getListings(query) {
308
+ const kind = str(query.kind);
309
+ const category = str(query.category);
310
+ const search = str(query.search).toLowerCase();
311
+ const limit = typeof query.limit === 'number' ? Math.max(1, Math.floor(num(query.limit))) : undefined;
312
+ const matches = this.listings.filter((l) => (!kind || l.kind === kind) &&
313
+ (!category || l.category === category) &&
314
+ (!search || l.title.toLowerCase().includes(search)));
315
+ return { ok: true, result: limit ? matches.slice(0, limit) : matches };
316
+ }
317
+ /**
318
+ * What the host's confirm popup should show for this attempt, or null when production would not pop
319
+ * one either: a missing ref/key (the request will refuse), an unknown ref (ProductNotFound is the
320
+ * world's own bug), or a settled row (the answer is an idempotent replay, no new confirmation).
321
+ */
322
+ purchaseConfirmContext(ref, idempotencyKey) {
323
+ if (!ref || !idempotencyKey)
324
+ return null;
325
+ const prior = this.state.purchases.find((p) => p.idempotencyKey === idempotencyKey && p.ref === ref);
326
+ if (prior && prior.status !== 'Pending')
327
+ return null;
328
+ const product = findDevShellProduct(this.products, ref);
329
+ const listing = product ? null : findDevShellListing(this.listings, ref);
330
+ if (!product && !listing)
331
+ return null;
332
+ const priceLix = product ? product.priceLix : (listing?.priceLix ?? 0);
333
+ return {
334
+ ref: devShellProductRef(ref),
335
+ idempotencyKey,
336
+ title: product ? product.title : (listing?.title ?? ref),
337
+ priceLix,
338
+ isFree: priceLix === 0,
339
+ balanceLix: this.state.wallet.lix,
340
+ balanceAfterLix: Math.max(0, this.state.wallet.lix - priceLix),
341
+ };
342
+ }
343
+ /**
344
+ * The popup's Cancel: nothing was charged, nothing is recorded — production's cancel-before-charge
345
+ * leaves no backend row, so a retried attempt (same key) confirms again instead of replaying Cancelled.
346
+ */
347
+ cancelPurchase(ref) {
348
+ this.log(`marketplace.purchase ${ref} → Cancelled (the simulated confirm was declined)`);
349
+ return {
350
+ ok: true,
351
+ result: { status: 'Cancelled', completed: false, reason: 'Purchase cancelled in the simulated confirm dialog.' },
352
+ };
353
+ }
354
+ /**
355
+ * Settle a purchase against simulated state. NEVER mints a receipt: settlePurchaseResult forwards on
356
+ * receipt PRESENCE (index.ts:1156-1162) and a junk receipt reaching a real room kicks the buyer.
357
+ */
358
+ purchase(ref, idempotencyKey) {
359
+ if (!ref)
360
+ return { ok: false, error: 'ref required' };
361
+ if (!idempotencyKey)
362
+ return { ok: false, error: 'idempotencyKey required' };
363
+ // A settled row replays verbatim, exactly as the backend answers a repeated key. A `Pending` row is
364
+ // money-unknown and never settled here, so a retry re-attempts it instead of replaying forever.
365
+ const prior = this.state.purchases.find((p) => p.idempotencyKey === idempotencyKey && p.ref === ref);
366
+ if (prior && prior.status !== 'Pending') {
367
+ this.log(`marketplace.purchase replayed ${idempotencyKey} → ${prior.status}`);
368
+ return { ok: true, result: resultOf(prior) };
369
+ }
370
+ const product = findDevShellProduct(this.products, ref);
371
+ const listing = product ? null : findDevShellListing(this.listings, ref);
372
+ if (!product && !listing) {
373
+ // A ref nothing answers is the world's own bug, so it outranks any injected failure.
374
+ return { ok: true, result: this.recordPurchase({ idempotencyKey, ref, status: 'ProductNotFound', priceLix: 0 }) };
375
+ }
376
+ const productKey = product ? product.key : null;
377
+ const priceLix = product ? product.priceLix : (listing?.priceLix ?? 0);
378
+ const ownedCount = productKey ? (this.state.entitlements.owned[productKey] ?? 0) : 0;
379
+ const maxPerUser = product?.maxPerUser ?? null;
380
+ if (this.purchaseFailure)
381
+ return this.injectedPurchaseFailure(ref, idempotencyKey, priceLix);
382
+ if (maxPerUser !== null && ownedCount >= maxPerUser) {
383
+ const status = maxPerUser === 1 ? 'AlreadyOwned' : 'MaxPerUserReached';
384
+ return { ok: true, result: this.recordPurchase({ idempotencyKey, ref, status, priceLix, ownedCount, maxPerUser }) };
385
+ }
386
+ if (priceLix > 0 && this.state.wallet.lix < priceLix) {
387
+ return {
388
+ ok: true,
389
+ result: this.recordPurchase({
390
+ idempotencyKey,
391
+ ref,
392
+ status: 'InsufficientFunds',
393
+ priceLix,
394
+ balanceLix: this.state.wallet.lix,
395
+ shortfallLix: priceLix - this.state.wallet.lix,
396
+ }),
397
+ };
398
+ }
399
+ if (priceLix > 0)
400
+ this.state.wallet.lix -= priceLix;
401
+ if (productKey)
402
+ this.state.entitlements.owned[productKey] = ownedCount + 1;
403
+ if (product) {
404
+ applyDevShellGrants(this.state, product.grants, productKey, (itemId) => this.titleOf(itemId));
405
+ }
406
+ else if (listing) {
407
+ addInventoryItem(this.state, { itemId: listing.itemId, title: listing.title, kind: listing.kind, category: listing.category });
408
+ }
409
+ const result = this.recordPurchase({
410
+ idempotencyKey,
411
+ ref,
412
+ status: priceLix > 0 ? 'Granted' : 'Claimed',
413
+ priceLix,
414
+ itemId: listing?.itemId ?? null,
415
+ balanceAfterLix: this.state.wallet.lix,
416
+ ownedCount: productKey ? this.state.entitlements.owned[productKey] : undefined,
417
+ maxPerUser,
418
+ });
419
+ // Same three pushes, in the same order, as the real shell's settled-purchase branch (bridge.ts).
420
+ this.emit('balance-changed', { ...this.state.wallet });
421
+ this.emit('inventory-changed');
422
+ this.emit('entitlements-changed');
423
+ // Only a Granted/Claimed settle pokes iwp criteria — AlreadyOwned never does (no charge, no grant).
424
+ this.pokeAchievements();
425
+ return { ok: true, result };
426
+ }
427
+ injectedPurchaseFailure(ref, idempotencyKey, priceLix) {
428
+ if (this.purchaseFailure === 'InsufficientFunds') {
429
+ return {
430
+ ok: true,
431
+ result: this.recordPurchase({
432
+ idempotencyKey,
433
+ ref,
434
+ status: 'InsufficientFunds',
435
+ priceLix,
436
+ balanceLix: this.state.wallet.lix,
437
+ shortfallLix: Math.max(1, priceLix - this.state.wallet.lix),
438
+ reason: 'Purchases Always Fail is on (simulated)',
439
+ }),
440
+ };
441
+ }
442
+ if (this.purchaseFailure === 'PriceChanged') {
443
+ // The confirm dialog's price went stale: nothing charged, nothing written, and the ECHOED price
444
+ // is what the world must re-render at.
445
+ const changedPriceLix = priceLix + Math.max(1, Math.round(priceLix * 0.2));
446
+ return {
447
+ ok: true,
448
+ result: this.recordPurchase({
449
+ idempotencyKey,
450
+ ref,
451
+ status: 'PriceChanged',
452
+ priceLix: changedPriceLix,
453
+ reason: 'Purchases Always Fail is on (simulated)',
454
+ }),
455
+ };
456
+ }
457
+ // Pending: the settle never answered. The row stays for iwp.getPurchase to recover, and the world
458
+ // sees a REJECTION — which is what keeps the SDK's automatic idempotency key alive for the retry.
459
+ this.recordPurchase({
460
+ idempotencyKey,
461
+ ref,
462
+ status: 'Pending',
463
+ priceLix,
464
+ reason: 'Purchases Always Fail is on (simulated)',
465
+ });
466
+ return {
467
+ ok: false,
468
+ error: 'Purchase settle did not answer (simulated) — the attempt is unresolved; recover it with Helix.purchases.getPurchase(key, ref).',
469
+ };
470
+ }
471
+ recordPurchase(row) {
472
+ const record = { ...row, at: new Date().toISOString() };
473
+ const index = this.state.purchases.findIndex((p) => p.idempotencyKey === record.idempotencyKey && p.ref === record.ref);
474
+ if (index >= 0)
475
+ this.state.purchases[index] = record;
476
+ else
477
+ this.state.purchases.push(record);
478
+ this.touched();
479
+ return resultOf(record);
480
+ }
481
+ getPurchase(idempotencyKey, ref) {
482
+ if (!idempotencyKey)
483
+ return { ok: false, error: 'idempotencyKey required' };
484
+ const normalizedRef = ref ? devShellProductRef(ref) : undefined;
485
+ const row = this.state.purchases.find((p) => p.idempotencyKey === idempotencyKey && (!normalizedRef || p.ref === normalizedRef));
486
+ return { ok: true, result: row ? resultOf(row) : null };
487
+ }
488
+ getPurchaseContext(ref) {
489
+ const product = findDevShellProduct(this.products, ref);
490
+ const listing = product ? null : findDevShellListing(this.listings, ref);
491
+ // An unknown ref 404s in production, and the shell maps a 404 to null.
492
+ if (!product && !listing)
493
+ return { ok: true, result: null };
494
+ const priceLix = product ? product.priceLix : (listing?.priceLix ?? 0);
495
+ const ownedCount = product ? (this.state.entitlements.owned[product.key] ?? 0) : 0;
496
+ const maxPerUser = product?.maxPerUser ?? null;
497
+ const balanceLix = this.state.wallet.lix;
498
+ const maxed = maxPerUser !== null && ownedCount >= maxPerUser;
499
+ const eligibilityStatus = maxed
500
+ ? maxPerUser === 1
501
+ ? 'AlreadyOwned'
502
+ : 'MaxPerUserReached'
503
+ : priceLix > balanceLix
504
+ ? 'InsufficientFunds'
505
+ : null;
506
+ const context = {
507
+ ref: devShellProductRef(ref),
508
+ title: product ? product.title : (listing?.title ?? ref),
509
+ description: product ? (product.description ?? null) : (listing?.description ?? null),
510
+ thumbnailUrl: product ? (product.thumbnailUrl ?? null) : (listing?.thumbnailUrl ?? null),
511
+ priceLix,
512
+ isFree: priceLix === 0,
513
+ balanceLix,
514
+ balanceAfterLix: Math.max(0, balanceLix - priceLix),
515
+ owned: ownedCount > 0,
516
+ ownedCount,
517
+ maxPerUser,
518
+ eligible: eligibilityStatus === null,
519
+ eligibilityStatus,
520
+ ...(product?.grants ? { grants: product.grants } : {}),
521
+ };
522
+ return { ok: true, result: context };
523
+ }
524
+ // ─────────────────────────── entitlements ───────────────────────────
525
+ getEntitlements() {
526
+ return { ok: true, result: devShellEntitlementsSnapshot(this.state) };
527
+ }
528
+ /** Atomic floor-at-zero spend, idempotent per opId — the same shape the backend's shaped op returns. */
529
+ consumeEntitlement(code, amount, opId) {
530
+ if (!code)
531
+ return { ok: false, error: 'code required' };
532
+ if (!Number.isInteger(amount) || amount < 1)
533
+ return { ok: false, error: 'amount must be a positive integer' };
534
+ if (!this.charge(this.consumes, DEV_SHELL_CAPS.consumesPerMinute)) {
535
+ return this.rateLimited(`Entitlement consume rate limit exceeded (${DEV_SHELL_CAPS.consumesPerMinute} ops / 60s for one player).`);
536
+ }
537
+ const replay = opId ? this.consumeOps.get(opId) : undefined;
538
+ if (replay)
539
+ return { ok: true, result: replay };
540
+ const balance = this.state.entitlements.balances[code] ?? 0;
541
+ const result = balance < amount
542
+ ? { applied: false, balance, reason: 'insufficient' }
543
+ : { applied: true, balance: balance - amount };
544
+ if (result.applied) {
545
+ this.state.entitlements.balances[code] = result.balance;
546
+ this.touched();
547
+ }
548
+ if (opId)
549
+ this.consumeOps.set(opId, result);
550
+ // No event by design: the real shell pushes nothing after a consume (bridge.ts routes it straight
551
+ // through), and the ConsumeResult already carries the post-op balance.
552
+ return { ok: true, result };
553
+ }
554
+ // ─────────────────────────── inventory ───────────────────────────
555
+ hasItem(itemId) {
556
+ return { ok: true, result: this.state.inventory.some((i) => i.itemId === itemId && i.quantity > 0) };
557
+ }
558
+ getQuantity(itemId) {
559
+ return { ok: true, result: this.state.inventory.find((i) => i.itemId === itemId)?.quantity ?? 0 };
560
+ }
561
+ getMyItems() {
562
+ return { ok: true, result: this.state.inventory.map((i) => ({ ...i })) };
563
+ }
564
+ equipItem(itemId) {
565
+ const item = this.state.inventory.find((i) => i.itemId === itemId);
566
+ if (!item)
567
+ return { ok: false, error: `Item "${itemId}" is not in this player's inventory.` };
568
+ for (const row of this.state.inventory) {
569
+ if (row.avatarSlot && row.avatarSlot === item.avatarSlot)
570
+ row.equipped = false;
571
+ }
572
+ item.equipped = true;
573
+ this.touched();
574
+ this.emit('inventory-changed');
575
+ return { ok: true };
576
+ }
577
+ // ─────────────────────────── data store ───────────────────────────
578
+ dataStoreGet(key) {
579
+ const verdict = checkDevShellRead(key);
580
+ if (!verdict.allowed)
581
+ return { ok: false, error: verdict.message, errorCode: verdict.rule };
582
+ return { ok: true, result: this.state.documents[key]?.value ?? null };
583
+ }
584
+ dataStoreGetEntry(key) {
585
+ const verdict = checkDevShellRead(key);
586
+ if (!verdict.allowed)
587
+ return { ok: false, error: verdict.message, errorCode: verdict.rule };
588
+ const doc = this.state.documents[key];
589
+ return { ok: true, result: doc ? { value: doc.value, version: doc.version } : null };
590
+ }
591
+ dataStoreSet(key, value, expectedVersion) {
592
+ const refusal = this.refuseWrite(key);
593
+ if (refusal)
594
+ return refusal;
595
+ let serialized;
596
+ try {
597
+ serialized = JSON.stringify(value);
598
+ }
599
+ catch {
600
+ serialized = undefined;
601
+ }
602
+ if (typeof serialized !== 'string')
603
+ return { ok: false, error: 'Value must be JSON-serializable' };
604
+ const bytes = utf8Bytes(serialized);
605
+ if (bytes > DEV_SHELL_CAPS.maxValueBytes) {
606
+ // A 400 in production, which carries no HTTP-mapped code — the message is the whole signal.
607
+ return { ok: false, error: `Value size (${bytes} bytes) exceeds plan limit (${DEV_SHELL_CAPS.maxValueBytes} bytes)` };
608
+ }
609
+ const existing = this.state.documents[key];
610
+ if (!existing && Object.keys(this.state.documents).length >= DEV_SHELL_CAPS.maxKeys) {
611
+ return { ok: false, error: `Key limit reached (${DEV_SHELL_CAPS.maxKeys} keys) for this world` };
612
+ }
613
+ const replaced = existing ? utf8Bytes(JSON.stringify(existing.value)) : 0;
614
+ if (this.storedBytes() - replaced + bytes > DEV_SHELL_CAPS.maxTotalBytes) {
615
+ return { ok: false, error: `Storage limit reached (${DEV_SHELL_CAPS.maxTotalBytes} bytes) for this world` };
616
+ }
617
+ const conflict = this.versionConflict(key, existing?.version ?? 0, expectedVersion);
618
+ if (conflict)
619
+ return conflict;
620
+ this.state.documents[key] = {
621
+ value: JSON.parse(serialized),
622
+ version: (existing?.version ?? 0) + 1,
623
+ updatedAt: new Date().toISOString(),
624
+ };
625
+ this.touched();
626
+ this.pokeAchievements();
627
+ return { ok: true };
628
+ }
629
+ dataStoreDelete(key, expectedVersion) {
630
+ const refusal = this.refuseWrite(key);
631
+ if (refusal)
632
+ return refusal;
633
+ const existing = this.state.documents[key];
634
+ const conflict = this.versionConflict(key, existing?.version ?? 0, expectedVersion);
635
+ if (conflict)
636
+ return conflict;
637
+ delete this.state.documents[key];
638
+ this.touched();
639
+ return { ok: true };
640
+ }
641
+ dataStoreList(payload) {
642
+ const prefix = str(payload.prefix);
643
+ const limit = Math.min(typeof payload.limit === 'number' ? Math.max(1, Math.floor(num(payload.limit))) : DEV_SHELL_CAPS.listPageMax, DEV_SHELL_CAPS.listPageMax);
644
+ const offset = Number.parseInt(str(payload.cursor), 10);
645
+ const start = Number.isInteger(offset) && offset > 0 ? offset : 0;
646
+ // Bulk listing hides the platform namespace, exactly as the world-facing controller does.
647
+ const keys = Object.keys(this.state.documents)
648
+ .filter((k) => !isPlatformKey(k) && (!prefix || k.startsWith(prefix)))
649
+ .sort();
650
+ const page = keys.slice(start, start + limit);
651
+ const result = {
652
+ keys: page,
653
+ ...(start + limit < keys.length ? { nextCursor: String(start + limit) } : {}),
654
+ };
655
+ return { ok: true, result };
656
+ }
657
+ storedBytes() {
658
+ let total = 0;
659
+ for (const doc of Object.values(this.state.documents))
660
+ total += utf8Bytes(JSON.stringify(doc.value));
661
+ return total;
662
+ }
663
+ chargePlayerWrite() {
664
+ if (this.charge(this.playerWrites, DEV_SHELL_CAPS.playerWritesPerMinute))
665
+ return null;
666
+ return this.rateLimited(`Data Store write rate limit exceeded (${DEV_SHELL_CAPS.playerWritesPerMinute} writes / 60s for one player).`);
667
+ }
668
+ chargeWorldWrite() {
669
+ if (this.charge(this.worldWrites, DEV_SHELL_CAPS.worldWritesPerMinute))
670
+ return null;
671
+ return this.rateLimited(`Data Store write rate limit exceeded (${DEV_SHELL_CAPS.worldWritesPerMinute} writes / 60s per world).`);
672
+ }
673
+ // Force Save Failure, then the key policy (a guard refusal, charged nothing), then the write budget —
674
+ // production's order, so a rejected key never spends a rate token, and an over-cap player never spends
675
+ // from the shared world budget on the way out.
676
+ refuseWrite(key) {
677
+ if (this.forceSaveFailure) {
678
+ return { ok: false, error: 'Data Store write failed (simulated: Force Save Failure is on).' };
679
+ }
680
+ const verdict = checkDevShellWrite(key, this.state.userId);
681
+ if (!verdict.allowed)
682
+ return { ok: false, error: verdict.message, errorCode: verdict.rule };
683
+ return this.chargePlayerWrite() ?? this.chargeWorldWrite();
684
+ }
685
+ versionConflict(key, current, expectedVersion) {
686
+ if (expectedVersion === undefined || expectedVersion === current)
687
+ return null;
688
+ return {
689
+ ok: false,
690
+ error: `Version conflict on "${key}": expected version ${expectedVersion}, found ${current}.`,
691
+ errorCode: 'version-conflict',
692
+ };
693
+ }
694
+ // ─────────────────────────── leaderboards ───────────────────────────
695
+ leaderboardSubmit(board, score, order) {
696
+ if (!board)
697
+ return { ok: false, error: 'board required' };
698
+ if (!Number.isFinite(score))
699
+ return { ok: false, error: 'score must be a finite number' };
700
+ // The billing splits as production's does: a session pays its own token per ATTEMPT (that is the
701
+ // spam bound), while the shared world budget is charged only for a submit that rewrites the board.
702
+ const denied = this.chargePlayerWrite();
703
+ if (denied)
704
+ return denied;
705
+ let doc = this.state.leaderboards[board];
706
+ if (!doc) {
707
+ if (Object.keys(this.state.leaderboards).length >= DEV_SHELL_CAPS.sessionBoardCap) {
708
+ return {
709
+ ok: false,
710
+ error: `This world already has ${DEV_SHELL_CAPS.sessionBoardCap} leaderboards — a session cannot create another; declared boards are created by the room or creator lane.`,
711
+ errorCode: 'leaderboard-cap',
712
+ };
713
+ }
714
+ // A board's shape is fixed at creation: a later submit can never reshape it.
715
+ doc = { order: order ?? 'desc', size: DEV_SHELL_CAPS.boardSize, entries: [] };
716
+ this.state.leaderboards[board] = doc;
717
+ }
718
+ const previous = doc.entries.find((e) => e.subject === this.state.userId);
719
+ const better = !previous || (doc.order === 'desc' ? score > previous.score : score < previous.score);
720
+ if (!better) {
721
+ return { ok: true, result: { best: previous.score, updated: false } };
722
+ }
723
+ const deniedWorld = this.chargeWorldWrite();
724
+ if (deniedWorld)
725
+ return deniedWorld;
726
+ const entry = {
727
+ subject: this.state.userId,
728
+ displayName: this.state.displayName ?? this.state.username,
729
+ score,
730
+ source: 'session',
731
+ updatedAt: new Date().toISOString(),
732
+ };
733
+ const entries = doc.entries.filter((e) => e.subject !== this.state.userId);
734
+ entries.push(entry);
735
+ // Best-first for the board's order; ties keep their standing position — a tie never displaces.
736
+ entries.sort((a, b) => (doc.order === 'desc' ? b.score - a.score : a.score - b.score));
737
+ doc.entries = entries.slice(0, doc.size);
738
+ this.touched();
739
+ const standing = doc.entries.find((e) => e.subject === this.state.userId);
740
+ return {
741
+ ok: true,
742
+ result: { best: standing ? standing.score : null, updated: Boolean(standing) },
743
+ };
744
+ }
745
+ leaderboardTop(board, limit, order) {
746
+ if (!board)
747
+ return { ok: false, error: 'board required' };
748
+ const doc = this.state.leaderboards[board];
749
+ const size = Math.min(limit === undefined ? DEV_SHELL_CAPS.leaderboardPageDefault : Math.max(1, Math.floor(limit)), DEV_SHELL_CAPS.leaderboardPageMax);
750
+ if (!doc)
751
+ return { ok: true, result: { entries: [], truncated: false } };
752
+ const direction = order ?? doc.order;
753
+ const entries = [...doc.entries].sort((a, b) => (direction === 'desc' ? b.score - a.score : a.score - b.score));
754
+ const page = { entries: entries.slice(0, size), truncated: entries.length > size };
755
+ return { ok: true, result: page };
756
+ }
757
+ // ─────────────────────────── achievements ───────────────────────────
758
+ achievementsList() {
759
+ const achievements = this.state.achievements.registry.map((row, index) => this.summaryOf(row, index));
760
+ const result = {
761
+ achievements,
762
+ total: achievements.length,
763
+ earned: achievements.filter((a) => a.earned).length,
764
+ };
765
+ return { ok: true, result };
766
+ }
767
+ achievementsMine() {
768
+ const achievements = this.state.achievements.registry
769
+ .map((row, index) => this.summaryOf(row, index))
770
+ .filter((a) => a.earned);
771
+ return { ok: true, result: { achievements } };
772
+ }
773
+ /**
774
+ * The player's equipped emote wheel — a STUB, and one that says so on every petal.
775
+ *
776
+ * There is no account here to read a wheel from, so the only two honest answers were a refusal or a
777
+ * loadout that cannot be mistaken for a real one. A refusal is what this used to be by omission, and
778
+ * it was the wrong one: the engine's native avatar runtime reports an unanswered read as "Couldn't
779
+ * load your emotes", so `helix dev` — the platform's own local command — could not show a creator
780
+ * the wheel at all.
781
+ *
782
+ * Read from state rather than returned as a constant so a creator can point it at their own clips by
783
+ * editing .helix/dev-state.json, and so `--reset` restores the stub. An older state file has no
784
+ * `emotes` field, hence the fallback.
785
+ */
786
+ emotesGetEquipped() {
787
+ const emotes = this.state.emotes ?? [...DEV_SHELL_SIMULATED_EMOTES];
788
+ return { ok: true, result: { emotes } };
789
+ }
790
+ summaryOf(row, index) {
791
+ const earned = this.state.achievements.earned.includes(row.key);
792
+ const redacted = Boolean(row.hidden) && !earned;
793
+ return {
794
+ id: row.id ?? `dev-achievement-${index + 1}`,
795
+ // A hidden, unearned row arrives redacted — neither the text nor the slug that spells it reaches
796
+ // world code, so a world must match on `id`.
797
+ key: redacted ? '' : row.key,
798
+ name: redacted ? 'Hidden achievement' : row.name,
799
+ description: redacted ? null : (row.description ?? null),
800
+ points: row.points ?? 0,
801
+ hidden: Boolean(row.hidden),
802
+ earned,
803
+ // A local run has no population to rank against, so never fabricate a rarity.
804
+ rarityTier: 'unranked',
805
+ earnPct: null,
806
+ iconUrl: redacted ? null : (row.iconUrl ?? null),
807
+ };
808
+ }
809
+ // ─────────────────────────── achievement unlocking (wave 1.5) ───────────────────────────
810
+ // Real-flow evidence (data-store writes, purchase settles) pokes through the debounce; a poke while one
811
+ // is pending collapses into it, which is safe because evaluation re-derives from CURRENT state.
812
+ pokeAchievements() {
813
+ const delay = this.options.achievementDebounceMs ?? DEV_SHELL_ACHIEVEMENT_DEBOUNCE_MS;
814
+ if (delay <= 0) {
815
+ this.evaluateAchievements();
816
+ return;
817
+ }
818
+ if (this.achievementPokeTimer !== null)
819
+ return;
820
+ this.achievementPokeTimer = setTimeout(() => {
821
+ this.achievementPokeTimer = null;
822
+ this.evaluateAchievements();
823
+ }, delay);
824
+ }
825
+ // Earned is add-only: an achievement is a soulbound instance in production, so shrinking evidence
826
+ // never revokes — which is also why deletes don't poke (a missing field measures null, fail-closed).
827
+ evaluateAchievements() {
828
+ const evidence = this.criteriaEvidence();
829
+ let unlocked = false;
830
+ for (const row of this.state.achievements.registry) {
831
+ if (!row.criteria || this.state.achievements.earned.includes(row.key))
832
+ continue;
833
+ const measured = measureDevShellCriteria(row.criteria, evidence);
834
+ if (!devShellCriteriaSatisfied(measured, row.criteria))
835
+ continue;
836
+ this.earnAchievement(row, `${formatDevShellCriteria(row.criteria)} (measured ${measured})`);
837
+ unlocked = true;
838
+ }
839
+ if (unlocked)
840
+ this.touched();
841
+ }
842
+ criteriaEvidence() {
843
+ return {
844
+ userId: this.state.userId,
845
+ documents: this.state.documents,
846
+ // IWP measures SETTLED WORLD-product purchases: Granted/Claimed only — NOT completedOf(), because
847
+ // AlreadyOwned also "ownsAfter" yet charged and granted nothing, and production never counts it.
848
+ // Listing rows are marketplace, not IWP. Replays never double-count — one row per key.
849
+ completedPurchases: this.state.purchases
850
+ .filter((p) => (p.status === 'Granted' || p.status === 'Claimed') &&
851
+ findDevShellProduct(this.products, p.ref) !== null)
852
+ .map((p) => ({ priceLix: p.priceLix })),
853
+ playtimeSeconds: this.state.playtimeSeconds,
854
+ analyticsCounts: this.state.analyticsCounts,
855
+ };
856
+ }
857
+ /** Append to earned + notify the host. The caller batches touched(); no world event exists to push. */
858
+ earnAchievement(row, via) {
859
+ this.state.achievements.earned.push(row.key);
860
+ this.log(`achievement unlocked: "${row.name}" (${row.key}) via ${via}`);
861
+ this.options.onAchievementEarned?.({
862
+ key: row.key,
863
+ name: row.name,
864
+ points: row.points ?? 0,
865
+ hidden: Boolean(row.hidden),
866
+ via,
867
+ });
868
+ }
869
+ // ─────────────────────────── debug menu (build plan §3.5) ───────────────────────────
870
+ grantAllEntitlements() {
871
+ for (const product of this.products)
872
+ this.applyProduct(product);
873
+ this.log(`granted every seeded product (${this.products.length})`);
874
+ this.afterDebugGrant();
875
+ }
876
+ grantEntitlement(ref) {
877
+ const product = findDevShellProduct(this.products, ref);
878
+ if (product)
879
+ this.applyProduct(product);
880
+ else {
881
+ const key = devShellProductRef(ref);
882
+ this.state.entitlements.owned[key] = (this.state.entitlements.owned[key] ?? 0) + 1;
883
+ this.log(`granted "${key}" — no seeded product answers that ref, so only the owned count moved`);
884
+ }
885
+ this.afterDebugGrant();
886
+ }
887
+ removeEntitlement(ref) {
888
+ const product = findDevShellProduct(this.products, ref);
889
+ const ent = this.state.entitlements;
890
+ if (product) {
891
+ delete ent.owned[product.key];
892
+ for (const grant of product.grants ?? []) {
893
+ if (grant.kind === 'pass')
894
+ delete ent.passes[grant.passKey ?? product.key];
895
+ else if (grant.kind === 'currency')
896
+ ent.balances[grant.code] = 0;
897
+ else
898
+ this.state.inventory = this.state.inventory.filter((i) => i.itemId !== grant.itemId);
899
+ }
900
+ }
901
+ else {
902
+ const key = devShellProductRef(ref);
903
+ delete ent.passes[ref];
904
+ delete ent.balances[ref];
905
+ delete ent.owned[key];
906
+ delete ent.owned[ref];
907
+ }
908
+ this.log(`removed entitlement "${ref}"`);
909
+ this.afterDebugGrant();
910
+ }
911
+ entitlementsSnapshot() {
912
+ const snapshot = devShellEntitlementsSnapshot(this.state);
913
+ this.log('owned entitlements', snapshot);
914
+ return snapshot;
915
+ }
916
+ setPurchasesAlwaysFail(mode) {
917
+ this.purchaseFailure = mode === 'off' ? null : mode;
918
+ this.log(`Purchases Always Fail → ${mode}`);
919
+ }
920
+ /** The debug-menu button: off → InsufficientFunds → PriceChanged → Pending → off. */
921
+ cyclePurchasesAlwaysFail() {
922
+ const order = ['off', ...DEV_SHELL_PURCHASE_FAILURE_MODES];
923
+ const next = order[(order.indexOf(this.purchaseFailure ?? 'off') + 1) % order.length];
924
+ this.setPurchasesAlwaysFail(next);
925
+ return next;
926
+ }
927
+ purchasesAlwaysFail() {
928
+ return this.purchaseFailure ?? 'off';
929
+ }
930
+ resetPlayerDocument() {
931
+ delete this.state.documents[`player:${this.state.userId}`];
932
+ this.log(`reset player:${this.state.userId}`);
933
+ this.touched();
934
+ }
935
+ setForceSaveFailure(on) {
936
+ this.forceSaveFailure = on;
937
+ this.log(`Force Save Failure → ${on ? 'on' : 'off'}`);
938
+ }
939
+ forceSaveFailureOn() {
940
+ return this.forceSaveFailure;
941
+ }
942
+ /** Fill the consume window so the next consume hits the real 120/min refusal. */
943
+ exhaustConsumeFence() {
944
+ const now = Date.now();
945
+ this.consumes = new Array(DEV_SHELL_CAPS.consumesPerMinute).fill(now);
946
+ this.log(`consume fence exhausted — the next consume answers RateLimited for up to 60s`);
947
+ }
948
+ setWallet(wallet) {
949
+ this.state.wallet = { ...this.state.wallet, ...wallet };
950
+ this.log('wallet set', this.state.wallet);
951
+ this.touched();
952
+ this.emit('balance-changed', { ...this.state.wallet });
953
+ }
954
+ // Debug-menu evidence evaluates IMMEDIATELY — these controls are the local analog of the admin sweep
955
+ // (`POST admin/criteria-sweep`), not of a world-lane write, so the write-path debounce does not apply.
956
+ /** The room/platform award lanes' stand-in. Refuses a key outside the registry, as the backend would. */
957
+ awardAchievement(key) {
958
+ const row = this.state.achievements.registry.find((a) => a.key === key);
959
+ if (!row) {
960
+ this.log(`award refused — "${key}" is not in the local registry (seed it in .helix/dev-achievements.json)`);
961
+ return false;
962
+ }
963
+ if (this.state.achievements.earned.includes(key)) {
964
+ this.log(`award replayed — "${key}" is already earned (the funnel is idempotent)`);
965
+ return true;
966
+ }
967
+ this.earnAchievement(row, 'debug menu award');
968
+ this.touched();
969
+ return true;
970
+ }
971
+ /** Local-only re-test convenience: production never revokes. Finer-grained than --reset. */
972
+ resetAchievements() {
973
+ this.state.achievements.earned = [];
974
+ this.log('earned achievements reset — criteria will re-unlock from current evidence on the next poke');
975
+ this.touched();
976
+ this.evaluateAchievements();
977
+ }
978
+ /** Playtime evidence — the shell page ticks this while open; the debug button adds minutes at once. */
979
+ addPlaytime(seconds) {
980
+ if (!Number.isFinite(seconds) || seconds <= 0)
981
+ return;
982
+ this.state.playtimeSeconds += seconds;
983
+ this.touched();
984
+ this.evaluateAchievements();
985
+ }
986
+ /** Analytics evidence. Counts only — analytics.track never reaches a shell, so nothing flows here live. */
987
+ bumpAnalyticsEvent(eventName, count = 1) {
988
+ if (!eventName || !Number.isFinite(count) || count <= 0)
989
+ return;
990
+ this.state.analyticsCounts[eventName] = (this.state.analyticsCounts[eventName] ?? 0) + count;
991
+ this.log(`analytics "${eventName}" → ${this.state.analyticsCounts[eventName]} (debug bump — real events never reach a shell)`);
992
+ this.touched();
993
+ this.evaluateAchievements();
994
+ }
995
+ /** The room's flush, by hand: writes the { v, vars } envelope a real room persists, then pokes. */
996
+ setMpPlayerVar(field, value) {
997
+ if (!DEV_SHELL_CRITERIA_FIELD_PATTERN.test(field)) {
998
+ this.log(`mp var refused — "${field}" must be a dot-path of letters, digits and underscores`);
999
+ return;
1000
+ }
1001
+ if (!Number.isFinite(value)) {
1002
+ this.log(`mp var refused — "${field}" needs a finite number (criteria leaves must be real JSON numbers)`);
1003
+ return;
1004
+ }
1005
+ const key = `mp:player:${this.state.userId}`;
1006
+ const existing = this.state.documents[key];
1007
+ const priorValue = existing ? existing.value : undefined;
1008
+ const envelope = isRecord(priorValue) && isRecord(priorValue.vars)
1009
+ ? { v: priorValue.v, vars: priorValue.vars }
1010
+ : { v: 0, vars: {} };
1011
+ setPath(envelope.vars, field, value);
1012
+ this.state.documents[key] = {
1013
+ value: { v: (typeof envelope.v === 'number' ? envelope.v : 0) + 1, vars: envelope.vars },
1014
+ version: (existing?.version ?? 0) + 1,
1015
+ updatedAt: new Date().toISOString(),
1016
+ };
1017
+ this.log(`mp:player var "${field}" = ${value} (simulating the room's persistent-var flush)`);
1018
+ this.touched();
1019
+ this.evaluateAchievements();
1020
+ }
1021
+ /**
1022
+ * The room's leaderboard submit, by hand: declared boards are written by room rules in production, so
1023
+ * with no room a board a world only READS stays empty forever. Seeds any subject (default the player),
1024
+ * skips the session fences (the room lane has its own, unreachable here), and keeps board shape rules:
1025
+ * creation fixes the order, best-per-subject wins, sorted and trimmed to size.
1026
+ */
1027
+ seedLeaderboardScore(board, score, opts = {}) {
1028
+ if (!board || !Number.isFinite(score)) {
1029
+ this.log(`leaderboard seed refused — board and a finite score are required`);
1030
+ return;
1031
+ }
1032
+ let doc = this.state.leaderboards[board];
1033
+ if (!doc) {
1034
+ doc = { order: opts.order ?? 'desc', size: DEV_SHELL_CAPS.boardSize, entries: [] };
1035
+ this.state.leaderboards[board] = doc;
1036
+ }
1037
+ const subject = opts.subject ?? this.state.userId;
1038
+ const previous = doc.entries.find((e) => e.subject === subject);
1039
+ const better = !previous || (doc.order === 'desc' ? score > previous.score : score < previous.score);
1040
+ if (better) {
1041
+ const entries = doc.entries.filter((e) => e.subject !== subject);
1042
+ entries.push({
1043
+ subject,
1044
+ displayName: opts.displayName ?? (subject === this.state.userId ? (this.state.displayName ?? this.state.username) : subject),
1045
+ score,
1046
+ source: 'server',
1047
+ updatedAt: new Date().toISOString(),
1048
+ });
1049
+ entries.sort((a, b) => (doc.order === 'desc' ? b.score - a.score : a.score - b.score));
1050
+ doc.entries = entries.slice(0, doc.size);
1051
+ }
1052
+ this.log(`leaderboard "${board}" seeded: ${subject} = ${score}${better ? '' : ' (kept the better existing score)'} — simulating the room's submit`);
1053
+ this.touched();
1054
+ }
1055
+ /**
1056
+ * The server's hand on the data store: write ANY key, including the ones a session may not touch
1057
+ * (world-global, mp:world:*, the reserved namespaces) — in production those are room/backend-written,
1058
+ * so a world that only READS them sees null locally until something stands in for the writer. Bypasses
1059
+ * the session key policy and the write fences deliberately; criteria evidence re-evaluates at once.
1060
+ */
1061
+ seedDocument(key, value) {
1062
+ if (!key) {
1063
+ this.log('document seed refused — a key is required');
1064
+ return;
1065
+ }
1066
+ let serialized;
1067
+ try {
1068
+ serialized = JSON.stringify(value);
1069
+ }
1070
+ catch {
1071
+ serialized = undefined;
1072
+ }
1073
+ if (typeof serialized !== 'string') {
1074
+ this.log(`document seed refused — the value for "${key}" must be JSON-serializable`);
1075
+ return;
1076
+ }
1077
+ const existing = this.state.documents[key];
1078
+ this.state.documents[key] = {
1079
+ value: JSON.parse(serialized),
1080
+ version: (existing?.version ?? 0) + 1,
1081
+ updatedAt: new Date().toISOString(),
1082
+ };
1083
+ this.log(`document "${key}" seeded by the debug hand (v${this.state.documents[key].version}) — simulating its server-side writer`);
1084
+ this.touched();
1085
+ this.evaluateAchievements();
1086
+ }
1087
+ /** The debug menu's progress print: measured-vs-target for every registered achievement. */
1088
+ achievementsProgress() {
1089
+ const evidence = this.criteriaEvidence();
1090
+ const rows = this.state.achievements.registry.map((row) => ({
1091
+ key: row.key,
1092
+ name: row.name,
1093
+ earned: this.state.achievements.earned.includes(row.key),
1094
+ ...(row.unlockMode ? { unlockMode: row.unlockMode } : {}),
1095
+ criteria: row.criteria ? formatDevShellCriteria(row.criteria) : null,
1096
+ measured: row.criteria ? measureDevShellCriteria(row.criteria, evidence) : null,
1097
+ }));
1098
+ this.log('achievement progress', rows);
1099
+ return rows;
1100
+ }
1101
+ applyProduct(product) {
1102
+ this.state.entitlements.owned[product.key] = (this.state.entitlements.owned[product.key] ?? 0) + 1;
1103
+ applyDevShellGrants(this.state, product.grants, product.key, (itemId) => this.titleOf(itemId));
1104
+ }
1105
+ afterDebugGrant() {
1106
+ this.touched();
1107
+ this.emit('entitlements-changed');
1108
+ this.emit('inventory-changed');
1109
+ }
1110
+ titleOf(itemId) {
1111
+ return this.listings.find((l) => l.itemId === itemId)?.title;
1112
+ }
1113
+ // ─────────────────────────── room types ───────────────────────────
1114
+ /** Replace the declared room types. A name the manifest validator would reject is ignored, loudly. */
1115
+ setRoomTypes(seed) {
1116
+ this.roomTypes = new Map();
1117
+ for (const [name, type] of Object.entries(seed ?? {})) {
1118
+ const reason = name === 'default' ? '"default" is reserved for the world\'s own multiplayer block'
1119
+ : !DEV_SHELL_ROOM_TYPE_NAME_PATTERN.test(name) ? 'the name must match ^[a-z][a-z0-9-]{0,31}$'
1120
+ : this.roomTypes.size >= DEV_SHELL_ROOM_TYPES_MAX ? `a world declares at most ${DEV_SHELL_ROOM_TYPES_MAX} room types`
1121
+ : !isRecord(type) || (type.access !== 'open' && type.access !== 'ticketed') ? 'access must be "open" or "ticketed"'
1122
+ : null;
1123
+ if (reason) {
1124
+ this.log(`room type "${name}" ignored — ${reason}`);
1125
+ continue;
1126
+ }
1127
+ this.roomTypes.set(name, { access: type.access, maxPlayers: type.maxPlayers });
1128
+ }
1129
+ }
1130
+ /**
1131
+ * `POST /instant-worlds/:worldId/join`, decided but not served: the body table of the join API.
1132
+ * No body / `{}` is the default room. With NO room types declared every typed body is `unknown-room-type`,
1133
+ * which is also what the backend answers while its ROOM_TYPES_ENABLED flag is off.
1134
+ */
1135
+ joinRoom(body = {}) {
1136
+ const refuse = (code, message) => {
1137
+ const status = DEV_SHELL_ROOM_REFUSALS[code];
1138
+ this.log(`join refused: ${status} ${code}`, body);
1139
+ return { ok: false, status, body: { statusCode: status, code, message } };
1140
+ };
1141
+ const { roomType, ticket } = payloadOf(body);
1142
+ if (typeof ticket === 'string') {
1143
+ if (this.roomTypes.size === 0)
1144
+ return refuse('unknown-room-type', 'Room types are not enabled for this world');
1145
+ const row = this.roomTickets.get(ticket);
1146
+ // Unknown is 404; anything that WAS a ticket but can no longer be claimed is 410 — and the three 410s
1147
+ // are distinct codes, because "the match ended" is not the same news as "your ticket is bad".
1148
+ if (!row)
1149
+ return refuse('unknown-room-ticket', 'Unknown room ticket');
1150
+ if (!this.roomInstances.get(row.instanceId)?.open)
1151
+ return refuse('room-instance-closed', 'Room instance closed');
1152
+ if (row.redeemed)
1153
+ return refuse('room-ticket-used', 'Room ticket already used');
1154
+ if (row.expiresAt <= Date.now())
1155
+ return refuse('room-ticket-expired', 'Room ticket expired');
1156
+ row.redeemed = true;
1157
+ this.log(`join: ticket ${ticket} redeemed → room type "${row.roomType}", instance ${row.instanceId}`);
1158
+ return { ok: true, status: 200, roomType: row.roomType, instanceKey: row.instanceId };
1159
+ }
1160
+ if (typeof roomType === 'string') {
1161
+ const declared = this.roomTypes.get(roomType);
1162
+ if (!declared)
1163
+ return refuse('unknown-room-type', `Unknown room type "${roomType}"`);
1164
+ if (declared.access === 'ticketed')
1165
+ return refuse('ticket-required', `Room type "${roomType}" requires a ticket`);
1166
+ this.log(`join: open room type "${roomType}"`);
1167
+ return { ok: true, status: 200, roomType };
1168
+ }
1169
+ this.log('join: default room type');
1170
+ return { ok: true, status: 200 };
1171
+ }
1172
+ /**
1173
+ * The room's `openRoom` effect, by hand: open (or reuse) an instance of a TICKETED type and mint this
1174
+ * player's ticket to it — the `helix:room-ticket` payload a room would send. Null when the type is not
1175
+ * declared ticketed, which is the same condition under which the real effect is a publish-time error.
1176
+ */
1177
+ issueRoomTicket(roomType, opts = {}) {
1178
+ const declared = this.roomTypes.get(roomType);
1179
+ if (!declared || declared.access !== 'ticketed') {
1180
+ this.log(`room ticket refused: "${roomType}" is not a declared ticketed room type`);
1181
+ return null;
1182
+ }
1183
+ let instanceId = opts.instanceId;
1184
+ if (instanceId !== undefined) {
1185
+ const existing = this.roomInstances.get(instanceId);
1186
+ if (!existing || !existing.open || existing.roomType !== roomType) {
1187
+ this.log(`room ticket refused: instance ${instanceId} is not an open "${roomType}" instance`);
1188
+ return null;
1189
+ }
1190
+ }
1191
+ else {
1192
+ instanceId = `dev-shell-instance-${++this.roomSerial}`;
1193
+ this.roomInstances.set(instanceId, { roomType, open: true, ticketIds: new Set() });
1194
+ }
1195
+ return this.mintRoomTicket(instanceId, roomType, opts.ttlMs);
1196
+ }
1197
+ /**
1198
+ * `POST …/room-instances/:instanceId/rejoin`: a fresh ticket for a player whose first one is spent, while
1199
+ * the instance is open and they hold a ticket row. 404 = no such instance for this player; 410 = closed.
1200
+ */
1201
+ rejoinRoomInstance(instanceId) {
1202
+ const instance = this.roomInstances.get(instanceId);
1203
+ if (!instance || instance.ticketIds.size === 0) {
1204
+ this.log(`rejoin refused: 404 unknown-room-instance — no ticket to instance ${instanceId}`);
1205
+ return { ok: false, status: 404, body: { statusCode: 404, code: 'unknown-room-instance', message: 'Unknown room instance' } };
1206
+ }
1207
+ if (!instance.open) {
1208
+ this.log(`rejoin refused: 410 room-instance-closed — instance ${instanceId} has closed`);
1209
+ return { ok: false, status: 410, body: { statusCode: 410, code: 'room-instance-closed', message: 'Room instance closed' } };
1210
+ }
1211
+ return { ok: true, status: 200, ticket: this.mintRoomTicket(instanceId, instance.roomType) };
1212
+ }
1213
+ /** The ticketed room disposing (it closes its backend instance). Idempotent; false = no such instance. */
1214
+ closeRoomInstance(instanceId) {
1215
+ const instance = this.roomInstances.get(instanceId);
1216
+ if (!instance)
1217
+ return false;
1218
+ if (instance.open)
1219
+ this.log(`room instance ${instanceId} closed`);
1220
+ instance.open = false;
1221
+ return true;
1222
+ }
1223
+ // ─────────────────────────── matchmaking and parties ───────────────────────────
1224
+ /** Replace the declared queues. One the manifest validator would reject is ignored, loudly. */
1225
+ setQueues(seed) {
1226
+ this.queues = new Map();
1227
+ for (const [id, queue] of Object.entries(seed ?? {})) {
1228
+ const teams = isRecord(queue) && Number.isInteger(queue.teams) ? queue.teams : 2;
1229
+ const teamSize = isRecord(queue) && Number.isInteger(queue.teamSize) ? queue.teamSize : 1;
1230
+ const target = isRecord(queue) ? this.roomTypes.get(str(queue.roomType)) : undefined;
1231
+ const reason = !DEV_SHELL_QUEUE_ID_PATTERN.test(id) ? 'the id must match ^[a-z][a-z0-9-]{0,31}$'
1232
+ : this.queues.size >= DEV_SHELL_QUEUES_MAX ? `a world declares at most ${DEV_SHELL_QUEUES_MAX} queues`
1233
+ : !target || target.access !== 'ticketed' ? 'roomType must be a declared ticketed room type'
1234
+ : teams < 1 || teams > 8 || teamSize < 1 || teamSize > 12 ? 'teams must be 1..8 and teamSize 1..12'
1235
+ : teams * teamSize > target.maxPlayers ? 'teams × teamSize must fit the maxPlayers of its room type'
1236
+ : null;
1237
+ if (reason) {
1238
+ this.log(`queue "${id}" ignored — ${reason}`);
1239
+ continue;
1240
+ }
1241
+ this.queues.set(id, { roomType: str(queue.roomType), teams, teamSize });
1242
+ }
1243
+ }
1244
+ /**
1245
+ * The v1 matchmaking / party route table, decided but not served. `path` is the request path with or
1246
+ * without the `/api/v1` prefix; the world id segment is not checked (there is one world here). The caller
1247
+ * is always the simulated player, who is an account — the guest refusals are the SDK's to make.
1248
+ * With NO queues declared every queue route answers 404 `matchmaking-disabled`, which is also what the
1249
+ * backend answers while its MATCHMAKING_ENABLED flag is off.
1250
+ */
1251
+ platformRequest(method, path, body) {
1252
+ const route = `${method.toUpperCase()} ${path.replace(/^\/api\/v1/, '').replace(/\?.*$/, '')}`;
1253
+ const refuse = (status, code, message) => {
1254
+ this.log(`${route} refused: ${status} ${code}`);
1255
+ return { status, body: { statusCode: status, code, message } };
1256
+ };
1257
+ const me = this.state.userId;
1258
+ let m;
1259
+ if (/^(POST|GET|DELETE) \/instant-worlds\/[^/]+\/queues\//.test(route) && this.queues.size === 0) {
1260
+ return refuse(404, 'matchmaking-disabled', 'Matchmaking is not enabled');
1261
+ }
1262
+ if ((m = /^POST \/instant-worlds\/[^/]+\/queues\/([^/]+)\/tickets$/.exec(route))) {
1263
+ const queueId = decodeURIComponent(m[1]);
1264
+ const queue = this.queues.get(queueId);
1265
+ if (!queue)
1266
+ return refuse(404, 'unknown-queue', `Unknown queue "${queueId}"`);
1267
+ // Another party member's match is still pending: refused, naming them. Their room ticket is theirs alone.
1268
+ if (this.memberWithMatch && this.party?.members.some((member) => member.userId === this.memberWithMatch)) {
1269
+ this.log(`${route} refused: 409 already-matched (held by ${this.memberWithMatch})`);
1270
+ return { status: 409, body: { statusCode: 409, code: 'already-matched', message: 'A party member has a match pending', memberUserId: this.memberWithMatch } };
1271
+ }
1272
+ const standing = this.currentQueueTicket();
1273
+ // A match that still stands unredeemed is not queued over: 409 with the match, as a late cancel gets.
1274
+ if (standing?.match) {
1275
+ const { ticketId, instanceId, roomType, expiresAt } = standing.match;
1276
+ this.log(`${route} refused: 409 already-matched`);
1277
+ return {
1278
+ status: 409,
1279
+ body: { statusCode: 409, code: 'already-matched', message: 'Already matched', match: { ticketId, instanceId, roomType, expiresAt: new Date(expiresAt).toISOString() } },
1280
+ };
1281
+ }
1282
+ if (standing)
1283
+ return refuse(409, 'already-queued', 'Already queued');
1284
+ if (this.party && this.party.leaderId !== me)
1285
+ return refuse(403, 'not-party-leader', 'Only the party leader can queue');
1286
+ if (this.party && this.party.members.length > queue.teamSize)
1287
+ return refuse(400, 'party-too-large', 'The party does not fit one team of this queue');
1288
+ const ticket = {
1289
+ ticketId: `dev-shell-queue-ticket-${++this.socialSerial}`,
1290
+ queueId,
1291
+ expiresAt: Date.now() + 300_000,
1292
+ match: null,
1293
+ };
1294
+ this.queueTicket = ticket;
1295
+ this.queueEnded = null;
1296
+ this.log(`queue "${queueId}": waiting (${this.queuedPlayers().length}/${queue.teams * queue.teamSize}) — form the match from the debug menu`);
1297
+ return {
1298
+ status: 201,
1299
+ body: {
1300
+ ticketId: ticket.ticketId,
1301
+ queueId,
1302
+ status: 'waiting',
1303
+ expiresAt: new Date(ticket.expiresAt).toISOString(),
1304
+ players: this.queuedPlayers(),
1305
+ waiting: { players: this.queuedPlayers().length, needed: queue.teams * queue.teamSize },
1306
+ },
1307
+ };
1308
+ }
1309
+ if (/^GET \/instant-worlds\/[^/]+\/queues\/tickets\/current$/.test(route)) {
1310
+ const ticket = this.currentQueueTicket();
1311
+ if (!ticket) {
1312
+ const ended = this.queueEnded && Date.now() - this.queueEnded.at < 60_000 ? this.queueEnded : null;
1313
+ return {
1314
+ status: 200,
1315
+ body: { status: 'none', ...(ended ? { ended: { queueId: ended.queueId, reason: ended.reason, at: new Date(ended.at).toISOString() } } : {}) },
1316
+ };
1317
+ }
1318
+ const queue = this.queues.get(ticket.queueId);
1319
+ if (!ticket.match) {
1320
+ return {
1321
+ status: 200,
1322
+ body: { status: 'waiting', queueId: ticket.queueId, waiting: { players: this.queuedPlayers().length, needed: queue ? queue.teams * queue.teamSize : 0 } },
1323
+ };
1324
+ }
1325
+ const { ticketId, instanceId, roomType, expiresAt } = ticket.match;
1326
+ return {
1327
+ status: 200,
1328
+ body: { status: 'matched', queueId: ticket.queueId, match: { ticketId, instanceId, roomType, expiresAt: new Date(expiresAt).toISOString() } },
1329
+ };
1330
+ }
1331
+ if (/^DELETE \/instant-worlds\/[^/]+\/queues\/tickets\/current$/.test(route)) {
1332
+ const ticket = this.currentQueueTicket();
1333
+ // Too late to cancel a match: 409 with the match, so the client redeems it instead of losing it.
1334
+ if (ticket?.match) {
1335
+ const { ticketId, instanceId, roomType, expiresAt } = ticket.match;
1336
+ this.log(`${route} refused: 409 already-matched`);
1337
+ return {
1338
+ status: 409,
1339
+ body: { statusCode: 409, code: 'already-matched', message: 'Already matched', match: { ticketId, instanceId, roomType, expiresAt: new Date(expiresAt).toISOString() } },
1340
+ };
1341
+ }
1342
+ if (ticket)
1343
+ this.closeQueueTicket('cancelled');
1344
+ return { status: 204 };
1345
+ }
1346
+ if (route === 'GET /parties/current') {
1347
+ this.partyInvites = this.partyInvites.filter((invite) => Date.parse(invite.expiresAt) > Date.now());
1348
+ return { status: 200, body: { party: this.partyBody(), invites: jsonCopy(this.partyInvites) } };
1349
+ }
1350
+ if (route === 'POST /parties/invites') {
1351
+ const userId = str(payloadOf(body).userId);
1352
+ if (this.party && this.party.leaderId !== me)
1353
+ return refuse(403, 'not-party-leader', 'Only the party leader can invite');
1354
+ // The simulated player has no friends list and nobody stands next to them: any OTHER account may be
1355
+ // invited. Inviting yourself is the one refusal that needs no social graph.
1356
+ if (!userId || userId === me)
1357
+ return refuse(403, 'cannot-invite', 'You cannot invite this player');
1358
+ if (this.party && this.party.members.length >= this.party.maxSize)
1359
+ return refuse(409, 'party-full', 'The party is full');
1360
+ if (this.outgoingInvites.size >= DEV_SHELL_PARTY_PENDING_INVITES_MAX)
1361
+ return refuse(409, 'too-many-invites', 'Too many pending invites');
1362
+ // Inviting someone who already has a pending invite hands back that same invite.
1363
+ for (const [pendingId, pending] of this.outgoingInvites) {
1364
+ if (pending.userId === userId && pending.expiresAt > Date.now()) {
1365
+ return { status: 201, body: { inviteId: pendingId, expiresAt: new Date(pending.expiresAt).toISOString() } };
1366
+ }
1367
+ }
1368
+ this.party ??= { id: `dev-shell-party-${++this.socialSerial}`, leaderId: me, maxSize: DEV_SHELL_PARTY_MAX_SIZE, members: [this.selfMember()] };
1369
+ const inviteId = `dev-shell-invite-${++this.socialSerial}`;
1370
+ const expiresAt = Date.now() + DEV_SHELL_PARTY_INVITE_TTL_MS;
1371
+ this.outgoingInvites.set(inviteId, { userId, expiresAt });
1372
+ this.log(`party invite ${inviteId} → ${userId} (they accept from the debug menu)`);
1373
+ return { status: 201, body: { inviteId, expiresAt: new Date(expiresAt).toISOString() } };
1374
+ }
1375
+ if ((m = /^POST \/parties\/invites\/([^/]+)\/accept$/.exec(route))) {
1376
+ const inviteId = decodeURIComponent(m[1]);
1377
+ const invite = this.partyInvites.find((row) => row.id === inviteId);
1378
+ if (!invite)
1379
+ return refuse(404, 'unknown-party-invite', 'Unknown party invite');
1380
+ if (Date.parse(invite.expiresAt) <= Date.now())
1381
+ return refuse(410, 'party-invite-expired', 'Party invite expired');
1382
+ // Only a party of two or more holds its member: from a party of one (their own invite or code made
1383
+ // it) the player is moved into the new party.
1384
+ if (this.party && this.party.members.length > 1)
1385
+ return refuse(409, 'already-in-party', 'Leave your party first');
1386
+ this.partyInvites = this.partyInvites.filter((row) => row.id !== inviteId);
1387
+ this.moveToParty(invite.partyId, invite.from);
1388
+ return { status: 200, body: this.partyBody() };
1389
+ }
1390
+ if (route === 'POST /parties/current/code') {
1391
+ if (this.party && this.party.leaderId !== me)
1392
+ return refuse(403, 'not-party-leader', 'Only the party leader can make a join code');
1393
+ this.party ??= { id: `dev-shell-party-${++this.socialSerial}`, leaderId: me, maxSize: DEV_SHELL_PARTY_MAX_SIZE, members: [this.selfMember()] };
1394
+ this.partyCode = { code: `DEVS${String(++this.socialSerial).padStart(4, '0')}`, expiresAt: Date.now() + DEV_SHELL_PARTY_CODE_TTL_MS };
1395
+ this.log(`party join code ${this.partyCode.code} created (another player uses it from the debug menu)`);
1396
+ return { status: 201, body: { code: this.partyCode.code, expiresAt: new Date(this.partyCode.expiresAt).toISOString() } };
1397
+ }
1398
+ if (route === 'DELETE /parties/current/code') {
1399
+ if (this.party && this.party.leaderId !== me)
1400
+ return refuse(403, 'not-party-leader', 'Only the party leader can revoke the join code');
1401
+ this.partyCode = null;
1402
+ return { status: 204 };
1403
+ }
1404
+ if (route === 'POST /parties/join') {
1405
+ const code = str(payloadOf(body).code).trim().toUpperCase();
1406
+ const target = this.foreignCodes.get(code);
1407
+ if (!target || target.expiresAt <= Date.now())
1408
+ return refuse(404, 'unknown-party-code', 'Unknown party code');
1409
+ if (this.party && this.party.members.length > 1)
1410
+ return refuse(409, 'already-in-party', 'Leave your party first');
1411
+ this.moveToParty(target.partyId, target.host);
1412
+ return { status: 200, body: this.partyBody() };
1413
+ }
1414
+ if ((m = /^DELETE \/parties\/invites\/([^/]+)$/.exec(route))) {
1415
+ const inviteId = decodeURIComponent(m[1]);
1416
+ this.partyInvites = this.partyInvites.filter((row) => row.id !== inviteId);
1417
+ this.outgoingInvites.delete(inviteId);
1418
+ return { status: 204 };
1419
+ }
1420
+ if ((m = /^DELETE \/parties\/current\/members\/([^/]+)$/.exec(route))) {
1421
+ const userId = decodeURIComponent(m[1]);
1422
+ if (!this.party)
1423
+ return refuse(404, 'not-in-party', 'You are not in a party');
1424
+ if (userId !== me && this.party.leaderId !== me)
1425
+ return refuse(403, 'not-party-leader', 'Only the party leader can remove a member');
1426
+ if (!this.party.members.some((member) => member.userId === userId))
1427
+ return refuse(404, 'unknown-party-member', 'Not a member of this party');
1428
+ if (userId === me) {
1429
+ this.party = null; // the others carry on without the simulated player; nothing here observes them
1430
+ this.outgoingInvites.clear();
1431
+ this.partyCode = null;
1432
+ }
1433
+ else {
1434
+ this.party.members = this.party.members.filter((member) => member.userId !== userId);
1435
+ }
1436
+ this.partyChanged(userId === me ? 'left the party' : `removed ${userId}`);
1437
+ return { status: 204 };
1438
+ }
1439
+ if (route === 'POST /parties/current/leader') {
1440
+ const userId = str(payloadOf(body).userId);
1441
+ if (!this.party)
1442
+ return refuse(404, 'not-in-party', 'You are not in a party');
1443
+ if (this.party.leaderId !== me)
1444
+ return refuse(403, 'not-party-leader', 'Only the party leader can promote');
1445
+ if (!this.party.members.some((member) => member.userId === userId))
1446
+ return refuse(404, 'unknown-party-member', 'Not a member of this party');
1447
+ this.party.leaderId = userId;
1448
+ this.partyChanged(`${userId} is now the leader`);
1449
+ return { status: 200, body: this.partyBody() };
1450
+ }
1451
+ return { status: 404, body: { statusCode: 404, message: `Cannot ${route}` } };
1452
+ }
1453
+ /**
1454
+ * The debug hand standing in for the matcher: the waiting ticket's match forms. Opens an instance of the
1455
+ * queue's ticketed room type and issues this player's room ticket from the simulated room-types table —
1456
+ * the ticket `GET …/queues/tickets/current` then reports as `matched`, redeemable with `joinRoom({ ticket })`.
1457
+ * Null when there is no waiting ticket.
1458
+ */
1459
+ formMatch(opts = {}) {
1460
+ const ticket = this.currentQueueTicket();
1461
+ const queue = ticket && this.queues.get(ticket.queueId);
1462
+ if (!ticket || !queue || ticket.match) {
1463
+ this.log('form match refused: no waiting queue ticket');
1464
+ return null;
1465
+ }
1466
+ ticket.match = this.issueRoomTicket(queue.roomType, { ttlMs: opts.ttlMs });
1467
+ if (ticket.match)
1468
+ this.log(`queue "${ticket.queueId}": matched → room ticket ${ticket.match.ticketId}`);
1469
+ return ticket.match;
1470
+ }
1471
+ /** Debug hand: another player invites the simulated player to their party. Shows up in `GET /parties/current`. */
1472
+ receivePartyInvite(from = {}, opts = {}) {
1473
+ const serial = ++this.socialSerial;
1474
+ const invite = {
1475
+ id: `dev-shell-invite-${serial}`,
1476
+ partyId: `dev-shell-party-${serial}`,
1477
+ from: { userId: from.userId ?? `dev-shell-player-${serial}`, displayName: from.displayName ?? `Player ${serial}` },
1478
+ expiresAt: new Date(Date.now() + (opts.ttlMs ?? DEV_SHELL_PARTY_INVITE_TTL_MS)).toISOString(),
1479
+ };
1480
+ this.partyInvites.push(invite);
1481
+ this.log(`party invite ${invite.id} received from ${invite.from.displayName}`);
1482
+ return jsonCopy(invite);
1483
+ }
1484
+ /** Debug hand: the player an invite was sent to accepts it and joins the party. False = no such pending invite, or no room. */
1485
+ acceptPartyInvite(inviteId, displayName) {
1486
+ const invite = this.outgoingInvites.get(inviteId);
1487
+ if (!invite || !this.party || invite.expiresAt <= Date.now() || this.party.members.length >= this.party.maxSize)
1488
+ return false;
1489
+ this.outgoingInvites.delete(inviteId);
1490
+ if (!this.party.members.some((member) => member.userId === invite.userId)) {
1491
+ this.party.members.push({ userId: invite.userId, displayName: displayName ?? invite.userId });
1492
+ }
1493
+ this.partyChanged(`${invite.userId} joined`);
1494
+ return true;
1495
+ }
1496
+ /**
1497
+ * Debug hand: the waiting ticket ends the way the platform would end it — `timeout`, `heartbeat-lapsed`,
1498
+ * `member-absent`, `build-changed`, `queue-removed`, or `replaced` (the player queued in another world).
1499
+ * `GET …/queues/tickets/current` then answers `none` with `ended` for 60 s. False when nothing is waiting.
1500
+ */
1501
+ endQueueTicket(reason) {
1502
+ const ticket = this.currentQueueTicket();
1503
+ if (!ticket || ticket.match)
1504
+ return false;
1505
+ this.closeQueueTicket(reason);
1506
+ return true;
1507
+ }
1508
+ /** Debug hand: a party member holds a match that still stands (null clears it). Enqueue is then refused naming them. */
1509
+ setPartyMemberMatch(userId) {
1510
+ this.memberWithMatch = userId;
1511
+ }
1512
+ closeQueueTicket(reason) {
1513
+ if (!this.queueTicket)
1514
+ return;
1515
+ this.log(`queue "${this.queueTicket.queueId}": ticket ended — ${reason}`);
1516
+ this.queueEnded = { queueId: this.queueTicket.queueId, reason, at: Date.now() };
1517
+ this.queueTicket = null;
1518
+ }
1519
+ /** Debug hand: another player's party has a join code. Returns it, for `POST /parties/join`. */
1520
+ openPartyCode(host = {}, opts = {}) {
1521
+ const serial = ++this.socialSerial;
1522
+ const code = `HOST${String(serial).padStart(4, '0')}`;
1523
+ const expiresAt = Date.now() + (opts.ttlMs ?? DEV_SHELL_PARTY_CODE_TTL_MS);
1524
+ this.foreignCodes.set(code, {
1525
+ partyId: `dev-shell-party-${serial}`,
1526
+ host: { userId: host.userId ?? `dev-shell-player-${serial}`, displayName: host.displayName ?? `Player ${serial}` },
1527
+ expiresAt,
1528
+ });
1529
+ this.log(`party join code ${code} opened by ${host.displayName ?? `Player ${serial}`}`);
1530
+ return { code, expiresAt: new Date(expiresAt).toISOString() };
1531
+ }
1532
+ /** Debug hand: another player joins the simulated player's party with its code. False = no such live code, or no room. */
1533
+ usePartyCode(code, member = {}) {
1534
+ const live = this.partyCode && this.partyCode.expiresAt > Date.now() && this.partyCode.code === code.trim().toUpperCase();
1535
+ if (!live || !this.party || this.party.members.length >= this.party.maxSize)
1536
+ return false;
1537
+ const serial = ++this.socialSerial;
1538
+ const joiner = { userId: member.userId ?? `dev-shell-player-${serial}`, displayName: member.displayName ?? `Player ${serial}` };
1539
+ if (!this.party.members.some((row) => row.userId === joiner.userId))
1540
+ this.party.members.push(joiner);
1541
+ this.partyChanged(`${joiner.userId} joined by code`);
1542
+ return true;
1543
+ }
1544
+ // The party as `GET /parties/current` and the party-returning routes serve it: the join code is shown to
1545
+ // the leader only, and is null otherwise.
1546
+ partyBody() {
1547
+ if (!this.party)
1548
+ return null;
1549
+ const live = this.partyCode && this.partyCode.expiresAt > Date.now() && this.party.leaderId === this.state.userId ? this.partyCode : null;
1550
+ return { ...jsonCopy(this.party), code: live ? { code: live.code, expiresAt: new Date(live.expiresAt).toISOString() } : null };
1551
+ }
1552
+ // The simulated player joins another player's party (by invite or by code), leaving a party of one behind.
1553
+ moveToParty(partyId, host) {
1554
+ this.outgoingInvites.clear();
1555
+ this.partyCode = null;
1556
+ this.party = { id: partyId, leaderId: host.userId, maxSize: DEV_SHELL_PARTY_MAX_SIZE, members: [{ ...host }, this.selfMember()] };
1557
+ this.partyChanged(`joined the party of ${host.displayName}`);
1558
+ }
1559
+ // The current queue ticket, or null once it stopped existing: a waiting ticket past its timeout, or a
1560
+ // matched one whose room ticket was redeemed or ran out ("matched until redeemed or expired, then none").
1561
+ currentQueueTicket() {
1562
+ const ticket = this.queueTicket;
1563
+ if (!ticket)
1564
+ return null;
1565
+ const room = ticket.match ? this.roomTickets.get(ticket.match.ticketId) : null;
1566
+ if (ticket.match) {
1567
+ // A match that was redeemed or ran out is simply over: there is no "ended" to report for it.
1568
+ if (!room || room.redeemed || room.expiresAt <= Date.now())
1569
+ this.queueTicket = null;
1570
+ }
1571
+ else if (ticket.expiresAt <= Date.now()) {
1572
+ this.closeQueueTicket('timeout');
1573
+ }
1574
+ return this.queueTicket;
1575
+ }
1576
+ queuedPlayers() {
1577
+ return this.party ? this.party.members.map((member) => member.userId) : [this.state.userId];
1578
+ }
1579
+ selfMember() {
1580
+ return { userId: this.state.userId, displayName: this.state.displayName ?? this.state.username };
1581
+ }
1582
+ // The backend's rule: a party change while its ticket is waiting cancels that ticket.
1583
+ partyChanged(what) {
1584
+ this.log(`party: ${what}`);
1585
+ if (this.queueTicket && !this.queueTicket.match)
1586
+ this.closeQueueTicket('party-changed');
1587
+ }
1588
+ mintRoomTicket(instanceId, roomType, ttlMs = DEV_SHELL_ROOM_TICKET_TTL_MS) {
1589
+ const ticketId = `dev-shell-ticket-${++this.roomSerial}`;
1590
+ const expiresAt = Date.now() + ttlMs;
1591
+ this.roomTickets.set(ticketId, { instanceId, roomType, expiresAt, redeemed: false });
1592
+ this.roomInstances.get(instanceId)?.ticketIds.add(ticketId);
1593
+ this.log(`room ticket ${ticketId} issued → "${roomType}" instance ${instanceId} (helix:room-ticket shape; NOT delivered to the world — there is no room here to send it)`);
1594
+ return { roomType, ticketId, instanceId, expiresAt };
1595
+ }
1596
+ }
1597
+ // A route answer must not alias simulator state: the caller owns what it is handed.
1598
+ const jsonCopy = (value) => JSON.parse(JSON.stringify(value));
1599
+ // Set a dot-path leaf inside the mp vars object, creating intermediate records. Non-record intermediates
1600
+ // are replaced — this is the debug hand, not a policy surface.
1601
+ function setPath(target, fieldPath, value) {
1602
+ const segments = fieldPath.split('.');
1603
+ let node = target;
1604
+ for (const segment of segments.slice(0, -1)) {
1605
+ const next = node[segment];
1606
+ if (!isRecord(next))
1607
+ node[segment] = {};
1608
+ node = node[segment];
1609
+ }
1610
+ node[segments[segments.length - 1]] = value;
1611
+ }
1612
+ // A stored row → the wire result. `completed` is derived from the shared meaning map, and no branch of
1613
+ // this function can add a `receipt`.
1614
+ function resultOf(record) {
1615
+ const result = { status: record.status, completed: completedOf(record.status) };
1616
+ if (record.reason !== undefined)
1617
+ result.reason = record.reason;
1618
+ if (record.itemId !== undefined)
1619
+ result.itemId = record.itemId;
1620
+ if (record.balanceAfterLix !== undefined)
1621
+ result.balanceAfterLix = record.balanceAfterLix;
1622
+ if (record.priceLix !== undefined)
1623
+ result.priceLix = record.priceLix;
1624
+ if (record.balanceLix !== undefined)
1625
+ result.balanceLix = record.balanceLix;
1626
+ if (record.shortfallLix !== undefined)
1627
+ result.shortfallLix = record.shortfallLix;
1628
+ if (record.ownedCount !== undefined)
1629
+ result.ownedCount = record.ownedCount;
1630
+ if (record.maxPerUser !== undefined)
1631
+ result.maxPerUser = record.maxPerUser;
1632
+ return result;
1633
+ }
1634
+ //# sourceMappingURL=simulator.js.map