@tearleads/client-sdk 0.1.87 → 0.1.89

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 (153) hide show
  1. package/Tearleads.js +1 -1
  2. package/Tearleads.js.map +1 -1
  3. package/client/containerContents/documentDiscovery.js +16 -2
  4. package/client/containerContents/documentDiscovery.js.map +1 -1
  5. package/client/containerContents/index.d.ts +1 -1
  6. package/client/containerContents/index.js +1 -0
  7. package/client/containerContents/index.js.map +1 -1
  8. package/client/index.d.ts +1 -1
  9. package/client/index.js.map +1 -1
  10. package/client/organizations/index.d.ts +4 -2
  11. package/client/organizations/index.js +15 -8
  12. package/client/organizations/index.js.map +1 -1
  13. package/client/organizations/organizationMemberships.d.ts +41 -0
  14. package/client/organizations/organizationMemberships.js +166 -0
  15. package/client/organizations/organizationMemberships.js.map +1 -0
  16. package/client/organizations/organizationReadModels.d.ts +7 -1
  17. package/client/organizations/organizationReadModels.js +15 -6
  18. package/client/organizations/organizationReadModels.js.map +1 -1
  19. package/client/organizations/organizationsTypes.d.ts +3 -0
  20. package/client/organizations/organizationsTypes.js.map +1 -1
  21. package/data/persistence/container-contents/containerStructuralRepair.js +19 -14
  22. package/data/persistence/container-contents/containerStructuralRepair.js.map +1 -1
  23. package/data/persistence/container-contents/exclusiveDocumentPlacements.js +60 -0
  24. package/data/persistence/container-contents/exclusiveDocumentPlacements.js.map +1 -0
  25. package/data/persistence/organizations/organizationReadModelPersistence.js +14 -0
  26. package/data/persistence/organizations/organizationReadModelPersistence.js.map +1 -1
  27. package/data/persistence/organizations/organizationReadModelProjection.js +12 -0
  28. package/data/persistence/organizations/organizationReadModelProjection.js.map +1 -1
  29. package/data/sqlite/schema/index.d.ts +90 -0
  30. package/data/sqlite/schema/index.js +3 -0
  31. package/data/sqlite/schema/index.js.map +1 -1
  32. package/data/sqlite/schema/organizationReadModelSchema.js +2 -0
  33. package/data/sqlite/schema/organizationReadModelSchema.js.map +1 -1
  34. package/data/sqlite/schema/organizationReadModelTableRegistry.d.ts +19 -0
  35. package/data/sqlite/schema/organizationSyncPauseSchema.js +32 -0
  36. package/data/sqlite/schema/organizationSyncPauseSchema.js.map +1 -0
  37. package/data/sync/organizationSyncPauses.d.ts +59 -0
  38. package/data/sync/organizationSyncPauses.js +149 -0
  39. package/data/sync/organizationSyncPauses.js.map +1 -0
  40. package/index.d.ts +2 -2
  41. package/index.js.map +1 -1
  42. package/internal/api-client/ApiClient.d.ts +21 -2
  43. package/internal/api-client/ApiClient.js +15 -1
  44. package/internal/api-client/ApiClient.js.map +1 -1
  45. package/internal/api-client/routes/organizations/memberships.js +36 -0
  46. package/internal/api-client/routes/organizations/memberships.js.map +1 -0
  47. package/internal/crypto/index.d.ts +1 -0
  48. package/internal/crypto/index.js +1 -0
  49. package/internal/crypto/index.js.map +1 -1
  50. package/internal/crypto/organizationLeaveRequest.d.ts +13 -0
  51. package/internal/crypto/organizationLeaveRequest.js +39 -0
  52. package/internal/crypto/organizationLeaveRequest.js.map +1 -0
  53. package/internal/validators/operation/index.d.ts +1 -0
  54. package/internal/validators/operation/index.js +1 -0
  55. package/internal/validators/operation/index.js.map +1 -1
  56. package/internal/validators/operation/organizationMemberships.d.ts +503 -0
  57. package/internal/validators/operation/organizationMemberships.js +93 -0
  58. package/internal/validators/operation/organizationMemberships.js.map +1 -0
  59. package/internal/validators/operation/organizations.d.ts +48 -0
  60. package/internal/validators/operation/registry.d.ts +5 -0
  61. package/internal/validators/operation/registry.js +5 -0
  62. package/internal/validators/operation/registry.js.map +1 -1
  63. package/internal/validators/realtime/index.js +1 -1
  64. package/internal/validators/realtime/index.js.map +1 -1
  65. package/internal/validators/realtime/wsInvalidationHints.js +8 -0
  66. package/internal/validators/realtime/wsInvalidationHints.js.map +1 -1
  67. package/internal/validators/request/index.d.ts +1 -1
  68. package/internal/validators/request/index.js +1 -1
  69. package/internal/validators/request/index.js.map +1 -1
  70. package/internal/validators/request/organization.d.ts +6 -0
  71. package/internal/validators/request/organization.js +7 -0
  72. package/internal/validators/request/organization.js.map +1 -1
  73. package/internal/validators/response/index.d.ts +1 -0
  74. package/internal/validators/response/index.js +1 -0
  75. package/internal/validators/response/index.js.map +1 -1
  76. package/internal/validators/response/organization.d.ts +82 -0
  77. package/internal/validators/response/organization.js +6 -0
  78. package/internal/validators/response/organization.js.map +1 -1
  79. package/internal/validators/response/organizationMembership.d.ts +66 -0
  80. package/internal/validators/response/organizationMembership.js +29 -0
  81. package/internal/validators/response/organizationMembership.js.map +1 -0
  82. package/internal/validators/response/organizationReadModel.d.ts +60 -0
  83. package/internal/validators/util/index.d.ts +1 -0
  84. package/internal/validators/util/index.js +1 -0
  85. package/internal/validators/util/index.js.map +1 -1
  86. package/internal/validators/util/organizationLeaveRequest.d.ts +15 -0
  87. package/internal/validators/util/organizationLeaveRequest.js +22 -0
  88. package/internal/validators/util/organizationLeaveRequest.js.map +1 -0
  89. package/package.json +1 -1
  90. package/stores/container-contents/containerContentsStore.d.ts +1 -1
  91. package/stores/container-contents/containerContentsStore.js +2 -0
  92. package/stores/container-contents/containerContentsStore.js.map +1 -1
  93. package/stores/container-contents/operations/forgetOrganizationContentOperation.js +76 -0
  94. package/stores/container-contents/operations/forgetOrganizationContentOperation.js.map +1 -0
  95. package/stores/container-contents/types.d.ts +6 -0
  96. package/stores/container-contents/types.js.map +1 -1
  97. package/stores/documents/documentStore/attachments/attachmentRemoval.js +3 -4
  98. package/stores/documents/documentStore/attachments/attachmentRemoval.js.map +1 -1
  99. package/stores/documents/documentStore/attachments/index.js +5 -7
  100. package/stores/documents/documentStore/attachments/index.js.map +1 -1
  101. package/stores/documents/documentStore/index.js +16 -12
  102. package/stores/documents/documentStore/index.js.map +1 -1
  103. package/stores/documents/documentStore/initialization/index.js +9 -0
  104. package/stores/documents/documentStore/initialization/index.js.map +1 -1
  105. package/stores/documents/documentStore/mutations.js +5 -7
  106. package/stores/documents/documentStore/mutations.js.map +1 -1
  107. package/stores/documents/documentStore/rotation/index.js +2 -1
  108. package/stores/documents/documentStore/rotation/index.js.map +1 -1
  109. package/stores/documents/documentStore/rows/index.js +3 -4
  110. package/stores/documents/documentStore/rows/index.js.map +1 -1
  111. package/stores/documents/documentStore/state.js +18 -0
  112. package/stores/documents/documentStore/state.js.map +1 -1
  113. package/stores/documents/documentStore/sync/index.js +5 -2
  114. package/stores/documents/documentStore/sync/index.js.map +1 -1
  115. package/stores/documents/registry.d.ts +32 -0
  116. package/stores/documents/registry.js +79 -4
  117. package/stores/documents/registry.js.map +1 -1
  118. package/stores/documents/removedDocumentStore.js +38 -0
  119. package/stores/documents/removedDocumentStore.js.map +1 -0
  120. package/stores/documents/types.d.ts +2 -0
  121. package/stores/documents/types.js.map +1 -1
  122. package/sync/reconciliation/service.js +2 -2
  123. package/sync/reconciliation/service.js.map +1 -1
  124. package/sync/reconciliation/serviceTypes.d.ts +8 -1
  125. package/sync/reconciliation/serviceTypes.js.map +1 -1
  126. package/workflows/container-contents/pendingWrites/index.d.ts +5 -0
  127. package/workflows/container-contents/pendingWrites/index.js +7 -0
  128. package/workflows/container-contents/pendingWrites/index.js.map +1 -1
  129. package/workflows/container-contents/remoteHydration/index.js +7 -1
  130. package/workflows/container-contents/remoteHydration/index.js.map +1 -1
  131. package/workflows/container-contents/remoteHydration/remoteContainers/organizationSyncPauseFilter.js +13 -0
  132. package/workflows/container-contents/remoteHydration/remoteContainers/organizationSyncPauseFilter.js.map +1 -0
  133. package/workflows/container-contents/remoteHydration/remoteContainers/remoteContainerPageHydration.js +13 -2
  134. package/workflows/container-contents/remoteHydration/remoteContainers/remoteContainerPageHydration.js.map +1 -1
  135. package/workflows/container-contents/syncPause/discoveryGuard.js +31 -0
  136. package/workflows/container-contents/syncPause/discoveryGuard.js.map +1 -0
  137. package/workflows/container-contents/syncPause/documentRemoval.js +154 -0
  138. package/workflows/container-contents/syncPause/documentRemoval.js.map +1 -0
  139. package/workflows/organizations/index.d.ts +3 -0
  140. package/workflows/organizations/index.js +3 -0
  141. package/workflows/organizations/index.js.map +1 -1
  142. package/workflows/organizations/memberships/leaveRequest.d.ts +31 -0
  143. package/workflows/organizations/memberships/leaveRequest.js +20 -0
  144. package/workflows/organizations/memberships/leaveRequest.js.map +1 -0
  145. package/workflows/organizations/memberships/leaveRequestVerification.d.ts +15 -0
  146. package/workflows/organizations/memberships/leaveRequestVerification.js +46 -0
  147. package/workflows/organizations/memberships/leaveRequestVerification.js.map +1 -0
  148. package/workflows/organizations/memberships/organizationMemberships.d.ts +84 -0
  149. package/workflows/organizations/memberships/organizationMemberships.js +95 -0
  150. package/workflows/organizations/memberships/organizationMemberships.js.map +1 -0
  151. package/workflows/sync/index.d.ts +1 -0
  152. package/workflows/sync/index.js +1 -0
  153. package/workflows/sync/index.js.map +1 -1
