@tearleads/client-sdk 0.1.248 → 0.1.250

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 (178) hide show
  1. package/client/organizations/index.js +5 -3
  2. package/client/organizations/index.js.map +1 -1
  3. package/client/organizations/organizationGroupPresentation.d.ts +1 -1
  4. package/client/organizations/organizationGroupPresentation.js.map +1 -1
  5. package/client/organizations/organizationLeaveRequestVerifier.js +21 -0
  6. package/client/organizations/organizationLeaveRequestVerifier.js.map +1 -0
  7. package/client/organizations/{organizationReadModels.d.ts → organizationReadModelCoordinator.d.ts} +18 -16
  8. package/client/organizations/organizationReadModelCoordinator.js +2 -0
  9. package/client/organizations/organizationReadModelCoordinator.js.map +1 -0
  10. package/client/organizations/organizationReadModelPresentation.js +51 -0
  11. package/client/organizations/organizationReadModelPresentation.js.map +1 -0
  12. package/client/organizations/organizationReadModelScopes.js +37 -0
  13. package/client/organizations/organizationReadModelScopes.js.map +1 -0
  14. package/client/organizations/organizationReadModels.js +131 -88
  15. package/client/organizations/organizationReadModels.js.map +1 -1
  16. package/client/organizations/organizationsTypes.d.ts +13 -5
  17. package/client/organizations/organizationsTypes.js.map +1 -1
  18. package/client/organizations/principalMutations.d.ts +18 -2
  19. package/client/organizations/principalMutations.js +29 -15
  20. package/client/organizations/principalMutations.js.map +1 -1
  21. package/client/runtime/principalMutationApi.d.ts +2 -0
  22. package/client/runtime/principalMutationApi.js +2 -0
  23. package/client/runtime/principalMutationApi.js.map +1 -1
  24. package/client/runtime/principalMutationDispatch.js +47 -10
  25. package/client/runtime/principalMutationDispatch.js.map +1 -1
  26. package/client/runtime/workflowRuntime.js +5 -4
  27. package/client/runtime/workflowRuntime.js.map +1 -1
  28. package/data/containers/shared/mutationRequestOptions.d.ts +2 -0
  29. package/data/containers/shared/mutationRequestOptions.js.map +1 -1
  30. package/data/containers/shared/types.d.ts +12 -2
  31. package/data/containers/shared/types.js.map +1 -1
  32. package/data/keyingProjectionVerification/principalPolicy/mergeProjectionPolicyEvidence.js +1 -4
  33. package/data/keyingProjectionVerification/principalPolicy/mergeProjectionPolicyEvidence.js.map +1 -1
  34. package/data/persistence/organizations/organizationReadModelRepository.js +20 -2
  35. package/data/persistence/organizations/organizationReadModelRepository.js.map +1 -1
  36. package/data/persistence/principalPolicy/heldOrganizationDirectories.js +6 -1
  37. package/data/persistence/principalPolicy/heldOrganizationDirectories.js.map +1 -1
  38. package/data/persistence/principalPolicy/principalPolicyBundleIntegrity.js +1 -1
  39. package/data/persistence/principalPolicy/principalPolicyBundleIntegrity.js.map +1 -1
  40. package/data/persistence/principalPolicy/verifiedPrincipalPolicyCurrent.js +1 -5
  41. package/data/persistence/principalPolicy/verifiedPrincipalPolicyCurrent.js.map +1 -1
  42. package/data/principals/organizationGroupDirectoryRequest.js +0 -2
  43. package/data/principals/organizationGroupDirectoryRequest.js.map +1 -1
  44. package/data/principals/organizationPolicyRequest.js +0 -2
  45. package/data/principals/organizationPolicyRequest.js.map +1 -1
  46. package/data/principals/principalPolicyRequest.js +0 -2
  47. package/data/principals/principalPolicyRequest.js.map +1 -1
  48. package/internal/api-client/ApiClient.d.ts +4 -59
  49. package/internal/api-client/client/apiClientContext.d.ts +0 -30
  50. package/internal/api-client/client/containerMutations.d.ts +2 -2
  51. package/internal/api-client/client/containerMutations.js +2 -1
  52. package/internal/api-client/client/containerMutations.js.map +1 -1
  53. package/internal/api-client/client/documents.d.ts +0 -12
  54. package/internal/api-client/client/principalPolicies.d.ts +3 -18
  55. package/internal/api-client/client/writerProjections.d.ts +0 -12
  56. package/internal/api-client/heldDirectoryCitations.d.ts +8 -4
  57. package/internal/api-client/heldDirectoryCitations.js +6 -10
  58. package/internal/api-client/heldDirectoryCitations.js.map +1 -1
  59. package/internal/api-client/organizationPolicyHistory.d.ts +0 -6
  60. package/internal/api-client/principalPolicyRequests.d.ts +2 -18
  61. package/internal/api-client/principalPolicyRequests.js +6 -4
  62. package/internal/api-client/principalPolicyRequests.js.map +1 -1
  63. package/internal/api-client/routes/containers/mutations.js +3 -3
  64. package/internal/api-client/routes/containers/mutations.js.map +1 -1
  65. package/internal/api-client/routes/organizations/createGroup.js +3 -5
  66. package/internal/api-client/routes/organizations/createGroup.js.map +1 -1
  67. package/internal/api-client/routes/principals/policy.js +2 -5
  68. package/internal/api-client/routes/principals/policy.js.map +1 -1
  69. package/internal/api-client/types.d.ts +6 -0
  70. package/internal/api-client/types.js.map +1 -1
  71. package/internal/api-client/verifiedManifestCitations.js +3 -3
  72. package/internal/api-client/verifiedManifestCitations.js.map +1 -1
  73. package/internal/crypto/index.d.ts +1 -1
  74. package/internal/crypto/index.js.map +1 -1
  75. package/internal/crypto/keying/principalPolicyPayload.js +2 -12
  76. package/internal/crypto/keying/principalPolicyPayload.js.map +1 -1
  77. package/internal/crypto/keying/principalPolicyTypes.d.ts +5 -6
  78. package/internal/crypto/keying/principalPolicyTypes.js.map +1 -1
  79. package/internal/crypto/principalState.d.ts +1 -1
  80. package/internal/crypto/principalState.js.map +1 -1
  81. package/internal/crypto/principalStateTypes.d.ts +0 -1
  82. package/internal/crypto/principalStateTypes.js.map +1 -1
  83. package/internal/validators/operation/auth.d.ts +0 -24
  84. package/internal/validators/operation/containerMutations.d.ts +20 -3
  85. package/internal/validators/operation/containerMutations.js +18 -20
  86. package/internal/validators/operation/containerMutations.js.map +1 -1
  87. package/internal/validators/operation/documentMutations.d.ts +0 -48
  88. package/internal/validators/operation/index.d.ts +1 -1
  89. package/internal/validators/operation/index.js +1 -1
  90. package/internal/validators/operation/index.js.map +1 -1
  91. package/internal/validators/operation/organizationPolicyHistory.d.ts +0 -24
  92. package/internal/validators/operation/organizations.d.ts +17 -49
  93. package/internal/validators/operation/organizations.js +4 -2
  94. package/internal/validators/operation/organizations.js.map +1 -1
  95. package/internal/validators/operation/principals.d.ts +17 -57
  96. package/internal/validators/operation/principals.js +5 -2
  97. package/internal/validators/operation/principals.js.map +1 -1
  98. package/internal/validators/operation/writerProjections.d.ts +0 -48
  99. package/internal/validators/request/index.d.ts +1 -1
  100. package/internal/validators/request/index.js +1 -1
  101. package/internal/validators/request/index.js.map +1 -1
  102. package/internal/validators/request/organization.d.ts +15 -32
  103. package/internal/validators/request/organization.js +8 -0
  104. package/internal/validators/request/organization.js.map +1 -1
  105. package/internal/validators/request/organizationProvisioning.d.ts +0 -72
  106. package/internal/validators/request/principal.d.ts +4 -48
  107. package/internal/validators/request/principal.js +4 -2
  108. package/internal/validators/request/principal.js.map +1 -1
  109. package/internal/validators/request/registration.d.ts +0 -24
  110. package/internal/validators/response/areas/organizations.d.ts +3 -2
  111. package/internal/validators/response/areas/organizations.js +3 -2
  112. package/internal/validators/response/areas/organizations.js.map +1 -1
  113. package/internal/validators/response/areas/principals.d.ts +1 -1
  114. package/internal/validators/response/areas/principals.js +1 -1
  115. package/internal/validators/response/areas/principals.js.map +1 -1
  116. package/internal/validators/response/committedReadModel.d.ts +697 -0
  117. package/internal/validators/response/committedReadModel.js +52 -0
  118. package/internal/validators/response/committedReadModel.js.map +1 -0
  119. package/internal/validators/response/container.d.ts +52 -48
  120. package/internal/validators/response/container.js +3 -3
  121. package/internal/validators/response/container.js.map +1 -1
  122. package/internal/validators/response/documentMutation.d.ts +0 -96
  123. package/internal/validators/response/organization.d.ts +0 -191
  124. package/internal/validators/response/organization.js +0 -7
  125. package/internal/validators/response/organization.js.map +1 -1
  126. package/internal/validators/response/organizationPolicyHistory.d.ts +0 -24
  127. package/internal/validators/response/organizationReadModel.d.ts +167 -0
  128. package/internal/validators/response/organizationReadModel.js +5 -0
  129. package/internal/validators/response/organizationReadModel.js.map +1 -1
  130. package/internal/validators/response/policyEvidenceWire.d.ts +5 -3
  131. package/internal/validators/response/policyEvidenceWire.js +6 -4
  132. package/internal/validators/response/policyEvidenceWire.js.map +1 -1
  133. package/internal/validators/response/principal.d.ts +0 -451
  134. package/internal/validators/response/principal.js +0 -8
  135. package/internal/validators/response/principal.js.map +1 -1
  136. package/internal/validators/response/principalPolicyPage.d.ts +0 -48
  137. package/internal/validators/response/principalSnapshot.d.ts +4 -24
  138. package/internal/validators/response/principalSnapshot.js +4 -6
  139. package/internal/validators/response/principalSnapshot.js.map +1 -1
  140. package/internal/validators/response/projectionPolicyEvidence.d.ts +0 -48
  141. package/package.json +1 -1
  142. package/workflows/container-contents/container-state/organizationHost.d.ts +9 -0
  143. package/workflows/container-contents/container-state/organizationHost.js.map +1 -1
  144. package/workflows/container-contents/container-state/remote.js +6 -0
  145. package/workflows/container-contents/container-state/remote.js.map +1 -1
  146. package/workflows/containers/child/share/index.d.ts +4 -2
  147. package/workflows/containers/child/share/index.js +37 -20
  148. package/workflows/containers/child/share/index.js.map +1 -1
  149. package/workflows/organizations/containerContentsHost.js +20 -1
  150. package/workflows/organizations/containerContentsHost.js.map +1 -1
  151. package/workflows/organizations/groupPolicy/commitCurrentGroupPolicyMutation.js +5 -1
  152. package/workflows/organizations/groupPolicy/commitCurrentGroupPolicyMutation.js.map +1 -1
  153. package/workflows/organizations/groupPolicy/currentPolicyMutationAcknowledgement.js +1 -6
  154. package/workflows/organizations/groupPolicy/currentPolicyMutationAcknowledgement.js.map +1 -1
  155. package/workflows/organizations/groupPolicy/groupPolicyMutationAcknowledgement.js +1 -6
  156. package/workflows/organizations/groupPolicy/groupPolicyMutationAcknowledgement.js.map +1 -1
  157. package/workflows/organizations/groups/createCurrentOrganizationGroup.js +8 -1
  158. package/workflows/organizations/groups/createCurrentOrganizationGroup.js.map +1 -1
  159. package/workflows/organizations/index.d.ts +1 -0
  160. package/workflows/organizations/index.js +1 -0
  161. package/workflows/organizations/index.js.map +1 -1
  162. package/workflows/organizations/policyHistory/organizationPolicyHistoryVerification.js +4 -6
  163. package/workflows/organizations/policyHistory/organizationPolicyHistoryVerification.js.map +1 -1
  164. package/workflows/organizations/principalPolicy/principalPolicyReceiptArtifacts.js +1 -7
  165. package/workflows/organizations/principalPolicy/principalPolicyReceiptArtifacts.js.map +1 -1
  166. package/workflows/organizations/readModel/committedReadModel.d.ts +66 -0
  167. package/workflows/organizations/readModel/committedReadModel.js +150 -0
  168. package/workflows/organizations/readModel/committedReadModel.js.map +1 -0
  169. package/workflows/organizations/readModel/readModelProjection.d.ts +15 -2
  170. package/workflows/organizations/readModel/readModelProjection.js +26 -4
  171. package/workflows/organizations/readModel/readModelProjection.js.map +1 -1
  172. package/workflows/principals/policyCache/principalPolicyCacheValidation.js +0 -13
  173. package/workflows/principals/policyCache/principalPolicyCacheValidation.js.map +1 -1
  174. package/workflows/principals/publicHistory/publicProjectionDirectory.js +4 -5
  175. package/workflows/principals/publicHistory/publicProjectionDirectory.js.map +1 -1
  176. package/workflows/registration/provisioningBootstrapBuilders.d.ts +0 -6
  177. package/workflows/registration/registrationPrincipalPolicyPersistence.js +1 -7
  178. package/workflows/registration/registrationPrincipalPolicyPersistence.js.map +1 -1
