@coasys/ad4m 0.13.1-staging.2 → 0.13.1-staging.3

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 (43) hide show
  1. package/lib/index.cjs +584 -203
  2. package/lib/index.js +581 -204
  3. package/lib/src/Ad4mClient.d.ts +7 -0
  4. package/lib/src/Ad4mClient.js +9 -0
  5. package/lib/src/apiClient.d.ts +13 -0
  6. package/lib/src/apiClient.js +67 -12
  7. package/lib/src/generated/api/AuthInfo.d.ts +4 -0
  8. package/lib/src/generated/api/RuntimeInfo.d.ts +5 -0
  9. package/lib/src/index.d.ts +1 -0
  10. package/lib/src/index.js +1 -0
  11. package/lib/src/model/Ad4mModel.js +45 -18
  12. package/lib/src/model/ModelQueryBuilder.d.ts +7 -3
  13. package/lib/src/model/ModelQueryBuilder.js +9 -4
  14. package/lib/src/model/query-common.js +7 -1
  15. package/lib/src/model/types.d.ts +45 -2
  16. package/lib/src/model/types.js +8 -0
  17. package/lib/src/perspectives/Container.d.ts +41 -0
  18. package/lib/src/perspectives/Container.js +62 -0
  19. package/lib/src/perspectives/PerspectiveProxy.d.ts +6 -3
  20. package/lib/src/perspectives/PerspectiveProxy.js +10 -4
  21. package/lib/src/perspectives/WakerSubscriptionManager.d.ts +94 -12
  22. package/lib/src/perspectives/WakerSubscriptionManager.js +273 -72
  23. package/lib/src/runtime/RuntimeTypes.d.ts +2 -0
  24. package/package.json +2 -2
  25. package/src/Ad4mClient.test.ts +1 -1
  26. package/src/Ad4mClient.ts +10 -0
  27. package/src/apiClient.test.ts +128 -2
  28. package/src/apiClient.ts +64 -11
  29. package/src/generated/api/AuthInfo.ts +6 -1
  30. package/src/generated/api/RuntimeInfo.ts +6 -1
  31. package/src/index.ts +1 -0
  32. package/src/model/Ad4mModel.ts +51 -19
  33. package/src/model/ModelQueryBuilder.ts +9 -6
  34. package/src/model/containment-scope.test.ts +104 -0
  35. package/src/model/query-common.ts +10 -1
  36. package/src/model/types.ts +56 -2
  37. package/src/perspectives/Container.test.ts +65 -0
  38. package/src/perspectives/Container.ts +46 -0
  39. package/src/perspectives/PerspectiveProxy.test.ts +11 -0
  40. package/src/perspectives/PerspectiveProxy.ts +10 -4
  41. package/src/perspectives/WakerSubscriptionManager.test.ts +398 -80
  42. package/src/perspectives/WakerSubscriptionManager.ts +318 -82
  43. package/src/runtime/RuntimeTypes.ts +2 -0
@@ -1,4 +1,4 @@
1
- import { WakerSubscriptionManager, hintFor } from './WakerSubscriptionManager';
1
+ import { MENTION_TEXT_LIMIT, WakerSubscriptionManager, hintFor, holdsAWholeWordTerm } from './WakerSubscriptionManager';
2
2
 
3
3
  /**
4
4
  * Regression guard for the fork that used to exist between this file and
@@ -25,7 +25,9 @@ describe('WakerSubscriptionManager', () => {
25
25
  type: 'mention' as const,
26
26
  perspective: 'fake-uuid',
27
27
  channel: '',
28
- query: 'SELECT * WHERE { ?s ?p ?o }',
28
+ className: 'ad4m://TextContent',
29
+ query: '{"properties":["text"]}',
30
+ terms: ['bot'],
29
31
  };
30
32
 
31
33
  /** A QuerySubscriptionProxy stand-in whose registration the executor rejects. */
@@ -184,10 +186,21 @@ describe('WakerSubscriptionManager', () => {
184
186
  manager.disposeAll();
185
187
  });
186
188
 
