@spellkave/sdk 0.0.0-bootstrap → 0.0.0-stage

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 (144) hide show
  1. package/README.md +2 -155
  2. package/package.json +4 -63
  3. package/LICENSE +0 -89
  4. package/src/binding_rows.ts +0 -186
  5. package/src/connection.ts +0 -964
  6. package/src/core/actor.ts +0 -62
  7. package/src/core/actor_control.ts +0 -193
  8. package/src/core/actor_control_query_methods.ts +0 -101
  9. package/src/core/actor_control_reaction_methods.ts +0 -79
  10. package/src/core/actor_control_sense_methods.ts +0 -81
  11. package/src/core/actor_control_source.ts +0 -57
  12. package/src/core/actor_session_methods.ts +0 -226
  13. package/src/core/binding_drift.ts +0 -301
  14. package/src/core/credential.ts +0 -259
  15. package/src/core/driver_control.ts +0 -54
  16. package/src/core/effective_environment_state.ts +0 -71
  17. package/src/core/factored_manipulation_attempt.ts +0 -158
  18. package/src/core/ids.ts +0 -60
  19. package/src/core/interaction/canonical.ts +0 -15
  20. package/src/core/interaction/fingerprint.ts +0 -118
  21. package/src/core/interaction/index.ts +0 -31
  22. package/src/core/interaction/intent.ts +0 -284
  23. package/src/core/interaction/outcome.ts +0 -67
  24. package/src/core/interaction/rejection_ledger.ts +0 -108
  25. package/src/core/kernel_contract.generated.ts +0 -10
  26. package/src/core/log.ts +0 -23
  27. package/src/core/movement.ts +0 -111
  28. package/src/core/node-io.ts +0 -208
  29. package/src/core/paths.ts +0 -220
  30. package/src/core/profile.ts +0 -270
  31. package/src/core/profiles.ts +0 -9
  32. package/src/core/provenance_buffer.ts +0 -102
  33. package/src/core/readers/_helpers.ts +0 -273
  34. package/src/core/readers/action_description.ts +0 -17
  35. package/src/core/readers/action_economy_events.ts +0 -149
  36. package/src/core/readers/actor_body_swaps.ts +0 -62
  37. package/src/core/readers/actor_snapshot.ts +0 -197
  38. package/src/core/readers/actor_states.ts +0 -163
  39. package/src/core/readers/actors_and_bodies.ts +0 -179
  40. package/src/core/readers/affordance_cue.ts +0 -59
  41. package/src/core/readers/affordance_defaults.ts +0 -158
  42. package/src/core/readers/affordance_group_membership.ts +0 -67
  43. package/src/core/readers/affordance_input.ts +0 -129
  44. package/src/core/readers/affordance_reference.ts +0 -41
  45. package/src/core/readers/apply_consequences.ts +0 -54
  46. package/src/core/readers/audience_trace_presentation.ts +0 -62
  47. package/src/core/readers/bounded_collection.ts +0 -29
  48. package/src/core/readers/bundle_definitions.ts +0 -74
  49. package/src/core/readers/bundle_entities.ts +0 -62
  50. package/src/core/readers/co_location.ts +0 -71
  51. package/src/core/readers/combat_session.ts +0 -124
  52. package/src/core/readers/combat_session_active.ts +0 -44
  53. package/src/core/readers/combat_session_feedback.ts +0 -37
  54. package/src/core/readers/combat_session_grid.ts +0 -117
  55. package/src/core/readers/combat_session_roster.ts +0 -98
  56. package/src/core/readers/combat_session_types.ts +0 -51
  57. package/src/core/readers/condition_deltas.ts +0 -53
  58. package/src/core/readers/container_contents.ts +0 -92
  59. package/src/core/readers/dialogue_guide.ts +0 -99
  60. package/src/core/readers/dialogue_prompt_presentation.ts +0 -90
  61. package/src/core/readers/driver_control.ts +0 -64
  62. package/src/core/readers/entity_art.ts +0 -219
  63. package/src/core/readers/entity_containment.ts +0 -119
  64. package/src/core/readers/equipment.ts +0 -99
  65. package/src/core/readers/intervention_windows.ts +0 -136
  66. package/src/core/readers/inventory_query.ts +0 -145
  67. package/src/core/readers/item_detail.ts +0 -198
  68. package/src/core/readers/location_snapshot.ts +0 -216
  69. package/src/core/readers/manifest_apply_provenance.ts +0 -32
  70. package/src/core/readers/manifest_export.ts +0 -81
  71. package/src/core/readers/manipulation_context.ts +0 -475
  72. package/src/core/readers/map_layers.ts +0 -49
  73. package/src/core/readers/metadata_rows.ts +0 -56
  74. package/src/core/readers/object_state.ts +0 -124
  75. package/src/core/readers/observer_knowledge.ts +0 -41
  76. package/src/core/readers/observer_place_knowledge.ts +0 -37
  77. package/src/core/readers/observer_trace_knowledge.ts +0 -45
  78. package/src/core/readers/outcome_template.ts +0 -41
  79. package/src/core/readers/place_topology.ts +0 -109
  80. package/src/core/readers/reaction_options.ts +0 -156
  81. package/src/core/readers/resource_deltas.ts +0 -47
  82. package/src/core/readers/scene.ts +0 -275
  83. package/src/core/readers/seats.ts +0 -33
  84. package/src/core/readers/self.ts +0 -245
  85. package/src/core/readers/self_capabilities.ts +0 -159
  86. package/src/core/readers/self_economy.ts +0 -101
  87. package/src/core/readers/self_economy_budget.ts +0 -93
  88. package/src/core/readers/self_evaluations.ts +0 -128
  89. package/src/core/readers/self_identity.ts +0 -104
  90. package/src/core/readers/sense_context.ts +0 -112
  91. package/src/core/readers/session.ts +0 -207
  92. package/src/core/readers/session_detail.ts +0 -211
  93. package/src/core/readers/session_status.ts +0 -68
  94. package/src/core/readers/spatial_environment_state.ts +0 -74
  95. package/src/core/readers/spatial_niche_attachments.ts +0 -28
  96. package/src/core/readers/substrate_definitions.ts +0 -27
  97. package/src/core/readers/suggest_next_action.ts +0 -72
  98. package/src/core/readers/surface_membership.ts +0 -78
  99. package/src/core/readers/tag_reads.ts +0 -54
  100. package/src/core/readers/trace_query.ts +0 -120
  101. package/src/core/readers/trace_response.ts +0 -80
  102. package/src/core/readers/traces.ts +0 -124
  103. package/src/core/readers/travel_session.ts +0 -88
  104. package/src/core/readers/turn_state.ts +0 -34
  105. package/src/core/readers/world_events.ts +0 -43
  106. package/src/core/readers/world_status.ts +0 -63
  107. package/src/core/reducers/manipulation_args.ts +0 -239
  108. package/src/core/reducers/manipulation_receipt.ts +0 -66
  109. package/src/core/reducers/r_actor_wake_up.ts +0 -32
  110. package/src/core/reducers/r_inscribe_trace.ts +0 -109
  111. package/src/core/reducers/r_manipulate.ts +0 -163
  112. package/src/core/reducers/r_move.ts +0 -155
  113. package/src/core/reducers/r_react.ts +0 -143
  114. package/src/core/reducers/r_release_claim.ts +0 -81
  115. package/src/core/reducers/r_sense.ts +0 -84
  116. package/src/core/reducers/r_session_close.ts +0 -130
  117. package/src/core/reducers/r_session_move.ts +0 -116
  118. package/src/core/reducers/r_session_open.ts +0 -91
  119. package/src/core/reducers/session_lookup.ts +0 -64
  120. package/src/core/reducers/tick.ts +0 -65
  121. package/src/core/reducers/trace_lookup.ts +0 -29
  122. package/src/core/reducers/transport.ts +0 -84
  123. package/src/core/resolve.ts +0 -228
  124. package/src/core/shape_telemetry.ts +0 -146
  125. package/src/core/snapshot_rows.ts +0 -109
  126. package/src/core/tick_cadence.ts +0 -61
  127. package/src/core/types.ts +0 -501
  128. package/src/core/watch_provenance.ts +0 -113
  129. package/src/core/world-contract/classify.ts +0 -38
  130. package/src/core/world-contract/index.ts +0 -12
  131. package/src/core/world-contract/normalise.ts +0 -574
  132. package/src/core/world-contract/runtime.ts +0 -144
  133. package/src/core/world-contract/served.ts +0 -173
  134. package/src/core/world-contract/strict-reducers.ts +0 -14
  135. package/src/core/world-contract/typetext.ts +0 -94
  136. package/src/core/world_time.ts +0 -22
  137. package/src/index.ts +0 -262
  138. package/src/manifest-apply.ts +0 -497
  139. package/src/provenance.ts +0 -568
  140. package/src/reader-manifest.ts +0 -338
  141. package/src/readers.ts +0 -392
  142. package/src/replay.ts +0 -515
  143. package/src/watch-buffer.ts +0 -438
  144. package/src/world-events/builder.ts +0 -1042
