@spellkave/sdk 0.0.0-stage → 0.1.0

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/LICENSE +89 -0
  2. package/README.md +155 -2
  3. package/package.json +63 -4
  4. package/src/binding_rows.ts +186 -0
  5. package/src/connection.ts +964 -0
  6. package/src/core/actor.ts +62 -0
  7. package/src/core/actor_control.ts +193 -0
  8. package/src/core/actor_control_query_methods.ts +101 -0
  9. package/src/core/actor_control_reaction_methods.ts +79 -0
  10. package/src/core/actor_control_sense_methods.ts +81 -0
  11. package/src/core/actor_control_source.ts +57 -0
  12. package/src/core/actor_session_methods.ts +226 -0
  13. package/src/core/binding_drift.ts +301 -0
  14. package/src/core/credential.ts +259 -0
  15. package/src/core/driver_control.ts +54 -0
  16. package/src/core/effective_environment_state.ts +71 -0
  17. package/src/core/factored_manipulation_attempt.ts +158 -0
  18. package/src/core/ids.ts +60 -0
  19. package/src/core/interaction/canonical.ts +15 -0
  20. package/src/core/interaction/fingerprint.ts +118 -0
  21. package/src/core/interaction/index.ts +31 -0
  22. package/src/core/interaction/intent.ts +284 -0
  23. package/src/core/interaction/outcome.ts +67 -0
  24. package/src/core/interaction/rejection_ledger.ts +108 -0
  25. package/src/core/kernel_contract.generated.ts +10 -0
  26. package/src/core/log.ts +23 -0
  27. package/src/core/movement.ts +111 -0
  28. package/src/core/node-io.ts +208 -0
  29. package/src/core/paths.ts +220 -0
  30. package/src/core/profile.ts +270 -0
  31. package/src/core/profiles.ts +9 -0
  32. package/src/core/provenance_buffer.ts +102 -0
  33. package/src/core/readers/_helpers.ts +273 -0
  34. package/src/core/readers/action_description.ts +17 -0
  35. package/src/core/readers/action_economy_events.ts +149 -0
  36. package/src/core/readers/actor_body_swaps.ts +62 -0
  37. package/src/core/readers/actor_snapshot.ts +197 -0
  38. package/src/core/readers/actor_states.ts +163 -0
  39. package/src/core/readers/actors_and_bodies.ts +179 -0
  40. package/src/core/readers/affordance_cue.ts +59 -0
  41. package/src/core/readers/affordance_defaults.ts +158 -0
  42. package/src/core/readers/affordance_group_membership.ts +67 -0
  43. package/src/core/readers/affordance_input.ts +129 -0
  44. package/src/core/readers/affordance_reference.ts +41 -0
  45. package/src/core/readers/apply_consequences.ts +54 -0
  46. package/src/core/readers/audience_trace_presentation.ts +62 -0
  47. package/src/core/readers/bounded_collection.ts +29 -0
  48. package/src/core/readers/bundle_definitions.ts +74 -0
  49. package/src/core/readers/bundle_entities.ts +62 -0
  50. package/src/core/readers/co_location.ts +71 -0
  51. package/src/core/readers/combat_session.ts +124 -0
  52. package/src/core/readers/combat_session_active.ts +44 -0
  53. package/src/core/readers/combat_session_feedback.ts +37 -0
  54. package/src/core/readers/combat_session_grid.ts +117 -0
  55. package/src/core/readers/combat_session_roster.ts +98 -0
  56. package/src/core/readers/combat_session_types.ts +51 -0
  57. package/src/core/readers/condition_deltas.ts +53 -0
  58. package/src/core/readers/container_contents.ts +92 -0
  59. package/src/core/readers/dialogue_guide.ts +99 -0
  60. package/src/core/readers/dialogue_prompt_presentation.ts +90 -0
  61. package/src/core/readers/driver_control.ts +64 -0
  62. package/src/core/readers/entity_art.ts +219 -0
  63. package/src/core/readers/entity_containment.ts +119 -0
  64. package/src/core/readers/equipment.ts +99 -0
  65. package/src/core/readers/intervention_windows.ts +136 -0
  66. package/src/core/readers/inventory_query.ts +145 -0
  67. package/src/core/readers/item_detail.ts +198 -0
  68. package/src/core/readers/location_snapshot.ts +216 -0
  69. package/src/core/readers/manifest_apply_provenance.ts +32 -0
  70. package/src/core/readers/manifest_export.ts +81 -0
  71. package/src/core/readers/manipulation_context.ts +475 -0
  72. package/src/core/readers/map_layers.ts +49 -0
  73. package/src/core/readers/metadata_rows.ts +56 -0
  74. package/src/core/readers/object_state.ts +124 -0
  75. package/src/core/readers/observer_knowledge.ts +41 -0
  76. package/src/core/readers/observer_place_knowledge.ts +37 -0
  77. package/src/core/readers/observer_trace_knowledge.ts +45 -0
  78. package/src/core/readers/outcome_template.ts +41 -0
  79. package/src/core/readers/place_topology.ts +109 -0
  80. package/src/core/readers/reaction_options.ts +156 -0
  81. package/src/core/readers/resource_deltas.ts +47 -0
  82. package/src/core/readers/scene.ts +275 -0
  83. package/src/core/readers/seats.ts +33 -0
  84. package/src/core/readers/self.ts +245 -0
  85. package/src/core/readers/self_capabilities.ts +159 -0
  86. package/src/core/readers/self_economy.ts +101 -0
  87. package/src/core/readers/self_economy_budget.ts +93 -0
  88. package/src/core/readers/self_evaluations.ts +128 -0
  89. package/src/core/readers/self_identity.ts +104 -0
  90. package/src/core/readers/sense_context.ts +112 -0
  91. package/src/core/readers/session.ts +207 -0
  92. package/src/core/readers/session_detail.ts +211 -0
  93. package/src/core/readers/session_status.ts +68 -0
  94. package/src/core/readers/spatial_environment_state.ts +74 -0
  95. package/src/core/readers/spatial_niche_attachments.ts +28 -0
  96. package/src/core/readers/substrate_definitions.ts +27 -0
  97. package/src/core/readers/suggest_next_action.ts +72 -0
  98. package/src/core/readers/surface_membership.ts +78 -0
  99. package/src/core/readers/tag_reads.ts +54 -0
  100. package/src/core/readers/trace_query.ts +120 -0
  101. package/src/core/readers/trace_response.ts +80 -0
  102. package/src/core/readers/traces.ts +124 -0
  103. package/src/core/readers/travel_session.ts +88 -0
  104. package/src/core/readers/turn_state.ts +34 -0
  105. package/src/core/readers/world_events.ts +43 -0
  106. package/src/core/readers/world_status.ts +63 -0
  107. package/src/core/reducers/manipulation_args.ts +239 -0
  108. package/src/core/reducers/manipulation_receipt.ts +66 -0
  109. package/src/core/reducers/r_actor_wake_up.ts +32 -0
  110. package/src/core/reducers/r_inscribe_trace.ts +109 -0
  111. package/src/core/reducers/r_manipulate.ts +163 -0
  112. package/src/core/reducers/r_move.ts +155 -0
  113. package/src/core/reducers/r_react.ts +143 -0
  114. package/src/core/reducers/r_release_claim.ts +81 -0
  115. package/src/core/reducers/r_sense.ts +84 -0
  116. package/src/core/reducers/r_session_close.ts +130 -0
  117. package/src/core/reducers/r_session_move.ts +116 -0
  118. package/src/core/reducers/r_session_open.ts +91 -0
  119. package/src/core/reducers/session_lookup.ts +64 -0
  120. package/src/core/reducers/tick.ts +65 -0
  121. package/src/core/reducers/trace_lookup.ts +29 -0
  122. package/src/core/reducers/transport.ts +84 -0
  123. package/src/core/resolve.ts +228 -0
  124. package/src/core/shape_telemetry.ts +146 -0
  125. package/src/core/snapshot_rows.ts +109 -0
  126. package/src/core/tick_cadence.ts +61 -0
  127. package/src/core/types.ts +501 -0
  128. package/src/core/watch_provenance.ts +113 -0
  129. package/src/core/world-contract/classify.ts +38 -0
  130. package/src/core/world-contract/index.ts +12 -0
  131. package/src/core/world-contract/normalise.ts +574 -0
  132. package/src/core/world-contract/runtime.ts +144 -0
  133. package/src/core/world-contract/served.ts +173 -0
  134. package/src/core/world-contract/strict-reducers.ts +14 -0
  135. package/src/core/world-contract/typetext.ts +94 -0
  136. package/src/core/world_time.ts +22 -0
  137. package/src/index.ts +262 -0
  138. package/src/manifest-apply.ts +497 -0
  139. package/src/provenance.ts +568 -0
  140. package/src/reader-manifest.ts +338 -0
  141. package/src/readers.ts +392 -0
  142. package/src/replay.ts +515 -0
  143. package/src/watch-buffer.ts +438 -0
  144. package/src/world-events/builder.ts +1042 -0