@@ -1,34 +1,17 @@
1
- import { OrganizationReadModelRepository } from "../../data/persistence/organizations/organizationReadModelRepository.js";
2
- import { recoverOrganizationAccess } from "../../workflows/container-contents/recovery/accessRestoration.js";
3
- import { loadLocalOrganizationContainerGrants, loadLocalOrganizationDirectoryAndGroups, loadLocalOrganizationGroupContainers, loadLocalOrganizationGroupMembers, loadLocalOrganizationUserDetail, reconcileOrganizationDirectoryAndGroups, withVerifiedLeaveRequests, withVerifiedUserLeaveRequest, } from "../../workflows/organizations/index.js";
4
- import { createRuntimeLeaveRequestMembershipCheck } from "../../workflows/organizations/memberships/leaveRequestMembersEvidence.js";
5
- import { organizationAccessScopeKey, wasOrganizationPresentationAccessDeniedByServer, } from "../../workflows/organizations/readModel/organizationPresentationAccessState.js";
1
+ import { organizationReadModelCursorPosition } from "../../internal/validators/organizationReadModelCursor.js";
2
+ import { applyCommittedOrganizationReadModel, awaitCommittedReadModelOffers, claimCommittedReadModelOffer, loadHeldOrganizationReadModelCursor, loadLocalOrganizationContainerGrants, loadLocalOrganizationDirectoryAndGroups, loadLocalOrganizationGroupContainers, loadLocalOrganizationGroupMembers, loadLocalOrganizationUserDetail, reconcileOrganizationDirectoryAndGroups, withVerifiedLeaveRequests, withVerifiedUserLeaveRequest, } from "../../workflows/organizations/index.js";
3
+ import { organizationAccessScopeKey } from "../../workflows/organizations/readModel/organizationPresentationAccessState.js";
6
4
  import { loadBoundedOrganizationGroupHistory } from "./organizationGroupHistory.js";
7
- import { hydrateOrganizationGroupNamesForRuntime } from "./organizationGroupNameHydration.js";
8
5
  import { loadBoundedOrganizationHistory } from "./organizationHistory.js";
6
+ import { leaveRequestVerifier } from "./organizationLeaveRequestVerifier.js";
7
+ import { presentOrganizationReadModelPass } from "./organizationReadModelPresentation.js";
8
+ import { committedScope, presentedAppliedCursor, scopedMap, sessionIsCurrent, } from "./organizationReadModelScopes.js";
9
9
  import { activeOrganizationDataRuntime, isOrganizationDataRuntimeCurrent, } from "./organizationWorkflowRuntime.js";
10
10
  const coordinatorsByRuntime = new WeakMap();
