@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.
- package/README.md +2 -155
- package/package.json +4 -63
- package/LICENSE +0 -89
- package/src/binding_rows.ts +0 -186
- package/src/connection.ts +0 -964
- package/src/core/actor.ts +0 -62
- package/src/core/actor_control.ts +0 -193
- package/src/core/actor_control_query_methods.ts +0 -101
- package/src/core/actor_control_reaction_methods.ts +0 -79
- package/src/core/actor_control_sense_methods.ts +0 -81
- package/src/core/actor_control_source.ts +0 -57
- package/src/core/actor_session_methods.ts +0 -226
- package/src/core/binding_drift.ts +0 -301
- package/src/core/credential.ts +0 -259
- package/src/core/driver_control.ts +0 -54
- package/src/core/effective_environment_state.ts +0 -71
- package/src/core/factored_manipulation_attempt.ts +0 -158
- package/src/core/ids.ts +0 -60
- package/src/core/interaction/canonical.ts +0 -15
- package/src/core/interaction/fingerprint.ts +0 -118
- package/src/core/interaction/index.ts +0 -31
- package/src/core/interaction/intent.ts +0 -284
- package/src/core/interaction/outcome.ts +0 -67
- package/src/core/interaction/rejection_ledger.ts +0 -108
- package/src/core/kernel_contract.generated.ts +0 -10
- package/src/core/log.ts +0 -23
- package/src/core/movement.ts +0 -111
- package/src/core/node-io.ts +0 -208
- package/src/core/paths.ts +0 -220
- package/src/core/profile.ts +0 -270
- package/src/core/profiles.ts +0 -9
- package/src/core/provenance_buffer.ts +0 -102
- package/src/core/readers/_helpers.ts +0 -273
- package/src/core/readers/action_description.ts +0 -17
- package/src/core/readers/action_economy_events.ts +0 -149
- package/src/core/readers/actor_body_swaps.ts +0 -62
- package/src/core/readers/actor_snapshot.ts +0 -197
- package/src/core/readers/actor_states.ts +0 -163
- package/src/core/readers/actors_and_bodies.ts +0 -179
- package/src/core/readers/affordance_cue.ts +0 -59
- package/src/core/readers/affordance_defaults.ts +0 -158
- package/src/core/readers/affordance_group_membership.ts +0 -67
- package/src/core/readers/affordance_input.ts +0 -129
- package/src/core/readers/affordance_reference.ts +0 -41
- package/src/core/readers/apply_consequences.ts +0 -54
- package/src/core/readers/audience_trace_presentation.ts +0 -62
- package/src/core/readers/bounded_collection.ts +0 -29
- package/src/core/readers/bundle_definitions.ts +0 -74
- package/src/core/readers/bundle_entities.ts +0 -62
- package/src/core/readers/co_location.ts +0 -71
- package/src/core/readers/combat_session.ts +0 -124
- package/src/core/readers/combat_session_active.ts +0 -44
- package/src/core/readers/combat_session_feedback.ts +0 -37
- package/src/core/readers/combat_session_grid.ts +0 -117
- package/src/core/readers/combat_session_roster.ts +0 -98
- package/src/core/readers/combat_session_types.ts +0 -51
- package/src/core/readers/condition_deltas.ts +0 -53
- package/src/core/readers/container_contents.ts +0 -92
- package/src/core/readers/dialogue_guide.ts +0 -99
- package/src/core/readers/dialogue_prompt_presentation.ts +0 -90
- package/src/core/readers/driver_control.ts +0 -64
- package/src/core/readers/entity_art.ts +0 -219
- package/src/core/readers/entity_containment.ts +0 -119
- package/src/core/readers/equipment.ts +0 -99
- package/src/core/readers/intervention_windows.ts +0 -136
- package/src/core/readers/inventory_query.ts +0 -145
- package/src/core/readers/item_detail.ts +0 -198
- package/src/core/readers/location_snapshot.ts +0 -216
- package/src/core/readers/manifest_apply_provenance.ts +0 -32
- package/src/core/readers/manifest_export.ts +0 -81
- package/src/core/readers/manipulation_context.ts +0 -475
- package/src/core/readers/map_layers.ts +0 -49
- package/src/core/readers/metadata_rows.ts +0 -56
- package/src/core/readers/object_state.ts +0 -124
- package/src/core/readers/observer_knowledge.ts +0 -41
- package/src/core/readers/observer_place_knowledge.ts +0 -37
- package/src/core/readers/observer_trace_knowledge.ts +0 -45
- package/src/core/readers/outcome_template.ts +0 -41
- package/src/core/readers/place_topology.ts +0 -109
- package/src/core/readers/reaction_options.ts +0 -156
- package/src/core/readers/resource_deltas.ts +0 -47
- package/src/core/readers/scene.ts +0 -275
- package/src/core/readers/seats.ts +0 -33
- package/src/core/readers/self.ts +0 -245
- package/src/core/readers/self_capabilities.ts +0 -159
- package/src/core/readers/self_economy.ts +0 -101
- package/src/core/readers/self_economy_budget.ts +0 -93
- package/src/core/readers/self_evaluations.ts +0 -128
- package/src/core/readers/self_identity.ts +0 -104
- package/src/core/readers/sense_context.ts +0 -112
- package/src/core/readers/session.ts +0 -207
- package/src/core/readers/session_detail.ts +0 -211
- package/src/core/readers/session_status.ts +0 -68
- package/src/core/readers/spatial_environment_state.ts +0 -74
- package/src/core/readers/spatial_niche_attachments.ts +0 -28
- package/src/core/readers/substrate_definitions.ts +0 -27
- package/src/core/readers/suggest_next_action.ts +0 -72
- package/src/core/readers/surface_membership.ts +0 -78
- package/src/core/readers/tag_reads.ts +0 -54
- package/src/core/readers/trace_query.ts +0 -120
- package/src/core/readers/trace_response.ts +0 -80
- package/src/core/readers/traces.ts +0 -124
- package/src/core/readers/travel_session.ts +0 -88
- package/src/core/readers/turn_state.ts +0 -34
- package/src/core/readers/world_events.ts +0 -43
- package/src/core/readers/world_status.ts +0 -63
- package/src/core/reducers/manipulation_args.ts +0 -239
- package/src/core/reducers/manipulation_receipt.ts +0 -66
- package/src/core/reducers/r_actor_wake_up.ts +0 -32
- package/src/core/reducers/r_inscribe_trace.ts +0 -109
- package/src/core/reducers/r_manipulate.ts +0 -163
- package/src/core/reducers/r_move.ts +0 -155
- package/src/core/reducers/r_react.ts +0 -143
- package/src/core/reducers/r_release_claim.ts +0 -81
- package/src/core/reducers/r_sense.ts +0 -84
- package/src/core/reducers/r_session_close.ts +0 -130
- package/src/core/reducers/r_session_move.ts +0 -116
- package/src/core/reducers/r_session_open.ts +0 -91
- package/src/core/reducers/session_lookup.ts +0 -64
- package/src/core/reducers/tick.ts +0 -65
- package/src/core/reducers/trace_lookup.ts +0 -29
- package/src/core/reducers/transport.ts +0 -84
- package/src/core/resolve.ts +0 -228
- package/src/core/shape_telemetry.ts +0 -146
- package/src/core/snapshot_rows.ts +0 -109
- package/src/core/tick_cadence.ts +0 -61
- package/src/core/types.ts +0 -501
- package/src/core/watch_provenance.ts +0 -113
- package/src/core/world-contract/classify.ts +0 -38
- package/src/core/world-contract/index.ts +0 -12
- package/src/core/world-contract/normalise.ts +0 -574
- package/src/core/world-contract/runtime.ts +0 -144
- package/src/core/world-contract/served.ts +0 -173
- package/src/core/world-contract/strict-reducers.ts +0 -14
- package/src/core/world-contract/typetext.ts +0 -94
- package/src/core/world_time.ts +0 -22
- package/src/index.ts +0 -262
- package/src/manifest-apply.ts +0 -497
- package/src/provenance.ts +0 -568
- package/src/reader-manifest.ts +0 -338
- package/src/readers.ts +0 -392
- package/src/replay.ts +0 -515
- package/src/watch-buffer.ts +0 -438
- package/src/world-events/builder.ts +0 -1042
|
@@ -1,574 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* One normaliser from a SpacetimeDB `RawModuleDefV10` to the kernel schema
|
|
3
|
-
* snapshot shape (sk-jay0.7.389.3). It reads both encodings of the same
|
|
4
|
-
* module definition:
|
|
5
|
-
*
|
|
6
|
-
* - decoded BSATN, as `packages/spellkave-bindings/scripts/schema-snapshot.ts`
|
|
7
|
-
* gets it from the wasm's `__describe_module__` through the `spacetimedb`
|
|
8
|
-
* codec: sums are `{ tag, value }`, fields camelCase, options bare;
|
|
9
|
-
* - the served SATS-JSON of `/v1/database/<db>/schema?version=10`, as the
|
|
10
|
-
* SDK fetches it at connect: sums are `{ Variant: payload }`, fields
|
|
11
|
-
* snake_case, options `{ some } | { none }`, bytes hex strings.
|
|
12
|
-
*
|
|
13
|
-
* The readers below accept either form, so the rendering rules exist once.
|
|
14
|
-
* Pure: no imports, safe for browser bundles.
|
|
15
|
-
*/
|
|
16
|
-
import type { SchemaSnapshot } from "./classify.ts";
|
|
17
|
-
import { typeNames } from "./typetext.ts";
|
|
18
|
-
|
|
19
|
-
type Obj = Record<string, unknown>;
|
|
20
|
-
|
|
21
|
-
function isObj(x: unknown): x is Obj {
|
|
22
|
-
return typeof x === "object" && x !== null && !Array.isArray(x);
|
|
23
|
-
}
|
|
24
|
-
|
|
25
|
-
/** A field by its snake_case name, or the camelCase name the codec uses. */
|
|
26
|
-
function field(obj: unknown, snake: string): unknown {
|
|
27
|
-
if (!isObj(obj)) return undefined;
|
|
28
|
-
if (snake in obj) return obj[snake];
|
|
29
|
-
return obj[snake.replace(/_([a-z])/g, (_m, c: string) => c.toUpperCase())];
|
|
30
|
-
}
|
|
31
|
-
|
|
32
|
-
/** A sum value as [variant, payload]. */
|
|
33
|
-
function sum(x: unknown): [string, unknown] {
|
|
34
|
-
if (isObj(x)) {
|
|
35
|
-
const keys = Object.keys(x);
|
|
36
|
-
if (keys.length === 2 && "tag" in x && "value" in x && typeof x.tag === "string") {
|
|
37
|
-
return [x.tag, x.value];
|
|
38
|
-
}
|
|
39
|
-
if (keys.length === 1) return [keys[0] as string, x[keys[0] as string]];
|
|
40
|
-
}
|
|
41
|
-
throw new Error(`kernel schema: not a sum value: ${JSON.stringify(x)?.slice(0, 80)}`);
|
|
42
|
-
}
|
|
43
|
-
|
|
44
|
-
/** An option: `{ some } | { none }` (served) or the bare value (decoded). */
|
|
45
|
-
function opt(x: unknown): unknown {
|
|
46
|
-
if (isObj(x)) {
|
|
47
|
-
const keys = Object.keys(x);
|
|
48
|
-
if (keys.length === 1 && keys[0] === "some") return x.some;
|
|
49
|
-
if (keys.length === 1 && keys[0] === "none") return undefined;
|
|
50
|
-
}
|
|
51
|
-
return x === null ? undefined : x;
|
|
52
|
-
}
|
|
53
|
-
|
|
54
|
-
function str(x: unknown): string {
|
|
55
|
-
const v = opt(x);
|
|
56
|
-
if (typeof v !== "string") throw new Error(`kernel schema: expected a string, got ${JSON.stringify(v)}`);
|
|
57
|
-
return v;
|
|
58
|
-
}
|
|
59
|
-
|
|
60
|
-
function num(x: unknown): number {
|
|
61
|
-
const v = typeof x === "bigint" ? Number(x) : x;
|
|
62
|
-
if (typeof v !== "number") throw new Error(`kernel schema: expected a number, got ${JSON.stringify(v)}`);
|
|
63
|
-
return v;
|
|
64
|
-
}
|
|
65
|
-
|
|
66
|
-
function arr(x: unknown): unknown[] {
|
|
67
|
-
return Array.isArray(x) ? x : [];
|
|
68
|
-
}
|
|
69
|
-
|
|
70
|
-
function hex(x: unknown): string {
|
|
71
|
-
if (typeof x === "string") return `0x${x.toLowerCase()}`;
|
|
72
|
-
const bytes = x instanceof Uint8Array ? [...x] : Object.values(x as Record<string, number>);
|
|
73
|
-
return `0x${bytes.map((b) => Number(b).toString(16).padStart(2, "0")).join("")}`;
|
|
74
|
-
}
|
|
75
|
-
|
|
76
|
-
const SPECIAL_PRODUCTS: Record<string, string> = {
|
|
77
|
-
__identity__: "Identity",
|
|
78
|
-
__connection_id__: "ConnectionId",
|
|
79
|
-
__timestamp_micros_since_unix_epoch__: "Timestamp",
|
|
80
|
-
__time_duration_micros__: "TimeDuration",
|
|
81
|
-
__uuid__: "Uuid",
|
|
82
|
-
};
|
|
83
|
-
|
|
84
|
-
function sorted<T>(entries: [string, T][]): Record<string, T> {
|
|
85
|
-
return Object.fromEntries(entries.sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)));
|
|
86
|
-
}
|
|
87
|
-
|
|
88
|
-
interface Member {
|
|
89
|
-
readonly name: string | undefined;
|
|
90
|
-
readonly type: unknown;
|
|
91
|
-
}
|
|
92
|
-
|
|
93
|
-
function members(product: unknown, list: "elements" | "variants"): Member[] {
|
|
94
|
-
return arr(field(product, list)).map((m) => ({
|
|
95
|
-
name: opt(field(m, "name")) as string | undefined,
|
|
96
|
-
type: field(m, "algebraic_type"),
|
|
97
|
-
}));
|
|
98
|
-
}
|
|
99
|
-
|
|
100
|
-
const isUnit = (ty: unknown) => {
|
|
101
|
-
const [tag, value] = sum(ty);
|
|
102
|
-
return tag === "Product" && members(value, "elements").length === 0;
|
|
103
|
-
};
|
|
104
|
-
|
|
105
|
-
type Snap = SchemaSnapshot;
|
|
106
|
-
type Kind = "table" | "view" | "reducer" | "procedure";
|
|
107
|
-
|
|
108
|
-
/**
|
|
109
|
-
* A lazy reader over one RawModuleDefV10: each item renders on request, with
|
|
110
|
-
* only the named types it reaches. The Typespace, Types and Schedules sections
|
|
111
|
-
* are read up front; an item is not touched until it is asked for, so an item
|
|
112
|
-
* a client never consumes cannot fail that client's check.
|
|
113
|
-
*/
|
|
114
|
-
export function moduleReader(def: unknown) {
|
|
115
|
-
const sections = new Map<string, unknown>();
|
|
116
|
-
let unnamedSections = 0;
|
|
117
|
-
for (const s of arr(field(def, "sections"))) {
|
|
118
|
-
// A section we cannot even name is skipped; every consumer below asks
|
|
119
|
-
// only for the sections it needs.
|
|
120
|
-
try {
|
|
121
|
-
const [tag, value] = sum(s);
|
|
122
|
-
sections.set(tag, value);
|
|
123
|
-
} catch {
|
|
124
|
-
unnamedSections++;
|
|
125
|
-
}
|
|
126
|
-
}
|
|
127
|
-
const section = (tag: string) => sections.get(tag);
|
|
128
|
-
const once = <T>(compute: () => T) => {
|
|
129
|
-
let done = false;
|
|
130
|
-
let value: T;
|
|
131
|
-
return () => {
|
|
132
|
-
if (!done) {
|
|
133
|
-
value = compute();
|
|
134
|
-
done = true;
|
|
135
|
-
}
|
|
136
|
-
return value as T;
|
|
137
|
-
};
|
|
138
|
-
};
|
|
139
|
-
const typespace = once(() => arr(field(section("Typespace"), "types")));
|
|
140
|
-
const typeNames = once(() => {
|
|
141
|
-
const names = new Map<number, string>();
|
|
142
|
-
for (const t of arr(section("Types"))) {
|
|
143
|
-
const n = field(t, "source_name");
|
|
144
|
-
names.set(num(field(t, "ty")), [...arr(field(n, "scope")).map(str), str(field(n, "source_name"))].join("."));
|
|
145
|
-
}
|
|
146
|
-
return names;
|
|
147
|
-
});
|
|
148
|
-
const ref = (i: number) => {
|
|
149
|
-
const types = typespace();
|
|
150
|
-
if (i < 0 || i >= types.length) throw new Error(`kernel schema: type ref ${i} is outside the typespace`);
|
|
151
|
-
return types[i];
|
|
152
|
-
};
|
|
153
|
-
const schedules = once(() => {
|
|
154
|
-
const out = new Map<string, [string, number]>();
|
|
155
|
-
for (const s of arr(section("Schedules"))) {
|
|
156
|
-
out.set(str(field(s, "table_name")), [str(field(s, "function_name")), num(field(s, "schedule_at_col"))]);
|
|
157
|
-
}
|
|
158
|
-
return out;
|
|
159
|
-
});
|
|
160
|
-
// The node serves a scheduled reducer as internal even when the wasm
|
|
161
|
-
// declares it client-callable (observed on 2.10.0 and 2.10.1).
|
|
162
|
-
const scheduled = once(() => new Set([...schedules().values()].map(([fn]) => fn)));
|
|
163
|
-
const TAGS = { table: "Tables", view: "Views", reducer: "Reducers", procedure: "Procedures" } as const;
|
|
164
|
-
const byKind = new Map<Kind, Map<string, unknown>>();
|
|
165
|
-
/** Entries of one item section by name; read on first use, unnamed entries skipped. */
|
|
166
|
-
const entries = (kind: Kind) => {
|
|
167
|
-
let map = byKind.get(kind);
|
|
168
|
-
if (!map) {
|
|
169
|
-
map = new Map();
|
|
170
|
-
for (const e of arr(section(TAGS[kind]))) {
|
|
171
|
-
try {
|
|
172
|
-
map.set(str(field(e, "source_name")), e);
|
|
173
|
-
} catch {}
|
|
174
|
-
}
|
|
175
|
-
byKind.set(kind, map);
|
|
176
|
-
}
|
|
177
|
-
return map;
|
|
178
|
-
};
|
|
179
|
-
/**
|
|
180
|
-
* The module-level definitions every item depends on (typespace, type
|
|
181
|
-
* names, schedules). Throws when any of them cannot be read: the caller
|
|
182
|
-
* then cannot judge any item.
|
|
183
|
-
*/
|
|
184
|
-
const prepare = () => {
|
|
185
|
-
typespace();
|
|
186
|
-
typeNames();
|
|
187
|
-
schedules();
|
|
188
|
-
};
|
|
189
|
-
|
|
190
|
-
/** Renders a type, adding every named type it reaches to `reached`. */
|
|
191
|
-
const renderer = (reached: Set<number>) => {
|
|
192
|
-
const render = (ty: unknown, seen: Set<number> = new Set()): string => {
|
|
193
|
-
const [tag, value] = sum(ty);
|
|
194
|
-
switch (tag) {
|
|
195
|
-
case "Ref": {
|
|
196
|
-
const i = num(value);
|
|
197
|
-
const name = typeNames().get(i);
|
|
198
|
-
if (name === undefined) {
|
|
199
|
-
// An unnamed type is rendered inline; a cycle without a name cannot be.
|
|
200
|
-
if (seen.has(i)) throw new Error(`kernel schema: unnamed recursive type ${i}`);
|
|
201
|
-
return render(ref(i), new Set([...seen, i]));
|
|
202
|
-
}
|
|
203
|
-
if (!reached.has(i)) {
|
|
204
|
-
reached.add(i);
|
|
205
|
-
render(ref(i));
|
|
206
|
-
}
|
|
207
|
-
return name;
|
|
208
|
-
}
|
|
209
|
-
case "Array":
|
|
210
|
-
return `Array<${render(value, seen)}>`;
|
|
211
|
-
case "Product": {
|
|
212
|
-
const elements = members(value, "elements");
|
|
213
|
-
const only = elements.length === 1 ? elements[0] : undefined;
|
|
214
|
-
const special = only?.name ? SPECIAL_PRODUCTS[only.name] : undefined;
|
|
215
|
-
if (special) return special;
|
|
216
|
-
if (elements.length === 0) return "()";
|
|
217
|
-
return `{${elements.map((e, i) => `${e.name ?? i}: ${render(e.type, seen)}`).join(", ")}}`;
|
|
218
|
-
}
|
|
219
|
-
case "Sum": {
|
|
220
|
-
const variants = members(value, "variants");
|
|
221
|
-
if (variants.length === 2 && variants[0]?.name === "some" && variants[1]?.name === "none" && isUnit(variants[1].type)) {
|
|
222
|
-
return `Option<${render(variants[0].type, seen)}>`;
|
|
223
|
-
}
|
|
224
|
-
return `(${variants.map((v, i) => (isUnit(v.type) ? `${v.name ?? i}` : `${v.name ?? i}(${render(v.type, seen)})`)).join(" | ")})`;
|
|
225
|
-
}
|
|
226
|
-
default:
|
|
227
|
-
return tag;
|
|
228
|
-
}
|
|
229
|
-
};
|
|
230
|
-
return render;
|
|
231
|
-
};
|
|
232
|
-
|
|
233
|
-
const renderItem = (kind: Kind, name: string, reached: Set<number>) => {
|
|
234
|
-
const entry = entries(kind).get(name);
|
|
235
|
-
if (entry === undefined) return undefined;
|
|
236
|
-
const render = renderer(reached);
|
|
237
|
-
const fields = (product: unknown) =>
|
|
238
|
-
members(product, "elements").map((e, i) => `${e.name ?? i}: ${render(e.type)}`);
|
|
239
|
-
const rowColumns = (i: number) => {
|
|
240
|
-
const [tag, value] = sum(ref(i));
|
|
241
|
-
if (tag !== "Product") throw new Error(`kernel schema: row type ${i} is not a product`);
|
|
242
|
-
return members(value, "elements");
|
|
243
|
-
};
|
|
244
|
-
const visibility = (v: unknown) => (sum(v)[0] === "ClientCallable" ? "client" : "internal");
|
|
245
|
-
if (kind === "table") {
|
|
246
|
-
const t = entry;
|
|
247
|
-
const elements = rowColumns(num(field(t, "product_type_ref")));
|
|
248
|
-
const colName = (i: number) => elements[i]?.name ?? String(i);
|
|
249
|
-
const cols = (ids: unknown[]) => ids.map((c) => colName(num(c)));
|
|
250
|
-
const defaults = new Map<number, string>();
|
|
251
|
-
for (const d of arr(field(t, "default_values"))) defaults.set(num(field(d, "col_id")), hex(field(d, "value")));
|
|
252
|
-
const indexes = arr(field(t, "indexes")).map((ix): [string, string] => {
|
|
253
|
-
const [algorithm, value] = sum(field(ix, "algorithm"));
|
|
254
|
-
const columns = Array.isArray(value) ? value : [value];
|
|
255
|
-
const accessor = (opt(field(ix, "accessor_name")) as string | undefined) ?? "";
|
|
256
|
-
return [str(field(ix, "source_name")), `${accessor}: ${algorithm.toLowerCase()}(${cols(columns).join(", ")})`];
|
|
257
|
-
});
|
|
258
|
-
const unique = arr(field(t, "constraints"))
|
|
259
|
-
.map((c) => sum(field(c, "data")))
|
|
260
|
-
.filter(([tag]) => tag === "Unique")
|
|
261
|
-
.map(([, v]) => cols(arr(field(v, "columns"))).join(", "))
|
|
262
|
-
.sort();
|
|
263
|
-
const schedule = schedules().get(name);
|
|
264
|
-
const table: Snap["tables"][string] = {
|
|
265
|
-
access: sum(field(t, "table_access"))[0].toLowerCase(),
|
|
266
|
-
kind: sum(field(t, "table_type"))[0].toLowerCase(),
|
|
267
|
-
event: field(t, "is_event") === true,
|
|
268
|
-
columns: elements.map((e, i) => {
|
|
269
|
-
const d = defaults.get(i);
|
|
270
|
-
return `${e.name ?? i}: ${render(e.type)}${d === undefined ? "" : ` = ${d}`}`;
|
|
271
|
-
}),
|
|
272
|
-
primaryKey: cols(arr(field(t, "primary_key"))),
|
|
273
|
-
unique,
|
|
274
|
-
indexes: sorted(indexes),
|
|
275
|
-
autoInc: arr(field(t, "sequences"))
|
|
276
|
-
.map((s) => colName(num(field(s, "column"))))
|
|
277
|
-
.sort(),
|
|
278
|
-
...(schedule ? { schedule: `${schedule[0]}(${colName(schedule[1])})` } : {}),
|
|
279
|
-
};
|
|
280
|
-
return table;
|
|
281
|
-
}
|
|
282
|
-
if (kind === "view") {
|
|
283
|
-
const v = entry;
|
|
284
|
-
const ret = field(v, "return_type");
|
|
285
|
-
let shape = "Value";
|
|
286
|
-
let inner: unknown = ret;
|
|
287
|
-
const [tag, value] = sum(ret);
|
|
288
|
-
if (tag === "Array") {
|
|
289
|
-
shape = "Array";
|
|
290
|
-
inner = value;
|
|
291
|
-
} else if (tag === "Sum") {
|
|
292
|
-
const variants = members(value, "variants");
|
|
293
|
-
if (variants[0]?.name === "some") {
|
|
294
|
-
shape = "Option";
|
|
295
|
-
inner = variants[0].type;
|
|
296
|
-
}
|
|
297
|
-
}
|
|
298
|
-
const [innerTag, innerValue] = sum(inner);
|
|
299
|
-
const rowRef = innerTag === "Ref" ? num(innerValue) : undefined;
|
|
300
|
-
const columns =
|
|
301
|
-
rowRef !== undefined && sum(ref(rowRef))[0] === "Product"
|
|
302
|
-
? rowColumns(rowRef).map((e, i) => `${e.name ?? i}: ${render(e.type)}`)
|
|
303
|
-
: undefined;
|
|
304
|
-
const view: Snap["views"][string] = {
|
|
305
|
-
public: field(v, "is_public") === true,
|
|
306
|
-
anonymous: field(v, "is_anonymous") === true,
|
|
307
|
-
params: fields(field(v, "params")),
|
|
308
|
-
returns: columns ? shape : render(ret),
|
|
309
|
-
...(columns ? { columns } : {}),
|
|
310
|
-
};
|
|
311
|
-
return view;
|
|
312
|
-
}
|
|
313
|
-
if (kind === "reducer") {
|
|
314
|
-
const r = entry;
|
|
315
|
-
const reducer: Snap["reducers"][string] = {
|
|
316
|
-
visibility: scheduled().has(name) ? "internal" : visibility(field(r, "visibility")),
|
|
317
|
-
params: fields(field(r, "params")),
|
|
318
|
-
ok: render(field(r, "ok_return_type")),
|
|
319
|
-
err: render(field(r, "err_return_type")),
|
|
320
|
-
};
|
|
321
|
-
return reducer;
|
|
322
|
-
}
|
|
323
|
-
const p = entry;
|
|
324
|
-
const procedure: Snap["procedures"][string] = {
|
|
325
|
-
visibility: visibility(field(p, "visibility")),
|
|
326
|
-
params: fields(field(p, "params")),
|
|
327
|
-
returns: render(field(p, "return_type")),
|
|
328
|
-
};
|
|
329
|
-
return procedure;
|
|
330
|
-
};
|
|
331
|
-
|
|
332
|
-
/** The named types in `reached`, rendered (rendering may reach more). */
|
|
333
|
-
const renderTypes = (reached: Set<number>) => {
|
|
334
|
-
const render = renderer(reached);
|
|
335
|
-
const out: [string, unknown][] = [];
|
|
336
|
-
const done = new Set<number>();
|
|
337
|
-
for (let changed = true; changed; ) {
|
|
338
|
-
changed = false;
|
|
339
|
-
for (const i of [...reached].sort((a, b) => a - b)) {
|
|
340
|
-
if (done.has(i)) continue;
|
|
341
|
-
done.add(i);
|
|
342
|
-
changed = true;
|
|
343
|
-
const [tag, value] = sum(ref(i));
|
|
344
|
-
const name = typeNames().get(i) as string;
|
|
345
|
-
if (tag === "Product") {
|
|
346
|
-
out.push([name, { product: members(value, "elements").map((e, k) => `${e.name ?? k}: ${render(e.type)}`) }]);
|
|
347
|
-
} else if (tag === "Sum") {
|
|
348
|
-
out.push([name, { sum: members(value, "variants").map((v, k) => `${v.name ?? k}: ${render(v.type)}`) }]);
|
|
349
|
-
} else out.push([name, { alias: render(ref(i)) }]);
|
|
350
|
-
}
|
|
351
|
-
}
|
|
352
|
-
return sorted(out);
|
|
353
|
-
};
|
|
354
|
-
|
|
355
|
-
const lifecycle = () =>
|
|
356
|
-
sorted(
|
|
357
|
-
arr(section("LifeCycleReducers")).map((l): [string, string] => [
|
|
358
|
-
sum(field(l, "lifecycle_spec"))[0],
|
|
359
|
-
str(field(l, "function_name")),
|
|
360
|
-
]),
|
|
361
|
-
);
|
|
362
|
-
// The node fills ExplicitNames with identity mappings the wasm leaves out;
|
|
363
|
-
// only a real rename (source != canonical) is part of the contract.
|
|
364
|
-
const explicitNames = () =>
|
|
365
|
-
arr(field(section("ExplicitNames"), "entries"))
|
|
366
|
-
.map((e) => {
|
|
367
|
-
const [kind, value] = sum(e);
|
|
368
|
-
const source = str(field(value, "source_name"));
|
|
369
|
-
const canonical = str(field(value, "canonical_name"));
|
|
370
|
-
return source === canonical ? undefined : `${kind} ${source} -> ${canonical}`;
|
|
371
|
-
})
|
|
372
|
-
.filter((e): e is string => e !== undefined)
|
|
373
|
-
.sort();
|
|
374
|
-
|
|
375
|
-
return { entries, prepare, renderItem, renderTypes, lifecycle, explicitNames, unnamedSections: () => unnamedSections };
|
|
376
|
-
}
|
|
377
|
-
|
|
378
|
-
/**
|
|
379
|
-
* Normalises a whole RawModuleDefV10 (the value inside the `V10` variant for
|
|
380
|
-
* the decoded form; the served JSON body as is) into the snapshot shape.
|
|
381
|
-
* Throws on anything it cannot read: the snapshot generator wants all of it.
|
|
382
|
-
*/
|
|
383
|
-
export function normaliseModuleDef(def: unknown): SchemaSnapshot {
|
|
384
|
-
const reader = moduleReader(def);
|
|
385
|
-
reader.prepare();
|
|
386
|
-
if (reader.unnamedSections() > 0) throw new Error("kernel schema: a module definition section is not a sum value");
|
|
387
|
-
const reached = new Set<number>();
|
|
388
|
-
const all = <K extends Kind>(kind: K) =>
|
|
389
|
-
sorted([...reader.entries(kind).keys()].map((name) => [name, reader.renderItem(kind, name, reached)] as [string, never]));
|
|
390
|
-
const explicitNames = reader.explicitNames();
|
|
391
|
-
return {
|
|
392
|
-
tables: all("table"),
|
|
393
|
-
views: all("view"),
|
|
394
|
-
reducers: all("reducer"),
|
|
395
|
-
procedures: all("procedure"),
|
|
396
|
-
lifecycle: reader.lifecycle(),
|
|
397
|
-
types: reader.renderTypes(reached),
|
|
398
|
-
...(explicitNames.length > 0 ? { explicitNames } : {}),
|
|
399
|
-
};
|
|
400
|
-
}
|
|
401
|
-
|
|
402
|
-
/** The `unchecked` item name when the module-level definitions cannot be read. */
|
|
403
|
-
export const MODULE_DEFINITION = "module definition";
|
|
404
|
-
|
|
405
|
-
export interface UncheckedItem {
|
|
406
|
-
readonly item: string;
|
|
407
|
-
readonly error: string;
|
|
408
|
-
}
|
|
409
|
-
|
|
410
|
-
/**
|
|
411
|
-
* Normalises only the named tables, views and reducers and the types they
|
|
412
|
-
* reach. An item that is absent is left out; an item that cannot be read is
|
|
413
|
-
* reported in `unchecked` instead of failing the rest.
|
|
414
|
-
*/
|
|
415
|
-
export function normaliseItems(
|
|
416
|
-
def: unknown,
|
|
417
|
-
names: { readonly tables: readonly string[]; readonly reducers: readonly string[] },
|
|
418
|
-
): {
|
|
419
|
-
readonly snapshot: SchemaSnapshot;
|
|
420
|
-
readonly unchecked: readonly UncheckedItem[];
|
|
421
|
-
/** The module-level definitions could not be read: no item was judged. */
|
|
422
|
-
readonly moduleUnreadable: boolean;
|
|
423
|
-
} {
|
|
424
|
-
const unchecked: UncheckedItem[] = [];
|
|
425
|
-
const reader = moduleReader(def);
|
|
426
|
-
try {
|
|
427
|
-
reader.prepare();
|
|
428
|
-
} catch (err) {
|
|
429
|
-
// Without the typespace, type names or schedules no item can be judged.
|
|
430
|
-
const empty: SchemaSnapshot = { tables: {}, views: {}, reducers: {}, procedures: {}, lifecycle: {}, types: {} };
|
|
431
|
-
return { snapshot: empty, unchecked: [{ item: MODULE_DEFINITION, error: (err as Error).message }], moduleUnreadable: true };
|
|
432
|
-
}
|
|
433
|
-
const reached = new Set<number>();
|
|
434
|
-
const pick = <K extends Kind>(kind: K, list: readonly string[]) => {
|
|
435
|
-
const out: [string, never][] = [];
|
|
436
|
-
for (const name of list) {
|
|
437
|
-
if (!reader.entries(kind).has(name)) continue;
|
|
438
|
-
// Render against a scratch set so a failed item adds no half-reached types.
|
|
439
|
-
const local = new Set(reached);
|
|
440
|
-
try {
|
|
441
|
-
out.push([name, reader.renderItem(kind, name, local) as never]);
|
|
442
|
-
for (const i of local) reached.add(i);
|
|
443
|
-
} catch (err) {
|
|
444
|
-
unchecked.push({ item: `${kind} ${name}`, error: (err as Error).message });
|
|
445
|
-
}
|
|
446
|
-
}
|
|
447
|
-
return sorted(out);
|
|
448
|
-
};
|
|
449
|
-
const tables = pick("table", names.tables);
|
|
450
|
-
const views = pick("view", names.tables);
|
|
451
|
-
const reducers = pick("reducer", names.reducers);
|
|
452
|
-
let types: Record<string, unknown> = {};
|
|
453
|
-
try {
|
|
454
|
-
types = reader.renderTypes(reached);
|
|
455
|
-
} catch (err) {
|
|
456
|
-
unchecked.push({ item: "named types", error: (err as Error).message });
|
|
457
|
-
}
|
|
458
|
-
return { snapshot: { tables, views, reducers, procedures: {}, lifecycle: {}, types }, unchecked, moduleUnreadable: false };
|
|
459
|
-
}
|
|
460
|
-
|
|
461
|
-
const fold = (s: string) => s.toLowerCase().replace(/_/g, "");
|
|
462
|
-
const MAP_SECTIONS = ["tables", "views", "reducers", "procedures", "lifecycle", "types"] as const;
|
|
463
|
-
|
|
464
|
-
/**
|
|
465
|
-
* Names whose folded form collides with another name of the same snapshot
|
|
466
|
-
* (`foo_bar` and `foobar`): those stay spelled as they are, or folding
|
|
467
|
-
* would merge two items into one.
|
|
468
|
-
*/
|
|
469
|
-
function collisions(snapshot: SchemaSnapshot): Set<string> {
|
|
470
|
-
// Names only collide within one namespace: one map of items, or the
|
|
471
|
-
// members of one row, parameter list, product or sum.
|
|
472
|
-
const groups: string[][] = MAP_SECTIONS.map((section) => Object.keys(snapshot[section] ?? {}));
|
|
473
|
-
const member = (m: string) => m.slice(0, m.indexOf(": "));
|
|
474
|
-
for (const t of Object.values(snapshot.tables)) groups.push(t.columns.map(member), Object.keys(t.indexes));
|
|
475
|
-
for (const v of Object.values(snapshot.views)) groups.push((v.columns ?? []).map(member), v.params.map(member));
|
|
476
|
-
for (const r of Object.values(snapshot.reducers)) groups.push(r.params.map(member));
|
|
477
|
-
for (const d of Object.values(snapshot.types) as { product?: string[]; sum?: string[] }[]) {
|
|
478
|
-
groups.push([...(d.product ?? []), ...(d.sum ?? [])].map(member));
|
|
479
|
-
}
|
|
480
|
-
const out = new Set<string>();
|
|
481
|
-
for (const names of groups) {
|
|
482
|
-
const byFold = new Map<string, Set<string>>();
|
|
483
|
-
for (const n of names) {
|
|
484
|
-
const set = byFold.get(fold(n)) ?? new Set<string>();
|
|
485
|
-
set.add(n);
|
|
486
|
-
byFold.set(fold(n), set);
|
|
487
|
-
}
|
|
488
|
-
for (const set of byFold.values()) if (set.size > 1) for (const n of set) out.add(n);
|
|
489
|
-
}
|
|
490
|
-
return out;
|
|
491
|
-
}
|
|
492
|
-
|
|
493
|
-
/**
|
|
494
|
-
* The served definition is the node's canonical form: it re-cases
|
|
495
|
-
* identifiers (`cell_res10` -> `cell_res_10`, enum variants lower case)
|
|
496
|
-
* where the wasm's own definition keeps the source spelling. BSATN does not
|
|
497
|
-
* carry names, so a connecting client compares shapes with every name folded
|
|
498
|
-
* (lower case, no underscores) on both sides: column order, types, arity and
|
|
499
|
-
* real renames still differ, spelling-only canonicalisation does not. Names
|
|
500
|
-
* that would collide once folded (`keep`, default: computed from both
|
|
501
|
-
* snapshots by the caller) keep their spelling.
|
|
502
|
-
*/
|
|
503
|
-
export function foldNames(snapshot: SchemaSnapshot, keep: ReadonlySet<string> = collisions(snapshot)): SchemaSnapshot {
|
|
504
|
-
const f = (s: string) => (keep.has(s) ? s : fold(s));
|
|
505
|
-
const text = (s: string) => s.replace(/[A-Za-z_][A-Za-z0-9_.]*/g, (w) => (/^0x/.test(w) ? w : f(w)));
|
|
506
|
-
const walk = (value: unknown, keysAreNames: boolean): unknown => {
|
|
507
|
-
if (typeof value === "string") return text(value);
|
|
508
|
-
if (Array.isArray(value)) return value.map((v) => walk(v, false));
|
|
509
|
-
if (isObj(value)) {
|
|
510
|
-
return Object.fromEntries(
|
|
511
|
-
Object.entries(value).map(([k, v]) => [
|
|
512
|
-
keysAreNames ? f(k) : k,
|
|
513
|
-
walk(v, !keysAreNames && (MAP_SECTIONS as readonly string[]).includes(k)) ,
|
|
514
|
-
]),
|
|
515
|
-
);
|
|
516
|
-
}
|
|
517
|
-
return value;
|
|
518
|
-
};
|
|
519
|
-
// Index maps are keyed by index name: fold those keys too.
|
|
520
|
-
const folded = walk(snapshot, false) as SchemaSnapshot;
|
|
521
|
-
for (const t of Object.values(folded.tables)) {
|
|
522
|
-
(t as { indexes: Record<string, string> }).indexes = Object.fromEntries(
|
|
523
|
-
Object.entries(t.indexes).map(([k, v]) => [f(k), v]),
|
|
524
|
-
);
|
|
525
|
-
}
|
|
526
|
-
return folded;
|
|
527
|
-
}
|
|
528
|
-
|
|
529
|
-
/** The fold-collision set of two snapshots together. */
|
|
530
|
-
export function foldCollisions(a: SchemaSnapshot, b: SchemaSnapshot): Set<string> {
|
|
531
|
-
return new Set([...collisions(a), ...collisions(b)]);
|
|
532
|
-
}
|
|
533
|
-
|
|
534
|
-
/**
|
|
535
|
-
* The part of a snapshot a client uses: the named tables or views, the named
|
|
536
|
-
* reducers, and every named type they reach. The SDK ships this, not the
|
|
537
|
-
* whole snapshot.
|
|
538
|
-
*/
|
|
539
|
-
export function restrictSnapshot(
|
|
540
|
-
snapshot: SchemaSnapshot,
|
|
541
|
-
items: { readonly tables: readonly string[]; readonly reducers: readonly string[] },
|
|
542
|
-
): SchemaSnapshot {
|
|
543
|
-
const pick = <T>(from: Readonly<Record<string, T>>, names: readonly string[]) =>
|
|
544
|
-
sorted(names.filter((n) => n in from).map((n): [string, T] => [n, from[n] as T]));
|
|
545
|
-
const tables = pick(snapshot.tables, items.tables);
|
|
546
|
-
const views = pick(snapshot.views, items.tables);
|
|
547
|
-
const reducers = pick(snapshot.reducers, items.reducers);
|
|
548
|
-
const queue = [
|
|
549
|
-
...Object.values(tables).flatMap((t) => t.columns),
|
|
550
|
-
...Object.values(views).flatMap((v) => [...(v.columns ?? []), ...v.params, v.returns]),
|
|
551
|
-
...Object.values(reducers).flatMap((r) => [...r.params, r.ok, r.err]),
|
|
552
|
-
]
|
|
553
|
-
// Members read `name: Type` (a column may end in ` = 0x..`); return types are bare.
|
|
554
|
-
.map((text) => (text.includes(": ") ? text.slice(text.indexOf(": ") + 2).replace(/ = 0x[0-9a-f]*$/, "") : text))
|
|
555
|
-
.flatMap((text) => typeNames(text).filter((n) => n in snapshot.types));
|
|
556
|
-
const reached = new Set<string>();
|
|
557
|
-
while (queue.length > 0) {
|
|
558
|
-
const name = queue.pop() as string;
|
|
559
|
-
if (reached.has(name)) continue;
|
|
560
|
-
reached.add(name);
|
|
561
|
-
const def = snapshot.types[name] as { product?: string[]; sum?: string[]; alias?: string };
|
|
562
|
-
const texts = [...(def.product ?? []), ...(def.sum ?? [])].map((m) => m.slice(m.indexOf(": ") + 2));
|
|
563
|
-
if (def.alias !== undefined) texts.push(def.alias);
|
|
564
|
-
queue.push(...texts.flatMap((t) => typeNames(t).filter((n) => n in snapshot.types)));
|
|
565
|
-
}
|
|
566
|
-
return {
|
|
567
|
-
tables,
|
|
568
|
-
views,
|
|
569
|
-
reducers,
|
|
570
|
-
procedures: {},
|
|
571
|
-
lifecycle: {},
|
|
572
|
-
types: pick(snapshot.types, [...reached]),
|
|
573
|
-
};
|
|
574
|
-
}
|