@almateam/app-sdk 0.6.0 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/index.js CHANGED
@@ -28,6 +28,55 @@ function applicationPath(value) {
28
28
  return parsed.origin === "https://application.invalid" && parsed.pathname === value ? value : null;
29
29
  }
30
30
  var UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
31
+ function parseAppHostEvent(told) {
32
+ if (typeof told !== "object" || told === null)
33
+ return null;
34
+ const message = told;
35
+ if (message["type"] !== "alma:event")
36
+ return null;
37
+ const kind = message["kind"];
38
+ if (kind !== "topic" && kind !== "type" && kind !== "execution")
39
+ return null;
40
+ const topicId = message["topic_id"];
41
+ const typeId = message["type_id"];
42
+ const executionId = message["execution_id"];
43
+ if (topicId !== undefined && (typeof topicId !== "string" || !UUID.test(topicId)))
44
+ return null;
45
+ if (typeId !== undefined && (typeof typeId !== "string" || !UUID.test(typeId)))
46
+ return null;
47
+ if (executionId !== undefined && (typeof executionId !== "string" || !UUID.test(executionId)))
48
+ return null;
49
+ if (kind === "topic" && topicId === undefined)
50
+ return null;
51
+ if (kind === "type" && typeId === undefined)
52
+ return null;
53
+ if (kind === "execution" && executionId === undefined)
54
+ return null;
55
+ return {
56
+ kind,
57
+ ...topicId !== undefined ? { topic_id: topicId } : {},
58
+ ...typeId !== undefined ? { type_id: typeId } : {},
59
+ ...executionId !== undefined ? { execution_id: executionId } : {},
60
+ ...kind === "type" && message["left"] === true ? { left: true } : {}
61
+ };
62
+ }
63
+ function hostEvents() {
64
+ const line = hostLine();
65
+ const listeners = new Set;
66
+ line.listen((told) => {
67
+ const event = parseAppHostEvent(told);
68
+ if (event === null)
69
+ return;
70
+ for (const listener of listeners)
71
+ listener(event);
72
+ });
73
+ return {
74
+ subscribe: (listener) => {
75
+ listeners.add(listener);
76
+ return () => listeners.delete(listener);
77
+ }
78
+ };
79
+ }
31
80
  function hostNavigation() {
32
81
  const line = hostLine();
33
82
  let path = applicationPath(document.documentElement.dataset["almaPath"]) ?? "/";
@@ -96,6 +145,32 @@ class AppCallError extends Error {
96
145
  function isFieldChanged(error) {
97
146
  return error instanceof Error && error.code === "field.changed" && error.current !== undefined;
98
147
  }
148
+ function isSharedStateConflict(error) {
149
+ return error instanceof Error && error.code === "app_shared_state.revision_conflict" && error.current !== undefined;
150
+ }
151
+ var LAST_LOOKED_KEY = "alma-last-looked";
152
+ var LAST_LOOKED_BYTES = 15000;
153
+ var VIEWER_QUESTION = "getViewer";
154
+ var VIEWER_WAIT_MS = 3000;
155
+ var SHELL_QUESTION = "getAppShell";
156
+ var SHELL_WAIT_MS = 3000;
157
+ var WATCH_QUESTION = "watchTopicChanges";
158
+ var WATCH_WAIT_MS = 5000;
159
+ var WATCH_TYPES_QUESTION = "watchTypeChanges";
160
+ var PUSHED_REREAD_MS = 300000;
161
+ var CATCH_UP_OVERLAP_MS = 60000;
162
+ var CATCH_UP_PAGE = 200;
163
+ var CATCH_UP_PAGES = 5;
164
+ var CATCH_UP_GAP_MS = 1000;
165
+ var WATCH_SHARED_QUESTION = "watchSharedState";
166
+ var SHARED_STATE_MESSAGE = "alma:shared";
167
+ var SHARED_POLL_MS = 5000;
168
+ var WATCH_PRESENCE_QUESTION = "watchPresence";
169
+ var PRESENCE_MESSAGE = "alma:presence";
170
+ var WATCH_BROADCASTS_QUESTION = "watchBroadcasts";
171
+ var BROADCAST_MESSAGE = "alma:broadcast";
172
+ var BROADCAST_EVENT = /^[A-Za-z0-9_.:-]{1,128}$/;
173
+ var oneRequest = () => crypto.randomUUID();
99
174
  function createAppSdk(transport) {
100
175
  const read = new Map;
101
176
  const precondition = (topicId, fieldKey, options) => {
@@ -113,14 +188,46 @@ function createAppSdk(transport) {
113
188
  const getExecution = (executionId) => transport.call("getExecution", {
114
189
  params: { id: executionId }
115
190
  });
191
+ let looked = null;
192
+ let saving = Promise.resolve();
193
+ const lookedAt = () => looked ??= transport.call("getAppState", {
194
+ params: { key: LAST_LOOKED_KEY }
195
+ }).then((entry) => new Map(entry.exists && typeof entry.value === "object" && entry.value ? Object.entries(entry.value) : []), (error) => {
196
+ looked = null;
197
+ throw error;
198
+ });
199
+ const seenOf = (record) => Object.fromEntries(Object.entries(record.revisions ?? {}).map(([key, revision]) => [
200
+ key,
201
+ revision.slice(0, 8)
202
+ ]));
116
203
  return {
117
204
  call: (operationId, request) => transport.call(operationId, request),
205
+ viewer: async () => {
206
+ if (!transport.viewer)
207
+ return null;
208
+ try {
209
+ return await transport.viewer();
210
+ } catch {
211
+ return null;
212
+ }
213
+ },
214
+ shell: async () => {
215
+ if (!transport.shell)
216
+ return null;
217
+ try {
218
+ return await transport.shell();
219
+ } catch {
220
+ return null;
221
+ }
222
+ },
118
223
  listTopics: async (query = {}) => {
119
224
  const page = await transport.call("listTopics", {
120
225
  query: {
121
226
  type: query.type,
227
+ schema: query.schema,
122
228
  filter: query.filter,
123
229
  sort: query.sort,
230
+ updated_after: query.updated_after,
124
231
  cursor: query.cursor,
125
232
  limit: query.limit
126
233
  }
@@ -130,6 +237,265 @@ function createAppSdk(transport) {
130
237
  read.set(topic.id, { ...topic.revisions });
131
238
  return page;
132
239
  },
240
+ watchTopics: (query, listener, options = {}) => {
241
+ const every = options.intervalMs ?? 15000;
242
+ const seen = new Map;
243
+ const listed = new Set;
244
+ const asked = new Set;
245
+ const told = new Set;
246
+ const watches = [];
247
+ let stopped = false;
248
+ let delay = every;
249
+ let timer;
250
+ let reading = false;
251
+ let again = false;
252
+ let catchUp = false;
253
+ let sweep = false;
254
+ let primed = false;
255
+ let typeId = null;
256
+ let typeWatch = null;
257
+ let typeAskedAt = Number.NEGATIVE_INFINITY;
258
+ let typeTold = false;
259
+ let baselined = false;
260
+ let joinedAfter = Number.NEGATIVE_INFINITY;
261
+ let newest = Number.NEGATIVE_INFINITY;
262
+ let resume = null;
263
+ let caughtUpAt = 0;
264
+ const page = (instead = {}) => transport.call("listTopics", {
265
+ query: {
266
+ type: query.type,
267
+ schema: query.schema,
268
+ filter: query.filter,
269
+ sort: query.sort,
270
+ updated_after: query.updated_after,
271
+ cursor: query.cursor,
272
+ limit: query.limit,
273
+ ...instead
274
+ }
275
+ });
276
+ const latest = (records) => {
277
+ let stamp = newest;
278
+ for (const topic of records) {
279
+ const at = Date.parse(topic.updated_at);
280
+ if (at > stamp)
281
+ stamp = at;
282
+ }
283
+ return stamp;
284
+ };
285
+ const note = (records, newAfter) => {
286
+ let changed = false;
287
+ for (const topic of records) {
288
+ if (stopped)
289
+ return changed;
290
+ const id = topic.id.toLowerCase();
291
+ const before = seen.get(id);
292
+ if (before === undefined ? Date.parse(topic.updated_at) > newAfter : before !== topic.updated_at) {
293
+ changed = true;
294
+ listener({
295
+ kind: before === undefined ? "added" : "topic",
296
+ topic_id: topic.id
297
+ });
298
+ }
299
+ seen.set(id, topic.updated_at);
300
+ }
301
+ return changed;
302
+ };
303
+ const pushed = async () => {
304
+ if (typeId && transport.watchTypes && !typeTold && !stopped && Date.now() - typeAskedAt >= PUSHED_REREAD_MS) {
305
+ typeAskedAt = Date.now();
306
+ const asking = typeId;
307
+ typeWatch?.stop();
308
+ typeWatch = await transport.watchTypes([asking], (heard, left) => {
309
+ if (heard.toLowerCase() === asking)
310
+ read(left ? "left" : "since");
311
+ }).catch(() => null);
312
+ if (stopped)
313
+ typeWatch?.stop();
314
+ typeTold = typeWatch?.watching.some((id) => id.toLowerCase() === asking) ?? false;
315
+ if (typeTold)
316
+ for (const watch of watches.splice(0))
317
+ watch.stop();
318
+ }
319
+ if (typeTold) {
320
+ catchUp = true;
321
+ return true;
322
+ }
323
+ if (!transport.watch || stopped)
324
+ return false;
325
+ const fresh = [...listed].filter((id) => !asked.has(id));
326
+ if (fresh.length > 0) {
327
+ for (const id of fresh)
328
+ asked.add(id);
329
+ const watch = await transport.watch(fresh, (id) => {
330
+ if (listed.has(id.toLowerCase()))
331
+ read();
332
+ });
333
+ if (stopped)
334
+ watch.stop();
335
+ else
336
+ watches.push(watch);
337
+ for (const id of watch.watching)
338
+ told.add(id.toLowerCase());
339
+ }
340
+ return [...listed].every((id) => told.has(id));
341
+ };
342
+ const tick = async () => {
343
+ try {
344
+ if (!baselined && query.type && transport.watchTypes) {
345
+ let cursor;
346
+ let oldest;
347
+ for (let pages = 0;pages < CATCH_UP_PAGES; pages += 1) {
348
+ const newestFirst = await page({
349
+ sort: "-updated_at",
350
+ cursor,
351
+ limit: CATCH_UP_PAGE
352
+ });
353
+ note(newestFirst.data, Number.POSITIVE_INFINITY);
354
+ newest = latest(newestFirst.data);
355
+ typeId ??= newestFirst.meta?.type_id?.toLowerCase() ?? null;
356
+ oldest = newestFirst.data.at(-1) ?? oldest;
357
+ cursor = newestFirst.meta?.next_cursor ?? undefined;
358
+ if (!cursor || !oldest || Date.parse(oldest.updated_at) < newest - CATCH_UP_OVERLAP_MS)
359
+ break;
360
+ }
361
+ joinedAfter = cursor && oldest ? Date.parse(oldest.updated_at) : Number.NEGATIVE_INFINITY;
362
+ baselined = true;
363
+ }
364
+ if (stopped)
365
+ return delay;
366
+ const answer = await page();
367
+ const changed = note(answer.data, primed || baselined ? joinedAfter : Number.POSITIVE_INFINITY);
368
+ primed = true;
369
+ for (const topic of answer.data)
370
+ listed.add(topic.id.toLowerCase());
371
+ typeId ??= answer.meta?.type_id?.toLowerCase() ?? null;
372
+ if (await pushed().catch(() => false))
373
+ return PUSHED_REREAD_MS;
374
+ delay = changed ? every : Math.min(delay * 2, 60000);
375
+ } catch {
376
+ delay = Math.min(delay * 2, 60000);
377
+ }
378
+ return delay;
379
+ };
380
+ const caughtUp = async () => {
381
+ const wait = caughtUpAt + CATCH_UP_GAP_MS - Date.now();
382
+ if (wait > 0)
383
+ await new Promise((resolve) => setTimeout(resolve, wait));
384
+ if (stopped)
385
+ return;
386
+ const floor = newest - CATCH_UP_OVERLAP_MS;
387
+ const requested = query.updated_after ? Date.parse(query.updated_after) : Number.NaN;
388
+ const since = resume ? resume.since : Number.isFinite(requested) && !(requested < floor) ? query.updated_after : Number.isFinite(floor) ? new Date(floor).toISOString() : undefined;
389
+ let cursor = resume?.cursor;
390
+ try {
391
+ for (let pages = 0;pages < CATCH_UP_PAGES; pages += 1) {
392
+ const answer = await page({
393
+ sort: "updated_at",
394
+ updated_after: since,
395
+ cursor,
396
+ limit: CATCH_UP_PAGE
397
+ });
398
+ if (stopped)
399
+ return;
400
+ note(answer.data, joinedAfter);
401
+ newest = latest(answer.data);
402
+ cursor = answer.meta.next_cursor ?? undefined;
403
+ resume = cursor ? { since, cursor } : null;
404
+ if (!cursor)
405
+ break;
406
+ }
407
+ if (resume)
408
+ catchUp = true;
409
+ } catch {
410
+ resume = null;
411
+ }
412
+ caughtUpAt = Date.now();
413
+ };
414
+ const swept = async () => {
415
+ const present = new Set;
416
+ const newestFirst = (cursor) => page({ sort: "-updated_at", cursor, limit: CATCH_UP_PAGE });
417
+ let cursor;
418
+ let oldest;
419
+ try {
420
+ let pages = 0;
421
+ while (pages < CATCH_UP_PAGES) {
422
+ const answer = await newestFirst(cursor);
423
+ if (stopped)
424
+ return;
425
+ pages += 1;
426
+ for (const topic of answer.data)
427
+ present.add(topic.id.toLowerCase());
428
+ oldest = answer.data.at(-1) ?? oldest;
429
+ cursor = answer.meta?.next_cursor ?? undefined;
430
+ if (!cursor)
431
+ break;
432
+ }
433
+ if (pages > 1) {
434
+ const moved = await newestFirst();
435
+ if (stopped)
436
+ return;
437
+ for (const topic of moved.data)
438
+ present.add(topic.id.toLowerCase());
439
+ }
440
+ const floor = cursor && oldest ? Date.parse(oldest.updated_at) + CATCH_UP_OVERLAP_MS : Number.NEGATIVE_INFINITY;
441
+ for (const [id, at] of seen) {
442
+ if (stopped)
443
+ return;
444
+ if (present.has(id) || !(Date.parse(at) > floor))
445
+ continue;
446
+ seen.delete(id);
447
+ listed.delete(id);
448
+ listener({ kind: "removed", topic_id: id });
449
+ }
450
+ } catch {}
451
+ };
452
+ const read = (what = "all") => {
453
+ if (stopped)
454
+ return;
455
+ if (what === "all")
456
+ again = true;
457
+ else
458
+ catchUp = true;
459
+ if (what === "left")
460
+ sweep = true;
461
+ if (reading)
462
+ return;
463
+ reading = true;
464
+ (async () => {
465
+ while (!stopped && (again || sweep || catchUp)) {
466
+ if (again) {
467
+ again = false;
468
+ clearTimeout(timer);
469
+ const next = await tick();
470
+ if (!stopped)
471
+ timer = setTimeout(() => read(), next);
472
+ } else if (sweep) {
473
+ sweep = false;
474
+ await swept();
475
+ } else {
476
+ catchUp = false;
477
+ await caughtUp();
478
+ }
479
+ }
480
+ reading = false;
481
+ })();
482
+ };
483
+ read();
484
+ return () => {
485
+ stopped = true;
486
+ clearTimeout(timer);
487
+ typeWatch?.stop();
488
+ for (const watch of watches)
489
+ watch.stop();
490
+ };
491
+ },
492
+ listViews: (type) => transport.call("listViews", {
493
+ query: { type }
494
+ }),
495
+ readView: (type, key, page = {}) => transport.call("readView", {
496
+ params: { key },
497
+ query: { type, cursor: page.cursor, limit: page.limit }
498
+ }),
133
499
  getTopicRecord: async (topicId) => {
134
500
  const record = await transport.call("getTopicRecord", { params: { id: topicId } });
135
501
  if (record.revisions)
@@ -138,6 +504,37 @@ function createAppSdk(transport) {
138
504
  },
139
505
  getTopicFactDiscussion: (topicId, factId) => transport.call("getTopicFactDiscussion", { params: { id: topicId, factId } }),
140
506
  getTopicFieldHistory: (topicId, fieldKey) => transport.call("getTopicFieldHistory", { params: { id: topicId, key: fieldKey } }),
507
+ getTopicSummary: (topicId) => transport.call("getTopicSummary", {
508
+ params: { id: topicId }
509
+ }),
510
+ listTopicReferences: (topicId, query = {}) => transport.call("listTopicReferences", {
511
+ params: { id: topicId },
512
+ query: {
513
+ type: query.type,
514
+ field: query.field,
515
+ cursor: query.cursor,
516
+ limit: query.limit
517
+ }
518
+ }),
519
+ countTopics: (query) => transport.call("countTopics", {
520
+ query: {
521
+ type: query.type,
522
+ filter: query.filter,
523
+ group_by: query.groupBy,
524
+ limit: query.limit
525
+ }
526
+ }),
527
+ listRelatedTopics: (topicId, query) => transport.call("listRelatedTopics", {
528
+ params: { id: topicId },
529
+ query: {
530
+ step: query.step,
531
+ depth: query.depth,
532
+ type: query.type,
533
+ filter: query.filter,
534
+ cursor: query.cursor,
535
+ limit: query.limit
536
+ }
537
+ }),
141
538
  downloadTopicFactAttachment: (topicId, factId, turn, attachmentId) => transport.call("downloadTopicFactAttachment", {
142
539
  params: { id: topicId, factId, attachmentId },
143
540
  query: { turn_kind: turn.kind, turn_id: turn.id }
@@ -158,17 +555,55 @@ function createAppSdk(transport) {
158
555
  fields[fieldKey] = revision;
159
556
  return receipt;
160
557
  },
161
- createTopic: (name, topicTypeId) => transport.call("createTopic", {
162
- body: { name, ...topicTypeId ? { topic_type_id: topicTypeId } : {} }
558
+ clearTopicField: async (topicId, fieldKey, options = {}) => {
559
+ const receipt = await transport.call("clearTopicField", {
560
+ params: { id: topicId, key: fieldKey },
561
+ body: precondition(topicId, fieldKey, options),
562
+ ...options.idempotencyKey ? { idempotencyKey: options.idempotencyKey } : {}
563
+ });
564
+ const revision = receipt.current_revision ?? receipt.revision;
565
+ const fields = read.get(topicId);
566
+ if (fields && revision)
567
+ fields[fieldKey] = revision;
568
+ return receipt;
569
+ },
570
+ createTopic: async (name, topicTypeId, options = {}) => {
571
+ const fields = options.fields ?? [];
572
+ const created = await transport.call("createTopic", {
573
+ body: {
574
+ name,
575
+ ...topicTypeId ? { topic_type_id: topicTypeId } : {},
576
+ ...fields.length > 0 ? {
577
+ fields: fields.map((field) => ({
578
+ key: field.key,
579
+ value: field.value,
580
+ ...field.refTopicId ? { ref_topic_id: field.refTopicId } : {}
581
+ }))
582
+ } : {}
583
+ },
584
+ idempotencyKey: options.idempotencyKey ?? oneRequest()
585
+ });
586
+ if (created.revisions)
587
+ read.set(created.id, { ...created.revisions });
588
+ return created;
589
+ },
590
+ deleteTopic: (topicId, options = {}) => transport.call("deleteTopic", {
591
+ params: { id: topicId },
592
+ idempotencyKey: options.idempotencyKey ?? oneRequest()
593
+ }),
594
+ restoreTopic: (topicId, options = {}) => transport.call("restoreTopic", {
595
+ params: { id: topicId },
596
+ idempotencyKey: options.idempotencyKey ?? oneRequest()
163
597
  }),
164
598
  listTopicTypes: () => transport.call("listTopicTypes"),
165
599
  listWorkflows: () => transport.call("listWorkflows"),
166
- runWorkflow: (workflowId, run = {}) => transport.call("runWorkflow", {
600
+ runWorkflow: (workflowId, run = {}, options = {}) => transport.call("runWorkflow", {
167
601
  params: { id: workflowId },
168
602
  body: {
169
603
  ...run.topicId ? { topic_id: run.topicId } : {},
170
604
  ...run.input ? { input: run.input } : {}
171
- }
605
+ },
606
+ idempotencyKey: options.idempotencyKey ?? oneRequest()
172
607
  }),
173
608
  getExecution,
174
609
  listRuns: (workflowId, run = {}) => transport.call("listWorkflowExecutions", {
@@ -197,12 +632,21 @@ function createAppSdk(transport) {
197
632
  getWorkflowCard: (workflowId) => transport.call("getWorkflowCard", {
198
633
  params: { id: workflowId }
199
634
  }),
200
- createWorkflowLesson: (workflowId, content) => transport.call("createLesson", {
201
- body: { workflow_id: workflowId, content }
635
+ createWorkflowLesson: (workflowId, content, options = {}) => transport.call("createLesson", {
636
+ body: { workflow_id: workflowId, content },
637
+ idempotencyKey: options.idempotencyKey ?? oneRequest()
202
638
  }),
203
- updateLesson: (lessonId, content, editRevision) => transport.call("updateLesson", {
639
+ updateLesson: (lessonId, content, editRevision, options = {}) => transport.call("updateLesson", {
204
640
  params: { id: lessonId },
205
- body: { content, expected_revision: editRevision }
641
+ body: { content, expected_revision: editRevision },
642
+ idempotencyKey: options.idempotencyKey ?? oneRequest()
643
+ }),
644
+ publishCard: (card) => transport.call("publishCard", {
645
+ body: { title: card.title, blocks: card.blocks }
646
+ }),
647
+ raiseEvent: (event, payload, options = {}) => transport.call("raiseAppEvent", {
648
+ body: { event, ...payload ? { payload } : {} },
649
+ idempotencyKey: options.idempotencyKey ?? oneRequest()
206
650
  }),
207
651
  state: {
208
652
  get: async (key) => {
@@ -219,14 +663,306 @@ function createAppSdk(transport) {
219
663
  await transport.call("deleteAppState", { params: { key } });
220
664
  }
221
665
  },
666
+ shared: {
667
+ get: (key) => transport.call("getAppSharedState", { params: { key } }),
668
+ list: () => transport.call("listAppSharedState"),
669
+ set: (key, value, options = {}) => transport.call("setAppSharedState", {
670
+ params: { key },
671
+ body: {
672
+ value,
673
+ ...options.ifRevision === undefined ? {} : { if_revision: options.ifRevision }
674
+ }
675
+ }),
676
+ delete: (key) => transport.call("deleteAppSharedState", { params: { key } }),
677
+ watch: (listener, options = {}) => {
678
+ const every = options.intervalMs ?? SHARED_POLL_MS;
679
+ const seen = new Map;
680
+ let toldWhileReading = null;
681
+ let watch = null;
682
+ let stopped = false;
683
+ let delay = every;
684
+ let timer;
685
+ let reading = false;
686
+ let again = false;
687
+ const deleted = (key) => ({
688
+ key,
689
+ exists: false,
690
+ value: null,
691
+ revision: 0
692
+ });
693
+ const tell = (entry) => {
694
+ if (stopped)
695
+ return false;
696
+ const before = seen.get(entry.key);
697
+ if (entry.exists) {
698
+ if (before && entry.revision <= before.revision)
699
+ return false;
700
+ seen.set(entry.key, { revision: entry.revision, exists: true });
701
+ } else {
702
+ if (!before?.exists)
703
+ return false;
704
+ seen.set(entry.key, { revision: before.revision, exists: false });
705
+ }
706
+ listener(entry);
707
+ return true;
708
+ };
709
+ const tellDeleted = (key, revision) => {
710
+ if (stopped)
711
+ return;
712
+ const before = seen.get(key);
713
+ if (before && revision <= before.revision)
714
+ return;
715
+ seen.set(key, { revision, exists: false });
716
+ if (before?.exists)
717
+ listener(deleted(key));
718
+ };
719
+ const readAll = async () => {
720
+ const told = new Set;
721
+ toldWhileReading = told;
722
+ try {
723
+ const entries = await transport.call("listAppSharedState");
724
+ const held = new Set(entries.map((entry) => entry.key));
725
+ let changed = false;
726
+ for (const entry of entries)
727
+ if (!told.has(entry.key))
728
+ changed = tell(entry) || changed;
729
+ for (const [key, was] of seen)
730
+ if (was.exists && !held.has(key) && !told.has(key))
731
+ changed = tell(deleted(key)) || changed;
732
+ return changed;
733
+ } finally {
734
+ toldWhileReading = null;
735
+ }
736
+ };
737
+ const tick = async () => {
738
+ try {
739
+ const changed = await readAll();
740
+ if (watch?.watching)
741
+ return PUSHED_REREAD_MS;
742
+ delay = changed ? every : Math.min(delay * 2, 60000);
743
+ } catch {
744
+ delay = Math.min(delay * 2, 60000);
745
+ }
746
+ return delay;
747
+ };
748
+ const read = () => {
749
+ if (stopped)
750
+ return;
751
+ again = true;
752
+ if (reading)
753
+ return;
754
+ reading = true;
755
+ (async () => {
756
+ while (!stopped && again) {
757
+ again = false;
758
+ clearTimeout(timer);
759
+ const next = await tick();
760
+ if (!stopped)
761
+ timer = setTimeout(read, next);
762
+ }
763
+ reading = false;
764
+ })();
765
+ };
766
+ const heard = (told) => {
767
+ if (stopped)
768
+ return;
769
+ if ("missed" in told)
770
+ return read();
771
+ toldWhileReading?.add(told.key);
772
+ if ("exists" in told)
773
+ tellDeleted(told.key, told.revision);
774
+ else if (Object.hasOwn(told, "value"))
775
+ tell({
776
+ key: told.key,
777
+ exists: true,
778
+ value: told.value,
779
+ revision: told.revision
780
+ });
781
+ else
782
+ transport.call("getAppSharedState", {
783
+ params: { key: told.key }
784
+ }).then(tell, read);
785
+ };
786
+ (async () => {
787
+ const asked = await transport.watchShared?.(heard).catch(() => null);
788
+ if (stopped)
789
+ asked?.stop();
790
+ else
791
+ watch = asked ?? null;
792
+ read();
793
+ })();
794
+ return () => {
795
+ stopped = true;
796
+ clearTimeout(timer);
797
+ watch?.stop();
798
+ };
799
+ }
800
+ },
801
+ presence: {
802
+ watch: (listener) => {
803
+ let stopped = false;
804
+ let watch = null;
805
+ (async () => {
806
+ const asked = await transport.watchPresence?.((presence) => {
807
+ if (!stopped)
808
+ listener(presence);
809
+ }).catch(() => null);
810
+ if (stopped)
811
+ asked?.stop();
812
+ else
813
+ watch = asked ?? null;
814
+ })();
815
+ return () => {
816
+ stopped = true;
817
+ watch?.stop();
818
+ };
819
+ }
820
+ },
821
+ broadcast: async (event, payload) => {
822
+ await transport.call("sendAppBroadcast", { body: { event, ...payload === undefined ? {} : { payload } } });
823
+ },
824
+ onBroadcast: (event, listener, options = {}) => {
825
+ let stopped = false;
826
+ let watch = null;
827
+ (async () => {
828
+ const asked = await transport.watchBroadcasts?.((message) => {
829
+ if (stopped || message.event !== event)
830
+ return;
831
+ if (message.self && !options.self)
832
+ return;
833
+ listener(message.payload);
834
+ }).catch(() => null);
835
+ if (stopped)
836
+ asked?.stop();
837
+ else
838
+ watch = asked ?? null;
839
+ })();
840
+ return () => {
841
+ stopped = true;
842
+ watch?.stop();
843
+ };
844
+ },
222
845
  listOutcomes: (page = {}) => transport.call("listOutcomes", {
223
846
  query: { limit: page.limit, offset: page.offset }
224
847
  }),
225
- getOrganizationAnalytics: () => transport.call("getOrganizationAnalytics")
848
+ lastLooked: {
849
+ changes: async (record) => {
850
+ const before = (await lookedAt()).get(record.id);
851
+ if (!before)
852
+ return null;
853
+ const now = seenOf(record);
854
+ return [
855
+ ...new Set([...Object.keys(before), ...Object.keys(now)])
856
+ ].filter((key) => before[key] !== now[key]);
857
+ },
858
+ mark: async (record) => {
859
+ const all = await lookedAt();
860
+ all.delete(record.id);
861
+ all.set(record.id, seenOf(record));
862
+ while (all.size > 1 && JSON.stringify(Object.fromEntries(all)).length > LAST_LOOKED_BYTES)
863
+ all.delete(all.keys().next().value);
864
+ const value = Object.fromEntries(all);
865
+ saving = saving.catch(() => {
866
+ return;
867
+ }).then(() => transport.call("setAppState", {
868
+ params: { key: LAST_LOOKED_KEY },
869
+ body: { value }
870
+ }));
871
+ await saving;
872
+ }
873
+ }
874
+ };
875
+ }
876
+ var SHARED_STATE_KEY = /^[A-Za-z0-9_-]{1,128}$/;
877
+ function sharedStateTold(told) {
878
+ if (typeof told !== "object" || told === null)
879
+ return null;
880
+ const message = told;
881
+ if (message["type"] !== SHARED_STATE_MESSAGE)
882
+ return null;
883
+ if (message["missed"] === true)
884
+ return { missed: true };
885
+ const { key, revision } = message;
886
+ if (typeof key !== "string" || !SHARED_STATE_KEY.test(key))
887
+ return null;
888
+ if (!Number.isSafeInteger(revision) || revision < 0)
889
+ return null;
890
+ if (message["exists"] === false)
891
+ return { key, revision, exists: false };
892
+ return Object.hasOwn(message, "value") ? { key, revision, value: message["value"] } : { key, revision };
893
+ }
894
+ function presenceTold(told) {
895
+ if (typeof told !== "object" || told === null)
896
+ return null;
897
+ const message = told;
898
+ if (message["type"] !== PRESENCE_MESSAGE)
899
+ return null;
900
+ const { count, people } = message;
901
+ if (!Number.isSafeInteger(count) || count < 0)
902
+ return null;
903
+ if (people === null)
904
+ return { count, people: null };
905
+ if (!Array.isArray(people))
906
+ return null;
907
+ const named = people.filter((person) => typeof person === "object" && person !== null && typeof person["person_id"] === "string");
908
+ return {
909
+ count,
910
+ people: named.map((person) => ({ person_id: person.person_id }))
226
911
  };
227
912
  }
913
+ function broadcastTold(told) {
914
+ if (typeof told !== "object" || told === null)
915
+ return null;
916
+ const message = told;
917
+ if (message["type"] !== BROADCAST_MESSAGE)
918
+ return null;
919
+ const { event } = message;
920
+ if (typeof event !== "string" || !BROADCAST_EVENT.test(event))
921
+ return null;
922
+ return {
923
+ event,
924
+ payload: message["payload"] ?? null,
925
+ self: message["self"] === true
926
+ };
927
+ }
928
+ var SHELL_LAYOUTS = ["list", "board", "table", "queue"];
929
+ function isAppShell(told) {
930
+ if (typeof told !== "object" || told === null)
931
+ return false;
932
+ const shell = told;
933
+ return typeof shell["record_type_id"] === "string" && typeof shell["layout"] === "string" && SHELL_LAYOUTS.includes(shell["layout"]) && Array.isArray(shell["fields"]);
934
+ }
228
935
  function hostTransport() {
229
936
  const line = hostLine();
937
+ const topicChanges = new Set;
938
+ const typeChanges = new Set;
939
+ const sharedChanges = new Set;
940
+ const presenceChanges = new Set;
941
+ const broadcasts = new Set;
942
+ let present = null;
943
+ line.listen((told) => {
944
+ const shared = sharedStateTold(told);
945
+ if (shared)
946
+ for (const heard of sharedChanges)
947
+ heard(shared);
948
+ const presence = presenceTold(told);
949
+ if (presence) {
950
+ present = presence;
951
+ for (const heard of presenceChanges)
952
+ heard(presence);
953
+ }
954
+ const broadcast = broadcastTold(told);
955
+ if (broadcast)
956
+ for (const heard of broadcasts)
957
+ heard(broadcast);
958
+ const event = parseAppHostEvent(told);
959
+ if (event?.kind === "topic" && event.topic_id !== undefined)
960
+ for (const changed of topicChanges)
961
+ changed(event.topic_id.toLowerCase());
962
+ if (event?.kind === "type" && event.type_id !== undefined)
963
+ for (const changed of typeChanges)
964
+ changed(event.type_id.toLowerCase(), event.left === true);
965
+ });
230
966
  const pending = new Map;
231
967
  line.listen((told) => {
232
968
  if (typeof told !== "object" || told === null)
@@ -251,39 +987,133 @@ function hostTransport() {
251
987
  else
252
988
  call.resolve(message["data"]);
253
989
  });
990
+ const ask = (operation, request = {}, waitMs = 30000) => new Promise((resolve, reject) => {
991
+ const id = crypto.randomUUID();
992
+ const timer = setTimeout(() => {
993
+ pending.delete(id);
994
+ reject(new Error("The host did not answer. Reload the app to reconnect."));
995
+ }, waitMs);
996
+ pending.set(id, {
997
+ resolve: (data) => resolve(data),
998
+ reject,
999
+ timer
1000
+ });
1001
+ const query = {};
1002
+ for (const [key, value] of Object.entries(request.query ?? {}))
1003
+ if (value !== undefined)
1004
+ query[key] = Array.isArray(value) ? value : String(value);
1005
+ line.post({
1006
+ type: "alma:operation",
1007
+ id,
1008
+ operation,
1009
+ params: request.params ?? {},
1010
+ query,
1011
+ ...request.body ? { body: request.body } : {},
1012
+ ...request.idempotencyKey ? { idempotency_key: request.idempotencyKey } : {}
1013
+ });
1014
+ });
1015
+ const watchFor = async (question, key, heardBy, ids, changed) => {
1016
+ const asked = new Set(ids.map((id) => id.toLowerCase()));
1017
+ const heard = (id, left) => {
1018
+ if (asked.has(id))
1019
+ changed(id, left);
1020
+ };
1021
+ heardBy.add(heard);
1022
+ const stop = () => heardBy.delete(heard);
1023
+ try {
1024
+ const told = await ask(question, { body: { [key]: [...asked] } }, WATCH_WAIT_MS);
1025
+ const watching = typeof told === "object" && told !== null ? told["watching"] : null;
1026
+ return {
1027
+ watching: Array.isArray(watching) ? watching.filter((id) => typeof id === "string" && asked.has(id.toLowerCase())) : [],
1028
+ stop
1029
+ };
1030
+ } catch {
1031
+ stop();
1032
+ return { watching: [], stop };
1033
+ }
1034
+ };
254
1035
  return {
255
- call: (operationId, request = {}) => new Promise((resolve, reject) => {
256
- const id = crypto.randomUUID();
257
- const timer = setTimeout(() => {
258
- pending.delete(id);
259
- reject(new Error("The host did not answer. Reload the app to reconnect."));
260
- }, 30000);
261
- pending.set(id, {
262
- resolve: (data) => resolve(data),
263
- reject,
264
- timer
265
- });
266
- const query = {};
267
- for (const [key, value] of Object.entries(request.query ?? {}))
268
- if (value !== undefined)
269
- query[key] = Array.isArray(value) ? value : String(value);
270
- line.post({
271
- type: "alma:operation",
272
- id,
273
- operation: operationId,
274
- params: request.params ?? {},
275
- query,
276
- ...request.body ? { body: request.body } : {},
277
- ...request.idempotencyKey ? { idempotency_key: request.idempotencyKey } : {}
278
- });
279
- })
1036
+ call: (operationId, request = {}) => ask(operationId, request),
1037
+ viewer: async () => {
1038
+ const told = await ask(VIEWER_QUESTION, {}, VIEWER_WAIT_MS);
1039
+ const personId = typeof told === "object" && told !== null ? told["person_id"] : null;
1040
+ return typeof personId === "string" ? { person_id: personId } : null;
1041
+ },
1042
+ shell: async () => {
1043
+ const told = await ask(SHELL_QUESTION, {}, SHELL_WAIT_MS);
1044
+ return isAppShell(told) ? told : null;
1045
+ },
1046
+ watch: (topicIds, changed) => watchFor(WATCH_QUESTION, "topic_ids", topicChanges, topicIds, changed),
1047
+ watchTypes: (typeIds, changed) => watchFor(WATCH_TYPES_QUESTION, "type_ids", typeChanges, typeIds, changed),
1048
+ watchShared: async (told) => {
1049
+ sharedChanges.add(told);
1050
+ const stop = () => sharedChanges.delete(told);
1051
+ try {
1052
+ const answer = await ask(WATCH_SHARED_QUESTION, {}, WATCH_WAIT_MS);
1053
+ const watching = typeof answer === "object" && answer !== null && answer["watching"] === true;
1054
+ if (!watching)
1055
+ stop();
1056
+ return { watching, stop };
1057
+ } catch {
1058
+ stop();
1059
+ return { watching: false, stop };
1060
+ }
1061
+ },
1062
+ watchPresence: async (told) => {
1063
+ let heard = false;
1064
+ const hear = (presence) => {
1065
+ heard = true;
1066
+ told(presence);
1067
+ };
1068
+ presenceChanges.add(hear);
1069
+ const stop = () => presenceChanges.delete(hear);
1070
+ try {
1071
+ const answer = await ask(WATCH_PRESENCE_QUESTION, {}, WATCH_WAIT_MS);
1072
+ const watching = typeof answer === "object" && answer !== null && answer["watching"] === true;
1073
+ if (!watching)
1074
+ stop();
1075
+ else if (present && !heard)
1076
+ told(present);
1077
+ return { watching, stop };
1078
+ } catch {
1079
+ stop();
1080
+ return { watching: false, stop };
1081
+ }
1082
+ },
1083
+ watchBroadcasts: async (told) => {
1084
+ broadcasts.add(told);
1085
+ const stop = () => broadcasts.delete(told);
1086
+ try {
1087
+ const answer = await ask(WATCH_BROADCASTS_QUESTION, {}, WATCH_WAIT_MS);
1088
+ const watching = typeof answer === "object" && answer !== null && answer["watching"] === true;
1089
+ if (!watching)
1090
+ stop();
1091
+ return { watching, stop };
1092
+ } catch {
1093
+ stop();
1094
+ return { watching: false, stop };
1095
+ }
1096
+ }
280
1097
  };
281
1098
  }
282
1099
  export {
283
1100
  AppCallError,
1101
+ BROADCAST_MESSAGE,
1102
+ PRESENCE_MESSAGE,
1103
+ SHARED_STATE_MESSAGE,
1104
+ SHELL_QUESTION,
1105
+ VIEWER_QUESTION,
1106
+ WATCH_BROADCASTS_QUESTION,
1107
+ WATCH_PRESENCE_QUESTION,
1108
+ WATCH_QUESTION,
1109
+ WATCH_SHARED_QUESTION,
1110
+ WATCH_TYPES_QUESTION,
284
1111
  applicationPath,
285
1112
  createAppSdk,
1113
+ hostEvents,
286
1114
  hostNavigation,
287
1115
  hostTransport,
288
- isFieldChanged
1116
+ isFieldChanged,
1117
+ isSharedStateConflict,
1118
+ parseAppHostEvent
289
1119
  };