package/src/replay.ts DELETED
@@ -1,515 +0,0 @@
1
- // Pure snapshot replay helpers.
2
- //
3
- // This entry intentionally has no live SpacetimeDB connection import and no
4
- // reducer surface. Reviewer/demo apps can replay captured rows without pulling
5
- // in connection construction or mutation-capable handles.
6
-
7
- interface TableHandle {
8
- iter(): Iterable<Record<string, unknown>>;
9
- /** Optional host delivery context and inserted row; snapshot-only hosts may omit both. */
10
- onInsert?: (cb: (context?: unknown, row?: unknown) => void) => void;
11
- removeOnInsert?: (cb: (context?: unknown, row?: unknown) => void) => void;
12
- onDelete?: (cb: () => void) => void;
13
- removeOnDelete?: (cb: () => void) => void;
14
- onUpdate?: (cb: () => void) => void;
15
- removeOnUpdate?: (cb: () => void) => void;
16
- }
17
-
18
- export interface SnapshotDb {
19
- [accessor: string]: TableHandle | undefined;
20
- }
21
-
22
- export type SnapshotFixtureTables = Record<string, Iterable<Record<string, unknown>>>;
23
-
24
- export interface SnapshotCaptureFrame {
25
- kind: "spellkave.snapshot_frame";
26
- version: 1;
27
- /** Logical world tick represented by this checkpoint. */
28
- tick: number;
29
- /** Binding-layer table rows, keyed by generated table accessor name. */
30
- tables: Record<string, Record<string, unknown>[]>;
31
- }
32
-
33
- export interface WorldEventRow {
34
- id: string;
35
- tick: number;
36
- kind: string;
37
- summary?: string;
38
- }
39
-
40
- // ── Portable UI recordings ───────────────────────────────────────────────
41
-
42
- /**
43
- * A deliberately small, host-neutral envelope for a bounded client-side
44
- * recording. Surface adapters own the payload schema: this module only owns
45
- * retention, cursor semantics, JSON safety and the outer version marker.
46
- */
47
- export const RECORDING_ENVELOPE_KIND = "spellkave.recording" as const;
48
- export const RECORDING_ENVELOPE_VERSION = 2 as const;
49
-
50
- export type JsonPrimitive = string | number | boolean | null;
51
- export type JsonValue = JsonPrimitive | JsonValue[] | { [key: string]: JsonValue };
52
-
53
- export interface RecordingFrame<T extends JsonValue> {
54
- /** Stable reference for authored scenario transitions. */
55
- id: string;
56
- /** Monotonic insertion sequence. It disambiguates equal wall-clock times. */
57
- sequence: number;
58
- /** Client wall-clock time for retention and display, never world truth. */
59
- capturedAt: number;
60
- payload: T;
61
- }
62
-
63
- /** Deliberately allowlisted capture context. Never place account or credential data here. */
64
- export interface RecordingProvenance {
65
- source: "live" | "legacy" | "fixture";
66
- build?: string;
67
- title?: string;
68
- }
69
-
70
- export type RecordingCursor = { kind: "live" } | { kind: "paused"; sequence: number };
71
-
72
- export interface RecordingEnvelope<T extends JsonValue> {
73
- kind: typeof RECORDING_ENVELOPE_KIND;
74
- version: typeof RECORDING_ENVELOPE_VERSION;
75
- /** Stable recording identity; scenario layers refer to frame ids beneath it. */
76
- id: string;
77
- surface: string;
78
- capturedAt: number;
79
- provenance?: RecordingProvenance;
80
- frames: RecordingFrame<T>[];
81
- }
82
-
83
- export interface BoundedRecordingOptions {
84
- /** Maximum retained frames. Must be a positive integer. */
85
- limit: number;
86
- /** Optional wall-clock retention window. Omit for count-only retention. */
87
- maxAgeMs?: number;
88
- /** Test seam; defaults to Date.now. */
89
- now?: () => number;
90
- /** Stable identity to retain across exports. Omit to derive one at first export. */
91
- id?: string;
92
- }
93
-
94
- export interface RecordingExportOptions {
95
- /** Pins the recording identity when the buffer was constructed without one. */
96
- id?: string;
97
- /** Optional, safe capture context for checked-in recordings. */
98
- provenance?: RecordingProvenance;
99
- }
100
-
101
- /**
102
- * A small FIFO timeline. Pausing changes only which retained frame is read;
103
- * new live frames still enter the buffer, just like the Maps watch radar.
104
- * Every public payload is JSON-cloned at the boundary so callers cannot
105
- * mutate the history by retaining a reference.
106
- */
107
- export class BoundedRecording<T extends JsonValue> {
108
- private readonly limit: number;
109
- private readonly maxAgeMs: number | undefined;
110
- private readonly now: () => number;
111
- private stored: RecordingFrame<T>[] = [];
112
- private nextSequence = 1;
113
- private mode: RecordingCursor = { kind: "live" };
114
- private id: string | undefined;
115
-
116
- constructor(options: BoundedRecordingOptions) {
117
- if (!Number.isInteger(options.limit) || options.limit < 1) {
118
- throw new Error("recording limit must be a positive integer");
119
- }
120
- if (
121
- options.maxAgeMs !== undefined &&
122
- (!Number.isFinite(options.maxAgeMs) || options.maxAgeMs < 0)
123
- ) {
124
- throw new Error("recording maxAgeMs must be a non-negative finite number");
125
- }
126
- this.limit = options.limit;
127
- this.maxAgeMs = options.maxAgeMs;
128
- this.now = options.now ?? (() => Date.now());
129
- if (options.id !== undefined && !isStableId(options.id)) {
130
- throw new Error("recording id must be a bounded stable identifier");
131
- }
132
- this.id = options.id;
133
- }
134
-
135
- record(payload: T): RecordingFrame<T> {
136
- const sequence = this.nextSequence++;
137
- const capturedAt = this.now();
138
- const frame: RecordingFrame<T> = {
139
- id: `frame_${stableHash(canonicalJson({ sequence, capturedAt, payload }))}`,
140
- sequence,
141
- capturedAt,
142
- payload: cloneJson(payload),
143
- };
144
- if (this.stored.some((stored) => stored.id === frame.id)) {
145
- throw new Error("recording generated a duplicate frame id");
146
- }
147
- this.stored.push(frame);
148
- this.prune(frame.capturedAt);
149
- return cloneJson(frame);
150
- }
151
-
152
- pause(): void {
153
- const latest = this.stored.at(-1);
154
- if (latest !== undefined) this.mode = { kind: "paused", sequence: latest.sequence };
155
- }
156
-
157
- play(): void {
158
- this.mode = { kind: "live" };
159
- }
160
-
161
- scrub(sequence: number): void {
162
- if (!Number.isInteger(sequence) || this.stored.length === 0) return;
163
- const first = this.stored[0]?.sequence ?? 0;
164
- const last = this.stored.at(-1)?.sequence ?? 0;
165
- this.mode = { kind: "paused", sequence: Math.max(first, Math.min(last, sequence)) };
166
- }
167
-
168
- cursor(): RecordingCursor {
169
- return { ...this.mode };
170
- }
171
-
172
- frames(): RecordingFrame<T>[] {
173
- return cloneJson(this.stored);
174
- }
175
-
176
- frameAtCursor(): RecordingFrame<T> | null {
177
- if (this.stored.length === 0) return null;
178
- if (this.mode.kind === "live") return cloneJson(this.stored.at(-1) as RecordingFrame<T>);
179
- let found: RecordingFrame<T> | undefined;
180
- for (const frame of this.stored) {
181
- if (frame.sequence <= this.mode.sequence) found = frame;
182
- if (frame.sequence === this.mode.sequence) break;
183
- }
184
- return found === undefined ? null : cloneJson(found);
185
- }
186
-
187
- export(surface: string, options: RecordingExportOptions = {}): RecordingEnvelope<T> {
188
- if (!isSurface(surface))
189
- throw new Error("recording surface must be a bounded non-empty string");
190
- if (options.id !== undefined && !isStableId(options.id)) {
191
- throw new Error("recording id must be a bounded stable identifier");
192
- }
193
- if (this.id !== undefined && options.id !== undefined && this.id !== options.id) {
194
- throw new Error("recording id cannot change after it is established");
195
- }
196
- this.id ??= options.id ?? generatedRecordingId();
197
- if (!isProvenance(options.provenance))
198
- throw new Error("recording provenance is not allowlisted");
199
- const frames = this.frames();
200
- return {
201
- kind: RECORDING_ENVELOPE_KIND,
202
- version: RECORDING_ENVELOPE_VERSION,
203
- id: this.id,
204
- surface,
205
- capturedAt: this.now(),
206
- ...(options.provenance === undefined ? {} : { provenance: cloneJson(options.provenance) }),
207
- frames,
208
- };
209
- }
210
-
211
- private prune(now: number): void {
212
- while (this.stored.length > this.limit) this.stored.shift();
213
- if (this.maxAgeMs !== undefined) {
214
- const oldestAllowed = now - this.maxAgeMs;
215
- while ((this.stored[0]?.capturedAt ?? oldestAllowed) < oldestAllowed) this.stored.shift();
216
- }
217
- if (
218
- this.mode.kind === "paused" &&
219
- this.stored.length > 0 &&
220
- this.mode.sequence < (this.stored[0]?.sequence ?? 0)
221
- ) {
222
- this.mode = { kind: "paused", sequence: this.stored[0]?.sequence ?? this.mode.sequence };
223
- }
224
- }
225
- }
226
-
227
- /** Parse the shared envelope, then delegate the surface-specific payload check. */
228
- export function parseRecordingEnvelope<T extends JsonValue>(
229
- value: unknown,
230
- options: { surface: string; parsePayload: (value: JsonValue) => T | null },
231
- ): RecordingEnvelope<T> | null {
232
- if (!isJsonRecord(value)) return null;
233
- if (value.kind !== RECORDING_ENVELOPE_KIND || !isJsonValue(value.version)) return null;
234
- if (value.version === 1) return migrateV1(value, options);
235
- if (
236
- value.version !== RECORDING_ENVELOPE_VERSION ||
237
- !hasOnlyKeys(value, ["kind", "version", "id", "surface", "capturedAt", "provenance", "frames"])
238
- )
239
- return null;
240
- const { id, capturedAt } = value;
241
- if (
242
- !isStableId(id) ||
243
- value.surface !== options.surface ||
244
- !isSurface(value.surface) ||
245
- !isFiniteNumber(capturedAt) ||
246
- !isProvenance(value.provenance) ||
247
- !Array.isArray(value.frames)
248
- )
249
- return null;
250
- return parseFrames(value.frames, options, { id, capturedAt, provenance: value.provenance });
251
- }
252
-
253
- function migrateV1<T extends JsonValue>(
254
- value: { [key: string]: JsonValue },
255
- options: { surface: string; parsePayload: (value: JsonValue) => T | null },
256
- ): RecordingEnvelope<T> | null {
257
- if (!hasOnlyKeys(value, ["kind", "version", "surface", "capturedAt", "frames"])) return null;
258
- const { capturedAt } = value;
259
- if (
260
- value.surface !== options.surface ||
261
- !isSurface(value.surface) ||
262
- !isFiniteNumber(capturedAt) ||
263
- !Array.isArray(value.frames)
264
- )
265
- return null;
266
- const id = `legacy_${stableHash(canonicalJson(value))}`;
267
- return parseFrames(value.frames, options, {
268
- id,
269
- capturedAt,
270
- provenance: { source: "legacy" },
271
- migrateLegacyFrames: true,
272
- });
273
- }
274
-
275
- function parseFrames<T extends JsonValue>(
276
- rawFrames: JsonValue[],
277
- options: { surface: string; parsePayload: (value: JsonValue) => T | null },
278
- envelope: {
279
- id: string;
280
- capturedAt: number;
281
- provenance: RecordingProvenance | undefined;
282
- migrateLegacyFrames?: boolean;
283
- },
284
- ): RecordingEnvelope<T> | null {
285
- if (rawFrames.length > MAX_RECORDING_FRAMES) return null;
286
- let previous = 0;
287
- const ids = new Set<string>();
288
- const frames: RecordingFrame<T>[] = [];
289
- for (const raw of rawFrames) {
290
- if (!isJsonRecord(raw)) return null;
291
- const allowedKeys = envelope.migrateLegacyFrames
292
- ? ["sequence", "capturedAt", "payload"]
293
- : ["id", "sequence", "capturedAt", "payload"];
294
- if (!hasOnlyKeys(raw, allowedKeys)) return null;
295
- const frameId = envelope.migrateLegacyFrames
296
- ? `legacy_frame_${stableHash(`${envelope.id}:${canonicalJson(raw)}`)}`
297
- : raw.id;
298
- const sequence = raw.sequence;
299
- const capturedAt = raw.capturedAt;
300
- if (
301
- !isStableId(frameId) ||
302
- ids.has(frameId) ||
303
- typeof sequence !== "number" ||
304
- !Number.isInteger(sequence) ||
305
- sequence <= previous ||
306
- typeof capturedAt !== "number" ||
307
- !Number.isFinite(capturedAt)
308
- )
309
- return null;
310
- if (!("payload" in raw) || !isJsonValue(raw.payload)) return null;
311
- const payload = options.parsePayload(raw.payload);
312
- if (payload === null) return null;
313
- frames.push({ id: frameId, sequence, capturedAt, payload: cloneJson(payload) });
314
- ids.add(frameId);
315
- previous = sequence;
316
- }
317
- return {
318
- kind: RECORDING_ENVELOPE_KIND,
319
- version: RECORDING_ENVELOPE_VERSION,
320
- id: envelope.id,
321
- surface: options.surface,
322
- capturedAt: envelope.capturedAt,
323
- ...(envelope.provenance === undefined ? {} : { provenance: cloneJson(envelope.provenance) }),
324
- frames,
325
- };
326
- }
327
-
328
- function isJsonRecord(value: unknown): value is { [key: string]: JsonValue } {
329
- return typeof value === "object" && value !== null && !Array.isArray(value);
330
- }
331
-
332
- function isJsonValue(value: unknown): value is JsonValue {
333
- if (value === null || typeof value === "string" || typeof value === "boolean") return true;
334
- if (typeof value === "number") return Number.isFinite(value);
335
- if (Array.isArray(value)) return value.every(isJsonValue);
336
- if (!isJsonRecord(value)) return false;
337
- return Object.values(value).every(isJsonValue);
338
- }
339
-
340
- const STABLE_ID = /^[a-z][a-z0-9_-]{0,127}$/;
341
- const MAX_METADATA_TEXT_LENGTH = 200;
342
- const MAX_RECORDING_FRAMES = 10_000;
343
- let generatedRecordingCount = 0;
344
-
345
- function isStableId(value: unknown): value is string {
346
- return typeof value === "string" && STABLE_ID.test(value);
347
- }
348
-
349
- function isSurface(value: unknown): value is string {
350
- return (
351
- typeof value === "string" && value.trim() !== "" && value.length <= MAX_METADATA_TEXT_LENGTH
352
- );
353
- }
354
-
355
- function isFiniteNumber(value: unknown): value is number {
356
- return typeof value === "number" && Number.isFinite(value);
357
- }
358
-
359
- function hasOnlyKeys(value: { [key: string]: JsonValue }, allowed: readonly string[]): boolean {
360
- return Object.keys(value).every((key) => allowed.includes(key));
361
- }
362
-
363
- function isProvenance(value: unknown): value is RecordingProvenance | undefined {
364
- if (value === undefined) return true;
365
- if (!isJsonRecord(value) || !hasOnlyKeys(value, ["source", "build", "title"])) return false;
366
- if (value.source !== "live" && value.source !== "legacy" && value.source !== "fixture")
367
- return false;
368
- return [value.build, value.title].every(
369
- (part) =>
370
- part === undefined ||
371
- (typeof part === "string" && part.trim() !== "" && part.length <= MAX_METADATA_TEXT_LENGTH),
372
- );
373
- }
374
-
375
- function generatedRecordingId(): string {
376
- const uuid = globalThis.crypto?.randomUUID?.();
377
- if (uuid !== undefined) return `recording_${uuid}`;
378
- generatedRecordingCount += 1;
379
- return `recording_${stableHash(`${Date.now()}:${generatedRecordingCount}:${Math.random()}`)}`;
380
- }
381
-
382
- /** Canonical object order keeps v1 migration ids stable across JSON reformatting. */
383
- function canonicalJson(value: JsonValue): string {
384
- if (value === null || typeof value !== "object") return JSON.stringify(value);
385
- if (Array.isArray(value)) return `[${value.map(canonicalJson).join(",")}]`;
386
- return `{${Object.keys(value)
387
- .sort()
388
- .map((key) => `${JSON.stringify(key)}:${canonicalJson(value[key] as JsonValue)}`)
389
- .join(",")}}`;
390
- }
391
-
392
- /** Small deterministic identifier hash; this is an identity aid, not a security primitive. */
393
- function stableHash(value: string): string {
394
- let first = 0x811c9dc5;
395
- let second = 0x01000193;
396
- for (let index = 0; index < value.length; index += 1) {
397
- const code = value.charCodeAt(index);
398
- first = Math.imul(first ^ code, 0x01000193);
399
- second = Math.imul(second ^ code, 0x811c9dc5);
400
- }
401
- return `${(first >>> 0).toString(36)}${(second >>> 0).toString(36)}`;
402
- }
403
-
404
- function cloneJson<T>(value: T): T {
405
- return JSON.parse(JSON.stringify(value)) as T;
406
- }
407
-
408
- /** Build a host-neutral reader snapshot from plain fixture rows. */
409
- export function snapshotDbFromFixture(tables: SnapshotFixtureTables): SnapshotDb {
410
- const db: SnapshotDb = {};
411
- for (const [tableName, rows] of Object.entries(tables)) {
412
- db[tableName] = {
413
- iter: () => rows,
414
- };
415
- }
416
- return db;
417
- }
418
-
419
- export function captureSnapshotFrame(
420
- db: SnapshotDb,
421
- args: { tick: number; tables: readonly string[] },
422
- ): SnapshotCaptureFrame {
423
- const tables: SnapshotCaptureFrame["tables"] = {};
424
- for (const tableName of args.tables) {
425
- tables[tableName] = Array.from(db[tableName]?.iter() ?? []).map(
426
- (row) => toFixtureValue(row) as Record<string, unknown>,
427
- );
428
- }
429
- return {
430
- kind: "spellkave.snapshot_frame",
431
- version: 1,
432
- tick: args.tick,
433
- tables,
434
- };
435
- }
436
-
437
- export function snapshotDbFromCaptureFrame(frame: SnapshotCaptureFrame): SnapshotDb {
438
- return snapshotDbFromFixture(frame.tables);
439
- }
440
-
441
- export function readRecentEvents(db: SnapshotDb, n: number): WorldEventRow[] {
442
- if (n <= 0) return [];
443
- // `world_event` is private (#915 PR-8); a live connection populates the
444
- // per-caller `visible_world_event` view instead. Try the new accessor
445
- // first, falling back to the raw name so pre-#915-PR-8 frozen captures
446
- // (e.g. apps/world-review/src/fixtures/review-capture.json) keyed under
447
- // the old accessor still replay correctly.
448
- const all = rows(db, "visible_world_event", "world_event").map(toEventRow);
449
- all.sort((a, b) => (b.tick !== a.tick ? b.tick - a.tick : b.id.localeCompare(a.id)));
450
- return all.slice(0, n);
451
- }
452
-
453
- function rows(db: SnapshotDb, ...accessors: string[]): Record<string, unknown>[] {
454
- for (const accessor of accessors) {
455
- const handle = db[accessor];
456
- if (handle !== undefined) return Array.from(handle.iter());
457
- }
458
- return [];
459
- }
460
-
461
- function toEventRow(row: Record<string, unknown>): WorldEventRow {
462
- const summary = optString(row.summary);
463
- const out: WorldEventRow = {
464
- id: asString(row.id),
465
- tick: asNumber(row.tick),
466
- kind: kindToString(row.kind),
467
- };
468
- if (summary !== undefined) out.summary = summary;
469
- return out;
470
- }
471
-
472
- function asString(value: unknown): string {
473
- return value === undefined || value === null ? "" : String(value);
474
- }
475
-
476
- function asNumber(value: unknown, fallback = 0): number {
477
- if (typeof value === "number") return value;
478
- if (typeof value === "bigint") return Number(value);
479
- if (typeof value === "string") {
480
- const n = Number(value);
481
- return Number.isFinite(n) ? n : fallback;
482
- }
483
- return fallback;
484
- }
485
-
486
- function optString(value: unknown): string | undefined {
487
- if (value === undefined || value === null) return undefined;
488
- if (value && typeof value === "object") {
489
- const some = (value as { some?: unknown }).some;
490
- if (some !== undefined && some !== null) return String(some);
491
- }
492
- const s = String(value);
493
- return s.length > 0 ? s : undefined;
494
- }
495
-
496
- function kindToString(value: unknown): string {
497
- if (typeof value === "string") return value;
498
- if (value && typeof value === "object") {
499
- const tag = (value as { tag?: unknown }).tag;
500
- if (typeof tag === "string") return tag;
501
- }
502
- return asString(value);
503
- }
504
-
505
- function toFixtureValue(value: unknown): unknown {
506
- if (typeof value === "bigint") {
507
- const asNumber = Number(value);
508
- return Number.isSafeInteger(asNumber) ? asNumber : value.toString();
509
- }
510
- if (Array.isArray(value)) return value.map((item) => toFixtureValue(item));
511
- if (value === null || typeof value !== "object") return value;
512
- return Object.fromEntries(
513
- Object.entries(value).map(([key, item]) => [key, toFixtureValue(item)]),
514
- );
515
- }