@@ -0,0 +1,226 @@
1
+ import type { SnapshotDb } from "../connection";
2
+ import { observeReducerAttempt } from "../provenance";
3
+ import type {
4
+ ActorClientReducers,
5
+ RAdvanceTurnFn,
6
+ RSessionCloseFn,
7
+ RSessionMoveFn,
8
+ RSessionOpenFn,
9
+ } from "./actor_control_source";
10
+ import type { DriverToken } from "./driver_control";
11
+ import type { ProvenanceRingBuffer } from "./provenance_buffer";
12
+ import { readActiveSessionWithRosterForParticipant } from "./readers/session";
13
+ import { rSessionCloseWrapper } from "./reducers/r_session_close";
14
+ import { rSessionMoveWrapper } from "./reducers/r_session_move";
15
+ import { rSessionOpenWrapper } from "./reducers/r_session_open";
16
+ import { firstPopulatedHandle } from "./reducers/session_lookup";
17
+ import type { TickIntervalEstimator } from "./tick_cadence";
18
+ import type {
19
+ ActorClientOptions,
20
+ AdvanceTurnResult,
21
+ SessionCloseResult,
22
+ SessionMoveResult,
23
+ SessionOpenResult,
24
+ } from "./types";
25
+
26
+ export interface ActorSessionMethodContext {
27
+ reducers?: ActorClientReducers;
28
+ options?: ActorClientOptions;
29
+ resolvedActorId: () => string;
30
+ snapshotDb: () => SnapshotDb;
31
+ timeoutMs: number;
32
+ pollMs: number;
33
+ estimator?: TickIntervalEstimator;
34
+ provenanceBuffer?: ProvenanceRingBuffer;
35
+ }
36
+
37
+ export function createActorSessionMethods(context: ActorSessionMethodContext) {
38
+ const rSessionOpen: RSessionOpenFn =
39
+ context.options?.rSessionOpen ??
40
+ context.reducers?.rSessionOpen ??
41
+ (async () => {
42
+ throw new Error("rSessionOpen reducer is not configured");
43
+ });
44
+ const rSessionClose: RSessionCloseFn =
45
+ context.options?.rSessionClose ??
46
+ context.reducers?.rSessionClose ??
47
+ (async () => {
48
+ throw new Error("rSessionClose reducer is not configured");
49
+ });
50
+ const rSessionMove: RSessionMoveFn =
51
+ context.options?.rSessionMove ??
52
+ context.reducers?.rSessionMove ??
53
+ (async () => {
54
+ throw new Error("rSessionMove reducer is not configured");
55
+ });
56
+ const rAdvanceTurn: RAdvanceTurnFn | undefined =
57
+ context.options?.rAdvanceTurn ?? context.reducers?.rAdvanceTurn;
58
+
59
+ const advanceTurn = async (sessionId: bigint): Promise<AdvanceTurnResult> => {
60
+ if (rAdvanceTurn === undefined) {
61
+ return { status: "rejected", sessionId, reason: "rAdvanceTurn reducer is not configured" };
62
+ }
63
+ if (sessionId !== 0n) {
64
+ const before = findSession(context.snapshotDb(), sessionId);
65
+ const result = await observeReducerAttempt<AdvanceTurnSnapshot | null>({
66
+ db: context.snapshotDb,
67
+ subjectId: context.resolvedActorId(),
68
+ invoke: () => rAdvanceTurn({ sessionId }),
69
+ successPredicate: (db) => {
70
+ const after = findSession(db, sessionId);
71
+ if (before === undefined) return after !== undefined;
72
+ // An advance is observed when the turn moved to someone else, the
73
+ // session re-stamped its advance tick, the advance terminated the
74
+ // session (lifecycle), or the turn counter moved. The last two
75
+ // matter under an authored turn_eligibility_pred (ADR-0143): when
76
+ // the caller is the only eligible participant it is handed its own
77
+ // turn back in the same tick, so neither currentActor nor
78
+ // lastAdvancedAt changes.
79
+ return (
80
+ after !== undefined &&
81
+ (after.currentActor !== before.currentActor ||
82
+ after.lastAdvancedAt !== before.lastAdvancedAt ||
83
+ after.lifecycle !== before.lifecycle ||
84
+ after.turn !== before.turn)
85
+ );
86
+ },
87
+ collectSnapshot: (db) => findSession(db, sessionId) ?? null,
88
+ timeoutMs: context.timeoutMs,
89
+ pollMs: context.pollMs,
90
+ tickEstimator: context.estimator,
91
+ provenanceBuffer: context.provenanceBuffer,
92
+ telemetry: context.options?.reducerAttemptTelemetry,
93
+ telemetryAttributes: {
94
+ "spellkave.reducer": "r_advance_turn",
95
+ "spellkave.actor_id": context.resolvedActorId(),
96
+ },
97
+ });
98
+ if (result.status === "success") return { status: "success", sessionId };
99
+ return {
100
+ status: "rejected",
101
+ sessionId,
102
+ reason:
103
+ result.status === "rejected"
104
+ ? "r_advance_turn rejected by server"
105
+ : `r_advance_turn for session '${sessionId}' not observed within ${context.timeoutMs}ms`,
106
+ };
107
+ }
108
+ try {
109
+ await rAdvanceTurn({ sessionId });
110
+ return { status: "success", sessionId };
111
+ } catch (err) {
112
+ return { status: "rejected", sessionId, reason: String(err) };
113
+ }
114
+ };
115
+
116
+ return {
117
+ sessionOpen(sessionDefId: string, participantsCsv = ""): Promise<SessionOpenResult> {
118
+ return rSessionOpenWrapper(
119
+ context.resolvedActorId(),
120
+ sessionDefId,
121
+ participantsCsv,
122
+ context.snapshotDb,
123
+ rSessionOpen,
124
+ context.timeoutMs,
125
+ context.pollMs,
126
+ context.estimator,
127
+ context.provenanceBuffer,
128
+ );
129
+ },
130
+ sessionClose(
131
+ sessionId: bigint,
132
+ outcome: string,
133
+ driverTokens?: readonly DriverToken[],
134
+ ): Promise<SessionCloseResult> {
135
+ return rSessionCloseWrapper(
136
+ context.resolvedActorId(),
137
+ sessionId,
138
+ outcome,
139
+ context.snapshotDb,
140
+ rSessionClose,
141
+ context.timeoutMs,
142
+ context.pollMs,
143
+ context.estimator,
144
+ context.provenanceBuffer,
145
+ context.options?.driverToken,
146
+ driverTokens,
147
+ );
148
+ },
149
+ sessionMove(sessionId: bigint, moveTemplateId: string): Promise<SessionMoveResult> {
150
+ return rSessionMoveWrapper(
151
+ context.resolvedActorId(),
152
+ sessionId,
153
+ moveTemplateId,
154
+ context.snapshotDb,
155
+ rSessionMove,
156
+ context.timeoutMs,
157
+ context.pollMs,
158
+ context.estimator,
159
+ context.provenanceBuffer,
160
+ );
161
+ },
162
+ advanceTurn,
163
+ async endTurn(): Promise<AdvanceTurnResult> {
164
+ const actorId = context.resolvedActorId();
165
+ const active = readActiveSessionWithRosterForParticipant(context.snapshotDb(), actorId);
166
+ if (active === null) {
167
+ return { status: "rejected", sessionId: 0n, reason: "no active participant session" };
168
+ }
169
+ if (active.session.currentActor !== actorId) {
170
+ return {
171
+ status: "rejected",
172
+ sessionId: active.session.sessionId,
173
+ reason: "not your turn",
174
+ };
175
+ }
176
+ return advanceTurn(active.session.sessionId);
177
+ },
178
+ };
179
+ }
180
+
181
+ interface AdvanceTurnSnapshot {
182
+ currentActor: string;
183
+ lastAdvancedAt: bigint;
184
+ lifecycle: string;
185
+ /** The world turn counter when the caller's cache carries the turn_state
186
+ * row scoped to this session; undefined otherwise. */
187
+ turn: bigint | undefined;
188
+ }
189
+
190
+ function findSession(db: SnapshotDb, sessionId: bigint): AdvanceTurnSnapshot | undefined {
191
+ const handle = firstPopulatedHandle(db, "visible_session", "session");
192
+ if (!handle) return undefined;
193
+ for (const raw of handle.iter()) {
194
+ const r = raw as unknown as {
195
+ sessionId: unknown;
196
+ currentActor: string;
197
+ lastAdvancedAt: unknown;
198
+ lifecycle?: string;
199
+ };
200
+ if (toBigInt(r.sessionId) === sessionId) {
201
+ return {
202
+ currentActor: r.currentActor,
203
+ lastAdvancedAt: toBigInt(r.lastAdvancedAt),
204
+ lifecycle: r.lifecycle ?? "",
205
+ turn: findSessionTurn(db, sessionId),
206
+ };
207
+ }
208
+ }
209
+ return undefined;
210
+ }
211
+
212
+ function findSessionTurn(db: SnapshotDb, sessionId: bigint): bigint | undefined {
213
+ const handle = firstPopulatedHandle(db, "visible_turn_state", "turn_state");
214
+ if (!handle) return undefined;
215
+ for (const raw of handle.iter()) {
216
+ const r = raw as unknown as { turn: unknown; scopeSessionId?: unknown };
217
+ if (r.scopeSessionId !== undefined && toBigInt(r.scopeSessionId) === sessionId) {
218
+ return toBigInt(r.turn);
219
+ }
220
+ }
221
+ return undefined;
222
+ }
223
+
224
+ function toBigInt(value: unknown): bigint {
225
+ return typeof value === "bigint" ? value : BigInt(String(value ?? 0));
226
+ }
@@ -0,0 +1,301 @@
1
+ // D6 binding-drift types + runtime schema surface fetch.
2
+
3
+ import {
4
+ classifyRuntimeChange,
5
+ foldCollisions,
6
+ foldNames,
7
+ normaliseItems,
8
+ type RuntimeChange,
9
+ type SchemaSnapshot,
10
+ type UncheckedItem,
11
+ } from "./world-contract/index.ts";
12
+
13
+ export interface SchemaSurface {
14
+ tables: string[];
15
+ reducers: string[];
16
+ }
17
+
18
+ export class SchemaInventoryError extends Error {
19
+ constructor(message: string) {
20
+ super(message);
21
+ this.name = "SchemaInventoryError";
22
+ }
23
+ }
24
+
25
+ export class BindingDriftError extends Error {
26
+ readonly expected: SchemaSurface;
27
+ readonly actual: SchemaSurface;
28
+ readonly mismatchKind: "table" | "reducer" | "row-shape";
29
+ readonly scope: "consumed";
30
+
31
+ constructor(
32
+ expected: SchemaSurface,
33
+ actual: SchemaSurface,
34
+ mismatchKind: "table" | "reducer" | "row-shape",
35
+ ) {
36
+ super(
37
+ `BindingDriftError(${mismatchKind}): strict schema surface mismatch — expected ${expected[mismatchKind === "table" ? "tables" : "reducers"].join(",")} got ${actual[mismatchKind === "table" ? "tables" : "reducers"].join(",")}`,
38
+ );
39
+ this.name = "BindingDriftError";
40
+ this.expected = expected;
41
+ this.actual = actual;
42
+ this.mismatchKind = mismatchKind;
43
+ this.scope = "consumed";
44
+ }
45
+ }
46
+
47
+ const REQUIRED_SECTIONS = ["Typespace", "Tables", "Reducers", "CaseConversionPolicy"] as const;
48
+ const ALLOWED_SECTIONS = [
49
+ ...REQUIRED_SECTIONS,
50
+ "Views",
51
+ "Types",
52
+ "Schedules",
53
+ "LifeCycleReducers",
54
+ "ExplicitNames",
55
+ // Array section. A module that defines a procedure publishes it.
56
+ // Absent on every module that defines none; required sections stay the four above.
57
+ "Procedures",
58
+ ] as const;
59
+ type SectionKind = (typeof ALLOWED_SECTIONS)[number];
60
+
61
+ function isSectionKind(kind: string): kind is SectionKind {
62
+ return (ALLOWED_SECTIONS as readonly string[]).includes(kind);
63
+ }
64
+
65
+ const OBJECT_SECTIONS = new Set<SectionKind>(["Typespace", "ExplicitNames"]);
66
+
67
+ function requireNonEmptyName(value: unknown, label: string, url: string): string {
68
+ if (typeof value !== "string" || value.trim() === "") {
69
+ throw new SchemaInventoryError(`Schema inventory malformed ${label} source_name: ${url}`);
70
+ }
71
+ return value;
72
+ }
73
+
74
+ function namedEntries(entries: unknown[], label: string, url: string): string[] {
75
+ const names: string[] = [];
76
+ const seen = new Set<string>();
77
+ for (const entry of entries) {
78
+ if (typeof entry !== "object" || entry === null || Array.isArray(entry)) {
79
+ throw new SchemaInventoryError(`Schema inventory malformed ${label} entry: ${url}`);
80
+ }
81
+ const name = requireNonEmptyName((entry as { source_name?: unknown }).source_name, label, url);
82
+ if (seen.has(name)) {
83
+ throw new SchemaInventoryError(`Schema inventory duplicate ${label} name '${name}': ${url}`);
84
+ }
85
+ seen.add(name);
86
+ names.push(name);
87
+ }
88
+ return names;
89
+ }
90
+
91
+ function publicViewNames(entries: unknown[], url: string): string[] {
92
+ const names: string[] = [];
93
+ const seen = new Set<string>();
94
+ for (const entry of entries) {
95
+ if (typeof entry !== "object" || entry === null || Array.isArray(entry)) {
96
+ throw new SchemaInventoryError(`Schema inventory malformed Views entry: ${url}`);
97
+ }
98
+ const view = entry as { source_name?: unknown; is_public?: unknown };
99
+ const name = requireNonEmptyName(view.source_name, "Views", url);
100
+ if (typeof view.is_public !== "boolean") {
101
+ throw new SchemaInventoryError(`Schema inventory malformed Views is_public: ${url}`);
102
+ }
103
+ if (seen.has(name)) {
104
+ throw new SchemaInventoryError(`Schema inventory duplicate Views name '${name}': ${url}`);
105
+ }
106
+ seen.add(name);
107
+ if (view.is_public) names.push(name);
108
+ }
109
+ return names;
110
+ }
111
+
112
+ /**
113
+ * Parse a RawModuleDefV10 JSON body into the name surface. Rejects missing,
114
+ * duplicate, or malformed section/entry structure instead of skipping it.
115
+ */
116
+ export function parseServerSurface(schema: unknown, url: string): SchemaSurface {
117
+ if (typeof schema !== "object" || schema === null || Array.isArray(schema)) {
118
+ throw new SchemaInventoryError(`Schema inventory is not an object: ${url}`);
119
+ }
120
+ const sections = (schema as { sections?: unknown }).sections;
121
+ if (!Array.isArray(sections)) {
122
+ throw new SchemaInventoryError(`Schema inventory missing sections: ${url}`);
123
+ }
124
+
125
+ const seen = new Set<SectionKind>();
126
+ let tables: unknown[] | undefined;
127
+ let views: unknown[] | undefined;
128
+ let reducers: unknown[] | undefined;
129
+
130
+ for (const section of sections) {
131
+ if (typeof section !== "object" || section === null || Array.isArray(section)) {
132
+ throw new SchemaInventoryError(`Schema inventory malformed section: ${url}`);
133
+ }
134
+ const keys = Object.keys(section);
135
+ if (keys.length !== 1) {
136
+ throw new SchemaInventoryError(`Schema inventory malformed section: ${url}`);
137
+ }
138
+ const kind = keys[0];
139
+ if (kind === undefined || !isSectionKind(kind)) {
140
+ throw new SchemaInventoryError(`Schema inventory unknown section '${kind}': ${url}`);
141
+ }
142
+ if (seen.has(kind)) {
143
+ throw new SchemaInventoryError(`Schema inventory duplicate ${kind} section: ${url}`);
144
+ }
145
+ seen.add(kind);
146
+ const value = (section as Record<string, unknown>)[kind];
147
+ if (kind === "CaseConversionPolicy") {
148
+ if (
149
+ typeof value !== "object" ||
150
+ value === null ||
151
+ Object.keys(value).length !== 1 ||
152
+ !("None" in value) ||
153
+ !Array.isArray(value.None) ||
154
+ value.None.length !== 0
155
+ ) {
156
+ throw new SchemaInventoryError(`Schema inventory unsupported ${kind}: ${url}`);
157
+ }
158
+ continue;
159
+ }
160
+ if (OBJECT_SECTIONS.has(kind)) {
161
+ if (typeof value !== "object" || value === null || Array.isArray(value)) {
162
+ throw new SchemaInventoryError(`Schema inventory ${kind} is not an object: ${url}`);
163
+ }
164
+ continue;
165
+ }
166
+ if (!Array.isArray(value)) {
167
+ throw new SchemaInventoryError(`Schema inventory ${kind} is not an array: ${url}`);
168
+ }
169
+ if (kind === "Tables") tables = value;
170
+ else if (kind === "Views") views = value;
171
+ else if (kind === "Reducers") reducers = value;
172
+ }
173
+
174
+ for (const kind of REQUIRED_SECTIONS) {
175
+ if (!seen.has(kind)) {
176
+ throw new SchemaInventoryError(`Schema inventory missing ${kind}: ${url}`);
177
+ }
178
+ }
179
+
180
+ const tableNames = namedEntries(tables ?? [], "Tables", url);
181
+ const viewNames = publicViewNames(views ?? [], url);
182
+ const reducerNames = namedEntries(reducers ?? [], "Reducers", url);
183
+ const tableSet = new Set(tableNames);
184
+ for (const name of viewNames) {
185
+ if (tableSet.has(name)) {
186
+ throw new SchemaInventoryError(`Schema inventory duplicate name '${name}': ${url}`);
187
+ }
188
+ }
189
+
190
+ return {
191
+ tables: [...tableNames, ...viewNames].sort(),
192
+ reducers: [...reducerNames].sort(),
193
+ };
194
+ }
195
+
196
+ /**
197
+ * A consumed table, view or reducer whose served shape this client cannot
198
+ * decode or call (sk-jay0.7.389.3): a changed, appended, removed or
199
+ * reordered column, changed reducer arguments or return type, a changed named
200
+ * type, a table made private. Thrown by connect() before the WebSocket opens,
201
+ * so the client never decodes rows with the wrong layout. Extends
202
+ * {@link BindingDriftError}, so existing handlers of the name check also catch
203
+ * it. Only in "strict" mode (the default); "warn" connects and reports.
204
+ */
205
+ export class BindingShapeError extends BindingDriftError {
206
+ readonly changes: readonly RuntimeChange[];
207
+ /** The world contract epoch this client was built for (build side only). */
208
+ readonly clientEpoch: number;
209
+
210
+ constructor(
211
+ expected: SchemaSurface,
212
+ actual: SchemaSurface,
213
+ changes: readonly RuntimeChange[],
214
+ clientEpoch: number,
215
+ ) {
216
+ super(expected, actual, "row-shape");
217
+ this.name = "BindingShapeError";
218
+ this.changes = changes;
219
+ this.clientEpoch = clientEpoch;
220
+ this.message = [
221
+ "BindingShapeError: this client cannot decode or call the world module it reached " +
222
+ `(built for contract epoch ${clientEpoch}; the module publishes no epoch, so connect compares shapes). ` +
223
+ "Use a client built from the deployed module, or roll the module back; " +
224
+ 'hosted apps run shapeCheck "warn" (SPELLKAVE_SHAPE_CHECK=warn) to log instead of refusing. Each line reads client -> server:',
225
+ ...changes.map((c) => ` ${c.item}: ${c.detail}`),
226
+ ].join("\n");
227
+ }
228
+ }
229
+
230
+ export interface ShapeComparison {
231
+ readonly breaking: readonly RuntimeChange[];
232
+ readonly diagnostics: readonly RuntimeChange[];
233
+ /** Consumed items the served definition did not let us read: not judged. */
234
+ readonly unchecked: readonly UncheckedItem[];
235
+ }
236
+
237
+ const foldText = (s: string) => s.toLowerCase().replace(/_/g, "");
238
+
239
+ /**
240
+ * Compares the served module definition with the contract this client was
241
+ * built with, for the items the contract lists only, with the connect-time
242
+ * (decode and call) rules of `@spellkave/bindings/contract`. Names are folded
243
+ * on both sides (the node re-cases identifiers; BSATN carries no names). An
244
+ * item the served definition does not let us read is `unchecked`, never a
245
+ * refusal: the check adds no fail-closed surface beyond the consumed shapes.
246
+ */
247
+ export function compareServedShape(served: unknown, contract: SchemaSnapshot): ShapeComparison {
248
+ const {
249
+ snapshot: server,
250
+ unchecked,
251
+ moduleUnreadable,
252
+ } = normaliseItems(served, {
253
+ tables: [...Object.keys(contract.tables), ...Object.keys(contract.views)],
254
+ reducers: Object.keys(contract.reducers),
255
+ });
256
+ // A module-level definition we cannot read leaves every item unjudged:
257
+ // report it, refuse nothing (the name check above already ran).
258
+ if (moduleUnreadable) return { breaking: [], diagnostics: [], unchecked };
259
+ const keep = foldCollisions(contract, server);
260
+ const folded = classifyRuntimeChange(foldNames(contract, keep), foldNames(server, keep));
261
+ // Judge on folded names; report in the module's own spelling where the
262
+ // unfolded comparison names the same change.
263
+ const spelled = classifyRuntimeChange(contract, server);
264
+ const changes = folded.map(
265
+ (f) =>
266
+ spelled.find(
267
+ (s) => foldText(s.item) === foldText(f.item) && foldText(s.detail) === foldText(f.detail),
268
+ ) ?? f,
269
+ );
270
+ const uncheckedNames = new Set(unchecked.map((u) => u.item));
271
+ return {
272
+ breaking: changes.filter((c) => c.verdict === "breaking" && !uncheckedNames.has(c.item)),
273
+ diagnostics: changes.filter((c) => c.verdict === "diagnostic"),
274
+ unchecked,
275
+ };
276
+ }
277
+
278
+ /** The served module definition and its name surface, from one request. */
279
+ export async function fetchServerSchema(
280
+ serverUrl: string,
281
+ dbName: string,
282
+ ): Promise<{ readonly url: string; readonly schema: unknown; readonly surface: SchemaSurface }> {
283
+ const url = `${serverUrl}/v1/database/${dbName}/schema?version=10`;
284
+ const res = await fetch(url);
285
+ if (!res.ok) throw new Error(`Schema fetch failed: ${res.status} ${res.statusText}`);
286
+ const schema: unknown = await res.json();
287
+ return { url, schema, surface: parseServerSurface(schema, url) };
288
+ }
289
+
290
+ /**
291
+ * Fetch the live schema from the SpacetimeDB HTTP endpoint and return the
292
+ * name surface the runtime gate can compare. connect() also compares row and
293
+ * argument shapes ({@link compareServedShape}); this name-only helper stays for
294
+ * callers that need just the inventory.
295
+ */
296
+ export async function fetchServerSurface(
297
+ serverUrl: string,
298
+ dbName: string,
299
+ ): Promise<SchemaSurface> {
300
+ return (await fetchServerSchema(serverUrl, dbName)).surface;
301
+ }