11
- /**
12
- * What one view's leave requests are checked against. The signer comes from
13
- * the device's durable pin first, so a request already stored still verifies
14
- * offline, then a trusted remote resolution for a member not pinned yet. The
15
- * membership comes from this device's verified organization policy.
16
- */
17
- export function leaveRequestVerifier(runtimeService, runtime, organization) {
18
- const { domainScope } = runtime.state;
19
- return {
20
- resolveTrustedUserIdentity: async (userId) => (await runtimeService.identityLinks.resolvePinned(userId)) ??
21
- runtime.resolveTrustedUserIdentity(userId),
22
- membershipIsCurrent: createRuntimeLeaveRequestMembershipCheck({
23
- currentUserId: organization.userId,
24
- organizationId: organization.organizationId,
25
- runtime,
26
- stillCurrent: () => runtimeService.workflowInput().state.domainScope === domainScope,
27
- }),
28
- };
29
- }
30
11
  class OrganizationReadModelCoordinatorImpl {
31
12
  runtimeService;
13
+ // The pass in flight per requester: a feed read, or a committed delta's
14
+ // local apply, which a feed refresh waits out instead of joining.
32
15
  reconciliationsByScope = new WeakMap();
33
16
  // The cursor each requester's last reconcile fully presented: applied,
34
17
  // group names hydrated and leave requests verified. A stored cursor whose
@@ -128,58 +111,38 @@ class OrganizationReadModelCoordinatorImpl {
128
111
  if (!active?.runtime.state.online) {
129
112
  return Promise.resolve(undefined);
130
113
  }
131
- const byKey = this.reconciliationMap(active);
132
- const key = organizationAccessScopeKey(active.organizationId, active.userId);
133
- const existing = byKey.get(key);
134
- if (existing) {
135
- return existing;
114
+ const inFlight = this.reconciliationMap(active).get(organizationAccessScopeKey(active.organizationId, active.userId));
115
+ // A delta's apply reflects its commit, not this request: read after it,
116
+ // for this scope only.
117
+ if (inFlight?.kind === "delta") {
118
+ const stillCurrent = sessionIsCurrent(this.runtimeService, active, this.runtimeService.sessionGeneration);
119
+ return inFlight.promise
120
+ .catch(() => null)
121
+ .then(() => stillCurrent() ? this.reconcile(active.organizationId) : null);
136
122
  }
137
- const presentedCursors = scopedMap(this.presentedCursorsByScope, active);
138
- // Snapshot the server-denied flag before reconciling. A reconcile that
139
- // flips it back to readable means org access was just restored (e.g. the
140
- // user was re-added to a group), and any write lanes idled by
141
- // permission-denied submissions have no self re-arm — regaining access is
142
- // their retry signal, mirroring how billing recovery re-requests all
143
- // lanes. Only a genuine server denial counts: a local session reset also
144
- // marks scopes denied, and re-arming on its first reconcile would race the
145
- // startup sync passes (e.g. pending-create adoption between panes).
146
- const accessWasDenied = wasOrganizationPresentationAccessDeniedByServer({
147
- execSql: active.runtime.infra.execSql,
148
- organizationId: active.organizationId,
149
- requesterUserId: active.userId,
150
- }, "readModel");
151
- const domainScope = active.runtime.state.domainScope;
152
- const stillCurrent = () => isOrganizationDataRuntimeCurrent(this.runtimeService, active, domainScope);
153
- const reconciliation = reconcileOrganizationDirectoryAndGroups({
123
+ return this.presentReconciliation(active, "feed", () => reconcileOrganizationDirectoryAndGroups({
154
124
  apiClient: active.runtime.apiClient,
155
125
  currentUserId: active.userId,
156
126
  execSql: active.runtime.infra.execSql,
157
127
  logError: active.runtime.util.logError,
158
128
  organizationId: active.organizationId,
159
- })
160
- .then(async (directoryAndGroups) => {
161
- if (!stillCurrent())
162
- return null;
163
- // Feed success restores retry eligibility even if name decryption fails.
164
- const accessWasRestored = accessWasDenied &&
165
- directoryAndGroups !== null &&
166
- directoryAndGroups !== undefined;
167
- if (accessWasRestored)
168
- await recoverOrganizationAccess({
169
- domainScope,
170
- execSql: active.runtime.infra.execSql,
171
- organizationId: active.organizationId,
172
- stillCurrent,
173
- userId: active.userId,
174
- });
175
- if (!stillCurrent())
176
- return null;
177
- return withVerifiedLeaveRequests(await hydrateOrganizationGroupNamesForRuntime(this.runtimeService, active, domainScope, directoryAndGroups), leaveRequestVerifier(this.runtimeService, active.runtime, active));
178
- })
129
+ }));
130
+ }
131
+ /** Run one projection pass for the scope, then present what it applied. */
132
+ presentReconciliation(active, kind, pass, passIsCurrent) {
133
+ const byKey = this.reconciliationMap(active);
134
+ const key = organizationAccessScopeKey(active.organizationId, active.userId);
135
+ const existing = byKey.get(key);
136
+ if (existing) {
137
+ return existing.promise;
138
+ }
139
+ const presentedCursors = scopedMap(this.presentedCursorsByScope, active);
140
+ const reconciliation = presentOrganizationReadModelPass(this.runtimeService, active, pass, passIsCurrent)
179
141
  .then((presented) => {
180
142
  if (presented)
181
143
  presentedCursors.set(key, presented.readModelCursor);
182
- else
144
+ // A delta that did not apply leaves what was presented standing.
145
+ else if (kind === "feed")
183
146
  presentedCursors.delete(key);
184
147
  return presented;
185
148
  }, (error) => {
@@ -187,11 +150,11 @@ class OrganizationReadModelCoordinatorImpl {
187
150
  throw error;
188
151
  })
189
152
  .finally(() => {
190
- if (byKey.get(key) === reconciliation) {
153
+ if (byKey.get(key)?.promise === reconciliation) {
191
154
  byKey.delete(key);
192
155
  }
193
156
  });
194
- byKey.set(key, reconciliation);
157
+ byKey.set(key, { kind, promise: reconciliation });
195
158
  return reconciliation;
196
159
  }
197
160
  async reconcileAfterMutation(organizationId) {
@@ -202,34 +165,114 @@ class OrganizationReadModelCoordinatorImpl {
202
165
  await this.settleInFlightReconcile(active);
203
166
  return this.reconcile(active.organizationId);
204
167
  }
205
- async loadAppliedCursor(organizationId) {
168
+ async applyCommittedReadModel(organizationId, delta) {
206
169
  const active = activeOrganizationDataRuntime(this.runtimeService, organizationId);
207
- if (!active) {
170
+ if (!active || !delta)
171
+ return undefined;
172
+ const { sessionGeneration } = this.runtimeService;
173
+ const stillCurrent = sessionIsCurrent(this.runtimeService, active, sessionGeneration);
174
+ // A hint's cursor check may have claimed this delta first; share its apply.
175
+ const outcome = await claimCommittedReadModelOffer(committedScope(active, sessionGeneration), delta, (offer) => this.applyClaimedOffer(active, offer, sessionGeneration));
176
+ if (!stillCurrent())
177
+ return undefined;
178
+ if (!outcome)
179
+ return outcome;
180
+ // An apply that finished earlier stands only while nothing replaced it: a
181
+ // later feed pass or purge leaves the caller to read instead. The mutation
182
+ // already committed, so a failed check is only a missed delta.
183
+ const presented = await presentedAppliedCursor(active, scopedMap(this.presentedCursorsByScope, active)).catch(() => null);
184
+ return stillCurrent() && presented === outcome.readModelCursor
185
+ ? outcome
186
+ : undefined;
187
+ }
188
+ async applyClaimedOffer(active, offer, sessionGeneration) {
189
+ // Distinct offers apply one after another: each waits out every pass in
190
+ // flight, so none joins another's apply and is consumed unapplied.
191
+ const key = organizationAccessScopeKey(active.organizationId, active.userId);
192
+ while (this.reconciliationMap(active).has(key))
193
+ await this.settleInFlightReconcile(active);
194
+ return this.applyCommittedOffer(active, offer, sessionGeneration);
195
+ }
196
+ /**
197
+ * Present an offer while the projection holds its sent cursor and the scope
198
+ * and session are the ones that waited; a failure only forgoes it.
199
+ */
200
+ applyCommittedOffer(active, offer, sessionGeneration) {
201
+ const stillCurrent = sessionIsCurrent(this.runtimeService, active, sessionGeneration);
202
+ return this.presentReconciliation(active, "delta", async () => {
203
+ const held = await loadHeldOrganizationReadModelCursor(committedScope(active, sessionGeneration));
204
+ if (held !== offer.heldCursor || !stillCurrent())
205
+ return undefined;
206
+ return applyCommittedOrganizationReadModel({
207
+ currentUserId: active.userId,
208
+ execSql: active.runtime.infra.execSql,
209
+ logError: active.runtime.util.logError,
210
+ organizationId: active.organizationId,
211
+ requestedCursor: offer.heldCursor,
212
+ response: offer.delta,
213
+ stillCurrent,
214
+ });
215
+ }, stillCurrent).catch((error) => {
216
+ active.runtime.util.logError("Failed to apply a committed organization read-model delta", error);
217
+ return undefined;
218
+ });
219
+ }
220
+ sessionGuard(organizationId) {
221
+ const active = activeOrganizationDataRuntime(this.runtimeService, organizationId);
222
+ return active
223
+ ? sessionIsCurrent(this.runtimeService, active, this.runtimeService.sessionGeneration)
224
+ : () => false;
225
+ }
226
+ async reconcileAfterOwnMutation(organizationId, delta, startedIn = () => true) {
227
+ const active = activeOrganizationDataRuntime(this.runtimeService, organizationId);
228
+ if (!active || !startedIn())
229
+ return undefined;
230
+ const current = sessionIsCurrent(this.runtimeService, active, this.runtimeService.sessionGeneration);
231
+ const stillCurrent = () => current() && startedIn();
232
+ const applied = await this.applyCommittedReadModel(organizationId, delta);
233
+ if (applied)
234
+ return applied;
235
+ // The fallback reads for the session that committed, or not at all.
236
+ await this.settleInFlightReconcile(active);
237
+ return stillCurrent() ? this.reconcile(active.organizationId) : undefined;
238
+ }
239
+ async loadAppliedCursor(hintPosition, organizationId) {
240
+ const active = activeOrganizationDataRuntime(this.runtimeService, organizationId);
241
+ if (!active)
208
242
  return null;
243
+ // The check belongs to the session it started in, before any await.
244
+ const { sessionGeneration } = this.runtimeService;
245
+ const stillCurrent = sessionIsCurrent(this.runtimeService, active, sessionGeneration);
246
+ const presentedCursors = scopedMap(this.presentedCursorsByScope, active);
247
+ // A hint the presentation already covers waits for nothing.
248
+ const presented = await presentedAppliedCursor(active, presentedCursors);
249
+ if (!stillCurrent())
250
+ return null;
251
+ if (hintPosition !== undefined &&
252
+ presented !== null &&
253
+ (organizationReadModelCursorPosition(presented, active.organizationId) ??
254
+ -1n) >= hintPosition)
255
+ return presented;
256
+ // Otherwise this scope's own mutations that could be the hint's commit
257
+ // settle first, and the deltas they carried apply, so a hint naming one of
258
+ // those commits needs no read.
259
+ const scope = committedScope(active, sessionGeneration);
260
+ for (const offer of await awaitCommittedReadModelOffers(scope, hintPosition)) {
261
+ if (!stillCurrent())
262
+ return null;
263
+ await claimCommittedReadModelOffer(scope, offer.delta, (claimed) => this.applyClaimedOffer(active, claimed, sessionGeneration));
209
264
  }
210
265
  await this.settleInFlightReconcile(active);
211
- const applied = await new OrganizationReadModelRepository(active.runtime.infra.execSql).loadAppliedOrganizationReadModelCursor({
212
- organizationId: active.organizationId,
213
- requesterUserId: active.userId,
214
- });
215
- const presented = scopedMap(this.presentedCursorsByScope, active).get(organizationAccessScopeKey(active.organizationId, active.userId));
216
- return applied !== null && applied === presented ? applied : null;
266
+ const applied = await presentedAppliedCursor(active, presentedCursors);
267
+ // A replacement session's cursor never answers this session's hint.
268
+ return stillCurrent() ? applied : null;
217
269
  }
218
270
  async settleInFlightReconcile(active) {
219
271
  await this.reconciliationMap(active)
220
272
  .get(organizationAccessScopeKey(active.organizationId, active.userId))
221
- ?.catch(() => null);
273
+ ?.promise.catch(() => null);
222
274
  }
223
275
  }
224
- function scopedMap(byScope, active) {
225
- const scope = active.runtime.state.domainScope;
226
- let byKey = byScope.get(scope);
227
- if (!byKey) {
228
- byKey = new Map();
229
- byScope.set(scope, byKey);
230
- }
231
- return byKey;
232
- }
233
276
  export function createOrganizationReadModelCoordinator(runtimeService) {
234
277
  const existing = coordinatorsByRuntime.get(runtimeService);
235
278
  if (existing) {
@@ -1 +1 @@
1
- {"version":3,"file":"organizationReadModels.js","sourceRoot":"","sources":["organizationReadModels.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,+BAA+B,EAAE,MAAM,sEAAsE,CAAC;AAEvH,OAAO,EAAE,yBAAyB,EAAE,MAAM,+DAA+D,CAAC;AAC1G,OAAO,EACL,oCAAoC,EACpC,uCAAuC,EACvC,oCAAoC,EACpC,iCAAiC,EACjC,+BAA+B,EAQ/B,uCAAuC,EACvC,yBAAyB,EACzB,4BAA4B,GAC7B,MAAM,+BAA+B,CAAC;AACvC,OAAO,EAAE,wCAAwC,EAAE,MAAM,u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I,CAAC,CAAC;IACxB,CAAC;CACF;AAED,SAAS,SAAS,CAChB,OAA6C,EAC7C,MAAqC;IAErC,MAAM,KAAK,GAAG,MAAM,CAAC,OAAO,CAAC,KAAK,CAAC,WAAW,CAAC;IAC/C,IAAI,KAAK,GAAG,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC;IAC/B,IAAI,CAAC,KAAK,EAAE,CAAC;QACX,KAAK,GAAG,IAAI,GAAG,EAAE,CAAC;QAClB,OAAO,CAAC,GAAG,CAAC,KAAK,EAAE,KAAK,CAAC,CAAC;IAC5B,CAAC;IACD,OAAO,KAAK,CAAC;AACf,CAAC;AAED,MAAM,UAAU,sCAAsC,CACpD,cAA+B;IAE/B,MAAM,QAAQ,GAAG,qBAAqB,CAAC,GAAG,CAAC,cAAc,CAAC,CAAC;IAC3D,IAAI,QAAQ,EAAE,CAAC;QACb,OAAO,QAAQ,CAAC;IAClB,CAAC;IAED,MAAM,WAAW,GAAG,IAAI,oCAAoC,CAAC,cAAc,CAAC,CAAC;IAC7E,qBAAqB,CAAC,GAAG,CAAC,cAAc,EAAE,WAAW,CAAC,CAAC;IACvD,OAAO,WAAW,CAAC;AACrB,CAAC","sourcesContent":["import { OrganizationReadModelRepository } from \"../../data/persistence/organizations/organizationReadModelRepository\";\nimport type { DomainScope } from \"../../data/shared/domainScope\";\nimport { recoverOrganizationAccess } from \"../../workflows/container-contents/recovery/accessRestoration\";\nimport {\n loadLocalOrganizationContainerGrants,\n loadLocalOrganizationDirectoryAndGroups,\n loadLocalOrganizationGroupContainers,\n loadLocalOrganizationGroupMembers,\n loadLocalOrganizationUserDetail,\n type OrganizationContainerGrants,\n type OrganizationDirectoryAndGroups,\n type OrganizationGroupContainers,\n type OrganizationGroupMembers,\n type OrganizationGroupPolicyHistory,\n type OrganizationPolicyHistory,\n type OrganizationUserDetail,\n reconcileOrganizationDirectoryAndGroups,\n withVerifiedLeaveRequests,\n withVerifiedUserLeaveRequest,\n} from \"../../workflows/organizations\";\nimport { createRuntimeLeaveRequestMembershipCheck } from \"../../workflows/organizations/memberships/leaveRequestMembersEvidence\";\nimport type { LeaveRequestVerifier } from \"../../workflows/organizations/memberships/leaveRequestVerification\";\nimport {\n organizationAccessScopeKey,\n wasOrganizationPresentationAccessDeniedByServer,\n} from \"../../workflows/organizations/readModel/organizationPresentationAccessState\";\nimport type {\n InternalRuntime,\n InternalWorkflowRuntimeInput,\n} from \"../runtime/workflowRuntime\";\nimport { loadBoundedOrganizationGroupHistory } from \"./organizationGroupHistory\";\nimport { hydrateOrganizationGroupNamesForRuntime } from \"./organizationGroupNameHydration\";\nimport { loadBoundedOrganizationHistory } from \"./organizationHistory\";\nimport {\n type ActiveOrganizationDataRuntime,\n activeOrganizationDataRuntime,\n isOrganizationDataRuntimeCurrent,\n} from \"./organizationWorkflowRuntime\";\n\nconst coordinatorsByRuntime = new WeakMap<\n InternalRuntime,\n OrganizationReadModelCoordinator\n>();\n\n/**\n * What one view's leave requests are checked against. The signer comes from\n * the device's durable pin first, so a request already stored still verifies\n * offline, then a trusted remote resolution for a member not pinned yet. The\n * membership comes from this device's verified organization policy.\n */\nexport function leaveRequestVerifier(\n runtimeService: InternalRuntime,\n runtime: InternalWorkflowRuntimeInput,\n organization: { readonly organizationId: string; readonly userId: string },\n): LeaveRequestVerifier {\n const { domainScope } = runtime.state;\n return {\n resolveTrustedUserIdentity: async (userId) =>\n (await runtimeService.identityLinks.resolvePinned(userId)) ??\n runtime.resolveTrustedUserIdentity(userId),\n membershipIsCurrent: createRuntimeLeaveRequestMembershipCheck({\n currentUserId: organization.userId,\n organizationId: organization.organizationId,\n runtime,\n stillCurrent: () =>\n runtimeService.workflowInput().state.domainScope === domainScope,\n }),\n };\n}\n\nexport interface OrganizationReadModelCoordinator {\n loadLocal(\n organizationId?: string | undefined,\n ): Promise<OrganizationDirectoryAndGroups | null>;\n loadLocalGroupMembers(\n groupId: string,\n organizationId?: string | undefined,\n ): Promise<OrganizationGroupMembers | null>;\n loadGroupPolicyHistory(\n groupId: string,\n organizationId?: string | undefined,\n beforeVersion?: number | undefined,\n ): Promise<OrganizationGroupPolicyHistory | null>;\n loadOrganizationPolicyHistory(\n organizationId?: string | undefined,\n beforeVersion?: number | undefined,\n ): Promise<OrganizationPolicyHistory | null>;\n loadLocalGrants(\n organizationId?: string | undefined,\n ): Promise<OrganizationContainerGrants | null>;\n loadLocalGroupContainers(\n groupId: string,\n organizationId?: string | undefined,\n ): Promise<OrganizationGroupContainers | null>;\n loadLocalUserDetail(\n userId: string,\n organizationId?: string | undefined,\n ): Promise<OrganizationUserDetail | null>;\n /**\n * Resolves `undefined` when the runtime declines without I/O (offline,\n * database not ready, organization mismatch) or when the feed failed,\n * even with locally retained data — passes that must not count as caught\n * up; `null` when the reconcile completed but produced nothing presentable\n * — including an authoritative denial that purged the projection, which\n * consumers must repaint.\n */\n reconcile(\n organizationId?: string | undefined,\n ): Promise<OrganizationDirectoryAndGroups | null | undefined>;\n reconcileAfterMutation(\n organizationId?: string | undefined,\n ): Promise<OrganizationDirectoryAndGroups | null | undefined>;\n /** The applied cursor once this scope's in-flight reconcile settles. */\n loadAppliedCursor(\n organizationId?: string | undefined,\n ): Promise<string | null>;\n}\n\nclass OrganizationReadModelCoordinatorImpl\n implements OrganizationReadModelCoordinator\n{\n private readonly reconciliationsByScope = new WeakMap<\n DomainScope,\n Map<string, Promise<OrganizationDirectoryAndGroups | null | undefined>>\n >();\n // The cursor each requester's last reconcile fully presented: applied,\n // group names hydrated and leave requests verified. A stored cursor whose\n // presentation work failed does not count as applied, so the next hint\n // reconciles and retries that work.\n private readonly presentedCursorsByScope = new WeakMap<\n DomainScope,\n Map<string, string>\n >();\n constructor(private readonly runtimeService: InternalRuntime) {}\n\n private reconciliationMap(active: ActiveOrganizationDataRuntime) {\n return scopedMap(this.reconciliationsByScope, active);\n }\n\n async loadLocal(organizationId?: string) {\n const active = activeOrganizationDataRuntime(\n this.runtimeService,\n organizationId,\n );\n if (!active) {\n return null;\n }\n return withVerifiedLeaveRequests(\n await loadLocalOrganizationDirectoryAndGroups({\n currentUserId: active.userId,\n execSql: active.runtime.infra.execSql,\n organizationId: active.organizationId,\n }),\n leaveRequestVerifier(this.runtimeService, active.runtime, active),\n );\n }\n\n async loadLocalGrants(organizationId?: string) {\n const active = activeOrganizationDataRuntime(\n this.runtimeService,\n organizationId,\n );\n if (!active) {\n return null;\n }\n return loadLocalOrganizationContainerGrants({\n currentUserId: active.userId,\n execSql: active.runtime.infra.execSql,\n organizationId: active.organizationId,\n });\n }\n\n async loadLocalGroupContainers(groupId: string, organizationId?: string) {\n const active = activeOrganizationDataRuntime(\n this.runtimeService,\n organizationId,\n );\n if (!active || groupId.length === 0) {\n return null;\n }\n return loadLocalOrganizationGroupContainers({\n currentUserId: active.userId,\n execSql: active.runtime.infra.execSql,\n groupId,\n organizationId: active.organizationId,\n });\n }\n\n async loadLocalGroupMembers(groupId: string, organizationId?: string) {\n const active = activeOrganizationDataRuntime(\n this.runtimeService,\n organizationId,\n );\n if (!active || groupId.length === 0) {\n return null;\n }\n return loadLocalOrganizationGroupMembers({\n currentUserId: active.userId,\n execSql: active.runtime.infra.execSql,\n groupId,\n organizationId: active.organizationId,\n });\n }\n\n async loadGroupPolicyHistory(\n groupId: string,\n organizationId?: string,\n beforeVersion?: number,\n ) {\n const active = activeOrganizationDataRuntime(\n this.runtimeService,\n organizationId,\n );\n if (!active || groupId.length === 0) {\n return null;\n }\n const domainScope = active.runtime.state.domainScope;\n return loadBoundedOrganizationGroupHistory({\n active,\n groupId,\n beforeVersion,\n stillCurrent: () =>\n isOrganizationDataRuntimeCurrent(\n this.runtimeService,\n active,\n domainScope,\n ),\n });\n }\n\n async loadOrganizationPolicyHistory(\n organizationId?: string,\n beforeVersion?: number,\n ) {\n const active = activeOrganizationDataRuntime(\n this.runtimeService,\n organizationId,\n );\n if (!active) return null;\n const domainScope = active.runtime.state.domainScope;\n return loadBoundedOrganizationHistory({\n active,\n beforeVersion,\n stillCurrent: () =>\n isOrganizationDataRuntimeCurrent(\n this.runtimeService,\n active,\n domainScope,\n ),\n });\n }\n\n async loadLocalUserDetail(userId: string, organizationId?: string) {\n const active = activeOrganizationDataRuntime(\n this.runtimeService,\n organizationId,\n );\n if (!active || userId.length === 0) {\n return null;\n }\n return withVerifiedUserLeaveRequest(\n await loadLocalOrganizationUserDetail({\n currentUserId: active.userId,\n execSql: active.runtime.infra.execSql,\n organizationId: active.organizationId,\n userId,\n }),\n active.organizationId,\n leaveRequestVerifier(this.runtimeService, active.runtime, active),\n );\n }\n\n reconcile(\n organizationId?: string,\n ): Promise<OrganizationDirectoryAndGroups | null | undefined> {\n const active = activeOrganizationDataRuntime(\n this.runtimeService,\n organizationId,\n );\n if (!active?.runtime.state.online) {\n return Promise.resolve(undefined);\n }\n\n const byKey = this.reconciliationMap(active);\n const key = organizationAccessScopeKey(\n active.organizationId,\n active.userId,\n );\n const existing = byKey.get(key);\n if (existing) {\n return existing;\n }\n const presentedCursors = scopedMap(this.presentedCursorsByScope, active);\n\n // Snapshot the server-denied flag before reconciling. A reconcile that\n // flips it back to readable means org access was just restored (e.g. the\n // user was re-added to a group), and any write lanes idled by\n // permission-denied submissions have no self re-arm — regaining access is\n // their retry signal, mirroring how billing recovery re-requests all\n // lanes. Only a genuine server denial counts: a local session reset also\n // marks scopes denied, and re-arming on its first reconcile would race the\n // startup sync passes (e.g. pending-create adoption between panes).\n const accessWasDenied = wasOrganizationPresentationAccessDeniedByServer(\n {\n execSql: active.runtime.infra.execSql,\n organizationId: active.organizationId,\n requesterUserId: active.userId,\n },\n \"readModel\",\n );\n const domainScope = active.runtime.state.domainScope;\n const stillCurrent = () =>\n isOrganizationDataRuntimeCurrent(\n this.runtimeService,\n active,\n domainScope,\n );\n\n const reconciliation = reconcileOrganizationDirectoryAndGroups({\n apiClient: active.runtime.apiClient,\n currentUserId: active.userId,\n execSql: active.runtime.infra.execSql,\n logError: active.runtime.util.logError,\n organizationId: active.organizationId,\n })\n .then(async (directoryAndGroups) => {\n if (!stillCurrent()) return null;\n // Feed success restores retry eligibility even if name decryption fails.\n const accessWasRestored =\n accessWasDenied &&\n directoryAndGroups !== null &&\n directoryAndGroups !== undefined;\n if (accessWasRestored)\n await recoverOrganizationAccess({\n domainScope,\n execSql: active.runtime.infra.execSql,\n organizationId: active.organizationId,\n stillCurrent,\n userId: active.userId,\n });\n if (!stillCurrent()) return null;\n return withVerifiedLeaveRequests(\n await hydrateOrganizationGroupNamesForRuntime(\n this.runtimeService,\n active,\n domainScope,\n directoryAndGroups,\n ),\n leaveRequestVerifier(this.runtimeService, active.runtime, active),\n );\n })\n .then(\n (presented) => {\n if (presented) presentedCursors.set(key, presented.readModelCursor);\n else presentedCursors.delete(key);\n return presented;\n },\n (error: unknown) => {\n presentedCursors.delete(key);\n throw error;\n },\n )\n .finally(() => {\n if (byKey.get(key) === reconciliation) {\n byKey.delete(key);\n }\n });\n byKey.set(key, reconciliation);\n return reconciliation;\n }\n\n async reconcileAfterMutation(\n organizationId?: string,\n ): Promise<OrganizationDirectoryAndGroups | null | undefined> {\n const active = activeOrganizationDataRuntime(\n this.runtimeService,\n organizationId,\n );\n if (!active?.runtime.state.online) {\n return undefined;\n }\n await this.settleInFlightReconcile(active);\n return this.reconcile(active.organizationId);\n }\n\n async loadAppliedCursor(organizationId?: string): Promise<string | null> {\n const active = activeOrganizationDataRuntime(\n this.runtimeService,\n organizationId,\n );\n if (!active) {\n return null;\n }\n await this.settleInFlightReconcile(active);\n const applied = await new OrganizationReadModelRepository(\n active.runtime.infra.execSql,\n ).loadAppliedOrganizationReadModelCursor({\n organizationId: active.organizationId,\n requesterUserId: active.userId,\n });\n const presented = scopedMap(this.presentedCursorsByScope, active).get(\n organizationAccessScopeKey(active.organizationId, active.userId),\n );\n return applied !== null && applied === presented ? applied : null;\n }\n\n private async settleInFlightReconcile(\n active: ActiveOrganizationDataRuntime,\n ): Promise<void> {\n await this.reconciliationMap(active)\n .get(organizationAccessScopeKey(active.organizationId, active.userId))\n ?.catch(() => null);\n }\n}\n\nfunction scopedMap<T>(\n byScope: WeakMap<DomainScope, Map<string, T>>,\n active: ActiveOrganizationDataRuntime,\n): Map<string, T> {\n const scope = active.runtime.state.domainScope;\n let byKey = byScope.get(scope);\n if (!byKey) {\n byKey = new Map();\n byScope.set(scope, byKey);\n }\n return byKey;\n}\n\nexport function createOrganizationReadModelCoordinator(\n runtimeService: InternalRuntime,\n): OrganizationReadModelCoordinator {\n const existing = coordinatorsByRuntime.get(runtimeService);\n if (existing) {\n return existing;\n }\n\n const coordinator = new OrganizationReadModelCoordinatorImpl(runtimeService);\n coordinatorsByRuntime.set(runtimeService, coordinator);\n return coordinator;\n}\n"]}
1
+ {"version":3,"file":"organizationReadModels.js","sourceRoot":"","sources":["organizationReadModels.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,mCAAmC,EAAE,MAAM,mDAAmD,CAAC;AAGxG,OAAO,EACL,mCAAmC,EACnC,6BAA6B,EAG7B,4BAA4B,EAC5B,mCAAmC,EACnC,oCAAoC,EACpC,uCAAuC,EACvC,oCAAoC,EACpC,iCAAiC,EACjC,+BAA+B,EAE/B,uCAAuC,EACvC,yBAAyB,EACzB,4BAA4B,GAC7B,MAAM,+BAA+B,CAAC;AACvC,OAAO,EAAE,0BAA0B,EAAE,MAAM,6EAA6E,CAAC;AAEzH,OAAO,EAAE,mCAAmC,EAAE,MAAM,4BAA4B,CAAC;AACjF,OAAO,EAAE,8BAA8B,EAAE,MAAM,uBAAuB,CAAC;AACvE,OAAO,EAAE,oBAAoB,EAAE,MAAM,oCAAoC,CAAC;AAK1E,OAAO,EAAE,gCAAgC,EAAE,MAAM,qCAAqC,CAAC;AACvF,OAAO,EACL,cAAc,EAEd,sBAAsB,EACtB,SAAS,EACT,gBAAgB,GACjB,MAAM,+BAA+B,CAAC;AACvC,OAAO,EAEL,6BAA6B,EAC7B,gCAAgC,GACjC,MAAM,+BAA+B,CAAC;AAEvC,MAAM,qBAAqB,GAAG,IAAI,OAAO,EAGtC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AAC,iBAAiB,CAAC,MAAM,EAAE,OAAO,EAAE,iBAAiB,CAAC,CAC3D,CAAC;QACJ,CAAC;QACD,MAAM,IAAI,CAAC,uBAAuB,CAAC,MAAM,CAAC,CAAC;QAC3C,MAAM,OAAO,GAAG,MAAM,sBAAsB,CAAC,MAAM,EAAE,gBAAgB,CAAC,CAAC;QACvE,oEAAoE;QACpE,OAAO,YAAY,EAAE,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,IAAI,CAAC;IACzC,CAAC;IAEO,KAAK,CAAC,uBAAuB,CACnC,MAAqC;QAErC,MAAM,IAAI,CAAC,iBAAiB,CAAC,MAAM,CAAC;aACjC,GAAG,CAAC,0BAA0B,CAAC,MAAM,CAAC,cAAc,EAAE,MAAM,CAAC,MAAM,CAAC,CAAC;YACtE,EAAE,OAAO,CAAC,KAAK,CAAC,GAAG,EAAE,CAAC,IAAI,CAAC,CAAC;IAChC,CAAC;CACF;AAED,MAAM,UAAU,sCAAsC,CACpD,cAA+B;IAE/B,MAAM,QAAQ,GAAG,qBAAqB,CAAC,GAAG,CAAC,cAAc,CAAC,CAAC;IAC3D,IAAI,QAAQ,EAAE,CAAC;QACb,OAAO,QAAQ,CAAC;IAClB,CAAC;IAED,MAAM,WAAW,GAAG,IAAI,oCAAoC,CAAC,cAAc,CAAC,CAAC;IAC7E,qBAAqB,CAAC,GAAG,CAAC,cAAc,EAAE,WAAW,CAAC,CAAC;IACvD,OAAO,WAAW,CAAC;AACrB,CAAC","sourcesContent":["import { organizationReadModelCursorPosition } from \"@tearleads/validators/organizationReadModelCursor\";\nimport type { OrganizationReadModelDeltaResponse } from \"@tearleads/validators/response\";\nimport type { DomainScope } from \"../../data/shared/domainScope\";\nimport {\n applyCommittedOrganizationReadModel,\n awaitCommittedReadModelOffers,\n type CommittedReadModelOffer,\n type CommittedReadModelOutcome,\n claimCommittedReadModelOffer,\n loadHeldOrganizationReadModelCursor,\n loadLocalOrganizationContainerGrants,\n loadLocalOrganizationDirectoryAndGroups,\n loadLocalOrganizationGroupContainers,\n loadLocalOrganizationGroupMembers,\n loadLocalOrganizationUserDetail,\n type OrganizationDirectoryAndGroups,\n reconcileOrganizationDirectoryAndGroups,\n withVerifiedLeaveRequests,\n withVerifiedUserLeaveRequest,\n} from \"../../workflows/organizations\";\nimport { organizationAccessScopeKey } from \"../../workflows/organizations/readModel/organizationPresentationAccessState\";\nimport type { InternalRuntime } from \"../runtime/workflowRuntime\";\nimport { loadBoundedOrganizationGroupHistory } from \"./organizationGroupHistory\";\nimport { loadBoundedOrganizationHistory } from \"./organizationHistory\";\nimport { leaveRequestVerifier } from \"./organizationLeaveRequestVerifier\";\nimport type { OrganizationReadModelCoordinator } from \"./organizationReadModelCoordinator\";\n\nexport type { OrganizationReadModelCoordinator } from \"./organizationReadModelCoordinator\";\n\nimport { presentOrganizationReadModelPass } from \"./organizationReadModelPresentation\";\nimport {\n committedScope,\n type InFlightReadModelPass,\n presentedAppliedCursor,\n scopedMap,\n sessionIsCurrent,\n} from \"./organizationReadModelScopes\";\nimport {\n type ActiveOrganizationDataRuntime,\n activeOrganizationDataRuntime,\n isOrganizationDataRuntimeCurrent,\n} from \"./organizationWorkflowRuntime\";\n\nconst coordinatorsByRuntime = new WeakMap<\n InternalRuntime,\n OrganizationReadModelCoordinator\n>();\n\nclass OrganizationReadModelCoordinatorImpl\n implements OrganizationReadModelCoordinator\n{\n // The pass in flight per requester: a feed read, or a committed delta's\n // local apply, which a feed refresh waits out instead of joining.\n private readonly reconciliationsByScope = new WeakMap<\n DomainScope,\n Map<string, InFlightReadModelPass>\n >();\n // The cursor each requester's last reconcile fully presented: applied,\n // group names hydrated and leave requests verified. A stored cursor whose\n // presentation work failed does not count as applied, so the next hint\n // reconciles and retries that work.\n private readonly presentedCursorsByScope = new WeakMap<\n DomainScope,\n Map<string, string>\n >();\n constructor(private readonly runtimeService: InternalRuntime) {}\n\n private reconciliationMap(active: ActiveOrganizationDataRuntime) {\n return scopedMap(this.reconciliationsByScope, active);\n }\n\n async loadLocal(organizationId?: string) {\n const active = activeOrganizationDataRuntime(\n this.runtimeService,\n organizationId,\n );\n if (!active) {\n return null;\n }\n return withVerifiedLeaveRequests(\n await loadLocalOrganizationDirectoryAndGroups({\n currentUserId: active.userId,\n execSql: active.runtime.infra.execSql,\n organizationId: active.organizationId,\n }),\n leaveRequestVerifier(this.runtimeService, active.runtime, active),\n );\n }\n\n async loadLocalGrants(organizationId?: string) {\n const active = activeOrganizationDataRuntime(\n this.runtimeService,\n organizationId,\n );\n if (!active) {\n return null;\n }\n return loadLocalOrganizationContainerGrants({\n currentUserId: active.userId,\n execSql: active.runtime.infra.execSql,\n organizationId: active.organizationId,\n });\n }\n\n async loadLocalGroupContainers(groupId: string, organizationId?: string) {\n const active = activeOrganizationDataRuntime(\n this.runtimeService,\n organizationId,\n );\n if (!active || groupId.length === 0) {\n return null;\n }\n return loadLocalOrganizationGroupContainers({\n currentUserId: active.userId,\n execSql: active.runtime.infra.execSql,\n groupId,\n organizationId: active.organizationId,\n });\n }\n\n async loadLocalGroupMembers(groupId: string, organizationId?: string) {\n const active = activeOrganizationDataRuntime(\n this.runtimeService,\n organizationId,\n );\n if (!active || groupId.length === 0) {\n return null;\n }\n return loadLocalOrganizationGroupMembers({\n currentUserId: active.userId,\n execSql: active.runtime.infra.execSql,\n groupId,\n organizationId: active.organizationId,\n });\n }\n\n async loadGroupPolicyHistory(\n groupId: string,\n organizationId?: string,\n beforeVersion?: number,\n ) {\n const active = activeOrganizationDataRuntime(\n this.runtimeService,\n organizationId,\n );\n if (!active || groupId.length === 0) {\n return null;\n }\n const domainScope = active.runtime.state.domainScope;\n return loadBoundedOrganizationGroupHistory({\n active,\n groupId,\n beforeVersion,\n stillCurrent: () =>\n isOrganizationDataRuntimeCurrent(\n this.runtimeService,\n active,\n domainScope,\n ),\n });\n }\n\n async loadOrganizationPolicyHistory(\n organizationId?: string,\n beforeVersion?: number,\n ) {\n const active = activeOrganizationDataRuntime(\n this.runtimeService,\n organizationId,\n );\n if (!active) return null;\n const domainScope = active.runtime.state.domainScope;\n return loadBoundedOrganizationHistory({\n active,\n beforeVersion,\n stillCurrent: () =>\n isOrganizationDataRuntimeCurrent(\n this.runtimeService,\n active,\n domainScope,\n ),\n });\n }\n\n async loadLocalUserDetail(userId: string, organizationId?: string) {\n const active = activeOrganizationDataRuntime(\n this.runtimeService,\n organizationId,\n );\n if (!active || userId.length === 0) {\n return null;\n }\n return withVerifiedUserLeaveRequest(\n await loadLocalOrganizationUserDetail({\n currentUserId: active.userId,\n execSql: active.runtime.infra.execSql,\n organizationId: active.organizationId,\n userId,\n }),\n active.organizationId,\n leaveRequestVerifier(this.runtimeService, active.runtime, active),\n );\n }\n\n reconcile(\n organizationId?: string,\n ): Promise<OrganizationDirectoryAndGroups | null | undefined> {\n const active = activeOrganizationDataRuntime(\n this.runtimeService,\n organizationId,\n );\n if (!active?.runtime.state.online) {\n return Promise.resolve(undefined);\n }\n const inFlight = this.reconciliationMap(active).get(\n organizationAccessScopeKey(active.organizationId, active.userId),\n );\n // A delta's apply reflects its commit, not this request: read after it,\n // for this scope only.\n if (inFlight?.kind === \"delta\") {\n const stillCurrent = sessionIsCurrent(\n this.runtimeService,\n active,\n this.runtimeService.sessionGeneration,\n );\n return inFlight.promise\n .catch(() => null)\n .then(() =>\n stillCurrent() ? this.reconcile(active.organizationId) : null,\n );\n }\n return this.presentReconciliation(active, \"feed\", () =>\n reconcileOrganizationDirectoryAndGroups({\n apiClient: active.runtime.apiClient,\n currentUserId: active.userId,\n execSql: active.runtime.infra.execSql,\n logError: active.runtime.util.logError,\n organizationId: active.organizationId,\n }),\n );\n }\n\n /** Run one projection pass for the scope, then present what it applied. */\n private presentReconciliation(\n active: ActiveOrganizationDataRuntime,\n kind: InFlightReadModelPass[\"kind\"],\n pass: () => Promise<OrganizationDirectoryAndGroups | null | undefined>,\n passIsCurrent?: () => boolean,\n ): Promise<OrganizationDirectoryAndGroups | null | undefined> {\n const byKey = this.reconciliationMap(active);\n const key = organizationAccessScopeKey(\n active.organizationId,\n active.userId,\n );\n const existing = byKey.get(key);\n if (existing) {\n return existing.promise;\n }\n const presentedCursors = scopedMap(this.presentedCursorsByScope, active);\n\n const reconciliation = presentOrganizationReadModelPass(\n this.runtimeService,\n active,\n pass,\n passIsCurrent,\n )\n .then(\n (presented) => {\n if (presented) presentedCursors.set(key, presented.readModelCursor);\n // A delta that did not apply leaves what was presented standing.\n else if (kind === \"feed\") presentedCursors.delete(key);\n return presented;\n },\n (error: unknown) => {\n presentedCursors.delete(key);\n throw error;\n },\n )\n .finally(() => {\n if (byKey.get(key)?.promise === reconciliation) {\n byKey.delete(key);\n }\n });\n byKey.set(key, { kind, promise: reconciliation });\n return reconciliation;\n }\n\n async reconcileAfterMutation(\n organizationId?: string,\n ): Promise<OrganizationDirectoryAndGroups | null | undefined> {\n const active = activeOrganizationDataRuntime(\n this.runtimeService,\n organizationId,\n );\n if (!active?.runtime.state.online) {\n return undefined;\n }\n await this.settleInFlightReconcile(active);\n return this.reconcile(active.organizationId);\n }\n\n async applyCommittedReadModel(\n organizationId: string,\n delta: OrganizationReadModelDeltaResponse | undefined,\n ): Promise<CommittedReadModelOutcome> {\n const active = activeOrganizationDataRuntime(\n this.runtimeService,\n organizationId,\n );\n if (!active || !delta) return undefined;\n const { sessionGeneration } = this.runtimeService;\n const stillCurrent = sessionIsCurrent(\n this.runtimeService,\n active,\n sessionGeneration,\n );\n // A hint's cursor check may have claimed this delta first; share its apply.\n const outcome = await claimCommittedReadModelOffer(\n committedScope(active, sessionGeneration),\n delta,\n (offer) => this.applyClaimedOffer(active, offer, sessionGeneration),\n );\n if (!stillCurrent()) return undefined;\n if (!outcome) return outcome;\n // An apply that finished earlier stands only while nothing replaced it: a\n // later feed pass or purge leaves the caller to read instead. The mutation\n // already committed, so a failed check is only a missed delta.\n const presented = await presentedAppliedCursor(\n active,\n scopedMap(this.presentedCursorsByScope, active),\n ).catch(() => null);\n return stillCurrent() && presented === outcome.readModelCursor\n ? outcome\n : undefined;\n }\n\n private async applyClaimedOffer(\n active: ActiveOrganizationDataRuntime,\n offer: CommittedReadModelOffer,\n sessionGeneration: number,\n ): Promise<CommittedReadModelOutcome> {\n // Distinct offers apply one after another: each waits out every pass in\n // flight, so none joins another's apply and is consumed unapplied.\n const key = organizationAccessScopeKey(\n active.organizationId,\n active.userId,\n );\n while (this.reconciliationMap(active).has(key))\n await this.settleInFlightReconcile(active);\n return this.applyCommittedOffer(active, offer, sessionGeneration);\n }\n\n /**\n * Present an offer while the projection holds its sent cursor and the scope\n * and session are the ones that waited; a failure only forgoes it.\n */\n private applyCommittedOffer(\n active: ActiveOrganizationDataRuntime,\n offer: CommittedReadModelOffer,\n sessionGeneration: number,\n ): Promise<OrganizationDirectoryAndGroups | null | undefined> {\n const stillCurrent = sessionIsCurrent(\n this.runtimeService,\n active,\n sessionGeneration,\n );\n return this.presentReconciliation(\n active,\n \"delta\",\n async () => {\n const held = await loadHeldOrganizationReadModelCursor(\n committedScope(active, sessionGeneration),\n );\n if (held !== offer.heldCursor || !stillCurrent()) return undefined;\n return applyCommittedOrganizationReadModel({\n currentUserId: active.userId,\n execSql: active.runtime.infra.execSql,\n logError: active.runtime.util.logError,\n organizationId: active.organizationId,\n requestedCursor: offer.heldCursor,\n response: offer.delta,\n stillCurrent,\n });\n },\n stillCurrent,\n ).catch((error: unknown) => {\n active.runtime.util.logError(\n \"Failed to apply a committed organization read-model delta\",\n error,\n );\n return undefined;\n });\n }\n\n sessionGuard(organizationId?: string): () => boolean {\n const active = activeOrganizationDataRuntime(\n this.runtimeService,\n organizationId,\n );\n return active\n ? sessionIsCurrent(\n this.runtimeService,\n active,\n this.runtimeService.sessionGeneration,\n )\n : () => false;\n }\n\n async reconcileAfterOwnMutation(\n organizationId: string,\n delta: OrganizationReadModelDeltaResponse | undefined,\n startedIn: () => boolean = () => true,\n ): Promise<OrganizationDirectoryAndGroups | null | undefined> {\n const active = activeOrganizationDataRuntime(\n this.runtimeService,\n organizationId,\n );\n if (!active || !startedIn()) return undefined;\n const current = sessionIsCurrent(\n this.runtimeService,\n active,\n this.runtimeService.sessionGeneration,\n );\n const stillCurrent = () => current() && startedIn();\n const applied = await this.applyCommittedReadModel(organizationId, delta);\n if (applied) return applied;\n // The fallback reads for the session that committed, or not at all.\n await this.settleInFlightReconcile(active);\n return stillCurrent() ? this.reconcile(active.organizationId) : undefined;\n }\n\n async loadAppliedCursor(\n hintPosition?: bigint,\n organizationId?: string,\n ): Promise<string | null> {\n const active = activeOrganizationDataRuntime(\n this.runtimeService,\n organizationId,\n );\n if (!active) return null;\n // The check belongs to the session it started in, before any await.\n const { sessionGeneration } = this.runtimeService;\n const stillCurrent = sessionIsCurrent(\n this.runtimeService,\n active,\n sessionGeneration,\n );\n const presentedCursors = scopedMap(this.presentedCursorsByScope, active);\n // A hint the presentation already covers waits for nothing.\n const presented = await presentedAppliedCursor(active, presentedCursors);\n if (!stillCurrent()) return null;\n if (\n hintPosition !== undefined &&\n presented !== null &&\n (organizationReadModelCursorPosition(presented, active.organizationId) ??\n -1n) >= hintPosition\n )\n return presented;\n // Otherwise this scope's own mutations that could be the hint's commit\n // settle first, and the deltas they carried apply, so a hint naming one of\n // those commits needs no read.\n const scope = committedScope(active, sessionGeneration);\n for (const offer of await awaitCommittedReadModelOffers(\n scope,\n hintPosition,\n )) {\n if (!stillCurrent()) return null;\n await claimCommittedReadModelOffer(scope, offer.delta, (claimed) =>\n this.applyClaimedOffer(active, claimed, sessionGeneration),\n );\n }\n await this.settleInFlightReconcile(active);\n const applied = await presentedAppliedCursor(active, presentedCursors);\n // A replacement session's cursor never answers this session's hint.\n return stillCurrent() ? applied : null;\n }\n\n private async settleInFlightReconcile(\n active: ActiveOrganizationDataRuntime,\n ): Promise<void> {\n await this.reconciliationMap(active)\n .get(organizationAccessScopeKey(active.organizationId, active.userId))\n ?.promise.catch(() => null);\n }\n}\n\nexport function createOrganizationReadModelCoordinator(\n runtimeService: InternalRuntime,\n): OrganizationReadModelCoordinator {\n const existing = coordinatorsByRuntime.get(runtimeService);\n if (existing) {\n return existing;\n }\n\n const coordinator = new OrganizationReadModelCoordinatorImpl(runtimeService);\n coordinatorsByRuntime.set(runtimeService, coordinator);\n return coordinator;\n}\n"]}
@@ -7,7 +7,7 @@ import type { InternalWorkflowRuntimeInput } from "../runtime/workflowRuntime.js
7
7
  import type { OrganizationDataUsageCoordinator } from "./organizationDataUsage.js";
8
8
  import type { loadOrganizationGroupPresentationDetails } from "./organizationGroupPresentation.js";
9
9
  import type { OrganizationMemberships } from "./organizationMemberships.js";
10
- import type { OrganizationReadModelCoordinator } from "./organizationReadModels.js";
10
+ import type { OrganizationReadModelCoordinator } from "./organizationReadModelCoordinator.js";
11
11
  import type { AbandonOrganizationPolicyMutationInput, DiscardUnreadableOrganizationPolicyMutationInput, readPendingOrganizationPolicyMutation } from "./principalMutationRecovery.js";
12
12
  import type { AddOrganizationGroupUserInput, deleteGroupForOrganization, OrganizationGrantRef, RemoveOrganizationGroupUserInput } from "./principalMutations.js";
13
13
  /** The verified head the group policy committed at, its server-assigned time, and container receipts. */
@@ -29,7 +29,12 @@ export interface Organizations {
29
29
  retryPendingPolicyMutation: (organizationId: string) => Promise<void>;
30
30
  abandonPendingPolicyMutation: (input: AbandonOrganizationPolicyMutationInput) => Promise<boolean>;
31
31
  addUserToGroup: (input: AddOrganizationGroupUserInput) => Promise<OrganizationGroupMutationResult>;
32
- createGroup: (name: string) => ReturnType<typeof createOrganizationGroup>;
32
+ /**
33
+ * The created group, plus the read model the SDK applied from the create's
34
+ * own response (`undefined` when it carried none or no longer applied, so
35
+ * the caller reads after the mutation as before).
36
+ */
37
+ createGroup: (name: string) => Promise<Awaited<ReturnType<typeof createOrganizationGroup>> & Pick<OrganizationGroupMutationResult, "directoryAndGroups">>;
33
38
  deleteGroup: (groupId: string) => ReturnType<typeof deleteGroupForOrganization>;
34
39
  loadBilling: () => ReturnType<typeof loadOrganizationBilling>;
35
40
  /** Billing for an organization the session is not currently switched to. */
@@ -74,10 +79,13 @@ export interface Organizations {
74
79
  */
75
80
  loadDeviceDataUsage: () => Promise<OrganizationDeviceDataUsage | null>;
76
81
  /**
77
- * The opaque read-model cursor the active requester has applied, once any
78
- * in-flight reconcile of that scope settles; null when it holds none.
82
+ * The opaque read-model cursor the active requester has applied and
83
+ * presented, once this device's mutations in flight and any in-flight
84
+ * reconcile of that scope settle; null when it holds none. Given a realtime
85
+ * hint's `hintPosition`, it returns at once when it already covers the hint
86
+ * and waits only for mutations that could be that commit.
79
87
  */
80
- loadAppliedReadModelCursor: () => Promise<string | null>;
88
+ loadAppliedReadModelCursor: (hintPosition?: bigint | undefined) => Promise<string | null>;
81
89
  loadDirectoryAndGroups: () => ReturnType<OrganizationReadModelCoordinator["reconcile"]>;
82
90
  loadDirectoryAndGroupsAfterMutation: () => ReturnType<OrganizationReadModelCoordinator["reconcileAfterMutation"]>;
83
91
  loadLocalDirectoryAndGroups: () => ReturnType<OrganizationReadModelCoordinator["loadLocal"]>;
@@ -1 +1 @@
1
- {"version":3,"file":"organizationsTypes.js","sourceRoot":"","sources":["organizationsTypes.ts"],"names":[],"mappings":"","sourcesContent":["import type { NativeSubscriptionStore } from \"@tearleads/validators/billing\";\nimport type { PendingBlobDeletionsQuery } from \"@tearleads/validators/operation\";\nimport type {\n PendingBlobDeletionsResponse,\n PrincipalPolicyMutationResponse,\n StripeCheckoutSessionResponse,\n StripePlanChange,\n} from \"@tearleads/validators/response\";\nimport type {\n cancelStripeSubscription,\n checkNativePurchaseEligibility,\n claimNativeOrganizationSubscription,\n createOrganizationGroup,\n LocalOrganizationSummary,\n loadOrganizationBilling,\n loadOrganizationBillingHistory,\n loadOrganizationBillingManagementUrl,\n loadStripeCheckoutOptions,\n OrganizationDeviceDataUsage,\n revokeOrganizationContainerGrant,\n StripeCheckoutIntent,\n startOrganizationTrial,\n updateOrganizationProfile,\n updateOrganizationRosterEntry,\n} from \"../../workflows/organizations\";\nimport type { RootRequestOutcome } from \"../../workflows/root\";\nimport type { InternalWorkflowRuntimeInput } from \"../runtime/workflowRuntime\";\nimport type { OrganizationDataUsageCoordinator } from \"./organizationDataUsage\";\nimport type { loadOrganizationGroupPresentationDetails } from \"./organizationGroupPresentation\";\nimport type { OrganizationMemberships } from \"./organizationMemberships\";\nimport type { OrganizationReadModelCoordinator } from \"./organizationReadModels\";\nimport type {\n AbandonOrganizationPolicyMutationInput,\n DiscardUnreadableOrganizationPolicyMutationInput,\n readPendingOrganizationPolicyMutation,\n} from \"./principalMutationRecovery\";\nimport type {\n AddOrganizationGroupUserInput,\n deleteGroupForOrganization,\n OrganizationGrantRef,\n RemoveOrganizationGroupUserInput,\n} from \"./principalMutations\";\n\n/** The verified head the group policy committed at, its server-assigned time, and container receipts. */\nexport type OrganizationGroupMutationReceipt = PrincipalPolicyMutationResponse;\n\n/**\n * A membership change and the read model the SDK reconciled after it\n * committed. `undefined` means that reconcile was declined without I/O\n * (offline or database not ready); `null` means an authoritative denial\n * purged the projection.\n */\nexport interface OrganizationGroupMutationResult {\n readonly directoryAndGroups: Awaited<\n ReturnType<OrganizationReadModelCoordinator[\"reconcileAfterMutation\"]>\n >;\n readonly receipt: OrganizationGroupMutationReceipt;\n}\n\nexport interface Organizations {\n listPendingBlobDeletions(\n organizationId: string,\n query?: PendingBlobDeletionsQuery,\n ): Promise<RootRequestOutcome<PendingBlobDeletionsResponse>>;\n discardUnreadablePolicyMutation: (\n input: DiscardUnreadableOrganizationPolicyMutationInput,\n ) => Promise<boolean>;\n readPendingPolicyMutation: (\n organizationId: string,\n ) => ReturnType<typeof readPendingOrganizationPolicyMutation>;\n retryPendingPolicyMutation: (organizationId: string) => Promise<void>;\n abandonPendingPolicyMutation: (\n input: AbandonOrganizationPolicyMutationInput,\n ) => Promise<boolean>;\n addUserToGroup: (\n input: AddOrganizationGroupUserInput,\n ) => Promise<OrganizationGroupMutationResult>;\n createGroup: (name: string) => ReturnType<typeof createOrganizationGroup>;\n deleteGroup: (\n groupId: string,\n ) => ReturnType<typeof deleteGroupForOrganization>;\n loadBilling: () => ReturnType<typeof loadOrganizationBilling>;\n /** Billing for an organization the session is not currently switched to. */\n loadBillingForOrganization: (\n organizationId: string,\n ) => ReturnType<typeof loadOrganizationBilling>;\n loadBillingHistory: () => ReturnType<typeof loadOrganizationBillingHistory>;\n loadBillingManagementUrl: () => ReturnType<\n typeof loadOrganizationBillingManagementUrl\n >;\n /** Direct Stripe checkout (issue #1654): options, start at Pay, and cancel. */\n loadStripeCheckoutOptions: (\n organizationId?: string,\n ) => ReturnType<typeof loadStripeCheckoutOptions>;\n /**\n * Starts the subscription at Pay, at the `priceId` of the plan the buyer\n * chose; null without an authenticated organization. A refusal throws an\n * `Error` with the server's billing `code`.\n */\n createStripeCheckout: (\n priceId: string,\n organizationId?: string,\n ) => Promise<StripeCheckoutIntent | null>;\n /**\n * Opens Stripe's hosted checkout for the chosen plan's `priceId`; null\n * without an authenticated organization, and a null `url` when Stripe\n * checkout is unconfigured. A refusal throws like `createStripeCheckout`.\n */\n createStripeCheckoutSession: (\n priceId: string,\n returnUrl: string,\n organizationId?: string,\n ) => Promise<StripeCheckoutSessionResponse | null>;\n cancelStripeSubscription: () => ReturnType<typeof cancelStripeSubscription>;\n /**\n * Changes the active Stripe subscription from the plan at\n * `currentSeatCount` (the one the admin saw) to the plan with `priceId`: a\n * larger plan is charged its prorated difference now and applies once paid\n * (`upgraded`); a smaller one takes effect at renewal (`scheduled`); the\n * current plan cancels a scheduled change (`kept`). Null when Stripe is\n * unconfigured or no organization is signed in. A refusal, including a\n * current plan that changed meanwhile, throws an `Error` with the server's\n * billing `code`.\n */\n changeStripePlan: (\n priceId: string,\n currentSeatCount: number,\n organizationId?: string,\n ) => Promise<StripePlanChange | null>;\n claimNativeSubscription: (\n organizationId: string,\n store: NativeSubscriptionStore,\n ) => ReturnType<typeof claimNativeOrganizationSubscription>;\n checkNativePurchaseEligibility: (\n organizationId: string,\n store: NativeSubscriptionStore,\n ) => ReturnType<typeof checkNativePurchaseEligibility>;\n loadDataUsage: () => ReturnType<\n OrganizationDataUsageCoordinator[\"reconcile\"]\n >;\n loadLocalDataUsage: () => ReturnType<\n OrganizationDataUsageCoordinator[\"loadLocal\"]\n >;\n /**\n * Measures what this device stores for the active organization: its\n * documents by category and the files held for them. Resolves null when no\n * organization runtime is active (signed out, no organization, or the\n * database not ready); rejects if the local read fails.\n */\n loadDeviceDataUsage: () => Promise<OrganizationDeviceDataUsage | null>;\n /**\n * The opaque read-model cursor the active requester has applied, once any\n * in-flight reconcile of that scope settles; null when it holds none.\n */\n loadAppliedReadModelCursor: () => Promise<string | null>;\n loadDirectoryAndGroups: () => ReturnType<\n OrganizationReadModelCoordinator[\"reconcile\"]\n >;\n loadDirectoryAndGroupsAfterMutation: () => ReturnType<\n OrganizationReadModelCoordinator[\"reconcileAfterMutation\"]\n >;\n loadLocalDirectoryAndGroups: () => ReturnType<\n OrganizationReadModelCoordinator[\"loadLocal\"]\n >;\n loadGroupMembers: (\n groupId: string,\n ) => ReturnType<\n InternalWorkflowRuntimeInput[\"apiClient\"][\"listOrganizationGroupMembers\"]\n >;\n loadGroupPresentationDetails(\n groupId: string,\n beforeVersion?: number,\n ): ReturnType<typeof loadOrganizationGroupPresentationDetails>;\n loadGroupContainers: (\n groupId: string,\n ) => ReturnType<OrganizationReadModelCoordinator[\"loadLocalGroupContainers\"]>;\n loadGrants: () => ReturnType<\n OrganizationReadModelCoordinator[\"loadLocalGrants\"]\n >;\n listLocalOrganizations: () => Promise<LocalOrganizationSummary[]>;\n /** The user's own memberships and per-organization sync choices. */\n readonly memberships: OrganizationMemberships;\n loadPolicyHistory: (\n beforeVersion?: number,\n ) => ReturnType<\n OrganizationReadModelCoordinator[\"loadOrganizationPolicyHistory\"]\n >;\n loadUserDetail: (\n userId: string,\n ) => ReturnType<OrganizationReadModelCoordinator[\"loadLocalUserDetail\"]>;\n updateRosterEntry: (\n userId: string,\n profileDocumentId: string | null,\n ) => ReturnType<typeof updateOrganizationRosterEntry>;\n updateProfile: (\n profileDocumentId: string | null,\n ) => ReturnType<typeof updateOrganizationProfile>;\n removeUserFromGroup: (\n input: RemoveOrganizationGroupUserInput,\n ) => Promise<OrganizationGroupMutationResult>;\n revokeGrant: (\n grant: OrganizationGrantRef,\n ) => Promise<\n | Awaited<ReturnType<typeof revokeOrganizationContainerGrant>>\n | OrganizationGroupMutationReceipt\n >;\n startTrial: (\n organizationId?: string,\n ) => ReturnType<typeof startOrganizationTrial>;\n}\n"]}
1
+ {"version":3,"file":"organizationsTypes.js","sourceRoot":"","sources":["organizationsTypes.ts"],"names":[],"mappings":"","sourcesContent":["import type { NativeSubscriptionStore } from \"@tearleads/validators/billing\";\nimport type { PendingBlobDeletionsQuery } from \"@tearleads/validators/operation\";\nimport type {\n PendingBlobDeletionsResponse,\n PrincipalPolicyMutationResponse,\n StripeCheckoutSessionResponse,\n StripePlanChange,\n} from \"@tearleads/validators/response\";\nimport type {\n cancelStripeSubscription,\n checkNativePurchaseEligibility,\n claimNativeOrganizationSubscription,\n createOrganizationGroup,\n LocalOrganizationSummary,\n loadOrganizationBilling,\n loadOrganizationBillingHistory,\n loadOrganizationBillingManagementUrl,\n loadStripeCheckoutOptions,\n OrganizationDeviceDataUsage,\n revokeOrganizationContainerGrant,\n StripeCheckoutIntent,\n startOrganizationTrial,\n updateOrganizationProfile,\n updateOrganizationRosterEntry,\n} from \"../../workflows/organizations\";\nimport type { RootRequestOutcome } from \"../../workflows/root\";\nimport type { InternalWorkflowRuntimeInput } from \"../runtime/workflowRuntime\";\nimport type { OrganizationDataUsageCoordinator } from \"./organizationDataUsage\";\nimport type { loadOrganizationGroupPresentationDetails } from \"./organizationGroupPresentation\";\nimport type { OrganizationMemberships } from \"./organizationMemberships\";\nimport type { OrganizationReadModelCoordinator } from \"./organizationReadModelCoordinator\";\nimport type {\n AbandonOrganizationPolicyMutationInput,\n DiscardUnreadableOrganizationPolicyMutationInput,\n readPendingOrganizationPolicyMutation,\n} from \"./principalMutationRecovery\";\nimport type {\n AddOrganizationGroupUserInput,\n deleteGroupForOrganization,\n OrganizationGrantRef,\n RemoveOrganizationGroupUserInput,\n} from \"./principalMutations\";\n\n/** The verified head the group policy committed at, its server-assigned time, and container receipts. */\nexport type OrganizationGroupMutationReceipt = PrincipalPolicyMutationResponse;\n\n/**\n * A membership change and the read model the SDK reconciled after it\n * committed. `undefined` means that reconcile was declined without I/O\n * (offline or database not ready); `null` means an authoritative denial\n * purged the projection.\n */\nexport interface OrganizationGroupMutationResult {\n readonly directoryAndGroups: Awaited<\n ReturnType<OrganizationReadModelCoordinator[\"reconcileAfterMutation\"]>\n >;\n readonly receipt: OrganizationGroupMutationReceipt;\n}\n\nexport interface Organizations {\n listPendingBlobDeletions(\n organizationId: string,\n query?: PendingBlobDeletionsQuery,\n ): Promise<RootRequestOutcome<PendingBlobDeletionsResponse>>;\n discardUnreadablePolicyMutation: (\n input: DiscardUnreadableOrganizationPolicyMutationInput,\n ) => Promise<boolean>;\n readPendingPolicyMutation: (\n organizationId: string,\n ) => ReturnType<typeof readPendingOrganizationPolicyMutation>;\n retryPendingPolicyMutation: (organizationId: string) => Promise<void>;\n abandonPendingPolicyMutation: (\n input: AbandonOrganizationPolicyMutationInput,\n ) => Promise<boolean>;\n addUserToGroup: (\n input: AddOrganizationGroupUserInput,\n ) => Promise<OrganizationGroupMutationResult>;\n /**\n * The created group, plus the read model the SDK applied from the create's\n * own response (`undefined` when it carried none or no longer applied, so\n * the caller reads after the mutation as before).\n */\n createGroup: (\n name: string,\n ) => Promise<\n Awaited<ReturnType<typeof createOrganizationGroup>> &\n Pick<OrganizationGroupMutationResult, \"directoryAndGroups\">\n >;\n deleteGroup: (\n groupId: string,\n ) => ReturnType<typeof deleteGroupForOrganization>;\n loadBilling: () => ReturnType<typeof loadOrganizationBilling>;\n /** Billing for an organization the session is not currently switched to. */\n loadBillingForOrganization: (\n organizationId: string,\n ) => ReturnType<typeof loadOrganizationBilling>;\n loadBillingHistory: () => ReturnType<typeof loadOrganizationBillingHistory>;\n loadBillingManagementUrl: () => ReturnType<\n typeof loadOrganizationBillingManagementUrl\n >;\n /** Direct Stripe checkout (issue #1654): options, start at Pay, and cancel. */\n loadStripeCheckoutOptions: (\n organizationId?: string,\n ) => ReturnType<typeof loadStripeCheckoutOptions>;\n /**\n * Starts the subscription at Pay, at the `priceId` of the plan the buyer\n * chose; null without an authenticated organization. A refusal throws an\n * `Error` with the server's billing `code`.\n */\n createStripeCheckout: (\n priceId: string,\n organizationId?: string,\n ) => Promise<StripeCheckoutIntent | null>;\n /**\n * Opens Stripe's hosted checkout for the chosen plan's `priceId`; null\n * without an authenticated organization, and a null `url` when Stripe\n * checkout is unconfigured. A refusal throws like `createStripeCheckout`.\n */\n createStripeCheckoutSession: (\n priceId: string,\n returnUrl: string,\n organizationId?: string,\n ) => Promise<StripeCheckoutSessionResponse | null>;\n cancelStripeSubscription: () => ReturnType<typeof cancelStripeSubscription>;\n /**\n * Changes the active Stripe subscription from the plan at\n * `currentSeatCount` (the one the admin saw) to the plan with `priceId`: a\n * larger plan is charged its prorated difference now and applies once paid\n * (`upgraded`); a smaller one takes effect at renewal (`scheduled`); the\n * current plan cancels a scheduled change (`kept`). Null when Stripe is\n * unconfigured or no organization is signed in. A refusal, including a\n * current plan that changed meanwhile, throws an `Error` with the server's\n * billing `code`.\n */\n changeStripePlan: (\n priceId: string,\n currentSeatCount: number,\n organizationId?: string,\n ) => Promise<StripePlanChange | null>;\n claimNativeSubscription: (\n organizationId: string,\n store: NativeSubscriptionStore,\n ) => ReturnType<typeof claimNativeOrganizationSubscription>;\n checkNativePurchaseEligibility: (\n organizationId: string,\n store: NativeSubscriptionStore,\n ) => ReturnType<typeof checkNativePurchaseEligibility>;\n loadDataUsage: () => ReturnType<\n OrganizationDataUsageCoordinator[\"reconcile\"]\n >;\n loadLocalDataUsage: () => ReturnType<\n OrganizationDataUsageCoordinator[\"loadLocal\"]\n >;\n /**\n * Measures what this device stores for the active organization: its\n * documents by category and the files held for them. Resolves null when no\n * organization runtime is active (signed out, no organization, or the\n * database not ready); rejects if the local read fails.\n */\n loadDeviceDataUsage: () => Promise<OrganizationDeviceDataUsage | null>;\n /**\n * The opaque read-model cursor the active requester has applied and\n * presented, once this device's mutations in flight and any in-flight\n * reconcile of that scope settle; null when it holds none. Given a realtime\n * hint's `hintPosition`, it returns at once when it already covers the hint\n * and waits only for mutations that could be that commit.\n */\n loadAppliedReadModelCursor: (\n hintPosition?: bigint | undefined,\n ) => Promise<string | null>;\n loadDirectoryAndGroups: () => ReturnType<\n OrganizationReadModelCoordinator[\"reconcile\"]\n >;\n loadDirectoryAndGroupsAfterMutation: () => ReturnType<\n OrganizationReadModelCoordinator[\"reconcileAfterMutation\"]\n >;\n loadLocalDirectoryAndGroups: () => ReturnType<\n OrganizationReadModelCoordinator[\"loadLocal\"]\n >;\n loadGroupMembers: (\n groupId: string,\n ) => ReturnType<\n InternalWorkflowRuntimeInput[\"apiClient\"][\"listOrganizationGroupMembers\"]\n >;\n loadGroupPresentationDetails(\n groupId: string,\n beforeVersion?: number,\n ): ReturnType<typeof loadOrganizationGroupPresentationDetails>;\n loadGroupContainers: (\n groupId: string,\n ) => ReturnType<OrganizationReadModelCoordinator[\"loadLocalGroupContainers\"]>;\n loadGrants: () => ReturnType<\n OrganizationReadModelCoordinator[\"loadLocalGrants\"]\n >;\n listLocalOrganizations: () => Promise<LocalOrganizationSummary[]>;\n /** The user's own memberships and per-organization sync choices. */\n readonly memberships: OrganizationMemberships;\n loadPolicyHistory: (\n beforeVersion?: number,\n ) => ReturnType<\n OrganizationReadModelCoordinator[\"loadOrganizationPolicyHistory\"]\n >;\n loadUserDetail: (\n userId: string,\n ) => ReturnType<OrganizationReadModelCoordinator[\"loadLocalUserDetail\"]>;\n updateRosterEntry: (\n userId: string,\n profileDocumentId: string | null,\n ) => ReturnType<typeof updateOrganizationRosterEntry>;\n updateProfile: (\n profileDocumentId: string | null,\n ) => ReturnType<typeof updateOrganizationProfile>;\n removeUserFromGroup: (\n input: RemoveOrganizationGroupUserInput,\n ) => Promise<OrganizationGroupMutationResult>;\n revokeGrant: (\n grant: OrganizationGrantRef,\n ) => Promise<\n | Awaited<ReturnType<typeof revokeOrganizationContainerGrant>>\n | OrganizationGroupMutationReceipt\n >;\n startTrial: (\n organizationId?: string,\n ) => ReturnType<typeof startOrganizationTrial>;\n}\n"]}
@@ -1,7 +1,7 @@
1
1
  import type { ContainerGrantSubjectType } from "../../internal/crypto/index.js";
2
2
  import type { ContainerContents } from "../containerContents/index.js";
3
3
  import type { InternalWorkflowRuntimeInput } from "../runtime/workflowRuntime.js";
4
- import type { OrganizationReadModelCoordinator } from "./organizationReadModels.js";
4
+ import type { OrganizationReadModelCoordinator } from "./organizationReadModelCoordinator.js";
5
5
  import type { GroupMemberAdmission } from "./recipientAdmission.js";
6
6
  export interface OrganizationGrantRef {
7
7
  containerId: string;
@@ -68,8 +68,24 @@ export declare function addUserToOrganizationGroup(input: PrincipalMutationRunti
68
68
  }>;
69
69
  export declare function createGroupForOrganization(input: OrganizationMutationScope & {
70
70
  readonly name: string;
71
+ readonly readModelCoordinator: OrganizationReadModelCoordinator;
71
72
  readonly stillCurrent: () => boolean;
72
- }): Promise<import("./index.js").OrganizationGroupSummary>;
73
+ }): Promise<{
74
+ directoryAndGroups: import("./index.js").OrganizationDirectoryAndGroups | undefined;
75
+ createdAt: string;
76
+ currentState: {
77
+ keyEpoch: number;
78
+ keyFingerprint: string;
79
+ memberCount: number;
80
+ stateHash: string;
81
+ version: number;
82
+ } | null;
83
+ groupId: string;
84
+ isBuiltin: boolean;
85
+ organizationId: string;
86
+ name: string;
87
+ nameUnreadable: boolean;
88
+ }>;
73
89
  export declare function deleteGroupForOrganization(input: OrganizationMutationScope & {
74
90
  readonly groupId: string;
75
91
  readonly stillCurrent: () => boolean;