@@ -1 +1 @@
1
- {"version":3,"file":"containerStructuralRepair.js","sourceRoot":"","sources":["containerStructuralRepair.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,EAAE,GAAG,EAAE,EAAE,EAAE,OAAO,EAAE,MAAM,aAAa,CAAC;AACpD,OAAO,EACL,UAAU,EACV,2BAA2B,EAC3B,kBAAkB,EAClB,sBAAsB,EACtB,iBAAiB,EACjB,kBAAkB,EAClB,YAAY,GACb,MAAM,qBAAqB,CAAC;AAE7B,OAAO,EAAE,kDAAkD,EAAE,MAAM,yDAAyD,CAAC;AAC7H,OAAO,EAAE,2CAA2C,EAAE,MAAM,2CAA2C,CAAC;AACxG,OAAO,EAAE,kBAAkB,EAAE,MAAM,oBAAoB,CAAC;AAKxD,OAAO,EAAE,yBAAyB,EAAE,MAAM,8BAA8B,CAAC;AACzE,OAAO,EAAE,sCAAsC,EAAE,MAAM,qCAAqC,CAAC;AAC7F,OAAO,EAAE,gDAAgD,EAAE,MAAM,4BAA4B,CAAC;AAE9F,8EAA8E;AAC9E,6EAA6E;AAC7E,8EAA8E;AAC9E,8CAA8C;AAC9C,KAAK,UAAU,gCAAgC,CAC7C,EAAgC,EAChC,YAAmC;IAEnC,MAAM,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,CAAC,EAAE,EAAE,WAAW,CAAC,CAAC,CAAC,GAAG,EAAE,CAAC;IACxE,MAAM,gDAAgD,CAAC,EAAE,EAAE,CAAC,WAAW,CAAC,CAAC,CAAC;IAC1E,MAAM,sCAAsC,CAAC,EAAE,EAAE,CAAC,WAAW,CAAC,CAAC,CAAC;AAClE,CAAC","sourcesContent":["import { and, asc, eq, inArray } from \"drizzle-orm\";\nimport {\n containers,\n documentContainerProjection,\n documentProjection,\n inContainerIntentLanes,\n inLocalIntentLane,\n LOCAL_INTENT_LANES,\n localIntents,\n} from \"../../sqlite/schema\";\nimport type { ClientSQLiteTransactionScope } from \"../../sqlite/sqlitePersistenceRuntime\";\nimport { deleteContainerDocumentTombstoneHoldsForContainers } from \"../documents/containerDocumentTombstoneHoldsPersistence\";\nimport { setDocumentProjectionContainerInTransaction } from \"../documents/documentProjectionContainers\";\nimport { getLatestTimestamp } from \"../latestTimestamp\";\nimport type {\n ContainerRemoval,\n LocalRootDescendantReparentInput,\n} from \"./containerContentsPersistenceTypes\";\nimport { saveContainerCreateIntent } from \"./containerIntentPersistence\";\nimport { deleteContainerWatermarksInTransaction } from \"./containerSyncWatermarkPersistence\";\nimport { deleteContainerMetadataDocumentRowsInTransaction } from \"./dormantContainerMetadata\";\n\n// The containers being removed still exist when repair runs (deletion follows\n// it). Capture their org attribution so a detached document's pending writes\n// keep a resolvable organization id after the join source is gone — e.g. when\n// access to a shared org is revoked mid-sync.\nasync function loadOrganizationIdsForContainers(\n tx: ClientSQLiteTransactionScope,\n containerIds: ReadonlyArray<string>,\n): Promise<Map<string, string>> {\n const rows = await tx\n .select({\n id: containers.id,\n organizationId: containers.organizationId,\n })\n .from(containers)\n .where(inArray(containers.id, containerIds));\n const organizationIdByContainerId = new Map<string, string>();\n for (const container of rows) {\n if (container.id && container.organizationId) {\n organizationIdByContainerId.set(container.id, container.organizationId);\n }\n }\n return organizationIdByContainerId;\n}\n\n// A document unlinked from a removed container may keep other live links; its\n// projection then re-homes to the first remaining link (deterministic order)\n// instead of dropping to null.\nasync function loadFirstRemainingContainerIdByDocumentId(\n tx: ClientSQLiteTransactionScope,\n documentIds: ReadonlyArray<string>,\n): Promise<Map<string, string>> {\n const firstRemainingContainerIdByDocumentId = new Map<string, string>();\n if (documentIds.length === 0) {\n return firstRemainingContainerIdByDocumentId;\n }\n const remainingLinks = await tx\n .select({\n containerId: documentContainerProjection.containerId,\n documentId: documentContainerProjection.documentId,\n })\n .from(documentContainerProjection)\n .where(inArray(documentContainerProjection.documentId, documentIds))\n .orderBy(\n asc(documentContainerProjection.documentId),\n asc(documentContainerProjection.containerId),\n );\n for (const link of remainingLinks) {\n if (!firstRemainingContainerIdByDocumentId.has(link.documentId)) {\n firstRemainingContainerIdByDocumentId.set(\n link.documentId,\n link.containerId,\n );\n }\n }\n return firstRemainingContainerIdByDocumentId;\n}\n\nexport async function repairDocumentsForRemovedContainersInTransaction(input: {\n removals: ReadonlyArray<ContainerRemoval>;\n tx: ClientSQLiteTransactionScope;\n}): Promise<void> {\n const { tx } = input;\n const updatedAtByContainerId = new Map(\n input.removals.map((removal) => [removal.containerId, removal.updatedAt]),\n );\n const containerIds = Array.from(updatedAtByContainerId.keys());\n if (containerIds.length === 0) {\n return;\n }\n\n {\n const selectedRows = await tx\n .select({\n containerId: documentProjection.containerId,\n documentId: documentProjection.documentId,\n localId: documentProjection.localId,\n updatedAt: documentProjection.updatedAt,\n })\n .from(documentProjection)\n .where(inArray(documentProjection.containerId, containerIds));\n\n const organizationIdByContainerId = await loadOrganizationIdsForContainers(\n tx,\n containerIds,\n );\n\n await tx\n .delete(documentContainerProjection)\n .where(inArray(documentContainerProjection.containerId, containerIds))\n .run();\n await deleteContainerDocumentTombstoneHoldsForContainers(tx, containerIds);\n\n const documentIds = Array.from(\n new Set(\n selectedRows.flatMap((row) => (row.documentId ? [row.documentId] : [])),\n ),\n );\n const firstRemainingContainerIdByDocumentId =\n await loadFirstRemainingContainerIdByDocumentId(tx, documentIds);\n\n for (const row of selectedRows) {\n if (!row.localId) {\n continue;\n }\n\n const removedOrganizationId = row.containerId\n ? organizationIdByContainerId.get(row.containerId)\n : undefined;\n await setDocumentProjectionContainerInTransaction(tx, row.localId, {\n containerId: row.documentId\n ? (firstRemainingContainerIdByDocumentId.get(row.documentId) ?? null)\n : null,\n organizationId: removedOrganizationId,\n updatedAt: getLatestTimestamp(\n row.updatedAt,\n row.containerId\n ? (updatedAtByContainerId.get(row.containerId) ?? row.updatedAt)\n : row.updatedAt,\n ),\n });\n }\n }\n}\n\nexport async function updateReparentedDescendantContainers(input: {\n descendantReparents: ReadonlyArray<LocalRootDescendantReparentInput>;\n remoteOrganizationId: string;\n tx: ClientSQLiteTransactionScope;\n updatedAt: string;\n}): Promise<void> {\n const { descendantReparents, remoteOrganizationId, tx, updatedAt } = input;\n const descendantIds = Array.from(\n new Set(descendantReparents.map((reparent) => reparent.containerId)),\n );\n if (descendantIds.length === 0) {\n return;\n }\n\n await tx\n .update(containers)\n .set({\n organizationId: remoteOrganizationId,\n localUpdatedAt: updatedAt,\n })\n .where(inArray(containers.id, descendantIds))\n .run();\n\n for (const reparent of descendantReparents) {\n await tx\n .update(containers)\n .set({ parentId: reparent.parentContainerId })\n .where(eq(containers.id, reparent.containerId))\n .run();\n\n if (reparent.updateCreateIntent && reparent.parentContainerId) {\n await saveContainerCreateIntent({\n containerId: reparent.containerId,\n createIntent: { parentContainerId: reparent.parentContainerId },\n tx,\n updatedAt,\n });\n }\n\n if (reparent.parentContainerId) {\n await tx\n .update(localIntents)\n .set({\n id: crypto.randomUUID(),\n targetContainerId: reparent.parentContainerId,\n syncStatus: \"pending\",\n updatedAt,\n })\n .where(\n and(\n inLocalIntentLane(LOCAL_INTENT_LANES.containerMove),\n eq(localIntents.subjectId, reparent.containerId),\n ),\n )\n .run();\n }\n }\n}\n\nexport async function reparentLocalContainerChildren(input: {\n fromContainerId: string;\n remoteOrganizationId: string;\n toContainerId: string;\n tx: ClientSQLiteTransactionScope;\n updatedAt: string;\n}): Promise<void> {\n const {\n fromContainerId,\n remoteOrganizationId,\n toContainerId,\n tx,\n updatedAt,\n } = input;\n await tx\n .update(containers)\n .set({\n organizationId: remoteOrganizationId,\n parentId: toContainerId,\n localUpdatedAt: updatedAt,\n })\n .where(eq(containers.parentId, fromContainerId))\n .run();\n const createLane = inLocalIntentLane(LOCAL_INTENT_LANES.containerCreate);\n const createIntentRows = await tx\n .select({ containerId: localIntents.subjectId })\n .from(localIntents)\n .where(and(createLane, eq(localIntents.targetContainerId, fromContainerId)))\n .all();\n for (const intent of createIntentRows) {\n await tx\n .update(localIntents)\n .set({\n id: crypto.randomUUID(),\n targetContainerId: toContainerId,\n updatedAt,\n })\n .where(and(createLane, eq(localIntents.subjectId, intent.containerId)))\n .run();\n }\n const moveLane = inLocalIntentLane(LOCAL_INTENT_LANES.containerMove);\n const moveIntentRows = await tx\n .select({ containerId: localIntents.subjectId })\n .from(localIntents)\n .where(and(moveLane, eq(localIntents.targetContainerId, fromContainerId)))\n .all();\n for (const intent of moveIntentRows) {\n await tx\n .update(localIntents)\n .set({\n id: crypto.randomUUID(),\n targetContainerId: toContainerId,\n syncStatus: \"pending\",\n updatedAt,\n })\n .where(and(moveLane, eq(localIntents.subjectId, intent.containerId)))\n .run();\n }\n}\n\nexport async function deleteLocalContainerRows(input: {\n containerId: string;\n tx: ClientSQLiteTransactionScope;\n}): Promise<void> {\n const { containerId, tx } = input;\n await tx\n .delete(localIntents)\n .where(\n and(inContainerIntentLanes(), eq(localIntents.subjectId, containerId)),\n )\n .run();\n await tx.delete(containers).where(eq(containers.id, containerId)).run();\n await deleteContainerMetadataDocumentRowsInTransaction(tx, [containerId]);\n await deleteContainerWatermarksInTransaction(tx, [containerId]);\n}\n"]}
1
+ {"version":3,"file":"containerStructuralRepair.js","sourceRoot":"","sources":["containerStructuralRepair.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,EAAE,GAAG,EAAE,EAAE,EAAE,OAAO,EAAE,MAAM,aAAa,CAA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AAE,CAAC,YAAY,CAAC,iBAAiB,EAAE,eAAe,CAAC,CAAC,CAAC;SACzE,GAAG,EAAE,CAAC;IACT,KAAK,MAAM,MAAM,IAAI,cAAc,EAAE,CAAC;QACpC,MAAM,EAAE;aACL,MAAM,CAAC,YAAY,CAAC;aACpB,GAAG,CAAC;YACH,EAAE,EAAE,MAAM,CAAC,UAAU,EAAE;YACvB,iBAAiB,EAAE,aAAa;YAChC,UAAU,EAAE,SAAS;YACrB,SAAS;SACV,CAAC;aACD,KAAK,CAAC,GAAG,CAAC,QAAQ,EAAE,EAAE,CAAC,YAAY,CAAC,SAAS,EAAE,MAAM,CAAC,WAAW,CAAC,CAAC,CAAC;aACpE,GAAG,EAAE,CAAC;IACX,CAAC;AACH,CAAC;AAED,MAAM,CAAC,KAAK,UAAU,wBAAwB,CAAC,KAG9C;IACC,MAAM,EAAE,WAAW,EAAE,EAAE,EAAE,GAAG,KAAK,CAAC;IAClC,MAAM,EAAE;SACL,MAAM,CAAC,YAAY,CAAC;SACpB,KAAK,CACJ,GAAG,CAAC,sBAAsB,EAAE,EAAE,EAAE,CAAC,YAAY,CAAC,SAAS,EAAE,WAAW,CAAC,CAAC,CACvE;SACA,GAAG,EAAE,CAAC;IACT,MAAM,EAAE,CAAC,MAAM,CAAC,UAAU,CAAC,CAAC,KAAK,CAAC,EAAE,CAAC,UAAU,CAAC,EAAE,EAAE,WAAW,CAAC,CAAC,CAAC,GAAG,EAAE,CAAC;IACxE,MAAM,gDAAgD,CAAC,EAAE,EAAE,CAAC,WAAW,CAAC,CAAC,CAAC;IAC1E,MAAM,sCAAsC,CAAC,EAAE,EAAE,CAAC,WAAW,CAAC,CAAC,CAAC;AAClE,CAAC","sourcesContent":["import { and, asc, eq, inArray } from \"drizzle-orm\";\nimport {\n containers,\n documentContainerProjection,\n documentProjection,\n inContainerIntentLanes,\n inLocalIntentLane,\n LOCAL_INTENT_LANES,\n localIntents,\n} from \"../../sqlite/schema\";\nimport { sqliteRowsPerStatement } from \"../../sqlite/sqliteBindBudget\";\nimport type { ClientSQLiteTransactionScope } from \"../../sqlite/sqlitePersistenceRuntime\";\nimport { deleteContainerDocumentTombstoneHoldsForContainers } from \"../documents/containerDocumentTombstoneHoldsPersistence\";\nimport { setDocumentProjectionContainerInTransaction } from \"../documents/documentProjectionContainers\";\nimport { getLatestTimestamp } from \"../latestTimestamp\";\nimport type {\n ContainerRemoval,\n LocalRootDescendantReparentInput,\n} from \"./containerContentsPersistenceTypes\";\nimport { saveContainerCreateIntent } from \"./containerIntentPersistence\";\nimport { deleteContainerWatermarksInTransaction } from \"./containerSyncWatermarkPersistence\";\nimport { deleteContainerMetadataDocumentRowsInTransaction } from \"./dormantContainerMetadata\";\n\n// The containers being removed still exist when repair runs (deletion follows\n// it). Capture their org attribution so a detached document's pending writes\n// keep a resolvable organization id after the join source is gone — e.g. when\n// access to a shared org is revoked mid-sync.\nasync function loadOrganizationIdsForContainers(\n tx: ClientSQLiteTransactionScope,\n containerIds: ReadonlyArray<string>,\n): Promise<Map<string, string>> {\n const rows = await tx\n .select({\n id: containers.id,\n organizationId: containers.organizationId,\n })\n .from(containers)\n .where(inArray(containers.id, containerIds));\n const organizationIdByContainerId = new Map<string, string>();\n for (const container of rows) {\n if (container.id && container.organizationId) {\n organizationIdByContainerId.set(container.id, container.organizationId);\n }\n }\n return organizationIdByContainerId;\n}\n\n// One removed container can hold any number of documents, so their ids are\n// read back in batches that fit SQLite's bind budget.\nconst DOCUMENT_ID_BATCH_SIZE = sqliteRowsPerStatement(1);\n\n// A document unlinked from a removed container may keep other live links; its\n// projection then re-homes to the first remaining link (deterministic order)\n// instead of dropping to null.\nasync function loadFirstRemainingContainerIdByDocumentId(\n tx: ClientSQLiteTransactionScope,\n documentIds: ReadonlyArray<string>,\n): Promise<Map<string, string>> {\n const firstRemainingContainerIdByDocumentId = new Map<string, string>();\n for (\n let index = 0;\n index < documentIds.length;\n index += DOCUMENT_ID_BATCH_SIZE\n ) {\n // A document's links all fall in its own batch, so the first per\n // document is still the lowest container id.\n const remainingLinks = await tx\n .select({\n containerId: documentContainerProjection.containerId,\n documentId: documentContainerProjection.documentId,\n })\n .from(documentContainerProjection)\n .where(\n inArray(\n documentContainerProjection.documentId,\n documentIds.slice(index, index + DOCUMENT_ID_BATCH_SIZE),\n ),\n )\n .orderBy(\n asc(documentContainerProjection.documentId),\n asc(documentContainerProjection.containerId),\n );\n for (const link of remainingLinks) {\n if (!firstRemainingContainerIdByDocumentId.has(link.documentId)) {\n firstRemainingContainerIdByDocumentId.set(\n link.documentId,\n link.containerId,\n );\n }\n }\n }\n return firstRemainingContainerIdByDocumentId;\n}\n\nexport async function repairDocumentsForRemovedContainersInTransaction(input: {\n removals: ReadonlyArray<ContainerRemoval>;\n tx: ClientSQLiteTransactionScope;\n}): Promise<void> {\n const { tx } = input;\n const updatedAtByContainerId = new Map(\n input.removals.map((removal) => [removal.containerId, removal.updatedAt]),\n );\n const containerIds = Array.from(updatedAtByContainerId.keys());\n if (containerIds.length === 0) {\n return;\n }\n\n {\n const selectedRows = await tx\n .select({\n containerId: documentProjection.containerId,\n documentId: documentProjection.documentId,\n localId: documentProjection.localId,\n updatedAt: documentProjection.updatedAt,\n })\n .from(documentProjection)\n .where(inArray(documentProjection.containerId, containerIds));\n\n const organizationIdByContainerId = await loadOrganizationIdsForContainers(\n tx,\n containerIds,\n );\n\n await tx\n .delete(documentContainerProjection)\n .where(inArray(documentContainerProjection.containerId, containerIds))\n .run();\n await deleteContainerDocumentTombstoneHoldsForContainers(tx, containerIds);\n\n const documentIds = Array.from(\n new Set(\n selectedRows.flatMap((row) => (row.documentId ? [row.documentId] : [])),\n ),\n );\n const firstRemainingContainerIdByDocumentId =\n await loadFirstRemainingContainerIdByDocumentId(tx, documentIds);\n\n for (const row of selectedRows) {\n if (!row.localId) {\n continue;\n }\n\n const removedOrganizationId = row.containerId\n ? organizationIdByContainerId.get(row.containerId)\n : undefined;\n await setDocumentProjectionContainerInTransaction(tx, row.localId, {\n containerId: row.documentId\n ? (firstRemainingContainerIdByDocumentId.get(row.documentId) ?? null)\n : null,\n organizationId: removedOrganizationId,\n updatedAt: getLatestTimestamp(\n row.updatedAt,\n row.containerId\n ? (updatedAtByContainerId.get(row.containerId) ?? row.updatedAt)\n : row.updatedAt,\n ),\n });\n }\n }\n}\n\nexport async function updateReparentedDescendantContainers(input: {\n descendantReparents: ReadonlyArray<LocalRootDescendantReparentInput>;\n remoteOrganizationId: string;\n tx: ClientSQLiteTransactionScope;\n updatedAt: string;\n}): Promise<void> {\n const { descendantReparents, remoteOrganizationId, tx, updatedAt } = input;\n const descendantIds = Array.from(\n new Set(descendantReparents.map((reparent) => reparent.containerId)),\n );\n if (descendantIds.length === 0) {\n return;\n }\n\n await tx\n .update(containers)\n .set({\n organizationId: remoteOrganizationId,\n localUpdatedAt: updatedAt,\n })\n .where(inArray(containers.id, descendantIds))\n .run();\n\n for (const reparent of descendantReparents) {\n await tx\n .update(containers)\n .set({ parentId: reparent.parentContainerId })\n .where(eq(containers.id, reparent.containerId))\n .run();\n\n if (reparent.updateCreateIntent && reparent.parentContainerId) {\n await saveContainerCreateIntent({\n containerId: reparent.containerId,\n createIntent: { parentContainerId: reparent.parentContainerId },\n tx,\n updatedAt,\n });\n }\n\n if (reparent.parentContainerId) {\n await tx\n .update(localIntents)\n .set({\n id: crypto.randomUUID(),\n targetContainerId: reparent.parentContainerId,\n syncStatus: \"pending\",\n updatedAt,\n })\n .where(\n and(\n inLocalIntentLane(LOCAL_INTENT_LANES.containerMove),\n eq(localIntents.subjectId, reparent.containerId),\n ),\n )\n .run();\n }\n }\n}\n\nexport async function reparentLocalContainerChildren(input: {\n fromContainerId: string;\n remoteOrganizationId: string;\n toContainerId: string;\n tx: ClientSQLiteTransactionScope;\n updatedAt: string;\n}): Promise<void> {\n const {\n fromContainerId,\n remoteOrganizationId,\n toContainerId,\n tx,\n updatedAt,\n } = input;\n await tx\n .update(containers)\n .set({\n organizationId: remoteOrganizationId,\n parentId: toContainerId,\n localUpdatedAt: updatedAt,\n })\n .where(eq(containers.parentId, fromContainerId))\n .run();\n const createLane = inLocalIntentLane(LOCAL_INTENT_LANES.containerCreate);\n const createIntentRows = await tx\n .select({ containerId: localIntents.subjectId })\n .from(localIntents)\n .where(and(createLane, eq(localIntents.targetContainerId, fromContainerId)))\n .all();\n for (const intent of createIntentRows) {\n await tx\n .update(localIntents)\n .set({\n id: crypto.randomUUID(),\n targetContainerId: toContainerId,\n updatedAt,\n })\n .where(and(createLane, eq(localIntents.subjectId, intent.containerId)))\n .run();\n }\n const moveLane = inLocalIntentLane(LOCAL_INTENT_LANES.containerMove);\n const moveIntentRows = await tx\n .select({ containerId: localIntents.subjectId })\n .from(localIntents)\n .where(and(moveLane, eq(localIntents.targetContainerId, fromContainerId)))\n .all();\n for (const intent of moveIntentRows) {\n await tx\n .update(localIntents)\n .set({\n id: crypto.randomUUID(),\n targetContainerId: toContainerId,\n syncStatus: \"pending\",\n updatedAt,\n })\n .where(and(moveLane, eq(localIntents.subjectId, intent.containerId)))\n .run();\n }\n}\n\nexport async function deleteLocalContainerRows(input: {\n containerId: string;\n tx: ClientSQLiteTransactionScope;\n}): Promise<void> {\n const { containerId, tx } = input;\n await tx\n .delete(localIntents)\n .where(\n and(inContainerIntentLanes(), eq(localIntents.subjectId, containerId)),\n )\n .run();\n await tx.delete(containers).where(eq(containers.id, containerId)).run();\n await deleteContainerMetadataDocumentRowsInTransaction(tx, [containerId]);\n await deleteContainerWatermarksInTransaction(tx, [containerId]);\n}\n"]}
@@ -0,0 +1,60 @@
1
+ import { and, eq, inArray } from "drizzle-orm";
2
+ import { DOCUMENTS_APP_KIND } from "../../documents/documentConstants.js";
3
+ import { documentContainerProjection, documents } from "../../sqlite/schema/index.js";
4
+ import { SQLITE_BOUND_VARIABLE_BUDGET } from "../../sqlite/sqliteBindBudget.js";
5
+ import { getClientSQLitePersistenceRuntime } from "../../sqlite/sqlitePersistenceRuntime.js";
6
+ // Leave room for the fixed binds each statement adds beside its id list.
7
+ const ID_BATCH_SIZE = SQLITE_BOUND_VARIABLE_BUDGET - 8;
8
+ function batches(values) {
9
+ const result = [];
10
+ for (let index = 0; index < values.length; index += ID_BATCH_SIZE) {
11
+ result.push(values.slice(index, index + ID_BATCH_SIZE));
12
+ }
13
+ return result;
14
+ }
15
+ /**
16
+ * Local ids of the documents whose every placement is one of `containerIds`.
17
+ * A document also placed in a container outside the set stays: removing these
18
+ * containers must not take a document another folder still shows.
19
+ */
20
+ export async function listDocumentLocalIdsPlacedOnlyIn(execSql, containerIds) {
21
+ const targets = new Set(containerIds);
22
+ if (targets.size === 0)
23
+ return [];
24
+ const { db } = getClientSQLitePersistenceRuntime(execSql);
25
+ const placedDocumentIds = new Set();
26
+ for (const batch of batches([...targets])) {
27
+ const rows = await db
28
+ .select({ documentId: documentContainerProjection.documentId })
29
+ .from(documentContainerProjection)
30
+ .where(inArray(documentContainerProjection.containerId, batch));
31
+ for (const row of rows)
32
+ placedDocumentIds.add(row.documentId);
33
+ }
34
+ const exclusiveDocumentIds = new Set(placedDocumentIds);
35
+ for (const batch of batches([...placedDocumentIds])) {
36
+ const rows = await db
37
+ .select({
38
+ containerId: documentContainerProjection.containerId,
39
+ documentId: documentContainerProjection.documentId,
40
+ })
41
+ .from(documentContainerProjection)
42
+ .where(inArray(documentContainerProjection.documentId, batch));
43
+ for (const row of rows) {
44
+ if (!targets.has(row.containerId)) {
45
+ exclusiveDocumentIds.delete(row.documentId);
46
+ }
47
+ }
48
+ }
49
+ const localIds = [];
50
+ for (const batch of batches([...exclusiveDocumentIds])) {
51
+ const rows = await db
52
+ .select({ localId: documents.localId })
53
+ .from(documents)
54
+ .where(and(eq(documents.appKind, DOCUMENTS_APP_KIND), inArray(documents.documentId, batch)));
55
+ for (const row of rows)
56
+ localIds.push(row.localId);
57
+ }
58
+ return localIds.sort();
59
+ }
60
+ //# sourceMappingURL=exclusiveDocumentPlacements.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"exclusiveDocumentPl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AO,CAAC,SAAS,CAAC,UAAU,EAAE,KAAK,CAAC,CACrC,CACF,CAAC;QACJ,KAAK,MAAM,GAAG,IAAI,IAAI;YAAE,QAAQ,CAAC,IAAI,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC;IACrD,CAAC;IACD,OAAO,QAAQ,CAAC,IAAI,EAAE,CAAC;AACzB,CAAC","sourcesContent":["import { and, eq, inArray } from \"drizzle-orm\";\nimport { DOCUMENTS_APP_KIND } from \"../../documents/documentConstants\";\nimport { documentContainerProjection, documents } from \"../../sqlite/schema\";\nimport { SQLITE_BOUND_VARIABLE_BUDGET } from \"../../sqlite/sqliteBindBudget\";\nimport { getClientSQLitePersistenceRuntime } from \"../../sqlite/sqlitePersistenceRuntime\";\nimport type { ExecSql } from \"../../sqlite/sqlSchema\";\n\n// Leave room for the fixed binds each statement adds beside its id list.\nconst ID_BATCH_SIZE = SQLITE_BOUND_VARIABLE_BUDGET - 8;\n\nfunction batches<T>(values: readonly T[]): T[][] {\n const result: T[][] = [];\n for (let index = 0; index < values.length; index += ID_BATCH_SIZE) {\n result.push(values.slice(index, index + ID_BATCH_SIZE));\n }\n return result;\n}\n\n/**\n * Local ids of the documents whose every placement is one of `containerIds`.\n * A document also placed in a container outside the set stays: removing these\n * containers must not take a document another folder still shows.\n */\nexport async function listDocumentLocalIdsPlacedOnlyIn(\n execSql: ExecSql,\n containerIds: readonly string[],\n): Promise<string[]> {\n const targets = new Set(containerIds);\n if (targets.size === 0) return [];\n const { db } = getClientSQLitePersistenceRuntime(execSql);\n const placedDocumentIds = new Set<string>();\n for (const batch of batches([...targets])) {\n const rows = await db\n .select({ documentId: documentContainerProjection.documentId })\n .from(documentContainerProjection)\n .where(inArray(documentContainerProjection.containerId, batch));\n for (const row of rows) placedDocumentIds.add(row.documentId);\n }\n\n const exclusiveDocumentIds = new Set(placedDocumentIds);\n for (const batch of batches([...placedDocumentIds])) {\n const rows = await db\n .select({\n containerId: documentContainerProjection.containerId,\n documentId: documentContainerProjection.documentId,\n })\n .from(documentContainerProjection)\n .where(inArray(documentContainerProjection.documentId, batch));\n for (const row of rows) {\n if (!targets.has(row.containerId)) {\n exclusiveDocumentIds.delete(row.documentId);\n }\n }\n }\n\n const localIds: string[] = [];\n for (const batch of batches([...exclusiveDocumentIds])) {\n const rows = await db\n .select({ localId: documents.localId })\n .from(documents)\n .where(\n and(\n eq(documents.appKind, DOCUMENTS_APP_KIND),\n inArray(documents.documentId, batch),\n ),\n );\n for (const row of rows) localIds.push(row.localId);\n }\n return localIds.sort();\n}\n"]}
@@ -14,6 +14,19 @@ import { loadWithOrganizationReadModelIntegrityPurge, pruneInactiveOrganizationR
14
14
  import { assertOrganizationReadModelResponse } from "./organizationReadModelResponseAssertions.js";
15
15
  const DIRECTORY_INSERT_BATCH_SIZE = sqliteInsertBatchSize(organizationReadModelDirectoryUsers);
16
16
  const GROUP_INSERT_BATCH_SIZE = sqliteInsertBatchSize(organizationReadModelGroups);
17
+ /**
18
+ * The member's leave request as stored JSON, kept only when it names this
19
+ * organization and member. Its signature is checked when read, against the
20
+ * member's trusted identity rather than the key served beside it.
21
+ */
22
+ function storedLeaveRequestJson(organizationId, user) {
23
+ const request = user.leaveRequest;
24
+ return request &&
25
+ request.organizationId === organizationId &&
26
+ request.userId === user.userId
27
+ ? JSON.stringify(request)
28
+ : null;
29
+ }
17
30
  async function replaceDirectoryLane(input) {
18
31
  await input.tx
19
32
  .delete(organizationReadModelDirectoryUsers)
@@ -35,6 +48,7 @@ async function replaceDirectoryLane(input) {
35
48
  updatedAt: user.updatedAt,
36
49
  disabledAt: user.disabledAt,
37
50
  disabledByUserId: user.disabledByUserId,
51
+ leaveRequest: storedLeaveRequestJson(input.organizationId, user),
38
52
  }));
39
53
  for (let index = 0; index < rows.length; index += DIRECTORY_INSERT_BATCH_SIZE) {
40
54
  await input.tx
@@ -1 +1 @@
1
- {"version":3,"file":"organizationReadModelPersistence.js","sourceRoot":"","sources":["organizationReadModelPersistence.ts"],"names":[],"mappings":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QACD,MAAM,aAAa,GAAG,oBAAoB,CAAC;YACzC,OAAO;YACP,QAAQ,EAAE,KAAK,CAAC,QAAQ;SACzB,CAAC,CAAC;QACH,MAAM,oBAAoB,GAAG,MAAM,kBAAkB,CAAC;YACpD,OAAO;YACP,aAAa,EAAE,KAAK,CAAC,aAAa;YAClC,aAAa;YACb,QAAQ,EAAE,KAAK,CAAC,QAAQ;YACxB,EAAE;SACH,CAAC,CAAC;QACH,MAAM,gCAAgC,CAAC;YACrC,OAAO;YACP,aAAa;YACb,oBAAoB;YACpB,GAAG;YACH,QAAQ,EAAE,KAAK,CAAC,QAAQ;YACxB,EAAE;SACH,CAAC,CAAC;QAEH,OAAO,SAAS,CAAC;IACnB,CAAC,CACF,CAAC;IACF,wEAAwE;IACxE,wEAAwE;IACxE,IAAI,WAAW,KAAK,SAAS;QAC3B,qCAAqC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,kBAAkB,CACrE,KAAK,CAAC,QAAQ,CAAC,cAAc,CAC9B,CAAC;IACJ,OAAO,WAAW,CAAC;AACrB,CAAC;AAED,MAAM,CAAC,KAAK,UAAU,oCAAoC,CACxD,OAAgB,EAChB,cAAsB,EACtB,UAAqD,EAAE;IAEvD,MAAM,eAAe,CAAC,OAAO,EAAE,2BAA2B,CAAC,CAAC;IAC5D,MAAM,iCAAiC,CAAC,OAAO,CAAC,CAAC,WAAW,CAAC,KAAK,EAAE,EAAE,EAAE,EAAE;QACxE,MAAM,iDAAiD,CAAC;YACtD,mBAAmB,EAAE,OAAO,CAAC,mBAAmB;YAChD,cAAc;YACd,EAAE;SACH,CAAC,CAAC;IACL,CAAC,CAAC,CAAC;AACL,CAAC","sourcesContent":["import type {\n ListOrganizationGroupsResponse,\n OrganizationGroupCurrentStateResponse,\n OrganizationReadModelDirectoryResponse,\n OrganizationReadModelResponse,\n} from \"@tearleads/validators/response\";\nimport { eq } from \"drizzle-orm\";\nimport { getOrCreatePrincipalPolicyCoordinator } from \"../../principals/principalPolicyCoordinator\";\nimport { organizationReadModelTables } from \"../../sqlite/schema\";\nimport { organizationDataUsageTables } from \"../../sqlite/schema/organizationDataUsageSchema\";\nimport {\n organizationReadModelDirectoryUsers,\n organizationReadModelGroups,\n organizationReadModelRequesters,\n organizationReadModelState,\n} from \"../../sqlite/schema/organizationReadModelSchema\";\nimport { sqliteInsertBatchSize } from \"../../sqlite/sqliteBindBudget\";\nimport {\n type ClientSQLiteTransactionScope,\n getClientSQLitePersistenceRuntime,\n} from \"../../sqlite/sqlitePersistenceRuntime\";\nimport { type ExecSql, ensureSqlTables } from \"../../sqlite/sqlSchema\";\nimport { clearOrganizationPresentationDenialInTransaction } from \"./organizationPresentationDenialPersistence\";\nimport { applyOrganizationReadModelGrantsLane } from \"./organizationReadModelGrantPersistence\";\nimport {\n applyGroupMembershipsLane,\n assertStoredGroupMembershipBindings,\n OrganizationReadModelBindingError,\n} from \"./organizationReadModelMembershipPersistence\";\nimport {\n loadOrganizationReadModelProjectionInTransaction,\n type OrganizationReadModelProjection,\n} from \"./organizationReadModelProjection\";\nimport {\n loadWithOrganizationReadModelIntegrityPurge,\n pruneInactiveOrganizationRequestersInTransaction,\n purgeOrganizationReadModelProjectionInTransaction,\n} from \"./organizationReadModelPurge\";\nimport { assertOrganizationReadModelResponse } from \"./organizationReadModelResponseAssertions\";\n\nexport type { OrganizationReadModelProjection } from \"./organizationReadModelProjection\";\n\nconst DIRECTORY_INSERT_BATCH_SIZE = sqliteInsertBatchSize(\n organizationReadModelDirectoryUsers,\n);\nconst GROUP_INSERT_BATCH_SIZE = sqliteInsertBatchSize(\n organizationReadModelGroups,\n);\n\ntype ApplyOrganizationReadModelResponseResult =\n | \"already-applied\"\n | \"applied\"\n | \"stale\";\n\ninterface CurrentOrganizationReadModelState {\n readonly cursor: string;\n readonly memberGroupId: string;\n readonly memberGroupStateHash: string;\n readonly organizationHead: OrganizationGroupCurrentStateResponse;\n readonly profileDocumentId: string | null;\n}\n\nasync function replaceDirectoryLane(input: {\n readonly directory: OrganizationReadModelDirectoryResponse;\n readonly organizationId: string;\n readonly tx: ClientSQLiteTransactionScope;\n}): Promise<void> {\n await input.tx\n .delete(organizationReadModelDirectoryUsers)\n .where(\n eq(\n organizationReadModelDirectoryUsers.organizationId,\n input.organizationId,\n ),\n )\n .run();\n\n const rows = input.directory.users.map((user, sortOrder) => ({\n organizationId: input.organizationId,\n userId: user.userId,\n sortOrder,\n signingKeyFingerprint: user.signingKeyFingerprint,\n signingPublicKey: user.signingPublicKey,\n encapsulationPublicKey: user.encapsulationPublicKey,\n encapsulationKeyFingerprint: user.encapsulationKeyFingerprint,\n isPersonalOrganizationOwner: user.isPersonalOrganizationOwner,\n createdAt: user.createdAt,\n status: user.status,\n profileDocumentId: user.profileDocumentId,\n joinedAt: user.joinedAt,\n updatedAt: user.updatedAt,\n disabledAt: user.disabledAt,\n disabledByUserId: user.disabledByUserId,\n }));\n for (\n let index = 0;\n index < rows.length;\n index += DIRECTORY_INSERT_BATCH_SIZE\n ) {\n await input.tx\n .insert(organizationReadModelDirectoryUsers)\n .values(rows.slice(index, index + DIRECTORY_INSERT_BATCH_SIZE))\n .run();\n }\n}\n\nasync function upsertRequester(input: {\n readonly currentUserId: string;\n readonly isOrgAdmin: boolean;\n readonly now: string;\n readonly organizationId: string;\n readonly tx: ClientSQLiteTransactionScope;\n}): Promise<void> {\n const requesterRow = {\n organizationId: input.organizationId,\n userId: input.currentUserId,\n isOrgAdmin: input.isOrgAdmin,\n updatedAt: input.now,\n };\n await input.tx\n .insert(organizationReadModelRequesters)\n .values(requesterRow)\n .onConflictDoUpdate({\n target: [\n organizationReadModelRequesters.organizationId,\n organizationReadModelRequesters.userId,\n ],\n set: {\n isOrgAdmin: requesterRow.isOrgAdmin,\n updatedAt: requesterRow.updatedAt,\n },\n })\n .run();\n // Storing an authoritative response proves access: retire the durable\n // denial marker for this scope in the same transaction.\n await clearOrganizationPresentationDenialInTransaction({\n organizationId: input.organizationId,\n projection: \"readModel\",\n requesterUserId: input.currentUserId,\n tx: input.tx,\n });\n}\n\nasync function replaceGroupsLane(input: {\n readonly groups: ListOrganizationGroupsResponse;\n readonly organizationId: string;\n readonly tx: ClientSQLiteTransactionScope;\n}): Promise<void> {\n // Hydrated names and delivered membership heads outlive a catalog\n // replacement; the groupMemberships lane rebinds any head that changed.\n const previousGroups = await input.tx\n .select({\n groupId: organizationReadModelGroups.groupId,\n membersStateHash: organizationReadModelGroups.membersStateHash,\n name: organizationReadModelGroups.name,\n })\n .from(organizationReadModelGroups)\n .where(\n eq(organizationReadModelGroups.organizationId, input.organizationId),\n );\n const previousById = new Map(\n previousGroups.map((group) => [group.groupId, group]),\n );\n await input.tx\n .delete(organizationReadModelGroups)\n .where(eq(organizationReadModelGroups.organizationId, input.organizationId))\n .run();\n\n const rows = input.groups.groups.map((group, sortOrder) => ({\n organizationId: input.organizationId,\n groupId: group.groupId,\n sortOrder,\n name: previousById.get(group.groupId)?.name ?? \"\",\n createdAt: group.createdAt,\n isBuiltin: group.isBuiltin,\n stateHash: group.currentState?.stateHash ?? null,\n stateVersion: group.currentState?.version ?? null,\n keyEpoch: group.currentState?.keyEpoch ?? null,\n keyFingerprint: group.currentState?.keyFingerprint ?? null,\n memberCount: group.currentState?.memberCount ?? null,\n membersStateHash: previousById.get(group.groupId)?.membersStateHash ?? null,\n }));\n for (let index = 0; index < rows.length; index += GROUP_INSERT_BATCH_SIZE) {\n await input.tx\n .insert(organizationReadModelGroups)\n .values(rows.slice(index, index + GROUP_INSERT_BATCH_SIZE))\n .run();\n }\n}\n\nasync function loadCurrentState(\n tx: ClientSQLiteTransactionScope,\n organizationId: string,\n): Promise<CurrentOrganizationReadModelState | null> {\n const [current] = await tx\n .select({\n cursor: organizationReadModelState.cursor,\n keyEpoch: organizationReadModelState.organizationKeyEpoch,\n keyFingerprint: organizationReadModelState.organizationKeyFingerprint,\n memberCount: organizationReadModelState.organizationMemberCount,\n memberGroupId: organizationReadModelState.memberGroupId,\n memberGroupStateHash: organizationReadModelState.memberGroupStateHash,\n profileDocumentId: organizationReadModelState.profileDocumentId,\n stateHash: organizationReadModelState.organizationStateHash,\n version: organizationReadModelState.organizationStateVersion,\n })\n .from(organizationReadModelState)\n .where(eq(organizationReadModelState.organizationId, organizationId))\n .limit(1);\n if (!current) {\n return null;\n }\n const { keyEpoch, keyFingerprint, memberCount, stateHash, version, ...rest } =\n current;\n return {\n ...rest,\n organizationHead: {\n keyEpoch,\n keyFingerprint,\n memberCount,\n stateHash,\n version,\n },\n };\n}\n\nfunction resolveApplyDisposition(input: {\n readonly current: CurrentOrganizationReadModelState | null;\n readonly requestedCursor: string | null;\n readonly response: OrganizationReadModelResponse;\n}): ApplyOrganizationReadModelResponseResult | null {\n const currentCursor = input.current?.cursor ?? null;\n if (currentCursor !== input.requestedCursor) {\n return currentCursor === input.response.nextCursor\n ? \"already-applied\"\n : \"stale\";\n }\n if (!input.current && input.response.mode !== \"snapshot\") {\n throw new Error(\"Organization read-model delta requires a local snapshot\");\n }\n return null;\n}\n\ninterface ResponseLanesInput {\n readonly current: CurrentOrganizationReadModelState | null;\n readonly memberGroupId: string;\n readonly response: OrganizationReadModelResponse;\n readonly tx: ClientSQLiteTransactionScope;\n}\n\n/** Apply every carried lane and return the reserved Members head. */\nasync function replaceResponseLanes(\n input: ResponseLanesInput,\n): Promise<string | null> {\n const { organizationId } = input.response;\n const directory = input.response.lanes.directory;\n if (directory) {\n await replaceDirectoryLane({ directory, organizationId, tx: input.tx });\n }\n const groups = input.response.lanes.groups;\n if (groups) {\n await replaceGroupsLane({ groups, organizationId, tx: input.tx });\n }\n const groupMemberships = input.response.lanes.groupMemberships;\n const memberGroupStateHash = groupMemberships\n ? await applyGroupMembershipsLane({\n currentMemberGroupStateHash:\n input.current?.memberGroupStateHash ?? null,\n lane: groupMemberships,\n memberGroupId: input.memberGroupId,\n organizationId,\n replaceAll: input.response.mode === \"snapshot\",\n tx: input.tx,\n })\n : (input.current?.memberGroupStateHash ?? null);\n const grants = input.response.lanes.grants;\n if (grants) {\n await applyOrganizationReadModelGrantsLane({\n lane: grants,\n organizationId,\n tx: input.tx,\n });\n }\n return memberGroupStateHash;\n}\n\nasync function applyResponseLanes(\n input: ResponseLanesInput & { readonly currentUserId: string },\n): Promise<string | null> {\n const memberGroupStateHash = await replaceResponseLanes(input);\n // The directory lane is the authoritative roster, already persisted above:\n // requester rows for users it no longer lists as active fall with it.\n if (input.response.lanes.directory) {\n await pruneInactiveOrganizationRequestersInTransaction({\n organizationId: input.response.organizationId,\n retainUserId: input.currentUserId,\n tx: input.tx,\n });\n }\n if (input.response.lanes.groups || input.response.lanes.groupMemberships) {\n await assertStoredGroupMembershipBindings({\n memberGroupId: input.memberGroupId,\n memberGroupStateHash,\n organizationId: input.response.organizationId,\n tx: input.tx,\n });\n }\n return memberGroupStateHash;\n}\n\n/**\n * Write the cursor with the organization policy head and the reserved Members\n * head in one row, so a failure anywhere in the page rolls them back together.\n */\nasync function upsertOrganizationReadModelState(input: {\n readonly current: CurrentOrganizationReadModelState | null;\n readonly memberGroupId: string;\n readonly memberGroupStateHash: string | null;\n readonly now: string;\n readonly response: OrganizationReadModelResponse;\n readonly tx: ClientSQLiteTransactionScope;\n}): Promise<void> {\n const organizationHead =\n input.response.lanes.organizationPolicy?.currentState ??\n input.current?.organizationHead;\n if (!organizationHead || input.memberGroupStateHash === null) {\n throw new OrganizationReadModelBindingError(\n \"Organization read-model policy or Members head is missing\",\n );\n }\n const directoryLane = input.response.lanes.directory;\n const values = {\n cursor: input.response.nextCursor,\n profileDocumentId:\n directoryLane !== undefined\n ? directoryLane.profileDocumentId\n : (input.current?.profileDocumentId ?? null),\n memberGroupId: input.memberGroupId,\n memberGroupStateHash: input.memberGroupStateHash,\n organizationStateHash: organizationHead.stateHash,\n organizationStateVersion: organizationHead.version,\n organizationKeyEpoch: organizationHead.keyEpoch,\n organizationKeyFingerprint: organizationHead.keyFingerprint,\n organizationMemberCount: organizationHead.memberCount,\n updatedAt: input.now,\n };\n await input.tx\n .insert(organizationReadModelState)\n .values({ ...values, organizationId: input.response.organizationId })\n .onConflictDoUpdate({\n target: organizationReadModelState.organizationId,\n set: values,\n })\n .run();\n}\n\nfunction requireMemberGroupId(input: {\n readonly current: CurrentOrganizationReadModelState | null;\n readonly response: OrganizationReadModelResponse;\n}): string {\n const memberGroupId =\n input.response.lanes.groups?.memberGroupId ?? input.current?.memberGroupId;\n if (!memberGroupId) {\n throw new Error(\"Organization read-model member group is missing\");\n }\n return memberGroupId;\n}\n\nexport async function loadOrganizationReadModelProjection(\n execSql: ExecSql,\n organizationId: string,\n currentUserId: string,\n): Promise<OrganizationReadModelProjection | null> {\n return loadWithOrganizationReadModelIntegrityPurge({\n execSql,\n organizationId,\n load: (tx) =>\n loadOrganizationReadModelProjectionInTransaction({\n currentUserId,\n organizationId,\n tx,\n }),\n });\n}\n\nexport async function applyOrganizationReadModelResponse(input: {\n readonly currentUserId: string;\n readonly execSql: ExecSql;\n readonly requestedCursor: string | null;\n readonly response: OrganizationReadModelResponse;\n}): Promise<ApplyOrganizationReadModelResponseResult> {\n assertOrganizationReadModelResponse({\n currentUserId: input.currentUserId,\n response: input.response,\n });\n // The requester prune below also retires pruned users' usage projections.\n await ensureSqlTables(input.execSql, [\n ...organizationReadModelTables,\n ...organizationDataUsageTables,\n ]);\n\n const disposition = await getClientSQLitePersistenceRuntime(\n input.execSql,\n ).transaction(\n async (tx): Promise<ApplyOrganizationReadModelResponseResult> => {\n const current = await loadCurrentState(tx, input.response.organizationId);\n const disposition = resolveApplyDisposition({\n current,\n requestedCursor: input.requestedCursor,\n response: input.response,\n });\n if (disposition === \"stale\") {\n return disposition;\n }\n const now = new Date().toISOString();\n await upsertRequester({\n currentUserId: input.currentUserId,\n isOrgAdmin: input.response.currentUser.isOrgAdmin,\n now,\n organizationId: input.response.organizationId,\n tx,\n });\n if (disposition === \"already-applied\") {\n return disposition;\n }\n const memberGroupId = requireMemberGroupId({\n current,\n response: input.response,\n });\n const memberGroupStateHash = await applyResponseLanes({\n current,\n currentUserId: input.currentUserId,\n memberGroupId,\n response: input.response,\n tx,\n });\n await upsertOrganizationReadModelState({\n current,\n memberGroupId,\n memberGroupStateHash,\n now,\n response: input.response,\n tx,\n });\n\n return \"applied\";\n },\n );\n // An applied change follows an organization hint or mutation; in-flight\n // operations recover the directory again instead of reusing their memo.\n if (disposition === \"applied\")\n getOrCreatePrincipalPolicyCoordinator(input.execSql).invalidateRecovery(\n input.response.organizationId,\n );\n return disposition;\n}\n\nexport async function purgeOrganizationReadModelProjection(\n execSql: ExecSql,\n organizationId: string,\n options: { readonly onlyRequesterUserId?: string } = {},\n): Promise<void> {\n await ensureSqlTables(execSql, organizationReadModelTables);\n await getClientSQLitePersistenceRuntime(execSql).transaction(async (tx) => {\n await purgeOrganizationReadModelProjectionInTransaction({\n onlyRequesterUserId: options.onlyRequesterUserId,\n organizationId,\n tx,\n });\n });\n}\n"]}
1
+ {"version":3,"file":"organizationReadModelPersistence.js","sourceRoot":"","sources":["organizationReadModelPersistence.ts"],"names":[],"mappings":"AAMA,OAAO,EAAE,EAAE,EAAE,MAAM,aAAa,CAAC;AACjC,OAAO,EAAE,qCAAqC,EAAE,MAAM,6CAA6C,CAAC;AACpG,OAAO,EAAE,2BAA2B,EAAE,MAAM,qBAAqB,CAAC;AAClE,OAAO,EAAE,2BAA2B,EAAE,MAAM,iDAAiD,CAAC;AAC9F,OAAO,EACL,mCAAmC,EACnC,2BAA2B,EAC3B,+BAA+B,EAC/B,0BAA0B,GAC3B,MAAM,iDAAiD,CAAC;AACzD,OAAO,EAAE,qBAAqB,EAAE,MAAM,+BAA+B,CAAC;AACtE,OAAO,EAEL,iCAAiC,GAClC,MAAM,uCAAuC,CAAC;AAC/C,OAAO,EAAgB,eAAe,EAAE,MAAM,wBAAwB,CAAC;AACvE,OAAO,EAAE,gDAAgD,EAAE,MAAM,6CAA6C,CAAC;AAC/G,OAAO,EAAE,oCAAoC,EAAE,MAAM,yCAAyC,CAAC;AAC/F,OAAO,EACL,yBAAyB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EAAE,KAAK,CAAC,QAAQ;YACxB,EAAE;SACH,CAAC,CAAC;QACH,MAAM,gCAAgC,CAAC;YACrC,OAAO;YACP,aAAa;YACb,oBAAoB;YACpB,GAAG;YACH,QAAQ,EAAE,KAAK,CAAC,QAAQ;YACxB,EAAE;SACH,CAAC,CAAC;QAEH,OAAO,SAAS,CAAC;IACnB,CAAC,CACF,CAAC;IACF,wEAAwE;IACxE,wEAAwE;IACxE,IAAI,WAAW,KAAK,SAAS;QAC3B,qCAAqC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,kBAAkB,CACrE,KAAK,CAAC,QAAQ,CAAC,cAAc,CAC9B,CAAC;IACJ,OAAO,WAAW,CAAC;AACrB,CAAC;AAED,MAAM,CAAC,KAAK,UAAU,oCAAoC,CACxD,OAAgB,EAChB,cAAsB,EACtB,UAAqD,EAAE;IAEvD,MAAM,eAAe,CAAC,OAAO,EAAE,2BAA2B,CAAC,CAAC;IAC5D,MAAM,iCAAiC,CAAC,OAAO,CAAC,CAAC,WAAW,CAAC,KAAK,EAAE,EAAE,EAAE,EAAE;QACxE,MAAM,iDAAiD,CAAC;YACtD,mBAAmB,EAAE,OAAO,CAAC,mBAAmB;YAChD,cAAc;YACd,EAAE;SACH,CAAC,CAAC;IACL,CAAC,CAAC,CAAC;AACL,CAAC","sourcesContent":["import type {\n ListOrganizationGroupsResponse,\n OrganizationGroupCurrentStateResponse,\n OrganizationReadModelDirectoryResponse,\n OrganizationReadModelResponse,\n} from \"@tearleads/validators/response\";\nimport { eq } from \"drizzle-orm\";\nimport { getOrCreatePrincipalPolicyCoordinator } from \"../../principals/principalPolicyCoordinator\";\nimport { organizationReadModelTables } from \"../../sqlite/schema\";\nimport { organizationDataUsageTables } from \"../../sqlite/schema/organizationDataUsageSchema\";\nimport {\n organizationReadModelDirectoryUsers,\n organizationReadModelGroups,\n organizationReadModelRequesters,\n organizationReadModelState,\n} from \"../../sqlite/schema/organizationReadModelSchema\";\nimport { sqliteInsertBatchSize } from \"../../sqlite/sqliteBindBudget\";\nimport {\n type ClientSQLiteTransactionScope,\n getClientSQLitePersistenceRuntime,\n} from \"../../sqlite/sqlitePersistenceRuntime\";\nimport { type ExecSql, ensureSqlTables } from \"../../sqlite/sqlSchema\";\nimport { clearOrganizationPresentationDenialInTransaction } from \"./organizationPresentationDenialPersistence\";\nimport { applyOrganizationReadModelGrantsLane } from \"./organizationReadModelGrantPersistence\";\nimport {\n applyGroupMembershipsLane,\n assertStoredGroupMembershipBindings,\n OrganizationReadModelBindingError,\n} from \"./organizationReadModelMembershipPersistence\";\nimport {\n loadOrganizationReadModelProjectionInTransaction,\n type OrganizationReadModelProjection,\n} from \"./organizationReadModelProjection\";\nimport {\n loadWithOrganizationReadModelIntegrityPurge,\n pruneInactiveOrganizationRequestersInTransaction,\n purgeOrganizationReadModelProjectionInTransaction,\n} from \"./organizationReadModelPurge\";\nimport { assertOrganizationReadModelResponse } from \"./organizationReadModelResponseAssertions\";\n\nexport type { OrganizationReadModelProjection } from \"./organizationReadModelProjection\";\n\nconst DIRECTORY_INSERT_BATCH_SIZE = sqliteInsertBatchSize(\n organizationReadModelDirectoryUsers,\n);\nconst GROUP_INSERT_BATCH_SIZE = sqliteInsertBatchSize(\n organizationReadModelGroups,\n);\n\ntype ApplyOrganizationReadModelResponseResult =\n | \"already-applied\"\n | \"applied\"\n | \"stale\";\n\ninterface CurrentOrganizationReadModelState {\n readonly cursor: string;\n readonly memberGroupId: string;\n readonly memberGroupStateHash: string;\n readonly organizationHead: OrganizationGroupCurrentStateResponse;\n readonly profileDocumentId: string | null;\n}\n\n/**\n * The member's leave request as stored JSON, kept only when it names this\n * organization and member. Its signature is checked when read, against the\n * member's trusted identity rather than the key served beside it.\n */\nfunction storedLeaveRequestJson(\n organizationId: string,\n user: OrganizationReadModelDirectoryResponse[\"users\"][number],\n): string | null {\n const request = user.leaveRequest;\n return request &&\n request.organizationId === organizationId &&\n request.userId === user.userId\n ? JSON.stringify(request)\n : null;\n}\n\nasync function replaceDirectoryLane(input: {\n readonly directory: OrganizationReadModelDirectoryResponse;\n readonly organizationId: string;\n readonly tx: ClientSQLiteTransactionScope;\n}): Promise<void> {\n await input.tx\n .delete(organizationReadModelDirectoryUsers)\n .where(\n eq(\n organizationReadModelDirectoryUsers.organizationId,\n input.organizationId,\n ),\n )\n .run();\n\n const rows = input.directory.users.map((user, sortOrder) => ({\n organizationId: input.organizationId,\n userId: user.userId,\n sortOrder,\n signingKeyFingerprint: user.signingKeyFingerprint,\n signingPublicKey: user.signingPublicKey,\n encapsulationPublicKey: user.encapsulationPublicKey,\n encapsulationKeyFingerprint: user.encapsulationKeyFingerprint,\n isPersonalOrganizationOwner: user.isPersonalOrganizationOwner,\n createdAt: user.createdAt,\n status: user.status,\n profileDocumentId: user.profileDocumentId,\n joinedAt: user.joinedAt,\n updatedAt: user.updatedAt,\n disabledAt: user.disabledAt,\n disabledByUserId: user.disabledByUserId,\n leaveRequest: storedLeaveRequestJson(input.organizationId, user),\n }));\n for (\n let index = 0;\n index < rows.length;\n index += DIRECTORY_INSERT_BATCH_SIZE\n ) {\n await input.tx\n .insert(organizationReadModelDirectoryUsers)\n .values(rows.slice(index, index + DIRECTORY_INSERT_BATCH_SIZE))\n .run();\n }\n}\n\nasync function upsertRequester(input: {\n readonly currentUserId: string;\n readonly isOrgAdmin: boolean;\n readonly now: string;\n readonly organizationId: string;\n readonly tx: ClientSQLiteTransactionScope;\n}): Promise<void> {\n const requesterRow = {\n organizationId: input.organizationId,\n userId: input.currentUserId,\n isOrgAdmin: input.isOrgAdmin,\n updatedAt: input.now,\n };\n await input.tx\n .insert(organizationReadModelRequesters)\n .values(requesterRow)\n .onConflictDoUpdate({\n target: [\n organizationReadModelRequesters.organizationId,\n organizationReadModelRequesters.userId,\n ],\n set: {\n isOrgAdmin: requesterRow.isOrgAdmin,\n updatedAt: requesterRow.updatedAt,\n },\n })\n .run();\n // Storing an authoritative response proves access: retire the durable\n // denial marker for this scope in the same transaction.\n await clearOrganizationPresentationDenialInTransaction({\n organizationId: input.organizationId,\n projection: \"readModel\",\n requesterUserId: input.currentUserId,\n tx: input.tx,\n });\n}\n\nasync function replaceGroupsLane(input: {\n readonly groups: ListOrganizationGroupsResponse;\n readonly organizationId: string;\n readonly tx: ClientSQLiteTransactionScope;\n}): Promise<void> {\n // Hydrated names and delivered membership heads outlive a catalog\n // replacement; the groupMemberships lane rebinds any head that changed.\n const previousGroups = await input.tx\n .select({\n groupId: organizationReadModelGroups.groupId,\n membersStateHash: organizationReadModelGroups.membersStateHash,\n name: organizationReadModelGroups.name,\n })\n .from(organizationReadModelGroups)\n .where(\n eq(organizationReadModelGroups.organizationId, input.organizationId),\n );\n const previousById = new Map(\n previousGroups.map((group) => [group.groupId, group]),\n );\n await input.tx\n .delete(organizationReadModelGroups)\n .where(eq(organizationReadModelGroups.organizationId, input.organizationId))\n .run();\n\n const rows = input.groups.groups.map((group, sortOrder) => ({\n organizationId: input.organizationId,\n groupId: group.groupId,\n sortOrder,\n name: previousById.get(group.groupId)?.name ?? \"\",\n createdAt: group.createdAt,\n isBuiltin: group.isBuiltin,\n stateHash: group.currentState?.stateHash ?? null,\n stateVersion: group.currentState?.version ?? null,\n keyEpoch: group.currentState?.keyEpoch ?? null,\n keyFingerprint: group.currentState?.keyFingerprint ?? null,\n memberCount: group.currentState?.memberCount ?? null,\n membersStateHash: previousById.get(group.groupId)?.membersStateHash ?? null,\n }));\n for (let index = 0; index < rows.length; index += GROUP_INSERT_BATCH_SIZE) {\n await input.tx\n .insert(organizationReadModelGroups)\n .values(rows.slice(index, index + GROUP_INSERT_BATCH_SIZE))\n .run();\n }\n}\n\nasync function loadCurrentState(\n tx: ClientSQLiteTransactionScope,\n organizationId: string,\n): Promise<CurrentOrganizationReadModelState | null> {\n const [current] = await tx\n .select({\n cursor: organizationReadModelState.cursor,\n keyEpoch: organizationReadModelState.organizationKeyEpoch,\n keyFingerprint: organizationReadModelState.organizationKeyFingerprint,\n memberCount: organizationReadModelState.organizationMemberCount,\n memberGroupId: organizationReadModelState.memberGroupId,\n memberGroupStateHash: organizationReadModelState.memberGroupStateHash,\n profileDocumentId: organizationReadModelState.profileDocumentId,\n stateHash: organizationReadModelState.organizationStateHash,\n version: organizationReadModelState.organizationStateVersion,\n })\n .from(organizationReadModelState)\n .where(eq(organizationReadModelState.organizationId, organizationId))\n .limit(1);\n if (!current) {\n return null;\n }\n const { keyEpoch, keyFingerprint, memberCount, stateHash, version, ...rest } =\n current;\n return {\n ...rest,\n organizationHead: {\n keyEpoch,\n keyFingerprint,\n memberCount,\n stateHash,\n version,\n },\n };\n}\n\nfunction resolveApplyDisposition(input: {\n readonly current: CurrentOrganizationReadModelState | null;\n readonly requestedCursor: string | null;\n readonly response: OrganizationReadModelResponse;\n}): ApplyOrganizationReadModelResponseResult | null {\n const currentCursor = input.current?.cursor ?? null;\n if (currentCursor !== input.requestedCursor) {\n return currentCursor === input.response.nextCursor\n ? \"already-applied\"\n : \"stale\";\n }\n if (!input.current && input.response.mode !== \"snapshot\") {\n throw new Error(\"Organization read-model delta requires a local snapshot\");\n }\n return null;\n}\n\ninterface ResponseLanesInput {\n readonly current: CurrentOrganizationReadModelState | null;\n readonly memberGroupId: string;\n readonly response: OrganizationReadModelResponse;\n readonly tx: ClientSQLiteTransactionScope;\n}\n\n/** Apply every carried lane and return the reserved Members head. */\nasync function replaceResponseLanes(\n input: ResponseLanesInput,\n): Promise<string | null> {\n const { organizationId } = input.response;\n const directory = input.response.lanes.directory;\n if (directory) {\n await replaceDirectoryLane({ directory, organizationId, tx: input.tx });\n }\n const groups = input.response.lanes.groups;\n if (groups) {\n await replaceGroupsLane({ groups, organizationId, tx: input.tx });\n }\n const groupMemberships = input.response.lanes.groupMemberships;\n const memberGroupStateHash = groupMemberships\n ? await applyGroupMembershipsLane({\n currentMemberGroupStateHash:\n input.current?.memberGroupStateHash ?? null,\n lane: groupMemberships,\n memberGroupId: input.memberGroupId,\n organizationId,\n replaceAll: input.response.mode === \"snapshot\",\n tx: input.tx,\n })\n : (input.current?.memberGroupStateHash ?? null);\n const grants = input.response.lanes.grants;\n if (grants) {\n await applyOrganizationReadModelGrantsLane({\n lane: grants,\n organizationId,\n tx: input.tx,\n });\n }\n return memberGroupStateHash;\n}\n\nasync function applyResponseLanes(\n input: ResponseLanesInput & { readonly currentUserId: string },\n): Promise<string | null> {\n const memberGroupStateHash = await replaceResponseLanes(input);\n // The directory lane is the authoritative roster, already persisted above:\n // requester rows for users it no longer lists as active fall with it.\n if (input.response.lanes.directory) {\n await pruneInactiveOrganizationRequestersInTransaction({\n organizationId: input.response.organizationId,\n retainUserId: input.currentUserId,\n tx: input.tx,\n });\n }\n if (input.response.lanes.groups || input.response.lanes.groupMemberships) {\n await assertStoredGroupMembershipBindings({\n memberGroupId: input.memberGroupId,\n memberGroupStateHash,\n organizationId: input.response.organizationId,\n tx: input.tx,\n });\n }\n return memberGroupStateHash;\n}\n\n/**\n * Write the cursor with the organization policy head and the reserved Members\n * head in one row, so a failure anywhere in the page rolls them back together.\n */\nasync function upsertOrganizationReadModelState(input: {\n readonly current: CurrentOrganizationReadModelState | null;\n readonly memberGroupId: string;\n readonly memberGroupStateHash: string | null;\n readonly now: string;\n readonly response: OrganizationReadModelResponse;\n readonly tx: ClientSQLiteTransactionScope;\n}): Promise<void> {\n const organizationHead =\n input.response.lanes.organizationPolicy?.currentState ??\n input.current?.organizationHead;\n if (!organizationHead || input.memberGroupStateHash === null) {\n throw new OrganizationReadModelBindingError(\n \"Organization read-model policy or Members head is missing\",\n );\n }\n const directoryLane = input.response.lanes.directory;\n const values = {\n cursor: input.response.nextCursor,\n profileDocumentId:\n directoryLane !== undefined\n ? directoryLane.profileDocumentId\n : (input.current?.profileDocumentId ?? null),\n memberGroupId: input.memberGroupId,\n memberGroupStateHash: input.memberGroupStateHash,\n organizationStateHash: organizationHead.stateHash,\n organizationStateVersion: organizationHead.version,\n organizationKeyEpoch: organizationHead.keyEpoch,\n organizationKeyFingerprint: organizationHead.keyFingerprint,\n organizationMemberCount: organizationHead.memberCount,\n updatedAt: input.now,\n };\n await input.tx\n .insert(organizationReadModelState)\n .values({ ...values, organizationId: input.response.organizationId })\n .onConflictDoUpdate({\n target: organizationReadModelState.organizationId,\n set: values,\n })\n .run();\n}\n\nfunction requireMemberGroupId(input: {\n readonly current: CurrentOrganizationReadModelState | null;\n readonly response: OrganizationReadModelResponse;\n}): string {\n const memberGroupId =\n input.response.lanes.groups?.memberGroupId ?? input.current?.memberGroupId;\n if (!memberGroupId) {\n throw new Error(\"Organization read-model member group is missing\");\n }\n return memberGroupId;\n}\n\nexport async function loadOrganizationReadModelProjection(\n execSql: ExecSql,\n organizationId: string,\n currentUserId: string,\n): Promise<OrganizationReadModelProjection | null> {\n return loadWithOrganizationReadModelIntegrityPurge({\n execSql,\n organizationId,\n load: (tx) =>\n loadOrganizationReadModelProjectionInTransaction({\n currentUserId,\n organizationId,\n tx,\n }),\n });\n}\n\nexport async function applyOrganizationReadModelResponse(input: {\n readonly currentUserId: string;\n readonly execSql: ExecSql;\n readonly requestedCursor: string | null;\n readonly response: OrganizationReadModelResponse;\n}): Promise<ApplyOrganizationReadModelResponseResult> {\n assertOrganizationReadModelResponse({\n currentUserId: input.currentUserId,\n response: input.response,\n });\n // The requester prune below also retires pruned users' usage projections.\n await ensureSqlTables(input.execSql, [\n ...organizationReadModelTables,\n ...organizationDataUsageTables,\n ]);\n\n const disposition = await getClientSQLitePersistenceRuntime(\n input.execSql,\n ).transaction(\n async (tx): Promise<ApplyOrganizationReadModelResponseResult> => {\n const current = await loadCurrentState(tx, input.response.organizationId);\n const disposition = resolveApplyDisposition({\n current,\n requestedCursor: input.requestedCursor,\n response: input.response,\n });\n if (disposition === \"stale\") {\n return disposition;\n }\n const now = new Date().toISOString();\n await upsertRequester({\n currentUserId: input.currentUserId,\n isOrgAdmin: input.response.currentUser.isOrgAdmin,\n now,\n organizationId: input.response.organizationId,\n tx,\n });\n if (disposition === \"already-applied\") {\n return disposition;\n }\n const memberGroupId = requireMemberGroupId({\n current,\n response: input.response,\n });\n const memberGroupStateHash = await applyResponseLanes({\n current,\n currentUserId: input.currentUserId,\n memberGroupId,\n response: input.response,\n tx,\n });\n await upsertOrganizationReadModelState({\n current,\n memberGroupId,\n memberGroupStateHash,\n now,\n response: input.response,\n tx,\n });\n\n return \"applied\";\n },\n );\n // An applied change follows an organization hint or mutation; in-flight\n // operations recover the directory again instead of reusing their memo.\n if (disposition === \"applied\")\n getOrCreatePrincipalPolicyCoordinator(input.execSql).invalidateRecovery(\n input.response.organizationId,\n );\n return disposition;\n}\n\nexport async function purgeOrganizationReadModelProjection(\n execSql: ExecSql,\n organizationId: string,\n options: { readonly onlyRequesterUserId?: string } = {},\n): Promise<void> {\n await ensureSqlTables(execSql, organizationReadModelTables);\n await getClientSQLitePersistenceRuntime(execSql).transaction(async (tx) => {\n await purgeOrganizationReadModelProjectionInTransaction({\n onlyRequesterUserId: options.onlyRequesterUserId,\n organizationId,\n tx,\n });\n });\n}\n"]}
@@ -1,4 +1,5 @@
1
1
  import { compareCanonicalStrings } from "../../../internal/crypto/index.js";
2
+ import { isOrganizationLeaveRequest, } from "../../../internal/validators/util/index.js";
2
3
  import { and, asc, eq } from "drizzle-orm";
3
4
  import { organizationReadModelDirectoryUsers, organizationReadModelGroupMembers, organizationReadModelGroups, organizationReadModelRequesters, organizationReadModelState, } from "../../sqlite/schema/organizationReadModelSchema.js";
4
5
  import { loadOrganizationReadModelGrantsInTransaction } from "./organizationReadModelGrantPersistence.js";
@@ -22,11 +23,21 @@ function toDirectoryUser(row, currentUserId) {
22
23
  status: row.status,
23
24
  profileDocumentId: row.profileDocumentId,
24
25
  joinedAt: row.joinedAt,
26
+ leaveRequest: readStoredLeaveRequest(row.leaveRequest),
25
27
  updatedAt: row.updatedAt,
26
28
  disabledAt: row.disabledAt,
27
29
  disabledByUserId: row.disabledByUserId,
28
30
  };
29
31
  }
32
+ function readStoredLeaveRequest(stored) {
33
+ if (stored === null)
34
+ return null;
35
+ const parsed = JSON.parse(stored);
36
+ if (!isOrganizationLeaveRequest(parsed)) {
37
+ throw new OrganizationReadModelIntegrityError("Stored organization leave request is invalid");
38
+ }
39
+ return parsed;
40
+ }
30
41
  function isValidPolicyHead(head) {
31
42
  return (head.stateHash.length > 0 &&
32
43
  Number.isInteger(head.version) &&
@@ -107,6 +118,7 @@ async function loadDirectoryRows(tx, organizationId) {
107
118
  encapsulationKeyFingerprint: organizationReadModelDirectoryUsers.encapsulationKeyFingerprint,
108
119
  encapsulationPublicKey: organizationReadModelDirectoryUsers.encapsulationPublicKey,
109
120
  joinedAt: organizationReadModelDirectoryUsers.joinedAt,
121
+ leaveRequest: organizationReadModelDirectoryUsers.leaveRequest,
110
122
  isPersonalOrganizationOwner: organizationReadModelDirectoryUsers.isPersonalOrganizationOwner,
111
123
  profileDocumentId: organizationReadModelDirectoryUsers.profileDocumentId,
112
124
  signingKeyFingerprint: organizationReadModelDirectoryUsers.signingKeyFingerprint,
@@ -1 +1 @@
1
- {"version":3,"file":"organizationReadModelProjection.js","sourceRoot":"","sources":["organizationReadModelProjection.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,uBAAuB,EAAE,MAAM,mBAAmB,CAAC;AAS5D,OAAO,EAAE,GAAG,EAAE,GAAG,EAAE,EAAE,EAAE,MAAM,aAAa,CAAC;AAC3C,OAAO,EACL,mCAAmC,EACnC,iCAAiC,EACjC,2BAA2B,EAC3B,+BAA+B,EAC/B,0BAA0B,GAC3B,MAAM,iDAAiD,CAAC;AAEzD,OAAO,EAAE,4CAA4C,EAAE,MAAM,yCAAyC,CAAC;AACvG,OAAO,EACL,wCAAwC,EACxC,mCAAmC,GACpC,MAAM,iCAAiC,CAAC;AA6EzC,SAAS,0BAA0B,CACjC,KAAa;IAEb,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,KAAK,UAAU,CAAC;AACpD,CAAC;AAED,SAAS,eAAe,CACtB,GAA0B,EAC1B,aAAqB;IAErB,IAAI,CAAC,0BAA0B,CAAC,G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AM;QACN,MAAM,EAAE;YACN,cAAc,EAAE,KAAK,CAAC,cAAc;YACpC,aAAa,EAAE,KAAK,CAAC,aAAa;YAClC,MAAM;SACP;QACD,eAAe;QACf,cAAc,EAAE,KAAK,CAAC,cAAc;QACpC,WAAW;QACX,eAAe,EAAE,wCAAwC;QACzD,SAAS,EAAE,SAAS,CAAC,CAAC,CAAC,EAAE,UAAU,EAAE,SAAS,CAAC,UAAU,EAAE,CAAC,CAAC,CAAC,IAAI;QAClE,SAAS,EAAE,KAAK,CAAC,SAAS;KAC3B,CAAC;AACJ,CAAC","sourcesContent":["import { compareCanonicalStrings } from \"@tearleads/crypto\";\nimport type {\n ListOrganizationGroupsResponse,\n OrganizationContainerGrantsResponse,\n OrganizationDirectoryResponse,\n OrganizationDirectoryUserResponse,\n OrganizationGroupCurrentStateResponse,\n OrganizationRosterStatus,\n} from \"@tearleads/validators/response\";\nimport { and, asc, eq } from \"drizzle-orm\";\nimport {\n organizationReadModelDirectoryUsers,\n organizationReadModelGroupMembers,\n organizationReadModelGroups,\n organizationReadModelRequesters,\n organizationReadModelState,\n} from \"../../sqlite/schema/organizationReadModelSchema\";\nimport type { ClientSQLiteTransactionScope } from \"../../sqlite/sqlitePersistenceRuntime\";\nimport { loadOrganizationReadModelGrantsInTransaction } from \"./organizationReadModelGrantPersistence\";\nimport {\n ORGANIZATION_READ_MODEL_PROTOCOL_VERSION,\n OrganizationReadModelIntegrityError,\n} from \"./organizationReadModelProtocol\";\n\nexport type OrganizationDirectoryProjection = Omit<\n OrganizationDirectoryResponse,\n \"currentUser\"\n>;\n\nexport interface OrganizationReadModelProjection {\n readonly cursor: string;\n readonly directory: OrganizationDirectoryProjection;\n readonly grants: OrganizationContainerGrantsResponse;\n readonly groups: Omit<ListOrganizationGroupsResponse, \"groups\"> & {\n groups: Array<\n ListOrganizationGroupsResponse[\"groups\"][number] & { name: string }\n >;\n };\n readonly membershipEdges: OrganizationReadModelMembershipEdge[];\n readonly organizationId: string;\n readonly policyHeads: readonly OrganizationReadModelPolicyHead[];\n readonly protocolVersion: typeof ORGANIZATION_READ_MODEL_PROTOCOL_VERSION;\n readonly requester: OrganizationDirectoryResponse[\"currentUser\"] | null;\n readonly updatedAt: string;\n}\n\nexport interface OrganizationReadModelPolicyHead {\n readonly keyEpoch: number;\n readonly keyFingerprint: string;\n readonly memberCount: number;\n readonly organizationId: string;\n readonly principalId: string;\n readonly principalType: \"group\" | \"organization\";\n readonly stateHash: string;\n readonly version: number;\n}\n\nexport interface OrganizationReadModelMembershipEdge {\n readonly groupId: string;\n readonly userId: string;\n}\n\ninterface SelectedDirectoryUser {\n readonly createdAt: string;\n readonly disabledAt: string | null;\n readonly disabledByUserId: string | null;\n readonly encapsulationKeyFingerprint: string;\n readonly encapsulationPublicKey: string;\n readonly isPersonalOrganizationOwner: boolean;\n readonly joinedAt: string;\n readonly profileDocumentId: string | null;\n readonly signingKeyFingerprint: string;\n readonly signingPublicKey: string;\n readonly status: string;\n readonly updatedAt: string;\n readonly userId: string;\n}\n\ninterface SelectedGroup {\n readonly createdAt: string;\n readonly groupId: string;\n readonly isBuiltin: boolean;\n readonly keyEpoch: number | null;\n readonly keyFingerprint: string | null;\n readonly memberCount: number | null;\n readonly name: string;\n readonly stateHash: string | null;\n readonly stateVersion: number | null;\n}\n\n/** A stored policy head before validation; `version` is the state version. */\ninterface StoredPolicyHead {\n readonly keyEpoch: number;\n readonly keyFingerprint: string;\n readonly memberCount: number;\n readonly stateHash: string;\n readonly version: number;\n}\n\nfunction isOrganizationRosterStatus(\n value: string,\n): value is OrganizationRosterStatus {\n return value === \"active\" || value === \"disabled\";\n}\n\nfunction toDirectoryUser(\n row: SelectedDirectoryUser,\n currentUserId: string,\n): OrganizationDirectoryUserResponse {\n if (!isOrganizationRosterStatus(row.status)) {\n throw new OrganizationReadModelIntegrityError(\n \"Stored organization directory status is invalid\",\n );\n }\n\n return {\n userId: row.userId,\n signingKeyFingerprint: row.signingKeyFingerprint,\n signingPublicKey: row.signingPublicKey,\n encapsulationPublicKey: row.encapsulationPublicKey,\n encapsulationKeyFingerprint: row.encapsulationKeyFingerprint,\n createdAt: row.createdAt,\n isPersonalOrganizationOwner: row.isPersonalOrganizationOwner,\n isSelf: row.userId === currentUserId,\n status: row.status,\n profileDocumentId: row.profileDocumentId,\n joinedAt: row.joinedAt,\n updatedAt: row.updatedAt,\n disabledAt: row.disabledAt,\n disabledByUserId: row.disabledByUserId,\n };\n}\n\nfunction isValidPolicyHead(head: StoredPolicyHead): boolean {\n return (\n head.stateHash.length > 0 &&\n Number.isInteger(head.version) &&\n head.version > 0 &&\n Number.isSafeInteger(head.keyEpoch) &&\n head.keyEpoch > 0 &&\n head.keyFingerprint.length > 0 &&\n Number.isInteger(head.memberCount) &&\n head.memberCount >= 0\n );\n}\n\n/** A group's state columns are all null (stateless) or one valid head. */\nfunction toGroupCurrentState(\n row: SelectedGroup,\n): OrganizationGroupCurrentStateResponse | null {\n const values = [\n row.stateHash,\n row.stateVersion,\n row.keyEpoch,\n row.keyFingerprint,\n row.memberCount,\n ];\n if (values.every((value) => value === null)) {\n return null;\n }\n const head =\n row.stateHash === null ||\n row.stateVersion === null ||\n row.keyEpoch === null ||\n row.keyFingerprint === null ||\n row.memberCount === null\n ? null\n : {\n stateHash: row.stateHash,\n version: row.stateVersion,\n keyEpoch: row.keyEpoch,\n keyFingerprint: row.keyFingerprint,\n memberCount: row.memberCount,\n };\n if (!head || !isValidPolicyHead(head)) {\n throw new OrganizationReadModelIntegrityError(\n \"Stored organization group state is invalid\",\n );\n }\n return head;\n}\n\nfunction toOrganizationPolicyHead(\n organizationId: string,\n head: StoredPolicyHead,\n): OrganizationReadModelPolicyHead {\n if (!isValidPolicyHead(head)) {\n throw new OrganizationReadModelIntegrityError(\n \"Stored organization policy head is invalid\",\n );\n }\n return {\n ...head,\n organizationId,\n principalId: organizationId,\n principalType: \"organization\",\n };\n}\n\n/** The organization head from the state row plus every stateful group head. */\nfunction toProjectionPolicyHeads(input: {\n readonly groups: ReadonlyArray<{\n readonly currentState: OrganizationGroupCurrentStateResponse | null;\n readonly groupId: string;\n }>;\n readonly organizationHead: StoredPolicyHead;\n readonly organizationId: string;\n}): OrganizationReadModelPolicyHead[] {\n const groupHeads = input.groups\n .flatMap((group): OrganizationReadModelPolicyHead[] =>\n group.currentState\n ? [\n {\n ...group.currentState,\n organizationId: input.organizationId,\n principalId: group.groupId,\n principalType: \"group\",\n },\n ]\n : [],\n )\n .sort((left, right) =>\n compareCanonicalStrings(left.principalId, right.principalId),\n );\n // Group heads precede the organization head, ordered by principal ID.\n return [\n ...groupHeads,\n toOrganizationPolicyHead(input.organizationId, input.organizationHead),\n ];\n}\n\nasync function loadDirectoryRows(\n tx: ClientSQLiteTransactionScope,\n organizationId: string,\n): Promise<SelectedDirectoryUser[]> {\n return tx\n .select({\n createdAt: organizationReadModelDirectoryUsers.createdAt,\n disabledAt: organizationReadModelDirectoryUsers.disabledAt,\n disabledByUserId: organizationReadModelDirectoryUsers.disabledByUserId,\n encapsulationKeyFingerprint:\n organizationReadModelDirectoryUsers.encapsulationKeyFingerprint,\n encapsulationPublicKey:\n organizationReadModelDirectoryUsers.encapsulationPublicKey,\n joinedAt: organizationReadModelDirectoryUsers.joinedAt,\n isPersonalOrganizationOwner:\n organizationReadModelDirectoryUsers.isPersonalOrganizationOwner,\n profileDocumentId: organizationReadModelDirectoryUsers.profileDocumentId,\n signingKeyFingerprint:\n organizationReadModelDirectoryUsers.signingKeyFingerprint,\n signingPublicKey: organizationReadModelDirectoryUsers.signingPublicKey,\n status: organizationReadModelDirectoryUsers.status,\n updatedAt: organizationReadModelDirectoryUsers.updatedAt,\n userId: organizationReadModelDirectoryUsers.userId,\n })\n .from(organizationReadModelDirectoryUsers)\n .where(\n eq(organizationReadModelDirectoryUsers.organizationId, organizationId),\n )\n .orderBy(\n asc(organizationReadModelDirectoryUsers.sortOrder),\n asc(organizationReadModelDirectoryUsers.userId),\n );\n}\n\nasync function loadGroupRows(\n tx: ClientSQLiteTransactionScope,\n organizationId: string,\n): Promise<SelectedGroup[]> {\n return tx\n .select({\n createdAt: organizationReadModelGroups.createdAt,\n groupId: organizationReadModelGroups.groupId,\n isBuiltin: organizationReadModelGroups.isBuiltin,\n keyEpoch: organizationReadModelGroups.keyEpoch,\n keyFingerprint: organizationReadModelGroups.keyFingerprint,\n memberCount: organizationReadModelGroups.memberCount,\n name: organizationReadModelGroups.name,\n stateHash: organizationReadModelGroups.stateHash,\n stateVersion: organizationReadModelGroups.stateVersion,\n })\n .from(organizationReadModelGroups)\n .where(eq(organizationReadModelGroups.organizationId, organizationId))\n .orderBy(\n asc(organizationReadModelGroups.sortOrder),\n asc(organizationReadModelGroups.groupId),\n );\n}\n\nasync function loadMembershipEdges(\n tx: ClientSQLiteTransactionScope,\n organizationId: string,\n): Promise<OrganizationReadModelMembershipEdge[]> {\n return tx\n .select({\n groupId: organizationReadModelGroupMembers.groupId,\n userId: organizationReadModelGroupMembers.userId,\n })\n .from(organizationReadModelGroupMembers)\n .where(eq(organizationReadModelGroupMembers.organizationId, organizationId))\n .orderBy(\n asc(organizationReadModelGroupMembers.groupId),\n asc(organizationReadModelGroupMembers.sortOrder),\n asc(organizationReadModelGroupMembers.userId),\n );\n}\n\nexport async function loadOrganizationReadModelProjectionInTransaction(input: {\n readonly currentUserId: string;\n readonly organizationId: string;\n readonly tx: ClientSQLiteTransactionScope;\n}): Promise<OrganizationReadModelProjection | null> {\n const [state] = await input.tx\n .select({\n cursor: organizationReadModelState.cursor,\n memberGroupId: organizationReadModelState.memberGroupId,\n organizationKeyEpoch: organizationReadModelState.organizationKeyEpoch,\n organizationKeyFingerprint:\n organizationReadModelState.organizationKeyFingerprint,\n organizationMemberCount:\n organizationReadModelState.organizationMemberCount,\n organizationStateHash: organizationReadModelState.organizationStateHash,\n organizationStateVersion:\n organizationReadModelState.organizationStateVersion,\n profileDocumentId: organizationReadModelState.profileDocumentId,\n updatedAt: organizationReadModelState.updatedAt,\n })\n .from(organizationReadModelState)\n .where(eq(organizationReadModelState.organizationId, input.organizationId))\n .limit(1);\n if (!state) {\n return null;\n }\n const [requester] = await input.tx\n .select({ isOrgAdmin: organizationReadModelRequesters.isOrgAdmin })\n .from(organizationReadModelRequesters)\n .where(\n and(\n eq(\n organizationReadModelRequesters.organizationId,\n input.organizationId,\n ),\n eq(organizationReadModelRequesters.userId, input.currentUserId),\n ),\n )\n .limit(1);\n const directoryRows = await loadDirectoryRows(input.tx, input.organizationId);\n const groupRows = await loadGroupRows(input.tx, input.organizationId);\n const grants = await loadOrganizationReadModelGrantsInTransaction(input);\n const membershipEdges = await loadMembershipEdges(\n input.tx,\n input.organizationId,\n );\n const groups = groupRows.map((row) => ({\n groupId: row.groupId,\n organizationId: input.organizationId,\n name: row.name,\n createdAt: row.createdAt,\n isBuiltin: row.isBuiltin,\n currentState: toGroupCurrentState(row),\n }));\n const policyHeads = toProjectionPolicyHeads({\n groups,\n organizationHead: {\n keyEpoch: state.organizationKeyEpoch,\n keyFingerprint: state.organizationKeyFingerprint,\n memberCount: state.organizationMemberCount,\n stateHash: state.organizationStateHash,\n version: state.organizationStateVersion,\n },\n organizationId: input.organizationId,\n });\n\n return {\n cursor: state.cursor,\n directory: {\n organizationId: input.organizationId,\n profileDocumentId: state.profileDocumentId,\n users: directoryRows.map((row) =>\n toDirectoryUser(row, input.currentUserId),\n ),\n },\n grants,\n groups: {\n organizationId: input.organizationId,\n memberGroupId: state.memberGroupId,\n groups,\n },\n membershipEdges,\n organizationId: input.organizationId,\n policyHeads,\n protocolVersion: ORGANIZATION_READ_MODEL_PROTOCOL_VERSION,\n requester: requester ? { isOrgAdmin: requester.isOrgAdmin } : null,\n updatedAt: state.updatedAt,\n };\n}\n"]}
1
+ {"version":3,"file":"organizationReadModelProjection.js","sourceRoot":"","sources":["organizationReadModelProjection.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,uBAAuB,EAAE,MAAM,mBAAmB,CAAC;AAS5D,OAAO,EACL,0BAA0B,GAE3B,MAAM,4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E,KAAK,CAAC,SAAS;KAC3B,CAAC;AACJ,CAAC","sourcesContent":["import { compareCanonicalStrings } from \"@tearleads/crypto\";\nimport type {\n ListOrganizationGroupsResponse,\n OrganizationContainerGrantsResponse,\n OrganizationDirectoryResponse,\n OrganizationDirectoryUserResponse,\n OrganizationGroupCurrentStateResponse,\n OrganizationRosterStatus,\n} from \"@tearleads/validators/response\";\nimport {\n isOrganizationLeaveRequest,\n type OrganizationLeaveRequest,\n} from \"@tearleads/validators/util\";\nimport { and, asc, eq } from \"drizzle-orm\";\nimport {\n organizationReadModelDirectoryUsers,\n organizationReadModelGroupMembers,\n organizationReadModelGroups,\n organizationReadModelRequesters,\n organizationReadModelState,\n} from \"../../sqlite/schema/organizationReadModelSchema\";\nimport type { ClientSQLiteTransactionScope } from \"../../sqlite/sqlitePersistenceRuntime\";\nimport { loadOrganizationReadModelGrantsInTransaction } from \"./organizationReadModelGrantPersistence\";\nimport {\n ORGANIZATION_READ_MODEL_PROTOCOL_VERSION,\n OrganizationReadModelIntegrityError,\n} from \"./organizationReadModelProtocol\";\n\nexport type OrganizationDirectoryProjection = Omit<\n OrganizationDirectoryResponse,\n \"currentUser\"\n>;\n\nexport interface OrganizationReadModelProjection {\n readonly cursor: string;\n readonly directory: OrganizationDirectoryProjection;\n readonly grants: OrganizationContainerGrantsResponse;\n readonly groups: Omit<ListOrganizationGroupsResponse, \"groups\"> & {\n groups: Array<\n ListOrganizationGroupsResponse[\"groups\"][number] & { name: string }\n >;\n };\n readonly membershipEdges: OrganizationReadModelMembershipEdge[];\n readonly organizationId: string;\n readonly policyHeads: readonly OrganizationReadModelPolicyHead[];\n readonly protocolVersion: typeof ORGANIZATION_READ_MODEL_PROTOCOL_VERSION;\n readonly requester: OrganizationDirectoryResponse[\"currentUser\"] | null;\n readonly updatedAt: string;\n}\n\nexport interface OrganizationReadModelPolicyHead {\n readonly keyEpoch: number;\n readonly keyFingerprint: string;\n readonly memberCount: number;\n readonly organizationId: string;\n readonly principalId: string;\n readonly principalType: \"group\" | \"organization\";\n readonly stateHash: string;\n readonly version: number;\n}\n\nexport interface OrganizationReadModelMembershipEdge {\n readonly groupId: string;\n readonly userId: string;\n}\n\ninterface SelectedDirectoryUser {\n readonly createdAt: string;\n readonly disabledAt: string | null;\n readonly disabledByUserId: string | null;\n readonly encapsulationKeyFingerprint: string;\n readonly encapsulationPublicKey: string;\n readonly isPersonalOrganizationOwner: boolean;\n readonly joinedAt: string;\n readonly leaveRequest: string | null;\n readonly profileDocumentId: string | null;\n readonly signingKeyFingerprint: string;\n readonly signingPublicKey: string;\n readonly status: string;\n readonly updatedAt: string;\n readonly userId: string;\n}\n\ninterface SelectedGroup {\n readonly createdAt: string;\n readonly groupId: string;\n readonly isBuiltin: boolean;\n readonly keyEpoch: number | null;\n readonly keyFingerprint: string | null;\n readonly memberCount: number | null;\n readonly name: string;\n readonly stateHash: string | null;\n readonly stateVersion: number | null;\n}\n\n/** A stored policy head before validation; `version` is the state version. */\ninterface StoredPolicyHead {\n readonly keyEpoch: number;\n readonly keyFingerprint: string;\n readonly memberCount: number;\n readonly stateHash: string;\n readonly version: number;\n}\n\nfunction isOrganizationRosterStatus(\n value: string,\n): value is OrganizationRosterStatus {\n return value === \"active\" || value === \"disabled\";\n}\n\nfunction toDirectoryUser(\n row: SelectedDirectoryUser,\n currentUserId: string,\n): OrganizationDirectoryUserResponse {\n if (!isOrganizationRosterStatus(row.status)) {\n throw new OrganizationReadModelIntegrityError(\n \"Stored organization directory status is invalid\",\n );\n }\n\n return {\n userId: row.userId,\n signingKeyFingerprint: row.signingKeyFingerprint,\n signingPublicKey: row.signingPublicKey,\n encapsulationPublicKey: row.encapsulationPublicKey,\n encapsulationKeyFingerprint: row.encapsulationKeyFingerprint,\n createdAt: row.createdAt,\n isPersonalOrganizationOwner: row.isPersonalOrganizationOwner,\n isSelf: row.userId === currentUserId,\n status: row.status,\n profileDocumentId: row.profileDocumentId,\n joinedAt: row.joinedAt,\n leaveRequest: readStoredLeaveRequest(row.leaveRequest),\n updatedAt: row.updatedAt,\n disabledAt: row.disabledAt,\n disabledByUserId: row.disabledByUserId,\n };\n}\n\nfunction readStoredLeaveRequest(\n stored: string | null,\n): OrganizationLeaveRequest | null {\n if (stored === null) return null;\n const parsed: unknown = JSON.parse(stored);\n if (!isOrganizationLeaveRequest(parsed)) {\n throw new OrganizationReadModelIntegrityError(\n \"Stored organization leave request is invalid\",\n );\n }\n return parsed;\n}\n\nfunction isValidPolicyHead(head: StoredPolicyHead): boolean {\n return (\n head.stateHash.length > 0 &&\n Number.isInteger(head.version) &&\n head.version > 0 &&\n Number.isSafeInteger(head.keyEpoch) &&\n head.keyEpoch > 0 &&\n head.keyFingerprint.length > 0 &&\n Number.isInteger(head.memberCount) &&\n head.memberCount >= 0\n );\n}\n\n/** A group's state columns are all null (stateless) or one valid head. */\nfunction toGroupCurrentState(\n row: SelectedGroup,\n): OrganizationGroupCurrentStateResponse | null {\n const values = [\n row.stateHash,\n row.stateVersion,\n row.keyEpoch,\n row.keyFingerprint,\n row.memberCount,\n ];\n if (values.every((value) => value === null)) {\n return null;\n }\n const head =\n row.stateHash === null ||\n row.stateVersion === null ||\n row.keyEpoch === null ||\n row.keyFingerprint === null ||\n row.memberCount === null\n ? null\n : {\n stateHash: row.stateHash,\n version: row.stateVersion,\n keyEpoch: row.keyEpoch,\n keyFingerprint: row.keyFingerprint,\n memberCount: row.memberCount,\n };\n if (!head || !isValidPolicyHead(head)) {\n throw new OrganizationReadModelIntegrityError(\n \"Stored organization group state is invalid\",\n );\n }\n return head;\n}\n\nfunction toOrganizationPolicyHead(\n organizationId: string,\n head: StoredPolicyHead,\n): OrganizationReadModelPolicyHead {\n if (!isValidPolicyHead(head)) {\n throw new OrganizationReadModelIntegrityError(\n \"Stored organization policy head is invalid\",\n );\n }\n return {\n ...head,\n organizationId,\n principalId: organizationId,\n principalType: \"organization\",\n };\n}\n\n/** The organization head from the state row plus every stateful group head. */\nfunction toProjectionPolicyHeads(input: {\n readonly groups: ReadonlyArray<{\n readonly currentState: OrganizationGroupCurrentStateResponse | null;\n readonly groupId: string;\n }>;\n readonly organizationHead: StoredPolicyHead;\n readonly organizationId: string;\n}): OrganizationReadModelPolicyHead[] {\n const groupHeads = input.groups\n .flatMap((group): OrganizationReadModelPolicyHead[] =>\n group.currentState\n ? [\n {\n ...group.currentState,\n organizationId: input.organizationId,\n principalId: group.groupId,\n principalType: \"group\",\n },\n ]\n : [],\n )\n .sort((left, right) =>\n compareCanonicalStrings(left.principalId, right.principalId),\n );\n // Group heads precede the organization head, ordered by principal ID.\n return [\n ...groupHeads,\n toOrganizationPolicyHead(input.organizationId, input.organizationHead),\n ];\n}\n\nasync function loadDirectoryRows(\n tx: ClientSQLiteTransactionScope,\n organizationId: string,\n): Promise<SelectedDirectoryUser[]> {\n return tx\n .select({\n createdAt: organizationReadModelDirectoryUsers.createdAt,\n disabledAt: organizationReadModelDirectoryUsers.disabledAt,\n disabledByUserId: organizationReadModelDirectoryUsers.disabledByUserId,\n encapsulationKeyFingerprint:\n organizationReadModelDirectoryUsers.encapsulationKeyFingerprint,\n encapsulationPublicKey:\n organizationReadModelDirectoryUsers.encapsulationPublicKey,\n joinedAt: organizationReadModelDirectoryUsers.joinedAt,\n leaveRequest: organizationReadModelDirectoryUsers.leaveRequest,\n isPersonalOrganizationOwner:\n organizationReadModelDirectoryUsers.isPersonalOrganizationOwner,\n profileDocumentId: organizationReadModelDirectoryUsers.profileDocumentId,\n signingKeyFingerprint:\n organizationReadModelDirectoryUsers.signingKeyFingerprint,\n signingPublicKey: organizationReadModelDirectoryUsers.signingPublicKey,\n status: organizationReadModelDirectoryUsers.status,\n updatedAt: organizationReadModelDirectoryUsers.updatedAt,\n userId: organizationReadModelDirectoryUsers.userId,\n })\n .from(organizationReadModelDirectoryUsers)\n .where(\n eq(organizationReadModelDirectoryUsers.organizationId, organizationId),\n )\n .orderBy(\n asc(organizationReadModelDirectoryUsers.sortOrder),\n asc(organizationReadModelDirectoryUsers.userId),\n );\n}\n\nasync function loadGroupRows(\n tx: ClientSQLiteTransactionScope,\n organizationId: string,\n): Promise<SelectedGroup[]> {\n return tx\n .select({\n createdAt: organizationReadModelGroups.createdAt,\n groupId: organizationReadModelGroups.groupId,\n isBuiltin: organizationReadModelGroups.isBuiltin,\n keyEpoch: organizationReadModelGroups.keyEpoch,\n keyFingerprint: organizationReadModelGroups.keyFingerprint,\n memberCount: organizationReadModelGroups.memberCount,\n name: organizationReadModelGroups.name,\n stateHash: organizationReadModelGroups.stateHash,\n stateVersion: organizationReadModelGroups.stateVersion,\n })\n .from(organizationReadModelGroups)\n .where(eq(organizationReadModelGroups.organizationId, organizationId))\n .orderBy(\n asc(organizationReadModelGroups.sortOrder),\n asc(organizationReadModelGroups.groupId),\n );\n}\n\nasync function loadMembershipEdges(\n tx: ClientSQLiteTransactionScope,\n organizationId: string,\n): Promise<OrganizationReadModelMembershipEdge[]> {\n return tx\n .select({\n groupId: organizationReadModelGroupMembers.groupId,\n userId: organizationReadModelGroupMembers.userId,\n })\n .from(organizationReadModelGroupMembers)\n .where(eq(organizationReadModelGroupMembers.organizationId, organizationId))\n .orderBy(\n asc(organizationReadModelGroupMembers.groupId),\n asc(organizationReadModelGroupMembers.sortOrder),\n asc(organizationReadModelGroupMembers.userId),\n );\n}\n\nexport async function loadOrganizationReadModelProjectionInTransaction(input: {\n readonly currentUserId: string;\n readonly organizationId: string;\n readonly tx: ClientSQLiteTransactionScope;\n}): Promise<OrganizationReadModelProjection | null> {\n const [state] = await input.tx\n .select({\n cursor: organizationReadModelState.cursor,\n memberGroupId: organizationReadModelState.memberGroupId,\n organizationKeyEpoch: organizationReadModelState.organizationKeyEpoch,\n organizationKeyFingerprint:\n organizationReadModelState.organizationKeyFingerprint,\n organizationMemberCount:\n organizationReadModelState.organizationMemberCount,\n organizationStateHash: organizationReadModelState.organizationStateHash,\n organizationStateVersion:\n organizationReadModelState.organizationStateVersion,\n profileDocumentId: organizationReadModelState.profileDocumentId,\n updatedAt: organizationReadModelState.updatedAt,\n })\n .from(organizationReadModelState)\n .where(eq(organizationReadModelState.organizationId, input.organizationId))\n .limit(1);\n if (!state) {\n return null;\n }\n const [requester] = await input.tx\n .select({ isOrgAdmin: organizationReadModelRequesters.isOrgAdmin })\n .from(organizationReadModelRequesters)\n .where(\n and(\n eq(\n organizationReadModelRequesters.organizationId,\n input.organizationId,\n ),\n eq(organizationReadModelRequesters.userId, input.currentUserId),\n ),\n )\n .limit(1);\n const directoryRows = await loadDirectoryRows(input.tx, input.organizationId);\n const groupRows = await loadGroupRows(input.tx, input.organizationId);\n const grants = await loadOrganizationReadModelGrantsInTransaction(input);\n const membershipEdges = await loadMembershipEdges(\n input.tx,\n input.organizationId,\n );\n const groups = groupRows.map((row) => ({\n groupId: row.groupId,\n organizationId: input.organizationId,\n name: row.name,\n createdAt: row.createdAt,\n isBuiltin: row.isBuiltin,\n currentState: toGroupCurrentState(row),\n }));\n const policyHeads = toProjectionPolicyHeads({\n groups,\n organizationHead: {\n keyEpoch: state.organizationKeyEpoch,\n keyFingerprint: state.organizationKeyFingerprint,\n memberCount: state.organizationMemberCount,\n stateHash: state.organizationStateHash,\n version: state.organizationStateVersion,\n },\n organizationId: input.organizationId,\n });\n\n return {\n cursor: state.cursor,\n directory: {\n organizationId: input.organizationId,\n profileDocumentId: state.profileDocumentId,\n users: directoryRows.map((row) =>\n toDirectoryUser(row, input.currentUserId),\n ),\n },\n grants,\n groups: {\n organizationId: input.organizationId,\n memberGroupId: state.memberGroupId,\n groups,\n },\n membershipEdges,\n organizationId: input.organizationId,\n policyHeads,\n protocolVersion: ORGANIZATION_READ_MODEL_PROTOCOL_VERSION,\n requester: requester ? { isOrgAdmin: requester.isOrgAdmin } : null,\n updatedAt: state.updatedAt,\n };\n}\n"]}
@@ -1733,6 +1733,77 @@ export declare const documentProjectionTables: ReadonlyArray<SqlTableSchema>;
1733
1733
  export declare const containerSyncWatermarkTables: ReadonlyArray<SqlTableSchema>;
1734
1734
  export declare const clientSqlTables: ReadonlyArray<SqlTableSchema>;
1735
1735
  export declare const clientSQLiteSchema: {
1736
+ organizationSyncPauseRemovals: import("drizzle-orm/sqlite-core").SQLiteTableWithColumns<{
1737
+ name: "organization_sync_pause_removals";
1738
+ schema: undefined;
1739
+ columns: {
1740
+ localId: import("drizzle-orm/sqlite-core").SQLiteColumn<{
1741
+ name: "local_id";
1742
+ tableName: "organization_sync_pause_removals";
1743
+ dataType: "string";
1744
+ columnType: "SQLiteText";
1745
+ data: string;
1746
+ driverParam: string;
1747
+ notNull: true;
1748
+ hasDefault: false;
1749
+ isPrimaryKey: true;
1750
+ isAutoincrement: false;
1751
+ hasRuntimeDefault: false;
1752
+ enumValues: [string, ...string[]];
1753
+ baseColumn: never;
1754
+ identity: undefined;
1755
+ generated: undefined;
1756
+ }, {}, {
1757
+ length: number | undefined;
1758
+ }>;
1759
+ organizationId: import("drizzle-orm/sqlite-core").SQLiteColumn<{
1760
+ name: "organization_id";
1761
+ tableName: "organization_sync_pause_removals";
1762
+ dataType: "string";
1763
+ columnType: "SQLiteText";
1764
+ data: string;
1765
+ driverParam: string;
1766
+ notNull: true;
1767
+ hasDefault: false;
1768
+ isPrimaryKey: false;
1769
+ isAutoincrement: false;
1770
+ hasRuntimeDefault: false;
1771
+ enumValues: [string, ...string[]];
1772
+ baseColumn: never;
1773
+ identity: undefined;
1774
+ generated: undefined;
1775
+ }, {}, {
1776
+ length: number | undefined;
1777
+ }>;
1778
+ };
1779
+ dialect: "sqlite";
1780
+ }>;
1781
+ organizationSyncPauses: import("drizzle-orm/sqlite-core").SQLiteTableWithColumns<{
1782
+ name: "organization_sync_pauses";
1783
+ schema: undefined;
1784
+ columns: {
1785
+ organizationId: import("drizzle-orm/sqlite-core").SQLiteColumn<{
1786
+ name: "organization_id";
1787
+ tableName: "organization_sync_pauses";
1788
+ dataType: "string";
1789
+ columnType: "SQLiteText";
1790
+ data: string;
1791
+ driverParam: string;
1792
+ notNull: true;
1793
+ hasDefault: false;
1794
+ isPrimaryKey: true;
1795
+ isAutoincrement: false;
1796
+ hasRuntimeDefault: false;
1797
+ enumValues: [string, ...string[]];
1798
+ baseColumn: never;
1799
+ identity: undefined;
1800
+ generated: undefined;
1801
+ }, {}, {
1802
+ length: number | undefined;
1803
+ }>;
1804
+ };
1805
+ dialect: "sqlite";
1806
+ }>;
1736
1807
  organizationProvisioningAttempts: import("drizzle-orm/sqlite-core").SQLiteTableWithColumns<{
1737
1808
  name: "organization_provisioning_attempts";
1738
1809
  schema: undefined;
@@ -2632,6 +2703,25 @@ export declare const clientSQLiteSchema: {
2632
2703
  }, {}, {
2633
2704
  length: number | undefined;
2634
2705
  }>;
2706
+ leaveRequest: import("drizzle-orm/sqlite-core").SQLiteColumn<{
2707
+ name: "leave_request";
2708
+ tableName: "organization_read_model_directory_users";
2709
+ dataType: "string";
2710
+ columnType: "SQLiteText";
2711
+ data: string;
2712
+ driverParam: string;
2713
+ notNull: false;
2714
+ hasDefault: false;
2715
+ isPrimaryKey: false;
2716
+ isAutoincrement: false;
2717
+ hasRuntimeDefault: false;
2718
+ enumValues: [string, ...string[]];
2719
+ baseColumn: never;
2720
+ identity: undefined;
2721
+ generated: undefined;
2722
+ }, {}, {
2723
+ length: number | undefined;
2724
+ }>;
2635
2725
  };
2636
2726
  dialect: "sqlite";
2637
2727
  }>;
@@ -12,6 +12,7 @@ import * as organizationDataUsage from "./organizationDataUsageSchema.js";
12
12
  import { organizationFounders } from "./organizationFounderSchema.js";
13
13
  import * as provisioningAttempt from "./organizationProvisioningAttemptSchema.js";
14
14
  import { organizationReadModelSQLiteSchema, organizationReadModelTables, } from "./organizationReadModelTableRegistry.js";
15
+ import * as organizationSyncPause from "./organizationSyncPauseSchema.js";
15
16
  import { principalGrantRetirements } from "./principalGrantRetirementSchema.js";
16
17
  import { principalHistoryEntries, principalHistoryEvidenceTables, principalHistoryNodes, principalHistoryPrefixes, } from "./principalHistoryEvidenceSchema.js";
17
18
  import { principalHistoryNodeReferences, principalHistoryRootOwners, } from "./principalHistoryNodeRetentionSchema.js";
@@ -486,6 +487,7 @@ export const clientSqlTables = [
486
487
  ...organizationReadModelTables,
487
488
  ...organizationDataUsage.organizationDataUsageTables,
488
489
  ...provisioningAttempt.organizationProvisioningAttemptTables,
490
+ ...organizationSyncPause.organizationSyncPauseTables,
489
491
  ];
490
492
  export const clientSQLiteSchema = {
491
493
  principalHistoryNodeReferences,
@@ -521,5 +523,6 @@ export const clientSQLiteSchema = {
521
523
  ...organizationReadModelSQLiteSchema,
522
524
  ...organizationDataUsage.organizationDataUsageSQLiteSchema,
523
525
  ...provisioningAttempt.organizationProvisioningAttemptSQLiteSchema,
526
+ ...organizationSyncPause.organizationSyncPauseSQLiteSchema,
524
527
  };
525
528
  //# sourceMappingURL=index.js.map