@pmate/chat-sdk 0.13.0-profile.8 → 0.14.0-seq.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.
Files changed (33) hide show
  1. package/README.md +57 -0
  2. package/lib/profile.d.ts +1 -1
  3. package/lib/profile.js +1 -1
  4. package/lib/runtime/profileChat.d.ts +7 -0
  5. package/lib/runtime/profileChat.js +105 -20
  6. package/lib/runtime/profileCommitQueue.js +3 -3
  7. package/lib/runtime/profileCoordinator.d.ts +25 -20
  8. package/lib/runtime/profileCoordinator.js +146 -128
  9. package/lib/runtime/profileDatabase.d.ts +6 -9
  10. package/lib/runtime/profileDatabase.js +10 -39
  11. package/lib/runtime/profileGenerationBuilder.d.ts +2 -3
  12. package/lib/runtime/profileGenerationBuilder.js +23 -23
  13. package/lib/runtime/profileInboxFeed.js +3 -2
  14. package/lib/runtime/profileLegacyInbox.js +2 -1
  15. package/lib/runtime/profileMemoryStore.d.ts +9 -3
  16. package/lib/runtime/profileMemoryStore.js +50 -10
  17. package/lib/runtime/profileOutboxDispatcher.js +4 -1
  18. package/lib/runtime/profileOwner.d.ts +2 -7
  19. package/lib/runtime/profileOwner.js +18 -46
  20. package/lib/runtime/profileProjection.d.ts +19 -1
  21. package/lib/runtime/profileProjection.js +139 -18
  22. package/lib/runtime/profileStoreTypes.d.ts +4 -11
  23. package/lib/runtime/profileWindows.d.ts +2 -0
  24. package/lib/runtime/profileWindows.js +13 -3
  25. package/lib/runtime/{profileReplica.d.ts → profileWorkerClient.d.ts} +9 -26
  26. package/lib/runtime/{profileReplica.js → profileWorkerClient.js} +46 -97
  27. package/lib/runtime/profileWorkerHost.d.ts +3 -6
  28. package/lib/runtime/profileWorkerHost.js +23 -30
  29. package/lib/runtime/readSync.d.ts +1 -1
  30. package/lib/runtime/readSync.js +10 -6
  31. package/lib/runtime/sourceCursor.d.ts +6 -0
  32. package/lib/runtime/sourceCursor.js +7 -0
  33. package/package.json +2 -2
@@ -7,7 +7,13 @@ import { ProfileReadingIndex } from "./profileReadingIndex.js";
7
7
  import { compareProfileOrder, ProfileWindowDirectory } from "./profileWindows.js";
8
8
  import { projectMessageContent } from "../messageView.js";
9
9
  export const profileDiscussionId = (parent, root) => `discussion:${JSON.stringify([parent, root])}`;
10
- const supportedLocalOperations = new Set(["migrationCompleted", "restoreReadingCommand", "restoreReadingIntent", "restoreEvent", "restoreInvitation", "register", "teamAccess", "send", "commandPayload", "observe", "commandResult", "restoreReading", "restoreReceipt", "receiptsReady"]);
10
+ function mergeAssignedLists(source, destination) {
11
+ const merged = { ...source };
12
+ for (const [key, values] of Object.entries(destination ?? {}))
13
+ merged[key] = [...new Map([...(merged[key] ?? []), ...values].map(value => [JSON.stringify(value), value])).values()];
14
+ return merged;
15
+ }
16
+ const supportedLocalOperations = new Set(["restoreReadingSources", "restoreMessageReadingFacts", "migrationCompleted", "restoreReadingCommand", "restoreReadingIntent", "restoreEvent", "restoreInvitation", "register", "groupSnapshot", "groupDenied", "teamAccess", "send", "commandPayload", "observe", "commandResult", "restoreReading", "restoreReceipt", "receiptsReady"]);
11
17
  /** Committed authority for the replay reducer. Drafts contain only changed rows;
12
18
  * failure discards the draft, leaving both entities and indexes untouched. */
13
19
  export class ProfileProjection {
@@ -140,6 +146,10 @@ class ProfileProjectionDraft {
140
146
  return Error("PROFILE_OPERATION_UNSUPPORTED");
141
147
  if (operation.type === "teamAccess" && operation.allowed && operation.expectedAccessRevision !== (this.teamAccessRevision ?? this.base.current.teamAccessRevision ?? 0))
142
148
  return Error("PROFILE_ACCESS_CHECK_STALE");
149
+ if (operation.type === "groupSnapshot" && operation.expectedControlRevision !== undefined && operation.expectedControlRevision !== (this.thread(operation.threadId)?.internal?.groupControlRevision ?? 0))
150
+ return Error("GROUP_METADATA_STALE");
151
+ if ((operation.type === "groupSnapshot" || operation.type === "groupDenied") && operation.expectedAccessRevision !== (this.teamAccessRevision ?? this.base.current.teamAccessRevision ?? 0))
152
+ return Error("PROFILE_ACCESS_CHECK_STALE");
143
153
  if (operation.type !== "send" && operation.type !== "observe")
144
154
  return;
145
155
  const thread = this.thread(operation.threadId);
@@ -354,6 +364,18 @@ class ProfileProjectionDraft {
354
364
  this.seq = seq;
355
365
  }
356
366
  local(operation) {
367
+ if (operation.type === "restoreReadingSources") {
368
+ if (this.thread(operation.threadId))
369
+ this.mergeAssignedReading(operation.threadId, operation.sources);
370
+ return;
371
+ }
372
+ if (operation.type === "restoreMessageReadingFacts") {
373
+ const message = this.message(operation.messageId);
374
+ if (message)
375
+ this.setMessage({ ...message, explicitReadingFacts: [...new Map([...message.explicitReadingFacts, ...operation.facts.filter(fact => fact.profileId === this.base.identity.profileId)]
376
+ .map(fact => [JSON.stringify(fact), fact])).values()] });
377
+ return;
378
+ }
357
379
  if (operation.type === "restoreInvitation") {
358
380
  const wire = operation.message, body = wire.body;
359
381
  if (wire.appId !== this.base.identity.appId || wire.seq || body?.kind !== "contact" || body.action !== "friendRequest" || ![wire.from, wire.to].includes(this.base.identity.profileId))
@@ -414,6 +436,30 @@ class ProfileProjectionDraft {
414
436
  recipients: message.recipients, body: operation.message.body, threadKind: this.thread(message.threadId)?.kind === "dm" ? "dm" : "group" }) });
415
437
  return;
416
438
  }
