@agentshouse/mdruntime 0.1.0-cf28918c2bf91 → 0.1.0-cf6d5f0a5c9c8

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 (79) hide show
  1. package/AGENTS.md +68 -22
  2. package/README.md +10 -10
  3. package/dist/adapter.d.ts +58 -25
  4. package/dist/adapter.d.ts.map +1 -1
  5. package/dist/adapter.js +1 -9
  6. package/dist/attached-model.d.ts +11 -0
  7. package/dist/attached-model.d.ts.map +1 -0
  8. package/dist/attached-model.js +47 -0
  9. package/dist/bootstrap.d.ts +20 -6
  10. package/dist/bootstrap.d.ts.map +1 -1
  11. package/dist/bootstrap.js +89 -35
  12. package/dist/change-set.d.ts.map +1 -1
  13. package/dist/change-set.js +13 -7
  14. package/dist/client.d.ts +6 -3
  15. package/dist/client.d.ts.map +1 -1
  16. package/dist/client.js +38 -10
  17. package/dist/collection.d.ts +6 -11
  18. package/dist/collection.d.ts.map +1 -1
  19. package/dist/collection.js +56 -19
  20. package/dist/connection.d.ts +13 -13
  21. package/dist/connection.d.ts.map +1 -1
  22. package/dist/connection.js +643 -542
  23. package/dist/conversation.d.ts +18 -6
  24. package/dist/conversation.d.ts.map +1 -1
  25. package/dist/conversation.js +179 -78
  26. package/dist/host.d.ts +8 -1
  27. package/dist/host.d.ts.map +1 -1
  28. package/dist/host.js +35 -31
  29. package/dist/identity.d.ts +1 -0
  30. package/dist/identity.d.ts.map +1 -1
  31. package/dist/identity.js +7 -1
  32. package/dist/index.d.ts +3 -3
  33. package/dist/index.d.ts.map +1 -1
  34. package/dist/memory.d.ts +12 -5
  35. package/dist/memory.d.ts.map +1 -1
  36. package/dist/memory.js +92 -31
  37. package/dist/model.d.ts +11 -11
  38. package/dist/model.d.ts.map +1 -1
  39. package/dist/model.js +6 -3
  40. package/dist/observation.d.ts +2 -0
  41. package/dist/observation.d.ts.map +1 -1
  42. package/dist/observation.js +24 -14
  43. package/dist/paths.d.ts +0 -1
  44. package/dist/paths.d.ts.map +1 -1
  45. package/dist/paths.js +0 -16
  46. package/dist/query.d.ts +8 -3
  47. package/dist/query.d.ts.map +1 -1
  48. package/dist/query.js +75 -36
  49. package/dist/reach.d.ts +40 -0
  50. package/dist/reach.d.ts.map +1 -0
  51. package/dist/reach.js +270 -0
  52. package/dist/react.d.ts +39 -0
  53. package/dist/react.d.ts.map +1 -0
  54. package/dist/react.js +63 -0
  55. package/dist/read-side.d.ts +4 -0
  56. package/dist/read-side.d.ts.map +1 -1
  57. package/dist/read-side.js +116 -54
  58. package/dist/refresh.d.ts +12 -1
  59. package/dist/refresh.d.ts.map +1 -1
  60. package/dist/refresh.js +35 -22
  61. package/dist/replica.d.ts +6 -6
  62. package/dist/replica.d.ts.map +1 -1
  63. package/dist/replica.js +41 -36
  64. package/dist/room-draft.d.ts +3 -0
  65. package/dist/room-draft.d.ts.map +1 -1
  66. package/dist/room-draft.js +7 -5
  67. package/dist/rows.d.ts +4 -1
  68. package/dist/rows.d.ts.map +1 -1
  69. package/dist/rows.js +82 -39
  70. package/dist/save.d.ts +1 -2
  71. package/dist/save.d.ts.map +1 -1
  72. package/dist/save.js +106 -58
  73. package/dist/store.d.ts +25 -2
  74. package/dist/store.d.ts.map +1 -1
  75. package/dist/store.js +206 -90
  76. package/dist/wire.d.ts +52 -16
  77. package/dist/wire.d.ts.map +1 -1
  78. package/dist/wire.js +51 -59
  79. package/package.json +14 -2
package/dist/query.js CHANGED
@@ -1,3 +1,5 @@
1
+ import { pointerFacts, } from '@agentshouse/mdmodel';
2
+ import { referenceField } from './model.js';
1
3
  import { normalize } from './paths.js';
