@agentshouse/mdruntime 0.1.0-c0d767f8f799a → 0.1.0-c104334047dfe

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 (71) hide show
  1. package/AGENTS.md +200 -194
  2. package/README.md +8 -8
  3. package/dist/adapter.d.ts +18 -1
  4. package/dist/adapter.d.ts.map +1 -1
  5. package/dist/chat/earlier.d.ts +10 -0
  6. package/dist/chat/earlier.d.ts.map +1 -0
  7. package/dist/chat/earlier.js +54 -0
  8. package/dist/chat/list.d.ts.map +1 -1
  9. package/dist/chat/list.js +39 -3
  10. package/dist/chat/provider.d.ts.map +1 -1
  11. package/dist/chat/provider.js +9 -10
  12. package/dist/chat/question.d.ts +1 -1
  13. package/dist/chat/question.d.ts.map +1 -1
  14. package/dist/chat/question.js +7 -18
  15. package/dist/chat/style.js +1 -1
  16. package/dist/client.d.ts +6 -2
  17. package/dist/client.d.ts.map +1 -1
  18. package/dist/client.js +7 -3
  19. package/dist/connection.d.ts +9 -2
  20. package/dist/connection.d.ts.map +1 -1
  21. package/dist/connection.js +254 -62
  22. package/dist/conversation.d.ts +5 -0
  23. package/dist/conversation.d.ts.map +1 -1
  24. package/dist/conversation.js +94 -31
  25. package/dist/host.d.ts.map +1 -1
  26. package/dist/host.js +8 -0
  27. package/dist/index.d.ts +3 -3
  28. package/dist/index.d.ts.map +1 -1
  29. package/dist/memory.d.ts +2 -1
  30. package/dist/memory.d.ts.map +1 -1
  31. package/dist/memory.js +10 -0
  32. package/dist/observation.d.ts +2 -0
  33. package/dist/observation.d.ts.map +1 -1
  34. package/dist/observation.js +9 -3
  35. package/dist/outcome.d.ts +8 -2
  36. package/dist/outcome.d.ts.map +1 -1
  37. package/dist/outcome.js +3 -0
  38. package/dist/query.d.ts +21 -1
  39. package/dist/query.d.ts.map +1 -1
  40. package/dist/query.js +28 -5
  41. package/dist/reach.d.ts.map +1 -1
  42. package/dist/reach.js +13 -0
  43. package/dist/react.d.ts +1 -2
  44. package/dist/react.d.ts.map +1 -1
  45. package/dist/react.js +2 -14
  46. package/dist/read-side.d.ts.map +1 -1
  47. package/dist/read-side.js +173 -48
  48. package/dist/replica.d.ts +5 -1
  49. package/dist/replica.d.ts.map +1 -1
  50. package/dist/replica.js +19 -3
  51. package/dist/rows.d.ts +1 -0
  52. package/dist/rows.d.ts.map +1 -1
  53. package/dist/rows.js +5 -0
  54. package/dist/save.d.ts +1 -0
  55. package/dist/save.d.ts.map +1 -1
  56. package/dist/save.js +17 -1
  57. package/dist/search.d.ts +15 -2
  58. package/dist/search.d.ts.map +1 -1
  59. package/dist/search.js +76 -17
  60. package/dist/seed.d.ts.map +1 -1
  61. package/dist/seed.js +18 -4
  62. package/dist/store.d.ts +16 -2
  63. package/dist/store.d.ts.map +1 -1
  64. package/dist/store.js +48 -14
  65. package/dist/windows.d.ts +26 -0
  66. package/dist/windows.d.ts.map +1 -0
  67. package/dist/windows.js +93 -0
  68. package/dist/wire.d.ts +16 -0
  69. package/dist/wire.d.ts.map +1 -1
  70. package/dist/wire.js +4 -0
  71. package/package.json +2 -2
package/dist/query.js CHANGED
@@ -1,6 +1,7 @@
1
1
  import { pointerFacts, } from '@agentshouse/mdmodel';
2
2
  import { referenceField } from './model.js';
3
3
  import { normalize } from './paths.js';