187
- /** Delivers one new mention and returns the parents it woke with, the parent query and any warnings. */
188
- async function wakeWithParentRows(rows: unknown, ancestorDepth?: number, address = 'test://message') {
189
+ /**
190
+ * Delivers one new mention (or each of the `deliveries` in turn) and returns what it woke with, every model query the
191
+ * manager made (`[className, parsed query]`), any warnings and the subscriptions it opened. `answer` gets each
192
+ * query's `parent` scope and returns the rows' ids, or a raw result to hand back as is.
193
+ */
194
+ async function wakeWith(
195
+ answer: (scope: any) => unknown,
196
+ ancestorDepth?: number,
197
+ address = 'test://message',
198
+ deliveries: any[] = [{ instances: [{ id: address, text: 'hi bot' }] }],
199
+ ) {
189
200
  let deliver: ((result: any) => Promise<void>) | undefined;
190
- const ProxyClass = function () {
201
+ const opened: any[][] = [];
202
+ const ProxyClass = function (...args: any[]) {
203
+ opened.push(args);
191
204
  return {
192
205
  initialized: Promise.resolve(true),
193
206
  subscribe: () => Promise.resolve(),
@@ -195,12 +208,17 @@ describe('WakerSubscriptionManager', () => {
195
208
  onResult: (cb: (result: any) => Promise<void>) => { deliver = cb; },
196
209
  };
197
210
  };
198
- const queries: string[] = [];
211
+ const queries: [string, any][] = [];
199
212
  const warnings: string[] = [];
200
213
  const client = {
201
- querySparql: (_uuid: string, query: string) => {
202
- queries.push(query);
203
- return Promise.resolve(typeof rows === 'function' ? rows(query) : rows);
214
+ querySparql: () => Promise.reject(new Error('the waker resolves containment through Container')),
215
+ modelQuery: (_uuid: string, className: string, queryJson: string) => {
216
+ const query = JSON.parse(queryJson);
217
+ queries.push([className, query]);
218
+ const rows = answer(query.parent);
219
+ return Promise.resolve(
220
+ Array.isArray(rows) ? { instances: rows.map((id) => ({ id })), totalCount: rows.length } : rows,
221
+ );
204
222
  },
205
223
  };
206
224
  const wakes: any[] = [];
@@ -215,108 +233,408 @@ describe('WakerSubscriptionManager', () => {
215
233
  });
216
234
 
217
235
  await manager.subscribe({ ...sub, id: 'mention-parents' });
218
- await deliver!([{ source: address }]);
236
+ for (const result of deliveries) {
237
+ await deliver!(result);
238
+ await new Promise((resolve) => setTimeout(resolve, 30));
239
+ }
219
240
  await waitUntil(() => wakes.length > 0);
220
241
  manager.disposeAll();
221
- return { wakes, queries, warnings };
242
+ return { wakes, queries, warnings, opened };
222
243
  }
223
244
 
224
- it('resolves the parents of a new mention from the flat rows querySparql returns', async () => {
225
- const { wakes, queries } = await wakeWithParentRows([{ source: 'test://parent' }]);
226
- expect(queries[0]).toContain('<ad4m://has_child> <test://message>');
227
- expect(wakes).toEqual([[{ address: 'test://message', parents: ['test://parent'], ancestors: [] }]]);
245
+ it('opens a mention subscription as a TextContent model query', async () => {
246
+ const { opened } = await wakeWith(() => []);
247
+ expect(opened).toEqual([[sub.perspective, sub.query, expect.anything(), 'ad4m://TextContent']]);
228
248
  });
229
249
 
230
- it('keeps only string parents when a row leaves ?source unbound', async () => {
231
- const { wakes } = await wakeWithParentRows([{ source: 'test://a' }, {}, { source: 'test://b' }]);
232
- expect(wakes).toEqual([[{ address: 'test://message', parents: ['test://a', 'test://b'], ancestors: [] }]]);
250
+ it('does not mark substring candidates as seen before a later whole-word edit', async () => {
251
+ const { wakes, queries } = await wakeWith(() => [], 0, 'test://message', [
252
+ { instances: [{ id: 'test://message', text: 'robots' }] },
253
+ { instances: [{ id: 'test://message', text: 'hi bot' }] },
254
+ { instances: [{ id: 'test://message', text: 'hi bot again' }] },
255
+ [{ source: 'test://not-model' }],
256
+ ]);
257
+ expect(wakes).toEqual([[{ address: 'test://message', parents: [], ancestors: [] }]]);
258
+ expect(queries).toHaveLength(1);
259
+ });
260
+
261
+ /**
262
+ * Containment as a map of child → holders, answered as the executor's `Container` answers: a
263
+ * step in returns each id's holders, a transitive walk in returns everything above the ids,
264
+ * breadth first, each once, never an anchor, up to `maxDepth`.
265
+ */
266
+ const tree = (holders: Record<string, string[]>) => (scope: any) => {
267
+ const anchors: string[] = scope.ids;
268
+ if (!scope.transitive) return [...new Set(anchors.flatMap((id) => holders[id] ?? []))];
269
+ const out: string[] = [];
270
+ const seen = new Set(anchors);
271
+ let level = anchors;
272
+ for (let depth = 0; level.length && depth < (scope.maxDepth ?? Infinity); depth++) {
273
+ const next = level.flatMap((id) => holders[id] ?? []).filter((h) => !seen.has(h) && (seen.add(h), true));
274
+ out.push(...next);
275
+ level = next;
276
+ }
277
+ return out;
278
+ };
279
+
280
+ it('asks Container for what holds a new mention, one step in', async () => {
281
+ const { wakes, queries } = await wakeWith(() => ['test://parent']);
282
+ expect(queries[0]).toEqual([
283
+ 'ad4m://Container',
284
+ { parent: { ids: ['test://message'], direction: 'in' }, properties: [] },
285
+ ]);
286
+ expect(wakes).toEqual([[{ address: 'test://message', parents: ['test://parent'], ancestors: [] }]]);
233
287
  });
234
288
 
235
- it('reports no parents, without a warning, when querySparql returns a non-array', async () => {
236
- const { wakes, warnings } = await wakeWithParentRows(true);
289
+ it('reports no parents, without a warning, when the executor returns no instances', async () => {
290
+ const { wakes, warnings } = await wakeWith(() => true);
237
291
  expect(wakes).toEqual([[{ address: 'test://message', parents: [], ancestors: [] }]]);
238
292
  expect(warnings).toEqual([]);
239
293
  });
240
294
 
241
- /** Containment as a map of child → parents, answered per query the way querySparql would. */
242
- const tree = (parents: Record<string, string[]>) => (query: string) => {
243
- const values = /VALUES \?child \{([^}]+)\}/.exec(query)?.[1];
244
- const children = values
245
- ? Array.from(values.matchAll(/<([^>]+)>/g), (match) => match[1])
246
- : [/<ad4m:\/\/has_child> <([^>]+)>/.exec(query)?.[1] ?? ''];
247
- return children.flatMap((child) => (parents[child] ?? []).map((source) => ({ source })));
248
- };
295
+ it('deduplicates two result rows for the same source in one mention pass', async () => {
296
+ const { wakes, queries } = await wakeWith(() => [], undefined, 'addr://msg-1', [
297
+ {
298
+ instances: [
299
+ { id: 'addr://msg-1', text: 'hi bot' },
300
+ { id: 'addr://msg-1', text: 'hi bot' },
301
+ ],
302
+ },
303
+ ]);
304
+ expect(wakes).toEqual([[{ address: 'addr://msg-1', parents: [], ancestors: [] }]]);
305
+ // The parent lookup runs once, not once per row.
306
+ expect(queries).toHaveLength(1);
307
+ });
308
+
309
+ /** A mention subscription whose results the test pushes by hand, with the wakes it produced. */
310
+ async function mentionHarness(
311
+ debounceMs: number,
312
+ onWake?: (mentions: any) => unknown,
313
+ // What the subscription holds when it opens (the proxy's `result`), and what a restart restored.
314
+ opening?: {
315
+ initial?: any;
316
+ previousSeen?: Record<string, string[]>;
317
+ modelQuery?: (uuid: string, className: string, queryJson: string) => Promise<any>;
318
+ },
319
+ ) {
320
+ let deliver: ((result: any) => Promise<void>) | undefined;
321
+ const ProxyClass = function () {
322
+ return {
323
+ initialized: Promise.resolve(true),
324
+ subscribe: () => Promise.resolve(),
325
+ dispose: () => {},
326
+ result: opening?.initial,
327
+ onResult: (cb: (result: any) => Promise<void>) => { deliver = cb; },
328
+ };
329
+ };
330
+ const wakes: any[] = [];
331
+ const persistedSeen: string[][] = [];
332
+ const manager = new WakerSubscriptionManager({
333
+ perspectiveClient: {
334
+ querySparql: () => Promise.resolve([]),
335
+ modelQuery: opening?.modelQuery ?? (() => Promise.resolve({ instances: [], totalCount: 0 })),
336
+ },
337
+ logger: noopLogger(),
338
+ QuerySubscriptionProxy: ProxyClass,
339
+ debounceMs,
340
+ retryPendingMs: 60_000,
341
+ retryWakeMs: 20,
342
+ onWake: (_sub, _result, mentions) => {
343
+ wakes.push(mentions);
344
+ return onWake?.(mentions);
345
+ },
346
+ onPersist: (_subs, seen) => { persistedSeen.push(seen['mention-harness'] ?? []); },
347
+ previousSeenMessages: opening?.previousSeen,
348
+ } as any);
349
+ await manager.subscribe({ ...sub, id: 'mention-harness' });
350
+ const msg = (...ids: string[]) => ({ instances: ids.map((id) => ({ id, text: 'hi bot' })) });
351
+ return { manager, deliver: (r: any) => deliver!(r), msg, wakes, persistedSeen };
352
+ }
353
+
354
+ /**
355
+ * Live test 2026-10-21 (T13b): a mention written while the gateway was down. The subscription
356
+ * opened after the restart already holds it, but the waker only listened for later changes.
357
+ */
358
+ it('wakes on a mention the restored subscription already holds when it opens', async () => {
359
+ const msg = (...ids: string[]) => ({ instances: ids.map((id) => ({ id, text: 'hi bot' })) });
360
+ const h = await mentionHarness(10, undefined, {
361
+ initial: msg('test://during-downtime', 'test://old'),
362
+ previousSeen: { 'mention-harness': ['test://old'] },
363
+ });
364
+ await waitUntil(() => h.wakes.length > 0, 1000);
365
+ h.manager.disposeAll();
366
+ expect(h.wakes.map((w: any) => w.map((m: any) => m.address))).toEqual([['test://during-downtime']]);
367
+ });
249
368
 
250
- it('reports the chain above the parents, nearest first, each address once', async () => {
251
- // A message in a thread in a call in a space — and the call is also in a second channel, so two
252
- // paths reach the space.
253
- const { wakes } = await wakeWithParentRows(
369
+ it('takes the mentions a new subscription opens on as history, and wakes only on later ones', async () => {
370
+ const h = await mentionHarness(10, undefined, {
371
+ initial: { instances: [{ id: 'test://old', text: 'hi bot' }, { id: 'test://robots', text: 'robots' }] },
372
+ });
373
+ await h.deliver({
374
+ instances: [
375
+ { id: 'test://new', text: 'hi bot' },
376
+ { id: 'test://old', text: 'hi bot' },
377
+ // Not a mention when the subscription opened, so a later edit that adds one still wakes.
378
+ { id: 'test://robots', text: 'robots, bot' },
379
+ ],
380
+ });
381
+ await waitUntil(() => h.wakes.length > 0, 1000);
382
+ await new Promise((r) => setTimeout(r, 30));
383
+ h.manager.disposeAll();
384
+ expect(h.wakes.map((w: any) => w.map((m: any) => m.address).sort())).toEqual([['test://new', 'test://robots']]);
385
+ });
386
+
387
+ /** Review of #1512 (Lal): B was persisted as seen while its parents were still resolving. */
388
+ it('does not persist a mention still resolving its parents when an earlier wake lands', async () => {
389
+ let landA: (delivered: boolean) => void = () => {};
390
+ let resolveB: () => void = () => {};
391
+ let bLookupStarted = false;
392
+ const h = await mentionHarness(
393
+ 10,
394
+ () => (h.wakes.length === 1 ? new Promise((r) => { landA = r; }) : true),
395
+ {
396
+ // A's lookups answer at once; B's waits until the test lets it go.
397
+ modelQuery: (_uuid: string, _className: string, queryJson: string) => {
398
+ const empty = { instances: [], totalCount: 0 };
399
+ if (!JSON.parse(queryJson).parent?.ids?.includes('test://b')) return Promise.resolve(empty);
400
+ bLookupStarted = true;
401
+ return new Promise((r) => { resolveB = () => r(empty); });
402
+ },
403
+ },
404
+ );
405
+ await h.deliver(h.msg('test://a'));
406
+ await waitUntil(() => h.wakes.length === 1, 1000);
407
+ const bHandled = h.deliver(h.msg('test://b', 'test://a'));
408
+ await waitUntil(() => bLookupStarted, 1000);
409
+ expect(bLookupStarted).toBe(true);
410
+ landA(true);
411
+ await waitUntil(() => h.persistedSeen.some((seen) => seen.includes('test://a')), 1000);
412
+ expect(h.persistedSeen.at(-1)).toEqual(['test://a']);
413
+ resolveB();
414
+ await bHandled;
415
+ await waitUntil(() => h.persistedSeen.some((seen) => seen.includes('test://b')), 1000);
416
+ h.manager.disposeAll();
417
+ expect(h.wakes.map((w: any) => w.map((m: any) => m.address))).toEqual([['test://a'], ['test://b']]);
418
+ });
419
+
420
+ it('names every mention that arrived inside one debounce window in the wake', async () => {
421
+ const h = await mentionHarness(100);
422
+ await h.deliver(h.msg('test://a'));
423
+ await new Promise((r) => setTimeout(r, 20));
424
+ await h.deliver(h.msg('test://b', 'test://a'));
425
+ await waitUntil(() => h.wakes.length > 0, 1000);
426
+ await new Promise((r) => setTimeout(r, 150));
427
+ h.manager.disposeAll();
428
+ expect(h.wakes).toHaveLength(1);
429
+ expect(h.wakes[0].map((m: any) => m.address).sort()).toEqual(['test://a', 'test://b']);
430
+ });
431
+
432
+ /**
433
+ * Live test 2026-10-21 (T13): a mention reached the waker while the gateway drained for a
434
+ * restart; the wake POST answered 503, the mention was persisted as seen and never woke anyone.
435
+ */
436
+ it('does not persist a mention as seen when its wake was not delivered, and retries it', async () => {
437
+ let accept = false;
438
+ const h = await mentionHarness(10, () => Promise.resolve(accept));
439
+ await h.deliver(h.msg('test://lost'));
440
+ await waitUntil(() => h.wakes.length > 0, 1000);
441
+ await new Promise((r) => setTimeout(r, 30));
442
+ expect(h.persistedSeen.every((seen) => !seen.includes('test://lost'))).toBe(true);
443
+ accept = true;
444
+ await waitUntil(() => h.persistedSeen.some((seen) => seen.includes('test://lost')), 5000);
445
+ h.manager.disposeAll();
446
+ expect(h.wakes.length).toBeGreaterThan(1);
447
+ expect(h.wakes.at(-1).map((m: any) => m.address)).toEqual(['test://lost']);
448
+ expect(h.persistedSeen.some((seen) => seen.includes('test://lost'))).toBe(true);
449
+ });
450
+
451
+ /**
452
+ * Test 11 (#1446): a mention under a message held by a We block. The block is a parent beside
453
+ * the channel that holds the message by has_child; the chain above both comes back nearest
454
+ * first, from one bounded walk in from the parents.
455
+ */
456
+ it('reports every container holding a mention, and the chain above, nearest first', async () => {
457
+ const { wakes, queries } = await wakeWith(
254
458
  tree({
255
- 'test://message': ['test://thread'],
256
- 'test://thread': ['test://call'],
257
- 'test://call': ['test://space', 'test://channel'],
258
- 'test://channel': ['test://space'],
459
+ 'test://message': ['test://channel', 'test://block'],
460
+ 'test://block': ['test://call'],
461
+ 'test://call': ['test://space'],
462
+ 'test://space': ['ad4m://self'],
259
463
  }),
260
464
  );
261
465
  expect(wakes).toEqual([
262
466
  [
263
467
  {
264
468
  address: 'test://message',
265
- parents: ['test://thread'],
266
- ancestors: ['test://call', 'test://space', 'test://channel'],
469
+ parents: ['test://channel', 'test://block'],
470
+ ancestors: ['test://call', 'test://space', 'ad4m://self'],
267
471
  },
268
472
  ],
269
473
  ]);
474
+ expect(queries).toHaveLength(2);
475
+ expect(queries[1]).toEqual([
476
+ 'ad4m://Container',
477
+ {
478
+ parent: { ids: ['test://channel', 'test://block'], direction: 'in', transitive: true, maxDepth: 3 },
479
+ properties: [],
480
+ },
481
+ ]);
270
482
  });
271
483
 
272
- it('stops at its depth, and at a cycle, rather than walking forever', async () => {
273
- const { wakes } = await wakeWithParentRows(
274
- tree({
275
- 'test://message': ['test://a'],
276
- 'test://a': ['test://b'],
277
- 'test://b': ['test://c'],
278
- 'test://c': ['test://message'],
279
- }),
280
- 5,
281
- );
282
- // c leads back to the message: seen already, so the walk ends there rather than going round.
484
+ it('bounds the walk by ancestorDepth, and never reports the mention itself', async () => {
485
+ const holders = {
486
+ 'test://message': ['test://a'],
487
+ 'test://a': ['test://b'],
488
+ 'test://b': ['test://c'],
489
+ 'test://c': ['test://message'],
490
+ };
491
+ const { wakes } = await wakeWith(tree(holders), 5);
492
+ // c leads back to the message: it is the mention, not something above it.
283
493
  expect(wakes[0][0].ancestors).toEqual(['test://b', 'test://c']);
284
- const shallow = await wakeWithParentRows(tree({ 'test://message': ['test://a'], 'test://a': ['test://b'], 'test://b': ['test://c'] }), 1);
494
+ const shallow = await wakeWith(tree(holders), 1);
285
495
  expect(shallow.wakes[0][0].ancestors).toEqual(['test://b']);
496
+ const none = await wakeWith(tree(holders), 0);
497
+ expect(none.wakes[0][0].ancestors).toEqual([]);
498
+ expect(none.queries).toHaveLength(1);
286
499
  });
287
500
 
288
- it('looks up a branching ancestor level in one query', async () => {
289
- const { wakes, queries } = await wakeWithParentRows(tree({
290
- 'test://message': ['test://left', 'test://right'],
291
- 'test://left': ['test://root'],
292
- 'test://right': ['test://root'],
293
- }));
294
- expect(wakes[0][0].ancestors).toEqual(['test://root']);
295
- expect(queries).toHaveLength(3);
296
- expect(queries[1]).toContain('VALUES ?child { <test://left> <test://right> }');
501
+ it('sends an address with query syntax in it as data', async () => {
502
+ const address = 'test://bad> . ?s ?p ?o . #';
503
+ const { wakes, queries } = await wakeWith(() => [], 3, address);
504
+ expect(queries[0][1].parent.ids).toEqual([address]);
505
+ expect(wakes[0][0]).toEqual({ address, parents: [], ancestors: [] });
297
506
  });
298
507
 
299
- it.each(['<', '>', '"', '{', '}', '|', '^', '`', '\\', ' ', '\t', '\n', '\u0000'])(
300
- 'does not query an unsafe mention address containing %p', async (character) => {
301
- const address = `test://unsafe${character}address`;
302
- const { wakes, queries, warnings } = await wakeWithParentRows([], 3, address);
303
- expect(queries).toEqual([]);
304
- expect(wakes[0][0]).toEqual({ address, parents: [], ancestors: [] });
305
- expect(warnings).toHaveLength(1);
306
- expect(warnings[0]).toContain('unsafe address');
307
- },
308
- );
309
-
310
- it('skips an unsafe ancestor lookup without dropping safe siblings', async () => {
311
- const unsafe = 'test://bad> . ?s ?p ?o . #';
312
- const { wakes, queries, warnings } = await wakeWithParentRows(tree({
313
- 'test://message': [unsafe, 'test://safe'],
314
- 'test://safe': ['test://root'],
315
- }));
316
- expect(wakes[0][0].ancestors).toEqual(['test://root']);
317
- expect(queries).toHaveLength(3);
318
- expect(queries.every((query) => !query.includes(unsafe))).toBe(true);
319
- expect(warnings).toHaveLength(1);
508
+ it('reads a model subscription by row id', async () => {
509
+ let deliver: ((result: any) => Promise<void>) | undefined;
510
+ const constructed: any[][] = [];
511
+ const ProxyClass = function (...args: any[]) {
512
+ constructed.push(args);
513
+ return {
514
+ initialized: Promise.resolve(true),
515
+ subscribe: () => Promise.resolve(),
516
+ dispose: () => {},
517
+ onResult: (cb: (result: any) => Promise<void>) => { deliver = cb; },
518
+ };
519
+ };
520
+ const wakes: any[] = [];
521
+ const manager = new WakerSubscriptionManager({
522
+ perspectiveClient,
523
+ logger: noopLogger(),
524
+ QuerySubscriptionProxy: ProxyClass,
525
+ debounceMs: 10,
526
+ onWake: (_sub, result) => { wakes.push(result); },
527
+ });
528
+ const query = JSON.stringify({ where: { id: 'test://call' }, properties: ['children'] });
529
+ await manager.subscribe({
530
+ id: 'children-of-call',
531
+ type: 'channel-messages',
532
+ perspective: 'fake-uuid',
533
+ channel: 'test://call',
534
+ query,
535
+ className: 'ad4m://Container',
536
+ });
537
+ expect(constructed[0]).toEqual(['fake-uuid', query, perspectiveClient, 'ad4m://Container']);
538
+ await deliver!({ instances: [{ id: 'test://call', children: ['test://block'] }], totalCount: 1 });
539
+ await waitUntil(() => wakes.length > 0);
540
+ expect(wakes[0].instances[0].children).toEqual(['test://block']);
541
+ // Not a model result: ignored.
542
+ await deliver!([{ source: 'x' }]);
543
+ manager.disposeAll();
544
+ });
545
+
546
+ // #1459's table (`mention_query_matches_the_name_as_a_whole_word_only` and the regex-characters
547
+ // case), now the waker's check: the query returns these as substring candidates
548
+ // (`the_mention_query_returns_substring_candidates_with_their_text` in Rust).
549
+ it('holds a term only as a whole word, case-insensitively and literally', () => {
550
+ const holds = (text: string, terms = ['Data']) => holdsAWholeWordTerm(text, terms);
551
+ expect(['hi Data!', 'DATA, look', '@data', 'data', "Data's turn"].filter((t) => !holds(t))).toEqual([]);
552
+ expect(['the metadata is stale', 'a database row', 'datas', '_data', 'dataé'].filter((t) => holds(t))).toEqual([]);
553
+ expect(holds('ask J.R. (bot) please', ['J.R. (bot)'])).toBe(true);
554
+ expect(holds('ask JxRx (bot) please', ['J.R. (bot)'])).toBe(false);
555
+ expect(holds('hi a"b\\c!', ['a"b\\c'])).toBe(true);
556
+ expect(holds('hi a"bc!', ['a"b\\c'])).toBe(false);
557
+ // The DID, inside a mention's HTML as apps write it.
558
+ expect(holds('<span data-id="did:key:zBot">@bot</span>', ['did:key:zBot'])).toBe(true);
559
+ expect(holds('did:key:zBotX', ['did:key:zBot'])).toBe(false);
560
+ expect(holds('hi Data', ['', 'Bob'])).toBe(false);
561
+ });
562
+
563
+ it('reads HTML as its visible text, and a mention by the DID in its target attribute', () => {
564
+ const bot = ['Data', 'did:key:zBot'];
565
+ const holds = (text: string) => holdsAWholeWordTerm(text, bot);
566
+ // Markup is not words: attribute names and values never wake "Data".
567
+ expect(holds('<div data-x="1">hi</div>')).toBe(false);
568
+ expect(holds('<p class="data">see the <a href="https://x.dev/data">notes</a></p>')).toBe(false);
569
+ // Another user's mention, in each app's markup.
570
+ expect(holds('<p>hi <a data-type="mention" href="did:key:zOther" data-label="Marvin">@Marvin</a> </p>')).toBe(false);
571
+ expect(holds('<span data-id="did:key:zOther">@Marvin</span> can you look?')).toBe(false);
572
+ expect(holds('<span class="we-mention" data-did="did:key:zOther">@Marvin</span> can you look?')).toBe(false);
573
+ // Visible words still count, inside and between elements.
574
+ expect(holds('<p>hey Data</p>')).toBe(true);
575
+ expect(holds('<p>hi</p><p>Data, look</p>')).toBe(true);
576
+ expect(holds('<p>hey <strong>@Data</strong>&nbsp;&amp; Bob</p>')).toBe(true);
577
+ expect(holds('meta<b>data</b>')).toBe(false);
578
+ // Flux's mention (tiptap `mention` node), by name and by DID alone.
579
+ expect(holds('<p>hi <a data-type="mention" href="did:key:zBot" data-label="Data">@Data</a> </p>')).toBe(true);
580
+ expect(holds('<p>hi <a data-type="mention" href="did:key:zBot" data-label="Bot">@Bot</a> </p>')).toBe(true);
581
+ expect(holds('<span data-id="did:key:zBot">@bot</span>')).toBe(true);
582
+ expect(holds('<a href="did:key:zBotExtra">@Other</a>')).toBe(false);
583
+ expect(holds('<a href="did:key:zbot">@Other</a>')).toBe(false);
584
+ expect(holds('<a href="Data">@Other</a>')).toBe(false);
585
+ expect(holds("<a title=' href=\"did:key:zBot\"'>@Other</a>")).toBe(false);
586
+ expect(holds('<a href=did:key:zBot>@Other</a>')).toBe(true);
587
+ // We stores a block as plain `text` with the DID in `marks`, so the name is what is read;
588
+ // its editor's chip carries the DID in `data-did`.
589
+ expect(holds('hey @Data can you look?')).toBe(true);
590
+ expect(holds('<span class="we-mention" data-did="did:key:zBot">@Bot</span> can you look?')).toBe(true);
591
+ // Plain text with a bare "<" is not markup.
592
+ expect(holds('a < b and Data > c')).toBe(true);
593
+ // Nor is "<" before a known element name without a valid attribute list, or before an unknown name.
594
+ expect(holds('if a <b then ask Data, else c -> d')).toBe(true);
595
+ expect(holds('<hey Data> can you look')).toBe(true);
596
+ // A real tag glued to a word is still markup, and inline tags glue as a reader sees them:
597
+ // "a<b>Data</b>" reads "aData", like "meta<b>data</b>" above.
598
+ expect(holds('a<b>Data</b>')).toBe(false);
599
+ expect(holds('a <b class=x>Data</b>!')).toBe(true);
600
+ // A quoted attribute value may hold ">": the tag ends at the real ">".
601
+ expect(holds('<span title="a > b" data-x="Data">hi</span>')).toBe(false);
602
+ expect(holds('<a title="x>y" href="did:key:zBot">@Bot</a>')).toBe(true);
603
+ // Script and style contents are not visible text; comments are not either.
604
+ expect(holds('<style>.Data { color: red }</style><p>hi</p>')).toBe(false);
605
+ expect(holds('<script>let Data = 1</script>hi')).toBe(false);
606
+ expect(holds('hi <!-- Data --> there')).toBe(false);
607
+ });
608
+
609
+ it('reads a bounded prefix, so a long run of unclosed openers cannot stall the waker', () => {
610
+ const bot = ['Data', 'did:key:zBot'];
611
+ // Unbounded, each of these took seconds: every unclosed opener scans to the end.
612
+ for (const opener of ['<script>', '<style>', '<!--']) {
613
+ const started = Date.now();
614
+ expect(holdsAWholeWordTerm('the metadata ' + opener.repeat(125_000), bot)).toBe(false);
615
+ expect(holdsAWholeWordTerm('hey Data ' + opener.repeat(125_000), bot)).toBe(true);
616
+ expect(Date.now() - started).toBeLessThan(1000);
617
+ }
618
+ // Within the limit a long message still wakes, by name and by DID target.
619
+ const filler = 'lorem ipsum '.repeat(1000);
620
+ expect(holdsAWholeWordTerm(filler + 'ask Data', bot)).toBe(true);
621
+ expect(holdsAWholeWordTerm(`${filler}<a href="did:key:zBot">@Bot</a>`, bot)).toBe(true);
622
+ // Past it, it does not.
623
+ expect(holdsAWholeWordTerm('x'.repeat(MENTION_TEXT_LIMIT) + ' Data', bot)).toBe(false);
624
+ });
625
+
626
+ it('refuses a mention subscription without its terms', async () => {
627
+ const manager = new WakerSubscriptionManager({
628
+ perspectiveClient,
629
+ logger: noopLogger(),
630
+ QuerySubscriptionProxy: function () { throw new Error('must not open'); },
631
+ onWake: () => {},
632
+ });
633
+ const { terms: _terms, ...withoutTerms } = sub;
634
+ await expect(manager.subscribe(withoutTerms)).rejects.toThrow(/needs its terms/);
635
+ await expect(manager.subscribe({ ...sub, terms: [] })).rejects.toThrow(/needs its terms/);
636
+ expect(manager.getActive()).toEqual([]);
637
+ expect(manager.getPending()).toEqual([]);
320
638
  });
321
639
 
322
640
  it('names the operator as the fix for a locked executor, on both message shapes', () => {