foldkit-surface 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.
- package/LICENSE +21 -0
- package/README.md +242 -0
- package/dist/index.d.mts +476 -0
- package/dist/index.d.mts.map +1 -0
- package/dist/index.mjs +691 -0
- package/dist/index.mjs.map +1 -0
- package/package.json +43 -0
package/dist/index.mjs
ADDED
|
@@ -0,0 +1,691 @@
|
|
|
1
|
+
import { Optic, Option, Result, Schema } from "effect";
|
|
2
|
+
//#region src/index.ts
|
|
3
|
+
/**
|
|
4
|
+
* `foldkit-surface` — **Phase 0 inference spike**.
|
|
5
|
+
*
|
|
6
|
+
* Minimal, deliberately non-final implementations of the Surface and Remote
|
|
7
|
+
* descriptors, written only to answer the five inference questions in
|
|
8
|
+
* `docs/design/REVISION_PLAN.md` §15 (Phase 0). Runtime behaviour is thin; the deliverable
|
|
9
|
+
* is the type surface, pinned by `test/inference.test-d.ts`.
|
|
10
|
+
*
|
|
11
|
+
* Phase 1 replaces the Surface half with the real package. Phase 3 moves the
|
|
12
|
+
* Entity/Selection/Remote half into `foldkit-remote`.
|
|
13
|
+
*/
|
|
14
|
+
/**
|
|
15
|
+
* Low-level escape hatch for a focus with no Model path of its own. Prefer the
|
|
16
|
+
* `App.model` tree; use this for an optic that is not part of the Model.
|
|
17
|
+
*/
|
|
18
|
+
const ModelRef = { fromOptic: (Schema, optic, dependency = []) => ({
|
|
19
|
+
Schema,
|
|
20
|
+
optic,
|
|
21
|
+
dependency,
|
|
22
|
+
get: (root) => Result.getOrThrow(optic.getResult(root)),
|
|
23
|
+
set: (root, value) => optic.replace(value, root)
|
|
24
|
+
}) };
|
|
25
|
+
/**
|
|
26
|
+
* Names that belong to the ModelRef surface. A Struct field with one of these
|
|
27
|
+
* names would silently shadow a method, so building the tree rejects it.
|
|
28
|
+
*/
|
|
29
|
+
const RESERVED_REF_NAMES = /* @__PURE__ */ new Set([
|
|
30
|
+
"Schema",
|
|
31
|
+
"optic",
|
|
32
|
+
"dependency",
|
|
33
|
+
"key",
|
|
34
|
+
"read",
|
|
35
|
+
"get",
|
|
36
|
+
"set",
|
|
37
|
+
"at",
|
|
38
|
+
"index",
|
|
39
|
+
"select"
|
|
40
|
+
]);
|
|
41
|
+
function propertyReader(root, key) {
|
|
42
|
+
return root === null || root === void 0 ? void 0 : root[key];
|
|
43
|
+
}
|
|
44
|
+
function optionalReader(value) {
|
|
45
|
+
return value === void 0 ? Option.none() : Option.some(value);
|
|
46
|
+
}
|
|
47
|
+
/** Reads the tag off a Foldkit Message constructor without constructing one. */
|
|
48
|
+
const messageTag = (constructor) => {
|
|
49
|
+
const literal = constructor.fields?._tag?.ast?.literal;
|
|
50
|
+
return typeof literal === "string" ? literal : void 0;
|
|
51
|
+
};
|
|
52
|
+
function makeTree(schema, path, optic, get, optional = false, set, owner) {
|
|
53
|
+
const erasedOptic = optic;
|
|
54
|
+
const setFocus = set ?? ((root, value) => optic.replace(value, root));
|
|
55
|
+
const node = {
|
|
56
|
+
Schema: schema,
|
|
57
|
+
optic,
|
|
58
|
+
dependency: path,
|
|
59
|
+
key: path[path.length - 1] ?? "",
|
|
60
|
+
owner,
|
|
61
|
+
get,
|
|
62
|
+
set: setFocus
|
|
63
|
+
};
|
|
64
|
+
const fields = schema.fields;
|
|
65
|
+
if (fields !== void 0) for (const key of Object.keys(fields)) {
|
|
66
|
+
if (RESERVED_REF_NAMES.has(key)) throw new Error(`Model field "${key}" is reserved by ModelRef`);
|
|
67
|
+
node[key] = makeTree(fields[key], [...path, key], erasedOptic.key(key), (root) => propertyReader(get(root), key), false, void 0, owner);
|
|
68
|
+
}
|
|
69
|
+
node.at = (key) => makeTree(schema, [...path, key], erasedOptic.at(key), (root) => optionalReader(propertyReader(get(root), key)), true, (root, value) => {
|
|
70
|
+
const container = get(root);
|
|
71
|
+
const option = value;
|
|
72
|
+
if (Option.isSome(option)) return setFocus(root, {
|
|
73
|
+
...container,
|
|
74
|
+
[key]: option.value
|
|
75
|
+
});
|
|
76
|
+
const { [key]: _removed, ...rest } = container;
|
|
77
|
+
return setFocus(root, rest);
|
|
78
|
+
}, owner);
|
|
79
|
+
node.index = (index) => makeTree(schema, [...path, String(index)], optic, (root) => optionalReader(Array.isArray(get(root)) ? get(root)[index] : void 0), true, (root, value) => {
|
|
80
|
+
const array = Array.isArray(get(root)) ? get(root) : [];
|
|
81
|
+
const option = value;
|
|
82
|
+
const next = Option.isSome(option) ? array.map((item, i) => i === index ? option.value : item) : array.filter((_, i) => i !== index);
|
|
83
|
+
return setFocus(root, next);
|
|
84
|
+
}, owner);
|
|
85
|
+
node.select = (projection) => {
|
|
86
|
+
const dependencies = mergeDependencies([path, ...projection.dependencies]);
|
|
87
|
+
return optional ? makeProjection(Schema.Option(projection.Model), dependencies, projection.requirements, (root) => Option.map(get(root), (value) => projection.read(value)), projection.connections) : makeProjection(projection.Model, dependencies, projection.requirements, (root) => projection.read(get(root)), projection.connections);
|
|
88
|
+
};
|
|
89
|
+
return node;
|
|
90
|
+
}
|
|
91
|
+
/** Unions dependency trees, dropping duplicates; the result is a set. */
|
|
92
|
+
function mergeDependencies(dependencies) {
|
|
93
|
+
const seen = /* @__PURE__ */ new Set();
|
|
94
|
+
const merged = [];
|
|
95
|
+
for (const dependency of dependencies) {
|
|
96
|
+
const key = dependency.join("\0");
|
|
97
|
+
if (seen.has(key)) continue;
|
|
98
|
+
seen.add(key);
|
|
99
|
+
merged.push(dependency);
|
|
100
|
+
}
|
|
101
|
+
return merged;
|
|
102
|
+
}
|
|
103
|
+
const windowKey = (window) => JSON.stringify([
|
|
104
|
+
window.first ?? null,
|
|
105
|
+
window.last ?? null,
|
|
106
|
+
window.after ?? null,
|
|
107
|
+
window.before ?? null
|
|
108
|
+
]);
|
|
109
|
+
/**
|
|
110
|
+
* Merges connection requirements for the same connection and window into one,
|
|
111
|
+
* unioning what they select of each item; the first keeps its other properties.
|
|
112
|
+
*/
|
|
113
|
+
function mergeConnections(connections) {
|
|
114
|
+
const merged = /* @__PURE__ */ new Map();
|
|
115
|
+
for (const connection of connections) {
|
|
116
|
+
const key = `${connection.identity}\u0000${windowKey(connection.window)}`;
|
|
117
|
+
const current = merged.get(key);
|
|
118
|
+
merged.set(key, current === void 0 ? connection : {
|
|
119
|
+
...current,
|
|
120
|
+
select: mergeRelation(current.select, connection.select)
|
|
121
|
+
});
|
|
122
|
+
}
|
|
123
|
+
return [...merged.values()];
|
|
124
|
+
}
|
|
125
|
+
/** Unions two relation slices for the same target: fields, windows, and nested relations. */
|
|
126
|
+
function mergeRelation(current, next) {
|
|
127
|
+
const fields = [...current.fields];
|
|
128
|
+
const seen = new Set(fields);
|
|
129
|
+
for (const field of next.fields) {
|
|
130
|
+
if (seen.has(field)) continue;
|
|
131
|
+
seen.add(field);
|
|
132
|
+
fields.push(field);
|
|
133
|
+
}
|
|
134
|
+
const windows = {
|
|
135
|
+
...current.windows,
|
|
136
|
+
...next.windows
|
|
137
|
+
};
|
|
138
|
+
const relations = mergeRelations(current.relations, next.relations);
|
|
139
|
+
return {
|
|
140
|
+
entity: current.entity,
|
|
141
|
+
fields,
|
|
142
|
+
...Object.keys(windows).length === 0 ? {} : { windows },
|
|
143
|
+
...relations === void 0 ? {} : { relations }
|
|
144
|
+
};
|
|
145
|
+
}
|
|
146
|
+
/** Unions two relation maps field by field; a field in both merges recursively. */
|
|
147
|
+
function mergeRelations(current, next) {
|
|
148
|
+
if (current === void 0) return next;
|
|
149
|
+
if (next === void 0) return current;
|
|
150
|
+
const merged = { ...current };
|
|
151
|
+
for (const [field, relation] of Object.entries(next)) {
|
|
152
|
+
const existing = merged[field];
|
|
153
|
+
merged[field] = existing === void 0 ? relation : mergeRelation(existing, relation);
|
|
154
|
+
}
|
|
155
|
+
return merged;
|
|
156
|
+
}
|
|
157
|
+
/** Unions requirements for the same entity + id, dropping duplicate fields. */
|
|
158
|
+
function mergeRequirements(requirements) {
|
|
159
|
+
const grouped = /* @__PURE__ */ new Map();
|
|
160
|
+
for (const requirement of requirements) {
|
|
161
|
+
const key = `${requirement.entity}\u0000${requirement.id}`;
|
|
162
|
+
const group = grouped.get(key);
|
|
163
|
+
const live = group?.live === true || requirement.live === true;
|
|
164
|
+
grouped.set(key, {
|
|
165
|
+
...mergeRelation(group ?? {
|
|
166
|
+
entity: requirement.entity,
|
|
167
|
+
fields: []
|
|
168
|
+
}, requirement),
|
|
169
|
+
id: requirement.id,
|
|
170
|
+
...live ? { live } : {}
|
|
171
|
+
});
|
|
172
|
+
}
|
|
173
|
+
return [...grouped.values()];
|
|
174
|
+
}
|
|
175
|
+
/**
|
|
176
|
+
* Requirement helpers, for the packages that plan and serve requirements.
|
|
177
|
+
* `merge` unions same-entity+id requirements; `mergeRelation` unions two
|
|
178
|
+
* slices of one target (fields, windows, nested relations).
|
|
179
|
+
*/
|
|
180
|
+
const Requirement = {
|
|
181
|
+
merge: mergeRequirements,
|
|
182
|
+
mergeRelation,
|
|
183
|
+
mergeConnections
|
|
184
|
+
};
|
|
185
|
+
function makeProjection(Model, dependencies, requirements, read, connections = []) {
|
|
186
|
+
return {
|
|
187
|
+
Model,
|
|
188
|
+
dependencies,
|
|
189
|
+
requirements,
|
|
190
|
+
connections,
|
|
191
|
+
read
|
|
192
|
+
};
|
|
193
|
+
}
|
|
194
|
+
/**
|
|
195
|
+
* `Schema.Struct({})` is not an empty-object schema: it accepts `{foo:1}`, `[]`,
|
|
196
|
+
* and `"str"` even with `onExcessProperty: 'error'`. A genuinely empty selection
|
|
197
|
+
* needs a `never`-valued record.
|
|
198
|
+
*/
|
|
199
|
+
function objectSchema(fields) {
|
|
200
|
+
return Object.keys(fields).length === 0 ? Schema.Record(Schema.String, Schema.Never) : Schema.Struct(fields);
|
|
201
|
+
}
|
|
202
|
+
const Projection = {
|
|
203
|
+
of: (schema) => (selection) => {
|
|
204
|
+
const picked = {};
|
|
205
|
+
const dependencies = [];
|
|
206
|
+
const requirements = [];
|
|
207
|
+
const connections = [];
|
|
208
|
+
const readers = [];
|
|
209
|
+
for (const key of Object.keys(selection)) {
|
|
210
|
+
const choice = selection[key];
|
|
211
|
+
if (choice === true) {
|
|
212
|
+
picked[key] = schema.fields[key];
|
|
213
|
+
readers.push([key, (root) => propertyReader(root, key)]);
|
|
214
|
+
} else {
|
|
215
|
+
const nested = choice;
|
|
216
|
+
picked[key] = nested.Model;
|
|
217
|
+
dependencies.push(...nested.dependencies);
|
|
218
|
+
requirements.push(...nested.requirements);
|
|
219
|
+
connections.push(...nested.connections);
|
|
220
|
+
readers.push([key, (root) => nested.read(propertyReader(root, key))]);
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
const read = (root) => {
|
|
224
|
+
const out = {};
|
|
225
|
+
for (const [key, reader] of readers) out[key] = reader(root);
|
|
226
|
+
return out;
|
|
227
|
+
};
|
|
228
|
+
return makeProjection(objectSchema(picked), mergeDependencies(dependencies), mergeRequirements(requirements), read, mergeConnections(connections));
|
|
229
|
+
},
|
|
230
|
+
struct: (entries) => {
|
|
231
|
+
const picked = {};
|
|
232
|
+
const dependencies = [];
|
|
233
|
+
const requirements = [];
|
|
234
|
+
const connections = [];
|
|
235
|
+
const readers = [];
|
|
236
|
+
for (const key of Object.keys(entries)) {
|
|
237
|
+
const entry = entries[key];
|
|
238
|
+
if ("dependencies" in entry) {
|
|
239
|
+
picked[key] = entry.Model;
|
|
240
|
+
dependencies.push(...entry.dependencies);
|
|
241
|
+
requirements.push(...entry.requirements);
|
|
242
|
+
connections.push(...entry.connections);
|
|
243
|
+
readers.push([key, entry.read]);
|
|
244
|
+
} else {
|
|
245
|
+
picked[key] = entry.Schema;
|
|
246
|
+
dependencies.push(entry.dependency);
|
|
247
|
+
readers.push([key, entry.get]);
|
|
248
|
+
}
|
|
249
|
+
}
|
|
250
|
+
const read = (root) => {
|
|
251
|
+
const out = {};
|
|
252
|
+
for (const [key, reader] of readers) out[key] = reader(root);
|
|
253
|
+
return out;
|
|
254
|
+
};
|
|
255
|
+
return makeProjection(objectSchema(picked), mergeDependencies(dependencies), mergeRequirements(requirements), read, mergeConnections(connections));
|
|
256
|
+
},
|
|
257
|
+
/**
|
|
258
|
+
* Maps a Projection over an array: `array(p): Projection<ReadonlyArray<Root>,
|
|
259
|
+
* ReadonlyArray<Value>>`. Nesting is explicit (an array of arrays stays an
|
|
260
|
+
* array of arrays); there is no flatten or double-wrap.
|
|
261
|
+
*/
|
|
262
|
+
array: (projection) => ({
|
|
263
|
+
Model: Schema.Array(projection.Model),
|
|
264
|
+
dependencies: projection.dependencies,
|
|
265
|
+
requirements: projection.requirements,
|
|
266
|
+
connections: projection.connections,
|
|
267
|
+
read: (root) => root.map((value) => projection.read(value))
|
|
268
|
+
}),
|
|
269
|
+
/** Maps a Projection inside an Option, preserving absence. */
|
|
270
|
+
option: (projection) => ({
|
|
271
|
+
Model: Schema.Option(projection.Model),
|
|
272
|
+
dependencies: projection.dependencies,
|
|
273
|
+
requirements: projection.requirements,
|
|
274
|
+
connections: projection.connections,
|
|
275
|
+
read: (root) => Option.map(root, (value) => projection.read(value))
|
|
276
|
+
}),
|
|
277
|
+
read: (projection, root) => projection.read(root),
|
|
278
|
+
/**
|
|
279
|
+
* Low-level escape hatch: a Projection from a Schema and a reader, for
|
|
280
|
+
* projections not derived from ModelRefs (agent context, adapters). Prefer
|
|
281
|
+
* `of`/`struct`/`select`; dependencies default to empty.
|
|
282
|
+
*/
|
|
283
|
+
fromReader: (Model, read, options) => ({
|
|
284
|
+
Model,
|
|
285
|
+
dependencies: options?.dependencies ?? [],
|
|
286
|
+
requirements: options?.requirements ?? [],
|
|
287
|
+
connections: options?.connections ?? [],
|
|
288
|
+
read
|
|
289
|
+
}),
|
|
290
|
+
/**
|
|
291
|
+
* Derives a writable projection from generated Model field references:
|
|
292
|
+
* `Projection.pick(App.model.todos, App.model.selectedTodoId)` infers
|
|
293
|
+
* `{ todos, selectedTodoId }` and its codec. Every reference must share one
|
|
294
|
+
* Root; a raw optic or an unrelated application is rejected. Repeated
|
|
295
|
+
* identical members deduplicate; a conflicting definition throws.
|
|
296
|
+
*/
|
|
297
|
+
pick: (...refs) => {
|
|
298
|
+
const selected = [...refs];
|
|
299
|
+
const owner = selected[0]?.owner;
|
|
300
|
+
for (const ref of selected) if (ref.owner !== owner) throw new Error("Projection.pick: references from different applications");
|
|
301
|
+
const fields = {};
|
|
302
|
+
for (const ref of selected) {
|
|
303
|
+
const existing = fields[ref.key];
|
|
304
|
+
if (existing !== void 0) {
|
|
305
|
+
if (existing === ref.Schema) continue;
|
|
306
|
+
throw new Error(`Projection.pick: conflicting definitions for "${ref.key}"`);
|
|
307
|
+
}
|
|
308
|
+
fields[ref.key] = ref.Schema;
|
|
309
|
+
}
|
|
310
|
+
return {
|
|
311
|
+
schema: objectSchema(fields),
|
|
312
|
+
dependencies: mergeDependencies(selected.map((ref) => ref.dependency)),
|
|
313
|
+
get: (model) => {
|
|
314
|
+
const out = {};
|
|
315
|
+
for (const ref of selected) out[ref.key] = ref.get(model);
|
|
316
|
+
return out;
|
|
317
|
+
},
|
|
318
|
+
set: (model, shared) => {
|
|
319
|
+
let next = model;
|
|
320
|
+
for (const ref of selected) next = ref.set(next, shared[ref.key]);
|
|
321
|
+
return next;
|
|
322
|
+
}
|
|
323
|
+
};
|
|
324
|
+
},
|
|
325
|
+
/**
|
|
326
|
+
* Merges disjoint writable projections into one: `Projection.compose(Todos,
|
|
327
|
+
* Selection)`. Every projection must own the same Model; a field defined twice
|
|
328
|
+
* with a different codec throws, while an identical definition deduplicates.
|
|
329
|
+
* `set` installs each part, so composed fields keep their own write behaviour.
|
|
330
|
+
*/
|
|
331
|
+
compose: (...projections) => {
|
|
332
|
+
const parts = [...projections];
|
|
333
|
+
const fields = {};
|
|
334
|
+
for (const part of parts) for (const [key, codec] of Object.entries(part.schema.fields)) {
|
|
335
|
+
const existing = fields[key];
|
|
336
|
+
if (existing !== void 0) {
|
|
337
|
+
if (existing === codec) continue;
|
|
338
|
+
throw new Error(`Projection.compose: conflicting definitions for "${key}"`);
|
|
339
|
+
}
|
|
340
|
+
fields[key] = codec;
|
|
341
|
+
}
|
|
342
|
+
return {
|
|
343
|
+
schema: objectSchema(fields),
|
|
344
|
+
dependencies: mergeDependencies(parts.flatMap((part) => [...part.dependencies])),
|
|
345
|
+
get: (model) => {
|
|
346
|
+
const out = {};
|
|
347
|
+
for (const part of parts) Object.assign(out, part.get(model));
|
|
348
|
+
return out;
|
|
349
|
+
},
|
|
350
|
+
set: (model, shared) => {
|
|
351
|
+
let next = model;
|
|
352
|
+
for (const part of parts) next = part.set(next, shared);
|
|
353
|
+
return next;
|
|
354
|
+
}
|
|
355
|
+
};
|
|
356
|
+
}
|
|
357
|
+
};
|
|
358
|
+
const isProjection = (value) => typeof value === "object" && value !== null && "read" in value && "requirements" in value;
|
|
359
|
+
const makeScope = (config) => {
|
|
360
|
+
const owner = {};
|
|
361
|
+
return {
|
|
362
|
+
Model: config.Model,
|
|
363
|
+
Message: config.Message,
|
|
364
|
+
owner,
|
|
365
|
+
model: makeTree(config.Model, [], Optic.id(), (root) => root, false, void 0, owner)
|
|
366
|
+
};
|
|
367
|
+
};
|
|
368
|
+
function application(config) {
|
|
369
|
+
const scope = makeScope(config);
|
|
370
|
+
const surface = (name, surfaceConfig) => Surface.make(scope, name, {
|
|
371
|
+
...surfaceConfig.params === void 0 ? {} : { Params: Schema.isSchema(surfaceConfig.params) ? surfaceConfig.params : Schema.Struct(surfaceConfig.params) },
|
|
372
|
+
model: (context) => {
|
|
373
|
+
const shape = surfaceConfig.model(context);
|
|
374
|
+
return isProjection(shape) ? shape : Projection.struct(shape);
|
|
375
|
+
},
|
|
376
|
+
messages: surfaceConfig.messages
|
|
377
|
+
});
|
|
378
|
+
return {
|
|
379
|
+
...scope,
|
|
380
|
+
initial: config.initial,
|
|
381
|
+
fields: scope.model,
|
|
382
|
+
update: config.update,
|
|
383
|
+
surface
|
|
384
|
+
};
|
|
385
|
+
}
|
|
386
|
+
/** Typed Message subsets of one application, by constructor reference. */
|
|
387
|
+
const MessageSet = {
|
|
388
|
+
/**
|
|
389
|
+
* Selects a typed Message subset by constructor reference:
|
|
390
|
+
* `MessageSet.make(App, [Message.CreatedTodo, Message.RenamedTodo])`. Each
|
|
391
|
+
* constructor must be this application's own variant; a duplicate or a variant
|
|
392
|
+
* from another union throws.
|
|
393
|
+
*/
|
|
394
|
+
make: (app, messages) => {
|
|
395
|
+
const tags = /* @__PURE__ */ new Set();
|
|
396
|
+
for (const constructor of messages) {
|
|
397
|
+
const tag = messageTag(constructor);
|
|
398
|
+
if (tag === void 0) throw new Error("MessageSet.make: expected Message constructors");
|
|
399
|
+
if (app.Message[tag] !== constructor) throw new Error(`MessageSet.make: "${tag}" is not a variant of this application's Message union`);
|
|
400
|
+
if (tags.has(tag)) throw new Error(`MessageSet.make: duplicate "${tag}"`);
|
|
401
|
+
tags.add(tag);
|
|
402
|
+
}
|
|
403
|
+
return {
|
|
404
|
+
owner: app.owner,
|
|
405
|
+
constructors: messages,
|
|
406
|
+
schema: Schema.Union([...messages]),
|
|
407
|
+
tags,
|
|
408
|
+
includes: (message) => tags.has(message._tag ?? "")
|
|
409
|
+
};
|
|
410
|
+
},
|
|
411
|
+
/**
|
|
412
|
+
* Unions several Message subsets into one. Every subset must belong to the
|
|
413
|
+
* same application; a tag declared twice throws. Disjoint feature modules can
|
|
414
|
+
* each declare their own subset and compose them here.
|
|
415
|
+
*/
|
|
416
|
+
union: (...subsets) => {
|
|
417
|
+
const parts = [...subsets];
|
|
418
|
+
const owner = parts[0]?.owner;
|
|
419
|
+
const tags = /* @__PURE__ */ new Set();
|
|
420
|
+
const constructors = [];
|
|
421
|
+
for (const part of parts) {
|
|
422
|
+
if (part.owner !== owner) throw new Error("MessageSet.union: subsets from different applications");
|
|
423
|
+
for (const constructor of part.constructors) {
|
|
424
|
+
const tag = messageTag(constructor);
|
|
425
|
+
if (tag === void 0) continue;
|
|
426
|
+
if (tags.has(tag)) throw new Error(`MessageSet.union: duplicate "${tag}"`);
|
|
427
|
+
tags.add(tag);
|
|
428
|
+
constructors.push(constructor);
|
|
429
|
+
}
|
|
430
|
+
}
|
|
431
|
+
return {
|
|
432
|
+
owner,
|
|
433
|
+
constructors,
|
|
434
|
+
schema: Schema.Union(constructors),
|
|
435
|
+
tags,
|
|
436
|
+
includes: (message) => tags.has(message._tag ?? "")
|
|
437
|
+
};
|
|
438
|
+
}
|
|
439
|
+
};
|
|
440
|
+
const Surface = {
|
|
441
|
+
application,
|
|
442
|
+
/**
|
|
443
|
+
* A Surface as the Model activates it. `params` is the value, or a function
|
|
444
|
+
* of the Model returning it (`undefined` while the Surface is inactive, e.g.
|
|
445
|
+
* on another route); the Surface's requirements then follow the Model.
|
|
446
|
+
*/
|
|
447
|
+
at: (surface, params) => ({
|
|
448
|
+
name: surface.name,
|
|
449
|
+
owner: surface.owner,
|
|
450
|
+
projectionOf: (model) => {
|
|
451
|
+
const resolved = typeof params === "function" ? params(model) : params;
|
|
452
|
+
return resolved === void 0 && surface.Params !== void 0 ? void 0 : surface.projection(resolved);
|
|
453
|
+
}
|
|
454
|
+
}),
|
|
455
|
+
make: (app, name, config) => {
|
|
456
|
+
const projection = (params) => config.model({
|
|
457
|
+
model: app.model,
|
|
458
|
+
params
|
|
459
|
+
});
|
|
460
|
+
return {
|
|
461
|
+
name,
|
|
462
|
+
owner: app.owner,
|
|
463
|
+
Params: config.Params,
|
|
464
|
+
Message: Schema.Never,
|
|
465
|
+
messages: config.messages ?? [],
|
|
466
|
+
projection
|
|
467
|
+
};
|
|
468
|
+
},
|
|
469
|
+
read: (surface, root, params) => surface.projection(params).read(root),
|
|
470
|
+
/**
|
|
471
|
+
* Binds a renderer to a Surface's projected Model and Message set. A
|
|
472
|
+
* type-level binder: the renderer already has this shape, but `Model` and
|
|
473
|
+
* `Message` are derived from the Surface instead of written by hand.
|
|
474
|
+
*/
|
|
475
|
+
view: (_surface, render) => render,
|
|
476
|
+
/**
|
|
477
|
+
* The application boundary: consume the Root Model, project it, and hand the
|
|
478
|
+
* projected Model to the renderer. `Subset` rejects a Surface whose Messages
|
|
479
|
+
* the application builder cannot route.
|
|
480
|
+
*/
|
|
481
|
+
rootView: (surface, params, render) => {
|
|
482
|
+
const projection = surface.projection(params);
|
|
483
|
+
return (root, h) => render(projection.read(root), h);
|
|
484
|
+
},
|
|
485
|
+
/**
|
|
486
|
+
* Embeds a child renderer in a parent view. `ParentModel extends ChildModel`
|
|
487
|
+
* enforces "child Model requirement ⊆ parent projected Model"; `Subset`
|
|
488
|
+
* enforces "child Message set ⊆ parent Message set".
|
|
489
|
+
*/
|
|
490
|
+
embed: (child) => (model, h) => child(model, h),
|
|
491
|
+
/**
|
|
492
|
+
* A Surface as a `Contract` for `Module`: what it observes, requires, and may
|
|
493
|
+
* emit. A parameterized Surface needs its `params` to build the projection.
|
|
494
|
+
*/
|
|
495
|
+
contract: (surface, params) => {
|
|
496
|
+
const projection = surface.projection(params);
|
|
497
|
+
return {
|
|
498
|
+
kind: "surface",
|
|
499
|
+
name: surface.name,
|
|
500
|
+
owner: surface.owner,
|
|
501
|
+
owns: [],
|
|
502
|
+
observes: projection.dependencies,
|
|
503
|
+
messages: surface.messages.map(messageTag).filter((tag) => tag !== void 0),
|
|
504
|
+
requirements: projection.requirements
|
|
505
|
+
};
|
|
506
|
+
},
|
|
507
|
+
/**
|
|
508
|
+
* Pure introspection for DevTools: what a Surface observes (dependencies,
|
|
509
|
+
* requirements) and what it may emit. No behavior change, no I/O.
|
|
510
|
+
*/
|
|
511
|
+
inspect: (surface, params) => {
|
|
512
|
+
const projection = surface.projection(params);
|
|
513
|
+
return {
|
|
514
|
+
name: surface.name,
|
|
515
|
+
dependencies: projection.dependencies,
|
|
516
|
+
requirements: projection.requirements,
|
|
517
|
+
emits: surface.messages
|
|
518
|
+
};
|
|
519
|
+
}
|
|
520
|
+
};
|
|
521
|
+
const label = (contract) => `${contract.kind}:${contract.name}`;
|
|
522
|
+
const pathKey = (path) => path.join(".");
|
|
523
|
+
const isPrefix = (prefix, path) => prefix.length <= path.length && prefix.every((segment, index) => segment === path[index]);
|
|
524
|
+
const toContract = (item) => "contract" in item ? item.contract : "projection" in item ? Surface.contract(item, void 0) : item;
|
|
525
|
+
const applicationTags = (app) => Object.entries(app.Message).filter(([key, value]) => messageTag(value) === key).map(([key]) => key);
|
|
526
|
+
/** Contracts that own at least one path, with a stable label. */
|
|
527
|
+
const owners = (module) => module.contracts.filter((contract) => contract.owns.length > 0);
|
|
528
|
+
/**
|
|
529
|
+
* Collects an application's contracts as pure data so their relationships can
|
|
530
|
+
* be validated and inspected without starting a runtime.
|
|
531
|
+
*
|
|
532
|
+
* ```ts
|
|
533
|
+
* const Project = Module.make(App, [BoardSurface, ProjectSync, ProjectRemote, ProjectAgent])
|
|
534
|
+
* Module.validate(Project) // findings, or []
|
|
535
|
+
* Module.toMarkdown(Project)
|
|
536
|
+
* ```
|
|
537
|
+
*/
|
|
538
|
+
const Module = {
|
|
539
|
+
make: (app, items = []) => ({
|
|
540
|
+
app,
|
|
541
|
+
contracts: items.map(toContract)
|
|
542
|
+
}),
|
|
543
|
+
/** A new Module with more contracts; the input is unchanged. */
|
|
544
|
+
add: (module, ...items) => ({
|
|
545
|
+
app: module.app,
|
|
546
|
+
contracts: [...module.contracts, ...items.map(toContract)]
|
|
547
|
+
}),
|
|
548
|
+
/**
|
|
549
|
+
* Cross-contract invariants the types cannot express: a contract from another
|
|
550
|
+
* application, a duplicate `kind:name`, two owners of overlapping Model paths,
|
|
551
|
+
* a Message recorded by two replication contracts, and a path or Message the
|
|
552
|
+
* application does not declare.
|
|
553
|
+
*/
|
|
554
|
+
validate: (module) => {
|
|
555
|
+
const findings = [];
|
|
556
|
+
const fields = new Set(Object.keys(module.app.Model.fields));
|
|
557
|
+
const tags = new Set(applicationTags(module.app));
|
|
558
|
+
const seen = /* @__PURE__ */ new Map();
|
|
559
|
+
for (const contract of module.contracts) {
|
|
560
|
+
const name = label(contract);
|
|
561
|
+
if (contract.owner !== void 0 && contract.owner !== module.app.owner) findings.push({
|
|
562
|
+
rule: "foreign-contract",
|
|
563
|
+
contracts: [name],
|
|
564
|
+
message: `${name} belongs to a different application`
|
|
565
|
+
});
|
|
566
|
+
const duplicate = seen.get(name);
|
|
567
|
+
if (duplicate !== void 0 && duplicate !== contract) findings.push({
|
|
568
|
+
rule: "duplicate-name",
|
|
569
|
+
contracts: [name],
|
|
570
|
+
message: `${name} is declared twice`
|
|
571
|
+
});
|
|
572
|
+
seen.set(name, contract);
|
|
573
|
+
for (const path of [...contract.owns, ...contract.observes]) {
|
|
574
|
+
const head = path[0];
|
|
575
|
+
if (head === void 0 || !fields.has(head)) findings.push({
|
|
576
|
+
rule: "unknown-path",
|
|
577
|
+
contracts: [name],
|
|
578
|
+
message: `${name} references "${pathKey(path)}", which is not a Model field`
|
|
579
|
+
});
|
|
580
|
+
}
|
|
581
|
+
for (const tag of contract.messages) if (!tags.has(tag)) findings.push({
|
|
582
|
+
rule: "unknown-message",
|
|
583
|
+
contracts: [name],
|
|
584
|
+
message: `${name} names "${tag}", which is not a Message of this application`
|
|
585
|
+
});
|
|
586
|
+
}
|
|
587
|
+
const owning = [...new Set(owners(module))];
|
|
588
|
+
for (let i = 0; i < owning.length; i += 1) for (let j = i + 1; j < owning.length; j += 1) {
|
|
589
|
+
const a = owning[i];
|
|
590
|
+
const b = owning[j];
|
|
591
|
+
for (const pa of a.owns) for (const pb of b.owns) if (pa.length > 0 && pb.length > 0 && (isPrefix(pa, pb) || isPrefix(pb, pa))) findings.push({
|
|
592
|
+
rule: "ownership-overlap",
|
|
593
|
+
contracts: [label(a), label(b)],
|
|
594
|
+
message: `${label(a)} owns "${pathKey(pa)}" and ${label(b)} owns "${pathKey(pb)}"`
|
|
595
|
+
});
|
|
596
|
+
}
|
|
597
|
+
const recorded = /* @__PURE__ */ new Map();
|
|
598
|
+
for (const contract of module.contracts.filter((contract) => contract.kind === "sync")) for (const tag of contract.messages) {
|
|
599
|
+
const other = recorded.get(tag);
|
|
600
|
+
if (other !== void 0 && other !== contract) findings.push({
|
|
601
|
+
rule: "message-claimed-twice",
|
|
602
|
+
contracts: [label(other), label(contract)],
|
|
603
|
+
message: `"${tag}" is durable in both ${label(other)} and ${label(contract)}`
|
|
604
|
+
});
|
|
605
|
+
else recorded.set(tag, contract);
|
|
606
|
+
}
|
|
607
|
+
return findings;
|
|
608
|
+
},
|
|
609
|
+
/**
|
|
610
|
+
* The application's fields and Messages, who owns each Model path (local when
|
|
611
|
+
* no contract does), every contract, and the findings. Reproducible for a
|
|
612
|
+
* given Module, so it can be committed and diffed.
|
|
613
|
+
*/
|
|
614
|
+
manifest: (module) => {
|
|
615
|
+
const ownership = [];
|
|
616
|
+
const owning = owners(module);
|
|
617
|
+
for (const field of Object.keys(module.app.Model.fields)) {
|
|
618
|
+
const claims = owning.flatMap((contract) => contract.owns.filter((path) => path[0] === field).map((path) => ({
|
|
619
|
+
path,
|
|
620
|
+
owner: {
|
|
621
|
+
kind: contract.kind,
|
|
622
|
+
name: contract.name
|
|
623
|
+
}
|
|
624
|
+
})));
|
|
625
|
+
const whole = claims.find((claim) => claim.path.length === 1);
|
|
626
|
+
if (whole !== void 0) ownership.push(whole);
|
|
627
|
+
else {
|
|
628
|
+
ownership.push({
|
|
629
|
+
path: [field],
|
|
630
|
+
owner: void 0
|
|
631
|
+
});
|
|
632
|
+
ownership.push(...claims.sort((a, b) => pathKey(a.path).localeCompare(pathKey(b.path))));
|
|
633
|
+
}
|
|
634
|
+
}
|
|
635
|
+
return {
|
|
636
|
+
fields: Object.keys(module.app.Model.fields),
|
|
637
|
+
messages: applicationTags(module.app),
|
|
638
|
+
ownership,
|
|
639
|
+
contracts: module.contracts.map(({ owner: _owner, ...rest }) => rest),
|
|
640
|
+
findings: Module.validate(module)
|
|
641
|
+
};
|
|
642
|
+
},
|
|
643
|
+
/** The manifest as Markdown: the ownership tree, a table of contracts, and findings. */
|
|
644
|
+
toMarkdown: (module) => {
|
|
645
|
+
const manifest = Module.manifest(module);
|
|
646
|
+
const lines = ["```text", "Model"];
|
|
647
|
+
const width = Math.max(0, ...manifest.ownership.map((row) => pathKey(row.path).length));
|
|
648
|
+
manifest.ownership.forEach((row, index) => {
|
|
649
|
+
const last = index === manifest.ownership.length - 1;
|
|
650
|
+
const owner = row.owner === void 0 ? "LOCAL" : `${row.owner.kind.toUpperCase()} ${row.owner.name}`;
|
|
651
|
+
lines.push(`${last ? "└── " : "├── "}${pathKey(row.path).padEnd(width)} ${owner}`);
|
|
652
|
+
});
|
|
653
|
+
lines.push("```", "", "| Contract | Owns | Observes | Messages | Requirements |", "| --- | --- | --- | --- | --- |");
|
|
654
|
+
for (const contract of manifest.contracts) lines.push(`| ${contract.kind}:${contract.name} | ${contract.owns.map(pathKey).join(", ")} | ${contract.observes.map(pathKey).join(", ")} | ${contract.messages.join(", ")} | ${contract.requirements.map((r) => `${r.entity}:${r.id}`).join(", ")} |`);
|
|
655
|
+
if (manifest.findings.length > 0) {
|
|
656
|
+
lines.push("", "## Findings", "");
|
|
657
|
+
for (const finding of manifest.findings) lines.push(`- **${finding.rule}** ${finding.message}`);
|
|
658
|
+
}
|
|
659
|
+
return lines.join("\n");
|
|
660
|
+
},
|
|
661
|
+
/**
|
|
662
|
+
* The manifest as a Mermaid flowchart: Model fields in a subgraph, one node
|
|
663
|
+
* per contract, a solid edge for ownership and a dotted edge for observation.
|
|
664
|
+
*/
|
|
665
|
+
toMermaid: (module) => {
|
|
666
|
+
const manifest = Module.manifest(module);
|
|
667
|
+
const lines = ["flowchart LR", " subgraph Model"];
|
|
668
|
+
manifest.fields.forEach((field, index) => lines.push(` f${index}["${field}"]`));
|
|
669
|
+
lines.push(" end");
|
|
670
|
+
const fieldId = (path) => {
|
|
671
|
+
const index = path.length === 0 ? -1 : manifest.fields.indexOf(path[0]);
|
|
672
|
+
return index < 0 ? void 0 : `f${index}`;
|
|
673
|
+
};
|
|
674
|
+
manifest.contracts.forEach((contract, index) => {
|
|
675
|
+
lines.push(` c${index}["${contract.kind}:${contract.name}"]`);
|
|
676
|
+
for (const path of contract.owns) {
|
|
677
|
+
const field = fieldId(path);
|
|
678
|
+
if (field !== void 0) lines.push(` c${index} -->|owns| ${field}`);
|
|
679
|
+
}
|
|
680
|
+
for (const path of contract.observes) {
|
|
681
|
+
const field = fieldId(path);
|
|
682
|
+
if (field !== void 0 && !contract.owns.some((owned) => pathKey(owned) === pathKey(path))) lines.push(` c${index} -.-> ${field}`);
|
|
683
|
+
}
|
|
684
|
+
});
|
|
685
|
+
return lines.join("\n");
|
|
686
|
+
}
|
|
687
|
+
};
|
|
688
|
+
//#endregion
|
|
689
|
+
export { MessageSet, ModelRef, Module, Projection, Requirement, Surface };
|
|
690
|
+
|
|
691
|
+
//# sourceMappingURL=index.mjs.map
|