4
+ import { decodedCursor } from './windows.js';
4
5
  export class QueryError extends Error {
5
6
  code;
6
7
  retryable = false;
@@ -11,7 +12,7 @@ export class QueryError extends Error {
11
12
  }
12
13
  const RANGE = ['$gt', '$gte', '$lt', '$lte'];
13
14
  const SINGLE = ['$eq', '$ne', '$in', '$nin', '$all', '$size', '$exists'];
14
- const FILTER = ['rooms', 'types', 'where', 'pathPrefix', 'hop', 'backlinks'];
15
+ const FILTER = ['rooms', 'types', 'where', 'pathPrefix', 'folder', 'paths', 'hop', 'backlinks'];
15
16
  const RELATED = ['types', 'where', 'pathPrefix', 'field'];
16
17
  const PARTS = ['fields', 'sections', 'preamble', 'markdown', 'backlinks', 'change', 'fileId'];
17
18
  const ORDER = ['by', 'direction', 'nulls', 'stringSort', 'locale', 'localeOptions'];
@@ -60,6 +61,13 @@ function names(input, at) {
60
61
  invalid(at, 'expects a list of names');
61
62
  return [...new Set(listed)].sort();
62
63
  }
64
+ function pathsOf(input) {
65
+ const listed = list(input, 'paths');
66
+ if (listed.some((item) => typeof item !== 'string' || item === '' || normalize(item) !== item)) {
67
+ invalid('paths', 'expects a list of Paths');
68
+ }
69
+ return [...new Set(listed)].sort();
70
+ }
63
71
  function directory(input, at) {
64
72
  if (typeof input !== 'string' || normalize(input) !== input) {
65
73
  invalid(at, 'expects a normalized directory');
@@ -279,15 +287,16 @@ function backlinksOf(facts, rooms, input) {
279
287
  return { types, where, pathPrefix, field };
280
288
  }
281
289
  function keyPlan(typed, input, at, path) {
282
- if (input === 'room' || input === 'type' || (path && input === 'path'))
290
+ if (input === 'room' || input === 'type' || input === 'folder' || (path && input === 'path')) {
283
291
  return { of: input };
292
+ }
284
293
  if (plain(input) && Object.hasOwn(input, 'field') && Object.keys(input).length === 1) {
285
294
  if (specs(typed, input.field, place(at, 'field')).some(several)) {
286
295
  invalid(place(at, 'field'), 'a path that can hold several values');
287
296
  }
288
297
  return { of: 'field', field: input.field };
289
298
  }
290
- return invalid(at, path ? 'expects room, path, type or a field' : 'expects room, type or a field');
299
+ return invalid(at, path ? 'expects room, path, type, folder or a field' : 'expects room, type, folder or a field');
291
300
  }
292
301
  function direction(input, at) {
293
302
  if (input === undefined)
@@ -423,21 +432,35 @@ export function planOf(input, facts, reach = null) {
423
432
  invalid('select', 'a grouped query selects nothing');
424
433
  if (!grouped && input.select === undefined)
425
434
  invalid('select', 'a Document query must select');
426
- known(input, [...FILTER, 'orderBy', 'limit', grouped ? 'groupBy' : 'select'], '');
435
+ known(input, [...FILTER, 'orderBy', 'limit', 'after', 'total', grouped ? 'groupBy' : 'select'], '');
427
436
  const limit = limitOf(input.limit);
428
437
  const rooms = input.rooms === undefined ? null : names(input.rooms, 'rooms');
429
438
  const { typed, ...root } = scope(facts, rooms, input, '');
439
+ const shape = grouped ? groupShape(typed, input) : documentShape(typed, input);
430
440
  return {
431
441
  key: queryKey(input),
432
442
  rooms,
433
443
  reach,
434
444
  root,
445
+ folder: input.folder === undefined ? null : directory(input.folder, 'folder'),
446
+ paths: input.paths === undefined ? null : pathsOf(input.paths),
435
447
  hop: input.hop === undefined ? null : hopOf(facts, rooms, typed, input.hop),
436
448
  backlinks: input.backlinks === undefined ? null : backlinksOf(facts, rooms, input.backlinks),
437
- shape: grouped ? groupShape(typed, input) : documentShape(typed, input),
449
+ shape,
438
450
  limit,
451
+ after: continuationOf(input.after, shape.orderBy.length + 1),
452
+ total: flag(input.total, 'total'),
439
453
  };
440
454
  }
455
+ function continuationOf(input, arity) {
456
+ if (input === undefined)
457
+ return null;
458
+ const values = typeof input === 'string' ? decodedCursor(input) : null;
459
+ if (values === null || (values.length !== 0 && values.length !== arity)) {
460
+ invalid('after', 'expects the next an earlier result of this query returned');
461
+ }
462
+ return { text: input, values: values.length === 0 ? null : values };
463
+ }
441
464
  export function limitOf(input) {
442
465
  if (input === undefined)
443
466
  return null;
@@ -1 +1 @@
1
- {"version":3,"file":"reach.d.ts","sourceRoot":"","sources":["../src/reach.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,cAAc,CAAC;AAClD,OAAO,KAAK,EAEV,SAAS,EACT,aAAa,EAEb,YAAY,EAEb,MAAM,iBAAiB,CAAC;AAazB,OAAO,KAAK,EAAE,IAAI,EAAE,SAAS,EAAE,WAAW,EAAE,MAAM,YAAY,CAAC;AAU/D,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,gBAAgB,CAAC;AAChD,OAAO,EAAoB,KAAK,YAAY,EAAE,MAAM,aAAa,CAAC;AAGlE,MAAM,MAAM,eAAe,GAAG;IAAE,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IAAC,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAA;CA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,GAAG,IAAI,EACvB,OAAO,EAAE,CAAC,SAAS,EAAE,SAAS,KAAK,IAAI,GACtC,MAAM,IAAI,CAAC;IACd,aAAa,CAAC,QAAQ,EAAE,OAAO,GAAG,aAAa,GAAG,IAAI,CAAC;CACxD,CAAC;AA0BF,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;AA2BD,wBAAgB,SAAS,CAAC,KAAK,EAAE,SAAS,GAAG,IAAI,GAAG,SAAS,GAAG,IAAI,CASnE;AA8ED,wBAAgB,QAAQ,CACtB,OAAO,EAAE,SAAS,EAClB,KAAK,EAAE,SAAS,GAAG,IAAI,EACvB,IAAI,EAAE,aAAa,GAClB,YAAY,CAwMd"}
package/dist/reach.js CHANGED
@@ -25,6 +25,7 @@ const NO_CONVERSATION = {
25
25
  };
26
26
  const NO_CHAT_DRAFT = {
27
27
  write: () => Promise.resolve(),
28
+ prepend: () => Promise.resolve(),
28
29
  discard: () => Promise.resolve(),
29
30
  };
30
31
  export function holds(reach, room) {
@@ -243,6 +244,14 @@ export function narrowed(runtime, given, told) {
243
244
  }
244
245
  return savedWithin(reach, room, await md.save(room, roomDrafts, writtenBy));
245
246
  },
247
+ async saveParts(room, parts, writtenBy) {
248
+ if (!holds(reach, room))
249
+ throw unreached(room);
250
+ if (parts.some(({ path, parts: one }) => !covers(reach, room, path) || !moves(reach, room, readParts(one).move))) {
251
+ throw unreached(room);
252
+ }
253
+ return savedWithin(reach, room, await md.saveParts(room, parts, writtenBy));
254
+ },
246
255
  history: (room, path, query) => covers(reach, room, path)
247
256
  ? md.history(room, path, query)
248
257
  : Promise.resolve(failure({ kind: 'room-not-readable', locator: room })),
@@ -250,6 +259,9 @@ export function narrowed(runtime, given, told) {
250
259
  read: (room, path, revision) => covers(reach, room, path)
251
260
  ? md.binaryFile.read(room, path, revision)
252
261
  : Promise.resolve(failure({ kind: 'room-not-readable', locator: room })),
262
+ link: (room, path, revision) => covers(reach, room, path)
263
+ ? md.binaryFile.link(room, path, revision)
264
+ : Promise.resolve(failure({ kind: 'room-not-readable', locator: room })),
253
265
  readReference: (reference) => refers(reach, runtime.referrerScope(reference.referrer))
254
266
  ? md.binaryFile.readReference(reference)
255
267
  : Promise.resolve(unreachedReference(reference.fileRef)),
@@ -285,6 +297,7 @@ export function narrowed(runtime, given, told) {
285
297
  },
286
298
  chatDraft: {
287
299
  write: (id, draft, revision) => chatDraft().write(id, draft, revision),
300
+ prepend: (id, draft) => chatDraft().prepend(id, draft),
288
301
  discard: (id) => chatDraft().discard(id),
289
302
  },
290
303
  observe: observing(within),
package/dist/react.d.ts CHANGED
@@ -35,10 +35,9 @@ export type Saving = {
35
35
  readonly busy: boolean;
36
36
  readonly outcome: SaveResult | null;
37
37
  readonly failure: RuntimeError | null;
38
- save(room: string, roomDrafts: ReadonlyMap<string, RoomDraftParts>): Promise<SaveResult>;
38
+ save(room: string, parts: ReadonlyMap<string, RoomDraftParts>): Promise<SaveResult>;
39
39
  saveWritten(room: string, roomDrafts: readonly SavedRoomDraft[]): Promise<SaveResult>;
40
40
  };
41
- export declare function saveRoomDrafts(client: MdRuntimeClient, room: string, roomDrafts: ReadonlyMap<string, RoomDraftParts>): Promise<SaveResult>;
42
41
  export declare function useSave(client: MdRuntimeClient): Saving;
43
42
  export {};
44
43
  //# sourceMappingURL=react.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"react.d.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C,CAAC;AACrF,wBAAgB,UAAU,CACxB,MAAM,EAAE,MAAM,EACd,KAAK,EAAE,cAAc,EACrB,YAAY,EAAE,MAAM,EACpB,OAAO,EAAE,mBAAmB,GAC3B,QAAQ,CAAC,gBAAgB,CAAC,CAAC;AAC9B,wBAAgB,UAAU,CACxB,MAAM,EAAE,MAAM,EACd,KAAK,EAAE,eAAe,GACrB,QAAQ,CAAC,SAAS,iBAAiB,EAAE,CAAC,CAAC;AAC1C,wBAAgB,UAAU,CAAC,MAAM,EAAE,MAAM,EAAE,KAAK,EAAE,QAAQ,GAAG,QAAQ,CAAC,SAAS,iBAAiB,EAAE,CAAC,CAAC;AAsCpG,MAAM,MAAM,MAAM,GAAG;IACnB,QAAQ,CAAC,IAAI,EAAE,OAAO,CAAC;IACvB,QAAQ,CAAC,OAAO,EAAE,UAAU,GAAG,IAAI,CAAC;IACpC,QAAQ,CAAC,OAAO,EAAE,YAAY,GAAG,IAAI,CAAC;IACtC,IAAI,CAAC,IAAI,EAAE,MAAM,EAAE,KAAK,EAAE,WAAW,CAAC,MAAM,EAAE,cAAc,CAAC,GAAG,OAAO,CAAC,UAAU,CAAC,CAAC;IACpF,WAAW,CAAC,IAAI,EAAE,MAAM,EAAE,UAAU,EAAE,SAAS,cAAc,EAAE,GAAG,OAAO,CAAC,UAAU,CAAC,CAAC;CACvF,CAAC;AAMF,wBAAgB,OAAO,CAAC,MAAM,EAAE,eAAe,GAAG,MAAM,CA8BvD"}
package/dist/react.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import { useCallback, useLayoutEffect, useRef, useState } from 'react';
2
- import { failed, runtimeError } from './failure.js';
2
+ import { failed } from './failure.js';
3
3
  const LOADING = { state: 'loading' };
4
4
  export function useObserve(client, topic, ...input) {
5
5
  const key = JSON.stringify([topic, ...input]);
@@ -33,18 +33,6 @@ export function useObserve(client, topic, ...input) {
33
33
  return held !== null && held.client === client && held.key === key ? held.observed : LOADING;
34
34
  }
35
35
  const IDLE = { busy: false, outcome: null, failure: null };
36
- export async function saveRoomDrafts(client, room, roomDrafts) {
37
- const kept = [];
38
- for (const [path, parts] of roomDrafts) {
39
- const prior = await client.roomDraft.read(room, path);
40
- const write = await client.roomDraft.write(room, path, prior?.revision ?? null, parts);
41
- if (write.outcome !== 'written' || write.roomDraft === null) {
42
- throw runtimeError(write.outcome === 'stale' ? write.code : 'room-draft-unwritten', `the Room Draft at ${path} was not written`);
43
- }
44
- kept.push({ path, revision: write.roomDraft.revision });
45
- }
46
- return client.save(room, kept);
47
- }
48
36
  export function useSave(client) {
49
37
  const [state, setState] = useState(IDLE);
50
38
  const settled = useCallback(async (saving) => {
@@ -60,7 +48,7 @@ export function useSave(client) {
60
48
  throw failure;
61
49
  }
62
50
  }, []);
63
- const save = useCallback((room, roomDrafts) => settled(() => saveRoomDrafts(client, room, roomDrafts)), [client, settled]);
51
+ const save = useCallback((room, parts) => settled(() => client.saveParts(room, [...parts].map(([path, one]) => ({ path, parts: one })))), [client, settled]);
64
52
  const saveWritten = useCallback((room, roomDrafts) => settled(() => client.save(room, roomDrafts)), [client, settled]);
65
53
  return { ...state, save, saveWritten };
66
54
  }
@@ -1 +1 @@
1
- {"version":3,"file":"read-side.d.ts","sourceRoot":"","sources":["../src/read-side.ts"],"names":[],"mappings":"AAsBA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,iBAAiB,CAAC;AACjD,OAAO,EAAE,KAAK,WAAW,EAAE,KAAK,YAAY,EAAe,MAAM,kBAAkB,CAAC;AACpF,OAAO,KAAK,EAOV,aAAa,EACb,IAAI,EAEJ,aAAa,EAGb,SAAS,EAIV,MAAM,YAAY,CAAC;AAGpB,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,aAAa,CAAC;AA4CpD,MAAM,MAAM,KAAK,GAAG;IAAE,QAAQ,EAAE,aAAa,CAAA;CAAE,GAAG,aAAa,CAAC;AAuBhE,MAAM,MAAM,QAAQ,GAAG;IACrB,KAAK,CAAC,GAAG,EAAE,SAAS,GAA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AAC;AAwBhE,MAAM,MAAM,QAAQ,GAAG;IACrB,KAAK,CAAC,GAAG,EAAE,SAAS,GAAG,IAAI,CAAC;IAC5B,OAAO,IAAI,IAAI,CAAC;IAChB,KAAK,CAAC,CAAC,EAAE,IAAI,EAAE,IAAI,EAAE,EAAE,EAAE,MAAM,CAAC,GAAG,OAAO,CAAC;QAAE,IAAI,EAAE,SAAS,CAAC;QAAC,EAAE,EAAE,CAAC,CAAA;KAAE,CAAC,CAAC;IACvE,KAAK,CACH,IAAI,EAAE,IAAI,EACV,QAAQ,EAAE,MAAM,EAChB,KAAK,EAAE,MAAM,KAAK,EAClB,OAAO,EAAE,CAAC,OAAO,EAAE,YAAY,KAAK,IAAI,GACvC,MAAM,IAAI,CAAC;IACd,IAAI,CAAC,IAAI,EAAE,MAAM,GAAG,SAAS,MAAM,EAAE,CAAC;IACtC,QAAQ,CAAC,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,GAAG,gBAAgB,GAAG,IAAI,CAAC;IAC9D,KAAK,IAAI,IAAI,CAAC;CACf,CAAC;AAucF,wBAAgB,UAAU,CACxB,QAAQ,EAAE,WAAW,EACrB,IAAI,EAAE,WAAW,GAChB;IAAE,KAAK,EAAE,WAAW,CAAC;IAAC,OAAO,EAAE,YAAY,CAAA;CAAE,GAAG,IAAI,CA+CtD;AA4BD,wBAAgB,cAAc,IAAI,QAAQ,CA8SzC"}
package/dist/read-side.js CHANGED
@@ -2,6 +2,7 @@ import { and, BasicIndex, configureIndexDevMode, count, createCollection, create
2
2
  import { ARRAY_INDEX, parse, pointerSegments } from '@agentshouse/mdmodel';
3
3
  import { documentKey } from './rows.js';
4
4
  import { after, inUnits, ROW_WEIGHT } from './turn.js';
5
+ import { beyond, cursorOf, MAXIMUM_WINDOW, windowed } from './windows.js';
5
6
  function every(expressions) {
6
7
  const [first, second, ...rest] = expressions;
7
8
  return second === undefined ? first : and(first, second, ...rest);
@@ -59,10 +60,12 @@ function reached(reach, room, document) {
59
60
  ? []
60
61
  : [or(inArray(room, [...reach.rooms]), inArray(document, [...reach.documents]))];
61
62
  }
62
- function scoped(scope, row, rooms, reach) {
63
+ function scoped(scope, row, rooms, reach, paths = null, folder = null) {
63
64
  return every([
64
65
  eq(row.kind, 'document'),
65
66
  ...(rooms === null ? [] : [inArray(row.room, [...rooms])]),
67
+ ...(paths === null ? [] : [inArray(row.path, [...paths])]),
68
+ ...(folder === null ? [] : [eq(row.folder, folder)]),
66
69
  ...reached(reach, row.room, row.key),
67
70
  ...(scope.types === null ? [] : [inArray(row.type, [...scope.types])]),
68
71
  ...(scope.pathPrefix === null ? [] : [inArray(scope.pathPrefix, row.directories)]),
@@ -90,7 +93,7 @@ function related(q, rows, scope, field, kept, reach) {
90
93
  }
91
94
  function filtered(q, rows, plan) {
92
95
  const from = q.from({ d: rows });
93
- let query = narrowed(from.where(({ d }) => scoped(plan.root, d, plan.rooms, plan.reach)), plan.root.where, 'd');
96
+ let query = narrowed(from.where(({ d }) => scoped(plan.root, d, plan.rooms, plan.reach, plan.paths, plan.folder)), plan.root.where, 'd');
94
97
  if (plan.hop !== null) {
95
98
  const hop = related(q, rows, plan.hop, plan.hop.field, 'source', plan.reach);
96
99
  query = query.innerJoin({ h: hop }, ({ d, h }) => eq(d.key, h.key));
@@ -104,21 +107,51 @@ function filtered(q, rows, plan) {
104
107
  function bodied(shape) {
105
108
  return shape.sections !== null || shape.preamble || shape.markdown;
106
109
  }
110
+ function orderingOf(options) {
111
+ const collated = options.stringSort === 'locale';
112
+ return {
113
+ direction: options.direction,
114
+ nulls: options.nulls ?? 'first',
115
+ stringSort: options.stringSort ?? 'locale',
116
+ locale: collated ? options.locale : undefined,
117
+ localeOptions: collated
118
+ ? options.localeOptions
119
+ : undefined,
120
+ };
121
+ }
122
+ function storedValue(key, row) {
123
+ return key.of === 'field' ? row.values[key.field] : row[key.of];
124
+ }
125
+ function documentOrder(shape) {
126
+ return shape.orderBy.map(({ options }) => orderingOf(options));
127
+ }
128
+ function documentCursor(shape, row) {
129
+ return cursorOf([
130
+ ...shape.orderBy.map((_, index) => row[`order${index}`]),
131
+ documentKey(row.room, row.path),
132
+ ]);
133
+ }
107
134
  function documents(q, rows, plan, shape) {
108
135
  let query = filtered(q, rows, plan);
136
+ const cursor = plan.after?.values ?? null;
137
+ if (cursor !== null) {
138
+ const orderings = documentOrder(shape);
139
+ query = query.fn.where(({ d }) => beyond([...shape.orderBy.map(({ key }) => storedValue(key, d)), d.key], cursor, orderings));
140
+ }
109
141
  for (const { key, options } of shape.orderBy) {
110
142
  query = query.orderBy(({ d }) => keyed(key, d), options);
111
143
  }
112
- if (shape.orderBy.length === 0 && plan.limit !== null) {
144
+ if (shape.orderBy.length > 0 || plan.limit !== null || plan.after !== null) {
113
145
  query = query.orderBy(({ d }) => d.key, { stringSort: 'lexical' });
114
146
  }
115
147
  if (plan.limit !== null)
116
- query = query.limit(plan.limit);
148
+ query = query.limit(plan.limit + 1);
117
149
  return query.select(({ d }) => ({
118
150
  room: d.room,
119
151
  path: d.path,
120
152
  type: d.type,
121
153
  binary: d.binary,
154
+ ...Object.fromEntries(shape.orderBy.map(({ key }, index) => [`order${index}`, keyed(key, d)])),
122
155
  ...(shape.fields === null ? {} : { fields: d.fields }),
123
156
  ...(bodied(shape) ? { text: d.text } : {}),
124
157
  ...(shape.backlinks ? { backlinks: toArray(backlinked(q, rows, d, plan.reach)) } : {}),
@@ -134,15 +167,13 @@ function backlinked(q, rows, document, reach) {
134
167
  .orderBy(({ r }) => r.field, { stringSort: 'lexical' })
135
168
  .select(({ r }) => ({ path: r.path, type: r.type, field: r.field }));
136
169
  }
137
- function groups(q, stage, shape, limit) {
170
+ function groups(q, stage, shape) {
138
171
  const keys = shape.groupBy.map((_, index) => `key${index}`);
139
172
  const from = q.from({ m: stage });
140
173
  let query = from.groupBy(({ m }) => keys.map((key) => m[key]));
141
174
  for (const { by, direction } of shape.orderBy) {
142
175
  query = query.orderBy(({ m }) => (by === 'count' ? count(m.key) : m[keys[by]]), direction);
143
176
  }
144
- if (limit !== null && shape.orderBy.length > 0)
145
- query = query.limit(limit);
146
177
  return query.select(({ m }) => ({
147
178
  ...Object.fromEntries(keys.map((key) => [key, m[key]])),
148
179
  count: count(m.key),
@@ -152,15 +183,27 @@ function built(rows, plan) {
152
183
  const shape = plan.shape;
153
184
  if (shape.kind === 'documents') {
154
185
  const collection = live((q) => documents(q, rows, plan, shape));
155
- return { live: collection, dispose: () => void collection.cleanup() };
186
+ const count = plan.total
187
+ ? live((q) => filtered(q, rows, plan).select(({ d }) => ({ key: d.key })))
188
+ : null;
189
+ return {
190
+ live: collection,
191
+ count,
192
+ dispose: () => {
193
+ void collection.cleanup();
194
+ if (count !== null)
195
+ void count.cleanup();
196
+ },
197
+ };
156
198
  }
157
199
  const stage = live((q) => filtered(q, rows, plan).select(({ d }) => ({
158
200
  key: d.key,
159
201
  ...Object.fromEntries(shape.groupBy.map((key, index) => [`key${index}`, keyed(key, d)])),
160
202
  })));
161
- const collection = live((q) => groups(q, stage, shape, plan.limit));
203
+ const collection = live((q) => groups(q, stage, shape));
162
204
  return {
163
205
  live: collection,
206
+ count: null,
164
207
  dispose: () => {
165
208
  void collection.cleanup();
166
209
  void stage.cleanup();
@@ -262,7 +305,9 @@ function documentOf(key, row, shape, bodies) {
262
305
  ...(shape.markdown && body !== null ? { markdown: body.content } : {}),
263
306
  ...(shape.backlinks
264
307
  ? {
265
- backlinks: row.backlinks.map(({ path, type, field }) => ({ path, type, field })),
308
+ backlinks: row.backlinks
309
+ .slice(0, MAXIMUM_WINDOW)
310
+ .map(({ path, type, field }) => ({ path, type, field })),
266
311
  }
267
312
  : {}),
268
313
  ...(shape.change ? { change: row.change } : {}),
@@ -272,24 +317,62 @@ function documentOf(key, row, shape, bodies) {
272
317
  function weight(row) {
273
318
  return ROW_WEIGHT + (typeof row?.text === 'string' ? row.text.length : 0);
274
319
  }
275
- function rowsOfPlan(plan, entries, bodies, each = (row) => row) {
320
+ function groupValues(shape, [key, row]) {
321
+ return [...shape.orderBy.map(({ by }) => (by === 'count' ? row.count : row[`key${by}`])), key];
322
+ }
323
+ function groupOrder(shape) {
324
+ return shape.orderBy.map(({ direction }) => ({
325
+ direction,
326
+ nulls: 'first',
327
+ stringSort: 'locale',
328
+ locale: undefined,
329
+ localeOptions: undefined,
330
+ }));
331
+ }
332
+ function windowOf(plan, entries, total) {
333
+ const shape = plan.shape;
334
+ if (shape.kind === 'documents') {
335
+ return {
336
+ ...windowed(entries, plan.limit, plan.after?.text, ([, row]) => documentCursor(shape, row)),
337
+ total,
338
+ };
339
+ }
340
+ const cursor = plan.after?.values ?? null;
341
+ const orderings = groupOrder(shape);
342
+ const following = cursor === null
343
+ ? entries
344
+ : entries.filter((entry) => beyond(groupValues(shape, entry), cursor, orderings));
345
+ return {
346
+ ...windowed(following, plan.limit, plan.after?.text, (entry) => cursorOf(groupValues(shape, entry))),
347
+ total: plan.total ? entries.length : undefined,
348
+ };
349
+ }
350
+ function framed(rows, { next, total }) {
351
+ return {
352
+ ...rows,
353
+ ...(next === undefined ? {} : { next }),
354
+ ...(total === undefined ? {} : { total }),
355
+ };
356
+ }
357
+ function rowsOfPlan(plan, entries, total, bodies, each = (row) => row) {
276
358
  const shape = plan.shape;
359
+ const { kept, ...window } = windowOf(plan, entries, total);
360
+ const keys = kept.map(([key]) => key);
277
361
  if (shape.kind === 'documents') {
278
362
  const documents = [];
279
- return after(inUnits(entries, ([key, row]) => {
363
+ return after(inUnits(kept, ([key, row]) => {
280
364
  documents.push(each(documentOf(key, row, shape, bodies)));
281
365
  return weight(row);
282
- }), () => ({ rows: { documents }, keys: entries.map(([key]) => key) }));
366
+ }), () => ({ rows: framed({ documents }, window), keys, ...window }));
283
367
  }
284
- const bounded = shape.orderBy.length === 0 && plan.limit !== null ? entries.slice(0, plan.limit) : entries;
285
368
  const groups = [];
286
- return after(inUnits(bounded, ([, row]) => {
369
+ return after(inUnits(kept, ([, row]) => {
287
370
  groups.push(each({
288
371
  key: shape.groupBy.map((_, index) => row[`key${index}`]),
289
372
  count: row.count,
290
373
  }));
291
374
  return ROW_WEIGHT;
292
- }), () => ({ rows: { groups }, keys: bounded.map(([key]) => key) }));
375
+ }), () => ({ rows: framed({ groups }, window), keys, ...window }));
293
376
  }
294
377
  export function reconciled(previous, next) {
295
378
  const before = previous.result;
@@ -314,13 +397,16 @@ export function reconciled(previous, next) {
314
397
  const removed = previous.keys.filter((key) => !present.has(key));
315
398
  const moved = reordered(previous.keys, next.keys, present);
316
399
  const covered = !deepEquals(before.coverage, after.coverage);
317
- if (changed.length === 0 && removed.length === 0 && !moved && !covered)
400
+ const framing = reframed(before, after);
401
+ if (changed.length === 0 && removed.length === 0 && !moved && !covered && framing === null) {
318
402
  return null;
403
+ }
404
+ const window = { next: after.next, total: after.total };
319
405
  return {
320
406
  keyed: {
321
407
  result: 'groups' in after
322
- ? { groups: rows, coverage: after.coverage }
323
- : { documents: rows, coverage: after.coverage },
408
+ ? framed({ groups: rows, coverage: after.coverage }, window)
409
+ : framed({ documents: rows, coverage: after.coverage }, window),
324
410
  keys: next.keys,
325
411
  },
326
412
  message: {
@@ -328,9 +414,17 @@ export function reconciled(previous, next) {
328
414
  removed,
329
415
  order: moved ? next.keys : null,
330
416
  ...(covered ? { coverage: after.coverage } : {}),
417
+ ...framing,
331
418
  },
332
419
  };
333
420
  }
421
+ function reframed(before, after) {
422
+ const next = before.next === after.next ? {} : { next: after.next ?? null };
423
+ const total = before.total === after.total || after.total === undefined ? {} : { total: after.total };
424
+ return Object.keys(next).length === 0 && Object.keys(total).length === 0
425
+ ? null
426
+ : { ...next, ...total };
427
+ }
334
428
  function reordered(previous, next, present) {
335
429
  let at = 0;
336
430
  for (const key of previous) {
@@ -379,8 +473,11 @@ export function createReadSide() {
379
473
  return;
380
474
  entry.rows.set(key, row);
381
475
  }
476
+ function counted(entry) {
477
+ return entry.built.count === null ? undefined : entry.built.count.size;
478
+ }
382
479
  function rebuilt(entry) {
383
- return after(rowsOfPlan(entry.plan, [...entry.built.live.entries()], entry.bodies), ({ rows: found, keys }) => {
480
+ return after(rowsOfPlan(entry.plan, [...entry.built.live.entries()], counted(entry), entry.bodies), ({ rows: found, keys, next, total }) => {
384
481
  const present = new Set(keys);
385
482
  for (const key of [...entry.rows.keys()])
386
483
  if (!present.has(key))
@@ -390,32 +487,34 @@ export function createReadSide() {
390
487
  entry.bodies.delete(key);
391
488
  }
392
489
  keys.forEach((key, index) => kept(entry, key, rowAt(found, index)));
393
- return keys;
490
+ return { keys, next, total };
394
491
  });
395
492
  }
396
493
  function refreshed(entry, dirty) {
397
494
  const shape = entry.plan.shape;
398
- const keys = [...entry.built.live.keys()];
399
- const named = new Set([...dirty, ...keys.filter((key) => !entry.rows.has(key))]);
400
- const values = [...named].map((key) => [key, entry.built.live.get(key)]);
495
+ const { kept: inWindow, next, total, } = windowOf(entry.plan, [...entry.built.live.entries()], counted(entry));
496
+ const keys = inWindow.map(([key]) => key);
497
+ const present = new Set(keys);
498
+ for (const key of [...entry.rows.keys()]) {
499
+ if (present.has(key))
500
+ continue;
501
+ entry.rows.delete(key);
502
+ entry.bodies.delete(key);
503
+ }
504
+ const values = inWindow.filter(([key]) => dirty.has(key) || !entry.rows.has(key));
401
505
  const done = inUnits(values, ([key, value]) => {
402
- if (value !== undefined)
403
- kept(entry, key, documentOf(key, value, shape, entry.bodies));
404
- else {
405
- entry.rows.delete(key);
406
- entry.bodies.delete(key);
407
- }
506
+ kept(entry, key, documentOf(key, value, shape, entry.bodies));
408
507
  return weight(value);
409
508
  });
410
- return after(done, () => keys);
509
+ return after(done, () => ({ keys, next, total }));
411
510
  }
412
- function current(entry, keys, coverage) {
413
- const found = keys.map((key) => entry.rows.get(key));
511
+ function current(entry, found, coverage) {
512
+ const rows = found.keys.map((key) => entry.rows.get(key));
414
513
  return {
415
514
  result: entry.plan.shape.kind === 'groups'
416
- ? { groups: found, coverage }
417
- : { documents: found, coverage },
418
- keys,
515
+ ? framed({ groups: rows, coverage }, found)
516
+ : framed({ documents: rows, coverage }, found),
517
+ keys: found.keys,
419
518
  };
420
519
  }
421
520
  function delivered(entry, next) {
@@ -451,12 +550,12 @@ export function createReadSide() {
451
550
  const dirty = entry.dirty;
452
551
  entry.dirty = new Set();
453
552
  entry.whole = false;
454
- const keys = whole ? rebuilt(entry) : refreshed(entry, dirty);
455
- if (keys instanceof Promise) {
456
- void keys
457
- .then((found) => {
553
+ const found = whole ? rebuilt(entry) : refreshed(entry, dirty);
554
+ if (found instanceof Promise) {
555
+ void found
556
+ .then((window) => {
458
557
  if (entry.listeners.size > 0)
459
- delivered(entry, current(entry, found, cover.coverage));
558
+ delivered(entry, current(entry, window, cover.coverage));
460
559
  run(entry);
461
560
  })
462
561
  .catch(() => {
@@ -464,7 +563,7 @@ export function createReadSide() {
464
563
  });
465
564
  return;
466
565
  }
467
- delivered(entry, current(entry, keys, cover.coverage));
566
+ delivered(entry, current(entry, found, cover.coverage));
468
567
  }
469
568
  entry.running = false;
470
569
  }
@@ -520,12 +619,14 @@ export function createReadSide() {
520
619
  },
521
620
  recover,
522
621
  async query(plan, at) {
523
- const { live: collection, dispose } = built(rows, plan);
622
+ const { live: collection, count, dispose } = built(rows, plan);
524
623
  try {
525
624
  await collection.toArrayWhenReady();
625
+ if (count !== null)
626
+ await count.toArrayWhenReady();
526
627
  const entries = [...collection.entries()];
527
628
  const held = at();
528
- const found = await rowsOfPlan(plan, entries, null, structuredClone);
629
+ const found = await rowsOfPlan(plan, entries, count?.size, null, structuredClone);
529
630
  return { rows: found.rows, at: held };
530
631
  }
531
632
  finally {
@@ -546,13 +647,16 @@ export function createReadSide() {
546
647
  fresh: new Set(),
547
648
  ready: new Set(),
548
649
  subscription: null,
650
+ counting: null,
549
651
  whole: true,
550
652
  dirty: new Set(),
551
653
  stale: false,
552
654
  running: false,
553
655
  };
554
656
  created.built.live.on('status:change', ({ status }) => {
555
- if (status === 'cleaned-up' && created.listeners.size === 0)
657
+ if (status !== 'cleaned-up' || created.listeners.size > 0)
658
+ return;
659
+ if (shared.get(identity) === created)
556
660
  shared.delete(identity);
557
661
  });
558
662
  shared.set(identity, created);
@@ -560,7 +664,14 @@ export function createReadSide() {
560
664
  }
561
665
  const observed = entry;
562
666
  observed.listeners.add(deliverTo);
563
- observed.built.live.onFirstReady(() => {
667
+ const ready = (then) => observed.built.live.onFirstReady(() => observed.built.count === null ? then() : observed.built.count.onFirstReady(then));
668
+ const settled = () => {
669
+ if (observed.built.count === null)
670
+ wake(observed);
671
+ else
672
+ queueMicrotask(() => wake(observed));
673
+ };
674
+ ready(() => {
564
675
  if (!observed.listeners.has(deliverTo))
565
676
  return;
566
677
  observed.fresh.add(deliverTo);
@@ -572,8 +683,13 @@ export function createReadSide() {
572
683
  else
573
684
  for (const { key } of changes)
574
685
  observed.dirty.add(key);
575
- wake(observed);
686
+ settled();
576
687
  }, { includeInitialState: false });
688
+ observed.counting =
689
+ observed.built.count?.subscribeChanges(() => {
690
+ observed.stale = true;
691
+ settled();
692
+ }, { includeInitialState: false }) ?? null;
577
693
  }
578
694
  wake(observed);
579
695
  });
@@ -584,11 +700,16 @@ export function createReadSide() {
584
700
  return;
585
701
  observed.subscription?.unsubscribe();
586
702
  observed.subscription = null;
703
+ observed.counting?.unsubscribe();
704
+ observed.counting = null;
587
705
  observed.result = undefined;
588
706
  observed.rows.clear();
589
707
  observed.bodies.clear();
590
708
  observed.dirty.clear();
591
709
  observed.whole = true;
710
+ if (shared.get(identity) === observed)
711
+ shared.delete(identity);
712
+ observed.built.dispose();
592
713
  };
593
714
  },
594
715
  room(room) {
@@ -604,6 +725,7 @@ export function createReadSide() {
604
725
  entry.fresh.clear();
605
726
  entry.ready.clear();
606
727
  entry.subscription?.unsubscribe();
728
+ entry.counting?.unsubscribe();
607
729
  entry.built.dispose();
608
730
  }
609
731
  shared.clear();
@@ -628,13 +750,16 @@ function changedFrom(previous, next) {
628
750
  const removed = previous.keys.filter((key) => !present.has(key));
629
751
  const moved = reordered(previous.keys, next.keys, present);
630
752
  const covered = !deepEquals(before.coverage, after.coverage);
631
- if (changed.length === 0 && removed.length === 0 && !moved && !covered)
753
+ const framing = reframed(before, after);
754
+ if (changed.length === 0 && removed.length === 0 && !moved && !covered && framing === null) {
632
755
  return null;
756
+ }
633
757
  return {
634
758
  changed,
635
759
  removed,
636
760
  order: moved ? next.keys : null,
637
761
  ...(covered ? { coverage: after.coverage } : {}),
762
+ ...framing,
638
763
  };
639
764
  }
640
765
  function rowAt(rows, index) {