2
4
  export class QueryError extends Error {
3
5
  constructor(code, at, problem) {
@@ -11,6 +13,7 @@ const RELATED = ['types', 'where', 'pathPrefix', 'field'];
11
13
  const PARTS = ['fields', 'sections', 'preamble', 'markdown', 'backlinks', 'change'];
12
14
  const ORDER = ['by', 'direction', 'nulls', 'stringSort', 'locale', 'localeOptions'];
13
15
  const CALENDAR_DATE = /^(\d{4})-(\d{2})-(\d{2})$/;
16
+ const STRAY_ESCAPE = /~(?![01])/u;
14
17
  export function invalid(at, problem) {
15
18
  throw new QueryError('invalid-query', at, problem);
16
19
  }
@@ -68,23 +71,29 @@ function calendarDate(value) {
68
71
  const date = new Date(Date.UTC(year, month - 1, day));
69
72
  return (date.getUTCFullYear() === year && date.getUTCMonth() === month - 1 && date.getUTCDate() === day);
70
73
  }
71
- function fits(spec, value) {
72
- const item = spec.kind === 'list' ? spec.of : spec;
73
- if (item.kind === 'number')
74
+ function itemOf(facts) {
75
+ return facts.type === 'array' ? facts.items : facts;
76
+ }
77
+ function fits(facts, value) {
78
+ const item = itemOf(facts);
79
+ if (item?.type === undefined)
80
+ return true;
81
+ if (item.values !== undefined)
82
+ return item.values.includes(value);
83
+ if (item.type === 'number')
74
84
  return typeof value === 'number';
75
- if (typeof value !== 'string')
85
+ if (item.type === 'integer')
86
+ return Number.isSafeInteger(value);
87
+ if (item.type === 'boolean')
88
+ return typeof value === 'boolean';
89
+ if (item.type !== 'string' || typeof value !== 'string')
76
90
  return false;
77
- if (item.kind === 'enum')
78
- return item.values.includes(value);
79
- if (item.kind === 'date')
80
- return calendarDate(value);
81
- if (item.kind === 'reference')
91
+ if (item.reference !== undefined)
82
92
  return value !== '' && normalize(value) === value;
93
+ if (item.format === 'date')
94
+ return calendarDate(value);
83
95
  return true;
84
96
  }
85
- function reference(spec) {
86
- return spec.kind === 'reference' || (spec.kind === 'list' && spec.of.kind === 'reference');
87
- }
88
97
  function typing(facts, rooms, types, at) {
89
98
  const read = rooms === null ? facts.rooms : facts.rooms.filter((room) => rooms.includes(room.locator));
90
99
  const acquiring = !facts.listed &&
@@ -102,22 +111,46 @@ function typing(facts, rooms, types, at) {
102
111
  types: types === null ? declared : declared.filter((type) => types.includes(type.name)),
103
112
  };
104
113
  }
105
- function specs(typed, field, at) {
106
- const declared = typed.types.flatMap((type) => Object.hasOwn(type.fields, field) ? [type.fields[field]] : []);
114
+ function pointer(input, at) {
115
+ if (typeof input !== 'string' || !input.startsWith('/') || STRAY_ESCAPE.test(input)) {
116
+ invalid(at, 'expects a JSON Pointer');
117
+ }
118
+ return input;
119
+ }
120
+ function specs(typed, input, at) {
121
+ const field = pointer(input, at);
122
+ const declared = typed.types.flatMap((type) => {
123
+ const spec = pointerFacts(type, field);
124
+ return spec === undefined ? [] : [spec];
125
+ });
107
126
  if (declared.length === 0 && !typed.untyped) {
108
127
  throw new QueryError('unknown-field', at, `no MD Type it reads declares ${field}`);
109
128
  }
110
- return declared;
129
+ if (!declared.some((spec) => spec.conditional))
130
+ return declared;
131
+ return declared.map((spec) => ({
132
+ facts: { prose: false },
133
+ through: several(spec),
134
+ conditional: true,
135
+ }));
136
+ }
137
+ function several(spec) {
138
+ return spec.through || spec.facts.type === 'array';
139
+ }
140
+ function single(spec) {
141
+ return spec.facts.type !== undefined && spec.facts.type !== 'array';
142
+ }
143
+ function every(declared, holds) {
144
+ return declared.length > 0 && declared.every(holds);
111
145
  }
112
146
  function kind(declared, checked, at) {
113
- if (checked === null || declared.length === 0 || declared.some((spec) => fits(spec, checked))) {
147
+ if (checked === null ||
148
+ declared.length === 0 ||
149
+ declared.some((spec) => fits(spec.facts, checked))) {
114
150
  return;
115
151
  }
116
152
  throw new QueryError('wrong-kind', at, `${JSON.stringify(checked)} is not of its field's kind`);
117
153
  }
118
- function listed(declared, list) {
119
- return declared.length > 0 && declared.every((spec) => (spec.kind === 'list') === list);
120
- }
121
154
  function test(declared, input, at) {
122
155
  if (!plain(input)) {
123
156
  const equal = value(input, at);
@@ -131,8 +164,11 @@ function test(declared, input, at) {
131
164
  const stray = operators.find((operator) => !RANGE.includes(operator));
132
165
  if (stray !== undefined)
133
166
  invalid(place(at, stray), 'cannot join a range');
134
- if (listed(declared, true))
167
+ if (every(declared, (spec) => spec.facts.type === 'array'))
135
168
  invalid(at, 'a range on a list');
169
+ if (every(declared, (spec) => spec.facts.type === 'boolean' || spec.facts.type === 'object')) {
170
+ throw new QueryError('wrong-kind', at, 'its field does not compare in order');
171
+ }
136
172
  return {
137
173
  op: 'range',
138
174
  bounds: RANGE.filter((operator) => operators.includes(operator)).map((operator) => {
@@ -165,7 +201,7 @@ function test(declared, input, at) {
165
201
  return { op: 'nin', values: compared };
166
202
  if (compared.includes(null))
167
203
  invalid(where, 'a list holds no null');
168
- if (listed(declared, false))
204
+ if (every(declared, single))
169
205
  invalid(where, 'the field is not a list');
170
206
  return { op: 'all', values: compared };
171
207
  }
@@ -173,7 +209,7 @@ function test(declared, input, at) {
173
209
  if (!Number.isSafeInteger(operand) || operand < 0) {
174
210
  invalid(where, 'expects a nonnegative integer');
175
211
  }
176
- if (listed(declared, false))
212
+ if (every(declared, single))
177
213
  invalid(where, 'the field is not a list');
178
214
  return { op: 'size', size: operand };
179
215
  }
@@ -186,7 +222,7 @@ function condition(typed, input, at) {
186
222
  invalid(at, 'expects an object of field predicates');
187
223
  const conditions = [];
188
224
  for (const name of Object.keys(input).sort()) {
189
- const where = place(at, name);
225
+ const where = name.startsWith('/') ? `${at}${name}` : place(at, name);
190
226
  const entry = input[name];
191
227
  if (name === '$and' || name === '$or') {
192
228
  const nested = list(entry, where).map((item, index) => condition(typed, item, `${where}[${index}]`));
@@ -215,19 +251,19 @@ function scope(facts, rooms, input, at) {
215
251
  pathPrefix: input.pathPrefix === undefined ? null : directory(input.pathPrefix, place(at, 'pathPrefix')),
216
252
  };
217
253
  }
218
- function referenceField(typed, field, at) {
219
- if (typeof field !== 'string')
220
- invalid(at, 'expects a field name');
254
+ function referenceName(typed, field, at) {
221
255
  const declared = specs(typed, field, at);
222
- if (declared.length > 0 && !declared.some(reference))
256
+ if (declared.length > 0 &&
257
+ !declared.some((spec) => spec.conditional || referenceField(spec.facts))) {
223
258
  invalid(at, 'not a reference field');
259
+ }
224
260
  return field;
225
261
  }
226
262
  function hopOf(facts, rooms, root, input) {
227
263
  if (!plain(input))
228
264
  invalid('hop', 'expects an object');
229
265
  known(input, RELATED, 'hop');
230
- const field = referenceField(root, input.field, 'hop.field');
266
+ const field = referenceName(root, input.field, 'hop.field');
231
267
  const { types, where, pathPrefix } = scope(facts, rooms, input, 'hop');
232
268
  return { types, where, pathPrefix, field };
233
269
  }
@@ -236,14 +272,16 @@ function backlinksOf(facts, rooms, input) {
236
272
  invalid('backlinks', 'expects an object');
237
273
  known(input, RELATED, 'backlinks');
238
274
  const { typed, types, where, pathPrefix } = scope(facts, rooms, input, 'backlinks');
239
- const field = input.field === undefined ? null : referenceField(typed, input.field, 'backlinks.field');
275
+ const field = input.field === undefined ? null : referenceName(typed, input.field, 'backlinks.field');
240
276
  return { types, where, pathPrefix, field };
241
277
  }
242
278
  function keyPlan(typed, input, at, path) {
243
279
  if (input === 'room' || input === 'type' || (path && input === 'path'))
244
280
  return { of: input };
245
- if (plain(input) && typeof input.field === 'string' && Object.keys(input).length === 1) {
246
- specs(typed, input.field, place(at, 'field'));
281
+ if (plain(input) && Object.hasOwn(input, 'field') && Object.keys(input).length === 1) {
282
+ if (specs(typed, input.field, place(at, 'field')).some(several)) {
283
+ invalid(place(at, 'field'), 'a path that can hold several values');
284
+ }
247
285
  return { of: 'field', field: input.field };
248
286
  }
249
287
  return invalid(at, path ? 'expects room, path, type or a field' : 'expects room, type or a field');
@@ -301,10 +339,10 @@ function parts(typed, input, at, fields) {
301
339
  return 'all';
302
340
  const named = list(input, at);
303
341
  named.forEach((name, index) => {
304
- if (typeof name !== 'string')
305
- invalid(`${at}[${index}]`, 'expects a name');
306
342
  if (fields)
307
343
  specs(typed, name, `${at}[${index}]`);
344
+ else if (typeof name !== 'string')
345
+ invalid(`${at}[${index}]`, 'expects a name');
308
346
  });
309
347
  return named;
310
348
  }
@@ -372,7 +410,7 @@ function groupShape(typed, input) {
372
410
  });
373
411
  return { kind: 'groups', groupBy, orderBy };
374
412
  }
375
- export function planOf(input, facts) {
413
+ export function planOf(input, facts, reach = null) {
376
414
  if (!plain(input))
377
415
  invalid('query', 'expects a query object');
378
416
  const grouped = input.groupBy !== undefined;
@@ -386,6 +424,7 @@ export function planOf(input, facts) {
386
424
  const { typed, ...root } = scope(facts, rooms, input, '');
387
425
  return {
388
426
  rooms,
427
+ reach,
389
428
  root,
390
429
  hop: input.hop === undefined ? null : hopOf(facts, rooms, typed, input.hop),
391
430
  backlinks: input.backlinks === undefined ? null : backlinksOf(facts, rooms, input.backlinks),
@@ -401,11 +440,11 @@ export function limitOf(input) {
401
440
  }
402
441
  return input;
403
442
  }
404
- export function filterOf(input, facts) {
443
+ export function filterOf(input, facts, reach = null) {
405
444
  if (!plain(input))
406
445
  invalid('documents', 'expects a filter object');
407
446
  known(input, FILTER, '');
408
- return planOf({ ...input, select: {} }, facts);
447
+ return planOf({ ...input, select: {} }, facts, reach);
409
448
  }
410
449
  function canonical(value) {
411
450
  if (Array.isArray(value))
@@ -0,0 +1,40 @@
1
+ import type { MdRuntime, RuntimeTopic } from './connection.js';
2
+ import type { Plan, PlanReach, QueryResult } from './query.js';
3
+ import type { SearchResult } from './search.js';
4
+ export type ReachedDocument = {
5
+ readonly room: string;
6
+ readonly path: string;
7
+ };
8
+ export type PortReach = {
9
+ readonly rooms: readonly string[];
10
+ readonly documents: readonly ReachedDocument[];
11
+ readonly conversations: boolean;
12
+ };
13
+ export type Deliver = (message: unknown) => void;
14
+ export type Watch = (topic: RuntimeTopic, input: readonly unknown[], deliver: Deliver) => () => void;
15
+ export type RuntimeView = {
16
+ md: MdRuntime;
17
+ watch: Watch;
18
+ };
19
+ export type NarrowedView = RuntimeView & {
20
+ narrow(reach: PortReach | null): void;
21
+ };
22
+ export type Reachable = RuntimeView & {
23
+ plan(input: unknown, reach: PortReach | null): Plan;
24
+ query(plan: Plan): Promise<QueryResult>;
25
+ watchPlan(plan: Plan, deliver: (message: unknown) => void): () => void;
26
+ search(input: unknown, reach: PortReach | null): Promise<SearchResult>;
27
+ };
28
+ export declare function holds(reach: PortReach | null, room: string): boolean;
29
+ export declare function governs(reach: PortReach | null, room: {
30
+ readonly locator: string;
31
+ readonly typedSelection: {
32
+ roots: readonly string[];
33
+ } | null;
34
+ }): {
35
+ readonly collection: boolean;
36
+ readonly selection: boolean;
37
+ };
38
+ export declare function planReach(reach: PortReach | null): PlanReach | null;
39
+ export declare function narrowed(runtime: Reachable, given: PortReach | null): NarrowedView;
40
+ //# sourceMappingURL=reach.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"reach.d.ts","sourceRoot":"","sources":["../src/reach.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAW,SAAS,EAAe,YAAY,EAAc,MAAM,iBAAiB,CAAC;AAMjG,OAAO,KAAK,EAAE,IAAI,EAAE,SAAS,EAAE,WAAW,EAAE,MAAM,YAAY,CAAC;AAI/D,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAGhD,MAAM,MAAM,eAAe,GAAG;IAAE,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IAAC,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAA;CAAE,CAAC;AAE/E,MAAM,MAAM,SAAS,GAAG;IACtB,QAAQ,CAAC,KAAK,EAAE,SAAS,MAAM,EAAE,CAAC;IAClC,QAAQ,CAAC,SAAS,EAAE,SAAS,eAAe,EAAE,CAAC;IAC/C,QAAQ,CAAC,aAAa,EAAE,OAAO,CAAC;CACjC,CAAC;AAEF,MAAM,MAAM,OAAO,GAAG,CAAC,OAAO,EAAE,OAAO,KAAK,IAAI,CAAC;AAEjD,MAAM,MAAM,KAAK,GAAG,CAClB,KAAK,EAAE,YAAY,EACnB,KAAK,EAAE,SAAS,OAAO,EAAE,EACzB,OAAO,EAAE,OAAO,KACb,MAAM,IAAI,CAAC;AAEhB,MAAM,MAAM,WAAW,GAAG;IAAE,EAAE,EAAE,SAAS,CAAC;IAAC,KAAK,EAAE,KAAK,CAAA;CAAE,CAAC;AAE1D,MAAM,MAAM,YAAY,GAAG,WAAW,GAAG;IAAE,MAAM,CAAC,KAAK,EAAE,SAAS,GAAG,IAAI,GAAG,IAAI,CAAA;CAAE,CAAC;AAEnF,MAAM,MAAM,SAAS,GAAG,WAAW,GAAG;IACpC,IAAI,CAAC,KAAK,EAAE,OAAO,EAAE,KAAK,EAAE,SAAS,GAAG,IAAI,GAAG,IAAI,CAAC;IACpD,KAAK,CAAC,IAAI,EAAE,IAAI,GAAG,OAAO,CAAC,WAAW,CAAC,CAAC;IACxC,SAAS,CAAC,IAAI,EAAE,IAAI,EAAE,OAAO,EAAE,CAAC,OAAO,EAAE,OAAO,KAAK,IAAI,GAAG,MAAM,IAAI,CAAC;IACvE,MAAM,CAAC,KAAK,EAAE,OAAO,EAAE,KAAK,EAAE,SAAS,GAAG,IAAI,GAAG,OAAO,CAAC,YAAY,CAAC,CAAC;CACxE,CAAC;AA2BF,wBAAgB,KAAK,CAAC,KAAK,EAAE,SAAS,GAAG,IAAI,EAAE,IAAI,EAAE,MAAM,GAAG,OAAO,CAMpE;AAMD,wBAAgB,OAAO,CACrB,KAAK,EAAE,SAAS,GAAG,IAAI,EACvB,IAAI,EAAE;IAAE,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAC;IAAC,QAAQ,CAAC,cAAc,EAAE;QAAE,KAAK,EAAE,SAAS,MAAM,EAAE,CAAA;KAAE,GAAG,IAAI,CAAA;CAAE,GAC/F;IAAE,QAAQ,CAAC,UAAU,EAAE,OAAO,CAAC;IAAC,QAAQ,CAAC,SAAS,EAAE,OAAO,CAAA;CAAE,CAU/D;AAcD,wBAAgB,SAAS,CAAC,KAAK,EAAE,SAAS,GAAG,IAAI,GAAG,SAAS,GAAG,IAAI,CASnE;AA8ED,wBAAgB,QAAQ,CAAC,OAAO,EAAE,SAAS,EAAE,KAAK,EAAE,SAAS,GAAG,IAAI,GAAG,YAAY,CAgKlF"}
package/dist/reach.js ADDED
@@ -0,0 +1,270 @@
1
+ import { unheldView } from './conversation.js';
2
+ import { modelTypes, NO_MODEL } from './model.js';
3
+ import { applied, observing } from './observation.js';
4
+ import { beneath } from './paths.js';
5
+ import { reconciled } from './read-side.js';
6
+ import { moveTarget, readParts } from './room-draft.js';
7
+ import { documentKey } from './rows.js';
8
+ const UNHELD_TYPES = { collection: modelTypes(NO_MODEL), typedSelection: null };
9
+ const UNDECLARED = { kind: 'undeclared' };
10
+ function undeclared() {
11
+ return Promise.resolve(UNDECLARED);
12
+ }
13
+ const NO_CONVERSATION = {
14
+ list: () => Promise.resolve([]),
15
+ read: (conversation) => Promise.resolve(unheldView(conversation)),
16
+ create: undeclared,
17
+ send: undeclared,
18
+ answer: undeclared,
19
+ interrupt: undeclared,
20
+ kill: undeclared,
21
+ cancel: undeclared,
22
+ delete: undeclared,
23
+ };
24
+ const NO_CHAT_DRAFT = {
25
+ write: () => Promise.resolve(),
26
+ discard: () => Promise.resolve(),
27
+ };
28
+ export function holds(reach, room) {
29
+ return (reach === null ||
30
+ reach.rooms.includes(room) ||
31
+ reach.documents.some((document) => document.room === room));
32
+ }
33
+ function wholly(reach, room) {
34
+ return reach === null || reach.rooms.includes(room);
35
+ }
36
+ export function governs(reach, room) {
37
+ if (wholly(reach, room.locator)) {
38
+ return { collection: true, selection: room.typedSelection !== null };
39
+ }
40
+ const selected = (path) => room.typedSelection?.roots.some((root) => beneath(root, path)) ?? false;
41
+ const paths = reach.documents
42
+ .filter((document) => document.room === room.locator)
43
+ .map(({ path }) => path);
44
+ return { collection: paths.some((path) => !selected(path)), selection: paths.some(selected) };
45
+ }
46
+ function covers(reach, room, path) {
47
+ return (reach === null ||
48
+ reach.rooms.includes(room) ||
49
+ reach.documents.some((document) => document.room === room && document.path === path));
50
+ }
51
+ function conversing(reach) {
52
+ return reach === null || reach.conversations;
53
+ }
54
+ export function planReach(reach) {
55
+ return reach === null
56
+ ? null
57
+ : {
58
+ rooms: [...new Set(reach.rooms)].sort(),
59
+ documents: [
60
+ ...new Set(reach.documents.map(({ room, path }) => documentKey(room, path))),
61
+ ].sort(),
62
+ };
63
+ }
64
+ function roomsWithin(reach, rooms) {
65
+ return rooms.filter((room) => wholly(reach, room.locator));
66
+ }
67
+ function typesWithin(reach, room, types) {
68
+ if (room === undefined)
69
+ return structuredClone(UNHELD_TYPES);
70
+ const governed = governs(reach, room);
71
+ return {
72
+ collection: governed.collection ? types.collection : modelTypes(NO_MODEL),
73
+ typedSelection: governed.selection ? types.typedSelection : null,
74
+ };
75
+ }
76
+ function moves(reach, room, move) {
77
+ return move === undefined || covers(reach, room, moveTarget(move));
78
+ }
79
+ function draftWithin(reach, draft) {
80
+ return covers(reach, draft.room, draft.path) && moves(reach, draft.room, draft.parts.move);
81
+ }
82
+ function draftsWithin(reach, drafts) {
83
+ return drafts.filter((draft) => draftWithin(reach, draft));
84
+ }
85
+ function shownDraft(reach, draft) {
86
+ return draft !== null && draftWithin(reach, draft) ? draft : null;
87
+ }
88
+ function writeWithin(reach, write) {
89
+ return write.outcome === 'written'
90
+ ? { outcome: 'written', roomDraft: shownDraft(reach, write.roomDraft) }
91
+ : { outcome: 'stale', current: shownDraft(reach, write.current) };
92
+ }
93
+ function savedWithin(reach, room, result) {
94
+ if (reach === null || result.outcome === 'saved')
95
+ return result;
96
+ const { file, location, referrers, ...refusal } = result;
97
+ const hidden = file !== undefined && !covers(reach, room, file);
98
+ return {
99
+ ...refusal,
100
+ ...(file === undefined || hidden ? {} : { file }),
101
+ ...(location === undefined || hidden ? {} : { location }),
102
+ ...(referrers === undefined
103
+ ? {}
104
+ : { referrers: referrers.filter((path) => covers(reach, room, path)) }),
105
+ };
106
+ }
107
+ function statusWithin(reach, status) {
108
+ return {
109
+ ...status,
110
+ attentionRequired: status.attentionRequired.filter((entry) => covers(reach, entry.room, entry.path)),
111
+ };
112
+ }
113
+ function queueWithin(reach, room, entries) {
114
+ return entries.filter(({ batch }) => batch.changes.every((change) => covers(reach, room, change.path) &&
115
+ (change.kind !== 'move' || covers(reach, room, change.to))));
116
+ }
117
+ function unreached(room) {
118
+ return new Error(`No Local Replica for ${room}`);
119
+ }
120
+ export function narrowed(runtime, given) {
121
+ const { md, watch } = runtime;
122
+ let reach = given;
123
+ const open = new Set();
124
+ function following(begin) {
125
+ let stop = begin();
126
+ const restart = () => {
127
+ stop();
128
+ stop = begin();
129
+ };
130
+ open.add(restart);
131
+ return () => {
132
+ open.delete(restart);
133
+ stop();
134
+ };
135
+ }
136
+ const within = (topic, input, deliver) => {
137
+ if (topic === 'rooms') {
138
+ return following(() => watch(topic, input, (rooms) => deliver(roomsWithin(reach, rooms))));
139
+ }
140
+ if (topic === 'sync-status') {
141
+ return following(() => watch(topic, input, (status) => deliver(statusWithin(reach, status))));
142
+ }
143
+ if (topic === 'room-drafts') {
144
+ return following(() => watch(topic, input, (drafts) => deliver(draftsWithin(reach, drafts))));
145
+ }
146
+ if (topic === 'queue') {
147
+ const room = input[0];
148
+ return following(() => {
149
+ if (!holds(reach, room)) {
150
+ deliver([]);
151
+ return () => { };
152
+ }
153
+ return watch(topic, input, (entries) => deliver(queueWithin(reach, room, entries)));
154
+ });
155
+ }
156
+ if (topic === 'query') {
157
+ const plan = runtime.plan(input[0], reach);
158
+ let held = null;
159
+ return following(() => {
160
+ let first = true;
161
+ return runtime.watchPlan({ ...plan, reach: planReach(reach) }, (message) => {
162
+ if (!first) {
163
+ held = applied(held, message);
164
+ deliver(message);
165
+ return;
166
+ }
167
+ first = false;
168
+ if (held === null) {
169
+ held = message;
170
+ deliver(message);
171
+ return;
172
+ }
173
+ const next = reconciled(held, message);
174
+ if (next === null)
175
+ return;
176
+ held = next.keyed;
177
+ deliver(next.change);
178
+ });
179
+ });
180
+ }
181
+ if (topic === 'conversation') {
182
+ return following(() => {
183
+ if (conversing(reach))
184
+ return watch(topic, input, deliver);
185
+ deliver(unheldView(input[0]));
186
+ return () => { };
187
+ });
188
+ }
189
+ if (topic === 'conversations') {
190
+ return following(() => {
191
+ if (conversing(reach))
192
+ return watch(topic, input, deliver);
193
+ deliver([]);
194
+ return () => { };
195
+ });
196
+ }
197
+ return watch(topic, input, deliver);
198
+ };
199
+ const conversation = () => (conversing(reach) ? md.conversation : NO_CONVERSATION);
200
+ const chatDraft = () => (conversing(reach) ? md.chatDraft : NO_CHAT_DRAFT);
201
+ const view = {
202
+ ...md,
203
+ rooms: () => roomsWithin(reach, md.rooms()),
204
+ query: ((input) => runtime.query(runtime.plan(input, reach))),
205
+ search: (input) => runtime.search(input, reach),
206
+ types(room) {
207
+ if (wholly(reach, room))
208
+ return md.types(room);
209
+ if (!holds(reach, room))
210
+ return structuredClone(UNHELD_TYPES);
211
+ const listed = md.rooms().find(({ locator }) => locator === room);
212
+ return typesWithin(reach, listed, md.types(room));
213
+ },
214
+ async save(room, roomDrafts, writtenBy) {
215
+ if (!holds(reach, room))
216
+ throw unreached(room);
217
+ const outside = roomDrafts.find(({ path }) => !covers(reach, room, path) ||
218
+ !moves(reach, room, md.roomDraft.read(room, path)?.parts.move));
219
+ if (outside !== undefined)
220
+ return { outcome: 'refused', rule: 'stale', file: outside.path };
221
+ return savedWithin(reach, room, await md.save(room, roomDrafts, writtenBy));
222
+ },
223
+ history: (room, path, query) => covers(reach, room, path)
224
+ ? md.history(room, path, query)
225
+ : Promise.resolve({ kind: 'room-not-readable', locator: room }),
226
+ reached: (room, roomVersion, path) => (path === undefined ? wholly(reach, room) : covers(reach, room, path)) &&
227
+ md.reached(room, roomVersion, path),
228
+ log: () => (reach === null ? md.log() : ''),
229
+ roomDraft: {
230
+ list: () => md.roomDraft.list().then((drafts) => draftsWithin(reach, drafts)),
231
+ read: (room, path) => covers(reach, room, path) ? shownDraft(reach, md.roomDraft.read(room, path)) : null,
232
+ async write(room, path, revision, parts) {
233
+ if (!covers(reach, room, path) || !moves(reach, room, readParts(parts).move)) {
234
+ throw unreached(room);
235
+ }
236
+ return writeWithin(reach, await md.roomDraft.write(room, path, revision, parts));
237
+ },
238
+ async discard(room, path, revision) {
239
+ if (!covers(reach, room, path))
240
+ return { outcome: 'stale', current: null };
241
+ return writeWithin(reach, await md.roomDraft.discard(room, path, revision));
242
+ },
243
+ },
244
+ conversation: {
245
+ list: () => conversation().list(),
246
+ read: (id, options) => conversation().read(id, options),
247
+ create: (input) => conversation().create(input),
248
+ send: (id) => conversation().send(id),
249
+ answer: (id, answer) => conversation().answer(id, answer),
250
+ interrupt: (id) => conversation().interrupt(id),
251
+ kill: (id) => conversation().kill(id),
252
+ cancel: (id, turn) => conversation().cancel(id, turn),
253
+ delete: (id) => conversation().delete(id),
254
+ },
255
+ chatDraft: {
256
+ write: (id, draft) => chatDraft().write(id, draft),
257
+ discard: (id) => chatDraft().discard(id),
258
+ },
259
+ observe: observing(within),
260
+ };
261
+ return {
262
+ md: view,
263
+ watch: within,
264
+ narrow(next) {
265
+ reach = next;
266
+ for (const restart of [...open])
267
+ restart();
268
+ },
269
+ };
270
+ }
@@ -0,0 +1,39 @@
1
+ import type { MdRuntimeClient } from './client.js';
2
+ import type { AppRoom, ConnectionRefusal, SaveResult } from './connection.js';
3
+ import type { Member, ServiceMode } from './adapter.js';
4
+ import type { ConversationEntry, ConversationOptions, ConversationView } from './conversation.js';
5
+ import type { QueueEntry } from './outcome.js';
6
+ import type { DocumentQuery, DocumentResult, GroupQuery, GroupResult } from './query.js';
7
+ import type { RoomDraft, RoomDraftParts } from './room-draft.js';
8
+ import type { SyncStatus } from './status.js';
9
+ type Client = MdRuntimeClient | null;
10
+ export type Observed<T> = {
11
+ readonly state: 'loading';
12
+ } | {
13
+ readonly state: 'ready';
14
+ readonly value: T;
15
+ };
16
+ export declare function useObserve(client: Client, topic: 'deployment-facts'): Observed<unknown>;
17
+ export declare function useObserve(client: Client, topic: 'rooms'): Observed<readonly AppRoom[]>;
18
+ export declare function useObserve(client: Client, topic: 'connection-refusal'): Observed<ConnectionRefusal | null>;
19
+ export declare function useObserve(client: Client, topic: 'storage-loss'): Observed<string | null>;
20
+ export declare function useObserve(client: Client, topic: 'sync-status'): Observed<SyncStatus>;
21
+ export declare function useObserve(client: Client, topic: 'service-mode'): Observed<ServiceMode>;
22
+ export declare function useObserve(client: Client, topic: 'member'): Observed<Member | null>;
23
+ export declare function useObserve(client: Client, topic: 'query', query: DocumentQuery): Observed<DocumentResult>;
24
+ export declare function useObserve(client: Client, topic: 'query', query: GroupQuery): Observed<GroupResult>;
25
+ export declare function useObserve(client: Client, topic: 'queue', locator: string): Observed<readonly QueueEntry[]>;
26
+ export declare function useObserve(client: Client, topic: 'room-drafts'): Observed<readonly RoomDraft[]>;
27
+ export declare function useObserve(client: Client, topic: 'presentation'): Observed<unknown>;
28
+ export declare function useObserve(client: Client, topic: 'conversation', conversation: string, options: ConversationOptions): Observed<ConversationView>;
29
+ export declare function useObserve(client: Client, topic: 'conversations'): Observed<readonly ConversationEntry[]>;
30
+ export type Saving = {
31
+ readonly busy: boolean;
32
+ readonly outcome: SaveResult | null;
33
+ readonly failure: Error | null;
34
+ save(room: string, roomDrafts: ReadonlyMap<string, RoomDraftParts>): Promise<SaveResult>;
35
+ };
36
+ export declare function saveRoomDrafts(client: MdRuntimeClient, room: string, roomDrafts: ReadonlyMap<string, RoomDraftParts>): Promise<SaveResult>;
37
+ export declare function useSave(client: MdRuntimeClient): Saving;
38
+ export {};
39
+ //# sourceMappingURL=react.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"react.d.ts","sourceRoot":"","sources":["../src/react.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,aAAa,CAAC;AACnD,OAAO,KAAK,EAAE,OAAO,EAAE,iBAAiB,EAAkB,UAAU,EAAE,MAAM,iBAAiB,CAAC;AAC9F,OAAO,KAAK,EAAE,MAAM,EAAE,WAAW,EAAE,MAAM,cAAc,CAAC;AACxD,OAAO,KAAK,EAAE,iBAAiB,EAAE,mBAAmB,EAAE,gBAAgB,EAAE,MAAM,mBAAmB,CAAC;AAElG,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,cAAc,CAAC;AAC/C,OAAO,KAAK,EAAE,aAAa,EAAE,cAAc,EAAE,UAAU,EAAE,WAAW,EAAE,MAAM,YAAY,CAAC;AACzF,OAA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U,EAAE,WAAW,CAAC,MAAM,EAAE,cAAc,CAAC,GAC9C,OAAO,CAAC,UAAU,CAAC,CAWrB;AAED,wBAAgB,OAAO,CAAC,MAAM,EAAE,eAAe,GAAG,MAAM,CAkBvD"}
package/dist/react.js ADDED
@@ -0,0 +1,63 @@
1
+ import { useCallback, useLayoutEffect, useRef, useState } from 'react';
2
+ const LOADING = { state: 'loading' };
3
+ export function useObserve(client, topic, ...input) {
4
+ const key = JSON.stringify([topic, ...input]);
5
+ const [held, setHeld] = useState(null);
6
+ const opened = useRef(input);
7
+ opened.current = input;
8
+ useLayoutEffect(() => {
9
+ if (client === null)
10
+ return;
11
+ let live = true;
12
+ let observation = null;
13
+ const observe = client.observe;
14
+ void observe(topic, ...opened.current).then((open) => {
15
+ if (!live) {
16
+ open.close();
17
+ return;
18
+ }
19
+ observation = open;
20
+ const take = (value) => {
21
+ if (live)
22
+ setHeld({ client, key, observed: { state: 'ready', value } });
23
+ };
24
+ take(open.current());
25
+ open.subscribe(take);
26
+ });
27
+ return () => {
28
+ live = false;
29
+ observation?.close();
30
+ };
31
+ }, [client, key]);
32
+ return held !== null && held.client === client && held.key === key ? held.observed : LOADING;
33
+ }
34
+ const IDLE = { busy: false, outcome: null, failure: null };
35
+ export async function saveRoomDrafts(client, room, roomDrafts) {
36
+ const kept = [];
37
+ for (const [path, parts] of roomDrafts) {
38
+ const prior = await client.roomDraft.read(room, path);
39
+ const write = await client.roomDraft.write(room, path, prior?.revision ?? null, parts);
40
+ if (write.outcome !== 'written' || write.roomDraft === null) {
41
+ throw new Error(`the Room Draft at ${path} was not written`);
42
+ }
43
+ kept.push({ path, revision: write.roomDraft.revision });
44
+ }
45
+ return client.save(room, kept);
46
+ }
47
+ export function useSave(client) {
48
+ const [state, setState] = useState(IDLE);
49
+ const save = useCallback(async (room, roomDrafts) => {
50
+ setState({ busy: true, outcome: null, failure: null });
51
+ try {
52
+ const outcome = await saveRoomDrafts(client, room, roomDrafts);
53
+ setState({ busy: false, outcome, failure: null });
54
+ return outcome;
55
+ }
56
+ catch (error) {
57
+ const failure = error instanceof Error ? error : new Error(String(error));
58
+ setState({ busy: false, outcome: null, failure });
59
+ throw failure;
60
+ }
61
+ }, [client]);
62
+ return { ...state, save };
63
+ }
@@ -10,5 +10,9 @@ export type ReadSide = {
10
10
  document(room: string, path: string): SearchedDocument | null;
11
11
  close(): void;
12
12
  };
13
+ export declare function reconciled(previous: KeyedResult, next: KeyedResult): {
14
+ keyed: KeyedResult;
15
+ change: QueryChange;
16
+ } | null;
13
17
  export declare function createReadSide(): ReadSide;
14
18
  //# sourceMappingURL=read-side.d.ts.map