439
+ if (operation.type === "groupSnapshot" || operation.type === "groupDenied") {
440
+ const thread = this.thread(operation.threadId);
441
+ if (!thread || thread.kind !== "group")
442
+ throw Error("INVALID_GROUP_CONVERSATION");
443
+ if (operation.type === "groupDenied") {
444
+ this.putThread({ ...thread, status: "unavailable", group: undefined, internal: { ...thread.internal, groupSource: "api" } });
445
+ return;
446
+ }
447
+ const group = operation.group;
448
+ if (group.appId !== this.base.identity.appId || group.teamId !== thread.teamId || group.groupId !== thread.internal?.targetId)
449
+ throw Error("INVALID_GROUP_METADATA");
450
+ if (thread.internal?.groupSource === "api" && thread.group) {
451
+ if (thread.group.versionNumber > group.versionNumber)
452
+ return;
453
+ if (thread.group.versionNumber === group.versionNumber && thread.group.revision !== group.revision)
454
+ throw Error("GROUP_REVISION_CONFLICT");
455
+ if (JSON.stringify(thread.group) === JSON.stringify(group) && thread.status === "ready")
456
+ return;
457
+ }
458
+ this.putThread({ ...thread, group, title: group.title ?? "", avatar: group.avatar ?? undefined,
459
+ status: group.status === "dissolved" || !group.members?.includes(this.base.identity.profileId) ? "unavailable" : "ready",
460
+ internal: { ...thread.internal, groupSource: "api" } });
461
+ return;
462
+ }
417
463
  if (operation.type === "register") {
418
464
  this.ensure(operation.threadId, operation.kind, { teamId: operation.teamId, title: operation.title ?? "", internal: { targetId: operation.targetId } });
419
465
  return;
@@ -492,7 +538,7 @@ class ProfileProjectionDraft {
492
538
  }
493
539
  if (operation.type === "commandResult") {
494
540
  const command = this.outbox.get(operation.commandId) ?? this.base.outbox.get(operation.commandId);
495
- if (!command)
541
+ if (!command || operation.state === command.state && operation.state !== "sending")
496
542
  return;
497
543
  if (operation.state === "confirmed")
498
544
  this.deleteOutbox.add(command.commandId);
@@ -516,9 +562,9 @@ class ProfileProjectionDraft {
516
562
  if (operation.policy === "visible" && message.readPolicy === "explicit" || operation.policy === "played" && message.readPolicy !== "explicit")
517
563
  continue;
518
564
  if (!message.sourceSeq) {
519
- if (!thread.internal?.pendingReadingIntents?.[id]?.some(intent => intent.policy === operation.policy))
520
- this.restoreReadingIntent({ type: "restoreReadingIntent", threadId: message.sourceThreadId, messageId: id,
521
- commandId: `${operation.commandId}:${encodeURIComponent(id)}`, policy: operation.policy, createdAt: operation.createdAt });
565
+ const previous = this.thread(message.sourceThreadId)?.internal?.pendingReadingIntents?.[id]?.find(intent => intent.policy === operation.policy);
566
+ this.restoreReadingIntent({ type: "restoreReadingIntent", threadId: message.sourceThreadId, messageId: id,
567
+ commandId: previous?.commandId ?? `${operation.commandId}:${encodeURIComponent(id)}`, policy: operation.policy, createdAt: previous?.createdAt ?? operation.createdAt });
522
568
  continue;
523
569
  }
524
570
  const group = grouped.get(message.sourceThreadId) ?? { readThroughSeq: 0, explicitReadMessageIds: [] };
@@ -563,9 +609,14 @@ class ProfileProjectionDraft {
563
609
  const parent = canonical ? this.ensure(canonical, wire.threadKind, { teamId: source.teamId }) : source;
564
610
  const body = wire.body;
565
611
  if (body?.kind === "group") {
566
- const controls = { ...parent.internal?.groupControls, [wire.messageId]: wire };
567
- const group = projectInboxGroup(this.base.identity.appId, wire.to, wire.teamId, Object.values(controls));
568
- this.putThread({ ...parent, internal: { ...parent.internal, groupControls: controls },
612
+ const control = canonical ? { ...wire, threadId: parent.threadId, teamId: parent.teamId } : wire;
613
+ const controls = { ...parent.internal?.groupControls, [wire.messageId]: control };
614
+ const group = parent.internal?.groupSource === "api" ? undefined : projectInboxGroup(this.base.identity.appId, wire.to, parent.teamId, Object.values(controls));
615
+ // A delivered removal/dissolution closes access immediately while Hub is
616
+ // rechecked. It never replaces the API-owned metadata with replayed state.
617
+ const revoked = parent.internal?.groupSource === "api" && (body.action === "groupDissolve" ||
618
+ body.action === "groupUpdate" && Array.isArray(body.payload?.members) && !body.payload.members.includes(this.base.identity.profileId));
619
+ this.putThread({ ...parent, ...(revoked ? { status: "unavailable" } : {}), internal: { ...parent.internal, groupControls: controls, groupControlRevision: (parent.internal?.groupControlRevision ?? 0) + 1 },
569
620
  ...(group ? { group, title: group.title, avatar: group.avatar ?? undefined,
570
621
  status: group.status === "dissolved" || !group.members?.includes(this.base.identity.profileId) ? "unavailable" : "ready" } : {}) });
571
622
  return;
@@ -638,6 +689,14 @@ class ProfileProjectionDraft {
638
689
  delete intents[operation.messageId];
639
690
  this.putThread({ ...source, internal: { ...source.internal, pendingReadingIntents: intents } });
640
691
  }
692
+ // Relationship-only historical invitations may never receive a message ordinal.
693
+ // Preserve an actual local observation separately from the deferred server cursor.
694
+ if (message && !message.sourceSeq && message.sourceThreadId === source.threadId &&
695
+ message.presentation?.kind === "invitation" && message.readPolicy === "visible" && operation.policy === "visible" &&
696
+ !message.explicitReadingFacts.some(fact => fact.profileId === this.base.identity.profileId)) {
697
+ this.setMessage({ ...message, explicitReadingFacts: [...message.explicitReadingFacts,
698
+ { profileId: this.base.identity.profileId, kind: "observed" }] });
699
+ }
641
700
  if (!known || message.from === this.base.identity.profileId || message.recalled || message.readPolicy === "discussion" ||
642
701
  (operation.policy === "played") !== (message.readPolicy === "explicit"))
643
702
  return;
@@ -746,7 +805,9 @@ class ProfileProjectionDraft {
746
805
  const data = event.fact;
747
806
  if (!data.threadId || !data.rootMessageId || !Array.isArray(data.messageIds) || !Number.isSafeInteger(data.revision))
748
807
  throw Error("INVALID_INBOX_ORGANIZATION");
749
- const parent = this.ensure(data.threadId), old = parent.internal?.organizationRevisions?.[data.rootMessageId] ?? -1;
808
+ const source = this.ensure(data.threadId);
809
+ const parent = source.internal?.assignments?.[source.threadId] ? this.ensure(source.internal.assignments[source.threadId]) : source;
810
+ const old = parent.internal?.organizationRevisions?.[data.rootMessageId] ?? -1;
750
811
  if (old >= data.revision)
751
812
  return;
752
813
  const messageRoots = { ...parent.internal?.messageRoots };
@@ -754,8 +815,9 @@ class ProfileProjectionDraft {
754
815
  if (messageId !== data.rootMessageId)
755
816
  messageRoots[messageId] = data.rootMessageId;
756
817
  this.putThread({ ...parent, internal: { ...parent.internal, messageRoots, organizationRevisions: { ...parent.internal?.organizationRevisions, [data.rootMessageId]: data.revision } } });
757
- const id = profileDiscussionId(data.threadId, data.rootMessageId);
758
- this.ensure(id, "discussion", { parentThreadId: data.threadId, rootMessageId: data.rootMessageId, teamId: parent.teamId });
818
+ const id = profileDiscussionId(parent.threadId, data.rootMessageId);
819
+ const discussion = this.ensure(id, "discussion", { parentThreadId: parent.threadId, rootMessageId: data.rootMessageId, teamId: parent.teamId });
820
+ this.putThread({ ...discussion, ownerAgentId: typeof data.ownerAgentId === "string" ? data.ownerAgentId : undefined });
759
821
  const root = this.message(data.rootMessageId);
760
822
  if (root)
761
823
  this.setMessage({ ...root, readPolicy: "discussion", discussionThreadId: id });
@@ -771,14 +833,73 @@ class ProfileProjectionDraft {
771
833
  const data = event.fact;
772
834
  if (!data.sourceThreadId || !data.threadId || !data.teamId)
773
835
  throw Error("INVALID_INBOX_ASSIGNMENT");
774
- const destination = this.ensure(data.threadId, "group", { teamId: data.teamId });
836
+ if (data.sourceThreadId === data.threadId)
837
+ return;
775
838
  const source = this.ensure(data.sourceThreadId);
776
- this.putThread({ ...destination, readingSources: [...destination.readingSources.filter(row => row.sourceThreadId !== source.threadId),
777
- ...source.readingSources.filter(row => row.sourceThreadId === source.threadId)] });
778
- for (const window of this.directory(source.threadId).blocks)
779
- for (const ref of window.refs)
780
- this.move(this.message(ref.messageId), destination.threadId);
781
- this.putThread({ ...this.thread(source.threadId), status: "unavailable", internal: { ...source.internal, assignments: { ...source.internal?.assignments, [source.threadId]: destination.threadId } } });
839
+ const destination = this.ensure(data.threadId, source.kind === "dm" ? "dm" : "group", { teamId: data.teamId });
840
+ const targetId = destination.internal?.targetId ?? source.internal?.targetId;
841
+ const groupControls = Object.fromEntries(Object.entries({ ...source.internal?.groupControls, ...destination.internal?.groupControls })
842
+ .map(([id, value]) => [id, { ...value, threadId: destination.threadId, teamId: data.teamId }]));
843
+ const group = destination.internal?.groupSource === "api" ? destination.group : targetId ? projectInboxGroup(this.base.identity.appId, targetId, data.teamId, Object.values(groupControls)) : undefined;
844
+ const organizationRevisions = { ...source.internal?.organizationRevisions };
845
+ for (const [root, revision] of Object.entries(destination.internal?.organizationRevisions ?? {}))
846
+ organizationRevisions[root] = Math.max(organizationRevisions[root] ?? -1, revision);
847
+ this.putThread({ ...destination, teamId: data.teamId, title: group?.title ?? (destination.title || source.title), avatar: group?.avatar ?? destination.avatar ?? source.avatar,
848
+ group: group ?? destination.group ?? (source.group ? { ...source.group, teamId: data.teamId } : undefined),
849
+ ...(group ? { status: group.status === "dissolved" || !group.members?.includes(this.base.identity.profileId) ? "unavailable" : "ready" } : {}),
850
+ internal: { ...source.internal, ...destination.internal, targetId, groupControls, organizationRevisions,
851
+ messageRoots: { ...source.internal?.messageRoots, ...destination.internal?.messageRoots },
852
+ pendingControls: mergeAssignedLists(source.internal?.pendingControls, destination.internal?.pendingControls),
853
+ pendingReceipts: mergeAssignedLists(source.internal?.pendingReceipts, destination.internal?.pendingReceipts),
854
+ pendingReadingIntents: mergeAssignedLists(source.internal?.pendingReadingIntents, destination.internal?.pendingReadingIntents),
855
+ participantCounts: destination.internal?.participantCounts, unknownReadingCount: destination.internal?.unknownReadingCount } });
856
+ this.mergeAssignedReading(destination.threadId, source.readingSources);
857
+ const children = new Set(this.base.children.get(source.threadId));
858
+ for (const row of this.threads.values())
859
+ if (row.parentThreadId === source.threadId)
860
+ children.add(row.threadId);
861
+ for (const childId of children) {
862
+ const child = this.thread(childId);
863
+ if (!child.rootMessageId)
864
+ continue;
865
+ const id = profileDiscussionId(destination.threadId, child.rootMessageId);
866
+ this.ensure(id, "discussion", { parentThreadId: destination.threadId, rootMessageId: child.rootMessageId, teamId: data.teamId,
867
+ title: child.title, ownerAgentId: child.ownerAgentId });
868
+ this.mergeAssignedReading(id, child.readingSources);
869
+ const root = this.message(child.rootMessageId);
870
+ if (root)
871
+ this.setMessage({ ...root, discussionThreadId: id });
872
+ for (const ref of this.directory(childId).blocks.flatMap(window => window.refs))
873
+ this.move(this.message(ref.messageId), id);
874
+ this.putThread({ ...this.thread(childId), status: "unavailable" });
875
+ }
876
+ for (const ref of this.directory(source.threadId).blocks.flatMap(window => window.refs))
877
+ this.move(this.message(ref.messageId), destination.threadId);
878
+ this.putThread({ ...this.thread(source.threadId), status: "unavailable", internal: { ...this.thread(source.threadId)?.internal, assignments: { ...source.internal?.assignments, [source.threadId]: destination.threadId } } });
879
+ }
880
+ mergeAssignedReading(id, incoming) {
881
+ const thread = this.thread(id), sources = new Map(thread.readingSources.map(source => [source.sourceThreadId, source]));
882
+ for (const source of incoming) {
883
+ const previous = sources.get(source.sourceThreadId);
884
+ if (!previous) {
885
+ sources.set(source.sourceThreadId, source);
886
+ continue;
887
+ }
888
+ sources.set(source.sourceThreadId, { ...previous, readThroughSeq: Math.max(previous.readThroughSeq, source.readThroughSeq),
889
+ pendingReadThroughSeq: Math.max(previous.pendingReadThroughSeq ?? 0, source.pendingReadThroughSeq ?? 0),
890
+ explicitReadMessageIds: [...new Set([...previous.explicitReadMessageIds, ...source.explicitReadMessageIds])],
891
+ pendingExplicitReadMessageIds: [...new Set([...(previous.pendingExplicitReadMessageIds ?? []), ...(source.pendingExplicitReadMessageIds ?? [])])],
892
+ preservedReadMessageIds: [...new Set([...previous.preservedReadMessageIds, ...source.preservedReadMessageIds])] });
893
+ }
894
+ const index = this.readingIndex(id), before = index.summary(thread.readingSources), next = { ...thread, readingSources: [...sources.values()] };
895
+ this.putThread(next);
896
+ for (const window of this.directory(id).blocks)
897
+ for (const ref of window.refs) {
898
+ const message = this.message(ref.messageId);
899
+ index.upsert(message, this.base.identity.profileId, sources.get(message.sourceThreadId));
900
+ }
901
+ const after = index.summary(next.readingSources);
902
+ this.updateSummary(id, after.unread - before.unread, after.mentions - before.mentions);
782
903
  }
783
904
  relationship(event, basis = false) {
784
905
  const data = event.fact;
@@ -42,6 +42,8 @@ export type ProfileThread = {
42
42
  revision: number;
43
43
  internal?: {
44
44
  targetId?: string;
45
+ groupSource?: "api";
46
+ groupControlRevision?: number;
45
47
  groupControls?: Record<string, unknown>;
46
48
  organizationRevisions?: Record<string, number>;
47
49
  assignments?: Record<string, string>;
@@ -105,7 +107,7 @@ export type ProfileMessage = {
105
107
  receiptStatus: "unknown" | "ready";
106
108
  explicitReadingFacts: {
107
109
  profileId: string;
108
- kind: "played" | "preserved";
110
+ kind: "played" | "preserved" | "observed";
109
111
  revision?: string;
110
112
  }[];
111
113
  controlVersions: Record<string, string | number>;
@@ -124,13 +126,6 @@ export type ProfileCurrentState = {
124
126
  revokedTeamIds?: string[];
125
127
  teamAccessRevision?: number;
126
128
  };
127
- export type ProfileWriterLease = {
128
- key: "lease";
129
- ownerId: string;
130
- fence: number;
131
- expiresAt: number;
132
- writerLock?: string;
133
- };
134
129
  export type ProfileGenerationState = {
135
130
  key: `build:${string}`;
136
131
  generation: string;
@@ -145,7 +140,7 @@ export type ProfileGenerationState = {
145
140
  windowStart?: number;
146
141
  receiptsReady?: boolean;
147
142
  };
148
- export type ProfileStateRecord = ProfileCurrentState | ProfileWriterLease | ProfileGenerationState;
143
+ export type ProfileStateRecord = ProfileCurrentState | ProfileGenerationState;
149
144
  export type ProfileOutboxCommand = {
150
145
  commandId: string;
151
146
  kind: "message" | "reading" | "played";
@@ -157,8 +152,6 @@ export type ProfileOutboxCommand = {
157
152
  attempts: number;
158
153
  };
159
154
  export type ProfileWriteBatch = {
160
- ownerId: string;
161
- fence: number;
162
155
  expectedRevision: number;
163
156
  generation: string;
164
157
  epoch: string;
@@ -15,6 +15,8 @@ export declare class ProfileWindowDirectory {
15
15
  private baseLookup?;
16
16
  private removed;
17
17
  private offsets;
18
+ private pageWindows;
19
+ private pageOffsets;
18
20
  private size;
19
21
  constructor(generation: string, threadId: string, windows?: readonly ProfileWindow[]);
20
22
  get count(): number;
@@ -28,6 +28,8 @@ export class ProfileWindowDirectory {
28
28
  baseLookup;
29
29
  removed = new Set();
30
30
  offsets = [];
31
+ pageWindows = [];
32
+ pageOffsets = [];
31
33
  size = 0;
32
34
  constructor(generation, threadId, windows = []) {
33
35
  this.generation = generation;
@@ -138,8 +140,14 @@ export class ProfileWindowDirectory {
138
140
  reindex() {
139
141
  this.size = 0;
140
142
  this.offsets = [];
143
+ this.pageWindows = [];
144
+ this.pageOffsets = [];
141
145
  for (const window of this.windows) {
142
146
  this.offsets.push(this.size);
147
+ if (window.refs.length) {
148
+ this.pageWindows.push(window);
149
+ this.pageOffsets.push(this.size);
150
+ }
143
151
  this.size += window.refs.length;
144
152
  }
145
153
  }
@@ -163,10 +171,12 @@ export class ProfileWindowDirectory {
163
171
  const end = direction === "older" ? position : Math.min(this.size, start + limit);
164
172
  if (start >= end)
165
173
  return [];
166
- let block = Math.max(0, lowerBound(this.offsets, offset => offset - (start + 1)) - 1);
174
+ // Empty sealed blocks keep historical routing boundaries, but must not
175
+ // turn a small page into a scan across all previously organized windows.
176
+ let block = Math.max(0, lowerBound(this.pageOffsets, offset => offset - (start + 1)) - 1);
167
177
  const result = [];
168
- while (block < this.windows.length && this.offsets[block] < end) {
169
- const offset = this.offsets[block], refs = this.windows[block].refs;
178
+ while (block < this.pageWindows.length && this.pageOffsets[block] < end) {
179
+ const offset = this.pageOffsets[block], refs = this.pageWindows[block].refs;
170
180
  result.push(...refs.slice(Math.max(0, start - offset), Math.min(refs.length, end - offset)));
171
181
  block++;
172
182
  }
@@ -1,4 +1,4 @@
1
- import { ProfileMemoryStore, type ProfileDelta } from "./profileMemoryStore.js";
1
+ import { ProfileMemoryStore } from "./profileMemoryStore.js";
2
2
  import type { ProfileOperation } from "./profileProjection.js";
3
3
  import type { ProfileOwner } from "./profileOwner.js";
4
4
  export type ProfileMessagePort = {
@@ -7,25 +7,11 @@ export type ProfileMessagePort = {
7
7
  removeEventListener(type: "message", listener: (event: MessageEvent) => void): void;
8
8
  start?(): void;
9
9
  };
10
- /** A bounded, volatile history: no extra persistence or full-team snapshot write.
11
- * A producer restart intentionally falls back to a prepared snapshot. */
12
- export declare class ProfileDeltaJournal {
13
- private maxEntries;
14
- private maxBytes;
15
- private rows;
16
- private bytes;
17
- constructor(maxEntries?: number, maxBytes?: number);
18
- append(delta: ProfileDelta): void;
19
- since(generation: string | undefined, revision: number | undefined, current: {
20
- activeGeneration: string;
21
- commitRevision: number;
22
- }): ProfileDelta[] | undefined;
23
- }
24
- /** Same adapter accepts a Dedicated Worker's message port or BroadcastChannel. */
25
- export declare function serveProfileOwner(owner: ProfileOwner, port: ProfileMessagePort, scope: string, onError?: (error: unknown) => void): () => void;
26
- /** UI/WebView replica. Reads and subscriptions use memory; only commands and
27
- * revision repair cross the message boundary. Normal deltas never read disk. */
28
- export declare class ProfileReplica {
10
+ /** Direct Dedicated Worker port; the rendering document is its only consumer. */
11
+ export declare function serveProfileWorker(owner: ProfileOwner, port: ProfileMessagePort, scope: string, onError?: (error: unknown) => void): () => void;
12
+ /** One rendering document consumes committed projections from its own Worker.
13
+ * Ordered port delivery needs no journal, polling or distributed repair. */
14
+ export declare class ProfileWorkerClient {
29
15
  private port;
30
16
  private scope;
31
17
  private onError;
@@ -33,18 +19,15 @@ export declare class ProfileReplica {
33
19
  readonly memory: ProfileMemoryStore;
34
20
  private clientId;
35
21
  private requests;
36
- private repairing?;
22
+ private restoring;
37
23
  private closed;
38
24
  private buffered;
39
- private timer?;
40
25
  private lastError?;
41
- constructor(port: ProfileMessagePort, scope: string, onError?: (error: unknown) => void, timeoutMs?: number, profileId?: string);
26
+ constructor(port: ProfileMessagePort, scope: string, onError?: (error: unknown) => void, timeoutMs?: number, profileId?: string, memory?: ProfileMemoryStore);
42
27
  private receive;
43
28
  private fail;
44
29
  private request;
45
- start(poll?: boolean): Promise<void>;
46
- check(): Promise<void>;
47
- repair(): Promise<void>;
30
+ start(): Promise<void>;
48
31
  submit(operation: ProfileOperation, immediate?: boolean): Promise<void>;
49
32
  synchronize(): Promise<void>;
50
33
  updateCredentials(token: string): Promise<void>;
@@ -1,44 +1,15 @@
1
1
  import { ProfileMemoryStore, PROFILE_PROTOCOL_VERSION } from "./profileMemoryStore.js";
2
- /** A bounded, volatile history: no extra persistence or full-team snapshot write.
3
- * A producer restart intentionally falls back to a prepared snapshot. */
4
- export class ProfileDeltaJournal {
5
- maxEntries;
6
- maxBytes;
7
- rows = [];
8
- bytes = 0;
9
- constructor(maxEntries = 256, maxBytes = 8 * 1024 * 1024) {
10
- this.maxEntries = maxEntries;
11
- this.maxBytes = maxBytes;
12
- }
13
- append(delta) {
14
- if (this.rows.length && (this.rows.at(-1).delta.generation !== delta.generation || this.rows.at(-1).delta.toRevision !== delta.fromRevision)) {
15
- this.rows = [];
16
- this.bytes = 0;
17
- }
18
- const bytes = new TextEncoder().encode(JSON.stringify(delta)).byteLength;
19
- this.rows.push({ delta, bytes });
20
- this.bytes += bytes;
21
- while (this.rows.length && (this.rows.length > this.maxEntries || this.bytes > this.maxBytes))
22
- this.bytes -= this.rows.shift().bytes;
23
- }
24
- since(generation, revision, current) {
25
- if (generation !== current.activeGeneration || revision === undefined || revision > current.commitRevision)
26
- return;
27
- if (revision === current.commitRevision)
28
- return [];
29
- const start = this.rows.findIndex(row => row.delta.fromRevision === revision && row.delta.generation === generation);
30
- if (start < 0 || this.rows.at(-1)?.delta.toRevision !== current.commitRevision)
31
- return;
32
- return this.rows.slice(start).map(row => row.delta);
33
- }
34
- }
35
- /** Same adapter accepts a Dedicated Worker's message port or BroadcastChannel. */
36
- export function serveProfileOwner(owner, port, scope, onError = () => { }) {
37
- const journal = new ProfileDeltaJournal();
2
+ /** Direct Dedicated Worker port; the rendering document is its only consumer. */
3
+ export function serveProfileWorker(owner, port, scope, onError = () => { }) {
38
4
  const send = (response) => port.postMessage({ ...response, profileProtocol: PROFILE_PROTOCOL_VERSION, scope });
5
+ let generation = owner.current.activeGeneration;
39
6
  const off = owner.subscribeCommitted(delta => {
40
- journal.append(delta);
41
- send({ clientId: "*", delta });
7
+ if (delta.generation !== generation) {
8
+ generation = delta.generation;
9
+ send({ clientId: "*", snapshot: owner.snapshot() });
10
+ }
11
+ else
12
+ send({ clientId: "*", delta });
42
13
  });
43
14
  let active = true;
44
15
  const controller = new AbortController();
@@ -50,12 +21,8 @@ export function serveProfileOwner(owner, port, scope, onError = () => { }) {
50
21
  if (request.profileProtocol !== PROFILE_PROTOCOL_VERSION)
51
22
  throw Error("PROFILE_PROTOCOL_INCOMPATIBLE");
52
23
  let result;
53
- if (request.action === "catchUp") {
54
- const deltas = journal.since(request.generation, request.revision, owner.current);
55
- result = deltas ? { deltas } : { snapshot: owner.snapshot() };
56
- }
57
- else if (request.action === "status")
58
- result = { generation: owner.current.activeGeneration, revision: owner.current.commitRevision };
24
+ if (request.action === "snapshot")
25
+ result = { snapshot: owner.snapshot() };
59
26
  else if (request.action === "synchronize") {
60
27
  await owner.synchronize();
61
28
  result = null;
@@ -102,9 +69,9 @@ export function serveProfileOwner(owner, port, scope, onError = () => { }) {
102
69
  port.start?.();
103
70
  return () => { active = false; controller.abort(); off(); port.removeEventListener("message", listener); };
104
71
  }
105
- /** UI/WebView replica. Reads and subscriptions use memory; only commands and
106
- * revision repair cross the message boundary. Normal deltas never read disk. */
107
- export class ProfileReplica {
72
+ /** One rendering document consumes committed projections from its own Worker.
73
+ * Ordered port delivery needs no journal, polling or distributed repair. */
74
+ export class ProfileWorkerClient {
108
75
  port;
109
76
  scope;
110
77
  onError;
@@ -112,17 +79,16 @@ export class ProfileReplica {
112
79
  memory;
113
80
  clientId = crypto.randomUUID();
114
81
  requests = new Map();
115
- repairing;
82
+ restoring = true;
116
83
  closed = false;
117
84
  buffered = [];
118
- timer;
119
85
  lastError;
120
- constructor(port, scope, onError = () => { }, timeoutMs = 30000, profileId = "") {
86
+ constructor(port, scope, onError = () => { }, timeoutMs = 30000, profileId = "", memory) {
121
87
  this.port = port;
122
88
  this.scope = scope;
123
89
  this.onError = onError;
124
90
  this.timeoutMs = timeoutMs;
125
- this.memory = new ProfileMemoryStore(onError, profileId);
91
+ this.memory = memory ?? new ProfileMemoryStore(onError, profileId);
126
92
  port.addEventListener("message", this.receive);
127
93
  port.start?.();
128
94
  }
@@ -145,36 +111,39 @@ export class ProfileReplica {
145
111
  else
146
112
  request.resolve(response.result);
147
113
  }
114
+ if (response.snapshot) {
115
+ if (this.restoring)
116
+ return; // The requested startup snapshot follows this message.
117
+ try {
118
+ this.memory.restore(response.snapshot);
119
+ }
120
+ catch (error) {
121
+ this.fail(error);
122
+ }
123
+ }
148
124
  if (response.delta) {
149
- if (this.repairing || this.memory.getStatus().phase === "restoring") {
125
+ if (this.restoring)
150
126
  this.buffered.push(response.delta);
151
- if (!this.repairing)
152
- void this.repair().catch(failure => this.fail(failure));
153
- }
154
- else {
127
+ else
155
128
  try {
156
129
  this.memory.apply(response.delta);
157
130
  }
158
131
  catch (error) {
159
- this.buffered.push(response.delta);
160
- void this.repair().catch(failure => this.fail(failure));
132
+ this.fail(error);
161
133
  }
162
- }
163
- if (this.buffered.length > 256)
164
- this.buffered = this.buffered.slice(-256);
165
134
  }
166
135
  };
167
- fail(error) { this.lastError = error instanceof Error ? error : Error("PROFILE_REPLICA_FAILED"); try {
136
+ fail(error) { this.lastError = error instanceof Error ? error : Error("PROFILE_WORKER_PROTOCOL_FAILED"); try {
168
137
  this.onError(this.lastError);
169
138
  }
170
139
  catch { } }
171
140
  request(action, fields = {}) {
172
141
  if (this.closed)
173
- return Promise.reject(Error("PROFILE_REPLICA_CLOSED"));
142
+ return Promise.reject(Error("PROFILE_WORKER_CLIENT_CLOSED"));
174
143
  const requestId = crypto.randomUUID();
175
144
  return new Promise((resolve, reject) => {
176
- const timeout = action === "status" || action === "catchUp" ? this.timeoutMs : Math.max(this.timeoutMs, 30000);
177
- const timer = setTimeout(() => { this.requests.delete(requestId); reject(Error("PROFILE_OWNER_TIMEOUT")); }, timeout);
145
+ const timeout = action === "snapshot" ? this.timeoutMs : Math.max(this.timeoutMs, 30000);
146
+ const timer = action === "waitCommand" ? undefined : setTimeout(() => { this.requests.delete(requestId); reject(Error("PROFILE_WORKER_TIMEOUT")); }, timeout);
178
147
  this.requests.set(requestId, { resolve, reject, timer });
179
148
  try {
180
149
  this.port.postMessage({ ...fields, profileProtocol: PROFILE_PROTOCOL_VERSION, scope: this.scope, clientId: this.clientId, requestId, action });
@@ -186,37 +155,17 @@ export class ProfileReplica {
186
155
  }
187
156
  });
188
157
  }
189
- async start(poll = true) {
190
- await this.repair();
191
- if (poll && !this.timer)
192
- this.timer = setInterval(() => { void this.check().catch(error => this.fail(error)); }, 10000);
193
- }
194
- async check() {
195
- const remote = await this.request("status"), local = this.memory.getStatus();
196
- if (remote.generation !== local.generation || remote.revision !== local.revision)
197
- await this.repair();
198
- }
199
- repair() {
200
- if (this.repairing)
201
- return this.repairing;
202
- const task = Promise.resolve().then(async () => {
203
- const local = this.memory.getStatus();
204
- const result = await this.request("catchUp", { generation: local.generation, revision: local.revision });
205
- if ("snapshot" in result)
206
- this.memory.restore(result.snapshot);
207
- else
208
- for (const delta of result.deltas)
209
- this.memory.apply(delta);
210
- const buffered = this.buffered;
211
- this.buffered = [];
212
- for (const delta of buffered)
158
+ async start() {
159
+ const result = await this.request("snapshot");
160
+ this.memory.restore(result.snapshot);
161
+ for (const delta of this.buffered) {
162
+ const status = this.memory.getStatus();
163
+ if (delta.generation === status.generation && delta.toRevision > (status.revision ?? -1))
213
164
  this.memory.apply(delta);
214
- this.lastError = undefined;
215
- });
216
- this.repairing = task;
217
- void task.finally(() => { if (this.repairing === task)
218
- this.repairing = undefined; }).catch(() => { });
219
- return task;
165
+ }
166
+ this.buffered = [];
167
+ this.restoring = false;
168
+ this.lastError = undefined;
220
169
  }
221
170
  submit(operation, immediate = false) {
222
171
  const payload = "type" in operation && operation.type === "send" ? operation.command.payload : undefined;
@@ -230,12 +179,12 @@ export class ProfileReplica {
230
179
  getStatus() { return { ...this.memory.getStatus(), error: this.lastError }; }
231
180
  close() {
232
181
  this.closed = true;
233
- clearInterval(this.timer);
234
182
  this.port.removeEventListener("message", this.receive);
235
183
  for (const request of this.requests.values()) {
236
184
  clearTimeout(request.timer);
237
- request.reject(Error("PROFILE_REPLICA_CLOSED"));
185
+ request.reject(Error("PROFILE_WORKER_CLIENT_CLOSED"));
238
186
  }
239
187
  this.requests.clear();
188
+ this.buffered = [];
240
189
  }
241
190
  }
@@ -1,5 +1,5 @@
1
1
  import { ProfileDatabase } from "./profileDatabase.js";
2
- import { ProfileReplica, type ProfileMessagePort } from "./profileReplica.js";
2
+ import { ProfileWorkerClient, type ProfileMessagePort } from "./profileWorkerClient.js";
3
3
  import type { ProfileIdentity } from "./profileStoreTypes.js";
4
4
  export type ProfileWorkerConfiguration = {
5
5
  identity: ProfileIdentity;
@@ -16,19 +16,16 @@ export declare const profileChannelName: (identity: ProfileIdentity) => string;
16
16
  * Identity cannot change within a host; a Profile switch creates another host. */
17
17
  export declare function installProfileWorker(port: ProfileMessagePort, options?: {
18
18
  database?: (identity: ProfileIdentity) => ProfileDatabase;
19
- channel?: (name: string) => ProfileMessagePort & {
20
- close(): void;
21
- };
22
19
  fetch?: typeof fetch;
23
20
  locks?: Pick<LockManager, "request"> | null;
24
21
  }): () => Promise<void>;
25
22
  /** The application passes its bundler-created Worker. Worker code and main-page
26
23
  * code ship together, so protocol negotiation precedes any snapshot handoff. */
27
- export declare function openProfileWorker(worker: ProfileMessagePort, configuration: ProfileWorkerConfiguration, timeoutMs?: number): Promise<{
24
+ export declare function openProfileWorker(worker: ProfileMessagePort, configuration: ProfileWorkerConfiguration, timeoutMs?: number, signal?: AbortSignal): Promise<{
28
25
  close: () => Promise<void>;
29
26
  update: (config: ProfileWorkerConfiguration) => Promise<void>;
30
27
  }>;
31
28
  export declare function connectProfileWorker(worker: ProfileMessagePort, configuration: ProfileWorkerConfiguration, timeoutMs?: number): Promise<{
32
- replica: ProfileReplica;
29
+ client: ProfileWorkerClient;
33
30
  close: () => Promise<void>;
34
31
  }>;